github.com/theQRL/go-zond@v0.1.1/accounts/scwallet/securechannel.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 "crypto/aes" 22 "crypto/cipher" 23 "crypto/elliptic" 24 "crypto/rand" 25 "crypto/sha256" 26 "crypto/sha512" 27 "errors" 28 "fmt" 29 30 pcsc "github.com/gballet/go-libpcsclite" 31 "github.com/theQRL/go-zond/crypto" 32 "golang.org/x/crypto/pbkdf2" 33 "golang.org/x/text/unicode/norm" 34 ) 35 36 const ( 37 maxPayloadSize = 223 38 pairP1FirstStep = 0 39 pairP1LastStep = 1 40 41 scSecretLength = 32 42 scBlockSize = 16 43 44 insOpenSecureChannel = 0x10 45 insMutuallyAuthenticate = 0x11 46 insPair = 0x12 47 insUnpair = 0x13 48 49 pairingSalt = "Keycard Pairing Password Salt" 50 ) 51 52 // SecureChannelSession enables secure communication with a hardware wallet. 53 type SecureChannelSession struct { 54 card *pcsc.Card // A handle to the smartcard for communication 55 secret []byte // A shared secret generated from our ECDSA keys 56 publicKey []byte // Our own ephemeral public key 57 PairingKey []byte // A permanent shared secret for a pairing, if present 58 sessionEncKey []byte // The current session encryption key 59 sessionMacKey []byte // The current session MAC key 60 iv []byte // The current IV 61 PairingIndex uint8 // The pairing index 62 } 63 64 // NewSecureChannelSession creates a new secure channel for the given card and public key. 65 func NewSecureChannelSession(card *pcsc.Card, keyData []byte) (*SecureChannelSession, error) { 66 // Generate an ECDSA keypair for ourselves 67 key, err := crypto.GenerateKey() 68 if err != nil { 69 return nil, err 70 } 71 cardPublic, err := crypto.UnmarshalPubkey(keyData) 72 if err != nil { 73 return nil, fmt.Errorf("could not unmarshal public key from card: %v", err) 74 } 75 secret, _ := key.Curve.ScalarMult(cardPublic.X, cardPublic.Y, key.D.Bytes()) 76 return &SecureChannelSession{ 77 card: card, 78 secret: secret.Bytes(), 79 publicKey: elliptic.Marshal(crypto.S256(), key.PublicKey.X, key.PublicKey.Y), 80 }, nil 81 } 82 83 // Pair establishes a new pairing with the smartcard. 84 func (s *SecureChannelSession) Pair(pairingPassword []byte) error { 85 secretHash := pbkdf2.Key(norm.NFKD.Bytes(pairingPassword), norm.NFKD.Bytes([]byte(pairingSalt)), 50000, 32, sha256.New) 86 87 challenge := make([]byte, 32) 88 if _, err := rand.Read(challenge); err != nil { 89 return err 90 } 91 92 response, err := s.pair(pairP1FirstStep, challenge) 93 if err != nil { 94 return err 95 } 96 97 md := sha256.New() 98 md.Write(secretHash[:]) 99 md.Write(challenge) 100 101 expectedCryptogram := md.Sum(nil) 102 cardCryptogram := response.Data[:32] 103 cardChallenge := response.Data[32:64] 104 105 if !bytes.Equal(expectedCryptogram, cardCryptogram) { 106 return fmt.Errorf("invalid card cryptogram %v != %v", expectedCryptogram, cardCryptogram) 107 } 108 109 md.Reset() 110 md.Write(secretHash[:]) 111 md.Write(cardChallenge) 112 response, err = s.pair(pairP1LastStep, md.Sum(nil)) 113 if err != nil { 114 return err 115 } 116 117 md.Reset() 118 md.Write(secretHash[:]) 119 md.Write(response.Data[1:]) 120 s.PairingKey = md.Sum(nil) 121 s.PairingIndex = response.Data[0] 122 123 return nil 124 } 125 126 // Unpair disestablishes an existing pairing. 127 func (s *SecureChannelSession) Unpair() error { 128 if s.PairingKey == nil { 129 return errors.New("cannot unpair: not paired") 130 } 131 132 _, err := s.transmitEncrypted(claSCWallet, insUnpair, s.PairingIndex, 0, []byte{}) 133 if err != nil { 134 return err 135 } 136 s.PairingKey = nil 137 // Close channel 138 s.iv = nil 139 return nil 140 } 141 142 // Open initializes the secure channel. 143 func (s *SecureChannelSession) Open() error { 144 if s.iv != nil { 145 return errors.New("session already opened") 146 } 147 148 response, err := s.open() 149 if err != nil { 150 return err 151 } 152 153 // Generate the encryption/mac key by hashing our shared secret, 154 // pairing key, and the first bytes returned from the Open APDU. 155 md := sha512.New() 156 md.Write(s.secret) 157 md.Write(s.PairingKey) 158 md.Write(response.Data[:scSecretLength]) 159 keyData := md.Sum(nil) 160 s.sessionEncKey = keyData[:scSecretLength] 161 s.sessionMacKey = keyData[scSecretLength : scSecretLength*2] 162 163 // The IV is the last bytes returned from the Open APDU. 164 s.iv = response.Data[scSecretLength:] 165 166 return s.mutuallyAuthenticate() 167 } 168 169 // mutuallyAuthenticate is an internal method to authenticate both ends of the 170 // connection. 171 func (s *SecureChannelSession) mutuallyAuthenticate() error { 172 data := make([]byte, scSecretLength) 173 if _, err := rand.Read(data); err != nil { 174 return err 175 } 176 177 response, err := s.transmitEncrypted(claSCWallet, insMutuallyAuthenticate, 0, 0, data) 178 if err != nil { 179 return err 180 } 181 if response.Sw1 != 0x90 || response.Sw2 != 0x00 { 182 return fmt.Errorf("got unexpected response from MUTUALLY_AUTHENTICATE: %#x%x", response.Sw1, response.Sw2) 183 } 184 185 if len(response.Data) != scSecretLength { 186 return fmt.Errorf("response from MUTUALLY_AUTHENTICATE was %d bytes, expected %d", len(response.Data), scSecretLength) 187 } 188 189 return nil 190 } 191 192 // open is an internal method that sends an open APDU. 193 func (s *SecureChannelSession) open() (*responseAPDU, error) { 194 return transmit(s.card, &commandAPDU{ 195 Cla: claSCWallet, 196 Ins: insOpenSecureChannel, 197 P1: s.PairingIndex, 198 P2: 0, 199 Data: s.publicKey, 200 Le: 0, 201 }) 202 } 203 204 // pair is an internal method that sends a pair APDU. 205 func (s *SecureChannelSession) pair(p1 uint8, data []byte) (*responseAPDU, error) { 206 return transmit(s.card, &commandAPDU{ 207 Cla: claSCWallet, 208 Ins: insPair, 209 P1: p1, 210 P2: 0, 211 Data: data, 212 Le: 0, 213 }) 214 } 215 216 // transmitEncrypted sends an encrypted message, and decrypts and returns the response. 217 func (s *SecureChannelSession) transmitEncrypted(cla, ins, p1, p2 byte, data []byte) (*responseAPDU, error) { 218 if s.iv == nil { 219 return nil, errors.New("channel not open") 220 } 221 222 data, err := s.encryptAPDU(data) 223 if err != nil { 224 return nil, err 225 } 226 meta := [16]byte{cla, ins, p1, p2, byte(len(data) + scBlockSize)} 227 if err = s.updateIV(meta[:], data); err != nil { 228 return nil, err 229 } 230 231 fulldata := make([]byte, len(s.iv)+len(data)) 232 copy(fulldata, s.iv) 233 copy(fulldata[len(s.iv):], data) 234 235 response, err := transmit(s.card, &commandAPDU{ 236 Cla: cla, 237 Ins: ins, 238 P1: p1, 239 P2: p2, 240 Data: fulldata, 241 }) 242 if err != nil { 243 return nil, err 244 } 245 246 rmeta := [16]byte{byte(len(response.Data))} 247 rmac := response.Data[:len(s.iv)] 248 rdata := response.Data[len(s.iv):] 249 plainData, err := s.decryptAPDU(rdata) 250 if err != nil { 251 return nil, err 252 } 253 254 if err = s.updateIV(rmeta[:], rdata); err != nil { 255 return nil, err 256 } 257 if !bytes.Equal(s.iv, rmac) { 258 return nil, errors.New("invalid MAC in response") 259 } 260 261 rapdu := &responseAPDU{} 262 rapdu.deserialize(plainData) 263 264 if rapdu.Sw1 != sw1Ok { 265 return nil, fmt.Errorf("unexpected response status Cla=%#x, Ins=%#x, Sw=%#x%x", cla, ins, rapdu.Sw1, rapdu.Sw2) 266 } 267 268 return rapdu, nil 269 } 270 271 // encryptAPDU is an internal method that serializes and encrypts an APDU. 272 func (s *SecureChannelSession) encryptAPDU(data []byte) ([]byte, error) { 273 if len(data) > maxPayloadSize { 274 return nil, fmt.Errorf("payload of %d bytes exceeds maximum of %d", len(data), maxPayloadSize) 275 } 276 data = pad(data, 0x80) 277 278 ret := make([]byte, len(data)) 279 280 a, err := aes.NewCipher(s.sessionEncKey) 281 if err != nil { 282 return nil, err 283 } 284 crypter := cipher.NewCBCEncrypter(a, s.iv) 285 crypter.CryptBlocks(ret, data) 286 return ret, nil 287 } 288 289 // pad applies message padding to a 16 byte boundary. 290 func pad(data []byte, terminator byte) []byte { 291 padded := make([]byte, (len(data)/16+1)*16) 292 copy(padded, data) 293 padded[len(data)] = terminator 294 return padded 295 } 296 297 // decryptAPDU is an internal method that decrypts and deserializes an APDU. 298 func (s *SecureChannelSession) decryptAPDU(data []byte) ([]byte, error) { 299 a, err := aes.NewCipher(s.sessionEncKey) 300 if err != nil { 301 return nil, err 302 } 303 304 ret := make([]byte, len(data)) 305 306 crypter := cipher.NewCBCDecrypter(a, s.iv) 307 crypter.CryptBlocks(ret, data) 308 return unpad(ret, 0x80) 309 } 310 311 // unpad strips padding from a message. 312 func unpad(data []byte, terminator byte) ([]byte, error) { 313 for i := 1; i <= 16; i++ { 314 switch data[len(data)-i] { 315 case 0: 316 continue 317 case terminator: 318 return data[:len(data)-i], nil 319 default: 320 return nil, fmt.Errorf("expected end of padding, got %d", data[len(data)-i]) 321 } 322 } 323 return nil, errors.New("expected end of padding, got 0") 324 } 325 326 // updateIV is an internal method that updates the initialization vector after 327 // each message exchanged. 328 func (s *SecureChannelSession) updateIV(meta, data []byte) error { 329 data = pad(data, 0) 330 a, err := aes.NewCipher(s.sessionMacKey) 331 if err != nil { 332 return err 333 } 334 crypter := cipher.NewCBCEncrypter(a, make([]byte, 16)) 335 crypter.CryptBlocks(meta, meta) 336 crypter.CryptBlocks(data, data) 337 // The first 16 bytes of the last block is the MAC 338 s.iv = data[len(data)-32 : len(data)-16] 339 return nil 340 }