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/>.
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 nonces := make(chan *[NonceSize]byte, NonceBucketSize*3)
62 buf := new([NonceSize]byte)
63 binary.BigEndian.PutUint64(buf[:], i)
75 // Statistics (they are at the beginning for correct int64 alignment)
79 BytesPayloadOut uint64
90 Conn io.Writer `json:"-"`
95 CPRCycle time.Duration `json:"-"`
99 key *[SSize]byte `json:"-"`
102 Timeout time.Duration `json:"-"`
103 Established time.Time
107 BusyR sync.Mutex `json:"-"`
110 keyAuthR *[SSize]byte
115 noncesR chan *[NonceSize]byte
116 nonceRecv [NonceSize]byte
117 nonceBucketL map[[NonceSize]byte]struct{}
118 nonceBucketM map[[NonceSize]byte]struct{}
119 nonceBucketH map[[NonceSize]byte]struct{}
122 NonceExpect []byte `json:"-"`
123 noncesExpect chan *[NonceSize]byte
126 BusyT sync.Mutex `json:"-"`
129 keyAuthT *[SSize]byte
132 noncesT chan *[NonceSize]byte
135 func (p *Peer) String() string {
136 return p.Id.String() + ":" + p.Addr
139 // Zero peer's memory state.
140 func (p *Peer) Zero() {
146 SliceZero(p.keyAuthR[:])
147 SliceZero(p.keyAuthT[:])
152 func cprCycleCalculate(conf *PeerConf) time.Duration {
154 return time.Duration(0)
156 rate := conf.CPR * 1 << 10
158 rate /= EnclessEnlargeSize + conf.MTU
162 return time.Second / time.Duration(rate)
165 func newPeer(isClient bool, addr string, conn io.Writer, conf *PeerConf, key *[SSize]byte) *Peer {
167 timeout := conf.Timeout
169 cprCycle := cprCycleCalculate(conf)
170 noiseEnable := conf.Noise
175 timeout = timeout / TimeoutHeartbeat
178 bufSize := S20BS + 2*conf.MTU
180 bufSize += EnclessEnlargeSize
189 NoiseEnable: noiseEnable,
192 Encless: conf.Encless,
201 bufR: make([]byte, bufSize),
202 bufT: make([]byte, bufSize),
203 tagR: new([TagSize]byte),
204 tagT: new([TagSize]byte),
205 keyAuthR: new([SSize]byte),
206 nonceR: new([16]byte),
207 keyAuthT: new([SSize]byte),
208 nonceT: new([16]byte),
212 peer.noncesT = newNonces(peer.key, 1+2)
213 peer.noncesR = newNonces(peer.key, 0+2)
214 peer.noncesExpect = newNonces(peer.key, 0+2)
216 peer.noncesT = newNonces(peer.key, 0+2)
217 peer.noncesR = newNonces(peer.key, 1+2)
218 peer.noncesExpect = newNonces(peer.key, 1+2)
221 peer.NonceExpect = make([]byte, NonceSize)
222 nonce := <-peer.noncesExpect
223 copy(peer.NonceExpect, nonce[:])
226 peer.nonceBucketL = make(map[[NonceSize]byte]struct{}, NonceBucketSize)
227 for i = 0; i < NonceBucketSize; i++ {
228 nonce = <-peer.noncesR
229 peer.nonceBucketL[*nonce] = struct{}{}
231 peer.nonceBucketM = make(map[[NonceSize]byte]struct{}, NonceBucketSize)
232 for i = 0; i < NonceBucketSize; i++ {
233 nonce = <-peer.noncesR
234 peer.nonceBucketM[*nonce] = struct{}{}
236 peer.nonceBucketH = make(map[[NonceSize]byte]struct{}, NonceBucketSize)
237 for i = 0; i < NonceBucketSize; i++ {
238 nonce = <-peer.noncesR
239 peer.nonceBucketH[*nonce] = struct{}{}
245 // Process incoming Ethernet packet.
246 // ready channel is TAPListen's synchronization channel used to tell him
247 // that he is free to receive new packets. Encrypted and authenticated
248 // packets will be sent to remote Peer side immediately.
249 func (p *Peer) EthProcess(data []byte) {
250 if len(data) > p.MTU-1 { // 1 is for padding byte
251 log.Println("Padded data packet size", len(data)+1, "is bigger than MTU", p.MTU, p)
256 // Zero size is a heartbeat packet
259 p.bufT[S20BS+0] = PadByte
262 // Copy payload to our internal buffer and we are ready to
263 // accept the next one
264 copy(p.bufT[S20BS:], data)
265 p.bufT[S20BS+len(data)] = PadByte
266 p.BytesPayloadOut += uint64(len(data))
269 if p.NoiseEnable && !p.Encless {
270 p.frameT = p.bufT[S20BS : S20BS+p.MTU-TagSize]
271 } else if p.Encless {
272 p.frameT = p.bufT[S20BS : S20BS+p.MTU]
274 p.frameT = p.bufT[S20BS : S20BS+len(data)+1+NonceSize]
276 copy(p.frameT[len(p.frameT)-NonceSize:], (<-p.noncesT)[:])
278 copy(p.nonceT[8:], p.frameT[len(p.frameT)-NonceSize:])
281 out, err = EnclessEncode(p.key, p.nonceT, p.frameT[:len(p.frameT)-NonceSize])
285 out = append(out, p.frameT[len(p.frameT)-NonceSize:]...)
287 chacha20.XORKeyStream(
288 p.bufT[:S20BS+len(p.frameT)-NonceSize],
289 p.bufT[:S20BS+len(p.frameT)-NonceSize],
293 copy(p.keyAuthT[:], p.bufT[:SSize])
294 poly1305.Sum(p.tagT, p.frameT, p.keyAuthT)
295 atomic.AddUint64(&p.BytesOut, uint64(len(p.frameT)+TagSize))
296 out = append(p.tagT[:], p.frameT...)
303 func (p *Peer) PktProcess(data []byte, tap io.Writer, reorderable bool) bool {
304 if len(data) < MinPktLength {
307 if !p.Encless && len(data) > len(p.bufR)-S20BS {
312 copy(p.nonceR[8:], data[len(data)-NonceSize:])
315 out, err = EnclessDecode(p.key, p.nonceR, data[:len(data)-NonceSize])
322 for i := 0; i < SSize; i++ {
325 copy(p.bufR[S20BS:], data[TagSize:])
326 chacha20.XORKeyStream(
327 p.bufR[:S20BS+len(data)-TagSize-NonceSize],
328 p.bufR[:S20BS+len(data)-TagSize-NonceSize],
332 copy(p.keyAuthR[:], p.bufR[:SSize])
333 copy(p.tagR[:], data[:TagSize])
334 if !poly1305.Verify(p.tagR, data[TagSize:], p.keyAuthR) {
339 out = p.bufR[S20BS : S20BS+len(data)-TagSize-NonceSize]
343 copy(p.nonceRecv[:], data[len(data)-NonceSize:])
344 _, foundL := p.nonceBucketL[p.nonceRecv]
345 _, foundM := p.nonceBucketM[p.nonceRecv]
346 _, foundH := p.nonceBucketH[p.nonceRecv]
347 // If found is none of buckets: either it is too old,
348 // or too new (many packets were lost)
349 if !(foundL || foundM || foundH) {
356 delete(p.nonceBucketL, p.nonceRecv)
359 delete(p.nonceBucketM, p.nonceRecv)
362 delete(p.nonceBucketH, p.nonceRecv)
364 // If we are dealing with the latest bucket, create the new one
366 p.nonceBucketL, p.nonceBucketM = p.nonceBucketM, p.nonceBucketH
367 p.nonceBucketH = make(map[[NonceSize]byte]struct{})
368 var nonce *[NonceSize]byte
369 for i := 0; i < NonceBucketSize; i++ {
371 p.nonceBucketH[*nonce] = struct{}{}
375 if subtle.ConstantTimeCompare(data[len(data)-NonceSize:], p.NonceExpect) != 1 {
380 copy(p.NonceExpect, (<-p.noncesExpect)[:])
384 atomic.AddUint64(&p.BytesIn, uint64(len(data)))
385 p.LastPing = time.Now()
386 p.pktSizeR = bytes.LastIndexByte(out, PadByte)
387 if p.pktSizeR == -1 {
392 for i := p.pktSizeR + 1; i < len(out); i++ {
404 p.BytesPayloadIn += uint64(p.pktSizeR)
405 tap.Write(out[:p.pktSizeR])
410 func PeerTapProcessor(peer *Peer, tap *TAP, terminator chan struct{}) {
413 lastSent := time.Now()
414 heartbeat := time.NewTicker(peer.Timeout)
415 if peer.CPRCycle == time.Duration(0) {
423 if lastSent.Add(peer.Timeout).Before(now) {
427 case data = <-tap.Sink:
428 peer.EthProcess(data)
429 lastSent = time.Now()
439 case data = <-tap.Sink:
440 peer.EthProcess(data)
446 time.Sleep(peer.CPRCycle)