-
Notifications
You must be signed in to change notification settings - Fork 81
/
device.go
365 lines (325 loc) · 10.4 KB
/
device.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
// Copyright 2018 Shift Devices AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package bitbox02bootloader contains the API to the physical device.
package bitbox02bootloader
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"io"
"math"
"sync"
"time"
"github.com/digitalbitbox/bitbox-wallet-app/backend/devices/bitbox02common"
"github.com/digitalbitbox/bitbox-wallet-app/backend/devices/device"
devicepkg "github.com/digitalbitbox/bitbox-wallet-app/backend/devices/device"
keystoreInterface "github.com/digitalbitbox/bitbox-wallet-app/backend/keystore"
"github.com/digitalbitbox/bitbox-wallet-app/backend/signing"
"github.com/digitalbitbox/bitbox-wallet-app/util/errp"
"github.com/digitalbitbox/bitbox-wallet-app/util/logging"
"github.com/digitalbitbox/bitbox-wallet-app/util/semver"
"github.com/sirupsen/logrus"
)
const (
chunkSize = 8 * 512
maxFirmwareSize = 884736
// max number of chunks that can be written when flashing the firmware
firmwareChunks = maxFirmwareSize / chunkSize
numRootKeys = 3
numSigningKeys = 3
magicLen = 4
versionLen = 4
signingPubkeysDataLen = versionLen + numSigningKeys*64 + numRootKeys*64
firmwareDataLen = versionLen + numSigningKeys*64
sigDataLen = signingPubkeysDataLen + firmwareDataLen
)
var sigDataMagic = map[bitbox02common.Edition]uint32{
bitbox02common.EditionStandard: 0x653f362b,
bitbox02common.EditionBTCOnly: 0x11233B0B,
}
// ProductName is the name of the BitBox02 bootloader product.
const ProductName = "bitbox02-bootloader"
// Communication contains functions needed to communicate with the device.
type Communication interface {
SendFrame(string) error
ReadFrame() ([]byte, error)
Close()
}
// Status has all the info to handle the bootloader mode.
type Status struct {
Upgrading bool `json:"upgrading"`
Progress float64 `json:"progress"`
UpgradeSuccessful bool `json:"upgradeSuccessful"`
ErrMsg string `json:"errMsg"`
RebootSeconds int `json:"rebootSeconds"`
}
// EventStatusChanged is fired when the status changes. Check the status using Status().
const EventStatusChanged device.Event = "statusChanged"
func toByte(b bool) byte {
if b {
return 1
}
return 0
}
// Device provides the API to communicate with the BitBox02 bootloader.
type Device struct {
deviceID string
communication Communication
edition bitbox02common.Edition
status *Status
mu sync.RWMutex
onEvent func(devicepkg.Event, interface{})
log *logrus.Entry
}
// NewDevice creates a new instance of Device.
func NewDevice(
deviceID string,
version *semver.SemVer,
edition bitbox02common.Edition,
communication Communication,
) *Device {
log := logging.Get().WithGroup("device").WithField("deviceID", deviceID)
log.Info("Plugged in device")
return &Device{
deviceID: deviceID,
communication: communication,
edition: edition,
status: &Status{},
log: log.WithField("deviceID", deviceID).WithField("productName", ProductName),
}
}
// Init implements device.Device.
func (device *Device) Init(testing bool) error {
return nil
}
// ProductName implements device.Device.
func (device *Device) ProductName() string {
return ProductName
}
// Identifier implements device.Device.
func (device *Device) Identifier() string {
return device.deviceID
}
// KeystoreForConfiguration implements device.Device.
func (device *Device) KeystoreForConfiguration(configuration *signing.Configuration, cosignerIndex int) keystoreInterface.Keystore {
panic("not supported")
}
// SetOnEvent implements device.Device.
func (device *Device) SetOnEvent(onEvent func(devicepkg.Event, interface{})) {
device.mu.Lock()
defer device.mu.Unlock()
device.onEvent = onEvent
}
func (device *Device) fireEvent() {
device.mu.RLock()
f := device.onEvent
device.mu.RUnlock()
if f != nil {
f(EventStatusChanged, nil)
}
}
// Close implements device.Device.
func (device *Device) Close() {
device.communication.Close()
}
// Status returns the progress of a firmware upgrade.
func (device *Device) Status() *Status {
return device.status
}
func (device *Device) query(cmd rune, data []byte) ([]byte, error) {
var buf bytes.Buffer
buf.WriteRune(cmd)
buf.Write(data)
if err := device.communication.SendFrame(buf.String()); err != nil {
return nil, err
}
reply, err := device.communication.ReadFrame()
if err != nil {
return nil, err
}
if reply[0] != byte(cmd) || len(reply) < 2 || reply[1] != 0 {
return nil, errp.WithContext(errp.New("Unexpected reply"), errp.Context{
"reply": reply,
})
}
return reply[2:], nil
}
// Versions queries the device for the firmware and signing pubkeys version.
func (device *Device) Versions() (uint32, uint32, error) {
response, err := device.query('v', nil)
if err != nil {
return 0, 0, err
}
firmwareVersion := binary.LittleEndian.Uint32(response[:4])
signingPubkeysVersion := binary.LittleEndian.Uint32(response[4:8])
return firmwareVersion, signingPubkeysVersion, err
}
// GetHashes queries the device for the firmware and signing keydata hashes.
// If the display flags are true, the hashes are also shown on the device screen.
func (device *Device) GetHashes(displayFirmwareHash, displaySigningKeydataHash bool) (
[]byte, []byte, error) {
response, err := device.query('h',
[]byte{toByte(displayFirmwareHash), toByte(displaySigningKeydataHash)})
if err != nil {
return nil, nil, err
}
firmwareHash := response[:32]
signingKeyDatahash := response[32:64]
return firmwareHash, signingKeyDatahash, nil
}
// ShowFirmwareHashEnabled returns whether the bootloader will automatically show the firmware
// hash on boot.
func (device *Device) ShowFirmwareHashEnabled() (bool, error) {
response, err := device.query('H', []byte{0xFF})
if err != nil {
return false, err
}
return response[0] == 1, nil
}
// SetShowFirmwareHashEnabled returns whether the bootloader will automatically show the firmware
// hash on boot.
func (device *Device) SetShowFirmwareHashEnabled(enabled bool) error {
_, err := device.query('H', []byte{toByte(enabled)})
return err
}
// Reboot reboots the device.
func (device *Device) Reboot() error {
return device.communication.SendFrame("r")
}
// ScreenRotate rotates the device screen.
func (device *Device) ScreenRotate() error {
_, err := device.query('f', nil)
return err
}
func (device *Device) erase(firmwareNumChunks uint8) error {
_, err := device.query('e', []byte{firmwareNumChunks})
return err
}
func (device *Device) writeChunk(chunkNum uint8, chunk []byte) error {
if len(chunk) > chunkSize {
return errp.New("chunk must max 4kB")
}
var buf bytes.Buffer
buf.WriteByte(chunkNum)
buf.Write(chunk)
buf.Write(bytes.Repeat([]byte{0xFF}, chunkSize-len(chunk)))
_, err := device.query('w', buf.Bytes())
return err
}
func (device *Device) flashUnsignedFirmware(firmware []byte, progressCallback func(float64)) error {
if len(firmware) > firmwareChunks*chunkSize {
return errp.New("firmware too big")
}
if progressCallback != nil {
progressCallback(0)
}
buf := bytes.NewBuffer(firmware)
totalChunks := uint8(math.Ceil(float64(buf.Len()) / float64(chunkSize)))
if err := device.erase(totalChunks); err != nil {
return err
}
chunkNum := byte(0)
for {
chunk := make([]byte, chunkSize)
readLen, err := buf.Read(chunk)
if readLen == 0 || err == io.EOF {
break
}
if err != nil {
return err
}
if err := device.writeChunk(chunkNum, chunk[:readLen]); err != nil {
return err
}
chunkNum++
if progressCallback != nil {
progressCallback(float64(chunkNum) / float64(totalChunks))
}
}
return nil
}
func (device *Device) flashSignedFirmware(firmware []byte, progressCallback func(float64)) error {
if len(firmware) <= magicLen+sigDataLen {
return errp.New("firmware too small")
}
magic, firmware := firmware[:magicLen], firmware[magicLen:]
sigData, firmware := firmware[:sigDataLen], firmware[sigDataLen:]
expectedMagic, ok := sigDataMagic[device.edition]
if !ok {
return errp.New("unrecognozed edition")
}
if binary.BigEndian.Uint32(magic) != expectedMagic {
return errp.New("invalid signing pubkeys data magic")
}
if err := device.flashUnsignedFirmware(firmware, progressCallback); err != nil {
return err
}
// write sig data
if _, err := device.query('s', sigData); err != nil {
return err
}
return nil
}
// UpgradeFirmware uploads a signed bitbox02 firmware release to the device.
func (device *Device) UpgradeFirmware() error {
if device.status.Upgrading {
return errp.New("already in progress")
}
device.log.Info("upgrading firmware")
device.fireEvent()
onProgress := func(progress float64) {
device.status.Upgrading = true
device.status.Progress = progress
device.fireEvent()
}
err := device.flashSignedFirmware(bundledFirmware(device.edition), onProgress)
if err != nil {
device.status.Upgrading = false
device.status.ErrMsg = err.Error()
device.fireEvent()
return err
}
device.status.Progress = 0
device.status.UpgradeSuccessful = true
device.fireEvent()
for seconds := 5; seconds > 0; seconds-- {
device.status.RebootSeconds = seconds
device.fireEvent()
time.Sleep(time.Second)
}
return device.Reboot()
}
// Erased returns true if the the device contains no firmware.
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()
if err != nil {
return false, err
}
firmwareVersionLE := make([]byte, 4)
binary.LittleEndian.PutUint32(firmwareVersionLE, firmwareVersion)
emptyFirmware := bytes.Repeat([]byte{0xFF}, maxFirmwareSize)
doubleHash := func(b []byte) []byte {
first := sha256.Sum256(b)
second := sha256.Sum256(first[:])
return second[:]
}
emptyFirmwareHash := doubleHash(append(firmwareVersionLE, emptyFirmware...))
firmwareHash, _, err := device.GetHashes(false, false)
if err != nil {
return false, err
}
return bytes.Equal(firmwareHash, emptyFirmwareHash), nil
}