wallet.go 34 KB

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