accounts, core, internal, node: Add support for smartcard wallets

This commit is contained in:
Nick Johnson
2018-01-07 18:38:11 +00:00
committed by Guillaume Ballet
parent 3996bc1ad9
commit f7027dd68c
21 changed files with 5364 additions and 0 deletions

View File

@ -17,6 +17,7 @@
package accounts
import (
"encoding/json"
"errors"
"fmt"
"math"
@ -133,3 +134,17 @@ func (path DerivationPath) String() string {
}
return result
}
func (path DerivationPath) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("\"%s\"", path.String())), nil
}
func (dp *DerivationPath) UnmarshalJSON(b []byte) error {
var path string
var err error
if err = json.Unmarshal(b, &path); err != nil {
return err
}
*dp, err = ParseDerivationPath(path)
return err
}

96
accounts/scwallet/apdu.go Normal file
View File

@ -0,0 +1,96 @@
// Copyright 2018 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package scwallet
import (
"bytes"
"encoding/binary"
)
const (
CLA_ISO7816 = 0
INS_SELECT = 0xA4
INS_GET_RESPONSE = 0xC0
INS_PAIR = 0x12
INS_UNPAIR = 0x13
INS_OPEN_SECURE_CHANNEL = 0x10
INS_MUTUALLY_AUTHENTICATE = 0x11
SW1_GET_RESPONSE = 0x61
SW1_OK = 0x90
)
// CommandAPDU represents an application data unit sent to a smartcard
type CommandAPDU struct {
Cla, Ins, P1, P2 uint8 // Class, Instruction, Parameter 1, Parameter 2
Data []byte // Command data
Le uint8 // Command data length
}
// serialize serializes a command APDU.
func (ca CommandAPDU) serialize() ([]byte, error) {
buf := new(bytes.Buffer)
if err := binary.Write(buf, binary.BigEndian, ca.Cla); err != nil {
return nil, err
}
if err := binary.Write(buf, binary.BigEndian, ca.Ins); err != nil {
return nil, err
}
if err := binary.Write(buf, binary.BigEndian, ca.P1); err != nil {
return nil, err
}
if err := binary.Write(buf, binary.BigEndian, ca.P2); err != nil {
return nil, err
}
if len(ca.Data) > 0 {
if err := binary.Write(buf, binary.BigEndian, uint8(len(ca.Data))); err != nil {
return nil, err
}
if err := binary.Write(buf, binary.BigEndian, ca.Data); err != nil {
return nil, err
}
}
if err := binary.Write(buf, binary.BigEndian, ca.Le); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// ResponseAPDU represents an application data unit received from a smart card
type ResponseAPDU struct {
Data []byte // response data
Sw1, Sw2 uint8 // status words 1 and 2
}
// deserialize deserializes a response APDU
func (ra *ResponseAPDU) deserialize(data []byte) error {
ra.Data = make([]byte, len(data)-2)
buf := bytes.NewReader(data)
if err := binary.Read(buf, binary.BigEndian, &ra.Data); err != nil {
return err
}
if err := binary.Read(buf, binary.BigEndian, &ra.Sw1); err != nil {
return err
}
if err := binary.Read(buf, binary.BigEndian, &ra.Sw2); err != nil {
return err
}
return nil
}

277
accounts/scwallet/hub.go Normal file
View File

@ -0,0 +1,277 @@
// Copyright 2018 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package scwallet
import (
"encoding/json"
"io/ioutil"
"os"
"reflect"
"sync"
"time"
"github.com/ebfe/scard"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/log"
)
const Scheme = "pcsc"
// refreshCycle is the maximum time between wallet refreshes (if USB hotplug
// notifications don't work).
const refreshCycle = 5 * time.Second
// refreshThrottling is the minimum time between wallet refreshes to avoid thrashing.
const refreshThrottling = 500 * time.Millisecond
// SmartcardPairing contains information about a smart card we have paired with
// or might pair withub.
type SmartcardPairing struct {
PublicKey []byte `json:"publicKey"`
PairingIndex uint8 `json:"pairingIndex"`
PairingKey []byte `json:"pairingKey"`
Accounts map[common.Address]accounts.DerivationPath `json:"accounts"`
}
// Hub is a accounts.Backend that can find and handle generic PC/SC hardware wallets.
type Hub struct {
scheme string // Protocol scheme prefixing account and wallet URLs.
context *scard.Context
datadir string
pairings map[string]SmartcardPairing
refreshed time.Time // Time instance when the list of wallets was last refreshed
wallets map[string]*Wallet // Mapping from reader names to wallet instances
updateFeed event.Feed // Event feed to notify wallet additions/removals
updateScope event.SubscriptionScope // Subscription scope tracking current live listeners
updating bool // Whether the event notification loop is running
quit chan chan error
stateLock sync.Mutex // Protects the internals of the hub from racey access
}
var HubType = reflect.TypeOf(&Hub{})
func (hub *Hub) readPairings() error {
hub.pairings = make(map[string]SmartcardPairing)
pairingFile, err := os.Open(hub.datadir + "/smartcards.json")
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
pairingData, err := ioutil.ReadAll(pairingFile)
if err != nil {
return err
}
var pairings []SmartcardPairing
if err := json.Unmarshal(pairingData, &pairings); err != nil {
return err
}
for _, pairing := range pairings {
hub.pairings[string(pairing.PublicKey)] = pairing
}
return nil
}
func (hub *Hub) writePairings() error {
pairingFile, err := os.OpenFile(hub.datadir+"/smartcards.json", os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
return err
}
pairings := make([]SmartcardPairing, 0, len(hub.pairings))
for _, pairing := range hub.pairings {
pairings = append(pairings, pairing)
}
pairingData, err := json.Marshal(pairings)
if err != nil {
return err
}
if _, err := pairingFile.Write(pairingData); err != nil {
return err
}
return pairingFile.Close()
}
func (hub *Hub) getPairing(wallet *Wallet) *SmartcardPairing {
pairing, ok := hub.pairings[string(wallet.PublicKey)]
if ok {
return &pairing
}
return nil
}
func (hub *Hub) setPairing(wallet *Wallet, pairing *SmartcardPairing) error {
if pairing == nil {
delete(hub.pairings, string(wallet.PublicKey))
} else {
hub.pairings[string(wallet.PublicKey)] = *pairing
}
return hub.writePairings()
}
// NewHub creates a new hardware wallet manager for smartcards.
func NewHub(scheme string, datadir string) (*Hub, error) {
context, err := scard.EstablishContext()
if err != nil {
return nil, err
}
hub := &Hub{
scheme: scheme,
context: context,
datadir: datadir,
wallets: make(map[string]*Wallet),
quit: make(chan chan error),
}
if err := hub.readPairings(); err != nil {
return nil, err
}
hub.refreshWallets()
return hub, nil
}
// Wallets implements accounts.Backend, returning all the currently tracked USB
// devices that appear to be hardware wallets.
func (hub *Hub) Wallets() []accounts.Wallet {
// Make sure the list of wallets is up to date
hub.stateLock.Lock()
defer hub.stateLock.Unlock()
hub.refreshWallets()
cpy := make([]accounts.Wallet, 0, len(hub.wallets))
for _, wallet := range hub.wallets {
if wallet != nil {
cpy = append(cpy, wallet)
}
}
return cpy
}
// refreshWallets scans the USB devices attached to the machine and updates the
// list of wallets based on the found devices.
func (hub *Hub) refreshWallets() {
elapsed := time.Since(hub.refreshed)
if elapsed < refreshThrottling {
return
}
readers, err := hub.context.ListReaders()
if err != nil {
log.Error("Error listing readers", "err", err)
}
events := []accounts.WalletEvent{}
seen := make(map[string]struct{})
for _, reader := range readers {
if wallet, ok := hub.wallets[reader]; ok {
// We already know about this card; check it's still present
if err := wallet.ping(); err != nil {
log.Debug("Got error pinging wallet", "reader", reader, "err", err)
} else {
seen[reader] = struct{}{}
}
continue
}
seen[reader] = struct{}{}
card, err := hub.context.Connect(reader, scard.ShareShared, scard.ProtocolAny)
if err != nil {
log.Debug("Error opening card", "reader", reader, "err", err)
continue
}
wallet := NewWallet(hub, card)
err = wallet.connect()
if err != nil {
log.Debug("Error connecting to wallet", "reader", reader, "err", err)
card.Disconnect(scard.LeaveCard)
continue
}
hub.wallets[reader] = wallet
events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived})
log.Info("Found new smartcard wallet", "reader", reader, "publicKey", hexutil.Encode(wallet.PublicKey[:4]))
}
// Remove any wallets we no longer see
for k, wallet := range hub.wallets {
if _, ok := seen[k]; !ok {
log.Info("Wallet disconnected", "pubkey", hexutil.Encode(wallet.PublicKey[:4]), "reader", k)
wallet.Close()
events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
delete(hub.wallets, k)
}
}
for _, event := range events {
hub.updateFeed.Send(event)
}
hub.refreshed = time.Now()
}
// Subscribe implements accounts.Backend, creating an async subscription to
// receive notifications on the addition or removal of wallets.
func (hub *Hub) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
// We need the mutex to reliably start/stop the update loop
hub.stateLock.Lock()
defer hub.stateLock.Unlock()
// Subscribe the caller and track the subscriber count
sub := hub.updateScope.Track(hub.updateFeed.Subscribe(sink))
// Subscribers require an active notification loop, start it
if !hub.updating {
hub.updating = true
go hub.updater()
}
return sub
}
// updater is responsible for maintaining an up-to-date list of wallets managed
// by the hub, and for firing wallet addition/removal events.
func (hub *Hub) updater() {
for {
time.Sleep(refreshCycle)
// Run the wallet refresher
hub.stateLock.Lock()
hub.refreshWallets()
// If all our subscribers left, stop the updater
if hub.updateScope.Count() == 0 {
hub.updating = false
hub.stateLock.Unlock()
return
}
hub.stateLock.Unlock()
}
}

View File

@ -0,0 +1,342 @@
// Copyright 2018 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package scwallet
import (
//"crypto/ecdsa"
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"crypto/sha512"
"fmt"
//"math/big"
"github.com/ebfe/scard"
"github.com/ethereum/go-ethereum/crypto"
ecdh "github.com/wsddn/go-ecdh"
)
const (
MAX_PAYLOAD_SIZE = 223
PAIR_P1_FIRST_STEP = 0
PAIR_P1_LAST_STEP = 1
SC_SECRET_LENGTH = 32
SC_BLOCK_SIZE = 16
)
// SecureChannelSession enables secure communication with a hardware wallet
type SecureChannelSession struct {
card *scard.Card // A handle to the smartcard for communication
secret []byte // A shared secret generated from our ECDSA keys
publicKey []byte // Our own ephemeral public key
PairingKey []byte // A permanent shared secret for a pairing, if present
sessionEncKey []byte // The current session encryption key
sessionMacKey []byte // The current session MAC key
iv []byte // The current IV
PairingIndex uint8 // The pairing index
}
// NewSecureChannelSession creates a new secure channel for the given card and public key
func NewSecureChannelSession(card *scard.Card, keyData []byte) (*SecureChannelSession, error) {
// Generate an ECDSA keypair for ourselves
gen := ecdh.NewEllipticECDH(crypto.S256())
private, public, err := gen.GenerateKey(rand.Reader)
if err != nil {
return nil, err
}
cardPublic, ok := gen.Unmarshal(keyData)
if !ok {
return nil, fmt.Errorf("Could not unmarshal public key from card")
}
secret, err := gen.GenerateSharedSecret(private, cardPublic)
if err != nil {
return nil, err
}
return &SecureChannelSession{
card: card,
secret: secret,
publicKey: gen.Marshal(public),
}, nil
}
// Pair establishes a new pairing with the smartcard
func (s *SecureChannelSession) Pair(sharedSecret []byte) error {
secretHash := sha256.Sum256(sharedSecret)
challenge := make([]byte, 32)
if _, err := rand.Read(challenge); err != nil {
return err
}
response, err := s.pair(PAIR_P1_FIRST_STEP, challenge)
if err != nil {
return err
}
md := sha256.New()
md.Write(secretHash[:])
md.Write(challenge)
expectedCryptogram := md.Sum(nil)
cardCryptogram := response.Data[:32]
cardChallenge := response.Data[32:]
if !bytes.Equal(expectedCryptogram, cardCryptogram) {
return fmt.Errorf("Invalid card cryptogram")
}
md.Reset()
md.Write(secretHash[:])
md.Write(cardChallenge)
response, err = s.pair(PAIR_P1_LAST_STEP, md.Sum(nil))
if err != nil {
return err
}
md.Reset()
md.Write(secretHash[:])
md.Write(response.Data[1:])
s.PairingKey = md.Sum(nil)
s.PairingIndex = response.Data[0]
return nil
}
// Unpair disestablishes an existing pairing
func (s *SecureChannelSession) Unpair() error {
if s.PairingKey == nil {
return fmt.Errorf("Cannot unpair: not paired")
}
_, err := s.TransmitEncrypted(CLA_SCWALLET, INS_UNPAIR, s.PairingIndex, 0, []byte{})
if err != nil {
return err
}
s.PairingKey = nil
// Close channel
s.iv = nil
return nil
}
// Open initializes the secure channel
func (s *SecureChannelSession) Open() error {
if s.iv != nil {
return fmt.Errorf("Session already opened")
}
response, err := s.open()
if err != nil {
return err
}
// Generate the encryption/mac key by hashing our shared secret,
// pairing key, and the first bytes returned from the Open APDU.
md := sha512.New()
md.Write(s.secret)
md.Write(s.PairingKey)
md.Write(response.Data[:SC_SECRET_LENGTH])
keyData := md.Sum(nil)
s.sessionEncKey = keyData[:SC_SECRET_LENGTH]
s.sessionMacKey = keyData[SC_SECRET_LENGTH : SC_SECRET_LENGTH*2]
// The IV is the last bytes returned from the Open APDU.
s.iv = response.Data[SC_SECRET_LENGTH:]
if err := s.mutuallyAuthenticate(); err != nil {
return err
}
return nil
}
// mutuallyAuthenticate is an internal method to authenticate both ends of the
// connection.
func (s *SecureChannelSession) mutuallyAuthenticate() error {
data := make([]byte, SC_SECRET_LENGTH)
if _, err := rand.Read(data); err != nil {
return err
}
response, err := s.TransmitEncrypted(CLA_SCWALLET, INS_MUTUALLY_AUTHENTICATE, 0, 0, data)
if err != nil {
return err
}
if response.Sw1 != 0x90 || response.Sw2 != 0x00 {
return fmt.Errorf("Got unexpected response from MUTUALLY_AUTHENTICATE: 0x%x%x", response.Sw1, response.Sw2)
}
if len(response.Data) != SC_SECRET_LENGTH {
return fmt.Errorf("Response from MUTUALLY_AUTHENTICATE was %d bytes, expected %d", len(response.Data), SC_SECRET_LENGTH)
}
return nil
}
// open is an internal method that sends an open APDU
func (s *SecureChannelSession) open() (*ResponseAPDU, error) {
return transmit(s.card, &CommandAPDU{
Cla: CLA_SCWALLET,
Ins: INS_OPEN_SECURE_CHANNEL,
P1: s.PairingIndex,
P2: 0,
Data: s.publicKey,
Le: 0,
})
}
// pair is an internal method that sends a pair APDU
func (s *SecureChannelSession) pair(p1 uint8, data []byte) (*ResponseAPDU, error) {
return transmit(s.card, &CommandAPDU{
Cla: CLA_SCWALLET,
Ins: INS_PAIR,
P1: p1,
P2: 0,
Data: data,
Le: 0,
})
}
// TransmitEncrypted sends an encrypted message, and decrypts and returns the response
func (s *SecureChannelSession) TransmitEncrypted(cla, ins, p1, p2 byte, data []byte) (*ResponseAPDU, error) {
if s.iv == nil {
return nil, fmt.Errorf("Channel not open")
}
data, err := s.encryptAPDU(data)
if err != nil {
return nil, err
}
meta := []byte{cla, ins, p1, p2, byte(len(data) + SC_BLOCK_SIZE), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
if err = s.updateIV(meta, data); err != nil {
return nil, err
}
fulldata := make([]byte, len(s.iv)+len(data))
copy(fulldata, s.iv)
copy(fulldata[len(s.iv):], data)
response, err := transmit(s.card, &CommandAPDU{
Cla: cla,
Ins: ins,
P1: p1,
P2: p2,
Data: fulldata,
})
if err != nil {
return nil, err
}
rmeta := []byte{byte(len(response.Data)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
rmac := response.Data[:len(s.iv)]
rdata := response.Data[len(s.iv):]
plainData, err := s.decryptAPDU(rdata)
if err != nil {
return nil, err
}
if err = s.updateIV(rmeta, rdata); err != nil {
return nil, err
}
if !bytes.Equal(s.iv, rmac) {
return nil, fmt.Errorf("Invalid MAC in response")
}
rapdu := &ResponseAPDU{}
rapdu.deserialize(plainData)
if rapdu.Sw1 != SW1_OK {
return nil, fmt.Errorf("Unexpected response status Cla=0x%x, Ins=0x%x, Sw=0x%x%x", cla, ins, rapdu.Sw1, rapdu.Sw2)
}
return rapdu, nil
}
// encryptAPDU is an internal method that serializes and encrypts an APDU
func (s *SecureChannelSession) encryptAPDU(data []byte) ([]byte, error) {
if len(data) > MAX_PAYLOAD_SIZE {
return nil, fmt.Errorf("Payload of %d bytes exceeds maximum of %d", len(data), MAX_PAYLOAD_SIZE)
}
data = pad(data, 0x80)
ret := make([]byte, len(data))
a, err := aes.NewCipher(s.sessionEncKey)
if err != nil {
return nil, err
}
crypter := cipher.NewCBCEncrypter(a, s.iv)
crypter.CryptBlocks(ret, data)
return ret, nil
}
// pad applies message padding to a 16 byte boundary
func pad(data []byte, terminator byte) []byte {
padded := make([]byte, (len(data)/16+1)*16)
copy(padded, data)
padded[len(data)] = terminator
return padded
}
// decryptAPDU is an internal method that decrypts and deserializes an APDU
func (s *SecureChannelSession) decryptAPDU(data []byte) ([]byte, error) {
a, err := aes.NewCipher(s.sessionEncKey)
if err != nil {
return nil, err
}
ret := make([]byte, len(data))
crypter := cipher.NewCBCDecrypter(a, s.iv)
crypter.CryptBlocks(ret, data)
return unpad(ret, 0x80)
}
// unpad strips padding from a message
func unpad(data []byte, terminator byte) ([]byte, error) {
for i := 1; i <= 16; i++ {
switch data[len(data)-i] {
case 0:
continue
case terminator:
return data[:len(data)-i], nil
default:
return nil, fmt.Errorf("Expected end of padding, got %d", data[len(data)-i])
}
}
return nil, fmt.Errorf("Expected end of padding, got 0")
}
// updateIV is an internal method that updates the initialization vector after
// each message exchanged.
func (s *SecureChannelSession) updateIV(meta, data []byte) error {
data = pad(data, 0)
a, err := aes.NewCipher(s.sessionMacKey)
if err != nil {
return err
}
crypter := cipher.NewCBCEncrypter(a, make([]byte, 16))
crypter.CryptBlocks(meta, meta)
crypter.CryptBlocks(data, data)
// The first 16 bytes of the last block is the MAC
s.iv = data[len(data)-32 : len(data)-16]
return nil
}

1011
accounts/scwallet/wallet.go Normal file

File diff suppressed because it is too large Load Diff