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/>.
28 "golang.org/x/crypto/poly1305"
29 "golang.org/x/crypto/salsa20"
30 "golang.org/x/crypto/xtea"
35 // S20BS is Salsa20's internal blocksize in bytes
37 // Maximal amount of bytes transfered with single key (4 GiB)
38 MaxBytesPerKey int64 = 1 << 32
39 // Size of packet's size mark in bytes
41 // Heartbeat rate, relative to Timeout
57 CPRCycle time.Duration `json:"-"`
59 // Cryptography related
60 Key *[SSize]byte `json:"-"`
62 NonceOur uint64 `json:"-"`
63 NonceRecv uint64 `json:"-"`
64 NonceCipher *xtea.Cipher `json:"-"`
67 Timeout time.Duration `json:"-"`
71 willSentCycle time.Time
73 // This variables are initialized only once to relief GC
75 tag *[poly1305.TagSize]byte
95 func (p *Peer) String() string {
96 return p.Id.String() + ":" + p.Addr.String()
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 // Create UDP listening goroutine.
183 // This function takes already listening UDP socket and a buffer where
184 // all UDP packet data will be saved, channel where information about
185 // remote address and number of written bytes are stored, and a channel
186 // used to tell that buffer is ready to be overwritten.
187 func ConnListen(conn *net.UDPConn) (chan UDPPkt, []byte, chan struct{}) {
188 buf := make([]byte, MTU)
189 sink := make(chan UDPPkt)
190 sinkReady := make(chan struct{})
191 go func(conn *net.UDPConn) {
193 var addr *net.UDPAddr
197 conn.SetReadDeadline(time.Now().Add(time.Second))
198 n, addr, err = conn.ReadFromUDP(buf)
200 // This is needed for ticking the timeouts counter outside
201 sink <- UDPPkt{nil, 0}
204 sink <- UDPPkt{addr, n}
207 sinkReady <- struct{}{}
208 return sink, buf, sinkReady
211 func newNonceCipher(key *[32]byte) *xtea.Cipher {
212 nonceKey := make([]byte, 16)
213 salsa20.XORKeyStream(
216 make([]byte, xtea.BlockSize),
219 ciph, err := xtea.NewCipher(nonceKey)
226 func cprCycleCalculate(rate int) time.Duration {
228 return time.Duration(0)
230 return time.Second / time.Duration(rate*(1<<10)/MTU)
233 func newPeer(addr *net.UDPAddr, conf *PeerConf, nonce int, key *[SSize]byte) *Peer {
235 timeout := conf.Timeout
236 cprCycle := cprCycleCalculate(conf.CPR)
237 noiseEnable := conf.NoiseEnable
242 timeout = timeout / TimeoutHeartbeat
250 NoiseEnable: noiseEnable,
253 Noncediff: conf.Noncediff,
254 NonceOur: uint64(conf.Noncediff + nonce),
255 NonceRecv: uint64(conf.Noncediff + 0),
257 NonceCipher: newNonceCipher(key),
258 buf: make([]byte, MTU+S20BS),
259 tag: new([poly1305.TagSize]byte),
260 keyAuth: new([SSize]byte),
261 nonce: make([]byte, NonceSize),
266 // Process incoming UDP packet.
267 // udpPkt is received data, related to the peer tap interface and
268 // ConnListen'es synchronization channel used to tell him that he is
269 // free to receive new packets. Authenticated and decrypted packets
270 // will be written to the interface immediately (except heartbeat ones).
271 func (p *Peer) UDPProcess(udpPkt []byte, tap io.Writer, ready chan struct{}) bool {
273 copy(p.buf, Emptiness)
274 copy(p.tag[:], udpPkt[size-poly1305.TagSize:])
275 copy(p.buf[S20BS:], udpPkt[NonceSize:size-poly1305.TagSize])
276 salsa20.XORKeyStream(
277 p.buf[:S20BS+size-poly1305.TagSize],
278 p.buf[:S20BS+size-poly1305.TagSize],
282 copy(p.keyAuth[:], p.buf[:SSize])
283 if !poly1305.Verify(p.tag, udpPkt[:size-poly1305.TagSize], p.keyAuth) {
288 p.NonceCipher.Decrypt(p.buf, udpPkt[:NonceSize])
289 p.nonceRecv, _ = binary.Uvarint(p.buf[:NonceSize])
290 if int(p.NonceRecv)-p.Noncediff >= 0 && int(p.nonceRecv) < int(p.NonceRecv)-p.Noncediff {
297 p.BytesIn += int64(size)
298 p.LastPing = time.Now()
299 p.NonceRecv = p.nonceRecv
300 p.pktSize, _ = binary.Uvarint(p.buf[S20BS : S20BS+PktSizeSize])
305 p.frame = p.buf[S20BS+PktSizeSize : S20BS+PktSizeSize+p.pktSize]
306 p.BytesPayloadIn += int64(p.pktSize)
311 type WriteToer interface {
312 WriteTo([]byte, net.Addr) (int, error)
315 // Process incoming Ethernet packet.
316 // ethPkt is received data, conn is our outgoing connection.
317 // ready channel is TAPListen's synchronization channel used to tell him
318 // that he is free to receive new packets. Encrypted and authenticated
319 // packets will be sent to remote Peer side immediately.
320 func (p *Peer) EthProcess(ethPkt []byte, conn WriteToer, ready chan struct{}) {
323 // If this heartbeat is necessary
324 if size == 0 && !p.LastSent.Add(p.Timeout).Before(now) {
327 copy(p.buf, Emptiness)
329 copy(p.buf[S20BS+PktSizeSize:], ethPkt)
331 binary.PutUvarint(p.buf[S20BS:S20BS+PktSizeSize], uint64(size))
332 p.BytesPayloadOut += int64(size)
338 copy(p.nonce, Emptiness)
339 binary.PutUvarint(p.nonce, p.NonceOur)
340 p.NonceCipher.Encrypt(p.nonce, p.nonce)
342 salsa20.XORKeyStream(p.buf, p.buf, p.nonce, p.Key)
343 copy(p.buf[S20BS-NonceSize:S20BS], p.nonce)
344 copy(p.keyAuth[:], p.buf[:SSize])
346 p.frame = p.buf[S20BS-NonceSize : S20BS+MTU-NonceSize-poly1305.TagSize]
348 p.frame = p.buf[S20BS-NonceSize : S20BS+PktSizeSize+size]
350 poly1305.Sum(p.tag, p.frame, p.keyAuth)
352 p.BytesOut += int64(len(p.frame) + poly1305.TagSize)
355 if p.CPRCycle != time.Duration(0) {
356 p.willSentCycle = p.LastSent.Add(p.CPRCycle)
357 if p.willSentCycle.After(now) {
358 time.Sleep(p.willSentCycle.Sub(now))
359 now = p.willSentCycle
363 if _, err := conn.WriteTo(append(p.frame, p.tag[:]...), p.Addr); err != nil {
364 log.Println("Error sending UDP", err)