2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2015 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/>.
26 "golang.org/x/crypto/poly1305"
27 "golang.org/x/crypto/salsa20"
28 "golang.org/x/crypto/xtea"
34 // S20BS is Salsa20's internal blocksize in bytes
36 // Maximal amount of bytes transfered with single key (4 GiB)
37 MaxBytesPerKey int64 = 1 << 32
38 // Size of packet's size mark in bytes
40 // Heartbeat rate, relative to Timeout
52 CPRCycle time.Duration `json:"-"`
54 // Cryptography related
55 Key *[SSize]byte `json:"-"`
56 NonceOur uint64 `json:"-"`
57 NonceRecv uint64 `json:"-"`
58 NonceCipher *xtea.Cipher `json:"-"`
59 nonceBucket0 map[uint64]struct{}
60 nonceBucket1 map[uint64]struct{}
65 Timeout time.Duration `json:"-"`
69 willSentCycle time.Time
71 // This variables are initialized only once to relief GC
73 tag *[poly1305.TagSize]byte
95 func (p *Peer) String() string {
96 return p.Id.String() + ":" + p.Addr
99 // Zero peer's memory state.
100 func (p *Peer) Zero() {
103 sliceZero(p.keyAuth[:])
110 Emptiness = make([]byte, 1<<14)
111 taps = make(map[string]*TAP)
114 // Create TAP listening goroutine.
115 // This function takes required TAP interface name, opens it and allocates
116 // a buffer where all frame data will be written, channel where information
117 // about number of read bytes is sent to, synchronization channel (external
118 // processes tell that read buffer can be used again) and possible channel
120 func TAPListen(ifaceName string, timeout time.Duration, cpr int) (*TAP, chan []byte, chan struct{}, chan struct{}, error) {
123 tap, exists := taps[ifaceName]
125 tap, err = NewTAP(ifaceName)
127 return nil, nil, nil, nil, err
129 taps[ifaceName] = tap
131 sink := make(chan []byte)
132 sinkReady := make(chan struct{})
133 sinkTerminate := make(chan struct{})
134 sinkSkip := make(chan struct{})
137 cprCycle := cprCycleCalculate(cpr)
138 if cprCycle != time.Duration(0) {
141 timeout = timeout / TimeoutHeartbeat
143 heartbeat := time.Tick(timeout)
148 case <-sinkTerminate:
151 go func() { sink <- make([]byte, 0) }()
155 tap.ready <- struct{}{}
161 go func() { sink <- make([]byte, 0) }()
162 goto HeartbeatCatched
163 case <-sinkTerminate:
165 case pkt = <-tap.sink:
174 if exists && tap.synced {
175 sinkSkip <- struct{}{}
177 sinkReady <- struct{}{}
179 return tap, sink, sinkReady, sinkTerminate, nil
182 func newNonceCipher(key *[32]byte) *xtea.Cipher {
183 nonceKey := make([]byte, 16)
184 salsa20.XORKeyStream(
187 make([]byte, xtea.BlockSize),
190 ciph, err := xtea.NewCipher(nonceKey)
197 func cprCycleCalculate(rate int) time.Duration {
199 return time.Duration(0)
201 return time.Second / time.Duration(rate*(1<<10)/MTU)
204 func newPeer(addr string, conn io.Writer, conf *PeerConf, nonce int, key *[SSize]byte) *Peer {
206 timeout := conf.Timeout
207 cprCycle := cprCycleCalculate(conf.CPR)
208 noiseEnable := conf.NoiseEnable
213 timeout = timeout / TimeoutHeartbeat
222 NoiseEnable: noiseEnable,
225 NonceOur: uint64(nonce),
226 NonceRecv: uint64(0),
227 nonceBucket0: make(map[uint64]struct{}, NonceBucketSize),
228 nonceBucket1: make(map[uint64]struct{}, NonceBucketSize),
230 NonceCipher: newNonceCipher(key),
231 buf: make([]byte, MTU+S20BS),
232 tag: new([poly1305.TagSize]byte),
233 keyAuth: new([SSize]byte),
234 nonce: make([]byte, NonceSize),
239 // Process incoming UDP packet.
240 // ConnListen'es synchronization channel used to tell him that he is
241 // free to receive new packets. Authenticated and decrypted packets
242 // will be written to the interface immediately (except heartbeat ones).
243 func (p *Peer) PktProcess(data []byte, tap io.Writer, ready chan struct{}) bool {
245 copy(p.buf, Emptiness)
246 copy(p.tag[:], data[p.size-poly1305.TagSize:])
247 copy(p.buf[S20BS:], data[NonceSize:p.size-poly1305.TagSize])
248 salsa20.XORKeyStream(
249 p.buf[:S20BS+p.size-poly1305.TagSize],
250 p.buf[:S20BS+p.size-poly1305.TagSize],
254 copy(p.keyAuth[:], p.buf[:SSize])
255 if !poly1305.Verify(p.tag, data[:p.size-poly1305.TagSize], p.keyAuth) {
261 // Check if received nonce is known to us in either of two buckets.
262 // If yes, then this is ignored duplicate.
263 // Check from the oldest bucket, as in most cases this will result
264 // in constant time check.
265 // If Bucket0 is filled, then it becomes Bucket1.
266 p.NonceCipher.Decrypt(p.buf, data[:NonceSize])
268 p.nonceRecv, _ = binary.Uvarint(p.buf[:NonceSize])
269 if _, p.nonceFound = p.nonceBucket1[p.NonceRecv]; p.nonceFound {
273 if _, p.nonceFound = p.nonceBucket0[p.NonceRecv]; p.nonceFound {
277 p.nonceBucket0[p.NonceRecv] = struct{}{}
279 if p.nonceBucketN == NonceBucketSize {
280 p.nonceBucket1 = p.nonceBucket0
281 p.nonceBucket0 = make(map[uint64]struct{}, NonceBucketSize)
286 p.BytesIn += int64(p.size)
287 p.LastPing = time.Now()
288 p.NonceRecv = p.nonceRecv
289 p.pktSize, _ = binary.Uvarint(p.buf[S20BS : S20BS+PktSizeSize])
294 p.frame = p.buf[S20BS+PktSizeSize : S20BS+PktSizeSize+p.pktSize]
295 p.BytesPayloadIn += int64(p.pktSize)
300 // Process incoming Ethernet packet.
301 // ready channel is TAPListen's synchronization channel used to tell him
302 // that he is free to receive new packets. Encrypted and authenticated
303 // packets will be sent to remote Peer side immediately.
304 func (p *Peer) EthProcess(data []byte, ready chan struct{}) {
307 // If this heartbeat is necessary
308 if p.size == 0 && !p.LastSent.Add(p.Timeout).Before(p.now) {
311 copy(p.buf, Emptiness)
313 copy(p.buf[S20BS+PktSizeSize:], data)
315 binary.PutUvarint(p.buf[S20BS:S20BS+PktSizeSize], uint64(p.size))
316 p.BytesPayloadOut += int64(p.size)
322 copy(p.nonce, Emptiness)
323 binary.PutUvarint(p.nonce, p.NonceOur)
324 p.NonceCipher.Encrypt(p.nonce, p.nonce)
326 salsa20.XORKeyStream(p.buf, p.buf, p.nonce, p.Key)
327 copy(p.buf[S20BS-NonceSize:S20BS], p.nonce)
328 copy(p.keyAuth[:], p.buf[:SSize])
330 p.frame = p.buf[S20BS-NonceSize : S20BS+MTU-NonceSize-poly1305.TagSize]
332 p.frame = p.buf[S20BS-NonceSize : S20BS+PktSizeSize+p.size]
334 poly1305.Sum(p.tag, p.frame, p.keyAuth)
336 p.BytesOut += int64(len(p.frame) + poly1305.TagSize)
339 if p.CPRCycle != time.Duration(0) {
340 p.willSentCycle = p.LastSent.Add(p.CPRCycle)
341 if p.willSentCycle.After(p.now) {
342 time.Sleep(p.willSentCycle.Sub(p.now))
343 p.now = p.willSentCycle
347 p.Conn.Write(append(p.frame, p.tag[:]...))