securechannel.go 9.0 KB

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