2 govpn -- high-performance secure virtual private network daemon
3 Copyright (C) 2014 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/>.
19 // High-performance secure virtual private network daemon
37 "golang.org/x/crypto/poly1305"
38 "golang.org/x/crypto/salsa20"
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")
57 // S20BS is Salsa20's internal blocksize in bytes
60 HeartBeatMark = "\x00\x00\x00HEARTBEAT"
61 // Maximal amount of bytes transfered with single key (4 GiB)
62 MaxBytesPerKey = 4294967296
72 key *[KeySize]byte // encryption key
73 nonceOur uint64 // nonce for our messages
74 nonceRecv uint64 // latest received nonce from remote peer
82 func ScriptCall(path *string) {
86 cmd := exec.Command(*path, *ifaceName)
89 if err := cmd.Run(); err != nil {
90 fmt.Println(time.Now(), "script error: ", err.Error(), string(out.Bytes()))
98 noncediff := uint64(*nonceDiff)
99 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
102 keyData, err := ioutil.ReadFile(*keyPath)
104 panic("Unable to read keyfile: " + err.Error())
106 if len(keyData) < 64 {
107 panic("Key must be 64 hex characters long")
109 keyDecoded, err := hex.DecodeString(string(keyData[0:64]))
111 panic("Unable to decode the key: " + err.Error())
113 key := new([KeySize]byte)
114 copy(key[:], keyDecoded)
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)
128 n, err := iface.Read(ethBuf)
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")
142 var conn *net.UDPConn
143 var remote *net.UDPAddr
145 bindTo := "0.0.0.0:0"
147 if len(*bindAddr) > 1 {
152 bind, err := net.ResolveUDPAddr("udp", bindTo)
156 conn, err = net.ListenUDP("udp", bind)
161 if len(*remoteAddr) > 1 {
162 remote, err = net.ResolveUDPAddr("udp", *remoteAddr)
168 udpBuf := make([]byte, *mtu)
169 udpSink := make(chan *UDPPkt)
170 udpSinkReady := make(chan bool)
171 go func(conn *net.UDPConn) {
174 conn.SetReadDeadline(time.Now().Add(time.Second))
175 n, addr, err := conn.ReadFromUDP(udpBuf)
182 udpSink <- &UDPPkt{addr, n}
190 var udpPktData []byte
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)
207 states[remote.String()] = HandshakeStart(conn, remote, key)
210 heartbeat := time.Tick(time.Second * time.Duration(timeout/3))
211 go func() { <-heartbeat }()
212 heartbeatMark := []byte(HeartBeatMark)
214 termSignal := make(chan os.Signal, 1)
215 signal.Notify(termSignal, os.Interrupt, os.Kill)
222 if !serverMode && bytes > MaxBytesPerKey {
223 states[remote.String()] = HandshakeStart(conn, remote, key)
230 go func() { ethSink <- -1 }()
231 case udpPkt = <-udpSink:
233 if !serverMode && timeouts >= timeout {
240 udpPktData = udpBuf[:udpPkt.size]
241 if isValidHandshakePkt(udpPktData) {
242 addr = udpPkt.addr.String()
243 state, exists := states[addr]
246 state = &Handshake{addr: udpPkt.addr}
249 p = state.Server(noncediff, conn, key, udpPktData)
256 p = state.Client(noncediff, conn, key, udpPktData)
261 go ScriptCall(upPath)
273 nonceRecv, _ := binary.Uvarint(udpPktData[:8])
274 if nonceRecv < peer.nonceRecv-noncediff {
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],
288 copy(keyAuth[:], buf[:KeySize])
289 if !poly1305.Verify(tag, udpPktData[:udpPkt.size-poly1305.TagSize], keyAuth) {
295 peer.nonceRecv = nonceRecv
297 frame = buf[S20BS : S20BS+udpPkt.size-NonceSize-poly1305.TagSize]
299 if string(frame[0:HeartBeatSize]) == HeartBeatMark {
302 if _, err := iface.Write(frame); err != nil {
303 log.Println("Error writing to iface: ", err)
308 case ethPktSize = <-ethSink:
309 if ethPktSize > maxIfacePktSize {
310 panic("Too large packet on interface")
316 peer.nonceOur = peer.nonceOur + 2
317 binary.PutUvarint(nonce, peer.nonceOur)
318 copy(buf[:KeySize], emptyKey)
320 copy(buf[S20BS:], ethBuf[:ethPktSize])
323 copy(buf[S20BS:], heartbeatMark)
324 ethPktSize = HeartBeatSize
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)