OSDN Git Service

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