2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2020 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, version 3 of the License.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
30 "go.cypherpunks.ru/govpn/v7/internal/chacha20"
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)
77 // Statistics (they are at the beginning for correct int64 alignment)
81 BytesPayloadOut uint64
92 Conn io.Writer `json:"-"`
97 CPRCycle time.Duration `json:"-"`
104 Timeout time.Duration `json:"-"`
105 Established time.Time
109 BusyR sync.Mutex `json:"-"`
112 keyAuthR *[SSize]byte
117 noncesR chan *[NonceSize]byte
118 nonceRecv [NonceSize]byte
119 nonceBucketL map[[NonceSize]byte]struct{}
120 nonceBucketM map[[NonceSize]byte]struct{}
121 nonceBucketH map[[NonceSize]byte]struct{}
124 NonceExpect []byte `json:"-"`
125 noncesExpect chan *[NonceSize]byte
128 BusyT sync.Mutex `json:"-"`
131 keyAuthT *[SSize]byte
134 noncesT chan *[NonceSize]byte
137 func (p *Peer) String() string {
138 return p.ID.String() + ":" + p.Addr
141 // Zero peer's memory state.
142 func (p *Peer) Zero() {
148 SliceZero(p.keyAuthR[:])
149 SliceZero(p.keyAuthT[:])
154 func cprCycleCalculate(conf *PeerConf) time.Duration {
156 return time.Duration(0)
158 rate := conf.CPR * 1 << 10
160 rate /= EnclessEnlargeSize + conf.MTU
164 return time.Second / time.Duration(rate)
167 func newPeer(isClient bool, addr string, conn io.Writer, conf *PeerConf, key *[SSize]byte) *Peer {
169 timeout := conf.Timeout
171 cprCycle := cprCycleCalculate(conf)
172 noiseEnable := conf.Noise
177 timeout = timeout / TimeoutHeartbeat
180 bufSize := S20BS + 2*conf.MTU
182 bufSize += EnclessEnlargeSize
191 NoiseEnable: noiseEnable,
194 Encless: conf.Encless,
203 bufR: make([]byte, bufSize),
204 bufT: make([]byte, bufSize),
205 tagR: new([TagSize]byte),
206 tagT: new([TagSize]byte),
207 keyAuthR: new([SSize]byte),
208 nonceR: new([16]byte),
209 keyAuthT: new([SSize]byte),
210 nonceT: new([16]byte),
214 peer.noncesT = newNonces(peer.key, 1+2)
215 peer.noncesR = newNonces(peer.key, 0+2)
216 peer.noncesExpect = newNonces(peer.key, 0+2)
218 peer.noncesT = newNonces(peer.key, 0+2)
219 peer.noncesR = newNonces(peer.key, 1+2)
220 peer.noncesExpect = newNonces(peer.key, 1+2)
223 peer.NonceExpect = make([]byte, NonceSize)
224 nonce := <-peer.noncesExpect
225 copy(peer.NonceExpect, nonce[:])
228 peer.nonceBucketL = make(map[[NonceSize]byte]struct{}, NonceBucketSize)
229 for i = 0; i < NonceBucketSize; i++ {
230 nonce = <-peer.noncesR
231 peer.nonceBucketL[*nonce] = struct{}{}
233 peer.nonceBucketM = make(map[[NonceSize]byte]struct{}, NonceBucketSize)
234 for i = 0; i < NonceBucketSize; i++ {
235 nonce = <-peer.noncesR
236 peer.nonceBucketM[*nonce] = struct{}{}
238 peer.nonceBucketH = make(map[[NonceSize]byte]struct{}, NonceBucketSize)
239 for i = 0; i < NonceBucketSize; i++ {
240 nonce = <-peer.noncesR
241 peer.nonceBucketH[*nonce] = struct{}{}
247 // Process incoming Ethernet packet.
248 // ready channel is TAPListen's synchronization channel used to tell him
249 // that he is free to receive new packets. Encrypted and authenticated
250 // packets will be sent to remote Peer side immediately.
251 func (p *Peer) EthProcess(data []byte) {
252 if len(data) > p.MTU-1 { // 1 is for padding byte
253 log.Println("Padded data packet size", len(data)+1, "is bigger than MTU", p.MTU, p)
258 // Zero size is a heartbeat packet
261 p.bufT[S20BS+0] = PadByte
264 // Copy payload to our internal buffer and we are ready to
265 // accept the next one
266 copy(p.bufT[S20BS:], data)
267 p.bufT[S20BS+len(data)] = PadByte
268 p.BytesPayloadOut += uint64(len(data))
271 if p.NoiseEnable && !p.Encless {
272 p.frameT = p.bufT[S20BS : S20BS+p.MTU-TagSize]
273 } else if p.Encless {
274 p.frameT = p.bufT[S20BS : S20BS+p.MTU]
276 p.frameT = p.bufT[S20BS : S20BS+len(data)+1+NonceSize]
278 copy(p.frameT[len(p.frameT)-NonceSize:], (<-p.noncesT)[:])
280 copy(p.nonceT[8:], p.frameT[len(p.frameT)-NonceSize:])
283 out, err = EnclessEncode(p.key, p.nonceT, p.frameT[:len(p.frameT)-NonceSize])
287 out = append(out, p.frameT[len(p.frameT)-NonceSize:]...)
289 chacha20.XORKeyStream(
290 p.bufT[:S20BS+len(p.frameT)-NonceSize],
291 p.bufT[:S20BS+len(p.frameT)-NonceSize],
295 copy(p.keyAuthT[:], p.bufT[:SSize])
296 poly1305.Sum(p.tagT, p.frameT, p.keyAuthT)
297 atomic.AddUint64(&p.BytesOut, uint64(len(p.frameT)+TagSize))
298 out = append(p.tagT[:], p.frameT...)
305 func (p *Peer) PktProcess(data []byte, tap io.Writer, reorderable bool) bool {
306 if len(data) < MinPktLength {
309 if !p.Encless && len(data) > len(p.bufR)-S20BS {
314 copy(p.nonceR[8:], data[len(data)-NonceSize:])
317 out, err = EnclessDecode(p.key, p.nonceR, data[:len(data)-NonceSize])
324 for i := 0; i < SSize; i++ {
327 copy(p.bufR[S20BS:], data[TagSize:])
328 chacha20.XORKeyStream(
329 p.bufR[:S20BS+len(data)-TagSize-NonceSize],
330 p.bufR[:S20BS+len(data)-TagSize-NonceSize],
334 copy(p.keyAuthR[:], p.bufR[:SSize])
335 copy(p.tagR[:], data[:TagSize])
336 if !poly1305.Verify(p.tagR, data[TagSize:], p.keyAuthR) {
341 out = p.bufR[S20BS : S20BS+len(data)-TagSize-NonceSize]
345 copy(p.nonceRecv[:], data[len(data)-NonceSize:])
346 _, foundL := p.nonceBucketL[p.nonceRecv]
347 _, foundM := p.nonceBucketM[p.nonceRecv]
348 _, foundH := p.nonceBucketH[p.nonceRecv]
349 // If found is none of buckets: either it is too old,
350 // or too new (many packets were lost)
351 if !(foundL || foundM || foundH) {
358 delete(p.nonceBucketL, p.nonceRecv)
361 delete(p.nonceBucketM, p.nonceRecv)
364 delete(p.nonceBucketH, p.nonceRecv)
366 // If we are dealing with the latest bucket, create the new one
368 p.nonceBucketL, p.nonceBucketM = p.nonceBucketM, p.nonceBucketH
369 p.nonceBucketH = make(map[[NonceSize]byte]struct{})
370 var nonce *[NonceSize]byte
371 for i := 0; i < NonceBucketSize; i++ {
373 p.nonceBucketH[*nonce] = struct{}{}
377 if subtle.ConstantTimeCompare(data[len(data)-NonceSize:], p.NonceExpect) != 1 {
382 copy(p.NonceExpect, (<-p.noncesExpect)[:])
386 atomic.AddUint64(&p.BytesIn, uint64(len(data)))
387 p.LastPing = time.Now()
388 p.pktSizeR = bytes.LastIndexByte(out, PadByte)
389 if p.pktSizeR == -1 {
394 for i := p.pktSizeR + 1; i < len(out); i++ {
406 p.BytesPayloadIn += uint64(p.pktSizeR)
407 tap.Write(out[:p.pktSizeR])
412 func PeerTapProcessor(peer *Peer, tap *TAP, terminator chan struct{}) {
415 lastSent := time.Now()
416 heartbeat := time.NewTicker(peer.Timeout)
417 if peer.CPRCycle == time.Duration(0) {
425 if lastSent.Add(peer.Timeout).Before(now) {
429 case data = <-tap.Sink:
430 peer.EthProcess(data)
431 lastSent = time.Now()
441 case data = <-tap.Sink:
442 peer.EthProcess(data)
448 time.Sleep(peer.CPRCycle)