| 1 |
// Copyright (c) 2018, Google LLC All rights reserved. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
// Package tpm2 supports direct communication with a TPM 2.0 device under Linux. |
| 16 |
package tpm2 |
| 17 |
|
| 18 |
import ( |
| 19 |
"bytes" |
| 20 |
"crypto" |
| 21 |
"fmt" |
| 22 |
"io" |
| 23 |
|
| 24 |
"github.com/google/go-tpm/tpmutil" |
| 25 |
) |
| 26 |
|
| 27 |
// GetRandom gets random bytes from the TPM. |
| 28 |
func GetRandom(rw io.ReadWriter, size uint16) ([]byte, error) { |
| 29 |
resp, err := runCommand(rw, TagNoSessions, CmdGetRandom, size) |
| 30 |
if err != nil { |
| 31 |
return nil, err |
| 32 |
} |
| 33 |
|
| 34 |
var randBytes tpmutil.U16Bytes |
| 35 |
if _, err := tpmutil.Unpack(resp, &randBytes); err != nil { |
| 36 |
return nil, err |
| 37 |
} |
| 38 |
return randBytes, nil |
| 39 |
} |
| 40 |
|
| 41 |
// FlushContext removes an object or session under handle to be removed from |
| 42 |
// the TPM. This must be called for any loaded handle to avoid out-of-memory |
| 43 |
// errors in TPM. |
| 44 |
func FlushContext(rw io.ReadWriter, handle tpmutil.Handle) error { |
| 45 |
_, err := runCommand(rw, TagNoSessions, CmdFlushContext, handle) |
| 46 |
return err |
| 47 |
} |
| 48 |
|
| 49 |
func encodeTPMLPCRSelection(sel ...PCRSelection) ([]byte, error) { |
| 50 |
if len(sel) == 0 { |
| 51 |
return tpmutil.Pack(uint32(0)) |
| 52 |
} |
| 53 |
|
| 54 |
if len(sel) == 1 && len(sel[0].PCRs) == 0 && sel[0].Hash == 0 { |
| 55 |
return tpmutil.Pack(uint32(0)) |
| 56 |
} |
| 57 |
|
| 58 |
// PCR selection is a variable-size bitmask, where position of a set bit is |
| 59 |
// the selected PCR index. |
| 60 |
// Size of the bitmask in bytes is pre-pended. It should be at least |
| 61 |
// sizeOfPCRSelect. |
| 62 |
// |
| 63 |
// For example, selecting PCRs 3 and 9 looks like: |
| 64 |
// size(3) mask mask mask |
| 65 |
// 00000011 00000000 00000001 00000100 |
| 66 |
var retBytes []byte |
| 67 |
for _, s := range sel { |
| 68 |
ts := tpmsPCRSelection{ |
| 69 |
Hash: s.Hash, |
| 70 |
Size: sizeOfPCRSelect, |
| 71 |
PCRs: make(tpmutil.RawBytes, sizeOfPCRSelect), |
| 72 |
} |
| 73 |
|
| 74 |
// s[i].PCRs parameter is indexes of PCRs, convert that to set bits. |
| 75 |
for _, n := range s.PCRs { |
| 76 |
if n >= 8*sizeOfPCRSelect { |
| 77 |
return nil, fmt.Errorf("PCR index %d is out of range (exceeds maximum value %d)", n, 8*sizeOfPCRSelect-1) |
| 78 |
} |
| 79 |
byteNum := n / 8 |
| 80 |
bytePos := byte(1 << byte(n%8)) |
| 81 |
ts.PCRs[byteNum] |= bytePos |
| 82 |
} |
| 83 |
|
| 84 |
tmpBytes, err := tpmutil.Pack(ts) |
| 85 |
if err != nil { |
| 86 |
return nil, err |
| 87 |
} |
| 88 |
|
| 89 |
retBytes = append(retBytes, tmpBytes...) |
| 90 |
} |
| 91 |
tmpSize, err := tpmutil.Pack(uint32(len(sel))) |
| 92 |
if err != nil { |
| 93 |
return nil, err |
| 94 |
} |
| 95 |
retBytes = append(tmpSize, retBytes...) |
| 96 |
|
| 97 |
return retBytes, nil |
| 98 |
} |
| 99 |
|
| 100 |
func decodeTPMLPCRSelection(buf *bytes.Buffer) ([]PCRSelection, error) { |
| 101 |
var count uint32 |
| 102 |
var sel []PCRSelection |
| 103 |
|
| 104 |
// This unpacks buffer which is of type TPMLPCRSelection |
| 105 |
// and returns the count of TPMSPCRSelections. |
| 106 |
if err := tpmutil.UnpackBuf(buf, &count); err != nil { |
| 107 |
return sel, err |
| 108 |
} |
| 109 |
|
| 110 |
var ts tpmsPCRSelection |
| 111 |
for i := 0; i < int(count); i++ { |
| 112 |
var s PCRSelection |
| 113 |
if err := tpmutil.UnpackBuf(buf, &ts.Hash, &ts.Size); err != nil { |
| 114 |
return sel, err |
| 115 |
} |
| 116 |
ts.PCRs = make(tpmutil.RawBytes, ts.Size) |
| 117 |
if _, err := buf.Read(ts.PCRs); err != nil { |
| 118 |
return sel, err |
| 119 |
} |
| 120 |
s.Hash = ts.Hash |
| 121 |
for j := 0; j < int(ts.Size); j++ { |
| 122 |
for k := 0; k < 8; k++ { |
| 123 |
set := ts.PCRs[j] & byte(1<<byte(k)) |
| 124 |
if set == 0 { |
| 125 |
continue |
| 126 |
} |
| 127 |
s.PCRs = append(s.PCRs, 8*j+k) |
| 128 |
} |
| 129 |
} |
| 130 |
sel = append(sel, s) |
| 131 |
} |
| 132 |
if len(sel) == 0 { |
| 133 |
sel = append(sel, PCRSelection{ |
| 134 |
Hash: AlgUnknown, |
| 135 |
}) |
| 136 |
} |
| 137 |
return sel, nil |
| 138 |
} |
| 139 |
|
| 140 |
func decodeOneTPMLPCRSelection(buf *bytes.Buffer) (PCRSelection, error) { |
| 141 |
sels, err := decodeTPMLPCRSelection(buf) |
| 142 |
if err != nil { |
| 143 |
return PCRSelection{}, err |
| 144 |
} |
| 145 |
if len(sels) != 1 { |
| 146 |
return PCRSelection{}, fmt.Errorf("got %d TPMS_PCR_SELECTION items in TPML_PCR_SELECTION, expected 1", len(sels)) |
| 147 |
} |
| 148 |
return sels[0], nil |
| 149 |
} |
| 150 |
|
| 151 |
func decodeReadPCRs(in []byte) (map[int][]byte, error) { |
| 152 |
buf := bytes.NewBuffer(in) |
| 153 |
var updateCounter uint32 |
| 154 |
if err := tpmutil.UnpackBuf(buf, &updateCounter); err != nil { |
| 155 |
return nil, err |
| 156 |
} |
| 157 |
|
| 158 |
sel, err := decodeOneTPMLPCRSelection(buf) |
| 159 |
if err != nil { |
| 160 |
return nil, err |
| 161 |
} |
| 162 |
|
| 163 |
var digestCount uint32 |
| 164 |
if err = tpmutil.UnpackBuf(buf, &digestCount); err != nil { |
| 165 |
return nil, fmt.Errorf("decoding TPML_DIGEST length: %v", err) |
| 166 |
} |
| 167 |
if int(digestCount) != len(sel.PCRs) { |
| 168 |
return nil, fmt.Errorf("received %d PCRs but %d digests", len(sel.PCRs), digestCount) |
| 169 |
} |
| 170 |
|
| 171 |
vals := make(map[int][]byte) |
| 172 |
for _, pcr := range sel.PCRs { |
| 173 |
var val tpmutil.U16Bytes |
| 174 |
if err = tpmutil.UnpackBuf(buf, &val); err != nil { |
| 175 |
return nil, fmt.Errorf("decoding TPML_DIGEST item: %v", err) |
| 176 |
} |
| 177 |
vals[pcr] = val |
| 178 |
} |
| 179 |
return vals, nil |
| 180 |
} |
| 181 |
|
| 182 |
// ReadPCRs reads PCR values from the TPM. |
| 183 |
// This is only a wrapper over TPM2_PCR_Read() call, thus can only return |
| 184 |
// at most 8 PCRs digests. |
| 185 |
func ReadPCRs(rw io.ReadWriter, sel PCRSelection) (map[int][]byte, error) { |
| 186 |
Cmd, err := encodeTPMLPCRSelection(sel) |
| 187 |
if err != nil { |
| 188 |
return nil, err |
| 189 |
} |
| 190 |
resp, err := runCommand(rw, TagNoSessions, CmdPCRRead, tpmutil.RawBytes(Cmd)) |
| 191 |
if err != nil { |
| 192 |
return nil, err |
| 193 |
} |
| 194 |
|
| 195 |
return decodeReadPCRs(resp) |
| 196 |
} |
| 197 |
|
| 198 |
func decodeReadClock(in []byte) (uint64, uint64, error) { |
| 199 |
var curTime, curClock uint64 |
| 200 |
|
| 201 |
if _, err := tpmutil.Unpack(in, &curTime, &curClock); err != nil { |
| 202 |
return 0, 0, err |
| 203 |
} |
| 204 |
return curTime, curClock, nil |
| 205 |
} |
| 206 |
|
| 207 |
// ReadClock returns current clock values from the TPM. |
| 208 |
// |
| 209 |
// First return value is time in milliseconds since TPM was initialized (since |
| 210 |
// system startup). |
| 211 |
// |
| 212 |
// Second return value is time in milliseconds since TPM reset (since Storage |
| 213 |
// Primary Seed is changed). |
| 214 |
func ReadClock(rw io.ReadWriter) (uint64, uint64, error) { |
| 215 |
resp, err := runCommand(rw, TagNoSessions, CmdReadClock) |
| 216 |
if err != nil { |
| 217 |
return 0, 0, err |
| 218 |
} |
| 219 |
return decodeReadClock(resp) |
| 220 |
} |
| 221 |
|
| 222 |
func decodeGetCapability(in []byte) ([]interface{}, bool, error) { |
| 223 |
var moreData byte |
| 224 |
var capReported Capability |
| 225 |
|
| 226 |
buf := bytes.NewBuffer(in) |
| 227 |
if err := tpmutil.UnpackBuf(buf, &moreData, &capReported); err != nil { |
| 228 |
return nil, false, err |
| 229 |
} |
| 230 |
|
| 231 |
switch capReported { |
| 232 |
case CapabilityHandles: |
| 233 |
var numHandles uint32 |
| 234 |
if err := tpmutil.UnpackBuf(buf, &numHandles); err != nil { |
| 235 |
return nil, false, fmt.Errorf("could not unpack handle count: %v", err) |
| 236 |
} |
| 237 |
|
| 238 |
var handles []interface{} |
| 239 |
for i := 0; i < int(numHandles); i++ { |
| 240 |
var handle tpmutil.Handle |
| 241 |
if err := tpmutil.UnpackBuf(buf, &handle); err != nil { |
| 242 |
return nil, false, fmt.Errorf("could not unpack handle: %v", err) |
| 243 |
} |
| 244 |
handles = append(handles, handle) |
| 245 |
} |
| 246 |
return handles, moreData > 0, nil |
| 247 |
case CapabilityAlgs: |
| 248 |
var numAlgs uint32 |
| 249 |
if err := tpmutil.UnpackBuf(buf, &numAlgs); err != nil { |
| 250 |
return nil, false, fmt.Errorf("could not unpack algorithm count: %v", err) |
| 251 |
} |
| 252 |
|
| 253 |
var algs []interface{} |
| 254 |
for i := 0; i < int(numAlgs); i++ { |
| 255 |
var alg AlgorithmDescription |
| 256 |
if err := tpmutil.UnpackBuf(buf, &alg); err != nil { |
| 257 |
return nil, false, fmt.Errorf("could not unpack algorithm description: %v", err) |
| 258 |
} |
| 259 |
algs = append(algs, alg) |
| 260 |
} |
| 261 |
return algs, moreData > 0, nil |
| 262 |
case CapabilityTPMProperties: |
| 263 |
var numProps uint32 |
| 264 |
if err := tpmutil.UnpackBuf(buf, &numProps); err != nil { |
| 265 |
return nil, false, fmt.Errorf("could not unpack fixed properties count: %v", err) |
| 266 |
} |
| 267 |
|
| 268 |
var props []interface{} |
| 269 |
for i := 0; i < int(numProps); i++ { |
| 270 |
var prop TaggedProperty |
| 271 |
if err := tpmutil.UnpackBuf(buf, &prop); err != nil { |
| 272 |
return nil, false, fmt.Errorf("could not unpack tagged property: %v", err) |
| 273 |
} |
| 274 |
props = append(props, prop) |
| 275 |
} |
| 276 |
return props, moreData > 0, nil |
| 277 |
|
| 278 |
case CapabilityPCRs: |
| 279 |
var pcrss []interface{} |
| 280 |
pcrs, err := decodeTPMLPCRSelection(buf) |
| 281 |
if err != nil { |
| 282 |
return nil, false, fmt.Errorf("could not unpack pcr selection: %v", err) |
| 283 |
} |
| 284 |
for i := 0; i < len(pcrs); i++ { |
| 285 |
pcrss = append(pcrss, pcrs[i]) |
| 286 |
} |
| 287 |
|
| 288 |
return pcrss, moreData > 0, nil |
| 289 |
|
| 290 |
default: |
| 291 |
return nil, false, fmt.Errorf("unsupported capability %v", capReported) |
| 292 |
} |
| 293 |
} |
| 294 |
|
| 295 |
// GetCapability returns various information about the TPM state. |
| 296 |
// |
| 297 |
// Currently only CapabilityHandles (list active handles) and CapabilityAlgs |
| 298 |
// (list supported algorithms) are supported. CapabilityHandles will return |
| 299 |
// a []tpmutil.Handle for vals, CapabilityAlgs will return |
| 300 |
// []AlgorithmDescription. |
| 301 |
// |
| 302 |
// moreData is true if the TPM indicated that more data is available. Follow |
| 303 |
// the spec for the capability in question on how to query for more data. |
| 304 |
func GetCapability(rw io.ReadWriter, capa Capability, count, property uint32) (vals []interface{}, moreData bool, err error) { |
| 305 |
resp, err := runCommand(rw, TagNoSessions, CmdGetCapability, capa, property, count) |
| 306 |
if err != nil { |
| 307 |
return nil, false, err |
| 308 |
} |
| 309 |
return decodeGetCapability(resp) |
| 310 |
} |
| 311 |
|
| 312 |
// GetManufacturer returns the manufacturer ID |
| 313 |
func GetManufacturer(rw io.ReadWriter) ([]byte, error) { |
| 314 |
caps, _, err := GetCapability(rw, CapabilityTPMProperties, 1, uint32(Manufacturer)) |
| 315 |
if err != nil { |
| 316 |
return nil, err |
| 317 |
} |
| 318 |
|
| 319 |
prop := caps[0].(TaggedProperty) |
| 320 |
return tpmutil.Pack(prop.Value) |
| 321 |
} |
| 322 |
|
| 323 |
func encodeAuthArea(sections ...AuthCommand) ([]byte, error) { |
| 324 |
var res tpmutil.RawBytes |
| 325 |
for _, s := range sections { |
| 326 |
buf, err := tpmutil.Pack(s) |
| 327 |
if err != nil { |
| 328 |
return nil, err |
| 329 |
} |
| 330 |
res = append(res, buf...) |
| 331 |
} |
| 332 |
|
| 333 |
size, err := tpmutil.Pack(uint32(len(res))) |
| 334 |
if err != nil { |
| 335 |
return nil, err |
| 336 |
} |
| 337 |
|
| 338 |
return concat(size, res) |
| 339 |
} |
| 340 |
|
| 341 |
func encodePCREvent(pcr tpmutil.Handle, eventData []byte) ([]byte, error) { |
| 342 |
ha, err := tpmutil.Pack(pcr) |
| 343 |
if err != nil { |
| 344 |
return nil, err |
| 345 |
} |
| 346 |
auth, err := encodeAuthArea(AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: EmptyAuth}) |
| 347 |
if err != nil { |
| 348 |
return nil, err |
| 349 |
} |
| 350 |
event, err := tpmutil.Pack(tpmutil.U16Bytes(eventData)) |
| 351 |
if err != nil { |
| 352 |
return nil, err |
| 353 |
} |
| 354 |
return concat(ha, auth, event) |
| 355 |
} |
| 356 |
|
| 357 |
// PCREvent writes an update to the specified PCR. |
| 358 |
func PCREvent(rw io.ReadWriter, pcr tpmutil.Handle, eventData []byte) error { |
| 359 |
Cmd, err := encodePCREvent(pcr, eventData) |
| 360 |
if err != nil { |
| 361 |
return err |
| 362 |
} |
| 363 |
_, err = runCommand(rw, TagSessions, CmdPCREvent, tpmutil.RawBytes(Cmd)) |
| 364 |
return err |
| 365 |
} |
| 366 |
|
| 367 |
func encodeSensitiveArea(s tpmsSensitiveCreate) ([]byte, error) { |
| 368 |
// TPMS_SENSITIVE_CREATE |
| 369 |
buf, err := tpmutil.Pack(s) |
| 370 |
if err != nil { |
| 371 |
return nil, err |
| 372 |
} |
| 373 |
// TPM2B_SENSITIVE_CREATE |
| 374 |
return tpmutil.Pack(tpmutil.U16Bytes(buf)) |
| 375 |
} |
| 376 |
|
| 377 |
// encodeCreate works for both TPM2_Create and TPM2_CreatePrimary. |
| 378 |
func encodeCreate(owner tpmutil.Handle, sel PCRSelection, auth AuthCommand, ownerPassword string, sensitiveData []byte, pub Public, outsideInfo []byte) ([]byte, error) { |
| 379 |
parent, err := tpmutil.Pack(owner) |
| 380 |
if err != nil { |
| 381 |
return nil, err |
| 382 |
} |
| 383 |
encodedAuth, err := encodeAuthArea(auth) |
| 384 |
if err != nil { |
| 385 |
return nil, err |
| 386 |
} |
| 387 |
inSensitive, err := encodeSensitiveArea(tpmsSensitiveCreate{ |
| 388 |
UserAuth: []byte(ownerPassword), |
| 389 |
Data: sensitiveData, |
| 390 |
}) |
| 391 |
if err != nil { |
| 392 |
return nil, err |
| 393 |
} |
| 394 |
inPublic, err := pub.Encode() |
| 395 |
if err != nil { |
| 396 |
return nil, err |
| 397 |
} |
| 398 |
publicBlob, err := tpmutil.Pack(tpmutil.U16Bytes(inPublic)) |
| 399 |
if err != nil { |
| 400 |
return nil, err |
| 401 |
} |
| 402 |
outsideInfoBlob, err := tpmutil.Pack(tpmutil.U16Bytes(outsideInfo)) |
| 403 |
if err != nil { |
| 404 |
return nil, err |
| 405 |
} |
| 406 |
creationPCR, err := encodeTPMLPCRSelection(sel) |
| 407 |
if err != nil { |
| 408 |
return nil, err |
| 409 |
} |
| 410 |
return concat( |
| 411 |
parent, |
| 412 |
encodedAuth, |
| 413 |
inSensitive, |
| 414 |
publicBlob, |
| 415 |
outsideInfoBlob, |
| 416 |
creationPCR, |
| 417 |
) |
| 418 |
} |
| 419 |
|
| 420 |
func decodeCreatePrimary(in []byte) (handle tpmutil.Handle, public, creationData, creationHash tpmutil.U16Bytes, ticket Ticket, creationName tpmutil.U16Bytes, err error) { |
| 421 |
var paramSize uint32 |
| 422 |
|
| 423 |
buf := bytes.NewBuffer(in) |
| 424 |
// Handle and auth data. |
| 425 |
if err := tpmutil.UnpackBuf(buf, &handle, ¶mSize); err != nil { |
| 426 |
return 0, nil, nil, nil, Ticket{}, nil, fmt.Errorf("decoding handle, paramSize: %v", err) |
| 427 |
} |
| 428 |
|
| 429 |
if err := tpmutil.UnpackBuf(buf, &public, &creationData, &creationHash, &ticket, &creationName); err != nil { |
| 430 |
return 0, nil, nil, nil, Ticket{}, nil, fmt.Errorf("decoding public, creationData, creationHash, ticket, creationName: %v", err) |
| 431 |
} |
| 432 |
|
| 433 |
if _, err := DecodeCreationData(creationData); err != nil { |
| 434 |
return 0, nil, nil, nil, Ticket{}, nil, fmt.Errorf("parsing CreationData: %v", err) |
| 435 |
} |
| 436 |
return handle, public, creationData, creationHash, ticket, creationName, err |
| 437 |
} |
| 438 |
|
| 439 |
// CreatePrimary initializes the primary key in a given hierarchy. |
| 440 |
// The second return value is the public part of the generated key. |
| 441 |
func CreatePrimary(rw io.ReadWriter, owner tpmutil.Handle, sel PCRSelection, parentPassword, ownerPassword string, p Public) (tpmutil.Handle, crypto.PublicKey, error) { |
| 442 |
hnd, public, _, _, _, _, err := CreatePrimaryEx(rw, owner, sel, parentPassword, ownerPassword, p) |
| 443 |
if err != nil { |
| 444 |
return 0, nil, err |
| 445 |
} |
| 446 |
|
| 447 |
pub, err := DecodePublic(public) |
| 448 |
if err != nil { |
| 449 |
return 0, nil, fmt.Errorf("parsing public: %v", err) |
| 450 |
} |
| 451 |
|
| 452 |
pubKey, err := pub.Key() |
| 453 |
if err != nil { |
| 454 |
return 0, nil, fmt.Errorf("extracting cryto.PublicKey from Public part of primary key: %v", err) |
| 455 |
} |
| 456 |
|
| 457 |
return hnd, pubKey, err |
| 458 |
} |
| 459 |
|
| 460 |
// CreatePrimaryEx initializes the primary key in a given hierarchy. |
| 461 |
// This function differs from CreatePrimary in that all response elements |
| 462 |
// are returned, and they are returned in relatively raw form. |
| 463 |
func CreatePrimaryEx(rw io.ReadWriter, owner tpmutil.Handle, sel PCRSelection, parentPassword, ownerPassword string, pub Public) (keyHandle tpmutil.Handle, public, creationData, creationHash []byte, ticket Ticket, creationName []byte, err error) { |
| 464 |
auth := AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(parentPassword)} |
| 465 |
Cmd, err := encodeCreate(owner, sel, auth, ownerPassword, nil /*inSensitive*/, pub, nil /*OutsideInfo*/) |
| 466 |
if err != nil { |
| 467 |
return 0, nil, nil, nil, Ticket{}, nil, err |
| 468 |
} |
| 469 |
resp, err := runCommand(rw, TagSessions, CmdCreatePrimary, tpmutil.RawBytes(Cmd)) |
| 470 |
if err != nil { |
| 471 |
return 0, nil, nil, nil, Ticket{}, nil, err |
| 472 |
} |
| 473 |
|
| 474 |
return decodeCreatePrimary(resp) |
| 475 |
} |
| 476 |
|
| 477 |
// CreatePrimaryRawTemplate is CreatePrimary, but with the public template |
| 478 |
// (TPMT_PUBLIC) provided pre-encoded. This is commonly used with key templates |
| 479 |
// stored in NV RAM. |
| 480 |
func CreatePrimaryRawTemplate(rw io.ReadWriter, owner tpmutil.Handle, sel PCRSelection, parentPassword, ownerPassword string, public []byte) (tpmutil.Handle, crypto.PublicKey, error) { |
| 481 |
pub, err := DecodePublic(public) |
| 482 |
if err != nil { |
| 483 |
return 0, nil, fmt.Errorf("parsing input template: %v", err) |
| 484 |
} |
| 485 |
return CreatePrimary(rw, owner, sel, parentPassword, ownerPassword, pub) |
| 486 |
} |
| 487 |
|
| 488 |
func decodeReadPublic(in []byte) (Public, []byte, []byte, error) { |
| 489 |
var resp struct { |
| 490 |
Public tpmutil.U16Bytes |
| 491 |
Name tpmutil.U16Bytes |
| 492 |
QualifiedName tpmutil.U16Bytes |
| 493 |
} |
| 494 |
if _, err := tpmutil.Unpack(in, &resp); err != nil { |
| 495 |
return Public{}, nil, nil, err |
| 496 |
} |
| 497 |
pub, err := DecodePublic(resp.Public) |
| 498 |
if err != nil { |
| 499 |
return Public{}, nil, nil, err |
| 500 |
} |
| 501 |
return pub, resp.Name, resp.QualifiedName, nil |
| 502 |
} |
| 503 |
|
| 504 |
// ReadPublic reads the public part of the object under handle. |
| 505 |
// Returns the public data, name and qualified name. |
| 506 |
func ReadPublic(rw io.ReadWriter, handle tpmutil.Handle) (Public, []byte, []byte, error) { |
| 507 |
resp, err := runCommand(rw, TagNoSessions, CmdReadPublic, handle) |
| 508 |
if err != nil { |
| 509 |
return Public{}, nil, nil, err |
| 510 |
} |
| 511 |
|
| 512 |
return decodeReadPublic(resp) |
| 513 |
} |
| 514 |
|
| 515 |
func decodeCreate(in []byte) (private, public, creationData, creationHash tpmutil.U16Bytes, creationTicket Ticket, err error) { |
| 516 |
buf := bytes.NewBuffer(in) |
| 517 |
var paramSize uint32 |
| 518 |
if err := tpmutil.UnpackBuf(buf, ¶mSize, &private, &public, &creationData, &creationHash, &creationTicket); err != nil { |
| 519 |
return nil, nil, nil, nil, Ticket{}, fmt.Errorf("decoding Handle, Private, Public, CreationData, CreationHash, CreationTicket: %v", err) |
| 520 |
} |
| 521 |
if err != nil { |
| 522 |
return nil, nil, nil, nil, Ticket{}, fmt.Errorf("decoding CreationTicket: %v", err) |
| 523 |
} |
| 524 |
if _, err := DecodeCreationData(creationData); err != nil { |
| 525 |
return nil, nil, nil, nil, Ticket{}, fmt.Errorf("decoding CreationData: %v", err) |
| 526 |
} |
| 527 |
return private, public, creationData, creationHash, creationTicket, nil |
| 528 |
} |
| 529 |
|
| 530 |
func create(rw io.ReadWriter, parentHandle tpmutil.Handle, auth AuthCommand, objectPassword string, sensitiveData []byte, pub Public, pcrSelection PCRSelection, outsideInfo []byte) (private, public, creationData, creationHash []byte, creationTicket Ticket, err error) { |
| 531 |
cmd, err := encodeCreate(parentHandle, pcrSelection, auth, objectPassword, sensitiveData, pub, outsideInfo) |
| 532 |
if err != nil { |
| 533 |
return nil, nil, nil, nil, Ticket{}, err |
| 534 |
} |
| 535 |
resp, err := runCommand(rw, TagSessions, CmdCreate, tpmutil.RawBytes(cmd)) |
| 536 |
if err != nil { |
| 537 |
return nil, nil, nil, nil, Ticket{}, err |
| 538 |
} |
| 539 |
return decodeCreate(resp) |
| 540 |
} |
| 541 |
|
| 542 |
// CreateKey creates a new key pair under the owner handle. |
| 543 |
// Returns private key and public key blobs as well as the |
| 544 |
// creation data, a hash of said data and the creation ticket. |
| 545 |
func CreateKey(rw io.ReadWriter, owner tpmutil.Handle, sel PCRSelection, parentPassword, ownerPassword string, pub Public) (private, public, creationData, creationHash []byte, creationTicket Ticket, err error) { |
| 546 |
auth := AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(parentPassword)} |
| 547 |
return create(rw, owner, auth, ownerPassword, nil /*inSensitive*/, pub, sel, nil /*OutsideInfo*/) |
| 548 |
} |
| 549 |
|
| 550 |
// CreateKeyUsingAuth creates a new key pair under the owner handle using the |
| 551 |
// provided AuthCommand. Returns private key and public key blobs as well as |
| 552 |
// the creation data, a hash of said data, and the creation ticket. |
| 553 |
func CreateKeyUsingAuth(rw io.ReadWriter, owner tpmutil.Handle, sel PCRSelection, auth AuthCommand, ownerPassword string, pub Public) (private, public, creationData, creationHash []byte, creationTicket Ticket, err error) { |
| 554 |
return create(rw, owner, auth, ownerPassword, nil /*inSensitive*/, pub, sel, nil /*OutsideInfo*/) |
| 555 |
} |
| 556 |
|
| 557 |
// CreateKeyWithSensitive is very similar to CreateKey, except |
| 558 |
// that it can take in a piece of sensitive data. |
| 559 |
func CreateKeyWithSensitive(rw io.ReadWriter, owner tpmutil.Handle, sel PCRSelection, parentPassword, ownerPassword string, pub Public, sensitive []byte) (private, public, creationData, creationHash []byte, creationTicket Ticket, err error) { |
| 560 |
auth := AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(parentPassword)} |
| 561 |
return create(rw, owner, auth, ownerPassword, sensitive, pub, sel, nil /*OutsideInfo*/) |
| 562 |
} |
| 563 |
|
| 564 |
// CreateKeyWithOutsideInfo is very similar to CreateKey, except |
| 565 |
// that it returns the outside information. |
| 566 |
func CreateKeyWithOutsideInfo(rw io.ReadWriter, owner tpmutil.Handle, sel PCRSelection, parentPassword, ownerPassword string, pub Public, outsideInfo []byte) (private, public, creationData, creationHash []byte, creationTicket Ticket, err error) { |
| 567 |
auth := AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(parentPassword)} |
| 568 |
return create(rw, owner, auth, ownerPassword, nil /*inSensitive*/, pub, sel, outsideInfo) |
| 569 |
} |
| 570 |
|
| 571 |
// Seal creates a data blob object that seals the sensitive data under a parent and with a |
| 572 |
// password and auth policy. Access to the parent must be available with a simple password. |
| 573 |
// Returns private and public portions of the created object. |
| 574 |
func Seal(rw io.ReadWriter, parentHandle tpmutil.Handle, parentPassword, objectPassword string, objectAuthPolicy []byte, sensitiveData []byte) ([]byte, []byte, error) { |
| 575 |
inPublic := Public{ |
| 576 |
Type: AlgKeyedHash, |
| 577 |
NameAlg: AlgSHA256, |
| 578 |
Attributes: FlagFixedTPM | FlagFixedParent, |
| 579 |
AuthPolicy: objectAuthPolicy, |
| 580 |
} |
| 581 |
auth := AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(parentPassword)} |
| 582 |
private, public, _, _, _, err := create(rw, parentHandle, auth, objectPassword, sensitiveData, inPublic, PCRSelection{}, nil /*OutsideInfo*/) |
| 583 |
if err != nil { |
| 584 |
return nil, nil, err |
| 585 |
} |
| 586 |
return private, public, nil |
| 587 |
} |
| 588 |
|
| 589 |
func encodeImport(parentHandle tpmutil.Handle, auth AuthCommand, publicBlob, privateBlob, symSeed, encryptionKey tpmutil.U16Bytes, sym *SymScheme) ([]byte, error) { |
| 590 |
ph, err := tpmutil.Pack(parentHandle) |
| 591 |
if err != nil { |
| 592 |
return nil, err |
| 593 |
} |
| 594 |
encodedAuth, err := encodeAuthArea(auth) |
| 595 |
if err != nil { |
| 596 |
return nil, err |
| 597 |
} |
| 598 |
data, err := tpmutil.Pack(encryptionKey, publicBlob, privateBlob, symSeed) |
| 599 |
if err != nil { |
| 600 |
return nil, err |
| 601 |
} |
| 602 |
encodedScheme, err := sym.encode() |
| 603 |
if err != nil { |
| 604 |
return nil, err |
| 605 |
} |
| 606 |
|
| 607 |
return concat(ph, encodedAuth, data, encodedScheme) |
| 608 |
} |
| 609 |
|
| 610 |
func decodeImport(resp []byte) ([]byte, error) { |
| 611 |
var paramSize uint32 |
| 612 |
var outPrivate tpmutil.U16Bytes |
| 613 |
_, err := tpmutil.Unpack(resp, ¶mSize, &outPrivate) |
| 614 |
return outPrivate, err |
| 615 |
} |
| 616 |
|
| 617 |
// Import allows a user to import a key created on a different computer |
| 618 |
// or in a different TPM. The publicBlob and privateBlob must always be |
| 619 |
// provided. symSeed should be non-nil iff an "outer wrapper" is used. Both of |
| 620 |
// encryptionKey and sym should be non-nil iff an "inner wrapper" is used. |
| 621 |
func Import(rw io.ReadWriter, parentHandle tpmutil.Handle, auth AuthCommand, publicBlob, privateBlob, symSeed, encryptionKey []byte, sym *SymScheme) ([]byte, error) { |
| 622 |
Cmd, err := encodeImport(parentHandle, auth, publicBlob, privateBlob, symSeed, encryptionKey, sym) |
| 623 |
if err != nil { |
| 624 |
return nil, err |
| 625 |
} |
| 626 |
resp, err := runCommand(rw, TagSessions, CmdImport, tpmutil.RawBytes(Cmd)) |
| 627 |
if err != nil { |
| 628 |
return nil, err |
| 629 |
} |
| 630 |
return decodeImport(resp) |
| 631 |
} |
| 632 |
|
| 633 |
func encodeLoad(parentHandle tpmutil.Handle, auth AuthCommand, publicBlob, privateBlob tpmutil.U16Bytes) ([]byte, error) { |
| 634 |
ah, err := tpmutil.Pack(parentHandle) |
| 635 |
if err != nil { |
| 636 |
return nil, err |
| 637 |
} |
| 638 |
encodedAuth, err := encodeAuthArea(auth) |
| 639 |
if err != nil { |
| 640 |
return nil, err |
| 641 |
} |
| 642 |
params, err := tpmutil.Pack(privateBlob, publicBlob) |
| 643 |
if err != nil { |
| 644 |
return nil, err |
| 645 |
} |
| 646 |
return concat(ah, encodedAuth, params) |
| 647 |
} |
| 648 |
|
| 649 |
func decodeLoad(in []byte) (tpmutil.Handle, []byte, error) { |
| 650 |
var handle tpmutil.Handle |
| 651 |
var paramSize uint32 |
| 652 |
var name tpmutil.U16Bytes |
| 653 |
|
| 654 |
if _, err := tpmutil.Unpack(in, &handle, ¶mSize, &name); err != nil { |
| 655 |
return 0, nil, err |
| 656 |
} |
| 657 |
|
| 658 |
// Re-encode the name as a TPM2B_NAME so it can be parsed by DecodeName(). |
| 659 |
b := &bytes.Buffer{} |
| 660 |
if err := name.TPMMarshal(b); err != nil { |
| 661 |
return 0, nil, err |
| 662 |
} |
| 663 |
return handle, b.Bytes(), nil |
| 664 |
} |
| 665 |
|
| 666 |
// Load loads public/private blobs into an object in the TPM. |
| 667 |
// Returns loaded object handle and its name. |
| 668 |
func Load(rw io.ReadWriter, parentHandle tpmutil.Handle, parentAuth string, publicBlob, privateBlob []byte) (tpmutil.Handle, []byte, error) { |
| 669 |
auth := AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(parentAuth)} |
| 670 |
return LoadUsingAuth(rw, parentHandle, auth, publicBlob, privateBlob) |
| 671 |
} |
| 672 |
|
| 673 |
// LoadUsingAuth loads public/private blobs into an object in the TPM using the |
| 674 |
// provided AuthCommand. Returns loaded object handle and its name. |
| 675 |
func LoadUsingAuth(rw io.ReadWriter, parentHandle tpmutil.Handle, auth AuthCommand, publicBlob, privateBlob []byte) (tpmutil.Handle, []byte, error) { |
| 676 |
Cmd, err := encodeLoad(parentHandle, auth, publicBlob, privateBlob) |
| 677 |
if err != nil { |
| 678 |
return 0, nil, err |
| 679 |
} |
| 680 |
resp, err := runCommand(rw, TagSessions, CmdLoad, tpmutil.RawBytes(Cmd)) |
| 681 |
if err != nil { |
| 682 |
return 0, nil, err |
| 683 |
} |
| 684 |
return decodeLoad(resp) |
| 685 |
} |
| 686 |
|
| 687 |
func encodeLoadExternal(pub Public, private Private, hierarchy tpmutil.Handle) ([]byte, error) { |
| 688 |
privateBlob, err := private.Encode() |
| 689 |
if err != nil { |
| 690 |
return nil, err |
| 691 |
} |
| 692 |
publicBlob, err := pub.Encode() |
| 693 |
if err != nil { |
| 694 |
return nil, err |
| 695 |
} |
| 696 |
|
| 697 |
return tpmutil.Pack(tpmutil.U16Bytes(privateBlob), tpmutil.U16Bytes(publicBlob), hierarchy) |
| 698 |
} |
| 699 |
|
| 700 |
func decodeLoadExternal(in []byte) (tpmutil.Handle, []byte, error) { |
| 701 |
var handle tpmutil.Handle |
| 702 |
var name tpmutil.U16Bytes |
| 703 |
|
| 704 |
if _, err := tpmutil.Unpack(in, &handle, &name); err != nil { |
| 705 |
return 0, nil, err |
| 706 |
} |
| 707 |
return handle, name, nil |
| 708 |
} |
| 709 |
|
| 710 |
// LoadExternal loads a public (and optionally a private) key into an object in |
| 711 |
// the TPM. Returns loaded object handle and its name. |
| 712 |
func LoadExternal(rw io.ReadWriter, pub Public, private Private, hierarchy tpmutil.Handle) (tpmutil.Handle, []byte, error) { |
| 713 |
Cmd, err := encodeLoadExternal(pub, private, hierarchy) |
| 714 |
if err != nil { |
| 715 |
return 0, nil, err |
| 716 |
} |
| 717 |
resp, err := runCommand(rw, TagNoSessions, CmdLoadExternal, tpmutil.RawBytes(Cmd)) |
| 718 |
if err != nil { |
| 719 |
return 0, nil, err |
| 720 |
} |
| 721 |
handle, name, err := decodeLoadExternal(resp) |
| 722 |
if err != nil { |
| 723 |
return 0, nil, err |
| 724 |
} |
| 725 |
return handle, name, nil |
| 726 |
} |
| 727 |
|
| 728 |
// PolicyPassword sets password authorization requirement on the object. |
| 729 |
func PolicyPassword(rw io.ReadWriter, handle tpmutil.Handle) error { |
| 730 |
_, err := runCommand(rw, TagNoSessions, CmdPolicyPassword, handle) |
| 731 |
return err |
| 732 |
} |
| 733 |
|
| 734 |
func encodePolicySecret(entityHandle tpmutil.Handle, entityAuth AuthCommand, policyHandle tpmutil.Handle, policyNonce, cpHash, policyRef tpmutil.U16Bytes, expiry int32) ([]byte, error) { |
| 735 |
auth, err := encodeAuthArea(entityAuth) |
| 736 |
if err != nil { |
| 737 |
return nil, err |
| 738 |
} |
| 739 |
handles, err := tpmutil.Pack(entityHandle, policyHandle) |
| 740 |
if err != nil { |
| 741 |
return nil, err |
| 742 |
} |
| 743 |
params, err := tpmutil.Pack(policyNonce, cpHash, policyRef, expiry) |
| 744 |
if err != nil { |
| 745 |
return nil, err |
| 746 |
} |
| 747 |
return concat(handles, auth, params) |
| 748 |
} |
| 749 |
|
| 750 |
func decodePolicySecret(in []byte) ([]byte, *Ticket, error) { |
| 751 |
buf := bytes.NewBuffer(in) |
| 752 |
|
| 753 |
var paramSize uint32 |
| 754 |
var timeout tpmutil.U16Bytes |
| 755 |
if err := tpmutil.UnpackBuf(buf, ¶mSize, &timeout); err != nil { |
| 756 |
return nil, nil, fmt.Errorf("decoding timeout: %v", err) |
| 757 |
} |
| 758 |
var t Ticket |
| 759 |
if err := tpmutil.UnpackBuf(buf, &t); err != nil { |
| 760 |
return nil, nil, fmt.Errorf("decoding ticket: %v", err) |
| 761 |
} |
| 762 |
return timeout, &t, nil |
| 763 |
} |
| 764 |
|
| 765 |
// PolicySecret sets a secret authorization requirement on the provided entity. |
| 766 |
func PolicySecret(rw io.ReadWriter, entityHandle tpmutil.Handle, entityAuth AuthCommand, policyHandle tpmutil.Handle, policyNonce, cpHash, policyRef []byte, expiry int32) ([]byte, *Ticket, error) { |
| 767 |
Cmd, err := encodePolicySecret(entityHandle, entityAuth, policyHandle, policyNonce, cpHash, policyRef, expiry) |
| 768 |
if err != nil { |
| 769 |
return nil, nil, err |
| 770 |
} |
| 771 |
resp, err := runCommand(rw, TagSessions, CmdPolicySecret, tpmutil.RawBytes(Cmd)) |
| 772 |
if err != nil { |
| 773 |
return nil, nil, err |
| 774 |
} |
| 775 |
return decodePolicySecret(resp) |
| 776 |
} |
| 777 |
|
| 778 |
func encodePolicySigned(validationKeyHandle tpmutil.Handle, policyHandle tpmutil.Handle, policyNonce, cpHash, policyRef tpmutil.U16Bytes, expiry int32, auth []byte) ([]byte, error) { |
| 779 |
handles, err := tpmutil.Pack(validationKeyHandle, policyHandle) |
| 780 |
if err != nil { |
| 781 |
return nil, err |
| 782 |
} |
| 783 |
params, err := tpmutil.Pack(policyNonce, cpHash, policyRef, expiry, auth) |
| 784 |
if err != nil { |
| 785 |
return nil, err |
| 786 |
} |
| 787 |
return concat(handles, params) |
| 788 |
} |
| 789 |
|
| 790 |
func decodePolicySigned(in []byte) ([]byte, *Ticket, error) { |
| 791 |
buf := bytes.NewBuffer(in) |
| 792 |
|
| 793 |
var timeout tpmutil.U16Bytes |
| 794 |
if err := tpmutil.UnpackBuf(buf, &timeout); err != nil { |
| 795 |
return nil, nil, fmt.Errorf("decoding timeout: %v", err) |
| 796 |
} |
| 797 |
var t Ticket |
| 798 |
if err := tpmutil.UnpackBuf(buf, &t); err != nil { |
| 799 |
return nil, nil, fmt.Errorf("decoding ticket: %v", err) |
| 800 |
} |
| 801 |
return timeout, &t, nil |
| 802 |
} |
| 803 |
|
| 804 |
// PolicySigned sets a signed authorization requirement on the provided policy. |
| 805 |
func PolicySigned(rw io.ReadWriter, validationKeyHandle tpmutil.Handle, policyHandle tpmutil.Handle, policyNonce, cpHash, policyRef []byte, expiry int32, signedAuth []byte) ([]byte, *Ticket, error) { |
| 806 |
Cmd, err := encodePolicySigned(validationKeyHandle, policyHandle, policyNonce, cpHash, policyRef, expiry, signedAuth) |
| 807 |
if err != nil { |
| 808 |
return nil, nil, err |
| 809 |
} |
| 810 |
resp, err := runCommand(rw, TagNoSessions, CmdPolicySigned, tpmutil.RawBytes(Cmd)) |
| 811 |
if err != nil { |
| 812 |
return nil, nil, err |
| 813 |
} |
| 814 |
return decodePolicySigned(resp) |
| 815 |
} |
| 816 |
|
| 817 |
func encodePolicyPCR(session tpmutil.Handle, expectedDigest tpmutil.U16Bytes, sel PCRSelection) ([]byte, error) { |
| 818 |
params, err := tpmutil.Pack(session, expectedDigest) |
| 819 |
if err != nil { |
| 820 |
return nil, err |
| 821 |
} |
| 822 |
pcrs, err := encodeTPMLPCRSelection(sel) |
| 823 |
if err != nil { |
| 824 |
return nil, err |
| 825 |
} |
| 826 |
return concat(params, pcrs) |
| 827 |
} |
| 828 |
|
| 829 |
// PolicyPCR sets PCR state binding for authorization on a session. |
| 830 |
// |
| 831 |
// expectedDigest is optional. When specified, it's compared against the digest |
| 832 |
// of PCRs matched by sel. |
| 833 |
// |
| 834 |
// Note that expectedDigest must be a *digest* of the expected PCR value. You |
| 835 |
// must compute the digest manually. ReadPCR returns raw PCR values, not their |
| 836 |
// digests. |
| 837 |
// If you wish to select multiple PCRs, concatenate their values before |
| 838 |
// computing the digest. See "TPM 2.0 Part 1, Selecting Multiple PCR". |
| 839 |
func PolicyPCR(rw io.ReadWriter, session tpmutil.Handle, expectedDigest []byte, sel PCRSelection) error { |
| 840 |
Cmd, err := encodePolicyPCR(session, expectedDigest, sel) |
| 841 |
if err != nil { |
| 842 |
return err |
| 843 |
} |
| 844 |
_, err = runCommand(rw, TagNoSessions, CmdPolicyPCR, tpmutil.RawBytes(Cmd)) |
| 845 |
return err |
| 846 |
} |
| 847 |
|
| 848 |
// PolicyOr compares PolicySession→Digest against the list of provided values. |
| 849 |
// If the current Session→Digest does not match any value in the list, |
| 850 |
// the TPM shall return TPM_RC_VALUE. Otherwise, the TPM will reset policySession→Digest |
| 851 |
// to a Zero Digest. Then policySession→Digest is extended by the concatenation of |
| 852 |
// TPM_CC_PolicyOR and the concatenation of all of the digests. |
| 853 |
func PolicyOr(rw io.ReadWriter, session tpmutil.Handle, digests TPMLDigest) error { |
| 854 |
d, err := digests.Encode() |
| 855 |
if err != nil { |
| 856 |
return err |
| 857 |
} |
| 858 |
data, err := tpmutil.Pack(session, d) |
| 859 |
if err != nil { |
| 860 |
return err |
| 861 |
} |
| 862 |
_, err = runCommand(rw, TagNoSessions, CmdPolicyOr, data) |
| 863 |
return err |
| 864 |
} |
| 865 |
|
| 866 |
// PolicyGetDigest returns the current policyDigest of the session. |
| 867 |
func PolicyGetDigest(rw io.ReadWriter, handle tpmutil.Handle) ([]byte, error) { |
| 868 |
resp, err := runCommand(rw, TagNoSessions, CmdPolicyGetDigest, handle) |
| 869 |
if err != nil { |
| 870 |
return nil, err |
| 871 |
} |
| 872 |
|
| 873 |
var digest tpmutil.U16Bytes |
| 874 |
_, err = tpmutil.Unpack(resp, &digest) |
| 875 |
return digest, err |
| 876 |
} |
| 877 |
|
| 878 |
func encodeStartAuthSession(tpmKey, bindKey tpmutil.Handle, nonceCaller, secret tpmutil.U16Bytes, se SessionType, sym, hashAlg Algorithm) ([]byte, error) { |
| 879 |
ha, err := tpmutil.Pack(tpmKey, bindKey) |
| 880 |
if err != nil { |
| 881 |
return nil, err |
| 882 |
} |
| 883 |
params, err := tpmutil.Pack(nonceCaller, secret, se, sym, hashAlg) |
| 884 |
if err != nil { |
| 885 |
return nil, err |
| 886 |
} |
| 887 |
return concat(ha, params) |
| 888 |
} |
| 889 |
|
| 890 |
func decodeStartAuthSession(in []byte) (tpmutil.Handle, []byte, error) { |
| 891 |
var handle tpmutil.Handle |
| 892 |
var nonce tpmutil.U16Bytes |
| 893 |
if _, err := tpmutil.Unpack(in, &handle, &nonce); err != nil { |
| 894 |
return 0, nil, err |
| 895 |
} |
| 896 |
return handle, nonce, nil |
| 897 |
} |
| 898 |
|
| 899 |
// StartAuthSession initializes a session object. |
| 900 |
// Returns session handle and the initial nonce from the TPM. |
| 901 |
func StartAuthSession(rw io.ReadWriter, tpmKey, bindKey tpmutil.Handle, nonceCaller, secret []byte, se SessionType, sym, hashAlg Algorithm) (tpmutil.Handle, []byte, error) { |
| 902 |
Cmd, err := encodeStartAuthSession(tpmKey, bindKey, nonceCaller, secret, se, sym, hashAlg) |
| 903 |
if err != nil { |
| 904 |
return 0, nil, err |
| 905 |
} |
| 906 |
resp, err := runCommand(rw, TagNoSessions, CmdStartAuthSession, tpmutil.RawBytes(Cmd)) |
| 907 |
if err != nil { |
| 908 |
return 0, nil, err |
| 909 |
} |
| 910 |
return decodeStartAuthSession(resp) |
| 911 |
} |
| 912 |
|
| 913 |
func encodeUnseal(sessionHandle, itemHandle tpmutil.Handle, password string) ([]byte, error) { |
| 914 |
ha, err := tpmutil.Pack(itemHandle) |
| 915 |
if err != nil { |
| 916 |
return nil, err |
| 917 |
} |
| 918 |
auth, err := encodeAuthArea(AuthCommand{Session: sessionHandle, Attributes: AttrContinueSession, Auth: []byte(password)}) |
| 919 |
if err != nil { |
| 920 |
return nil, err |
| 921 |
} |
| 922 |
return concat(ha, auth) |
| 923 |
} |
| 924 |
|
| 925 |
func decodeUnseal(in []byte) ([]byte, error) { |
| 926 |
var paramSize uint32 |
| 927 |
var unsealed tpmutil.U16Bytes |
| 928 |
|
| 929 |
if _, err := tpmutil.Unpack(in, ¶mSize, &unsealed); err != nil { |
| 930 |
return nil, err |
| 931 |
} |
| 932 |
return unsealed, nil |
| 933 |
} |
| 934 |
|
| 935 |
// Unseal returns the data for a loaded sealed object. |
| 936 |
func Unseal(rw io.ReadWriter, itemHandle tpmutil.Handle, password string) ([]byte, error) { |
| 937 |
return UnsealWithSession(rw, HandlePasswordSession, itemHandle, password) |
| 938 |
} |
| 939 |
|
| 940 |
// UnsealWithSession returns the data for a loaded sealed object. |
| 941 |
func UnsealWithSession(rw io.ReadWriter, sessionHandle, itemHandle tpmutil.Handle, password string) ([]byte, error) { |
| 942 |
Cmd, err := encodeUnseal(sessionHandle, itemHandle, password) |
| 943 |
if err != nil { |
| 944 |
return nil, err |
| 945 |
} |
| 946 |
resp, err := runCommand(rw, TagSessions, CmdUnseal, tpmutil.RawBytes(Cmd)) |
| 947 |
if err != nil { |
| 948 |
return nil, err |
| 949 |
} |
| 950 |
return decodeUnseal(resp) |
| 951 |
} |
| 952 |
|
| 953 |
func encodeQuote(signingHandle tpmutil.Handle, signerAuth string, toQuote tpmutil.U16Bytes, sel PCRSelection, sigAlg Algorithm) ([]byte, error) { |
| 954 |
ha, err := tpmutil.Pack(signingHandle) |
| 955 |
if err != nil { |
| 956 |
return nil, err |
| 957 |
} |
| 958 |
auth, err := encodeAuthArea(AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(signerAuth)}) |
| 959 |
if err != nil { |
| 960 |
return nil, err |
| 961 |
} |
| 962 |
params, err := tpmutil.Pack(toQuote, sigAlg) |
| 963 |
if err != nil { |
| 964 |
return nil, err |
| 965 |
} |
| 966 |
pcrs, err := encodeTPMLPCRSelection(sel) |
| 967 |
if err != nil { |
| 968 |
return nil, err |
| 969 |
} |
| 970 |
return concat(ha, auth, params, pcrs) |
| 971 |
} |
| 972 |
|
| 973 |
func decodeQuote(in []byte) ([]byte, []byte, error) { |
| 974 |
buf := bytes.NewBuffer(in) |
| 975 |
var paramSize uint32 |
| 976 |
if err := tpmutil.UnpackBuf(buf, ¶mSize); err != nil { |
| 977 |
return nil, nil, err |
| 978 |
} |
| 979 |
buf.Truncate(int(paramSize)) |
| 980 |
var attest tpmutil.U16Bytes |
| 981 |
if err := tpmutil.UnpackBuf(buf, &attest); err != nil { |
| 982 |
return nil, nil, err |
| 983 |
} |
| 984 |
return attest, buf.Bytes(), nil |
| 985 |
} |
| 986 |
|
| 987 |
// Quote returns a quote of PCR values. A quote is a signature of the PCR |
| 988 |
// values, created using a signing TPM key. |
| 989 |
// |
| 990 |
// Returns attestation data and the decoded signature. |
| 991 |
func Quote(rw io.ReadWriter, signingHandle tpmutil.Handle, signerAuth, unused string, toQuote []byte, sel PCRSelection, sigAlg Algorithm) ([]byte, *Signature, error) { |
| 992 |
// TODO: Remove "unused" parameter on next breaking change. |
| 993 |
attest, sigRaw, err := QuoteRaw(rw, signingHandle, signerAuth, unused, toQuote, sel, sigAlg) |
| 994 |
if err != nil { |
| 995 |
return nil, nil, err |
| 996 |
} |
| 997 |
sig, err := DecodeSignature(bytes.NewBuffer(sigRaw)) |
| 998 |
if err != nil { |
| 999 |
return nil, nil, err |
| 1000 |
} |
| 1001 |
return attest, sig, nil |
| 1002 |
} |
| 1003 |
|
| 1004 |
// QuoteRaw is very similar to Quote, except that it will return |
| 1005 |
// the raw signature in a byte array without decoding. |
| 1006 |
func QuoteRaw(rw io.ReadWriter, signingHandle tpmutil.Handle, signerAuth, _ string, toQuote []byte, sel PCRSelection, sigAlg Algorithm) ([]byte, []byte, error) { |
| 1007 |
// TODO: Remove "unused" parameter on next breaking change. |
| 1008 |
Cmd, err := encodeQuote(signingHandle, signerAuth, toQuote, sel, sigAlg) |
| 1009 |
if err != nil { |
| 1010 |
return nil, nil, err |
| 1011 |
} |
| 1012 |
resp, err := runCommand(rw, TagSessions, CmdQuote, tpmutil.RawBytes(Cmd)) |
| 1013 |
if err != nil { |
| 1014 |
return nil, nil, err |
| 1015 |
} |
| 1016 |
return decodeQuote(resp) |
| 1017 |
} |
| 1018 |
|
| 1019 |
func encodeActivateCredential(auth []AuthCommand, activeHandle tpmutil.Handle, keyHandle tpmutil.Handle, credBlob, secret tpmutil.U16Bytes) ([]byte, error) { |
| 1020 |
ha, err := tpmutil.Pack(activeHandle, keyHandle) |
| 1021 |
if err != nil { |
| 1022 |
return nil, err |
| 1023 |
} |
| 1024 |
a, err := encodeAuthArea(auth...) |
| 1025 |
if err != nil { |
| 1026 |
return nil, err |
| 1027 |
} |
| 1028 |
params, err := tpmutil.Pack(credBlob, secret) |
| 1029 |
if err != nil { |
| 1030 |
return nil, err |
| 1031 |
} |
| 1032 |
return concat(ha, a, params) |
| 1033 |
} |
| 1034 |
|
| 1035 |
func decodeActivateCredential(in []byte) ([]byte, error) { |
| 1036 |
var paramSize uint32 |
| 1037 |
var certInfo tpmutil.U16Bytes |
| 1038 |
|
| 1039 |
if _, err := tpmutil.Unpack(in, ¶mSize, &certInfo); err != nil { |
| 1040 |
return nil, err |
| 1041 |
} |
| 1042 |
return certInfo, nil |
| 1043 |
} |
| 1044 |
|
| 1045 |
// ActivateCredential associates an object with a credential. |
| 1046 |
// Returns decrypted certificate information. |
| 1047 |
func ActivateCredential(rw io.ReadWriter, activeHandle, keyHandle tpmutil.Handle, activePassword, protectorPassword string, credBlob, secret []byte) ([]byte, error) { |
| 1048 |
return ActivateCredentialUsingAuth(rw, []AuthCommand{ |
| 1049 |
{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(activePassword)}, |
| 1050 |
{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(protectorPassword)}, |
| 1051 |
}, activeHandle, keyHandle, credBlob, secret) |
| 1052 |
} |
| 1053 |
|
| 1054 |
// ActivateCredentialUsingAuth associates an object with a credential, using the |
| 1055 |
// given set of authorizations. Two authorization must be provided. |
| 1056 |
// Returns decrypted certificate information. |
| 1057 |
func ActivateCredentialUsingAuth(rw io.ReadWriter, auth []AuthCommand, activeHandle, keyHandle tpmutil.Handle, credBlob, secret []byte) ([]byte, error) { |
| 1058 |
if len(auth) != 2 { |
| 1059 |
return nil, fmt.Errorf("len(auth) = %d, want 2", len(auth)) |
| 1060 |
} |
| 1061 |
|
| 1062 |
Cmd, err := encodeActivateCredential(auth, activeHandle, keyHandle, credBlob, secret) |
| 1063 |
if err != nil { |
| 1064 |
return nil, err |
| 1065 |
} |
| 1066 |
resp, err := runCommand(rw, TagSessions, CmdActivateCredential, tpmutil.RawBytes(Cmd)) |
| 1067 |
if err != nil { |
| 1068 |
return nil, err |
| 1069 |
} |
| 1070 |
return decodeActivateCredential(resp) |
| 1071 |
} |
| 1072 |
|
| 1073 |
func encodeMakeCredential(protectorHandle tpmutil.Handle, credential, activeName tpmutil.U16Bytes) ([]byte, error) { |
| 1074 |
ha, err := tpmutil.Pack(protectorHandle) |
| 1075 |
if err != nil { |
| 1076 |
return nil, err |
| 1077 |
} |
| 1078 |
params, err := tpmutil.Pack(credential, activeName) |
| 1079 |
if err != nil { |
| 1080 |
return nil, err |
| 1081 |
} |
| 1082 |
return concat(ha, params) |
| 1083 |
} |
| 1084 |
|
| 1085 |
func decodeMakeCredential(in []byte) ([]byte, []byte, error) { |
| 1086 |
var credBlob, encryptedSecret tpmutil.U16Bytes |
| 1087 |
|
| 1088 |
if _, err := tpmutil.Unpack(in, &credBlob, &encryptedSecret); err != nil { |
| 1089 |
return nil, nil, err |
| 1090 |
} |
| 1091 |
return credBlob, encryptedSecret, nil |
| 1092 |
} |
| 1093 |
|
| 1094 |
// MakeCredential creates an encrypted credential for use in MakeCredential. |
| 1095 |
// Returns encrypted credential and wrapped secret used to encrypt it. |
| 1096 |
func MakeCredential(rw io.ReadWriter, protectorHandle tpmutil.Handle, credential, activeName []byte) ([]byte, []byte, error) { |
| 1097 |
Cmd, err := encodeMakeCredential(protectorHandle, credential, activeName) |
| 1098 |
if err != nil { |
| 1099 |
return nil, nil, err |
| 1100 |
} |
| 1101 |
resp, err := runCommand(rw, TagNoSessions, CmdMakeCredential, tpmutil.RawBytes(Cmd)) |
| 1102 |
if err != nil { |
| 1103 |
return nil, nil, err |
| 1104 |
} |
| 1105 |
return decodeMakeCredential(resp) |
| 1106 |
} |
| 1107 |
|
| 1108 |
func encodeEvictControl(ownerAuth string, owner, objectHandle, persistentHandle tpmutil.Handle) ([]byte, error) { |
| 1109 |
ha, err := tpmutil.Pack(owner, objectHandle) |
| 1110 |
if err != nil { |
| 1111 |
return nil, err |
| 1112 |
} |
| 1113 |
auth, err := encodeAuthArea(AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(ownerAuth)}) |
| 1114 |
if err != nil { |
| 1115 |
return nil, err |
| 1116 |
} |
| 1117 |
params, err := tpmutil.Pack(persistentHandle) |
| 1118 |
if err != nil { |
| 1119 |
return nil, err |
| 1120 |
} |
| 1121 |
return concat(ha, auth, params) |
| 1122 |
} |
| 1123 |
|
| 1124 |
// EvictControl toggles persistence of an object within the TPM. |
| 1125 |
func EvictControl(rw io.ReadWriter, ownerAuth string, owner, objectHandle, persistentHandle tpmutil.Handle) error { |
| 1126 |
Cmd, err := encodeEvictControl(ownerAuth, owner, objectHandle, persistentHandle) |
| 1127 |
if err != nil { |
| 1128 |
return err |
| 1129 |
} |
| 1130 |
_, err = runCommand(rw, TagSessions, CmdEvictControl, tpmutil.RawBytes(Cmd)) |
| 1131 |
return err |
| 1132 |
} |
| 1133 |
|
| 1134 |
func encodeClear(handle tpmutil.Handle, auth AuthCommand) ([]byte, error) { |
| 1135 |
ah, err := tpmutil.Pack(handle) |
| 1136 |
if err != nil { |
| 1137 |
return nil, err |
| 1138 |
} |
| 1139 |
encodedAuth, err := encodeAuthArea(auth) |
| 1140 |
if err != nil { |
| 1141 |
return nil, err |
| 1142 |
} |
| 1143 |
return concat(ah, encodedAuth) |
| 1144 |
} |
| 1145 |
|
| 1146 |
// Clear clears lockout, endorsement and owner hierarchy authorization values |
| 1147 |
func Clear(rw io.ReadWriter, handle tpmutil.Handle, auth AuthCommand) error { |
| 1148 |
Cmd, err := encodeClear(handle, auth) |
| 1149 |
if err != nil { |
| 1150 |
return err |
| 1151 |
} |
| 1152 |
_, err = runCommand(rw, TagSessions, CmdClear, tpmutil.RawBytes(Cmd)) |
| 1153 |
return err |
| 1154 |
} |
| 1155 |
|
| 1156 |
func encodePCRAllocate(handle tpmutil.Handle, auth AuthCommand, pcrSelection []PCRSelection) ([]byte, error) { |
| 1157 |
ah, err := tpmutil.Pack(handle) |
| 1158 |
if err != nil { |
| 1159 |
return nil, err |
| 1160 |
} |
| 1161 |
authEncoded, err := encodeAuthArea(auth) |
| 1162 |
if err != nil { |
| 1163 |
return nil, err |
| 1164 |
} |
| 1165 |
|
| 1166 |
pcrEncoded, err := encodeTPMLPCRSelection(pcrSelection...) |
| 1167 |
if err != nil { |
| 1168 |
return nil, err |
| 1169 |
} |
| 1170 |
return concat(ah, authEncoded, pcrEncoded) |
| 1171 |
} |
| 1172 |
|
| 1173 |
// PCRAllocate sets the desired PCR allocation of PCR and algorithms. |
| 1174 |
// The changes take effect once the TPM is restarted. |
| 1175 |
func PCRAllocate(rw io.ReadWriter, handle tpmutil.Handle, auth AuthCommand, pcrSelection []PCRSelection) error { |
| 1176 |
Cmd, err := encodePCRAllocate(handle, auth, pcrSelection) |
| 1177 |
if err != nil { |
| 1178 |
return err |
| 1179 |
} |
| 1180 |
_, err = runCommand(rw, TagSessions, CmdPCRAllocate, tpmutil.RawBytes(Cmd)) |
| 1181 |
return err |
| 1182 |
} |
| 1183 |
|
| 1184 |
func encodeHierarchyChangeAuth(handle tpmutil.Handle, auth AuthCommand, newAuth string) ([]byte, error) { |
| 1185 |
ah, err := tpmutil.Pack(handle) |
| 1186 |
if err != nil { |
| 1187 |
return nil, err |
| 1188 |
} |
| 1189 |
encodedAuth, err := encodeAuthArea(auth) |
| 1190 |
if err != nil { |
| 1191 |
return nil, err |
| 1192 |
} |
| 1193 |
param, err := tpmutil.Pack(tpmutil.U16Bytes(newAuth)) |
| 1194 |
if err != nil { |
| 1195 |
return nil, err |
| 1196 |
} |
| 1197 |
return concat(ah, encodedAuth, param) |
| 1198 |
} |
| 1199 |
|
| 1200 |
// HierarchyChangeAuth changes the authorization values for a hierarchy or for the lockout authority |
| 1201 |
func HierarchyChangeAuth(rw io.ReadWriter, handle tpmutil.Handle, auth AuthCommand, newAuth string) error { |
| 1202 |
Cmd, err := encodeHierarchyChangeAuth(handle, auth, newAuth) |
| 1203 |
if err != nil { |
| 1204 |
return err |
| 1205 |
} |
| 1206 |
_, err = runCommand(rw, TagSessions, CmdHierarchyChangeAuth, tpmutil.RawBytes(Cmd)) |
| 1207 |
return err |
| 1208 |
} |
| 1209 |
|
| 1210 |
// ContextSave returns an encrypted version of the session, object or sequence |
| 1211 |
// context for storage outside of the TPM. The handle references context to |
| 1212 |
// store. |
| 1213 |
func ContextSave(rw io.ReadWriter, handle tpmutil.Handle) ([]byte, error) { |
| 1214 |
return runCommand(rw, TagNoSessions, CmdContextSave, handle) |
| 1215 |
} |
| 1216 |
|
| 1217 |
// ContextLoad reloads context data created by ContextSave. |
| 1218 |
func ContextLoad(rw io.ReadWriter, saveArea []byte) (tpmutil.Handle, error) { |
| 1219 |
resp, err := runCommand(rw, TagNoSessions, CmdContextLoad, tpmutil.RawBytes(saveArea)) |
| 1220 |
if err != nil { |
| 1221 |
return 0, err |
| 1222 |
} |
| 1223 |
var handle tpmutil.Handle |
| 1224 |
_, err = tpmutil.Unpack(resp, &handle) |
| 1225 |
return handle, err |
| 1226 |
} |
| 1227 |
|
| 1228 |
func encodeIncrementNV(handle tpmutil.Handle, authString string) ([]byte, error) { |
| 1229 |
auth, err := encodeAuthArea(AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(authString)}) |
| 1230 |
if err != nil { |
| 1231 |
return nil, err |
| 1232 |
} |
| 1233 |
out, err := tpmutil.Pack(handle, handle) |
| 1234 |
if err != nil { |
| 1235 |
return nil, err |
| 1236 |
} |
| 1237 |
return concat(out, auth) |
| 1238 |
} |
| 1239 |
|
| 1240 |
// NVIncrement increments a counter in NVRAM. |
| 1241 |
func NVIncrement(rw io.ReadWriter, handle tpmutil.Handle, authString string) error { |
| 1242 |
Cmd, err := encodeIncrementNV(handle, authString) |
| 1243 |
if err != nil { |
| 1244 |
return err |
| 1245 |
} |
| 1246 |
_, err = runCommand(rw, TagSessions, CmdIncrementNVCounter, tpmutil.RawBytes(Cmd)) |
| 1247 |
return err |
| 1248 |
} |
| 1249 |
|
| 1250 |
// NVUndefineSpace removes an index from TPM's NV storage. |
| 1251 |
func NVUndefineSpace(rw io.ReadWriter, ownerAuth string, owner, index tpmutil.Handle) error { |
| 1252 |
authArea := AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(ownerAuth)} |
| 1253 |
return NVUndefineSpaceEx(rw, owner, index, authArea) |
| 1254 |
} |
| 1255 |
|
| 1256 |
// NVUndefineSpaceEx removes an index from NVRAM. Unlike, NVUndefineSpace(), custom command |
| 1257 |
// authorization can be provided. |
| 1258 |
func NVUndefineSpaceEx(rw io.ReadWriter, owner, index tpmutil.Handle, authArea AuthCommand) error { |
| 1259 |
out, err := tpmutil.Pack(owner, index) |
| 1260 |
if err != nil { |
| 1261 |
return err |
| 1262 |
} |
| 1263 |
auth, err := encodeAuthArea(authArea) |
| 1264 |
if err != nil { |
| 1265 |
return err |
| 1266 |
} |
| 1267 |
cmd, err := concat(out, auth) |
| 1268 |
if err != nil { |
| 1269 |
return err |
| 1270 |
} |
| 1271 |
_, err = runCommand(rw, TagSessions, CmdUndefineSpace, tpmutil.RawBytes(cmd)) |
| 1272 |
return err |
| 1273 |
} |
| 1274 |
|
| 1275 |
// NVUndefineSpaceSpecial This command allows removal of a platform-created NV Index that has TPMA_NV_POLICY_DELETE SET. |
| 1276 |
// The policy to authorize NV index access needs to be created with PolicyCommandCode(rw, sessionHandle, CmdNVUndefineSpaceSpecial) function |
| 1277 |
// nvAuthCmd takes the session handle for the policy and the AuthValue (which can be emptyAuth) for the authorization. |
| 1278 |
// platformAuth takes either a sessionHandle for the platform policy or HandlePasswordSession and the platformAuth value for authorization. |
| 1279 |
func NVUndefineSpaceSpecial(rw io.ReadWriter, nvIndex tpmutil.Handle, nvAuth, platformAuth AuthCommand) error { |
| 1280 |
authBytes, err := encodeAuthArea(nvAuth, platformAuth) |
| 1281 |
if err != nil { |
| 1282 |
return err |
| 1283 |
} |
| 1284 |
auth, err := tpmutil.Pack(authBytes) |
| 1285 |
if err != nil { |
| 1286 |
return err |
| 1287 |
} |
| 1288 |
_, err = runCommand(rw, TagSessions, CmdNVUndefineSpaceSpecial, nvIndex, HandlePlatform, tpmutil.RawBytes(auth)) |
| 1289 |
return err |
| 1290 |
} |
| 1291 |
|
| 1292 |
// NVDefineSpace creates an index in TPM's NV storage. |
| 1293 |
func NVDefineSpace(rw io.ReadWriter, owner, handle tpmutil.Handle, ownerAuth, authString string, policy []byte, attributes NVAttr, dataSize uint16) error { |
| 1294 |
nvPub := NVPublic{ |
| 1295 |
NVIndex: handle, |
| 1296 |
NameAlg: AlgSHA1, |
| 1297 |
Attributes: attributes, |
| 1298 |
AuthPolicy: policy, |
| 1299 |
DataSize: dataSize, |
| 1300 |
} |
| 1301 |
authArea := AuthCommand{ |
| 1302 |
Session: HandlePasswordSession, |
| 1303 |
Attributes: AttrContinueSession, |
| 1304 |
Auth: []byte(ownerAuth), |
| 1305 |
} |
| 1306 |
return NVDefineSpaceEx(rw, owner, authString, nvPub, authArea) |
| 1307 |
} |
| 1308 |
|
| 1309 |
// NVDefineSpaceEx accepts NVPublic structure and AuthCommand, allowing more flexibility. |
| 1310 |
func NVDefineSpaceEx(rw io.ReadWriter, owner tpmutil.Handle, authVal string, pubInfo NVPublic, authArea AuthCommand) error { |
| 1311 |
ha, err := tpmutil.Pack(owner) |
| 1312 |
if err != nil { |
| 1313 |
return err |
| 1314 |
} |
| 1315 |
auth, err := encodeAuthArea(authArea) |
| 1316 |
if err != nil { |
| 1317 |
return err |
| 1318 |
} |
| 1319 |
publicInfo, err := tpmutil.Pack(pubInfo) |
| 1320 |
if err != nil { |
| 1321 |
return err |
| 1322 |
} |
| 1323 |
params, err := tpmutil.Pack(tpmutil.U16Bytes(authVal), tpmutil.U16Bytes(publicInfo)) |
| 1324 |
if err != nil { |
| 1325 |
return err |
| 1326 |
} |
| 1327 |
cmd, err := concat(ha, auth, params) |
| 1328 |
if err != nil { |
| 1329 |
return err |
| 1330 |
} |
| 1331 |
_, err = runCommand(rw, TagSessions, CmdDefineSpace, tpmutil.RawBytes(cmd)) |
| 1332 |
return err |
| 1333 |
} |
| 1334 |
|
| 1335 |
// NVWrite writes data into the TPM's NV storage. |
| 1336 |
func NVWrite(rw io.ReadWriter, authHandle, nvIndex tpmutil.Handle, authString string, data tpmutil.U16Bytes, offset uint16) error { |
| 1337 |
auth := AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(authString)} |
| 1338 |
return NVWriteEx(rw, authHandle, nvIndex, auth, data, offset) |
| 1339 |
} |
| 1340 |
|
| 1341 |
// NVWriteEx does the same as NVWrite with the exception of letting the user take care of the AuthCommand before calling the function. |
| 1342 |
// This allows more flexibility and does not limit the AuthCommand to PasswordSession. |
| 1343 |
func NVWriteEx(rw io.ReadWriter, authHandle, nvIndex tpmutil.Handle, authArea AuthCommand, data tpmutil.U16Bytes, offset uint16) error { |
| 1344 |
h, err := tpmutil.Pack(authHandle, nvIndex) |
| 1345 |
if err != nil { |
| 1346 |
return err |
| 1347 |
} |
| 1348 |
authEnc, err := encodeAuthArea(authArea) |
| 1349 |
if err != nil { |
| 1350 |
return err |
| 1351 |
} |
| 1352 |
|
| 1353 |
d, err := tpmutil.Pack(data, offset) |
| 1354 |
if err != nil { |
| 1355 |
return err |
| 1356 |
} |
| 1357 |
|
| 1358 |
b, err := concat(h, authEnc, d) |
| 1359 |
if err != nil { |
| 1360 |
return err |
| 1361 |
} |
| 1362 |
_, err = runCommand(rw, TagSessions, CmdWriteNV, tpmutil.RawBytes(b)) |
| 1363 |
return err |
| 1364 |
} |
| 1365 |
|
| 1366 |
func encodeLockNV(owner, handle tpmutil.Handle, authString string) ([]byte, error) { |
| 1367 |
auth, err := encodeAuthArea(AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(authString)}) |
| 1368 |
if err != nil { |
| 1369 |
return nil, err |
| 1370 |
} |
| 1371 |
out, err := tpmutil.Pack(owner, handle) |
| 1372 |
if err != nil { |
| 1373 |
return nil, err |
| 1374 |
} |
| 1375 |
return concat(out, auth) |
| 1376 |
} |
| 1377 |
|
| 1378 |
// NVWriteLock inhibits further writes on the given NV index if at least one of |
| 1379 |
// the AttrWriteSTClear or AttrWriteDefine bits is set. |
| 1380 |
// |
| 1381 |
// AttrWriteSTClear causes the index to be locked until the TPM is restarted |
| 1382 |
// (see the Startup function). |
| 1383 |
// |
| 1384 |
// AttrWriteDefine causes the index to be locked permanently if data has been |
| 1385 |
// written to the index; otherwise the lock is removed on startup. |
| 1386 |
// |
| 1387 |
// NVWriteLock returns an error if neither bit is set. |
| 1388 |
// |
| 1389 |
// It is not an error to call NVWriteLock for an index that is already locked |
| 1390 |
// for writing. |
| 1391 |
func NVWriteLock(rw io.ReadWriter, owner, handle tpmutil.Handle, authString string) error { |
| 1392 |
Cmd, err := encodeLockNV(owner, handle, authString) |
| 1393 |
if err != nil { |
| 1394 |
return err |
| 1395 |
} |
| 1396 |
_, err = runCommand(rw, TagSessions, CmdWriteLockNV, tpmutil.RawBytes(Cmd)) |
| 1397 |
return err |
| 1398 |
} |
| 1399 |
|
| 1400 |
func decodeNVReadPublic(in []byte) (NVPublic, error) { |
| 1401 |
var pub NVPublic |
| 1402 |
var buf tpmutil.U16Bytes |
| 1403 |
if _, err := tpmutil.Unpack(in, &buf); err != nil { |
| 1404 |
return pub, err |
| 1405 |
} |
| 1406 |
_, err := tpmutil.Unpack(buf, &pub) |
| 1407 |
return pub, err |
| 1408 |
} |
| 1409 |
|
| 1410 |
// NVReadPublic reads the public data of an NV index. |
| 1411 |
func NVReadPublic(rw io.ReadWriter, index tpmutil.Handle) (NVPublic, error) { |
| 1412 |
// Read public area to determine data size. |
| 1413 |
resp, err := runCommand(rw, TagNoSessions, CmdReadPublicNV, index) |
| 1414 |
if err != nil { |
| 1415 |
return NVPublic{}, err |
| 1416 |
} |
| 1417 |
return decodeNVReadPublic(resp) |
| 1418 |
} |
| 1419 |
|
| 1420 |
func decodeNVRead(in []byte) ([]byte, error) { |
| 1421 |
var paramSize uint32 |
| 1422 |
var data tpmutil.U16Bytes |
| 1423 |
if _, err := tpmutil.Unpack(in, ¶mSize, &data); err != nil { |
| 1424 |
return nil, err |
| 1425 |
} |
| 1426 |
return data, nil |
| 1427 |
} |
| 1428 |
|
| 1429 |
func encodeNVRead(nvIndex, authHandle tpmutil.Handle, password string, offset, dataSize uint16) ([]byte, error) { |
| 1430 |
handles, err := tpmutil.Pack(authHandle, nvIndex) |
| 1431 |
if err != nil { |
| 1432 |
return nil, err |
| 1433 |
} |
| 1434 |
auth, err := encodeAuthArea(AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(password)}) |
| 1435 |
if err != nil { |
| 1436 |
return nil, err |
| 1437 |
} |
| 1438 |
|
| 1439 |
params, err := tpmutil.Pack(dataSize, offset) |
| 1440 |
if err != nil { |
| 1441 |
return nil, err |
| 1442 |
} |
| 1443 |
|
| 1444 |
return concat(handles, auth, params) |
| 1445 |
} |
| 1446 |
|
| 1447 |
// NVRead reads a full data blob from an NV index. This function is |
| 1448 |
// deprecated; use NVReadEx instead. |
| 1449 |
func NVRead(rw io.ReadWriter, index tpmutil.Handle) ([]byte, error) { |
| 1450 |
return NVReadEx(rw, index, index, "", 0) |
| 1451 |
} |
| 1452 |
|
| 1453 |
// NVReadEx reads a full data blob from an NV index, using the given |
| 1454 |
// authorization handle. NVRead commands are done in blocks of blockSize. |
| 1455 |
// If blockSize is 0, the TPM is queried for TPM_PT_NV_BUFFER_MAX, and that |
| 1456 |
// value is used. |
| 1457 |
func NVReadEx(rw io.ReadWriter, index, authHandle tpmutil.Handle, password string, blockSize int) ([]byte, error) { |
| 1458 |
if blockSize == 0 { |
| 1459 |
readBuff, _, err := GetCapability(rw, CapabilityTPMProperties, 1, uint32(NVMaxBufferSize)) |
| 1460 |
if err != nil { |
| 1461 |
return nil, fmt.Errorf("GetCapability for TPM_PT_NV_BUFFER_MAX failed: %v", err) |
| 1462 |
} |
| 1463 |
if len(readBuff) != 1 { |
| 1464 |
return nil, fmt.Errorf("could not determine NVRAM read/write buffer size") |
| 1465 |
} |
| 1466 |
rb, ok := readBuff[0].(TaggedProperty) |
| 1467 |
if !ok { |
| 1468 |
return nil, fmt.Errorf("GetCapability returned unexpected type: %T, expected TaggedProperty", readBuff[0]) |
| 1469 |
} |
| 1470 |
blockSize = int(rb.Value) |
| 1471 |
} |
| 1472 |
|
| 1473 |
// Read public area to determine data size. |
| 1474 |
pub, err := NVReadPublic(rw, index) |
| 1475 |
if err != nil { |
| 1476 |
return nil, fmt.Errorf("decoding NV_ReadPublic response: %v", err) |
| 1477 |
} |
| 1478 |
|
| 1479 |
// Read the NVRAM area in blocks. |
| 1480 |
outBuff := make([]byte, 0, int(pub.DataSize)) |
| 1481 |
for len(outBuff) < int(pub.DataSize) { |
| 1482 |
readSize := blockSize |
| 1483 |
if readSize > (int(pub.DataSize) - len(outBuff)) { |
| 1484 |
readSize = int(pub.DataSize) - len(outBuff) |
| 1485 |
} |
| 1486 |
|
| 1487 |
Cmd, err := encodeNVRead(index, authHandle, password, uint16(len(outBuff)), uint16(readSize)) |
| 1488 |
if err != nil { |
| 1489 |
return nil, fmt.Errorf("building NV_Read command: %v", err) |
| 1490 |
} |
| 1491 |
resp, err := runCommand(rw, TagSessions, CmdReadNV, tpmutil.RawBytes(Cmd)) |
| 1492 |
if err != nil { |
| 1493 |
return nil, fmt.Errorf("running NV_Read command (cursor=%d,size=%d): %v", len(outBuff), readSize, err) |
| 1494 |
} |
| 1495 |
data, err := decodeNVRead(resp) |
| 1496 |
if err != nil { |
| 1497 |
return nil, fmt.Errorf("decoding NV_Read command: %v", err) |
| 1498 |
} |
| 1499 |
outBuff = append(outBuff, data...) |
| 1500 |
} |
| 1501 |
return outBuff, nil |
| 1502 |
} |
| 1503 |
|
| 1504 |
// NVReadLock inhibits further reads of the given NV index if AttrReadSTClear |
| 1505 |
// is set. After the TPM is restarted the index can be read again (see the |
| 1506 |
// Startup function). |
| 1507 |
// |
| 1508 |
// NVReadLock returns an error if the AttrReadSTClear bit is not set. |
| 1509 |
// |
| 1510 |
// It is not an error to call NVReadLock for an index that is already locked |
| 1511 |
// for reading. |
| 1512 |
func NVReadLock(rw io.ReadWriter, owner, handle tpmutil.Handle, authString string) error { |
| 1513 |
Cmd, err := encodeLockNV(owner, handle, authString) |
| 1514 |
if err != nil { |
| 1515 |
return err |
| 1516 |
} |
| 1517 |
_, err = runCommand(rw, TagSessions, CmdReadLockNV, tpmutil.RawBytes(Cmd)) |
| 1518 |
return err |
| 1519 |
} |
| 1520 |
|
| 1521 |
// decodeHash unpacks a successful response to TPM2_Hash, returning the computed digest and |
| 1522 |
// validation ticket. |
| 1523 |
func decodeHash(resp []byte) ([]byte, *Ticket, error) { |
| 1524 |
var digest tpmutil.U16Bytes |
| 1525 |
var validation Ticket |
| 1526 |
|
| 1527 |
buf := bytes.NewBuffer(resp) |
| 1528 |
if err := tpmutil.UnpackBuf(buf, &digest, &validation); err != nil { |
| 1529 |
return nil, nil, err |
| 1530 |
} |
| 1531 |
return digest, &validation, nil |
| 1532 |
} |
| 1533 |
|
| 1534 |
// Hash computes a hash of data in buf using TPM2_Hash, returning the computed |
| 1535 |
// digest and validation ticket. The validation ticket serves as confirmation |
| 1536 |
// from the TPM that the data in buf did not begin with TPM_GENERATED_VALUE. |
| 1537 |
// NOTE: TPM2_Hash can only accept data up to MAX_DIGEST_BUFFER in size, which |
| 1538 |
// is implementation-dependent, but guaranteed to be at least 1024 octets. |
| 1539 |
func Hash(rw io.ReadWriter, alg Algorithm, buf tpmutil.U16Bytes, hierarchy tpmutil.Handle) (digest []byte, validation *Ticket, err error) { |
| 1540 |
resp, err := runCommand(rw, TagNoSessions, CmdHash, buf, alg, hierarchy) |
| 1541 |
if err != nil { |
| 1542 |
return nil, nil, err |
| 1543 |
} |
| 1544 |
return decodeHash(resp) |
| 1545 |
} |
| 1546 |
|
| 1547 |
// HashSequenceStart starts a hash or an event sequence. If hashAlg is an |
| 1548 |
// implemented hash, then a hash sequence is started. If hashAlg is |
| 1549 |
// TPM_ALG_NULL, then an event sequence is started. |
| 1550 |
func HashSequenceStart(rw io.ReadWriter, sequenceAuth string, hashAlg Algorithm) (seqHandle tpmutil.Handle, err error) { |
| 1551 |
resp, err := runCommand(rw, TagNoSessions, CmdHashSequenceStart, tpmutil.U16Bytes(sequenceAuth), hashAlg) |
| 1552 |
if err != nil { |
| 1553 |
return 0, err |
| 1554 |
} |
| 1555 |
var handle tpmutil.Handle |
| 1556 |
_, err = tpmutil.Unpack(resp, &handle) |
| 1557 |
return handle, err |
| 1558 |
} |
| 1559 |
|
| 1560 |
func encodeSequenceUpdate(sequenceAuth string, seqHandle tpmutil.Handle, buf tpmutil.U16Bytes) ([]byte, error) { |
| 1561 |
ha, err := tpmutil.Pack(seqHandle) |
| 1562 |
if err != nil { |
| 1563 |
return nil, err |
| 1564 |
} |
| 1565 |
auth, err := encodeAuthArea(AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(sequenceAuth)}) |
| 1566 |
if err != nil { |
| 1567 |
return nil, err |
| 1568 |
} |
| 1569 |
params, err := tpmutil.Pack(buf) |
| 1570 |
if err != nil { |
| 1571 |
return nil, err |
| 1572 |
} |
| 1573 |
return concat(ha, auth, params) |
| 1574 |
} |
| 1575 |
|
| 1576 |
// SequenceUpdate is used to add data to a hash or HMAC sequence. |
| 1577 |
func SequenceUpdate(rw io.ReadWriter, sequenceAuth string, seqHandle tpmutil.Handle, buffer []byte) error { |
| 1578 |
cmd, err := encodeSequenceUpdate(sequenceAuth, seqHandle, buffer) |
| 1579 |
if err != nil { |
| 1580 |
return err |
| 1581 |
} |
| 1582 |
_, err = runCommand(rw, TagSessions, CmdSequenceUpdate, tpmutil.RawBytes(cmd)) |
| 1583 |
return err |
| 1584 |
} |
| 1585 |
|
| 1586 |
func decodeSequenceComplete(resp []byte) ([]byte, *Ticket, error) { |
| 1587 |
var digest tpmutil.U16Bytes |
| 1588 |
var validation Ticket |
| 1589 |
var paramSize uint32 |
| 1590 |
|
| 1591 |
if _, err := tpmutil.Unpack(resp, ¶mSize, &digest, &validation); err != nil { |
| 1592 |
return nil, nil, err |
| 1593 |
} |
| 1594 |
return digest, &validation, nil |
| 1595 |
} |
| 1596 |
|
| 1597 |
func encodeSequenceComplete(sequenceAuth string, seqHandle, hierarchy tpmutil.Handle, buf tpmutil.U16Bytes) ([]byte, error) { |
| 1598 |
ha, err := tpmutil.Pack(seqHandle) |
| 1599 |
if err != nil { |
| 1600 |
return nil, err |
| 1601 |
} |
| 1602 |
auth, err := encodeAuthArea(AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(sequenceAuth)}) |
| 1603 |
if err != nil { |
| 1604 |
return nil, err |
| 1605 |
} |
| 1606 |
params, err := tpmutil.Pack(buf, hierarchy) |
| 1607 |
if err != nil { |
| 1608 |
return nil, err |
| 1609 |
} |
| 1610 |
return concat(ha, auth, params) |
| 1611 |
} |
| 1612 |
|
| 1613 |
// SequenceComplete adds the last part of data, if any, to a hash/HMAC sequence |
| 1614 |
// and returns the result. |
| 1615 |
func SequenceComplete(rw io.ReadWriter, sequenceAuth string, seqHandle, hierarchy tpmutil.Handle, buffer []byte) (digest []byte, validation *Ticket, err error) { |
| 1616 |
cmd, err := encodeSequenceComplete(sequenceAuth, seqHandle, hierarchy, buffer) |
| 1617 |
if err != nil { |
| 1618 |
return nil, nil, err |
| 1619 |
} |
| 1620 |
resp, err := runCommand(rw, TagSessions, CmdSequenceComplete, tpmutil.RawBytes(cmd)) |
| 1621 |
if err != nil { |
| 1622 |
return nil, nil, err |
| 1623 |
} |
| 1624 |
return decodeSequenceComplete(resp) |
| 1625 |
} |
| 1626 |
|
| 1627 |
func encodeEventSequenceComplete(auths []AuthCommand, pcrHandle, seqHandle tpmutil.Handle, buf tpmutil.U16Bytes) ([]byte, error) { |
| 1628 |
ha, err := tpmutil.Pack(pcrHandle, seqHandle) |
| 1629 |
if err != nil { |
| 1630 |
return nil, err |
| 1631 |
} |
| 1632 |
auth, err := encodeAuthArea(auths...) |
| 1633 |
if err != nil { |
| 1634 |
return nil, err |
| 1635 |
} |
| 1636 |
params, err := tpmutil.Pack(buf) |
| 1637 |
if err != nil { |
| 1638 |
return nil, err |
| 1639 |
} |
| 1640 |
return concat(ha, auth, params) |
| 1641 |
} |
| 1642 |
|
| 1643 |
func decodeEventSequenceComplete(resp []byte) ([]*HashValue, error) { |
| 1644 |
var paramSize uint32 |
| 1645 |
var hashCount uint32 |
| 1646 |
var err error |
| 1647 |
|
| 1648 |
buf := bytes.NewBuffer(resp) |
| 1649 |
if err := tpmutil.UnpackBuf(buf, ¶mSize, &hashCount); err != nil { |
| 1650 |
return nil, err |
| 1651 |
} |
| 1652 |
|
| 1653 |
buf.Truncate(int(paramSize)) |
| 1654 |
digests := make([]*HashValue, hashCount) |
| 1655 |
for i := uint32(0); i < hashCount; i++ { |
| 1656 |
if digests[i], err = decodeHashValue(buf); err != nil { |
| 1657 |
return nil, err |
| 1658 |
} |
| 1659 |
} |
| 1660 |
|
| 1661 |
return digests, nil |
| 1662 |
} |
| 1663 |
|
| 1664 |
// EventSequenceComplete adds the last part of data, if any, to an Event |
| 1665 |
// Sequence and returns the result in a digest list. If pcrHandle references a |
| 1666 |
// PCR and not AlgNull, then the returned digest list is processed in the same |
| 1667 |
// manner as the digest list input parameter to PCRExtend() with the pcrHandle |
| 1668 |
// in each bank extended with the associated digest value. |
| 1669 |
func EventSequenceComplete(rw io.ReadWriter, pcrAuth, sequenceAuth string, pcrHandle, seqHandle tpmutil.Handle, buffer []byte) (digests []*HashValue, err error) { |
| 1670 |
auth := []AuthCommand{ |
| 1671 |
{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(pcrAuth)}, |
| 1672 |
{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(sequenceAuth)}, |
| 1673 |
} |
| 1674 |
cmd, err := encodeEventSequenceComplete(auth, pcrHandle, seqHandle, buffer) |
| 1675 |
if err != nil { |
| 1676 |
return nil, err |
| 1677 |
} |
| 1678 |
resp, err := runCommand(rw, TagSessions, CmdEventSequenceComplete, tpmutil.RawBytes(cmd)) |
| 1679 |
if err != nil { |
| 1680 |
return nil, err |
| 1681 |
} |
| 1682 |
return decodeEventSequenceComplete(resp) |
| 1683 |
} |
| 1684 |
|
| 1685 |
// Startup initializes a TPM (usually done by the OS). |
| 1686 |
func Startup(rw io.ReadWriter, typ StartupType) error { |
| 1687 |
_, err := runCommand(rw, TagNoSessions, CmdStartup, typ) |
| 1688 |
return err |
| 1689 |
} |
| 1690 |
|
| 1691 |
// Shutdown shuts down a TPM (usually done by the OS). |
| 1692 |
func Shutdown(rw io.ReadWriter, typ StartupType) error { |
| 1693 |
_, err := runCommand(rw, TagNoSessions, CmdShutdown, typ) |
| 1694 |
return err |
| 1695 |
} |
| 1696 |
|
| 1697 |
// nullTicket is a hard-coded null ticket of type TPMT_TK_HASHCHECK. |
| 1698 |
// It is for Sign commands that do not require the TPM to verify that the digest |
| 1699 |
// is not from data that started with TPM_GENERATED_VALUE. |
| 1700 |
var nullTicket = Ticket{ |
| 1701 |
Type: TagHashCheck, |
| 1702 |
Hierarchy: HandleNull, |
| 1703 |
Digest: tpmutil.U16Bytes{}, |
| 1704 |
} |
| 1705 |
|
| 1706 |
func encodeSign(sessionHandle, key tpmutil.Handle, password string, digest tpmutil.U16Bytes, sigScheme *SigScheme, validation *Ticket) ([]byte, error) { |
| 1707 |
ha, err := tpmutil.Pack(key) |
| 1708 |
if err != nil { |
| 1709 |
return nil, err |
| 1710 |
} |
| 1711 |
auth, err := encodeAuthArea(AuthCommand{Session: sessionHandle, Attributes: AttrContinueSession, Auth: []byte(password)}) |
| 1712 |
if err != nil { |
| 1713 |
return nil, err |
| 1714 |
} |
| 1715 |
d, err := tpmutil.Pack(digest) |
| 1716 |
if err != nil { |
| 1717 |
return nil, err |
| 1718 |
} |
| 1719 |
s, err := sigScheme.encode() |
| 1720 |
if err != nil { |
| 1721 |
return nil, err |
| 1722 |
} |
| 1723 |
if validation == nil { |
| 1724 |
validation = &nullTicket |
| 1725 |
} |
| 1726 |
v, err := tpmutil.Pack(validation) |
| 1727 |
if err != nil { |
| 1728 |
return nil, err |
| 1729 |
} |
| 1730 |
|
| 1731 |
return concat(ha, auth, d, s, v) |
| 1732 |
} |
| 1733 |
|
| 1734 |
func decodeSign(buf []byte) (*Signature, error) { |
| 1735 |
in := bytes.NewBuffer(buf) |
| 1736 |
var paramSize uint32 |
| 1737 |
if err := tpmutil.UnpackBuf(in, ¶mSize); err != nil { |
| 1738 |
return nil, err |
| 1739 |
} |
| 1740 |
return DecodeSignature(in) |
| 1741 |
} |
| 1742 |
|
| 1743 |
// SignWithSession computes a signature for digest using a given loaded key. Signature |
| 1744 |
// algorithm depends on the key type. Used for keys with non-password authorization policies. |
| 1745 |
// If 'key' references a Restricted Decryption key, 'validation' must be a valid hash verification |
| 1746 |
// ticket from the TPM, which can be obtained by using Hash() to hash the data with the TPM. |
| 1747 |
// If 'validation' is nil, a NULL ticket is passed to TPM2_Sign. |
| 1748 |
func SignWithSession(rw io.ReadWriter, sessionHandle, key tpmutil.Handle, password string, digest []byte, validation *Ticket, sigScheme *SigScheme) (*Signature, error) { |
| 1749 |
Cmd, err := encodeSign(sessionHandle, key, password, digest, sigScheme, validation) |
| 1750 |
if err != nil { |
| 1751 |
return nil, err |
| 1752 |
} |
| 1753 |
resp, err := runCommand(rw, TagSessions, CmdSign, tpmutil.RawBytes(Cmd)) |
| 1754 |
if err != nil { |
| 1755 |
return nil, err |
| 1756 |
} |
| 1757 |
return decodeSign(resp) |
| 1758 |
} |
| 1759 |
|
| 1760 |
// Sign computes a signature for digest using a given loaded key. Signature |
| 1761 |
// algorithm depends on the key type. |
| 1762 |
// If 'key' references a Restricted Decryption key, 'validation' must be a valid hash verification |
| 1763 |
// ticket from the TPM, which can be obtained by using Hash() to hash the data with the TPM. |
| 1764 |
// If 'validation' is nil, a NULL ticket is passed to TPM2_Sign. |
| 1765 |
func Sign(rw io.ReadWriter, key tpmutil.Handle, password string, digest []byte, validation *Ticket, sigScheme *SigScheme) (*Signature, error) { |
| 1766 |
return SignWithSession(rw, HandlePasswordSession, key, password, digest, validation, sigScheme) |
| 1767 |
} |
| 1768 |
|
| 1769 |
func encodeCertify(objectAuth, signerAuth string, object, signer tpmutil.Handle, qualifyingData tpmutil.U16Bytes) ([]byte, error) { |
| 1770 |
ha, err := tpmutil.Pack(object, signer) |
| 1771 |
if err != nil { |
| 1772 |
return nil, err |
| 1773 |
} |
| 1774 |
|
| 1775 |
auth, err := encodeAuthArea(AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(objectAuth)}, AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(signerAuth)}) |
| 1776 |
if err != nil { |
| 1777 |
return nil, err |
| 1778 |
} |
| 1779 |
|
| 1780 |
scheme := SigScheme{Alg: AlgRSASSA, Hash: AlgSHA256} |
| 1781 |
// Use signing key's scheme. |
| 1782 |
s, err := scheme.encode() |
| 1783 |
if err != nil { |
| 1784 |
return nil, err |
| 1785 |
} |
| 1786 |
data, err := tpmutil.Pack(qualifyingData) |
| 1787 |
if err != nil { |
| 1788 |
return nil, err |
| 1789 |
} |
| 1790 |
return concat(ha, auth, data, s) |
| 1791 |
} |
| 1792 |
|
| 1793 |
// This function differs from encodeCertify in that it takes the scheme to be used as an additional argument. |
| 1794 |
func encodeCertifyEx(objectAuth, signerAuth string, object, signer tpmutil.Handle, qualifyingData tpmutil.U16Bytes, scheme SigScheme) ([]byte, error) { |
| 1795 |
ha, err := tpmutil.Pack(object, signer) |
| 1796 |
if err != nil { |
| 1797 |
return nil, err |
| 1798 |
} |
| 1799 |
|
| 1800 |
auth, err := encodeAuthArea(AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(objectAuth)}, AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(signerAuth)}) |
| 1801 |
if err != nil { |
| 1802 |
return nil, err |
| 1803 |
} |
| 1804 |
|
| 1805 |
s, err := scheme.encode() |
| 1806 |
if err != nil { |
| 1807 |
return nil, err |
| 1808 |
} |
| 1809 |
data, err := tpmutil.Pack(qualifyingData) |
| 1810 |
if err != nil { |
| 1811 |
return nil, err |
| 1812 |
} |
| 1813 |
return concat(ha, auth, data, s) |
| 1814 |
} |
| 1815 |
|
| 1816 |
func decodeCertify(resp []byte) ([]byte, []byte, error) { |
| 1817 |
var paramSize uint32 |
| 1818 |
var attest tpmutil.U16Bytes |
| 1819 |
|
| 1820 |
buf := bytes.NewBuffer(resp) |
| 1821 |
if err := tpmutil.UnpackBuf(buf, ¶mSize); err != nil { |
| 1822 |
return nil, nil, err |
| 1823 |
} |
| 1824 |
buf.Truncate(int(paramSize)) |
| 1825 |
if err := tpmutil.UnpackBuf(buf, &attest); err != nil { |
| 1826 |
return nil, nil, err |
| 1827 |
} |
| 1828 |
return attest, buf.Bytes(), nil |
| 1829 |
} |
| 1830 |
|
| 1831 |
// Certify generates a signature of a loaded TPM object with a signing key |
| 1832 |
// signer. This function calls encodeCertify which makes use of the hardcoded |
| 1833 |
// signing scheme {AlgRSASSA, AlgSHA256}. Returned values are: attestation data (TPMS_ATTEST), |
| 1834 |
// signature and error, if any. |
| 1835 |
func Certify(rw io.ReadWriter, objectAuth, signerAuth string, object, signer tpmutil.Handle, qualifyingData []byte) ([]byte, []byte, error) { |
| 1836 |
cmd, err := encodeCertify(objectAuth, signerAuth, object, signer, qualifyingData) |
| 1837 |
if err != nil { |
| 1838 |
return nil, nil, err |
| 1839 |
} |
| 1840 |
resp, err := runCommand(rw, TagSessions, CmdCertify, tpmutil.RawBytes(cmd)) |
| 1841 |
if err != nil { |
| 1842 |
return nil, nil, err |
| 1843 |
} |
| 1844 |
return decodeCertify(resp) |
| 1845 |
} |
| 1846 |
|
| 1847 |
// CertifyEx generates a signature of a loaded TPM object with a signing key |
| 1848 |
// signer. This function differs from Certify in that it takes the scheme |
| 1849 |
// to be used as an additional argument and calls encodeCertifyEx instead |
| 1850 |
// of encodeCertify. Returned values are: attestation data (TPMS_ATTEST), |
| 1851 |
// signature and error, if any. |
| 1852 |
func CertifyEx(rw io.ReadWriter, objectAuth, signerAuth string, object, signer tpmutil.Handle, qualifyingData []byte, scheme SigScheme) ([]byte, []byte, error) { |
| 1853 |
cmd, err := encodeCertifyEx(objectAuth, signerAuth, object, signer, qualifyingData, scheme) |
| 1854 |
if err != nil { |
| 1855 |
return nil, nil, err |
| 1856 |
} |
| 1857 |
resp, err := runCommand(rw, TagSessions, CmdCertify, tpmutil.RawBytes(cmd)) |
| 1858 |
if err != nil { |
| 1859 |
return nil, nil, err |
| 1860 |
} |
| 1861 |
return decodeCertify(resp) |
| 1862 |
} |
| 1863 |
|
| 1864 |
func encodeCertifyCreation(objectAuth string, object, signer tpmutil.Handle, qualifyingData, creationHash tpmutil.U16Bytes, scheme SigScheme, ticket Ticket) ([]byte, error) { |
| 1865 |
handles, err := tpmutil.Pack(signer, object) |
| 1866 |
if err != nil { |
| 1867 |
return nil, err |
| 1868 |
} |
| 1869 |
auth, err := encodeAuthArea(AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(objectAuth)}) |
| 1870 |
if err != nil { |
| 1871 |
return nil, err |
| 1872 |
} |
| 1873 |
s, err := scheme.encode() |
| 1874 |
if err != nil { |
| 1875 |
return nil, err |
| 1876 |
} |
| 1877 |
params, err := tpmutil.Pack(qualifyingData, creationHash, tpmutil.RawBytes(s), ticket) |
| 1878 |
if err != nil { |
| 1879 |
return nil, err |
| 1880 |
} |
| 1881 |
return concat(handles, auth, params) |
| 1882 |
} |
| 1883 |
|
| 1884 |
// CertifyCreation generates a signature of a newly-created & |
| 1885 |
// loaded TPM object, using signer as the signing key. |
| 1886 |
func CertifyCreation(rw io.ReadWriter, objectAuth string, object, signer tpmutil.Handle, qualifyingData, creationHash []byte, sigScheme SigScheme, creationTicket Ticket) (attestation, signature []byte, err error) { |
| 1887 |
Cmd, err := encodeCertifyCreation(objectAuth, object, signer, qualifyingData, creationHash, sigScheme, creationTicket) |
| 1888 |
if err != nil { |
| 1889 |
return nil, nil, err |
| 1890 |
} |
| 1891 |
resp, err := runCommand(rw, TagSessions, CmdCertifyCreation, tpmutil.RawBytes(Cmd)) |
| 1892 |
if err != nil { |
| 1893 |
return nil, nil, err |
| 1894 |
} |
| 1895 |
return decodeCertify(resp) |
| 1896 |
} |
| 1897 |
|
| 1898 |
func runCommand(rw io.ReadWriter, tag tpmutil.Tag, Cmd tpmutil.Command, in ...interface{}) ([]byte, error) { |
| 1899 |
resp, code, err := tpmutil.RunCommand(rw, tag, Cmd, in...) |
| 1900 |
if err != nil { |
| 1901 |
return nil, err |
| 1902 |
} |
| 1903 |
if code != tpmutil.RCSuccess { |
| 1904 |
return nil, decodeResponse(code) |
| 1905 |
} |
| 1906 |
return resp, decodeResponse(code) |
| 1907 |
} |
| 1908 |
|
| 1909 |
// concat is a helper for encoding functions that separately encode handle, |
| 1910 |
// auth and param areas. A nil error is always returned, so that callers can |
| 1911 |
// simply return concat(a, b, c). |
| 1912 |
func concat(chunks ...[]byte) ([]byte, error) { |
| 1913 |
return bytes.Join(chunks, nil), nil |
| 1914 |
} |
| 1915 |
|
| 1916 |
func encodePCRExtend(pcr tpmutil.Handle, hashAlg Algorithm, hash tpmutil.RawBytes, password string) ([]byte, error) { |
| 1917 |
ha, err := tpmutil.Pack(pcr) |
| 1918 |
if err != nil { |
| 1919 |
return nil, err |
| 1920 |
} |
| 1921 |
auth, err := encodeAuthArea(AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(password)}) |
| 1922 |
if err != nil { |
| 1923 |
return nil, err |
| 1924 |
} |
| 1925 |
pcrCount := uint32(1) |
| 1926 |
extend, err := tpmutil.Pack(pcrCount, hashAlg, hash) |
| 1927 |
if err != nil { |
| 1928 |
return nil, err |
| 1929 |
} |
| 1930 |
return concat(ha, auth, extend) |
| 1931 |
} |
| 1932 |
|
| 1933 |
// PCRExtend extends a value into the selected PCR |
| 1934 |
func PCRExtend(rw io.ReadWriter, pcr tpmutil.Handle, hashAlg Algorithm, hash []byte, password string) error { |
| 1935 |
Cmd, err := encodePCRExtend(pcr, hashAlg, hash, password) |
| 1936 |
if err != nil { |
| 1937 |
return err |
| 1938 |
} |
| 1939 |
_, err = runCommand(rw, TagSessions, CmdPCRExtend, tpmutil.RawBytes(Cmd)) |
| 1940 |
return err |
| 1941 |
} |
| 1942 |
|
| 1943 |
// ReadPCR reads the value of the given PCR. |
| 1944 |
func ReadPCR(rw io.ReadWriter, pcr int, hashAlg Algorithm) ([]byte, error) { |
| 1945 |
pcrSelection := PCRSelection{ |
| 1946 |
Hash: hashAlg, |
| 1947 |
PCRs: []int{pcr}, |
| 1948 |
} |
| 1949 |
pcrVals, err := ReadPCRs(rw, pcrSelection) |
| 1950 |
if err != nil { |
| 1951 |
return nil, fmt.Errorf("unable to read PCRs from TPM: %v", err) |
| 1952 |
} |
| 1953 |
pcrVal, present := pcrVals[pcr] |
| 1954 |
if !present { |
| 1955 |
return nil, fmt.Errorf("PCR %d value missing from response", pcr) |
| 1956 |
} |
| 1957 |
return pcrVal, nil |
| 1958 |
} |
| 1959 |
|
| 1960 |
func encodePCRReset(pcr tpmutil.Handle) ([]byte, error) { |
| 1961 |
ha, err := tpmutil.Pack(pcr) |
| 1962 |
if err != nil { |
| 1963 |
return nil, err |
| 1964 |
} |
| 1965 |
auth, err := encodeAuthArea(AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: EmptyAuth}) |
| 1966 |
if err != nil { |
| 1967 |
return nil, err |
| 1968 |
} |
| 1969 |
return concat(ha, auth) |
| 1970 |
} |
| 1971 |
|
| 1972 |
// PCRReset resets the value of the given PCR. Usually, only PCR 16 (Debug) and |
| 1973 |
// PCR 23 (Application) are resettable on the default locality. |
| 1974 |
func PCRReset(rw io.ReadWriter, pcr tpmutil.Handle) error { |
| 1975 |
Cmd, err := encodePCRReset(pcr) |
| 1976 |
if err != nil { |
| 1977 |
return err |
| 1978 |
} |
| 1979 |
_, err = runCommand(rw, TagSessions, CmdPCRReset, tpmutil.RawBytes(Cmd)) |
| 1980 |
return err |
| 1981 |
} |
| 1982 |
|
| 1983 |
// EncryptSymmetric encrypts data using a symmetric key. |
| 1984 |
// |
| 1985 |
// WARNING: This command performs low-level cryptographic operations. |
| 1986 |
// Secure use of this command is subtle and requires careful analysis. |
| 1987 |
// Please consult with experts in cryptography for how to use it securely. |
| 1988 |
// |
| 1989 |
// The iv is the initialization vector. The iv must not be empty and its size depends on the |
| 1990 |
// details of the symmetric encryption scheme. |
| 1991 |
// |
| 1992 |
// The data may be longer than block size, EncryptSymmetric will chain |
| 1993 |
// multiple TPM calls to encrypt the entire blob. |
| 1994 |
// |
| 1995 |
// Key handle should point at SymCipher object which is a child of the key (and |
| 1996 |
// not e.g. RSA key itself). |
| 1997 |
func EncryptSymmetric(rw io.ReadWriteCloser, keyAuth string, key tpmutil.Handle, iv, data []byte) ([]byte, error) { |
| 1998 |
return encryptDecryptSymmetric(rw, keyAuth, key, iv, data, false) |
| 1999 |
} |
| 2000 |
|
| 2001 |
// DecryptSymmetric decrypts data using a symmetric key. |
| 2002 |
// |
| 2003 |
// WARNING: This command performs low-level cryptographic operations. |
| 2004 |
// Secure use of this command is subtle and requires careful analysis. |
| 2005 |
// Please consult with experts in cryptography for how to use it securely. |
| 2006 |
// |
| 2007 |
// The iv is the initialization vector. The iv must not be empty and its size |
| 2008 |
// depends on the details of the symmetric encryption scheme. |
| 2009 |
// |
| 2010 |
// The data may be longer than block size, DecryptSymmetric will chain multiple |
| 2011 |
// TPM calls to decrypt the entire blob. |
| 2012 |
// |
| 2013 |
// Key handle should point at SymCipher object which is a child of the key (and |
| 2014 |
// not e.g. RSA key itself). |
| 2015 |
func DecryptSymmetric(rw io.ReadWriteCloser, keyAuth string, key tpmutil.Handle, iv, data []byte) ([]byte, error) { |
| 2016 |
return encryptDecryptSymmetric(rw, keyAuth, key, iv, data, true) |
| 2017 |
} |
| 2018 |
|
| 2019 |
func encodeEncryptDecrypt(keyAuth string, key tpmutil.Handle, iv, data tpmutil.U16Bytes, decrypt bool) ([]byte, error) { |
| 2020 |
ha, err := tpmutil.Pack(key) |
| 2021 |
if err != nil { |
| 2022 |
return nil, err |
| 2023 |
} |
| 2024 |
auth, err := encodeAuthArea(AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(keyAuth)}) |
| 2025 |
if err != nil { |
| 2026 |
return nil, err |
| 2027 |
} |
| 2028 |
// Use encryption key's mode. |
| 2029 |
params, err := tpmutil.Pack(decrypt, AlgNull, iv, data) |
| 2030 |
if err != nil { |
| 2031 |
return nil, err |
| 2032 |
} |
| 2033 |
return concat(ha, auth, params) |
| 2034 |
} |
| 2035 |
|
| 2036 |
func encodeEncryptDecrypt2(keyAuth string, key tpmutil.Handle, iv, data tpmutil.U16Bytes, decrypt bool) ([]byte, error) { |
| 2037 |
ha, err := tpmutil.Pack(key) |
| 2038 |
if err != nil { |
| 2039 |
return nil, err |
| 2040 |
} |
| 2041 |
auth, err := encodeAuthArea(AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(keyAuth)}) |
| 2042 |
if err != nil { |
| 2043 |
return nil, err |
| 2044 |
} |
| 2045 |
// Use encryption key's mode. |
| 2046 |
params, err := tpmutil.Pack(data, decrypt, AlgNull, iv) |
| 2047 |
if err != nil { |
| 2048 |
return nil, err |
| 2049 |
} |
| 2050 |
return concat(ha, auth, params) |
| 2051 |
} |
| 2052 |
|
| 2053 |
func decodeEncryptDecrypt(resp []byte) ([]byte, []byte, error) { |
| 2054 |
var paramSize uint32 |
| 2055 |
var out, nextIV tpmutil.U16Bytes |
| 2056 |
if _, err := tpmutil.Unpack(resp, ¶mSize, &out, &nextIV); err != nil { |
| 2057 |
return nil, nil, err |
| 2058 |
} |
| 2059 |
return out, nextIV, nil |
| 2060 |
} |
| 2061 |
|
| 2062 |
func encryptDecryptBlockSymmetric(rw io.ReadWriteCloser, keyAuth string, key tpmutil.Handle, iv, data []byte, decrypt bool) ([]byte, []byte, error) { |
| 2063 |
Cmd, err := encodeEncryptDecrypt2(keyAuth, key, iv, data, decrypt) |
| 2064 |
if err != nil { |
| 2065 |
return nil, nil, err |
| 2066 |
} |
| 2067 |
resp, err := runCommand(rw, TagSessions, CmdEncryptDecrypt2, tpmutil.RawBytes(Cmd)) |
| 2068 |
if err != nil { |
| 2069 |
fmt0Err, ok := err.(Error) |
| 2070 |
if ok && fmt0Err.Code == RCCommandCode { |
| 2071 |
// If TPM2_EncryptDecrypt2 is not supported, fall back to |
| 2072 |
// TPM2_EncryptDecrypt. |
| 2073 |
Cmd, _ := encodeEncryptDecrypt(keyAuth, key, iv, data, decrypt) |
| 2074 |
resp, err = runCommand(rw, TagSessions, CmdEncryptDecrypt, tpmutil.RawBytes(Cmd)) |
| 2075 |
if err != nil { |
| 2076 |
return nil, nil, err |
| 2077 |
} |
| 2078 |
} |
| 2079 |
} |
| 2080 |
if err != nil { |
| 2081 |
return nil, nil, err |
| 2082 |
} |
| 2083 |
return decodeEncryptDecrypt(resp) |
| 2084 |
} |
| 2085 |
|
| 2086 |
func encryptDecryptSymmetric(rw io.ReadWriteCloser, keyAuth string, key tpmutil.Handle, iv, data []byte, decrypt bool) ([]byte, error) { |
| 2087 |
var out, block []byte |
| 2088 |
var err error |
| 2089 |
|
| 2090 |
for rest := data; len(rest) > 0; { |
| 2091 |
if len(rest) > maxDigestBuffer { |
| 2092 |
block, rest = rest[:maxDigestBuffer], rest[maxDigestBuffer:] |
| 2093 |
} else { |
| 2094 |
block, rest = rest, nil |
| 2095 |
} |
| 2096 |
block, iv, err = encryptDecryptBlockSymmetric(rw, keyAuth, key, iv, block, decrypt) |
| 2097 |
if err != nil { |
| 2098 |
return nil, err |
| 2099 |
} |
| 2100 |
out = append(out, block...) |
| 2101 |
} |
| 2102 |
|
| 2103 |
return out, nil |
| 2104 |
} |
| 2105 |
|
| 2106 |
func encodeRSAEncrypt(key tpmutil.Handle, message tpmutil.U16Bytes, scheme *AsymScheme, label string) ([]byte, error) { |
| 2107 |
ha, err := tpmutil.Pack(key) |
| 2108 |
if err != nil { |
| 2109 |
return nil, err |
| 2110 |
} |
| 2111 |
m, err := tpmutil.Pack(message) |
| 2112 |
if err != nil { |
| 2113 |
return nil, err |
| 2114 |
} |
| 2115 |
s, err := scheme.encode() |
| 2116 |
if err != nil { |
| 2117 |
return nil, err |
| 2118 |
} |
| 2119 |
if label != "" { |
| 2120 |
label += "\x00" |
| 2121 |
} |
| 2122 |
l, err := tpmutil.Pack(tpmutil.U16Bytes(label)) |
| 2123 |
if err != nil { |
| 2124 |
return nil, err |
| 2125 |
} |
| 2126 |
return concat(ha, m, s, l) |
| 2127 |
} |
| 2128 |
|
| 2129 |
func decodeRSAEncrypt(resp []byte) ([]byte, error) { |
| 2130 |
var out tpmutil.U16Bytes |
| 2131 |
_, err := tpmutil.Unpack(resp, &out) |
| 2132 |
return out, err |
| 2133 |
} |
| 2134 |
|
| 2135 |
// RSAEncrypt performs RSA encryption in the TPM according to RFC 3447. The key must be |
| 2136 |
// a (public) key loaded into the TPM beforehand. Note that when using OAEP with a label, |
| 2137 |
// a null byte is appended to the label and the null byte is included in the padding |
| 2138 |
// scheme. |
| 2139 |
func RSAEncrypt(rw io.ReadWriter, key tpmutil.Handle, message []byte, scheme *AsymScheme, label string) ([]byte, error) { |
| 2140 |
Cmd, err := encodeRSAEncrypt(key, message, scheme, label) |
| 2141 |
if err != nil { |
| 2142 |
return nil, err |
| 2143 |
} |
| 2144 |
resp, err := runCommand(rw, TagNoSessions, CmdRSAEncrypt, tpmutil.RawBytes(Cmd)) |
| 2145 |
if err != nil { |
| 2146 |
return nil, err |
| 2147 |
} |
| 2148 |
return decodeRSAEncrypt(resp) |
| 2149 |
} |
| 2150 |
|
| 2151 |
func encodeRSADecrypt(sessionHandle, key tpmutil.Handle, password string, message tpmutil.U16Bytes, scheme *AsymScheme, label string) ([]byte, error) { |
| 2152 |
ha, err := tpmutil.Pack(key) |
| 2153 |
if err != nil { |
| 2154 |
return nil, err |
| 2155 |
} |
| 2156 |
auth, err := encodeAuthArea(AuthCommand{Session: sessionHandle, Attributes: AttrContinueSession, Auth: []byte(password)}) |
| 2157 |
if err != nil { |
| 2158 |
return nil, err |
| 2159 |
} |
| 2160 |
m, err := tpmutil.Pack(message) |
| 2161 |
if err != nil { |
| 2162 |
return nil, err |
| 2163 |
} |
| 2164 |
s, err := scheme.encode() |
| 2165 |
if err != nil { |
| 2166 |
return nil, err |
| 2167 |
} |
| 2168 |
if label != "" { |
| 2169 |
label += "\x00" |
| 2170 |
} |
| 2171 |
l, err := tpmutil.Pack(tpmutil.U16Bytes(label)) |
| 2172 |
if err != nil { |
| 2173 |
return nil, err |
| 2174 |
} |
| 2175 |
return concat(ha, auth, m, s, l) |
| 2176 |
} |
| 2177 |
|
| 2178 |
func decodeRSADecrypt(resp []byte) ([]byte, error) { |
| 2179 |
var out tpmutil.U16Bytes |
| 2180 |
var paramSize uint32 |
| 2181 |
_, err := tpmutil.Unpack(resp, ¶mSize, &out) |
| 2182 |
return out, err |
| 2183 |
} |
| 2184 |
|
| 2185 |
// RSADecrypt performs RSA decryption in the TPM according to RFC 3447. The key must be |
| 2186 |
// a private RSA key in the TPM with FlagDecrypt set. Note that when using OAEP with a |
| 2187 |
// label, a null byte is appended to the label and the null byte is included in the |
| 2188 |
// padding scheme. |
| 2189 |
func RSADecrypt(rw io.ReadWriter, key tpmutil.Handle, password string, message []byte, scheme *AsymScheme, label string) ([]byte, error) { |
| 2190 |
return RSADecryptWithSession(rw, HandlePasswordSession, key, password, message, scheme, label) |
| 2191 |
} |
| 2192 |
|
| 2193 |
// RSADecryptWithSession performs RSA decryption in the TPM according to RFC 3447. The key must be |
| 2194 |
// a private RSA key in the TPM with FlagDecrypt set. Note that when using OAEP with a |
| 2195 |
// label, a null byte is appended to the label and the null byte is included in the |
| 2196 |
// padding scheme. |
| 2197 |
func RSADecryptWithSession(rw io.ReadWriter, sessionHandle, key tpmutil.Handle, password string, message []byte, scheme *AsymScheme, label string) ([]byte, error) { |
| 2198 |
Cmd, err := encodeRSADecrypt(sessionHandle, key, password, message, scheme, label) |
| 2199 |
if err != nil { |
| 2200 |
return nil, err |
| 2201 |
} |
| 2202 |
resp, err := runCommand(rw, TagSessions, CmdRSADecrypt, tpmutil.RawBytes(Cmd)) |
| 2203 |
if err != nil { |
| 2204 |
return nil, err |
| 2205 |
} |
| 2206 |
return decodeRSADecrypt(resp) |
| 2207 |
} |
| 2208 |
|
| 2209 |
func encodeECDHKeyGen(key tpmutil.Handle) ([]byte, error) { |
| 2210 |
return tpmutil.Pack(key) |
| 2211 |
} |
| 2212 |
|
| 2213 |
func decodeECDHKeyGen(resp []byte) (*ECPoint, *ECPoint, error) { |
| 2214 |
// Unpack z and pub as TPM2B_ECC_POINT, which is a TPMS_ECC_POINT with a total size prepended. |
| 2215 |
var z2B, pub2B tpmutil.U16Bytes |
| 2216 |
_, err := tpmutil.Unpack(resp, &z2B, &pub2B) |
| 2217 |
if err != nil { |
| 2218 |
return nil, nil, err |
| 2219 |
} |
| 2220 |
var zPoint, pubPoint ECPoint |
| 2221 |
_, err = tpmutil.Unpack(z2B, &zPoint.XRaw, &zPoint.YRaw) |
| 2222 |
if err != nil { |
| 2223 |
return nil, nil, err |
| 2224 |
} |
| 2225 |
_, err = tpmutil.Unpack(pub2B, &pubPoint.XRaw, &pubPoint.YRaw) |
| 2226 |
if err != nil { |
| 2227 |
return nil, nil, err |
| 2228 |
} |
| 2229 |
return &zPoint, &pubPoint, nil |
| 2230 |
} |
| 2231 |
|
| 2232 |
// ECDHKeyGen generates an ephemeral ECC key, calculates the ECDH point multiplcation of the |
| 2233 |
// ephemeral private key and a loaded public key, and returns the public ephemeral point along with |
| 2234 |
// the coordinates of the resulting point. |
| 2235 |
func ECDHKeyGen(rw io.ReadWriter, key tpmutil.Handle) (zPoint, pubPoint *ECPoint, err error) { |
| 2236 |
Cmd, err := encodeECDHKeyGen(key) |
| 2237 |
if err != nil { |
| 2238 |
return nil, nil, err |
| 2239 |
} |
| 2240 |
resp, err := runCommand(rw, TagNoSessions, CmdECDHKeyGen, tpmutil.RawBytes(Cmd)) |
| 2241 |
if err != nil { |
| 2242 |
return nil, nil, err |
| 2243 |
} |
| 2244 |
return decodeECDHKeyGen(resp) |
| 2245 |
} |
| 2246 |
|
| 2247 |
func encodeECDHZGen(key tpmutil.Handle, password string, inPoint ECPoint) ([]byte, error) { |
| 2248 |
ha, err := tpmutil.Pack(key) |
| 2249 |
if err != nil { |
| 2250 |
return nil, err |
| 2251 |
} |
| 2252 |
auth, err := encodeAuthArea(AuthCommand{Session: HandlePasswordSession, Attributes: AttrContinueSession, Auth: []byte(password)}) |
| 2253 |
if err != nil { |
| 2254 |
return nil, err |
| 2255 |
} |
| 2256 |
p, err := tpmutil.Pack(inPoint) |
| 2257 |
if err != nil { |
| 2258 |
return nil, err |
| 2259 |
} |
| 2260 |
// Pack the TPMS_ECC_POINT as a TPM2B_ECC_POINT. |
| 2261 |
p2B, err := tpmutil.Pack(tpmutil.U16Bytes(p)) |
| 2262 |
if err != nil { |
| 2263 |
return nil, err |
| 2264 |
} |
| 2265 |
return concat(ha, auth, p2B) |
| 2266 |
} |
| 2267 |
|
| 2268 |
func decodeECDHZGen(resp []byte) (*ECPoint, error) { |
| 2269 |
var paramSize uint32 |
| 2270 |
// Unpack a TPM2B_ECC_POINT, which is a TPMS_ECC_POINT with a total size prepended. |
| 2271 |
var z2B tpmutil.U16Bytes |
| 2272 |
_, err := tpmutil.Unpack(resp, ¶mSize, &z2B) |
| 2273 |
if err != nil { |
| 2274 |
return nil, err |
| 2275 |
} |
| 2276 |
var zPoint ECPoint |
| 2277 |
_, err = tpmutil.Unpack(z2B, &zPoint.XRaw, &zPoint.YRaw) |
| 2278 |
if err != nil { |
| 2279 |
return nil, err |
| 2280 |
} |
| 2281 |
return &zPoint, nil |
| 2282 |
} |
| 2283 |
|
| 2284 |
// ECDHZGen performs ECDH point multiplication between a private key held in the TPM and a given |
| 2285 |
// public point, returning the coordinates of the resulting point. The key must have FlagDecrypt |
| 2286 |
// set. |
| 2287 |
func ECDHZGen(rw io.ReadWriter, key tpmutil.Handle, password string, inPoint ECPoint) (zPoint *ECPoint, err error) { |
| 2288 |
Cmd, err := encodeECDHZGen(key, password, inPoint) |
| 2289 |
if err != nil { |
| 2290 |
return nil, err |
| 2291 |
} |
| 2292 |
resp, err := runCommand(rw, TagSessions, CmdECDHZGen, tpmutil.RawBytes(Cmd)) |
| 2293 |
if err != nil { |
| 2294 |
return nil, err |
| 2295 |
} |
| 2296 |
return decodeECDHZGen(resp) |
| 2297 |
} |
| 2298 |
|
| 2299 |
// DictionaryAttackLockReset cancels the effect of a TPM lockout due to a number |
| 2300 |
// of successive authorization failures, by setting the lockout counter to zero. |
| 2301 |
// The command requires Lockout Authorization and only one lockoutAuth authorization |
| 2302 |
// failure is allowed for this command during a lockoutRecovery interval. |
| 2303 |
// Lockout Authorization value by default is empty and can be changed via |
| 2304 |
// a call to HierarchyChangeAuth(HandleLockout). |
| 2305 |
func DictionaryAttackLockReset(rw io.ReadWriter, auth AuthCommand) error { |
| 2306 |
ha, err := tpmutil.Pack(HandleLockout) |
| 2307 |
if err != nil { |
| 2308 |
return err |
| 2309 |
} |
| 2310 |
encodedAuth, err := encodeAuthArea(auth) |
| 2311 |
if err != nil { |
| 2312 |
return err |
| 2313 |
} |
| 2314 |
Cmd, err := concat(ha, encodedAuth) |
| 2315 |
if err != nil { |
| 2316 |
return err |
| 2317 |
} |
| 2318 |
_, err = runCommand(rw, TagSessions, CmdDictionaryAttackLockReset, tpmutil.RawBytes(Cmd)) |
| 2319 |
return err |
| 2320 |
} |
| 2321 |
|
| 2322 |
// DictionaryAttackParameters changes the lockout parameters. |
| 2323 |
// The command requires Lockout Authorization and has same authorization policy |
| 2324 |
// as in DictionaryAttackLockReset. |
| 2325 |
func DictionaryAttackParameters(rw io.ReadWriter, auth AuthCommand, maxTries, recoveryTime, lockoutRecovery uint32) error { |
| 2326 |
ha, err := tpmutil.Pack(HandleLockout) |
| 2327 |
if err != nil { |
| 2328 |
return err |
| 2329 |
} |
| 2330 |
encodedAuth, err := encodeAuthArea(auth) |
| 2331 |
if err != nil { |
| 2332 |
return err |
| 2333 |
} |
| 2334 |
params, err := tpmutil.Pack(maxTries, recoveryTime, lockoutRecovery) |
| 2335 |
if err != nil { |
| 2336 |
return err |
| 2337 |
} |
| 2338 |
Cmd, err := concat(ha, encodedAuth, params) |
| 2339 |
if err != nil { |
| 2340 |
return err |
| 2341 |
} |
| 2342 |
_, err = runCommand(rw, TagSessions, CmdDictionaryAttackParameters, tpmutil.RawBytes(Cmd)) |
| 2343 |
return err |
| 2344 |
} |
| 2345 |
|
| 2346 |
// PolicyCommandCode indicates that the authorization will be limited to a specific command code |
| 2347 |
func PolicyCommandCode(rw io.ReadWriter, session tpmutil.Handle, cc tpmutil.Command) error { |
| 2348 |
data, err := tpmutil.Pack(session, cc) |
| 2349 |
if err != nil { |
| 2350 |
return err |
| 2351 |
} |
| 2352 |
_, err = runCommand(rw, TagNoSessions, CmdPolicyCommandCode, data) |
| 2353 |
return err |
| 2354 |
} |