Skip to content

Commit

Permalink
api/bootloader: add ParseSignedFirwmare() util function
Browse files Browse the repository at this point in the history
  • Loading branch information
benma committed May 13, 2024
1 parent ee41ccd commit fb2552b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 11 deletions.
16 changes: 5 additions & 11 deletions api/bootloader/device.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,18 +233,12 @@ func (device *Device) flashUnsignedFirmware(firmware []byte, progressCallback fu
// format is invalid, or the firmware magic does not match the expected magic according to the
// device product.
func (device *Device) parseSignedFirmware(firmware []byte) ([]byte, []byte, error) {
if len(firmware) <= magicLen+sigDataLen {
return nil, nil, errp.New("firmware too small")
}
magic, firmware := firmware[:magicLen], firmware[magicLen:]
sigData, firmware := firmware[:sigDataLen], firmware[sigDataLen:]

expectedMagic, ok := sigDataMagic[device.product]
if !ok {
return nil, nil, errp.New("unrecognized product")
product, sigData, firmware, err := ParseSignedFirmware(firmware)
if err != nil {
return nil, nil, err
}
if binary.BigEndian.Uint32(magic) != expectedMagic {
return nil, nil, errp.New("invalid signing pubkeys data magic")
if product != device.product {
return nil, nil, errp.New("signed firmware binary does not match device product")
}
return sigData, firmware, nil
}
Expand Down
28 changes: 28 additions & 0 deletions api/bootloader/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ import (
"bytes"
"crypto/sha256"
"encoding/binary"

"github.com/digitalbitbox/bitbox02-api-go/api/common"
"github.com/digitalbitbox/bitbox02-api-go/util/errp"
)

// HashFirmware returns the hash of `<firmware version><firmware>`, as computed by the bootloader to
Expand All @@ -35,3 +38,28 @@ func HashFirmware(firmwareVersion uint32, unsignedFirmware []byte) []byte {
copy(padded, unsignedFirmware)
return doubleHash(append(firmwareVersionLE, padded...))
}

// ParseSignedFirmware parses a signed firmware file and returns (sigdata, firmware). Errors if the
// format is invalid, or the firmware magic does not match the expected magic according to the
// device product.
func ParseSignedFirmware(firmware []byte) (common.Product, []byte, []byte, error) {
if len(firmware) <= magicLen+sigDataLen {
return "", nil, nil, errp.New("firmware too small")
}
magic, firmware := firmware[:magicLen], firmware[magicLen:]
sigData, firmware := firmware[:sigDataLen], firmware[sigDataLen:]

var product common.Product
magicInt := binary.BigEndian.Uint32(magic)
for p, productMagic := range sigDataMagic {
if magicInt == productMagic {
product = p
break
}
}
if product == "" {
return "", nil, nil, errp.Newf("unrecognized magic")
}

return product, sigData, firmware, nil
}

0 comments on commit fb2552b

Please sign in to comment.