Debian Codegraph @

tpm2/audit.go

raw
1 package tpm2
2
3 import (
4 "bytes"
5 "fmt"
6 "reflect"
7 )
8
9 // CommandAudit represents an audit session for attesting the execution of a
10 // series of commands in the TPM. It is useful for both command and session
11 // auditing.
12 type CommandAudit struct {
13 hash TPMIAlgHash
14 digest []byte
15 }
16
17 // NewAudit initializes a new CommandAudit with the specified hash algorithm.
18 func NewAudit(hash TPMIAlgHash) (*CommandAudit, error) {
19 h, err := hash.Hash()
20 if err != nil {
21 return nil, err
22 }
23 return &CommandAudit{
24 hash: hash,
25 digest: make([]byte, h.Size()),
26 }, nil
27 }
28
29 // AuditCommand extends the audit digest with the given command and response.
30 // Go Generics do not allow type parameters on methods, otherwise this would be
31 // a method on CommandAudit.
32 // See https://github.com/golang/go/issues/49085 for more information.
33 func AuditCommand[C Command[R, *R], R any](a *CommandAudit, cmd C, rsp *R) error {
34 cc := cmd.Command()
35 cpHash, err := auditCPHash[R](cc, a.hash, cmd)
36 if err != nil {
37 return err
38 }
39 rpHash, err := auditRPHash(cc, a.hash, rsp)
40 if err != nil {
41 return err
42 }
43 ha, err := a.hash.Hash()
44 if err != nil {
45 return err
46 }
47 h := ha.New()
48 h.Write(a.digest)
49 h.Write(cpHash)
50 h.Write(rpHash)
51 a.digest = h.Sum(nil)
52 return nil
53 }
54
55 // Digest returns the current digest of the audit.
56 func (a *CommandAudit) Digest() []byte {
57 return a.digest
58 }
59
60 // auditCPHash calculates the command parameter hash for a given command with
61 // the given hash algorithm. The command is assumed to not have any decrypt
62 // sessions.
63 func auditCPHash[R any](cc TPMCC, h TPMIAlgHash, c Command[R, *R]) ([]byte, error) {
64 names, err := cmdNames(c)
65 if err != nil {
66 return nil, err
67 }
68 parms, err := cmdParameters(c, nil)
69 if err != nil {
70 return nil, err
71 }
72 return cpHash(h, cc, names, parms)
73 }
74
75 // auditRPHash calculates the response parameter hash for a given response with
76 // the given hash algorithm. The command is assumed to be successful and to not
77 // have any encrypt sessions.
78 func auditRPHash(cc TPMCC, h TPMIAlgHash, r any) ([]byte, error) {
79 var parms bytes.Buffer
80 parameters := taggedMembers(reflect.ValueOf(r).Elem(), "handle", true)
81 for i, parameter := range parameters {
82 if err := marshal(&parms, parameter); err != nil {
83 return nil, fmt.Errorf("marshalling parameter %v: %w", i+1, err)
84 }
85 }
86 return rpHash(h, TPMRCSuccess, cc, parms.Bytes())
87 }