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