]> Cypherpunks.ru repositories - govpn.git/blob - govpn.go
Specify PSK through the file, not as command line argument
[govpn.git] / govpn.go
1 /*
2 govpn -- high-performance 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 package main
19
20 import (
21         "encoding/binary"
22         "encoding/hex"
23         "flag"
24         "fmt"
25         "io"
26         "io/ioutil"
27         "log"
28         "net"
29         "time"
30
31         "code.google.com/p/go.crypto/poly1305"
32         "code.google.com/p/go.crypto/salsa20"
33 )
34
35 var (
36         remoteAddr = flag.String("remote", "", "Remote server address")
37         bindAddr   = flag.String("bind", "", "Bind to address")
38         ifaceName  = flag.String("iface", "tap0", "TAP network interface")
39         keyPath    = flag.String("key", "", "Path to authentication key file")
40         mtu        = flag.Int("mtu", 1500, "MTU")
41         timeout    = flag.Int("timeout", 60, "Timeout seconds")
42         verbose    = flag.Bool("v", false, "Increase verbosity")
43 )
44
45 const (
46         NonceSize = 8
47         KeySize   = 32
48         // S20BS is Salsa20's internal blocksize in bytes
49         S20BS = 64
50 )
51
52 type TAP interface {
53         io.Reader
54         io.Writer
55 }
56
57 type Peer struct {
58         addr      *net.UDPAddr
59         key       *[KeySize]byte // encryption key
60         nonceOur  uint64         // nonce for our messages
61         nonceRecv uint64         // latest received nonce from remote peer
62 }
63
64 type UDPPkt struct {
65         addr *net.UDPAddr
66         size int
67 }
68
69 func main() {
70         flag.Parse()
71         log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
72
73         // Key decoding
74         keyData, err := ioutil.ReadFile(*keyPath)
75         if err != nil {
76                 panic("Unable to read keyfile: " + err.Error())
77         }
78         if len(keyData) < 64 {
79                 panic("Key must be 64 hex characters long")
80         }
81         keyDecoded, err := hex.DecodeString(string(keyData[0:64]))
82         if err != nil {
83                 panic("Unable to decode the key: " + err.Error())
84         }
85         key := new([KeySize]byte)
86         copy(key[:], keyDecoded)
87         keyDecoded = nil
88         keyData = nil
89
90         // Interface listening
91         maxIfacePktSize := *mtu - poly1305.TagSize - NonceSize
92         log.Println("Max MTU", maxIfacePktSize, "on interface", *ifaceName)
93         iface := NewTAP(*ifaceName)
94         ethBuf := make([]byte, maxIfacePktSize)
95         ethSink := make(chan int)
96         ethSinkReady := make(chan bool)
97         go func() {
98                 for {
99                         <-ethSinkReady
100                         n, err := iface.Read(ethBuf)
101                         if err != nil {
102                                 panic(err)
103                         }
104                         ethSink <- n
105                 }
106         }()
107         ethSinkReady <- true
108
109         // Network address parsing
110         if (len(*bindAddr) > 1 && len(*remoteAddr) > 1) ||
111                 (len(*bindAddr) == 0 && len(*remoteAddr) == 0) {
112                 panic("Either -bind or -remote must be specified only")
113         }
114         var conn *net.UDPConn
115         var remote *net.UDPAddr
116         serverMode := false
117         bindTo := "0.0.0.0:0"
118
119         if len(*bindAddr) > 1 {
120                 bindTo = *bindAddr
121                 serverMode = true
122         }
123
124         bind, err := net.ResolveUDPAddr("udp", bindTo)
125         if err != nil {
126                 panic(err)
127         }
128         conn, err = net.ListenUDP("udp", bind)
129         if err != nil {
130                 panic(err)
131         }
132
133         if len(*remoteAddr) > 1 {
134                 remote, err = net.ResolveUDPAddr("udp", *remoteAddr)
135                 if err != nil {
136                         panic(err)
137                 }
138         }
139
140         udpBuf := make([]byte, *mtu)
141         udpSink := make(chan *UDPPkt)
142         udpSinkReady := make(chan bool)
143         go func(conn *net.UDPConn) {
144                 for {
145                         <-udpSinkReady
146                         conn.SetReadDeadline(time.Now().Add(time.Second))
147                         n, addr, err := conn.ReadFromUDP(udpBuf)
148                         if err != nil {
149                                 if *verbose {
150                                         fmt.Print("B")
151                                 }
152                                 udpSink <- nil
153                         } else {
154                                 udpSink <- &UDPPkt{addr, n}
155                         }
156                 }
157         }(conn)
158         udpSinkReady <- true
159
160         // Process packets
161         var udpPkt *UDPPkt
162         var udpPktData []byte
163         var ethPktSize int
164         var addr string
165         var peer *Peer
166         var p *Peer
167
168         timeouts := 0
169         states := make(map[string]*Handshake)
170         nonce := make([]byte, NonceSize)
171         keyAuth := new([KeySize]byte)
172         tag := new([poly1305.TagSize]byte)
173         buf := make([]byte, *mtu+S20BS)
174         emptyKey := make([]byte, KeySize)
175         ethPkt := make([]byte, maxIfacePktSize)
176         udpPktDataBuf := make([]byte, *mtu)
177
178         if !serverMode {
179                 states[remote.String()] = HandshakeStart(conn, remote, key)
180         }
181
182         finished := false
183         for {
184                 if finished {
185                         break
186                 }
187                 select {
188                 case udpPkt = <-udpSink:
189                         timeouts++
190                         if !serverMode && timeouts >= *timeout {
191                                 finished = true
192                         }
193                         if udpPkt == nil {
194                                 udpSinkReady <- true
195                                 continue
196                         }
197                         copy(udpPktDataBuf, udpBuf[:udpPkt.size])
198                         udpSinkReady <- true
199                         udpPktData = udpPktDataBuf[:udpPkt.size]
200                         if isValidHandshakePkt(udpPktData) {
201                                 addr = udpPkt.addr.String()
202                                 state, exists := states[addr]
203                                 if serverMode {
204                                         if !exists {
205                                                 state = &Handshake{addr: udpPkt.addr}
206                                                 states[addr] = state
207                                         }
208                                         p = state.Server(conn, key, udpPktData)
209                                 } else {
210                                         if !exists {
211                                                 fmt.Print("[HS?]")
212                                                 continue
213                                         }
214                                         p = state.Client(conn, key, udpPktData)
215                                 }
216                                 if p != nil {
217                                         fmt.Print("[HS-OK]")
218                                         peer = p
219                                         delete(states, addr)
220                                 }
221                                 continue
222                         }
223                         if peer == nil {
224                                 continue
225                         }
226                         nonceRecv, _ := binary.Uvarint(udpPktData[:8])
227                         if peer.nonceRecv >= nonceRecv {
228                                 fmt.Print("R")
229                                 continue
230                         }
231                         copy(buf[:KeySize], emptyKey)
232                         copy(tag[:], udpPktData[udpPkt.size-poly1305.TagSize:])
233                         copy(buf[S20BS:], udpPktData[NonceSize:udpPkt.size-poly1305.TagSize])
234                         salsa20.XORKeyStream(
235                                 buf[:S20BS+udpPkt.size-poly1305.TagSize],
236                                 buf[:S20BS+udpPkt.size-poly1305.TagSize],
237                                 udpPktData[:NonceSize],
238                                 peer.key,
239                         )
240                         copy(keyAuth[:], buf[:KeySize])
241                         if !poly1305.Verify(tag, udpPktData[:udpPkt.size-poly1305.TagSize], keyAuth) {
242                                 fmt.Print("T")
243                                 continue
244                         }
245                         peer.nonceRecv = nonceRecv
246                         timeouts = 0
247                         if _, err := iface.Write(buf[S20BS : S20BS+udpPkt.size-NonceSize-poly1305.TagSize]); err != nil {
248                                 log.Println("Error writing to iface: ", err)
249                         }
250                         if *verbose {
251                                 fmt.Print("r")
252                         }
253                 case ethPktSize = <-ethSink:
254                         if ethPktSize > maxIfacePktSize {
255                                 panic("Too large packet on interface")
256                         }
257                         if peer == nil {
258                                 ethSinkReady <- true
259                                 continue
260                         }
261                         copy(ethPkt, ethBuf[:ethPktSize])
262                         ethSinkReady <- true
263                         peer.nonceOur = peer.nonceOur + 2
264                         binary.PutUvarint(nonce, peer.nonceOur)
265                         copy(buf[:KeySize], emptyKey)
266                         copy(buf[S20BS:], ethPkt[:ethPktSize])
267                         salsa20.XORKeyStream(buf, buf, nonce, peer.key)
268                         copy(buf[S20BS-NonceSize:S20BS], nonce)
269                         copy(keyAuth[:], buf[:KeySize])
270                         dataToSend := buf[S20BS-NonceSize : S20BS+ethPktSize]
271                         poly1305.Sum(tag, dataToSend, keyAuth)
272                         if _, err := conn.WriteTo(append(dataToSend, tag[:]...), peer.addr); err != nil {
273                                 log.Println("Error sending UDP", err)
274                         }
275                         if *verbose {
276                                 fmt.Print("w")
277                         }
278                 }
279         }
280 }