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"
36 // S20BS is Salsa20's internal blocksize in bytes
38 // Maximal amount of bytes transfered with single key (4 GiB)
39 MaxBytesPerKey int64 = 1 << 32
40 // Size of packet's size mark in bytes
42 // Heartbeat rate, relative to Timeout
54 Key *[KeySize]byte `json:"-"`
55 NonceOur uint64 `json:"-"`
56 NonceRecv uint64 `json:"-"`
57 NonceCipher *xtea.Cipher `json:"-"`
60 willSentCycle time.Time
62 tag *[poly1305.TagSize]byte
63 keyAuth *[KeySize]byte
80 func (p *Peer) String() string {
81 return p.Id.String() + ":" + p.Addr.String()
84 // Zero peer's memory state
85 func (p *Peer) Zero() {
88 sliceZero(p.keyAuth[:])
95 Emptiness = make([]byte, 1<<14)
96 taps = make(map[string]*TAP)
97 heartbeatPeriod time.Duration
100 func heartbeatPeriodGet() time.Duration {
101 if heartbeatPeriod == time.Duration(0) {
102 heartbeatPeriod = Timeout / TimeoutHeartbeat
104 return heartbeatPeriod
107 // Create TAP listening goroutine.
108 // This function takes required TAP interface name, opens it and allocates
109 // a buffer where all frame data will be written, channel where information
110 // about number of read bytes is sent to, synchronization channel (external
111 // processes tell that read buffer can be used again) and possible channel
113 func TAPListen(ifaceName string) (*TAP, chan []byte, chan struct{}, chan struct{}, error) {
116 tap, exists := taps[ifaceName]
118 tap, err = NewTAP(ifaceName)
120 return nil, nil, nil, nil, err
122 taps[ifaceName] = tap
124 sink := make(chan []byte)
125 sinkReady := make(chan struct{})
126 sinkTerminate := make(chan struct{})
127 sinkSkip := make(chan struct{})
130 heartbeat := time.Tick(heartbeatPeriodGet())
135 case <-sinkTerminate:
138 go func() { sink <- make([]byte, 0) }()
142 tap.ready <- struct{}{}
148 go func() { sink <- make([]byte, 0) }()
149 goto HeartbeatCatched
150 case <-sinkTerminate:
152 case pkt = <-tap.sink:
161 if exists && tap.synced {
162 sinkSkip <- struct{}{}
164 sinkReady <- struct{}{}
166 return tap, sink, sinkReady, sinkTerminate, nil
169 // Create UDP listening goroutine.
170 // This function takes already listening UDP socket and a buffer where
171 // all UDP packet data will be saved, channel where information about
172 // remote address and number of written bytes are stored, and a channel
173 // used to tell that buffer is ready to be overwritten.
174 func ConnListen(conn *net.UDPConn) (chan UDPPkt, []byte, chan struct{}) {
175 buf := make([]byte, MTU)
176 sink := make(chan UDPPkt)
177 sinkReady := make(chan struct{})
178 go func(conn *net.UDPConn) {
180 var addr *net.UDPAddr
184 conn.SetReadDeadline(time.Now().Add(time.Second))
185 n, addr, err = conn.ReadFromUDP(buf)
187 // This is needed for ticking the timeouts counter outside
188 sink <- UDPPkt{nil, 0}
191 sink <- UDPPkt{addr, n}
194 sinkReady <- struct{}{}
195 return sink, buf, sinkReady
198 func newNonceCipher(key *[KeySize]byte) *xtea.Cipher {
199 nonceKey := make([]byte, 16)
200 salsa20.XORKeyStream(
202 make([]byte, KeySize),
203 make([]byte, xtea.BlockSize),
206 ciph, err := xtea.NewCipher(nonceKey)
213 func newPeer(addr *net.UDPAddr, id PeerId, nonce int, key *[KeySize]byte) *Peer {
216 LastPing: time.Now(),
218 NonceOur: uint64(Noncediff + nonce),
219 NonceRecv: uint64(Noncediff + 0),
221 NonceCipher: newNonceCipher(key),
222 buf: make([]byte, MTU+S20BS),
223 tag: new([poly1305.TagSize]byte),
224 keyAuth: new([KeySize]byte),
225 nonce: make([]byte, NonceSize),
230 // Process incoming UDP packet.
231 // udpPkt is received data, related to the peer tap interface and
232 // ConnListen'es synchronization channel used to tell him that he is
233 // free to receive new packets. Authenticated and decrypted packets
234 // will be written to the interface immediately (except heartbeat ones).
235 func (p *Peer) UDPProcess(udpPkt []byte, tap io.Writer, ready chan struct{}) bool {
237 copy(p.buf, Emptiness)
238 copy(p.tag[:], udpPkt[size-poly1305.TagSize:])
239 copy(p.buf[S20BS:], udpPkt[NonceSize:size-poly1305.TagSize])
240 salsa20.XORKeyStream(
241 p.buf[:S20BS+size-poly1305.TagSize],
242 p.buf[:S20BS+size-poly1305.TagSize],
246 copy(p.keyAuth[:], p.buf[:KeySize])
247 if !poly1305.Verify(p.tag, udpPkt[:size-poly1305.TagSize], p.keyAuth) {
252 p.NonceCipher.Decrypt(p.buf, udpPkt[:NonceSize])
253 p.nonceRecv, _ = binary.Uvarint(p.buf[:NonceSize])
254 if int(p.NonceRecv)-Noncediff >= 0 && int(p.nonceRecv) < int(p.NonceRecv)-Noncediff {
261 p.BytesIn += int64(size)
262 p.LastPing = time.Now()
263 p.NonceRecv = p.nonceRecv
264 p.pktSize, _ = binary.Uvarint(p.buf[S20BS : S20BS+PktSizeSize])
269 p.frame = p.buf[S20BS+PktSizeSize : S20BS+PktSizeSize+p.pktSize]
270 p.BytesPayloadIn += int64(p.pktSize)
275 type WriteToer interface {
276 WriteTo([]byte, net.Addr) (int, error)
279 // Process incoming Ethernet packet.
280 // ethPkt is received data, conn is our outgoing connection.
281 // ready channel is TAPListen's synchronization channel used to tell him
282 // that he is free to receive new packets. Encrypted and authenticated
283 // packets will be sent to remote Peer side immediately.
284 func (p *Peer) EthProcess(ethPkt []byte, conn WriteToer, ready chan struct{}) {
287 // If this heartbeat is necessary
288 if size == 0 && !p.LastSent.Add(heartbeatPeriodGet()).Before(now) {
291 copy(p.buf, Emptiness)
293 copy(p.buf[S20BS+PktSizeSize:], ethPkt)
295 binary.PutUvarint(p.buf[S20BS:S20BS+PktSizeSize], uint64(size))
296 p.BytesPayloadOut += int64(size)
302 copy(p.nonce, Emptiness)
303 binary.PutUvarint(p.nonce, p.NonceOur)
304 p.NonceCipher.Encrypt(p.nonce, p.nonce)
306 salsa20.XORKeyStream(p.buf, p.buf, p.nonce, p.Key)
307 copy(p.buf[S20BS-NonceSize:S20BS], p.nonce)
308 copy(p.keyAuth[:], p.buf[:KeySize])
310 p.frame = p.buf[S20BS-NonceSize : S20BS+MTU-NonceSize-poly1305.TagSize]
312 p.frame = p.buf[S20BS-NonceSize : S20BS+PktSizeSize+size]
314 poly1305.Sum(p.tag, p.frame, p.keyAuth)
316 p.BytesOut += int64(len(p.frame) + poly1305.TagSize)
320 p.willSentCycle = p.LastSent.Add(cprCycle)
321 if p.willSentCycle.After(now) {
322 time.Sleep(p.willSentCycle.Sub(now))
323 now = p.willSentCycle
327 if _, err := conn.WriteTo(append(p.frame, p.tag[:]...), p.Addr); err != nil {
328 log.Println("Error sending UDP", err)