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
52 Key *[KeySize]byte `json:"-"`
53 NonceOur uint64 `json:"-"`
54 NonceRecv uint64 `json:"-"`
55 NonceCipher *xtea.Cipher `json:"-"`
59 tag *[poly1305.TagSize]byte
60 keyAuth *[KeySize]byte
75 func (p *Peer) String() string {
76 return p.Id.String() + ":" + p.Addr.String()
79 // Zero peer's memory state
80 func (p *Peer) Zero() {
83 sliceZero(p.keyAuth[:])
90 Emptiness = make([]byte, 1<<16)
91 taps = make(map[string]*TAP)
92 heartbeatPeriod *time.Duration
95 func heartbeatPeriodGet() time.Duration {
96 if heartbeatPeriod == nil {
97 period := time.Second * time.Duration(Timeout/4)
98 heartbeatPeriod = &period
100 return *heartbeatPeriod
103 // Create TAP listening goroutine.
104 // This function takes required TAP interface name, opens it and allocates
105 // a buffer where all frame data will be written, channel where information
106 // about number of read bytes is sent to, synchronization channel (external
107 // processes tell that read buffer can be used again) and possible channel
109 func TAPListen(ifaceName string) (*TAP, chan []byte, chan struct{}, chan struct{}, error) {
112 tap, exists := taps[ifaceName]
114 tap, err = NewTAP(ifaceName)
116 return nil, nil, nil, nil, err
118 taps[ifaceName] = tap
120 sink := make(chan []byte)
121 sinkReady := make(chan struct{})
122 sinkTerminate := make(chan struct{})
123 sinkSkip := make(chan struct{})
126 heartbeat := time.Tick(heartbeatPeriodGet())
131 case <-sinkTerminate:
134 go func() { sink <- make([]byte, 0) }()
138 tap.ready <- struct{}{}
144 go func() { sink <- make([]byte, 0) }()
145 goto HeartbeatCatched
146 case <-sinkTerminate:
148 case pkt = <-tap.sink:
157 if exists && tap.synced {
158 sinkSkip <- struct{}{}
160 sinkReady <- struct{}{}
162 return tap, sink, sinkReady, sinkTerminate, nil
165 // Create UDP listening goroutine.
166 // This function takes already listening UDP socket and a buffer where
167 // all UDP packet data will be saved, channel where information about
168 // remote address and number of written bytes are stored, and a channel
169 // used to tell that buffer is ready to be overwritten.
170 func ConnListen(conn *net.UDPConn) (chan UDPPkt, []byte, chan struct{}) {
171 buf := make([]byte, MTU)
172 sink := make(chan UDPPkt)
173 sinkReady := make(chan struct{})
174 go func(conn *net.UDPConn) {
176 var addr *net.UDPAddr
180 conn.SetReadDeadline(time.Now().Add(time.Second))
181 n, addr, err = conn.ReadFromUDP(buf)
183 // This is needed for ticking the timeouts counter outside
184 sink <- UDPPkt{nil, 0}
187 sink <- UDPPkt{addr, n}
190 sinkReady <- struct{}{}
191 return sink, buf, sinkReady
194 func newNonceCipher(key *[KeySize]byte) *xtea.Cipher {
195 nonceKey := make([]byte, 16)
196 salsa20.XORKeyStream(
198 make([]byte, KeySize),
199 make([]byte, xtea.BlockSize),
202 ciph, err := xtea.NewCipher(nonceKey)
209 func newPeer(addr *net.UDPAddr, id PeerId, nonce int, key *[KeySize]byte) *Peer {
212 LastPing: time.Now(),
214 NonceOur: uint64(Noncediff + nonce),
215 NonceRecv: uint64(Noncediff + 0),
217 NonceCipher: newNonceCipher(key),
218 buf: make([]byte, MTU+S20BS),
219 tag: new([poly1305.TagSize]byte),
220 keyAuth: new([KeySize]byte),
221 nonce: make([]byte, NonceSize),
226 // Process incoming UDP packet.
227 // udpPkt is received data, related to the peer tap interface and
228 // ConnListen'es synchronization channel used to tell him that he is
229 // free to receive new packets. Authenticated and decrypted packets
230 // will be written to the interface immediately (except heartbeat ones).
231 func (p *Peer) UDPProcess(udpPkt []byte, tap io.Writer, ready chan struct{}) bool {
233 copy(p.buf, Emptiness)
234 copy(p.tag[:], udpPkt[size-poly1305.TagSize:])
235 copy(p.buf[S20BS:], udpPkt[NonceSize:size-poly1305.TagSize])
236 salsa20.XORKeyStream(
237 p.buf[:S20BS+size-poly1305.TagSize],
238 p.buf[:S20BS+size-poly1305.TagSize],
242 copy(p.keyAuth[:], p.buf[:KeySize])
243 if !poly1305.Verify(p.tag, udpPkt[:size-poly1305.TagSize], p.keyAuth) {
248 p.NonceCipher.Decrypt(p.buf, udpPkt[:NonceSize])
249 p.nonceRecv, _ = binary.Uvarint(p.buf[:NonceSize])
250 if int(p.NonceRecv)-Noncediff >= 0 && int(p.nonceRecv) < int(p.NonceRecv)-Noncediff {
256 p.LastPing = time.Now()
257 p.NonceRecv = p.nonceRecv
258 p.pktSize, _ = binary.Uvarint(p.buf[S20BS : S20BS+PktSizeSize])
263 p.frame = p.buf[S20BS+PktSizeSize : S20BS+PktSizeSize+p.pktSize]
264 p.BytesIn += int64(p.pktSize)
270 type WriteToer interface {
271 WriteTo([]byte, net.Addr) (int, error)
274 // Process incoming Ethernet packet.
275 // ethPkt is received data, conn is our outgoing connection.
276 // ready channel is TAPListen's synchronization channel used to tell him
277 // that he is free to receive new packets. Encrypted and authenticated
278 // packets will be sent to remote Peer side immediately.
279 func (p *Peer) EthProcess(ethPkt []byte, conn WriteToer, ready chan struct{}) {
282 // If this heartbeat is necessary
283 if size == 0 && !p.LastSent.Add(heartbeatPeriodGet()).Before(now) {
286 copy(p.buf, Emptiness)
288 copy(p.buf[S20BS+PktSizeSize:], ethPkt)
290 binary.PutUvarint(p.buf[S20BS:S20BS+PktSizeSize], uint64(size))
291 p.BytesOut += int64(size)
296 p.NonceOur = p.NonceOur + 2
297 copy(p.nonce, Emptiness)
298 binary.PutUvarint(p.nonce, p.NonceOur)
299 p.NonceCipher.Encrypt(p.nonce, p.nonce)
301 salsa20.XORKeyStream(p.buf, p.buf, p.nonce, p.Key)
302 copy(p.buf[S20BS-NonceSize:S20BS], p.nonce)
303 copy(p.keyAuth[:], p.buf[:KeySize])
305 p.frame = p.buf[S20BS-NonceSize : S20BS+MTU-NonceSize-poly1305.TagSize]
307 p.frame = p.buf[S20BS-NonceSize : S20BS+PktSizeSize+size]
309 poly1305.Sum(p.tag, p.frame, p.keyAuth)
313 if _, err := conn.WriteTo(append(p.frame, p.tag[:]...), p.Addr); err != nil {
314 log.Println("Error sending UDP", err)