|
root / base / usr / src / cmd / bhyve / common / tpm_emul_passthru.c
tpm_emul_passthru.c C 120 lines 2.2 KB
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*-
 * SPDX-License-Identifier: BSD-2-Clause
 *
 * Copyright (c) 2023 Beckhoff Automation GmbH & Co. KG
 * Author: Corvin Köhne <corvink@FreeBSD.org>
 */

#include <sys/types.h>

#include <err.h>
#include <errno.h>
#include <fcntl.h>
#ifdef	__FreeBSD__
#include <malloc_np.h>
#else
#include <sys/vmm.h>
#endif
#include <stdlib.h>
#include <unistd.h>

#include "config.h"
#include "tpm_device.h"
#include "tpm_emul.h"

struct tpm_passthru {
	int fd;
};

struct tpm_resp_hdr {
	uint16_t tag;
	uint32_t len;
	uint32_t errcode;
} __packed;

static int
tpm_passthru_init(void **sc, nvlist_t *nvl)
{
#ifndef	__FreeBSD__
	/*
	 * Until illumos has a TPM 2.0 driver, we can't finish plumbing the TPM
	 * pass-through.
	 */
	errx(4, "TPM pass-through devices are not yet supported on illumos");
#else
	struct tpm_passthru *tpm;
	const char *path;

	tpm = calloc(1, sizeof(struct tpm_passthru));
	if (tpm == NULL) {
		warnx("%s: failed to allocate tpm passthru", __func__);
		return (ENOMEM);
	}

	path = get_config_value_node(nvl, "path");
	tpm->fd = open(path, O_RDWR);
	if (tpm->fd < 0) {
		warnx("%s: unable to open tpm device \"%s\"", __func__, path);
		return (ENOENT);
	}

	*sc = tpm;
#endif	/* __FreeBSD__ */

	return (0);
}

static int
tpm_passthru_execute_cmd(void *sc, void *cmd, uint32_t cmd_size, void *rsp,
    uint32_t rsp_size)
{
	struct tpm_passthru *tpm;
	ssize_t len;

	if (rsp_size < (ssize_t)sizeof(struct tpm_resp_hdr)) {
		warn("%s: rsp_size of %u is too small", __func__, rsp_size);
		return (EINVAL);
	}

	tpm = sc;

	len = write(tpm->fd, cmd, cmd_size);
	if (len != cmd_size) {
		warn("%s: cmd write failed (bytes written: %zd / %d)", __func__,
		    len, cmd_size);
		return (EFAULT);
	}

	len = read(tpm->fd, rsp, rsp_size);
	if (len < (ssize_t)sizeof(struct tpm_resp_hdr)) {
		warn("%s: rsp read failed (bytes read: %zd / %d)", __func__,
		    len, rsp_size);
		return (EFAULT);
	}

	return (0);
}

static void
tpm_passthru_deinit(void *sc)
{
	struct tpm_passthru *tpm;

	tpm = sc;
	if (tpm == NULL)
		return;

	if (tpm->fd >= 0)
		close(tpm->fd);

	free(tpm);
}

static const struct tpm_emul tpm_emul_passthru = {
	.name = "passthru",
	.init = tpm_passthru_init,
	.deinit = tpm_passthru_deinit,
	.execute_cmd = tpm_passthru_execute_cmd,
};
TPM_EMUL_SET(tpm_emul_passthru);