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
42 chacha20InternalBlockSize = 64
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 := chacha20InternalBlockSize + 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
297 if lenData > p.MTU-paddingSize {
298 logger.WithFields(p.LogFields()).WithFields(p.ConfigurationLogFields()).WithFields(
300 "func": logFuncPrefix + "Peer.EthProcess",
301 "padding": paddingSize,
302 "packet_size": lenData,
303 }).Warning("Ignore padded data packet larger than MTU")
307 defer p.BusyT.Unlock()
309 // Zero size is a heartbeat packet
312 p.bufT[chacha20InternalBlockSize+0] = padByte
315 // Copy payload to our internal buffer and we are ready to
316 // accept the next one
317 copy(p.bufT[chacha20InternalBlockSize:], data)
318 p.bufT[chacha20InternalBlockSize+lenData] = padByte
319 p.BytesPayloadOut += uint64(lenData)
322 if p.NoiseEnable && !p.Encless {
323 p.frameT = p.bufT[chacha20InternalBlockSize : chacha20InternalBlockSize+p.MTU-tagSize]
324 } else if p.Encless {
325 p.frameT = p.bufT[chacha20InternalBlockSize : chacha20InternalBlockSize+p.MTU]
327 p.frameT = p.bufT[chacha20InternalBlockSize : chacha20InternalBlockSize+lenData+1+NonceSize]
329 copy(p.frameT[len(p.frameT)-NonceSize:], (<-p.noncesT)[:])
331 copy(p.nonceT[8:], p.frameT[len(p.frameT)-NonceSize:])
334 out, err = EnclessEncode(p.key, p.nonceT, p.frameT[:len(p.frameT)-NonceSize])
336 return errors.Wrap(err, wrapEnclessEncode)
338 out = append(out, p.frameT[len(p.frameT)-NonceSize:]...)
340 chacha20.XORKeyStream(
341 p.bufT[:chacha20InternalBlockSize+len(p.frameT)-NonceSize],
342 p.bufT[:chacha20InternalBlockSize+len(p.frameT)-NonceSize],
346 copy(p.keyAuthT[:], p.bufT[:SSize])
347 poly1305.Sum(p.tagT, p.frameT, p.keyAuthT)
348 atomic.AddUint64(&p.BytesOut, uint64(len(p.frameT)+tagSize))
349 out = append(p.tagT[:], p.frameT...)
352 _, err := p.Conn.Write(out)
353 return errors.Wrap(err, "p.Conn.Write")
356 // PktProcess processes data of a single packet
357 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 lenData < MinPktLength {
365 logger.WithFields(p.LogFields()).WithFields(fields).WithField("minimum_packet_Length", MinPktLength).Debug("Ignore packet smaller than allowed minimum")
368 if !p.Encless && lenData > len(p.bufR)-chacha20InternalBlockSize {
372 p.BusyR.Lock() // TODO use defer to unlock?
373 copy(p.nonceR[8:], data[lenData-NonceSize:])
376 out, err = EnclessDecode(p.key, p.nonceR, data[:lenData-NonceSize])
378 logger.WithFields(p.LogFields()).WithError(err).Debug("Failed to decode encless")
384 for i := 0; i < SSize; i++ {
387 copy(p.bufR[chacha20InternalBlockSize:], data[tagSize:])
388 chacha20.XORKeyStream(
389 p.bufR[:chacha20InternalBlockSize+lenData-tagSize-NonceSize],
390 p.bufR[:chacha20InternalBlockSize+lenData-tagSize-NonceSize],
394 copy(p.keyAuthR[:], p.bufR[:SSize])
395 copy(p.tagR[:], data[:tagSize])
396 if !poly1305.Verify(p.tagR, data[tagSize:], p.keyAuthR) {
401 out = p.bufR[chacha20InternalBlockSize : chacha20InternalBlockSize+lenData-tagSize-NonceSize]
405 copy(p.nonceRecv[:], data[lenData-NonceSize:])
406 _, foundL := p.nonceBucketL[p.nonceRecv]
407 _, foundM := p.nonceBucketM[p.nonceRecv]
408 _, foundH := p.nonceBucketH[p.nonceRecv]
409 // If found is none of buckets: either it is too old,
410 // or too new (many packets were lost)
411 if !(foundL || foundM || foundH) {
418 delete(p.nonceBucketL, p.nonceRecv)
421 delete(p.nonceBucketM, p.nonceRecv)
424 delete(p.nonceBucketH, p.nonceRecv)
426 // If we are dealing with the latest bucket, create the new one
428 p.nonceBucketL, p.nonceBucketM = p.nonceBucketM, p.nonceBucketH
429 p.nonceBucketH = make(map[[NonceSize]byte]struct{})
430 var nonce *[NonceSize]byte
431 for i := 0; i < nonceBucketSize; i++ {
433 p.nonceBucketH[*nonce] = struct{}{}
437 if subtle.ConstantTimeCompare(data[lenData-NonceSize:], p.NonceExpect) != 1 {
442 copy(p.NonceExpect, (<-p.noncesExpect)[:])
446 atomic.AddUint64(&p.BytesIn, uint64(lenData))
447 p.LastPing = time.Now()
448 p.pktSizeR = bytes.LastIndexByte(out, padByte)
449 if p.pktSizeR == -1 {
454 for i := p.pktSizeR + 1; i < len(out); i++ {
466 p.BytesPayloadIn += uint64(p.pktSizeR)
467 tap.Write(out[:p.pktSizeR])
472 // PeerTapProcessor processes a TUN/TAP peer
473 func PeerTapProcessor(peer *Peer, tap *TAP, terminator chan struct{}) {
477 fields := logrus.Fields{
478 "func": logFuncPrefix + "PeerTapProcessor",
481 lastSent := time.Now()
482 heartbeat := time.NewTicker(peer.Timeout)
483 if peer.CPRCycle == time.Duration(0) {
491 if lastSent.Add(peer.Timeout).Before(now) {
492 if err = peer.EthProcess(nil); err != nil {
493 logger.WithFields(fields).WithFields(peer.LogFields()).WithError(err).Warn("Can't process nil ethernet packet")
497 case data = <-tap.Sink:
498 if err = peer.EthProcess(data); err != nil {
499 logger.WithFields(fields).WithFields(peer.LogFields()).WithError(err).Warn("Can't process ethernet packet")
501 lastSent = time.Now()
511 case data = <-tap.Sink:
512 if err = peer.EthProcess(data); err != nil {
513 logger.WithFields(fields).WithFields(peer.LogFields()).WithError(err).Warn("Can't process ethernet packet")
518 if err = peer.EthProcess(nil); err != nil {
519 logger.WithFields(fields).WithFields(peer.LogFields()).WithError(err).Warn("Can't process nil ethernet packet")
522 time.Sleep(peer.CPRCycle)