Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tpmutil: Fix integer casting on 32-bit platforms #253

Merged
merged 1 commit into from
Jun 29, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions tpmutil/structures.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import (
// from resulting in a massive memory allocation, potentially causing
// an OOM condition on the system.
// We expect no buffer from a TPM to approach 1Mb in size.
const maxBytesBufferSize = 1024 * 1024 // 1Mb.
const maxBytesBufferSize uint32 = 1024 * 1024 // 1Mb.

// RawBytes is for Pack and RunCommand arguments that are already encoded.
// Compared to []byte, RawBytes will not be prepended with slice length during
Expand All @@ -38,16 +38,16 @@ type U16Bytes []byte

// TPMMarshal packs U16Bytes
func (b *U16Bytes) TPMMarshal(out io.Writer) error {
size := uint16(len([]byte(*b)))
if err := binary.Write(out, binary.BigEndian, size); err != nil {
size := len([]byte(*b))
if err := binary.Write(out, binary.BigEndian, uint16(size)); err != nil {
return err
}

n, err := out.Write(*b)
if err != nil {
return err
}
if n != int(size) {
if n != size {
return fmt.Errorf("unable to write all contents of U16Bytes")
}
return nil
Expand Down Expand Up @@ -82,16 +82,16 @@ type U32Bytes []byte

// TPMMarshal packs U32Bytes
func (b *U32Bytes) TPMMarshal(out io.Writer) error {
size := uint32(len([]byte(*b)))
if err := binary.Write(out, binary.BigEndian, size); err != nil {
size := len([]byte(*b))
if err := binary.Write(out, binary.BigEndian, uint32(size)); err != nil {
return err
}

n, err := out.Write(*b)
if err != nil {
return err
}
if n != int(size) {
if n != size {
return fmt.Errorf("unable to write all contents of U32Bytes")
}
return nil
Expand All @@ -103,11 +103,12 @@ func (b *U32Bytes) TPMUnmarshal(in io.Reader) error {
if err := binary.Read(in, binary.BigEndian, &tmpSize); err != nil {
return err
}
size := int(tmpSize)

if size > maxBytesBufferSize {
if tmpSize > maxBytesBufferSize {
return bytes.ErrTooLarge
}
// We can now safely cast to an int on 32-bit or 64-bit machines
size := int(tmpSize)

if len(*b) >= size {
*b = (*b)[:size]
Expand Down