]> Cypherpunks.ru repositories - govpn.git/blob - transport.go
Keep TAP listener state and skip sinkReady step if necessary
[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         sinkSkip := make(chan struct{})
106
107         go func() {
108                 heartbeat := time.Tick(heartbeatPeriodGet())
109                 var pkt []byte
110         ListenCycle:
111                 for {
112                         select {
113                         case <-sinkTerminate:
114                                 break ListenCycle
115                         case <-heartbeat:
116                                 go func() { sink <- make([]byte, 0) }()
117                                 continue
118                         case <-sinkSkip:
119                         case <-sinkReady:
120                                 tap.ready <- struct{}{}
121                                 tap.synced = true
122                         }
123                 HeartbeatCatched:
124                         select {
125                         case <-heartbeat:
126                                 go func() { sink <- make([]byte, 0) }()
127                                 goto HeartbeatCatched
128                         case <-sinkTerminate:
129                                 break ListenCycle
130                         case pkt = <-tap.sink:
131                                 tap.synced = false
132                                 sink <- pkt
133                         }
134                 }
135                 close(sink)
136                 close(sinkReady)
137                 close(sinkTerminate)
138         }()
139         if exists && tap.synced {
140                 sinkSkip <- struct{}{}
141         } else {
142                 sinkReady <- struct{}{}
143         }
144         return tap, sink, sinkReady, sinkTerminate, nil
145 }
146
147 // Create UDP listening goroutine.
148 // This function takes already listening UDP socket and a buffer where
149 // all UDP packet data will be saved, channel where information about
150 // remote address and number of written bytes are stored, and a channel
151 // used to tell that buffer is ready to be overwritten.
152 func ConnListen(conn *net.UDPConn) (chan *UDPPkt, []byte, chan struct{}) {
153         buf := make([]byte, MTU)
154         sink := make(chan *UDPPkt)
155         sinkReady := make(chan struct{})
156         go func(conn *net.UDPConn) {
157                 var n int
158                 var addr *net.UDPAddr
159                 var err error
160                 for {
161                         <-sinkReady
162                         conn.SetReadDeadline(time.Now().Add(time.Second))
163                         n, addr, err = conn.ReadFromUDP(buf)
164                         if err != nil {
165                                 // This is needed for ticking the timeouts counter outside
166                                 sink <- nil
167                                 continue
168                         }
169                         sink <- &UDPPkt{addr, n}
170                 }
171         }(conn)
172         sinkReady <- struct{}{}
173         return sink, buf, sinkReady
174 }
175
176 func newNonceCipher(key *[KeySize]byte) *xtea.Cipher {
177         nonceKey := make([]byte, 16)
178         salsa20.XORKeyStream(nonceKey, make([]byte, KeySize), make([]byte, xtea.BlockSize), key)
179         ciph, err := xtea.NewCipher(nonceKey)
180         if err != nil {
181                 panic(err)
182         }
183         return ciph
184 }
185
186 func newPeer(addr *net.UDPAddr, id PeerId, nonce int, key *[KeySize]byte) *Peer {
187         peer := Peer{
188                 Addr:        addr,
189                 LastPing:    time.Now(),
190                 Id:          id,
191                 NonceOur:    uint64(Noncediff + nonce),
192                 NonceRecv:   uint64(Noncediff + 0),
193                 Key:         key,
194                 NonceCipher: newNonceCipher(key),
195                 Bytes:       0,
196                 buf:         make([]byte, MTU+S20BS),
197                 tag:         new([poly1305.TagSize]byte),
198                 keyAuth:     new([KeySize]byte),
199                 nonce:       make([]byte, NonceSize),
200         }
201         return &peer
202 }
203
204 // Process incoming UDP packet.
205 // udpPkt is received data, related to the peer tap interface and
206 // ConnListen'es synchronization channel used to tell him that he is
207 // free to receive new packets. Authenticated and decrypted packets
208 // will be written to the interface immediately (except heartbeat ones).
209 func (p *Peer) UDPProcess(udpPkt []byte, tap *TAP, ready chan struct{}) bool {
210         size := len(udpPkt)
211         copy(p.buf[:KeySize], Emptiness)
212         copy(p.tag[:], udpPkt[size-poly1305.TagSize:])
213         copy(p.buf[S20BS:], udpPkt[NonceSize:size-poly1305.TagSize])
214         salsa20.XORKeyStream(
215                 p.buf[:S20BS+size-poly1305.TagSize],
216                 p.buf[:S20BS+size-poly1305.TagSize],
217                 udpPkt[:NonceSize],
218                 p.Key,
219         )
220         copy(p.keyAuth[:], p.buf[:KeySize])
221         if !poly1305.Verify(p.tag, udpPkt[:size-poly1305.TagSize], p.keyAuth) {
222                 ready <- struct{}{}
223                 return false
224         }
225         p.NonceCipher.Decrypt(p.buf, udpPkt[:NonceSize])
226         p.nonceRecv, _ = binary.Uvarint(p.buf[:NonceSize])
227         if int(p.NonceRecv)-Noncediff >= 0 && int(p.nonceRecv) < int(p.NonceRecv)-Noncediff {
228                 ready <- struct{}{}
229                 return false
230         }
231         ready <- struct{}{}
232         p.LastPing = time.Now()
233         p.NonceRecv = p.nonceRecv
234         p.frame = p.buf[S20BS : S20BS+size-NonceSize-poly1305.TagSize]
235         p.Bytes += len(p.frame)
236         if subtle.ConstantTimeCompare(p.frame[:HeartbeatSize], HeartbeatMark) == 1 {
237                 return true
238         }
239         tap.Write(p.frame)
240         return true
241 }
242
243 // Process incoming Ethernet packet.
244 // ethPkt is received data, conn is our outgoing connection.
245 // ready channel is TAPListen's synchronization channel used to tell him
246 // that he is free to receive new packets. Encrypted and authenticated
247 // packets will be sent to remote Peer side immediately.
248 func (p *Peer) EthProcess(ethPkt []byte, conn *net.UDPConn, ready chan struct{}) {
249         now := time.Now()
250         size := len(ethPkt)
251         // If this heartbeat is necessary
252         if size == 0 && !p.LastSent.Add(heartbeatPeriodGet()).Before(now) {
253                 return
254         }
255         copy(p.buf[:KeySize], Emptiness)
256         if size > 0 {
257                 copy(p.buf[S20BS:], ethPkt)
258                 ready <- struct{}{}
259         } else {
260                 copy(p.buf[S20BS:], HeartbeatMark)
261                 size = HeartbeatSize
262         }
263
264         p.NonceOur = p.NonceOur + 2
265         copy(p.nonce, Emptiness)
266         binary.PutUvarint(p.nonce, p.NonceOur)
267         p.NonceCipher.Encrypt(p.nonce, p.nonce)
268
269         salsa20.XORKeyStream(p.buf, p.buf, p.nonce, p.Key)
270         copy(p.buf[S20BS-NonceSize:S20BS], p.nonce)
271         copy(p.keyAuth[:], p.buf[:KeySize])
272         p.frame = p.buf[S20BS-NonceSize : S20BS+size]
273         poly1305.Sum(p.tag, p.frame, p.keyAuth)
274
275         p.Bytes += len(p.frame)
276         p.LastSent = now
277         if _, err := conn.WriteTo(append(p.frame, p.tag[:]...), p.Addr); err != nil {
278                 log.Println("Error sending UDP", err)
279         }
280 }