| Seq | Timestamp | Type | Name | Duration |
|---|---|---|---|---|
| 0/0 | 2026/09/19 12:40 | flow | patch-triage |
15mArgs:null Results: {
"EnableConfigs": [
"SWAP",
"HIBERNATION",
"HIBERNATION_SNAPSHOT_DEV",
"ENCRYPTED_HIBERNATION"
],
"FocusSymbols": [
"snapshot_store_encryption_seed",
"snapshot_get_encryption_key",
"snapshot_set_encryption_key",
"snapshot_set_user_key",
"snapshot_read_encrypted",
"snapshot_write_encrypted",
"snapshot_finalize_decrypted_image",
"snapshot_get_encrypted_image_size",
"snapshot_teardown_encryption",
"hibernate_snapshot_write_begin",
"hibernate_snapshot_write_end",
"hibernate_snapshot_write_active",
"hibernation_snapshot_dev_available",
"swsusp_swap_range_allocated",
"swapdev_block_to_extent"
],
"KMSANReasoning": "The patch introduces support for kernel-based encryption of userland hibernation snapshots (CONFIG_ENCRYPTED_HIBERNATION), including two new ioctls (SNAPSHOT_ENABLE_ENCRYPTION and SNAPSHOT_SET_USER_KEY), a write-only sysfs file (/sys/power/snapshot_seed), and swap write mediation in block/fops.c.\n\nAnalysis of memory initialization and usercopy operations:\n1. Kernel structures copied to userspace:\n - In `snapshot_get_encryption_key()`, the kernel writes to user fields `blob_len`, `blob`, and `nonce`. The source structure `struct snapshot_wrapped_key` is packed (`__packed`), explicitly initialized to zero with `{}` and `memset()`, and all its fields are fully populated prior to `copy_to_user()`. The `nonce` buffer is completely populated with `get_random_bytes()`. No uninitialized padding or buffer tails are copied to userspace.\n - In `snapshot_set_user_key()`, only a scalar `meta_size` (`u64`) is returned via `put_user()`.\n - In `snapshot_read_encrypted()`, `copy_to_user()` only transfers pages that have been populated by `snapshot_read_next()` and encrypted via AEAD, along with the authentication tag produced by the cipher.\n - The sysfs attribute `/sys/power/snapshot_seed` is write-only (permissions 0200) without any read callback.\n\n2. Kernel internal buffers and uninitialized memory usage:\n - All cryptographic keys, nonces, and buffers (`seed`, `wrap_key`, `buf`, `image_key`, `wrapped`, `user_key`) are either zero-initialized (`= {}`, `memset()`) or fully populated (`get_random_bytes()`, `hex2bin()`, `copy_from_user()`) before use, and wiped via `memzero_explicit()` / `kfree_sensitive()`.\n - In `snapshot_decrypt_drain()`, strict chunk-length checks ensure that only bytes fully received via `copy_from_user()` are decrypted and applied.\n - In `swsusp_swap_range_allocated()`, out-parameters from `swapdev_block_to_extent()` are only evaluated when the function returns 0 (success), where both pointers are guaranteed to be assigned.\n\n3. KASAN vs KMSAN applicability:\n - Any potential bugs introduced by this patch involve concurrency/locking (`system_transition_mutex`, `crypt_lock`), block extent range arithmetic, or boundary validation on swap/snapshot devices. These classes of issues are covered by KASAN, LOCKDEP, and standard assertion checks.\n - There are no risks of uninitialized memory reads or kernel information leaks. Spawning a dedicated KMSAN fuzzing session is not justified.",
"NeedsKMSAN": false,
"Reasoning": "The patch introduces kernel-based encryption support for userspace hibernation snapshots (/dev/snapshot), adding new ioctls (SNAPSHOT_ENABLE_ENCRYPTION, SNAPSHOT_SET_USER_KEY), sysfs attribute (/sys/power/snapshot_seed), encryption/decryption streaming and AEAD transform management (kernel/power/snapenc.c), block write reservation and extent checking hooks in block/fops.c and mm/swapfile.c, and state management in kernel/power/user.c. All modified code is reachable in standard virtualized environments.",
"WorthFuzzing": true
} |
| 1/1 | 2026/09/19 12:40 | action | read-patch-diff |
0mArgs:null Results: {
"PatchDiff": "commit 712876b1fef77d723912a260c8cc2b0ae6fed5c0\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate: Sat Sep 19 12:40:15 2026 +0000\n\n syz-cluster: applied patch under review\n\ndiff --git a/Documentation/ABI/testing/sysfs-power b/Documentation/ABI/testing/sysfs-power\nindex d38da077905a9..c756712a9df5e 100644\n--- a/Documentation/ABI/testing/sysfs-power\n+++ b/Documentation/ABI/testing/sysfs-power\n@@ -470,3 +470,21 @@ Description:\n \n Minimum value: 1\n Default value: 3\n+\n+What:\t\t/sys/power/snapshot_seed\n+Date:\t\tJuly 2026\n+Contact:\tlinux-pm@vger.kernel.org\n+Description:\n+\t\tWrite-only file present when CONFIG_ENCRYPTED_HIBERNATION=y.\n+\n+\t\tTrusted early userspace writes a 32-byte seed, encoded as\n+\t\t64 hexadecimal characters plus an optional newline, before\n+\t\tenabling encrypted userspace hibernation snapshots.\n+\n+\t\tThe first successful write locks the seed until the next boot.\n+\t\tWriting the same seed again succeeds. Writing a different seed\n+\t\tfails with EPERM.\n+\n+\t\tThe kernel does not authenticate the first writer. Trusted early\n+\t\tuserspace must provision this file before untrusted privileged\n+\t\tcode can run.\ndiff --git a/Documentation/power/userland-swsusp.rst b/Documentation/power/userland-swsusp.rst\nindex 1cf62d80a9ca1..957be396dcf5d 100644\n--- a/Documentation/power/userland-swsusp.rst\n+++ b/Documentation/power/userland-swsusp.rst\n@@ -115,6 +115,39 @@ SNAPSHOT_S2RAM\n \tto resume the system from RAM if there's enough battery power or restore\n \tits state on the basis of the saved suspend image otherwise)\n \n+SNAPSHOT_ENABLE_ENCRYPTION\n+\tEnables encryption of the hibernate image within the kernel. Trusted\n+\tearly userspace must write the 32-byte snapshot encryption seed to\n+\t/sys/power/snapshot_seed before calling this ioctl. Upon suspend\n+\t(ie when the snapshot device was opened for reading), this ioctl returns\n+\tan opaque wrapped key blob and the starting nonce. Upon resume (ie when\n+\tthe snapshot device was opened for writing), this ioctl receives the\n+\tsame blob and nonce from usermode after the same seed has been written\n+\tto /sys/power/snapshot_seed. The plaintext image key is generated and\n+\tunwrapped inside the kernel.\n+\n+\tThe first successful seed write establishes the wrapping key for that\n+\tboot. The kernel does not authenticate the writer, the TPM policy used to\n+\tunseal the seed, or image freshness. Early userspace must provision the\n+\tseed before untrusted privileged code can run and must enforce any TPM\n+\tpolicy and rollback protection.\n+\n+\tUnder lockdown, direct block-device write() calls to the active swap\n+\tbackend are restricted to the process which owns the snapshot device and\n+\tthe extents allocated with SNAPSHOT_ALLOC_SWAP_PAGE. These writes must\n+\tuse synchronous buffered I/O (O_DSYNC without O_DIRECT), and cannot\n+\texceed the number of pages returned by that ioctl. The swap header may\n+\tonly be written at the offset supplied with SNAPSHOT_SET_SWAP_AREA.\n+\n+SNAPSHOT_SET_USER_KEY\n+\tMixes additional user key material into the data portion of an encrypted\n+\thibernate image. The ioctl argument points to struct uswsusp_user_key.\n+\tkey_len must be between 8 and USWSUSP_USER_KEY_SIZE bytes, and reserved\n+\tmust be zero. During hibernation the kernel writes meta_size with the\n+\tencrypted metadata size. During resume, userspace passes the saved\n+\tmeta_size back so the kernel can switch keys at the metadata boundary\n+\tbefore the snapshot header has been decrypted.\n+\n The device's read() operation can be used to transfer the snapshot image from\n the kernel. It has the following limitations:\n \ndiff --git a/block/fops.c b/block/fops.c\nindex 2ce7c6c4714e4..bdc9f2cf7156f 100644\n--- a/block/fops.c\n+++ b/block/fops.c\n@@ -725,43 +725,68 @@ static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)\n \tstruct file *file = iocb-\u003eki_filp;\n \tstruct inode *bd_inode = bdev_file_inode(file);\n \tstruct block_device *bdev = I_BDEV(bd_inode);\n+\tdev_t dev = bd_inode-\u003ei_rdev;\n \tbool atomic = iocb-\u003eki_flags \u0026 IOCB_ATOMIC;\n \tloff_t size = bdev_nr_bytes(bdev);\n+\tenum hibernate_snapshot_write hibernate_write;\n+\tbool hibernate_active;\n+\tsize_t hibernate_len = 0;\n \tsize_t shorted = 0;\n+\tssize_t hibernate_written = 0;\n \tssize_t ret;\n \n \tif (bdev_read_only(bdev))\n \t\treturn -EPERM;\n \n-\tif (IS_SWAPFILE(bd_inode) \u0026\u0026 !is_hibernate_resume_dev(bd_inode-\u003ei_rdev))\n-\t\treturn -ETXTBSY;\n+\thibernate_active = hibernate_snapshot_write_active(dev);\n+\tif ((IS_SWAPFILE(bd_inode) \u0026\u0026 !is_hibernate_resume_dev(dev)) ||\n+\t hibernate_active) {\n+\t\tif (!is_sync_kiocb(iocb) || !iocb_is_dsync(iocb) ||\n+\t\t (iocb-\u003eki_flags \u0026 IOCB_DIRECT))\n+\t\t\treturn -ETXTBSY;\n+\n+\t\thibernate_len = iov_iter_count(from);\n+\t\thibernate_write = hibernate_snapshot_write_begin(dev, iocb-\u003eki_pos, hibernate_len);\n+\t\tif (hibernate_write == HIBERNATE_SNAPSHOT_WRITE_NONE)\n+\t\t\treturn -ETXTBSY;\n+\t} else {\n+\t\thibernate_write = HIBERNATE_SNAPSHOT_WRITE_NONE;\n+\t}\n \n-\tif (!iov_iter_count(from))\n-\t\treturn 0;\n+\tif (!iov_iter_count(from)) {\n+\t\tret = 0;\n+\t\tgoto out_hibernate;\n+\t}\n \n-\tif (iocb-\u003eki_pos \u003e= size)\n-\t\treturn -ENOSPC;\n+\tif (iocb-\u003eki_pos \u003e= size) {\n+\t\tret = -ENOSPC;\n+\t\tgoto out_hibernate;\n+\t}\n \n-\tif ((iocb-\u003eki_flags \u0026 (IOCB_NOWAIT | IOCB_DIRECT)) == IOCB_NOWAIT)\n-\t\treturn -EOPNOTSUPP;\n+\tif ((iocb-\u003eki_flags \u0026 (IOCB_NOWAIT | IOCB_DIRECT)) == IOCB_NOWAIT) {\n+\t\tret = -EOPNOTSUPP;\n+\t\tgoto out_hibernate;\n+\t}\n \n \tif (atomic) {\n \t\tret = generic_atomic_write_valid(iocb, from);\n \t\tif (ret)\n-\t\t\treturn ret;\n+\t\t\tgoto out_hibernate;\n \t}\n \n \tsize -= iocb-\u003eki_pos;\n \tif (iov_iter_count(from) \u003e size) {\n-\t\tif (atomic)\n-\t\t\treturn -EINVAL;\n+\t\tif (atomic) {\n+\t\t\tret = -EINVAL;\n+\t\t\tgoto out_hibernate;\n+\t\t}\n \t\tshorted = iov_iter_count(from) - size;\n \t\tiov_iter_truncate(from, size);\n \t}\n \n \tret = file_update_time(file);\n \tif (ret)\n-\t\treturn ret;\n+\t\tgoto out_hibernate;\n \n \tif (iocb-\u003eki_flags \u0026 IOCB_DIRECT) {\n \t\tret = blkdev_direct_write(iocb, from);\n@@ -779,9 +804,16 @@ static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)\n \t\tinode_unlock_shared(bd_inode);\n \t}\n \n-\tif (ret \u003e 0)\n+\tif (ret \u003e 0) {\n+\t\thibernate_written = ret;\n \t\tret = generic_write_sync(iocb, ret);\n+\t}\n \tiov_iter_reexpand(from, iov_iter_count(from) + shorted);\n+\n+out_hibernate:\n+\tif (hibernate_len)\n+\t\thibernate_snapshot_write_end(hibernate_write, hibernate_len,\n+\t\t\t\t\t hibernate_written);\n \treturn ret;\n }\n \ndiff --git a/include/linux/suspend.h b/include/linux/suspend.h\nindex b02876f1ae38a..a2a8863f89cf1 100644\n--- a/include/linux/suspend.h\n+++ b/include/linux/suspend.h\n@@ -426,10 +426,34 @@ static inline bool pm_hibernation_mode_is_suspend(void) { return false; }\n \n int arch_resume_nosmt(void);\n \n+enum hibernate_snapshot_write {\n+\tHIBERNATE_SNAPSHOT_WRITE_NONE,\n+\tHIBERNATE_SNAPSHOT_WRITE_IMAGE,\n+\tHIBERNATE_SNAPSHOT_WRITE_HEADER,\n+};\n+\n #ifdef CONFIG_HIBERNATION_SNAPSHOT_DEV\n int is_hibernate_resume_dev(dev_t dev);\n+bool hibernate_snapshot_write_active(dev_t dev);\n+enum hibernate_snapshot_write\n+hibernate_snapshot_write_begin(dev_t dev, loff_t pos, size_t count);\n+void hibernate_snapshot_write_end(enum hibernate_snapshot_write type,\n+\t\t\t\t size_t reserved, ssize_t written);\n #else\n static inline int is_hibernate_resume_dev(dev_t dev) { return 0; }\n+static inline bool hibernate_snapshot_write_active(dev_t dev) { return false; }\n+\n+static inline enum hibernate_snapshot_write\n+hibernate_snapshot_write_begin(dev_t dev, loff_t pos, size_t count)\n+{\n+\treturn HIBERNATE_SNAPSHOT_WRITE_NONE;\n+}\n+\n+static inline void hibernate_snapshot_write_end(enum hibernate_snapshot_write type,\n+\t\t\t\t\t\tsize_t reserved,\n+\t\t\t\t\t\tssize_t written)\n+{\n+}\n #endif\n \n /* Hibernation and suspend events */\ndiff --git a/include/linux/swap.h b/include/linux/swap.h\nindex 5658a1634b85e..deab983ef3d65 100644\n--- a/include/linux/swap.h\n+++ b/include/linux/swap.h\n@@ -377,6 +377,8 @@ extern int find_hibernation_swap_type(dev_t device, sector_t offset);\n int find_first_swap(dev_t *device);\n extern unsigned int count_swap_pages(int, int);\n extern sector_t swapdev_block(int, pgoff_t);\n+int swapdev_block_to_extent(int type, sector_t block, pgoff_t *offset,\n+\t\t\t pgoff_t *nr_pages);\n extern int __swap_count(swp_entry_t entry);\n extern bool swap_entry_swapped(struct swap_info_struct *si, swp_entry_t entry);\n extern int swp_swapcount(swp_entry_t entry);\n@@ -472,6 +474,13 @@ static inline int add_swap_extent(struct swap_info_struct *sis,\n {\n \treturn -EINVAL;\n }\n+\n+static inline int swapdev_block_to_extent(int type, sector_t block,\n+\t\t\t\t\t pgoff_t *offset,\n+\t\t\t\t\t pgoff_t *nr_pages)\n+{\n+\treturn -EINVAL;\n+}\n #endif /* CONFIG_SWAP */\n #ifdef CONFIG_MEMCG\n void lru_reparent_memcg(struct mem_cgroup *memcg, struct mem_cgroup *parent, int nid);\ndiff --git a/include/uapi/linux/suspend_ioctls.h b/include/uapi/linux/suspend_ioctls.h\nindex bcce04e21c0dc..5e23bf936277e 100644\n--- a/include/uapi/linux/suspend_ioctls.h\n+++ b/include/uapi/linux/suspend_ioctls.h\n@@ -13,6 +13,31 @@ struct resume_swap_area {\n \t__u32 dev;\n } __attribute__((packed));\n \n+#define USWSUSP_KEY_NONCE_SIZE 16\n+#define USWSUSP_USER_KEY_SIZE 32\n+\n+/*\n+ * This structure is used to pass the opaque wrapped hibernate image\n+ * encryption key and starting nonce in either direction.\n+ */\n+struct uswsusp_key_blob {\n+\t__u32 blob_len;\n+\t__u8 blob[512];\n+\t__u8 nonce[USWSUSP_KEY_NONCE_SIZE] __kernel_nonstring;\n+} __attribute__((packed));\n+\n+/*\n+ * Allow user mode to fold in key material for the data portion of the hibernate\n+ * image.\n+ */\n+struct uswsusp_user_key {\n+\t/* Kernel returns the metadata size; resume passes the saved value in. */\n+\t__u64 meta_size;\n+\t__u32 key_len;\n+\t__u32 reserved;\n+\t__u8 key[USWSUSP_USER_KEY_SIZE] __kernel_nonstring;\n+} __attribute__((packed));\n+\n #define SNAPSHOT_IOC_MAGIC\t'3'\n #define SNAPSHOT_FREEZE\t\t\t_IO(SNAPSHOT_IOC_MAGIC, 1)\n #define SNAPSHOT_UNFREEZE\t\t_IO(SNAPSHOT_IOC_MAGIC, 2)\n@@ -29,6 +54,10 @@ struct resume_swap_area {\n #define SNAPSHOT_PREF_IMAGE_SIZE\t_IO(SNAPSHOT_IOC_MAGIC, 18)\n #define SNAPSHOT_AVAIL_SWAP_SIZE\t_IOR(SNAPSHOT_IOC_MAGIC, 19, __kernel_loff_t)\n #define SNAPSHOT_ALLOC_SWAP_PAGE\t_IOR(SNAPSHOT_IOC_MAGIC, 20, __kernel_loff_t)\n-#define SNAPSHOT_IOC_MAXNR\t20\n+#define SNAPSHOT_ENABLE_ENCRYPTION\t_IOWR(SNAPSHOT_IOC_MAGIC, 21, \\\n+\t\t\t\t\t\t\tstruct uswsusp_key_blob)\n+#define SNAPSHOT_SET_USER_KEY\t\t_IOWR(SNAPSHOT_IOC_MAGIC, 22, \\\n+\t\t\t\t\t\t\tstruct uswsusp_user_key)\n+#define SNAPSHOT_IOC_MAXNR\t22\n \n #endif /* _LINUX_SUSPEND_IOCTLS_H */\ndiff --git a/kernel/power/Kconfig b/kernel/power/Kconfig\nindex 71165e7f04f47..f23d1c7e0ecd1 100644\n--- a/kernel/power/Kconfig\n+++ b/kernel/power/Kconfig\n@@ -115,6 +115,21 @@ config HIBERNATION_DEF_COMP\n \thelp\n \t Default compressor to be used for hibernation.\n \n+config ENCRYPTED_HIBERNATION\n+\tbool \"Encryption support for userspace snapshots\"\n+\tdepends on HIBERNATION_SNAPSHOT_DEV\n+\tselect CRYPTO_AES\n+\tselect CRYPTO_GCM\n+\tselect CRYPTO_LIB_SHA256\n+\thelp\n+\t Enable support for kernel-based encryption of hibernation snapshots\n+\t created by uswsusp tools. A trusted early userspace component must\n+\t provide the snapshot encryption seed before enabling encryption.\n+\n+\t Say N if userspace handles the image encryption.\n+\n+\t If in doubt, say N.\n+\n config PM_STD_PARTITION\n \tstring \"Default resume partition\"\n \tdepends on HIBERNATION\ndiff --git a/kernel/power/Makefile b/kernel/power/Makefile\nindex 773e2789412b9..2fd31b2a250f5 100644\n--- a/kernel/power/Makefile\n+++ b/kernel/power/Makefile\n@@ -16,6 +16,7 @@ obj-$(CONFIG_SUSPEND)\t\t+= suspend.o\n obj-$(CONFIG_PM_TEST_SUSPEND)\t+= suspend_test.o\n obj-$(CONFIG_HIBERNATION)\t+= hibernate.o snapshot.o swap.o\n obj-$(CONFIG_HIBERNATION_SNAPSHOT_DEV) += user.o\n+obj-$(CONFIG_ENCRYPTED_HIBERNATION) += snapenc.o\n obj-$(CONFIG_PM_AUTOSLEEP)\t+= autosleep.o\n obj-$(CONFIG_PM_WAKELOCKS)\t+= wakelock.o\n \ndiff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c\nindex d2479c69d71a4..0b8626bdf81a8 100644\n--- a/kernel/power/hibernate.c\n+++ b/kernel/power/hibernate.c\n@@ -36,6 +36,7 @@\n #include \u003ctrace/events/power.h\u003e\n \n #include \"power.h\"\n+#include \"user.h\"\n \n \n static int nocompress;\n@@ -113,6 +114,14 @@ bool hibernation_available(void)\n \t\t!secretmem_active() \u0026\u0026 !cxl_mem_active();\n }\n \n+bool hibernation_snapshot_dev_available(void)\n+{\n+\treturn nohibernate == 0 \u0026\u0026\n+\t\t(!security_locked_down(LOCKDOWN_HIBERNATION) ||\n+\t\t IS_ENABLED(CONFIG_ENCRYPTED_HIBERNATION)) \u0026\u0026\n+\t\t!secretmem_active() \u0026\u0026 !cxl_mem_active();\n+}\n+\n /**\n * hibernation_set_ops - Set the global hibernate operations.\n * @ops: Hibernation operations to use in subsequent hibernation transitions.\n@@ -1376,12 +1385,35 @@ static ssize_t reserved_size_store(struct kobject *kobj,\n \n power_attr(reserved_size);\n \n+#ifdef CONFIG_ENCRYPTED_HIBERNATION\n+static ssize_t snapshot_seed_store(struct kobject *kobj,\n+\t\t\t\t struct kobj_attribute *attr,\n+\t\t\t\t const char *buf, size_t n)\n+{\n+\tint ret;\n+\n+\tret = snapshot_store_encryption_seed(buf, n);\n+\treturn ret ? ret : n;\n+}\n+\n+static struct kobj_attribute snapshot_seed_attr = {\n+\t.attr\t= {\n+\t\t.name = \"snapshot_seed\",\n+\t\t.mode = 0200,\n+\t},\n+\t.store\t= snapshot_seed_store,\n+};\n+#endif\n+\n static struct attribute *g[] = {\n \t\u0026disk_attr.attr,\n \t\u0026resume_offset_attr.attr,\n \t\u0026resume_attr.attr,\n \t\u0026image_size_attr.attr,\n \t\u0026reserved_size_attr.attr,\n+#ifdef CONFIG_ENCRYPTED_HIBERNATION\n+\t\u0026snapshot_seed_attr.attr,\n+#endif\n \tNULL,\n };\n \ndiff --git a/kernel/power/power.h b/kernel/power/power.h\nindex 75b63843886ee..351b5f68bde34 100644\n--- a/kernel/power/power.h\n+++ b/kernel/power/power.h\n@@ -160,6 +160,7 @@ struct snapshot_handle {\n \n extern unsigned int snapshot_additional_pages(struct zone *zone);\n extern unsigned long snapshot_get_image_size(void);\n+unsigned long snapshot_get_meta_page_count(void);\n extern int snapshot_read_next(struct snapshot_handle *handle);\n extern int snapshot_write_next(struct snapshot_handle *handle);\n int snapshot_write_finalize(struct snapshot_handle *handle);\n@@ -167,8 +168,10 @@ extern int snapshot_image_loaded(struct snapshot_handle *handle);\n \n extern bool hibernate_acquire(void);\n extern void hibernate_release(void);\n+bool hibernation_snapshot_dev_available(void);\n \n extern sector_t alloc_swapdev_block(int swap);\n+bool swsusp_swap_range_allocated(int swap, loff_t pos, size_t count);\n extern void free_all_swap_pages(int swap);\n extern int swsusp_swap_in_use(void);\n \ndiff --git a/kernel/power/snapenc.c b/kernel/power/snapenc.c\nnew file mode 100644\nindex 0000000000000..b555a699b5644\n--- /dev/null\n+++ b/kernel/power/snapenc.c\n@@ -0,0 +1,952 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/* This file provides encryption support for system snapshots. */\n+\n+#include \u003clinux/crypto.h\u003e\n+#include \u003ccrypto/aead.h\u003e\n+#include \u003ccrypto/gcm.h\u003e\n+#include \u003ccrypto/sha2.h\u003e\n+#include \u003ccrypto/utils.h\u003e\n+#include \u003clinux/hex.h\u003e\n+#include \u003clinux/mutex.h\u003e\n+#include \u003clinux/random.h\u003e\n+#include \u003clinux/mm.h\u003e\n+#include \u003clinux/slab.h\u003e\n+#include \u003clinux/string.h\u003e\n+#include \u003clinux/uaccess.h\u003e\n+\n+#include \"power.h\"\n+#include \"user.h\"\n+\n+#define SNAPSHOT_SEED_SIZE SHA256_DIGEST_SIZE\n+#define SNAPSHOT_KEY_BLOB_VERSION 1\n+\n+static const u8 snapshot_key_blob_magic[8] = {\n+\t'S', 'W', 'S', 'U', 'S', 'P', 'K', '1',\n+};\n+\n+struct snapshot_wrapped_key {\n+\tu8 magic[sizeof(snapshot_key_blob_magic)];\n+\t__le32 version;\n+\tu8 wrap_nonce[GCM_AES_IV_SIZE] __nonstring;\n+\tu8 encrypted_key[SNAPSHOT_ENCRYPTION_KEY_SIZE] __nonstring;\n+\tu8 tag[SNAPSHOT_AUTH_TAG_SIZE] __nonstring;\n+} __packed;\n+\n+static DEFINE_MUTEX(snapshot_seed_mutex);\n+static u8 snapshot_seed[SNAPSHOT_SEED_SIZE] __nonstring;\n+static bool snapshot_seed_valid;\n+\n+int snapshot_store_encryption_seed(const char *buf, size_t count)\n+{\n+\tu8 seed[SNAPSHOT_SEED_SIZE] __nonstring;\n+\tsize_t len = count;\n+\tint ret;\n+\n+\tif (len \u0026\u0026 buf[len - 1] == '\\n')\n+\t\tlen--;\n+\tif (len != SNAPSHOT_SEED_SIZE * 2)\n+\t\treturn -EINVAL;\n+\n+\tret = hex2bin(seed, buf, sizeof(seed));\n+\tif (ret)\n+\t\treturn ret;\n+\n+\tmutex_lock(\u0026snapshot_seed_mutex);\n+\tif (snapshot_seed_valid) {\n+\t\tret = crypto_memneq(snapshot_seed, seed, sizeof(seed)) ? -EPERM : 0;\n+\t\tgoto out;\n+\t}\n+\n+\tmemcpy(snapshot_seed, seed, sizeof(seed));\n+\tsnapshot_seed_valid = true;\n+\tpr_info(\"PM: hibernate: snapshot encryption seed locked\\n\");\n+\n+out:\n+\tmutex_unlock(\u0026snapshot_seed_mutex);\n+\tmemzero_explicit(seed, sizeof(seed));\n+\treturn ret;\n+}\n+\n+static bool snapshot_copy_encryption_seed(u8 seed[SNAPSHOT_SEED_SIZE])\n+{\n+\tbool valid;\n+\n+\tmutex_lock(\u0026snapshot_seed_mutex);\n+\tvalid = snapshot_seed_valid;\n+\tif (valid)\n+\t\tmemcpy(seed, snapshot_seed, SNAPSHOT_SEED_SIZE);\n+\tmutex_unlock(\u0026snapshot_seed_mutex);\n+\n+\treturn valid;\n+}\n+\n+static int snapshot_derive_wrapping_key(u8 key[SNAPSHOT_ENCRYPTION_KEY_SIZE])\n+{\n+\tstatic const char label[] = \"Linux hibernate snapshot key wrap v1\";\n+\tu8 digest[SHA256_DIGEST_SIZE];\n+\tu8 seed[SNAPSHOT_SEED_SIZE] __nonstring;\n+\tstruct sha256_ctx sha256_ctx;\n+\n+\tif (!snapshot_copy_encryption_seed(seed))\n+\t\treturn -ENOKEY;\n+\n+\tsha256_init(\u0026sha256_ctx);\n+\tsha256_update(\u0026sha256_ctx, label, strlen(label));\n+\tsha256_update(\u0026sha256_ctx, seed, sizeof(seed));\n+\tsha256_final(\u0026sha256_ctx, digest);\n+\n+\tmemcpy(key, digest, SNAPSHOT_ENCRYPTION_KEY_SIZE);\n+\tmemzero_explicit(seed, sizeof(seed));\n+\tmemzero_explicit(digest, sizeof(digest));\n+\treturn 0;\n+}\n+\n+static int snapshot_crypt_wrapped_key(struct snapshot_wrapped_key *wrapped,\n+\t\t\t\t u8 image_key[SNAPSHOT_ENCRYPTION_KEY_SIZE],\n+\t\t\t\t bool encrypt)\n+{\n+\tu8 wrap_key[SNAPSHOT_ENCRYPTION_KEY_SIZE] __nonstring;\n+\tu8 buf[SNAPSHOT_ENCRYPTION_KEY_SIZE + SNAPSHOT_AUTH_TAG_SIZE] __nonstring;\n+\tstruct crypto_aead *tfm;\n+\tstruct aead_request *req;\n+\tstruct scatterlist sg;\n+\tDECLARE_CRYPTO_WAIT(wait);\n+\tint rc;\n+\n+\trc = snapshot_derive_wrapping_key(wrap_key);\n+\tif (rc)\n+\t\treturn rc;\n+\n+\ttfm = crypto_alloc_aead(\"gcm(aes)\", 0, 0);\n+\tif (IS_ERR(tfm)) {\n+\t\trc = PTR_ERR(tfm);\n+\t\tgoto out_key;\n+\t}\n+\n+\trc = crypto_aead_setkey(tfm, wrap_key, sizeof(wrap_key));\n+\tif (rc)\n+\t\tgoto out_tfm;\n+\n+\trc = crypto_aead_setauthsize(tfm, SNAPSHOT_AUTH_TAG_SIZE);\n+\tif (rc)\n+\t\tgoto out_tfm;\n+\n+\treq = aead_request_alloc(tfm, GFP_KERNEL);\n+\tif (!req) {\n+\t\trc = -ENOMEM;\n+\t\tgoto out_tfm;\n+\t}\n+\n+\tif (encrypt) {\n+\t\tget_random_bytes(wrapped-\u003ewrap_nonce, sizeof(wrapped-\u003ewrap_nonce));\n+\t\tmemcpy(buf, image_key, SNAPSHOT_ENCRYPTION_KEY_SIZE);\n+\t} else {\n+\t\tmemcpy(buf, wrapped-\u003eencrypted_key, SNAPSHOT_ENCRYPTION_KEY_SIZE);\n+\t\tmemcpy(buf + SNAPSHOT_ENCRYPTION_KEY_SIZE, wrapped-\u003etag,\n+\t\t SNAPSHOT_AUTH_TAG_SIZE);\n+\t}\n+\n+\tsg_init_one(\u0026sg, buf, sizeof(buf));\n+\taead_request_set_callback(req, 0, crypto_req_done, \u0026wait);\n+\taead_request_set_ad(req, 0);\n+\taead_request_set_crypt(req, \u0026sg, \u0026sg,\n+\t\t\t encrypt ? SNAPSHOT_ENCRYPTION_KEY_SIZE :\n+\t\t\t\t\t sizeof(buf),\n+\t\t\t wrapped-\u003ewrap_nonce);\n+\n+\trc = crypto_wait_req(encrypt ? crypto_aead_encrypt(req) :\n+\t\t\t\t crypto_aead_decrypt(req),\n+\t\t\t \u0026wait);\n+\tif (rc)\n+\t\tgoto out_req;\n+\n+\tif (encrypt) {\n+\t\tmemcpy(wrapped-\u003eencrypted_key, buf, SNAPSHOT_ENCRYPTION_KEY_SIZE);\n+\t\tmemcpy(wrapped-\u003etag, buf + SNAPSHOT_ENCRYPTION_KEY_SIZE,\n+\t\t SNAPSHOT_AUTH_TAG_SIZE);\n+\t} else {\n+\t\tmemcpy(image_key, buf, SNAPSHOT_ENCRYPTION_KEY_SIZE);\n+\t}\n+\n+out_req:\n+\taead_request_free(req);\n+out_tfm:\n+\tcrypto_free_aead(tfm);\n+out_key:\n+\tmemzero_explicit(buf, sizeof(buf));\n+\tmemzero_explicit(wrap_key, sizeof(wrap_key));\n+\treturn rc;\n+}\n+\n+static int snapshot_wrap_image_key(const u8 image_key[SNAPSHOT_ENCRYPTION_KEY_SIZE],\n+\t\t\t\t struct snapshot_wrapped_key *wrapped)\n+{\n+\tu8 key[SNAPSHOT_ENCRYPTION_KEY_SIZE] __nonstring;\n+\tint rc;\n+\n+\tmemset(wrapped, 0, sizeof(*wrapped));\n+\tmemcpy(wrapped-\u003emagic, snapshot_key_blob_magic, sizeof(wrapped-\u003emagic));\n+\twrapped-\u003eversion = cpu_to_le32(SNAPSHOT_KEY_BLOB_VERSION);\n+\n+\tmemcpy(key, image_key, sizeof(key));\n+\trc = snapshot_crypt_wrapped_key(wrapped, key, true);\n+\tmemzero_explicit(key, sizeof(key));\n+\treturn rc;\n+}\n+\n+static int snapshot_unwrap_image_key(const struct snapshot_wrapped_key *wrapped,\n+\t\t\t\t u8 image_key[SNAPSHOT_ENCRYPTION_KEY_SIZE])\n+{\n+\tstruct snapshot_wrapped_key tmp;\n+\tint rc;\n+\n+\tif (memcmp(wrapped-\u003emagic, snapshot_key_blob_magic,\n+\t\t sizeof(snapshot_key_blob_magic)))\n+\t\treturn -EINVAL;\n+\tif (le32_to_cpu(wrapped-\u003eversion) != SNAPSHOT_KEY_BLOB_VERSION)\n+\t\treturn -EINVAL;\n+\n+\ttmp = *wrapped;\n+\trc = snapshot_crypt_wrapped_key(\u0026tmp, image_key, false);\n+\tmemzero_explicit(\u0026tmp, sizeof(tmp));\n+\treturn rc;\n+}\n+\n+static int snapshot_install_image_key(struct snapshot_data *data,\n+\t\t\t\t const u8 image_key[SNAPSHOT_ENCRYPTION_KEY_SIZE])\n+{\n+\tint rc;\n+\n+\tmemcpy(data-\u003eencryption_key, image_key, sizeof(data-\u003eencryption_key));\n+\trc = crypto_aead_setkey(data-\u003eaead_tfm, data-\u003eencryption_key,\n+\t\t\t\tsizeof(data-\u003eencryption_key));\n+\tif (rc)\n+\t\tmemzero_explicit(data-\u003eencryption_key,\n+\t\t\t\t sizeof(data-\u003eencryption_key));\n+\n+\treturn rc;\n+}\n+\n+/* Derive a key from the kernel and user keys for data encryption. */\n+static int snapshot_use_user_key(struct snapshot_data *data)\n+{\n+\tu8 digest[SHA256_DIGEST_SIZE];\n+\tstruct sha256_ctx sha256_ctx;\n+\tint rc;\n+\n+\t/*\n+\t * Hash the kernel key and the user key together. This folds in the user\n+\t * key, but not in a way that gives the user mode predictable control\n+\t * over the key bits.\n+\t */\n+\tsha256_init(\u0026sha256_ctx);\n+\n+\tsha256_update(\u0026sha256_ctx, data-\u003eencryption_key,\n+\t\t SNAPSHOT_ENCRYPTION_KEY_SIZE);\n+\tsha256_update(\u0026sha256_ctx, data-\u003euser_key, sizeof(data-\u003euser_key));\n+\tsha256_final(\u0026sha256_ctx, digest);\n+\n+\tBUILD_BUG_ON(SNAPSHOT_ENCRYPTION_KEY_SIZE \u003e SHA256_DIGEST_SIZE);\n+\n+\trc = crypto_aead_setkey(data-\u003eaead_tfm,\n+\t\t\t\tdigest,\n+\t\t\t\tSNAPSHOT_ENCRYPTION_KEY_SIZE);\n+\tmemzero_explicit(digest, sizeof(digest));\n+\n+\treturn rc;\n+}\n+\n+/* Check to see if it's time to switch to the user key, and do it if so. */\n+static int snapshot_check_user_key_switch(struct snapshot_data *data)\n+{\n+\tif (data-\u003euser_key_valid \u0026\u0026 data-\u003emeta_size \u0026\u0026\n+\t data-\u003ecrypt_total == data-\u003emeta_size) {\n+\t\treturn snapshot_use_user_key(data);\n+\t}\n+\n+\treturn 0;\n+}\n+\n+static loff_t snapshot_encrypted_byte_count(loff_t plain_size);\n+\n+static void snapshot_set_meta_size(struct snapshot_data *data, u64 meta_size)\n+{\n+\tdata-\u003emeta_size = meta_size;\n+\tdata-\u003ecrypt_meta_size = snapshot_encrypted_byte_count(meta_size);\n+}\n+\n+/* Encrypt more data from the snapshot into the staging area. */\n+static int snapshot_encrypt_refill(struct snapshot_data *data)\n+{\n+\tstruct aead_request *req = data-\u003eaead_req;\n+\tu8 nonce[GCM_AES_IV_SIZE];\n+\tDECLARE_CRYPTO_WAIT(wait);\n+\tsize_t total = 0;\n+\tint pg_idx;\n+\tint res;\n+\n+\tif (data-\u003ecrypt_total == 0) {\n+\t\tsnapshot_set_meta_size(data,\n+\t\t\t\t snapshot_get_meta_page_count() \u003c\u003c PAGE_SHIFT);\n+\t} else {\n+\t\tres = snapshot_check_user_key_switch(data);\n+\t\tif (res)\n+\t\t\treturn res;\n+\t}\n+\n+\t/*\n+\t * The first buffer is the associated data, set to the offset to prevent\n+\t * attacks that rearrange chunks.\n+\t */\n+\tsg_set_buf(\u0026data-\u003esg[0], \u0026data-\u003ecrypt_total, sizeof(data-\u003ecrypt_total));\n+\n+\t/* Load the crypt buffer with snapshot pages. */\n+\tfor (pg_idx = 0; pg_idx \u003c SNAPSHOT_CHUNK_SIZE; pg_idx++) {\n+\t\tvoid *buf = data-\u003ecrypt_pages[pg_idx];\n+\n+\t\t/* Stop at the meta page boundary before switching keys. */\n+\t\tif (data-\u003euser_key_valid \u0026\u0026 total \u0026\u0026\n+\t\t ((data-\u003ecrypt_total + total) == data-\u003emeta_size))\n+\t\t\tbreak;\n+\n+\t\tres = snapshot_read_next(\u0026data-\u003ehandle);\n+\t\tif (res \u003c 0)\n+\t\t\treturn res;\n+\t\tif (res == 0)\n+\t\t\tbreak;\n+\n+\t\tWARN_ON(res != PAGE_SIZE);\n+\n+\t\t/*\n+\t\t * Copy the page into the staging area. A future optimization\n+\t\t * could potentially skip this copy for lowmem pages.\n+\t\t */\n+\t\tmemcpy(buf, data_of(data-\u003ehandle), PAGE_SIZE);\n+\t\tsg_set_buf(\u0026data-\u003esg[1 + pg_idx], buf, PAGE_SIZE);\n+\t\ttotal += PAGE_SIZE;\n+\t}\n+\n+\tif (!total)\n+\t\treturn 0;\n+\n+\tsg_set_buf(\u0026data-\u003esg[1 + pg_idx], \u0026data-\u003eauth_tag, SNAPSHOT_AUTH_TAG_SIZE);\n+\taead_request_set_callback(req, 0, crypto_req_done, \u0026wait);\n+\t/*\n+\t * Use incrementing nonces for each chunk, since a 64 bit value won't\n+\t * roll into re-use for any given hibernate image.\n+\t */\n+\tmemcpy(\u0026nonce[0], \u0026data-\u003enonce_low, sizeof(data-\u003enonce_low));\n+\tmemcpy(\u0026nonce[sizeof(data-\u003enonce_low)],\n+\t \u0026data-\u003enonce_high,\n+\t sizeof(nonce) - sizeof(data-\u003enonce_low));\n+\n+\tdata-\u003enonce_low += 1;\n+\t/* Total does not include AAD or the auth tag. */\n+\taead_request_set_crypt(req, data-\u003esg, data-\u003esg, total, nonce);\n+\tres = crypto_wait_req(crypto_aead_encrypt(req), \u0026wait);\n+\tif (res)\n+\t\treturn res;\n+\n+\tdata-\u003ecrypt_size = total;\n+\tdata-\u003ecrypt_total += total;\n+\treturn 0;\n+}\n+\n+/* Decrypt data from the staging area and push it to the snapshot. */\n+static int snapshot_decrypt_drain(struct snapshot_data *data)\n+{\n+\tstruct aead_request *req = data-\u003eaead_req;\n+\tu8 nonce[GCM_AES_IV_SIZE];\n+\tDECLARE_CRYPTO_WAIT(wait);\n+\tint page_count;\n+\tsize_t total;\n+\tint pg_idx;\n+\tint res;\n+\n+\t/* Set up the associated data. */\n+\tsg_set_buf(\u0026data-\u003esg[0], \u0026data-\u003ecrypt_total, sizeof(data-\u003ecrypt_total));\n+\n+\t/*\n+\t * Get the number of full pages, which could be short at the end. There\n+\t * should also be a tag at the end, so the offset won't be an even page.\n+\t */\n+\tpage_count = data-\u003ecrypt_offset \u003e\u003e PAGE_SHIFT;\n+\ttotal = page_count \u003c\u003c PAGE_SHIFT;\n+\tif (total == 0 || total == data-\u003ecrypt_offset)\n+\t\treturn -EINVAL;\n+\n+\t/*\n+\t * Load the sg list with the crypt buffer. Inline decrypt back into the\n+\t * staging buffer. A future optimization could decrypt directly into\n+\t * lowmem pages.\n+\t */\n+\tfor (pg_idx = 0; pg_idx \u003c page_count; pg_idx++)\n+\t\tsg_set_buf(\u0026data-\u003esg[1 + pg_idx], data-\u003ecrypt_pages[pg_idx], PAGE_SIZE);\n+\n+\t/*\n+\t * It's possible this is the final decrypt, or the final decrypt of the\n+\t * meta region, and there are fewer than SNAPSHOT_CHUNK_SIZE pages. If this is\n+\t * the case we would have just written the auth tag into the first few\n+\t * bytes of a new page. Copy to the tag if so.\n+\t */\n+\tif (page_count \u003c SNAPSHOT_CHUNK_SIZE \u0026\u0026\n+\t (data-\u003ecrypt_offset - total) == sizeof(data-\u003eauth_tag)) {\n+\t\tmemcpy(data-\u003eauth_tag, data-\u003ecrypt_pages[pg_idx],\n+\t\t sizeof(data-\u003eauth_tag));\n+\t} else if (data-\u003ecrypt_offset !=\n+\t\t ((SNAPSHOT_CHUNK_SIZE \u003c\u003c PAGE_SHIFT) + SNAPSHOT_AUTH_TAG_SIZE)) {\n+\t\treturn -EINVAL;\n+\t}\n+\n+\tsg_set_buf(\u0026data-\u003esg[1 + pg_idx], \u0026data-\u003eauth_tag, SNAPSHOT_AUTH_TAG_SIZE);\n+\taead_request_set_callback(req, 0, crypto_req_done, \u0026wait);\n+\tmemcpy(\u0026nonce[0], \u0026data-\u003enonce_low, sizeof(data-\u003enonce_low));\n+\tmemcpy(\u0026nonce[sizeof(data-\u003enonce_low)],\n+\t \u0026data-\u003enonce_high,\n+\t sizeof(nonce) - sizeof(data-\u003enonce_low));\n+\n+\tdata-\u003enonce_low += 1;\n+\taead_request_set_crypt(req, data-\u003esg, data-\u003esg, total + SNAPSHOT_AUTH_TAG_SIZE, nonce);\n+\tres = crypto_wait_req(crypto_aead_decrypt(req), \u0026wait);\n+\tif (res)\n+\t\treturn res;\n+\n+\tdata-\u003ecrypt_size = 0;\n+\tdata-\u003ecrypt_offset = 0;\n+\n+\t/* Push the decrypted pages further down the stack. */\n+\ttotal = 0;\n+\tfor (pg_idx = 0; pg_idx \u003c page_count; pg_idx++) {\n+\t\tvoid *buf = data-\u003ecrypt_pages[pg_idx];\n+\n+\t\tres = snapshot_write_next(\u0026data-\u003ehandle);\n+\t\tif (res \u003c 0)\n+\t\t\treturn res;\n+\t\tif (res == 0)\n+\t\t\tbreak;\n+\n+\t\tif (!data_of(data-\u003ehandle))\n+\t\t\treturn -EINVAL;\n+\n+\t\tWARN_ON(res != PAGE_SIZE);\n+\n+\t\t/* Copy the decrypted page into the snapshot image. */\n+\t\tmemcpy(data_of(data-\u003ehandle), buf, PAGE_SIZE);\n+\t\ttotal += PAGE_SIZE;\n+\t}\n+\n+\tif (data-\u003ecrypt_total == 0) {\n+\t\tu64 meta_size = snapshot_get_meta_page_count() \u003c\u003c PAGE_SHIFT;\n+\n+\t\tdata-\u003emeta_size = meta_size;\n+\t\tif (data-\u003euser_key_valid \u0026\u0026\n+\t\t data-\u003ecrypt_meta_size != snapshot_encrypted_byte_count(meta_size))\n+\t\t\treturn -EINVAL;\n+\t}\n+\n+\tdata-\u003ecrypt_total += total;\n+\tres = snapshot_check_user_key_switch(data);\n+\tif (res)\n+\t\treturn res;\n+\n+\treturn 0;\n+}\n+\n+static ssize_t snapshot_read_next_encrypted(struct snapshot_data *data,\n+\t\t\t\t\t void **buf)\n+{\n+\tsize_t tag_off;\n+\n+\t/* Refill the encrypted buffer if it's empty. */\n+\tif (data-\u003ecrypt_size == 0 ||\n+\t (data-\u003ecrypt_offset \u003e=\n+\t (data-\u003ecrypt_size + SNAPSHOT_AUTH_TAG_SIZE))) {\n+\t\tint rc;\n+\n+\t\tdata-\u003ecrypt_size = 0;\n+\t\tdata-\u003ecrypt_offset = 0;\n+\t\trc = snapshot_encrypt_refill(data);\n+\t\tif (rc \u003c 0)\n+\t\t\treturn rc;\n+\t\tif (!data-\u003ecrypt_size)\n+\t\t\treturn 0;\n+\t}\n+\n+\t/* Return data pages if the offset is in that region. */\n+\tif (data-\u003ecrypt_offset \u003c data-\u003ecrypt_size) {\n+\t\tsize_t pg_idx = data-\u003ecrypt_offset \u003e\u003e PAGE_SHIFT;\n+\t\tsize_t pg_off = data-\u003ecrypt_offset \u0026 (PAGE_SIZE - 1);\n+\t\t*buf = data-\u003ecrypt_pages[pg_idx] + pg_off;\n+\t\treturn PAGE_SIZE - pg_off;\n+\t}\n+\n+\t/* Use offsets just beyond the size to return the tag. */\n+\ttag_off = data-\u003ecrypt_offset - data-\u003ecrypt_size;\n+\tif (tag_off \u003e SNAPSHOT_AUTH_TAG_SIZE)\n+\t\ttag_off = SNAPSHOT_AUTH_TAG_SIZE;\n+\n+\t*buf = data-\u003eauth_tag + tag_off;\n+\treturn SNAPSHOT_AUTH_TAG_SIZE - tag_off;\n+}\n+\n+static ssize_t snapshot_write_next_encrypted(struct snapshot_data *data,\n+\t\t\t\t\t void **buf)\n+{\n+\tsize_t size_avail;\n+\tsize_t tag_off;\n+\n+\t/* Return data pages if the offset is in that region. */\n+\tif (data-\u003ecrypt_offset \u003c (PAGE_SIZE * SNAPSHOT_CHUNK_SIZE)) {\n+\t\tsize_t pg_idx = data-\u003ecrypt_offset \u003e\u003e PAGE_SHIFT;\n+\t\tsize_t pg_off = data-\u003ecrypt_offset \u0026 (PAGE_SIZE - 1);\n+\n+\t\t*buf = data-\u003ecrypt_pages[pg_idx] + pg_off;\n+\t\tsize_avail = PAGE_SIZE - pg_off;\n+\t} else {\n+\t\t/* Use offsets just beyond the size to return the tag. */\n+\t\ttag_off = data-\u003ecrypt_offset - (PAGE_SIZE * SNAPSHOT_CHUNK_SIZE);\n+\t\tif (tag_off \u003e SNAPSHOT_AUTH_TAG_SIZE)\n+\t\t\ttag_off = SNAPSHOT_AUTH_TAG_SIZE;\n+\n+\t\t*buf = data-\u003eauth_tag + tag_off;\n+\t\tsize_avail = SNAPSHOT_AUTH_TAG_SIZE - tag_off;\n+\t}\n+\n+\tif (data-\u003euser_key_valid \u0026\u0026 data-\u003ecrypt_meta_size \u0026\u0026\n+\t data-\u003ecrypt_stream_total \u003c data-\u003ecrypt_meta_size) {\n+\t\tu64 meta_avail = data-\u003ecrypt_meta_size - data-\u003ecrypt_stream_total;\n+\n+\t\tsize_avail = min_t(u64, size_avail, meta_avail);\n+\t}\n+\n+\treturn size_avail;\n+}\n+\n+ssize_t snapshot_read_encrypted(struct snapshot_data *data,\n+\t\t\t\tchar __user *buf, size_t count, loff_t *offp)\n+{\n+\tsize_t copy_size;\n+\tsize_t not_done;\n+\tsize_t pg_off;\n+\tvoid *src;\n+\tssize_t src_size;\n+\n+\tif (!count)\n+\t\treturn 0;\n+\n+\tpg_off = *offp \u0026 (PAGE_SIZE - 1);\n+\tcount = min_t(size_t, count, PAGE_SIZE - pg_off);\n+\n+\tsrc_size = snapshot_read_next_encrypted(data, \u0026src);\n+\tif (src_size \u003c= 0)\n+\t\treturn src_size;\n+\n+\tcopy_size = min_t(size_t, count, src_size);\n+\tnot_done = copy_to_user(buf, src, copy_size);\n+\tcopy_size -= not_done;\n+\tif (!copy_size)\n+\t\treturn -EFAULT;\n+\n+\tdata-\u003ecrypt_offset += copy_size;\n+\t*offp += copy_size;\n+\treturn copy_size;\n+}\n+\n+ssize_t snapshot_write_encrypted(struct snapshot_data *data,\n+\t\t\t\t const char __user *buf, size_t count,\n+\t\t\t\t loff_t *offp)\n+{\n+\tsize_t copy_size;\n+\tsize_t not_done;\n+\tsize_t pg_off;\n+\tvoid *dst;\n+\tssize_t dst_size;\n+\tint rc;\n+\n+\tif (!count)\n+\t\treturn 0;\n+\n+\tpg_off = *offp \u0026 (PAGE_SIZE - 1);\n+\tcount = min_t(size_t, count, PAGE_SIZE - pg_off);\n+\n+\tdst_size = snapshot_write_next_encrypted(data, \u0026dst);\n+\tif (dst_size \u003c= 0)\n+\t\treturn dst_size;\n+\n+\tcopy_size = min_t(size_t, count, dst_size);\n+\tnot_done = copy_from_user(dst, buf, copy_size);\n+\tcopy_size -= not_done;\n+\tif (!copy_size)\n+\t\treturn -EFAULT;\n+\n+\tdata-\u003ecrypt_offset += copy_size;\n+\tdata-\u003ecrypt_stream_total += copy_size;\n+\t/*\n+\t * Drain the encrypted buffer if it's full, or if we hit the end of the\n+\t * encrypted metadata and need a key change before user data pages.\n+\t */\n+\tif (data-\u003ecrypt_offset \u003e=\n+\t (PAGE_SIZE * SNAPSHOT_CHUNK_SIZE) + SNAPSHOT_AUTH_TAG_SIZE ||\n+\t (data-\u003euser_key_valid \u0026\u0026 data-\u003ecrypt_meta_size \u0026\u0026\n+\t data-\u003ecrypt_stream_total == data-\u003ecrypt_meta_size)) {\n+\t\trc = snapshot_decrypt_drain(data);\n+\t\tif (rc \u003c 0)\n+\t\t\treturn rc;\n+\t}\n+\n+\t*offp += copy_size;\n+\treturn copy_size;\n+}\n+\n+static void snapshot_reset_encryption_state(struct snapshot_data *data)\n+{\n+\tdata-\u003ecrypt_offset = 0;\n+\tdata-\u003ecrypt_size = 0;\n+\tdata-\u003ecrypt_total = 0;\n+\tdata-\u003ecrypt_stream_total = 0;\n+\tdata-\u003enonce_low = 0;\n+\tdata-\u003enonce_high = 0;\n+\tdata-\u003emeta_size = 0;\n+\tdata-\u003ecrypt_meta_size = 0;\n+\tdata-\u003euser_key_valid = false;\n+\tmemset(data-\u003eauth_tag, 0, sizeof(data-\u003eauth_tag));\n+}\n+\n+void snapshot_teardown_encryption(struct snapshot_data *data)\n+{\n+\tint i;\n+\n+\tif (data-\u003eaead_req) {\n+\t\taead_request_free(data-\u003eaead_req);\n+\t\tdata-\u003eaead_req = NULL;\n+\t}\n+\n+\tif (data-\u003eaead_tfm) {\n+\t\tcrypto_free_aead(data-\u003eaead_tfm);\n+\t\tdata-\u003eaead_tfm = NULL;\n+\t}\n+\n+\tfor (i = 0; i \u003c SNAPSHOT_CHUNK_SIZE; i++) {\n+\t\tif (data-\u003ecrypt_pages[i]) {\n+\t\t\tfree_page((unsigned long)data-\u003ecrypt_pages[i]);\n+\t\t\tdata-\u003ecrypt_pages[i] = NULL;\n+\t\t}\n+\t}\n+\n+\tmemzero_explicit(data-\u003eencryption_key, sizeof(data-\u003eencryption_key));\n+\tmemzero_explicit(data-\u003euser_key, sizeof(data-\u003euser_key));\n+\tsnapshot_reset_encryption_state(data);\n+}\n+\n+static int snapshot_setup_encryption_common(struct snapshot_data *data)\n+{\n+\tint i, rc;\n+\n+\t/* This only works once per hibernate. */\n+\tif (data-\u003eaead_tfm)\n+\t\treturn -EINVAL;\n+\n+\tsnapshot_reset_encryption_state(data);\n+\tmemset(data-\u003ecrypt_pages, 0, sizeof(data-\u003ecrypt_pages));\n+\n+\t/* Set up the encryption transform */\n+\tdata-\u003eaead_tfm = crypto_alloc_aead(\"gcm(aes)\", 0, 0);\n+\tif (IS_ERR(data-\u003eaead_tfm)) {\n+\t\trc = PTR_ERR(data-\u003eaead_tfm);\n+\t\tdata-\u003eaead_tfm = NULL;\n+\t\treturn rc;\n+\t}\n+\n+\trc = -ENOMEM;\n+\tdata-\u003eaead_req = aead_request_alloc(data-\u003eaead_tfm, GFP_KERNEL);\n+\tif (!data-\u003eaead_req)\n+\t\tgoto setup_fail;\n+\n+\t/* Allocate the staging area */\n+\tfor (i = 0; i \u003c SNAPSHOT_CHUNK_SIZE; i++) {\n+\t\tdata-\u003ecrypt_pages[i] = (void *)__get_free_page(GFP_KERNEL);\n+\t\tif (!data-\u003ecrypt_pages[i])\n+\t\t\tgoto setup_fail;\n+\t}\n+\n+\tsg_init_table(data-\u003esg, SNAPSHOT_CHUNK_SIZE + 2);\n+\n+\t/*\n+\t * The associated data will be the offset so that blocks can't be\n+\t * rearranged.\n+\t */\n+\taead_request_set_ad(data-\u003eaead_req, sizeof(data-\u003ecrypt_total));\n+\trc = crypto_aead_setauthsize(data-\u003eaead_tfm, SNAPSHOT_AUTH_TAG_SIZE);\n+\tif (rc)\n+\t\tgoto setup_fail;\n+\n+\treturn 0;\n+\n+setup_fail:\n+\tsnapshot_teardown_encryption(data);\n+\treturn rc;\n+}\n+\n+int snapshot_get_encryption_key(struct snapshot_data *data,\n+\t\t\t\tstruct uswsusp_key_blob __user *key)\n+{\n+\tstruct snapshot_wrapped_key wrapped = {};\n+\tu8 image_key[SNAPSHOT_ENCRYPTION_KEY_SIZE] __nonstring = {};\n+\tu8 nonce[USWSUSP_KEY_NONCE_SIZE];\n+\tint rc;\n+\n+\t/* Don't pull a random key from a world that can be reset. */\n+\tif (data-\u003eready)\n+\t\treturn -EPIPE;\n+\n+\trc = snapshot_setup_encryption_common(data);\n+\tif (rc)\n+\t\treturn rc;\n+\n+\t/* Build a random starting nonce. */\n+\tget_random_bytes(nonce, sizeof(nonce));\n+\tmemcpy(\u0026data-\u003enonce_low, \u0026nonce[0], sizeof(data-\u003enonce_low));\n+\tmemcpy(\u0026data-\u003enonce_high, \u0026nonce[8], sizeof(data-\u003enonce_high));\n+\n+\t/* Build and install a random image encryption key. */\n+\tget_random_bytes(image_key, sizeof(image_key));\n+\trc = snapshot_install_image_key(data, image_key);\n+\tif (rc)\n+\t\tgoto fail;\n+\n+\trc = snapshot_wrap_image_key(image_key, \u0026wrapped);\n+\tif (rc)\n+\t\tgoto fail;\n+\n+\t/* Hand the wrapped key and clear nonce back to user mode. */\n+\trc = put_user(sizeof(wrapped), \u0026key-\u003eblob_len);\n+\tif (rc)\n+\t\tgoto fail;\n+\n+\tBUILD_BUG_ON(sizeof(wrapped) \u003e\n+\t\t sizeof(((struct uswsusp_key_blob *)0)-\u003eblob));\n+\tif (copy_to_user(\u0026key-\u003eblob, \u0026wrapped, sizeof(wrapped))) {\n+\t\trc = -EFAULT;\n+\t\tgoto fail;\n+\t}\n+\n+\tif (copy_to_user(\u0026key-\u003enonce, \u0026nonce, sizeof(nonce))) {\n+\t\trc = -EFAULT;\n+\t\tgoto fail;\n+\t}\n+\n+\tmemzero_explicit(image_key, sizeof(image_key));\n+\tmemzero_explicit(\u0026wrapped, sizeof(wrapped));\n+\treturn 0;\n+\n+fail:\n+\tmemzero_explicit(image_key, sizeof(image_key));\n+\tmemzero_explicit(\u0026wrapped, sizeof(wrapped));\n+\tsnapshot_teardown_encryption(data);\n+\treturn rc;\n+}\n+\n+int snapshot_set_encryption_key(struct snapshot_data *data,\n+\t\t\t\tstruct uswsusp_key_blob __user *key)\n+{\n+\tstruct uswsusp_key_blob *blob;\n+\tstruct snapshot_wrapped_key wrapped = {};\n+\tu8 image_key[SNAPSHOT_ENCRYPTION_KEY_SIZE] __nonstring = {};\n+\tint rc;\n+\n+\t/* It's too late if data's been pushed in. */\n+\tif (data-\u003ehandle.cur)\n+\t\treturn -EPIPE;\n+\n+\trc = snapshot_setup_encryption_common(data);\n+\tif (rc)\n+\t\treturn rc;\n+\n+\t/* Load the key from user mode. */\n+\tblob = memdup_user(key, sizeof(*blob));\n+\tif (IS_ERR(blob)) {\n+\t\trc = PTR_ERR(blob);\n+\t\tgoto crypto_setup_fail;\n+\t}\n+\n+\tif (blob-\u003eblob_len != sizeof(wrapped)) {\n+\t\trc = -EINVAL;\n+\t\tgoto out_blob;\n+\t}\n+\n+\tmemcpy(\u0026wrapped, blob-\u003eblob, sizeof(wrapped));\n+\trc = snapshot_unwrap_image_key(\u0026wrapped, image_key);\n+\tif (rc)\n+\t\tgoto out_blob;\n+\n+\trc = snapshot_install_image_key(data, image_key);\n+\tif (rc)\n+\t\tgoto out_blob;\n+\n+\t/* Load the starting nonce. */\n+\tmemcpy(\u0026data-\u003enonce_low, \u0026blob-\u003enonce[0], sizeof(data-\u003enonce_low));\n+\tmemcpy(\u0026data-\u003enonce_high, \u0026blob-\u003enonce[8], sizeof(data-\u003enonce_high));\n+\n+out_blob:\n+\tkfree_sensitive(blob);\n+\tmemzero_explicit(\u0026wrapped, sizeof(wrapped));\n+\tmemzero_explicit(image_key, sizeof(image_key));\n+\tif (rc)\n+\t\tgoto crypto_setup_fail;\n+\n+\treturn 0;\n+\n+crypto_setup_fail:\n+\tmemzero_explicit(\u0026wrapped, sizeof(wrapped));\n+\tmemzero_explicit(image_key, sizeof(image_key));\n+\tsnapshot_teardown_encryption(data);\n+\treturn rc;\n+}\n+\n+static loff_t snapshot_encrypted_byte_count(loff_t plain_size)\n+{\n+\tloff_t pages = plain_size \u003e\u003e PAGE_SHIFT;\n+\tloff_t chunks = (pages + (SNAPSHOT_CHUNK_SIZE - 1)) / SNAPSHOT_CHUNK_SIZE;\n+\t/*\n+\t * The encrypted size is the normal size, plus a stitched in\n+\t * authentication tag for every chunk of pages.\n+\t */\n+\treturn plain_size + (chunks * SNAPSHOT_AUTH_TAG_SIZE);\n+}\n+\n+static loff_t snapshot_encrypted_split_byte_count(loff_t raw_size,\n+\t\t\t\t\t\t loff_t meta_plain_size)\n+{\n+\tif (raw_size \u003c= meta_plain_size)\n+\t\treturn snapshot_encrypted_byte_count(raw_size);\n+\n+\treturn snapshot_encrypted_byte_count(meta_plain_size) +\n+\t\tsnapshot_encrypted_byte_count(raw_size - meta_plain_size);\n+}\n+\n+int snapshot_set_user_key(struct snapshot_data *data,\n+\t\t\t struct uswsusp_user_key __user *key)\n+{\n+\tstruct uswsusp_user_key user_key = {};\n+\tunsigned int key_len;\n+\tu64 size;\n+\tint rc;\n+\n+\tif (!snapshot_encryption_enabled(data))\n+\t\treturn -EINVAL;\n+\n+\tif (copy_from_user(\u0026user_key, key, sizeof(struct uswsusp_user_key)))\n+\t\treturn -EFAULT;\n+\n+\tBUILD_BUG_ON(sizeof(data-\u003euser_key) \u003c sizeof(user_key.key));\n+\trc = -EINVAL;\n+\tif (user_key.reserved)\n+\t\tgoto out;\n+\tif (user_key.key_len \u003e sizeof(data-\u003euser_key))\n+\t\tgoto out;\n+\tif (user_key.key_len \u003c 8)\n+\t\tgoto out;\n+\n+\tif (data-\u003emode == O_RDONLY \u0026\u0026 !data-\u003eready) {\n+\t\trc = -ENODATA;\n+\t\tgoto out;\n+\t}\n+\n+\t/*\n+\t * Return the metadata size, the number of bytes that can be fed in before\n+\t * the user data key is needed at resume time.\n+\t */\n+\tif (data-\u003emode == O_WRONLY \u0026\u0026 !data-\u003emeta_size) {\n+\t\tif (user_key.meta_size \u003c PAGE_SIZE + SNAPSHOT_AUTH_TAG_SIZE)\n+\t\t\tgoto out;\n+\n+\t\tdata-\u003ecrypt_meta_size = user_key.meta_size;\n+\t\tsize = data-\u003ecrypt_meta_size;\n+\t} else {\n+\t\tsnapshot_set_meta_size(data,\n+\t\t\t\t snapshot_get_meta_page_count() \u003c\u003c PAGE_SHIFT);\n+\t\tsize = data-\u003ecrypt_meta_size;\n+\t}\n+\n+\trc = put_user(size, \u0026key-\u003emeta_size);\n+\tif (rc)\n+\t\tgoto out;\n+\n+\tkey_len = user_key.key_len;\n+\n+\t/* Don't allow it if it's too late. */\n+\tif ((data-\u003emeta_size \u0026\u0026 data-\u003ecrypt_total \u003e data-\u003emeta_size) ||\n+\t (data-\u003ecrypt_meta_size \u0026\u0026\n+\t data-\u003ecrypt_stream_total \u003e data-\u003ecrypt_meta_size)) {\n+\t\trc = -EBUSY;\n+\t\tgoto out;\n+\t}\n+\n+\t/*\n+\t * Resume may preload the user key before writing any image data, or\n+\t * install it after writing exactly the saved metadata stream. In the\n+\t * latter case, authenticate and publish the buffered metadata under the\n+\t * original image key before switching keys.\n+\t */\n+\tif (data-\u003emode == O_WRONLY \u0026\u0026 data-\u003ecrypt_meta_size \u0026\u0026\n+\t data-\u003ecrypt_stream_total == data-\u003ecrypt_meta_size \u0026\u0026\n+\t data-\u003ecrypt_offset) {\n+\t\trc = snapshot_decrypt_drain(data);\n+\t\tif (rc)\n+\t\t\tgoto out;\n+\t\tif (data-\u003ecrypt_total != data-\u003emeta_size) {\n+\t\t\trc = -EINVAL;\n+\t\t\tgoto out;\n+\t\t}\n+\t}\n+\n+\tmemset(data-\u003euser_key, 0, sizeof(data-\u003euser_key));\n+\tmemcpy(data-\u003euser_key, user_key.key, key_len);\n+\tdata-\u003euser_key_valid = true;\n+\t/* Install the key if the user is just under the wire. */\n+\trc = snapshot_check_user_key_switch(data);\n+\tif (rc)\n+\t\tgoto out;\n+\n+\trc = 0;\n+\n+out:\n+\tmemzero_explicit(\u0026user_key, sizeof(user_key));\n+\treturn rc;\n+}\n+\n+loff_t snapshot_get_encrypted_image_size(struct snapshot_data *data,\n+\t\t\t\t\t loff_t raw_size)\n+{\n+\tloff_t meta_plain_size = data-\u003emeta_size;\n+\tloff_t split_size;\n+\n+\tif (!meta_plain_size)\n+\t\tmeta_plain_size = snapshot_get_meta_page_count() \u003c\u003c PAGE_SHIFT;\n+\n+\tsplit_size = snapshot_encrypted_split_byte_count(raw_size,\n+\t\t\t\t\t\t\t meta_plain_size);\n+\tif (!data-\u003euser_key_valid) {\n+\t\t/*\n+\t\t * Userspace may install a user key after querying the image size.\n+\t\t * Reserve enough space for either framing so that later splitting at\n+\t\t * the metadata boundary cannot make the reported size too small.\n+\t\t */\n+\t\treturn max(snapshot_encrypted_byte_count(raw_size), split_size);\n+\t}\n+\n+\treturn split_size;\n+}\n+\n+int snapshot_finalize_decrypted_image(struct snapshot_data *data)\n+{\n+\tint rc;\n+\n+\tif (data-\u003ecrypt_offset != 0) {\n+\t\trc = snapshot_decrypt_drain(data);\n+\t\tif (rc)\n+\t\t\treturn rc;\n+\t}\n+\n+\treturn 0;\n+}\ndiff --git a/kernel/power/snapshot.c b/kernel/power/snapshot.c\nindex b209712cb2c3a..d1a226a25d27e 100644\n--- a/kernel/power/snapshot.c\n+++ b/kernel/power/snapshot.c\n@@ -2177,6 +2177,11 @@ unsigned long snapshot_get_image_size(void)\n \treturn nr_copy_pages + nr_meta_pages + 1;\n }\n \n+unsigned long snapshot_get_meta_page_count(void)\n+{\n+\treturn nr_meta_pages + 1;\n+}\n+\n static int init_header(struct swsusp_info *info)\n {\n \tmemset(info, 0, sizeof(struct swsusp_info));\ndiff --git a/kernel/power/swap.c b/kernel/power/swap.c\nindex c78f1593600bb..ac736d2b59e3f 100644\n--- a/kernel/power/swap.c\n+++ b/kernel/power/swap.c\n@@ -166,6 +166,93 @@ static int swsusp_extents_insert(unsigned long swap_offset)\n \treturn 0;\n }\n \n+static bool swsusp_extents_contain_range(unsigned long swap_offset,\n+\t\t\t\t\t unsigned long nr_pages)\n+{\n+\tstruct rb_node *node = swsusp_extents.rb_node;\n+\tstruct swsusp_extent *ext;\n+\tunsigned long end;\n+\n+\tif (!nr_pages)\n+\t\treturn false;\n+\n+\tend = swap_offset + nr_pages - 1;\n+\tif (end \u003c swap_offset)\n+\t\treturn false;\n+\n+\twhile (node) {\n+\t\text = rb_entry(node, struct swsusp_extent, node);\n+\t\tif (swap_offset \u003c ext-\u003estart)\n+\t\t\tnode = node-\u003erb_left;\n+\t\telse if (swap_offset \u003e ext-\u003eend)\n+\t\t\tnode = node-\u003erb_right;\n+\t\telse\n+\t\t\tgoto found;\n+\t}\n+\n+\treturn false;\n+\n+found:\n+\tfor (;;) {\n+\t\tif (swap_offset \u003c ext-\u003estart)\n+\t\t\treturn false;\n+\t\tif (end \u003c= ext-\u003eend)\n+\t\t\treturn true;\n+\t\tif (ext-\u003eend == (unsigned long)-1)\n+\t\t\treturn false;\n+\n+\t\tswap_offset = ext-\u003eend + 1;\n+\t\tnode = rb_next(\u0026ext-\u003enode);\n+\t\tif (!node)\n+\t\t\treturn false;\n+\n+\t\text = rb_entry(node, struct swsusp_extent, node);\n+\t}\n+}\n+\n+bool swsusp_swap_range_allocated(int swap, loff_t pos, size_t count)\n+{\n+\tu64 block;\n+\tu64 end;\n+\tu64 end_block;\n+\n+\tif (swap \u003c 0 || pos \u003c 0 || !count)\n+\t\treturn false;\n+\n+\tend = (u64)pos + count - 1;\n+\tif (end \u003c (u64)pos)\n+\t\treturn false;\n+\n+\tblock = (u64)pos \u003e\u003e PAGE_SHIFT;\n+\tend_block = end \u003e\u003e PAGE_SHIFT;\n+\n+\tfor (;;) {\n+\t\tu64 remaining_pages = end_block - block + 1;\n+\t\tpgoff_t swap_offset;\n+\t\tpgoff_t mapped_pages;\n+\t\tsector_t page_block = block;\n+\t\tu64 pages;\n+\n+\t\tif (!remaining_pages)\n+\t\t\treturn false;\n+\t\tif ((u64)page_block != block)\n+\t\t\treturn false;\n+\t\tif (swapdev_block_to_extent(swap, page_block, \u0026swap_offset,\n+\t\t\t\t\t \u0026mapped_pages))\n+\t\t\treturn false;\n+\t\tif (!mapped_pages)\n+\t\t\treturn false;\n+\t\tpages = min_t(u64, mapped_pages, remaining_pages);\n+\t\tif ((u64)(unsigned long)pages != pages)\n+\t\t\treturn false;\n+\t\tif (!swsusp_extents_contain_range(swap_offset, pages))\n+\t\t\treturn false;\n+\t\tif (pages == remaining_pages)\n+\t\t\treturn true;\n+\t\tblock += pages;\n+\t}\n+}\n+\n sector_t alloc_swapdev_block(int swap)\n {\n \tunsigned long offset;\ndiff --git a/kernel/power/user.c b/kernel/power/user.c\nindex d0fcfba7ac235..b8d3342f1548f 100644\n--- a/kernel/power/user.c\n+++ b/kernel/power/user.c\n@@ -21,54 +21,196 @@\n #include \u003clinux/console.h\u003e\n #include \u003clinux/cpu.h\u003e\n #include \u003clinux/freezer.h\u003e\n+#include \u003clinux/pid.h\u003e\n+#include \u003clinux/sched/signal.h\u003e\n+#include \u003clinux/security.h\u003e\n \n #include \u003clinux/uaccess.h\u003e\n \n #include \"power.h\"\n+#include \"user.h\"\n \n static bool need_wait;\n-\n-static struct snapshot_data {\n-\tstruct snapshot_handle handle;\n-\tint swap;\n-\tint mode;\n-\tbool frozen;\n-\tbool ready;\n-\tbool platform_support;\n-\tbool free_bitmaps;\n-\tdev_t dev;\n-} snapshot_state;\n+static struct snapshot_data snapshot_state;\n \n int is_hibernate_resume_dev(dev_t dev)\n {\n \treturn hibernation_available() \u0026\u0026 snapshot_state.dev == dev;\n }\n \n+bool hibernate_snapshot_write_active(dev_t dev)\n+{\n+#if defined(CONFIG_ENCRYPTED_HIBERNATION)\n+\tstruct snapshot_data *data = \u0026snapshot_state;\n+\n+\treturn data-\u003eencryption_required \u0026\u0026 data-\u003emode == O_RDONLY \u0026\u0026\n+\t\tdata-\u003eready \u0026\u0026 data-\u003edev == dev \u0026\u0026\n+\t\tsnapshot_encryption_enabled(data);\n+#else\n+\treturn false;\n+#endif\n+}\n+\n+#if defined(CONFIG_ENCRYPTED_HIBERNATION)\n+static bool snapshot_encrypted_output_owned(struct snapshot_data *data, dev_t dev)\n+{\n+\treturn hibernate_snapshot_write_active(dev) \u0026\u0026\n+\t\tdata-\u003eowner_tgid == task_tgid(current);\n+}\n+\n+static bool snapshot_header_write_range(struct snapshot_data *data,\n+\t\t\t\t\tloff_t pos, size_t count)\n+{\n+\tloff_t header_offset = data-\u003eswap_header_offset;\n+\tloff_t offset;\n+\n+\tif (pos \u003c header_offset)\n+\t\treturn false;\n+\n+\toffset = pos - header_offset;\n+\treturn offset \u003c PAGE_SIZE \u0026\u0026 count \u003c= PAGE_SIZE - offset;\n+}\n+\n+static u64 snapshot_swap_write_budget(struct snapshot_data *data)\n+{\n+\tif (data-\u003ecrypt_swap_allocated \u003e U64_MAX \u003e\u003e PAGE_SHIFT)\n+\t\treturn 0;\n+\n+\treturn data-\u003ecrypt_swap_allocated \u003c\u003c PAGE_SHIFT;\n+}\n+\n+static void snapshot_reset_swap_write_state(struct snapshot_data *data,\n+\t\t\t\t\t bool reset_allocation)\n+{\n+\tspin_lock(\u0026data-\u003ecrypt_lock);\n+\tif (reset_allocation)\n+\t\tdata-\u003ecrypt_swap_allocated = 0;\n+\tdata-\u003ecrypt_swap_reserved = 0;\n+\tdata-\u003ecrypt_header_reserved = 0;\n+\tspin_unlock(\u0026data-\u003ecrypt_lock);\n+}\n+#endif\n+\n+enum hibernate_snapshot_write\n+hibernate_snapshot_write_begin(dev_t dev, loff_t pos, size_t count)\n+{\n+#if defined(CONFIG_ENCRYPTED_HIBERNATION)\n+\tstruct snapshot_data *data = \u0026snapshot_state;\n+\tenum hibernate_snapshot_write type = HIBERNATE_SNAPSHOT_WRITE_NONE;\n+\tbool image_range_allocated;\n+\tu64 swap_budget;\n+\n+\tif (!count || !snapshot_encrypted_output_owned(data, dev))\n+\t\treturn HIBERNATE_SNAPSHOT_WRITE_NONE;\n+\n+\tmutex_lock(\u0026system_transition_mutex);\n+\n+\tif (!snapshot_encrypted_output_owned(data, dev))\n+\t\tgoto unlock;\n+\n+\timage_range_allocated = swsusp_swap_range_allocated(data-\u003eswap, pos, count);\n+\n+\tspin_lock(\u0026data-\u003ecrypt_lock);\n+\tswap_budget = snapshot_swap_write_budget(data);\n+\tif (snapshot_header_write_range(data, pos, count) \u0026\u0026\n+\t data-\u003ecrypt_header_reserved \u003c= PAGE_SIZE \u0026\u0026\n+\t PAGE_SIZE - data-\u003ecrypt_header_reserved \u003e= count) {\n+\t\tdata-\u003ecrypt_header_reserved += count;\n+\t\ttype = HIBERNATE_SNAPSHOT_WRITE_HEADER;\n+\t} else if (image_range_allocated \u0026\u0026\n+\t\t swap_budget \u003e= data-\u003ecrypt_swap_reserved \u0026\u0026\n+\t\t swap_budget - data-\u003ecrypt_swap_reserved \u003e= count) {\n+\t\tdata-\u003ecrypt_swap_reserved += count;\n+\t\ttype = HIBERNATE_SNAPSHOT_WRITE_IMAGE;\n+\t}\n+\tspin_unlock(\u0026data-\u003ecrypt_lock);\n+\n+\tif (type == HIBERNATE_SNAPSHOT_WRITE_NONE)\n+\t\tgoto unlock;\n+\n+\treturn type;\n+\n+unlock:\n+\tmutex_unlock(\u0026system_transition_mutex);\n+\treturn HIBERNATE_SNAPSHOT_WRITE_NONE;\n+#else\n+\treturn HIBERNATE_SNAPSHOT_WRITE_NONE;\n+#endif\n+}\n+\n+void hibernate_snapshot_write_end(enum hibernate_snapshot_write type,\n+\t\t\t\t size_t reserved, ssize_t written)\n+{\n+#if defined(CONFIG_ENCRYPTED_HIBERNATION)\n+\tstruct snapshot_data *data = \u0026snapshot_state;\n+\tu64 *reserved_total;\n+\tsize_t unused;\n+\n+\tif (type == HIBERNATE_SNAPSHOT_WRITE_NONE)\n+\t\treturn;\n+\tif (!reserved)\n+\t\tgoto unlock;\n+\n+\tif (type == HIBERNATE_SNAPSHOT_WRITE_HEADER)\n+\t\tunused = reserved;\n+\telse if (written \u003c= 0)\n+\t\tunused = reserved;\n+\telse if (written \u003c reserved)\n+\t\tunused = reserved - written;\n+\telse\n+\t\tgoto unlock;\n+\n+\treserved_total = type == HIBERNATE_SNAPSHOT_WRITE_HEADER ?\n+\t\t\u0026data-\u003ecrypt_header_reserved : \u0026data-\u003ecrypt_swap_reserved;\n+\n+\tspin_lock(\u0026data-\u003ecrypt_lock);\n+\t*reserved_total -= min_t(u64, *reserved_total, unused);\n+\tspin_unlock(\u0026data-\u003ecrypt_lock);\n+\n+unlock:\n+\tmutex_unlock(\u0026system_transition_mutex);\n+#endif\n+}\n+\n+static bool snapshot_encryption_required(struct snapshot_data *data)\n+{\n+\tdata-\u003eencryption_required = security_locked_down(LOCKDOWN_HIBERNATION);\n+\treturn data-\u003eencryption_required;\n+}\n+\n static int snapshot_open(struct inode *inode, struct file *filp)\n {\n \tstruct snapshot_data *data;\n \tunsigned int sleep_flags;\n \tint error;\n \n-\tif (!hibernation_available())\n+\tif (!hibernation_snapshot_dev_available())\n \t\treturn -EPERM;\n \n \tsleep_flags = lock_system_sleep();\n \n \tif (!hibernate_acquire()) {\n \t\terror = -EBUSY;\n-\t\tgoto Unlock;\n+\t\tgoto unlock;\n \t}\n \n \tif ((filp-\u003ef_flags \u0026 O_ACCMODE) == O_RDWR) {\n \t\thibernate_release();\n \t\terror = -ENOSYS;\n-\t\tgoto Unlock;\n+\t\tgoto unlock;\n \t}\n \tnonseekable_open(inode, filp);\n \tdata = \u0026snapshot_state;\n \tfilp-\u003eprivate_data = data;\n \tmemset(\u0026data-\u003ehandle, 0, sizeof(struct snapshot_handle));\n+#if defined(CONFIG_ENCRYPTED_HIBERNATION)\n+\tspin_lock_init(\u0026data-\u003ecrypt_lock);\n+\tdata-\u003ecrypt_swap_allocated = 0;\n+\tdata-\u003ecrypt_swap_reserved = 0;\n+\tdata-\u003ecrypt_header_reserved = 0;\n+\tdata-\u003eswap_header_offset = 0;\n+\tdata-\u003eowner_tgid = NULL;\n+#endif\n \tif ((filp-\u003ef_flags \u0026 O_ACCMODE) == O_RDONLY) {\n \t\t/* Hibernating. The image device should be accessible. */\n \t\tdata-\u003eswap = pin_hibernation_swap_type(swsusp_resume_device, 0);\n@@ -99,8 +241,13 @@ static int snapshot_open(struct inode *inode, struct file *filp)\n \tdata-\u003eready = false;\n \tdata-\u003eplatform_support = false;\n \tdata-\u003edev = 0;\n+\tdata-\u003eencryption_required = snapshot_encryption_required(data);\n+#if defined(CONFIG_ENCRYPTED_HIBERNATION)\n+\tif (!error)\n+\t\tdata-\u003eowner_tgid = get_task_pid(current, PIDTYPE_TGID);\n+#endif\n \n- Unlock:\n+ unlock:\n \tunlock_system_sleep(sleep_flags);\n \n \treturn error;\n@@ -116,6 +263,10 @@ static int snapshot_release(struct inode *inode, struct file *filp)\n \tswsusp_free();\n \tdata = filp-\u003eprivate_data;\n \tdata-\u003edev = 0;\n+#if defined(CONFIG_ENCRYPTED_HIBERNATION)\n+\tput_pid(data-\u003eowner_tgid);\n+\tdata-\u003eowner_tgid = NULL;\n+#endif\n \tfree_all_swap_pages(data-\u003eswap);\n \tunpin_hibernation_swap_type(data-\u003eswap);\n \tif (data-\u003efrozen) {\n@@ -125,6 +276,7 @@ static int snapshot_release(struct inode *inode, struct file *filp)\n \t} else if (data-\u003efree_bitmaps) {\n \t\tfree_basic_memory_bitmaps();\n \t}\n+\tsnapshot_teardown_encryption(data);\n \tpm_notifier_call_chain(data-\u003emode == O_RDONLY ?\n \t\t\tPM_POST_HIBERNATION : PM_POST_RESTORE);\n \thibernate_release();\n@@ -147,12 +299,23 @@ static ssize_t snapshot_read(struct file *filp, char __user *buf,\n \tdata = filp-\u003eprivate_data;\n \tif (!data-\u003eready) {\n \t\tres = -ENODATA;\n-\t\tgoto Unlock;\n+\t\tgoto unlock;\n+\t}\n+\tif (snapshot_encryption_required(data) \u0026\u0026\n+\t !snapshot_encryption_enabled(data)) {\n+\t\tres = -EPERM;\n+\t\tgoto unlock;\n \t}\n+\n+\tif (snapshot_encryption_enabled(data)) {\n+\t\tres = snapshot_read_encrypted(data, buf, count, offp);\n+\t\tgoto unlock;\n+\t}\n+\n \tif (!pg_offp) { /* on page boundary? */\n \t\tres = snapshot_read_next(\u0026data-\u003ehandle);\n \t\tif (res \u003c= 0)\n-\t\t\tgoto Unlock;\n+\t\t\tgoto unlock;\n \t} else {\n \t\tres = PAGE_SIZE - pg_offp;\n \t}\n@@ -162,7 +325,7 @@ static ssize_t snapshot_read(struct file *filp, char __user *buf,\n \tif (res \u003e 0)\n \t\t*offp += res;\n \n- Unlock:\n+ unlock:\n \tunlock_system_sleep(sleep_flags);\n \n \treturn res;\n@@ -185,6 +348,17 @@ static ssize_t snapshot_write(struct file *filp, const char __user *buf,\n \n \tdata = filp-\u003eprivate_data;\n \n+\tif (snapshot_encryption_required(data) \u0026\u0026\n+\t !snapshot_encryption_enabled(data)) {\n+\t\tres = -EPERM;\n+\t\tgoto unlock;\n+\t}\n+\n+\tif (snapshot_encryption_enabled(data)) {\n+\t\tres = snapshot_write_encrypted(data, buf, count, offp);\n+\t\tgoto unlock;\n+\t}\n+\n \tif (!pg_offp) {\n \t\tres = snapshot_write_next(\u0026data-\u003ehandle);\n \t\tif (res \u003c= 0)\n@@ -252,6 +426,9 @@ static int snapshot_set_swap_area(struct snapshot_data *data,\n \tif (data-\u003eswap \u003c 0)\n \t\treturn swdev ? -ENODEV : -EINVAL;\n \tdata-\u003edev = swdev;\n+#if defined(CONFIG_ENCRYPTED_HIBERNATION)\n+\tdata-\u003eswap_header_offset = (loff_t)offset \u003c\u003c PAGE_SHIFT;\n+#endif\n \treturn 0;\n }\n \n@@ -318,6 +495,11 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,\n \t\t\terror = -EPERM;\n \t\t\tbreak;\n \t\t}\n+\t\tif (snapshot_encryption_required(data) \u0026\u0026\n+\t\t !snapshot_encryption_enabled(data)) {\n+\t\t\terror = -EPERM;\n+\t\t\tbreak;\n+\t\t}\n \t\tpm_restore_gfp_mask();\n \t\terror = hibernation_snapshot(data-\u003eplatform_support);\n \t\tif (!error) {\n@@ -328,6 +510,17 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,\n \t\tbreak;\n \n \tcase SNAPSHOT_ATOMIC_RESTORE:\n+\t\tif (snapshot_encryption_required(data) \u0026\u0026\n+\t\t !snapshot_encryption_enabled(data)) {\n+\t\t\terror = -EPERM;\n+\t\t\tbreak;\n+\t\t}\n+\t\tif (snapshot_encryption_enabled(data)) {\n+\t\t\terror = snapshot_finalize_decrypted_image(data);\n+\t\t\tif (error)\n+\t\t\t\tbreak;\n+\t\t}\n+\n \t\terror = snapshot_write_finalize(\u0026data-\u003ehandle);\n \t\tif (error)\n \t\t\tbreak;\n@@ -346,6 +539,10 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,\n \t\tswsusp_free();\n \t\tmemset(\u0026data-\u003ehandle, 0, sizeof(struct snapshot_handle));\n \t\tdata-\u003eready = false;\n+\t\tsnapshot_teardown_encryption(data);\n+#if defined(CONFIG_ENCRYPTED_HIBERNATION)\n+\t\tsnapshot_reset_swap_write_state(data, false);\n+#endif\n \t\t/*\n \t\t * It is necessary to thaw kernel threads here, because\n \t\t * SNAPSHOT_CREATE_IMAGE may be invoked directly after\n@@ -368,6 +565,8 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,\n \t\t}\n \t\tsize = snapshot_get_image_size();\n \t\tsize \u003c\u003c= PAGE_SHIFT;\n+\t\tif (snapshot_encryption_enabled(data))\n+\t\t\tsize = snapshot_get_encrypted_image_size(data, size);\n \t\terror = put_user(size, (loff_t __user *)arg);\n \t\tbreak;\n \n@@ -386,6 +585,13 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,\n \t\tif (offset) {\n \t\t\toffset \u003c\u003c= PAGE_SHIFT;\n \t\t\terror = put_user(offset, (loff_t __user *)arg);\n+#if defined(CONFIG_ENCRYPTED_HIBERNATION)\n+\t\t\tif (!error) {\n+\t\t\t\tspin_lock(\u0026data-\u003ecrypt_lock);\n+\t\t\t\tdata-\u003ecrypt_swap_allocated++;\n+\t\t\t\tspin_unlock(\u0026data-\u003ecrypt_lock);\n+\t\t\t}\n+#endif\n \t\t} else {\n \t\t\terror = -ENOSPC;\n \t\t}\n@@ -397,6 +603,9 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,\n \t\t\tbreak;\n \t\t}\n \t\tfree_all_swap_pages(data-\u003eswap);\n+#if defined(CONFIG_ENCRYPTED_HIBERNATION)\n+\t\tsnapshot_reset_swap_write_state(data, true);\n+#endif\n \t\tbreak;\n \n \tcase SNAPSHOT_S2RAM:\n@@ -404,6 +613,11 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,\n \t\t\terror = -EPERM;\n \t\t\tbreak;\n \t\t}\n+\t\tif (snapshot_encryption_required(data) \u0026\u0026\n+\t\t !snapshot_encryption_enabled(data)) {\n+\t\t\terror = -EPERM;\n+\t\t\tbreak;\n+\t\t}\n \t\t/*\n \t\t * Tasks are frozen and the notifiers have been called with\n \t\t * PM_HIBERNATION_PREPARE\n@@ -417,6 +631,11 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,\n \t\tbreak;\n \n \tcase SNAPSHOT_POWER_OFF:\n+\t\tif (snapshot_encryption_required(data) \u0026\u0026\n+\t\t !snapshot_encryption_enabled(data)) {\n+\t\t\terror = -EPERM;\n+\t\t\tbreak;\n+\t\t}\n \t\tif (data-\u003eplatform_support)\n \t\t\terror = hibernation_platform_enter();\n \t\tbreak;\n@@ -425,6 +644,21 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,\n \t\terror = snapshot_set_swap_area(data, (void __user *)arg);\n \t\tbreak;\n \n+\tcase SNAPSHOT_ENABLE_ENCRYPTION:\n+\t\tif (data-\u003emode == O_RDONLY)\n+\t\t\terror = snapshot_get_encryption_key(data, (void __user *)arg);\n+\t\telse\n+\t\t\terror = snapshot_set_encryption_key(data, (void __user *)arg);\n+#if defined(CONFIG_ENCRYPTED_HIBERNATION)\n+\t\tif (!error)\n+\t\t\tsnapshot_reset_swap_write_state(data, false);\n+#endif\n+\t\tbreak;\n+\n+\tcase SNAPSHOT_SET_USER_KEY:\n+\t\terror = snapshot_set_user_key(data, (void __user *)arg);\n+\t\tbreak;\n+\n \tdefault:\n \t\terror = -ENOTTY;\n \n@@ -448,6 +682,8 @@ snapshot_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)\n \tcase SNAPSHOT_ALLOC_SWAP_PAGE:\n \tcase SNAPSHOT_CREATE_IMAGE:\n \tcase SNAPSHOT_SET_SWAP_AREA:\n+\tcase SNAPSHOT_ENABLE_ENCRYPTION:\n+\tcase SNAPSHOT_SET_USER_KEY:\n \t\treturn snapshot_ioctl(file, cmd,\n \t\t\t\t (unsigned long) compat_ptr(arg));\n \tdefault:\ndiff --git a/kernel/power/user.h b/kernel/power/user.h\nnew file mode 100644\nindex 0000000000000..0e1e123e32300\n--- /dev/null\n+++ b/kernel/power/user.h\n@@ -0,0 +1,150 @@\n+/* SPDX-License-Identifier: GPL-2.0 */\n+\n+#ifndef __POWER_USER_H\n+#define __POWER_USER_H\n+\n+#include \u003clinux/crypto.h\u003e\n+#include \u003clinux/scatterlist.h\u003e\n+#include \u003clinux/spinlock.h\u003e\n+#include \u003clinux/suspend_ioctls.h\u003e\n+#include \u003ccrypto/aead.h\u003e\n+#include \u003ccrypto/aes.h\u003e\n+\n+struct pid;\n+\n+#define SNAPSHOT_ENCRYPTION_KEY_SIZE AES_KEYSIZE_128\n+#define SNAPSHOT_AUTH_TAG_SIZE 16\n+\n+/* Define the number of pages in a single AEAD encryption chunk. */\n+#define SNAPSHOT_CHUNK_SIZE 16\n+\n+struct snapshot_data {\n+\tstruct snapshot_handle handle;\n+\tint swap;\n+\tint mode;\n+\tbool frozen;\n+\tbool ready;\n+\tbool platform_support;\n+\tbool free_bitmaps;\n+\tbool encryption_required;\n+\tdev_t dev;\n+\n+#if defined(CONFIG_ENCRYPTED_HIBERNATION)\n+\tstruct crypto_aead *aead_tfm;\n+\tstruct aead_request *aead_req;\n+\tvoid *crypt_pages[SNAPSHOT_CHUNK_SIZE];\n+\tu8 auth_tag[SNAPSHOT_AUTH_TAG_SIZE];\n+\tstruct scatterlist sg[SNAPSHOT_CHUNK_SIZE + 2]; /* Add room for AD and auth tag. */\n+\tsize_t crypt_offset;\n+\tsize_t crypt_size;\n+\tu64 crypt_total;\n+\tu64 crypt_stream_total;\n+\tu64 nonce_low;\n+\tu64 nonce_high;\n+\tu8 encryption_key[SNAPSHOT_ENCRYPTION_KEY_SIZE] __nonstring;\n+\tu8 user_key[USWSUSP_USER_KEY_SIZE] __nonstring;\n+\tbool user_key_valid;\n+\tu64 meta_size;\n+\tu64 crypt_meta_size;\n+\t/* Protect the swap allocation and block-write reservations. */\n+\tspinlock_t crypt_lock;\n+\tu64 crypt_swap_allocated;\n+\tu64 crypt_swap_reserved;\n+\tu64 crypt_header_reserved;\n+\tloff_t swap_header_offset;\n+\tstruct pid *owner_tgid;\n+#endif\n+\n+};\n+\n+/* kernel/power/snapenc.c routines */\n+#if defined(CONFIG_ENCRYPTED_HIBERNATION)\n+\n+ssize_t snapshot_read_encrypted(struct snapshot_data *data,\n+\t\t\t\tchar __user *buf, size_t count, loff_t *offp);\n+\n+ssize_t snapshot_write_encrypted(struct snapshot_data *data,\n+\t\t\t\t const char __user *buf, size_t count,\n+\t\t\t\t loff_t *offp);\n+\n+void snapshot_teardown_encryption(struct snapshot_data *data);\n+int snapshot_get_encryption_key(struct snapshot_data *data,\n+\t\t\t\tstruct uswsusp_key_blob __user *key);\n+\n+int snapshot_set_encryption_key(struct snapshot_data *data,\n+\t\t\t\tstruct uswsusp_key_blob __user *key);\n+\n+int snapshot_set_user_key(struct snapshot_data *data,\n+\t\t\t struct uswsusp_user_key __user *key);\n+\n+int snapshot_store_encryption_seed(const char *buf, size_t count);\n+\n+loff_t snapshot_get_encrypted_image_size(struct snapshot_data *data,\n+\t\t\t\t\t loff_t raw_size);\n+\n+int snapshot_finalize_decrypted_image(struct snapshot_data *data);\n+\n+static inline bool snapshot_encryption_enabled(struct snapshot_data *data)\n+{\n+\treturn data-\u003eaead_tfm;\n+}\n+\n+#else\n+\n+static inline ssize_t snapshot_read_encrypted(struct snapshot_data *data,\n+\t\t\t\t\t char __user *buf, size_t count,\n+\t\t\t\t\t loff_t *offp)\n+{\n+\treturn -ENOTTY;\n+}\n+\n+static inline ssize_t snapshot_write_encrypted(struct snapshot_data *data,\n+\t\t\t\t\t const char __user *buf,\n+\t\t\t\t\t size_t count, loff_t *offp)\n+{\n+\treturn -ENOTTY;\n+}\n+\n+static inline void snapshot_teardown_encryption(struct snapshot_data *data) {}\n+static inline int snapshot_get_encryption_key(struct snapshot_data *data,\n+\t\t\t\t\t struct uswsusp_key_blob __user *key)\n+{\n+\treturn -ENOTTY;\n+}\n+\n+static inline int snapshot_set_encryption_key(struct snapshot_data *data,\n+\t\t\t\t\t struct uswsusp_key_blob __user *key)\n+{\n+\treturn -ENOTTY;\n+}\n+\n+static inline int snapshot_set_user_key(struct snapshot_data *data,\n+\t\t\t\t\tstruct uswsusp_user_key __user *key)\n+{\n+\treturn -ENOTTY;\n+}\n+\n+static inline int snapshot_store_encryption_seed(const char *buf, size_t count)\n+{\n+\treturn -ENOTTY;\n+}\n+\n+static inline loff_t snapshot_get_encrypted_image_size(struct snapshot_data *data,\n+\t\t\t\t\t\t loff_t raw_size)\n+{\n+\treturn raw_size;\n+}\n+\n+static inline int snapshot_finalize_decrypted_image(struct snapshot_data *data)\n+{\n+\treturn -ENOTTY;\n+}\n+\n+static inline bool snapshot_encryption_enabled(struct snapshot_data *data)\n+{\n+\treturn false;\n+}\n+\n+#endif\n+\n+#endif /* __POWER_USER_H */\ndiff --git a/mm/swapfile.c b/mm/swapfile.c\nindex 601979b97f95b..ebddf954ad840 100644\n--- a/mm/swapfile.c\n+++ b/mm/swapfile.c\n@@ -2379,6 +2379,31 @@ sector_t swapdev_block(int type, pgoff_t offset)\n \treturn se-\u003estart_block + (offset - se-\u003estart_page);\n }\n \n+int swapdev_block_to_extent(int type, sector_t block, pgoff_t *offset,\n+\t\t\t pgoff_t *nr_pages)\n+{\n+\tstruct swap_info_struct *si = swap_type_to_info(type);\n+\tstruct swap_extent *se;\n+\tstruct rb_node *rb;\n+\n+\tif (!si || !(si-\u003eflags \u0026 SWP_WRITEOK))\n+\t\treturn -ENODEV;\n+\n+\tfor (rb = rb_first(\u0026si-\u003eswap_extent_root); rb; rb = rb_next(rb)) {\n+\t\tse = rb_entry(rb, struct swap_extent, rb_node);\n+\t\tif (block \u003e= se-\u003estart_block \u0026\u0026\n+\t\t block - se-\u003estart_block \u003c se-\u003enr_pages) {\n+\t\t\tpgoff_t page = block - se-\u003estart_block;\n+\n+\t\t\t*offset = se-\u003estart_page + page;\n+\t\t\t*nr_pages = se-\u003enr_pages - page;\n+\t\t\treturn 0;\n+\t\t}\n+\t}\n+\n+\treturn -ENOENT;\n+}\n+\n /*\n * Return either the total number of swap pages of given type, or the number\n * of free pages of that type (depending on @free)\n"
} |
| 2/1 | 2026/09/19 12:40 | agent | patch-evaluator |
2mModel:core Args: null Results: {
"EnableConfigs": [
"SWAP",
"HIBERNATION",
"HIBERNATION_SNAPSHOT_DEV",
"ENCRYPTED_HIBERNATION"
],
"FocusSymbols": [
"snapshot_store_encryption_seed",
"snapshot_get_encryption_key",
"snapshot_set_encryption_key",
"snapshot_set_user_key",
"snapshot_read_encrypted",
"snapshot_write_encrypted",
"snapshot_finalize_decrypted_image",
"snapshot_get_encrypted_image_size",
"snapshot_teardown_encryption",
"hibernate_snapshot_write_begin",
"hibernate_snapshot_write_end",
"hibernate_snapshot_write_active",
"hibernation_snapshot_dev_available",
"swsusp_swap_range_allocated",
"swapdev_block_to_extent"
],
"Reasoning": "The patch introduces kernel-based encryption support for userspace hibernation snapshots (/dev/snapshot), adding new ioctls (SNAPSHOT_ENABLE_ENCRYPTION, SNAPSHOT_SET_USER_KEY), sysfs attribute (/sys/power/snapshot_seed), encryption/decryption streaming and AEAD transform management (kernel/power/snapenc.c), block write reservation and extent checking hooks in block/fops.c and mm/swapfile.c, and state management in kernel/power/user.c. All modified code is reachable in standard virtualized environments.",
"WorthFuzzing": true
}Instruction: You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.
IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.
================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.
- REACHABILITY IS THE PRIMARY GATE:
Fuzzing can only discover bugs in code that can actually execute in standard virtualized
environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
regardless of whether it adds assertions or complex logic.
- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
Patch authors routinely label changes as "cleanups", "refactorings", or state
"No functional change intended". Do NOT take these claims at face value.
Code refactorings that rearrange logic, introduce helper functions, or alter state management
in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
If reachable executable code is modified or refactored, it MUST be fuzzed.
- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
Even if the author believes the invariant always holds, fuzzing is essential to verify whether
an unusual sequence of operations can violate it.
================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:
- Non-kernel and non-executable changes:
* Modifications to Documentation/, comments, or spelling fixes.
* User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
that do not affect the compiled kernel image (vmlinux) or kernel modules.
* Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
that do not alter control flow or data structures.
* Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
* Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
* Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
physical PCI hot-unplug or manual sysfs driver unbinding.
* Code paths exclusive to architectures other than the target architecture.
================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
* Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
* Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
* Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
* Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).
================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:
- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
Do NOT list generic, ubiquitous functions called by almost every program in the corpus
(including, but not limited to: general memory allocators and deallocators, page fault
and trap handlers, or core synchronization primitives; this is not an exhaustive list).
Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
which severely dilutes fuzzing effort away from the actual changes.
- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
List functions that specifically implement the logic being added or altered, or direct API entrypoints
for the subsystem feature under review.
- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).
================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit 712876b1fef77d723912a260c8cc2b0ae6fed5c0
Author: syz-cluster <triage@syzkaller.com>
Date: Sat Sep 19 12:40:15 2026 +0000
syz-cluster: applied patch under review
diff --git a/Documentation/ABI/testing/sysfs-power b/Documentation/ABI/testing/sysfs-power
index d38da077905a9..c756712a9df5e 100644
--- a/Documentation/ABI/testing/sysfs-power
+++ b/Documentation/ABI/testing/sysfs-power
@@ -470,3 +470,21 @@ Description:
Minimum value: 1
Default value: 3
+
+What: /sys/power/snapshot_seed
+Date: July 2026
+Contact: linux-pm@vger.kernel.org
+Description:
+ Write-only file present when CONFIG_ENCRYPTED_HIBERNATION=y.
+
+ Trusted early userspace writes a 32-byte seed, encoded as
+ 64 hexadecimal characters plus an optional newline, before
+ enabling encrypted userspace hibernation snapshots.
+
+ The first successful write locks the seed until the next boot.
+ Writing the same seed again succeeds. Writing a different seed
+ fails with EPERM.
+
+ The kernel does not authenticate the first writer. Trusted early
+ userspace must provision this file before untrusted privileged
+ code can run.
diff --git a/Documentation/power/userland-swsusp.rst b/Documentation/power/userland-swsusp.rst
index 1cf62d80a9ca1..957be396dcf5d 100644
--- a/Documentation/power/userland-swsusp.rst
+++ b/Documentation/power/userland-swsusp.rst
@@ -115,6 +115,39 @@ SNAPSHOT_S2RAM
to resume the system from RAM if there's enough battery power or restore
its state on the basis of the saved suspend image otherwise)
+SNAPSHOT_ENABLE_ENCRYPTION
+ Enables encryption of the hibernate image within the kernel. Trusted
+ early userspace must write the 32-byte snapshot encryption seed to
+ /sys/power/snapshot_seed before calling this ioctl. Upon suspend
+ (ie when the snapshot device was opened for reading), this ioctl returns
+ an opaque wrapped key blob and the starting nonce. Upon resume (ie when
+ the snapshot device was opened for writing), this ioctl receives the
+ same blob and nonce from usermode after the same seed has been written
+ to /sys/power/snapshot_seed. The plaintext image key is generated and
+ unwrapped inside the kernel.
+
+ The first successful seed write establishes the wrapping key for that
+ boot. The kernel does not authenticate the writer, the TPM policy used to
+ unseal the seed, or image freshness. Early userspace must provision the
+ seed before untrusted privileged code can run and must enforce any TPM
+ policy and rollback protection.
+
+ Under lockdown, direct block-device write() calls to the active swap
+ backend are restricted to the process which owns the snapshot device and
+ the extents allocated with SNAPSHOT_ALLOC_SWAP_PAGE. These writes must
+ use synchronous buffered I/O (O_DSYNC without O_DIRECT), and cannot
+ exceed the number of pages returned by that ioctl. The swap header may
+ only be written at the offset supplied with SNAPSHOT_SET_SWAP_AREA.
+
+SNAPSHOT_SET_USER_KEY
+ Mixes additional user key material into the data portion of an encrypted
+ hibernate image. The ioctl argument points to struct uswsusp_user_key.
+ key_len must be between 8 and USWSUSP_USER_KEY_SIZE bytes, and reserved
+ must be zero. During hibernation the kernel writes meta_size with the
+ encrypted metadata size. During resume, userspace passes the saved
+ meta_size back so the kernel can switch keys at the metadata boundary
+ before the snapshot header has been decrypted.
+
The device's read() operation can be used to transfer the snapshot image from
the kernel. It has the following limitations:
diff --git a/block/fops.c b/block/fops.c
index 2ce7c6c4714e4..bdc9f2cf7156f 100644
--- a/block/fops.c
+++ b/block/fops.c
@@ -725,43 +725,68 @@ static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
struct file *file = iocb->ki_filp;
struct inode *bd_inode = bdev_file_inode(file);
struct block_device *bdev = I_BDEV(bd_inode);
+ dev_t dev = bd_inode->i_rdev;
bool atomic = iocb->ki_flags & IOCB_ATOMIC;
loff_t size = bdev_nr_bytes(bdev);
+ enum hibernate_snapshot_write hibernate_write;
+ bool hibernate_active;
+ size_t hibernate_len = 0;
size_t shorted = 0;
+ ssize_t hibernate_written = 0;
ssize_t ret;
if (bdev_read_only(bdev))
return -EPERM;
- if (IS_SWAPFILE(bd_inode) && !is_hibernate_resume_dev(bd_inode->i_rdev))
- return -ETXTBSY;
+ hibernate_active = hibernate_snapshot_write_active(dev);
+ if ((IS_SWAPFILE(bd_inode) && !is_hibernate_resume_dev(dev)) ||
+ hibernate_active) {
+ if (!is_sync_kiocb(iocb) || !iocb_is_dsync(iocb) ||
+ (iocb->ki_flags & IOCB_DIRECT))
+ return -ETXTBSY;
+
+ hibernate_len = iov_iter_count(from);
+ hibernate_write = hibernate_snapshot_write_begin(dev, iocb->ki_pos, hibernate_len);
+ if (hibernate_write == HIBERNATE_SNAPSHOT_WRITE_NONE)
+ return -ETXTBSY;
+ } else {
+ hibernate_write = HIBERNATE_SNAPSHOT_WRITE_NONE;
+ }
- if (!iov_iter_count(from))
- return 0;
+ if (!iov_iter_count(from)) {
+ ret = 0;
+ goto out_hibernate;
+ }
- if (iocb->ki_pos >= size)
- return -ENOSPC;
+ if (iocb->ki_pos >= size) {
+ ret = -ENOSPC;
+ goto out_hibernate;
+ }
- if ((iocb->ki_flags & (IOCB_NOWAIT | IOCB_DIRECT)) == IOCB_NOWAIT)
- return -EOPNOTSUPP;
+ if ((iocb->ki_flags & (IOCB_NOWAIT | IOCB_DIRECT)) == IOCB_NOWAIT) {
+ ret = -EOPNOTSUPP;
+ goto out_hibernate;
+ }
if (atomic) {
ret = generic_atomic_write_valid(iocb, from);
if (ret)
- return ret;
+ goto out_hibernate;
}
size -= iocb->ki_pos;
if (iov_iter_count(from) > size) {
- if (atomic)
- return -EINVAL;
+ if (atomic) {
+ ret = -EINVAL;
+ goto out_hibernate;
+ }
shorted = iov_iter_count(from) - size;
iov_iter_truncate(from, size);
}
ret = file_update_time(file);
if (ret)
- return ret;
+ goto out_hibernate;
if (iocb->ki_flags & IOCB_DIRECT) {
ret = blkdev_direct_write(iocb, from);
@@ -779,9 +804,16 @@ static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
inode_unlock_shared(bd_inode);
}
- if (ret > 0)
+ if (ret > 0) {
+ hibernate_written = ret;
ret = generic_write_sync(iocb, ret);
+ }
iov_iter_reexpand(from, iov_iter_count(from) + shorted);
+
+out_hibernate:
+ if (hibernate_len)
+ hibernate_snapshot_write_end(hibernate_write, hibernate_len,
+ hibernate_written);
return ret;
}
diff --git a/include/linux/suspend.h b/include/linux/suspend.h
index b02876f1ae38a..a2a8863f89cf1 100644
--- a/include/linux/suspend.h
+++ b/include/linux/suspend.h
@@ -426,10 +426,34 @@ static inline bool pm_hibernation_mode_is_suspend(void) { return false; }
int arch_resume_nosmt(void);
+enum hibernate_snapshot_write {
+ HIBERNATE_SNAPSHOT_WRITE_NONE,
+ HIBERNATE_SNAPSHOT_WRITE_IMAGE,
+ HIBERNATE_SNAPSHOT_WRITE_HEADER,
+};
+
#ifdef CONFIG_HIBERNATION_SNAPSHOT_DEV
int is_hibernate_resume_dev(dev_t dev);
+bool hibernate_snapshot_write_active(dev_t dev);
+enum hibernate_snapshot_write
+hibernate_snapshot_write_begin(dev_t dev, loff_t pos, size_t count);
+void hibernate_snapshot_write_end(enum hibernate_snapshot_write type,
+ size_t reserved, ssize_t written);
#else
static inline int is_hibernate_resume_dev(dev_t dev) { return 0; }
+static inline bool hibernate_snapshot_write_active(dev_t dev) { return false; }
+
+static inline enum hibernate_snapshot_write
+hibernate_snapshot_write_begin(dev_t dev, loff_t pos, size_t count)
+{
+ return HIBERNATE_SNAPSHOT_WRITE_NONE;
+}
+
+static inline void hibernate_snapshot_write_end(enum hibernate_snapshot_write type,
+ size_t reserved,
+ ssize_t written)
+{
+}
#endif
/* Hibernation and suspend events */
diff --git a/include/linux/swap.h b/include/linux/swap.h
index 5658a1634b85e..deab983ef3d65 100644
--- a/include/linux/swap.h
+++ b/include/linux/swap.h
@@ -377,6 +377,8 @@ extern int find_hibernation_swap_type(dev_t device, sector_t offset);
int find_first_swap(dev_t *device);
extern unsigned int count_swap_pages(int, int);
extern sector_t swapdev_block(int, pgoff_t);
+int swapdev_block_to_extent(int type, sector_t block, pgoff_t *offset,
+ pgoff_t *nr_pages);
extern int __swap_count(swp_entry_t entry);
extern bool swap_entry_swapped(struct swap_info_struct *si, swp_entry_t entry);
extern int swp_swapcount(swp_entry_t entry);
@@ -472,6 +474,13 @@ static inline int add_swap_extent(struct swap_info_struct *sis,
{
return -EINVAL;
}
+
+static inline int swapdev_block_to_extent(int type, sector_t block,
+ pgoff_t *offset,
+ pgoff_t *nr_pages)
+{
+ return -EINVAL;
+}
#endif /* CONFIG_SWAP */
#ifdef CONFIG_MEMCG
void lru_reparent_memcg(struct mem_cgroup *memcg, struct mem_cgroup *parent, int nid);
diff --git a/include/uapi/linux/suspend_ioctls.h b/include/uapi/linux/suspend_ioctls.h
index bcce04e21c0dc..5e23bf936277e 100644
--- a/include/uapi/linux/suspend_ioctls.h
+++ b/include/uapi/linux/suspend_ioctls.h
@@ -13,6 +13,31 @@ struct resume_swap_area {
__u32 dev;
} __attribute__((packed));
+#define USWSUSP_KEY_NONCE_SIZE 16
+#define USWSUSP_USER_KEY_SIZE 32
+
+/*
+ * This structure is used to pass the opaque wrapped hibernate image
+ * encryption key and starting nonce in either direction.
+ */
+struct uswsusp_key_blob {
+ __u32 blob_len;
+ __u8 blob[512];
+ __u8 nonce[USWSUSP_KEY_NONCE_SIZE] __kernel_nonstring;
+} __attribute__((packed));
+
+/*
+ * Allow user mode to fold in key material for the data portion of the hibernate
+ * image.
+ */
+struct uswsusp_user_key {
+ /* Kernel returns the metadata size; resume passes the saved value in. */
+ __u64 meta_size;
+ __u32 key_len;
+ __u32 reserved;
+ __u8 key[USWSUSP_USER_KEY_SIZE] __kernel_nonstring;
+} __attribute__((packed));
+
#define SNAPSHOT_IOC_MAGIC '3'
#define SNAPSHOT_FREEZE _IO(SNAPSHOT_IOC_MAGIC, 1)
#define SNAPSHOT_UNFREEZE _IO(SNAPSHOT_IOC_MAGIC, 2)
@@ -29,6 +54,10 @@ struct resume_swap_area {
#define SNAPSHOT_PREF_IMAGE_SIZE _IO(SNAPSHOT_IOC_MAGIC, 18)
#define SNAPSHOT_AVAIL_SWAP_SIZE _IOR(SNAPSHOT_IOC_MAGIC, 19, __kernel_loff_t)
#define SNAPSHOT_ALLOC_SWAP_PAGE _IOR(SNAPSHOT_IOC_MAGIC, 20, __kernel_loff_t)
-#define SNAPSHOT_IOC_MAXNR 20
+#define SNAPSHOT_ENABLE_ENCRYPTION _IOWR(SNAPSHOT_IOC_MAGIC, 21, \
+ struct uswsusp_key_blob)
+#define SNAPSHOT_SET_USER_KEY _IOWR(SNAPSHOT_IOC_MAGIC, 22, \
+ struct uswsusp_user_key)
+#define SNAPSHOT_IOC_MAXNR 22
#endif /* _LINUX_SUSPEND_IOCTLS_H */
diff --git a/kernel/power/Kconfig b/kernel/power/Kconfig
index 71165e7f04f47..f23d1c7e0ecd1 100644
--- a/kernel/power/Kconfig
+++ b/kernel/power/Kconfig
@@ -115,6 +115,21 @@ config HIBERNATION_DEF_COMP
help
Default compressor to be used for hibernation.
+config ENCRYPTED_HIBERNATION
+ bool "Encryption support for userspace snapshots"
+ depends on HIBERNATION_SNAPSHOT_DEV
+ select CRYPTO_AES
+ select CRYPTO_GCM
+ select CRYPTO_LIB_SHA256
+ help
+ Enable support for kernel-based encryption of hibernation snapshots
+ created by uswsusp tools. A trusted early userspace component must
+ provide the snapshot encryption seed before enabling encryption.
+
+ Say N if userspace handles the image encryption.
+
+ If in doubt, say N.
+
config PM_STD_PARTITION
string "Default resume partition"
depends on HIBERNATION
diff --git a/kernel/power/Makefile b/kernel/power/Makefile
index 773e2789412b9..2fd31b2a250f5 100644
--- a/kernel/power/Makefile
+++ b/kernel/power/Makefile
@@ -16,6 +16,7 @@ obj-$(CONFIG_SUSPEND) += suspend.o
obj-$(CONFIG_PM_TEST_SUSPEND) += suspend_test.o
obj-$(CONFIG_HIBERNATION) += hibernate.o snapshot.o swap.o
obj-$(CONFIG_HIBERNATION_SNAPSHOT_DEV) += user.o
+obj-$(CONFIG_ENCRYPTED_HIBERNATION) += snapenc.o
obj-$(CONFIG_PM_AUTOSLEEP) += autosleep.o
obj-$(CONFIG_PM_WAKELOCKS) += wakelock.o
diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c
index d2479c69d71a4..0b8626bdf81a8 100644
--- a/kernel/power/hibernate.c
+++ b/kernel/power/hibernate.c
@@ -36,6 +36,7 @@
#include <trace/events/power.h>
#include "power.h"
+#include "user.h"
static int nocompress;
@@ -113,6 +114,14 @@ bool hibernation_available(void)
!secretmem_active() && !cxl_mem_active();
}
+bool hibernation_snapshot_dev_available(void)
+{
+ return nohibernate == 0 &&
+ (!security_locked_down(LOCKDOWN_HIBERNATION) ||
+ IS_ENABLED(CONFIG_ENCRYPTED_HIBERNATION)) &&
+ !secretmem_active() && !cxl_mem_active();
+}
+
/**
* hibernation_set_ops - Set the global hibernate operations.
* @ops: Hibernation operations to use in subsequent hibernation transitions.
@@ -1376,12 +1385,35 @@ static ssize_t reserved_size_store(struct kobject *kobj,
power_attr(reserved_size);
+#ifdef CONFIG_ENCRYPTED_HIBERNATION
+static ssize_t snapshot_seed_store(struct kobject *kobj,
+ struct kobj_attribute *attr,
+ const char *buf, size_t n)
+{
+ int ret;
+
+ ret = snapshot_store_encryption_seed(buf, n);
+ return ret ? ret : n;
+}
+
+static struct kobj_attribute snapshot_seed_attr = {
+ .attr = {
+ .name = "snapshot_seed",
+ .mode = 0200,
+ },
+ .store = snapshot_seed_store,
+};
+#endif
+
static struct attribute *g[] = {
&disk_attr.attr,
&resume_offset_attr.attr,
&resume_attr.attr,
&image_size_attr.attr,
&reserved_size_attr.attr,
+#ifdef CONFIG_ENCRYPTED_HIBERNATION
+ &snapshot_seed_attr.attr,
+#endif
NULL,
};
diff --git a/kernel/power/power.h b/kernel/power/power.h
index 75b63843886ee..351b5f68bde34 100644
--- a/kernel/power/power.h
+++ b/kernel/power/power.h
@@ -160,6 +160,7 @@ struct snapshot_handle {
extern unsigned int snapshot_additional_pages(struct zone *zone);
extern unsigned long snapshot_get_image_size(void);
+unsigned long snapshot_get_meta_page_count(void);
extern int snapshot_read_next(struct snapshot_handle *handle);
extern int snapshot_write_next(struct snapshot_handle *handle);
int snapshot_write_finalize(struct snapshot_handle *handle);
@@ -167,8 +168,10 @@ extern int snapshot_image_loaded(struct snapshot_handle *handle);
extern bool hibernate_acquire(void);
extern void hibernate_release(void);
+bool hibernation_snapshot_dev_available(void);
extern sector_t alloc_swapdev_block(int swap);
+bool swsusp_swap_range_allocated(int swap, loff_t pos, size_t count);
extern void free_all_swap_pages(int swap);
extern int swsusp_swap_in_use(void);
diff --git a/kernel/power/snapenc.c b/kernel/power/snapenc.c
new file mode 100644
index 0000000000000..b555a699b5644
--- /dev/null
+++ b/kernel/power/snapenc.c
@@ -0,0 +1,952 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* This file provides encryption support for system snapshots. */
+
+#include <linux/crypto.h>
+#include <crypto/aead.h>
+#include <crypto/gcm.h>
+#include <crypto/sha2.h>
+#include <crypto/utils.h>
+#include <linux/hex.h>
+#include <linux/mutex.h>
+#include <linux/random.h>
+#include <linux/mm.h>
+#include <linux/slab.h>
+#include <linux/string.h>
+#include <linux/uaccess.h>
+
+#include "power.h"
+#include "user.h"
+
+#define SNAPSHOT_SEED_SIZE SHA256_DIGEST_SIZE
+#define SNAPSHOT_KEY_BLOB_VERSION 1
+
+static const u8 snapshot_key_blob_magic[8] = {
+ 'S', 'W', 'S', 'U', 'S', 'P', 'K', '1',
+};
+
+struct snapshot_wrapped_key {
+ u8 magic[sizeof(snapshot_key_blob_magic)];
+ __le32 version;
+ u8 wrap_nonce[GCM_AES_IV_SIZE] __nonstring;
+ u8 encrypted_key[SNAPSHOT_ENCRYPTION_KEY_SIZE] __nonstring;
+ u8 tag[SNAPSHOT_AUTH_TAG_SIZE] __nonstring;
+} __packed;
+
+static DEFINE_MUTEX(snapshot_seed_mutex);
+static u8 snapshot_seed[SNAPSHOT_SEED_SIZE] __nonstring;
+static bool snapshot_seed_valid;
+
+int snapshot_store_encryption_seed(const char *buf, size_t count)
+{
+ u8 seed[SNAPSHOT_SEED_SIZE] __nonstring;
+ size_t len = count;
+ int ret;
+
+ if (len && buf[len - 1] == '\n')
+ len--;
+ if (len != SNAPSHOT_SEED_SIZE * 2)
+ return -EINVAL;
+
+ ret = hex2bin(seed, buf, sizeof(seed));
+ if (ret)
+ return ret;
+
+ mutex_lock(&snapshot_seed_mutex);
+ if (snapshot_seed_valid) {
+ ret = crypto_memneq(snapshot_seed, seed, sizeof(seed)) ? -EPERM : 0;
+ goto out;
+ }
+
+ memcpy(snapshot_seed, seed, sizeof(seed));
+ snapshot_seed_valid = true;
+ pr_info("PM: hibernate: snapshot encryption seed locked\n");
+
+out:
+ mutex_unlock(&snapshot_seed_mutex);
+ memzero_explicit(seed, sizeof(seed));
+ return ret;
+}
+
+static bool snapshot_copy_encryption_seed(u8 seed[SNAPSHOT_SEED_SIZE])
+{
+ bool valid;
+
+ mutex_lock(&snapshot_seed_mutex);
+ valid = snapshot_seed_valid;
+ if (valid)
+ memcpy(seed, snapshot_seed, SNAPSHOT_SEED_SIZE);
+ mutex_unlock(&snapshot_seed_mutex);
+
+ return valid;
+}
+
+static int snapshot_derive_wrapping_key(u8 key[SNAPSHOT_ENCRYPTION_KEY_SIZE])
+{
+ static const char label[] = "Linux hibernate snapshot key wrap v1";
+ u8 digest[SHA256_DIGEST_SIZE];
+ u8 seed[SNAPSHOT_SEED_SIZE] __nonstring;
+ struct sha256_ctx sha256_ctx;
+
+ if (!snapshot_copy_encryption_seed(seed))
+ return -ENOKEY;
+
+ sha256_init(&sha256_ctx);
+ sha256_update(&sha256_ctx, label, strlen(label));
+ sha256_update(&sha256_ctx, seed, sizeof(seed));
+ sha256_final(&sha256_ctx, digest);
+
+ memcpy(key, digest, SNAPSHOT_ENCRYPTION_KEY_SIZE);
+ memzero_explicit(seed, sizeof(seed));
+ memzero_explicit(digest, sizeof(digest));
+ return 0;
+}
+
+static int snapshot_crypt_wrapped_key(struct snapshot_wrapped_key *wrapped,
+ u8 image_key[SNAPSHOT_ENCRYPTION_KEY_SIZE],
+ bool encrypt)
+{
+ u8 wrap_key[SNAPSHOT_ENCRYPTION_KEY_SIZE] __nonstring;
+ u8 buf[SNAPSHOT_ENCRYPTION_KEY_SIZE + SNAPSHOT_AUTH_TAG_SIZE] __nonstring;
+ struct crypto_aead *tfm;
+ struct aead_request *req;
+ struct scatterlist sg;
+ DECLARE_CRYPTO_WAIT(wait);
+ int rc;
+
+ rc = snapshot_derive_wrapping_key(wrap_key);
+ if (rc)
+ return rc;
+
+ tfm = crypto_alloc_aead("gcm(aes)", 0, 0);
+ if (IS_ERR(tfm)) {
+ rc = PTR_ERR(tfm);
+ goto out_key;
+ }
+
+ rc = crypto_aead_setkey(tfm, wrap_key, sizeof(wrap_key));
+ if (rc)
+ goto out_tfm;
+
+ rc = crypto_aead_setauthsize(tfm, SNAPSHOT_AUTH_TAG_SIZE);
+ if (rc)
+ goto out_tfm;
+
+ req = aead_request_alloc(tfm, GFP_KERNEL);
+ if (!req) {
+ rc = -ENOMEM;
+ goto out_tfm;
+ }
+
+ if (encrypt) {
+ get_random_bytes(wrapped->wrap_nonce, sizeof(wrapped->wrap_nonce));
+ memcpy(buf, image_key, SNAPSHOT_ENCRYPTION_KEY_SIZE);
+ } else {
+ memcpy(buf, wrapped->encrypted_key, SNAPSHOT_ENCRYPTION_KEY_SIZE);
+ memcpy(buf + SNAPSHOT_ENCRYPTION_KEY_SIZE, wrapped->tag,
+ SNAPSHOT_AUTH_TAG_SIZE);
+ }
+
+ sg_init_one(&sg, buf, sizeof(buf));
+ aead_request_set_callback(req, 0, crypto_req_done, &wait);
+ aead_request_set_ad(req, 0);
+ aead_request_set_crypt(req, &sg, &sg,
+ encrypt ? SNAPSHOT_ENCRYPTION_KEY_SIZE :
+ sizeof(buf),
+ wrapped->wrap_nonce);
+
+ rc = crypto_wait_req(encrypt ? crypto_aead_encrypt(req) :
+ crypto_aead_decrypt(req),
+ &wait);
+ if (rc)
+ goto out_req;
+
+ if (encrypt) {
+ memcpy(wrapped->encrypted_key, buf, SNAPSHOT_ENCRYPTION_KEY_SIZE);
+ memcpy(wrapped->tag, buf + SNAPSHOT_ENCRYPTION_KEY_SIZE,
+ SNAPSHOT_AUTH_TAG_SIZE);
+ } else {
+ memcpy(image_key, buf, SNAPSHOT_ENCRYPTION_KEY_SIZE);
+ }
+
+out_req:
+ aead_request_free(req);
+out_tfm:
+ crypto_free_aead(tfm);
+out_key:
+ memzero_explicit(buf, sizeof(buf));
+ memzero_explicit(wrap_key, sizeof(wrap_key));
+ return rc;
+}
+
+static int snapshot_wrap_image_key(const u8 image_key[SNAPSHOT_ENCRYPTION_KEY_SIZE],
+ struct snapshot_wrapped_key *wrapped)
+{
+ u8 key[SNAPSHOT_ENCRYPTION_KEY_SIZE] __nonstring;
+ int rc;
+
+ memset(wrapped, 0, sizeof(*wrapped));
+ memcpy(wrapped->magic, snapshot_key_blob_magic, sizeof(wrapped->magic));
+ wrapped->version = cpu_to_le32(SNAPSHOT_KEY_BLOB_VERSION);
+
+ memcpy(key, image_key, sizeof(key));
+ rc = snapshot_crypt_wrapped_key(wrapped, key, true);
+ memzero_explicit(key, sizeof(key));
+ return rc;
+}
+
+static int snapshot_unwrap_image_key(const struct snapshot_wrapped_key *wrapped,
+ u8 image_key[SNAPSHOT_ENCRYPTION_KEY_SIZE])
+{
+ struct snapshot_wrapped_key tmp;
+ int rc;
+
+ if (memcmp(wrapped->magic, snapshot_key_blob_magic,
+ sizeof(snapshot_key_blob_magic)))
+ return -EINVAL;
+ if (le32_to_cpu(wrapped->version) != SNAPSHOT_KEY_BLOB_VERSION)
+ return -EINVAL;
+
+ tmp = *wrapped;
+ rc = snapshot_crypt_wrapped_key(&tmp, image_key, false);
+ memzero_explicit(&tmp, sizeof(tmp));
+ return rc;
+}
+
+static int snapshot_install_image_key(struct snapshot_data *data,
+ const u8 image_key[SNAPSHOT_ENCRYPTION_KEY_SIZE])
+{
+ int rc;
+
+ memcpy(data->encryption_key, image_key, sizeof(data->encryption_key));
+ rc = crypto_aead_setkey(data->aead_tfm, data->encryption_key,
+ sizeof(data->encryption_key));
+ if (rc)
+ memzero_explicit(data->encryption_key,
+ sizeof(data->encryption_key));
+
+ return rc;
+}
+
+/* Derive a key from the kernel and user keys for data encryption. */
+static int snapshot_use_user_key(struct snapshot_data *data)
+{
+ u8 digest[SHA256_DIGEST_SIZE];
+ struct sha256_ctx sha256_ctx;
+ int rc;
+
+ /*
+ * Hash the kernel key and the user key together. This folds in the user
+ * key, but not in a way that gives the user mode predictable control
+ * over the key bits.
+ */
+ sha256_init(&sha256_ctx);
+
+ sha256_update(&sha256_ctx, data->encryption_key,
+ SNAPSHOT_ENCRYPTION_KEY_SIZE);
+ sha256_update(&sha256_ctx, data->user_key, sizeof(data->user_key));
+ sha256_final(&sha256_ctx, digest);
+
+ BUILD_BUG_ON(SNAPSHOT_ENCRYPTION_KEY_SIZE > SHA256_DIGEST_SIZE);
+
+ rc = crypto_aead_setkey(data->aead_tfm,
+ digest,
+ SNAPSHOT_ENCRYPTION_KEY_SIZE);
+ memzero_explicit(digest, sizeof(digest));
+
+ return rc;
+}
+
+/* Check to see if it's time to switch to the user key, and do it if so. */
+static int snapshot_check_user_key_switch(struct snapshot_data *data)
+{
+ if (data->user_key_valid && data->meta_size &&
+ data->crypt_total == data->meta_size) {
+ return snapshot_use_user_key(data);
+ }
+
+ return 0;
+}
+
+static loff_t snapshot_encrypted_byte_count(loff_t plain_size);
+
+static void snapshot_set_meta_size(struct snapshot_data *data, u64 meta_size)
+{
+ data->meta_size = meta_size;
+ data->crypt_meta_size = snapshot_encrypted_byte_count(meta_size);
+}
+
+/* Encrypt more data from the snapshot into the staging area. */
+static int snapshot_encrypt_refill(struct snapshot_data *data)
+{
+ struct aead_request *req = data->aead_req;
+ u8 nonce[GCM_AES_IV_SIZE];
+ DECLARE_CRYPTO_WAIT(wait);
+ size_t total = 0;
+ int pg_idx;
+ int res;
+
+ if (data->crypt_total == 0) {
+ snapshot_set_meta_size(data,
+ snapshot_get_meta_page_count() << PAGE_SHIFT);
+ } else {
+ res = snapshot_check_user_key_switch(data);
+ if (res)
+ return res;
+ }
+
+ /*
+ * The first buffer is the associated data, set to the offset to prevent
+ * attacks that rearrange chunks.
+ */
+ sg_set_buf(&data->sg[0], &data->crypt_total, sizeof(data->crypt_total));
+
+ /* Load the crypt buffer with snapshot pages. */
+ for (pg_idx = 0; pg_idx < SNAPSHOT_CHUNK_SIZE; pg_idx++) {
+ void *buf = data->crypt_pages[pg_idx];
+
+ /* Stop at the meta page boundary before switching keys. */
+ if (data->user_key_valid && total &&
+ ((data->crypt_total + total) == data->meta_size))
+ break;
+
+ res = snapshot_read_next(&data->handle);
+ if (res < 0)
+ return res;
+ if (res == 0)
+ break;
+
+ WARN_ON(res != PAGE_SIZE);
+
+ /*
+ * Copy the page into the staging area. A future optimization
+ * could potentially skip this copy for lowmem pages.
+ */
+ memcpy(buf, data_of(data->handle), PAGE_SIZE);
+ sg_set_buf(&data->sg[1 + pg_idx], buf, PAGE_SIZE);
+ total += PAGE_SIZE;
+ }
+
+ if (!total)
+ return 0;
+
+ sg_set_buf(&data->sg[1 + pg_idx], &data->auth_tag, SNAPSHOT_AUTH_TAG_SIZE);
+ aead_request_set_callback(req, 0, crypto_req_done, &wait);
+ /*
+ * Use incrementing nonces for each chunk, since a 64 bit value won't
+ * roll into re-use for any given hibernate image.
+ */
+ memcpy(&nonce[0], &data->nonce_low, sizeof(data->nonce_low));
+ memcpy(&nonce[sizeof(data->nonce_low)],
+ &data->nonce_high,
+ sizeof(nonce) - sizeof(data->nonce_low));
+
+ data->nonce_low += 1;
+ /* Total does not include AAD or the auth tag. */
+ aead_request_set_crypt(req, data->sg, data->sg, total, nonce);
+ res = crypto_wait_req(crypto_aead_encrypt(req), &wait);
+ if (res)
+ return res;
+
+ data->crypt_size = total;
+ data->crypt_total += total;
+ return 0;
+}
+
+/* Decrypt data from the staging area and push it to the snapshot. */
+static int snapshot_decrypt_drain(struct snapshot_data *data)
+{
+ struct aead_request *req = data->aead_req;
+ u8 nonce[GCM_AES_IV_SIZE];
+ DECLARE_CRYPTO_WAIT(wait);
+ int page_count;
+ size_t total;
+ int pg_idx;
+ int res;
+
+ /* Set up the associated data. */
+ sg_set_buf(&data->sg[0], &data->crypt_total, sizeof(data->crypt_total));
+
+ /*
+ * Get the number of full pages, which could be short at the end. There
+ * should also be a tag at the end, so the offset won't be an even page.
+ */
+ page_count = data->crypt_offset >> PAGE_SHIFT;
+ total = page_count << PAGE_SHIFT;
+ if (total == 0 || total == data->crypt_offset)
+ return -EINVAL;
+
+ /*
+ * Load the sg list with the crypt buffer. Inline decrypt back into the
+ * staging buffer. A future optimization could decrypt directly into
+ * lowmem pages.
+ */
+ for (pg_idx = 0; pg_idx < page_count; pg_idx++)
+ sg_set_buf(&data->sg[1 + pg_idx], data->crypt_pages[pg_idx], PAGE_SIZE);
+
+ /*
+ * It's possible this is the final decrypt, or the final decrypt of the
+ * meta region, and there are fewer than SNAPSHOT_CHUNK_SIZE pages. If this is
+ * the case we would have just written the auth tag into the first few
+ * bytes of a new page. Copy to the tag if so.
+ */
+ if (page_count < SNAPSHOT_CHUNK_SIZE &&
+ (data->crypt_offset - total) == sizeof(data->auth_tag)) {
+ memcpy(data->auth_tag, data->crypt_pages[pg_idx],
+ sizeof(data->auth_tag));
+ } else if (data->crypt_offset !=
+ ((SNAPSHOT_CHUNK_SIZE << PAGE_SHIFT) + SNAPSHOT_AUTH_TAG_SIZE)) {
+ return -EINVAL;
+ }
+
+ sg_set_buf(&data->sg[1 + pg_idx], &data->auth_tag, SNAPSHOT_AUTH_TAG_SIZE);
+ aead_request_set_callback(req, 0, crypto_req_done, &wait);
+ memcpy(&nonce[0], &data->nonce_low, sizeof(data->nonce_low));
+ memcpy(&nonce[sizeof(data->nonce_low)],
+ &data->nonce_high,
+ sizeof(nonce) - sizeof(data->nonce_low));
+
+ data->nonce_low += 1;
+ aead_request_set_crypt(req, data->sg, data->sg, total + SNAPSHOT_AUTH_TAG_SIZE, nonce);
+ res = crypto_wait_req(crypto_aead_decrypt(req), &wait);
+ if (res)
+ return res;
+
+ data->crypt_size = 0;
+ data->crypt_offset = 0;
+
+ /* Push the decrypted pages further down the stack. */
+ total = 0;
+ for (pg_idx = 0; pg_idx < page_count; pg_idx++) {
+ void *buf = data->crypt_pages[pg_idx];
+
+ res = snapshot_write_next(&data->handle);
+ if (res < 0)
+ return res;
+ if (res == 0)
+ break;
+
+ if (!data_of(data->handle))
+ return -EINVAL;
+
+ WARN_ON(res != PAGE_SIZE);
+
+ /* Copy the decrypted page into the snapshot image. */
+ memcpy(data_of(data->handle), buf, PAGE_SIZE);
+ total += PAGE_SIZE;
+ }
+
+ if (data->crypt_total == 0) {
+ u64 meta_size = snapshot_get_meta_page_count() << PAGE_SHIFT;
+
+ data->meta_size = meta_size;
+ if (data->user_key_valid &&
+ data->crypt_meta_size != snapshot_encrypted_byte_count(meta_size))
+ return -EINVAL;
+ }
+
+ data->crypt_total += total;
+ res = snapshot_check_user_key_switch(data);
+ if (res)
+ return res;
+
+ return 0;
+}
+
+static ssize_t snapshot_read_next_encrypted(struct snapshot_data *data,
+ void **buf)
+{
+ size_t tag_off;
+
+ /* Refill the encrypted buffer if it's empty. */
+ if (data->crypt_size == 0 ||
+ (data->crypt_offset >=
+ (data->crypt_size + SNAPSHOT_AUTH_TAG_SIZE))) {
+ int rc;
+
+ data->crypt_size = 0;
+ data->crypt_offset = 0;
+ rc = snapshot_encrypt_refill(data);
+ if (rc < 0)
+ return rc;
+ if (!data->crypt_size)
+ return 0;
+ }
+
+ /* Return data pages if the offset is in that region. */
+ if (data->crypt_offset < data->crypt_size) {
+ size_t pg_idx = data->crypt_offset >> PAGE_SHIFT;
+ size_t pg_off = data->crypt_offset & (PAGE_SIZE - 1);
+ *buf = data->crypt_pages[pg_idx] + pg_off;
+ return PAGE_SIZE - pg_off;
+ }
+
+ /* Use offsets just beyond the size to return the tag. */
+ tag_off = data->crypt_offset - data->crypt_size;
+ if (tag_off > SNAPSHOT_AUTH_TAG_SIZE)
+ tag_off = SNAPSHOT_AUTH_TAG_SIZE;
+
+ *buf = data->auth_tag + tag_off;
+ return SNAPSHOT_AUTH_TAG_SIZE - tag_off;
+}
+
+static ssize_t snapshot_write_next_encrypted(struct snapshot_data *data,
+ void **buf)
+{
+ size_t size_avail;
+ size_t tag_off;
+
+ /* Return data pages if the offset is in that region. */
+ if (data->crypt_offset < (PAGE_SIZE * SNAPSHOT_CHUNK_SIZE)) {
+ size_t pg_idx = data->crypt_offset >> PAGE_SHIFT;
+ size_t pg_off = data->crypt_offset & (PAGE_SIZE - 1);
+
+ *buf = data->crypt_pages[pg_idx] + pg_off;
+ size_avail = PAGE_SIZE - pg_off;
+ } else {
+ /* Use offsets just beyond the size to return the tag. */
+ tag_off = data->crypt_offset - (PAGE_SIZE * SNAPSHOT_CHUNK_SIZE);
+ if (tag_off > SNAPSHOT_AUTH_TAG_SIZE)
+ tag_off = SNAPSHOT_AUTH_TAG_SIZE;
+
+ *buf = data->auth_tag + tag_off;
+ size_avail = SNAPSHOT_AUTH_TAG_SIZE - tag_off;
+ }
+
+ if (data->user_key_valid && data->crypt_meta_size &&
+ data->crypt_stream_total < data->crypt_meta_size) {
+ u64 meta_avail = data->crypt_meta_size - data->crypt_stream_total;
+
+ size_avail = min_t(u64, size_avail, meta_avail);
+ }
+
+ return size_avail;
+}
+
+ssize_t snapshot_read_encrypted(struct snapshot_data *data,
+ char __user *buf, size_t count, loff_t *offp)
+{
+ size_t copy_size;
+ size_t not_done;
+ size_t pg_off;
+ void *src;
+ ssize_t src_size;
+
+ if (!count)
+ return 0;
+
+ pg_off = *offp & (PAGE_SIZE - 1);
+ count = min_t(size_t, count, PAGE_SIZE - pg_off);
+
+ src_size = snapshot_read_next_encrypted(data, &src);
+ if (src_size <= 0)
+ return src_size;
+
+ copy_size = min_t(size_t, count, src_size);
+ not_done = copy_to_user(buf, src, copy_size);
+ copy_size -= not_done;
+ if (!copy_size)
+ return -EFAULT;
+
+ data->crypt_offset += copy_size;
+ *offp += copy_size;
+ return copy_size;
+}
+
+ssize_t snapshot_write_encrypted(struct snapshot_data *data,
+ const char __user *buf, size_t count,
+ loff_t *offp)
+{
+ size_t copy_size;
+ size_t not_done;
+ size_t pg_off;
+ void *dst;
+ ssize_t dst_size;
+ int rc;
+
+ if (!count)
+ return 0;
+
+ pg_off = *offp & (PAGE_SIZE - 1);
+ count = min_t(size_t, count, PAGE_SIZE - pg_off);
+
+ dst_size = snapshot_write_next_encrypted(data, &dst);
+ if (dst_size <= 0)
+ return dst_size;
+
+ copy_size = min_t(size_t, count, dst_size);
+ not_done = copy_from_user(dst, buf, copy_size);
+ copy_size -= not_done;
+ if (!copy_size)
+ return -EFAULT;
+
+ data->crypt_offset += copy_size;
+ data->crypt_stream_total += copy_size;
+ /*
+ * Drain the encrypted buffer if it's full, or if we hit the end of the
+ * encrypted metadata and need a key change before user data pages.
+ */
+ if (data->crypt_offset >=
+ (PAGE_SIZE * SNAPSHOT_CHUNK_SIZE) + SNAPSHOT_AUTH_TAG_SIZE ||
+ (data->user_key_valid && data->crypt_meta_size &&
+ data->crypt_stream_total == data->crypt_meta_size)) {
+ rc = snapshot_decrypt_drain(data);
+ if (rc < 0)
+ return rc;
+ }
+
+ *offp += copy_size;
+ return copy_size;
+}
+
+static void snapshot_reset_encryption_state(struct snapshot_data *data)
+{
+ data->crypt_offset = 0;
+ data->crypt_size = 0;
+ data->crypt_total = 0;
+ data->crypt_stream_total = 0;
+ data->nonce_low = 0;
+ data->nonce_high = 0;
+ data->meta_size = 0;
+ data->crypt_meta_size = 0;
+ data->user_key_valid = false;
+ memset(data->auth_tag, 0, sizeof(data->auth_tag));
+}
+
+void snapshot_teardown_encryption(struct snapshot_data *data)
+{
+ int i;
+
+ if (data->aead_req) {
+ aead_request_free(data->aead_req);
+ data->aead_req = NULL;
+ }
+
+ if (data->aead_tfm) {
+ crypto_free_aead(data->aead_tfm);
+ data->aead_tfm = NULL;
+ }
+
+ for (i = 0; i < SNAPSHOT_CHUNK_SIZE; i++) {
+ if (data->crypt_pages[i]) {
+ free_page((unsigned long)data->crypt_pages[i]);
+ data->crypt_pages[i] = NULL;
+ }
+ }
+
+ memzero_explicit(data->encryption_key, sizeof(data->encryption_key));
+ memzero_explicit(data->user_key, sizeof(data->user_key));
+ snapshot_reset_encryption_state(data);
+}
+
+static int snapshot_setup_encryption_common(struct snapshot_data *data)
+{
+ int i, rc;
+
+ /* This only works once per hibernate. */
+ if (data->aead_tfm)
+ return -EINVAL;
+
+ snapshot_reset_encryption_state(data);
+ memset(data->crypt_pages, 0, sizeof(data->crypt_pages));
+
+ /* Set up the encryption transform */
+ data->aead_tfm = crypto_alloc_aead("gcm(aes)", 0, 0);
+ if (IS_ERR(data->aead_tfm)) {
+ rc = PTR_ERR(data->aead_tfm);
+ data->aead_tfm = NULL;
+ return rc;
+ }
+
+ rc = -ENOMEM;
+ data->aead_req = aead_request_alloc(data->aead_tfm, GFP_KERNEL);
+ if (!data->aead_req)
+ goto setup_fail;
+
+ /* Allocate the staging area */
+ for (i = 0; i < SNAPSHOT_CHUNK_SIZE; i++) {
+ data->crypt_pages[i] = (void *)__get_free_page(GFP_KERNEL);
+ if (!data->crypt_pages[i])
+ goto setup_fail;
+ }
+
+ sg_init_table(data->sg, SNAPSHOT_CHUNK_SIZE + 2);
+
+ /*
+ * The associated data will be the offset so that blocks can't be
+ * rearranged.
+ */
+ aead_request_set_ad(data->aead_req, sizeof(data->crypt_total));
+ rc = crypto_aead_setauthsize(data->aead_tfm, SNAPSHOT_AUTH_TAG_SIZE);
+ if (rc)
+ goto setup_fail;
+
+ return 0;
+
+setup_fail:
+ snapshot_teardown_encryption(data);
+ return rc;
+}
+
+int snapshot_get_encryption_key(struct snapshot_data *data,
+ struct uswsusp_key_blob __user *key)
+{
+ struct snapshot_wrapped_key wrapped = {};
+ u8 image_key[SNAPSHOT_ENCRYPTION_KEY_SIZE] __nonstring = {};
+ u8 nonce[USWSUSP_KEY_NONCE_SIZE];
+ int rc;
+
+ /* Don't pull a random key from a world that can be reset. */
+ if (data->ready)
+ return -EPIPE;
+
+ rc = snapshot_setup_encryption_common(data);
+ if (rc)
+ return rc;
+
+ /* Build a random starting nonce. */
+ get_random_bytes(nonce, sizeof(nonce));
+ memcpy(&data->nonce_low, &nonce[0], sizeof(data->nonce_low));
+ memcpy(&data->nonce_high, &nonce[8], sizeof(data->nonce_high));
+
+ /* Build and install a random image encryption key. */
+ get_random_bytes(image_key, sizeof(image_key));
+ rc = snapshot_install_image_key(data, image_key);
+ if (rc)
+ goto fail;
+
+ rc = snapshot_wrap_image_key(image_key, &wrapped);
+ if (rc)
+ goto fail;
+
+ /* Hand the wrapped key and clear nonce back to user mode. */
+ rc = put_user(sizeof(wrapped), &key->blob_len);
+ if (rc)
+ goto fail;
+
+ BUILD_BUG_ON(sizeof(wrapped) >
+ sizeof(((struct uswsusp_key_blob *)0)->blob));
+ if (copy_to_user(&key->blob, &wrapped, sizeof(wrapped))) {
+ rc = -EFAULT;
+ goto fail;
+ }
+
+ if (copy_to_user(&key->nonce, &nonce, sizeof(nonce))) {
+ rc = -EFAULT;
+ goto fail;
+ }
+
+ memzero_explicit(image_key, sizeof(image_key));
+ memzero_explicit(&wrapped, sizeof(wrapped));
+ return 0;
+
+fail:
+ memzero_explicit(image_key, sizeof(image_key));
+ memzero_explicit(&wrapped, sizeof(wrapped));
+ snapshot_teardown_encryption(data);
+ return rc;
+}
+
+int snapshot_set_encryption_key(struct snapshot_data *data,
+ struct uswsusp_key_blob __user *key)
+{
+ struct uswsusp_key_blob *blob;
+ struct snapshot_wrapped_key wrapped = {};
+ u8 image_key[SNAPSHOT_ENCRYPTION_KEY_SIZE] __nonstring = {};
+ int rc;
+
+ /* It's too late if data's been pushed in. */
+ if (data->handle.cur)
+ return -EPIPE;
+
+ rc = snapshot_setup_encryption_common(data);
+ if (rc)
+ return rc;
+
+ /* Load the key from user mode. */
+ blob = memdup_user(key, sizeof(*blob));
+ if (IS_ERR(blob)) {
+ rc = PTR_ERR(blob);
+ goto crypto_setup_fail;
+ }
+
+ if (blob->blob_len != sizeof(wrapped)) {
+ rc = -EINVAL;
+ goto out_blob;
+ }
+
+ memcpy(&wrapped, blob->blob, sizeof(wrapped));
+ rc = snapshot_unwrap_image_key(&wrapped, image_key);
+ if (rc)
+ goto out_blob;
+
+ rc = snapshot_install_image_key(data, image_key);
+ if (rc)
+ goto out_blob;
+
+ /* Load the starting nonce. */
+ memcpy(&data->nonce_low, &blob->nonce[0], sizeof(data->nonce_low));
+ memcpy(&data->nonce_high, &blob->nonce[8], sizeof(data->nonce_high));
+
+out_blob:
+ kfree_sensitive(blob);
+ memzero_explicit(&wrapped, sizeof(wrapped));
+ memzero_explicit(image_key, sizeof(image_key));
+ if (rc)
+ goto crypto_setup_fail;
+
+ return 0;
+
+crypto_setup_fail:
+ memzero_explicit(&wrapped, sizeof(wrapped));
+ memzero_explicit(image_key, sizeof(image_key));
+ snapshot_teardown_encryption(data);
+ return rc;
+}
+
+static loff_t snapshot_encrypted_byte_count(loff_t plain_size)
+{
+ loff_t pages = plain_size >> PAGE_SHIFT;
+ loff_t chunks = (pages + (SNAPSHOT_CHUNK_SIZE - 1)) / SNAPSHOT_CHUNK_SIZE;
+ /*
+ * The encrypted size is the normal size, plus a stitched in
+ * authentication tag for every chunk of pages.
+ */
+ return plain_size + (chunks * SNAPSHOT_AUTH_TAG_SIZE);
+}
+
+static loff_t snapshot_encrypted_split_byte_count(loff_t raw_size,
+ loff_t meta_plain_size)
+{
+ if (raw_size <= meta_plain_size)
+ return snapshot_encrypted_byte_count(raw_size);
+
+ return snapshot_encrypted_byte_count(meta_plain_size) +
+ snapshot_encrypted_byte_count(raw_size - meta_plain_size);
+}
+
+int snapshot_set_user_key(struct snapshot_data *data,
+ struct uswsusp_user_key __user *key)
+{
+ struct uswsusp_user_key user_key = {};
+ unsigned int key_len;
+ u64 size;
+ int rc;
+
+ if (!snapshot_encryption_enabled(data))
+ return -EINVAL;
+
+ if (copy_from_user(&user_key, key, sizeof(struct uswsusp_user_key)))
+ return -EFAULT;
+
+ BUILD_BUG_ON(sizeof(data->user_key) < sizeof(user_key.key));
+ rc = -EINVAL;
+ if (user_key.reserved)
+ goto out;
+ if (user_key.key_len > sizeof(data->user_key))
+ goto out;
+ if (user_key.key_len < 8)
+ goto out;
+
+ if (data->mode == O_RDONLY && !data->ready) {
+ rc = -ENODATA;
+ goto out;
+ }
+
+ /*
+ * Return the metadata size, the number of bytes that can be fed in before
+ * the user data key is needed at resume time.
+ */
+ if (data->mode == O_WRONLY && !data->meta_size) {
+ if (user_key.meta_size < PAGE_SIZE + SNAPSHOT_AUTH_TAG_SIZE)
+ goto out;
+
+ data->crypt_meta_size = user_key.meta_size;
+ size = data->crypt_meta_size;
+ } else {
+ snapshot_set_meta_size(data,
+ snapshot_get_meta_page_count() << PAGE_SHIFT);
+ size = data->crypt_meta_size;
+ }
+
+ rc = put_user(size, &key->meta_size);
+ if (rc)
+ goto out;
+
+ key_len = user_key.key_len;
+
+ /* Don't allow it if it's too late. */
+ if ((data->meta_size && data->crypt_total > data->meta_size) ||
+ (data->crypt_meta_size &&
+ data->crypt_stream_total > data->crypt_meta_size)) {
+ rc = -EBUSY;
+ goto out;
+ }
+
+ /*
+ * Resume may preload the user key before writing any image data, or
+ * install it after writing exactly the saved metadata stream. In the
+ * latter case, authenticate and publish the buffered metadata under the
+ * original image key before switching keys.
+ */
+ if (data->mode == O_WRONLY && data->crypt_meta_size &&
+ data->crypt_stream_total == data->crypt_meta_size &&
+ data->crypt_offset) {
+ rc = snapshot_decrypt_drain(data);
+ if (rc)
+ goto out;
+ if (data->crypt_total != data->meta_size) {
+ rc = -EINVAL;
+ goto out;
+ }
+ }
+
+ memset(data->user_key, 0, sizeof(data->user_key));
+ memcpy(data->user_key, user_key.key, key_len);
+ data->user_key_valid = true;
+ /* Install the key if the user is just under the wire. */
+ rc = snapshot_check_user_key_switch(data);
+ if (rc)
+ goto out;
+
+ rc = 0;
+
+out:
+ memzero_explicit(&user_key, sizeof(user_key));
+ return rc;
+}
+
+loff_t snapshot_get_encrypted_image_size(struct snapshot_data *data,
+ loff_t raw_size)
+{
+ loff_t meta_plain_size = data->meta_size;
+ loff_t split_size;
+
+ if (!meta_plain_size)
+ meta_plain_size = snapshot_get_meta_page_count() << PAGE_SHIFT;
+
+ split_size = snapshot_encrypted_split_byte_count(raw_size,
+ meta_plain_size);
+ if (!data->user_key_valid) {
+ /*
+ * Userspace may install a user key after querying the image size.
+ * Reserve enough space for either framing so that later splitting at
+ * the metadata boundary cannot make the reported size too small.
+ */
+ return max(snapshot_encrypted_byte_count(raw_size), split_size);
+ }
+
+ return split_size;
+}
+
+int snapshot_finalize_decrypted_image(struct snapshot_data *data)
+{
+ int rc;
+
+ if (data->crypt_offset != 0) {
+ rc = snapshot_decrypt_drain(data);
+ if (rc)
+ return rc;
+ }
+
+ return 0;
+}
diff --git a/kernel/power/snapshot.c b/kernel/power/snapshot.c
index b209712cb2c3a..d1a226a25d27e 100644
--- a/kernel/power/snapshot.c
+++ b/kernel/power/snapshot.c
@@ -2177,6 +2177,11 @@ unsigned long snapshot_get_image_size(void)
return nr_copy_pages + nr_meta_pages + 1;
}
+unsigned long snapshot_get_meta_page_count(void)
+{
+ return nr_meta_pages + 1;
+}
+
static int init_header(struct swsusp_info *info)
{
memset(info, 0, sizeof(struct swsusp_info));
diff --git a/kernel/power/swap.c b/kernel/power/swap.c
index c78f1593600bb..ac736d2b59e3f 100644
--- a/kernel/power/swap.c
+++ b/kernel/power/swap.c
@@ -166,6 +166,93 @@ static int swsusp_extents_insert(unsigned long swap_offset)
return 0;
}
+static bool swsusp_extents_contain_range(unsigned long swap_offset,
+ unsigned long nr_pages)
+{
+ struct rb_node *node = swsusp_extents.rb_node;
+ struct swsusp_extent *ext;
+ unsigned long end;
+
+ if (!nr_pages)
+ return false;
+
+ end = swap_offset + nr_pages - 1;
+ if (end < swap_offset)
+ return false;
+
+ while (node) {
+ ext = rb_entry(node, struct swsusp_extent, node);
+ if (swap_offset < ext->start)
+ node = node->rb_left;
+ else if (swap_offset > ext->end)
+ node = node->rb_right;
+ else
+ goto found;
+ }
+
+ return false;
+
+found:
+ for (;;) {
+ if (swap_offset < ext->start)
+ return false;
+ if (end <= ext->end)
+ return true;
+ if (ext->end == (unsigned long)-1)
+ return false;
+
+ swap_offset = ext->end + 1;
+ node = rb_next(&ext->node);
+ if (!node)
+ return false;
+
+ ext = rb_entry(node, struct swsusp_extent, node);
+ }
+}
+
+bool swsusp_swap_range_allocated(int swap, loff_t pos, size_t count)
+{
+ u64 block;
+ u64 end;
+ u64 end_block;
+
+ if (swap < 0 || pos < 0 || !count)
+ return false;
+
+ end = (u64)pos + count - 1;
+ if (end < (u64)pos)
+ return false;
+
+ block = (u64)pos >> PAGE_SHIFT;
+ end_block = end >> PAGE_SHIFT;
+
+ for (;;) {
+ u64 remaining_pages = end_block - block + 1;
+ pgoff_t swap_offset;
+ pgoff_t mapped_pages;
+ sector_t page_block = block;
+ u64 pages;
+
+ if (!remaining_pages)
+ return false;
+ if ((u64)page_block != block)
+ return false;
+ if (swapdev_block_to_extent(swap, page_block, &swap_offset,
+ &mapped_pages))
+ return false;
+ if (!mapped_pages)
+ return false;
+ pages = min_t(u64, mapped_pages, remaining_pages);
+ if ((u64)(unsigned long)pages != pages)
+ return false;
+ if (!swsusp_extents_contain_range(swap_offset, pages))
+ return false;
+ if (pages == remaining_pages)
+ return true;
+ block += pages;
+ }
+}
+
sector_t alloc_swapdev_block(int swap)
{
unsigned long offset;
diff --git a/kernel/power/user.c b/kernel/power/user.c
index d0fcfba7ac235..b8d3342f1548f 100644
--- a/kernel/power/user.c
+++ b/kernel/power/user.c
@@ -21,54 +21,196 @@
#include <linux/console.h>
#include <linux/cpu.h>
#include <linux/freezer.h>
+#include <linux/pid.h>
+#include <linux/sched/signal.h>
+#include <linux/security.h>
#include <linux/uaccess.h>
#include "power.h"
+#include "user.h"
static bool need_wait;
-
-static struct snapshot_data {
- struct snapshot_handle handle;
- int swap;
- int mode;
- bool frozen;
- bool ready;
- bool platform_support;
- bool free_bitmaps;
- dev_t dev;
-} snapshot_state;
+static struct snapshot_data snapshot_state;
int is_hibernate_resume_dev(dev_t dev)
{
return hibernation_available() && snapshot_state.dev == dev;
}
+bool hibernate_snapshot_write_active(dev_t dev)
+{
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ struct snapshot_data *data = &snapshot_state;
+
+ return data->encryption_required && data->mode == O_RDONLY &&
+ data->ready && data->dev == dev &&
+ snapshot_encryption_enabled(data);
+#else
+ return false;
+#endif
+}
+
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+static bool snapshot_encrypted_output_owned(struct snapshot_data *data, dev_t dev)
+{
+ return hibernate_snapshot_write_active(dev) &&
+ data->owner_tgid == task_tgid(current);
+}
+
+static bool snapshot_header_write_range(struct snapshot_data *data,
+ loff_t pos, size_t count)
+{
+ loff_t header_offset = data->swap_header_offset;
+ loff_t offset;
+
+ if (pos < header_offset)
+ return false;
+
+ offset = pos - header_offset;
+ return offset < PAGE_SIZE && count <= PAGE_SIZE - offset;
+}
+
+static u64 snapshot_swap_write_budget(struct snapshot_data *data)
+{
+ if (data->crypt_swap_allocated > U64_MAX >> PAGE_SHIFT)
+ return 0;
+
+ return data->crypt_swap_allocated << PAGE_SHIFT;
+}
+
+static void snapshot_reset_swap_write_state(struct snapshot_data *data,
+ bool reset_allocation)
+{
+ spin_lock(&data->crypt_lock);
+ if (reset_allocation)
+ data->crypt_swap_allocated = 0;
+ data->crypt_swap_reserved = 0;
+ data->crypt_header_reserved = 0;
+ spin_unlock(&data->crypt_lock);
+}
+#endif
+
+enum hibernate_snapshot_write
+hibernate_snapshot_write_begin(dev_t dev, loff_t pos, size_t count)
+{
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ struct snapshot_data *data = &snapshot_state;
+ enum hibernate_snapshot_write type = HIBERNATE_SNAPSHOT_WRITE_NONE;
+ bool image_range_allocated;
+ u64 swap_budget;
+
+ if (!count || !snapshot_encrypted_output_owned(data, dev))
+ return HIBERNATE_SNAPSHOT_WRITE_NONE;
+
+ mutex_lock(&system_transition_mutex);
+
+ if (!snapshot_encrypted_output_owned(data, dev))
+ goto unlock;
+
+ image_range_allocated = swsusp_swap_range_allocated(data->swap, pos, count);
+
+ spin_lock(&data->crypt_lock);
+ swap_budget = snapshot_swap_write_budget(data);
+ if (snapshot_header_write_range(data, pos, count) &&
+ data->crypt_header_reserved <= PAGE_SIZE &&
+ PAGE_SIZE - data->crypt_header_reserved >= count) {
+ data->crypt_header_reserved += count;
+ type = HIBERNATE_SNAPSHOT_WRITE_HEADER;
+ } else if (image_range_allocated &&
+ swap_budget >= data->crypt_swap_reserved &&
+ swap_budget - data->crypt_swap_reserved >= count) {
+ data->crypt_swap_reserved += count;
+ type = HIBERNATE_SNAPSHOT_WRITE_IMAGE;
+ }
+ spin_unlock(&data->crypt_lock);
+
+ if (type == HIBERNATE_SNAPSHOT_WRITE_NONE)
+ goto unlock;
+
+ return type;
+
+unlock:
+ mutex_unlock(&system_transition_mutex);
+ return HIBERNATE_SNAPSHOT_WRITE_NONE;
+#else
+ return HIBERNATE_SNAPSHOT_WRITE_NONE;
+#endif
+}
+
+void hibernate_snapshot_write_end(enum hibernate_snapshot_write type,
+ size_t reserved, ssize_t written)
+{
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ struct snapshot_data *data = &snapshot_state;
+ u64 *reserved_total;
+ size_t unused;
+
+ if (type == HIBERNATE_SNAPSHOT_WRITE_NONE)
+ return;
+ if (!reserved)
+ goto unlock;
+
+ if (type == HIBERNATE_SNAPSHOT_WRITE_HEADER)
+ unused = reserved;
+ else if (written <= 0)
+ unused = reserved;
+ else if (written < reserved)
+ unused = reserved - written;
+ else
+ goto unlock;
+
+ reserved_total = type == HIBERNATE_SNAPSHOT_WRITE_HEADER ?
+ &data->crypt_header_reserved : &data->crypt_swap_reserved;
+
+ spin_lock(&data->crypt_lock);
+ *reserved_total -= min_t(u64, *reserved_total, unused);
+ spin_unlock(&data->crypt_lock);
+
+unlock:
+ mutex_unlock(&system_transition_mutex);
+#endif
+}
+
+static bool snapshot_encryption_required(struct snapshot_data *data)
+{
+ data->encryption_required = security_locked_down(LOCKDOWN_HIBERNATION);
+ return data->encryption_required;
+}
+
static int snapshot_open(struct inode *inode, struct file *filp)
{
struct snapshot_data *data;
unsigned int sleep_flags;
int error;
- if (!hibernation_available())
+ if (!hibernation_snapshot_dev_available())
return -EPERM;
sleep_flags = lock_system_sleep();
if (!hibernate_acquire()) {
error = -EBUSY;
- goto Unlock;
+ goto unlock;
}
if ((filp->f_flags & O_ACCMODE) == O_RDWR) {
hibernate_release();
error = -ENOSYS;
- goto Unlock;
+ goto unlock;
}
nonseekable_open(inode, filp);
data = &snapshot_state;
filp->private_data = data;
memset(&data->handle, 0, sizeof(struct snapshot_handle));
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ spin_lock_init(&data->crypt_lock);
+ data->crypt_swap_allocated = 0;
+ data->crypt_swap_reserved = 0;
+ data->crypt_header_reserved = 0;
+ data->swap_header_offset = 0;
+ data->owner_tgid = NULL;
+#endif
if ((filp->f_flags & O_ACCMODE) == O_RDONLY) {
/* Hibernating. The image device should be accessible. */
data->swap = pin_hibernation_swap_type(swsusp_resume_device, 0);
@@ -99,8 +241,13 @@ static int snapshot_open(struct inode *inode, struct file *filp)
data->ready = false;
data->platform_support = false;
data->dev = 0;
+ data->encryption_required = snapshot_encryption_required(data);
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ if (!error)
+ data->owner_tgid = get_task_pid(current, PIDTYPE_TGID);
+#endif
- Unlock:
+ unlock:
unlock_system_sleep(sleep_flags);
return error;
@@ -116,6 +263,10 @@ static int snapshot_release(struct inode *inode, struct file *filp)
swsusp_free();
data = filp->private_data;
data->dev = 0;
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ put_pid(data->owner_tgid);
+ data->owner_tgid = NULL;
+#endif
free_all_swap_pages(data->swap);
unpin_hibernation_swap_type(data->swap);
if (data->frozen) {
@@ -125,6 +276,7 @@ static int snapshot_release(struct inode *inode, struct file *filp)
} else if (data->free_bitmaps) {
free_basic_memory_bitmaps();
}
+ snapshot_teardown_encryption(data);
pm_notifier_call_chain(data->mode == O_RDONLY ?
PM_POST_HIBERNATION : PM_POST_RESTORE);
hibernate_release();
@@ -147,12 +299,23 @@ static ssize_t snapshot_read(struct file *filp, char __user *buf,
data = filp->private_data;
if (!data->ready) {
res = -ENODATA;
- goto Unlock;
+ goto unlock;
+ }
+ if (snapshot_encryption_required(data) &&
+ !snapshot_encryption_enabled(data)) {
+ res = -EPERM;
+ goto unlock;
}
+
+ if (snapshot_encryption_enabled(data)) {
+ res = snapshot_read_encrypted(data, buf, count, offp);
+ goto unlock;
+ }
+
if (!pg_offp) { /* on page boundary? */
res = snapshot_read_next(&data->handle);
if (res <= 0)
- goto Unlock;
+ goto unlock;
} else {
res = PAGE_SIZE - pg_offp;
}
@@ -162,7 +325,7 @@ static ssize_t snapshot_read(struct file *filp, char __user *buf,
if (res > 0)
*offp += res;
- Unlock:
+ unlock:
unlock_system_sleep(sleep_flags);
return res;
@@ -185,6 +348,17 @@ static ssize_t snapshot_write(struct file *filp, const char __user *buf,
data = filp->private_data;
+ if (snapshot_encryption_required(data) &&
+ !snapshot_encryption_enabled(data)) {
+ res = -EPERM;
+ goto unlock;
+ }
+
+ if (snapshot_encryption_enabled(data)) {
+ res = snapshot_write_encrypted(data, buf, count, offp);
+ goto unlock;
+ }
+
if (!pg_offp) {
res = snapshot_write_next(&data->handle);
if (res <= 0)
@@ -252,6 +426,9 @@ static int snapshot_set_swap_area(struct snapshot_data *data,
if (data->swap < 0)
return swdev ? -ENODEV : -EINVAL;
data->dev = swdev;
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ data->swap_header_offset = (loff_t)offset << PAGE_SHIFT;
+#endif
return 0;
}
@@ -318,6 +495,11 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,
error = -EPERM;
break;
}
+ if (snapshot_encryption_required(data) &&
+ !snapshot_encryption_enabled(data)) {
+ error = -EPERM;
+ break;
+ }
pm_restore_gfp_mask();
error = hibernation_snapshot(data->platform_support);
if (!error) {
@@ -328,6 +510,17 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,
break;
case SNAPSHOT_ATOMIC_RESTORE:
+ if (snapshot_encryption_required(data) &&
+ !snapshot_encryption_enabled(data)) {
+ error = -EPERM;
+ break;
+ }
+ if (snapshot_encryption_enabled(data)) {
+ error = snapshot_finalize_decrypted_image(data);
+ if (error)
+ break;
+ }
+
error = snapshot_write_finalize(&data->handle);
if (error)
break;
@@ -346,6 +539,10 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,
swsusp_free();
memset(&data->handle, 0, sizeof(struct snapshot_handle));
data->ready = false;
+ snapshot_teardown_encryption(data);
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ snapshot_reset_swap_write_state(data, false);
+#endif
/*
* It is necessary to thaw kernel threads here, because
* SNAPSHOT_CREATE_IMAGE may be invoked directly after
@@ -368,6 +565,8 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,
}
size = snapshot_get_image_size();
size <<= PAGE_SHIFT;
+ if (snapshot_encryption_enabled(data))
+ size = snapshot_get_encrypted_image_size(data, size);
error = put_user(size, (loff_t __user *)arg);
break;
@@ -386,6 +585,13 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,
if (offset) {
offset <<= PAGE_SHIFT;
error = put_user(offset, (loff_t __user *)arg);
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ if (!error) {
+ spin_lock(&data->crypt_lock);
+ data->crypt_swap_allocated++;
+ spin_unlock(&data->crypt_lock);
+ }
+#endif
} else {
error = -ENOSPC;
}
@@ -397,6 +603,9 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,
break;
}
free_all_swap_pages(data->swap);
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ snapshot_reset_swap_write_state(data, true);
+#endif
break;
case SNAPSHOT_S2RAM:
@@ -404,6 +613,11 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,
error = -EPERM;
break;
}
+ if (snapshot_encryption_required(data) &&
+ !snapshot_encryption_enabled(data)) {
+ error = -EPERM;
+ break;
+ }
/*
* Tasks are frozen and the notifiers have been called with
* PM_HIBERNATION_PREPARE
@@ -417,6 +631,11 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,
break;
case SNAPSHOT_POWER_OFF:
+ if (snapshot_encryption_required(data) &&
+ !snapshot_encryption_enabled(data)) {
+ error = -EPERM;
+ break;
+ }
if (data->platform_support)
error = hibernation_platform_enter();
break;
@@ -425,6 +644,21 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,
error = snapshot_set_swap_area(data, (void __user *)arg);
break;
+ case SNAPSHOT_ENABLE_ENCRYPTION:
+ if (data->mode == O_RDONLY)
+ error = snapshot_get_encryption_key(data, (void __user *)arg);
+ else
+ error = snapshot_set_encryption_key(data, (void __user *)arg);
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ if (!error)
+ snapshot_reset_swap_write_state(data, false);
+#endif
+ break;
+
+ case SNAPSHOT_SET_USER_KEY:
+ error = snapshot_set_user_key(data, (void __user *)arg);
+ break;
+
default:
error = -ENOTTY;
@@ -448,6 +682,8 @@ snapshot_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
case SNAPSHOT_ALLOC_SWAP_PAGE:
case SNAPSHOT_CREATE_IMAGE:
case SNAPSHOT_SET_SWAP_AREA:
+ case SNAPSHOT_ENABLE_ENCRYPTION:
+ case SNAPSHOT_SET_USER_KEY:
return snapshot_ioctl(file, cmd,
(unsigned long) compat_ptr(arg));
default:
diff --git a/kernel/power/user.h b/kernel/power/user.h
new file mode 100644
index 0000000000000..0e1e123e32300
--- /dev/null
+++ b/kernel/power/user.h
@@ -0,0 +1,150 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+#ifndef __POWER_USER_H
+#define __POWER_USER_H
+
+#include <linux/crypto.h>
+#include <linux/scatterlist.h>
+#include <linux/spinlock.h>
+#include <linux/suspend_ioctls.h>
+#include <crypto/aead.h>
+#include <crypto/aes.h>
+
+struct pid;
+
+#define SNAPSHOT_ENCRYPTION_KEY_SIZE AES_KEYSIZE_128
+#define SNAPSHOT_AUTH_TAG_SIZE 16
+
+/* Define the number of pages in a single AEAD encryption chunk. */
+#define SNAPSHOT_CHUNK_SIZE 16
+
+struct snapshot_data {
+ struct snapshot_handle handle;
+ int swap;
+ int mode;
+ bool frozen;
+ bool ready;
+ bool platform_support;
+ bool free_bitmaps;
+ bool encryption_required;
+ dev_t dev;
+
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ struct crypto_aead *aead_tfm;
+ struct aead_request *aead_req;
+ void *crypt_pages[SNAPSHOT_CHUNK_SIZE];
+ u8 auth_tag[SNAPSHOT_AUTH_TAG_SIZE];
+ struct scatterlist sg[SNAPSHOT_CHUNK_SIZE + 2]; /* Add room for AD and auth tag. */
+ size_t crypt_offset;
+ size_t crypt_size;
+ u64 crypt_total;
+ u64 crypt_stream_total;
+ u64 nonce_low;
+ u64 nonce_high;
+ u8 encryption_key[SNAPSHOT_ENCRYPTION_KEY_SIZE] __nonstring;
+ u8 user_key[USWSUSP_USER_KEY_SIZE] __nonstring;
+ bool user_key_valid;
+ u64 meta_size;
+ u64 crypt_meta_size;
+ /* Protect the swap allocation and block-write reservations. */
+ spinlock_t crypt_lock;
+ u64 crypt_swap_allocated;
+ u64 crypt_swap_reserved;
+ u64 crypt_header_reserved;
+ loff_t swap_header_offset;
+ struct pid *owner_tgid;
+#endif
+
+};
+
+/* kernel/power/snapenc.c routines */
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+
+ssize_t snapshot_read_encrypted(struct snapshot_data *data,
+ char __user *buf, size_t count, loff_t *offp);
+
+ssize_t snapshot_write_encrypted(struct snapshot_data *data,
+ const char __user *buf, size_t count,
+ loff_t *offp);
+
+void snapshot_teardown_encryption(struct snapshot_data *data);
+int snapshot_get_encryption_key(struct snapshot_data *data,
+ struct uswsusp_key_blob __user *key);
+
+int snapshot_set_encryption_key(struct snapshot_data *data,
+ struct uswsusp_key_blob __user *key);
+
+int snapshot_set_user_key(struct snapshot_data *data,
+ struct uswsusp_user_key __user *key);
+
+int snapshot_store_encryption_seed(const char *buf, size_t count);
+
+loff_t snapshot_get_encrypted_image_size(struct snapshot_data *data,
+ loff_t raw_size);
+
+int snapshot_finalize_decrypted_image(struct snapshot_data *data);
+
+static inline bool snapshot_encryption_enabled(struct snapshot_data *data)
+{
+ return data->aead_tfm;
+}
+
+#else
+
+static inline ssize_t snapshot_read_encrypted(struct snapshot_data *data,
+ char __user *buf, size_t count,
+ loff_t *offp)
+{
+ return -ENOTTY;
+}
+
+static inline ssize_t snapshot_write_encrypted(struct snapshot_data *data,
+ const char __user *buf,
+ size_t count, loff_t *offp)
+{
+ return -ENOTTY;
+}
+
+static inline void snapshot_teardown_encryption(struct snapshot_data *data) {}
+static inline int snapshot_get_encryption_key(struct snapshot_data *data,
+ struct uswsusp_key_blob __user *key)
+{
+ return -ENOTTY;
+}
+
+static inline int snapshot_set_encryption_key(struct snapshot_data *data,
+ struct uswsusp_key_blob __user *key)
+{
+ return -ENOTTY;
+}
+
+static inline int snapshot_set_user_key(struct snapshot_data *data,
+ struct uswsusp_user_key __user *key)
+{
+ return -ENOTTY;
+}
+
+static inline int snapshot_store_encryption_seed(const char *buf, size_t count)
+{
+ return -ENOTTY;
+}
+
+static inline loff_t snapshot_get_encrypted_image_size(struct snapshot_data *data,
+ loff_t raw_size)
+{
+ return raw_size;
+}
+
+static inline int snapshot_finalize_decrypted_image(struct snapshot_data *data)
+{
+ return -ENOTTY;
+}
+
+static inline bool snapshot_encryption_enabled(struct snapshot_data *data)
+{
+ return false;
+}
+
+#endif
+
+#endif /* __POWER_USER_H */
diff --git a/mm/swapfile.c b/mm/swapfile.c
index 601979b97f95b..ebddf954ad840 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -2379,6 +2379,31 @@ sector_t swapdev_block(int type, pgoff_t offset)
return se->start_block + (offset - se->start_page);
}
+int swapdev_block_to_extent(int type, sector_t block, pgoff_t *offset,
+ pgoff_t *nr_pages)
+{
+ struct swap_info_struct *si = swap_type_to_info(type);
+ struct swap_extent *se;
+ struct rb_node *rb;
+
+ if (!si || !(si->flags & SWP_WRITEOK))
+ return -ENODEV;
+
+ for (rb = rb_first(&si->swap_extent_root); rb; rb = rb_next(rb)) {
+ se = rb_entry(rb, struct swap_extent, rb_node);
+ if (block >= se->start_block &&
+ block - se->start_block < se->nr_pages) {
+ pgoff_t page = block - se->start_block;
+
+ *offset = se->start_page + page;
+ *nr_pages = se->nr_pages - page;
+ return 0;
+ }
+ }
+
+ return -ENOENT;
+}
+
/*
* Return either the total number of swap pages of given type, or the number
* of free pages of that type (depending on @free)
|
| 3/2 | 2026/09/19 12:40 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 26100 output: 23 thoughts: 511 Thoughts: **Analyzing a Substantial Hibernation Patch** Okay, this patch is quite extensive; let's break it down methodically. First, the summary: it touches a wide range of files, which is always a good indicator of some significant architectural changes. Let's list those files again so I can check them later. * `Documentation/ABI/testing/sysfs-power` * `Documentation/power/userland-swsusp.rst` * `block/fops.c` * `include/linux/suspend.h` * `include/linux/swap.h` * `include/uapi/linux/suspend_ioctls.h` * `kernel/power/Kconfig` * `kernel/power/Makefile` * `kernel/power/hibernate.c` * `kernel/power/power.h` * `kernel/power/snapenc.c` (new file) * `kernel/power/snapshot.c` * `kernel/power/swap.c` * `kernel/power/user.c` * `kernel/power/user.h` (new file) * `mm/swapfile.c` The key points are: encrypted hibernation via userspace snapshots, modification to `blkdev_write_iter`, new ioctls for the snapshot device, a new sysfs attribute for a snapshot seed, new encryption logic, and swap block checking. It looks like it enables `CONFIG_ENCRYPTED_HIBERNATION`. The changes look pretty comprehensive, especially since we have new files for encryption. The `/dev/snapshot` device is interesting. I'll need to check if that’s a standard device that I can reliably test in my environments, like QEMU or GCE. It seems like it's created if we enable `CONFIG_HIBERNATION_SNAPSHOT_DEV`. I need to verify its creation via `grepper`. |
| 4/2 | 2026/09/19 12:40 | tool | grepper |
0mArgs:{
"Expression": "snapshot_register|misc_register.*snapshot"
}Results: {
"Output": "kernel/power/user.c=712=static int __init snapshot_device_init(void)\nkernel/power/user.c-713-{\nkernel/power/user.c:714:\treturn misc_register(\u0026snapshot_device);\nkernel/power/user.c-715-};\n"
} |
| 5/2 | 2026/09/19 12:40 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 27155 output: 35 thoughts: 21 Thoughts: Here's my summary, as though I'm thinking through this process: **Diving into the User-Space Interaction for Device Power Management** Okay, so I need to understand how user-space interacts with device power management. The logical place to start digging is `kernel/power/user.c`, specifically around the `snapshot_device_init` function. I'm assuming that this is where the initial setup or registration of devices, or at least some crucial part of the power management flow, begins. That naming convention suggests that this function might have some linkage to device snapshots when coming out of a suspend/resume cycle. Let's see how things are initialized in this context. I'm particularly interested in seeing how user-space settings propagate into the kernel's power management framework here. I'll be looking for relevant data structures and function calls to other power management subsystems. |
| 6/2 | 2026/09/19 12:40 | tool | read-file |
0mArgs:{
"File": "kernel/power/user.c",
"FirstLine": 700,
"LineCount": 30
}Results: {
"Contents": " 700:\t\t.unlocked_ioctl = snapshot_ioctl,\n 701:\t#ifdef CONFIG_COMPAT\n 702:\t\t.compat_ioctl = snapshot_compat_ioctl,\n 703:\t#endif\n 704:\t};\n 705:\t\n 706:\tstatic struct miscdevice snapshot_device = {\n 707:\t\t.minor = SNAPSHOT_MINOR,\n 708:\t\t.name = \"snapshot\",\n 709:\t\t.fops = \u0026snapshot_fops,\n 710:\t};\n 711:\t\n 712:\tstatic int __init snapshot_device_init(void)\n 713:\t{\n 714:\t\treturn misc_register(\u0026snapshot_device);\n 715:\t};\n 716:\t\n 717:\tdevice_initcall(snapshot_device_init);\n"
} |
| 7/2 | 2026/09/19 12:40 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 27633 output: 23 thoughts: 36 Thoughts: Okay, here's my take on those Kconfig options, from a technical perspective: **Investigating Hibernation Configuration in Kconfig** Alright, let's dig into how `CONFIG_HIBERNATION_SNAPSHOT_DEV` and `CONFIG_ENCRYPTED_HIBERNATION` are set up within the Kconfig system. We need to understand their relationships and implications. I know these options affect how hibernation works, specifically whether a dedicated device is used for the snapshot and if that snapshot is encrypted. My focus now is how the system is designed to handle different configurations and how dependencies are managed. This gives context on how other components depend on these configurations. I need to ensure the system is optimized, secure, and flexible. |
| 8/2 | 2026/09/19 12:40 | tool | grepper |
0mArgs:{
"Expression": "config HIBERNATION_SNAPSHOT_DEV"
}Results: {
"Output": "kernel/power/Kconfig=38=config HIBERNATION\n--\nkernel/power/Kconfig-83-\nkernel/power/Kconfig:84:config HIBERNATION_SNAPSHOT_DEV\nkernel/power/Kconfig-85-\tbool \"Userspace snapshot device\"\n"
} |
| 9/2 | 2026/09/19 12:40 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 27923 output: 33 thoughts: 22 Thoughts: Here's my summary, as though I'm processing those thoughts: **Analyzing Kernel Power Configuration** Okay, time to dive into `kernel/power/Kconfig`. Specifically, let's zero in on lines 80 through 135. I want to understand what's being configured there. Knowing what those options are will help me to be able to use the power manager effectively, and configure the kernel to best suit the power profile of the target hardware. I'll be looking for relevant variables that impact overall power consumption and battery life. I expect to be able to see various power management features and settings detailed, probably including options for suspend modes, governors, and potentially some hardware-specific configurations. The goal is a clear overview of the available power-related settings and how they're intended to work together. |
| 10/2 | 2026/09/19 12:40 | tool | read-file |
0mArgs:{
"File": "kernel/power/Kconfig",
"FirstLine": 80,
"LineCount": 55
}Results: {
"Contents": " 80:\t\t will get corrupted in a nasty way.\n 81:\t\n 82:\t\t For more information take a look at \u003cfile:Documentation/power/swsusp.rst\u003e.\n 83:\t\n 84:\tconfig HIBERNATION_SNAPSHOT_DEV\n 85:\t\tbool \"Userspace snapshot device\"\n 86:\t\tdepends on HIBERNATION\n 87:\t\tdefault y\n 88:\t\thelp\n 89:\t\t Device used by the uswsusp tools.\n 90:\t\n 91:\t\t Say N if no snapshotting from userspace is needed, this also\n 92:\t\t reduces the attack surface of the kernel.\n 93:\t\n 94:\t\t If in doubt, say Y.\n 95:\t\n 96:\tchoice\n 97:\t\tprompt \"Default compressor\"\n 98:\t\tdefault HIBERNATION_COMP_LZO\n 99:\t\tdepends on HIBERNATION\n 100:\t\n 101:\tconfig HIBERNATION_COMP_LZO\n 102:\t\tbool \"lzo\"\n 103:\t\tdepends on CRYPTO_LZO\n 104:\t\n 105:\tconfig HIBERNATION_COMP_LZ4\n 106:\t\tbool \"lz4\"\n 107:\t\tdepends on CRYPTO_LZ4\n 108:\t\n 109:\tendchoice\n 110:\t\n 111:\tconfig HIBERNATION_DEF_COMP\n 112:\t\tstring\n 113:\t\tdefault \"lzo\" if HIBERNATION_COMP_LZO\n 114:\t\tdefault \"lz4\" if HIBERNATION_COMP_LZ4\n 115:\t\thelp\n 116:\t\t Default compressor to be used for hibernation.\n 117:\t\n 118:\tconfig ENCRYPTED_HIBERNATION\n 119:\t\tbool \"Encryption support for userspace snapshots\"\n 120:\t\tdepends on HIBERNATION_SNAPSHOT_DEV\n 121:\t\tselect CRYPTO_AES\n 122:\t\tselect CRYPTO_GCM\n 123:\t\tselect CRYPTO_LIB_SHA256\n 124:\t\thelp\n 125:\t\t Enable support for kernel-based encryption of hibernation snapshots\n 126:\t\t created by uswsusp tools. A trusted early userspace component must\n 127:\t\t provide the snapshot encryption seed before enabling encryption.\n 128:\t\n 129:\t\t Say N if userspace handles the image encryption.\n 130:\t\n 131:\t\t If in doubt, say N.\n 132:\t\n 133:\tconfig PM_STD_PARTITION\n 134:\t\tstring \"Default resume partition\"\n"
} |
| 11/2 | 2026/09/19 12:40 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 28860 output: 33 thoughts: 61 Thoughts: **My Analysis of Kernel Hibernation Configuration** Okay, so I'm looking at `CONFIG_ENCRYPTED_HIBERNATION` and immediately see it's built on a chain of dependencies. It relies on `CONFIG_HIBERNATION_SNAPSHOT_DEV`, and that in turn hinges on `CONFIG_HIBERNATION`. Right, so encrypted hibernation needs the snapshot device, which requires hibernation itself. Makes sense, security on top of a base functionality. But hold on, I need to understand that base. What *exactly* does `CONFIG_HIBERNATION` depend on? I don't want to make assumptions here, I need to be precise. Time to dig into the `kernel/power/Kconfig` file. Let's see what that reveals about the core requirements of hibernation. I need to understand the fundamental building blocks before I can evaluate the security layer. |
| 12/2 | 2026/09/19 12:40 | tool | read-file |
0mArgs:{
"File": "kernel/power/Kconfig",
"FirstLine": 35,
"LineCount": 45
}Results: {
"Contents": " 35:\tconfig HIBERNATE_CALLBACKS\n 36:\t\tbool\n 37:\t\n 38:\tconfig HIBERNATION\n 39:\t\tbool \"Hibernation (aka 'suspend to disk')\"\n 40:\t\tdepends on SWAP \u0026\u0026 ARCH_HIBERNATION_POSSIBLE\n 41:\t\tselect HIBERNATE_CALLBACKS\n 42:\t\tselect CRC32\n 43:\t\tselect CRYPTO\n 44:\t\tselect CRYPTO_LZO\n 45:\t\tselect CRYPTO_LZ4\n 46:\t\thelp\n 47:\t\t Enable the suspend to disk (STD) functionality, which is usually\n 48:\t\t called \"hibernation\" in user interfaces. STD checkpoints the\n 49:\t\t system and powers it off; and restores that checkpoint on reboot.\n 50:\t\n 51:\t\t You can suspend your machine with 'echo disk \u003e /sys/power/state'\n 52:\t\t after placing resume=/dev/swappartition on the kernel command line\n 53:\t\t in your bootloader's configuration file.\n 54:\t\n 55:\t\t Alternatively, you can use the additional userland tools available\n 56:\t\t from \u003chttp://suspend.sf.net\u003e.\n 57:\t\n 58:\t\t In principle it does not require ACPI or APM, although for example\n 59:\t\t ACPI will be used for the final steps when it is available. One\n 60:\t\t of the reasons to use software suspend is that the firmware hooks\n 61:\t\t for suspend states like suspend-to-RAM (STR) often don't work very\n 62:\t\t well with Linux.\n 63:\t\n 64:\t\t It creates an image which is saved in your active swap. Upon the next\n 65:\t\t boot, pass the 'resume=/dev/swappartition' argument to the kernel to\n 66:\t\t have it detect the saved image, restore memory state from it, and\n 67:\t\t continue to run as before. If you do not want the previous state to\n 68:\t\t be reloaded, then use the 'noresume' kernel command line argument.\n 69:\t\t Note, however, that fsck will be run on your filesystems and you will\n 70:\t\t need to run mkswap against the swap partition used for the suspend.\n 71:\t\n 72:\t\t It also works with swap files to a limited extent (for details see\n 73:\t\t \u003cfile:Documentation/power/swsusp-and-swap-files.rst\u003e).\n 74:\t\n 75:\t\t Right now you may boot without resuming and resume later but in the\n 76:\t\t meantime you cannot use the swap partition(s)/file(s) involved in\n 77:\t\t suspending. Also in this case you must not use the filesystems\n 78:\t\t that were mounted before the suspend. In particular, you MUST NOT\n 79:\t\t MOUNT any journaled filesystems mounted before the suspend or they\n"
} |
| 13/2 | 2026/09/19 12:40 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 29896 output: 35 thoughts: 76 Thoughts: Here's my thought process, as an expert in systems security: **Investigating Potential Security Vulnerabilities in Snapshot Mechanisms** Okay, so I need to dig into the security implications of these snapshot mechanisms. My primary concern is unauthorized access or modification. First, I'm going to determine what permissions are actually required to interact with `/dev/snapshot` or, alternatively, `/sys/power/snapshot_seed`. I'm thinking file permissions are the most obvious place to start. If those don't reveal anything obviously concerning, I'll have to delve deeper. My next step is to examine the kernel code, specifically focusing on functions related to handling snapshots. I'm especially interested in looking at `snapshot_open` (and related functions) and looking if it checks the `CAP_SYS_ADMIN` capability anywhere. Any unchecked use of that capability here would immediately be a red flag. I know that function is likely going to reside in the `kernel/power/user.c` file, so that's where I'll begin my code review. I'll need to see how the system is designed to prevent unauthorized snapshots from being created or manipulated. |
| 14/2 | 2026/09/19 12:40 | tool | read-file |
0mArgs:{
"File": "kernel/power/user.c",
"FirstLine": 195,
"LineCount": 60
}Results: {
"Contents": " 195:\t\t}\n 196:\t\n 197:\t\tif ((filp-\u003ef_flags \u0026 O_ACCMODE) == O_RDWR) {\n 198:\t\t\thibernate_release();\n 199:\t\t\terror = -ENOSYS;\n 200:\t\t\tgoto unlock;\n 201:\t\t}\n 202:\t\tnonseekable_open(inode, filp);\n 203:\t\tdata = \u0026snapshot_state;\n 204:\t\tfilp-\u003eprivate_data = data;\n 205:\t\tmemset(\u0026data-\u003ehandle, 0, sizeof(struct snapshot_handle));\n 206:\t#if defined(CONFIG_ENCRYPTED_HIBERNATION)\n 207:\t\tspin_lock_init(\u0026data-\u003ecrypt_lock);\n 208:\t\tdata-\u003ecrypt_swap_allocated = 0;\n 209:\t\tdata-\u003ecrypt_swap_reserved = 0;\n 210:\t\tdata-\u003ecrypt_header_reserved = 0;\n 211:\t\tdata-\u003eswap_header_offset = 0;\n 212:\t\tdata-\u003eowner_tgid = NULL;\n 213:\t#endif\n 214:\t\tif ((filp-\u003ef_flags \u0026 O_ACCMODE) == O_RDONLY) {\n 215:\t\t\t/* Hibernating. The image device should be accessible. */\n 216:\t\t\tdata-\u003eswap = pin_hibernation_swap_type(swsusp_resume_device, 0);\n 217:\t\t\tdata-\u003emode = O_RDONLY;\n 218:\t\t\tdata-\u003efree_bitmaps = false;\n 219:\t\t\terror = pm_notifier_call_chain_robust(PM_HIBERNATION_PREPARE, PM_POST_HIBERNATION);\n 220:\t\t} else {\n 221:\t\t\t/*\n 222:\t\t\t * Resuming. We may need to wait for the image device to\n 223:\t\t\t * appear.\n 224:\t\t\t */\n 225:\t\t\tneed_wait = true;\n 226:\t\n 227:\t\t\tdata-\u003eswap = -1;\n 228:\t\t\tdata-\u003emode = O_WRONLY;\n 229:\t\t\terror = pm_notifier_call_chain_robust(PM_RESTORE_PREPARE, PM_POST_RESTORE);\n 230:\t\t\tif (!error) {\n 231:\t\t\t\terror = create_basic_memory_bitmaps();\n 232:\t\t\t\tdata-\u003efree_bitmaps = !error;\n 233:\t\t\t}\n 234:\t\t}\n 235:\t\tif (error) {\n 236:\t\t\tunpin_hibernation_swap_type(data-\u003eswap);\n 237:\t\t\thibernate_release();\n 238:\t\t}\n 239:\t\n 240:\t\tdata-\u003efrozen = false;\n 241:\t\tdata-\u003eready = false;\n 242:\t\tdata-\u003eplatform_support = false;\n 243:\t\tdata-\u003edev = 0;\n 244:\t\tdata-\u003eencryption_required = snapshot_encryption_required(data);\n 245:\t#if defined(CONFIG_ENCRYPTED_HIBERNATION)\n 246:\t\tif (!error)\n 247:\t\t\tdata-\u003eowner_tgid = get_task_pid(current, PIDTYPE_TGID);\n 248:\t#endif\n 249:\t\n 250:\t unlock:\n 251:\t\tunlock_system_sleep(sleep_flags);\n 252:\t\n 253:\t\treturn error;\n 254:\t}\n"
} |
| 15/2 | 2026/09/19 12:40 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 31173 output: 22 thoughts: 2063 Thoughts: **WorthFuzzing Evaluation: Analysis of Kernel Patch** Okay, let's break this down. My initial thought was to quickly check if `snapshot_open` might be relevant, and I started thinking about `syzkaller` and `/dev/snapshot`, but that's not the critical path here. I have to remember to *carefully* consider the criteria. I needed to move past my initial line of reasoning. First, I went through the core triage philosophy, to ensure that the logic is reachable. The prompt emphasizes that reachable execution paths are paramount. This involves determining if a crash is in code that can actually be executed in the tested environment. I had to focus on the question of whether this patch affects code that's *actually* reachable in standard virtualized environments. I then went through the negative criteria (when to return `WorthFuzzing=false`). I was looking for the following: if any of the modifications were non-kernel, structurally unreachable hardware, or unreachable execution paths. I reviewed the positive criteria (when to return `WorthFuzzing=true`). The key here is to determine whether any of the modifications touched reachable executable code, including core subsystems, refactorings and code cleanups, assertions, and reachable drivers and protocols. Alright, now the critical part. I found that `blkdev_write_iter` in `block/fops.c` was modified. *Crucially*, `blkdev_write_iter` is called on *every* write to a block device, like `/dev/loopX`, `/dev/sda`, etc. That's a *massive* surface area. This, in turn, touches the swap subsystem (`mm/swapfile.c`) and power management/snapshot device code (`kernel/power/*`). It's all connected. Since I knew that these are standard components of QEMU or GCE virtualized environments, then this immediately tells me that this patch *definitely* doesn't fall into any of the negative criteria. It clearly touches core subsystems (block layer, swap) and virtual/reachable char device drivers (`/dev/snapshot`). Therefore, *WorthFuzzing* is unequivocally `TRUE`. Now, the important follow-up. I need to understand: 1. `EnableConfigs`: What Kconfig options are required to enable this code? 2. `FocusSymbols`: Are there *specific* non-ubiquitous symbols to emphasize for fuzzing? 3. `Reasoning`: A concise summary. I checked for `#ifdef` directives and Kconfig options to determine the minimal configuration necessary to reach the modified code. Here's the result: * `CONFIG_HIBERNATION_SNAPSHOT_DEV` is needed. This depends on `CONFIG_HIBERNATION`. * `CONFIG_HIBERNATION` depends on `CONFIG_SWAP` and `ARCH_HIBERNATION_POSSIBLE`. * If encryption is enabled, `CONFIG_ENCRYPTED_HIBERNATION` is needed, which depends on `HIBERNATION_SNAPSHOT_DEV`. I am confident about `WorthFuzzing=true`. This patch modifies crucial code paths that are readily accessible in standard virtualized environments. The surface area is large (block devices!), the code involves core subsystems (block layer, swap, power management), and it directly interacts with the virtual `/dev/snapshot` device. The patch introduces logic that is directly exercised whenever block devices are written to, under certain conditions. The `CONFIG` options are reasonable for a standard kernel configuration. |
| 16/2 | 2026/09/19 12:41 | tool | grepper |
0mArgs:{
"Expression": "ARCH_HIBERNATION_POSSIBLE"
}Results: {
"Output": "arch/arm/Kconfig=1758=config ARM_CPU_SUSPEND\n--\narch/arm/Kconfig-1761-\narch/arm/Kconfig:1762:config ARCH_HIBERNATION_POSSIBLE\narch/arm/Kconfig-1763-\tbool\n--\narch/arm64/Kconfig=2571=source \"kernel/power/Kconfig\"\narch/arm64/Kconfig-2572-\narch/arm64/Kconfig:2573:config ARCH_HIBERNATION_POSSIBLE\narch/arm64/Kconfig-2574-\tdef_bool y\n--\narch/loongarch/Kconfig=811=config ARCH_SUSPEND_POSSIBLE\n--\narch/loongarch/Kconfig-813-\narch/loongarch/Kconfig:814:config ARCH_HIBERNATION_POSSIBLE\narch/loongarch/Kconfig-815-\tdef_bool y\n--\narch/mips/Kconfig=3145=menu \"Power management options\"\narch/mips/Kconfig-3146-\narch/mips/Kconfig:3147:config ARCH_HIBERNATION_POSSIBLE\narch/mips/Kconfig-3148-\tdef_bool y\n--\narch/powerpc/Kconfig=395=config DEFAULT_UIMAGE\n--\narch/powerpc/Kconfig-399-\narch/powerpc/Kconfig:400:config ARCH_HIBERNATION_POSSIBLE\narch/powerpc/Kconfig-401-\tbool\n--\narch/riscv/Kconfig=1391=source \"kernel/power/Kconfig\"\narch/riscv/Kconfig-1392-\narch/riscv/Kconfig:1393:config ARCH_HIBERNATION_POSSIBLE\narch/riscv/Kconfig-1394-\tdef_bool y\n--\narch/sh/Kconfig=2=config SUPERH\n--\narch/sh/Kconfig-13-\tselect ARCH_HAS_TICK_BROADCAST if GENERIC_CLOCKEVENTS_BROADCAST\narch/sh/Kconfig:14:\tselect ARCH_HIBERNATION_POSSIBLE if MMU\narch/sh/Kconfig-15-\tselect ARCH_MIGHT_HAVE_PC_PARPORT\n--\narch/sh/Kconfig=96=config ARCH_SUSPEND_POSSIBLE\n--\narch/sh/Kconfig-98-\narch/sh/Kconfig:99:config ARCH_HIBERNATION_POSSIBLE\narch/sh/Kconfig-100-\tdef_bool n\n--\narch/sparc/Kconfig=129=config LOCKDEP_SUPPORT\n--\narch/sparc/Kconfig-132-\narch/sparc/Kconfig:133:config ARCH_HIBERNATION_POSSIBLE\narch/sparc/Kconfig-134-\tdef_bool y if SPARC64\n--\narch/x86/Kconfig=401=config ARCH_HAS_CPU_RELAX\n--\narch/x86/Kconfig-403-\narch/x86/Kconfig:404:config ARCH_HIBERNATION_POSSIBLE\narch/x86/Kconfig-405-\tdef_bool y\n--\narch/xtensa/Kconfig=810=menu \"Power management options\"\narch/xtensa/Kconfig-811-\narch/xtensa/Kconfig:812:config ARCH_HIBERNATION_POSSIBLE\narch/xtensa/Kconfig-813-\tdef_bool y\n--\nkernel/power/Kconfig=38=config HIBERNATION\nkernel/power/Kconfig-39-\tbool \"Hibernation (aka 'suspend to disk')\"\nkernel/power/Kconfig:40:\tdepends on SWAP \u0026\u0026 ARCH_HIBERNATION_POSSIBLE\nkernel/power/Kconfig-41-\tselect HIBERNATE_CALLBACKS\n--\nkernel/power/Kconfig=160=config PM_SLEEP_SMP\n--\nkernel/power/Kconfig-162-\tdepends on SMP\nkernel/power/Kconfig:163:\tdepends on ARCH_SUSPEND_POSSIBLE || ARCH_HIBERNATION_POSSIBLE\nkernel/power/Kconfig-164-\tdepends on PM_SLEEP\n"
} |
| 17/2 | 2026/09/19 12:41 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 35075 output: 32 thoughts: 252 Thoughts: **My Hibernation Configuration Thoughts** Okay, so on x86, which is what I'm dealing with, `ARCH_HIBERNATION_POSSIBLE` is automatically set to "yes". That means to get hibernation working, I need to make sure I've got the following enabled in my kernel config: `SWAP`, `HIBERNATION`, `HIBERNATION_SNAPSHOT_DEV`, and `ENCRYPTED_HIBERNATION`. Wait a minute, I need to double-check something. Are there any *crypto* options that need to be selected manually, or are they handled automatically? Let's see... looking at the `kernel/power/Kconfig` file... aha! `ENCRYPTED_HIBERNATION` *selects* `CRYPTO_AES`, `CRYPTO_GCM`, and `CRYPTO_LIB_SHA256`. Excellent, so those are taken care of. But hold on, isn't `CRYPTO` a dependency of *something*? Right, `HIBERNATION` itself *selects* `CRYPTO`. Perfect. Okay, let me just scan `kernel/power/Kconfig` one more time. Just to be sure, I need to make sure that I haven't missed a dependency. Let's make sure that `security_locked_down` isn't dependent on anything in particular. Ah, time to check the definition in `include/linux/security.h`. |
| 18/2 | 2026/09/19 12:41 | tool | grepper |
0mArgs:{
"Expression": "security_locked_down",
"PathPrefix": "include/linux/security.h"
}Results: {
"Output": "include/linux/security.h=97=enum lsm_integrity_type {\n--\ninclude/linux/security.h-103-/*\ninclude/linux/security.h:104: * These are reasons that can be passed to the security_locked_down()\ninclude/linux/security.h-105- * LSM hook. Lockdown reasons that protect kernel integrity (ie, the\n--\ninclude/linux/security.h=583=int security_inode_getsecctx(struct inode *inode, struct lsm_context *cp);\ninclude/linux/security.h:584:int security_locked_down(enum lockdown_reason what);\ninclude/linux/security.h-585-int lsm_fill_user_ctx(struct lsm_ctx __user *uctx, u32 *uctx_len,\n--\ninclude/linux/security.h=1607=static inline int security_inode_getsecctx(struct inode *inode,\n--\ninclude/linux/security.h-1611-}\ninclude/linux/security.h:1612:static inline int security_locked_down(enum lockdown_reason what)\ninclude/linux/security.h-1613-{\n"
} |
| 19/2 | 2026/09/19 12:41 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 35969 output: 20 thoughts: 66 Thoughts: **My Analysis of Security and Lockdown Configuration** Okay, so I'm looking at this `security_locked_down` function. Interesting. It seems that if the kernel isn't compiled with the overall `CONFIG_SECURITY` option, there's a static inline stub in place. That's good, it means the code doesn't strictly *need* `SECURITY` enabled to compile or even run, which allows for a more modular system. But, and this is the key, `SECURITY_LOCKDOWN_LSM` is specifically tied to the lockdown functionality. Just to be absolutely sure, I'd better double-check the configuration definition for `CONFIG_SECURITY_LOCKDOWN_LSM`. It's crucial to understand how deeply this lockdown mode is integrated with the wider security framework. I need to clarify what the dependencies are, and that would impact the broader implications. |
| 20/2 | 2026/09/19 12:41 | tool | grepper |
0mArgs:{
"Expression": "LOCKDOWN_HIBERNATION"
}Results: {
"Output": "include/linux/security.h=127=enum lockdown_reason {\n--\ninclude/linux/security.h-132-\tLOCKDOWN_KEXEC,\ninclude/linux/security.h:133:\tLOCKDOWN_HIBERNATION,\ninclude/linux/security.h-134-\tLOCKDOWN_PCI_ACCESS,\n--\nkernel/power/hibernate.c=110=bool hibernation_available(void)\n--\nkernel/power/hibernate.c-112-\treturn nohibernate == 0 \u0026\u0026\nkernel/power/hibernate.c:113:\t\t!security_locked_down(LOCKDOWN_HIBERNATION) \u0026\u0026\nkernel/power/hibernate.c-114-\t\t!secretmem_active() \u0026\u0026 !cxl_mem_active();\n--\nkernel/power/hibernate.c=117=bool hibernation_snapshot_dev_available(void)\n--\nkernel/power/hibernate.c-119-\treturn nohibernate == 0 \u0026\u0026\nkernel/power/hibernate.c:120:\t\t(!security_locked_down(LOCKDOWN_HIBERNATION) ||\nkernel/power/hibernate.c-121-\t\t IS_ENABLED(CONFIG_ENCRYPTED_HIBERNATION)) \u0026\u0026\n--\nkernel/power/user.c=175=static bool snapshot_encryption_required(struct snapshot_data *data)\nkernel/power/user.c-176-{\nkernel/power/user.c:177:\tdata-\u003eencryption_required = security_locked_down(LOCKDOWN_HIBERNATION);\nkernel/power/user.c-178-\treturn data-\u003eencryption_required;\n--\nsecurity/security.c=43=const char *const lockdown_reasons[LOCKDOWN_CONFIDENTIALITY_MAX + 1] = {\n--\nsecurity/security.c-48-\t[LOCKDOWN_KEXEC] = \"kexec of unsigned images\",\nsecurity/security.c:49:\t[LOCKDOWN_HIBERNATION] = \"hibernation\",\nsecurity/security.c-50-\t[LOCKDOWN_PCI_ACCESS] = \"direct PCI access\",\n"
} |
| 21/2 | 2026/09/19 12:41 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 36753 output: 22 thoughts: 357 Thoughts: **Analyzing Hibernation and Encryption Logic** Okay, let's break down this code snippet from `kernel/power/user.c`. I'm seeing a connection between lockdown, hibernation, and encryption, and I need to fully understand how they interact. Specifically, I see that `data->encryption_required` is set to the result of `security_locked_down(LOCKDOWN_HIBERNATION)`. Then I see the `hibernate_snapshot_dev_available()` function, which seems to determine if a hibernation snapshot device is accessible. It looks like it only allows the snapshot if lockdown isn't enabled *or* if encrypted hibernation is configured (and some other conditions). Now, here's where it gets interesting: the `hibernate_snapshot_write_active(dev)` function checks `data->encryption_required` – that is, if the system *requires* encryption for the snapshot write. And, as noted before, `data->encryption_required` directly reflects the state of `security_locked_down(LOCKDOWN_HIBERNATION)`. This means that if lockdown is enabled (specifically, with the hibernation flag set), `data->encryption_required` *will* be true, right? So, the snapshot will only be written if the system is configured to encrypt the snapshot. And if lockdown is *not* enabled, then encryption is not required. But wait a minute… what happens when lockdown *isn't* enabled? The `data->encryption_required` flag will be false! So in that case, the system *won't* write the snapshot? I need to check the code, and specifically, the configuration options regarding `SECURITY_LOCKDOWN_LSM` to make sure I am seeing this correctly. |
| 22/2 | 2026/09/19 12:41 | tool | grepper |
0mArgs:{
"Expression": "config SECURITY_LOCKDOWN_LSM"
}Results: {
"Output": "security/lockdown/Kconfig:1:config SECURITY_LOCKDOWN_LSM\nsecurity/lockdown/Kconfig-2-\tbool \"Basic module for enforcing kernel lockdown\"\n--\nsecurity/lockdown/Kconfig-8-\nsecurity/lockdown/Kconfig:9:config SECURITY_LOCKDOWN_LSM_EARLY\nsecurity/lockdown/Kconfig-10-\tbool \"Enable lockdown LSM early in init\"\n"
} |
| 23/2 | 2026/09/19 12:41 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 37610 output: 33 thoughts: 13 Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience: **Analyzing the Lockdown Kconfig** Alright, let's dive into this `security/lockdown/Kconfig` file. Given the location, this is *the* configuration file controlling the Lockdown feature, so I need to understand its impact on the system. My initial focus will be on the dependencies, options, and how it interacts with other security modules. I'm looking for where this feature can be enabled, and under what conditions. Are there any hardware or kernel module dependencies I should be aware of, right off the bat? Are there any subtle implications or conflicts with other security frameworks like LSMs or SELinux? I'll probably start scanning for the `config` options and associated help text. I'm keen to see the options. Is there a default configuration? What impact does lockdown have on the system? How granular are the options? Are there any obvious security holes or misconfigurations I can immediately identify? Any chance it is missing something? Understanding the configuration options is only one part, understanding how the features are enabled is the important component. |
| 24/2 | 2026/09/19 12:41 | tool | read-file |
0mArgs:{
"File": "security/lockdown/Kconfig",
"FirstLine": 1,
"LineCount": 35
}Results: {
"Contents": " 1:\tconfig SECURITY_LOCKDOWN_LSM\n 2:\t\tbool \"Basic module for enforcing kernel lockdown\"\n 3:\t\tdepends on SECURITY\n 4:\t\tselect MODULE_SIG if MODULES\n 5:\t\thelp\n 6:\t\t Build support for an LSM that enforces a coarse kernel lockdown\n 7:\t\t behaviour.\n 8:\t\n 9:\tconfig SECURITY_LOCKDOWN_LSM_EARLY\n 10:\t\tbool \"Enable lockdown LSM early in init\"\n 11:\t\tdepends on SECURITY_LOCKDOWN_LSM\n 12:\t\thelp\n 13:\t\t Enable the lockdown LSM early in boot. This is necessary in order\n 14:\t\t to ensure that lockdown enforcement can be carried out on kernel\n 15:\t\t boot parameters that are otherwise parsed before the security\n 16:\t\t subsystem is fully initialised. If enabled, lockdown will\n 17:\t\t unconditionally be called before any other LSMs.\n 18:\t\n 19:\tchoice\n 20:\t\tprompt \"Kernel default lockdown mode\"\n 21:\t\tdefault LOCK_DOWN_KERNEL_FORCE_NONE\n 22:\t\tdepends on SECURITY_LOCKDOWN_LSM\n 23:\t\thelp\n 24:\t\t The kernel can be configured to default to differing levels of\n 25:\t\t lockdown.\n 26:\t\n 27:\tconfig LOCK_DOWN_KERNEL_FORCE_NONE\n 28:\t\tbool \"None\"\n 29:\t\thelp\n 30:\t\t No lockdown functionality is enabled by default. Lockdown may be\n 31:\t\t enabled via the kernel commandline or /sys/kernel/security/lockdown.\n 32:\t\n 33:\tconfig LOCK_DOWN_KERNEL_FORCE_INTEGRITY\n 34:\t\tbool \"Integrity\"\n 35:\t\thelp\n"
} |
| 25/2 | 2026/09/19 12:41 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 38347 output: 49 thoughts: 2135 Thoughts: **Analysis of Encrypted Hibernation Patch** Okay, let's break this down. My initial thought was around the interaction of `SECURITY_LOCKDOWN_LSM` with this encrypted hibernation functionality, and what configurations would be required to build it. Turns out, `CONFIG_ENCRYPTED_HIBERNATION` triggers `snapenc.c` directly through an `#ifdef`, so `SECURITY_LOCKDOWN_LSM` isn't a direct compile dependency. However, `SECURITY_LOCKDOWN_LSM` can still be enabled to test the lockdown path, but it's independent. I then wanted to see if the core encryption functions like `snapshot_get_encryption_key`, `snapshot_set_encryption_key`, and the associated read/write functions would work even *without* lockdown. Looking at `kernel/power/user.c`, I see that the encryption key set and get functions are called through the `SNAPSHOT_ENABLE_ENCRYPTION` ioctl, and `snapshot_set_user_key` is called for the `SNAPSHOT_SET_USER_KEY` ioctl, and neither appears to have any dependency on `data->encryption_required`. Further analysis of `snapshot_read` and `snapshot_write` confirms this; if encryption is *enabled*, the encrypted read/write functions (`snapshot_read_encrypted`, `snapshot_write_encrypted`) are called, regardless of the lockdown state. This also occurs for `SNAPSHOT_ATOMIC_RESTORE` and `SNAPSHOT_GET_IMAGE_SIZE`. Furthermore, `snapshot_store_encryption_seed` is always available when `CONFIG_ENCRYPTED_HIBERNATION=y` is set. Now, let's identify the key functions introduced or modified by this patch to aid fuzzing. The goal is to focus on the new feature logic and the entrypoints. The core functions of `snapenc.c` are: - `snapshot_store_encryption_seed` - `snapshot_get_encryption_key` - `snapshot_set_encryption_key` - `snapshot_set_user_key` - `snapshot_read_encrypted` - `snapshot_write_encrypted` - `snapshot_finalize_decrypted_image` - `snapshot_get_encrypted_image_size` - `snapshot_teardown_encryption` From `kernel/power/user.c`: - `hibernate_snapshot_write_begin` - `hibernate_snapshot_write_end` - `hibernate_snapshot_write_active` - `hibernation_snapshot_dev_available` From `kernel/power/swap.c`: - `swsusp_swap_range_allocated` And from `mm/swapfile.c`: - `swapdev_block_to_extent` I considered the ubiquity of `blkdev_write_iter`, but given that `hibernate_snapshot_write_begin` and `hibernate_snapshot_write_end` are feature-specific functions *called* by it, I included them. `/dev/snapshot` ioctls are specific to this device, so `snapshot_ioctl` is a good entrypoint. The encryption key set, get, and set user functions are the direct handlers for the new ioctls. I'm going to double check non-static symbols for export/external references. |
| 26/2 | 2026/09/19 12:42 | tool | grepper |
0mArgs:{
"Expression": "^int snapshot_|^ssize_t snapshot_|^void snapshot_|^loff_t snapshot_",
"PathPrefix": "kernel/power/snapenc.c"
}Results: {
"Output": "kernel/power/snapenc.c=37=static bool snapshot_seed_valid;\nkernel/power/snapenc.c-38-\nkernel/power/snapenc.c:39:int snapshot_store_encryption_seed(const char *buf, size_t count)\nkernel/power/snapenc.c-40-{\n--\nkernel/power/snapenc.c=492=static ssize_t snapshot_write_next_encrypted(struct snapshot_data *data,\n--\nkernel/power/snapenc.c-524-\nkernel/power/snapenc.c:525:ssize_t snapshot_read_encrypted(struct snapshot_data *data,\nkernel/power/snapenc.c-526-\t\t\t\tchar __user *buf, size_t count, loff_t *offp)\n--\nkernel/power/snapenc.c-554-\nkernel/power/snapenc.c:555:ssize_t snapshot_write_encrypted(struct snapshot_data *data,\nkernel/power/snapenc.c-556-\t\t\t\t const char __user *buf, size_t count,\n--\nkernel/power/snapenc.c=601=static void snapshot_reset_encryption_state(struct snapshot_data *data)\n--\nkernel/power/snapenc.c-614-\nkernel/power/snapenc.c:615:void snapshot_teardown_encryption(struct snapshot_data *data)\nkernel/power/snapenc.c-616-{\n--\nkernel/power/snapenc.c=641=static int snapshot_setup_encryption_common(struct snapshot_data *data)\n--\nkernel/power/snapenc.c-689-\nkernel/power/snapenc.c:690:int snapshot_get_encryption_key(struct snapshot_data *data,\nkernel/power/snapenc.c-691-\t\t\t\tstruct uswsusp_key_blob __user *key)\n--\nkernel/power/snapenc.c-748-\nkernel/power/snapenc.c:749:int snapshot_set_encryption_key(struct snapshot_data *data,\nkernel/power/snapenc.c-750-\t\t\t\tstruct uswsusp_key_blob __user *key)\n--\nkernel/power/snapenc.c=817=static loff_t snapshot_encrypted_split_byte_count(loff_t raw_size,\n--\nkernel/power/snapenc.c-826-\nkernel/power/snapenc.c:827:int snapshot_set_user_key(struct snapshot_data *data,\nkernel/power/snapenc.c-828-\t\t\t struct uswsusp_user_key __user *key)\n--\nkernel/power/snapenc.c-917-\nkernel/power/snapenc.c:918:loff_t snapshot_get_encrypted_image_size(struct snapshot_data *data,\nkernel/power/snapenc.c-919-\t\t\t\t\t loff_t raw_size)\n--\nkernel/power/snapenc.c-940-\nkernel/power/snapenc.c:941:int snapshot_finalize_decrypted_image(struct snapshot_data *data)\nkernel/power/snapenc.c-942-{\n"
} |
| 27/2 | 2026/09/19 12:42 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 42055 output: 20 thoughts: 968 Thoughts: **Analyzing Encrypted Hibernation Implementation** Okay, here's what I'm thinking as I dive into this code. First, the key observation: all those symbols in `snapenc.c` are *non-static*. That immediately grabs my attention. Let's see if this pattern holds elsewhere in the relevant code. I check `kernel/power/swap.c` and find `swsusp_swap_range_allocated` is also non-static. Moving on to `kernel/power/user.c`, I see a cluster of non-static functions: `hibernate_snapshot_write_begin`, `hibernate_snapshot_write_end`, `hibernate_snapshot_write_active`, and `hibernation_snapshot_dev_available`. Finally, in `mm/swapfile.c`, `swapdev_block_to_extent` is also non-static. The significance of this is crucial. Generally, the compiler might inline static functions, or they appear as symbols in `kallsyms`. But non-static symbols are *guaranteed* to be distinct symbols in the vmlinux image. This gives us clear entry points, which helps me understand the structure better. Now, I need to make sure we're not missing anything. I need to know if any important static functions might be interesting. The approach is to check if these non-static entry points cover all the relevant logic. I've now checked the static functions, and I see: * `snapshot_store_encryption_seed` calls `crypto_memneq`, `hex2bin`. * `snapshot_get_encryption_key` calls `snapshot_setup_encryption_common`, `snapshot_install_image_key`, `snapshot_wrap_image_key` -> `snapshot_crypt_wrapped_key` -> `snapshot_derive_wrapping_key`. * `snapshot_set_encryption_key` calls `snapshot_setup_encryption_common`, `snapshot_unwrap_image_key`, `snapshot_install_image_key`. * `snapshot_read_encrypted` calls `snapshot_read_next_encrypted` -> `snapshot_encrypt_refill` -> `snapshot_check_user_key_switch` -> `snapshot_use_user_key`. * `snapshot_write_encrypted` calls `snapshot_write_next_encrypted`, `snapshot_decrypt_drain` -> `snapshot_check_user_key_switch`. * `snapshot_set_user_key` calls `snapshot_set_meta_size`, `snapshot_decrypt_drain`, `snapshot_check_user_key_switch`. * `snapshot_finalize_decrypted_image` calls `snapshot_decrypt_drain`. * `snapshot_get_encrypted_image_size` calls `snapshot_encrypted_split_byte_count`, `snapshot_encrypted_byte_count`. * `swsusp_swap_range_allocated` calls `swapdev_block_to_extent` and `swsusp_extents_contain_range`. * `hibernate_snapshot_write_begin` calls `snapshot_encrypted_output_owned`, `swsusp_swap_range_allocated`, `snapshot_swap_write_budget`, `snapshot_header_write_range`. * `hibernate_snapshot_write_end` modifies reserved totals. Crucially, every single piece of logic added in this patch *is* indeed covered by these non-static functions! This simplifies the analysis greatly. It really helps to see this level of careful design. Let's quickly review the required kernel configs: * `ENCRYPTED_HIBERNATION`, which depends on `HIBERNATION_SNAPSHOT_DEV`, and selects `CRYPTO_AES`, `CRYPTO_GCM`, `CRYPTO_LIB_SHA256`. * `HIBERNATION_SNAPSHOT_DEV`, which depends on `HIBERNATION`. * `HIBERNATION`, which depends on `SWAP` and `ARCH_HIBERNATION_POSSIBLE`, and selects `HIBERNATE_CALLBACKS`, `CRC32`, `CRYPTO`, `CRYPTO_LZO`, `CRYPTO_LZ4`. * `SWAP` which `swapfile.c` and `swapdev_block_to_extent` depend on. Therefore, the EnableConfigs are: * `SWAP` * `HIBERNATION` * `HIBERNATION_SNAPSHOT_DEV` * `ENCRYPTED_HIBERNATION` Now, let's just do a quick sanity check to see if `CRYPTO_GCM` or `CRYPTO_AES` have any other dependencies. I'll check `crypto/Kconfig` for the |
| 28/2 | 2026/09/19 12:42 | tool | grepper |
0mArgs:{
"Expression": "config CRYPTO_GCM"
}Results: {
"Output": "crypto/Kconfig=773=config CRYPTO_CCM\n--\ncrypto/Kconfig-782-\ncrypto/Kconfig:783:config CRYPTO_GCM\ncrypto/Kconfig-784-\ttristate \"GCM (Galois/Counter Mode) and GMAC (GCM MAC)\"\n"
} |
| 29/2 | 2026/09/19 12:42 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 44156 output: 32 thoughts: 17 Thoughts: Here's a summary of my thought process, as if I were the one thinking it: **Digging into crypto/Kconfig** Okay, time to zero in on something specific. The code I'm looking at in `crypto/Kconfig` seems a bit opaque, so I'm going to start by getting a better look at what's happening around line 783. This is usually the best approach when the overall picture isn't immediately clear – focus on a specific area and expand outwards from there. I’m hoping to find some clues, some context that'll illuminate the larger issue. That line number usually gives me enough of a hook to get the ball rolling and understand the connections. Let's see what's in there. |
| 30/2 | 2026/09/19 12:42 | tool | read-file |
0mArgs:{
"File": "crypto/Kconfig",
"FirstLine": 780,
"LineCount": 20
}Results: {
"Contents": " 780:\t\t CCM (Counter with Cipher Block Chaining-Message Authentication Code)\n 781:\t\t authenticated encryption mode (NIST SP800-38C)\n 782:\t\n 783:\tconfig CRYPTO_GCM\n 784:\t\ttristate \"GCM (Galois/Counter Mode) and GMAC (GCM MAC)\"\n 785:\t\tselect CRYPTO_CTR\n 786:\t\tselect CRYPTO_AEAD\n 787:\t\tselect CRYPTO_LIB_GF128HASH\n 788:\t\tselect CRYPTO_MANAGER\n 789:\t\thelp\n 790:\t\t GCM (Galois/Counter Mode) authenticated encryption mode and GMAC\n 791:\t\t (GCM Message Authentication Code) (NIST SP800-38D)\n 792:\t\n 793:\t\t This is required for IPSec ESP (XFRM_ESP).\n 794:\t\n 795:\tconfig CRYPTO_GENIV\n 796:\t\ttristate\n 797:\t\tselect CRYPTO_AEAD\n 798:\t\tselect CRYPTO_MANAGER\n 799:\t\n"
} |
| 31/2 | 2026/09/19 12:42 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 44675 output: 330 thoughts: 723 Thoughts: **My Analysis of Encrypted Hibernation Configuration** Okay, so `ENCRYPTED_HIBERNATION` triggers `CRYPTO_GCM`, which makes perfect sense. Now, a quick check to see if `CRYPTO_GCM` could be anything *other* than 'y' – nope. Since `ENCRYPTED_HIBERNATION` is a boolean and it selects a tristate like `CRYPTO_GCM`, Kconfig forces the tristate to 'y'. Therefore, `CRYPTO_AES` is also set to 'y' as a result. Now, let's explore if there are any other configuration implications. What about `SECURITY_LOCKDOWN_LSM`? I remember the code uses `security_locked_down` to check if lockdown is triggered. It seems `SECURITY_LOCKDOWN_LSM` is *not* strictly required because all the encryption logic can run even without lockdown being active. However, enabling it *does* allow us to exercise lockdown paths, which is useful for testing. Following the `EnableConfigs` guidelines, let's nail down the essential configurations. We need to: - Inspect Kconfig files and #ifdef guards; don't make assumptions. - Check "depends on" lines to include needed parent subsystem configs. - Strip the `CONFIG_` prefix. The *essential* configs to reach the modified code are: `SWAP`, `HIBERNATION`, `HIBERNATION_SNAPSHOT_DEV`, and `ENCRYPTED_HIBERNATION`. That covers the dependencies. Now, let's consider the key symbols, as I've been instructed. Let's see... - `snapshot_store_encryption_seed` - `snapshot_get_encryption_key` - `snapshot_set_encryption_key` - `snapshot_set_user_key` - `snapshot_read_encrypted` - `snapshot_write_encrypted` - `snapshot_finalize_decrypted_image` - `snapshot_get_encrypted_image_size` - `snapshot_teardown_encryption` - `hibernate_snapshot_write_begin` - `hibernate_snapshot_write_end` - `hibernate_snapshot_write_active` - `hibernation_snapshot_dev_available` - `swsusp_swap_range_allocated` - `swapdev_block_to_extent` A quick check to determine if any of these are core system primitives, like memory allocators, scheduler primitives, lock functions, page fault handlers, or generic syscall dispatchers. Nope, none of them. - Specifically, `hibernate_snapshot_write_begin` and `hibernate_snapshot_write_end` are hooks in `blkdev_write_iter`, but only active during snapshot writes, which is specific to this patch. - All `snapshot_*` functions are, of course, specific to `/dev/snapshot` and the new encrypted hibernation feature. - `swsusp_swap_range_allocated` and `swapdev_block_to_extent` are there specifically for swap range checks during the hibernation snapshot process. Everything is clear, concise, and I've fully verified the code's configuration dependencies. Now, let's call `set-results`. |
| 32/2 | 2026/09/19 12:43 | tool | set-results |
0mArgs:{
"EnableConfigs": [
"SWAP",
"HIBERNATION",
"HIBERNATION_SNAPSHOT_DEV",
"ENCRYPTED_HIBERNATION"
],
"FocusSymbols": [
"snapshot_store_encryption_seed",
"snapshot_get_encryption_key",
"snapshot_set_encryption_key",
"snapshot_set_user_key",
"snapshot_read_encrypted",
"snapshot_write_encrypted",
"snapshot_finalize_decrypted_image",
"snapshot_get_encrypted_image_size",
"snapshot_teardown_encryption",
"hibernate_snapshot_write_begin",
"hibernate_snapshot_write_end",
"hibernate_snapshot_write_active",
"hibernation_snapshot_dev_available",
"swsusp_swap_range_allocated",
"swapdev_block_to_extent"
],
"Reasoning": "The patch introduces kernel-based encryption support for userspace hibernation snapshots (/dev/snapshot), adding new ioctls (SNAPSHOT_ENABLE_ENCRYPTION, SNAPSHOT_SET_USER_KEY), sysfs attribute (/sys/power/snapshot_seed), encryption/decryption streaming and AEAD transform management (kernel/power/snapenc.c), block write reservation and extent checking hooks in block/fops.c and mm/swapfile.c, and state management in kernel/power/user.c. All modified code is reachable in standard virtualized environments.",
"WorthFuzzing": true
}Results: {
"EnableConfigs": [
"SWAP",
"HIBERNATION",
"HIBERNATION_SNAPSHOT_DEV",
"ENCRYPTED_HIBERNATION"
],
"FocusSymbols": [
"snapshot_store_encryption_seed",
"snapshot_get_encryption_key",
"snapshot_set_encryption_key",
"snapshot_set_user_key",
"snapshot_read_encrypted",
"snapshot_write_encrypted",
"snapshot_finalize_decrypted_image",
"snapshot_get_encrypted_image_size",
"snapshot_teardown_encryption",
"hibernate_snapshot_write_begin",
"hibernate_snapshot_write_end",
"hibernate_snapshot_write_active",
"hibernation_snapshot_dev_available",
"swsusp_swap_range_allocated",
"swapdev_block_to_extent"
],
"Reasoning": "The patch introduces kernel-based encryption support for userspace hibernation snapshots (/dev/snapshot), adding new ioctls (SNAPSHOT_ENABLE_ENCRYPTION, SNAPSHOT_SET_USER_KEY), sysfs attribute (/sys/power/snapshot_seed), encryption/decryption streaming and AEAD transform management (kernel/power/snapenc.c), block write reservation and extent checking hooks in block/fops.c and mm/swapfile.c, and state management in kernel/power/user.c. All modified code is reachable in standard virtualized environments.",
"WorthFuzzing": true
} |
| 33/1 | 2026/09/19 12:43 | action | If |
12mArgs:{
"WorthFuzzing": true
}Results: null |
| 34/2 | 2026/09/19 12:43 | agent | kmsan-evaluator |
12mModel:core Args: null Results: {
"KMSANReasoning": "The patch introduces support for kernel-based encryption of userland hibernation snapshots (CONFIG_ENCRYPTED_HIBERNATION), including two new ioctls (SNAPSHOT_ENABLE_ENCRYPTION and SNAPSHOT_SET_USER_KEY), a write-only sysfs file (/sys/power/snapshot_seed), and swap write mediation in block/fops.c.\n\nAnalysis of memory initialization and usercopy operations:\n1. Kernel structures copied to userspace:\n - In `snapshot_get_encryption_key()`, the kernel writes to user fields `blob_len`, `blob`, and `nonce`. The source structure `struct snapshot_wrapped_key` is packed (`__packed`), explicitly initialized to zero with `{}` and `memset()`, and all its fields are fully populated prior to `copy_to_user()`. The `nonce` buffer is completely populated with `get_random_bytes()`. No uninitialized padding or buffer tails are copied to userspace.\n - In `snapshot_set_user_key()`, only a scalar `meta_size` (`u64`) is returned via `put_user()`.\n - In `snapshot_read_encrypted()`, `copy_to_user()` only transfers pages that have been populated by `snapshot_read_next()` and encrypted via AEAD, along with the authentication tag produced by the cipher.\n - The sysfs attribute `/sys/power/snapshot_seed` is write-only (permissions 0200) without any read callback.\n\n2. Kernel internal buffers and uninitialized memory usage:\n - All cryptographic keys, nonces, and buffers (`seed`, `wrap_key`, `buf`, `image_key`, `wrapped`, `user_key`) are either zero-initialized (`= {}`, `memset()`) or fully populated (`get_random_bytes()`, `hex2bin()`, `copy_from_user()`) before use, and wiped via `memzero_explicit()` / `kfree_sensitive()`.\n - In `snapshot_decrypt_drain()`, strict chunk-length checks ensure that only bytes fully received via `copy_from_user()` are decrypted and applied.\n - In `swsusp_swap_range_allocated()`, out-parameters from `swapdev_block_to_extent()` are only evaluated when the function returns 0 (success), where both pointers are guaranteed to be assigned.\n\n3. KASAN vs KMSAN applicability:\n - Any potential bugs introduced by this patch involve concurrency/locking (`system_transition_mutex`, `crypt_lock`), block extent range arithmetic, or boundary validation on swap/snapshot devices. These classes of issues are covered by KASAN, LOCKDEP, and standard assertion checks.\n - There are no risks of uninitialized memory reads or kernel information leaks. Spawning a dedicated KMSAN fuzzing session is not justified.",
"NeedsKMSAN": false
}Instruction: You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.
CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
a comprehensive suite of debugging tools and sanitizers, including KASAN
(out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
(locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
or page allocations) and kernel-to-user memory info-leaks.
Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.
Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.
Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
attributes, ioctl output arguments, socket options, or BPF buffers) where fields
or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
uninitialized bytes of existing buffers.
Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
dereferences, locking deadlocks, or use-after-free bugs (these are already caught
by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.
Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit 712876b1fef77d723912a260c8cc2b0ae6fed5c0
Author: syz-cluster <triage@syzkaller.com>
Date: Sat Sep 19 12:40:15 2026 +0000
syz-cluster: applied patch under review
diff --git a/Documentation/ABI/testing/sysfs-power b/Documentation/ABI/testing/sysfs-power
index d38da077905a9..c756712a9df5e 100644
--- a/Documentation/ABI/testing/sysfs-power
+++ b/Documentation/ABI/testing/sysfs-power
@@ -470,3 +470,21 @@ Description:
Minimum value: 1
Default value: 3
+
+What: /sys/power/snapshot_seed
+Date: July 2026
+Contact: linux-pm@vger.kernel.org
+Description:
+ Write-only file present when CONFIG_ENCRYPTED_HIBERNATION=y.
+
+ Trusted early userspace writes a 32-byte seed, encoded as
+ 64 hexadecimal characters plus an optional newline, before
+ enabling encrypted userspace hibernation snapshots.
+
+ The first successful write locks the seed until the next boot.
+ Writing the same seed again succeeds. Writing a different seed
+ fails with EPERM.
+
+ The kernel does not authenticate the first writer. Trusted early
+ userspace must provision this file before untrusted privileged
+ code can run.
diff --git a/Documentation/power/userland-swsusp.rst b/Documentation/power/userland-swsusp.rst
index 1cf62d80a9ca1..957be396dcf5d 100644
--- a/Documentation/power/userland-swsusp.rst
+++ b/Documentation/power/userland-swsusp.rst
@@ -115,6 +115,39 @@ SNAPSHOT_S2RAM
to resume the system from RAM if there's enough battery power or restore
its state on the basis of the saved suspend image otherwise)
+SNAPSHOT_ENABLE_ENCRYPTION
+ Enables encryption of the hibernate image within the kernel. Trusted
+ early userspace must write the 32-byte snapshot encryption seed to
+ /sys/power/snapshot_seed before calling this ioctl. Upon suspend
+ (ie when the snapshot device was opened for reading), this ioctl returns
+ an opaque wrapped key blob and the starting nonce. Upon resume (ie when
+ the snapshot device was opened for writing), this ioctl receives the
+ same blob and nonce from usermode after the same seed has been written
+ to /sys/power/snapshot_seed. The plaintext image key is generated and
+ unwrapped inside the kernel.
+
+ The first successful seed write establishes the wrapping key for that
+ boot. The kernel does not authenticate the writer, the TPM policy used to
+ unseal the seed, or image freshness. Early userspace must provision the
+ seed before untrusted privileged code can run and must enforce any TPM
+ policy and rollback protection.
+
+ Under lockdown, direct block-device write() calls to the active swap
+ backend are restricted to the process which owns the snapshot device and
+ the extents allocated with SNAPSHOT_ALLOC_SWAP_PAGE. These writes must
+ use synchronous buffered I/O (O_DSYNC without O_DIRECT), and cannot
+ exceed the number of pages returned by that ioctl. The swap header may
+ only be written at the offset supplied with SNAPSHOT_SET_SWAP_AREA.
+
+SNAPSHOT_SET_USER_KEY
+ Mixes additional user key material into the data portion of an encrypted
+ hibernate image. The ioctl argument points to struct uswsusp_user_key.
+ key_len must be between 8 and USWSUSP_USER_KEY_SIZE bytes, and reserved
+ must be zero. During hibernation the kernel writes meta_size with the
+ encrypted metadata size. During resume, userspace passes the saved
+ meta_size back so the kernel can switch keys at the metadata boundary
+ before the snapshot header has been decrypted.
+
The device's read() operation can be used to transfer the snapshot image from
the kernel. It has the following limitations:
diff --git a/block/fops.c b/block/fops.c
index 2ce7c6c4714e4..bdc9f2cf7156f 100644
--- a/block/fops.c
+++ b/block/fops.c
@@ -725,43 +725,68 @@ static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
struct file *file = iocb->ki_filp;
struct inode *bd_inode = bdev_file_inode(file);
struct block_device *bdev = I_BDEV(bd_inode);
+ dev_t dev = bd_inode->i_rdev;
bool atomic = iocb->ki_flags & IOCB_ATOMIC;
loff_t size = bdev_nr_bytes(bdev);
+ enum hibernate_snapshot_write hibernate_write;
+ bool hibernate_active;
+ size_t hibernate_len = 0;
size_t shorted = 0;
+ ssize_t hibernate_written = 0;
ssize_t ret;
if (bdev_read_only(bdev))
return -EPERM;
- if (IS_SWAPFILE(bd_inode) && !is_hibernate_resume_dev(bd_inode->i_rdev))
- return -ETXTBSY;
+ hibernate_active = hibernate_snapshot_write_active(dev);
+ if ((IS_SWAPFILE(bd_inode) && !is_hibernate_resume_dev(dev)) ||
+ hibernate_active) {
+ if (!is_sync_kiocb(iocb) || !iocb_is_dsync(iocb) ||
+ (iocb->ki_flags & IOCB_DIRECT))
+ return -ETXTBSY;
+
+ hibernate_len = iov_iter_count(from);
+ hibernate_write = hibernate_snapshot_write_begin(dev, iocb->ki_pos, hibernate_len);
+ if (hibernate_write == HIBERNATE_SNAPSHOT_WRITE_NONE)
+ return -ETXTBSY;
+ } else {
+ hibernate_write = HIBERNATE_SNAPSHOT_WRITE_NONE;
+ }
- if (!iov_iter_count(from))
- return 0;
+ if (!iov_iter_count(from)) {
+ ret = 0;
+ goto out_hibernate;
+ }
- if (iocb->ki_pos >= size)
- return -ENOSPC;
+ if (iocb->ki_pos >= size) {
+ ret = -ENOSPC;
+ goto out_hibernate;
+ }
- if ((iocb->ki_flags & (IOCB_NOWAIT | IOCB_DIRECT)) == IOCB_NOWAIT)
- return -EOPNOTSUPP;
+ if ((iocb->ki_flags & (IOCB_NOWAIT | IOCB_DIRECT)) == IOCB_NOWAIT) {
+ ret = -EOPNOTSUPP;
+ goto out_hibernate;
+ }
if (atomic) {
ret = generic_atomic_write_valid(iocb, from);
if (ret)
- return ret;
+ goto out_hibernate;
}
size -= iocb->ki_pos;
if (iov_iter_count(from) > size) {
- if (atomic)
- return -EINVAL;
+ if (atomic) {
+ ret = -EINVAL;
+ goto out_hibernate;
+ }
shorted = iov_iter_count(from) - size;
iov_iter_truncate(from, size);
}
ret = file_update_time(file);
if (ret)
- return ret;
+ goto out_hibernate;
if (iocb->ki_flags & IOCB_DIRECT) {
ret = blkdev_direct_write(iocb, from);
@@ -779,9 +804,16 @@ static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
inode_unlock_shared(bd_inode);
}
- if (ret > 0)
+ if (ret > 0) {
+ hibernate_written = ret;
ret = generic_write_sync(iocb, ret);
+ }
iov_iter_reexpand(from, iov_iter_count(from) + shorted);
+
+out_hibernate:
+ if (hibernate_len)
+ hibernate_snapshot_write_end(hibernate_write, hibernate_len,
+ hibernate_written);
return ret;
}
diff --git a/include/linux/suspend.h b/include/linux/suspend.h
index b02876f1ae38a..a2a8863f89cf1 100644
--- a/include/linux/suspend.h
+++ b/include/linux/suspend.h
@@ -426,10 +426,34 @@ static inline bool pm_hibernation_mode_is_suspend(void) { return false; }
int arch_resume_nosmt(void);
+enum hibernate_snapshot_write {
+ HIBERNATE_SNAPSHOT_WRITE_NONE,
+ HIBERNATE_SNAPSHOT_WRITE_IMAGE,
+ HIBERNATE_SNAPSHOT_WRITE_HEADER,
+};
+
#ifdef CONFIG_HIBERNATION_SNAPSHOT_DEV
int is_hibernate_resume_dev(dev_t dev);
+bool hibernate_snapshot_write_active(dev_t dev);
+enum hibernate_snapshot_write
+hibernate_snapshot_write_begin(dev_t dev, loff_t pos, size_t count);
+void hibernate_snapshot_write_end(enum hibernate_snapshot_write type,
+ size_t reserved, ssize_t written);
#else
static inline int is_hibernate_resume_dev(dev_t dev) { return 0; }
+static inline bool hibernate_snapshot_write_active(dev_t dev) { return false; }
+
+static inline enum hibernate_snapshot_write
+hibernate_snapshot_write_begin(dev_t dev, loff_t pos, size_t count)
+{
+ return HIBERNATE_SNAPSHOT_WRITE_NONE;
+}
+
+static inline void hibernate_snapshot_write_end(enum hibernate_snapshot_write type,
+ size_t reserved,
+ ssize_t written)
+{
+}
#endif
/* Hibernation and suspend events */
diff --git a/include/linux/swap.h b/include/linux/swap.h
index 5658a1634b85e..deab983ef3d65 100644
--- a/include/linux/swap.h
+++ b/include/linux/swap.h
@@ -377,6 +377,8 @@ extern int find_hibernation_swap_type(dev_t device, sector_t offset);
int find_first_swap(dev_t *device);
extern unsigned int count_swap_pages(int, int);
extern sector_t swapdev_block(int, pgoff_t);
+int swapdev_block_to_extent(int type, sector_t block, pgoff_t *offset,
+ pgoff_t *nr_pages);
extern int __swap_count(swp_entry_t entry);
extern bool swap_entry_swapped(struct swap_info_struct *si, swp_entry_t entry);
extern int swp_swapcount(swp_entry_t entry);
@@ -472,6 +474,13 @@ static inline int add_swap_extent(struct swap_info_struct *sis,
{
return -EINVAL;
}
+
+static inline int swapdev_block_to_extent(int type, sector_t block,
+ pgoff_t *offset,
+ pgoff_t *nr_pages)
+{
+ return -EINVAL;
+}
#endif /* CONFIG_SWAP */
#ifdef CONFIG_MEMCG
void lru_reparent_memcg(struct mem_cgroup *memcg, struct mem_cgroup *parent, int nid);
diff --git a/include/uapi/linux/suspend_ioctls.h b/include/uapi/linux/suspend_ioctls.h
index bcce04e21c0dc..5e23bf936277e 100644
--- a/include/uapi/linux/suspend_ioctls.h
+++ b/include/uapi/linux/suspend_ioctls.h
@@ -13,6 +13,31 @@ struct resume_swap_area {
__u32 dev;
} __attribute__((packed));
+#define USWSUSP_KEY_NONCE_SIZE 16
+#define USWSUSP_USER_KEY_SIZE 32
+
+/*
+ * This structure is used to pass the opaque wrapped hibernate image
+ * encryption key and starting nonce in either direction.
+ */
+struct uswsusp_key_blob {
+ __u32 blob_len;
+ __u8 blob[512];
+ __u8 nonce[USWSUSP_KEY_NONCE_SIZE] __kernel_nonstring;
+} __attribute__((packed));
+
+/*
+ * Allow user mode to fold in key material for the data portion of the hibernate
+ * image.
+ */
+struct uswsusp_user_key {
+ /* Kernel returns the metadata size; resume passes the saved value in. */
+ __u64 meta_size;
+ __u32 key_len;
+ __u32 reserved;
+ __u8 key[USWSUSP_USER_KEY_SIZE] __kernel_nonstring;
+} __attribute__((packed));
+
#define SNAPSHOT_IOC_MAGIC '3'
#define SNAPSHOT_FREEZE _IO(SNAPSHOT_IOC_MAGIC, 1)
#define SNAPSHOT_UNFREEZE _IO(SNAPSHOT_IOC_MAGIC, 2)
@@ -29,6 +54,10 @@ struct resume_swap_area {
#define SNAPSHOT_PREF_IMAGE_SIZE _IO(SNAPSHOT_IOC_MAGIC, 18)
#define SNAPSHOT_AVAIL_SWAP_SIZE _IOR(SNAPSHOT_IOC_MAGIC, 19, __kernel_loff_t)
#define SNAPSHOT_ALLOC_SWAP_PAGE _IOR(SNAPSHOT_IOC_MAGIC, 20, __kernel_loff_t)
-#define SNAPSHOT_IOC_MAXNR 20
+#define SNAPSHOT_ENABLE_ENCRYPTION _IOWR(SNAPSHOT_IOC_MAGIC, 21, \
+ struct uswsusp_key_blob)
+#define SNAPSHOT_SET_USER_KEY _IOWR(SNAPSHOT_IOC_MAGIC, 22, \
+ struct uswsusp_user_key)
+#define SNAPSHOT_IOC_MAXNR 22
#endif /* _LINUX_SUSPEND_IOCTLS_H */
diff --git a/kernel/power/Kconfig b/kernel/power/Kconfig
index 71165e7f04f47..f23d1c7e0ecd1 100644
--- a/kernel/power/Kconfig
+++ b/kernel/power/Kconfig
@@ -115,6 +115,21 @@ config HIBERNATION_DEF_COMP
help
Default compressor to be used for hibernation.
+config ENCRYPTED_HIBERNATION
+ bool "Encryption support for userspace snapshots"
+ depends on HIBERNATION_SNAPSHOT_DEV
+ select CRYPTO_AES
+ select CRYPTO_GCM
+ select CRYPTO_LIB_SHA256
+ help
+ Enable support for kernel-based encryption of hibernation snapshots
+ created by uswsusp tools. A trusted early userspace component must
+ provide the snapshot encryption seed before enabling encryption.
+
+ Say N if userspace handles the image encryption.
+
+ If in doubt, say N.
+
config PM_STD_PARTITION
string "Default resume partition"
depends on HIBERNATION
diff --git a/kernel/power/Makefile b/kernel/power/Makefile
index 773e2789412b9..2fd31b2a250f5 100644
--- a/kernel/power/Makefile
+++ b/kernel/power/Makefile
@@ -16,6 +16,7 @@ obj-$(CONFIG_SUSPEND) += suspend.o
obj-$(CONFIG_PM_TEST_SUSPEND) += suspend_test.o
obj-$(CONFIG_HIBERNATION) += hibernate.o snapshot.o swap.o
obj-$(CONFIG_HIBERNATION_SNAPSHOT_DEV) += user.o
+obj-$(CONFIG_ENCRYPTED_HIBERNATION) += snapenc.o
obj-$(CONFIG_PM_AUTOSLEEP) += autosleep.o
obj-$(CONFIG_PM_WAKELOCKS) += wakelock.o
diff --git a/kernel/power/hibernate.c b/kernel/power/hibernate.c
index d2479c69d71a4..0b8626bdf81a8 100644
--- a/kernel/power/hibernate.c
+++ b/kernel/power/hibernate.c
@@ -36,6 +36,7 @@
#include <trace/events/power.h>
#include "power.h"
+#include "user.h"
static int nocompress;
@@ -113,6 +114,14 @@ bool hibernation_available(void)
!secretmem_active() && !cxl_mem_active();
}
+bool hibernation_snapshot_dev_available(void)
+{
+ return nohibernate == 0 &&
+ (!security_locked_down(LOCKDOWN_HIBERNATION) ||
+ IS_ENABLED(CONFIG_ENCRYPTED_HIBERNATION)) &&
+ !secretmem_active() && !cxl_mem_active();
+}
+
/**
* hibernation_set_ops - Set the global hibernate operations.
* @ops: Hibernation operations to use in subsequent hibernation transitions.
@@ -1376,12 +1385,35 @@ static ssize_t reserved_size_store(struct kobject *kobj,
power_attr(reserved_size);
+#ifdef CONFIG_ENCRYPTED_HIBERNATION
+static ssize_t snapshot_seed_store(struct kobject *kobj,
+ struct kobj_attribute *attr,
+ const char *buf, size_t n)
+{
+ int ret;
+
+ ret = snapshot_store_encryption_seed(buf, n);
+ return ret ? ret : n;
+}
+
+static struct kobj_attribute snapshot_seed_attr = {
+ .attr = {
+ .name = "snapshot_seed",
+ .mode = 0200,
+ },
+ .store = snapshot_seed_store,
+};
+#endif
+
static struct attribute *g[] = {
&disk_attr.attr,
&resume_offset_attr.attr,
&resume_attr.attr,
&image_size_attr.attr,
&reserved_size_attr.attr,
+#ifdef CONFIG_ENCRYPTED_HIBERNATION
+ &snapshot_seed_attr.attr,
+#endif
NULL,
};
diff --git a/kernel/power/power.h b/kernel/power/power.h
index 75b63843886ee..351b5f68bde34 100644
--- a/kernel/power/power.h
+++ b/kernel/power/power.h
@@ -160,6 +160,7 @@ struct snapshot_handle {
extern unsigned int snapshot_additional_pages(struct zone *zone);
extern unsigned long snapshot_get_image_size(void);
+unsigned long snapshot_get_meta_page_count(void);
extern int snapshot_read_next(struct snapshot_handle *handle);
extern int snapshot_write_next(struct snapshot_handle *handle);
int snapshot_write_finalize(struct snapshot_handle *handle);
@@ -167,8 +168,10 @@ extern int snapshot_image_loaded(struct snapshot_handle *handle);
extern bool hibernate_acquire(void);
extern void hibernate_release(void);
+bool hibernation_snapshot_dev_available(void);
extern sector_t alloc_swapdev_block(int swap);
+bool swsusp_swap_range_allocated(int swap, loff_t pos, size_t count);
extern void free_all_swap_pages(int swap);
extern int swsusp_swap_in_use(void);
diff --git a/kernel/power/snapenc.c b/kernel/power/snapenc.c
new file mode 100644
index 0000000000000..b555a699b5644
--- /dev/null
+++ b/kernel/power/snapenc.c
@@ -0,0 +1,952 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* This file provides encryption support for system snapshots. */
+
+#include <linux/crypto.h>
+#include <crypto/aead.h>
+#include <crypto/gcm.h>
+#include <crypto/sha2.h>
+#include <crypto/utils.h>
+#include <linux/hex.h>
+#include <linux/mutex.h>
+#include <linux/random.h>
+#include <linux/mm.h>
+#include <linux/slab.h>
+#include <linux/string.h>
+#include <linux/uaccess.h>
+
+#include "power.h"
+#include "user.h"
+
+#define SNAPSHOT_SEED_SIZE SHA256_DIGEST_SIZE
+#define SNAPSHOT_KEY_BLOB_VERSION 1
+
+static const u8 snapshot_key_blob_magic[8] = {
+ 'S', 'W', 'S', 'U', 'S', 'P', 'K', '1',
+};
+
+struct snapshot_wrapped_key {
+ u8 magic[sizeof(snapshot_key_blob_magic)];
+ __le32 version;
+ u8 wrap_nonce[GCM_AES_IV_SIZE] __nonstring;
+ u8 encrypted_key[SNAPSHOT_ENCRYPTION_KEY_SIZE] __nonstring;
+ u8 tag[SNAPSHOT_AUTH_TAG_SIZE] __nonstring;
+} __packed;
+
+static DEFINE_MUTEX(snapshot_seed_mutex);
+static u8 snapshot_seed[SNAPSHOT_SEED_SIZE] __nonstring;
+static bool snapshot_seed_valid;
+
+int snapshot_store_encryption_seed(const char *buf, size_t count)
+{
+ u8 seed[SNAPSHOT_SEED_SIZE] __nonstring;
+ size_t len = count;
+ int ret;
+
+ if (len && buf[len - 1] == '\n')
+ len--;
+ if (len != SNAPSHOT_SEED_SIZE * 2)
+ return -EINVAL;
+
+ ret = hex2bin(seed, buf, sizeof(seed));
+ if (ret)
+ return ret;
+
+ mutex_lock(&snapshot_seed_mutex);
+ if (snapshot_seed_valid) {
+ ret = crypto_memneq(snapshot_seed, seed, sizeof(seed)) ? -EPERM : 0;
+ goto out;
+ }
+
+ memcpy(snapshot_seed, seed, sizeof(seed));
+ snapshot_seed_valid = true;
+ pr_info("PM: hibernate: snapshot encryption seed locked\n");
+
+out:
+ mutex_unlock(&snapshot_seed_mutex);
+ memzero_explicit(seed, sizeof(seed));
+ return ret;
+}
+
+static bool snapshot_copy_encryption_seed(u8 seed[SNAPSHOT_SEED_SIZE])
+{
+ bool valid;
+
+ mutex_lock(&snapshot_seed_mutex);
+ valid = snapshot_seed_valid;
+ if (valid)
+ memcpy(seed, snapshot_seed, SNAPSHOT_SEED_SIZE);
+ mutex_unlock(&snapshot_seed_mutex);
+
+ return valid;
+}
+
+static int snapshot_derive_wrapping_key(u8 key[SNAPSHOT_ENCRYPTION_KEY_SIZE])
+{
+ static const char label[] = "Linux hibernate snapshot key wrap v1";
+ u8 digest[SHA256_DIGEST_SIZE];
+ u8 seed[SNAPSHOT_SEED_SIZE] __nonstring;
+ struct sha256_ctx sha256_ctx;
+
+ if (!snapshot_copy_encryption_seed(seed))
+ return -ENOKEY;
+
+ sha256_init(&sha256_ctx);
+ sha256_update(&sha256_ctx, label, strlen(label));
+ sha256_update(&sha256_ctx, seed, sizeof(seed));
+ sha256_final(&sha256_ctx, digest);
+
+ memcpy(key, digest, SNAPSHOT_ENCRYPTION_KEY_SIZE);
+ memzero_explicit(seed, sizeof(seed));
+ memzero_explicit(digest, sizeof(digest));
+ return 0;
+}
+
+static int snapshot_crypt_wrapped_key(struct snapshot_wrapped_key *wrapped,
+ u8 image_key[SNAPSHOT_ENCRYPTION_KEY_SIZE],
+ bool encrypt)
+{
+ u8 wrap_key[SNAPSHOT_ENCRYPTION_KEY_SIZE] __nonstring;
+ u8 buf[SNAPSHOT_ENCRYPTION_KEY_SIZE + SNAPSHOT_AUTH_TAG_SIZE] __nonstring;
+ struct crypto_aead *tfm;
+ struct aead_request *req;
+ struct scatterlist sg;
+ DECLARE_CRYPTO_WAIT(wait);
+ int rc;
+
+ rc = snapshot_derive_wrapping_key(wrap_key);
+ if (rc)
+ return rc;
+
+ tfm = crypto_alloc_aead("gcm(aes)", 0, 0);
+ if (IS_ERR(tfm)) {
+ rc = PTR_ERR(tfm);
+ goto out_key;
+ }
+
+ rc = crypto_aead_setkey(tfm, wrap_key, sizeof(wrap_key));
+ if (rc)
+ goto out_tfm;
+
+ rc = crypto_aead_setauthsize(tfm, SNAPSHOT_AUTH_TAG_SIZE);
+ if (rc)
+ goto out_tfm;
+
+ req = aead_request_alloc(tfm, GFP_KERNEL);
+ if (!req) {
+ rc = -ENOMEM;
+ goto out_tfm;
+ }
+
+ if (encrypt) {
+ get_random_bytes(wrapped->wrap_nonce, sizeof(wrapped->wrap_nonce));
+ memcpy(buf, image_key, SNAPSHOT_ENCRYPTION_KEY_SIZE);
+ } else {
+ memcpy(buf, wrapped->encrypted_key, SNAPSHOT_ENCRYPTION_KEY_SIZE);
+ memcpy(buf + SNAPSHOT_ENCRYPTION_KEY_SIZE, wrapped->tag,
+ SNAPSHOT_AUTH_TAG_SIZE);
+ }
+
+ sg_init_one(&sg, buf, sizeof(buf));
+ aead_request_set_callback(req, 0, crypto_req_done, &wait);
+ aead_request_set_ad(req, 0);
+ aead_request_set_crypt(req, &sg, &sg,
+ encrypt ? SNAPSHOT_ENCRYPTION_KEY_SIZE :
+ sizeof(buf),
+ wrapped->wrap_nonce);
+
+ rc = crypto_wait_req(encrypt ? crypto_aead_encrypt(req) :
+ crypto_aead_decrypt(req),
+ &wait);
+ if (rc)
+ goto out_req;
+
+ if (encrypt) {
+ memcpy(wrapped->encrypted_key, buf, SNAPSHOT_ENCRYPTION_KEY_SIZE);
+ memcpy(wrapped->tag, buf + SNAPSHOT_ENCRYPTION_KEY_SIZE,
+ SNAPSHOT_AUTH_TAG_SIZE);
+ } else {
+ memcpy(image_key, buf, SNAPSHOT_ENCRYPTION_KEY_SIZE);
+ }
+
+out_req:
+ aead_request_free(req);
+out_tfm:
+ crypto_free_aead(tfm);
+out_key:
+ memzero_explicit(buf, sizeof(buf));
+ memzero_explicit(wrap_key, sizeof(wrap_key));
+ return rc;
+}
+
+static int snapshot_wrap_image_key(const u8 image_key[SNAPSHOT_ENCRYPTION_KEY_SIZE],
+ struct snapshot_wrapped_key *wrapped)
+{
+ u8 key[SNAPSHOT_ENCRYPTION_KEY_SIZE] __nonstring;
+ int rc;
+
+ memset(wrapped, 0, sizeof(*wrapped));
+ memcpy(wrapped->magic, snapshot_key_blob_magic, sizeof(wrapped->magic));
+ wrapped->version = cpu_to_le32(SNAPSHOT_KEY_BLOB_VERSION);
+
+ memcpy(key, image_key, sizeof(key));
+ rc = snapshot_crypt_wrapped_key(wrapped, key, true);
+ memzero_explicit(key, sizeof(key));
+ return rc;
+}
+
+static int snapshot_unwrap_image_key(const struct snapshot_wrapped_key *wrapped,
+ u8 image_key[SNAPSHOT_ENCRYPTION_KEY_SIZE])
+{
+ struct snapshot_wrapped_key tmp;
+ int rc;
+
+ if (memcmp(wrapped->magic, snapshot_key_blob_magic,
+ sizeof(snapshot_key_blob_magic)))
+ return -EINVAL;
+ if (le32_to_cpu(wrapped->version) != SNAPSHOT_KEY_BLOB_VERSION)
+ return -EINVAL;
+
+ tmp = *wrapped;
+ rc = snapshot_crypt_wrapped_key(&tmp, image_key, false);
+ memzero_explicit(&tmp, sizeof(tmp));
+ return rc;
+}
+
+static int snapshot_install_image_key(struct snapshot_data *data,
+ const u8 image_key[SNAPSHOT_ENCRYPTION_KEY_SIZE])
+{
+ int rc;
+
+ memcpy(data->encryption_key, image_key, sizeof(data->encryption_key));
+ rc = crypto_aead_setkey(data->aead_tfm, data->encryption_key,
+ sizeof(data->encryption_key));
+ if (rc)
+ memzero_explicit(data->encryption_key,
+ sizeof(data->encryption_key));
+
+ return rc;
+}
+
+/* Derive a key from the kernel and user keys for data encryption. */
+static int snapshot_use_user_key(struct snapshot_data *data)
+{
+ u8 digest[SHA256_DIGEST_SIZE];
+ struct sha256_ctx sha256_ctx;
+ int rc;
+
+ /*
+ * Hash the kernel key and the user key together. This folds in the user
+ * key, but not in a way that gives the user mode predictable control
+ * over the key bits.
+ */
+ sha256_init(&sha256_ctx);
+
+ sha256_update(&sha256_ctx, data->encryption_key,
+ SNAPSHOT_ENCRYPTION_KEY_SIZE);
+ sha256_update(&sha256_ctx, data->user_key, sizeof(data->user_key));
+ sha256_final(&sha256_ctx, digest);
+
+ BUILD_BUG_ON(SNAPSHOT_ENCRYPTION_KEY_SIZE > SHA256_DIGEST_SIZE);
+
+ rc = crypto_aead_setkey(data->aead_tfm,
+ digest,
+ SNAPSHOT_ENCRYPTION_KEY_SIZE);
+ memzero_explicit(digest, sizeof(digest));
+
+ return rc;
+}
+
+/* Check to see if it's time to switch to the user key, and do it if so. */
+static int snapshot_check_user_key_switch(struct snapshot_data *data)
+{
+ if (data->user_key_valid && data->meta_size &&
+ data->crypt_total == data->meta_size) {
+ return snapshot_use_user_key(data);
+ }
+
+ return 0;
+}
+
+static loff_t snapshot_encrypted_byte_count(loff_t plain_size);
+
+static void snapshot_set_meta_size(struct snapshot_data *data, u64 meta_size)
+{
+ data->meta_size = meta_size;
+ data->crypt_meta_size = snapshot_encrypted_byte_count(meta_size);
+}
+
+/* Encrypt more data from the snapshot into the staging area. */
+static int snapshot_encrypt_refill(struct snapshot_data *data)
+{
+ struct aead_request *req = data->aead_req;
+ u8 nonce[GCM_AES_IV_SIZE];
+ DECLARE_CRYPTO_WAIT(wait);
+ size_t total = 0;
+ int pg_idx;
+ int res;
+
+ if (data->crypt_total == 0) {
+ snapshot_set_meta_size(data,
+ snapshot_get_meta_page_count() << PAGE_SHIFT);
+ } else {
+ res = snapshot_check_user_key_switch(data);
+ if (res)
+ return res;
+ }
+
+ /*
+ * The first buffer is the associated data, set to the offset to prevent
+ * attacks that rearrange chunks.
+ */
+ sg_set_buf(&data->sg[0], &data->crypt_total, sizeof(data->crypt_total));
+
+ /* Load the crypt buffer with snapshot pages. */
+ for (pg_idx = 0; pg_idx < SNAPSHOT_CHUNK_SIZE; pg_idx++) {
+ void *buf = data->crypt_pages[pg_idx];
+
+ /* Stop at the meta page boundary before switching keys. */
+ if (data->user_key_valid && total &&
+ ((data->crypt_total + total) == data->meta_size))
+ break;
+
+ res = snapshot_read_next(&data->handle);
+ if (res < 0)
+ return res;
+ if (res == 0)
+ break;
+
+ WARN_ON(res != PAGE_SIZE);
+
+ /*
+ * Copy the page into the staging area. A future optimization
+ * could potentially skip this copy for lowmem pages.
+ */
+ memcpy(buf, data_of(data->handle), PAGE_SIZE);
+ sg_set_buf(&data->sg[1 + pg_idx], buf, PAGE_SIZE);
+ total += PAGE_SIZE;
+ }
+
+ if (!total)
+ return 0;
+
+ sg_set_buf(&data->sg[1 + pg_idx], &data->auth_tag, SNAPSHOT_AUTH_TAG_SIZE);
+ aead_request_set_callback(req, 0, crypto_req_done, &wait);
+ /*
+ * Use incrementing nonces for each chunk, since a 64 bit value won't
+ * roll into re-use for any given hibernate image.
+ */
+ memcpy(&nonce[0], &data->nonce_low, sizeof(data->nonce_low));
+ memcpy(&nonce[sizeof(data->nonce_low)],
+ &data->nonce_high,
+ sizeof(nonce) - sizeof(data->nonce_low));
+
+ data->nonce_low += 1;
+ /* Total does not include AAD or the auth tag. */
+ aead_request_set_crypt(req, data->sg, data->sg, total, nonce);
+ res = crypto_wait_req(crypto_aead_encrypt(req), &wait);
+ if (res)
+ return res;
+
+ data->crypt_size = total;
+ data->crypt_total += total;
+ return 0;
+}
+
+/* Decrypt data from the staging area and push it to the snapshot. */
+static int snapshot_decrypt_drain(struct snapshot_data *data)
+{
+ struct aead_request *req = data->aead_req;
+ u8 nonce[GCM_AES_IV_SIZE];
+ DECLARE_CRYPTO_WAIT(wait);
+ int page_count;
+ size_t total;
+ int pg_idx;
+ int res;
+
+ /* Set up the associated data. */
+ sg_set_buf(&data->sg[0], &data->crypt_total, sizeof(data->crypt_total));
+
+ /*
+ * Get the number of full pages, which could be short at the end. There
+ * should also be a tag at the end, so the offset won't be an even page.
+ */
+ page_count = data->crypt_offset >> PAGE_SHIFT;
+ total = page_count << PAGE_SHIFT;
+ if (total == 0 || total == data->crypt_offset)
+ return -EINVAL;
+
+ /*
+ * Load the sg list with the crypt buffer. Inline decrypt back into the
+ * staging buffer. A future optimization could decrypt directly into
+ * lowmem pages.
+ */
+ for (pg_idx = 0; pg_idx < page_count; pg_idx++)
+ sg_set_buf(&data->sg[1 + pg_idx], data->crypt_pages[pg_idx], PAGE_SIZE);
+
+ /*
+ * It's possible this is the final decrypt, or the final decrypt of the
+ * meta region, and there are fewer than SNAPSHOT_CHUNK_SIZE pages. If this is
+ * the case we would have just written the auth tag into the first few
+ * bytes of a new page. Copy to the tag if so.
+ */
+ if (page_count < SNAPSHOT_CHUNK_SIZE &&
+ (data->crypt_offset - total) == sizeof(data->auth_tag)) {
+ memcpy(data->auth_tag, data->crypt_pages[pg_idx],
+ sizeof(data->auth_tag));
+ } else if (data->crypt_offset !=
+ ((SNAPSHOT_CHUNK_SIZE << PAGE_SHIFT) + SNAPSHOT_AUTH_TAG_SIZE)) {
+ return -EINVAL;
+ }
+
+ sg_set_buf(&data->sg[1 + pg_idx], &data->auth_tag, SNAPSHOT_AUTH_TAG_SIZE);
+ aead_request_set_callback(req, 0, crypto_req_done, &wait);
+ memcpy(&nonce[0], &data->nonce_low, sizeof(data->nonce_low));
+ memcpy(&nonce[sizeof(data->nonce_low)],
+ &data->nonce_high,
+ sizeof(nonce) - sizeof(data->nonce_low));
+
+ data->nonce_low += 1;
+ aead_request_set_crypt(req, data->sg, data->sg, total + SNAPSHOT_AUTH_TAG_SIZE, nonce);
+ res = crypto_wait_req(crypto_aead_decrypt(req), &wait);
+ if (res)
+ return res;
+
+ data->crypt_size = 0;
+ data->crypt_offset = 0;
+
+ /* Push the decrypted pages further down the stack. */
+ total = 0;
+ for (pg_idx = 0; pg_idx < page_count; pg_idx++) {
+ void *buf = data->crypt_pages[pg_idx];
+
+ res = snapshot_write_next(&data->handle);
+ if (res < 0)
+ return res;
+ if (res == 0)
+ break;
+
+ if (!data_of(data->handle))
+ return -EINVAL;
+
+ WARN_ON(res != PAGE_SIZE);
+
+ /* Copy the decrypted page into the snapshot image. */
+ memcpy(data_of(data->handle), buf, PAGE_SIZE);
+ total += PAGE_SIZE;
+ }
+
+ if (data->crypt_total == 0) {
+ u64 meta_size = snapshot_get_meta_page_count() << PAGE_SHIFT;
+
+ data->meta_size = meta_size;
+ if (data->user_key_valid &&
+ data->crypt_meta_size != snapshot_encrypted_byte_count(meta_size))
+ return -EINVAL;
+ }
+
+ data->crypt_total += total;
+ res = snapshot_check_user_key_switch(data);
+ if (res)
+ return res;
+
+ return 0;
+}
+
+static ssize_t snapshot_read_next_encrypted(struct snapshot_data *data,
+ void **buf)
+{
+ size_t tag_off;
+
+ /* Refill the encrypted buffer if it's empty. */
+ if (data->crypt_size == 0 ||
+ (data->crypt_offset >=
+ (data->crypt_size + SNAPSHOT_AUTH_TAG_SIZE))) {
+ int rc;
+
+ data->crypt_size = 0;
+ data->crypt_offset = 0;
+ rc = snapshot_encrypt_refill(data);
+ if (rc < 0)
+ return rc;
+ if (!data->crypt_size)
+ return 0;
+ }
+
+ /* Return data pages if the offset is in that region. */
+ if (data->crypt_offset < data->crypt_size) {
+ size_t pg_idx = data->crypt_offset >> PAGE_SHIFT;
+ size_t pg_off = data->crypt_offset & (PAGE_SIZE - 1);
+ *buf = data->crypt_pages[pg_idx] + pg_off;
+ return PAGE_SIZE - pg_off;
+ }
+
+ /* Use offsets just beyond the size to return the tag. */
+ tag_off = data->crypt_offset - data->crypt_size;
+ if (tag_off > SNAPSHOT_AUTH_TAG_SIZE)
+ tag_off = SNAPSHOT_AUTH_TAG_SIZE;
+
+ *buf = data->auth_tag + tag_off;
+ return SNAPSHOT_AUTH_TAG_SIZE - tag_off;
+}
+
+static ssize_t snapshot_write_next_encrypted(struct snapshot_data *data,
+ void **buf)
+{
+ size_t size_avail;
+ size_t tag_off;
+
+ /* Return data pages if the offset is in that region. */
+ if (data->crypt_offset < (PAGE_SIZE * SNAPSHOT_CHUNK_SIZE)) {
+ size_t pg_idx = data->crypt_offset >> PAGE_SHIFT;
+ size_t pg_off = data->crypt_offset & (PAGE_SIZE - 1);
+
+ *buf = data->crypt_pages[pg_idx] + pg_off;
+ size_avail = PAGE_SIZE - pg_off;
+ } else {
+ /* Use offsets just beyond the size to return the tag. */
+ tag_off = data->crypt_offset - (PAGE_SIZE * SNAPSHOT_CHUNK_SIZE);
+ if (tag_off > SNAPSHOT_AUTH_TAG_SIZE)
+ tag_off = SNAPSHOT_AUTH_TAG_SIZE;
+
+ *buf = data->auth_tag + tag_off;
+ size_avail = SNAPSHOT_AUTH_TAG_SIZE - tag_off;
+ }
+
+ if (data->user_key_valid && data->crypt_meta_size &&
+ data->crypt_stream_total < data->crypt_meta_size) {
+ u64 meta_avail = data->crypt_meta_size - data->crypt_stream_total;
+
+ size_avail = min_t(u64, size_avail, meta_avail);
+ }
+
+ return size_avail;
+}
+
+ssize_t snapshot_read_encrypted(struct snapshot_data *data,
+ char __user *buf, size_t count, loff_t *offp)
+{
+ size_t copy_size;
+ size_t not_done;
+ size_t pg_off;
+ void *src;
+ ssize_t src_size;
+
+ if (!count)
+ return 0;
+
+ pg_off = *offp & (PAGE_SIZE - 1);
+ count = min_t(size_t, count, PAGE_SIZE - pg_off);
+
+ src_size = snapshot_read_next_encrypted(data, &src);
+ if (src_size <= 0)
+ return src_size;
+
+ copy_size = min_t(size_t, count, src_size);
+ not_done = copy_to_user(buf, src, copy_size);
+ copy_size -= not_done;
+ if (!copy_size)
+ return -EFAULT;
+
+ data->crypt_offset += copy_size;
+ *offp += copy_size;
+ return copy_size;
+}
+
+ssize_t snapshot_write_encrypted(struct snapshot_data *data,
+ const char __user *buf, size_t count,
+ loff_t *offp)
+{
+ size_t copy_size;
+ size_t not_done;
+ size_t pg_off;
+ void *dst;
+ ssize_t dst_size;
+ int rc;
+
+ if (!count)
+ return 0;
+
+ pg_off = *offp & (PAGE_SIZE - 1);
+ count = min_t(size_t, count, PAGE_SIZE - pg_off);
+
+ dst_size = snapshot_write_next_encrypted(data, &dst);
+ if (dst_size <= 0)
+ return dst_size;
+
+ copy_size = min_t(size_t, count, dst_size);
+ not_done = copy_from_user(dst, buf, copy_size);
+ copy_size -= not_done;
+ if (!copy_size)
+ return -EFAULT;
+
+ data->crypt_offset += copy_size;
+ data->crypt_stream_total += copy_size;
+ /*
+ * Drain the encrypted buffer if it's full, or if we hit the end of the
+ * encrypted metadata and need a key change before user data pages.
+ */
+ if (data->crypt_offset >=
+ (PAGE_SIZE * SNAPSHOT_CHUNK_SIZE) + SNAPSHOT_AUTH_TAG_SIZE ||
+ (data->user_key_valid && data->crypt_meta_size &&
+ data->crypt_stream_total == data->crypt_meta_size)) {
+ rc = snapshot_decrypt_drain(data);
+ if (rc < 0)
+ return rc;
+ }
+
+ *offp += copy_size;
+ return copy_size;
+}
+
+static void snapshot_reset_encryption_state(struct snapshot_data *data)
+{
+ data->crypt_offset = 0;
+ data->crypt_size = 0;
+ data->crypt_total = 0;
+ data->crypt_stream_total = 0;
+ data->nonce_low = 0;
+ data->nonce_high = 0;
+ data->meta_size = 0;
+ data->crypt_meta_size = 0;
+ data->user_key_valid = false;
+ memset(data->auth_tag, 0, sizeof(data->auth_tag));
+}
+
+void snapshot_teardown_encryption(struct snapshot_data *data)
+{
+ int i;
+
+ if (data->aead_req) {
+ aead_request_free(data->aead_req);
+ data->aead_req = NULL;
+ }
+
+ if (data->aead_tfm) {
+ crypto_free_aead(data->aead_tfm);
+ data->aead_tfm = NULL;
+ }
+
+ for (i = 0; i < SNAPSHOT_CHUNK_SIZE; i++) {
+ if (data->crypt_pages[i]) {
+ free_page((unsigned long)data->crypt_pages[i]);
+ data->crypt_pages[i] = NULL;
+ }
+ }
+
+ memzero_explicit(data->encryption_key, sizeof(data->encryption_key));
+ memzero_explicit(data->user_key, sizeof(data->user_key));
+ snapshot_reset_encryption_state(data);
+}
+
+static int snapshot_setup_encryption_common(struct snapshot_data *data)
+{
+ int i, rc;
+
+ /* This only works once per hibernate. */
+ if (data->aead_tfm)
+ return -EINVAL;
+
+ snapshot_reset_encryption_state(data);
+ memset(data->crypt_pages, 0, sizeof(data->crypt_pages));
+
+ /* Set up the encryption transform */
+ data->aead_tfm = crypto_alloc_aead("gcm(aes)", 0, 0);
+ if (IS_ERR(data->aead_tfm)) {
+ rc = PTR_ERR(data->aead_tfm);
+ data->aead_tfm = NULL;
+ return rc;
+ }
+
+ rc = -ENOMEM;
+ data->aead_req = aead_request_alloc(data->aead_tfm, GFP_KERNEL);
+ if (!data->aead_req)
+ goto setup_fail;
+
+ /* Allocate the staging area */
+ for (i = 0; i < SNAPSHOT_CHUNK_SIZE; i++) {
+ data->crypt_pages[i] = (void *)__get_free_page(GFP_KERNEL);
+ if (!data->crypt_pages[i])
+ goto setup_fail;
+ }
+
+ sg_init_table(data->sg, SNAPSHOT_CHUNK_SIZE + 2);
+
+ /*
+ * The associated data will be the offset so that blocks can't be
+ * rearranged.
+ */
+ aead_request_set_ad(data->aead_req, sizeof(data->crypt_total));
+ rc = crypto_aead_setauthsize(data->aead_tfm, SNAPSHOT_AUTH_TAG_SIZE);
+ if (rc)
+ goto setup_fail;
+
+ return 0;
+
+setup_fail:
+ snapshot_teardown_encryption(data);
+ return rc;
+}
+
+int snapshot_get_encryption_key(struct snapshot_data *data,
+ struct uswsusp_key_blob __user *key)
+{
+ struct snapshot_wrapped_key wrapped = {};
+ u8 image_key[SNAPSHOT_ENCRYPTION_KEY_SIZE] __nonstring = {};
+ u8 nonce[USWSUSP_KEY_NONCE_SIZE];
+ int rc;
+
+ /* Don't pull a random key from a world that can be reset. */
+ if (data->ready)
+ return -EPIPE;
+
+ rc = snapshot_setup_encryption_common(data);
+ if (rc)
+ return rc;
+
+ /* Build a random starting nonce. */
+ get_random_bytes(nonce, sizeof(nonce));
+ memcpy(&data->nonce_low, &nonce[0], sizeof(data->nonce_low));
+ memcpy(&data->nonce_high, &nonce[8], sizeof(data->nonce_high));
+
+ /* Build and install a random image encryption key. */
+ get_random_bytes(image_key, sizeof(image_key));
+ rc = snapshot_install_image_key(data, image_key);
+ if (rc)
+ goto fail;
+
+ rc = snapshot_wrap_image_key(image_key, &wrapped);
+ if (rc)
+ goto fail;
+
+ /* Hand the wrapped key and clear nonce back to user mode. */
+ rc = put_user(sizeof(wrapped), &key->blob_len);
+ if (rc)
+ goto fail;
+
+ BUILD_BUG_ON(sizeof(wrapped) >
+ sizeof(((struct uswsusp_key_blob *)0)->blob));
+ if (copy_to_user(&key->blob, &wrapped, sizeof(wrapped))) {
+ rc = -EFAULT;
+ goto fail;
+ }
+
+ if (copy_to_user(&key->nonce, &nonce, sizeof(nonce))) {
+ rc = -EFAULT;
+ goto fail;
+ }
+
+ memzero_explicit(image_key, sizeof(image_key));
+ memzero_explicit(&wrapped, sizeof(wrapped));
+ return 0;
+
+fail:
+ memzero_explicit(image_key, sizeof(image_key));
+ memzero_explicit(&wrapped, sizeof(wrapped));
+ snapshot_teardown_encryption(data);
+ return rc;
+}
+
+int snapshot_set_encryption_key(struct snapshot_data *data,
+ struct uswsusp_key_blob __user *key)
+{
+ struct uswsusp_key_blob *blob;
+ struct snapshot_wrapped_key wrapped = {};
+ u8 image_key[SNAPSHOT_ENCRYPTION_KEY_SIZE] __nonstring = {};
+ int rc;
+
+ /* It's too late if data's been pushed in. */
+ if (data->handle.cur)
+ return -EPIPE;
+
+ rc = snapshot_setup_encryption_common(data);
+ if (rc)
+ return rc;
+
+ /* Load the key from user mode. */
+ blob = memdup_user(key, sizeof(*blob));
+ if (IS_ERR(blob)) {
+ rc = PTR_ERR(blob);
+ goto crypto_setup_fail;
+ }
+
+ if (blob->blob_len != sizeof(wrapped)) {
+ rc = -EINVAL;
+ goto out_blob;
+ }
+
+ memcpy(&wrapped, blob->blob, sizeof(wrapped));
+ rc = snapshot_unwrap_image_key(&wrapped, image_key);
+ if (rc)
+ goto out_blob;
+
+ rc = snapshot_install_image_key(data, image_key);
+ if (rc)
+ goto out_blob;
+
+ /* Load the starting nonce. */
+ memcpy(&data->nonce_low, &blob->nonce[0], sizeof(data->nonce_low));
+ memcpy(&data->nonce_high, &blob->nonce[8], sizeof(data->nonce_high));
+
+out_blob:
+ kfree_sensitive(blob);
+ memzero_explicit(&wrapped, sizeof(wrapped));
+ memzero_explicit(image_key, sizeof(image_key));
+ if (rc)
+ goto crypto_setup_fail;
+
+ return 0;
+
+crypto_setup_fail:
+ memzero_explicit(&wrapped, sizeof(wrapped));
+ memzero_explicit(image_key, sizeof(image_key));
+ snapshot_teardown_encryption(data);
+ return rc;
+}
+
+static loff_t snapshot_encrypted_byte_count(loff_t plain_size)
+{
+ loff_t pages = plain_size >> PAGE_SHIFT;
+ loff_t chunks = (pages + (SNAPSHOT_CHUNK_SIZE - 1)) / SNAPSHOT_CHUNK_SIZE;
+ /*
+ * The encrypted size is the normal size, plus a stitched in
+ * authentication tag for every chunk of pages.
+ */
+ return plain_size + (chunks * SNAPSHOT_AUTH_TAG_SIZE);
+}
+
+static loff_t snapshot_encrypted_split_byte_count(loff_t raw_size,
+ loff_t meta_plain_size)
+{
+ if (raw_size <= meta_plain_size)
+ return snapshot_encrypted_byte_count(raw_size);
+
+ return snapshot_encrypted_byte_count(meta_plain_size) +
+ snapshot_encrypted_byte_count(raw_size - meta_plain_size);
+}
+
+int snapshot_set_user_key(struct snapshot_data *data,
+ struct uswsusp_user_key __user *key)
+{
+ struct uswsusp_user_key user_key = {};
+ unsigned int key_len;
+ u64 size;
+ int rc;
+
+ if (!snapshot_encryption_enabled(data))
+ return -EINVAL;
+
+ if (copy_from_user(&user_key, key, sizeof(struct uswsusp_user_key)))
+ return -EFAULT;
+
+ BUILD_BUG_ON(sizeof(data->user_key) < sizeof(user_key.key));
+ rc = -EINVAL;
+ if (user_key.reserved)
+ goto out;
+ if (user_key.key_len > sizeof(data->user_key))
+ goto out;
+ if (user_key.key_len < 8)
+ goto out;
+
+ if (data->mode == O_RDONLY && !data->ready) {
+ rc = -ENODATA;
+ goto out;
+ }
+
+ /*
+ * Return the metadata size, the number of bytes that can be fed in before
+ * the user data key is needed at resume time.
+ */
+ if (data->mode == O_WRONLY && !data->meta_size) {
+ if (user_key.meta_size < PAGE_SIZE + SNAPSHOT_AUTH_TAG_SIZE)
+ goto out;
+
+ data->crypt_meta_size = user_key.meta_size;
+ size = data->crypt_meta_size;
+ } else {
+ snapshot_set_meta_size(data,
+ snapshot_get_meta_page_count() << PAGE_SHIFT);
+ size = data->crypt_meta_size;
+ }
+
+ rc = put_user(size, &key->meta_size);
+ if (rc)
+ goto out;
+
+ key_len = user_key.key_len;
+
+ /* Don't allow it if it's too late. */
+ if ((data->meta_size && data->crypt_total > data->meta_size) ||
+ (data->crypt_meta_size &&
+ data->crypt_stream_total > data->crypt_meta_size)) {
+ rc = -EBUSY;
+ goto out;
+ }
+
+ /*
+ * Resume may preload the user key before writing any image data, or
+ * install it after writing exactly the saved metadata stream. In the
+ * latter case, authenticate and publish the buffered metadata under the
+ * original image key before switching keys.
+ */
+ if (data->mode == O_WRONLY && data->crypt_meta_size &&
+ data->crypt_stream_total == data->crypt_meta_size &&
+ data->crypt_offset) {
+ rc = snapshot_decrypt_drain(data);
+ if (rc)
+ goto out;
+ if (data->crypt_total != data->meta_size) {
+ rc = -EINVAL;
+ goto out;
+ }
+ }
+
+ memset(data->user_key, 0, sizeof(data->user_key));
+ memcpy(data->user_key, user_key.key, key_len);
+ data->user_key_valid = true;
+ /* Install the key if the user is just under the wire. */
+ rc = snapshot_check_user_key_switch(data);
+ if (rc)
+ goto out;
+
+ rc = 0;
+
+out:
+ memzero_explicit(&user_key, sizeof(user_key));
+ return rc;
+}
+
+loff_t snapshot_get_encrypted_image_size(struct snapshot_data *data,
+ loff_t raw_size)
+{
+ loff_t meta_plain_size = data->meta_size;
+ loff_t split_size;
+
+ if (!meta_plain_size)
+ meta_plain_size = snapshot_get_meta_page_count() << PAGE_SHIFT;
+
+ split_size = snapshot_encrypted_split_byte_count(raw_size,
+ meta_plain_size);
+ if (!data->user_key_valid) {
+ /*
+ * Userspace may install a user key after querying the image size.
+ * Reserve enough space for either framing so that later splitting at
+ * the metadata boundary cannot make the reported size too small.
+ */
+ return max(snapshot_encrypted_byte_count(raw_size), split_size);
+ }
+
+ return split_size;
+}
+
+int snapshot_finalize_decrypted_image(struct snapshot_data *data)
+{
+ int rc;
+
+ if (data->crypt_offset != 0) {
+ rc = snapshot_decrypt_drain(data);
+ if (rc)
+ return rc;
+ }
+
+ return 0;
+}
diff --git a/kernel/power/snapshot.c b/kernel/power/snapshot.c
index b209712cb2c3a..d1a226a25d27e 100644
--- a/kernel/power/snapshot.c
+++ b/kernel/power/snapshot.c
@@ -2177,6 +2177,11 @@ unsigned long snapshot_get_image_size(void)
return nr_copy_pages + nr_meta_pages + 1;
}
+unsigned long snapshot_get_meta_page_count(void)
+{
+ return nr_meta_pages + 1;
+}
+
static int init_header(struct swsusp_info *info)
{
memset(info, 0, sizeof(struct swsusp_info));
diff --git a/kernel/power/swap.c b/kernel/power/swap.c
index c78f1593600bb..ac736d2b59e3f 100644
--- a/kernel/power/swap.c
+++ b/kernel/power/swap.c
@@ -166,6 +166,93 @@ static int swsusp_extents_insert(unsigned long swap_offset)
return 0;
}
+static bool swsusp_extents_contain_range(unsigned long swap_offset,
+ unsigned long nr_pages)
+{
+ struct rb_node *node = swsusp_extents.rb_node;
+ struct swsusp_extent *ext;
+ unsigned long end;
+
+ if (!nr_pages)
+ return false;
+
+ end = swap_offset + nr_pages - 1;
+ if (end < swap_offset)
+ return false;
+
+ while (node) {
+ ext = rb_entry(node, struct swsusp_extent, node);
+ if (swap_offset < ext->start)
+ node = node->rb_left;
+ else if (swap_offset > ext->end)
+ node = node->rb_right;
+ else
+ goto found;
+ }
+
+ return false;
+
+found:
+ for (;;) {
+ if (swap_offset < ext->start)
+ return false;
+ if (end <= ext->end)
+ return true;
+ if (ext->end == (unsigned long)-1)
+ return false;
+
+ swap_offset = ext->end + 1;
+ node = rb_next(&ext->node);
+ if (!node)
+ return false;
+
+ ext = rb_entry(node, struct swsusp_extent, node);
+ }
+}
+
+bool swsusp_swap_range_allocated(int swap, loff_t pos, size_t count)
+{
+ u64 block;
+ u64 end;
+ u64 end_block;
+
+ if (swap < 0 || pos < 0 || !count)
+ return false;
+
+ end = (u64)pos + count - 1;
+ if (end < (u64)pos)
+ return false;
+
+ block = (u64)pos >> PAGE_SHIFT;
+ end_block = end >> PAGE_SHIFT;
+
+ for (;;) {
+ u64 remaining_pages = end_block - block + 1;
+ pgoff_t swap_offset;
+ pgoff_t mapped_pages;
+ sector_t page_block = block;
+ u64 pages;
+
+ if (!remaining_pages)
+ return false;
+ if ((u64)page_block != block)
+ return false;
+ if (swapdev_block_to_extent(swap, page_block, &swap_offset,
+ &mapped_pages))
+ return false;
+ if (!mapped_pages)
+ return false;
+ pages = min_t(u64, mapped_pages, remaining_pages);
+ if ((u64)(unsigned long)pages != pages)
+ return false;
+ if (!swsusp_extents_contain_range(swap_offset, pages))
+ return false;
+ if (pages == remaining_pages)
+ return true;
+ block += pages;
+ }
+}
+
sector_t alloc_swapdev_block(int swap)
{
unsigned long offset;
diff --git a/kernel/power/user.c b/kernel/power/user.c
index d0fcfba7ac235..b8d3342f1548f 100644
--- a/kernel/power/user.c
+++ b/kernel/power/user.c
@@ -21,54 +21,196 @@
#include <linux/console.h>
#include <linux/cpu.h>
#include <linux/freezer.h>
+#include <linux/pid.h>
+#include <linux/sched/signal.h>
+#include <linux/security.h>
#include <linux/uaccess.h>
#include "power.h"
+#include "user.h"
static bool need_wait;
-
-static struct snapshot_data {
- struct snapshot_handle handle;
- int swap;
- int mode;
- bool frozen;
- bool ready;
- bool platform_support;
- bool free_bitmaps;
- dev_t dev;
-} snapshot_state;
+static struct snapshot_data snapshot_state;
int is_hibernate_resume_dev(dev_t dev)
{
return hibernation_available() && snapshot_state.dev == dev;
}
+bool hibernate_snapshot_write_active(dev_t dev)
+{
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ struct snapshot_data *data = &snapshot_state;
+
+ return data->encryption_required && data->mode == O_RDONLY &&
+ data->ready && data->dev == dev &&
+ snapshot_encryption_enabled(data);
+#else
+ return false;
+#endif
+}
+
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+static bool snapshot_encrypted_output_owned(struct snapshot_data *data, dev_t dev)
+{
+ return hibernate_snapshot_write_active(dev) &&
+ data->owner_tgid == task_tgid(current);
+}
+
+static bool snapshot_header_write_range(struct snapshot_data *data,
+ loff_t pos, size_t count)
+{
+ loff_t header_offset = data->swap_header_offset;
+ loff_t offset;
+
+ if (pos < header_offset)
+ return false;
+
+ offset = pos - header_offset;
+ return offset < PAGE_SIZE && count <= PAGE_SIZE - offset;
+}
+
+static u64 snapshot_swap_write_budget(struct snapshot_data *data)
+{
+ if (data->crypt_swap_allocated > U64_MAX >> PAGE_SHIFT)
+ return 0;
+
+ return data->crypt_swap_allocated << PAGE_SHIFT;
+}
+
+static void snapshot_reset_swap_write_state(struct snapshot_data *data,
+ bool reset_allocation)
+{
+ spin_lock(&data->crypt_lock);
+ if (reset_allocation)
+ data->crypt_swap_allocated = 0;
+ data->crypt_swap_reserved = 0;
+ data->crypt_header_reserved = 0;
+ spin_unlock(&data->crypt_lock);
+}
+#endif
+
+enum hibernate_snapshot_write
+hibernate_snapshot_write_begin(dev_t dev, loff_t pos, size_t count)
+{
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ struct snapshot_data *data = &snapshot_state;
+ enum hibernate_snapshot_write type = HIBERNATE_SNAPSHOT_WRITE_NONE;
+ bool image_range_allocated;
+ u64 swap_budget;
+
+ if (!count || !snapshot_encrypted_output_owned(data, dev))
+ return HIBERNATE_SNAPSHOT_WRITE_NONE;
+
+ mutex_lock(&system_transition_mutex);
+
+ if (!snapshot_encrypted_output_owned(data, dev))
+ goto unlock;
+
+ image_range_allocated = swsusp_swap_range_allocated(data->swap, pos, count);
+
+ spin_lock(&data->crypt_lock);
+ swap_budget = snapshot_swap_write_budget(data);
+ if (snapshot_header_write_range(data, pos, count) &&
+ data->crypt_header_reserved <= PAGE_SIZE &&
+ PAGE_SIZE - data->crypt_header_reserved >= count) {
+ data->crypt_header_reserved += count;
+ type = HIBERNATE_SNAPSHOT_WRITE_HEADER;
+ } else if (image_range_allocated &&
+ swap_budget >= data->crypt_swap_reserved &&
+ swap_budget - data->crypt_swap_reserved >= count) {
+ data->crypt_swap_reserved += count;
+ type = HIBERNATE_SNAPSHOT_WRITE_IMAGE;
+ }
+ spin_unlock(&data->crypt_lock);
+
+ if (type == HIBERNATE_SNAPSHOT_WRITE_NONE)
+ goto unlock;
+
+ return type;
+
+unlock:
+ mutex_unlock(&system_transition_mutex);
+ return HIBERNATE_SNAPSHOT_WRITE_NONE;
+#else
+ return HIBERNATE_SNAPSHOT_WRITE_NONE;
+#endif
+}
+
+void hibernate_snapshot_write_end(enum hibernate_snapshot_write type,
+ size_t reserved, ssize_t written)
+{
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ struct snapshot_data *data = &snapshot_state;
+ u64 *reserved_total;
+ size_t unused;
+
+ if (type == HIBERNATE_SNAPSHOT_WRITE_NONE)
+ return;
+ if (!reserved)
+ goto unlock;
+
+ if (type == HIBERNATE_SNAPSHOT_WRITE_HEADER)
+ unused = reserved;
+ else if (written <= 0)
+ unused = reserved;
+ else if (written < reserved)
+ unused = reserved - written;
+ else
+ goto unlock;
+
+ reserved_total = type == HIBERNATE_SNAPSHOT_WRITE_HEADER ?
+ &data->crypt_header_reserved : &data->crypt_swap_reserved;
+
+ spin_lock(&data->crypt_lock);
+ *reserved_total -= min_t(u64, *reserved_total, unused);
+ spin_unlock(&data->crypt_lock);
+
+unlock:
+ mutex_unlock(&system_transition_mutex);
+#endif
+}
+
+static bool snapshot_encryption_required(struct snapshot_data *data)
+{
+ data->encryption_required = security_locked_down(LOCKDOWN_HIBERNATION);
+ return data->encryption_required;
+}
+
static int snapshot_open(struct inode *inode, struct file *filp)
{
struct snapshot_data *data;
unsigned int sleep_flags;
int error;
- if (!hibernation_available())
+ if (!hibernation_snapshot_dev_available())
return -EPERM;
sleep_flags = lock_system_sleep();
if (!hibernate_acquire()) {
error = -EBUSY;
- goto Unlock;
+ goto unlock;
}
if ((filp->f_flags & O_ACCMODE) == O_RDWR) {
hibernate_release();
error = -ENOSYS;
- goto Unlock;
+ goto unlock;
}
nonseekable_open(inode, filp);
data = &snapshot_state;
filp->private_data = data;
memset(&data->handle, 0, sizeof(struct snapshot_handle));
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ spin_lock_init(&data->crypt_lock);
+ data->crypt_swap_allocated = 0;
+ data->crypt_swap_reserved = 0;
+ data->crypt_header_reserved = 0;
+ data->swap_header_offset = 0;
+ data->owner_tgid = NULL;
+#endif
if ((filp->f_flags & O_ACCMODE) == O_RDONLY) {
/* Hibernating. The image device should be accessible. */
data->swap = pin_hibernation_swap_type(swsusp_resume_device, 0);
@@ -99,8 +241,13 @@ static int snapshot_open(struct inode *inode, struct file *filp)
data->ready = false;
data->platform_support = false;
data->dev = 0;
+ data->encryption_required = snapshot_encryption_required(data);
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ if (!error)
+ data->owner_tgid = get_task_pid(current, PIDTYPE_TGID);
+#endif
- Unlock:
+ unlock:
unlock_system_sleep(sleep_flags);
return error;
@@ -116,6 +263,10 @@ static int snapshot_release(struct inode *inode, struct file *filp)
swsusp_free();
data = filp->private_data;
data->dev = 0;
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ put_pid(data->owner_tgid);
+ data->owner_tgid = NULL;
+#endif
free_all_swap_pages(data->swap);
unpin_hibernation_swap_type(data->swap);
if (data->frozen) {
@@ -125,6 +276,7 @@ static int snapshot_release(struct inode *inode, struct file *filp)
} else if (data->free_bitmaps) {
free_basic_memory_bitmaps();
}
+ snapshot_teardown_encryption(data);
pm_notifier_call_chain(data->mode == O_RDONLY ?
PM_POST_HIBERNATION : PM_POST_RESTORE);
hibernate_release();
@@ -147,12 +299,23 @@ static ssize_t snapshot_read(struct file *filp, char __user *buf,
data = filp->private_data;
if (!data->ready) {
res = -ENODATA;
- goto Unlock;
+ goto unlock;
+ }
+ if (snapshot_encryption_required(data) &&
+ !snapshot_encryption_enabled(data)) {
+ res = -EPERM;
+ goto unlock;
}
+
+ if (snapshot_encryption_enabled(data)) {
+ res = snapshot_read_encrypted(data, buf, count, offp);
+ goto unlock;
+ }
+
if (!pg_offp) { /* on page boundary? */
res = snapshot_read_next(&data->handle);
if (res <= 0)
- goto Unlock;
+ goto unlock;
} else {
res = PAGE_SIZE - pg_offp;
}
@@ -162,7 +325,7 @@ static ssize_t snapshot_read(struct file *filp, char __user *buf,
if (res > 0)
*offp += res;
- Unlock:
+ unlock:
unlock_system_sleep(sleep_flags);
return res;
@@ -185,6 +348,17 @@ static ssize_t snapshot_write(struct file *filp, const char __user *buf,
data = filp->private_data;
+ if (snapshot_encryption_required(data) &&
+ !snapshot_encryption_enabled(data)) {
+ res = -EPERM;
+ goto unlock;
+ }
+
+ if (snapshot_encryption_enabled(data)) {
+ res = snapshot_write_encrypted(data, buf, count, offp);
+ goto unlock;
+ }
+
if (!pg_offp) {
res = snapshot_write_next(&data->handle);
if (res <= 0)
@@ -252,6 +426,9 @@ static int snapshot_set_swap_area(struct snapshot_data *data,
if (data->swap < 0)
return swdev ? -ENODEV : -EINVAL;
data->dev = swdev;
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ data->swap_header_offset = (loff_t)offset << PAGE_SHIFT;
+#endif
return 0;
}
@@ -318,6 +495,11 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,
error = -EPERM;
break;
}
+ if (snapshot_encryption_required(data) &&
+ !snapshot_encryption_enabled(data)) {
+ error = -EPERM;
+ break;
+ }
pm_restore_gfp_mask();
error = hibernation_snapshot(data->platform_support);
if (!error) {
@@ -328,6 +510,17 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,
break;
case SNAPSHOT_ATOMIC_RESTORE:
+ if (snapshot_encryption_required(data) &&
+ !snapshot_encryption_enabled(data)) {
+ error = -EPERM;
+ break;
+ }
+ if (snapshot_encryption_enabled(data)) {
+ error = snapshot_finalize_decrypted_image(data);
+ if (error)
+ break;
+ }
+
error = snapshot_write_finalize(&data->handle);
if (error)
break;
@@ -346,6 +539,10 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,
swsusp_free();
memset(&data->handle, 0, sizeof(struct snapshot_handle));
data->ready = false;
+ snapshot_teardown_encryption(data);
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ snapshot_reset_swap_write_state(data, false);
+#endif
/*
* It is necessary to thaw kernel threads here, because
* SNAPSHOT_CREATE_IMAGE may be invoked directly after
@@ -368,6 +565,8 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,
}
size = snapshot_get_image_size();
size <<= PAGE_SHIFT;
+ if (snapshot_encryption_enabled(data))
+ size = snapshot_get_encrypted_image_size(data, size);
error = put_user(size, (loff_t __user *)arg);
break;
@@ -386,6 +585,13 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,
if (offset) {
offset <<= PAGE_SHIFT;
error = put_user(offset, (loff_t __user *)arg);
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ if (!error) {
+ spin_lock(&data->crypt_lock);
+ data->crypt_swap_allocated++;
+ spin_unlock(&data->crypt_lock);
+ }
+#endif
} else {
error = -ENOSPC;
}
@@ -397,6 +603,9 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,
break;
}
free_all_swap_pages(data->swap);
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ snapshot_reset_swap_write_state(data, true);
+#endif
break;
case SNAPSHOT_S2RAM:
@@ -404,6 +613,11 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,
error = -EPERM;
break;
}
+ if (snapshot_encryption_required(data) &&
+ !snapshot_encryption_enabled(data)) {
+ error = -EPERM;
+ break;
+ }
/*
* Tasks are frozen and the notifiers have been called with
* PM_HIBERNATION_PREPARE
@@ -417,6 +631,11 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,
break;
case SNAPSHOT_POWER_OFF:
+ if (snapshot_encryption_required(data) &&
+ !snapshot_encryption_enabled(data)) {
+ error = -EPERM;
+ break;
+ }
if (data->platform_support)
error = hibernation_platform_enter();
break;
@@ -425,6 +644,21 @@ static long snapshot_ioctl(struct file *filp, unsigned int cmd,
error = snapshot_set_swap_area(data, (void __user *)arg);
break;
+ case SNAPSHOT_ENABLE_ENCRYPTION:
+ if (data->mode == O_RDONLY)
+ error = snapshot_get_encryption_key(data, (void __user *)arg);
+ else
+ error = snapshot_set_encryption_key(data, (void __user *)arg);
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ if (!error)
+ snapshot_reset_swap_write_state(data, false);
+#endif
+ break;
+
+ case SNAPSHOT_SET_USER_KEY:
+ error = snapshot_set_user_key(data, (void __user *)arg);
+ break;
+
default:
error = -ENOTTY;
@@ -448,6 +682,8 @@ snapshot_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
case SNAPSHOT_ALLOC_SWAP_PAGE:
case SNAPSHOT_CREATE_IMAGE:
case SNAPSHOT_SET_SWAP_AREA:
+ case SNAPSHOT_ENABLE_ENCRYPTION:
+ case SNAPSHOT_SET_USER_KEY:
return snapshot_ioctl(file, cmd,
(unsigned long) compat_ptr(arg));
default:
diff --git a/kernel/power/user.h b/kernel/power/user.h
new file mode 100644
index 0000000000000..0e1e123e32300
--- /dev/null
+++ b/kernel/power/user.h
@@ -0,0 +1,150 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+#ifndef __POWER_USER_H
+#define __POWER_USER_H
+
+#include <linux/crypto.h>
+#include <linux/scatterlist.h>
+#include <linux/spinlock.h>
+#include <linux/suspend_ioctls.h>
+#include <crypto/aead.h>
+#include <crypto/aes.h>
+
+struct pid;
+
+#define SNAPSHOT_ENCRYPTION_KEY_SIZE AES_KEYSIZE_128
+#define SNAPSHOT_AUTH_TAG_SIZE 16
+
+/* Define the number of pages in a single AEAD encryption chunk. */
+#define SNAPSHOT_CHUNK_SIZE 16
+
+struct snapshot_data {
+ struct snapshot_handle handle;
+ int swap;
+ int mode;
+ bool frozen;
+ bool ready;
+ bool platform_support;
+ bool free_bitmaps;
+ bool encryption_required;
+ dev_t dev;
+
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+ struct crypto_aead *aead_tfm;
+ struct aead_request *aead_req;
+ void *crypt_pages[SNAPSHOT_CHUNK_SIZE];
+ u8 auth_tag[SNAPSHOT_AUTH_TAG_SIZE];
+ struct scatterlist sg[SNAPSHOT_CHUNK_SIZE + 2]; /* Add room for AD and auth tag. */
+ size_t crypt_offset;
+ size_t crypt_size;
+ u64 crypt_total;
+ u64 crypt_stream_total;
+ u64 nonce_low;
+ u64 nonce_high;
+ u8 encryption_key[SNAPSHOT_ENCRYPTION_KEY_SIZE] __nonstring;
+ u8 user_key[USWSUSP_USER_KEY_SIZE] __nonstring;
+ bool user_key_valid;
+ u64 meta_size;
+ u64 crypt_meta_size;
+ /* Protect the swap allocation and block-write reservations. */
+ spinlock_t crypt_lock;
+ u64 crypt_swap_allocated;
+ u64 crypt_swap_reserved;
+ u64 crypt_header_reserved;
+ loff_t swap_header_offset;
+ struct pid *owner_tgid;
+#endif
+
+};
+
+/* kernel/power/snapenc.c routines */
+#if defined(CONFIG_ENCRYPTED_HIBERNATION)
+
+ssize_t snapshot_read_encrypted(struct snapshot_data *data,
+ char __user *buf, size_t count, loff_t *offp);
+
+ssize_t snapshot_write_encrypted(struct snapshot_data *data,
+ const char __user *buf, size_t count,
+ loff_t *offp);
+
+void snapshot_teardown_encryption(struct snapshot_data *data);
+int snapshot_get_encryption_key(struct snapshot_data *data,
+ struct uswsusp_key_blob __user *key);
+
+int snapshot_set_encryption_key(struct snapshot_data *data,
+ struct uswsusp_key_blob __user *key);
+
+int snapshot_set_user_key(struct snapshot_data *data,
+ struct uswsusp_user_key __user *key);
+
+int snapshot_store_encryption_seed(const char *buf, size_t count);
+
+loff_t snapshot_get_encrypted_image_size(struct snapshot_data *data,
+ loff_t raw_size);
+
+int snapshot_finalize_decrypted_image(struct snapshot_data *data);
+
+static inline bool snapshot_encryption_enabled(struct snapshot_data *data)
+{
+ return data->aead_tfm;
+}
+
+#else
+
+static inline ssize_t snapshot_read_encrypted(struct snapshot_data *data,
+ char __user *buf, size_t count,
+ loff_t *offp)
+{
+ return -ENOTTY;
+}
+
+static inline ssize_t snapshot_write_encrypted(struct snapshot_data *data,
+ const char __user *buf,
+ size_t count, loff_t *offp)
+{
+ return -ENOTTY;
+}
+
+static inline void snapshot_teardown_encryption(struct snapshot_data *data) {}
+static inline int snapshot_get_encryption_key(struct snapshot_data *data,
+ struct uswsusp_key_blob __user *key)
+{
+ return -ENOTTY;
+}
+
+static inline int snapshot_set_encryption_key(struct snapshot_data *data,
+ struct uswsusp_key_blob __user *key)
+{
+ return -ENOTTY;
+}
+
+static inline int snapshot_set_user_key(struct snapshot_data *data,
+ struct uswsusp_user_key __user *key)
+{
+ return -ENOTTY;
+}
+
+static inline int snapshot_store_encryption_seed(const char *buf, size_t count)
+{
+ return -ENOTTY;
+}
+
+static inline loff_t snapshot_get_encrypted_image_size(struct snapshot_data *data,
+ loff_t raw_size)
+{
+ return raw_size;
+}
+
+static inline int snapshot_finalize_decrypted_image(struct snapshot_data *data)
+{
+ return -ENOTTY;
+}
+
+static inline bool snapshot_encryption_enabled(struct snapshot_data *data)
+{
+ return false;
+}
+
+#endif
+
+#endif /* __POWER_USER_H */
diff --git a/mm/swapfile.c b/mm/swapfile.c
index 601979b97f95b..ebddf954ad840 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -2379,6 +2379,31 @@ sector_t swapdev_block(int type, pgoff_t offset)
return se->start_block + (offset - se->start_page);
}
+int swapdev_block_to_extent(int type, sector_t block, pgoff_t *offset,
+ pgoff_t *nr_pages)
+{
+ struct swap_info_struct *si = swap_type_to_info(type);
+ struct swap_extent *se;
+ struct rb_node *rb;
+
+ if (!si || !(si->flags & SWP_WRITEOK))
+ return -ENODEV;
+
+ for (rb = rb_first(&si->swap_extent_root); rb; rb = rb_next(rb)) {
+ se = rb_entry(rb, struct swap_extent, rb_node);
+ if (block >= se->start_block &&
+ block - se->start_block < se->nr_pages) {
+ pgoff_t page = block - se->start_block;
+
+ *offset = se->start_page + page;
+ *nr_pages = se->nr_pages - page;
+ return 0;
+ }
+ }
+
+ return -ENOENT;
+}
+
/*
* Return either the total number of swap pages of given type, or the number
* of free pages of that type (depending on @free)
|
| 35/3 | 2026/09/19 12:43 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 25312 output: 30 thoughts: 3819 Thoughts: **KMSAN Needs Analysis: Suspend/Hibernate Patch Series**
Okay, let's break this down. My task is to determine if this patch series necessitates a dedicated KMSAN fuzzing session, beyond the usual KASAN coverage. The core idea is that KMSAN is only relevant if the patch introduces or exposes risks of uninitialized memory *that KMSAN specifically catches*. If KASAN, LOCKDEP, or other tools would catch it, then no KMSAN is needed.
The key areas I need to investigate are:
1. **User-Space Interfaces**: Does the patch introduce or change structures that are copied to/from user space (via `copy_to_user`, `put_user`, netlink, ioctl, etc.)? I need to focus on where uninitialized data could leak to user space.
2. **Conditional Logic**: Are there branches or logic paths that depend on the value of potentially uninitialized variables or struct fields?
3. **Data Structure Initialization**: Does the patch allocate complex data structures where uninitialized fields could be read later in reachable code?
4. **Bounds/Length Checks**: Does the patch have any interactions with buffers or memory that could be accessed based on uninitialized data?
Now, let's go line-by-line through the provided code.
* **`include/uapi/linux/suspend_ioctls.h`**: The new `struct uswsusp_key_blob` and `struct uswsusp_user_key` are introduced. The crucial point here is the `__attribute__((packed))` attribute. This means there's no compiler-inserted padding, which reduces the potential for uninitialized data. However, I need to check the copy operations.
* **`snapshot_get_encryption_key`**: This function copies `struct uswsusp_key_blob` to userspace.
* `snapshot_wrapped_key wrapped = {};` Zero-initializes `wrapped`.
* The `memcpy` operations and the `get_random_bytes` on `nonce` look safe and initialized.
* The critical line is `copy_to_user(&key->blob, &wrapped, sizeof(wrapped))`. `key` is a user-provided pointer to `struct uswsusp_key_blob`. The code is copying a portion (56 bytes) of the `wrapped` key structure into the `key->blob` field, which is 512 bytes. *This looks suspicious because the remainder of the buffer could be uninitialized*.
* However, `wrapped` is zeroed and fully initialized before the copy.
* The `nonce` is also fully initialized.
* No obvious KMSAN issue here.
* **`snapshot_set_user_key`**: This only copies a `u64` (meta_size) to user space via `put_user`. Looks safe.
* **`snapshot_read_encrypted`**: This reads encrypted data and copies it to userspace via `copy_to_user`. I need to track the `src`.
* `src` is returned by `snapshot_read_next_encrypted`.
* `snapshot_read_next_encrypted` checks if a buffer is empty. It copies the tag if the offset is beyond the data size. The critical part is `snapshot_encrypt_refill`.
* **`snapshot_encrypt_refill`**: It reads snapshot pages. The `aead_request_set_crypt` seems to encrypt into the `data->crypt_pages`.
* `sg_set_buf(&data->sg[1 + pg_idx], &data->auth_tag, SNAPSHOT_AUTH_TAG_SIZE);` This copies the authentication tag from `data->auth_tag`. The encryption operation writes an authentication tag at the end. The encryption writes into the pages. No direct copy to user of uninitialized memory that KMSAN would catch.
Based on this analysis, I don't see any scenarios where KMSAN would catch an uninitialized memory read that KASAN wouldn't. Therefore, **I do not believe a dedicated KMSAN fuzzing session is justified for this patch series.**
|
| 36/3 | 2026/09/19 12:43 | tool | grepper |
0mArgs:{
"Expression": "aead_request_set_crypt",
"PathPrefix": "crypto/"
}Results: {
"Output": "crypto/algif_aead.c=70=static int _aead_recvmsg(struct socket *sock, struct msghdr *msg,\n--\ncrypto/algif_aead.c-199-\t/* Initialize the crypto operation */\ncrypto/algif_aead.c:200:\taead_request_set_crypt(\u0026areq-\u003ecra_u.aead_req, tsgl_src,\ncrypto/algif_aead.c-201-\t\t\t areq-\u003efirst_rsgl.sgl.sgt.sgl, used, iv);\n--\ncrypto/ccm.c=598=static struct aead_request *crypto_rfc4309_crypt(struct aead_request *req)\n--\ncrypto/ccm.c-633-\t\t\t\t req-\u003ebase.data);\ncrypto/ccm.c:634:\taead_request_set_crypt(subreq, rctx-\u003esrc,\ncrypto/ccm.c-635-\t\t\t req-\u003esrc == req-\u003edst ? rctx-\u003esrc : rctx-\u003edst,\n--\ncrypto/cryptd.c=728=static void cryptd_aead_crypt(struct aead_request *req,\n--\ncrypto/cryptd.c-751-\t\t\t\t NULL, NULL);\ncrypto/cryptd.c:752:\taead_request_set_crypt(subreq, req-\u003esrc, req-\u003edst, req-\u003ecryptlen,\ncrypto/cryptd.c-753-\t\t\t req-\u003eiv);\n--\ncrypto/echainiv.c=26=static int echainiv_encrypt(struct aead_request *req)\n--\ncrypto/echainiv.c-48-\t\t\t\t req-\u003ebase.complete, req-\u003ebase.data);\ncrypto/echainiv.c:49:\taead_request_set_crypt(subreq, req-\u003edst, req-\u003edst,\ncrypto/echainiv.c-50-\t\t\t req-\u003ecryptlen, info);\n--\ncrypto/echainiv.c=73=static int echainiv_decrypt(struct aead_request *req)\n--\ncrypto/echainiv.c-90-\taead_request_set_callback(subreq, req-\u003ebase.flags, compl, data);\ncrypto/echainiv.c:91:\taead_request_set_crypt(subreq, req-\u003esrc, req-\u003edst,\ncrypto/echainiv.c-92-\t\t\t req-\u003ecryptlen - ivsize, req-\u003eiv);\n--\ncrypto/essiv.c=183=static int essiv_aead_crypt(struct aead_request *req, bool enc)\n--\ncrypto/essiv.c-247-\t\t\t\t essiv_aead_done, req);\ncrypto/essiv.c:248:\taead_request_set_crypt(subreq, src, req-\u003edst, req-\u003ecryptlen, req-\u003eiv);\ncrypto/essiv.c-249-\n--\ncrypto/gcm.c=470=static struct aead_request *crypto_rfc4106_crypt(struct aead_request *req)\n--\ncrypto/gcm.c-502-\t\t\t\t req-\u003ebase.data);\ncrypto/gcm.c:503:\taead_request_set_crypt(subreq, rctx-\u003esrc,\ncrypto/gcm.c-504-\t\t\t req-\u003esrc == req-\u003edst ? rctx-\u003esrc : rctx-\u003edst,\n--\ncrypto/gcm.c=676=static int crypto_rfc4543_crypt(struct aead_request *req, bool enc)\n--\ncrypto/gcm.c-698-\t\t\t\t req-\u003ebase.complete, req-\u003ebase.data);\ncrypto/gcm.c:699:\taead_request_set_crypt(subreq, req-\u003esrc, req-\u003edst,\ncrypto/gcm.c-700-\t\t\t enc ? 0 : authsize, iv);\n--\ncrypto/krb5/rfc3961_simplified.c=540=ssize_t krb5_aead_encrypt(const struct krb5_enctype *krb5,\n--\ncrypto/krb5/rfc3961_simplified.c-591-\taead_request_set_callback(req, 0, NULL, NULL);\ncrypto/krb5/rfc3961_simplified.c:592:\taead_request_set_crypt(req, sg, sg, secure_len, iv);\ncrypto/krb5/rfc3961_simplified.c-593-\tret = crypto_aead_encrypt(req);\n--\ncrypto/krb5/rfc3961_simplified.c=608=int krb5_aead_decrypt(const struct krb5_enctype *krb5,\n--\ncrypto/krb5/rfc3961_simplified.c-636-\taead_request_set_callback(req, 0, NULL, NULL);\ncrypto/krb5/rfc3961_simplified.c:637:\taead_request_set_crypt(req, sg, sg, *_len, iv);\ncrypto/krb5/rfc3961_simplified.c-638-\tret = crypto_aead_decrypt(req);\n--\ncrypto/krb5/rfc8009_aes2.c=172=static ssize_t rfc8009_encrypt(const struct krb5_enctype *krb5,\n--\ncrypto/krb5/rfc8009_aes2.c-231-\taead_request_set_ad(req, krb5_aead_ivsize(aead));\ncrypto/krb5/rfc8009_aes2.c:232:\taead_request_set_crypt(req, bsg, bsg, secure_len, iv);\ncrypto/krb5/rfc8009_aes2.c-233-\tret = crypto_aead_encrypt(req);\n--\ncrypto/krb5/rfc8009_aes2.c=251=static int rfc8009_decrypt(const struct krb5_enctype *krb5,\n--\ncrypto/krb5/rfc8009_aes2.c-287-\taead_request_set_ad(req, krb5_aead_ivsize(aead));\ncrypto/krb5/rfc8009_aes2.c:288:\taead_request_set_crypt(req, bsg, bsg, *_len, iv);\ncrypto/krb5/rfc8009_aes2.c-289-\tret = crypto_aead_decrypt(req);\n--\ncrypto/pcrypt.c=95=static int pcrypt_aead_encrypt(struct aead_request *req)\n--\ncrypto/pcrypt.c-115-\t\t\t\t pcrypt_aead_done, req);\ncrypto/pcrypt.c:116:\taead_request_set_crypt(creq, req-\u003esrc, req-\u003edst,\ncrypto/pcrypt.c-117-\t\t\t req-\u003ecryptlen, req-\u003eiv);\n--\ncrypto/pcrypt.c=148=static int pcrypt_aead_decrypt(struct aead_request *req)\n--\ncrypto/pcrypt.c-168-\t\t\t\t pcrypt_aead_done, req);\ncrypto/pcrypt.c:169:\taead_request_set_crypt(creq, req-\u003esrc, req-\u003edst,\ncrypto/pcrypt.c-170-\t\t\t req-\u003ecryptlen, req-\u003eiv);\n--\ncrypto/seqiv.c=47=static int seqiv_aead_encrypt(struct aead_request *req)\n--\ncrypto/seqiv.c-85-\taead_request_set_callback(subreq, req-\u003ebase.flags, compl, data);\ncrypto/seqiv.c:86:\taead_request_set_crypt(subreq, req-\u003edst, req-\u003edst,\ncrypto/seqiv.c-87-\t\t\t req-\u003ecryptlen - ivsize, info);\n--\ncrypto/seqiv.c=99=static int seqiv_aead_decrypt(struct aead_request *req)\n--\ncrypto/seqiv.c-116-\taead_request_set_callback(subreq, req-\u003ebase.flags, compl, data);\ncrypto/seqiv.c:117:\taead_request_set_crypt(subreq, req-\u003esrc, req-\u003edst,\ncrypto/seqiv.c-118-\t\t\t req-\u003ecryptlen - ivsize, req-\u003eiv);\n--\ncrypto/tcrypt.c=243=static void test_mb_aead_speed(const char *algo, int enc, int secs,\n--\ncrypto/tcrypt.c-392-\ncrypto/tcrypt.c:393:\t\t\t\t\taead_request_set_crypt(cur-\u003ereq,\ncrypto/tcrypt.c-394-\t\t\t\t\t\t\t cur-\u003esgout,\n--\ncrypto/tcrypt.c-406-\ncrypto/tcrypt.c:407:\t\t\t\taead_request_set_crypt(cur-\u003ereq, cur-\u003esg,\ncrypto/tcrypt.c-408-\t\t\t\t\t\t cur-\u003esgout, bs +\n--\ncrypto/tcrypt.c=518=static void test_aead_speed(const char *algo, int enc, unsigned int secs,\n--\ncrypto/tcrypt.c-650-\t\t\t\t */\ncrypto/tcrypt.c:651:\t\t\t\taead_request_set_crypt(req, sgout, sg,\ncrypto/tcrypt.c-652-\t\t\t\t\t\t bs, iv);\n--\ncrypto/tcrypt.c-662-\ncrypto/tcrypt.c:663:\t\t\taead_request_set_crypt(req, sg, sgout,\ncrypto/tcrypt.c-664-\t\t\t\t\t bs + (enc ? 0 : authsize),\n--\ncrypto/testmgr.c=2031=static int test_aead_vec_cfg(int enc, const struct aead_testvec *vec,\n--\ncrypto/testmgr.c-2115-\taead_request_set_callback(req, req_flags, crypto_req_done, \u0026wait);\ncrypto/testmgr.c:2116:\taead_request_set_crypt(req, tsgls-\u003esrc.sgl_ptr, tsgls-\u003edst.sgl_ptr,\ncrypto/testmgr.c-2117-\t\t\t enc ? vec-\u003eplen : vec-\u003eclen, iv);\n--\ncrypto/testmgr.c=2306=static void generate_aead_message(struct rnd_state *rng,\n--\ncrypto/testmgr.c-2344-\t\taead_request_set_callback(req, 0, crypto_req_done, \u0026wait);\ncrypto/testmgr.c:2345:\t\taead_request_set_crypt(req, src, \u0026dst, vec-\u003eplen, iv);\ncrypto/testmgr.c-2346-\t\taead_request_set_ad(req, vec-\u003ealen);\n"
} |
| 37/3 | 2026/09/19 12:43 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 32791 output: 28 thoughts: 23 Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience: **AEAD API Usage Deep Dive** Okay, so I need to refresh my memory on the recommended AEAD API usage within this kernel context. Let's see... the most direct route is usually through the official documentation. My initial thought is to dive into `Documentation/crypto/api-samples.rst` or something similarly named. That location, or a similar one, should provide concrete code examples and best practices. I'm expecting to find typical usage patterns there—key setup, encryption, decryption, authentication tag handling, and potential error checking. Hopefully, it's comprehensive enough to cover different AEAD algorithms and modes. It's also possible that there are more recent examples in the testing suite, so I'll keep that in mind as a potential secondary resource, or if the main samples are outdated. Time to dig in and see what's actually in there. |
| 38/3 | 2026/09/19 12:43 | tool | grepper |
0mArgs:{
"Expression": "crypto_aead_encrypt",
"PathPrefix": "Documentation/"
}Results: {
"Output": "Documentation/crypto/api-aead.rst=13=Authenticated Encryption With Associated Data (AEAD) Cipher API\n--\nDocumentation/crypto/api-aead.rst-16-.. kernel-doc:: include/crypto/aead.h\nDocumentation/crypto/api-aead.rst:17: :functions: crypto_alloc_aead crypto_free_aead crypto_aead_ivsize crypto_aead_authsize crypto_aead_blocksize crypto_aead_setkey crypto_aead_setauthsize crypto_a...\nDocumentation/crypto/api-aead.rst-18-\n--\nDocumentation/crypto/architecture.rst=320=the ASCII art above:\nDocumentation/crypto/architecture.rst-321-\nDocumentation/crypto/architecture.rst:322:1. esp_output() invokes crypto_aead_encrypt() to trigger an\nDocumentation/crypto/architecture.rst-323- encryption operation of the AEAD cipher with IV generator.\n"
} |
| 39/3 | 2026/09/19 12:43 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 33283 output: 36 thoughts: 25 Thoughts: Here's my take on the thought process, as requested: **Diving into `aead_request_set_crypt`** Alright, let's pull up `include/crypto/aead.h` and specifically zero in on the `aead_request_set_crypt` function. From a high-level perspective, this is where we're configuring the AEAD (Authenticated Encryption with Associated Data) request. It's the point where we're telling the crypto API exactly *what* we want to do – encryption or decryption – and the parameters surrounding that operation. I'm keen to see how the request struct is populated. I need to understand how the plaintext/ciphertext buffers, the associated data buffer, the key handle, and the authentication tag are linked together at this level. I'm especially interested in how the memory management is handled here; are we dealing with scatter-gather lists, direct memory access (DMA), or something else entirely? I also want to check for any potential gotchas with byte order or alignment. It's crucial to ensure that everything is setup according to the hardware or underlying crypto primitives. Time to start digging into the details... |
| 40/3 | 2026/09/19 12:43 | tool | grepper |
0mArgs:{
"Expression": "aead_request_set_crypt",
"PathPrefix": "include/crypto/aead.h"
}Results: {
"Output": "include/crypto/aead.h-69- * of the associated data buffer must contain a second copy of the IV. This is\ninclude/crypto/aead.h:70: * in addition to the copy passed to aead_request_set_crypt(). These two IV\ninclude/crypto/aead.h-71- * copies must not differ; different implementations of the same algorithm may\n--\ninclude/crypto/aead.h=565=static inline void aead_request_set_callback(struct aead_request *req,\n--\ninclude/crypto/aead.h-575-/**\ninclude/crypto/aead.h:576: * aead_request_set_crypt - set data buffers\ninclude/crypto/aead.h-577- * @req: request handle\n--\ninclude/crypto/aead.h-604- */\ninclude/crypto/aead.h:605:static inline void aead_request_set_crypt(struct aead_request *req,\ninclude/crypto/aead.h-606-\t\t\t\t\t struct scatterlist *src,\n"
} |
| 41/3 | 2026/09/19 12:43 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 33860 output: 36 thoughts: 25 Thoughts: Here's my summary, as if I were thinking these thoughts: **Analyzing `include/crypto/aead.h` – Lines 575-625** Okay, time to dive into that section of the `aead.h` header file. Let's see... I'm focusing on lines 575 to 625. Right off the bat, I'm expecting to see something related to the AEAD cipher structure and how it’s defined, specifically the interfaces it exposes. I'll need to understand how the AEAD is organized. Given the context, this chunk is probably dealing with the core data structures used for the Authenticated Encryption with Associated Data (AEAD) operations. I'm looking for structs, function prototypes, or possibly macros. My goal is to grasp how they’ve implemented the core API calls and how this particular segment fits into the bigger picture of the cryptographic library. I'm checking for details like the data structure layout (especially the `req` or `ctx` members) or maybe even some inline functions for efficiency. Knowing this structure and its functions helps in writing secure and optimised code for applications. |
| 42/3 | 2026/09/19 12:43 | tool | read-file |
0mArgs:{
"File": "include/crypto/aead.h",
"FirstLine": 575,
"LineCount": 50
}Results: {
"Contents": " 575:\t/**\n 576:\t * aead_request_set_crypt - set data buffers\n 577:\t * @req: request handle\n 578:\t * @src: source scatter / gather list\n 579:\t * @dst: destination scatter / gather list\n 580:\t * @cryptlen: number of bytes to process from @src\n 581:\t * @iv: IV for the cipher operation which must comply with the IV size defined\n 582:\t * by crypto_aead_ivsize()\n 583:\t *\n 584:\t * Setting the source data and destination data scatter / gather lists which\n 585:\t * hold the associated data concatenated with the plaintext or ciphertext. See\n 586:\t * below for the authentication tag.\n 587:\t *\n 588:\t * For encryption, the source is treated as the plaintext and the\n 589:\t * destination is the ciphertext. For a decryption operation, the use is\n 590:\t * reversed - the source is the ciphertext and the destination is the plaintext.\n 591:\t *\n 592:\t * The memory structure for cipher operation has the following structure:\n 593:\t *\n 594:\t * - AEAD encryption input: assoc data || plaintext\n 595:\t * - AEAD encryption output: assoc data || ciphertext || auth tag\n 596:\t * - AEAD decryption input: assoc data || ciphertext || auth tag\n 597:\t * - AEAD decryption output: assoc data || plaintext\n 598:\t *\n 599:\t * Albeit the kernel requires the presence of the AAD buffer, however,\n 600:\t * the kernel does not fill the AAD buffer in the output case. If the\n 601:\t * caller wants to have that data buffer filled, the caller must either\n 602:\t * use an in-place cipher operation (i.e. same memory location for\n 603:\t * input/output memory location).\n 604:\t */\n 605:\tstatic inline void aead_request_set_crypt(struct aead_request *req,\n 606:\t\t\t\t\t\t struct scatterlist *src,\n 607:\t\t\t\t\t\t struct scatterlist *dst,\n 608:\t\t\t\t\t\t unsigned int cryptlen, u8 *iv)\n 609:\t{\n 610:\t\treq-\u003esrc = src;\n 611:\t\treq-\u003edst = dst;\n 612:\t\treq-\u003ecryptlen = cryptlen;\n 613:\t\treq-\u003eiv = iv;\n 614:\t}\n 615:\t\n 616:\t/**\n 617:\t * aead_request_set_ad - set associated data information\n 618:\t * @req: request handle\n 619:\t * @assoclen: number of bytes in associated data\n 620:\t *\n 621:\t * Setting the AD information. This function sets the length of\n 622:\t * the associated data.\n 623:\t */\n 624:\tstatic inline void aead_request_set_ad(struct aead_request *req,\n"
} |
| 43/3 | 2026/09/19 12:43 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 34963 output: 34 thoughts: 1032 Thoughts: **Analyzing the AEAD Memory Structure and Implementation** Okay, let's break this down. First, I'm reminding myself of the basic memory layout for AEAD operations: we have associated data, plaintext, ciphertext, and an authentication tag. That seems straightforward enough. Now I'm jumping into the code, specifically `snapenc.c`. I need to figure out how they are implementing this in `snapshot_setup_encryption_common` and `snapshot_encrypt_refill`. Looking at `snapshot_setup_encryption_common`, I see they initialize the scatter gather list (`sg`) with `SNAPSHOT_CHUNK_SIZE + 2` entries. The associated data (`aead_request_set_ad`) is set to the offset, `data->crypt_total`. They also set the authentication tag size. Then, I'm in `snapshot_encrypt_refill`, which is where things get interesting. The first buffer in the SG list (`data->sg[0]`) is indeed the associated data, which is set to `&data->crypt_total`. The subsequent buffers are loaded with snapshot pages. This is a bit of a pattern I see often: the use of scatter-gather lists to manage memory in the kernel. I notice that the loop copies pages into a staging area. They use `memcpy` which might be a performance bottleneck, and they mention a possible future optimization to skip this copy for low-memory pages, which is something I need to keep in mind. Now I am at the crux of my concern. I see `sg_set_buf(&data->sg[1 + pg_idx], &data->auth_tag, SNAPSHOT_AUTH_TAG_SIZE);`. That `[1 + pg_idx]` is what's catching my eye. Given the SG list initialization with `SNAPSHOT_CHUNK_SIZE + 2`, `data->sg[0]` is the AAD, `data->sg[1..pg_idx]` are the plaintext pages, and now they are using `data->sg[1 + pg_idx]` to set the authentication tag, `&data->auth_tag`. But I am stopping here. I have to make sure the SG list is properly terminated. I need to know if `sg_set_buf` implicitly terminates the list, or if there is a separate call to `sg_mark_end`. This is a crucial detail I can't ignore. I need to understand exactly what `sg_set_buf` does. Does it set the end of the SG list? Or do I have to call another function to finalize the SG list? I need to check the definition of `sg_set_buf`. This is important, or the whole operation is at risk! |
| 44/3 | 2026/09/19 12:43 | tool | grepper |
0mError:no matches Args: {
"Expression": "def sg_set_buf",
"PathPrefix": "include/linux/scatterlist.h"
}Results: {
"error": "no matches"
} |
| 45/3 | 2026/09/19 12:43 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 36627 output: 33 thoughts: 23 Thoughts: Here's my take on those thoughts: **Investigating a Potential Memory Management Issue** Okay, so I'm thinking, I need to get to the bottom of something potentially related to how scatter-gather lists interact with buffers. My gut feeling is leading me towards some function related to setting up or manipulating buffers within the scatter-gather framework. Let's start with `sg_set_buf`. I'm going to quickly grep for that within the `include/linux/scatterlist.h` file. That header is the obvious starting point, it will probably contain the relevant declarations or macros. This should quickly give me a sense of what's going on with `sg_set_buf` and how it's used within the context of scatter-gather lists. From there, I can start to follow the calls and understand the full data flow. |
| 46/3 | 2026/09/19 12:43 | tool | grepper |
0mArgs:{
"Expression": "sg_set_buf",
"PathPrefix": "include/linux/scatterlist.h"
}Results: {
"Output": "include/linux/scatterlist.h=191=static inline struct page *sg_page(struct scatterlist *sg)\n--\ninclude/linux/scatterlist.h-199-/**\ninclude/linux/scatterlist.h:200: * sg_set_buf - Set sg entry to point at given data\ninclude/linux/scatterlist.h-201- * @sg:\t\t SG entry\n--\ninclude/linux/scatterlist.h-205- **/\ninclude/linux/scatterlist.h:206:static inline void sg_set_buf(struct scatterlist *sg, const void *buf,\ninclude/linux/scatterlist.h-207-\t\t\t unsigned int buflen)\n"
} |
| 47/3 | 2026/09/19 12:43 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 37043 output: 36 thoughts: 24 Thoughts: Here's my summary, as if I were the one thinking it: **Diving into Scatter/Gather List Structures** Okay, time to get into the nitty-gritty of scatter/gather lists within the Linux kernel. Let's zero in on lines 200-220 of `include/linux/scatterlist.h`. I'm expecting to find some crucial definitions and perhaps some explanations of how these structures are employed in memory management, DMA transfers, and generally anything needing the ability to represent non-contiguous memory regions. I'm keen to see if there are any new macro optimizations or structure enhancements since the last time I dug into this area. I'm especially interested in how the `sg_table` struct is defined, and what sort of context/comments it contains. Any clever tricks they are using to maintain cache coherency are always worth a look! |
| 48/3 | 2026/09/19 12:44 | tool | read-file |
0mArgs:{
"File": "include/linux/scatterlist.h",
"FirstLine": 200,
"LineCount": 20
}Results: {
"Contents": " 200:\t * sg_set_buf - Set sg entry to point at given data\n 201:\t * @sg:\t\t SG entry\n 202:\t * @buf:\t Data\n 203:\t * @buflen:\t Data length\n 204:\t *\n 205:\t **/\n 206:\tstatic inline void sg_set_buf(struct scatterlist *sg, const void *buf,\n 207:\t\t\t\t unsigned int buflen)\n 208:\t{\n 209:\t#ifdef CONFIG_DEBUG_SG\n 210:\t\tBUG_ON(!virt_addr_valid(buf));\n 211:\t#endif\n 212:\t\tsg_set_page(sg, virt_to_page(buf), buflen, offset_in_page(buf));\n 213:\t}\n 214:\t\n 215:\t/*\n 216:\t * Loop over each sg element, following the pointer to a new list if necessary\n 217:\t */\n 218:\t#define for_each_sg(sglist, sg, nr, __i)\t\\\n 219:\t\tfor (__i = 0, sg = (sglist); __i \u003c (nr); __i++, sg = sg_next(sg))\n"
} |
| 49/3 | 2026/09/19 12:44 | llm | kmsan-evaluator |
8mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 37627 output: 26 thoughts: 275 Thoughts: **My Encryption Workflow Deep Dive** Okay, so I'm really digging into this `sg_init_table` function and how it interacts with the scatter-gather lists. I just had a thought: if `pg_idx` is less than `SNAPSHOT_CHUNK_SIZE`, like, say, it's just `1`, that means the final scatter gather element, `sg[2]`, isn't being flagged as the end, right? But hold on, the `aead_request_set_crypt` function sets `cryptlen` to the *total* length. And the crypto walk *stops* at either `cryptlen + authsize` or just `cryptlen` bytes, right? Scatterwalk and `cryptlen` handle that, it seems. Wait a second, what *exactly* happens during encryption? Specifically, when we call `aead_request_set_crypt(req, data->sg, data->sg, total, nonce);`? I need to clarify that. Hang on. Back in `snapshot_setup_encryption_common`, we have `aead_request_set_ad(data->aead_req, sizeof(data->crypt_total));` which is just 8 bytes. And `cryptlen` is, as I said, set to the `total` length. This is critical. Alright, so for the AEAD encryption, the real question here is this: does the *destination* scatter-gather list need to contain: `associated data (8 bytes) || ciphertext (total bytes) || authentication tag (16 bytes)`? That's the crux of this. Okay, let's step back a bit and check how `scatterwalk` processes `req->dst` inside the `crypto_aead_encrypt` function. I think that might have my answer. Let me take a look at the `crypto/gcm.c` file as well. This is important to understand the details. |
| 50/3 | 2026/09/19 12:52 | tool | grepper |
0mArgs:{
"Expression": "gcm_encrypt",
"PathPrefix": "crypto/"
}Results: {
"Output": "crypto/aes.c=732=static void crypto_aes_gcm_auth_update(struct aes_gcm_ctx *ctx,\n--\ncrypto/aes.c-738-\ncrypto/aes.c:739:static void aes_gcm_encrypt_update_helper(u8 *dst, const u8 *src,\ncrypto/aes.c-740-\t\t\t\t\t unsigned int len,\n--\ncrypto/aes.c-742-{\ncrypto/aes.c:743:\taes_gcm_encrypt_update(ctx, dst, src, len);\ncrypto/aes.c-744-}\n--\ncrypto/aes.c=746=static void aes_gcm_decrypt_update_helper(u8 *dst, const u8 *src,\n--\ncrypto/aes.c-752-\ncrypto/aes.c:753:static int crypto_aes_gcm_encrypt_common(struct aead_request *req,\ncrypto/aes.c-754-\t\t\t\t\t const struct aes_gcm_key *key,\n--\ncrypto/aes.c-761-\tcrypto_aes_gcm_auth_update(\u0026ctx, req-\u003esrc, assoclen);\ncrypto/aes.c:762:\tAES_CRYPT_SG(aes_gcm_encrypt_update_helper, req-\u003edst, req-\u003esrc,\ncrypto/aes.c-763-\t\t req-\u003ecryptlen, req-\u003eassoclen, \u0026ctx);\ncrypto/aes.c:764:\taes_gcm_encrypt_final(\u0026ctx, authtag);\ncrypto/aes.c-765-\tmemcpy_to_sglist(req-\u003edst, req-\u003eassoclen + req-\u003ecryptlen, authtag,\n--\ncrypto/aes.c=771=static int crypto_aes_gcm_decrypt_common(struct aead_request *req,\n--\ncrypto/aes.c-794-\ncrypto/aes.c:795:static __maybe_unused int crypto_aes_gcm_encrypt(struct aead_request *req)\ncrypto/aes.c-796-{\n--\ncrypto/aes.c-799-\ncrypto/aes.c:800:\treturn crypto_aes_gcm_encrypt_common(req, key, req-\u003eiv, req-\u003eassoclen);\ncrypto/aes.c-801-}\n--\ncrypto/aes.c=845=static __maybe_unused int crypto_aes_rfc4106_encrypt(struct aead_request *req)\n--\ncrypto/aes.c-855-\ncrypto/aes.c:856:\treturn crypto_aes_gcm_encrypt_common(req, \u0026key-\u003egcm, iv,\ncrypto/aes.c-857-\t\t\t\t\t req-\u003eassoclen - 8);\n--\ncrypto/aes.c=982=static struct aead_alg aead_algs[] = {\n--\ncrypto/aes.c-992-\t\t.setauthsize = crypto_aes_gcm_setauthsize,\ncrypto/aes.c:993:\t\t.encrypt = crypto_aes_gcm_encrypt,\ncrypto/aes.c-994-\t\t.decrypt = crypto_aes_gcm_decrypt,\n--\ncrypto/gcm.c=215=static int gcm_add_auth_tag(struct aead_request *req)\n--\ncrypto/gcm.c-227-\ncrypto/gcm.c:228:static void gcm_encrypt_done(void *data, int err)\ncrypto/gcm.c-229-{\n--\ncrypto/gcm.c-240-\ncrypto/gcm.c:241:static int crypto_gcm_encrypt(struct aead_request *req)\ncrypto/gcm.c-242-{\n--\ncrypto/gcm.c-248-\tcrypto_gcm_init_crypt(req, req-\u003ecryptlen);\ncrypto/gcm.c:249:\tskcipher_request_set_callback(skreq, flags, gcm_encrypt_done, req);\ncrypto/gcm.c-250-\n--\ncrypto/gcm.c=333=static int crypto_gcm_create_common(struct crypto_template *tmpl,\n--\ncrypto/gcm.c-383-\tinst-\u003ealg.setauthsize = crypto_gcm_setauthsize;\ncrypto/gcm.c:384:\tinst-\u003ealg.encrypt = crypto_gcm_encrypt;\ncrypto/gcm.c-385-\tinst-\u003ealg.decrypt = crypto_gcm_decrypt;\n"
} |
| 51/3 | 2026/09/19 12:52 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 39468 output: 34 thoughts: 34 Thoughts: Here's my take on the process, considering my expertise: **Diving into `gcm_encrypt_done` / `gcm_add_auth_tag`** Okay, time to dissect these functions in `crypto/gcm.c`. I need to get a clear picture of how the authenticated encryption process is finalized, specifically looking at how the GCM mode is handled. `gcm_encrypt_done` and `gcm_add_auth_tag` are likely the critical pieces for understanding the authenticated encryption finalization within the larger GCM context. I'm assuming that `gcm_encrypt_done` handles housekeeping after the bulk encryption is complete, perhaps managing state and ensuring everything is properly flushed, while `gcm_add_auth_tag` actually computes and appends the authentication tag. Given my experience, I'll be focused on how efficiently this is done, looking for any potential optimizations or areas where side-channel vulnerabilities might be present. Specifically I'll be looking at things like if there are constant-time operations used in tag generation, or if there's any branching based on secret keys or internal state. |
| 52/3 | 2026/09/19 12:52 | tool | read-file |
0mArgs:{
"File": "crypto/gcm.c",
"FirstLine": 210,
"LineCount": 40
}Results: {
"Contents": " 210:\t\tghash_update(\u0026ghash, (const u8 *)lengths, sizeof(lengths));\n 211:\t\n 212:\t\tghash_final(\u0026ghash, out);\n 213:\t}\n 214:\t\n 215:\tstatic int gcm_add_auth_tag(struct aead_request *req)\n 216:\t{\n 217:\t\tstruct crypto_aead *aead = crypto_aead_reqtfm(req);\n 218:\t\tstruct crypto_gcm_req_priv_ctx *pctx = crypto_gcm_reqctx(req);\n 219:\t\n 220:\t\tgcm_hash(req, sg_next(req-\u003esrc == req-\u003edst ? pctx-\u003esrc : pctx-\u003edst),\n 221:\t\t\t req-\u003ecryptlen, pctx-\u003eiauth_tag);\n 222:\t\tcrypto_xor(pctx-\u003eauth_tag, pctx-\u003eiauth_tag, 16);\n 223:\t\tmemcpy_to_sglist(req-\u003edst, req-\u003eassoclen + req-\u003ecryptlen,\n 224:\t\t\t\t pctx-\u003eauth_tag, crypto_aead_authsize(aead));\n 225:\t\treturn 0;\n 226:\t}\n 227:\t\n 228:\tstatic void gcm_encrypt_done(void *data, int err)\n 229:\t{\n 230:\t\tstruct aead_request *req = data;\n 231:\t\n 232:\t\tif (err)\n 233:\t\t\tgoto out;\n 234:\t\n 235:\t\terr = gcm_add_auth_tag(req);\n 236:\t\n 237:\tout:\n 238:\t\taead_request_complete(req, err);\n 239:\t}\n 240:\t\n 241:\tstatic int crypto_gcm_encrypt(struct aead_request *req)\n 242:\t{\n 243:\t\tstruct crypto_gcm_req_priv_ctx *pctx = crypto_gcm_reqctx(req);\n 244:\t\tstruct skcipher_request *skreq = \u0026pctx-\u003eskreq;\n 245:\t\tu32 flags = aead_request_flags(req);\n 246:\t\n 247:\t\tcrypto_gcm_init_common(req);\n 248:\t\tcrypto_gcm_init_crypt(req, req-\u003ecryptlen);\n 249:\t\tskcipher_request_set_callback(skreq, flags, gcm_encrypt_done, req);\n"
} |
| 53/3 | 2026/09/19 12:52 | llm | kmsan-evaluator |
1mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 40454 output: 34 thoughts: 779 Thoughts: **Analyzing the Data Encryption and Read Flow** Okay, here's what I'm seeing. Line 223 is key: `memcpy_to_sglist` is writing the authentication tag to `req->dst` at an offset of `assoclen + cryptlen`. I need to trace where those values are coming from to confirm the expected write target. Looking at `snapshot_encrypt_refill`, I see the structure `data->sg` is built as follows: `data->sg[0]` has length `assoclen` (which is 8). Then, `data->sg[1]` up to `data->sg[pg_idx]` each contain a full `PAGE_SIZE` buffer, summing to `cryptlen`, then finally the authentication tag (16 bytes) at `data->sg[1 + pg_idx]`. So the target of the `memcpy` _is_ `data->auth_tag`, as expected. That's good. The authentication tag is being written into the `data->auth_tag` field. Now, let's follow that through in `snapshot_read_next_encrypted`. It seems to be reading the encrypted data and then the auth tag in sequence. Specifically, the offset calculation for the tag looks a bit fragile though. I see `tag_off = data->crypt_offset - data->crypt_size;` and I'm a bit concerned about what happens when this value reaches `SNAPSHOT_AUTH_TAG_SIZE`. It might lead to some off-by-one errors or some confusion about how much data is read/written. I need to confirm the read sequence. Specifically, in `snapshot_read_next_encrypted`, there's a check: `data->crypt_offset >= data->crypt_size + SNAPSHOT_AUTH_TAG_SIZE`. If it's true, the buffer is refilled. But what if `snapshot_encrypt_refill` returns 0? It would set `data->crypt_size` to 0. Then the subsequent check `if (!data->crypt_size) return 0;` will cause the function to return EOF! It's a valid way to exit, but this is the critical section to look out for. I'm now curious about where these pages are coming from that are read via `snapshot_read_next`. I'll have to investigate that flow next by looking in `kernel/power/snapshot.c` to see the complete lifecycle of how this is handled. |
| 54/3 | 2026/09/19 12:53 | tool | grepper |
0mArgs:{
"Expression": "int snapshot_read_next\\(",
"PathPrefix": "kernel/power/snapshot.c"
}Results: {
"Output": "kernel/power/snapshot.c=2210=static inline void pack_pfns(unsigned long *buf, struct memory_bitmap *bm,\n--\nkernel/power/snapshot.c-2239- */\nkernel/power/snapshot.c:2240:int snapshot_read_next(struct snapshot_handle *handle)\nkernel/power/snapshot.c-2241-{\n"
} |
| 55/3 | 2026/09/19 12:53 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 41909 output: 36 thoughts: 21 Thoughts: Here's a summary of my thought process, as if I were the one thinking it: **Diving into the Snapshot Read** Alright, time to dig into the `snapshot_read_next` function within `kernel/power/snapshot.c`. I need to understand how the system's handling of snapshot reads works, and this function seems like the logical entry point for that. I'm going to start by tracing its execution flow and seeing what data structures it interacts with. I'll be looking for how it determines the next piece of data to read from the snapshot image, any error handling it implements, and how it interacts with the underlying storage mechanisms. I'll keep an eye out for any potential concurrency issues or optimizations that are in place. This is where the magic happens, so I'll need to pay close attention to the details. |
| 56/3 | 2026/09/19 12:53 | tool | read-file |
0mArgs:{
"File": "kernel/power/snapshot.c",
"FirstLine": 2240,
"LineCount": 60
}Results: {
"Contents": "2240:\tint snapshot_read_next(struct snapshot_handle *handle)\n2241:\t{\n2242:\t\tif (handle-\u003ecur \u003e nr_meta_pages + nr_copy_pages)\n2243:\t\t\treturn 0;\n2244:\t\n2245:\t\tif (!buffer) {\n2246:\t\t\t/* This makes the buffer be freed by swsusp_free() */\n2247:\t\t\tbuffer = get_image_page(GFP_ATOMIC, PG_ANY);\n2248:\t\t\tif (!buffer)\n2249:\t\t\t\treturn -ENOMEM;\n2250:\t\t}\n2251:\t\tif (!handle-\u003ecur) {\n2252:\t\t\tint error;\n2253:\t\n2254:\t\t\terror = init_header((struct swsusp_info *)buffer);\n2255:\t\t\tif (error)\n2256:\t\t\t\treturn error;\n2257:\t\t\thandle-\u003ebuffer = buffer;\n2258:\t\t\tmemory_bm_position_reset(\u0026orig_bm);\n2259:\t\t\tmemory_bm_position_reset(\u0026copy_bm);\n2260:\t\t} else if (handle-\u003ecur \u003c= nr_meta_pages) {\n2261:\t\t\tclear_page(buffer);\n2262:\t\t\tpack_pfns(buffer, \u0026orig_bm, \u0026zero_bm);\n2263:\t\t} else {\n2264:\t\t\tstruct page *page;\n2265:\t\n2266:\t\t\tpage = pfn_to_page(memory_bm_next_pfn(\u0026copy_bm));\n2267:\t\t\tif (PageHighMem(page)) {\n2268:\t\t\t\t/*\n2269:\t\t\t\t * Highmem pages are copied to the buffer,\n2270:\t\t\t\t * because we can't return with a kmapped\n2271:\t\t\t\t * highmem page (we may not be called again).\n2272:\t\t\t\t */\n2273:\t\t\t\tvoid *kaddr;\n2274:\t\n2275:\t\t\t\tkaddr = kmap_local_page(page);\n2276:\t\t\t\tcopy_page(buffer, kaddr);\n2277:\t\t\t\tkunmap_local(kaddr);\n2278:\t\t\t\thandle-\u003ebuffer = buffer;\n2279:\t\t\t} else {\n2280:\t\t\t\thandle-\u003ebuffer = page_address(page);\n2281:\t\t\t}\n2282:\t\t}\n2283:\t\thandle-\u003ecur++;\n2284:\t\treturn PAGE_SIZE;\n2285:\t}\n2286:\t\n2287:\tstatic void duplicate_memory_bitmap(struct memory_bitmap *dst,\n2288:\t\t\t\t\t struct memory_bitmap *src)\n2289:\t{\n2290:\t\tunsigned long pfn;\n2291:\t\n2292:\t\tmemory_bm_position_reset(src);\n2293:\t\tpfn = memory_bm_next_pfn(src);\n2294:\t\twhile (pfn != BM_END_OF_MAP) {\n2295:\t\t\tmemory_bm_set_bit(dst, pfn);\n2296:\t\t\tpfn = memory_bm_next_pfn(src);\n2297:\t\t}\n2298:\t}\n2299:\t\n"
} |
| 57/3 | 2026/09/19 12:53 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 42995 output: 27 thoughts: 5449 Thoughts: **Deep Dive into Encrypted Hibernation Code** Okay, I've thoroughly examined this encrypted hibernation code. Here's what I've discovered, breaking down my thought process step-by-step: 1. **Memory Allocation and Initialization:** I started by verifying how `__get_free_page(GFP_KERNEL)` is used. The key question was whether it zeroes the allocated page. It doesn't, which is crucial. I checked the initialization of `data->crypt_pages`. They are allocated, and this is followed immediately by a `memcpy` operation. So the allocated pages are filled before they're used. 2. **Encryption and Buffer Management:** I then focused on the encryption process, especially how the code handles `snapshot_read_next`, the staging buffer `data->crypt_pages` , and the Scatter-Gather list. The `memcpy` within the `snapshot_encrypt_refill` function is the core; every page read by `snapshot_read_next` is copied into `data->crypt_pages`. The code correctly sets the `sg` list to point to these buffers, and `total` (which tracks the number of pages in `data->crypt_pages`) is used to control how much is encrypted using `aead_request_set_crypt`. I confirmed that the `crypt_pages` pages not part of the current encryption process are never read. 3. **Decryption and Write Operations:** Next, I went through the reverse operation during resume. `snapshot_write_next_encrypted` determines where the userspace is writing to. I traced the execution flow if the user writes metadata into the initial portion of `data->crypt_pages` and then an attempt to write the auth tag. Crucially, I found that even when metadata is written, the correct `crypt_pages` buffer is correctly addressed. This means it isn't overwriting unrelated memory. 4. **Decryption Drain:** I investigated `snapshot_decrypt_drain`, focusing on the scenario when only a part of the buffer (metadata + tag) is written. The code intelligently handles a short decryption at the end of the metadata, where the auth tag is written to a page, then copied into the correct `auth_tag` location. This is crucial for handling situations where the written data doesn't align perfectly with page boundaries. The code will copy the auth tag if there is a short write (fewer than SNAPSHOT_CHUNK_SIZE pages). Decryption is correctly performed on the contents of the `data->crypt_pages` and copied to the `data_of(data->handle)` buffer. 5. **Finalization:** I considered `snapshot_finalize_decrypted_image`. This function ensures that the decrypted image is finalized, and any remaining data is decrypted. 6. **Hibernation Swap:** I examined how the swap device's range is checked via `swapdev_block_to_extent` and subsequent functions, ensuring that we're dealing with valid swap extents. I traced the control flow within `kernel/power/swap.c` and validated the use of `swsusp_extents_contain_range`, which determines if the hibernation swap range has valid extents. 7. **Block Device Operations:** I took a look at `block/fops.c`. I confirmed that when dealing with a block device for hibernation, if the operation is active, there are checks to verify that the block device isn't read-only, and if it is, that will lead to a failure. `hibernate_len` and `hibernate_written` are used but seem to be initialized safely. 8. **Encryption Seed:** Lastly, I looked into the `snapshot_seed_store` function and how it handled the encryption key. This function correctly uses `hex2bin` to convert the hex string to binary for the seed. The code performs a check that the seed is of the correct length. It locks the seed using a mutex, and compares old seeds. Finally, `memzero_explicit` is used to clear any sensitive data. **Conclusion:** Based on my analysis, I am confident that the code is well-structured and performs memory operations and checks on the integrity of the data. I don't see any obvious issues related to reading uninitialized memory, writing to invalid addresses, or security vulnerabilities in any of the code snippets I've examined. I do see a sophisticated approach to buffer management and decryption. |
| 58/3 | 2026/09/19 12:54 | tool | grepper |
0mArgs:{
"Expression": "int hex2bin\\(",
"PathPrefix": "lib/"
}Results: {
"Output": "lib/hexdump.c=54=EXPORT_SYMBOL(hex_to_bin);\n--\nlib/hexdump.c-63- */\nlib/hexdump.c:64:int hex2bin(u8 *dst, const char *src, size_t count)\nlib/hexdump.c-65-{\n"
} |
| 59/3 | 2026/09/19 12:54 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 49507 output: 34 thoughts: 19 Thoughts: Here's my summary, as though I'm thinking through this process: **Diving into the Hexdump Implementation** Okay, time to get my hands dirty. I need to take a look at the `lib/hexdump.c` file. Given my understanding of the codebase and debugging needs, line 64 feels like a good starting point. I suspect there's a specific calculation or data manipulation happening around there that's relevant to the issue I'm tackling. Let's see what's coded in that neighborhood and what the surrounding logic is. I'll focus on the data structures, function calls, and any potential off-by-one errors or boundary condition issues in that particular area. It’s likely a critical piece of the puzzle. |
| 60/3 | 2026/09/19 12:54 | tool | read-file |
0mArgs:{
"File": "lib/hexdump.c",
"FirstLine": 60,
"LineCount": 25
}Results: {
"Contents": " 60:\t * @count: result length\n 61:\t *\n 62:\t * Return 0 on success, -EINVAL in case of bad input.\n 63:\t */\n 64:\tint hex2bin(u8 *dst, const char *src, size_t count)\n 65:\t{\n 66:\t\twhile (count--) {\n 67:\t\t\tint hi, lo;\n 68:\t\n 69:\t\t\thi = hex_to_bin(*src++);\n 70:\t\t\tif (unlikely(hi \u003c 0))\n 71:\t\t\t\treturn -EINVAL;\n 72:\t\t\tlo = hex_to_bin(*src++);\n 73:\t\t\tif (unlikely(lo \u003c 0))\n 74:\t\t\t\treturn -EINVAL;\n 75:\t\n 76:\t\t\t*dst++ = (hi \u003c\u003c 4) | lo;\n 77:\t\t}\n 78:\t\treturn 0;\n 79:\t}\n 80:\tEXPORT_SYMBOL(hex2bin);\n 81:\t\n 82:\t/**\n 83:\t * bin2hex - convert binary data to an ascii hexadecimal string\n 84:\t * @dst: ascii hexadecimal result\n"
} |
| 61/3 | 2026/09/19 12:54 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 50038 output: 34 thoughts: 1351 Thoughts: **Encryption Key Handling Analysis** Okay, let's break this down systematically. My initial observation is focused on how the encryption seed is handled. The `hex2bin` function's return value of `-EINVAL` indicates an invalid input, while a zero return fills `seed` bytes. If `snapshot_store_encryption_seed` returns a non-zero value, it immediately returns the error code; otherwise, the `seed` is initialized and `memzero_explicit` is called. So far, so good – we're controlling the initialization and clearing. Now, that brings up `snapshot_copy_encryption_seed`. A quick look reveals that it simply copies the seed if `snapshot_seed_valid` is true, after acquiring a mutex lock. If it returns `false`, `snapshot_derive_wrapping_key` returns `-ENOKEY`, which is expected. If it returns `true`, then `seed` is fully copied. This seems correct. Moving on, `snapshot_get_encryption_key` appears to generate and wrap an image encryption key. It first checks if the snapshot is "ready," and if so, it returns `-EPIPE`. Then, it calls `snapshot_setup_encryption_common`, which I'll assume sets up some common encryption context, and derives a nonce. Interestingly, it derives a random image key using `get_random_bytes`. The key is wrapped using `snapshot_wrap_image_key`, and the wrapped key and nonce are passed back to user space. After copying the wrapped key and the nonce to the user, `memzero_explicit` is used to clear both the image key and the wrapped key. This is the desired behavior for security. I'm now curious about the data structure: `struct uswsusp_key_blob`. It appears to hold the length of the blob, a 512-byte blob, and a nonce, which is a good design to encapsulate the key data. Let’s check the interaction from userspace, specifically through `ioctl(fd, SNAPSHOT_ENABLE_ENCRYPTION, arg)`. The `snapshot_ioctl` function handles the `SNAPSHOT_ENABLE_ENCRYPTION` ioctl. If the data mode is `O_RDONLY`, it calls `snapshot_get_encryption_key`; otherwise, it calls `snapshot_set_encryption_key`. Since `SNAPSHOT_ENABLE_ENCRYPTION` is defined with `_IOWR`, this indicates a read-write ioctl. The critical question: Is the `struct uswsusp_key_blob` copied by the generic ioctl dispatcher, or is the copy handled inside `snapshot_ioctl`? To answer this, let’s quickly look at how other ioctls are handled. For example, `SNAPSHOT_AVAIL_SWAP_SIZE` directly uses `put_user`, while `SNAPSHOT_ALLOC_SWAP_PAGE` also returns data with `put_user`. `SNAPSHOT_SET_SWAP_AREA` takes a `void __user *` argument. Now, looking at `snapshot_set_swap_area` suggests that user-space data is being handled. This suggests that the kernel likely calls this ioctl and then hands the data to a function. This implies that the kernel *does* copy the key blob in `snapshot_ioctl` using the usual ioctl mechanisms and that the function then *works* with the blob in memory in kernel space, thus avoiding an additional `copy_from_user` call. This is as I'd expect. The use of a structure also is good. In summary, the encryption key flow seems well-designed, with explicit zeroing of sensitive data and clear separation of concerns, and it is likely that the encryption key is handled correctly. |
| 62/3 | 2026/09/19 12:54 | tool | grepper |
0mArgs:{
"Expression": "snapshot_set_swap_area",
"PathPrefix": "kernel/power/user.c"
}Results: {
"Output": "kernel/power/user.c=385=struct compat_resume_swap_area {\n--\nkernel/power/user.c-389-\nkernel/power/user.c:390:static int snapshot_set_swap_area(struct snapshot_data *data,\nkernel/power/user.c-391-\t\tvoid __user *argp)\n--\nkernel/power/user.c=435=static long snapshot_ioctl(struct file *filp, unsigned int cmd,\n--\nkernel/power/user.c-643-\tcase SNAPSHOT_SET_SWAP_AREA:\nkernel/power/user.c:644:\t\terror = snapshot_set_swap_area(data, (void __user *)arg);\nkernel/power/user.c-645-\t\tbreak;\n"
} |
| 63/3 | 2026/09/19 12:54 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 52429 output: 35 thoughts: 24 Thoughts: Okay, here's my interpretation of what's going through my mind as I approach this code, rendered in the first person: **Diving into `kernel/power/user.c`** Alright, time to dig in. I need to understand what's happening within lines 385 to 430 of `kernel/power/user.c`. Given the file name and the context, I'm expecting this section to deal with power management functionalities, likely related to user-space interactions. This could be anything from handling user requests for suspend/resume, managing power-related sysfs attributes, or coordinating power-related events initiated by user-space applications. I need to quickly grasp the logical flow here. I'll be looking for key function calls, conditional statements, and any data structures involved. Specifically, I'll be watching out for any interactions with the `pm_notifier_block` infrastructure, since this is in the `power` subsystem. Are there calls to functions like `pm_suspend`, `pm_resume`, `pm_register_notifier`, or anything similar? Any state variables being modified? Are there any obvious race conditions that might be exposed? I'll be paying close attention to any error handling. Kernel code, especially around power management, demands robust error checking to avoid unexpected system behavior or, worse, hard crashes. I'm expecting to see checks for return values of various functions and how those errors are propagated or handled. The interplay between various power states and the interaction with user-space is always a place for potential issues. Let's see what we've got. |
| 64/3 | 2026/09/19 12:54 | tool | read-file |
0mArgs:{
"File": "kernel/power/user.c",
"FirstLine": 385,
"LineCount": 45
}Results: {
"Contents": " 385:\tstruct compat_resume_swap_area {\n 386:\t\tcompat_loff_t offset;\n 387:\t\tu32 dev;\n 388:\t} __packed;\n 389:\t\n 390:\tstatic int snapshot_set_swap_area(struct snapshot_data *data,\n 391:\t\t\tvoid __user *argp)\n 392:\t{\n 393:\t\tsector_t offset;\n 394:\t\tdev_t swdev;\n 395:\t\n 396:\t\tif (swsusp_swap_in_use())\n 397:\t\t\treturn -EPERM;\n 398:\t\n 399:\t\tif (in_compat_syscall()) {\n 400:\t\t\tstruct compat_resume_swap_area swap_area;\n 401:\t\n 402:\t\t\tif (copy_from_user(\u0026swap_area, argp, sizeof(swap_area)))\n 403:\t\t\t\treturn -EFAULT;\n 404:\t\t\tswdev = new_decode_dev(swap_area.dev);\n 405:\t\t\toffset = swap_area.offset;\n 406:\t\t} else {\n 407:\t\t\tstruct resume_swap_area swap_area;\n 408:\t\n 409:\t\t\tif (copy_from_user(\u0026swap_area, argp, sizeof(swap_area)))\n 410:\t\t\t\treturn -EFAULT;\n 411:\t\t\tswdev = new_decode_dev(swap_area.dev);\n 412:\t\t\toffset = swap_area.offset;\n 413:\t\t}\n 414:\t\n 415:\t\t/*\n 416:\t\t * Unpin the swap device if a swap area was already\n 417:\t\t * set by SNAPSHOT_SET_SWAP_AREA.\n 418:\t\t */\n 419:\t\tunpin_hibernation_swap_type(data-\u003eswap);\n 420:\t\n 421:\t\t/*\n 422:\t\t * User space encodes device types as two-byte values,\n 423:\t\t * so we need to recode them\n 424:\t\t */\n 425:\t\tdata-\u003eswap = pin_hibernation_swap_type(swdev, offset);\n 426:\t\tif (data-\u003eswap \u003c 0)\n 427:\t\t\treturn swdev ? -ENODEV : -EINVAL;\n 428:\t\tdata-\u003edev = swdev;\n 429:\t#if defined(CONFIG_ENCRYPTED_HIBERNATION)\n"
} |
| 65/3 | 2026/09/19 12:54 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 53491 output: 29 thoughts: 6521 Thoughts: **Deep Dive into Snapshot Encryption** Okay, here's the breakdown of my thought process while dissecting this snapshot encryption code. I'm starting from the basics, considering how it interacts with user space, and then working my way through the key exchange and data handling. First, I observe that character and miscellaneous devices typically utilize `unlocked_ioctl`. The kernel doesn't automatically copy data in or out in these cases, unlike sockets. However, `snapshot_ioctl` explicitly uses `copy_from_user`, `copy_to_user`, and `put_user`. I need to remember this distinction and look out for user-space interaction. I also quickly looked at the `snapshot_compat_ioctl` function, noting that it seemed to support legacy ABI interfaces for compatibility. I then went through several structs used in the snapshot code, namely `uswsusp_key_blob`, `uswsusp_user_key` and `snapshot_wrapped_key`, checking their layouts for potential issues on 32-bit and 64-bit architectures, especially around pointers and sizes. I confirmed that these structures are packed, meaning there's no padding, and that sizes of individual fields in the structs were consistent between architectures. However, the contents of these structs are handled in copy_from_user/copy_to_user, which is important to consider. Moving on to `snapshot_set_encryption_key`, I observed that it takes a `struct uswsusp_key_blob` from user space via `memdup_user`. I notice that there's a size check to ensure the blob length matches the expected size of `struct snapshot_wrapped_key`. Inside `snapshot_set_encryption_key` this user space blob is used to construct a `struct snapshot_wrapped_key`. The `snapshot_wrapped_key` is then used to encrypt the image key. Importantly, the encryption and decryption are performed using AEAD (Authenticated Encryption with Associated Data). I'm carefully tracking the use of `buf` here, which holds the encrypted key and the authentication tag. AEAD performs in-place encryption, encrypting the key, and also writing an authentication tag to `buf`. Then the contents of `buf` are copied to the `wrapped` structure in user space for transfer. After that, these buffers are zeroed to prevent key leakage. I also made sure to confirm that the integrity of the key is protected by the `snapshot_unwrap_image_key`, which ensures the wrapped key data is valid before using it. I am also aware that the kernel will read from these pointers in future operations, so I must take extra care to note where it makes the copies. Next, `snapshot_set_user_key` is where things get interesting. It takes a `struct uswsusp_user_key` from user space, and the data is copied with `copy_from_user`. I paid attention to the length and size checks involved in the copy to prevent buffer overflows. There is a size check that ensures the key fits within `data->user_key` (32 bytes). It checks `user_key.key_len` against `sizeof(data->user_key)` to prevent overflows. After the data is validated, the user key is copied to `data->user_key`, then used by `snapshot_use_user_key`, where it's mixed with the kernel key to generate a combined key for encryption. It is key to understand that `data->user_key` is fully initialized with zeroed data prior to `memcpy`, meaning there's no uninitialized memory. Also, the combined key generation via SHA256 ensures that the user doesn't have predictable control over the key bits. The key thing is that `snapshot_state` is a statically allocated variable, zero-initialized at boot, so its contents are well-defined on the first open. `snapshot_open` assigns the data pointer from a static struct, and the private data of `filp` is also set. However, a `snapshot_release` or subsequent `snapshot_open` call could potentially reset the data structures. This is particularly important for the encryption state. `snapshot_teardown_encryption` performs a clean teardown, which zeroing key data and resetting encryption state. That is called by `snapshot_release`. I also considered `snapshot_setup_encryption_common` which also resets the encryption state to ensure a clean state before encryption, and I confirmed that there's no potential leakage across open/close operations. Finally, I analyzed the read path with `snapshot_read_encrypted`, the `snapshot_read_next_encrypted` to understand how the encrypted data is read and the authentication tag is handled. The code refills a buffer with encrypted pages. It reads both the data and the auth tags. It uses a `data-> |
| 66/3 | 2026/09/19 12:54 | tool | grepper |
0mArgs:{
"Expression": "#define data_of",
"PathPrefix": "kernel/power/"
}Results: {
"Output": "kernel/power/power.h=142=struct snapshot_handle {\n--\nkernel/power/power.h-158- */\nkernel/power/power.h:159:#define data_of(handle)\t((handle).buffer)\nkernel/power/power.h-160-\n"
} |
| 67/3 | 2026/09/19 12:54 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 61151 output: 30 thoughts: 9549 Thoughts: **KMSAN Analysis of Encrypted Hibernation Patch**
As an expert, my primary concern is introducing or exposing uninitialized memory risks. Let's break this down meticulously:
1. **Data Sent to Userspace:** The initial focus is on kernel structures transferred via `copy_to_user`, `put_user`, etc.
* `snapshot_get_encryption_key`: This function is the main candidate for memory leaks. It involves a `struct snapshot_wrapped_key` and a nonce. Critical check: *Is the entire structure initialized?* `wrapped = {}` zero-initializes the struct and `memset` ensures it. Subsequent operations like `get_random_bytes` (for nonce), `memcpy` and `cpu_to_le32` completely populate the structure. `put_user` and `copy_to_user` transfer only specified initialized bytes. Specifically, only the valid bytes of `key->blob` are filled. There's no info leak. The user key structure `struct uswsusp_key_blob` is sent to userspace, but we are only using the parts of the struct that were initialized in kernel space.
* `snapshot_set_user_key`: This only writes `meta_size` to user space.
* `snapshot_read_encrypted`: Data read to userspace is from encrypted buffers (`crypt_pages`, `auth_tag`) that are *completely* filled before use. These buffers have fully initialized and are transferred in a secure method.
* `snapshot_ioctl`: Simple `put_user` calls to return calculated values and offsets.
* Sysfs attribute: The sysfs `snapshot_seed` is write-only, eliminating read-related risks.
2. **Conditional Logic & Uninitialized Variables:** The next step is a deep dive into conditional logic. I need to guarantee that every variable used in any branch is initialized. This includes:
* `blkdev_write_iter`: `hibernate_active`, `hibernate_len`, and `hibernate_write` are all initialized *before* conditional branches. The mutex locking logic is correct.
* `swsusp_swap_range_allocated`: Pointers passed to `swapdev_block_to_extent` and `swapdev_block_to_extent` is called. `swap_offset`, `mapped_pages`, and `nr_pages` are fully initialized.
* `snapshot_store_encryption_seed`: Checks involve `hex2bin` and `seed` variables. `hex2bin` fully initializes the seed.
* `snapshot_derive_wrapping_key`: Ensures the seed is fully initialized.
* `snapshot_get_encryption_key`: Completely initialized values are always used.
* `snapshot_set_encryption_key`: Fully initialized values are used.
* `snapshot_set_user_key`: Completely initialized values are used.
3. **Complex Data Structures:** Static or dynamically allocated complex structures are checked for uninitialized fields.
* `struct snapshot_data snapshot_state`: This struct is statically allocated (BSS). The struct is carefully initialized via `memset` and individual field initialization.
4. **Buffer Access & Lengths:** Carefully check any bounds checks and memory operations for potential issues.
* `data->crypt_pages`: This is the most crucial part. The contents of this is only ever read after `memcpy` is performed. The pages are read in a secure method. All `data->crypt_pages` are initialized by the encrypt/decrypt workflow.
* `snapshot_finalize_decrypted_image`: Incomplete chunks are handled by returning an error, never allowing partial data to be processed.
In conclusion, this patch is safe from a KMSAN perspective. Careful initialization of memory and correct usage of kernel structures ensures that it does not introduce any uninitialized memory risks. All of the KMSAN criteria are carefully addressed.
|
| 68/3 | 2026/09/19 12:55 | tool | grepper |
0mArgs:{
"Expression": "SNAPSHOT_IOC_MAXNR",
"PathPrefix": "kernel/power/"
}Results: {
"Output": "kernel/power/user.c=435=static long snapshot_ioctl(struct file *filp, unsigned int cmd,\n--\nkernel/power/user.c-449-\t\treturn -ENOTTY;\nkernel/power/user.c:450:\tif (_IOC_NR(cmd) \u003e SNAPSHOT_IOC_MAXNR)\nkernel/power/user.c-451-\t\treturn -ENOTTY;\n"
} |
| 69/3 | 2026/09/19 12:55 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 71698 output: 35 thoughts: 16 Thoughts: Here's a summary of my thought process, as requested: **Diving into `snapshot_ioctl` - Line 450 and Beyond** Okay, let's get down to brass tacks. Based on the context, I need to focus on how `snapshot_ioctl` is implemented, specifically around line 450. I'm immediately thinking, "What could be going on there?" Is this where a critical decision is made? Is this where we branch based on input parameters? Are there potential race conditions in this section? What kind of data is being handled at that point? Is there a memory allocation/deallocation in this area? This line number will serve as my initial reference point, a place to anchor my investigation. I'll need to consider how the code flows around this line as well. I'm going to want to understand its dependencies, understand the surrounding logic, and then evaluate potential vulnerabilities, performance bottlenecks, or unexpected behavior. Time to delve into the code! |
| 70/3 | 2026/09/19 12:55 | tool | read-file |
0mArgs:{
"File": "kernel/power/user.c",
"FirstLine": 440,
"LineCount": 25
}Results: {
"Contents": " 440:\t\tloff_t size;\n 441:\t\tsector_t offset;\n 442:\t\n 443:\t\tif (need_wait) {\n 444:\t\t\twait_for_device_probe();\n 445:\t\t\tneed_wait = false;\n 446:\t\t}\n 447:\t\n 448:\t\tif (_IOC_TYPE(cmd) != SNAPSHOT_IOC_MAGIC)\n 449:\t\t\treturn -ENOTTY;\n 450:\t\tif (_IOC_NR(cmd) \u003e SNAPSHOT_IOC_MAXNR)\n 451:\t\t\treturn -ENOTTY;\n 452:\t\tif (!capable(CAP_SYS_ADMIN))\n 453:\t\t\treturn -EPERM;\n 454:\t\n 455:\t\tif (!mutex_trylock(\u0026system_transition_mutex))\n 456:\t\t\treturn -EBUSY;\n 457:\t\n 458:\t\tlock_device_hotplug();\n 459:\t\tdata = filp-\u003eprivate_data;\n 460:\t\n 461:\t\tswitch (cmd) {\n 462:\t\n 463:\t\tcase SNAPSHOT_FREEZE:\n 464:\t\t\tif (data-\u003efrozen)\n"
} |
| 71/3 | 2026/09/19 12:55 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 72291 output: 642 thoughts: 4328 Thoughts: **Analysis of Hibernation Encryption Code and KMSAN Applicability**
Okay, so I've been diving deep into this hibernation encryption code, specifically focusing on potential vulnerabilities related to uninitialized memory access and information leaks. The main areas of concern are the interactions with user space, particularly through the ioctls, sysfs, and swap write paths, alongside encryption key management. Let's break it down methodically.
First, I examined the `SNAPSHOT_ENABLE_ENCRYPTION` and `SNAPSHOT_SET_USER_KEY` ioctls. These are the primary entry points for setting encryption keys and providing the encryption seed/user key. The code copies data to and from user space via `copy_to_user` and `copy_from_user` and the concern is about leaving something uninitialized. In the `get` key operation, the `wrapped` key is copied out, but it’s created with `{}` and `memset` and is `__packed` so there's no way padding can be a concern. The `nonce` is initialized with `get_random_bytes`. This is great. All the `copy_from_user` ops read the provided key from userspace. The blob is fine, completely initialized. It's a key! It also copies meta_size via `put_user`. So good!
I checked for uninitialized reads in encryption-related functions like `snapshot_setup_encryption_common`, `snapshot_unwrap_image_key`, and `snapshot_store_encryption_seed`. `snapshot_setup_encryption_common` allocates crypto transforms and buffers, but cleans up on failure, preventing any uninitialized data from being used. `snapshot_unwrap_image_key` handles the wrapped key, but properly zero-initializes the temporary buffer before manipulation. `snapshot_store_encryption_seed` validates and copies the seed, zeroing it out afterwards. The encryption seed process seems solid, with mutex protection and careful memory handling.
Next, I looked at data flow in reading/writing the encrypted snapshot image with `snapshot_read_next_encrypted` and `snapshot_write_next_encrypted`. The read function pulls from either pre-filled crypt pages or the authentication tag, and the tag logic is always safe because all writes update `auth_tag`. Write follows a similar pattern, managing offsets and sizes carefully. The write and drain process is correct, tracking `crypt_offset` and `crypt_stream_total` with `crypt_meta_size` ensures that user input cannot overflow. The key change occurs before we write user data. I followed the flow and it appears that `crypt_offset` is always properly reset after a drain, preventing reads from uninitialized regions. I verified the condition where `tag_off` can get a value and that's okay, and there is no uninitialized buffer.
Finally, I checked `bdev_write_iter`. It's fine as well. No issues there.
Now, considering KMSAN, it looks like potential risks are around locking, out-of-bounds array access, null dereferences, or use-after-free bugs. KASAN and standard kernel debug tools can handle those scenarios. KMSAN is typically necessary when there are risks of uninitialized memory use or information leaks. Since all kernel buffers are either zero-initialized or populated before usage, no uninitialized data leaks to user space, and the flow is super clean. This patch doesn't introduce any new risks that would necessitate KMSAN.
Therefore, `NeedsKMSAN=false`! This seems like a reasonable conclusion after a pretty thorough review. I'm feeling confident about this. I'm ready to mark the results.
|
| 72/3 | 2026/09/19 12:55 | tool | set-results |
0mArgs:{
"KMSANReasoning": "The patch introduces support for kernel-based encryption of userland hibernation snapshots (CONFIG_ENCRYPTED_HIBERNATION), including two new ioctls (SNAPSHOT_ENABLE_ENCRYPTION and SNAPSHOT_SET_USER_KEY), a write-only sysfs file (/sys/power/snapshot_seed), and swap write mediation in block/fops.c.\n\nAnalysis of memory initialization and usercopy operations:\n1. Kernel structures copied to userspace:\n - In `snapshot_get_encryption_key()`, the kernel writes to user fields `blob_len`, `blob`, and `nonce`. The source structure `struct snapshot_wrapped_key` is packed (`__packed`), explicitly initialized to zero with `{}` and `memset()`, and all its fields are fully populated prior to `copy_to_user()`. The `nonce` buffer is completely populated with `get_random_bytes()`. No uninitialized padding or buffer tails are copied to userspace.\n - In `snapshot_set_user_key()`, only a scalar `meta_size` (`u64`) is returned via `put_user()`.\n - In `snapshot_read_encrypted()`, `copy_to_user()` only transfers pages that have been populated by `snapshot_read_next()` and encrypted via AEAD, along with the authentication tag produced by the cipher.\n - The sysfs attribute `/sys/power/snapshot_seed` is write-only (permissions 0200) without any read callback.\n\n2. Kernel internal buffers and uninitialized memory usage:\n - All cryptographic keys, nonces, and buffers (`seed`, `wrap_key`, `buf`, `image_key`, `wrapped`, `user_key`) are either zero-initialized (`= {}`, `memset()`) or fully populated (`get_random_bytes()`, `hex2bin()`, `copy_from_user()`) before use, and wiped via `memzero_explicit()` / `kfree_sensitive()`.\n - In `snapshot_decrypt_drain()`, strict chunk-length checks ensure that only bytes fully received via `copy_from_user()` are decrypted and applied.\n - In `swsusp_swap_range_allocated()`, out-parameters from `swapdev_block_to_extent()` are only evaluated when the function returns 0 (success), where both pointers are guaranteed to be assigned.\n\n3. KASAN vs KMSAN applicability:\n - Any potential bugs introduced by this patch involve concurrency/locking (`system_transition_mutex`, `crypt_lock`), block extent range arithmetic, or boundary validation on swap/snapshot devices. These classes of issues are covered by KASAN, LOCKDEP, and standard assertion checks.\n - There are no risks of uninitialized memory reads or kernel information leaks. Spawning a dedicated KMSAN fuzzing session is not justified.",
"NeedsKMSAN": false
}Results: {
"KMSANReasoning": "The patch introduces support for kernel-based encryption of userland hibernation snapshots (CONFIG_ENCRYPTED_HIBERNATION), including two new ioctls (SNAPSHOT_ENABLE_ENCRYPTION and SNAPSHOT_SET_USER_KEY), a write-only sysfs file (/sys/power/snapshot_seed), and swap write mediation in block/fops.c.\n\nAnalysis of memory initialization and usercopy operations:\n1. Kernel structures copied to userspace:\n - In `snapshot_get_encryption_key()`, the kernel writes to user fields `blob_len`, `blob`, and `nonce`. The source structure `struct snapshot_wrapped_key` is packed (`__packed`), explicitly initialized to zero with `{}` and `memset()`, and all its fields are fully populated prior to `copy_to_user()`. The `nonce` buffer is completely populated with `get_random_bytes()`. No uninitialized padding or buffer tails are copied to userspace.\n - In `snapshot_set_user_key()`, only a scalar `meta_size` (`u64`) is returned via `put_user()`.\n - In `snapshot_read_encrypted()`, `copy_to_user()` only transfers pages that have been populated by `snapshot_read_next()` and encrypted via AEAD, along with the authentication tag produced by the cipher.\n - The sysfs attribute `/sys/power/snapshot_seed` is write-only (permissions 0200) without any read callback.\n\n2. Kernel internal buffers and uninitialized memory usage:\n - All cryptographic keys, nonces, and buffers (`seed`, `wrap_key`, `buf`, `image_key`, `wrapped`, `user_key`) are either zero-initialized (`= {}`, `memset()`) or fully populated (`get_random_bytes()`, `hex2bin()`, `copy_from_user()`) before use, and wiped via `memzero_explicit()` / `kfree_sensitive()`.\n - In `snapshot_decrypt_drain()`, strict chunk-length checks ensure that only bytes fully received via `copy_from_user()` are decrypted and applied.\n - In `swsusp_swap_range_allocated()`, out-parameters from `swapdev_block_to_extent()` are only evaluated when the function returns 0 (success), where both pointers are guaranteed to be assigned.\n\n3. KASAN vs KMSAN applicability:\n - Any potential bugs introduced by this patch involve concurrency/locking (`system_transition_mutex`, `crypt_lock`), block extent range arithmetic, or boundary validation on swap/snapshot devices. These classes of issues are covered by KASAN, LOCKDEP, and standard assertion checks.\n - There are no risks of uninitialized memory reads or kernel information leaks. Spawning a dedicated KMSAN fuzzing session is not justified.",
"NeedsKMSAN": false
} |
| Total Calls | Total Tokens | Avg Tokens | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|
| Total Calls | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|