2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2016 Sergey Matveev <stargrave@stargrave.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
29 "golang.org/x/crypto/poly1305"
30 "golang.org/x/crypto/salsa20"
31 "golang.org/x/crypto/xtea"
37 TagSize = poly1305.TagSize
38 // S20BS is Salsa20's internal blocksize in bytes
40 // Maximal amount of bytes transfered with single key (4 GiB)
41 MaxBytesPerKey int64 = 1 << 32
42 // Heartbeat rate, relative to Timeout
44 // Minimal valid packet length
45 MinPktLength = 1 + 16 + 8
50 func newNonceCipher(key *[32]byte) *xtea.Cipher {
51 nonceKey := make([]byte, 16)
55 make([]byte, xtea.BlockSize),
58 ciph, err := xtea.NewCipher(nonceKey)
73 CPRCycle time.Duration `json:"-"`
76 // Cryptography related
77 Key *[SSize]byte `json:"-"`
78 NonceCipher *xtea.Cipher `json:"-"`
82 NonceExpect uint64 `json:"-"`
83 nonceBucket0 map[uint64]struct{}
84 nonceBucket1 map[uint64]struct{}
90 Timeout time.Duration `json:"-"`
94 willSentCycle time.Time
100 BytesPayloadOut int64
109 BusyR sync.Mutex `json:"-"`
112 keyAuthR *[SSize]byte
116 BusyT sync.Mutex `json:"-"`
119 keyAuthT *[SSize]byte
124 func (p *Peer) String() string {
125 return p.Id.String() + ":" + p.Addr
128 // Zero peer's memory state.
129 func (p *Peer) Zero() {
135 SliceZero(p.keyAuthR[:])
136 SliceZero(p.keyAuthT[:])
141 func (p *Peer) NonceExpectation(buf []byte) {
142 binary.BigEndian.PutUint64(buf, p.NonceExpect)
143 p.NonceCipher.Encrypt(buf, buf)
146 func newPeer(isClient bool, addr string, conn io.Writer, conf *PeerConf, key *[SSize]byte) *Peer {
148 timeout := conf.Timeout
150 cprCycle := cprCycleCalculate(conf.CPR)
151 noiseEnable := conf.Noise
156 timeout = timeout / TimeoutHeartbeat
159 bufSize := S20BS + MTU + NonceSize
161 bufSize += EncLessEnlargeSize
169 NoiseEnable: noiseEnable,
172 EncLess: conf.EncLess,
175 NonceCipher: newNonceCipher(key),
176 nonceBucket0: make(map[uint64]struct{}, NonceBucketSize),
177 nonceBucket1: make(map[uint64]struct{}, NonceBucketSize),
183 bufR: make([]byte, bufSize),
184 bufT: make([]byte, bufSize),
185 tagR: new([TagSize]byte),
186 tagT: new([TagSize]byte),
187 keyAuthR: new([SSize]byte),
188 keyAuthT: new([SSize]byte),
192 peer.NonceExpect = 0 + 2
195 peer.NonceExpect = 1 + 2
201 // Process incoming Ethernet packet.
202 // ready channel is TAPListen's synchronization channel used to tell him
203 // that he is free to receive new packets. Encrypted and authenticated
204 // packets will be sent to remote Peer side immediately.
205 func (p *Peer) EthProcess(data []byte) {
209 // Zero size is a heartbeat packet
212 // If this heartbeat is necessary
213 if !p.LastSent.Add(p.Timeout).Before(p.now) {
217 p.bufT[S20BS+0] = PadByte
220 // Copy payload to our internal buffer and we are ready to
221 // accept the next one
222 copy(p.bufT[S20BS:], data)
223 p.bufT[S20BS+len(data)] = PadByte
224 p.BytesPayloadOut += int64(len(data))
227 if p.NoiseEnable && !p.EncLess {
228 p.frameT = p.bufT[S20BS : S20BS+MTU-TagSize]
229 } else if p.EncLess {
230 p.frameT = p.bufT[S20BS : S20BS+MTU]
232 p.frameT = p.bufT[S20BS : S20BS+len(data)+1+NonceSize]
235 binary.BigEndian.PutUint64(p.frameT[len(p.frameT)-NonceSize:], p.nonceOur)
236 p.NonceCipher.Encrypt(
237 p.frameT[len(p.frameT)-NonceSize:],
238 p.frameT[len(p.frameT)-NonceSize:],
243 out, err = EncLessEncode(
245 p.frameT[len(p.frameT)-NonceSize:],
246 p.frameT[:len(p.frameT)-NonceSize],
251 out = append(out, p.frameT[len(p.frameT)-NonceSize:]...)
253 salsa20.XORKeyStream(
254 p.bufT[:S20BS+len(p.frameT)-NonceSize],
255 p.bufT[:S20BS+len(p.frameT)-NonceSize],
256 p.frameT[len(p.frameT)-NonceSize:],
259 copy(p.keyAuthT[:], p.bufT[:SSize])
260 poly1305.Sum(p.tagT, p.frameT, p.keyAuthT)
261 atomic.AddInt64(&p.BytesOut, int64(len(p.frameT)+TagSize))
262 out = append(p.tagT[:], p.frameT...)
266 if p.CPRCycle != time.Duration(0) {
267 p.willSentCycle = p.LastSent.Add(p.CPRCycle)
268 if p.willSentCycle.After(p.now) {
269 time.Sleep(p.willSentCycle.Sub(p.now))
270 p.now = p.willSentCycle
279 func (p *Peer) PktProcess(data []byte, tap io.Writer, reorderable bool) bool {
280 if len(data) < MinPktLength {
287 out, err = EncLessDecode(
289 data[len(data)-NonceSize:],
290 data[:len(data)-NonceSize],
298 for i := 0; i < SSize; i++ {
301 copy(p.bufR[S20BS:], data[TagSize:])
302 salsa20.XORKeyStream(
303 p.bufR[:S20BS+len(data)-TagSize-NonceSize],
304 p.bufR[:S20BS+len(data)-TagSize-NonceSize],
305 data[len(data)-NonceSize:],
308 copy(p.keyAuthR[:], p.bufR[:SSize])
309 copy(p.tagR[:], data[:TagSize])
310 if !poly1305.Verify(p.tagR, data[TagSize:], p.keyAuthR) {
315 out = p.bufR[S20BS : S20BS+len(data)-TagSize-NonceSize]
318 // Check if received nonce is known to us in either of two buckets.
319 // If yes, then this is ignored duplicate.
320 // Check from the oldest bucket, as in most cases this will result
321 // in constant time check.
322 // If Bucket0 is filled, then it becomes Bucket1.
323 p.NonceCipher.Decrypt(
324 data[len(data)-NonceSize:],
325 data[len(data)-NonceSize:],
327 p.nonceRecv = binary.BigEndian.Uint64(data[len(data)-NonceSize:])
329 _, p.nonceFound0 = p.nonceBucket0[p.nonceRecv]
330 _, p.nonceFound1 = p.nonceBucket1[p.nonceRecv]
331 if p.nonceFound0 || p.nonceFound1 || p.nonceRecv+2*NonceBucketSize < p.nonceLatest {
336 p.nonceBucket0[p.nonceRecv] = struct{}{}
338 if p.nonceBucketN == NonceBucketSize {
339 p.nonceBucket1 = p.nonceBucket0
340 p.nonceBucket0 = make(map[uint64]struct{}, NonceBucketSize)
344 if p.nonceRecv != p.NonceExpect {
351 if p.nonceRecv > p.nonceLatest {
352 p.nonceLatest = p.nonceRecv
356 atomic.AddInt64(&p.BytesIn, int64(len(data)))
357 p.LastPing = time.Now()
358 p.pktSizeR = bytes.LastIndexByte(out, PadByte)
359 if p.pktSizeR == -1 {
364 for i := p.pktSizeR + 1; i < len(out); i++ {
376 p.BytesPayloadIn += int64(p.pktSizeR)
377 tap.Write(out[:p.pktSizeR])