You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

352 lines
9.4 KiB

  1. // Uses nacl's secret_box to encrypt a net.Conn.
  2. // It is (meant to be) an implementation of the STS protocol.
  3. // Note we do not (yet) assume that a remote peer's pubkey
  4. // is known ahead of time, and thus we are technically
  5. // still vulnerable to MITM. (TODO!)
  6. // See docs/sts-final.pdf for more info
  7. package conn
  8. import (
  9. "bytes"
  10. crand "crypto/rand"
  11. "crypto/sha256"
  12. "encoding/binary"
  13. "errors"
  14. "io"
  15. "net"
  16. "time"
  17. "golang.org/x/crypto/nacl/box"
  18. "golang.org/x/crypto/nacl/secretbox"
  19. "golang.org/x/crypto/ripemd160"
  20. "github.com/tendermint/tendermint/crypto"
  21. cmn "github.com/tendermint/tendermint/libs/common"
  22. )
  23. // 4 + 1024 == 1028 total frame size
  24. const dataLenSize = 4
  25. const dataMaxSize = 1024
  26. const totalFrameSize = dataMaxSize + dataLenSize
  27. const sealedFrameSize = totalFrameSize + secretbox.Overhead
  28. // Implements net.Conn
  29. type SecretConnection struct {
  30. conn io.ReadWriteCloser
  31. recvBuffer []byte
  32. recvNonce *[24]byte
  33. sendNonce *[24]byte
  34. remPubKey crypto.PubKey
  35. shrSecret *[32]byte // shared secret
  36. }
  37. // Performs handshake and returns a new authenticated SecretConnection.
  38. // Returns nil if error in handshake.
  39. // Caller should call conn.Close()
  40. // See docs/sts-final.pdf for more information.
  41. func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey crypto.PrivKey) (*SecretConnection, error) {
  42. locPubKey := locPrivKey.PubKey()
  43. // Generate ephemeral keys for perfect forward secrecy.
  44. locEphPub, locEphPriv := genEphKeys()
  45. // Write local ephemeral pubkey and receive one too.
  46. // NOTE: every 32-byte string is accepted as a Curve25519 public key
  47. // (see DJB's Curve25519 paper: http://cr.yp.to/ecdh/curve25519-20060209.pdf)
  48. remEphPub, err := shareEphPubKey(conn, locEphPub)
  49. if err != nil {
  50. return nil, err
  51. }
  52. // Compute common shared secret.
  53. shrSecret := computeSharedSecret(remEphPub, locEphPriv)
  54. // Sort by lexical order.
  55. loEphPub, hiEphPub := sort32(locEphPub, remEphPub)
  56. // Check if the local ephemeral public key
  57. // was the least, lexicographically sorted.
  58. locIsLeast := bytes.Equal(locEphPub[:], loEphPub[:])
  59. // Generate nonces to use for secretbox.
  60. recvNonce, sendNonce := genNonces(loEphPub, hiEphPub, locIsLeast)
  61. // Generate common challenge to sign.
  62. challenge := genChallenge(loEphPub, hiEphPub)
  63. // Construct SecretConnection.
  64. sc := &SecretConnection{
  65. conn: conn,
  66. recvBuffer: nil,
  67. recvNonce: recvNonce,
  68. sendNonce: sendNonce,
  69. shrSecret: shrSecret,
  70. }
  71. // Sign the challenge bytes for authentication.
  72. locSignature := signChallenge(challenge, locPrivKey)
  73. // Share (in secret) each other's pubkey & challenge signature
  74. authSigMsg, err := shareAuthSignature(sc, locPubKey, locSignature)
  75. if err != nil {
  76. return nil, err
  77. }
  78. remPubKey, remSignature := authSigMsg.Key, authSigMsg.Sig
  79. if !remPubKey.VerifyBytes(challenge[:], remSignature) {
  80. return nil, errors.New("Challenge verification failed")
  81. }
  82. // We've authorized.
  83. sc.remPubKey = remPubKey
  84. return sc, nil
  85. }
  86. // Returns authenticated remote pubkey
  87. func (sc *SecretConnection) RemotePubKey() crypto.PubKey {
  88. return sc.remPubKey
  89. }
  90. // Writes encrypted frames of `sealedFrameSize`
  91. // CONTRACT: data smaller than dataMaxSize is read atomically.
  92. func (sc *SecretConnection) Write(data []byte) (n int, err error) {
  93. for 0 < len(data) {
  94. var frame = make([]byte, totalFrameSize)
  95. var chunk []byte
  96. if dataMaxSize < len(data) {
  97. chunk = data[:dataMaxSize]
  98. data = data[dataMaxSize:]
  99. } else {
  100. chunk = data
  101. data = nil
  102. }
  103. chunkLength := len(chunk)
  104. binary.BigEndian.PutUint32(frame, uint32(chunkLength))
  105. copy(frame[dataLenSize:], chunk)
  106. // encrypt the frame
  107. var sealedFrame = make([]byte, sealedFrameSize)
  108. secretbox.Seal(sealedFrame[:0], frame, sc.sendNonce, sc.shrSecret)
  109. // fmt.Printf("secretbox.Seal(sealed:%X,sendNonce:%X,shrSecret:%X\n", sealedFrame, sc.sendNonce, sc.shrSecret)
  110. incr2Nonce(sc.sendNonce)
  111. // end encryption
  112. _, err := sc.conn.Write(sealedFrame)
  113. if err != nil {
  114. return n, err
  115. }
  116. n += len(chunk)
  117. }
  118. return
  119. }
  120. // CONTRACT: data smaller than dataMaxSize is read atomically.
  121. func (sc *SecretConnection) Read(data []byte) (n int, err error) {
  122. if 0 < len(sc.recvBuffer) {
  123. n = copy(data, sc.recvBuffer)
  124. sc.recvBuffer = sc.recvBuffer[n:]
  125. return
  126. }
  127. sealedFrame := make([]byte, sealedFrameSize)
  128. _, err = io.ReadFull(sc.conn, sealedFrame)
  129. if err != nil {
  130. return
  131. }
  132. // decrypt the frame
  133. var frame = make([]byte, totalFrameSize)
  134. // fmt.Printf("secretbox.Open(sealed:%X,recvNonce:%X,shrSecret:%X\n", sealedFrame, sc.recvNonce, sc.shrSecret)
  135. _, ok := secretbox.Open(frame[:0], sealedFrame, sc.recvNonce, sc.shrSecret)
  136. if !ok {
  137. return n, errors.New("Failed to decrypt SecretConnection")
  138. }
  139. incr2Nonce(sc.recvNonce)
  140. // end decryption
  141. var chunkLength = binary.BigEndian.Uint32(frame) // read the first two bytes
  142. if chunkLength > dataMaxSize {
  143. return 0, errors.New("chunkLength is greater than dataMaxSize")
  144. }
  145. var chunk = frame[dataLenSize : dataLenSize+chunkLength]
  146. n = copy(data, chunk)
  147. sc.recvBuffer = chunk[n:]
  148. return
  149. }
  150. // Implements net.Conn
  151. func (sc *SecretConnection) Close() error { return sc.conn.Close() }
  152. func (sc *SecretConnection) LocalAddr() net.Addr { return sc.conn.(net.Conn).LocalAddr() }
  153. func (sc *SecretConnection) RemoteAddr() net.Addr { return sc.conn.(net.Conn).RemoteAddr() }
  154. func (sc *SecretConnection) SetDeadline(t time.Time) error { return sc.conn.(net.Conn).SetDeadline(t) }
  155. func (sc *SecretConnection) SetReadDeadline(t time.Time) error {
  156. return sc.conn.(net.Conn).SetReadDeadline(t)
  157. }
  158. func (sc *SecretConnection) SetWriteDeadline(t time.Time) error {
  159. return sc.conn.(net.Conn).SetWriteDeadline(t)
  160. }
  161. func genEphKeys() (ephPub, ephPriv *[32]byte) {
  162. var err error
  163. ephPub, ephPriv, err = box.GenerateKey(crand.Reader)
  164. if err != nil {
  165. panic("Could not generate ephemeral keypairs")
  166. }
  167. return
  168. }
  169. func shareEphPubKey(conn io.ReadWriteCloser, locEphPub *[32]byte) (remEphPub *[32]byte, err error) {
  170. // Send our pubkey and receive theirs in tandem.
  171. var trs, _ = cmn.Parallel(
  172. func(_ int) (val interface{}, err error, abort bool) {
  173. var _, err1 = cdc.MarshalBinaryWriter(conn, locEphPub)
  174. if err1 != nil {
  175. return nil, err1, true // abort
  176. } else {
  177. return nil, nil, false
  178. }
  179. },
  180. func(_ int) (val interface{}, err error, abort bool) {
  181. var _remEphPub [32]byte
  182. var _, err2 = cdc.UnmarshalBinaryReader(conn, &_remEphPub, 1024*1024) // TODO
  183. if err2 != nil {
  184. return nil, err2, true // abort
  185. } else {
  186. return _remEphPub, nil, false
  187. }
  188. },
  189. )
  190. // If error:
  191. if trs.FirstError() != nil {
  192. err = trs.FirstError()
  193. return
  194. }
  195. // Otherwise:
  196. var _remEphPub = trs.FirstValue().([32]byte)
  197. return &_remEphPub, nil
  198. }
  199. func computeSharedSecret(remPubKey, locPrivKey *[32]byte) (shrSecret *[32]byte) {
  200. shrSecret = new([32]byte)
  201. box.Precompute(shrSecret, remPubKey, locPrivKey)
  202. return
  203. }
  204. func sort32(foo, bar *[32]byte) (lo, hi *[32]byte) {
  205. if bytes.Compare(foo[:], bar[:]) < 0 {
  206. lo = foo
  207. hi = bar
  208. } else {
  209. lo = bar
  210. hi = foo
  211. }
  212. return
  213. }
  214. func genNonces(loPubKey, hiPubKey *[32]byte, locIsLo bool) (recvNonce, sendNonce *[24]byte) {
  215. nonce1 := hash24(append(loPubKey[:], hiPubKey[:]...))
  216. nonce2 := new([24]byte)
  217. copy(nonce2[:], nonce1[:])
  218. nonce2[len(nonce2)-1] ^= 0x01
  219. if locIsLo {
  220. recvNonce = nonce1
  221. sendNonce = nonce2
  222. } else {
  223. recvNonce = nonce2
  224. sendNonce = nonce1
  225. }
  226. return
  227. }
  228. func genChallenge(loPubKey, hiPubKey *[32]byte) (challenge *[32]byte) {
  229. return hash32(append(loPubKey[:], hiPubKey[:]...))
  230. }
  231. func signChallenge(challenge *[32]byte, locPrivKey crypto.PrivKey) (signature crypto.Signature) {
  232. signature, err := locPrivKey.Sign(challenge[:])
  233. // TODO(ismail): let signChallenge return an error instead
  234. if err != nil {
  235. panic(err)
  236. }
  237. return
  238. }
  239. type authSigMessage struct {
  240. Key crypto.PubKey
  241. Sig crypto.Signature
  242. }
  243. func shareAuthSignature(sc *SecretConnection, pubKey crypto.PubKey, signature crypto.Signature) (recvMsg authSigMessage, err error) {
  244. // Send our info and receive theirs in tandem.
  245. var trs, _ = cmn.Parallel(
  246. func(_ int) (val interface{}, err error, abort bool) {
  247. var _, err1 = cdc.MarshalBinaryWriter(sc, authSigMessage{pubKey, signature})
  248. if err1 != nil {
  249. return nil, err1, true // abort
  250. } else {
  251. return nil, nil, false
  252. }
  253. },
  254. func(_ int) (val interface{}, err error, abort bool) {
  255. var _recvMsg authSigMessage
  256. var _, err2 = cdc.UnmarshalBinaryReader(sc, &_recvMsg, 1024*1024) // TODO
  257. if err2 != nil {
  258. return nil, err2, true // abort
  259. } else {
  260. return _recvMsg, nil, false
  261. }
  262. },
  263. )
  264. // If error:
  265. if trs.FirstError() != nil {
  266. err = trs.FirstError()
  267. return
  268. }
  269. var _recvMsg = trs.FirstValue().(authSigMessage)
  270. return _recvMsg, nil
  271. }
  272. //--------------------------------------------------------------------------------
  273. // sha256
  274. func hash32(input []byte) (res *[32]byte) {
  275. hasher := sha256.New()
  276. hasher.Write(input) // nolint: errcheck, gas
  277. resSlice := hasher.Sum(nil)
  278. res = new([32]byte)
  279. copy(res[:], resSlice)
  280. return
  281. }
  282. // We only fill in the first 20 bytes with ripemd160
  283. func hash24(input []byte) (res *[24]byte) {
  284. hasher := ripemd160.New()
  285. hasher.Write(input) // nolint: errcheck, gas
  286. resSlice := hasher.Sum(nil)
  287. res = new([24]byte)
  288. copy(res[:], resSlice)
  289. return
  290. }
  291. // increment nonce big-endian by 2 with wraparound.
  292. func incr2Nonce(nonce *[24]byte) {
  293. incrNonce(nonce)
  294. incrNonce(nonce)
  295. }
  296. // increment nonce big-endian by 1 with wraparound.
  297. func incrNonce(nonce *[24]byte) {
  298. for i := 23; 0 <= i; i-- {
  299. nonce[i]++
  300. if nonce[i] != 0 {
  301. return
  302. }
  303. }
  304. }