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.

355 lines
9.7 KiB

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