2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2017 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/>.
32 "golang.org/x/crypto/blake2b"
33 "golang.org/x/crypto/poly1305"
39 TagSize = poly1305.TagSize
40 // S20BS is ChaCha20's internal blocksize in bytes
42 // Maximal amount of bytes transfered with single key (4 GiB)
43 MaxBytesPerKey uint64 = 1 << 32
44 // Heartbeat rate, relative to Timeout
46 // Minimal valid packet length
47 MinPktLength = 1 + 16 + 8
52 func newNonces(key *[32]byte, i uint64) chan *[NonceSize]byte {
53 macKey := make([]byte, 32)
54 chacha20.XORKeyStream(macKey, make([]byte, 32), new([16]byte), key)
55 mac, err := blake2b.New256(macKey)
59 sum := make([]byte, mac.Size())
60 nonces := make(chan *[NonceSize]byte, NonceBucketSize*3)
63 buf := new([NonceSize]byte)
64 binary.BigEndian.PutUint64(buf[:], i)
67 for index := 0; index < NonceSize; index++ {
68 buf[index] = sum[index]
79 // Statistics (they are at the beginning for correct int64 alignment)
83 BytesPayloadOut uint64
94 Conn io.Writer `json:"-"`
99 CPRCycle time.Duration `json:"-"`
103 key *[SSize]byte `json:"-"`
106 Timeout time.Duration `json:"-"`
107 Established time.Time
111 BusyR sync.Mutex `json:"-"`
114 keyAuthR *[SSize]byte
119 noncesR chan *[NonceSize]byte
120 nonceRecv [NonceSize]byte
121 nonceBucketL map[[NonceSize]byte]struct{}
122 nonceBucketM map[[NonceSize]byte]struct{}
123 nonceBucketH map[[NonceSize]byte]struct{}
126 NonceExpect []byte `json:"-"`
127 noncesExpect chan *[NonceSize]byte
130 BusyT sync.Mutex `json:"-"`
133 keyAuthT *[SSize]byte
136 noncesT chan *[NonceSize]byte
139 func (p *Peer) String() string {
140 return p.Id.String() + ":" + p.Addr
143 // Zero peer's memory state.
144 func (p *Peer) Zero() {
150 SliceZero(p.keyAuthR[:])
151 SliceZero(p.keyAuthT[:])
156 func cprCycleCalculate(conf *PeerConf) time.Duration {
158 return time.Duration(0)
160 rate := conf.CPR * 1 << 10
162 rate /= EnclessEnlargeSize + conf.MTU
166 return time.Second / time.Duration(rate)
169 func newPeer(isClient bool, addr string, conn io.Writer, conf *PeerConf, key *[SSize]byte) *Peer {
171 timeout := conf.Timeout
173 cprCycle := cprCycleCalculate(conf)
174 noiseEnable := conf.Noise
179 timeout = timeout / TimeoutHeartbeat
182 bufSize := S20BS + 2*conf.MTU
184 bufSize += EnclessEnlargeSize
193 NoiseEnable: noiseEnable,
196 Encless: conf.Encless,
205 bufR: make([]byte, bufSize),
206 bufT: make([]byte, bufSize),
207 tagR: new([TagSize]byte),
208 tagT: new([TagSize]byte),
209 keyAuthR: new([SSize]byte),
210 nonceR: new([16]byte),
211 keyAuthT: new([SSize]byte),
212 nonceT: new([16]byte),
216 peer.noncesT = newNonces(peer.key, 1+2)
217 peer.noncesR = newNonces(peer.key, 0+2)
218 peer.noncesExpect = newNonces(peer.key, 0+2)
220 peer.noncesT = newNonces(peer.key, 0+2)
221 peer.noncesR = newNonces(peer.key, 1+2)
222 peer.noncesExpect = newNonces(peer.key, 1+2)
225 peer.NonceExpect = make([]byte, NonceSize)
226 nonce := <-peer.noncesExpect
227 copy(peer.NonceExpect, nonce[:])
230 peer.nonceBucketL = make(map[[NonceSize]byte]struct{}, NonceBucketSize)
231 for i = 0; i < NonceBucketSize; i++ {
232 nonce = <-peer.noncesR
233 peer.nonceBucketL[*nonce] = struct{}{}
235 peer.nonceBucketM = make(map[[NonceSize]byte]struct{}, NonceBucketSize)
236 for i = 0; i < NonceBucketSize; i++ {
237 nonce = <-peer.noncesR
238 peer.nonceBucketM[*nonce] = struct{}{}
240 peer.nonceBucketH = make(map[[NonceSize]byte]struct{}, NonceBucketSize)
241 for i = 0; i < NonceBucketSize; i++ {
242 nonce = <-peer.noncesR
243 peer.nonceBucketH[*nonce] = struct{}{}
249 // Process incoming Ethernet packet.
250 // ready channel is TAPListen's synchronization channel used to tell him
251 // that he is free to receive new packets. Encrypted and authenticated
252 // packets will be sent to remote Peer side immediately.
253 func (p *Peer) EthProcess(data []byte) {
254 if len(data) > p.MTU-1 { // 1 is for padding byte
255 log.Println("Padded data packet size", len(data)+1, "is bigger than MTU", p.MTU, p)
260 // Zero size is a heartbeat packet
263 p.bufT[S20BS+0] = PadByte
266 // Copy payload to our internal buffer and we are ready to
267 // accept the next one
268 copy(p.bufT[S20BS:], data)
269 p.bufT[S20BS+len(data)] = PadByte
270 p.BytesPayloadOut += uint64(len(data))
273 if p.NoiseEnable && !p.Encless {
274 p.frameT = p.bufT[S20BS : S20BS+p.MTU-TagSize]
275 } else if p.Encless {
276 p.frameT = p.bufT[S20BS : S20BS+p.MTU]
278 p.frameT = p.bufT[S20BS : S20BS+len(data)+1+NonceSize]
280 copy(p.frameT[len(p.frameT)-NonceSize:], (<-p.noncesT)[:])
282 copy(p.nonceT[8:], p.frameT[len(p.frameT)-NonceSize:])
285 out, err = EnclessEncode(p.key, p.nonceT, p.frameT[:len(p.frameT)-NonceSize])
289 out = append(out, p.frameT[len(p.frameT)-NonceSize:]...)
291 chacha20.XORKeyStream(
292 p.bufT[:S20BS+len(p.frameT)-NonceSize],
293 p.bufT[:S20BS+len(p.frameT)-NonceSize],
297 copy(p.keyAuthT[:], p.bufT[:SSize])
298 poly1305.Sum(p.tagT, p.frameT, p.keyAuthT)
299 atomic.AddUint64(&p.BytesOut, uint64(len(p.frameT)+TagSize))
300 out = append(p.tagT[:], p.frameT...)
307 func (p *Peer) PktProcess(data []byte, tap io.Writer, reorderable bool) bool {
308 if len(data) < MinPktLength {
311 if !p.Encless && len(data) > len(p.bufR)-S20BS {
316 copy(p.nonceR[8:], data[len(data)-NonceSize:])
319 out, err = EnclessDecode(p.key, p.nonceR, data[:len(data)-NonceSize])
326 for i := 0; i < SSize; i++ {
329 copy(p.bufR[S20BS:], data[TagSize:])
330 chacha20.XORKeyStream(
331 p.bufR[:S20BS+len(data)-TagSize-NonceSize],
332 p.bufR[:S20BS+len(data)-TagSize-NonceSize],
336 copy(p.keyAuthR[:], p.bufR[:SSize])
337 copy(p.tagR[:], data[:TagSize])
338 if !poly1305.Verify(p.tagR, data[TagSize:], p.keyAuthR) {
343 out = p.bufR[S20BS : S20BS+len(data)-TagSize-NonceSize]
347 copy(p.nonceRecv[:], data[len(data)-NonceSize:])
348 _, foundL := p.nonceBucketL[p.nonceRecv]
349 _, foundM := p.nonceBucketM[p.nonceRecv]
350 _, foundH := p.nonceBucketH[p.nonceRecv]
351 // If found is none of buckets: either it is too old,
352 // or too new (many packets were lost)
353 if !(foundL || foundM || foundH) {
360 delete(p.nonceBucketL, p.nonceRecv)
363 delete(p.nonceBucketM, p.nonceRecv)
366 delete(p.nonceBucketH, p.nonceRecv)
368 // If we are dealing with the latest bucket, create the new one
370 p.nonceBucketL, p.nonceBucketM = p.nonceBucketM, p.nonceBucketH
371 p.nonceBucketH = make(map[[NonceSize]byte]struct{})
372 var nonce *[NonceSize]byte
373 for i := 0; i < NonceBucketSize; i++ {
375 p.nonceBucketH[*nonce] = struct{}{}
379 if subtle.ConstantTimeCompare(data[len(data)-NonceSize:], p.NonceExpect) != 1 {
384 copy(p.NonceExpect, (<-p.noncesExpect)[:])
388 atomic.AddUint64(&p.BytesIn, uint64(len(data)))
389 p.LastPing = time.Now()
390 p.pktSizeR = bytes.LastIndexByte(out, PadByte)
391 if p.pktSizeR == -1 {
396 for i := p.pktSizeR + 1; i < len(out); i++ {
408 p.BytesPayloadIn += uint64(p.pktSizeR)
409 tap.Write(out[:p.pktSizeR])
414 func PeerTapProcessor(peer *Peer, tap *TAP, terminator chan struct{}) {
417 lastSent := time.Now()
418 heartbeat := time.NewTicker(peer.Timeout)
419 if peer.CPRCycle == time.Duration(0) {
427 if lastSent.Add(peer.Timeout).Before(now) {
431 case data = <-tap.Sink:
432 peer.EthProcess(data)
433 lastSent = time.Now()
443 case data = <-tap.Sink:
444 peer.EthProcess(data)
450 time.Sleep(peer.CPRCycle)