Skip to contentSkip to conversation

x86: Support Intel Key Locker

RFC PATCH Superseded Chang S. Bae 9 participants 30 messages Dec 16, 2020 – May 14, 2021

Subsystems (6)

v1 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

cover x86: Support Intel Key Locker

Key Locker [1][2] is a new security feature available in new Intel CPUs to protect data encryption keys for the Advanced Encryption Standard algorithm. The protection limits the amount of time an AES key is exposed in memory by sealing a key and referencing it with new AES instructions.

The new AES instruction set is a successor of Intel's AES-NI (AES New Instruction). Users may switch to the Key Locker version from crypto libraries. This series includes a new AES implementation for the Crypto API, which was validated through the crypto unit tests. The performance in the test cases was measured and found comparable to the AES-NI version.

Key Locker introduces a (CPU-)internal key to encode AES keys. The kernel needs to load it and ensure it unchanged as long as CPUs are operational.

The series has three parts:
* PATCH1-6: Implement the internal key management
* PATCH7: Add AES implementation in Crypto library
* PATCH8: Provide the hardware randomization option for the internal key

This RFC series has been reviewed by Dan Williams, with an open question of whether to use hardware backup/restore, or to synchronize reinitialize the internal key over suspend / resume to avoid the implications of key restore failures.

[1] Intel Architecture Instruction Set Extensions Programming Reference:
https://software.intel.com/content/dam/develop/external/us/en/documents/architecture-instruction-set-$
[2] Intel Key Locker Specification:
https://software.intel.com/content/dam/develop/external/us/en/documents/343965-intel-key-locker-speci$

Chang S. Bae (8):
x86/cpufeature: Enumerate Key Locker feature
x86/cpu: Load Key Locker internal key at boot-time x86/msr-index: Add MSRs for Key Locker internal key x86/power: Restore Key Locker internal key from the ACPI S3/4 sleep
states
x86/cpu: Add a config option and a chicken bit for Key Locker selftests/x86: Test Key Locker internal key maintenance
crypto: x86/aes-kl - Support AES algorithm using Key Locker
instructions
x86/cpu: Support the hardware randomization option for Key Locker
internal key

 .../admin-guide/kernel-parameters.txt         |   2 +
 arch/x86/Kconfig                              |  14 +
 arch/x86/crypto/Makefile                      |   3 +
 arch/x86/crypto/aeskl-intel_asm.S             | 881 ++++++++++++++++++
 arch/x86/crypto/aeskl-intel_glue.c            | 697 ++++++++++++++
 arch/x86/include/asm/cpufeatures.h            |   1 +
 arch/x86/include/asm/disabled-features.h      |   8 +-
 arch/x86/include/asm/inst.h                   | 201 ++++
 arch/x86/include/asm/keylocker.h              |  41 +
 arch/x86/include/asm/msr-index.h              |   6 +
 arch/x86/include/uapi/asm/processor-flags.h   |   2 +
 arch/x86/kernel/Makefile                      |   1 +
 arch/x86/kernel/cpu/common.c                  |  66 +-
 arch/x86/kernel/cpu/cpuid-deps.c              |   1 +
 arch/x86/kernel/keylocker.c                   | 147 +++
 arch/x86/kernel/smpboot.c                     |   2 +
 arch/x86/lib/x86-opcode-map.txt               |   2 +-
 arch/x86/power/cpu.c                          |  34 +
 crypto/Kconfig                                |  28 +
 drivers/char/random.c                         |   6 +
 include/linux/random.h                        |   2 +
 tools/arch/x86/lib/x86-opcode-map.txt         |   2 +-
 tools/testing/selftests/x86/Makefile          |   2 +-
 tools/testing/selftests/x86/keylocker.c       | 177 ++++
 24 files changed, 2321 insertions(+), 5 deletions(-)
 create mode 100644 arch/x86/crypto/aeskl-intel_asm.S
 create mode 100644 arch/x86/crypto/aeskl-intel_glue.c
 create mode 100644 arch/x86/include/asm/keylocker.h
 create mode 100644 arch/x86/kernel/keylocker.c
 create mode 100644 tools/testing/selftests/x86/keylocker.c
Signature · 1 line
2.17.1
#1 lore raw

RFC PATCH 1/8 x86/cpufeature: Enumerate Key Locker feature

Intel's Key Locker is a new security feature providing a mechanism to protect a data encryption key when processing the Advanced Encryption Standard algorithm.

Here we add it to the kernel/user ABI by enumerating the hardware capability. E.g., /proc/cpuinfo: keylocker.

Also, define the feature-specific CPUID leaf and bits for the feature enablement.

Key Locker is on the disabled list, which is useful for compile-time configuration later.

---
 arch/x86/include/asm/cpufeatures.h          |  1 +
 arch/x86/include/asm/disabled-features.h    |  8 +++++++-
 arch/x86/include/asm/keylocker.h            | 18 ++++++++++++++++++
 arch/x86/include/uapi/asm/processor-flags.h |  2 ++
 arch/x86/kernel/cpu/cpuid-deps.c            |  1 +
 5 files changed, 29 insertions(+), 1 deletion(-)
 create mode 100644 arch/x86/include/asm/keylocker.h
arch/x86/include/asm/cpufeatures.h +1 -0
index dad350d42ecf..8f2f050023b7 100644
@@ -352,6 +352,7 @@
 #define X86_FEATURE_AVX512_VPOPCNTDQ	(16*32+14) /* POPCNT for vectors of DW/QW */
 #define X86_FEATURE_LA57		(16*32+16) /* 5-level page tables */
 #define X86_FEATURE_RDPID		(16*32+22) /* RDPID instruction */
+#define X86_FEATURE_KEYLOCKER		(16*32+23) /* Key Locker */
 #define X86_FEATURE_CLDEMOTE		(16*32+25) /* CLDEMOTE instruction */
 #define X86_FEATURE_MOVDIRI		(16*32+27) /* MOVDIRI instruction */
 #define X86_FEATURE_MOVDIR64B		(16*32+28) /* MOVDIR64B instruction */
arch/x86/include/asm/disabled-features.h +7 -1
index 5861d34f9771..0ac9414da242 100644
@@ -44,6 +44,12 @@
 # define DISABLE_OSPKE		(1<<(X86_FEATURE_OSPKE & 31))
 #endif /* CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS */
 
+#ifdef CONFIG_X86_KEYLOCKER
+# define DISABLE_KEYLOCKER	0
+#else
+# define DISABLE_KEYLOCKER	(1<<(X86_FEATURE_KEYLOCKER & 31))
+#endif /* CONFIG_X86_KEYLOCKER */
+
 #ifdef CONFIG_X86_5LEVEL
 # define DISABLE_LA57	0
 #else
@@ -82,7 +88,7 @@
 #define DISABLED_MASK14	0
 #define DISABLED_MASK15	0
 #define DISABLED_MASK16	(DISABLE_PKU|DISABLE_OSPKE|DISABLE_LA57|DISABLE_UMIP| \
-			 DISABLE_ENQCMD)
+			 DISABLE_ENQCMD|DISABLE_KEYLOCKER)
 #define DISABLED_MASK17	0
 #define DISABLED_MASK18	0
 #define DISABLED_MASK_CHECK BUILD_BUG_ON_ZERO(NCAPINTS != 19)
arch/x86/include/asm/keylocker.h new file +18 -0
new file mode 100644
index 000000000000..2fe13c21c63f
@@ -0,0 +1,18 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+
+#ifndef _ASM_KEYLOCKER_H
+#define _ASM_KEYLOCKER_H
+
+#ifndef __ASSEMBLY__
+
+#include <linux/bits.h>
+
+#define KEYLOCKER_CPUID                0x019
+#define KEYLOCKER_CPUID_EAX_SUPERVISOR BIT(0)
+#define KEYLOCKER_CPUID_EBX_AESKLE     BIT(0)
+#define KEYLOCKER_CPUID_EBX_WIDE       BIT(2)
+#define KEYLOCKER_CPUID_EBX_BACKUP     BIT(4)
+#define KEYLOCKER_CPUID_ECX_RAND       BIT(1)
+
+#endif /*__ASSEMBLY__ */
+#endif /* _ASM_KEYLOCKER_H */
arch/x86/include/uapi/asm/processor-flags.h +2 -0
index bcba3c643e63..b958a95a0908 100644
@@ -124,6 +124,8 @@
 #define X86_CR4_PCIDE		_BITUL(X86_CR4_PCIDE_BIT)
 #define X86_CR4_OSXSAVE_BIT	18 /* enable xsave and xrestore */
 #define X86_CR4_OSXSAVE		_BITUL(X86_CR4_OSXSAVE_BIT)
+#define X86_CR4_KEYLOCKER_BIT	19 /* enable Key Locker */
+#define X86_CR4_KEYLOCKER	_BITUL(X86_CR4_KEYLOCKER_BIT)
 #define X86_CR4_SMEP_BIT	20 /* enable SMEP support */
 #define X86_CR4_SMEP		_BITUL(X86_CR4_SMEP_BIT)
 #define X86_CR4_SMAP_BIT	21 /* enable SMAP support */
arch/x86/kernel/cpu/cpuid-deps.c +1 -0
index d502241995a3..b8edcb91fe4f 100644
@@ -71,6 +71,7 @@ static const struct cpuid_dep cpuid_deps[] = {
 	{ X86_FEATURE_AVX512_BF16,		X86_FEATURE_AVX512VL  },
 	{ X86_FEATURE_ENQCMD,			X86_FEATURE_XSAVES    },
 	{ X86_FEATURE_PER_THREAD_MBA,		X86_FEATURE_MBA       },
+	{ X86_FEATURE_KEYLOCKER,		X86_FEATURE_XMM2      },
 	{}
 };
 
Signature · 1 line
2.17.1
#2 lore raw

RFC PATCH 2/8 x86/cpu: Load Key Locker internal key at boot-time

In reply to Chang S. Bae

Internal (Wrapping) Key is a new entity of Intel Key Locker feature. This internal key is loaded in a software-inaccessible CPU state and used to encode a data encryption key.

The kernel makes random data and loads it as the internal key in each CPU. The data need to be invalidated as soon as the load is done.

The BIOS may disable the feature. Check the dynamic CPUID bit (KEYLOCKER_CPUID_EBX_AESKLE) at first.

Add byte code for LOADIWKEY -- an instruction to load the internal key, in the 'x86-opcode-map.txt' file to avoid objtool's misinterpretation.

---
 arch/x86/include/asm/keylocker.h      | 11 +++++
 arch/x86/kernel/Makefile              |  1 +
 arch/x86/kernel/cpu/common.c          | 38 +++++++++++++-
 arch/x86/kernel/keylocker.c           | 71 +++++++++++++++++++++++++++
 arch/x86/kernel/smpboot.c             |  2 +
 arch/x86/lib/x86-opcode-map.txt       |  2 +-
 tools/arch/x86/lib/x86-opcode-map.txt |  2 +-
 7 files changed, 124 insertions(+), 3 deletions(-)
 create mode 100644 arch/x86/kernel/keylocker.c
arch/x86/include/asm/keylocker.h +11 -0
index 2fe13c21c63f..daf0734a4095 100644
@@ -14,5 +14,16 @@
 #define KEYLOCKER_CPUID_EBX_BACKUP     BIT(4)
 #define KEYLOCKER_CPUID_ECX_RAND       BIT(1)
 
+bool check_keylocker_readiness(void);
+
+bool load_keylocker(void);
+
+void make_keylocker_data(void);
+#ifdef CONFIG_X86_KEYLOCKER
+void invalidate_keylocker_data(void);
+#else
+#define invalidate_keylocker_data() do { } while (0)
+#endif
+
 #endif /*__ASSEMBLY__ */
 #endif /* _ASM_KEYLOCKER_H */
arch/x86/kernel/Makefile +1 -0
index 68608bd892c0..085dbf49b3b9 100644
@@ -145,6 +145,7 @@ obj-$(CONFIG_PERF_EVENTS)		+= perf_regs.o
 obj-$(CONFIG_TRACING)			+= tracepoint.o
 obj-$(CONFIG_SCHED_MC_PRIO)		+= itmt.o
 obj-$(CONFIG_X86_UMIP)			+= umip.o
+obj-$(CONFIG_X86_KEYLOCKER)		+= keylocker.o
 
 obj-$(CONFIG_UNWINDER_ORC)		+= unwind_orc.o
 obj-$(CONFIG_UNWINDER_FRAME_POINTER)	+= unwind_frame.o
arch/x86/kernel/cpu/common.c +37 -1
index 35ad8480c464..d675075848bb 100644
@@ -57,6 +57,8 @@
 #include <asm/microcode_intel.h>
 #include <asm/intel-family.h>
 #include <asm/cpu_device_id.h>
+#include <asm/keylocker.h>
+
 #include <asm/uv/uv.h>
 
 #include "cpu.h"
@@ -459,6 +461,39 @@ static __init int x86_nofsgsbase_setup(char *arg)
 }
 __setup("nofsgsbase", x86_nofsgsbase_setup);
 
+static __always_inline void setup_keylocker(struct cpuinfo_x86 *c)
+{
+	bool keyloaded;
+
+	if (!cpu_feature_enabled(X86_FEATURE_KEYLOCKER))
+		goto out;
+
+	cr4_set_bits(X86_CR4_KEYLOCKER);
+
+	if (c == &boot_cpu_data) {
+		if (!check_keylocker_readiness())
+			goto disable_keylocker;
+
+		make_keylocker_data();
+	}
+
+	keyloaded = load_keylocker();
+	if (!keyloaded) {
+		pr_err_once("x86/keylocker: Failed to load internal key\n");
+		goto disable_keylocker;
+	}
+
+	pr_info_once("x86/keylocker: Activated\n");
+	return;
+
+disable_keylocker:
+	clear_cpu_cap(c, X86_FEATURE_KEYLOCKER);
+	pr_info_once("x86/keylocker: Disabled\n");
+out:
+	/* Make sure the feature disabled for kexec-reboot. */
+	cr4_clear_bits(X86_CR4_KEYLOCKER);
+}
+
 /*
  * Protection Keys are not available in 32-bit mode.
  */
@@ -1554,10 +1589,11 @@ static void identify_cpu(struct cpuinfo_x86 *c)
 	/* Disable the PN if appropriate */
 	squash_the_stupid_serial_number(c);
 
-	/* Set up SMEP/SMAP/UMIP */
+	/* Setup various Intel-specific CPU security features */
 	setup_smep(c);
 	setup_smap(c);
 	setup_umip(c);
+	setup_keylocker(c);
 
 	/* Enable FSGSBASE instructions if available. */
 	if (cpu_has(c, X86_FEATURE_FSGSBASE)) {
arch/x86/kernel/keylocker.c new file +71 -0

71 lines not on this page · raw message

arch/x86/kernel/smpboot.c +2 -0
index de776b2e6046..a01edf46d4c7 100644
@@ -81,6 +81,7 @@
 #include <asm/spec-ctrl.h>
 #include <asm/hw_irq.h>
 #include <asm/stackprotector.h>
+#include <asm/keylocker.h>
 
 /* representing HT siblings of each logical CPU */
 DEFINE_PER_CPU_READ_MOSTLY(cpumask_var_t, cpu_sibling_map);
@@ -1423,6 +1424,7 @@ void __init native_smp_cpus_done(unsigned int max_cpus)
 	nmi_selftest();
 	impress_friends();
 	mtrr_aps_init();
+	invalidate_keylocker_data();
 }
 
 static int __initdata setup_possible_cpus = -1;
arch/x86/lib/x86-opcode-map.txt +1 -1
index ec31f5b60323..3e241cddfc86 100644
@@ -795,7 +795,7 @@ cc: sha256msg1 Vdq,Wdq | vrsqrt28ps/d Vx,Wx (66),(ev)
 cd: sha256msg2 Vdq,Wdq | vrsqrt28ss/d Vx,Hx,Wx (66),(ev)
 cf: vgf2p8mulb Vx,Wx (66)
 db: VAESIMC Vdq,Wdq (66),(v1)
-dc: vaesenc Vx,Hx,Wx (66)
+dc: vaesenc Vx,Hx,Wx (66) | loadiwkey Vx,Hx (F3)
 dd: vaesenclast Vx,Hx,Wx (66)
 de: vaesdec Vx,Hx,Wx (66)
 df: vaesdeclast Vx,Hx,Wx (66)
tools/arch/x86/lib/x86-opcode-map.txt +1 -1
index ec31f5b60323..3e241cddfc86 100644
@@ -795,7 +795,7 @@ cc: sha256msg1 Vdq,Wdq | vrsqrt28ps/d Vx,Wx (66),(ev)
 cd: sha256msg2 Vdq,Wdq | vrsqrt28ss/d Vx,Hx,Wx (66),(ev)
 cf: vgf2p8mulb Vx,Wx (66)
 db: VAESIMC Vdq,Wdq (66),(v1)
-dc: vaesenc Vx,Hx,Wx (66)
+dc: vaesenc Vx,Hx,Wx (66) | loadiwkey Vx,Hx (F3)
 dd: vaesenclast Vx,Hx,Wx (66)
 de: vaesdec Vx,Hx,Wx (66)
 df: vaesdeclast Vx,Hx,Wx (66)
Signature · 1 line
2.17.1
#24 lore raw

RFC PATCH 8/8 x86/cpu: Support the hardware randomization option for Key Locker internal key

In reply to Chang S. Bae

Hardware can load the internal key with randomization. random.trust_cpu determines the use of the CPU's random number generator. Take the parameter to use the CPU's internal key randomization.

The backup mechanism is required to distribute the key. It is the only way to copy the (unknown) key value to other CPUs.

This randomization option is disabled when hardware does not support the key backup.

---
 arch/x86/include/asm/keylocker.h |  2 +-
 arch/x86/kernel/cpu/common.c     |  3 ++-
 arch/x86/kernel/keylocker.c      | 31 ++++++++++++++++++++++++++++---
 drivers/char/random.c            |  6 ++++++
 include/linux/random.h           |  2 ++
 5 files changed, 39 insertions(+), 5 deletions(-)
arch/x86/include/asm/keylocker.h +1 -1
index 722574c305c2..a6774ced916a 100644
@@ -19,7 +19,7 @@ bool check_keylocker_readiness(void);
 
 bool load_keylocker(void);
 
-void make_keylocker_data(void);
+void make_keylocker_data(bool use_hwrand);
 #ifdef CONFIG_X86_KEYLOCKER
 void invalidate_keylocker_data(void);
 #else
arch/x86/kernel/cpu/common.c +2 -1
index ba5bd79fbac2..48881d8ea559 100644
@@ -485,12 +485,13 @@ static __always_inline void setup_keylocker(struct cpuinfo_x86 *c)
 	cr4_set_bits(X86_CR4_KEYLOCKER);
 
 	if (c == &boot_cpu_data) {
+		bool use_hwrand = check_random_trust_cpu();
 		bool keyloaded;
 
 		if (!check_keylocker_readiness())
 			goto disable_keylocker;
 
-		make_keylocker_data();
+		make_keylocker_data(use_hwrand);
 
 		keyloaded = load_keylocker();
 		if (!keyloaded) {
arch/x86/kernel/keylocker.c +28 -3
index 229875ac80d5..e77e4c3d785e 100644
@@ -13,6 +13,7 @@
 #include <asm/fpu/api.h>
 
 static bool keybackup_available;
+static bool keyhwrand_available;
 
 bool check_keylocker_readiness(void)
 {
@@ -33,25 +34,33 @@ bool check_keylocker_readiness(void)
 		pr_debug("x86/keylocker: no key backup support with possible S3/4\n");
 		return false;
 	}
+
+	keyhwrand_available = (ecx & KEYLOCKER_CPUID_ECX_RAND);
 	return true;
 }
 
 /* Load Internal (Wrapping) Key */
 #define LOADIWKEY		".byte 0xf3,0x0f,0x38,0xdc,0xd1"
 #define LOADIWKEY_NUM_OPERANDS	3
+#define LOADIWKEY_HWRAND_RETRY	10
 
 static struct key {
 	bool valid;
+	bool hwrand;
 	struct reg_128_bit value[LOADIWKEY_NUM_OPERANDS];
 } keydata;
 
-void make_keylocker_data(void)
+void make_keylocker_data(bool use_hwrand)
 {
 	int i;
 
 	for (i = 0; i < LOADIWKEY_NUM_OPERANDS; i++)
 		get_random_bytes(&keydata.value[i], sizeof(struct reg_128_bit));
 
+	keydata.hwrand = (use_hwrand && keyhwrand_available && keybackup_available);
+	if (use_hwrand && !keydata.hwrand)
+		pr_warn("x86/keylocker: hardware random key not fully supported\n");
+
 	keydata.valid = true;
 }
 
@@ -63,12 +72,22 @@ void invalidate_keylocker_data(void)
 }
 
 #define USE_SWKEY	0
+#define USE_HWRANDKEY	BIT(1)
 
 bool load_keylocker(void)
 {
 	struct reg_128_bit zeros = { 0 };
-	u32 keysrc = USE_SWKEY;
 	bool err = true;
+	u32 keysrc;
+	int retry;
+
+	if (keydata.hwrand) {
+		keysrc = USE_HWRANDKEY;
+		retry = LOADIWKEY_HWRAND_RETRY;
+	} else {
+		keysrc = USE_SWKEY;
+		retry = 0;
+	}
 
 	kernel_fpu_begin();
 
@@ -77,13 +96,19 @@ bool load_keylocker(void)
 			 "m"(keydata.value[1]),
 			 "m"(keydata.value[2]));
 
-	asm volatile (LOADIWKEY CC_SET(z) : CC_OUT(z) (err) : "a"(keysrc));
+	do {
+		asm volatile (LOADIWKEY CC_SET(z) : CC_OUT(z) (err) : "a"(keysrc));
+		retry--;
+	} while (err && retry >= 0);
 
 	asm volatile ("movdqu %0, %%xmm0; movdqu %0, %%xmm1; movdqu %0, %%xmm2;"
 		      :: "m"(zeros));
 
 	kernel_fpu_end();
 
+	if (keydata.hwrand)
+		invalidate_keylocker_data();
+
 	return err ? false : true;
 }
 
drivers/char/random.c +6 -0
index 2a41b21623ae..3ee0d659ab2a 100644
@@ -781,6 +781,12 @@ static int __init parse_trust_cpu(char *arg)
 }
 early_param("random.trust_cpu", parse_trust_cpu);
 
+bool check_random_trust_cpu(void)
+{
+	return trust_cpu;
+}
+EXPORT_SYMBOL(check_random_trust_cpu);
+
 static bool crng_init_try_arch(struct crng_state *crng)
 {
 	int		i;
include/linux/random.h +2 -0
index f45b8be3e3c4..f08f44988b13 100644
@@ -158,4 +158,6 @@ static inline bool __init arch_get_random_long_early(unsigned long *v)
 }
 #endif
 
+extern bool check_random_trust_cpu(void);
+
 #endif /* _LINUX_RANDOM_H */
Signature · 1 line
2.17.1
#3 lore raw

RFC PATCH 3/8 x86/msr-index: Add MSRs for Key Locker internal key

In reply to Chang S. Bae

Key Locker internal key in a CPU state can be backed up in a platform register. The backup can be also copied back to a CPU state. This mechanism is useful to restore the key (after system sleep).

Add MSRs for the internal key backup, copy, and status check.

---
 arch/x86/include/asm/msr-index.h | 6 ++++++
 1 file changed, 6 insertions(+)
arch/x86/include/asm/msr-index.h +6 -0
index 972a34d93505..c0b9157806f7 100644
@@ -922,4 +922,10 @@
 #define MSR_VM_IGNNE                    0xc0010115
 #define MSR_VM_HSAVE_PA                 0xc0010117
 
+/* MSRs for Key Locker Internal (Wrapping) Key management */
+#define MSR_IA32_COPY_LOCAL_TO_PLATFORM	0x00000d91
+#define MSR_IA32_COPY_PLATFORM_TO_LOCAL	0x00000d92
+#define MSR_IA32_COPY_STATUS		0x00000990
+#define MSR_IA32_IWKEYBACKUP_STATUS	0x00000991
+
 #endif /* _ASM_X86_MSR_INDEX_H */
Signature · 1 line
2.17.1
#4 lore raw

RFC PATCH 4/8 x86/power: Restore Key Locker internal key from the ACPI S3/4 sleep states

In reply to Chang S. Bae

When the system state switches to these sleep states, the internal key gets reset. Since this system transition is transparent to userspace, the internal key needs to be restored properly.

Key Locker provides a mechanism to back up the internal key in non-volatile memory. The kernel requests a backup right after the key loaded at boot-time and copies it later when the system wakes up.

The backup during the S5 sleep state is not trusted. It is overwritten by a new key at the next boot.

On a system with the S3/4 states, enable the feature only when the backup mechanism is supported.

Disable the feature when the copy fails (or the backup corrupts). The shutdown is considered too noisy. A new key is considerable only when threads can be synchronously suspended.

---
 arch/x86/include/asm/keylocker.h | 12 ++++++++
 arch/x86/kernel/cpu/common.c     | 25 +++++++++++-----
 arch/x86/kernel/keylocker.c      | 51 ++++++++++++++++++++++++++++++++
 arch/x86/power/cpu.c             | 34 +++++++++++++++++++++
 4 files changed, 115 insertions(+), 7 deletions(-)
arch/x86/include/asm/keylocker.h +12 -0
index daf0734a4095..722574c305c2 100644
@@ -6,6 +6,7 @@
 #ifndef __ASSEMBLY__
 
 #include <linux/bits.h>
+#include <asm/msr.h>
 
 #define KEYLOCKER_CPUID                0x019
 #define KEYLOCKER_CPUID_EAX_SUPERVISOR BIT(0)
@@ -25,5 +26,16 @@ void invalidate_keylocker_data(void);
 #define invalidate_keylocker_data() do { } while (0)
 #endif
 
+static inline u64 read_keylocker_backup_status(void)
+{
+	u64 status;
+
+	rdmsrl(MSR_IA32_IWKEYBACKUP_STATUS, status);
+	return status;
+}
+
+void backup_keylocker(void);
+bool copy_keylocker(void);
+
 #endif /*__ASSEMBLY__ */
 #endif /* _ASM_KEYLOCKER_H */
arch/x86/kernel/cpu/common.c +18 -7
index d675075848bb..a446d5aff08f 100644
@@ -463,24 +463,35 @@ __setup("nofsgsbase", x86_nofsgsbase_setup);
 
 static __always_inline void setup_keylocker(struct cpuinfo_x86 *c)
 {
-	bool keyloaded;
-
 	if (!cpu_feature_enabled(X86_FEATURE_KEYLOCKER))
 		goto out;
 
 	cr4_set_bits(X86_CR4_KEYLOCKER);
 
 	if (c == &boot_cpu_data) {
+		bool keyloaded;
+
 		if (!check_keylocker_readiness())
 			goto disable_keylocker;
 
 		make_keylocker_data();
-	}
 
-	keyloaded = load_keylocker();
-	if (!keyloaded) {
-		pr_err_once("x86/keylocker: Failed to load internal key\n");
-		goto disable_keylocker;
+		keyloaded = load_keylocker();
+		if (!keyloaded) {
+			pr_err("x86/keylocker: Fail to load internal key\n");
+			goto disable_keylocker;
+		}
+
+		backup_keylocker();
+	} else {
+		bool keycopied;
+
+		/* NB: When system wakes up, this path recovers the internal key. */
+		keycopied = copy_keylocker();
+		if (!keycopied) {
+			pr_err_once("x86/keylocker: Fail to copy internal key\n");
+			goto disable_keylocker;
+		}
 	}
 
 	pr_info_once("x86/keylocker: Activated\n");
arch/x86/kernel/keylocker.c +51 -0

88 lines not on this page · raw message

arch/x86/power/cpu.c +34 -0
index db1378c6ff26..5412440e7c5c 100644
@@ -25,6 +25,7 @@
 #include <asm/cpu.h>
 #include <asm/mmu_context.h>
 #include <asm/cpu_device_id.h>
+#include <asm/keylocker.h>
 
 #ifdef CONFIG_X86_32
 __visible unsigned long saved_context_ebx;
@@ -57,6 +58,38 @@ static void msr_restore_context(struct saved_context *ctxt)
 	}
 }
 
+/*
+ * The boot CPU executes this function, while other CPUs restore the key
+ * through the setup path in setup_keylocker().
+ */
+static void restore_keylocker(void)
+{
+	u64 keybackup_status;
+	bool keycopied;
+
+	if (!cpu_feature_enabled(X86_FEATURE_KEYLOCKER))
+		return;
+
+	keybackup_status = read_keylocker_backup_status();
+	if (!(keybackup_status & BIT(0))) {
+		pr_err("x86/keylocker: internal key restoration failed with %s\n",
+		       (keybackup_status & BIT(2)) ? "read error" : "invalid status");
+		WARN_ON(1);
+		goto disable_keylocker;
+	}
+
+	keycopied = copy_keylocker();
+	if (keycopied)
+		return;
+
+	pr_err("x86/keylocker: internal key copy failure\n");
+
+disable_keylocker:
+	pr_info("x86/keylocker: Disabled with internal key restoration failure\n");
+	setup_clear_cpu_cap(X86_FEATURE_KEYLOCKER);
+	cr4_clear_bits(X86_CR4_KEYLOCKER);
+}
+
 /**
  *	__save_processor_state - save CPU registers before creating a
  *		hibernation image and before restoring the memory state from it
@@ -265,6 +298,7 @@ static void notrace __restore_processor_state(struct saved_context *ctxt)
 	mtrr_bp_restore();
 	perf_restore_debug_store();
 	msr_restore_context(ctxt);
+	restore_keylocker();
 
 	c = &cpu_data(smp_processor_id());
 	if (cpu_has(c, X86_FEATURE_MSR_IA32_FEAT_CTL))
Signature · 1 line
2.17.1
#9 lore raw

RFC PATCH 5/8 x86/cpu: Add a config option and a chicken bit for Key Locker

In reply to Chang S. Bae

Add a kernel config option to enable the feature (disabled by default) at compile-time.

Also, add a new command-line parameter -- 'nokeylocker' to disable the feature at boot-time.

---
 Documentation/admin-guide/kernel-parameters.txt |  2 ++
 arch/x86/Kconfig                                | 14 ++++++++++++++
 arch/x86/kernel/cpu/common.c                    | 16 ++++++++++++++++
 3 files changed, 32 insertions(+)
Documentation/admin-guide/kernel-parameters.txt +2 -0
index 44fde25bb221..c389ad8fb9de 100644
@@ -3220,6 +3220,8 @@
 
 	nohugeiomap	[KNL,X86,PPC,ARM64] Disable kernel huge I/O mappings.
 
+	nokeylocker	[X86] Disables Key Locker hardware feature.
+
 	nosmt		[KNL,S390] Disable symmetric multithreading (SMT).
 			Equivalent to smt=1.
 
arch/x86/Kconfig +14 -0
index fbf26e0f7a6a..7623af32f919 100644
@@ -1886,6 +1886,20 @@ config X86_INTEL_MEMORY_PROTECTION_KEYS
 
 	  If unsure, say y.
 
+config X86_KEYLOCKER
+	prompt "Key Locker"
+	def_bool n
+	depends on CPU_SUP_INTEL
+	help
+	  Key Locker is a new security feature to protect a data encryption
+	  key for the Advanced Encryption Standard (AES) algorithm.
+
+	  When enabled, every CPU has a unique internal key to wrap the AES
+	  key into an encoded format.  The internal key is not accessible
+	  to software once loaded.
+
+	  If unsure, say y.
+
 choice
 	prompt "TSX enable mode"
 	depends on CPU_SUP_INTEL
arch/x86/kernel/cpu/common.c +16 -0
index a446d5aff08f..ba5bd79fbac2 100644
@@ -354,6 +354,22 @@ static __always_inline void setup_umip(struct cpuinfo_x86 *c)
 /* These bits should not change their value after CPU init is finished. */
 static const unsigned long cr4_pinned_mask =
 	X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_UMIP | X86_CR4_FSGSBASE;
+
+static __init int x86_nokeylocker_setup(char *arg)
+{
+	/* Expect an exact match without trailing characters */
+	if (strlen(arg))
+		return 0;
+
+	if (!cpu_feature_enabled(X86_FEATURE_KEYLOCKER))
+		return 1;
+
+	setup_clear_cpu_cap(X86_FEATURE_KEYLOCKER);
+	pr_info("x86/keylocker: Disabled by kernel command line\n");
+	return 1;
+}
+__setup("nokeylocker", x86_nokeylocker_setup);
+
 static DEFINE_STATIC_KEY_FALSE_RO(cr_pinning);
 static unsigned long cr4_pinned_bits __ro_after_init;
 
Signature · 1 line
2.17.1
#10 lore raw

RFC PATCH 6/8 selftests/x86: Test Key Locker internal key maintenance

In reply to Chang S. Bae

The test validates the internal key to be the same in all CPUs.

It performs the validation again with the Suspend-To-RAM (ACPI S3) state.

---
 tools/testing/selftests/x86/Makefile    |   2 +-
 tools/testing/selftests/x86/keylocker.c | 177 ++++++++++++++++++++++++
 2 files changed, 178 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/x86/keylocker.c
tools/testing/selftests/x86/Makefile +1 -1
index 6703c7906b71..c53e496d77b2 100644
@@ -13,7 +13,7 @@ CAN_BUILD_WITH_NOPIE := $(shell ./check_cc.sh $(CC) trivial_program.c -no-pie)
 TARGETS_C_BOTHBITS := single_step_syscall sysret_ss_attrs syscall_nt test_mremap_vdso \
 			check_initial_reg_state sigreturn iopl ioperm \
 			test_vdso test_vsyscall mov_ss_trap \
-			syscall_arg_fault fsgsbase_restore
+			syscall_arg_fault fsgsbase_restore keylocker
 TARGETS_C_32BIT_ONLY := entry_from_vm86 test_syscall_vdso unwind_vdso \
 			test_FCMOV test_FCOMI test_FISTTP \
 			vdso_restorer
tools/testing/selftests/x86/keylocker.c new file +177 -0

177 lines not on this page · raw message

Signature · 1 line
2.17.1
#13 lore raw

RFC PATCH 7/8 crypto: x86/aes-kl - Support AES algorithm using Key Locker instructions

In reply to Chang S. Bae

Key Locker (KL) is Intel's new security feature that protects the AES key at the time of data transformation. New AES SIMD instructions -- as a successor of Intel's AES-NI -- are provided to encode an AES key and reference it for the AES algorithm.

New instructions support 128/256-bit keys. While it is not desirable to receive any 192-bit key, AES-NI instructions are taken to serve this size.

New instructions are operational in both 32-/64-bit modes.

Add a set of new macros for the new instructions so that no new binutils version is required.

Implemented methods are for a single block as well as ECB, CBC, CTR, and XTS modes. The methods are not compatible with other AES implementations as accessing an encrypted key instead of the normal AES key.

setkey() call encodes an AES key. User may displace the AES key once encoded, as encrypt()/decrypt() methods do not need the key.

Most C code follows the AES-NI implementation. It has higher priority than the AES-NI as providing key protection.

---
 arch/x86/crypto/Makefile           |   3 +
 arch/x86/crypto/aeskl-intel_asm.S  | 881 +++++++++++++++++++++++++++++
 arch/x86/crypto/aeskl-intel_glue.c | 697 +++++++++++++++++++++++
 arch/x86/include/asm/inst.h        | 201 +++++++
 crypto/Kconfig                     |  28 +
 5 files changed, 1810 insertions(+)
 create mode 100644 arch/x86/crypto/aeskl-intel_asm.S
 create mode 100644 arch/x86/crypto/aeskl-intel_glue.c
arch/x86/crypto/Makefile +3 -0
index a31de0c6ccde..8e2e34e73a21 100644
@@ -54,6 +54,9 @@ obj-$(CONFIG_CRYPTO_AES_NI_INTEL) += aesni-intel.o
 aesni-intel-y := aesni-intel_asm.o aesni-intel_glue.o
 aesni-intel-$(CONFIG_64BIT) += aesni-intel_avx-x86_64.o aes_ctrby8_avx-x86_64.o
 
+obj-$(CONFIG_CRYPTO_AES_KL) += aeskl-intel.o
+aeskl-intel-y := aeskl-intel_asm.o aesni-intel_asm.o aeskl-intel_glue.o
+
 obj-$(CONFIG_CRYPTO_SHA1_SSSE3) += sha1-ssse3.o
 sha1-ssse3-y := sha1_avx2_x86_64_asm.o sha1_ssse3_asm.o sha1_ssse3_glue.o
 sha1-ssse3-$(CONFIG_AS_SHA1_NI) += sha1_ni_asm.o
arch/x86/crypto/aeskl-intel_asm.S new file +881 -0

881 lines not on this page · raw message

arch/x86/crypto/aeskl-intel_glue.c new file +697 -0

697 lines not on this page · raw message

arch/x86/include/asm/inst.h +201 -0

222 lines not on this page · raw message

crypto/Kconfig +28 -0
index 094ef56ab7b4..75a184179c72 100644
@@ -1159,6 +1159,34 @@ config CRYPTO_AES_NI_INTEL
 	  ECB, CBC, LRW, XTS. The 64 bit version has additional
 	  acceleration for CTR.
 
+config CRYPTO_AES_KL
+	tristate "AES cipher algorithms (AES-KL)"
+	depends on X86_KEYLOCKER
+	select CRYPTO_AES_NI_INTEL
+	help
+	  Use AES Key Locker instructions for AES algorithm.
+
+	  AES cipher algorithms (FIPS-197). AES uses the Rijndael
+	  algorithm.
+
+	  Rijndael appears to be consistently a very good performer in both
+	  hardware and software across a wide range of computing
+	  environments regardless of its use in feedback or non-feedback
+	  modes. Its key setup time is excellent, and its key agility is
+	  good. Rijndael's very low memory requirements make it very well
+	  suited for restricted-space environments, in which it also
+	  demonstrates excellent performance. Rijndael's operations are
+	  among the easiest to defend against power and timing attacks.
+
+	  The AES specifies three key sizes: 128, 192 and 256 bits
+
+	  See <http://csrc.nist.gov/encryption/aes/> for more information.
+
+	  For 128- and 256-bit keys, the AES cipher algorithm is
+	  implemented by AES Key Locker instructions. This implementation
+	  does not need an AES key once wrapped to an encoded form. For AES
+	  compliance, 192-bit is processed by AES-NI instructions.
+
 config CRYPTO_AES_SPARC64
 	tristate "AES cipher algorithms (SPARC64)"
 	depends on SPARC64
Signature · 1 line
2.17.1
#14 lore raw

Re: [RFC PATCH 7/8] crypto: x86/aes-kl - Support AES algorithm using Key Locker instructions

Hello Chang,

Quoted 29 lines · Chang S. Bae

Key Locker (KL) is Intel's new security feature that protects the AES key at the time of data transformation. New AES SIMD instructions -- as a successor of Intel's AES-NI -- are provided to encode an AES key and reference it for the AES algorithm.

New instructions support 128/256-bit keys. While it is not desirable to receive any 192-bit key, AES-NI instructions are taken to serve this size.

New instructions are operational in both 32-/64-bit modes.

Add a set of new macros for the new instructions so that no new binutils version is required.

Implemented methods are for a single block as well as ECB, CBC, CTR, and XTS modes. The methods are not compatible with other AES implementations as accessing an encrypted key instead of the normal AES key.

setkey() call encodes an AES key. User may displace the AES key once encoded, as encrypt()/decrypt() methods do not need the key.

Most C code follows the AES-NI implementation. It has higher priority than the AES-NI as providing key protection.

Quoted 7 lines
---
 arch/x86/crypto/Makefile           |   3 +
 arch/x86/crypto/aeskl-intel_asm.S  | 881 +++++++++++++++++++++++++++++
 arch/x86/crypto/aeskl-intel_glue.c | 697 +++++++++++++++++++++++
 arch/x86/include/asm/inst.h        | 201 +++++++
 crypto/Kconfig                     |  28 +
 5 files changed, 1810 insertions(+)

We will need to refactor this - cloning the entire driver and just replacing aes-ni with aes-kl is a maintenance nightmare.

Please refer to the arm64 tree for an example how to combine chaining mode routines implemented in assembler with different implementations of the core AES transforms (aes-modes.S is combined with either aes-ce.S or aes-neon.S to produce two different drivers)

...

Quoted 6 lines
arch/x86/crypto/aeskl-intel_glue.c new file +0 -0
new file mode 100644
index 000000000000..9e3f900ad4af
@@ -0,0 +1,697 @@

...

arch/x86/crypto/aeskl-intel_glue.c line 144

Quoted 8 lines
arch/x86/crypto/aeskl-intel_glue.c new file +8 -0
+static void aeskl_encrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
+{
+       struct crypto_aes_ctx *ctx = aes_ctx(crypto_tfm_ctx(tfm));
+       int err = 0;
+
+       if (!crypto_simd_usable())
+               return;
+

It is clear that AES-KL cannot be handled by a fallback algorithm, given that the key is no longer available. But that doesn't mean that you can just give up like this.

This basically implies that we cannot expose the cipher interface at all, and so AES-KL can only be used by callers that use the asynchronous interface, which rules out 802.11, s/w kTLS, macsec and kerberos.

This ties in to a related discussion that is going on about when to allow kernel mode SIMD. I am currently investigating whether we can change the rules a bit so that crypto_simd_usable() is guaranteed to be true.

Quoted 52 lines
arch/x86/crypto/aeskl-intel_glue.c new file +52 -0
+       kernel_fpu_begin();
+       /* 192-bit key not supported, fall back to AES-NI.*/
+       if (unlikely(ctx->key_length == AES_KEYSIZE_192))
+               aesni_enc(ctx, dst, src);
+       else
+               err = __aeskl_enc1(ctx, dst, src);
+       kernel_fpu_end();
+
+       if (err)
+               pr_err("aes-kl (encrypt): invalid handle\n");
+}
+
+static void aeskl_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
+{
+       struct crypto_aes_ctx *ctx = aes_ctx(crypto_tfm_ctx(tfm));
+       int err = 0;
+
+       if (!crypto_simd_usable())
+               return;
+
+       kernel_fpu_begin();
+       /* 192-bit key not supported, fall back to AES-NI */
+       if (unlikely(ctx->key_length == AES_KEYSIZE_192))
+               aesni_dec(ctx, dst, src);
+       else
+               err = __aeskl_dec1(ctx, dst, src);
+       kernel_fpu_end();
+
+       if (err)
+               pr_err("aes-kl (encrypt): invalid handle\n");
+}
+
+static int aeskl_skcipher_setkey(struct crypto_skcipher *tfm, const u8 *key,
+                                unsigned int len)
+{
+       return aeskl_setkey_common(crypto_skcipher_tfm(tfm),
+                                  crypto_skcipher_ctx(tfm), key, len);
+}
+
+static int ecb_encrypt(struct skcipher_request *req)
+{
+       struct crypto_skcipher *tfm;
+       struct crypto_aes_ctx *ctx;
+       struct skcipher_walk walk;
+       unsigned int nbytes;
+       int err;
+
+       tfm = crypto_skcipher_reqtfm(req);
+       ctx = aes_ctx(crypto_skcipher_ctx(tfm));
+
+       err = skcipher_walk_virt(&walk, req, true);
+       if (err)

arch/x86/crypto/aeskl-intel_glue.c line 206

Quoted 10 lines
arch/x86/crypto/aeskl-intel_glue.c new file +10 -0
+               return err;
+
+       while ((nbytes = walk.nbytes)) {
+               unsigned int len = nbytes & AES_BLOCK_MASK;
+               const u8 *src = walk.src.virt.addr;
+               u8 *dst = walk.dst.virt.addr;
+
+               kernel_fpu_begin();
+               if (unlikely(ctx->key_length == AES_KEYSIZE_192))
+                       aesni_ecb_enc(ctx, dst, src, len);

Could we please use a proper fallback here, and relay the entire request?

arch/x86/crypto/aeskl-intel_glue.c line 212

Quoted 6 lines
arch/x86/crypto/aeskl-intel_glue.c new file +6 -0
+               else
+                       err = __aeskl_ecb_enc(ctx, dst, src, len);
+               kernel_fpu_end();
+
+               if (err) {
+                       skcipher_walk_done(&walk, nbytes & (AES_BLOCK_SIZE - 1));

This doesn't look right. The skcipher scatterlist walker may have a live kmap() here so you can't just return.

Quoted 756 lines
arch/x86/crypto/aeskl-intel_glue.c new file +485 -0
+                       return -EINVAL;
+               }
+
+               nbytes &= AES_BLOCK_SIZE - 1;
+
+               err = skcipher_walk_done(&walk, nbytes);
+               if (err)
+                       return err;
+       }
+
+       return err;
+}
+
+static int ecb_decrypt(struct skcipher_request *req)
+{
+       struct crypto_skcipher *tfm;
+       struct crypto_aes_ctx *ctx;
+       struct skcipher_walk walk;
+       unsigned int nbytes;
+       int err;
+
+       tfm = crypto_skcipher_reqtfm(req);
+       ctx = aes_ctx(crypto_skcipher_ctx(tfm));
+
+       err = skcipher_walk_virt(&walk, req, true);
+       if (err)
+               return err;
+
+       while ((nbytes = walk.nbytes)) {
+               unsigned int len = nbytes & AES_BLOCK_MASK;
+               const u8 *src = walk.src.virt.addr;
+               u8 *dst = walk.dst.virt.addr;
+
+               kernel_fpu_begin();
+               if (unlikely(ctx->key_length == AES_KEYSIZE_192))
+                       aesni_ecb_dec(ctx, dst, src, len);
+               else
+                       err = __aeskl_ecb_dec(ctx, dst, src, len);
+               kernel_fpu_end();
+
+               if (err) {
+                       skcipher_walk_done(&walk, nbytes & (AES_BLOCK_SIZE - 1));
+                       return -EINVAL;
+               }
+
+               nbytes &= AES_BLOCK_SIZE - 1;
+
+               err = skcipher_walk_done(&walk, nbytes);
+               if (err)
+                       return err;
+       }
+
+       return err;
+}
+
+static int cbc_encrypt(struct skcipher_request *req)
+{
+       struct crypto_skcipher *tfm;
+       struct crypto_aes_ctx *ctx;
+       struct skcipher_walk walk;
+       unsigned int nbytes;
+       int err;
+
+       tfm = crypto_skcipher_reqtfm(req);
+       ctx = aes_ctx(crypto_skcipher_ctx(tfm));
+       err = skcipher_walk_virt(&walk, req, true);
+       if (err)
+               return err;
+
+       while ((nbytes = walk.nbytes)) {
+               unsigned int len = nbytes & AES_BLOCK_MASK;
+               const u8 *src = walk.src.virt.addr;
+               u8 *dst = walk.dst.virt.addr;
+               u8 *iv = walk.iv;
+
+               kernel_fpu_begin();
+               if (unlikely(ctx->key_length == AES_KEYSIZE_192))
+                       aesni_cbc_enc(ctx, dst, src, len, iv);
+               else
+                       err = __aeskl_cbc_enc(ctx, dst, src, len, iv);
+               kernel_fpu_end();
+
+               if (err) {
+                       skcipher_walk_done(&walk, nbytes & (AES_BLOCK_SIZE - 1));
+                       return -EINVAL;
+               }
+
+               nbytes &= AES_BLOCK_SIZE - 1;
+
+               err = skcipher_walk_done(&walk, nbytes);
+               if (err)
+                       return err;
+       }
+
+       return err;
+}
+
+static int cbc_decrypt(struct skcipher_request *req)
+{
+       struct crypto_skcipher *tfm;
+       struct crypto_aes_ctx *ctx;
+       struct skcipher_walk walk;
+       unsigned int nbytes;
+       int err;
+
+       tfm = crypto_skcipher_reqtfm(req);
+       ctx = aes_ctx(crypto_skcipher_ctx(tfm));
+       err = skcipher_walk_virt(&walk, req, true);
+       if (err)
+               return err;
+
+       while ((nbytes = walk.nbytes)) {
+               unsigned int len = nbytes & AES_BLOCK_MASK;
+               const u8 *src = walk.src.virt.addr;
+               u8 *dst = walk.dst.virt.addr;
+               u8 *iv = walk.iv;
+
+               kernel_fpu_begin();
+               if (unlikely(ctx->key_length == AES_KEYSIZE_192))
+                       aesni_cbc_dec(ctx, dst, src, len, iv);
+               else
+                       err = __aeskl_cbc_dec(ctx, dst, src, len, iv);
+               kernel_fpu_end();
+
+               if (err) {
+                       skcipher_walk_done(&walk, nbytes & (AES_BLOCK_SIZE - 1));
+                       return -EINVAL;
+               }
+
+               nbytes &= AES_BLOCK_SIZE - 1;
+
+               err = skcipher_walk_done(&walk, nbytes);
+               if (err)
+                       return err;
+       }
+
+       return err;
+}
+
+#ifdef CONFIG_X86_64
+static int ctr_crypt(struct skcipher_request *req)
+{
+       struct crypto_skcipher *tfm;
+       struct crypto_aes_ctx *ctx;
+       struct skcipher_walk walk;
+       unsigned int nbytes;
+       int err;
+
+       tfm = crypto_skcipher_reqtfm(req);
+       ctx = aes_ctx(crypto_skcipher_ctx(tfm));
+
+       err = skcipher_walk_virt(&walk, req, true);
+       if (err)
+               return err;
+
+       while ((nbytes = walk.nbytes) >= AES_BLOCK_SIZE) {
+               unsigned int len = nbytes & AES_BLOCK_MASK;
+               const u8 *src = walk.src.virt.addr;
+               u8 *dst = walk.dst.virt.addr;
+               u8 *iv = walk.iv;
+
+               kernel_fpu_begin();
+               if (unlikely(ctx->key_length == AES_KEYSIZE_192))
+                       aesni_ctr_enc(ctx, dst, src, len, iv);
+               else
+                       err = __aeskl_ctr_enc(ctx, dst, src, len, iv);
+               kernel_fpu_end();
+
+               if (err) {
+                       skcipher_walk_done(&walk, nbytes & (AES_BLOCK_SIZE - 1));
+                       return -EINVAL;
+               }
+
+               nbytes &= AES_BLOCK_SIZE - 1;
+
+               err = skcipher_walk_done(&walk, nbytes);
+               if (err)
+                       return err;
+       }
+
+       if (nbytes) {
+               u8 keystream[AES_BLOCK_SIZE];
+               u8 *src = walk.src.virt.addr;
+               u8 *dst = walk.dst.virt.addr;
+               u8 *ctrblk = walk.iv;
+
+               kernel_fpu_begin();
+               if (unlikely(ctx->key_length == AES_KEYSIZE_192))
+                       aesni_enc(ctx, keystream, ctrblk);
+               else
+                       err = __aeskl_enc1(ctx, keystream, ctrblk);
+               kernel_fpu_end();
+
+               if (err) {
+                       skcipher_walk_done(&walk, 0);
+                       return -EINVAL;
+               }
+
+               crypto_xor(keystream, src, nbytes);
+               memcpy(dst, keystream, nbytes);
+               crypto_inc(ctrblk, AES_BLOCK_SIZE);
+
+               err = skcipher_walk_done(&walk, 0);
+       }
+
+       return err;
+}
+
+static int aeskl_xts_setkey(struct crypto_skcipher *tfm, const u8 *key,
+                           unsigned int keylen)
+{
+       struct aeskl_xts_ctx *ctx = crypto_skcipher_ctx(tfm);
+       int err;
+
+       err = xts_verify_key(tfm, key, keylen);
+       if (err)
+               return err;
+
+       keylen /= 2;
+
+       /* first half of xts-key is for crypt */
+       err = aeskl_setkey_common(crypto_skcipher_tfm(tfm), ctx->raw_crypt_ctx, key, keylen);
+       if (err)
+               return err;
+
+       /* second half of xts-key is for tweak */
+       return aeskl_setkey_common(crypto_skcipher_tfm(tfm), ctx->raw_tweak_ctx, key + keylen,
+                                  keylen);
+}
+
+static void aeskl_xts_tweak(const void *raw_ctx, u8 *out, const u8 *in)
+{
+       struct crypto_aes_ctx *ctx = aes_ctx((void *)raw_ctx);
+
+       if (unlikely(ctx->key_length == AES_KEYSIZE_192))
+               aesni_enc(raw_ctx, out, in);
+       else
+               aeskl_enc1(raw_ctx, out, in);
+}
+
+static void aeskl_xts_enc1(const void *raw_ctx, u8 *dst, const u8 *src, le128 *iv)
+{
+       struct crypto_aes_ctx *ctx = aes_ctx((void *)raw_ctx);
+       common_glue_func_t fn = aeskl_enc1;
+
+       if (unlikely(ctx->key_length == AES_KEYSIZE_192))
+               fn = aesni_enc;
+
+       glue_xts_crypt_128bit_one(raw_ctx, dst, src, iv, fn);
+}
+
+static void aeskl_xts_dec1(const void *raw_ctx, u8 *dst, const u8 *src, le128 *iv)
+{
+       struct crypto_aes_ctx *ctx = aes_ctx((void *)raw_ctx);
+       common_glue_func_t fn = aeskl_dec1;
+
+       if (unlikely(ctx->key_length == AES_KEYSIZE_192))
+               fn = aesni_dec;
+
+       glue_xts_crypt_128bit_one(raw_ctx, dst, src, iv, fn);
+}
+
+static void aeskl_xts_enc8(const void *raw_ctx, u8 *dst, const u8 *src, le128 *iv)
+{
+       struct crypto_aes_ctx *ctx = aes_ctx((void *)raw_ctx);
+       int err = 0;
+
+       if (unlikely(ctx->key_length == AES_KEYSIZE_192))
+               aesni_xts_crypt8(raw_ctx, dst, src, true, (u8 *)iv);
+       else
+               err = __aeskl_xts_crypt8(raw_ctx, dst, src, true, (u8 *)iv);
+
+       if (err)
+               pr_err("aes-kl (XTS encrypt): invalid handle\n");
+}
+
+static void aeskl_xts_dec8(const void *raw_ctx, u8 *dst, const u8 *src, le128 *iv)
+{
+       struct crypto_aes_ctx *ctx = aes_ctx((void *)raw_ctx);
+       int err = 0;
+
+       if (unlikely(ctx->key_length == AES_KEYSIZE_192))
+               aesni_xts_crypt8(raw_ctx, dst, src, false, (u8 *)iv);
+       else
+               __aeskl_xts_crypt8(raw_ctx, dst, src, false, (u8 *)iv);
+
+       if (err)
+               pr_err("aes-kl (XTS decrypt): invalid handle\n");
+}
+
+static const struct common_glue_ctx aeskl_xts_enc = {
+       .num_funcs = 2,
+       .fpu_blocks_limit = 1,
+
+       .funcs = { {
+               .num_blocks = 8,
+               .fn_u = { .xts = aeskl_xts_enc8 }
+       }, {
+               .num_blocks = 1,
+               .fn_u = { .xts = aeskl_xts_enc1 }
+       } }
+};
+
+static const struct common_glue_ctx aeskl_xts_dec = {
+       .num_funcs = 2,
+       .fpu_blocks_limit = 1,
+
+       .funcs = { {
+               .num_blocks = 8,
+               .fn_u = { .xts = aeskl_xts_dec8 }
+       }, {
+               .num_blocks = 1,
+               .fn_u = { .xts = aeskl_xts_dec1 }
+       } }
+};
+
+static int xts_crypt(struct skcipher_request *req, bool decrypt)
+{
+       struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
+       struct aeskl_xts_ctx *ctx = crypto_skcipher_ctx(tfm);
+       const struct common_glue_ctx *gctx;
+
+       if (decrypt)
+               gctx = &aeskl_xts_dec;
+       else
+               gctx = &aeskl_xts_enc;
+
+       return glue_xts_req_128bit(gctx, req, aeskl_xts_tweak,
+                                  aes_ctx(ctx->raw_tweak_ctx),
+                                  aes_ctx(ctx->raw_crypt_ctx),
+                                  decrypt);
+}
+
+static int xts_encrypt(struct skcipher_request *req)
+{
+       return xts_crypt(req, false);
+}
+
+static int xts_decrypt(struct skcipher_request *req)
+{
+       return xts_crypt(req, true);
+}
+#endif
+
+static struct crypto_alg aeskl_cipher_alg = {
+       .cra_name               = "aes",
+       .cra_driver_name        = "aes-aeskl",
+       .cra_priority           = 301,
+       .cra_flags              = CRYPTO_ALG_TYPE_CIPHER,
+       .cra_blocksize          = AES_BLOCK_SIZE,
+       .cra_ctxsize            = CRYPTO_AESKL_CTX_SIZE,
+       .cra_module             = THIS_MODULE,
+       .cra_u  = {
+               .cipher = {
+                       .cia_min_keysize        = AES_MIN_KEY_SIZE,
+                       .cia_max_keysize        = AES_MAX_KEY_SIZE,
+                       .cia_setkey             = aeskl_setkey,
+                       .cia_encrypt            = aeskl_encrypt,
+                       .cia_decrypt            = aeskl_decrypt
+               }
+       }
+};
+
+static struct skcipher_alg aeskl_skciphers[] = {
+       {
+               .base = {
+                       .cra_name               = "__ecb(aes)",
+                       .cra_driver_name        = "__ecb-aes-aeskl",
+                       .cra_priority           = 401,
+                       .cra_flags              = CRYPTO_ALG_INTERNAL,
+                       .cra_blocksize          = AES_BLOCK_SIZE,
+                       .cra_ctxsize            = CRYPTO_AESKL_CTX_SIZE,
+                       .cra_module             = THIS_MODULE,
+               },
+               .min_keysize    = AES_MIN_KEY_SIZE,
+               .max_keysize    = AES_MAX_KEY_SIZE,
+               .setkey         = aeskl_skcipher_setkey,
+               .encrypt        = ecb_encrypt,
+               .decrypt        = ecb_decrypt,
+       }, {
+               .base = {
+                       .cra_name               = "__cbc(aes)",
+                       .cra_driver_name        = "__cbc-aes-aeskl",
+                       .cra_priority           = 401,
+                       .cra_flags              = CRYPTO_ALG_INTERNAL,
+                       .cra_blocksize          = AES_BLOCK_SIZE,
+                       .cra_ctxsize            = CRYPTO_AESKL_CTX_SIZE,
+                       .cra_module             = THIS_MODULE,
+               },
+               .min_keysize    = AES_MIN_KEY_SIZE,
+               .max_keysize    = AES_MAX_KEY_SIZE,
+               .ivsize         = AES_BLOCK_SIZE,
+               .setkey         = aeskl_skcipher_setkey,
+               .encrypt        = cbc_encrypt,
+               .decrypt        = cbc_decrypt,
+#ifdef CONFIG_X86_64
+       }, {
+               .base = {
+                       .cra_name               = "__ctr(aes)",
+                       .cra_driver_name        = "__ctr-aes-aeskl",
+                       .cra_priority           = 401,
+                       .cra_flags              = CRYPTO_ALG_INTERNAL,
+                       .cra_blocksize          = 1,
+                       .cra_ctxsize            = CRYPTO_AESKL_CTX_SIZE,
+                       .cra_module             = THIS_MODULE,
+               },
+               .min_keysize    = AES_MIN_KEY_SIZE,
+               .max_keysize    = AES_MAX_KEY_SIZE,
+               .ivsize         = AES_BLOCK_SIZE,
+               .chunksize      = AES_BLOCK_SIZE,
+               .setkey         = aeskl_skcipher_setkey,
+               .encrypt        = ctr_crypt,
+               .decrypt        = ctr_crypt,
+       }, {
+               .base = {
+                       .cra_name               = "__xts(aes)",
+                       .cra_driver_name        = "__xts-aes-aeskl",
+                       .cra_priority           = 402,
+                       .cra_flags              = CRYPTO_ALG_INTERNAL,
+                       .cra_blocksize          = AES_BLOCK_SIZE,
+                       .cra_ctxsize            = XTS_AESKL_CTX_SIZE,
+                       .cra_module             = THIS_MODULE,
+               },
+               .min_keysize    = 2 * AES_MIN_KEY_SIZE,
+               .max_keysize    = 2 * AES_MAX_KEY_SIZE,
+               .ivsize         = AES_BLOCK_SIZE,
+               .setkey         = aeskl_xts_setkey,
+               .encrypt        = xts_encrypt,
+               .decrypt        = xts_decrypt,
+#endif
+       }
+};
+
+static struct simd_skcipher_alg *aeskl_simd_skciphers[ARRAY_SIZE(aeskl_skciphers)];
+
+static const struct x86_cpu_id aes_keylocker_cpuid[] = {
+       X86_MATCH_FEATURE(X86_FEATURE_AES, NULL),
+       X86_MATCH_FEATURE(X86_FEATURE_KEYLOCKER, NULL),
+       {}
+};
+
+static int __init aeskl_init(void)
+{
+       u32 eax, ebx, ecx, edx;
+       int err;
+
+       if (!x86_match_cpu(aes_keylocker_cpuid))
+               return -ENODEV;
+
+       cpuid_count(KEYLOCKER_CPUID, 0, &eax, &ebx, &ecx, &edx);
+       if (!(ebx & KEYLOCKER_CPUID_EBX_AESKLE) ||
+           !(eax & KEYLOCKER_CPUID_EAX_SUPERVISOR) ||
+           !(ebx & KEYLOCKER_CPUID_EBX_WIDE))
+               return -ENODEV;
+
+       err = crypto_register_alg(&aeskl_cipher_alg);
+       if (err)
+               return err;
+
+       err = simd_register_skciphers_compat(aeskl_skciphers, ARRAY_SIZE(aeskl_skciphers),
+                                            aeskl_simd_skciphers);
+       if (err)
+               goto unregister_algs;
+
+       return 0;
+
+unregister_algs:
+       crypto_unregister_alg(&aeskl_cipher_alg);
+
+       return err;
+}
+
+static void __exit aeskl_exit(void)
+{
+       simd_unregister_skciphers(aeskl_skciphers, ARRAY_SIZE(aeskl_skciphers),
+                                 aeskl_simd_skciphers);
+       crypto_unregister_alg(&aeskl_cipher_alg);
+}
+
+late_initcall(aeskl_init);
+module_exit(aeskl_exit);
+
+MODULE_DESCRIPTION("Rijndael (AES) Cipher Algorithm, AES Key Locker implementation");
+MODULE_LICENSE("GPL");
+MODULE_ALIAS_CRYPTO("aes");
arch/x86/include/asm/inst.h +201 -0
index bd7f02480ca1..b719a11a2905 100644
@@ -122,9 +122,62 @@
 #endif
        .endm
 
+       .macro XMM_NUM opd xmm
+       \opd = REG_NUM_INVALID
+       .ifc \xmm,%xmm0
+       \opd = 0
+       .endif
+       .ifc \xmm,%xmm1
+       \opd = 1
+       .endif
+       .ifc \xmm,%xmm2
+       \opd = 2
+       .endif
+       .ifc \xmm,%xmm3
+       \opd = 3
+       .endif
+       .ifc \xmm,%xmm4
+       \opd = 4
+       .endif
+       .ifc \xmm,%xmm5
+       \opd = 5
+       .endif
+       .ifc \xmm,%xmm6
+       \opd = 6
+       .endif
+       .ifc \xmm,%xmm7
+       \opd = 7
+       .endif
+       .ifc \xmm,%xmm8
+       \opd = 8
+       .endif
+       .ifc \xmm,%xmm9
+       \opd = 9
+       .endif
+       .ifc \xmm,%xmm10
+       \opd = 10
+       .endif
+       .ifc \xmm,%xmm11
+       \opd = 11
+       .endif
+       .ifc \xmm,%xmm12
+       \opd = 12
+       .endif
+       .ifc \xmm,%xmm13
+       \opd = 13
+       .endif
+       .ifc \xmm,%xmm14
+       \opd = 14
+       .endif
+       .ifc \xmm,%xmm15
+       \opd = 15
+       .endif
+       .endm
+
        .macro REG_TYPE type reg
        R32_NUM reg_type_r32 \reg
        R64_NUM reg_type_r64 \reg
+       XMM_NUM reg_type_xmm \reg
        .if reg_type_r64 <> REG_NUM_INVALID
        \type = REG_TYPE_R64
        .elseif reg_type_r32 <> REG_NUM_INVALID
@@ -134,6 +187,14 @@
        .endif
        .endm
 
+       .macro PFX_OPD_SIZE
+       .byte 0x66
+       .endm
+
+       .macro PFX_RPT
+       .byte 0xf3
+       .endm
+
        .macro PFX_REX opd1 opd2 W=0
        .if ((\opd1 | \opd2) & 8) || \W
        .byte 0x40 | ((\opd1 & 8) >> 3) | ((\opd2 & 8) >> 1) | (\W << 3)
@@ -158,6 +219,146 @@
        .byte 0x0f, 0xc7
        MODRM 0xc0 rdpid_opd 0x7
 .endm
+
+       .macro ENCODEKEY128 reg1 reg2
+       R32_NUM encodekey128_opd1 \reg1
+       R32_NUM encodekey128_opd2 \reg2
+       PFX_RPT
+       .byte 0xf, 0x38, 0xfa
+       MODRM 0xc0  encodekey128_opd2 encodekey128_opd1
+       .endm
+
+       .macro ENCODEKEY256 reg1 reg2
+       R32_NUM encodekey256_opd1 \reg1
+       R32_NUM encodekey256_opd2 \reg2
+       PFX_RPT
+       .byte 0x0f, 0x38, 0xfb
+       MODRM 0xc0 encodekey256_opd1 encodekey256_opd2
+       .endm
+
+       .macro AESENC128KL reg, xmm
+       REG_TYPE aesenc128kl_opd1_type \reg
+       .if aesenc128kl_opd1_type == REG_TYPE_R64
+       R64_NUM aesenc128kl_opd1 \reg
+       .elseif aesenc128kl_opd1_type == REG_TYPE_R32
+       R32_NUM aesenc128kl_opd1 \reg
+       .else
+       aesenc128kl_opd1 = REG_NUM_INVALID
+       .endif
+       XMM_NUM aesenc128kl_opd2 \xmm
+       PFX_RPT
+       .byte 0x0f, 0x38, 0xdc
+       MODRM 0x0 aesenc128kl_opd1 aesenc128kl_opd2
+       .endm
+
+       .macro AESDEC128KL reg, xmm
+       REG_TYPE aesdec128kl_opd1_type \reg
+       .if aesdec128kl_opd1_type == REG_TYPE_R64
+       R64_NUM aesdec128kl_opd1 \reg
+       .elseif aesdec128kl_opd1_type == REG_TYPE_R32
+       R32_NUM aesdec128kl_opd1 \reg
+       .else
+       aesdec128kl_opd1 = REG_NUM_INVALID
+       .endif
+       XMM_NUM aesdec128kl_opd2 \xmm
+       PFX_RPT
+       .byte 0x0f, 0x38, 0xdd
+       MODRM 0x0 aesdec128kl_opd1 aesdec128kl_opd2
+       .endm
+
+       .macro AESENC256KL reg, xmm
+       REG_TYPE aesenc256kl_opd1_type \reg
+       .if aesenc256kl_opd1_type == REG_TYPE_R64
+       R64_NUM aesenc256kl_opd1 \reg
+       .elseif aesenc256kl_opd1_type == REG_TYPE_R32
+       R32_NUM aesenc256kl_opd1 \reg
+       .else
+       aesenc256kl_opd1 = REG_NUM_INVALID
+       .endif
+       XMM_NUM aesenc256kl_opd2 \xmm
+       PFX_RPT
+       .byte 0x0f, 0x38, 0xde
+       MODRM 0x0 aesenc256kl_opd1 aesenc256kl_opd2
+       .endm
+
+       .macro AESDEC256KL reg, xmm
+       REG_TYPE aesdec256kl_opd1_type \reg
+       .if aesdec256kl_opd1_type == REG_TYPE_R64
+       R64_NUM aesdec256kl_opd1 \reg
+       .elseif aesdec256kl_opd1_type == REG_TYPE_R32
+       R32_NUM aesdec256kl_opd1 \reg
+       .else
+       aesdec256kl_opd1 = REG_NUM_INVALID
+       .endif
+       XMM_NUM aesdec256kl_opd2 \xmm
+       PFX_RPT
+       .byte 0x0f, 0x38, 0xdf
+       MODRM 0x0 aesdec256kl_opd1 aesdec256kl_opd2
+       .endm
+
+       .macro AESENCWIDE128KL reg
+       REG_TYPE aesencwide128kl_opd1_type \reg
+       .if aesencwide128kl_opd1_type == REG_TYPE_R64
+       R64_NUM aesencwide128kl_opd1 \reg
+       .elseif aesencwide128kl_opd1_type == REG_TYPE_R32
+       R32_NUM aesencwide128kl_opd1 \reg
+       .else
+       aesencwide128kl_opd1 = REG_NUM_INVALID
+       .endif
+       PFX_RPT
+       .byte 0x0f, 0x38, 0xd8
+       MODRM 0x0 aesencwide128kl_opd1 0x0
+       .endm
+
+       .macro AESDECWIDE128KL reg
+       REG_TYPE aesdecwide128kl_opd1_type \reg
+       .if aesdecwide128kl_opd1_type == REG_TYPE_R64
+       R64_NUM aesdecwide128kl_opd1 \reg
+       .elseif aesdecwide128kl_opd1_type == REG_TYPE_R32
+       R32_NUM aesdecwide128kl_opd1 \reg
+       .else
+       aesdecwide128kl_opd1 = REG_NUM_INVALID
+       .endif
+       PFX_RPT
+       .byte 0x0f, 0x38, 0xd8
+       MODRM 0x0 aesdecwide128kl_opd1 0x1
+       .endm
+
+       .macro AESENCWIDE256KL reg
+       REG_TYPE aesencwide256kl_opd1_type \reg
+       .if aesencwide256kl_opd1_type == REG_TYPE_R64
+       R64_NUM aesencwide256kl_opd1 \reg
+       .elseif aesencwide256kl_opd1_type == REG_TYPE_R32
+       R32_NUM aesencwide256kl_opd1 \reg
+       .else
+       aesencwide256kl_opd1 = REG_NUM_INVALID
+       .endif
+       PFX_RPT
+       .byte 0x0f, 0x38, 0xd8
+       MODRM 0x0 aesencwide256kl_opd1 0x2
+       .endm
+
+       .macro AESDECWIDE256KL reg
+       REG_TYPE aesdecwide256kl_opd1_type \reg
+       .if aesdecwide256kl_opd1_type == REG_TYPE_R64
+       R64_NUM aesdecwide256kl_opd1 \reg
+       .elseif aesdecwide256kl_opd1_type == REG_TYPE_R32
+       R32_NUM aesdecwide256kl_opd1 \reg
+       .else
+       aesdecwide256kl_opd1 = REG_NUM_INVALID
+       .endif
+       PFX_RPT
+       .byte 0x0f, 0x38, 0xd8
+       MODRM 0x0 aesdecwide256kl_opd1 0x3
+       .endm
+
+       .macro LOADIWKEY xmm1, xmm2
+       XMM_NUM loadiwkey_opd1 \xmm1
+       XMM_NUM loadiwkey_opd2 \xmm2
+       PFX_RPT
+       .byte 0x0f, 0x38, 0xdc
+       MODRM 0xc0 loadiwkey_opd1 loadiwkey_opd2
+       .endm
 #endif
 
 #endif
crypto/Kconfig +28 -1
index 094ef56ab7b4..75a184179c72 100644
@@ -1159,6 +1159,34 @@ config CRYPTO_AES_NI_INTEL
          ECB, CBC, LRW, XTS. The 64 bit version has additional
          acceleration for CTR.
 
+config CRYPTO_AES_KL
+       tristate "AES cipher algorithms (AES-KL)"
+       depends on X86_KEYLOCKER
+       select CRYPTO_AES_NI_INTEL
+       help
+         Use AES Key Locker instructions for AES algorithm.
+
+         AES cipher algorithms (FIPS-197). AES uses the Rijndael
+         algorithm.
+
+         Rijndael appears to be consistently a very good performer in both
+         hardware and software across a wide range of computing
+         environments regardless of its use in feedback or non-feedback
+         modes. Its key setup time is excellent, and its key agility is
+         good. Rijndael's very low memory requirements make it very well
+         suited for restricted-space environments, in which it also
+         demonstrates excellent performance. Rijndael's operations are
+         among the easiest to defend against power and timing attacks.
+
+         The AES specifies three key sizes: 128, 192 and 256 bits
+
+         See <http://csrc.nist.gov/encryption/aes/> for more information.
+
+         For 128- and 256-bit keys, the AES cipher algorithm is
+         implemented by AES Key Locker instructions. This implementation
+         does not need an AES key once wrapped to an encoded form. For AES
+         compliance, 192-bit is processed by AES-NI instructions.
+
 config CRYPTO_AES_SPARC64
        tristate "AES cipher algorithms (SPARC64)"
        depends on SPARC64
--

2.17.1

#5 lore raw

Re: [RFC PATCH 4/8] x86/power: Restore Key Locker internal key from the ACPI S3/4 sleep states

In reply to Chang S. Bae
Quoted 11 lines · Chang S. Bae

When the system state switches to these sleep states, the internal key gets reset. Since this system transition is transparent to userspace, the internal key needs to be restored properly.

Key Locker provides a mechanism to back up the internal key in non-volatile memory. The kernel requests a backup right after the key loaded at boot-time and copies it later when the system wakes up.

The backup during the S5 sleep state is not trusted. It is overwritten by a new key at the next boot.

Quoted 6 lines

On a system with the S3/4 states, enable the feature only when the backup mechanism is supported.

Disable the feature when the copy fails (or the backup corrupts). The shutdown is considered too noisy. A new key is considerable only when threads can be synchronously suspended.

Can this backup key be used to decrypt the encoded AES keys without executing the keylocker instructions on the same CPU?

- Eric

#26 lore raw
#16 lore raw

Re: [RFC PATCH 7/8] crypto: x86/aes-kl - Support AES algorithm using Key Locker instructions

In reply to Chang S. Bae
Quoted 18 lines · Chang S. Bae

Key Locker (KL) is Intel's new security feature that protects the AES key at the time of data transformation. New AES SIMD instructions -- as a successor of Intel's AES-NI -- are provided to encode an AES key and reference it for the AES algorithm.

New instructions support 128/256-bit keys. While it is not desirable to receive any 192-bit key, AES-NI instructions are taken to serve this size.

New instructions are operational in both 32-/64-bit modes.

Add a set of new macros for the new instructions so that no new binutils version is required.

Implemented methods are for a single block as well as ECB, CBC, CTR, and XTS modes. The methods are not compatible with other AES implementations as accessing an encrypted key instead of the normal AES key.

Quoted 5 lines

setkey() call encodes an AES key. User may displace the AES key once encoded, as encrypt()/decrypt() methods do not need the key.

Most C code follows the AES-NI implementation. It has higher priority than the AES-NI as providing key protection.

What does this patch *do*?

IKL gives a few special key slots that have certain restrictions and certain security properties. What can you use them for? With this series installed, what is the user-visible effect? Is there a new API? Do you use them with the netlink user crypto interface? Do you use them for encrypting disks? Swap? How? How do you allocate, reset, and free keys? Who has permissions to use them?

#18 lore raw

Re: [NEEDS-REVIEW] [RFC PATCH 7/8] crypto: x86/aes-kl - Support AES algorithm using Key Locker instructions

In reply to Chang S. Bae
Quoted 17 lines · Chang S. Bae
crypto/Kconfig +17 -0
+config CRYPTO_AES_KL
+	tristate "AES cipher algorithms (AES-KL)"
+	depends on X86_KEYLOCKER
+	select CRYPTO_AES_NI_INTEL
+	help
+	  Use AES Key Locker instructions for AES algorithm.
+
+	  AES cipher algorithms (FIPS-197). AES uses the Rijndael
+	  algorithm.
+
+	  Rijndael appears to be consistently a very good performer in both
+	  hardware and software across a wide range of computing
+	  environments regardless of its use in feedback or non-feedback
+	  modes. Its key setup time is excellent, and its key agility is
+	  good. Rijndael's very low memory requirements make it very well
+	  suited for restricted-space environments, in which it also
+	  demonstrates excellent performance. Rijndael's operations are

crypto/Kconfig config CRYPTO_AES_NI_INTEL · line 1188

Quoted 10 lines
crypto/Kconfig +10 -0
+	  among the easiest to defend against power and timing attacks.
+
+	  The AES specifies three key sizes: 128, 192 and 256 bits
+
+	  See <http://csrc.nist.gov/encryption/aes/> for more information.
+
+	  For 128- and 256-bit keys, the AES cipher algorithm is
+	  implemented by AES Key Locker instructions. This implementation
+	  does not need an AES key once wrapped to an encoded form. For AES
+	  compliance, 192-bit is processed by AES-NI instructions.

Giving a history lesson and high-level overview of AES doesn't quite seem appropriate here, unless this is the first the kernel has seen of AES.

#6 lore raw

Re: [RFC PATCH 4/8] x86/power: Restore Key Locker internal key from the ACPI S3/4 sleep states

In reply to Eric Biggers
Quoted 18 lines · Eric Biggers
Quoted 14 lines · Chang S. Bae

When the system state switches to these sleep states, the internal key gets reset. Since this system transition is transparent to userspace, the internal key needs to be restored properly.

Key Locker provides a mechanism to back up the internal key in non-volatile memory. The kernel requests a backup right after the key loaded at boot-time and copies it later when the system wakes up.

The backup during the S5 sleep state is not trusted. It is overwritten by a new key at the next boot.

On a system with the S3/4 states, enable the feature only when the backup mechanism is supported.

Quoted 6 lines
Quoted 3 lines

Disable the feature when the copy fails (or the backup corrupts). The shutdown is considered too noisy. A new key is considerable only when threads can be synchronously suspended.

Can this backup key be used to decrypt the encoded AES keys without executing the keylocker instructions on the same CPU?

No. The backup key itself is inaccessible to the software.

Thanks,
Chang

#27 lore raw
In reply to Eric Biggers
Quoted 10 lines · Eric Biggers
Quoted 4 lines · Chang S. Bae

[1] Intel Architecture Instruction Set Extensions Programming Reference:
https://software.intel.com/content/dam/develop/external/us/en/documents/architecture-instruction-set-$
[2] Intel Key Locker Specification:
https://software.intel.com/content/dam/develop/external/us/en/documents/343965-intel-key-locker-speci$

Both of these links are broken.

Sorry, my bad -- my editor ate some strings with copy & paste.

Dan has provided the links already, thank you.

Chang

#19 lore raw

Re: [NEEDS-REVIEW] [RFC PATCH 7/8] crypto: x86/aes-kl - Support AES algorithm using Key Locker instructions

In reply to Dave Hansen
Quoted 16 lines · Dave Hansen
Quoted 15 lines · Chang S. Bae
crypto/Kconfig +15 -0
+config CRYPTO_AES_KL
+	tristate "AES cipher algorithms (AES-KL)"
+	depends on X86_KEYLOCKER
+	select CRYPTO_AES_NI_INTEL
+	help
+	  Use AES Key Locker instructions for AES algorithm.
+
+	  AES cipher algorithms (FIPS-197). AES uses the Rijndael
+	  algorithm.
+
+	  Rijndael appears to be consistently a very good performer in both
+	  hardware and software across a wide range of computing
+	  environments regardless of its use in feedback or non-feedback
+	  modes. Its key setup time is excellent, and its key agility is
+	  good. Rijndael's very low memory requirements make it very well
Quoted 8 lines

crypto/Kconfig config CRYPTO_AES_NI_INTEL · line 1184

Quoted 8 lines
crypto/Kconfig +8 -0
+	  suited for restricted-space environments, in which it also
+	  demonstrates excellent performance. Rijndael's operations are
+	  among the easiest to defend against power and timing attacks.
+
+	  The AES specifies three key sizes: 128, 192 and 256 bits
+
+	  See <http://csrc.nist.gov/encryption/aes/> for more information.
+

It's direct copy-pasta from CRYPTO_AES_NI_INTEL until about here.

Quoted 7 lines

crypto/Kconfig config CRYPTO_AES_NI_INTEL · line 1188

Quoted 4 lines
crypto/Kconfig +4 -0
+	  For 128- and 256-bit keys, the AES cipher algorithm is
+	  implemented by AES Key Locker instructions. This implementation
+	  does not need an AES key once wrapped to an encoded form. For AES
+	  compliance, 192-bit is processed by AES-NI instructions.

Giving a history lesson and high-level overview of AES doesn't quite seem appropriate here, unless this is the first the kernel has seen of AES.

And the new bits aren't really enlightening either, as you point out.

#11 lore raw

Re: [RFC PATCH 6/8] selftests/x86: Test Key Locker internal key maintenance

In reply to Chang S. Bae

tools/testing/selftests/x86/keylocker.c line 34

Quoted 2 lines · Chang S. Bae
tools/testing/selftests/x86/keylocker.c new file +2 -0
+	/* ENCODEKEY128 %EAX */
+	asm volatile (".byte 0xf3, 0xf, 0x38, 0xfa, 0xc0");

This is lacking a binutils version number. Boris, didn't you do a checkpatch.pl thing for that?

#20 lore raw

Re: [RFC PATCH 7/8] crypto: x86/aes-kl - Support AES algorithm using Key Locker instructions

In reply to Chang S. Bae
Quoted 219 lines · Chang S. Bae
arch/x86/include/asm/inst.h +194 -0
index bd7f02480ca1..b719a11a2905 100644
@@ -122,9 +122,62 @@
 #endif
 	.endm
 
+	.macro XMM_NUM opd xmm
+	\opd = REG_NUM_INVALID
+	.ifc \xmm,%xmm0
+	\opd = 0
+	.endif
+	.ifc \xmm,%xmm1
+	\opd = 1
+	.endif
+	.ifc \xmm,%xmm2
+	\opd = 2
+	.endif
+	.ifc \xmm,%xmm3
+	\opd = 3
+	.endif
+	.ifc \xmm,%xmm4
+	\opd = 4
+	.endif
+	.ifc \xmm,%xmm5
+	\opd = 5
+	.endif
+	.ifc \xmm,%xmm6
+	\opd = 6
+	.endif
+	.ifc \xmm,%xmm7
+	\opd = 7
+	.endif
+	.ifc \xmm,%xmm8
+	\opd = 8
+	.endif
+	.ifc \xmm,%xmm9
+	\opd = 9
+	.endif
+	.ifc \xmm,%xmm10
+	\opd = 10
+	.endif
+	.ifc \xmm,%xmm11
+	\opd = 11
+	.endif
+	.ifc \xmm,%xmm12
+	\opd = 12
+	.endif
+	.ifc \xmm,%xmm13
+	\opd = 13
+	.endif
+	.ifc \xmm,%xmm14
+	\opd = 14
+	.endif
+	.ifc \xmm,%xmm15
+	\opd = 15
+	.endif
+	.endm
+
 	.macro REG_TYPE type reg
 	R32_NUM reg_type_r32 \reg
 	R64_NUM reg_type_r64 \reg
+	XMM_NUM reg_type_xmm \reg
 	.if reg_type_r64 <> REG_NUM_INVALID
 	\type = REG_TYPE_R64
 	.elseif reg_type_r32 <> REG_NUM_INVALID
@@ -134,6 +187,14 @@
 	.endif
 	.endm
 
+	.macro PFX_OPD_SIZE
+	.byte 0x66
+	.endm
+
+	.macro PFX_RPT
+	.byte 0xf3
+	.endm
+
 	.macro PFX_REX opd1 opd2 W=0
 	.if ((\opd1 | \opd2) & 8) || \W
 	.byte 0x40 | ((\opd1 & 8) >> 3) | ((\opd2 & 8) >> 1) | (\W << 3)
@@ -158,6 +219,146 @@
 	.byte 0x0f, 0xc7
 	MODRM 0xc0 rdpid_opd 0x7
 .endm
+
+	.macro ENCODEKEY128 reg1 reg2
+	R32_NUM encodekey128_opd1 \reg1
+	R32_NUM encodekey128_opd2 \reg2
+	PFX_RPT
+	.byte 0xf, 0x38, 0xfa
+	MODRM 0xc0  encodekey128_opd2 encodekey128_opd1
+	.endm
+
+	.macro ENCODEKEY256 reg1 reg2
+	R32_NUM encodekey256_opd1 \reg1
+	R32_NUM encodekey256_opd2 \reg2
+	PFX_RPT
+	.byte 0x0f, 0x38, 0xfb
+	MODRM 0xc0 encodekey256_opd1 encodekey256_opd2
+	.endm
+
+	.macro AESENC128KL reg, xmm
+	REG_TYPE aesenc128kl_opd1_type \reg
+	.if aesenc128kl_opd1_type == REG_TYPE_R64
+	R64_NUM aesenc128kl_opd1 \reg
+	.elseif aesenc128kl_opd1_type == REG_TYPE_R32
+	R32_NUM aesenc128kl_opd1 \reg
+	.else
+	aesenc128kl_opd1 = REG_NUM_INVALID
+	.endif
+	XMM_NUM aesenc128kl_opd2 \xmm
+	PFX_RPT
+	.byte 0x0f, 0x38, 0xdc
+	MODRM 0x0 aesenc128kl_opd1 aesenc128kl_opd2
+	.endm
+
+	.macro AESDEC128KL reg, xmm
+	REG_TYPE aesdec128kl_opd1_type \reg
+	.if aesdec128kl_opd1_type == REG_TYPE_R64
+	R64_NUM aesdec128kl_opd1 \reg
+	.elseif aesdec128kl_opd1_type == REG_TYPE_R32
+	R32_NUM aesdec128kl_opd1 \reg
+	.else
+	aesdec128kl_opd1 = REG_NUM_INVALID
+	.endif
+	XMM_NUM aesdec128kl_opd2 \xmm
+	PFX_RPT
+	.byte 0x0f, 0x38, 0xdd
+	MODRM 0x0 aesdec128kl_opd1 aesdec128kl_opd2
+	.endm
+
+	.macro AESENC256KL reg, xmm
+	REG_TYPE aesenc256kl_opd1_type \reg
+	.if aesenc256kl_opd1_type == REG_TYPE_R64
+	R64_NUM aesenc256kl_opd1 \reg
+	.elseif aesenc256kl_opd1_type == REG_TYPE_R32
+	R32_NUM aesenc256kl_opd1 \reg
+	.else
+	aesenc256kl_opd1 = REG_NUM_INVALID
+	.endif
+	XMM_NUM aesenc256kl_opd2 \xmm
+	PFX_RPT
+	.byte 0x0f, 0x38, 0xde
+	MODRM 0x0 aesenc256kl_opd1 aesenc256kl_opd2
+	.endm
+
+	.macro AESDEC256KL reg, xmm
+	REG_TYPE aesdec256kl_opd1_type \reg
+	.if aesdec256kl_opd1_type == REG_TYPE_R64
+	R64_NUM aesdec256kl_opd1 \reg
+	.elseif aesdec256kl_opd1_type == REG_TYPE_R32
+	R32_NUM aesdec256kl_opd1 \reg
+	.else
+	aesdec256kl_opd1 = REG_NUM_INVALID
+	.endif
+	XMM_NUM aesdec256kl_opd2 \xmm
+	PFX_RPT
+	.byte 0x0f, 0x38, 0xdf
+	MODRM 0x0 aesdec256kl_opd1 aesdec256kl_opd2
+	.endm
+
+	.macro AESENCWIDE128KL reg
+	REG_TYPE aesencwide128kl_opd1_type \reg
+	.if aesencwide128kl_opd1_type == REG_TYPE_R64
+	R64_NUM aesencwide128kl_opd1 \reg
+	.elseif aesencwide128kl_opd1_type == REG_TYPE_R32
+	R32_NUM aesencwide128kl_opd1 \reg
+	.else
+	aesencwide128kl_opd1 = REG_NUM_INVALID
+	.endif
+	PFX_RPT
+	.byte 0x0f, 0x38, 0xd8
+	MODRM 0x0 aesencwide128kl_opd1 0x0
+	.endm
+
+	.macro AESDECWIDE128KL reg
+	REG_TYPE aesdecwide128kl_opd1_type \reg
+	.if aesdecwide128kl_opd1_type == REG_TYPE_R64
+	R64_NUM aesdecwide128kl_opd1 \reg
+	.elseif aesdecwide128kl_opd1_type == REG_TYPE_R32
+	R32_NUM aesdecwide128kl_opd1 \reg
+	.else
+	aesdecwide128kl_opd1 = REG_NUM_INVALID
+	.endif
+	PFX_RPT
+	.byte 0x0f, 0x38, 0xd8
+	MODRM 0x0 aesdecwide128kl_opd1 0x1
+	.endm
+
+	.macro AESENCWIDE256KL reg
+	REG_TYPE aesencwide256kl_opd1_type \reg
+	.if aesencwide256kl_opd1_type == REG_TYPE_R64
+	R64_NUM aesencwide256kl_opd1 \reg
+	.elseif aesencwide256kl_opd1_type == REG_TYPE_R32
+	R32_NUM aesencwide256kl_opd1 \reg
+	.else
+	aesencwide256kl_opd1 = REG_NUM_INVALID
+	.endif
+	PFX_RPT
+	.byte 0x0f, 0x38, 0xd8
+	MODRM 0x0 aesencwide256kl_opd1 0x2
+	.endm
+
+	.macro AESDECWIDE256KL reg
+	REG_TYPE aesdecwide256kl_opd1_type \reg
+	.if aesdecwide256kl_opd1_type == REG_TYPE_R64
+	R64_NUM aesdecwide256kl_opd1 \reg
+	.elseif aesdecwide256kl_opd1_type == REG_TYPE_R32
+	R32_NUM aesdecwide256kl_opd1 \reg
+	.else
+	aesdecwide256kl_opd1 = REG_NUM_INVALID
+	.endif
+	PFX_RPT
+	.byte 0x0f, 0x38, 0xd8
+	MODRM 0x0 aesdecwide256kl_opd1 0x3
+	.endm
+

arch/x86/include/asm/inst.h line 364

Quoted 10 lines
arch/x86/include/asm/inst.h +7 -0
+	.macro LOADIWKEY xmm1, xmm2
+	XMM_NUM loadiwkey_opd1 \xmm1
+	XMM_NUM loadiwkey_opd2 \xmm2
+	PFX_RPT
+	.byte 0x0f, 0x38, 0xdc
+	MODRM 0xc0 loadiwkey_opd1 loadiwkey_opd2
+	.endm
 #endif
 
 #endif

*groan*, so what actual version of binutils is needed and why is this driver important enough to build on ancient crud to warrant all this gunk?

#21 lore raw

Re: [RFC PATCH 7/8] crypto: x86/aes-kl - Support AES algorithm using Key Locker instructions

Quoted 6 lines · Peter Zijlstra

*groan*, so what actual version of binutils is needed and why is this driver important enough to build on ancient crud to warrant all this gunk?

The new Key Locker instructions look to be added a few month ago [1]. But the latest binutils release (2.35.1) does not include them yet.

I’m open to drop the macros if there is any better way to define them without binutils support.

Thanks,
Chang

[1] https://sourceware.org/git/?p=binutils-gdb.git;a=commit;h=c4694f172b51a2168b8cc15109ab1b97fc0bcb9c

#12 lore raw

Re: [RFC PATCH 6/8] selftests/x86: Test Key Locker internal key maintenance

In reply to Peter Zijlstra
Quoted 8 lines · Peter Zijlstra

tools/testing/selftests/x86/keylocker.c line 34

Quoted 2 lines · Chang S. Bae
tools/testing/selftests/x86/keylocker.c new file +2 -0
+	/* ENCODEKEY128 %EAX */
+	asm volatile (".byte 0xf3, 0xf, 0x38, 0xfa, 0xc0");

This is lacking a binutils version number.

I will add the version number when any new release begins to support this.

Thanks,
Chang

#22 lore raw

Re: [RFC PATCH 7/8] crypto: x86/aes-kl - Support AES algorithm using Key Locker instructions

In reply to Bae, Chang Seok
Quoted 2 lines · Chang Seok

I’m open to drop the macros if there is any better way to define them without binutils support.

Yap, make the driver build depend on the binutils version which supports them.

Signature · 4 lines
Regards/Gruss,
    Boris.

SUSE Software Solutions Germany GmbH, GF: Felix Imendörffer, HRB 36809, AG Nürnberg
#23 lore raw

Re: [RFC PATCH 7/8] crypto: x86/aes-kl - Support AES algorithm using Key Locker instructions

In reply to Bae, Chang Seok
Quoted 7 lines · Chang Seok
Quoted 6 lines · Peter Zijlstra

*groan*, so what actual version of binutils is needed and why is this driver important enough to build on ancient crud to warrant all this gunk?

Quoted 5 lines

The new Key Locker instructions look to be added a few month ago [1]. But the latest binutils release (2.35.1) does not include them yet.

I’m open to drop the macros if there is any better way to define them without binutils support.

It's just a driver, make it depend on binutils having the instructions.

#28 lore raw
In reply to Chang S. Bae
Quoted 5 lines · Chang S. Bae

Key Locker [1][2] is a new security feature available in new Intel CPUs to protect data encryption keys for the Advanced Encryption Standard algorithm. The protection limits the amount of time an AES key is exposed in memory by sealing a key and referencing it with new AES instructions.

I think some fundamental issues need to be worked out before we can enable key locker upstream at all.

First, how fast is LOADIWKEY? Does it depend on the mode? Is it credible to context switch the wrapping key?

First, on bare metal, we need to decide whether to use a wrapping key or a software-provided wrapping key. Both choices have pros and cons, and it's not clear to me whether Linux should have a boot-time parameter, a runtime control, a fixed value, or something else. If we use a random key, we need to figure out what to do about S5 and hibernation. No matter what we do, we're going to have some issues with CRIU.

We also need to understand the virtualization situation. What do we expect hypervisors to do with Key Locker? The only obviously performant way I can see for VMMs to support migration is to use the same wrapping key fleetwide. (This is also the only way I can see for VMMs to manage the wrapping key in a way that a side channel can't extract it from hypervisor memory.) But VMMs can't do this without some degree of cooperation from the guest. Perhaps we should disable KL if CPUID.HYPERVISOR is set for now?

It's a shame that the spec seems to have some holes in the key management mechanisms. It would be very nice if there was a way to load IWKey from an SGX enclave, and it would also be nice if there was a way to load an IWKey that is wrapped by a different key. Also, for non-random IWKey values, there doesn't seem to be a way for software (in an enclave or otherwise) to confirm that it's wrapping an AES key against a particular wrapping key, which seems to severely limit the ability to safely provision a new wrapped key at runtime.

--Andy

#29 lore raw
Quoted 10 lines · Andy Lutomirski
Quoted 5 lines · Chang S. Bae

Key Locker [1][2] is a new security feature available in new Intel CPUs to protect data encryption keys for the Advanced Encryption Standard algorithm. The protection limits the amount of time an AES key is exposed in memory by sealing a key and referencing it with new AES instructions.

Quoted 5 lines

I think some fundamental issues need to be worked out before we can enable key locker upstream at all.

First, how fast is LOADIWKEY? Does it depend on the mode? Is it credible to context switch the wrapping key?

I saw it took 110-130 cycles without the hardware rand. But about 25K cycles with it.

It is not executable in userspace.

Quoted 4 lines

First, on bare metal, we need to decide whether to use a wrapping key or a software-provided wrapping key. Both choices have pros and cons, and it's not clear to me whether Linux should have a boot-time parameter, a runtime control, a fixed value, or something else.

It is assumed that all the CPUs need to have the same key loaded (at boot-time).

I thought the software wrapping key is simple to be loaded.

With hardware rand, the key value is unknown to software. The key needs the backup mechanism to copy it to every CPU.

Quoted 2 lines

If we use a random key, we need to figure out what to do about S5 and hibernation.

It was considered to restore the key from the backup before resuming any suspended thread. That’s the case for S3 and S4 (hibernation) sleep states. The system restarts with S5.

Quoted 1 line

No matter what we do, we're going to have some issues with CRIU.

It looks like the case as long as the wrapping key is not fully restored by it.

Quoted 8 lines

We also need to understand the virtualization situation. What do we expect hypervisors to do with Key Locker? The only obviously performant way I can see for VMMs to support migration is to use the same wrapping key fleetwide. (This is also the only way I can see for VMMs to manage the wrapping key in a way that a side channel can't extract it from hypervisor memory.) But VMMs can't do this without some degree of cooperation from the guest. Perhaps we should disable KL if CPUID.HYPERVISOR is set for now?

This is one of the options we considered too.

Quoted 8 lines

It's a shame that the spec seems to have some holes in the key management mechanisms. It would be very nice if there was a way to load IWKey from an SGX enclave, and it would also be nice if there was a way to load an IWKey that is wrapped by a different key. Also, for non-random IWKey values, there doesn't seem to be a way for software (in an enclave or otherwise) to confirm that it's wrapping an AES key against a particular wrapping key, which seems to severely limit the ability to safely provision a new wrapped key at runtime.

The current use of the wrapping key is only for an AES key. Maybe the feature will be extended in the future.

Thanks,
Chang

#7 lore raw

Re: [RFC PATCH 4/8] x86/power: Restore Key Locker internal key from the ACPI S3/4 sleep states

In reply to Chang S. Bae
Quoted 228 lines · Chang S. Bae

When the system state switches to these sleep states, the internal key gets reset. Since this system transition is transparent to userspace, the internal key needs to be restored properly.

Key Locker provides a mechanism to back up the internal key in non-volatile memory. The kernel requests a backup right after the key loaded at boot-time and copies it later when the system wakes up.

The backup during the S5 sleep state is not trusted. It is overwritten by a new key at the next boot.

On a system with the S3/4 states, enable the feature only when the backup mechanism is supported.

Disable the feature when the copy fails (or the backup corrupts). The shutdown is considered too noisy. A new key is considerable only when threads can be synchronously suspended.

---
 arch/x86/include/asm/keylocker.h | 12 ++++++++
 arch/x86/kernel/cpu/common.c     | 25 +++++++++++-----
 arch/x86/kernel/keylocker.c      | 51 ++++++++++++++++++++++++++++++++
 arch/x86/power/cpu.c             | 34 +++++++++++++++++++++
 4 files changed, 115 insertions(+), 7 deletions(-)
arch/x86/include/asm/keylocker.h +12 -0
index daf0734a4095..722574c305c2 100644
@@ -6,6 +6,7 @@
 #ifndef __ASSEMBLY__
 
 #include <linux/bits.h>
+#include <asm/msr.h>
 
 #define KEYLOCKER_CPUID                0x019
 #define KEYLOCKER_CPUID_EAX_SUPERVISOR BIT(0)
@@ -25,5 +26,16 @@ void invalidate_keylocker_data(void);
 #define invalidate_keylocker_data() do { } while (0)
 #endif
 
+static inline u64 read_keylocker_backup_status(void)
+{
+       u64 status;
+
+       rdmsrl(MSR_IA32_IWKEYBACKUP_STATUS, status);
+       return status;
+}
+
+void backup_keylocker(void);
+bool copy_keylocker(void);
+
 #endif /*__ASSEMBLY__ */
 #endif /* _ASM_KEYLOCKER_H */
arch/x86/kernel/cpu/common.c +18 -7
index d675075848bb..a446d5aff08f 100644
@@ -463,24 +463,35 @@ __setup("nofsgsbase", x86_nofsgsbase_setup);
 
 static __always_inline void setup_keylocker(struct cpuinfo_x86 *c)
 {
-       bool keyloaded;
-
        if (!cpu_feature_enabled(X86_FEATURE_KEYLOCKER))
                goto out;
 
        cr4_set_bits(X86_CR4_KEYLOCKER);
 
        if (c == &boot_cpu_data) {
+               bool keyloaded;
+
                if (!check_keylocker_readiness())
                        goto disable_keylocker;
 
                make_keylocker_data();
-       }
 
-       keyloaded = load_keylocker();
-       if (!keyloaded) {
-               pr_err_once("x86/keylocker: Failed to load internal key\n");
-               goto disable_keylocker;
+               keyloaded = load_keylocker();
+               if (!keyloaded) {
+                       pr_err("x86/keylocker: Fail to load internal key\n");
+                       goto disable_keylocker;
+               }
+
+               backup_keylocker();
+       } else {
+               bool keycopied;
+
+               /* NB: When system wakes up, this path recovers the internal key. */
+               keycopied = copy_keylocker();
+               if (!keycopied) {
+                       pr_err_once("x86/keylocker: Fail to copy internal key\n");
+                       goto disable_keylocker;
+               }
        }
 
        pr_info_once("x86/keylocker: Activated\n");
arch/x86/kernel/keylocker.c +51 -0
index e455d806b80c..229875ac80d5 100644
@@ -5,11 +5,15 @@
  */
 
 #include <linux/random.h>
+#include <linux/acpi.h>
+#include <linux/delay.h>
 
 #include <asm/keylocker.h>
 #include <asm/fpu/types.h>
 #include <asm/fpu/api.h>
 
+static bool keybackup_available;
+
 bool check_keylocker_readiness(void)
 {
        u32 eax, ebx, ecx, edx;
@@ -21,6 +25,14 @@ bool check_keylocker_readiness(void)
                return false;
        }
 
+       keybackup_available = (ebx & KEYLOCKER_CPUID_EBX_BACKUP);
+       /* Internal Key backup is essential with S3/4 states */
+       if (!keybackup_available &&
+           (acpi_sleep_state_supported(ACPI_STATE_S3) ||
+            acpi_sleep_state_supported(ACPI_STATE_S4))) {
+               pr_debug("x86/keylocker: no key backup support with possible S3/4\n");
+               return false;
+       }
        return true;
 }
 
@@ -29,6 +41,7 @@ bool check_keylocker_readiness(void)
 #define LOADIWKEY_NUM_OPERANDS 3
 
 static struct key {
+       bool valid;
        struct reg_128_bit value[LOADIWKEY_NUM_OPERANDS];
 } keydata;
 
@@ -38,11 +51,15 @@ void make_keylocker_data(void)
 
        for (i = 0; i < LOADIWKEY_NUM_OPERANDS; i++)
                get_random_bytes(&keydata.value[i], sizeof(struct reg_128_bit));
+
+       keydata.valid = true;
 }
 
 void invalidate_keylocker_data(void)
 {
        memset(&keydata.value, 0, sizeof(struct reg_128_bit) * LOADIWKEY_NUM_OPERANDS);
+
+       keydata.valid = false;
 }
 
 #define USE_SWKEY      0
@@ -69,3 +86,37 @@ bool load_keylocker(void)
 
        return err ? false : true;
 }
+
+void backup_keylocker(void)
+{
+       if (keybackup_available)
+               wrmsrl(MSR_IA32_COPY_LOCAL_TO_PLATFORM, 1);
+}
+
+#define KEYRESTORE_RETRY       1
+
+bool copy_keylocker(void)
+{
+       bool copied = false;
+       int i;
+
+       /* Use valid key data when available */
+       if (keydata.valid)
+               return load_keylocker();
+
+       if (!keybackup_available)
+               return copied;
+
+       wrmsrl(MSR_IA32_COPY_PLATFORM_TO_LOCAL, 1);
+
+       for (i = 0; (i <= KEYRESTORE_RETRY) && !copied; i++) {
+               u64 status;
+
+               if (i)
+                       udelay(1);
+               rdmsrl(MSR_IA32_COPY_STATUS, status);
+               copied = status & BIT(0) ? true : false;
+       }
+
+       return copied;
+}
arch/x86/power/cpu.c +10 -0
index db1378c6ff26..5412440e7c5c 100644
@@ -25,6 +25,7 @@
 #include <asm/cpu.h>
 #include <asm/mmu_context.h>
 #include <asm/cpu_device_id.h>
+#include <asm/keylocker.h>
 
 #ifdef CONFIG_X86_32
 __visible unsigned long saved_context_ebx;
@@ -57,6 +58,38 @@ static void msr_restore_context(struct saved_context *ctxt)
        }
 }
 
+/*
+ * The boot CPU executes this function, while other CPUs restore the key
+ * through the setup path in setup_keylocker().
+ */
+static void restore_keylocker(void)
+{
+       u64 keybackup_status;
+       bool keycopied;
+

arch/x86/power/cpu.c static void msr_restore_context(struct saved_context *ctxt) · line 79

Quoted 10 lines
arch/x86/power/cpu.c +10 -0
+       if (!cpu_feature_enabled(X86_FEATURE_KEYLOCKER))
+               return;
+
+       keybackup_status = read_keylocker_backup_status();
+       if (!(keybackup_status & BIT(0))) {
+               pr_err("x86/keylocker: internal key restoration failed with %s\n",
+                      (keybackup_status & BIT(2)) ? "read error" : "invalid status");
+               WARN_ON(1);
+               goto disable_keylocker;
+       }

The above conditional could be consolidated a bit by using WARN():

if (WARN(!(keybackup_status & BIT(0)), "x86/keylocker: internal key restoration failed with %s\n",
(keybackup_status & BIT(2)) ? "read error" : "invalid status")
goto disable_keylocker;

Apart from this the patch LGTM.

Thanks!

Quoted 27 lines
arch/x86/power/cpu.c +14 -1
+
+       keycopied = copy_keylocker();
+       if (keycopied)
+               return;
+
+       pr_err("x86/keylocker: internal key copy failure\n");
+
+disable_keylocker:
+       pr_info("x86/keylocker: Disabled with internal key restoration failure\n");
+       setup_clear_cpu_cap(X86_FEATURE_KEYLOCKER);
+       cr4_clear_bits(X86_CR4_KEYLOCKER);
+}
+
 /**
  *     __save_processor_state - save CPU registers before creating a
  *             hibernation image and before restoring the memory state from it
@@ -265,6 +298,7 @@ static void notrace __restore_processor_state(struct saved_context *ctxt)
        mtrr_bp_restore();
        perf_restore_debug_store();
        msr_restore_context(ctxt);
+       restore_keylocker();
 
        c = &cpu_data(smp_processor_id());
        if (cpu_has(c, X86_FEATURE_MSR_IA32_FEAT_CTL))
--

2.17.1

#8 lore raw

Re: [RFC PATCH 4/8] x86/power: Restore Key Locker internal key from the ACPI S3/4 sleep states

Quoted 10 lines · Rafael J. Wysocki

arch/x86/power/cpu.c static void msr_restore_context(struct saved_context *ctxt) · line 79

Quoted 8 lines · Chang S. Bae
arch/x86/power/cpu.c +7 -0
+       keybackup_status = read_keylocker_backup_status();
+       if (!(keybackup_status & BIT(0))) {
+               pr_err("x86/keylocker: internal key restoration failed with %s\n",
+                      (keybackup_status & BIT(2)) ? "read error" : "invalid status");
+               WARN_ON(1);
+               goto disable_keylocker;
+       }
Quoted 8 lines

The above conditional could be consolidated a bit by using WARN():

if (WARN(!(keybackup_status & BIT(0)), "x86/keylocker: internal key restoration failed with %s\n",
(keybackup_status & BIT(2)) ? "read error" : "invalid status")
goto disable_keylocker;

Apart from this the patch LGTM.

Thanks for the review! I will make this change on my next revision.

Chang

#15 lore raw

Re: [RFC PATCH 7/8] crypto: x86/aes-kl - Support AES algorithm using Key Locker instructions

In reply to Ard Biesheuvel
Quoted 8 lines · Ard Biesheuvel

We will need to refactor this - cloning the entire driver and just replacing aes-ni with aes-kl is a maintenance nightmare.

Please refer to the arm64 tree for an example how to combine chaining mode routines implemented in assembler with different implementations of the core AES transforms (aes-modes.S is combined with either aes-ce.S or aes-neon.S to produce two different drivers)

I just post v2 [1]. PATCH9 [2] refactors some glue code out of AES-NI to prepare AES-KL.

[ Past a few months were not fully spent on this but it took a while to
address comments and to debug test cases. ]

Quoted 21 lines

...

Quoted 6 lines
arch/x86/crypto/aeskl-intel_glue.c new file +0 -0
new file mode 100644
index 000000000000..9e3f900ad4af
@@ -0,0 +1,697 @@

...

arch/x86/crypto/aeskl-intel_glue.c line 144

Quoted 8 lines
arch/x86/crypto/aeskl-intel_glue.c new file +8 -0
+static void aeskl_encrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
+{
+       struct crypto_aes_ctx *ctx = aes_ctx(crypto_tfm_ctx(tfm));
+       int err = 0;
+
+       if (!crypto_simd_usable())
+               return;
+

It is clear that AES-KL cannot be handled by a fallback algorithm, given that the key is no longer available. But that doesn't mean that you can just give up like this.

Quoted 4 lines

This basically implies that we cannot expose the cipher interface at all, and so AES-KL can only be used by callers that use the asynchronous interface, which rules out 802.11, s/w kTLS, macsec and kerberos.

I made not to expose the synchronous interface, in v2.

Quoted 4 lines

This ties in to a related discussion that is going on about when to allow kernel mode SIMD. I am currently investigating whether we can change the rules a bit so that crypto_simd_usable() is guaranteed to be true.

I saw your series [3]. Yes, I’m very interested in it.

Quoted 17 lines
Quoted 17 lines
arch/x86/crypto/aeskl-intel_glue.c new file +17 -0
+static int ecb_encrypt(struct skcipher_request *req)
+{
+       struct crypto_skcipher *tfm;
+       struct crypto_aes_ctx *ctx;
+       struct skcipher_walk walk;
+       unsigned int nbytes;
+       int err;
+
+       tfm = crypto_skcipher_reqtfm(req);
+       ctx = aes_ctx(crypto_skcipher_ctx(tfm));
+
+       err = skcipher_walk_virt(&walk, req, true);
+       if (err)
+               return err;
+
+       while ((nbytes = walk.nbytes)) {
+               unsigned int len = nbytes & AES_BLOCK_MASK;
Quoted 8 lines

arch/x86/crypto/aeskl-intel_glue.c line 206

Quoted 6 lines
arch/x86/crypto/aeskl-intel_glue.c new file +6 -0
+               const u8 *src = walk.src.virt.addr;
+               u8 *dst = walk.dst.virt.addr;
+
+               kernel_fpu_begin();
+               if (unlikely(ctx->key_length == AES_KEYSIZE_192))
+                       aesni_ecb_enc(ctx, dst, src, len);

Could we please use a proper fallback here, and relay the entire request?

I made a change like this in v2:

+static int ecb_encrypt(struct skcipher_request *req) +{
+ struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
+
+ if (likely(keylength(crypto_skcipher_ctx(tfm)) != AES_KEYSIZE_192))
+ return ecb_crypt_common(req, aeskl_ecb_enc);
+ else
+ return ecb_crypt_common(req, aesni_ecb_enc);
+}

Quoted 9 lines

arch/x86/crypto/aeskl-intel_glue.c line 212

Quoted 6 lines
arch/x86/crypto/aeskl-intel_glue.c new file +6 -0
+               else
+                       err = __aeskl_ecb_enc(ctx, dst, src, len);
+               kernel_fpu_end();
+
+               if (err) {
+                       skcipher_walk_done(&walk, nbytes & (AES_BLOCK_SIZE - 1));

This doesn't look right. The skcipher scatterlist walker may have a live kmap() here so you can't just return.

I’ve added a preparatory patch [4] to deal with cases like this.

Thanks,
Chang

[1] https://lore.kernel.org/lkml/[email protected]/
[2] https://lore.kernel.org/lkml/[email protected]/
[3] https://lore.kernel.org/lkml/[email protected]/
[4] https://lore.kernel.org/lkml/[email protected]/

#17 lore raw

Re: [RFC PATCH 7/8] crypto: x86/aes-kl - Support AES algorithm using Key Locker instructions

In reply to Andy Lutomirski

First of all, my apologies for the delay. I wish now with v2 [1] is a momentum.

Quoted 2 lines · Andy Lutomirski

What does this patch *do*?

It adds a new AES implementation that can be a replacement for the AES-NI version.

Quoted 2 lines

IKL gives a few special key slots that have certain restrictions and certain security properties.

I think this can be viewed as one implementation of Envelope Encryption. Internal Wrapping Key (IWKey) on the spec is practically Key-Encryption Key. Each CPU has one key state and it is used to encode AES keys (or Data Encryption Key) as many as a user wants. An encoded form may convey access restrictions.

Quoted 3 lines

What can you use them for? With this series installed, what is the user-visible effect? Is there a new API? Do you use them with the netlink user crypto interface? Do you use them for encrypting disks? Swap?

No new API is added here.

No observable effect is expected to end-users. AES Key Locker provides the same function of transforming data and does this for the chaining modes at the same speed (or a bit faster).

As a replacement for AES-NI, the usage will be pretty much the same as AES-NI’s. Admittedly, this instruction set has some limitations, e.g., with no 192-bit key support.

Since it can protect AES keys during the transformation, I think one may consider using it for huge data. So, yes, block disk encryption for instance. For testing purposes though, I was able to run it with dm-crypt [2].

Quoted 2 lines

How? How do you allocate, reset, and free keys? Who has permissions to use them?

IWKey (or KEK) is loaded only in kernel mode. The value is randomized.

FWIW, the code intentionally sets a restriction to the encoded form. Once encoded from an AES key, AES instructions that referencing it have to be executed in kernel mode.

Thanks,
Chang

[1] https://lore.kernel.org/lkml/[email protected]/
[2] https://gitlab.com/cryptsetup/cryptsetup/-/wikis/DMCrypt