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/>.
28 "golang.org/x/crypto/poly1305"
29 "golang.org/x/crypto/salsa20"
30 "golang.org/x/crypto/xtea"
36 TagSize = poly1305.TagSize
37 // S20BS is Salsa20's internal blocksize in bytes
39 // Maximal amount of bytes transfered with single key (4 GiB)
40 MaxBytesPerKey int64 = 1 << 32
41 // Size of packet's size mark in bytes
43 // Heartbeat rate, relative to Timeout
45 // Minimal valid packet length
46 MinPktLength = 2 + 16 + 8
49 func newNonceCipher(key *[32]byte) *xtea.Cipher {
50 nonceKey := make([]byte, 16)
54 make([]byte, xtea.BlockSize),
57 ciph, err := xtea.NewCipher(nonceKey)
72 CPRCycle time.Duration `json:"-"`
75 // Cryptography related
76 Key *[SSize]byte `json:"-"`
77 NonceCipher *xtea.Cipher `json:"-"`
81 NonceExpect uint64 `json:"-"`
82 nonceBucket0 map[uint64]struct{}
83 nonceBucket1 map[uint64]struct{}
89 Timeout time.Duration `json:"-"`
93 willSentCycle time.Time
108 BusyR sync.Mutex `json:"-"`
111 keyAuthR *[SSize]byte
115 BusyT sync.Mutex `json:"-"`
118 keyAuthT *[SSize]byte
123 func (p *Peer) String() string {
124 return p.Id.String() + ":" + p.Addr
127 // Zero peer's memory state.
128 func (p *Peer) Zero() {
134 SliceZero(p.keyAuthR[:])
135 SliceZero(p.keyAuthT[:])
140 func (p *Peer) NonceExpectation(buf []byte) {
141 binary.BigEndian.PutUint64(buf, p.NonceExpect)
142 p.NonceCipher.Encrypt(buf, buf)
145 func newPeer(isClient bool, addr string, conn io.Writer, conf *PeerConf, key *[SSize]byte) *Peer {
147 timeout := conf.Timeout
149 cprCycle := cprCycleCalculate(conf.CPR)
150 noiseEnable := conf.Noise
155 timeout = timeout / TimeoutHeartbeat
158 bufSize := S20BS + MTU + NonceSize
160 bufSize += EncLessEnlargeSize
168 NoiseEnable: noiseEnable,
171 EncLess: conf.EncLess,
174 NonceCipher: newNonceCipher(key),
175 nonceBucket0: make(map[uint64]struct{}, NonceBucketSize),
176 nonceBucket1: make(map[uint64]struct{}, NonceBucketSize),
182 bufR: make([]byte, bufSize),
183 bufT: make([]byte, bufSize),
184 tagR: new([TagSize]byte),
185 tagT: new([TagSize]byte),
186 keyAuthR: new([SSize]byte),
187 keyAuthT: new([SSize]byte),
191 peer.NonceExpect = 0 + 2
194 peer.NonceExpect = 1 + 2
200 // Process incoming Ethernet packet.
201 // ready channel is TAPListen's synchronization channel used to tell him
202 // that he is free to receive new packets. Encrypted and authenticated
203 // packets will be sent to remote Peer side immediately.
204 func (p *Peer) EthProcess(data []byte) {
208 // Zero size is a heartbeat packet
210 // If this heartbeat is necessary
211 if !p.LastSent.Add(p.Timeout).Before(p.now) {
219 // Copy payload to our internal buffer and we are ready to
220 // accept the next one
221 binary.BigEndian.PutUint16(
222 p.bufT[S20BS:S20BS+PktSizeSize],
225 copy(p.bufT[S20BS+PktSizeSize:], data)
226 p.BytesPayloadOut += int64(len(data))
229 if p.NoiseEnable && !p.EncLess {
230 p.frameT = p.bufT[S20BS : S20BS+MTU-TagSize]
231 } else if p.EncLess {
232 p.frameT = p.bufT[S20BS : S20BS+MTU]
234 p.frameT = p.bufT[S20BS : S20BS+PktSizeSize+len(data)+NonceSize]
237 binary.BigEndian.PutUint64(p.frameT[len(p.frameT)-NonceSize:], p.nonceOur)
238 p.NonceCipher.Encrypt(
239 p.frameT[len(p.frameT)-NonceSize:],
240 p.frameT[len(p.frameT)-NonceSize:],
245 out, err = EncLessEncode(
247 p.frameT[len(p.frameT)-NonceSize:],
248 p.frameT[:len(p.frameT)-NonceSize],
253 out = append(out, p.frameT[len(p.frameT)-NonceSize:]...)
255 for i := 0; i < SSize; i++ {
258 salsa20.XORKeyStream(
259 p.bufT[:S20BS+len(p.frameT)-NonceSize],
260 p.bufT[:S20BS+len(p.frameT)-NonceSize],
261 p.frameT[len(p.frameT)-NonceSize:],
264 copy(p.keyAuthT[:], p.bufT[:SSize])
265 poly1305.Sum(p.tagT, p.frameT, p.keyAuthT)
266 atomic.AddInt64(&p.BytesOut, int64(len(p.frameT)+TagSize))
267 out = append(p.tagT[:], p.frameT...)
271 if p.CPRCycle != time.Duration(0) {
272 p.willSentCycle = p.LastSent.Add(p.CPRCycle)
273 if p.willSentCycle.After(p.now) {
274 time.Sleep(p.willSentCycle.Sub(p.now))
275 p.now = p.willSentCycle
284 func (p *Peer) PktProcess(data []byte, tap io.Writer, reorderable bool) bool {
285 if len(data) < MinPktLength {
292 out, err = EncLessDecode(
294 data[len(data)-NonceSize:],
295 data[:len(data)-NonceSize],
303 for i := 0; i < SSize; i++ {
306 copy(p.bufR[S20BS:], data[TagSize:])
307 salsa20.XORKeyStream(
308 p.bufR[:S20BS+len(data)-TagSize-NonceSize],
309 p.bufR[:S20BS+len(data)-TagSize-NonceSize],
310 data[len(data)-NonceSize:],
313 copy(p.keyAuthR[:], p.bufR[:SSize])
314 copy(p.tagR[:], data[:TagSize])
315 if !poly1305.Verify(p.tagR, data[TagSize:], p.keyAuthR) {
323 // Check if received nonce is known to us in either of two buckets.
324 // If yes, then this is ignored duplicate.
325 // Check from the oldest bucket, as in most cases this will result
326 // in constant time check.
327 // If Bucket0 is filled, then it becomes Bucket1.
328 p.NonceCipher.Decrypt(
329 data[len(data)-NonceSize:],
330 data[len(data)-NonceSize:],
332 p.nonceRecv = binary.BigEndian.Uint64(data[len(data)-NonceSize:])
334 _, p.nonceFound0 = p.nonceBucket0[p.nonceRecv]
335 _, p.nonceFound1 = p.nonceBucket1[p.nonceRecv]
336 if p.nonceFound0 || p.nonceFound1 || p.nonceRecv+2*NonceBucketSize < p.nonceLatest {
341 p.nonceBucket0[p.nonceRecv] = struct{}{}
343 if p.nonceBucketN == NonceBucketSize {
344 p.nonceBucket1 = p.nonceBucket0
345 p.nonceBucket0 = make(map[uint64]struct{}, NonceBucketSize)
349 if p.nonceRecv != p.NonceExpect {
356 if p.nonceRecv > p.nonceLatest {
357 p.nonceLatest = p.nonceRecv
361 atomic.AddInt64(&p.BytesIn, int64(len(data)))
362 p.LastPing = time.Now()
363 p.pktSizeR = binary.BigEndian.Uint16(out[:PktSizeSize])
370 if int(p.pktSizeR) > len(data)-MinPktLength {
373 p.BytesPayloadIn += int64(p.pktSizeR)
374 tap.Write(out[PktSizeSize : PktSizeSize+p.pktSizeR])