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 {
297 logger.WithFields(p.LogFields()).WithFields(
298 p.ConfigurationLogFields(),
301 "func": logFuncPrefix + "Peer.EthProcess",
302 "padding": paddingSize,
303 "packet_size": len(data),
304 }).Warning("Ignore padded data packet larger than MTU")
308 defer p.BusyT.Unlock()
310 // Zero size is a heartbeat packet
313 p.bufT[CC20IBS+0] = padByte
316 // Copy payload to our internal buffer and we are ready to
317 // accept the next one
318 copy(p.bufT[CC20IBS:], data)
319 p.bufT[CC20IBS+len(data)] = padByte
320 p.BytesPayloadOut += uint64(len(data))
323 if p.NoiseEnable && !p.Encless {
324 p.frameT = p.bufT[CC20IBS : CC20IBS+p.MTU-tagSize]
325 } else if p.Encless {
326 p.frameT = p.bufT[CC20IBS : CC20IBS+p.MTU]
328 p.frameT = p.bufT[CC20IBS : CC20IBS+len(data)+1+NonceSize]
330 copy(p.frameT[len(p.frameT)-NonceSize:], (<-p.noncesT)[:])
332 copy(p.nonceT[8:], p.frameT[len(p.frameT)-NonceSize:])
335 out, err = EnclessEncode(p.key, p.nonceT, p.frameT[:len(p.frameT)-NonceSize])
337 return errors.Wrap(err, wrapEnclessEncode)
339 out = append(out, p.frameT[len(p.frameT)-NonceSize:]...)
341 chacha20.XORKeyStream(
342 p.bufT[:CC20IBS+len(p.frameT)-NonceSize],
343 p.bufT[:CC20IBS+len(p.frameT)-NonceSize],
347 copy(p.keyAuthT[:], p.bufT[:SSize])
348 poly1305.Sum(p.tagT, p.frameT, p.keyAuthT)
349 atomic.AddUint64(&p.BytesOut, uint64(len(p.frameT)+tagSize))
350 out = append(p.tagT[:], p.frameT...)
353 _, err := p.Conn.Write(out)
354 return errors.Wrap(err, "p.Conn.Write")
357 // PktProcess processes data of a single packet
358 func (p *Peer) PktProcess(data []byte, tap io.Writer, reorderable bool) bool {
359 fields := logrus.Fields{
360 "func": logFuncPrefix + "Peer.PktProcess",
361 "reorderable": reorderable,
364 if len(data) < MinPktLength {
365 logger.WithFields(p.LogFields()).WithFields(fields).WithField(
366 "minimum_packet_Length", MinPktLength,
367 ).Debug("Ignore packet smaller than allowed minimum")
370 if !p.Encless && len(data) > len(p.bufR)-CC20IBS {
374 p.BusyR.Lock() // TODO use defer to unlock?
375 copy(p.nonceR[8:], data[len(data)-NonceSize:])
378 out, err = EnclessDecode(p.key, p.nonceR, data[:len(data)-NonceSize])
380 logger.WithFields(p.LogFields()).WithError(err).Debug("Failed to decode encless")
386 for i := 0; i < SSize; i++ {
389 copy(p.bufR[CC20IBS:], data[tagSize:])
390 chacha20.XORKeyStream(
391 p.bufR[:CC20IBS+len(data)-tagSize-NonceSize],
392 p.bufR[:CC20IBS+len(data)-tagSize-NonceSize],
396 copy(p.keyAuthR[:], p.bufR[:SSize])
397 copy(p.tagR[:], data[:tagSize])
398 if !poly1305.Verify(p.tagR, data[tagSize:], p.keyAuthR) {
403 out = p.bufR[CC20IBS : CC20IBS+len(data)-tagSize-NonceSize]
407 copy(p.nonceRecv[:], data[len(data)-NonceSize:])
408 _, foundL := p.nonceBucketL[p.nonceRecv]
409 _, foundM := p.nonceBucketM[p.nonceRecv]
410 _, foundH := p.nonceBucketH[p.nonceRecv]
411 // If found is none of buckets: either it is too old,
412 // or too new (many packets were lost)
413 if !(foundL || foundM || foundH) {
420 delete(p.nonceBucketL, p.nonceRecv)
423 delete(p.nonceBucketM, p.nonceRecv)
426 delete(p.nonceBucketH, p.nonceRecv)
428 // If we are dealing with the latest bucket, create the new one
430 p.nonceBucketL, p.nonceBucketM = p.nonceBucketM, p.nonceBucketH
431 p.nonceBucketH = make(map[[NonceSize]byte]struct{})
432 var nonce *[NonceSize]byte
433 for i := 0; i < nonceBucketSize; i++ {
435 p.nonceBucketH[*nonce] = struct{}{}
439 if subtle.ConstantTimeCompare(data[len(data)-NonceSize:], p.NonceExpect) != 1 {
444 copy(p.NonceExpect, (<-p.noncesExpect)[:])
448 atomic.AddUint64(&p.BytesIn, uint64(len(data)))
449 p.LastPing = time.Now()
450 p.pktSizeR = bytes.LastIndexByte(out, padByte)
451 if p.pktSizeR == -1 {
456 for i := p.pktSizeR + 1; i < len(out); i++ {
468 p.BytesPayloadIn += uint64(p.pktSizeR)
469 tap.Write(out[:p.pktSizeR])
474 // PeerTapProcessor processes a TUN/TAP peer
475 func PeerTapProcessor(peer *Peer, tap *TAP, terminator chan struct{}) {
479 fields := logrus.Fields{
480 "func": logFuncPrefix + "PeerTapProcessor",
483 lastSent := time.Now()
484 heartbeat := time.NewTicker(peer.Timeout)
485 if peer.CPRCycle == time.Duration(0) {
493 if lastSent.Add(peer.Timeout).Before(now) {
494 if err = peer.EthProcess(nil); err != nil {
499 ).WithError(err).Warn(
500 "Can't process nil ethernet packet",
505 case data = <-tap.Sink:
506 if err = peer.EthProcess(data); err != nil {
507 logger.WithFields(fields).WithFields(
509 ).WithError(err).Warn("Can't process ethernet packet")
511 lastSent = time.Now()
521 case data = <-tap.Sink:
522 if err = peer.EthProcess(data); err != nil {
523 logger.WithFields(fields).WithFields(
525 ).WithError(err).Warn("Can't process ethernet packet")
530 if err = peer.EthProcess(nil); err != nil {
531 logger.WithFields(fields).WithFields(
533 ).WithError(err).Warn("Can't process nil ethernet packet")
536 time.Sleep(peer.CPRCycle)