|
| 1 | +// + build linux |
| 2 | + |
| 3 | +package vtpmhelper |
| 4 | + |
| 5 | +import ( |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + |
| 9 | + "github.com/opencontainers/runc/libcontainer/configs" |
| 10 | + "github.com/opencontainers/runc/libcontainer/vtpm" |
| 11 | + |
| 12 | + "github.com/opencontainers/runtime-spec/specs-go" |
| 13 | +) |
| 14 | + |
| 15 | +// Create a VTPM |
| 16 | +func CreateVTPM(spec *specs.Spec, config *configs.Config, vtpmdev *specs.VTPM, devnum int, uid int, gid int) error { |
| 17 | + |
| 18 | + vtpm, err := vtpm.NewVTPM(vtpmdev.Statepath, vtpmdev.TPMVersion, vtpmdev.CreateCertificates) |
| 19 | + if err != nil { |
| 20 | + return err |
| 21 | + } |
| 22 | + |
| 23 | + // Start the vTPM process; once stopped, the device pair will |
| 24 | + // also disappear |
| 25 | + err, createdStatepath := vtpm.Start() |
| 26 | + if err != nil { |
| 27 | + return err |
| 28 | + } |
| 29 | + |
| 30 | + hostdev := vtpm.GetTPMDevname() |
| 31 | + major, minor := vtpm.GetMajorMinor() |
| 32 | + |
| 33 | + device := &configs.Device{ |
| 34 | + Type: 'c', |
| 35 | + Path: fmt.Sprintf("/dev/tpm%d", devnum), |
| 36 | + Major: int64(major), |
| 37 | + Minor: int64(minor), |
| 38 | + Permissions: "rwm", |
| 39 | + FileMode: 0600, |
| 40 | + Allow: true, |
| 41 | + Uid: 0, |
| 42 | + Gid: 0, |
| 43 | + } |
| 44 | + |
| 45 | + config.Devices = append(config.Devices, device) |
| 46 | + |
| 47 | + major_p := new(int64) |
| 48 | + *major_p = int64(major) |
| 49 | + minor_p := new(int64) |
| 50 | + *minor_p = int64(minor) |
| 51 | + |
| 52 | + ld := &specs.LinuxDeviceCgroup{ |
| 53 | + Allow: true, |
| 54 | + Type: "c", |
| 55 | + Major: major_p, |
| 56 | + Minor: minor_p, |
| 57 | + Access: "rwm", |
| 58 | + } |
| 59 | + spec.Linux.Resources.Devices = append(spec.Linux.Resources.Devices, *ld) |
| 60 | + |
| 61 | + config.VTPMs = append(config.VTPMs, vtpm) |
| 62 | + |
| 63 | + if uid != 0 { |
| 64 | + // adapt ownership of the device since only root can access it |
| 65 | + if err := os.Chown(hostdev, uid, gid); err != nil { |
| 66 | + vtpm.Stop(createdStatepath) |
| 67 | + return err |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + return nil |
| 72 | +} |
| 73 | + |
| 74 | +func DestroyVTPMs(config *configs.Config) { |
| 75 | + for _, vtpm := range config.VTPMs { |
| 76 | + vtpm.Stop(true) |
| 77 | + } |
| 78 | + config.VTPMs = make([]*vtpm.VTPM, 0) |
| 79 | +} |
0 commit comments