]> Cypherpunks.ru repositories - govpn.git/blob - transport.go
Texinfo documentation, client ID, simultaneous clients
[govpn.git] / transport.go
1 /*
2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2015 Sergey Matveev <stargrave@stargrave.org>
4
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.
9
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.
14
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/>.
17 */
18
19 package govpn
20
21 import (
22         "crypto/subtle"
23         "encoding/binary"
24         "log"
25         "net"
26         "time"
27
28         "golang.org/x/crypto/poly1305"
29         "golang.org/x/crypto/salsa20"
30         "golang.org/x/crypto/xtea"
31 )
32
33 const (
34         NonceSize = 8
35         KeySize   = 32
36         // S20BS is Salsa20's internal blocksize in bytes
37         S20BS         = 64
38         HeartbeatSize = 12
39         // Maximal amount of bytes transfered with single key (4 GiB)
40         MaxBytesPerKey = 4294967296
41 )
42
43 type UDPPkt struct {
44         Addr *net.UDPAddr
45         Size int
46 }
47
48 type Peer struct {
49         Addr        *net.UDPAddr
50         Id          PeerId
51         Key         *[KeySize]byte // encryption key
52         NonceOur    uint64         // nonce for our messages
53         NonceRecv   uint64         // latest received nonce from remote peer
54         NonceCipher *xtea.Cipher   // nonce cipher
55         LastPing    time.Time
56         LastSent    time.Time
57         buf         []byte
58         tag         *[poly1305.TagSize]byte
59         keyAuth     *[KeySize]byte
60         nonceRecv   uint64
61         Bytes       int
62         frame       []byte
63         nonce       []byte
64 }
65
66 func (p *Peer) String() string {
67         return p.Id.String() + ":" + p.Addr.String()
68 }
69
70 var (
71         HeartbeatMark   = []byte("\x00\x00\x00HEARTBEAT")
72         Emptiness       = make([]byte, KeySize)
73         taps            = make(map[string]*TAP)
74         heartbeatPeriod *time.Duration
75 )
76
77 func heartbeatPeriodGet() time.Duration {
78         if heartbeatPeriod == nil {
79                 period := time.Second * time.Duration(Timeout/4)
80                 heartbeatPeriod = &period
81         }
82         return *heartbeatPeriod
83 }
84
85 // Create TAP listening goroutine.
86 // This function takes required TAP interface name, opens it and allocates
87 // a buffer where all frame data will be written, channel where information
88 // about number of read bytes is sent to, synchronization channel (external
89 // processes tell that read buffer can be used again) and possible channel
90 // opening error.
91 func TAPListen(ifaceName string) (*TAP, chan []byte, chan struct{}, chan struct{}, error) {
92         var tap *TAP
93         var err error
94         tap, exists := taps[ifaceName]
95         if !exists {
96                 tap, err = NewTAP(ifaceName)
97                 if err != nil {
98                         return nil, nil, nil, nil, err
99                 }
100                 taps[ifaceName] = tap
101         }
102         sink := make(chan []byte)
103         sinkReady := make(chan struct{})
104         sinkTerminate := make(chan struct{})
105
106         go func() {
107                 heartbeat := time.Tick(heartbeatPeriodGet())
108                 var pkt []byte
109         ListenCycle:
110                 for {
111                         select {
112                         case <-sinkTerminate:
113                                 break ListenCycle
114                         case <-heartbeat:
115                                 sink <- make([]byte, 0)
116                                 continue
117                         case <-sinkReady:
118                                 if exists {
119                                         exists = false
120                                         break
121                                 }
122                                 tap.ready <- struct{}{}
123                         }
124                 HeartbeatCatched:
125                         select {
126                         case <-heartbeat:
127                                 sink <- make([]byte, 0)
128                                 goto HeartbeatCatched
129                         case <-sinkTerminate:
130                                 break ListenCycle
131                         case pkt = <-tap.sink:
132                                 sink <- pkt
133                         }
134                 }
135                 close(sink)
136         }()
137         sinkReady <- struct{}{}
138         return tap, sink, sinkReady, sinkTerminate, nil
139 }
140
141 // Create UDP listening goroutine.
142 // This function takes already listening UDP socket and a buffer where
143 // all UDP packet data will be saved, channel where information about
144 // remote address and number of written bytes are stored, and a channel
145 // used to tell that buffer is ready to be overwritten.
146 func ConnListen(conn *net.UDPConn) (chan *UDPPkt, []byte, chan struct{}) {
147         buf := make([]byte, MTU)
148         sink := make(chan *UDPPkt)
149         sinkReady := make(chan struct{})
150         go func(conn *net.UDPConn) {
151                 var n int
152                 var addr *net.UDPAddr
153                 var err error
154                 for {
155                         <-sinkReady
156                         conn.SetReadDeadline(time.Now().Add(time.Second))
157                         n, addr, err = conn.ReadFromUDP(buf)
158                         if err != nil {
159                                 // This is needed for ticking the timeouts counter outside
160                                 sink <- nil
161                                 continue
162                         }
163                         sink <- &UDPPkt{addr, n}
164                 }
165         }(conn)
166         sinkReady <- struct{}{}
167         return sink, buf, sinkReady
168 }
169
170 func newNonceCipher(key *[KeySize]byte) *xtea.Cipher {
171         nonceKey := make([]byte, 16)
172         salsa20.XORKeyStream(nonceKey, make([]byte, KeySize), make([]byte, xtea.BlockSize), key)
173         ciph, err := xtea.NewCipher(nonceKey)
174         if err != nil {
175                 panic(err)
176         }
177         return ciph
178 }
179
180 func newPeer(addr *net.UDPAddr, id PeerId, nonce int, key *[KeySize]byte) *Peer {
181         peer := Peer{
182                 Addr:        addr,
183                 LastPing:    time.Now(),
184                 Id:          id,
185                 NonceOur:    uint64(Noncediff + nonce),
186                 NonceRecv:   uint64(Noncediff + 0),
187                 Key:         key,
188                 NonceCipher: newNonceCipher(key),
189                 Bytes:       0,
190                 buf:         make([]byte, MTU+S20BS),
191                 tag:         new([poly1305.TagSize]byte),
192                 keyAuth:     new([KeySize]byte),
193                 nonce:       make([]byte, NonceSize),
194         }
195         return &peer
196 }
197
198 // Process incoming UDP packet.
199 // udpPkt is received data, related to the peer tap interface and
200 // ConnListen'es synchronization channel used to tell him that he is
201 // free to receive new packets. Authenticated and decrypted packets
202 // will be written to the interface immediately (except heartbeat ones).
203 func (p *Peer) UDPProcess(udpPkt []byte, tap *TAP, ready chan struct{}) bool {
204         size := len(udpPkt)
205         copy(p.buf[:KeySize], Emptiness)
206         copy(p.tag[:], udpPkt[size-poly1305.TagSize:])
207         copy(p.buf[S20BS:], udpPkt[NonceSize:size-poly1305.TagSize])
208         salsa20.XORKeyStream(
209                 p.buf[:S20BS+size-poly1305.TagSize],
210                 p.buf[:S20BS+size-poly1305.TagSize],
211                 udpPkt[:NonceSize],
212                 p.Key,
213         )
214         copy(p.keyAuth[:], p.buf[:KeySize])
215         if !poly1305.Verify(p.tag, udpPkt[:size-poly1305.TagSize], p.keyAuth) {
216                 ready <- struct{}{}
217                 return false
218         }
219         p.NonceCipher.Decrypt(p.buf, udpPkt[:NonceSize])
220         p.nonceRecv, _ = binary.Uvarint(p.buf[:NonceSize])
221         if int(p.NonceRecv)-Noncediff >= 0 && int(p.nonceRecv) < int(p.NonceRecv)-Noncediff {
222                 ready <- struct{}{}
223                 return false
224         }
225         ready <- struct{}{}
226         p.LastPing = time.Now()
227         p.NonceRecv = p.nonceRecv
228         p.frame = p.buf[S20BS : S20BS+size-NonceSize-poly1305.TagSize]
229         p.Bytes += len(p.frame)
230         if subtle.ConstantTimeCompare(p.frame[:HeartbeatSize], HeartbeatMark) == 1 {
231                 return true
232         }
233         tap.Write(p.frame)
234         return true
235 }
236
237 // Process incoming Ethernet packet.
238 // ethPkt is received data, conn is our outgoing connection.
239 // ready channel is TAPListen's synchronization channel used to tell him
240 // that he is free to receive new packets. Encrypted and authenticated
241 // packets will be sent to remote Peer side immediately.
242 func (p *Peer) EthProcess(ethPkt []byte, conn *net.UDPConn, ready chan struct{}) {
243         now := time.Now()
244         size := len(ethPkt)
245         // If this heartbeat is necessary
246         if size == 0 && !p.LastSent.Add(heartbeatPeriodGet()).Before(now) {
247                 return
248         }
249         copy(p.buf[:KeySize], Emptiness)
250         if size > 0 {
251                 copy(p.buf[S20BS:], ethPkt)
252                 ready <- struct{}{}
253         } else {
254                 copy(p.buf[S20BS:], HeartbeatMark)
255                 size = HeartbeatSize
256         }
257
258         p.NonceOur = p.NonceOur + 2
259         copy(p.nonce, Emptiness)
260         binary.PutUvarint(p.nonce, p.NonceOur)
261         p.NonceCipher.Encrypt(p.nonce, p.nonce)
262
263         salsa20.XORKeyStream(p.buf, p.buf, p.nonce, p.Key)
264         copy(p.buf[S20BS-NonceSize:S20BS], p.nonce)
265         copy(p.keyAuth[:], p.buf[:KeySize])
266         p.frame = p.buf[S20BS-NonceSize : S20BS+size]
267         poly1305.Sum(p.tag, p.frame, p.keyAuth)
268
269         p.Bytes += len(p.frame)
270         p.LastSent = now
271         if _, err := conn.WriteTo(append(p.frame, p.tag[:]...), p.Addr); err != nil {
272                 log.Println("Error sending UDP", err)
273         }
274 }