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
44 type RemoteConn interface {
46 // Can incoming packets be reordered
58 CPRCycle time.Duration `json:"-"`
60 // Cryptography related
61 Key *[SSize]byte `json:"-"`
62 NonceOur uint64 `json:"-"`
63 NonceRecv uint64 `json:"-"`
64 NonceCipher *xtea.Cipher `json:"-"`
65 nonceExpect uint64 `json:"-"`
66 nonceBucket0 map[uint64]struct{}
67 nonceBucket1 map[uint64]struct{}
72 Timeout time.Duration `json:"-"`
76 willSentCycle time.Time
78 // This variables are initialized only once to relief GC
80 tag *[poly1305.TagSize]byte
102 func (p *Peer) String() string {
103 return p.Id.String() + ":" + p.Addr
106 // Zero peer's memory state.
107 func (p *Peer) Zero() {
110 sliceZero(p.keyAuth[:])
117 Emptiness = make([]byte, 1<<14)
118 taps = make(map[string]*TAP)
121 // Create TAP listening goroutine.
122 // This function takes required TAP interface name, opens it and allocates
123 // a buffer where all frame data will be written, channel where information
124 // about number of read bytes is sent to, synchronization channel (external
125 // processes tell that read buffer can be used again) and possible channel
127 func TAPListen(ifaceName string, timeout time.Duration, cpr int) (*TAP, chan []byte, chan struct{}, chan struct{}, error) {
130 tap, exists := taps[ifaceName]
132 tap, err = NewTAP(ifaceName)
134 return nil, nil, nil, nil, err
136 taps[ifaceName] = tap
138 sink := make(chan []byte)
139 sinkReady := make(chan struct{})
140 sinkTerminate := make(chan struct{})
141 sinkSkip := make(chan struct{})
144 cprCycle := cprCycleCalculate(cpr)
145 if cprCycle != time.Duration(0) {
148 timeout = timeout / TimeoutHeartbeat
150 heartbeat := time.Tick(timeout)
155 case <-sinkTerminate:
158 go func() { sink <- make([]byte, 0) }()
162 tap.ready <- struct{}{}
168 go func() { sink <- make([]byte, 0) }()
169 goto HeartbeatCatched
170 case <-sinkTerminate:
172 case pkt = <-tap.sink:
181 if exists && tap.synced {
182 sinkSkip <- struct{}{}
184 sinkReady <- struct{}{}
186 return tap, sink, sinkReady, sinkTerminate, nil
189 func newNonceCipher(key *[32]byte) *xtea.Cipher {
190 nonceKey := make([]byte, 16)
191 salsa20.XORKeyStream(
194 make([]byte, xtea.BlockSize),
197 ciph, err := xtea.NewCipher(nonceKey)
204 func cprCycleCalculate(rate int) time.Duration {
206 return time.Duration(0)
208 return time.Second / time.Duration(rate*(1<<10)/MTU)
211 func newPeer(isClient bool, addr string, conn RemoteConn, conf *PeerConf, key *[SSize]byte) *Peer {
213 timeout := conf.Timeout
214 cprCycle := cprCycleCalculate(conf.CPR)
215 noiseEnable := conf.NoiseEnable
220 timeout = timeout / TimeoutHeartbeat
229 NoiseEnable: noiseEnable,
234 NonceCipher: newNonceCipher(key),
235 buf: make([]byte, MTU+S20BS),
236 tag: new([poly1305.TagSize]byte),
237 keyAuth: new([SSize]byte),
238 nonce: make([]byte, NonceSize),
242 peer.nonceExpect = 0 + 2
245 peer.nonceExpect = 1 + 2
247 if conn.Reorderable() {
248 peer.nonceBucket0 = make(map[uint64]struct{}, NonceBucketSize)
249 peer.nonceBucket1 = make(map[uint64]struct{}, NonceBucketSize)
254 // Process incoming UDP packet.
255 // ConnListen'es synchronization channel used to tell him that he is
256 // free to receive new packets. Authenticated and decrypted packets
257 // will be written to the interface immediately (except heartbeat ones).
258 func (p *Peer) PktProcess(data []byte, tap io.Writer, ready chan struct{}) bool {
260 copy(p.buf, Emptiness)
261 copy(p.tag[:], data[p.size-poly1305.TagSize:])
262 copy(p.buf[S20BS:], data[NonceSize:p.size-poly1305.TagSize])
263 salsa20.XORKeyStream(
264 p.buf[:S20BS+p.size-poly1305.TagSize],
265 p.buf[:S20BS+p.size-poly1305.TagSize],
269 copy(p.keyAuth[:], p.buf[:SSize])
270 if !poly1305.Verify(p.tag, data[:p.size-poly1305.TagSize], p.keyAuth) {
276 // Check if received nonce is known to us in either of two buckets.
277 // If yes, then this is ignored duplicate.
278 // Check from the oldest bucket, as in most cases this will result
279 // in constant time check.
280 // If Bucket0 is filled, then it becomes Bucket1.
281 p.NonceCipher.Decrypt(p.buf, data[:NonceSize])
284 p.nonceRecv, _ = binary.Uvarint(p.buf[:NonceSize])
285 if p.Conn.Reorderable() {
286 if _, p.nonceFound = p.nonceBucket1[p.NonceRecv]; p.nonceFound {
290 if _, p.nonceFound = p.nonceBucket0[p.NonceRecv]; p.nonceFound {
294 p.nonceBucket0[p.NonceRecv] = struct{}{}
296 if p.nonceBucketN == NonceBucketSize {
297 p.nonceBucket1 = p.nonceBucket0
298 p.nonceBucket0 = make(map[uint64]struct{}, NonceBucketSize)
302 if p.nonceRecv != p.nonceExpect {
310 p.BytesIn += int64(p.size)
311 p.LastPing = time.Now()
312 p.NonceRecv = p.nonceRecv
313 p.pktSize, _ = binary.Uvarint(p.buf[S20BS : S20BS+PktSizeSize])
318 p.frame = p.buf[S20BS+PktSizeSize : S20BS+PktSizeSize+p.pktSize]
319 p.BytesPayloadIn += int64(p.pktSize)
324 // Process incoming Ethernet packet.
325 // ready channel is TAPListen's synchronization channel used to tell him
326 // that he is free to receive new packets. Encrypted and authenticated
327 // packets will be sent to remote Peer side immediately.
328 func (p *Peer) EthProcess(data []byte, ready chan struct{}) {
331 // If this heartbeat is necessary
332 if p.size == 0 && !p.LastSent.Add(p.Timeout).Before(p.now) {
335 copy(p.buf, Emptiness)
337 copy(p.buf[S20BS+PktSizeSize:], data)
339 binary.PutUvarint(p.buf[S20BS:S20BS+PktSizeSize], uint64(p.size))
340 p.BytesPayloadOut += int64(p.size)
346 copy(p.nonce, Emptiness)
347 binary.PutUvarint(p.nonce, p.NonceOur)
348 p.NonceCipher.Encrypt(p.nonce, p.nonce)
350 salsa20.XORKeyStream(p.buf, p.buf, p.nonce, p.Key)
351 copy(p.buf[S20BS-NonceSize:S20BS], p.nonce)
352 copy(p.keyAuth[:], p.buf[:SSize])
354 p.frame = p.buf[S20BS-NonceSize : S20BS+MTU-NonceSize-poly1305.TagSize]
356 p.frame = p.buf[S20BS-NonceSize : S20BS+PktSizeSize+p.size]
358 poly1305.Sum(p.tag, p.frame, p.keyAuth)
360 p.BytesOut += int64(len(p.frame) + poly1305.TagSize)
363 if p.CPRCycle != time.Duration(0) {
364 p.willSentCycle = p.LastSent.Add(p.CPRCycle)
365 if p.willSentCycle.After(p.now) {
366 time.Sleep(p.willSentCycle.Sub(p.now))
367 p.now = p.willSentCycle
371 p.Conn.Write(append(p.frame, p.tag[:]...))