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/>.
31 "github.com/Sirupsen/logrus"
32 "github.com/pkg/errors"
33 "golang.org/x/crypto/blake2b"
34 "golang.org/x/crypto/poly1305"
38 // NonceSize is nonce size
41 tagSize = poly1305.TagSize
43 // MaxBytesPerKey is maximal amount of bytes transferred with single key (4 GiB)
44 MaxBytesPerKey uint64 = 1 << 32
45 // Heartbeat rate, relative to Timeout
47 // MinPktLength is minimal valid packet length
48 MinPktLength = 1 + 16 + 8
52 logPrefixPeer = "peer_"
55 func newNonces(key *[32]byte, i uint64) (chan *[NonceSize]byte, error) {
56 macKey := make([]byte, 32)
57 chacha20.XORKeyStream(macKey, make([]byte, 32), new([16]byte), key)
58 mac, err := blake2b.New256(macKey)
62 sum := make([]byte, mac.Size())
63 nonces := make(chan *[NonceSize]byte, nonceBucketSize*3)
66 buf := new([NonceSize]byte)
67 binary.BigEndian.PutUint64(buf[:], i)
79 // Peer is a GoVPN peer (client)
81 // Statistics (they are at the beginning for correct int64 alignment)
85 BytesPayloadOut uint64
96 Conn io.Writer `json:"-"`
102 CPRCycle time.Duration `json:"-"`
109 Timeout time.Duration `json:"-"`
110 Established time.Time
114 BusyR sync.Mutex `json:"-"`
117 keyAuthR *[SSize]byte
122 noncesR chan *[NonceSize]byte
123 nonceRecv [NonceSize]byte
124 nonceBucketL map[[NonceSize]byte]struct{}
125 nonceBucketM map[[NonceSize]byte]struct{}
126 nonceBucketH map[[NonceSize]byte]struct{}
129 NonceExpect []byte `json:"-"`
130 noncesExpect chan *[NonceSize]byte
133 BusyT sync.Mutex `json:"-"`
136 keyAuthT *[SSize]byte
139 noncesT chan *[NonceSize]byte
142 // LogFields returns a logrus compatible Fields to identity a single
144 func (p *Peer) LogFields() logrus.Fields {
145 return logrus.Fields{
146 logPrefixPeer + "addr": p.Addr,
147 logPrefixPeer + "id": p.ID.String(),
148 logPrefixPeer + "established": p.Established.String(),
149 logPrefixPeer + "last_ping": p.LastPing.String(),
153 // ConfigurationLogFields returns a logrus compatible Fields with the
154 // settings of a single peer. Complement LogFields() for extra debugging
156 func (p *Peer) ConfigurationLogFields() logrus.Fields {
157 return logrus.Fields{
158 logPrefixPeer + "timeout": p.Timeout.String(),
159 logPrefixPeer + "protocol": p.Protocol.String(),
160 logPrefixPeer + "noise": p.NoiseEnable,
161 logPrefixPeer + "cpr": p.CPR,
162 logPrefixPeer + "mtu": p.MTU,
163 logPrefixPeer + "encless": p.Encless,
167 func (p *Peer) String() string {
168 return p.ID.String() + ":" + p.Addr
171 // Zero peer's memory state.
172 func (p *Peer) Zero() {
178 SliceZero(p.keyAuthR[:])
179 SliceZero(p.keyAuthT[:])
184 func cprCycleCalculate(conf *PeerConf) time.Duration {
186 return time.Duration(0)
188 rate := conf.CPR * 1 << 10
190 rate /= EnclessEnlargeSize + conf.MTU
194 return time.Second / time.Duration(rate)
197 func newPeer(isClient bool, addr string, conn io.Writer, conf *PeerConf, key *[SSize]byte) (*Peer, error) {
199 timeout := conf.Timeout
201 cprCycle := cprCycleCalculate(conf)
202 noiseEnable := conf.Noise
207 timeout = timeout / timeoutHeartbeat
210 bufSize := CC20IBS + 2*conf.MTU
212 bufSize += EnclessEnlargeSize
221 NoiseEnable: noiseEnable,
224 Encless: conf.Encless,
233 bufR: make([]byte, bufSize),
234 bufT: make([]byte, bufSize),
235 tagR: new([tagSize]byte),
236 tagT: new([tagSize]byte),
237 keyAuthR: new([SSize]byte),
238 nonceR: new([16]byte),
239 keyAuthT: new([SSize]byte),
240 nonceT: new([16]byte),
245 if peer.noncesT, err = newNonces(peer.key, 1+2); err != nil {
248 if peer.noncesR, err = newNonces(peer.key, 0+2); err != nil {
251 if peer.noncesExpect, err = newNonces(peer.key, 0+2); err != nil {
255 if peer.noncesT, err = newNonces(peer.key, 0+2); err != nil {
258 if peer.noncesR, err = newNonces(peer.key, 1+2); err != nil {
261 if peer.noncesExpect, err = newNonces(peer.key, 1+2); err != nil {
266 peer.NonceExpect = make([]byte, NonceSize)
267 nonce := <-peer.noncesExpect
268 copy(peer.NonceExpect, nonce[:])
271 peer.nonceBucketL = make(map[[NonceSize]byte]struct{}, nonceBucketSize)
272 for i = 0; i < nonceBucketSize; i++ {
273 nonce = <-peer.noncesR
274 peer.nonceBucketL[*nonce] = struct{}{}
276 peer.nonceBucketM = make(map[[NonceSize]byte]struct{}, nonceBucketSize)
277 for i = 0; i < nonceBucketSize; i++ {
278 nonce = <-peer.noncesR
279 peer.nonceBucketM[*nonce] = struct{}{}
281 peer.nonceBucketH = make(map[[NonceSize]byte]struct{}, nonceBucketSize)
282 for i = 0; i < nonceBucketSize; i++ {
283 nonce = <-peer.noncesR
284 peer.nonceBucketH[*nonce] = struct{}{}
290 // EthProcess processes incoming Ethernet packet.
291 // ready channel is TAPListen's synchronization channel used to tell him
292 // that he is free to receive new packets. Encrypted and authenticated
293 // packets will be sent to remote Peer side immediately.
294 func (p *Peer) EthProcess(data []byte) error {
295 const paddingSize = 1
296 if len(data) > p.MTU-paddingSize {
300 p.ConfigurationLogFields(),
303 "func": logFuncPrefix + "Peer.EthProcess",
304 "padding": paddingSize,
305 "packet_size": len(data),
307 ).Warning("Ignore padded data packet larger than MTU")
311 defer p.BusyT.Unlock()
313 // Zero size is a heartbeat packet
316 p.bufT[CC20IBS+0] = padByte
319 // Copy payload to our internal buffer and we are ready to
320 // accept the next one
321 copy(p.bufT[CC20IBS:], data)
322 p.bufT[CC20IBS+len(data)] = padByte
323 p.BytesPayloadOut += uint64(len(data))
326 if p.NoiseEnable && !p.Encless {
327 p.frameT = p.bufT[CC20IBS : CC20IBS+p.MTU-tagSize]
328 } else if p.Encless {
329 p.frameT = p.bufT[CC20IBS : CC20IBS+p.MTU]
331 p.frameT = p.bufT[CC20IBS : CC20IBS+len(data)+1+NonceSize]
333 copy(p.frameT[len(p.frameT)-NonceSize:], (<-p.noncesT)[:])
335 copy(p.nonceT[8:], p.frameT[len(p.frameT)-NonceSize:])
338 out, err = EnclessEncode(p.key, p.nonceT, p.frameT[:len(p.frameT)-NonceSize])
340 return errors.Wrap(err, wrapEnclessEncode)
342 out = append(out, p.frameT[len(p.frameT)-NonceSize:]...)
344 chacha20.XORKeyStream(
345 p.bufT[:CC20IBS+len(p.frameT)-NonceSize],
346 p.bufT[:CC20IBS+len(p.frameT)-NonceSize],
350 copy(p.keyAuthT[:], p.bufT[:SSize])
351 poly1305.Sum(p.tagT, p.frameT, p.keyAuthT)
352 atomic.AddUint64(&p.BytesOut, uint64(len(p.frameT)+tagSize))
353 out = append(p.tagT[:], p.frameT...)
356 _, err := p.Conn.Write(out)
357 return errors.Wrap(err, "p.Conn.Write")
360 // PktProcess processes data of a single packet
361 func (p *Peer) PktProcess(data []byte, tap io.Writer, reorderable bool) bool {
362 fields := logrus.Fields{
363 "func": logFuncPrefix + "Peer.PktProcess",
364 "reorderable": reorderable,
367 if len(data) < MinPktLength {
373 "minimum_packet_Length",
375 ).Debug("Ignore packet smaller than allowed minimum")
378 if !p.Encless && len(data) > len(p.bufR)-CC20IBS {
383 defer p.BusyR.Unlock()
384 copy(p.nonceR[8:], data[len(data)-NonceSize:])
387 out, err = EnclessDecode(p.key, p.nonceR, data[:len(data)-NonceSize])
391 ).WithError(err).Debug("Failed to decode encless")
396 for i := 0; i < SSize; i++ {
399 copy(p.bufR[CC20IBS:], data[tagSize:])
400 chacha20.XORKeyStream(
401 p.bufR[:CC20IBS+len(data)-tagSize-NonceSize],
402 p.bufR[:CC20IBS+len(data)-tagSize-NonceSize],
406 copy(p.keyAuthR[:], p.bufR[:SSize])
407 copy(p.tagR[:], data[:tagSize])
408 if !poly1305.Verify(p.tagR, data[tagSize:], p.keyAuthR) {
412 out = p.bufR[CC20IBS : CC20IBS+len(data)-tagSize-NonceSize]
416 copy(p.nonceRecv[:], data[len(data)-NonceSize:])
417 _, foundL := p.nonceBucketL[p.nonceRecv]
418 _, foundM := p.nonceBucketM[p.nonceRecv]
419 _, foundH := p.nonceBucketH[p.nonceRecv]
420 // If found is none of buckets: either it is too old,
421 // or too new (many packets were lost)
422 if !(foundL || foundM || foundH) {
428 delete(p.nonceBucketL, p.nonceRecv)
431 delete(p.nonceBucketM, p.nonceRecv)
434 delete(p.nonceBucketH, p.nonceRecv)
436 // If we are dealing with the latest bucket, create the new one
438 p.nonceBucketL, p.nonceBucketM = p.nonceBucketM, p.nonceBucketH
439 p.nonceBucketH = make(map[[NonceSize]byte]struct{})
440 var nonce *[NonceSize]byte
441 for i := 0; i < nonceBucketSize; i++ {
443 p.nonceBucketH[*nonce] = struct{}{}
447 if subtle.ConstantTimeCompare(data[len(data)-NonceSize:], p.NonceExpect) != 1 {
451 copy(p.NonceExpect, (<-p.noncesExpect)[:])
455 atomic.AddUint64(&p.BytesIn, uint64(len(data)))
456 p.LastPing = time.Now()
457 p.pktSizeR = bytes.LastIndexByte(out, padByte)
458 if p.pktSizeR == -1 {
462 for i := p.pktSizeR + 1; i < len(out); i++ {
472 p.BytesPayloadIn += uint64(p.pktSizeR)
473 tap.Write(out[:p.pktSizeR])
477 // PeerTapProcessor processes a TUN/TAP peer
478 func PeerTapProcessor(peer *Peer, tap *TAP, terminator chan struct{}) {
482 fields := logrus.Fields{
483 "func": logFuncPrefix + "PeerTapProcessor",
486 lastSent := time.Now()
487 heartbeat := time.NewTicker(peer.Timeout)
488 if peer.CPRCycle == time.Duration(0) {
496 if lastSent.Add(peer.Timeout).Before(now) {
497 if err = peer.EthProcess(nil); err != nil {
502 ).WithError(err).Warn(
503 "Can't process nil ethernet packet",
508 case data = <-tap.Sink:
509 if err = peer.EthProcess(data); err != nil {
514 ).WithError(err).Warn("Can't process ethernet packet")
516 lastSent = time.Now()
526 case data = <-tap.Sink:
527 if err = peer.EthProcess(data); err != nil {
532 ).WithError(err).Warn("Can't process ethernet packet")
537 if err = peer.EthProcess(nil); err != nil {
542 ).WithError(err).Warn("Can't process nil ethernet packet")
545 time.Sleep(peer.CPRCycle)