]> Cypherpunks.ru repositories - govpn.git/blob - govpn.go
Well, performance is not so high actually
[govpn.git] / govpn.go
1 /*
2 govpn -- simple secure virtual private network daemon
3 Copyright (C) 2014 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 // Simple secure virtual private network daemon
20 package main
21
22 import (
23         "bytes"
24         "encoding/binary"
25         "encoding/hex"
26         "flag"
27         "fmt"
28         "io"
29         "io/ioutil"
30         "log"
31         "net"
32         "os"
33         "os/exec"
34         "os/signal"
35         "time"
36
37         "golang.org/x/crypto/poly1305"
38         "golang.org/x/crypto/salsa20"
39 )
40
41 var (
42         remoteAddr = flag.String("remote", "", "Remote server address")
43         bindAddr   = flag.String("bind", "", "Bind to address")
44         ifaceName  = flag.String("iface", "tap0", "TAP network interface")
45         keyPath    = flag.String("key", "", "Path to authentication key file")
46         upPath     = flag.String("up", "", "Path to up-script")
47         downPath   = flag.String("down", "", "Path to down-script")
48         mtu        = flag.Int("mtu", 1500, "MTU")
49         nonceDiff  = flag.Int("noncediff", 1, "Allow nonce difference")
50         timeoutP   = flag.Int("timeout", 60, "Timeout seconds")
51         verboseP   = flag.Bool("v", false, "Increase verbosity")
52 )
53
54 const (
55         NonceSize = 8
56         KeySize   = 32
57         // S20BS is Salsa20's internal blocksize in bytes
58         S20BS         = 64
59         HeartBeatSize = 12
60         HeartBeatMark = "\x00\x00\x00HEARTBEAT"
61         // Maximal amount of bytes transfered with single key (4 GiB)
62         MaxBytesPerKey = 4294967296
63 )
64
65 type TAP interface {
66         io.Reader
67         io.Writer
68 }
69
70 type Peer struct {
71         addr      *net.UDPAddr
72         key       *[KeySize]byte // encryption key
73         nonceOur  uint64         // nonce for our messages
74         nonceRecv uint64         // latest received nonce from remote peer
75 }
76
77 type UDPPkt struct {
78         addr *net.UDPAddr
79         size int
80 }
81
82 func ScriptCall(path *string) {
83         if *path == "" {
84                 return
85         }
86         cmd := exec.Command(*path, *ifaceName)
87         var out bytes.Buffer
88         cmd.Stdout = &out
89         if err := cmd.Run(); err != nil {
90                 fmt.Println(time.Now(), "script error: ", err.Error(), string(out.Bytes()))
91         }
92 }
93
94 func main() {
95         flag.Parse()
96         timeout := *timeoutP
97         verbose := *verboseP
98         noncediff := uint64(*nonceDiff)
99         log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
100
101         // Key decoding
102         keyData, err := ioutil.ReadFile(*keyPath)
103         if err != nil {
104                 panic("Unable to read keyfile: " + err.Error())
105         }
106         if len(keyData) < 64 {
107                 panic("Key must be 64 hex characters long")
108         }
109         keyDecoded, err := hex.DecodeString(string(keyData[0:64]))
110         if err != nil {
111                 panic("Unable to decode the key: " + err.Error())
112         }
113         key := new([KeySize]byte)
114         copy(key[:], keyDecoded)
115         keyDecoded = nil
116         keyData = nil
117
118         // Interface listening
119         maxIfacePktSize := *mtu - poly1305.TagSize - NonceSize
120         log.Println("Max MTU", maxIfacePktSize, "on interface", *ifaceName)
121         iface := NewTAP(*ifaceName)
122         ethBuf := make([]byte, maxIfacePktSize)
123         ethSink := make(chan int)
124         ethSinkReady := make(chan bool)
125         go func() {
126                 for {
127                         <-ethSinkReady
128                         n, err := iface.Read(ethBuf)
129                         if err != nil {
130                                 panic(err)
131                         }
132                         ethSink <- n
133                 }
134         }()
135         ethSinkReady <- true
136
137         // Network address parsing
138         if (len(*bindAddr) > 1 && len(*remoteAddr) > 1) ||
139                 (len(*bindAddr) == 0 && len(*remoteAddr) == 0) {
140                 panic("Either -bind or -remote must be specified only")
141         }
142         var conn *net.UDPConn
143         var remote *net.UDPAddr
144         serverMode := false
145         bindTo := "0.0.0.0:0"
146
147         if len(*bindAddr) > 1 {
148                 bindTo = *bindAddr
149                 serverMode = true
150         }
151
152         bind, err := net.ResolveUDPAddr("udp", bindTo)
153         if err != nil {
154                 panic(err)
155         }
156         conn, err = net.ListenUDP("udp", bind)
157         if err != nil {
158                 panic(err)
159         }
160
161         if len(*remoteAddr) > 1 {
162                 remote, err = net.ResolveUDPAddr("udp", *remoteAddr)
163                 if err != nil {
164                         panic(err)
165                 }
166         }
167
168         udpBuf := make([]byte, *mtu)
169         udpSink := make(chan *UDPPkt)
170         udpSinkReady := make(chan bool)
171         go func(conn *net.UDPConn) {
172                 for {
173                         <-udpSinkReady
174                         conn.SetReadDeadline(time.Now().Add(time.Second))
175                         n, addr, err := conn.ReadFromUDP(udpBuf)
176                         if err != nil {
177                                 if verbose {
178                                         fmt.Print("B")
179                                 }
180                                 udpSink <- nil
181                         } else {
182                                 udpSink <- &UDPPkt{addr, n}
183                         }
184                 }
185         }(conn)
186         udpSinkReady <- true
187
188         // Process packets
189         var udpPkt *UDPPkt
190         var udpPktData []byte
191         var ethPktSize int
192         var frame []byte
193         var addr string
194         var peer *Peer
195         var p *Peer
196
197         timeouts := 0
198         bytes := 0
199         states := make(map[string]*Handshake)
200         nonce := make([]byte, NonceSize)
201         keyAuth := new([KeySize]byte)
202         tag := new([poly1305.TagSize]byte)
203         buf := make([]byte, *mtu+S20BS)
204         emptyKey := make([]byte, KeySize)
205
206         if !serverMode {
207                 states[remote.String()] = HandshakeStart(conn, remote, key)
208         }
209
210         heartbeat := time.Tick(time.Second * time.Duration(timeout/3))
211         go func() { <-heartbeat }()
212         heartbeatMark := []byte(HeartBeatMark)
213
214         termSignal := make(chan os.Signal, 1)
215         signal.Notify(termSignal, os.Interrupt, os.Kill)
216
217         finished := false
218         for {
219                 if finished {
220                         break
221                 }
222                 if !serverMode && bytes > MaxBytesPerKey {
223                         states[remote.String()] = HandshakeStart(conn, remote, key)
224                         bytes = 0
225                 }
226                 select {
227                 case <-termSignal:
228                         finished = true
229                 case <-heartbeat:
230                         go func() { ethSink <- -1 }()
231                 case udpPkt = <-udpSink:
232                         timeouts++
233                         if !serverMode && timeouts >= timeout {
234                                 finished = true
235                         }
236                         if udpPkt == nil {
237                                 udpSinkReady <- true
238                                 continue
239                         }
240                         udpPktData = udpBuf[:udpPkt.size]
241                         if isValidHandshakePkt(udpPktData) {
242                                 addr = udpPkt.addr.String()
243                                 state, exists := states[addr]
244                                 if serverMode {
245                                         if !exists {
246                                                 state = &Handshake{addr: udpPkt.addr}
247                                                 states[addr] = state
248                                         }
249                                         p = state.Server(noncediff, conn, key, udpPktData)
250                                 } else {
251                                         if !exists {
252                                                 fmt.Print("[HS?]")
253                                                 udpSinkReady <- true
254                                                 continue
255                                         }
256                                         p = state.Client(noncediff, conn, key, udpPktData)
257                                 }
258                                 if p != nil {
259                                         fmt.Print("[HS-OK]")
260                                         if peer == nil {
261                                                 go ScriptCall(upPath)
262                                         }
263                                         peer = p
264                                         delete(states, addr)
265                                 }
266                                 udpSinkReady <- true
267                                 continue
268                         }
269                         if peer == nil {
270                                 udpSinkReady <- true
271                                 continue
272                         }
273                         nonceRecv, _ := binary.Uvarint(udpPktData[:8])
274                         if nonceRecv < peer.nonceRecv-noncediff {
275                                 fmt.Print("R")
276                                 udpSinkReady <- true
277                                 continue
278                         }
279                         copy(buf[:KeySize], emptyKey)
280                         copy(tag[:], udpPktData[udpPkt.size-poly1305.TagSize:])
281                         copy(buf[S20BS:], udpPktData[NonceSize:udpPkt.size-poly1305.TagSize])
282                         salsa20.XORKeyStream(
283                                 buf[:S20BS+udpPkt.size-poly1305.TagSize],
284                                 buf[:S20BS+udpPkt.size-poly1305.TagSize],
285                                 udpPktData[:NonceSize],
286                                 peer.key,
287                         )
288                         copy(keyAuth[:], buf[:KeySize])
289                         if !poly1305.Verify(tag, udpPktData[:udpPkt.size-poly1305.TagSize], keyAuth) {
290                                 udpSinkReady <- true
291                                 fmt.Print("T")
292                                 continue
293                         }
294                         udpSinkReady <- true
295                         peer.nonceRecv = nonceRecv
296                         timeouts = 0
297                         frame = buf[S20BS : S20BS+udpPkt.size-NonceSize-poly1305.TagSize]
298                         bytes += len(frame)
299                         if string(frame[0:HeartBeatSize]) == HeartBeatMark {
300                                 continue
301                         }
302                         if _, err := iface.Write(frame); err != nil {
303                                 log.Println("Error writing to iface: ", err)
304                         }
305                         if verbose {
306                                 fmt.Print("r")
307                         }
308                 case ethPktSize = <-ethSink:
309                         if ethPktSize > maxIfacePktSize {
310                                 panic("Too large packet on interface")
311                         }
312                         if peer == nil {
313                                 ethSinkReady <- true
314                                 continue
315                         }
316                         peer.nonceOur = peer.nonceOur + 2
317                         binary.PutUvarint(nonce, peer.nonceOur)
318                         copy(buf[:KeySize], emptyKey)
319                         if ethPktSize > -1 {
320                                 copy(buf[S20BS:], ethBuf[:ethPktSize])
321                                 ethSinkReady <- true
322                         } else {
323                                 copy(buf[S20BS:], heartbeatMark)
324                                 ethPktSize = HeartBeatSize
325                         }
326                         salsa20.XORKeyStream(buf, buf, nonce, peer.key)
327                         copy(buf[S20BS-NonceSize:S20BS], nonce)
328                         copy(keyAuth[:], buf[:KeySize])
329                         dataToSend := buf[S20BS-NonceSize : S20BS+ethPktSize]
330                         poly1305.Sum(tag, dataToSend, keyAuth)
331                         bytes += len(dataToSend)
332                         if _, err := conn.WriteTo(append(dataToSend, tag[:]...), peer.addr); err != nil {
333                                 log.Println("Error sending UDP", err)
334                         }
335                         if verbose {
336                                 fmt.Print("w")
337                         }
338                 }
339         }
340         ScriptCall(downPath)
341 }