| 1 |
package tpm2 |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"crypto/aes" |
| 6 |
"crypto/cipher" |
| 7 |
"crypto/hmac" |
| 8 |
"crypto/rand" |
| 9 |
"encoding/binary" |
| 10 |
"fmt" |
| 11 |
|
| 12 |
"github.com/google/go-tpm/tpm2/transport" |
| 13 |
) |
| 14 |
|
| 15 |
// Session represents a session in the TPM. |
| 16 |
type Session interface { |
| 17 |
// Initializes the session, if needed. Has no effect if not needed or |
| 18 |
// already done. Some types of sessions may need to be initialized |
| 19 |
// just-in-time, e.g., to support calling patterns that help the user |
| 20 |
// securely authorize their actions without writing a lot of code. |
| 21 |
Init(tpm transport.TPM) error |
| 22 |
// Cleans up the session, if needed. |
| 23 |
// Some types of session need to be cleaned up if the command failed, |
| 24 |
// again to support calling patterns that help the user securely |
| 25 |
// authorize their actions without writing a lot of code. |
| 26 |
CleanupFailure(tpm transport.TPM) error |
| 27 |
// The last nonceTPM for this session. |
| 28 |
NonceTPM() TPM2BNonce |
| 29 |
// Updates nonceCaller to a new random value. |
| 30 |
NewNonceCaller() error |
| 31 |
// Computes the authorization HMAC for the session. |
| 32 |
// If this is the first authorization session for a command, and |
| 33 |
// there is another session (or sessions) for parameter |
| 34 |
// decryption and/or encryption, then addNonces contains the |
| 35 |
// nonceTPMs from each of them, respectively (see Part 1, 19.6.5) |
| 36 |
Authorize(cc TPMCC, parms, addNonces []byte, names []TPM2BName, authIndex int) (*TPMSAuthCommand, error) |
| 37 |
// Validates the response for the session. |
| 38 |
// Updates NonceTPM for the session. |
| 39 |
Validate(rc TPMRC, cc TPMCC, parms []byte, names []TPM2BName, authIndex int, auth *TPMSAuthResponse) error |
| 40 |
// Returns true if this is an encryption session. |
| 41 |
IsEncryption() bool |
| 42 |
// Returns true if this is a decryption session. |
| 43 |
IsDecryption() bool |
| 44 |
// If this session is used for parameter decryption, encrypts the |
| 45 |
// parameter. Otherwise, does not modify the parameter. |
| 46 |
Encrypt(parameter []byte) error |
| 47 |
// If this session is used for parameter encryption, encrypts the |
| 48 |
// parameter. Otherwise, does not modify the parameter. |
| 49 |
Decrypt(parameter []byte) error |
| 50 |
// Returns the handle value of this session. |
| 51 |
Handle() TPMHandle |
| 52 |
} |
| 53 |
|
| 54 |
// CPHash calculates the TPM command parameter hash for a given Command. |
| 55 |
// N.B. Authorization sessions on handles are ignored, but names aren't. |
| 56 |
func CPHash[R any](alg TPMIAlgHash, cmd Command[R, *R]) (*TPM2BDigest, error) { |
| 57 |
cc := cmd.Command() |
| 58 |
names, err := cmdNames(cmd) |
| 59 |
if err != nil { |
| 60 |
return nil, err |
| 61 |
} |
| 62 |
parms, err := cmdParameters(cmd, nil) |
| 63 |
if err != nil { |
| 64 |
return nil, err |
| 65 |
} |
| 66 |
digest, err := cpHash(alg, cc, names, parms) |
| 67 |
if err != nil { |
| 68 |
return nil, err |
| 69 |
} |
| 70 |
return &TPM2BDigest{ |
| 71 |
Buffer: digest, |
| 72 |
}, nil |
| 73 |
} |
| 74 |
|
| 75 |
// pwSession represents a password-pseudo-session. |
| 76 |
type pwSession struct { |
| 77 |
auth []byte |
| 78 |
} |
| 79 |
|
| 80 |
// PasswordAuth assembles a password pseudo-session with the given auth value. |
| 81 |
func PasswordAuth(auth []byte) Session { |
| 82 |
return &pwSession{ |
| 83 |
auth: auth, |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
// Init is not required and has no effect for a password session. |
| 88 |
func (s *pwSession) Init(_ transport.TPM) error { return nil } |
| 89 |
|
| 90 |
// Cleanup is not required and has no effect for a password session. |
| 91 |
func (s *pwSession) CleanupFailure(_ transport.TPM) error { return nil } |
| 92 |
|
| 93 |
// NonceTPM normally returns the last nonceTPM value from the session. |
| 94 |
// Since a password session is a pseudo-session with the auth value stuffed |
| 95 |
// in where the HMAC should go, this is not used. |
| 96 |
func (s *pwSession) NonceTPM() TPM2BNonce { return TPM2BNonce{} } |
| 97 |
|
| 98 |
// NewNonceCaller updates the nonceCaller for this session. |
| 99 |
// Password sessions don't have nonces. |
| 100 |
func (s *pwSession) NewNonceCaller() error { return nil } |
| 101 |
|
| 102 |
// Computes the authorization structure for the session. |
| 103 |
func (s *pwSession) Authorize(_ TPMCC, _, _ []byte, _ []TPM2BName, _ int) (*TPMSAuthCommand, error) { |
| 104 |
return &TPMSAuthCommand{ |
| 105 |
Handle: TPMRSPW, |
| 106 |
Nonce: TPM2BNonce{}, |
| 107 |
Attributes: TPMASession{}, |
| 108 |
Authorization: TPM2BData{ |
| 109 |
Buffer: s.auth, |
| 110 |
}, |
| 111 |
}, nil |
| 112 |
} |
| 113 |
|
| 114 |
// Validates the response session structure for the session. |
| 115 |
func (s *pwSession) Validate(_ TPMRC, _ TPMCC, _ []byte, _ []TPM2BName, _ int, auth *TPMSAuthResponse) error { |
| 116 |
if len(auth.Nonce.Buffer) != 0 { |
| 117 |
return fmt.Errorf("expected empty nonce in response auth to PW session, got %x", auth.Nonce) |
| 118 |
} |
| 119 |
expectedAttrs := TPMASession{ |
| 120 |
ContinueSession: true, |
| 121 |
} |
| 122 |
if auth.Attributes != expectedAttrs { |
| 123 |
return fmt.Errorf("expected only ContinueSession in response auth to PW session, got %v", auth.Attributes) |
| 124 |
} |
| 125 |
if len(auth.Authorization.Buffer) != 0 { |
| 126 |
return fmt.Errorf("expected empty HMAC in response auth to PW session, got %x", auth.Authorization) |
| 127 |
} |
| 128 |
return nil |
| 129 |
} |
| 130 |
|
| 131 |
// IsEncryption returns true if this is an encryption session. |
| 132 |
// Password sessions can't be used for encryption. |
| 133 |
func (s *pwSession) IsEncryption() bool { return false } |
| 134 |
|
| 135 |
// IsDecryption returns true if this is a decryption session. |
| 136 |
// Password sessions can't be used for decryption. |
| 137 |
func (s *pwSession) IsDecryption() bool { return false } |
| 138 |
|
| 139 |
// If this session is used for parameter decryption, encrypts the |
| 140 |
// parameter. Otherwise, does not modify the parameter. |
| 141 |
// Password sessions can't be used for decryption. |
| 142 |
func (s *pwSession) Encrypt(_ []byte) error { return nil } |
| 143 |
|
| 144 |
// If this session is used for parameter encryption, encrypts the |
| 145 |
// parameter. Otherwise, does not modify the parameter. |
| 146 |
// Password sessions can't be used for encryption. |
| 147 |
func (s *pwSession) Decrypt(_ []byte) error { return nil } |
| 148 |
|
| 149 |
// Handle returns the handle value associated with this session. |
| 150 |
// In the case of a password session, this is always TPM_RS_PW. |
| 151 |
func (s *pwSession) Handle() TPMHandle { return TPMRSPW } |
| 152 |
|
| 153 |
// cpHash calculates the TPM command parameter hash. |
| 154 |
// cpHash = hash(CC || names || parms) |
| 155 |
func cpHash(alg TPMIAlgHash, cc TPMCC, names []TPM2BName, parms []byte) ([]byte, error) { |
| 156 |
ha, err := alg.Hash() |
| 157 |
if err != nil { |
| 158 |
return nil, err |
| 159 |
} |
| 160 |
h := ha.New() |
| 161 |
binary.Write(h, binary.BigEndian, cc) |
| 162 |
for _, name := range names { |
| 163 |
h.Write(name.Buffer) |
| 164 |
} |
| 165 |
h.Write(parms) |
| 166 |
return h.Sum(nil), nil |
| 167 |
} |
| 168 |
|
| 169 |
// rpHash calculates the TPM response parameter hash. |
| 170 |
// rpHash = hash(RC || CC || parms) |
| 171 |
func rpHash(alg TPMIAlgHash, rc TPMRC, cc TPMCC, parms []byte) ([]byte, error) { |
| 172 |
ha, err := alg.Hash() |
| 173 |
if err != nil { |
| 174 |
return nil, err |
| 175 |
} |
| 176 |
h := ha.New() |
| 177 |
binary.Write(h, binary.BigEndian, rc) |
| 178 |
binary.Write(h, binary.BigEndian, cc) |
| 179 |
h.Write(parms) |
| 180 |
return h.Sum(nil), nil |
| 181 |
} |
| 182 |
|
| 183 |
// sessionOptions represents extra options used when setting up an HMAC or policy session. |
| 184 |
type sessionOptions struct { |
| 185 |
auth []byte |
| 186 |
password bool |
| 187 |
bindHandle TPMIDHEntity |
| 188 |
bindName TPM2BName |
| 189 |
bindAuth []byte |
| 190 |
saltHandle TPMIDHObject |
| 191 |
saltPub TPMTPublic |
| 192 |
attrs TPMASession |
| 193 |
symmetric TPMTSymDef |
| 194 |
trialPolicy bool |
| 195 |
} |
| 196 |
|
| 197 |
// defaultOptions represents the default options used when none are provided. |
| 198 |
func defaultOptions() sessionOptions { |
| 199 |
return sessionOptions{ |
| 200 |
symmetric: TPMTSymDef{ |
| 201 |
Algorithm: TPMAlgNull, |
| 202 |
}, |
| 203 |
bindHandle: TPMRHNull, |
| 204 |
saltHandle: TPMRHNull, |
| 205 |
} |
| 206 |
} |
| 207 |
|
| 208 |
// AuthOption is an option for setting up an auth session variadically. |
| 209 |
type AuthOption func(*sessionOptions) |
| 210 |
|
| 211 |
// Auth uses the session to prove knowledge of the object's auth value. |
| 212 |
func Auth(auth []byte) AuthOption { |
| 213 |
return func(o *sessionOptions) { |
| 214 |
o.auth = auth |
| 215 |
} |
| 216 |
} |
| 217 |
|
| 218 |
// Password is a policy-session-only option that specifies to provide the |
| 219 |
// object's auth value in place of the authorization HMAC when authorizing. |
| 220 |
// For HMAC sessions, has the same effect as using Auth. |
| 221 |
// Deprecated: This is not recommended and is only provided for completeness; |
| 222 |
// use Auth instead. |
| 223 |
func Password(auth []byte) AuthOption { |
| 224 |
return func(o *sessionOptions) { |
| 225 |
o.auth = auth |
| 226 |
o.password = true |
| 227 |
} |
| 228 |
} |
| 229 |
|
| 230 |
// Bound specifies that this session's session key should depend on the auth |
| 231 |
// value of the given object. |
| 232 |
func Bound(handle TPMIDHEntity, name TPM2BName, auth []byte) AuthOption { |
| 233 |
return func(o *sessionOptions) { |
| 234 |
o.bindHandle = handle |
| 235 |
o.bindName = name |
| 236 |
o.bindAuth = auth |
| 237 |
} |
| 238 |
} |
| 239 |
|
| 240 |
// Salted specifies that this session's session key should depend on an |
| 241 |
// encrypted seed value using the given public key. |
| 242 |
// 'handle' must refer to a loaded RSA or ECC key. |
| 243 |
func Salted(handle TPMIDHObject, pub TPMTPublic) AuthOption { |
| 244 |
return func(o *sessionOptions) { |
| 245 |
o.saltHandle = handle |
| 246 |
o.saltPub = pub |
| 247 |
} |
| 248 |
} |
| 249 |
|
| 250 |
// parameterEncryptiontpm2ion specifies whether the session-encrypted |
| 251 |
// parameters are encrypted on the way into the TPM, out of the TPM, or both. |
| 252 |
type parameterEncryptiontpm2ion int |
| 253 |
|
| 254 |
const ( |
| 255 |
// EncryptIn specifies a decrypt session. |
| 256 |
EncryptIn parameterEncryptiontpm2ion = 1 + iota |
| 257 |
// EncryptOut specifies an encrypt session. |
| 258 |
EncryptOut |
| 259 |
// EncryptInOut specifies a decrypt+encrypt session. |
| 260 |
EncryptInOut |
| 261 |
) |
| 262 |
|
| 263 |
// AESEncryption uses the session to encrypt the first parameter sent to/from |
| 264 |
// the TPM. |
| 265 |
// Note that only commands whose first command/response parameter is a 2B can |
| 266 |
// support session encryption. |
| 267 |
func AESEncryption(keySize TPMKeyBits, dir parameterEncryptiontpm2ion) AuthOption { |
| 268 |
return func(o *sessionOptions) { |
| 269 |
o.attrs.Decrypt = (dir == EncryptIn || dir == EncryptInOut) |
| 270 |
o.attrs.Encrypt = (dir == EncryptOut || dir == EncryptInOut) |
| 271 |
o.symmetric = TPMTSymDef{ |
| 272 |
Algorithm: TPMAlgAES, |
| 273 |
KeyBits: NewTPMUSymKeyBits( |
| 274 |
TPMAlgAES, |
| 275 |
TPMKeyBits(keySize), |
| 276 |
), |
| 277 |
Mode: NewTPMUSymMode( |
| 278 |
TPMAlgAES, |
| 279 |
TPMAlgCFB, |
| 280 |
), |
| 281 |
} |
| 282 |
} |
| 283 |
} |
| 284 |
|
| 285 |
// Audit uses the session to compute extra HMACs. |
| 286 |
// An Audit session can be used with GetSessionAuditDigest to obtain attestation |
| 287 |
// over a sequence of commands. |
| 288 |
func Audit() AuthOption { |
| 289 |
return func(o *sessionOptions) { |
| 290 |
o.attrs.Audit = true |
| 291 |
} |
| 292 |
} |
| 293 |
|
| 294 |
// AuditExclusive is like an audit session, but even more powerful. |
| 295 |
// This allows an audit session to additionally indicate that no other auditable |
| 296 |
// commands were executed other than the ones described by the audit hash. |
| 297 |
func AuditExclusive() AuthOption { |
| 298 |
return func(o *sessionOptions) { |
| 299 |
o.attrs.Audit = true |
| 300 |
o.attrs.AuditExclusive = true |
| 301 |
} |
| 302 |
} |
| 303 |
|
| 304 |
// Trial indicates that the policy session should be in trial-mode. |
| 305 |
// This allows using the TPM to calculate policy hashes. |
| 306 |
// This option has no effect on non-Policy sessions. |
| 307 |
func Trial() AuthOption { |
| 308 |
return func(o *sessionOptions) { |
| 309 |
o.trialPolicy = true |
| 310 |
} |
| 311 |
} |
| 312 |
|
| 313 |
// hmacSession generally implements the HMAC session. |
| 314 |
type hmacSession struct { |
| 315 |
sessionOptions |
| 316 |
hash TPMIAlgHash |
| 317 |
nonceSize int |
| 318 |
handle TPMHandle |
| 319 |
sessionKey []byte |
| 320 |
// last nonceCaller |
| 321 |
nonceCaller TPM2BNonce |
| 322 |
// last nonceTPM |
| 323 |
nonceTPM TPM2BNonce |
| 324 |
} |
| 325 |
|
| 326 |
// HMAC sets up a just-in-time HMAC session that is used only once. |
| 327 |
// A real session is created, but just in time and it is flushed when used. |
| 328 |
func HMAC(hash TPMIAlgHash, nonceSize int, opts ...AuthOption) Session { |
| 329 |
// Set up a one-off session that knows the auth value. |
| 330 |
sess := hmacSession{ |
| 331 |
sessionOptions: defaultOptions(), |
| 332 |
hash: hash, |
| 333 |
nonceSize: nonceSize, |
| 334 |
handle: TPMRHNull, |
| 335 |
} |
| 336 |
for _, opt := range opts { |
| 337 |
opt(&sess.sessionOptions) |
| 338 |
} |
| 339 |
return &sess |
| 340 |
} |
| 341 |
|
| 342 |
// HMACSession sets up a reusable HMAC session that needs to be closed. |
| 343 |
func HMACSession(t transport.TPM, hash TPMIAlgHash, nonceSize int, opts ...AuthOption) (s Session, close func() error, err error) { |
| 344 |
// Set up a not-one-off session that knows the auth value. |
| 345 |
sess := hmacSession{ |
| 346 |
sessionOptions: defaultOptions(), |
| 347 |
hash: hash, |
| 348 |
nonceSize: nonceSize, |
| 349 |
handle: TPMRHNull, |
| 350 |
} |
| 351 |
for _, opt := range opts { |
| 352 |
opt(&sess.sessionOptions) |
| 353 |
} |
| 354 |
// This session is reusable and is closed with the function we'll |
| 355 |
// return. |
| 356 |
sess.sessionOptions.attrs.ContinueSession = true |
| 357 |
|
| 358 |
// Initialize the session. |
| 359 |
if err := sess.Init(t); err != nil { |
| 360 |
return nil, nil, err |
| 361 |
} |
| 362 |
|
| 363 |
closer := func() error { |
| 364 |
_, err := (&FlushContext{FlushHandle: sess.handle}).Execute(t) |
| 365 |
return err |
| 366 |
} |
| 367 |
|
| 368 |
return &sess, closer, nil |
| 369 |
} |
| 370 |
|
| 371 |
// getEncryptedSalt creates a salt value for salted sessions. |
| 372 |
// Returns the encrypted salt and plaintext salt, or an error value. |
| 373 |
func getEncryptedSalt(pub TPMTPublic) (*TPM2BEncryptedSecret, []byte, error) { |
| 374 |
key, err := ImportEncapsulationKey(&pub) |
| 375 |
if err != nil { |
| 376 |
return nil, nil, err |
| 377 |
} |
| 378 |
salt, encSalt, err := CreateEncryptedSalt(rand.Reader, key) |
| 379 |
if err != nil { |
| 380 |
return nil, nil, err |
| 381 |
} |
| 382 |
return &TPM2BEncryptedSecret{ |
| 383 |
Buffer: encSalt, |
| 384 |
}, salt, nil |
| 385 |
} |
| 386 |
|
| 387 |
// Init initializes the session, just in time, if needed. |
| 388 |
func (s *hmacSession) Init(t transport.TPM) error { |
| 389 |
if s.handle != TPMRHNull { |
| 390 |
// Session is already initialized. |
| 391 |
return nil |
| 392 |
} |
| 393 |
|
| 394 |
// Get a high-quality nonceCaller for our use. |
| 395 |
// Store it with the session object for later reference. |
| 396 |
s.nonceCaller = TPM2BNonce{ |
| 397 |
Buffer: make([]byte, s.nonceSize), |
| 398 |
} |
| 399 |
if _, err := rand.Read(s.nonceCaller.Buffer); err != nil { |
| 400 |
return err |
| 401 |
} |
| 402 |
|
| 403 |
// Start up the actual auth session. |
| 404 |
sasCmd := StartAuthSession{ |
| 405 |
TPMKey: s.saltHandle, |
| 406 |
Bind: s.bindHandle, |
| 407 |
NonceCaller: s.nonceCaller, |
| 408 |
SessionType: TPMSEHMAC, |
| 409 |
Symmetric: s.symmetric, |
| 410 |
AuthHash: s.hash, |
| 411 |
} |
| 412 |
var salt []byte |
| 413 |
if s.saltHandle != TPMRHNull { |
| 414 |
var err error |
| 415 |
var encSalt *TPM2BEncryptedSecret |
| 416 |
encSalt, salt, err = getEncryptedSalt(s.saltPub) |
| 417 |
if err != nil { |
| 418 |
return err |
| 419 |
} |
| 420 |
sasCmd.EncryptedSalt = *encSalt |
| 421 |
} |
| 422 |
sasRsp, err := sasCmd.Execute(t) |
| 423 |
if err != nil { |
| 424 |
return err |
| 425 |
} |
| 426 |
s.handle = TPMHandle(sasRsp.SessionHandle.HandleValue()) |
| 427 |
s.nonceTPM = sasRsp.NonceTPM |
| 428 |
// Part 1, 19.6 |
| 429 |
ha, err := s.hash.Hash() |
| 430 |
if err != nil { |
| 431 |
return err |
| 432 |
} |
| 433 |
if s.bindHandle != TPMRHNull || len(salt) != 0 { |
| 434 |
var authSalt []byte |
| 435 |
authSalt = append(authSalt, s.bindAuth...) |
| 436 |
authSalt = append(authSalt, salt...) |
| 437 |
s.sessionKey = KDFa(ha, authSalt, "ATH", s.nonceTPM.Buffer, s.nonceCaller.Buffer, ha.Size()*8) |
| 438 |
} |
| 439 |
return nil |
| 440 |
} |
| 441 |
|
| 442 |
// Cleanup cleans up the session, if needed. |
| 443 |
func (s *hmacSession) CleanupFailure(t transport.TPM) error { |
| 444 |
// The user is already responsible to clean up this session. |
| 445 |
if s.attrs.ContinueSession { |
| 446 |
return nil |
| 447 |
} |
| 448 |
fc := FlushContext{FlushHandle: s.handle} |
| 449 |
if _, err := fc.Execute(t); err != nil { |
| 450 |
return err |
| 451 |
} |
| 452 |
s.handle = TPMRHNull |
| 453 |
return nil |
| 454 |
} |
| 455 |
|
| 456 |
// NonceTPM returns the last nonceTPM value from the session. |
| 457 |
// May be nil, if the session hasn't been initialized yet. |
| 458 |
func (s *hmacSession) NonceTPM() TPM2BNonce { return s.nonceTPM } |
| 459 |
|
| 460 |
// To avoid a circular dependency on gotpm by tpm2, implement a |
| 461 |
// tiny serialization by hand for TPMASession here |
| 462 |
func attrsToBytes(attrs TPMASession) []byte { |
| 463 |
var res byte |
| 464 |
if attrs.ContinueSession { |
| 465 |
res |= (1 << 0) |
| 466 |
} |
| 467 |
if attrs.AuditExclusive { |
| 468 |
res |= (1 << 1) |
| 469 |
} |
| 470 |
if attrs.AuditReset { |
| 471 |
res |= (1 << 2) |
| 472 |
} |
| 473 |
if attrs.Decrypt { |
| 474 |
res |= (1 << 5) |
| 475 |
} |
| 476 |
if attrs.Encrypt { |
| 477 |
res |= (1 << 6) |
| 478 |
} |
| 479 |
if attrs.Audit { |
| 480 |
res |= (1 << 7) |
| 481 |
} |
| 482 |
return []byte{res} |
| 483 |
} |
| 484 |
|
| 485 |
// computeHMAC computes an authorization HMAC according to various equations in |
| 486 |
// Part 1. |
| 487 |
// This applies to both commands and responses. |
| 488 |
// The value of key depends on whether the session is bound and/or salted. |
| 489 |
// pHash cpHash for a command, or an rpHash for a response. |
| 490 |
// nonceNewer in a command is the new nonceCaller sent in the command session packet. |
| 491 |
// nonceNewer in a response is the new nonceTPM sent in the response session packet. |
| 492 |
// nonceOlder in a command is the last nonceTPM sent by the TPM for this session. |
| 493 |
// This may be when the session was created, or the last time it was used. |
| 494 |
// nonceOlder in a response is the corresponding nonceCaller sent in the command. |
| 495 |
func computeHMAC(alg TPMIAlgHash, key, pHash, nonceNewer, nonceOlder, addNonces []byte, attrs TPMASession) ([]byte, error) { |
| 496 |
ha, err := alg.Hash() |
| 497 |
if err != nil { |
| 498 |
return nil, err |
| 499 |
} |
| 500 |
mac := hmac.New(ha.New, key) |
| 501 |
mac.Write(pHash) |
| 502 |
mac.Write(nonceNewer) |
| 503 |
mac.Write(nonceOlder) |
| 504 |
mac.Write(addNonces) |
| 505 |
mac.Write(attrsToBytes(attrs)) |
| 506 |
return mac.Sum(nil), nil |
| 507 |
} |
| 508 |
|
| 509 |
// Trim trailing zeros from the auth value. Part 1, 19.6.5, Note 2 |
| 510 |
// Does not allocate a new underlying byte array. |
| 511 |
func hmacKeyFromAuthValue(auth []byte) []byte { |
| 512 |
key := auth |
| 513 |
for i := len(key) - 1; i >= 0; i-- { |
| 514 |
if key[i] == 0 { |
| 515 |
key = key[:i] |
| 516 |
} |
| 517 |
} |
| 518 |
return key |
| 519 |
} |
| 520 |
|
| 521 |
// NewNonceCaller updates the nonceCaller for this session. |
| 522 |
func (s *hmacSession) NewNonceCaller() error { |
| 523 |
_, err := rand.Read(s.nonceCaller.Buffer) |
| 524 |
return err |
| 525 |
} |
| 526 |
|
| 527 |
// Authorize computes the authorization structure for the session. |
| 528 |
// Unlike the TPM spec, authIndex is zero-based. |
| 529 |
func (s *hmacSession) Authorize(cc TPMCC, parms, addNonces []byte, names []TPM2BName, authIndex int) (*TPMSAuthCommand, error) { |
| 530 |
if s.handle == TPMRHNull { |
| 531 |
// Session is not initialized. |
| 532 |
return nil, fmt.Errorf("session not initialized") |
| 533 |
} |
| 534 |
|
| 535 |
// Part 1, 19.6 |
| 536 |
// HMAC key is (sessionKey || auth) unless this session is authorizing |
| 537 |
// its bind target |
| 538 |
var hmacKey []byte |
| 539 |
hmacKey = append(hmacKey, s.sessionKey...) |
| 540 |
if len(s.bindName.Buffer) == 0 || authIndex >= len(names) || !bytes.Equal(names[authIndex].Buffer, s.bindName.Buffer) { |
| 541 |
hmacKey = append(hmacKey, hmacKeyFromAuthValue(s.auth)...) |
| 542 |
} |
| 543 |
|
| 544 |
// Compute the authorization HMAC. |
| 545 |
cph, err := cpHash(s.hash, cc, names, parms) |
| 546 |
if err != nil { |
| 547 |
return nil, err |
| 548 |
} |
| 549 |
hmac, err := computeHMAC(s.hash, hmacKey, cph, s.nonceCaller.Buffer, s.nonceTPM.Buffer, addNonces, s.attrs) |
| 550 |
if err != nil { |
| 551 |
return nil, err |
| 552 |
} |
| 553 |
result := TPMSAuthCommand{ |
| 554 |
Handle: s.handle, |
| 555 |
Nonce: s.nonceCaller, |
| 556 |
Attributes: s.attrs, |
| 557 |
Authorization: TPM2BData{ |
| 558 |
Buffer: hmac, |
| 559 |
}, |
| 560 |
} |
| 561 |
return &result, nil |
| 562 |
} |
| 563 |
|
| 564 |
// Validate validates the response session structure for the session. |
| 565 |
// It updates nonceTPM from the TPM's response. |
| 566 |
func (s *hmacSession) Validate(rc TPMRC, cc TPMCC, parms []byte, names []TPM2BName, authIndex int, auth *TPMSAuthResponse) error { |
| 567 |
// Track the new nonceTPM for the session. |
| 568 |
s.nonceTPM = auth.Nonce |
| 569 |
// Track the session being automatically flushed. |
| 570 |
if !auth.Attributes.ContinueSession { |
| 571 |
s.handle = TPMRHNull |
| 572 |
} |
| 573 |
|
| 574 |
// Part 1, 19.6 |
| 575 |
// HMAC key is (sessionKey || auth) unless this session is authorizing |
| 576 |
// its bind target |
| 577 |
var hmacKey []byte |
| 578 |
hmacKey = append(hmacKey, s.sessionKey...) |
| 579 |
if len(s.bindName.Buffer) == 0 || authIndex >= len(names) || !bytes.Equal(names[authIndex].Buffer, s.bindName.Buffer) { |
| 580 |
hmacKey = append(hmacKey, hmacKeyFromAuthValue(s.auth)...) |
| 581 |
} |
| 582 |
|
| 583 |
// Compute the authorization HMAC. |
| 584 |
rph, err := rpHash(s.hash, rc, cc, parms) |
| 585 |
if err != nil { |
| 586 |
return err |
| 587 |
} |
| 588 |
mac, err := computeHMAC(s.hash, hmacKey, rph, s.nonceTPM.Buffer, s.nonceCaller.Buffer, nil, auth.Attributes) |
| 589 |
if err != nil { |
| 590 |
return err |
| 591 |
} |
| 592 |
// Compare the HMAC (constant time) |
| 593 |
if !hmac.Equal(mac, auth.Authorization.Buffer) { |
| 594 |
return fmt.Errorf("incorrect authorization HMAC") |
| 595 |
} |
| 596 |
return nil |
| 597 |
} |
| 598 |
|
| 599 |
// IsEncryption returns true if this is an encryption session. |
| 600 |
func (s *hmacSession) IsEncryption() bool { |
| 601 |
return s.attrs.Encrypt |
| 602 |
} |
| 603 |
|
| 604 |
// IsDecryption returns true if this is a decryption session. |
| 605 |
func (s *hmacSession) IsDecryption() bool { |
| 606 |
return s.attrs.Decrypt |
| 607 |
} |
| 608 |
|
| 609 |
// Encrypt decrypts the parameter in place, if this session is used for |
| 610 |
// parameter decryption. Otherwise, it does not modify the parameter. |
| 611 |
func (s *hmacSession) Encrypt(parameter []byte) error { |
| 612 |
if !s.IsDecryption() { |
| 613 |
return nil |
| 614 |
} |
| 615 |
// Only AES-CFB is supported. |
| 616 |
bits, err := s.symmetric.KeyBits.AES() |
| 617 |
if err != nil { |
| 618 |
return err |
| 619 |
} |
| 620 |
keyBytes := *bits / 8 |
| 621 |
keyIVBytes := int(keyBytes) + 16 |
| 622 |
var sessionValue []byte |
| 623 |
sessionValue = append(sessionValue, s.sessionKey...) |
| 624 |
sessionValue = append(sessionValue, s.auth...) |
| 625 |
ha, err := s.hash.Hash() |
| 626 |
if err != nil { |
| 627 |
return err |
| 628 |
} |
| 629 |
keyIV := KDFa(ha, sessionValue, "CFB", s.nonceCaller.Buffer, s.nonceTPM.Buffer, keyIVBytes*8) |
| 630 |
key, err := aes.NewCipher(keyIV[:keyBytes]) |
| 631 |
if err != nil { |
| 632 |
return err |
| 633 |
} |
| 634 |
stream := cipher.NewCFBEncrypter(key, keyIV[keyBytes:]) |
| 635 |
stream.XORKeyStream(parameter, parameter) |
| 636 |
return nil |
| 637 |
} |
| 638 |
|
| 639 |
// Decrypt encrypts the parameter in place, if this session is used for |
| 640 |
// parameter encryption. Otherwise, it does not modify the parameter. |
| 641 |
func (s *hmacSession) Decrypt(parameter []byte) error { |
| 642 |
if !s.IsEncryption() { |
| 643 |
return nil |
| 644 |
} |
| 645 |
// Only AES-CFB is supported. |
| 646 |
bits, err := s.symmetric.KeyBits.AES() |
| 647 |
if err != nil { |
| 648 |
return err |
| 649 |
} |
| 650 |
keyBytes := *bits / 8 |
| 651 |
keyIVBytes := int(keyBytes) + 16 |
| 652 |
// Part 1, 21.1 |
| 653 |
var sessionValue []byte |
| 654 |
sessionValue = append(sessionValue, s.sessionKey...) |
| 655 |
sessionValue = append(sessionValue, s.auth...) |
| 656 |
ha, err := s.hash.Hash() |
| 657 |
if err != nil { |
| 658 |
return err |
| 659 |
} |
| 660 |
keyIV := KDFa(ha, sessionValue, "CFB", s.nonceTPM.Buffer, s.nonceCaller.Buffer, keyIVBytes*8) |
| 661 |
key, err := aes.NewCipher(keyIV[:keyBytes]) |
| 662 |
if err != nil { |
| 663 |
return err |
| 664 |
} |
| 665 |
stream := cipher.NewCFBDecrypter(key, keyIV[keyBytes:]) |
| 666 |
stream.XORKeyStream(parameter, parameter) |
| 667 |
return nil |
| 668 |
} |
| 669 |
|
| 670 |
// Handle returns the handle value of the session. |
| 671 |
// If the session is created with HMAC (instead of HMACSession) this will be |
| 672 |
// TPM_RH_NULL. |
| 673 |
func (s *hmacSession) Handle() TPMHandle { |
| 674 |
return s.handle |
| 675 |
} |
| 676 |
|
| 677 |
// PolicyCallback represents an object's policy in the form of a function. |
| 678 |
// This function makes zero or more TPM policy commands and returns error. |
| 679 |
type PolicyCallback = func(tpm transport.TPM, handle TPMISHPolicy, nonceTPM TPM2BNonce) error |
| 680 |
|
| 681 |
// policySession generally implements the policy session. |
| 682 |
type policySession struct { |
| 683 |
sessionOptions |
| 684 |
hash TPMIAlgHash |
| 685 |
nonceSize int |
| 686 |
handle TPMHandle |
| 687 |
sessionKey []byte |
| 688 |
// last nonceCaller |
| 689 |
nonceCaller TPM2BNonce |
| 690 |
// last nonceTPM |
| 691 |
nonceTPM TPM2BNonce |
| 692 |
callback *PolicyCallback |
| 693 |
} |
| 694 |
|
| 695 |
// Policy sets up a just-in-time policy session that created each time it's |
| 696 |
// needed. |
| 697 |
// Each time the policy is created, the callback is invoked to authorize the |
| 698 |
// session. |
| 699 |
// A real session is created, but just in time, and it is flushed when used. |
| 700 |
func Policy(hash TPMIAlgHash, nonceSize int, callback PolicyCallback, opts ...AuthOption) Session { |
| 701 |
// Set up a one-off session that knows the auth value. |
| 702 |
sess := policySession{ |
| 703 |
sessionOptions: defaultOptions(), |
| 704 |
hash: hash, |
| 705 |
nonceSize: nonceSize, |
| 706 |
handle: TPMRHNull, |
| 707 |
callback: &callback, |
| 708 |
} |
| 709 |
for _, opt := range opts { |
| 710 |
opt(&sess.sessionOptions) |
| 711 |
} |
| 712 |
return &sess |
| 713 |
} |
| 714 |
|
| 715 |
// PolicySession opens a policy session that needs to be closed. |
| 716 |
// The caller is responsible to call whichever policy commands they want in the |
| 717 |
// session. |
| 718 |
// Note that the TPM resets a policy session after it is successfully used. |
| 719 |
func PolicySession(t transport.TPM, hash TPMIAlgHash, nonceSize int, opts ...AuthOption) (s Session, close func() error, err error) { |
| 720 |
// Set up a not-one-off session that knows the auth value. |
| 721 |
sess := policySession{ |
| 722 |
sessionOptions: defaultOptions(), |
| 723 |
hash: hash, |
| 724 |
nonceSize: nonceSize, |
| 725 |
handle: TPMRHNull, |
| 726 |
} |
| 727 |
for _, opt := range opts { |
| 728 |
opt(&sess.sessionOptions) |
| 729 |
} |
| 730 |
|
| 731 |
// This session is reusable and is closed with the function we'll |
| 732 |
// return. |
| 733 |
sess.sessionOptions.attrs.ContinueSession = true |
| 734 |
|
| 735 |
// Initialize the session. |
| 736 |
if err := sess.Init(t); err != nil { |
| 737 |
return nil, nil, err |
| 738 |
} |
| 739 |
|
| 740 |
closer := func() error { |
| 741 |
_, err := (&FlushContext{sess.handle}).Execute(t) |
| 742 |
return err |
| 743 |
} |
| 744 |
|
| 745 |
return &sess, closer, nil |
| 746 |
} |
| 747 |
|
| 748 |
// Init initializes the session, just in time, if needed. |
| 749 |
func (s *policySession) Init(t transport.TPM) error { |
| 750 |
if s.handle != TPMRHNull { |
| 751 |
// Session is already initialized. |
| 752 |
return nil |
| 753 |
} |
| 754 |
|
| 755 |
// Get a high-quality nonceCaller for our use. |
| 756 |
// Store it with the session object for later reference. |
| 757 |
s.nonceCaller = TPM2BNonce{ |
| 758 |
Buffer: make([]byte, s.nonceSize), |
| 759 |
} |
| 760 |
if _, err := rand.Read(s.nonceCaller.Buffer); err != nil { |
| 761 |
return err |
| 762 |
} |
| 763 |
|
| 764 |
sessType := TPMSEPolicy |
| 765 |
if s.sessionOptions.trialPolicy { |
| 766 |
sessType = TPMSETrial |
| 767 |
} |
| 768 |
|
| 769 |
// Start up the actual auth session. |
| 770 |
sasCmd := StartAuthSession{ |
| 771 |
TPMKey: s.saltHandle, |
| 772 |
Bind: s.bindHandle, |
| 773 |
NonceCaller: s.nonceCaller, |
| 774 |
SessionType: sessType, |
| 775 |
Symmetric: s.symmetric, |
| 776 |
AuthHash: s.hash, |
| 777 |
} |
| 778 |
var salt []byte |
| 779 |
if s.saltHandle != TPMRHNull { |
| 780 |
var err error |
| 781 |
var encSalt *TPM2BEncryptedSecret |
| 782 |
encSalt, salt, err = getEncryptedSalt(s.saltPub) |
| 783 |
if err != nil { |
| 784 |
return err |
| 785 |
} |
| 786 |
sasCmd.EncryptedSalt = *encSalt |
| 787 |
} |
| 788 |
sasRsp, err := sasCmd.Execute(t) |
| 789 |
if err != nil { |
| 790 |
return err |
| 791 |
} |
| 792 |
s.handle = TPMHandle(sasRsp.SessionHandle.HandleValue()) |
| 793 |
s.nonceTPM = sasRsp.NonceTPM |
| 794 |
// Part 1, 19.6 |
| 795 |
if s.bindHandle != TPMRHNull || len(salt) != 0 { |
| 796 |
var authSalt []byte |
| 797 |
authSalt = append(authSalt, s.bindAuth...) |
| 798 |
authSalt = append(authSalt, salt...) |
| 799 |
ha, err := s.hash.Hash() |
| 800 |
if err != nil { |
| 801 |
return err |
| 802 |
} |
| 803 |
s.sessionKey = KDFa(ha, authSalt, "ATH", s.nonceTPM.Buffer, s.nonceCaller.Buffer, ha.Size()*8) |
| 804 |
} |
| 805 |
|
| 806 |
// Call the callback to execute the policy, if needed |
| 807 |
if s.callback != nil { |
| 808 |
if err := (*s.callback)(t, s.handle, s.nonceTPM); err != nil { |
| 809 |
return fmt.Errorf("executing policy: %w", err) |
| 810 |
} |
| 811 |
} |
| 812 |
|
| 813 |
return nil |
| 814 |
} |
| 815 |
|
| 816 |
// CleanupFailure cleans up the session, if needed. |
| 817 |
func (s *policySession) CleanupFailure(t transport.TPM) error { |
| 818 |
// The user is already responsible to clean up this session. |
| 819 |
if s.attrs.ContinueSession { |
| 820 |
return nil |
| 821 |
} |
| 822 |
fc := FlushContext{FlushHandle: s.handle} |
| 823 |
if _, err := fc.Execute(t); err != nil { |
| 824 |
return err |
| 825 |
} |
| 826 |
s.handle = TPMRHNull |
| 827 |
return nil |
| 828 |
} |
| 829 |
|
| 830 |
// NonceTPM returns the last nonceTPM value from the session. |
| 831 |
// May be nil, if the session hasn't been initialized yet. |
| 832 |
func (s *policySession) NonceTPM() TPM2BNonce { return s.nonceTPM } |
| 833 |
|
| 834 |
// NewNonceCaller updates the nonceCaller for this session. |
| 835 |
func (s *policySession) NewNonceCaller() error { |
| 836 |
_, err := rand.Read(s.nonceCaller.Buffer) |
| 837 |
return err |
| 838 |
} |
| 839 |
|
| 840 |
// Authorize computes the authorization structure for the session. |
| 841 |
func (s *policySession) Authorize(cc TPMCC, parms, addNonces []byte, names []TPM2BName, _ int) (*TPMSAuthCommand, error) { |
| 842 |
if s.handle == TPMRHNull { |
| 843 |
// Session is not initialized. |
| 844 |
return nil, fmt.Errorf("session not initialized") |
| 845 |
} |
| 846 |
|
| 847 |
var hmac []byte |
| 848 |
if s.password { |
| 849 |
hmac = s.auth |
| 850 |
} else { |
| 851 |
// Part 1, 19.6 |
| 852 |
// HMAC key is (sessionKey || auth). |
| 853 |
var hmacKey []byte |
| 854 |
hmacKey = append(hmacKey, s.sessionKey...) |
| 855 |
hmacKey = append(hmacKey, hmacKeyFromAuthValue(s.auth)...) |
| 856 |
|
| 857 |
// Compute the authorization HMAC. |
| 858 |
cph, err := cpHash(s.hash, cc, names, parms) |
| 859 |
if err != nil { |
| 860 |
return nil, err |
| 861 |
} |
| 862 |
hmac, err = computeHMAC(s.hash, hmacKey, cph, s.nonceCaller.Buffer, s.nonceTPM.Buffer, addNonces, s.attrs) |
| 863 |
if err != nil { |
| 864 |
return nil, err |
| 865 |
} |
| 866 |
} |
| 867 |
|
| 868 |
result := TPMSAuthCommand{ |
| 869 |
Handle: s.handle, |
| 870 |
Nonce: s.nonceCaller, |
| 871 |
Attributes: s.attrs, |
| 872 |
Authorization: TPM2BData{ |
| 873 |
Buffer: hmac, |
| 874 |
}, |
| 875 |
} |
| 876 |
return &result, nil |
| 877 |
} |
| 878 |
|
| 879 |
// Validate valitades the response session structure for the session. |
| 880 |
// Updates nonceTPM from the TPM's response. |
| 881 |
func (s *policySession) Validate(rc TPMRC, cc TPMCC, parms []byte, _ []TPM2BName, _ int, auth *TPMSAuthResponse) error { |
| 882 |
// Track the new nonceTPM for the session. |
| 883 |
s.nonceTPM = auth.Nonce |
| 884 |
// Track the session being automatically flushed. |
| 885 |
if !auth.Attributes.ContinueSession { |
| 886 |
s.handle = TPMRHNull |
| 887 |
} |
| 888 |
|
| 889 |
if s.password { |
| 890 |
// If we used a password, expect no nonce and no response HMAC. |
| 891 |
if len(auth.Nonce.Buffer) != 0 { |
| 892 |
return fmt.Errorf("expected empty nonce in response auth to PW policy, got %x", auth.Nonce) |
| 893 |
} |
| 894 |
if len(auth.Authorization.Buffer) != 0 { |
| 895 |
return fmt.Errorf("expected empty HMAC in response auth to PW policy, got %x", auth.Authorization) |
| 896 |
} |
| 897 |
} else { |
| 898 |
// Part 1, 19.6 |
| 899 |
// HMAC key is (sessionKey || auth). |
| 900 |
var hmacKey []byte |
| 901 |
hmacKey = append(hmacKey, s.sessionKey...) |
| 902 |
hmacKey = append(hmacKey, hmacKeyFromAuthValue(s.auth)...) |
| 903 |
// Compute the authorization HMAC. |
| 904 |
rph, err := rpHash(s.hash, rc, cc, parms) |
| 905 |
if err != nil { |
| 906 |
return err |
| 907 |
} |
| 908 |
mac, err := computeHMAC(s.hash, hmacKey, rph, s.nonceTPM.Buffer, s.nonceCaller.Buffer, nil, auth.Attributes) |
| 909 |
if err != nil { |
| 910 |
return err |
| 911 |
} |
| 912 |
// Compare the HMAC (constant time) |
| 913 |
if !hmac.Equal(mac, auth.Authorization.Buffer) { |
| 914 |
return fmt.Errorf("incorrect authorization HMAC") |
| 915 |
} |
| 916 |
} |
| 917 |
return nil |
| 918 |
} |
| 919 |
|
| 920 |
// IsEncryption returns true if this is an encryption session. |
| 921 |
func (s *policySession) IsEncryption() bool { |
| 922 |
return s.attrs.Encrypt |
| 923 |
} |
| 924 |
|
| 925 |
// IsDecryption returns true if this is a decryption session. |
| 926 |
func (s *policySession) IsDecryption() bool { |
| 927 |
return s.attrs.Decrypt |
| 928 |
} |
| 929 |
|
| 930 |
// Encrypt encrypts the parameter in place, if this session is used for |
| 931 |
// parameter decryption. Otherwise, it does not modify the parameter. |
| 932 |
func (s *policySession) Encrypt(parameter []byte) error { |
| 933 |
if !s.IsDecryption() { |
| 934 |
return nil |
| 935 |
} |
| 936 |
// Only AES-CFB is supported. |
| 937 |
bits, err := s.symmetric.KeyBits.AES() |
| 938 |
if err != nil { |
| 939 |
return err |
| 940 |
} |
| 941 |
keyBytes := *bits / 8 |
| 942 |
keyIVBytes := int(keyBytes) + 16 |
| 943 |
var sessionValue []byte |
| 944 |
sessionValue = append(sessionValue, s.sessionKey...) |
| 945 |
sessionValue = append(sessionValue, s.auth...) |
| 946 |
ha, err := s.hash.Hash() |
| 947 |
if err != nil { |
| 948 |
return err |
| 949 |
} |
| 950 |
keyIV := KDFa(ha, sessionValue, "CFB", s.nonceCaller.Buffer, s.nonceTPM.Buffer, keyIVBytes*8) |
| 951 |
key, err := aes.NewCipher(keyIV[:keyBytes]) |
| 952 |
if err != nil { |
| 953 |
return err |
| 954 |
} |
| 955 |
stream := cipher.NewCFBEncrypter(key, keyIV[keyBytes:]) |
| 956 |
stream.XORKeyStream(parameter, parameter) |
| 957 |
return nil |
| 958 |
} |
| 959 |
|
| 960 |
// Decrypt decrypts the parameter in place, if this session is used for |
| 961 |
// parameter encryption. Otherwise, it does not modify the parameter. |
| 962 |
func (s *policySession) Decrypt(parameter []byte) error { |
| 963 |
if !s.IsEncryption() { |
| 964 |
return nil |
| 965 |
} |
| 966 |
// Only AES-CFB is supported. |
| 967 |
bits, err := s.symmetric.KeyBits.AES() |
| 968 |
if err != nil { |
| 969 |
return err |
| 970 |
} |
| 971 |
keyBytes := *bits / 8 |
| 972 |
keyIVBytes := int(keyBytes) + 16 |
| 973 |
// Part 1, 21.1 |
| 974 |
var sessionValue []byte |
| 975 |
sessionValue = append(sessionValue, s.sessionKey...) |
| 976 |
sessionValue = append(sessionValue, s.auth...) |
| 977 |
ha, err := s.hash.Hash() |
| 978 |
if err != nil { |
| 979 |
return err |
| 980 |
} |
| 981 |
keyIV := KDFa(ha, sessionValue, "CFB", s.nonceTPM.Buffer, s.nonceCaller.Buffer, keyIVBytes*8) |
| 982 |
key, err := aes.NewCipher(keyIV[:keyBytes]) |
| 983 |
if err != nil { |
| 984 |
return err |
| 985 |
} |
| 986 |
stream := cipher.NewCFBDecrypter(key, keyIV[keyBytes:]) |
| 987 |
stream.XORKeyStream(parameter, parameter) |
| 988 |
return nil |
| 989 |
} |
| 990 |
|
| 991 |
// Handle returns the handle value of the session. |
| 992 |
// If the session is created with Policy (instead of PolicySession) this will be |
| 993 |
// TPM_RH_NULL. |
| 994 |
func (s *policySession) Handle() TPMHandle { |
| 995 |
return s.handle |
| 996 |
} |