xref: /linux/drivers/virt/coco/tdx-guest/tdx-guest.c (revision 4a8bdffce502d70405391a7ac38bac6dcef94749)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * TDX guest user interface driver
4  *
5  * Copyright (C) 2022 Intel Corporation
6  */
7 
8 #define pr_fmt(fmt)			KBUILD_MODNAME ": " fmt
9 
10 #include <linux/kernel.h>
11 #include <linux/miscdevice.h>
12 #include <linux/mm.h>
13 #include <linux/module.h>
14 #include <linux/string.h>
15 #include <linux/uaccess.h>
16 #include <linux/set_memory.h>
17 #include <linux/io.h>
18 #include <linux/delay.h>
19 #include <linux/sockptr.h>
20 #include <linux/tsm.h>
21 #include <linux/tsm-mr.h>
22 
23 #include <uapi/linux/tdx-guest.h>
24 
25 #include <asm/cpu_device_id.h>
26 #include <asm/tdx.h>
27 
28 /* TDREPORT buffer */
29 static u8 *tdx_report_buf;
30 
31 /* Lock to serialize TDG.MR.REPORT and TDG.MR.RTMR.EXTEND TDCALLs */
32 static DEFINE_MUTEX(mr_lock);
33 
34 /* TDREPORT fields */
35 enum {
36 	TDREPORT_reportdata = 128,
37 	TDREPORT_tee_tcb_info = 256,
38 	TDREPORT_tdinfo = TDREPORT_tee_tcb_info + 256,
39 	TDREPORT_attributes = TDREPORT_tdinfo,
40 	TDREPORT_xfam = TDREPORT_attributes + sizeof(u64),
41 	TDREPORT_mrtd = TDREPORT_xfam + sizeof(u64),
42 	TDREPORT_mrconfigid = TDREPORT_mrtd + SHA384_DIGEST_SIZE,
43 	TDREPORT_mrowner = TDREPORT_mrconfigid + SHA384_DIGEST_SIZE,
44 	TDREPORT_mrownerconfig = TDREPORT_mrowner + SHA384_DIGEST_SIZE,
45 	TDREPORT_rtmr0 = TDREPORT_mrownerconfig + SHA384_DIGEST_SIZE,
46 	TDREPORT_rtmr1 = TDREPORT_rtmr0 + SHA384_DIGEST_SIZE,
47 	TDREPORT_rtmr2 = TDREPORT_rtmr1 + SHA384_DIGEST_SIZE,
48 	TDREPORT_rtmr3 = TDREPORT_rtmr2 + SHA384_DIGEST_SIZE,
49 	TDREPORT_servtd_hash = TDREPORT_rtmr3 + SHA384_DIGEST_SIZE,
50 };
51 
tdx_do_report(sockptr_t data,sockptr_t tdreport)52 static int tdx_do_report(sockptr_t data, sockptr_t tdreport)
53 {
54 	scoped_cond_guard(mutex_intr, return -EINTR, &mr_lock) {
55 		u8 *reportdata = tdx_report_buf + TDREPORT_reportdata;
56 		int ret;
57 
58 		if (!sockptr_is_null(data) &&
59 		    copy_from_sockptr(reportdata, data, TDX_REPORTDATA_LEN))
60 			return -EFAULT;
61 
62 		ret = tdx_mcall_get_report0(reportdata, tdx_report_buf);
63 		if (WARN_ONCE(ret, "tdx_mcall_get_report0() failed: %d", ret))
64 			return ret;
65 
66 		if (!sockptr_is_null(tdreport) &&
67 		    copy_to_sockptr(tdreport, tdx_report_buf, TDX_REPORT_LEN))
68 			return -EFAULT;
69 	}
70 	return 0;
71 }
72 
tdx_do_extend(u8 mr_ind,const u8 * data)73 static int tdx_do_extend(u8 mr_ind, const u8 *data)
74 {
75 	scoped_cond_guard(mutex_intr, return -EINTR, &mr_lock) {
76 		/*
77 		 * TDX requires @extend_buf to be 64-byte aligned.
78 		 * It's safe to use REPORTDATA buffer for that purpose because
79 		 * tdx_mr_report/extend_lock() are mutually exclusive.
80 		 */
81 		u8 *extend_buf = tdx_report_buf + TDREPORT_reportdata;
82 		int ret;
83 
84 		memcpy(extend_buf, data, SHA384_DIGEST_SIZE);
85 
86 		ret = tdx_mcall_extend_rtmr(mr_ind, extend_buf);
87 		if (WARN_ONCE(ret, "tdx_mcall_extend_rtmr(%u) failed: %d", mr_ind, ret))
88 			return ret;
89 	}
90 	return 0;
91 }
92 
93 #define TDX_MR_(r) .mr_value = (void *)TDREPORT_##r, TSM_MR_(r, SHA384)
94 static struct tsm_measurement_register tdx_mrs[] = {
95 	{ TDX_MR_(rtmr0) | TSM_MR_F_RTMR },
96 	{ TDX_MR_(rtmr1) | TSM_MR_F_RTMR },
97 	{ TDX_MR_(rtmr2) | TSM_MR_F_RTMR },
98 	{ TDX_MR_(rtmr3) | TSM_MR_F_RTMR },
99 	{ TDX_MR_(mrtd) },
100 	{ TDX_MR_(mrconfigid) | TSM_MR_F_NOHASH },
101 	{ TDX_MR_(mrowner) | TSM_MR_F_NOHASH },
102 	{ TDX_MR_(mrownerconfig) | TSM_MR_F_NOHASH },
103 };
104 #undef TDX_MR_
105 
tdx_mr_refresh(const struct tsm_measurements * tm)106 static int tdx_mr_refresh(const struct tsm_measurements *tm)
107 {
108 	return tdx_do_report(KERNEL_SOCKPTR(NULL), KERNEL_SOCKPTR(NULL));
109 }
110 
tdx_mr_extend(const struct tsm_measurements * tm,const struct tsm_measurement_register * mr,const u8 * data)111 static int tdx_mr_extend(const struct tsm_measurements *tm,
112 			 const struct tsm_measurement_register *mr,
113 			 const u8 *data)
114 {
115 	return tdx_do_extend(mr - tm->mrs, data);
116 }
117 
118 static struct tsm_measurements tdx_measurements = {
119 	.mrs = tdx_mrs,
120 	.nr_mrs = ARRAY_SIZE(tdx_mrs),
121 	.refresh = tdx_mr_refresh,
122 	.write = tdx_mr_extend,
123 };
124 
tdx_mr_init(void)125 static const struct attribute_group *tdx_mr_init(void)
126 {
127 	const struct attribute_group *g;
128 	int rc;
129 
130 	u8 *buf __free(kfree) = kzalloc(TDX_REPORT_LEN, GFP_KERNEL);
131 	if (!buf)
132 		return ERR_PTR(-ENOMEM);
133 
134 	tdx_report_buf = buf;
135 	rc = tdx_mr_refresh(&tdx_measurements);
136 	if (rc)
137 		return ERR_PTR(rc);
138 
139 	/*
140 	 * @mr_value was initialized with the offset only, while the base
141 	 * address is being added here.
142 	 */
143 	for (size_t i = 0; i < ARRAY_SIZE(tdx_mrs); ++i)
144 		*(long *)&tdx_mrs[i].mr_value += (long)buf;
145 
146 	g = tsm_mr_create_attribute_group(&tdx_measurements);
147 	if (!IS_ERR(g))
148 		tdx_report_buf = no_free_ptr(buf);
149 
150 	return g;
151 }
152 
tdx_mr_deinit(const struct attribute_group * mr_grp)153 static void tdx_mr_deinit(const struct attribute_group *mr_grp)
154 {
155 	tsm_mr_free_attribute_group(mr_grp);
156 	kfree(tdx_report_buf);
157 }
158 
159 /*
160  * Intel's SGX QE implementation generally uses Quote size less
161  * than 8K (2K Quote data + ~5K of certificate blob).
162  * DICE-based attestation uses layered evidence that requires
163  * larger Quote size (~100K).
164  */
165 #define TDX_DEFAULT_QUOTE_SIZE		SZ_128K
166 
167 #define GET_QUOTE_CMD_VER		1
168 
169 /* TDX GetQuote status codes */
170 #define GET_QUOTE_SUCCESS		0
171 #define GET_QUOTE_IN_FLIGHT		0xffffffffffffffff
172 
173 /* struct tdx_quote_buf: Format of Quote request buffer.
174  * @version: Quote format version, filled by TD.
175  * @status: Status code of Quote request, filled by VMM.
176  * @in_len: Length of TDREPORT, filled by TD.
177  * @out_len: Length of Quote data, filled by VMM.
178  * @data: Quote data on output or TDREPORT on input.
179  *
180  * More details of Quote request buffer can be found in TDX
181  * Guest-Host Communication Interface (GHCI) for Intel TDX 1.0,
182  * section titled "TDG.VP.VMCALL<GetQuote>"
183  */
184 struct tdx_quote_buf {
185 	u64 version;
186 	u64 status;
187 	u32 in_len;
188 	u32 out_len;
189 	u8 data[];
190 };
191 
192 static struct tdx_quote_buf *quote_buf;
193 
194 /* Lock to streamline quote requests */
195 static DEFINE_MUTEX(quote_lock);
196 
197 /*
198  * GetQuote request timeout in seconds. Expect that 30 seconds
199  * is enough time for QE to respond to any Quote requests.
200  */
201 static u32 getquote_timeout = 30;
202 
tdx_get_report0(struct tdx_report_req __user * req)203 static long tdx_get_report0(struct tdx_report_req __user *req)
204 {
205 	return tdx_do_report(USER_SOCKPTR(req->reportdata),
206 			     USER_SOCKPTR(req->tdreport));
207 }
208 
209 /* Size of the header metadata plus the largest possible raw Quote. */
get_quote_buf_size(void)210 static size_t get_quote_buf_size(void)
211 {
212 	size_t buf_size;
213 	u64 max_size;
214 
215 	/* Start with the default buffer size, which includes the header */
216 	buf_size = TDX_DEFAULT_QUOTE_SIZE;
217 
218 	/*
219 	 * Override the default when the TDX module reports a size. Add room
220 	 * for the header metadata. The size is fixed during TD runtime.
221 	 */
222 	if (!tdx_get_max_quote_size(&max_size))
223 		buf_size = struct_size_t(struct tdx_quote_buf, data, max_size);
224 
225 	return buf_size;
226 }
227 
free_quote_buf(struct tdx_quote_buf * buf)228 static void free_quote_buf(struct tdx_quote_buf *buf)
229 {
230 	size_t alloc_size = PAGE_ALIGN(get_quote_buf_size());
231 	unsigned int count;
232 
233 	count = alloc_size >> PAGE_SHIFT;
234 
235 	if (set_memory_encrypted((unsigned long)buf, count)) {
236 		pr_err("Failed to restore encryption mask for Quote buffer, leak it\n");
237 		return;
238 	}
239 
240 	free_pages_exact(buf, alloc_size);
241 }
242 
alloc_quote_buf(void)243 static struct tdx_quote_buf *alloc_quote_buf(void)
244 {
245 	size_t alloc_size = PAGE_ALIGN(get_quote_buf_size());
246 	struct tdx_quote_buf *buf;
247 	unsigned int count;
248 
249 	count = alloc_size >> PAGE_SHIFT;
250 
251 	buf = alloc_pages_exact(alloc_size, GFP_KERNEL | __GFP_ZERO);
252 	if (!buf)
253 		return NULL;
254 
255 	if (set_memory_decrypted((unsigned long)buf, count))
256 		return NULL;
257 
258 	return buf;
259 }
260 
261 /*
262  * wait_for_quote_completion() - Wait for Quote request completion
263  * @buf: Address of Quote buffer.
264  * @timeout: Timeout in seconds to wait for the Quote generation.
265  *
266  * As per TDX GHCI v1.0 specification, sec titled "TDG.VP.VMCALL<GetQuote>",
267  * the status field in the Quote buffer will be set to GET_QUOTE_IN_FLIGHT
268  * while VMM processes the GetQuote request, and will change it to success
269  * or error code after processing is complete. So wait till the status
270  * changes from GET_QUOTE_IN_FLIGHT or the request being timed out.
271  */
wait_for_quote_completion(struct tdx_quote_buf * buf,u32 timeout)272 static int wait_for_quote_completion(struct tdx_quote_buf *buf, u32 timeout)
273 {
274 	int i = 0;
275 
276 	/*
277 	 * Quote requests usually take a few seconds to complete, so waking up
278 	 * once per second to recheck the status is fine for this use case.
279 	 */
280 	while (buf->status == GET_QUOTE_IN_FLIGHT && i++ < timeout) {
281 		if (msleep_interruptible(MSEC_PER_SEC))
282 			return -EINTR;
283 	}
284 
285 	return (i == timeout) ? -ETIMEDOUT : 0;
286 }
287 
tdx_report_new_locked(struct tsm_report * report)288 static int tdx_report_new_locked(struct tsm_report *report)
289 {
290 	u8 *buf;
291 	struct tsm_report_desc *desc = &report->desc;
292 	size_t quote_buf_size = get_quote_buf_size();
293 	u32 out_len;
294 	int ret;
295 	u64 err;
296 
297 	/*
298 	 * If the previous request is timedout or interrupted, and the
299 	 * Quote buf status is still in GET_QUOTE_IN_FLIGHT (owned by
300 	 * VMM), don't permit any new request.
301 	 */
302 	if (quote_buf->status == GET_QUOTE_IN_FLIGHT)
303 		return -EBUSY;
304 
305 	if (desc->inblob_len != TDX_REPORTDATA_LEN)
306 		return -EINVAL;
307 
308 	memset(quote_buf, 0, quote_buf_size);
309 
310 	/* Update Quote buffer header */
311 	quote_buf->version = GET_QUOTE_CMD_VER;
312 	quote_buf->in_len = TDX_REPORT_LEN;
313 
314 	ret = tdx_do_report(KERNEL_SOCKPTR(desc->inblob),
315 			    KERNEL_SOCKPTR(quote_buf->data));
316 	if (ret)
317 		return ret;
318 
319 	err = tdx_hcall_get_quote(quote_buf, PAGE_ALIGN(quote_buf_size));
320 	if (err) {
321 		pr_err("GetQuote hypercall failed, status:%llx\n", err);
322 		return -EIO;
323 	}
324 
325 	ret = wait_for_quote_completion(quote_buf, getquote_timeout);
326 	if (ret) {
327 		pr_err("GetQuote request timedout\n");
328 		return ret;
329 	}
330 
331 	if (quote_buf->status != GET_QUOTE_SUCCESS) {
332 		pr_debug("GetQuote request failed, status:%llx\n", quote_buf->status);
333 		return -EIO;
334 	}
335 
336 	out_len = READ_ONCE(quote_buf->out_len);
337 
338 	if (struct_size(quote_buf, data, out_len) > quote_buf_size)
339 		return -EFBIG;
340 
341 	buf = kvmemdup(quote_buf->data, out_len, GFP_KERNEL);
342 	if (!buf)
343 		return -ENOMEM;
344 
345 	report->outblob = buf;
346 	report->outblob_len = out_len;
347 
348 	/*
349 	 * TODO: parse the PEM-formatted cert chain out of the quote buffer when
350 	 * provided
351 	 */
352 
353 	return ret;
354 }
355 
tdx_report_new(struct tsm_report * report,void * unused)356 static int tdx_report_new(struct tsm_report *report, void *unused)
357 {
358 	scoped_cond_guard(mutex_intr, return -EINTR, &quote_lock)
359 		return tdx_report_new_locked(report);
360 }
361 
tdx_report_attr_visible(int n)362 static bool tdx_report_attr_visible(int n)
363 {
364 	switch (n) {
365 	case TSM_REPORT_GENERATION:
366 	case TSM_REPORT_PROVIDER:
367 		return true;
368 	}
369 
370 	return false;
371 }
372 
tdx_report_bin_attr_visible(int n)373 static bool tdx_report_bin_attr_visible(int n)
374 {
375 	switch (n) {
376 	case TSM_REPORT_INBLOB:
377 	case TSM_REPORT_OUTBLOB:
378 		return true;
379 	}
380 
381 	return false;
382 }
383 
tdx_guest_ioctl(struct file * file,unsigned int cmd,unsigned long arg)384 static long tdx_guest_ioctl(struct file *file, unsigned int cmd,
385 			    unsigned long arg)
386 {
387 	switch (cmd) {
388 	case TDX_CMD_GET_REPORT0:
389 		return tdx_get_report0((struct tdx_report_req __user *)arg);
390 	default:
391 		return -ENOTTY;
392 	}
393 }
394 
395 static const struct file_operations tdx_guest_fops = {
396 	.owner = THIS_MODULE,
397 	.unlocked_ioctl = tdx_guest_ioctl,
398 };
399 
400 static const struct attribute_group *tdx_attr_groups[] = {
401 	NULL, /* measurements */
402 	NULL
403 };
404 
405 static struct miscdevice tdx_misc_dev = {
406 	.name = KBUILD_MODNAME,
407 	.minor = MISC_DYNAMIC_MINOR,
408 	.fops = &tdx_guest_fops,
409 	.groups = tdx_attr_groups,
410 };
411 
412 static const struct x86_cpu_id tdx_guest_ids[] = {
413 	X86_MATCH_FEATURE(X86_FEATURE_TDX_GUEST, NULL),
414 	{}
415 };
416 MODULE_DEVICE_TABLE(x86cpu, tdx_guest_ids);
417 
418 static const struct tsm_report_ops tdx_tsm_ops = {
419 	.name = KBUILD_MODNAME,
420 	.report_new = tdx_report_new,
421 	.report_attr_visible = tdx_report_attr_visible,
422 	.report_bin_attr_visible = tdx_report_bin_attr_visible,
423 };
424 
tdx_guest_init(void)425 static int __init tdx_guest_init(void)
426 {
427 	int ret;
428 
429 	if (!x86_match_cpu(tdx_guest_ids))
430 		return -ENODEV;
431 
432 	tdx_attr_groups[0] = tdx_mr_init();
433 	if (IS_ERR(tdx_attr_groups[0]))
434 		return PTR_ERR(tdx_attr_groups[0]);
435 
436 	ret = misc_register(&tdx_misc_dev);
437 	if (ret)
438 		goto deinit_mr;
439 
440 	quote_buf = alloc_quote_buf();
441 	if (!quote_buf) {
442 		pr_err("Failed to allocate Quote buffer\n");
443 		ret = -ENOMEM;
444 		goto free_misc;
445 	}
446 
447 	ret = tsm_report_register(&tdx_tsm_ops, NULL);
448 	if (ret)
449 		goto free_quote;
450 
451 	return 0;
452 
453 free_quote:
454 	free_quote_buf(quote_buf);
455 free_misc:
456 	misc_deregister(&tdx_misc_dev);
457 deinit_mr:
458 	tdx_mr_deinit(tdx_attr_groups[0]);
459 
460 	return ret;
461 }
462 module_init(tdx_guest_init);
463 
tdx_guest_exit(void)464 static void __exit tdx_guest_exit(void)
465 {
466 	tsm_report_unregister(&tdx_tsm_ops);
467 	free_quote_buf(quote_buf);
468 	misc_deregister(&tdx_misc_dev);
469 	tdx_mr_deinit(tdx_attr_groups[0]);
470 }
471 module_exit(tdx_guest_exit);
472 
473 MODULE_AUTHOR("Kuppuswamy Sathyanarayanan <sathyanarayanan.kuppuswamy@linux.intel.com>");
474 MODULE_DESCRIPTION("TDX Guest Driver");
475 MODULE_LICENSE("GPL");
476