wallet.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  1. // Copyright 2018 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. package scwallet
  17. import (
  18. "bytes"
  19. "context"
  20. "crypto/hmac"
  21. "crypto/sha256"
  22. "crypto/sha512"
  23. "encoding/asn1"
  24. "encoding/binary"
  25. "errors"
  26. "fmt"
  27. "math/big"
  28. "sort"
  29. "strings"
  30. "sync"
  31. "time"
  32. ethereum "github.com/ethereum/go-ethereum"
  33. "github.com/ethereum/go-ethereum/accounts"
  34. "github.com/ethereum/go-ethereum/common"
  35. "github.com/ethereum/go-ethereum/core/types"
  36. "github.com/ethereum/go-ethereum/crypto"
  37. "github.com/ethereum/go-ethereum/crypto/secp256k1"
  38. "github.com/ethereum/go-ethereum/log"
  39. pcsc "github.com/gballet/go-libpcsclite"
  40. )
  41. // ErrPairingPasswordNeeded is returned if opening the smart card requires pairing with a pairing
  42. // password. In this case, the calling application should request user input to enter
  43. // the pairing password and send it back.
  44. var ErrPairingPasswordNeeded = errors.New("smartcard: pairing password needed")
  45. // ErrPINNeeded is returned if opening the smart card requires a PIN code. In
  46. // this case, the calling application should request user input to enter the PIN
  47. // and send it back.
  48. var ErrPINNeeded = errors.New("smartcard: pin needed")
  49. // ErrPINUnblockNeeded is returned if opening the smart card requires a PIN code,
  50. // but all PIN attempts have already been exhausted. In this case the calling
  51. // application should request user input for the PUK and a new PIN code to set
  52. // fo the card.
  53. var ErrPINUnblockNeeded = errors.New("smartcard: pin unblock needed")
  54. // ErrAlreadyOpen is returned if the smart card is attempted to be opened, but
  55. // there is already a paired and unlocked session.
  56. var ErrAlreadyOpen = errors.New("smartcard: already open")
  57. // ErrPubkeyMismatch is returned if the public key recovered from a signature
  58. // does not match the one expected by the user.
  59. var ErrPubkeyMismatch = errors.New("smartcard: recovered public key mismatch")
  60. var (
  61. // appletAID = []byte{0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x57, 0x61, 0x6C, 0x6C, 0x65, 0x74, 0x41, 0x70, 0x70}
  62. appletAID = []byte{0xA0, 0x00, 0x00, 0x08, 0x04, 0x00, 0x01, 0x01, 0x01}
  63. DerivationSignatureHash = sha256.Sum256([]byte("STATUS KEY DERIVATION"))
  64. )
  65. const (
  66. claISO7816 = 0
  67. claSCWallet = 0x80
  68. insSelect = 0xA4
  69. insGetResponse = 0xC0
  70. sw1GetResponse = 0x61
  71. sw1Ok = 0x90
  72. insVerifyPin = 0x20
  73. insUnblockPin = 0x22
  74. insExportKey = 0xC2
  75. insSign = 0xC0
  76. insLoadKey = 0xD0
  77. insDeriveKey = 0xD1
  78. insStatus = 0xF2
  79. P1DeriveKeyFromMaster = uint8(0x00)
  80. P1DeriveKeyFromParent = uint8(0x01)
  81. P1DeriveKeyFromCurrent = uint8(0x10)
  82. deriveP1Assisted = uint8(0x01)
  83. deriveP1Append = uint8(0x80)
  84. deriveP2KeyPath = uint8(0x00)
  85. deriveP2PublicKey = uint8(0x01)
  86. statusP1WalletStatus = uint8(0x00)
  87. statusP1Path = uint8(0x01)
  88. signP1PrecomputedHash = uint8(0x01)
  89. signP2OnlyBlock = uint8(0x81)
  90. exportP1Any = uint8(0x00)
  91. exportP2Pubkey = uint8(0x01)
  92. // Minimum time to wait between self derivation attempts, even it the user is
  93. // requesting accounts like crazy.
  94. selfDeriveThrottling = time.Second
  95. )
  96. // Wallet represents a smartcard wallet instance.
  97. type Wallet struct {
  98. Hub *Hub // A handle to the Hub that instantiated this wallet.
  99. PublicKey []byte // The wallet's public key (used for communication and identification, not signing!)
  100. lock sync.Mutex // Lock that gates access to struct fields and communication with the card
  101. card *pcsc.Card // A handle to the smartcard interface for the wallet.
  102. session *Session // The secure communication session with the card
  103. log log.Logger // Contextual logger to tag the base with its id
  104. deriveNextPath accounts.DerivationPath // Next derivation path for account auto-discovery
  105. deriveNextAddr common.Address // Next derived account address for auto-discovery
  106. deriveChain ethereum.ChainStateReader // Blockchain state reader to discover used account with
  107. deriveReq chan chan struct{} // Channel to request a self-derivation on
  108. deriveQuit chan chan error // Channel to terminate the self-deriver with
  109. }
  110. // NewWallet constructs and returns a new Wallet instance.
  111. func NewWallet(hub *Hub, card *pcsc.Card) *Wallet {
  112. wallet := &Wallet{
  113. Hub: hub,
  114. card: card,
  115. }
  116. return wallet
  117. }
  118. // transmit sends an APDU to the smartcard and receives and decodes the response.
  119. // It automatically handles requests by the card to fetch the return data separately,
  120. // and returns an error if the response status code is not success.
  121. func transmit(card *pcsc.Card, command *commandAPDU) (*responseAPDU, error) {
  122. data, err := command.serialize()
  123. if err != nil {
  124. return nil, err
  125. }
  126. responseData, _, err := card.Transmit(data)
  127. if err != nil {
  128. return nil, err
  129. }
  130. response := new(responseAPDU)
  131. if err = response.deserialize(responseData); err != nil {
  132. return nil, err
  133. }
  134. // Are we being asked to fetch the response separately?
  135. if response.Sw1 == sw1GetResponse && (command.Cla != claISO7816 || command.Ins != insGetResponse) {
  136. return transmit(card, &commandAPDU{
  137. Cla: claISO7816,
  138. Ins: insGetResponse,
  139. P1: 0,
  140. P2: 0,
  141. Data: nil,
  142. Le: response.Sw2,
  143. })
  144. }
  145. if response.Sw1 != sw1Ok {
  146. return nil, fmt.Errorf("Unexpected insecure response status Cla=0x%x, Ins=0x%x, Sw=0x%x%x", command.Cla, command.Ins, response.Sw1, response.Sw2)
  147. }
  148. return response, nil
  149. }
  150. // applicationInfo encodes information about the smartcard application - its
  151. // instance UID and public key.
  152. type applicationInfo struct {
  153. InstanceUID []byte `asn1:"tag:15"`
  154. PublicKey []byte `asn1:"tag:0"`
  155. }
  156. // connect connects to the wallet application and establishes a secure channel with it.
  157. // must be called before any other interaction with the wallet.
  158. func (w *Wallet) connect() error {
  159. w.lock.Lock()
  160. defer w.lock.Unlock()
  161. appinfo, err := w.doselect()
  162. if err != nil {
  163. return err
  164. }
  165. channel, err := NewSecureChannelSession(w.card, appinfo.PublicKey)
  166. if err != nil {
  167. return err
  168. }
  169. w.PublicKey = appinfo.PublicKey
  170. w.log = log.New("url", w.URL())
  171. w.session = &Session{
  172. Wallet: w,
  173. Channel: channel,
  174. }
  175. return nil
  176. }
  177. // doselect is an internal (unlocked) function to send a SELECT APDU to the card.
  178. func (w *Wallet) doselect() (*applicationInfo, error) {
  179. response, err := transmit(w.card, &commandAPDU{
  180. Cla: claISO7816,
  181. Ins: insSelect,
  182. P1: 4,
  183. P2: 0,
  184. Data: appletAID,
  185. })
  186. if err != nil {
  187. return nil, err
  188. }
  189. appinfo := new(applicationInfo)
  190. if _, err := asn1.UnmarshalWithParams(response.Data, appinfo, "tag:4"); err != nil {
  191. return nil, err
  192. }
  193. return appinfo, nil
  194. }
  195. // ping checks the card's status and returns an error if unsuccessful.
  196. func (w *Wallet) ping() error {
  197. w.lock.Lock()
  198. defer w.lock.Unlock()
  199. // We can't ping if not paired
  200. if !w.session.paired() {
  201. return nil
  202. }
  203. if _, err := w.session.walletStatus(); err != nil {
  204. return err
  205. }
  206. return nil
  207. }
  208. // release releases any resources held by an open wallet instance.
  209. func (w *Wallet) release() error {
  210. if w.session != nil {
  211. return w.session.release()
  212. }
  213. return nil
  214. }
  215. // pair is an internal (unlocked) function for establishing a new pairing
  216. // with the wallet.
  217. func (w *Wallet) pair(puk []byte) error {
  218. if w.session.paired() {
  219. return fmt.Errorf("Wallet already paired")
  220. }
  221. pairing, err := w.session.pair(puk)
  222. if err != nil {
  223. return err
  224. }
  225. if err = w.Hub.setPairing(w, &pairing); err != nil {
  226. return err
  227. }
  228. return w.session.authenticate(pairing)
  229. }
  230. // Unpair deletes an existing wallet pairing.
  231. func (w *Wallet) Unpair(pin []byte) error {
  232. w.lock.Lock()
  233. defer w.lock.Unlock()
  234. if !w.session.paired() {
  235. return fmt.Errorf("wallet %x not paired", w.PublicKey)
  236. }
  237. if err := w.session.verifyPin(pin); err != nil {
  238. return fmt.Errorf("failed to verify pin: %s", err)
  239. }
  240. if err := w.session.unpair(); err != nil {
  241. return fmt.Errorf("failed to unpair: %s", err)
  242. }
  243. if err := w.Hub.setPairing(w, nil); err != nil {
  244. return err
  245. }
  246. return nil
  247. }
  248. // URL retrieves the canonical path under which this wallet is reachable. It is
  249. // user by upper layers to define a sorting order over all wallets from multiple
  250. // backends.
  251. func (w *Wallet) URL() accounts.URL {
  252. return accounts.URL{
  253. Scheme: w.Hub.scheme,
  254. Path: fmt.Sprintf("%x", w.PublicKey[1:5]), // Byte #0 isn't unique; 1:5 covers << 64K cards, bump to 1:9 for << 4M
  255. }
  256. }
  257. // Status returns a textual status to aid the user in the current state of the
  258. // wallet. It also returns an error indicating any failure the wallet might have
  259. // encountered.
  260. func (w *Wallet) Status() (string, error) {
  261. w.lock.Lock()
  262. defer w.lock.Unlock()
  263. // If the card is not paired, we can only wait
  264. if !w.session.paired() {
  265. return "Unpaired, waiting for PUK", nil
  266. }
  267. // Yay, we have an encrypted session, retrieve the actual status
  268. status, err := w.session.walletStatus()
  269. if err != nil {
  270. return fmt.Sprintf("Failed: %v", err), err
  271. }
  272. switch {
  273. case !w.session.verified && status.PinRetryCount == 0:
  274. return fmt.Sprintf("Blocked, waiting for PUK and new PIN"), nil
  275. case !w.session.verified:
  276. return fmt.Sprintf("Locked, waiting for PIN (%d attempts left)", status.PinRetryCount), nil
  277. case !status.Initialized:
  278. return fmt.Sprintf("Empty, waiting for initialization"), nil
  279. case status.SupportsPKDerivation:
  280. return fmt.Sprintf("Online, can derive public keys"), nil
  281. default:
  282. return fmt.Sprintf("Online, cannot derive public keys"), nil
  283. }
  284. }
  285. // Open initializes access to a wallet instance. It is not meant to unlock or
  286. // decrypt account keys, rather simply to establish a connection to hardware
  287. // wallets and/or to access derivation seeds.
  288. //
  289. // The passphrase parameter may or may not be used by the implementation of a
  290. // particular wallet instance. The reason there is no passwordless open method
  291. // is to strive towards a uniform wallet handling, oblivious to the different
  292. // backend providers.
  293. //
  294. // Please note, if you open a wallet, you must close it to release any allocated
  295. // resources (especially important when working with hardware wallets).
  296. func (w *Wallet) Open(passphrase string) error {
  297. w.lock.Lock()
  298. defer w.lock.Unlock()
  299. // If the session is already open, bail out
  300. if w.session.verified {
  301. return ErrAlreadyOpen
  302. }
  303. // If the smart card is not yet paired, attempt to do so either from a previous
  304. // pairing key or form the supplied PUK code.
  305. if !w.session.paired() {
  306. // If a previous pairing exists, only ever try to use that
  307. if pairing := w.Hub.pairing(w); pairing != nil {
  308. if err := w.session.authenticate(*pairing); err != nil {
  309. return fmt.Errorf("failed to authenticate card %x: %s", w.PublicKey[:4], err)
  310. }
  311. // Pairing still ok, fall through to PIN checks
  312. } else {
  313. // If no passphrase was supplied, request the PUK from the user
  314. if passphrase == "" {
  315. return ErrPairingPasswordNeeded
  316. }
  317. // Attempt to pair the smart card with the user supplied PUK
  318. if err := w.pair([]byte(passphrase)); err != nil {
  319. return err
  320. }
  321. // Pairing succeeded, fall through to PIN checks. This will of course fail,
  322. // but we can't return ErrPINNeeded directly here becase we don't know whether
  323. // a PIN check or a PIN reset is needed.
  324. passphrase = ""
  325. }
  326. }
  327. // The smart card was successfully paired, retrieve its status to check whether
  328. // PIN verification or unblocking is needed.
  329. status, err := w.session.walletStatus()
  330. if err != nil {
  331. return err
  332. }
  333. // Request the appropriate next authentication data, or use the one supplied
  334. switch {
  335. case passphrase == "" && status.PinRetryCount > 0:
  336. return ErrPINNeeded
  337. case passphrase == "":
  338. return ErrPINUnblockNeeded
  339. case status.PinRetryCount > 0:
  340. if err := w.session.verifyPin([]byte(passphrase)); err != nil {
  341. return err
  342. }
  343. default:
  344. if err := w.session.unblockPin([]byte(passphrase)); err != nil {
  345. return err
  346. }
  347. }
  348. // Smart card paired and unlocked, initialize and register
  349. w.deriveReq = make(chan chan struct{})
  350. w.deriveQuit = make(chan chan error)
  351. go w.selfDerive()
  352. // Notify anyone listening for wallet events that a new device is accessible
  353. go w.Hub.updateFeed.Send(accounts.WalletEvent{Wallet: w, Kind: accounts.WalletOpened})
  354. return nil
  355. }
  356. // Close stops and closes the wallet, freeing any resources.
  357. func (w *Wallet) Close() error {
  358. // Ensure the wallet was opened
  359. w.lock.Lock()
  360. dQuit := w.deriveQuit
  361. w.lock.Unlock()
  362. // Terminate the self-derivations
  363. var derr error
  364. if dQuit != nil {
  365. errc := make(chan error)
  366. dQuit <- errc
  367. derr = <-errc // Save for later, we *must* close the USB
  368. }
  369. // Terminate the device connection
  370. w.lock.Lock()
  371. defer w.lock.Unlock()
  372. w.deriveQuit = nil
  373. w.deriveReq = nil
  374. if err := w.release(); err != nil {
  375. return err
  376. }
  377. return derr
  378. }
  379. // selfDerive is an account derivation loop that upon request attempts to find
  380. // new non-zero accounts.
  381. func (w *Wallet) selfDerive() {
  382. w.log.Debug("Smart card wallet self-derivation started")
  383. defer w.log.Debug("Smart card wallet self-derivation stopped")
  384. // Execute self-derivations until termination or error
  385. var (
  386. reqc chan struct{}
  387. errc chan error
  388. err error
  389. )
  390. for errc == nil && err == nil {
  391. // Wait until either derivation or termination is requested
  392. select {
  393. case errc = <-w.deriveQuit:
  394. // Termination requested
  395. continue
  396. case reqc = <-w.deriveReq:
  397. // Account discovery requested
  398. }
  399. // Derivation needs a chain and device access, skip if either unavailable
  400. w.lock.Lock()
  401. if w.session == nil || w.deriveChain == nil {
  402. w.lock.Unlock()
  403. reqc <- struct{}{}
  404. continue
  405. }
  406. pairing := w.Hub.pairing(w)
  407. // Device lock obtained, derive the next batch of accounts
  408. var (
  409. paths []accounts.DerivationPath
  410. nextAcc accounts.Account
  411. nextAddr = w.deriveNextAddr
  412. nextPath = w.deriveNextPath
  413. context = context.Background()
  414. )
  415. for empty := false; !empty; {
  416. // Retrieve the next derived Ethereum account
  417. if nextAddr == (common.Address{}) {
  418. if nextAcc, err = w.session.derive(nextPath); err != nil {
  419. w.log.Warn("Smartcard wallet account derivation failed", "err", err)
  420. break
  421. }
  422. nextAddr = nextAcc.Address
  423. }
  424. // Check the account's status against the current chain state
  425. var (
  426. balance *big.Int
  427. nonce uint64
  428. )
  429. balance, err = w.deriveChain.BalanceAt(context, nextAddr, nil)
  430. if err != nil {
  431. w.log.Warn("Smartcard wallet balance retrieval failed", "err", err)
  432. break
  433. }
  434. nonce, err = w.deriveChain.NonceAt(context, nextAddr, nil)
  435. if err != nil {
  436. w.log.Warn("Smartcard wallet nonce retrieval failed", "err", err)
  437. break
  438. }
  439. // If the next account is empty, stop self-derivation, but add it nonetheless
  440. if balance.Sign() == 0 && nonce == 0 {
  441. empty = true
  442. }
  443. // We've just self-derived a new account, start tracking it locally
  444. path := make(accounts.DerivationPath, len(nextPath))
  445. copy(path[:], nextPath[:])
  446. paths = append(paths, path)
  447. // Display a log message to the user for new (or previously empty accounts)
  448. if _, known := pairing.Accounts[nextAddr]; !known || !empty || nextAddr != w.deriveNextAddr {
  449. w.log.Info("Smartcard wallet discovered new account", "address", nextAddr, "path", path, "balance", balance, "nonce", nonce)
  450. }
  451. pairing.Accounts[nextAddr] = path
  452. // Fetch the next potential account
  453. if !empty {
  454. nextAddr = common.Address{}
  455. nextPath[len(nextPath)-1]++
  456. }
  457. }
  458. // If there are new accounts, write them out
  459. if len(paths) > 0 {
  460. err = w.Hub.setPairing(w, pairing)
  461. }
  462. // Shift the self-derivation forward
  463. w.deriveNextAddr = nextAddr
  464. w.deriveNextPath = nextPath
  465. // Self derivation complete, release device lock
  466. w.lock.Unlock()
  467. // Notify the user of termination and loop after a bit of time (to avoid trashing)
  468. reqc <- struct{}{}
  469. if err == nil {
  470. select {
  471. case errc = <-w.deriveQuit:
  472. // Termination requested, abort
  473. case <-time.After(selfDeriveThrottling):
  474. // Waited enough, willing to self-derive again
  475. }
  476. }
  477. }
  478. // In case of error, wait for termination
  479. if err != nil {
  480. w.log.Debug("Smartcard wallet self-derivation failed", "err", err)
  481. errc = <-w.deriveQuit
  482. }
  483. errc <- err
  484. }
  485. // Accounts retrieves the list of signing accounts the wallet is currently aware
  486. // of. For hierarchical deterministic wallets, the list will not be exhaustive,
  487. // rather only contain the accounts explicitly pinned during account derivation.
  488. func (w *Wallet) Accounts() []accounts.Account {
  489. // Attempt self-derivation if it's running
  490. reqc := make(chan struct{}, 1)
  491. select {
  492. case w.deriveReq <- reqc:
  493. // Self-derivation request accepted, wait for it
  494. <-reqc
  495. default:
  496. // Self-derivation offline, throttled or busy, skip
  497. }
  498. w.lock.Lock()
  499. defer w.lock.Unlock()
  500. if pairing := w.Hub.pairing(w); pairing != nil {
  501. ret := make([]accounts.Account, 0, len(pairing.Accounts))
  502. for address, path := range pairing.Accounts {
  503. ret = append(ret, w.makeAccount(address, path))
  504. }
  505. sort.Sort(accounts.AccountsByURL(ret))
  506. return ret
  507. }
  508. return nil
  509. }
  510. func (w *Wallet) makeAccount(address common.Address, path accounts.DerivationPath) accounts.Account {
  511. return accounts.Account{
  512. Address: address,
  513. URL: accounts.URL{
  514. Scheme: w.Hub.scheme,
  515. Path: fmt.Sprintf("%x/%s", w.PublicKey[1:3], path.String()),
  516. },
  517. }
  518. }
  519. // Contains returns whether an account is part of this particular wallet or not.
  520. func (w *Wallet) Contains(account accounts.Account) bool {
  521. if pairing := w.Hub.pairing(w); pairing != nil {
  522. _, ok := pairing.Accounts[account.Address]
  523. return ok
  524. }
  525. return false
  526. }
  527. // Initialize installs a keypair generated from the provided key into the wallet.
  528. func (w *Wallet) Initialize(seed []byte) error {
  529. w.lock.Lock()
  530. defer w.lock.Unlock()
  531. return w.session.initialize(seed)
  532. }
  533. // Derive attempts to explicitly derive a hierarchical deterministic account at
  534. // the specified derivation path. If requested, the derived account will be added
  535. // to the wallet's tracked account list.
  536. func (w *Wallet) Derive(path accounts.DerivationPath, pin bool) (accounts.Account, error) {
  537. w.lock.Lock()
  538. defer w.lock.Unlock()
  539. account, err := w.session.derive(path)
  540. if err != nil {
  541. return accounts.Account{}, err
  542. }
  543. if pin {
  544. pairing := w.Hub.pairing(w)
  545. pairing.Accounts[account.Address] = path
  546. if err := w.Hub.setPairing(w, pairing); err != nil {
  547. return accounts.Account{}, err
  548. }
  549. }
  550. return account, nil
  551. }
  552. // SelfDerive sets a base account derivation path from which the wallet attempts
  553. // to discover non zero accounts and automatically add them to list of tracked
  554. // accounts.
  555. //
  556. // Note, self derivaton will increment the last component of the specified path
  557. // opposed to decending into a child path to allow discovering accounts starting
  558. // from non zero components.
  559. //
  560. // You can disable automatic account discovery by calling SelfDerive with a nil
  561. // chain state reader.
  562. func (w *Wallet) SelfDerive(base accounts.DerivationPath, chain ethereum.ChainStateReader) {
  563. w.lock.Lock()
  564. defer w.lock.Unlock()
  565. w.deriveNextPath = make(accounts.DerivationPath, len(base))
  566. copy(w.deriveNextPath[:], base[:])
  567. w.deriveNextAddr = common.Address{}
  568. w.deriveChain = chain
  569. }
  570. // SignData requests the wallet to sign the hash of the given data.
  571. //
  572. // It looks up the account specified either solely via its address contained within,
  573. // or optionally with the aid of any location metadata from the embedded URL field.
  574. //
  575. // If the wallet requires additional authentication to sign the request (e.g.
  576. // a password to decrypt the account, or a PIN code o verify the transaction),
  577. // an AuthNeededError instance will be returned, containing infos for the user
  578. // about which fields or actions are needed. The user may retry by providing
  579. // the needed details via SignDataWithPassphrase, or by other means (e.g. unlock
  580. // the account in a keystore).
  581. func (w *Wallet) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) {
  582. return w.signHash(account, crypto.Keccak256(data))
  583. }
  584. func (w *Wallet) signHash(account accounts.Account, hash []byte) ([]byte, error) {
  585. w.lock.Lock()
  586. defer w.lock.Unlock()
  587. path, err := w.findAccountPath(account)
  588. if err != nil {
  589. return nil, err
  590. }
  591. return w.session.sign(path, hash)
  592. }
  593. // SignTx requests the wallet to sign the given transaction.
  594. //
  595. // It looks up the account specified either solely via its address contained within,
  596. // or optionally with the aid of any location metadata from the embedded URL field.
  597. //
  598. // If the wallet requires additional authentication to sign the request (e.g.
  599. // a password to decrypt the account, or a PIN code o verify the transaction),
  600. // an AuthNeededError instance will be returned, containing infos for the user
  601. // about which fields or actions are needed. The user may retry by providing
  602. // the needed details via SignTxWithPassphrase, or by other means (e.g. unlock
  603. // the account in a keystore).
  604. func (w *Wallet) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
  605. signer := types.NewEIP155Signer(chainID)
  606. hash := signer.Hash(tx)
  607. sig, err := w.signHash(account, hash[:])
  608. if err != nil {
  609. return nil, err
  610. }
  611. return tx.WithSignature(signer, sig)
  612. }
  613. // SignDataWithPassphrase requests the wallet to sign the given hash with the
  614. // given passphrase as extra authentication information.
  615. //
  616. // It looks up the account specified either solely via its address contained within,
  617. // or optionally with the aid of any location metadata from the embedded URL field.
  618. func (w *Wallet) SignDataWithPassphrase(account accounts.Account, passphrase, mimeType string, data []byte) ([]byte, error) {
  619. return w.signHashWithPassphrase(account, passphrase, crypto.Keccak256(data))
  620. }
  621. func (w *Wallet) signHashWithPassphrase(account accounts.Account, passphrase string, hash []byte) ([]byte, error) {
  622. if !w.session.verified {
  623. if err := w.Open(passphrase); err != nil {
  624. return nil, err
  625. }
  626. }
  627. return w.signHash(account, hash)
  628. }
  629. // SignText requests the wallet to sign the hash of a given piece of data, prefixed
  630. // by the Ethereum prefix scheme
  631. // It looks up the account specified either solely via its address contained within,
  632. // or optionally with the aid of any location metadata from the embedded URL field.
  633. //
  634. // If the wallet requires additional authentication to sign the request (e.g.
  635. // a password to decrypt the account, or a PIN code o verify the transaction),
  636. // an AuthNeededError instance will be returned, containing infos for the user
  637. // about which fields or actions are needed. The user may retry by providing
  638. // the needed details via SignHashWithPassphrase, or by other means (e.g. unlock
  639. // the account in a keystore).
  640. func (w *Wallet) SignText(account accounts.Account, text []byte) ([]byte, error) {
  641. return w.signHash(account, accounts.TextHash(text))
  642. }
  643. // SignTextWithPassphrase implements accounts.Wallet, attempting to sign the
  644. // given hash with the given account using passphrase as extra authentication
  645. func (w *Wallet) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) {
  646. return w.signHashWithPassphrase(account, passphrase, crypto.Keccak256(accounts.TextHash(text)))
  647. }
  648. // SignTxWithPassphrase requests the wallet to sign the given transaction, with the
  649. // given passphrase as extra authentication information.
  650. //
  651. // It looks up the account specified either solely via its address contained within,
  652. // or optionally with the aid of any location metadata from the embedded URL field.
  653. func (w *Wallet) SignTxWithPassphrase(account accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
  654. if !w.session.verified {
  655. if err := w.Open(passphrase); err != nil {
  656. return nil, err
  657. }
  658. }
  659. return w.SignTx(account, tx, chainID)
  660. }
  661. // findAccountPath returns the derivation path for the provided account.
  662. // It first checks for the address in the list of pinned accounts, and if it is
  663. // not found, attempts to parse the derivation path from the account's URL.
  664. func (w *Wallet) findAccountPath(account accounts.Account) (accounts.DerivationPath, error) {
  665. pairing := w.Hub.pairing(w)
  666. if path, ok := pairing.Accounts[account.Address]; ok {
  667. return path, nil
  668. }
  669. // Look for the path in the URL
  670. if account.URL.Scheme != w.Hub.scheme {
  671. return nil, fmt.Errorf("Scheme %s does not match wallet scheme %s", account.URL.Scheme, w.Hub.scheme)
  672. }
  673. parts := strings.SplitN(account.URL.Path, "/", 2)
  674. if len(parts) != 2 {
  675. return nil, fmt.Errorf("Invalid URL format: %s", account.URL)
  676. }
  677. if parts[0] != fmt.Sprintf("%x", w.PublicKey[1:3]) {
  678. return nil, fmt.Errorf("URL %s is not for this wallet", account.URL)
  679. }
  680. return accounts.ParseDerivationPath(parts[1])
  681. }
  682. // Session represents a secured communication session with the wallet.
  683. type Session struct {
  684. Wallet *Wallet // A handle to the wallet that opened the session
  685. Channel *SecureChannelSession // A secure channel for encrypted messages
  686. verified bool // Whether the pin has been verified in this session.
  687. }
  688. // pair establishes a new pairing over this channel, using the provided secret.
  689. func (s *Session) pair(secret []byte) (smartcardPairing, error) {
  690. err := s.Channel.Pair(secret)
  691. if err != nil {
  692. return smartcardPairing{}, err
  693. }
  694. return smartcardPairing{
  695. PublicKey: s.Wallet.PublicKey,
  696. PairingIndex: s.Channel.PairingIndex,
  697. PairingKey: s.Channel.PairingKey,
  698. Accounts: make(map[common.Address]accounts.DerivationPath),
  699. }, nil
  700. }
  701. // unpair deletes an existing pairing.
  702. func (s *Session) unpair() error {
  703. if !s.verified {
  704. return fmt.Errorf("Unpair requires that the PIN be verified")
  705. }
  706. return s.Channel.Unpair()
  707. }
  708. // verifyPin unlocks a wallet with the provided pin.
  709. func (s *Session) verifyPin(pin []byte) error {
  710. if _, err := s.Channel.TransmitEncrypted(claSCWallet, insVerifyPin, 0, 0, pin); err != nil {
  711. return err
  712. }
  713. s.verified = true
  714. return nil
  715. }
  716. // unblockPin unblocks a wallet with the provided puk and resets the pin to the
  717. // new one specified.
  718. func (s *Session) unblockPin(pukpin []byte) error {
  719. if _, err := s.Channel.TransmitEncrypted(claSCWallet, insUnblockPin, 0, 0, pukpin); err != nil {
  720. return err
  721. }
  722. s.verified = true
  723. return nil
  724. }
  725. // release releases resources associated with the channel.
  726. func (s *Session) release() error {
  727. return s.Wallet.card.Disconnect(pcsc.LeaveCard)
  728. }
  729. // paired returns true if a valid pairing exists.
  730. func (s *Session) paired() bool {
  731. return s.Channel.PairingKey != nil
  732. }
  733. // authenticate uses an existing pairing to establish a secure channel.
  734. func (s *Session) authenticate(pairing smartcardPairing) error {
  735. if !bytes.Equal(s.Wallet.PublicKey, pairing.PublicKey) {
  736. return fmt.Errorf("Cannot pair using another wallet's pairing; %x != %x", s.Wallet.PublicKey, pairing.PublicKey)
  737. }
  738. s.Channel.PairingKey = pairing.PairingKey
  739. s.Channel.PairingIndex = pairing.PairingIndex
  740. return s.Channel.Open()
  741. }
  742. // walletStatus describes a smartcard wallet's status information.
  743. type walletStatus struct {
  744. PinRetryCount int // Number of remaining PIN retries
  745. PukRetryCount int // Number of remaining PUK retries
  746. Initialized bool // Whether the card has been initialized with a private key
  747. SupportsPKDerivation bool // Whether the card supports doing public key derivation itself
  748. }
  749. // walletStatus fetches the wallet's status from the card.
  750. func (s *Session) walletStatus() (*walletStatus, error) {
  751. response, err := s.Channel.TransmitEncrypted(claSCWallet, insStatus, statusP1WalletStatus, 0, nil)
  752. if err != nil {
  753. return nil, err
  754. }
  755. // There is an issue with ASN1 decoding that I am struggling with,
  756. // so I unpack it manually, like is being done in the status-im
  757. // card management code.
  758. if len(response.Data) != int(response.Data[1])-1 {
  759. return nil, fmt.Errorf("invalid response length %d", len(response.Data))
  760. }
  761. if response.Data[0] != 0xA3 {
  762. return nil, fmt.Errorf("invalid tag %v, expected 0xA3", response.Data[0])
  763. }
  764. if response.Data[2] != 2 || response.Data[3] != 1 || response.Data[5] != 2 || response.Data[6] != 1 || response.Data[8] != 1 || response.Data[9] != 1 {
  765. return nil, fmt.Errorf("invalid response tag format")
  766. }
  767. status := &walletStatus{
  768. PinRetryCount: int(response.Data[4]),
  769. PukRetryCount: int(response.Data[7]),
  770. Initialized: (response.Data[10] == 0xff),
  771. SupportsPKDerivation: true, /* Cards that don't aren't supported */
  772. }
  773. /*
  774. if _, err := asn1.Unmarshal(response.Data, status); err != nil {
  775. //if _, err := asn1.UnmarshalWithParams(response.Data, status, "tag:3"); err != nil {
  776. fmt.Println("###### asn1 err", err)
  777. return nil, err
  778. }*/
  779. return status, nil
  780. }
  781. // derivationPath fetches the wallet's current derivation path from the card.
  782. func (s *Session) derivationPath() (accounts.DerivationPath, error) {
  783. response, err := s.Channel.TransmitEncrypted(claSCWallet, insStatus, statusP1Path, 0, nil)
  784. if err != nil {
  785. return nil, err
  786. }
  787. buf := bytes.NewReader(response.Data)
  788. path := make(accounts.DerivationPath, len(response.Data)/4)
  789. return path, binary.Read(buf, binary.BigEndian, &path)
  790. }
  791. // initializeData contains data needed to initialize the smartcard wallet.
  792. type initializeData struct {
  793. PublicKey []byte `asn1:"tag:0"`
  794. PrivateKey []byte `asn1:"tag:1"`
  795. ChainCode []byte `asn1:"tag:2"`
  796. }
  797. // initialize initializes the card with new key data.
  798. func (s *Session) initialize(seed []byte) error {
  799. // HMAC the seed to produce the private key and chain code
  800. mac := hmac.New(sha512.New, []byte("Bitcoin seed"))
  801. mac.Write(seed)
  802. seed = mac.Sum(nil)
  803. key, err := crypto.ToECDSA(seed[:32])
  804. if err != nil {
  805. return err
  806. }
  807. id := initializeData{}
  808. id.PublicKey = crypto.FromECDSAPub(&key.PublicKey)
  809. id.PrivateKey = seed[:32]
  810. id.ChainCode = seed[32:]
  811. data, err := asn1.Marshal(id)
  812. if err != nil {
  813. return err
  814. }
  815. // Nasty hack to force the top-level struct tag to be context-specific
  816. data[0] = 0xA1
  817. _, err = s.Channel.TransmitEncrypted(claSCWallet, insLoadKey, 0x02, 0, data)
  818. return err
  819. }
  820. // derive derives a new HD key path on the card.
  821. func (s *Session) derive(path accounts.DerivationPath) (accounts.Account, error) {
  822. // If the current path is a prefix of the desired path, we don't have to
  823. // start again.
  824. remainingPath := path
  825. pubkey, err := s.publicKey()
  826. if err != nil {
  827. return accounts.Account{}, err
  828. }
  829. currentPath, err := s.derivationPath()
  830. if err != nil {
  831. return accounts.Account{}, err
  832. }
  833. reset := false
  834. if len(currentPath) <= len(path) {
  835. for i := 0; i < len(currentPath); i++ {
  836. if path[i] != currentPath[i] {
  837. reset = true
  838. break
  839. }
  840. }
  841. if !reset {
  842. remainingPath = path[len(currentPath):]
  843. }
  844. } else {
  845. reset = true
  846. }
  847. for _, pathComponent := range remainingPath {
  848. pubkey, err = s.deriveKeyAssisted(reset, pathComponent)
  849. reset = false
  850. if err != nil {
  851. return accounts.Account{}, err
  852. }
  853. }
  854. pub, err := crypto.UnmarshalPubkey(pubkey)
  855. if err != nil {
  856. return accounts.Account{}, err
  857. }
  858. return s.Wallet.makeAccount(crypto.PubkeyToAddress(*pub), path), nil
  859. }
  860. // keyDerivationInfo contains information on the current key derivation step.
  861. type keyDerivationInfo struct {
  862. PublicKeyX []byte `asn1:"tag:3"` // The X coordinate of the current public key
  863. Signature struct {
  864. R *big.Int
  865. S *big.Int
  866. }
  867. }
  868. // deriveKeyAssisted does one step of assisted key generation, asking the card to generate
  869. // a specific path, and performing the necessary computations to finish the public key
  870. // generation step.
  871. func (s *Session) deriveKeyAssisted(reset bool, pathComponent uint32) ([]byte, error) {
  872. p1 := deriveP1Assisted
  873. if !reset {
  874. p1 |= deriveP1Append
  875. }
  876. buf := new(bytes.Buffer)
  877. if err := binary.Write(buf, binary.BigEndian, pathComponent); err != nil {
  878. return nil, err
  879. }
  880. response, err := s.Channel.TransmitEncrypted(claSCWallet, insDeriveKey, p1, deriveP2KeyPath, buf.Bytes())
  881. if err != nil {
  882. return nil, err
  883. }
  884. keyinfo := new(keyDerivationInfo)
  885. if _, err := asn1.UnmarshalWithParams(response.Data, keyinfo, "tag:2"); err != nil {
  886. return nil, err
  887. }
  888. rbytes, sbytes := keyinfo.Signature.R.Bytes(), keyinfo.Signature.S.Bytes()
  889. sig := make([]byte, 65)
  890. copy(sig[32-len(rbytes):32], rbytes)
  891. copy(sig[64-len(sbytes):64], sbytes)
  892. pubkey, err := determinePublicKey(sig, keyinfo.PublicKeyX)
  893. if err != nil {
  894. return nil, err
  895. }
  896. _, err = s.Channel.TransmitEncrypted(claSCWallet, insDeriveKey, deriveP1Assisted|deriveP1Append, deriveP2PublicKey, pubkey)
  897. if err != nil {
  898. return nil, err
  899. }
  900. return pubkey, nil
  901. }
  902. // keyExport contains information on an exported keypair.
  903. type keyExport struct {
  904. PublicKey []byte `asn1:"tag:0"`
  905. PrivateKey []byte `asn1:"tag:1,optional"`
  906. }
  907. // publicKey returns the public key for the current derivation path.
  908. func (s *Session) publicKey() ([]byte, error) {
  909. response, err := s.Channel.TransmitEncrypted(claSCWallet, insExportKey, exportP1Any, exportP2Pubkey, nil)
  910. if err != nil {
  911. return nil, err
  912. }
  913. keys := new(keyExport)
  914. if _, err := asn1.UnmarshalWithParams(response.Data, keys, "tag:1"); err != nil {
  915. return nil, err
  916. }
  917. return keys.PublicKey, nil
  918. }
  919. // signatureData contains information on a signature - the signature itself and
  920. // the corresponding public key.
  921. type signatureData struct {
  922. PublicKey []byte `asn1:"tag:0"`
  923. Signature struct {
  924. R *big.Int
  925. S *big.Int
  926. }
  927. }
  928. // sign asks the card to sign a message, and returns a valid signature after
  929. // recovering the v value.
  930. func (s *Session) sign(path accounts.DerivationPath, hash []byte) ([]byte, error) {
  931. startTime := time.Now()
  932. _, err := s.derive(path)
  933. if err != nil {
  934. return nil, err
  935. }
  936. deriveTime := time.Now()
  937. response, err := s.Channel.TransmitEncrypted(claSCWallet, insSign, signP1PrecomputedHash, signP2OnlyBlock, hash)
  938. if err != nil {
  939. return nil, err
  940. }
  941. sigdata := new(signatureData)
  942. if _, err := asn1.UnmarshalWithParams(response.Data, sigdata, "tag:0"); err != nil {
  943. return nil, err
  944. }
  945. // Serialize the signature
  946. rbytes, sbytes := sigdata.Signature.R.Bytes(), sigdata.Signature.S.Bytes()
  947. sig := make([]byte, 65)
  948. copy(sig[32-len(rbytes):32], rbytes)
  949. copy(sig[64-len(sbytes):64], sbytes)
  950. // Recover the V value.
  951. sig, err = makeRecoverableSignature(hash, sig, sigdata.PublicKey)
  952. if err != nil {
  953. return nil, err
  954. }
  955. log.Debug("Signed using smartcard", "deriveTime", deriveTime.Sub(startTime), "signingTime", time.Since(deriveTime))
  956. return sig, nil
  957. }
  958. // determinePublicKey uses a signature and the X component of a public key to
  959. // recover the entire public key.
  960. func determinePublicKey(sig, pubkeyX []byte) ([]byte, error) {
  961. for v := 0; v < 2; v++ {
  962. sig[64] = byte(v)
  963. pubkey, err := crypto.Ecrecover(DerivationSignatureHash[:], sig)
  964. if err == nil {
  965. if bytes.Equal(pubkey[1:33], pubkeyX) {
  966. return pubkey, nil
  967. }
  968. } else if v == 1 || err != secp256k1.ErrRecoverFailed {
  969. return nil, err
  970. }
  971. }
  972. return nil, ErrPubkeyMismatch
  973. }
  974. // makeRecoverableSignature uses a signature and an expected public key to
  975. // recover the v value and produce a recoverable signature.
  976. func makeRecoverableSignature(hash, sig, expectedPubkey []byte) ([]byte, error) {
  977. for v := 0; v < 2; v++ {
  978. sig[64] = byte(v)
  979. pubkey, err := crypto.Ecrecover(hash, sig)
  980. if err == nil {
  981. if bytes.Equal(pubkey, expectedPubkey) {
  982. return sig, nil
  983. }
  984. } else if v == 1 || err != secp256k1.ErrRecoverFailed {
  985. return nil, err
  986. }
  987. }
  988. return nil, ErrPubkeyMismatch
  989. }