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.

336 lines
9.0 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
  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 p2p
  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/go-crypto"
  21. "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.PubKeyEd25519
  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.PrivKeyEd25519) (*SecretConnection, error) {
  44. locPubKey := locPrivKey.PubKey().Unwrap().(crypto.PubKeyEd25519)
  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.Unwrap().(crypto.PubKeyEd25519)
  86. return sc, nil
  87. }
  88. // Returns authenticated remote pubkey
  89. func (sc *SecretConnection) RemotePubKey() crypto.PubKeyEd25519 {
  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. var err1, err2 error
  174. cmn.Parallel(
  175. func() {
  176. _, err1 = conn.Write(locEphPub[:])
  177. },
  178. func() {
  179. remEphPub = new([32]byte)
  180. _, err2 = io.ReadFull(conn, remEphPub[:])
  181. },
  182. )
  183. if err1 != nil {
  184. return nil, err1
  185. }
  186. if err2 != nil {
  187. return nil, err2
  188. }
  189. return remEphPub, nil
  190. }
  191. func computeSharedSecret(remPubKey, locPrivKey *[32]byte) (shrSecret *[32]byte) {
  192. shrSecret = new([32]byte)
  193. box.Precompute(shrSecret, remPubKey, locPrivKey)
  194. return
  195. }
  196. func sort32(foo, bar *[32]byte) (lo, hi *[32]byte) {
  197. if bytes.Compare(foo[:], bar[:]) < 0 {
  198. lo = foo
  199. hi = bar
  200. } else {
  201. lo = bar
  202. hi = foo
  203. }
  204. return
  205. }
  206. func genNonces(loPubKey, hiPubKey *[32]byte, locIsLo bool) (recvNonce, sendNonce *[24]byte) {
  207. nonce1 := hash24(append(loPubKey[:], hiPubKey[:]...))
  208. nonce2 := new([24]byte)
  209. copy(nonce2[:], nonce1[:])
  210. nonce2[len(nonce2)-1] ^= 0x01
  211. if locIsLo {
  212. recvNonce = nonce1
  213. sendNonce = nonce2
  214. } else {
  215. recvNonce = nonce2
  216. sendNonce = nonce1
  217. }
  218. return
  219. }
  220. func genChallenge(loPubKey, hiPubKey *[32]byte) (challenge *[32]byte) {
  221. return hash32(append(loPubKey[:], hiPubKey[:]...))
  222. }
  223. func signChallenge(challenge *[32]byte, locPrivKey crypto.PrivKeyEd25519) (signature crypto.SignatureEd25519) {
  224. signature = locPrivKey.Sign(challenge[:]).Unwrap().(crypto.SignatureEd25519)
  225. return
  226. }
  227. type authSigMessage struct {
  228. Key crypto.PubKey
  229. Sig crypto.Signature
  230. }
  231. func shareAuthSignature(sc *SecretConnection, pubKey crypto.PubKeyEd25519, signature crypto.SignatureEd25519) (*authSigMessage, error) {
  232. var recvMsg authSigMessage
  233. var err1, err2 error
  234. cmn.Parallel(
  235. func() {
  236. msgBytes := wire.BinaryBytes(authSigMessage{pubKey.Wrap(), signature.Wrap()})
  237. _, err1 = sc.Write(msgBytes)
  238. },
  239. func() {
  240. readBuffer := make([]byte, authSigMsgSize)
  241. _, err2 = io.ReadFull(sc, readBuffer)
  242. if err2 != nil {
  243. return
  244. }
  245. n := int(0) // not used.
  246. recvMsg = wire.ReadBinary(authSigMessage{}, bytes.NewBuffer(readBuffer), authSigMsgSize, &n, &err2).(authSigMessage)
  247. })
  248. if err1 != nil {
  249. return nil, err1
  250. }
  251. if err2 != nil {
  252. return nil, err2
  253. }
  254. return &recvMsg, nil
  255. }
  256. //--------------------------------------------------------------------------------
  257. // sha256
  258. func hash32(input []byte) (res *[32]byte) {
  259. hasher := sha256.New()
  260. hasher.Write(input) // does not error
  261. resSlice := hasher.Sum(nil)
  262. res = new([32]byte)
  263. copy(res[:], resSlice)
  264. return
  265. }
  266. // We only fill in the first 20 bytes with ripemd160
  267. func hash24(input []byte) (res *[24]byte) {
  268. hasher := ripemd160.New()
  269. hasher.Write(input) // does not error
  270. resSlice := hasher.Sum(nil)
  271. res = new([24]byte)
  272. copy(res[:], resSlice)
  273. return
  274. }
  275. // increment nonce big-endian by 2 with wraparound.
  276. func incr2Nonce(nonce *[24]byte) {
  277. incrNonce(nonce)
  278. incrNonce(nonce)
  279. }
  280. // increment nonce big-endian by 1 with wraparound.
  281. func incrNonce(nonce *[24]byte) {
  282. for i := 23; 0 <= i; i-- {
  283. nonce[i] += 1
  284. if nonce[i] != 0 {
  285. return
  286. }
  287. }
  288. }