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/>.
35 "code.google.com/p/go.crypto/poly1305"
36 "code.google.com/p/go.crypto/salsa20"
40 remoteAddr = flag.String("remote", "", "Remote server address")
41 bindAddr = flag.String("bind", "", "Bind to address")
42 ifaceName = flag.String("iface", "tap0", "TAP network interface")
43 keyPath = flag.String("key", "", "Path to authentication key file")
44 upPath = flag.String("up", "", "Path to up-script")
45 downPath = flag.String("down", "", "Path to down-script")
46 mtu = flag.Int("mtu", 1500, "MTU")
47 timeoutP = flag.Int("timeout", 60, "Timeout seconds")
48 verboseP = flag.Bool("v", false, "Increase verbosity")
54 // S20BS is Salsa20's internal blocksize in bytes
57 HeartBeatMark = "\x00\x00\x00HEARTBEAT"
67 key *[KeySize]byte // encryption key
68 nonceOur uint64 // nonce for our messages
69 nonceRecv uint64 // latest received nonce from remote peer
77 func ScriptCall(path *string) {
81 cmd := exec.Command(*path, *ifaceName)
84 if err := cmd.Run(); err != nil {
85 fmt.Println(time.Now(), "script error: ", err.Error(), string(out.Bytes()))
93 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
96 keyData, err := ioutil.ReadFile(*keyPath)
98 panic("Unable to read keyfile: " + err.Error())
100 if len(keyData) < 64 {
101 panic("Key must be 64 hex characters long")
103 keyDecoded, err := hex.DecodeString(string(keyData[0:64]))
105 panic("Unable to decode the key: " + err.Error())
107 key := new([KeySize]byte)
108 copy(key[:], keyDecoded)
112 // Interface listening
113 maxIfacePktSize := *mtu - poly1305.TagSize - NonceSize
114 log.Println("Max MTU", maxIfacePktSize, "on interface", *ifaceName)
115 iface := NewTAP(*ifaceName)
116 ethBuf := make([]byte, maxIfacePktSize)
117 ethSink := make(chan int)
118 ethSinkReady := make(chan bool)
122 n, err := iface.Read(ethBuf)
131 // Network address parsing
132 if (len(*bindAddr) > 1 && len(*remoteAddr) > 1) ||
133 (len(*bindAddr) == 0 && len(*remoteAddr) == 0) {
134 panic("Either -bind or -remote must be specified only")
136 var conn *net.UDPConn
137 var remote *net.UDPAddr
139 bindTo := "0.0.0.0:0"
141 if len(*bindAddr) > 1 {
146 bind, err := net.ResolveUDPAddr("udp", bindTo)
150 conn, err = net.ListenUDP("udp", bind)
155 if len(*remoteAddr) > 1 {
156 remote, err = net.ResolveUDPAddr("udp", *remoteAddr)
162 udpBuf := make([]byte, *mtu)
163 udpSink := make(chan *UDPPkt)
164 udpSinkReady := make(chan bool)
165 go func(conn *net.UDPConn) {
168 conn.SetReadDeadline(time.Now().Add(time.Second))
169 n, addr, err := conn.ReadFromUDP(udpBuf)
176 udpSink <- &UDPPkt{addr, n}
184 var udpPktData []byte
192 states := make(map[string]*Handshake)
193 nonce := make([]byte, NonceSize)
194 keyAuth := new([KeySize]byte)
195 tag := new([poly1305.TagSize]byte)
196 buf := make([]byte, *mtu+S20BS)
197 emptyKey := make([]byte, KeySize)
198 ethPkt := make([]byte, maxIfacePktSize)
199 udpPktDataBuf := make([]byte, *mtu)
202 states[remote.String()] = HandshakeStart(conn, remote, key)
205 heartbeat := time.Tick(time.Second * time.Duration(timeout/3))
206 heartbeatMark := []byte(HeartBeatMark)
208 termSignal := make(chan os.Signal, 1)
209 signal.Notify(termSignal, os.Interrupt, os.Kill)
220 go func() { ethSink <- -1 }()
221 case udpPkt = <-udpSink:
223 if !serverMode && timeouts >= timeout {
230 copy(udpPktDataBuf, udpBuf[:udpPkt.size])
232 udpPktData = udpPktDataBuf[:udpPkt.size]
233 if isValidHandshakePkt(udpPktData) {
234 addr = udpPkt.addr.String()
235 state, exists := states[addr]
238 state = &Handshake{addr: udpPkt.addr}
241 p = state.Server(conn, key, udpPktData)
247 p = state.Client(conn, key, udpPktData)
253 go ScriptCall(upPath)
260 nonceRecv, _ := binary.Uvarint(udpPktData[:8])
261 if peer.nonceRecv >= nonceRecv {
265 copy(buf[:KeySize], emptyKey)
266 copy(tag[:], udpPktData[udpPkt.size-poly1305.TagSize:])
267 copy(buf[S20BS:], udpPktData[NonceSize:udpPkt.size-poly1305.TagSize])
268 salsa20.XORKeyStream(
269 buf[:S20BS+udpPkt.size-poly1305.TagSize],
270 buf[:S20BS+udpPkt.size-poly1305.TagSize],
271 udpPktData[:NonceSize],
274 copy(keyAuth[:], buf[:KeySize])
275 if !poly1305.Verify(tag, udpPktData[:udpPkt.size-poly1305.TagSize], keyAuth) {
279 peer.nonceRecv = nonceRecv
281 frame = buf[S20BS : S20BS+udpPkt.size-NonceSize-poly1305.TagSize]
282 if string(frame[0:HeartBeatSize]) == HeartBeatMark {
285 if _, err := iface.Write(frame); err != nil {
286 log.Println("Error writing to iface: ", err)
291 case ethPktSize = <-ethSink:
292 if ethPktSize > maxIfacePktSize {
293 panic("Too large packet on interface")
300 copy(ethPkt, ethBuf[:ethPktSize])
303 copy(ethPkt, heartbeatMark)
304 ethPktSize = HeartBeatSize
306 peer.nonceOur = peer.nonceOur + 2
307 binary.PutUvarint(nonce, peer.nonceOur)
308 copy(buf[:KeySize], emptyKey)
309 copy(buf[S20BS:], ethPkt[:ethPktSize])
310 salsa20.XORKeyStream(buf, buf, nonce, peer.key)
311 copy(buf[S20BS-NonceSize:S20BS], nonce)
312 copy(keyAuth[:], buf[:KeySize])
313 dataToSend := buf[S20BS-NonceSize : S20BS+ethPktSize]
314 poly1305.Sum(tag, dataToSend, keyAuth)
315 if _, err := conn.WriteTo(append(dataToSend, tag[:]...), peer.addr); err != nil {
316 log.Println("Error sending UDP", err)