securechannel.go 9.2 KB

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