Skip to content
Merged
Show file tree
Hide file tree
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
182 changes: 182 additions & 0 deletions api/bootloader/development_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
// SPDX-License-Identifier: Apache-2.0

package bootloader_test

import (
"bytes"
"encoding/binary"
"encoding/hex"
"errors"
"os"
"testing"

"github.com/BitBoxSwiss/bitbox02-api-go/api/bootloader"
"github.com/BitBoxSwiss/bitbox02-api-go/api/common"
"github.com/BitBoxSwiss/bitbox02-api-go/util/semver"
"github.com/stretchr/testify/require"
)

// Extending OP_VERSIONS must preserve the old counters and tolerate future trailing fields.
func TestVersionsStage0(t *testing.T) {
legacy := binary.LittleEndian.AppendUint32([]byte{'v', 0}, 56)
legacy = binary.LittleEndian.AppendUint32(legacy, 4)
for _, test := range []struct {
name string
tail []byte
stage0 uint16
}{
{"legacy", nil, 0},
{"unknown", []byte{0, 0}, 0},
{"stage0-v3", []byte{3, 0}, 3},
{"future", []byte{0x34, 0x12, 7, 8}, 0x1234},
} {
t.Run(test.name, func(t *testing.T) {
communication := &communicationMock{query: func(msg []byte) ([]byte, error) {
require.Equal(t, []byte{'v'}, msg)
return append(bytes.Clone(legacy), test.tail...), nil
}}
device := bootloader.NewDevice(semver.NewSemVer(1, 2, 4), common.ProductBitBox02Multi, communication, nil)
info, err := device.Versions()
require.NoError(t, err)
require.Equal(t, uint32(56), info.FirmwareVersion)
require.Equal(t, uint32(4), info.SigningPubkeysVersion)
if test.stage0 == 0 {
require.Nil(t, info.Stage0Version)
} else {
require.NotNil(t, info.Stage0Version)
require.Equal(t, test.stage0, *info.Stage0Version)
}
})
}
for _, length := range []int{0, 1, 7, 9} {
communication := &communicationMock{query: func([]byte) ([]byte, error) {
return append([]byte{'v', 0}, make([]byte, length)...), nil
}}
device := bootloader.NewDevice(semver.NewSemVer(1, 2, 4), common.ProductBitBox02Multi, communication, nil)
_, err := device.Versions()
require.Error(t, err)
}
}

// Unsigned uploads must omit signature writes and must never be offered to production devices.
func TestUpgradeUnsignedFirmware(t *testing.T) {
for _, development := range []bool{false, true} {
firmware := bytes.Repeat([]byte{0x42}, 4097)
var commands []byte
var written []byte
communication := &communicationMock{
query: func(msg []byte) ([]byte, error) {
commands = append(commands, msg[0])
switch msg[0] {
case 'e':
require.Equal(t, []byte{'e', 2}, msg)
case 'w':
require.Equal(t, byte(len(written)/4096), msg[1])
written = append(written, msg[2:]...)
default:
t.Fatalf("unexpected command %q", msg[0])
}
return []byte{msg[0], 0}, nil
},
sendFrame: func(msg string) error {
commands = append(commands, msg...)
return nil
},
}
device := bootloader.NewDevice(semver.NewSemVer(1, 2, 2), common.ProductBitBox02Multi,
communication, func(*bootloader.Status) {}, bootloader.WithDevelopment(development))
err := device.UpgradeUnsignedFirmware(firmware)
if !development {
require.Error(t, err)
require.Empty(t, commands)
continue
}
require.NoError(t, err)
require.Equal(t, []byte("ewwr"), commands)
require.Equal(t, firmware, written[:len(firmware)])
require.Equal(t, bytes.Repeat([]byte{0xff}, 8192-len(firmware)), written[len(firmware):])
require.True(t, device.Status().UpgradeSuccessful)
require.Error(t, device.UpgradeUnsignedFirmware(firmware))
}
}

// A failed write must prevent reboot; retrying must clear the previous error status.
func TestUpgradeUnsignedFirmwareFailure(t *testing.T) {
fail := true
communication := &communicationMock{query: func(msg []byte) ([]byte, error) {
if fail {
return nil, errors.New("write failed")
}
return []byte{msg[0], 0}, nil
}, sendFrame: func(string) error {
require.False(t, fail)
return nil
}}
device := bootloader.NewDevice(semver.NewSemVer(1, 2, 4), common.ProductBitBox02Multi,
communication, func(*bootloader.Status) {}, bootloader.WithDevelopment(true))
require.Error(t, device.UpgradeUnsignedFirmware(nil))
require.Error(t, device.UpgradeUnsignedFirmware(make([]byte, 884737)))
require.Error(t, device.UpgradeUnsignedFirmware([]byte{1}))
require.False(t, device.Status().Upgrading)
require.False(t, device.Status().UpgradeSuccessful)
fail = false
require.NoError(t, device.UpgradeUnsignedFirmware([]byte{1}))
require.Empty(t, device.Status().ErrMsg)
}

// Development devices must still report signature failures for regular signed releases.
func TestDevelopmentSignedFirmwareFailure(t *testing.T) {
firmware, err := os.ReadFile("testdata/firmware-btc.v4.2.2.signed.bin")
require.NoError(t, err)
communication := &communicationMock{query: func(msg []byte) ([]byte, error) {
if msg[0] == 's' {
return []byte{'s', 1}, nil
}
return []byte{msg[0], 0}, nil
}, sendFrame: func(string) error {
t.Fatal("must not reboot after a failed signature check")
return nil
}}
device := bootloader.NewDevice(semver.NewSemVer(1, 2, 4), common.ProductBitBox02BTCOnly,
communication, func(*bootloader.Status) {}, bootloader.WithDevelopment(true))
require.Error(t, device.UpgradeFirmware(firmware))
require.False(t, device.Status().Upgrading)
require.False(t, device.Status().UpgradeSuccessful)
}

// The stored counter remains 56 while the bootloader's hash scheme changes.
func TestContainsFirmware(t *testing.T) {
firmware, err := os.ReadFile("testdata/firmware-btc.v4.2.2.bin")
require.NoError(t, err)
for _, test := range []struct {
version *semver.SemVer
hash string
}{
{semver.NewSemVer(1, 0, 0), "c130ffbcfffbb47be8780300b0476c91795f5e1d815dfe4c91db2edbec53d322"},
{semver.NewSemVer(1, 2, 2), "f90cd5f1b068322cc157ec3a3d855089f868c2343ccc2fe81153054dfc8d5ac8"},
{semver.NewSemVer(1, 2, 4), "a69c75696c16fc75002224264647c4e10ec31c9aef8c188ce5e4f43e8a207511"},
} {
t.Run(test.version.String(), func(t *testing.T) {
hash, err := hex.DecodeString(test.hash)
require.NoError(t, err)
communication := &communicationMock{query: func(msg []byte) ([]byte, error) {
switch msg[0] {
case 'v':
return []byte{'v', 0, 56, 0, 0, 0, 4, 0, 0, 0}, nil
case 'h':
require.Equal(t, []byte{'h', 0, 0}, msg)
return append(append([]byte{'h', 0}, hash...), make([]byte, 32)...), nil
default:
return nil, errors.New("unexpected command")
}
}}
device := bootloader.NewDevice(test.version, common.ProductBitBox02Multi, communication, nil)
matches, err := device.ContainsFirmware(firmware)
require.NoError(t, err)
require.True(t, matches)
matches, err = device.ContainsFirmware([]byte("different firmware"))
require.NoError(t, err)
require.False(t, matches)
})
}
}
92 changes: 79 additions & 13 deletions api/bootloader/device.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ type Device struct {
communication Communication
version *semver.SemVer
product common.Product
development bool
status *Status
onStatusChanged func(*Status)
}
Expand All @@ -74,14 +75,32 @@ func NewDevice(
product common.Product,
communication Communication,
onStatusChanged func(*Status),
options ...DeviceOption,
) *Device {
return &Device{
device := &Device{
communication: communication,
version: version,
product: product,
status: &Status{},
onStatusChanged: onStatusChanged,
}
for _, option := range options {
option(device)
}
return device
}

// DeviceOption configures a bootloader device.
type DeviceOption func(*Device)

// WithDevelopment records whether this is a development bootloader.
func WithDevelopment(development bool) DeviceOption {
return func(device *Device) { device.development = development }
}

// IsDevelopment reports whether this is a development bootloader.
func (device *Device) IsDevelopment() bool {
return device.development
}

// Product returns the bootloader product.
Expand Down Expand Up @@ -116,18 +135,38 @@ func (device *Device) query(cmd rune, data []byte) ([]byte, error) {
return reply[2:], nil
}

// Versions queries the device for the firmware and signing pubkeys version.
func (device *Device) Versions() (uint32, uint32, error) {
// VersionInfo contains the installed firmware, signing key and stage0 versions.
type VersionInfo struct {
FirmwareVersion uint32
SigningPubkeysVersion uint32
// Stage0Version is nil when the bootloader does not report a known stage0 version.
Stage0Version *uint16
}

// Versions queries version information, including stage0 starting with bootloader v1.2.4.
func (device *Device) Versions() (*VersionInfo, error) {
response, err := device.query('v', nil)
if err != nil {
return 0, 0, err
return nil, err
}
if len(response) < 8 {
return 0, 0, errp.Newf("Unexpected reply: %v", response)
reader := bytes.NewReader(response)
info := &VersionInfo{}
if err := binary.Read(reader, binary.LittleEndian, &info.FirmwareVersion); err != nil {
return nil, errp.WithMessage(err, "invalid firmware version")
}
firmwareVersion := binary.LittleEndian.Uint32(response[:4])
signingPubkeysVersion := binary.LittleEndian.Uint32(response[4:8])
return firmwareVersion, signingPubkeysVersion, nil
if err := binary.Read(reader, binary.LittleEndian, &info.SigningPubkeysVersion); err != nil {
return nil, errp.WithMessage(err, "invalid signing pubkeys version")
}
if reader.Len() > 0 {
var stage0Version uint16
if err := binary.Read(reader, binary.LittleEndian, &stage0Version); err != nil {
return nil, errp.WithMessage(err, "invalid stage0 version")
}
if stage0Version != 0 {
info.Stage0Version = &stage0Version
}
}
return info, nil
}

// GetHashes queries the device for the firmware and signing keydata hashes.
Expand Down Expand Up @@ -239,6 +278,9 @@ func (device *Device) writeChunk(chunkNum uint8, chunk []byte) error {
}

func (device *Device) flashUnsignedFirmware(firmware []byte, progressCallback func(float64)) error {
if len(firmware) == 0 {
return errp.New("firmware is empty")
}
if len(firmware) > firmwareChunks*chunkSize {
return errp.New("firmware too big")
}
Expand Down Expand Up @@ -309,16 +351,34 @@ func (device *Device) flashSignedFirmware(firmware []byte, progressCallback func

// UpgradeFirmware uploads a signed bitbox02 firmware release to the device.
func (device *Device) UpgradeFirmware(firmware []byte) error {
return device.upgradeFirmware(func(onProgress func(float64)) error {
return device.flashSignedFirmware(firmware, onProgress)
})
}

// UpgradeUnsignedFirmware uploads unsigned firmware to a development device without changing
// its firmware counter or signing data, then reboots it.
func (device *Device) UpgradeUnsignedFirmware(firmware []byte) error {
if !device.IsDevelopment() {
return errp.New("unsigned firmware requires a development bootloader")
}
return device.upgradeFirmware(func(onProgress func(float64)) error {
return device.flashUnsignedFirmware(firmware, onProgress)
})
}

func (device *Device) upgradeFirmware(flash func(func(float64)) error) error {
if device.status.Upgrading {
return errp.New("already in progress")
}
*device.status = Status{}
device.onStatusChanged(device.status)
onProgress := func(progress float64) {
device.status.Upgrading = true
device.status.Progress = progress
device.onStatusChanged(device.status)
}
err := device.flashSignedFirmware(firmware, onProgress)
err := flash(onProgress)
if err != nil {
device.status.Upgrading = false
device.status.ErrMsg = err.Error()
Expand All @@ -336,7 +396,13 @@ func (device *Device) Erased() (bool, error) {
// We check by comparing the device reported firmware hash. If erased, the firmware is all
// '\xFF'.

firmwareVersion, _, err := device.Versions()
return device.ContainsFirmware(nil)
}

// ContainsFirmware compares the installed firmware with an unsigned image, including erased
// padding. It uses the connected bootloader's hash format and stored firmware counter.
func (device *Device) ContainsFirmware(firmware []byte) (bool, error) {
versions, err := device.Versions()
if err != nil {
return false, err
}
Expand All @@ -348,7 +414,7 @@ func (device *Device) Erased() (bool, error) {
} else if device.version.AtLeast(semver.NewSemVer(1, 2, 0)) {
scheme = firmwareHashProduct
}
emptyFirmwareHash, err := hashFirmware(device.product, firmwareVersion, nil, scheme)
expectedFirmwareHash, err := hashFirmware(device.product, versions.FirmwareVersion, firmware, scheme)
if err != nil {
return false, err
}
Expand All @@ -357,5 +423,5 @@ func (device *Device) Erased() (bool, error) {
if err != nil {
return false, err
}
return bytes.Equal(firmwareHash, emptyFirmwareHash), nil
return bytes.Equal(firmwareHash, expectedFirmwareHash), nil
}
11 changes: 6 additions & 5 deletions api/bootloader/device_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,18 +96,19 @@ func TestVersions(t *testing.T) {
signingPubkeysVersion := "\xe6\x1d\x00\x00"
return []byte("v\x00" + firmwareVersion + signingPubkeysVersion), nil
}
firmwareVersion, signingPubkeysVersion, err := env.device.Versions()
versions, err := env.device.Versions()
require.NoError(t, err)
require.Equal(t, uint32(323213), firmwareVersion)
require.Equal(t, uint32(7654), signingPubkeysVersion)
require.Equal(t, uint32(323213), versions.FirmwareVersion)
require.Equal(t, uint32(7654), versions.SigningPubkeysVersion)
require.Nil(t, versions.Stage0Version)
})

// error response
expectedErr := errors.New("fail")
env.communication.query = func(msg []byte) ([]byte, error) {
return nil, expectedErr
}
_, _, err := env.device.Versions()
_, err := env.device.Versions()
require.Equal(t, expectedErr, err)

for _, testResponse := range []string{
Expand All @@ -120,7 +121,7 @@ func TestVersions(t *testing.T) {
env.communication.query = func([]byte) ([]byte, error) {
return []byte(testResponse), nil
}
_, _, err := env.device.Versions()
_, err := env.device.Versions()
require.Error(t, err)
}
})
Expand Down
Loading