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/>.
30 "golang.org/x/crypto/poly1305"
31 "golang.org/x/crypto/salsa20"
32 "golang.org/x/crypto/xtea"
38 TagSize = poly1305.TagSize
39 // S20BS is Salsa20's internal blocksize in bytes
41 // Maximal amount of bytes transfered with single key (4 GiB)
42 MaxBytesPerKey int64 = 1 << 32
43 // Heartbeat rate, relative to Timeout
45 // Minimal valid packet length
46 MinPktLength = 1 + 16 + 8
51 func newNonceCipher(key *[32]byte) *xtea.Cipher {
52 nonceKey := make([]byte, 16)
56 make([]byte, xtea.BlockSize),
59 ciph, err := xtea.NewCipher(nonceKey)
74 CPRCycle time.Duration `json:"-"`
78 // Cryptography related
79 Key *[SSize]byte `json:"-"`
80 NonceCipher *xtea.Cipher `json:"-"`
84 NonceExpect uint64 `json:"-"`
85 nonceBucket0 map[uint64]struct{}
86 nonceBucket1 map[uint64]struct{}
92 Timeout time.Duration `json:"-"`
96 willSentCycle time.Time
102 BytesPayloadOut int64
111 BusyR sync.Mutex `json:"-"`
114 keyAuthR *[SSize]byte
118 BusyT sync.Mutex `json:"-"`
121 keyAuthT *[SSize]byte
126 func (p *Peer) String() string {
127 return p.Id.String() + ":" + p.Addr
130 // Zero peer's memory state.
131 func (p *Peer) Zero() {
137 SliceZero(p.keyAuthR[:])
138 SliceZero(p.keyAuthT[:])
143 func (p *Peer) NonceExpectation(buf []byte) {
144 binary.BigEndian.PutUint64(buf, p.NonceExpect)
145 p.NonceCipher.Encrypt(buf, buf)
148 func cprCycleCalculate(rate int) time.Duration {
150 return time.Duration(0)
152 return time.Second / time.Duration(rate*(1<<10)/MTUMax)
155 func newPeer(isClient bool, addr string, conn io.Writer, conf *PeerConf, key *[SSize]byte) *Peer {
157 timeout := conf.Timeout
159 cprCycle := cprCycleCalculate(conf.CPR)
160 noiseEnable := conf.Noise
165 timeout = timeout / TimeoutHeartbeat
168 bufSize := S20BS + 2*conf.MTU
170 bufSize += EncLessEnlargeSize
178 NoiseEnable: noiseEnable,
181 EncLess: conf.EncLess,
185 NonceCipher: newNonceCipher(key),
186 nonceBucket0: make(map[uint64]struct{}, NonceBucketSize),
187 nonceBucket1: make(map[uint64]struct{}, NonceBucketSize),
193 bufR: make([]byte, bufSize),
194 bufT: make([]byte, bufSize),
195 tagR: new([TagSize]byte),
196 tagT: new([TagSize]byte),
197 keyAuthR: new([SSize]byte),
198 keyAuthT: new([SSize]byte),
202 peer.NonceExpect = 0 + 2
205 peer.NonceExpect = 1 + 2
211 // Process incoming Ethernet packet.
212 // ready channel is TAPListen's synchronization channel used to tell him
213 // that he is free to receive new packets. Encrypted and authenticated
214 // packets will be sent to remote Peer side immediately.
215 func (p *Peer) EthProcess(data []byte) {
216 if len(data) > p.MTU-1 { // 1 is for padding byte
217 log.Println("Padded data packet size", len(data)+1, "is bigger than MTU", p.MTU, p)
223 // Zero size is a heartbeat packet
226 // If this heartbeat is necessary
227 if !p.LastSent.Add(p.Timeout).Before(p.now) {
231 p.bufT[S20BS+0] = PadByte
234 // Copy payload to our internal buffer and we are ready to
235 // accept the next one
236 copy(p.bufT[S20BS:], data)
237 p.bufT[S20BS+len(data)] = PadByte
238 p.BytesPayloadOut += int64(len(data))
241 if p.NoiseEnable && !p.EncLess {
242 p.frameT = p.bufT[S20BS : S20BS+p.MTU-TagSize]
243 } else if p.EncLess {
244 p.frameT = p.bufT[S20BS : S20BS+p.MTU]
246 p.frameT = p.bufT[S20BS : S20BS+len(data)+1+NonceSize]
249 binary.BigEndian.PutUint64(p.frameT[len(p.frameT)-NonceSize:], p.nonceOur)
250 p.NonceCipher.Encrypt(
251 p.frameT[len(p.frameT)-NonceSize:],
252 p.frameT[len(p.frameT)-NonceSize:],
257 out, err = EncLessEncode(
259 p.frameT[len(p.frameT)-NonceSize:],
260 p.frameT[:len(p.frameT)-NonceSize],
265 out = append(out, p.frameT[len(p.frameT)-NonceSize:]...)
267 salsa20.XORKeyStream(
268 p.bufT[:S20BS+len(p.frameT)-NonceSize],
269 p.bufT[:S20BS+len(p.frameT)-NonceSize],
270 p.frameT[len(p.frameT)-NonceSize:],
273 copy(p.keyAuthT[:], p.bufT[:SSize])
274 poly1305.Sum(p.tagT, p.frameT, p.keyAuthT)
275 atomic.AddInt64(&p.BytesOut, int64(len(p.frameT)+TagSize))
276 out = append(p.tagT[:], p.frameT...)
280 if p.CPRCycle != time.Duration(0) {
281 p.willSentCycle = p.LastSent.Add(p.CPRCycle)
282 if p.willSentCycle.After(p.now) {
283 time.Sleep(p.willSentCycle.Sub(p.now))
284 p.now = p.willSentCycle
293 func (p *Peer) PktProcess(data []byte, tap io.Writer, reorderable bool) bool {
294 if len(data) < MinPktLength {
301 out, err = EncLessDecode(
303 data[len(data)-NonceSize:],
304 data[:len(data)-NonceSize],
312 for i := 0; i < SSize; i++ {
315 copy(p.bufR[S20BS:], data[TagSize:])
316 salsa20.XORKeyStream(
317 p.bufR[:S20BS+len(data)-TagSize-NonceSize],
318 p.bufR[:S20BS+len(data)-TagSize-NonceSize],
319 data[len(data)-NonceSize:],
322 copy(p.keyAuthR[:], p.bufR[:SSize])
323 copy(p.tagR[:], data[:TagSize])
324 if !poly1305.Verify(p.tagR, data[TagSize:], p.keyAuthR) {
329 out = p.bufR[S20BS : S20BS+len(data)-TagSize-NonceSize]
332 // Check if received nonce is known to us in either of two buckets.
333 // If yes, then this is ignored duplicate.
334 // Check from the oldest bucket, as in most cases this will result
335 // in constant time check.
336 // If Bucket0 is filled, then it becomes Bucket1.
337 p.NonceCipher.Decrypt(
338 data[len(data)-NonceSize:],
339 data[len(data)-NonceSize:],
341 p.nonceRecv = binary.BigEndian.Uint64(data[len(data)-NonceSize:])
343 _, p.nonceFound0 = p.nonceBucket0[p.nonceRecv]
344 _, p.nonceFound1 = p.nonceBucket1[p.nonceRecv]
345 if p.nonceFound0 || p.nonceFound1 || p.nonceRecv+2*NonceBucketSize < p.nonceLatest {
350 p.nonceBucket0[p.nonceRecv] = struct{}{}
352 if p.nonceBucketN == NonceBucketSize {
353 p.nonceBucket1 = p.nonceBucket0
354 p.nonceBucket0 = make(map[uint64]struct{}, NonceBucketSize)
358 if p.nonceRecv != p.NonceExpect {
365 if p.nonceRecv > p.nonceLatest {
366 p.nonceLatest = p.nonceRecv
370 atomic.AddInt64(&p.BytesIn, int64(len(data)))
371 p.LastPing = time.Now()
372 p.pktSizeR = bytes.LastIndexByte(out, PadByte)
373 if p.pktSizeR == -1 {
378 for i := p.pktSizeR + 1; i < len(out); i++ {
390 p.BytesPayloadIn += int64(p.pktSizeR)
391 tap.Write(out[:p.pktSizeR])