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/>.
31 "golang.org/x/crypto/blake2b"
32 "golang.org/x/crypto/poly1305"
33 "golang.org/x/crypto/salsa20"
39 TagSize = poly1305.TagSize
40 // S20BS is Salsa20'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 salsa20.XORKeyStream(macKey, make([]byte, 32), make([]byte, 8), 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
114 noncesR chan *[NonceSize]byte
115 nonceRecv [NonceSize]byte
116 nonceBucketL map[[NonceSize]byte]struct{}
117 nonceBucketM map[[NonceSize]byte]struct{}
118 nonceBucketH map[[NonceSize]byte]struct{}
121 NonceExpect []byte `json:"-"`
122 noncesExpect chan *[NonceSize]byte
125 BusyT sync.Mutex `json:"-"`
128 keyAuthT *[SSize]byte
130 noncesT chan *[NonceSize]byte
133 func (p *Peer) String() string {
134 return p.Id.String() + ":" + p.Addr
137 // Zero peer's memory state.
138 func (p *Peer) Zero() {
144 SliceZero(p.keyAuthR[:])
145 SliceZero(p.keyAuthT[:])
150 func cprCycleCalculate(conf *PeerConf) time.Duration {
152 return time.Duration(0)
154 rate := conf.CPR * 1 << 10
156 rate /= EnclessEnlargeSize + conf.MTU
160 return time.Second / time.Duration(rate)
163 func newPeer(isClient bool, addr string, conn io.Writer, conf *PeerConf, key *[SSize]byte) *Peer {
165 timeout := conf.Timeout
167 cprCycle := cprCycleCalculate(conf)
168 noiseEnable := conf.Noise
173 timeout = timeout / TimeoutHeartbeat
176 bufSize := S20BS + 2*conf.MTU
178 bufSize += EnclessEnlargeSize
187 NoiseEnable: noiseEnable,
190 Encless: conf.Encless,
199 bufR: make([]byte, bufSize),
200 bufT: make([]byte, bufSize),
201 tagR: new([TagSize]byte),
202 tagT: new([TagSize]byte),
203 keyAuthR: new([SSize]byte),
204 keyAuthT: new([SSize]byte),
208 peer.noncesT = newNonces(peer.key, 1+2)
209 peer.noncesR = newNonces(peer.key, 0+2)
210 peer.noncesExpect = newNonces(peer.key, 0+2)
212 peer.noncesT = newNonces(peer.key, 0+2)
213 peer.noncesR = newNonces(peer.key, 1+2)
214 peer.noncesExpect = newNonces(peer.key, 1+2)
217 peer.NonceExpect = make([]byte, NonceSize)
218 nonce := <-peer.noncesExpect
219 copy(peer.NonceExpect, nonce[:])
222 peer.nonceBucketL = make(map[[NonceSize]byte]struct{}, NonceBucketSize)
223 for i = 0; i < NonceBucketSize; i++ {
224 nonce = <-peer.noncesR
225 peer.nonceBucketL[*nonce] = struct{}{}
227 peer.nonceBucketM = make(map[[NonceSize]byte]struct{}, NonceBucketSize)
228 for i = 0; i < NonceBucketSize; i++ {
229 nonce = <-peer.noncesR
230 peer.nonceBucketM[*nonce] = struct{}{}
232 peer.nonceBucketH = make(map[[NonceSize]byte]struct{}, NonceBucketSize)
233 for i = 0; i < NonceBucketSize; i++ {
234 nonce = <-peer.noncesR
235 peer.nonceBucketH[*nonce] = struct{}{}
241 // Process incoming Ethernet packet.
242 // ready channel is TAPListen's synchronization channel used to tell him
243 // that he is free to receive new packets. Encrypted and authenticated
244 // packets will be sent to remote Peer side immediately.
245 func (p *Peer) EthProcess(data []byte) {
246 if len(data) > p.MTU-1 { // 1 is for padding byte
247 log.Println("Padded data packet size", len(data)+1, "is bigger than MTU", p.MTU, p)
252 // Zero size is a heartbeat packet
255 p.bufT[S20BS+0] = PadByte
258 // Copy payload to our internal buffer and we are ready to
259 // accept the next one
260 copy(p.bufT[S20BS:], data)
261 p.bufT[S20BS+len(data)] = PadByte
262 p.BytesPayloadOut += uint64(len(data))
265 if p.NoiseEnable && !p.Encless {
266 p.frameT = p.bufT[S20BS : S20BS+p.MTU-TagSize]
267 } else if p.Encless {
268 p.frameT = p.bufT[S20BS : S20BS+p.MTU]
270 p.frameT = p.bufT[S20BS : S20BS+len(data)+1+NonceSize]
272 copy(p.frameT[len(p.frameT)-NonceSize:], (<-p.noncesT)[:])
276 out, err = EnclessEncode(
278 p.frameT[len(p.frameT)-NonceSize:],
279 p.frameT[:len(p.frameT)-NonceSize],
284 out = append(out, p.frameT[len(p.frameT)-NonceSize:]...)
286 salsa20.XORKeyStream(
287 p.bufT[:S20BS+len(p.frameT)-NonceSize],
288 p.bufT[:S20BS+len(p.frameT)-NonceSize],
289 p.frameT[len(p.frameT)-NonceSize:],
292 copy(p.keyAuthT[:], p.bufT[:SSize])
293 poly1305.Sum(p.tagT, p.frameT, p.keyAuthT)
294 atomic.AddUint64(&p.BytesOut, uint64(len(p.frameT)+TagSize))
295 out = append(p.tagT[:], p.frameT...)
302 func (p *Peer) PktProcess(data []byte, tap io.Writer, reorderable bool) bool {
303 if len(data) < MinPktLength {
306 if !p.Encless && len(data) > len(p.bufR)-S20BS {
313 out, err = EnclessDecode(
315 data[len(data)-NonceSize:],
316 data[:len(data)-NonceSize],
324 for i := 0; i < SSize; i++ {
327 copy(p.bufR[S20BS:], data[TagSize:])
328 salsa20.XORKeyStream(
329 p.bufR[:S20BS+len(data)-TagSize-NonceSize],
330 p.bufR[:S20BS+len(data)-TagSize-NonceSize],
331 data[len(data)-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)