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 "code.google.com/p/go.crypto/poly1305"
38 "code.google.com/p/go.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 timeoutP = flag.Int("timeout", 60, "Timeout seconds")
50 verboseP = flag.Bool("v", false, "Increase verbosity")
56 // S20BS is Salsa20's internal blocksize in bytes
59 HeartBeatMark = "\x00\x00\x00HEARTBEAT"
60 // Maximal amount of bytes transfered with single key (4 GiB)
61 MaxBytesPerKey = 4294967296
71 key *[KeySize]byte // encryption key
72 nonceOur uint64 // nonce for our messages
73 nonceRecv uint64 // latest received nonce from remote peer
81 func ScriptCall(path *string) {
85 cmd := exec.Command(*path, *ifaceName)
88 if err := cmd.Run(); err != nil {
89 fmt.Println(time.Now(), "script error: ", err.Error(), string(out.Bytes()))
97 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
100 keyData, err := ioutil.ReadFile(*keyPath)
102 panic("Unable to read keyfile: " + err.Error())
104 if len(keyData) < 64 {
105 panic("Key must be 64 hex characters long")
107 keyDecoded, err := hex.DecodeString(string(keyData[0:64]))
109 panic("Unable to decode the key: " + err.Error())
111 key := new([KeySize]byte)
112 copy(key[:], keyDecoded)
116 // Interface listening
117 maxIfacePktSize := *mtu - poly1305.TagSize - NonceSize
118 log.Println("Max MTU", maxIfacePktSize, "on interface", *ifaceName)
119 iface := NewTAP(*ifaceName)
120 ethBuf := make([]byte, maxIfacePktSize)
121 ethSink := make(chan int)
122 ethSinkReady := make(chan bool)
126 n, err := iface.Read(ethBuf)
135 // Network address parsing
136 if (len(*bindAddr) > 1 && len(*remoteAddr) > 1) ||
137 (len(*bindAddr) == 0 && len(*remoteAddr) == 0) {
138 panic("Either -bind or -remote must be specified only")
140 var conn *net.UDPConn
141 var remote *net.UDPAddr
143 bindTo := "0.0.0.0:0"
145 if len(*bindAddr) > 1 {
150 bind, err := net.ResolveUDPAddr("udp", bindTo)
154 conn, err = net.ListenUDP("udp", bind)
159 if len(*remoteAddr) > 1 {
160 remote, err = net.ResolveUDPAddr("udp", *remoteAddr)
166 udpBuf := make([]byte, *mtu)
167 udpSink := make(chan *UDPPkt)
168 udpSinkReady := make(chan bool)
169 go func(conn *net.UDPConn) {
172 conn.SetReadDeadline(time.Now().Add(time.Second))
173 n, addr, err := conn.ReadFromUDP(udpBuf)
180 udpSink <- &UDPPkt{addr, n}
188 var udpPktData []byte
197 states := make(map[string]*Handshake)
198 nonce := make([]byte, NonceSize)
199 keyAuth := new([KeySize]byte)
200 tag := new([poly1305.TagSize]byte)
201 buf := make([]byte, *mtu+S20BS)
202 emptyKey := make([]byte, KeySize)
205 states[remote.String()] = HandshakeStart(conn, remote, key)
208 heartbeat := time.Tick(time.Second * time.Duration(timeout/3))
209 go func() { <-heartbeat }()
210 heartbeatMark := []byte(HeartBeatMark)
212 termSignal := make(chan os.Signal, 1)
213 signal.Notify(termSignal, os.Interrupt, os.Kill)
220 if !serverMode && bytes > MaxBytesPerKey {
221 states[remote.String()] = HandshakeStart(conn, remote, key)
228 go func() { ethSink <- -1 }()
229 case udpPkt = <-udpSink:
231 if !serverMode && timeouts >= timeout {
238 udpPktData = udpBuf[:udpPkt.size]
239 if isValidHandshakePkt(udpPktData) {
240 addr = udpPkt.addr.String()
241 state, exists := states[addr]
244 state = &Handshake{addr: udpPkt.addr}
247 p = state.Server(conn, key, udpPktData)
254 p = state.Client(conn, key, udpPktData)
259 go ScriptCall(upPath)
271 nonceRecv, _ := binary.Uvarint(udpPktData[:8])
272 if peer.nonceRecv >= nonceRecv {
277 copy(buf[:KeySize], emptyKey)
278 copy(tag[:], udpPktData[udpPkt.size-poly1305.TagSize:])
279 copy(buf[S20BS:], udpPktData[NonceSize:udpPkt.size-poly1305.TagSize])
280 salsa20.XORKeyStream(
281 buf[:S20BS+udpPkt.size-poly1305.TagSize],
282 buf[:S20BS+udpPkt.size-poly1305.TagSize],
283 udpPktData[:NonceSize],
286 copy(keyAuth[:], buf[:KeySize])
287 if !poly1305.Verify(tag, udpPktData[:udpPkt.size-poly1305.TagSize], keyAuth) {
293 peer.nonceRecv = nonceRecv
295 frame = buf[S20BS : S20BS+udpPkt.size-NonceSize-poly1305.TagSize]
297 if string(frame[0:HeartBeatSize]) == HeartBeatMark {
300 if _, err := iface.Write(frame); err != nil {
301 log.Println("Error writing to iface: ", err)
306 case ethPktSize = <-ethSink:
307 if ethPktSize > maxIfacePktSize {
308 panic("Too large packet on interface")
314 peer.nonceOur = peer.nonceOur + 2
315 binary.PutUvarint(nonce, peer.nonceOur)
316 copy(buf[:KeySize], emptyKey)
318 copy(buf[S20BS:], ethBuf[:ethPktSize])
321 copy(buf[S20BS:], heartbeatMark)
322 ethPktSize = HeartBeatSize
324 salsa20.XORKeyStream(buf, buf, nonce, peer.key)
325 copy(buf[S20BS-NonceSize:S20BS], nonce)
326 copy(keyAuth[:], buf[:KeySize])
327 dataToSend := buf[S20BS-NonceSize : S20BS+ethPktSize]
328 poly1305.Sum(tag, dataToSend, keyAuth)
329 bytes += len(dataToSend)
330 if _, err := conn.WriteTo(append(dataToSend, tag[:]...), peer.addr); err != nil {
331 log.Println("Error sending UDP", err)