ledger.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. // Copyright 2017 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // This file contains the implementation for interacting with the Ledger hardware
  17. // wallets. The wire protocol spec can be found in the Ledger Blue GitHub repo:
  18. // https://raw.githubusercontent.com/LedgerHQ/blue-app-eth/master/doc/ethapp.asc
  19. package usbwallet
  20. import (
  21. "encoding/binary"
  22. "encoding/hex"
  23. "errors"
  24. "fmt"
  25. "io"
  26. "math/big"
  27. "github.com/ethereum/go-ethereum/accounts"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/common/hexutil"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. "github.com/ethereum/go-ethereum/log"
  33. "github.com/ethereum/go-ethereum/rlp"
  34. )
  35. // ledgerOpcode is an enumeration encoding the supported Ledger opcodes.
  36. type ledgerOpcode byte
  37. // ledgerParam1 is an enumeration encoding the supported Ledger parameters for
  38. // specific opcodes. The same parameter values may be reused between opcodes.
  39. type ledgerParam1 byte
  40. // ledgerParam2 is an enumeration encoding the supported Ledger parameters for
  41. // specific opcodes. The same parameter values may be reused between opcodes.
  42. type ledgerParam2 byte
  43. const (
  44. ledgerOpRetrieveAddress ledgerOpcode = 0x02 // Returns the public key and Ethereum address for a given BIP 32 path
  45. ledgerOpSignTransaction ledgerOpcode = 0x04 // Signs an Ethereum transaction after having the user validate the parameters
  46. ledgerOpGetConfiguration ledgerOpcode = 0x06 // Returns specific wallet application configuration
  47. ledgerP1DirectlyFetchAddress ledgerParam1 = 0x00 // Return address directly from the wallet
  48. ledgerP1InitTransactionData ledgerParam1 = 0x00 // First transaction data block for signing
  49. ledgerP1ContTransactionData ledgerParam1 = 0x80 // Subsequent transaction data block for signing
  50. ledgerP2DiscardAddressChainCode ledgerParam2 = 0x00 // Do not return the chain code along with the address
  51. )
  52. // errLedgerReplyInvalidHeader is the error message returned by a Ledger data exchange
  53. // if the device replies with a mismatching header. This usually means the device
  54. // is in browser mode.
  55. var errLedgerReplyInvalidHeader = errors.New("ledger: invalid reply header")
  56. // errLedgerInvalidVersionReply is the error message returned by a Ledger version retrieval
  57. // when a response does arrive, but it does not contain the expected data.
  58. var errLedgerInvalidVersionReply = errors.New("ledger: invalid version reply")
  59. // ledgerDriver implements the communication with a Ledger hardware wallet.
  60. type ledgerDriver struct {
  61. device io.ReadWriter // USB device connection to communicate through
  62. version [3]byte // Current version of the Ledger firmware (zero if app is offline)
  63. browser bool // Flag whether the Ledger is in browser mode (reply channel mismatch)
  64. failure error // Any failure that would make the device unusable
  65. log log.Logger // Contextual logger to tag the ledger with its id
  66. }
  67. // newLedgerDriver creates a new instance of a Ledger USB protocol driver.
  68. func newLedgerDriver(logger log.Logger) driver {
  69. return &ledgerDriver{
  70. log: logger,
  71. }
  72. }
  73. // Status implements usbwallet.driver, returning various states the Ledger can
  74. // currently be in.
  75. func (w *ledgerDriver) Status() (string, error) {
  76. if w.failure != nil {
  77. return fmt.Sprintf("Failed: %v", w.failure), w.failure
  78. }
  79. if w.browser {
  80. return "Ethereum app in browser mode", w.failure
  81. }
  82. if w.offline() {
  83. return "Ethereum app offline", w.failure
  84. }
  85. return fmt.Sprintf("Ethereum app v%d.%d.%d online", w.version[0], w.version[1], w.version[2]), w.failure
  86. }
  87. // offline returns whether the wallet and the Ethereum app is offline or not.
  88. //
  89. // The method assumes that the state lock is held!
  90. func (w *ledgerDriver) offline() bool {
  91. return w.version == [3]byte{0, 0, 0}
  92. }
  93. // Open implements usbwallet.driver, attempting to initialize the connection to the
  94. // Ledger hardware wallet. The Ledger does not require a user passphrase, so that
  95. // parameter is silently discarded.
  96. func (w *ledgerDriver) Open(device io.ReadWriter, passphrase string) error {
  97. w.device, w.failure = device, nil
  98. _, err := w.ledgerDerive(accounts.DefaultBaseDerivationPath)
  99. if err != nil {
  100. // Ethereum app is not running or in browser mode, nothing more to do, return
  101. if err == errLedgerReplyInvalidHeader {
  102. w.browser = true
  103. }
  104. return nil
  105. }
  106. // Try to resolve the Ethereum app's version, will fail prior to v1.0.2
  107. if w.version, err = w.ledgerVersion(); err != nil {
  108. w.version = [3]byte{1, 0, 0} // Assume worst case, can't verify if v1.0.0 or v1.0.1
  109. }
  110. return nil
  111. }
  112. // Close implements usbwallet.driver, cleaning up and metadata maintained within
  113. // the Ledger driver.
  114. func (w *ledgerDriver) Close() error {
  115. w.browser, w.version = false, [3]byte{}
  116. return nil
  117. }
  118. // Heartbeat implements usbwallet.driver, performing a sanity check against the
  119. // Ledger to see if it's still online.
  120. func (w *ledgerDriver) Heartbeat() error {
  121. if _, err := w.ledgerVersion(); err != nil && err != errLedgerInvalidVersionReply {
  122. w.failure = err
  123. return err
  124. }
  125. return nil
  126. }
  127. // Derive implements usbwallet.driver, sending a derivation request to the Ledger
  128. // and returning the Ethereum address located on that derivation path.
  129. func (w *ledgerDriver) Derive(path accounts.DerivationPath) (common.Address, error) {
  130. return w.ledgerDerive(path)
  131. }
  132. // SignTx implements usbwallet.driver, sending the transaction to the Ledger and
  133. // waiting for the user to confirm or deny the transaction.
  134. //
  135. // Note, if the version of the Ethereum application running on the Ledger wallet is
  136. // too old to sign EIP-155 transactions, but such is requested nonetheless, an error
  137. // will be returned opposed to silently signing in Homestead mode.
  138. func (w *ledgerDriver) SignTx(path accounts.DerivationPath, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error) {
  139. // If the Ethereum app doesn't run, abort
  140. if w.offline() {
  141. return common.Address{}, nil, accounts.ErrWalletClosed
  142. }
  143. // Ensure the wallet is capable of signing the given transaction
  144. if chainID != nil && w.version[0] <= 1 && w.version[2] <= 2 {
  145. //lint:ignore ST1005 brand name displayed on the console
  146. return common.Address{}, nil, fmt.Errorf("Ledger v%d.%d.%d doesn't support signing this transaction, please update to v1.0.3 at least", w.version[0], w.version[1], w.version[2])
  147. }
  148. // All infos gathered and metadata checks out, request signing
  149. return w.ledgerSign(path, tx, chainID)
  150. }
  151. // ledgerVersion retrieves the current version of the Ethereum wallet app running
  152. // on the Ledger wallet.
  153. //
  154. // The version retrieval protocol is defined as follows:
  155. //
  156. // CLA | INS | P1 | P2 | Lc | Le
  157. // ----+-----+----+----+----+---
  158. // E0 | 06 | 00 | 00 | 00 | 04
  159. //
  160. // With no input data, and the output data being:
  161. //
  162. // Description | Length
  163. // ---------------------------------------------------+--------
  164. // Flags 01: arbitrary data signature enabled by user | 1 byte
  165. // Application major version | 1 byte
  166. // Application minor version | 1 byte
  167. // Application patch version | 1 byte
  168. func (w *ledgerDriver) ledgerVersion() ([3]byte, error) {
  169. // Send the request and wait for the response
  170. reply, err := w.ledgerExchange(ledgerOpGetConfiguration, 0, 0, nil)
  171. if err != nil {
  172. return [3]byte{}, err
  173. }
  174. if len(reply) != 4 {
  175. return [3]byte{}, errLedgerInvalidVersionReply
  176. }
  177. // Cache the version for future reference
  178. var version [3]byte
  179. copy(version[:], reply[1:])
  180. return version, nil
  181. }
  182. // ledgerDerive retrieves the currently active Ethereum address from a Ledger
  183. // wallet at the specified derivation path.
  184. //
  185. // The address derivation protocol is defined as follows:
  186. //
  187. // CLA | INS | P1 | P2 | Lc | Le
  188. // ----+-----+----+----+-----+---
  189. // E0 | 02 | 00 return address
  190. // 01 display address and confirm before returning
  191. // | 00: do not return the chain code
  192. // | 01: return the chain code
  193. // | var | 00
  194. //
  195. // Where the input data is:
  196. //
  197. // Description | Length
  198. // -------------------------------------------------+--------
  199. // Number of BIP 32 derivations to perform (max 10) | 1 byte
  200. // First derivation index (big endian) | 4 bytes
  201. // ... | 4 bytes
  202. // Last derivation index (big endian) | 4 bytes
  203. //
  204. // And the output data is:
  205. //
  206. // Description | Length
  207. // ------------------------+-------------------
  208. // Public Key length | 1 byte
  209. // Uncompressed Public Key | arbitrary
  210. // Ethereum address length | 1 byte
  211. // Ethereum address | 40 bytes hex ascii
  212. // Chain code if requested | 32 bytes
  213. func (w *ledgerDriver) ledgerDerive(derivationPath []uint32) (common.Address, error) {
  214. // Flatten the derivation path into the Ledger request
  215. path := make([]byte, 1+4*len(derivationPath))
  216. path[0] = byte(len(derivationPath))
  217. for i, component := range derivationPath {
  218. binary.BigEndian.PutUint32(path[1+4*i:], component)
  219. }
  220. // Send the request and wait for the response
  221. reply, err := w.ledgerExchange(ledgerOpRetrieveAddress, ledgerP1DirectlyFetchAddress, ledgerP2DiscardAddressChainCode, path)
  222. if err != nil {
  223. return common.Address{}, err
  224. }
  225. // Discard the public key, we don't need that for now
  226. if len(reply) < 1 || len(reply) < 1+int(reply[0]) {
  227. return common.Address{}, errors.New("reply lacks public key entry")
  228. }
  229. reply = reply[1+int(reply[0]):]
  230. // Extract the Ethereum hex address string
  231. if len(reply) < 1 || len(reply) < 1+int(reply[0]) {
  232. return common.Address{}, errors.New("reply lacks address entry")
  233. }
  234. hexstr := reply[1 : 1+int(reply[0])]
  235. // Decode the hex sting into an Ethereum address and return
  236. var address common.Address
  237. if _, err = hex.Decode(address[:], hexstr); err != nil {
  238. return common.Address{}, err
  239. }
  240. return address, nil
  241. }
  242. // ledgerSign sends the transaction to the Ledger wallet, and waits for the user
  243. // to confirm or deny the transaction.
  244. //
  245. // The transaction signing protocol is defined as follows:
  246. //
  247. // CLA | INS | P1 | P2 | Lc | Le
  248. // ----+-----+----+----+-----+---
  249. // E0 | 04 | 00: first transaction data block
  250. // 80: subsequent transaction data block
  251. // | 00 | variable | variable
  252. //
  253. // Where the input for the first transaction block (first 255 bytes) is:
  254. //
  255. // Description | Length
  256. // -------------------------------------------------+----------
  257. // Number of BIP 32 derivations to perform (max 10) | 1 byte
  258. // First derivation index (big endian) | 4 bytes
  259. // ... | 4 bytes
  260. // Last derivation index (big endian) | 4 bytes
  261. // RLP transaction chunk | arbitrary
  262. //
  263. // And the input for subsequent transaction blocks (first 255 bytes) are:
  264. //
  265. // Description | Length
  266. // ----------------------+----------
  267. // RLP transaction chunk | arbitrary
  268. //
  269. // And the output data is:
  270. //
  271. // Description | Length
  272. // ------------+---------
  273. // signature V | 1 byte
  274. // signature R | 32 bytes
  275. // signature S | 32 bytes
  276. func (w *ledgerDriver) ledgerSign(derivationPath []uint32, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error) {
  277. // Flatten the derivation path into the Ledger request
  278. path := make([]byte, 1+4*len(derivationPath))
  279. path[0] = byte(len(derivationPath))
  280. for i, component := range derivationPath {
  281. binary.BigEndian.PutUint32(path[1+4*i:], component)
  282. }
  283. // Create the transaction RLP based on whether legacy or EIP155 signing was requested
  284. var (
  285. txrlp []byte
  286. err error
  287. )
  288. if chainID == nil {
  289. if txrlp, err = rlp.EncodeToBytes([]interface{}{tx.Nonce(), tx.GasPrice(), tx.Gas(), tx.To(), tx.Value(), tx.Data()}); err != nil {
  290. return common.Address{}, nil, err
  291. }
  292. } else {
  293. if txrlp, err = rlp.EncodeToBytes([]interface{}{tx.Nonce(), tx.GasPrice(), tx.Gas(), tx.To(), tx.Value(), tx.Data(), chainID, big.NewInt(0), big.NewInt(0)}); err != nil {
  294. return common.Address{}, nil, err
  295. }
  296. }
  297. payload := append(path, txrlp...)
  298. // Send the request and wait for the response
  299. var (
  300. op = ledgerP1InitTransactionData
  301. reply []byte
  302. )
  303. for len(payload) > 0 {
  304. // Calculate the size of the next data chunk
  305. chunk := 255
  306. if chunk > len(payload) {
  307. chunk = len(payload)
  308. }
  309. // Send the chunk over, ensuring it's processed correctly
  310. reply, err = w.ledgerExchange(ledgerOpSignTransaction, op, 0, payload[:chunk])
  311. if err != nil {
  312. return common.Address{}, nil, err
  313. }
  314. // Shift the payload and ensure subsequent chunks are marked as such
  315. payload = payload[chunk:]
  316. op = ledgerP1ContTransactionData
  317. }
  318. // Extract the Ethereum signature and do a sanity validation
  319. if len(reply) != crypto.SignatureLength {
  320. return common.Address{}, nil, errors.New("reply lacks signature")
  321. }
  322. signature := append(reply[1:], reply[0])
  323. // Create the correct signer and signature transform based on the chain ID
  324. var signer types.Signer
  325. if chainID == nil {
  326. signer = new(types.HomesteadSigner)
  327. } else {
  328. signer = types.NewEIP155Signer(chainID)
  329. signature[64] -= byte(chainID.Uint64()*2 + 35)
  330. }
  331. signed, err := tx.WithSignature(signer, signature)
  332. if err != nil {
  333. return common.Address{}, nil, err
  334. }
  335. sender, err := types.Sender(signer, signed)
  336. if err != nil {
  337. return common.Address{}, nil, err
  338. }
  339. return sender, signed, nil
  340. }
  341. // ledgerExchange performs a data exchange with the Ledger wallet, sending it a
  342. // message and retrieving the response.
  343. //
  344. // The common transport header is defined as follows:
  345. //
  346. // Description | Length
  347. // --------------------------------------+----------
  348. // Communication channel ID (big endian) | 2 bytes
  349. // Command tag | 1 byte
  350. // Packet sequence index (big endian) | 2 bytes
  351. // Payload | arbitrary
  352. //
  353. // The Communication channel ID allows commands multiplexing over the same
  354. // physical link. It is not used for the time being, and should be set to 0101
  355. // to avoid compatibility issues with implementations ignoring a leading 00 byte.
  356. //
  357. // The Command tag describes the message content. Use TAG_APDU (0x05) for standard
  358. // APDU payloads, or TAG_PING (0x02) for a simple link test.
  359. //
  360. // The Packet sequence index describes the current sequence for fragmented payloads.
  361. // The first fragment index is 0x00.
  362. //
  363. // APDU Command payloads are encoded as follows:
  364. //
  365. // Description | Length
  366. // -----------------------------------
  367. // APDU length (big endian) | 2 bytes
  368. // APDU CLA | 1 byte
  369. // APDU INS | 1 byte
  370. // APDU P1 | 1 byte
  371. // APDU P2 | 1 byte
  372. // APDU length | 1 byte
  373. // Optional APDU data | arbitrary
  374. func (w *ledgerDriver) ledgerExchange(opcode ledgerOpcode, p1 ledgerParam1, p2 ledgerParam2, data []byte) ([]byte, error) {
  375. // Construct the message payload, possibly split into multiple chunks
  376. apdu := make([]byte, 2, 7+len(data))
  377. binary.BigEndian.PutUint16(apdu, uint16(5+len(data)))
  378. apdu = append(apdu, []byte{0xe0, byte(opcode), byte(p1), byte(p2), byte(len(data))}...)
  379. apdu = append(apdu, data...)
  380. // Stream all the chunks to the device
  381. header := []byte{0x01, 0x01, 0x05, 0x00, 0x00} // Channel ID and command tag appended
  382. chunk := make([]byte, 64)
  383. space := len(chunk) - len(header)
  384. for i := 0; len(apdu) > 0; i++ {
  385. // Construct the new message to stream
  386. chunk = append(chunk[:0], header...)
  387. binary.BigEndian.PutUint16(chunk[3:], uint16(i))
  388. if len(apdu) > space {
  389. chunk = append(chunk, apdu[:space]...)
  390. apdu = apdu[space:]
  391. } else {
  392. chunk = append(chunk, apdu...)
  393. apdu = nil
  394. }
  395. // Send over to the device
  396. w.log.Trace("Data chunk sent to the Ledger", "chunk", hexutil.Bytes(chunk))
  397. if _, err := w.device.Write(chunk); err != nil {
  398. return nil, err
  399. }
  400. }
  401. // Stream the reply back from the wallet in 64 byte chunks
  402. var reply []byte
  403. chunk = chunk[:64] // Yeah, we surely have enough space
  404. for {
  405. // Read the next chunk from the Ledger wallet
  406. if _, err := io.ReadFull(w.device, chunk); err != nil {
  407. return nil, err
  408. }
  409. w.log.Trace("Data chunk received from the Ledger", "chunk", hexutil.Bytes(chunk))
  410. // Make sure the transport header matches
  411. if chunk[0] != 0x01 || chunk[1] != 0x01 || chunk[2] != 0x05 {
  412. return nil, errLedgerReplyInvalidHeader
  413. }
  414. // If it's the first chunk, retrieve the total message length
  415. var payload []byte
  416. if chunk[3] == 0x00 && chunk[4] == 0x00 {
  417. reply = make([]byte, 0, int(binary.BigEndian.Uint16(chunk[5:7])))
  418. payload = chunk[7:]
  419. } else {
  420. payload = chunk[5:]
  421. }
  422. // Append to the reply and stop when filled up
  423. if left := cap(reply) - len(reply); left > len(payload) {
  424. reply = append(reply, payload...)
  425. } else {
  426. reply = append(reply, payload[:left]...)
  427. break
  428. }
  429. }
  430. return reply[:len(reply)-2], nil
  431. }