securechannel.go 9.2 KB

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