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"
58 // Maximal amount of bytes transfered with single key (4 GiB)
59 MaxBytesPerKey = 4294967296
69 key *[KeySize]byte // encryption key
70 nonceOur uint64 // nonce for our messages
71 nonceRecv uint64 // latest received nonce from remote peer
79 func ScriptCall(path *string) {
83 cmd := exec.Command(*path, *ifaceName)
86 if err := cmd.Run(); err != nil {
87 fmt.Println(time.Now(), "script error: ", err.Error(), string(out.Bytes()))
95 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
98 keyData, err := ioutil.ReadFile(*keyPath)
100 panic("Unable to read keyfile: " + err.Error())
102 if len(keyData) < 64 {
103 panic("Key must be 64 hex characters long")
105 keyDecoded, err := hex.DecodeString(string(keyData[0:64]))
107 panic("Unable to decode the key: " + err.Error())
109 key := new([KeySize]byte)
110 copy(key[:], keyDecoded)
114 // Interface listening
115 maxIfacePktSize := *mtu - poly1305.TagSize - NonceSize
116 log.Println("Max MTU", maxIfacePktSize, "on interface", *ifaceName)
117 iface := NewTAP(*ifaceName)
118 ethBuf := make([]byte, maxIfacePktSize)
119 ethSink := make(chan int)
120 ethSinkReady := make(chan bool)
124 n, err := iface.Read(ethBuf)
133 // Network address parsing
134 if (len(*bindAddr) > 1 && len(*remoteAddr) > 1) ||
135 (len(*bindAddr) == 0 && len(*remoteAddr) == 0) {
136 panic("Either -bind or -remote must be specified only")
138 var conn *net.UDPConn
139 var remote *net.UDPAddr
141 bindTo := "0.0.0.0:0"
143 if len(*bindAddr) > 1 {
148 bind, err := net.ResolveUDPAddr("udp", bindTo)
152 conn, err = net.ListenUDP("udp", bind)
157 if len(*remoteAddr) > 1 {
158 remote, err = net.ResolveUDPAddr("udp", *remoteAddr)
164 udpBuf := make([]byte, *mtu)
165 udpSink := make(chan *UDPPkt)
166 udpSinkReady := make(chan bool)
167 go func(conn *net.UDPConn) {
170 conn.SetReadDeadline(time.Now().Add(time.Second))
171 n, addr, err := conn.ReadFromUDP(udpBuf)
178 udpSink <- &UDPPkt{addr, n}
186 var udpPktData []byte
195 states := make(map[string]*Handshake)
196 nonce := make([]byte, NonceSize)
197 keyAuth := new([KeySize]byte)
198 tag := new([poly1305.TagSize]byte)
199 buf := make([]byte, *mtu+S20BS)
200 emptyKey := make([]byte, KeySize)
203 states[remote.String()] = HandshakeStart(conn, remote, key)
206 heartbeat := time.Tick(time.Second * time.Duration(timeout/3))
207 go func() { <-heartbeat }()
208 heartbeatMark := []byte(HeartBeatMark)
210 termSignal := make(chan os.Signal, 1)
211 signal.Notify(termSignal, os.Interrupt, os.Kill)
218 if !serverMode && bytes > MaxBytesPerKey {
219 states[remote.String()] = HandshakeStart(conn, remote, key)
226 go func() { ethSink <- -1 }()
227 case udpPkt = <-udpSink:
229 if !serverMode && timeouts >= timeout {
236 udpPktData = udpBuf[:udpPkt.size]
237 if isValidHandshakePkt(udpPktData) {
238 addr = udpPkt.addr.String()
239 state, exists := states[addr]
242 state = &Handshake{addr: udpPkt.addr}
245 p = state.Server(conn, key, udpPktData)
252 p = state.Client(conn, key, udpPktData)
257 go ScriptCall(upPath)
269 nonceRecv, _ := binary.Uvarint(udpPktData[:8])
270 if peer.nonceRecv >= nonceRecv {
275 copy(buf[:KeySize], emptyKey)
276 copy(tag[:], udpPktData[udpPkt.size-poly1305.TagSize:])
277 copy(buf[S20BS:], udpPktData[NonceSize:udpPkt.size-poly1305.TagSize])
278 salsa20.XORKeyStream(
279 buf[:S20BS+udpPkt.size-poly1305.TagSize],
280 buf[:S20BS+udpPkt.size-poly1305.TagSize],
281 udpPktData[:NonceSize],
284 copy(keyAuth[:], buf[:KeySize])
285 if !poly1305.Verify(tag, udpPktData[:udpPkt.size-poly1305.TagSize], keyAuth) {
291 peer.nonceRecv = nonceRecv
293 frame = buf[S20BS : S20BS+udpPkt.size-NonceSize-poly1305.TagSize]
295 if string(frame[0:HeartBeatSize]) == HeartBeatMark {
298 if _, err := iface.Write(frame); err != nil {
299 log.Println("Error writing to iface: ", err)
304 case ethPktSize = <-ethSink:
305 if ethPktSize > maxIfacePktSize {
306 panic("Too large packet on interface")
312 peer.nonceOur = peer.nonceOur + 2
313 binary.PutUvarint(nonce, peer.nonceOur)
314 copy(buf[:KeySize], emptyKey)
316 copy(buf[S20BS:], ethBuf[:ethPktSize])
319 copy(buf[S20BS:], heartbeatMark)
320 ethPktSize = HeartBeatSize
322 salsa20.XORKeyStream(buf, buf, nonce, peer.key)
323 copy(buf[S20BS-NonceSize:S20BS], nonce)
324 copy(keyAuth[:], buf[:KeySize])
325 dataToSend := buf[S20BS-NonceSize : S20BS+ethPktSize]
326 poly1305.Sum(tag, dataToSend, keyAuth)
327 bytes += len(dataToSend)
328 if _, err := conn.WriteTo(append(dataToSend, tag[:]...), peer.addr); err != nil {
329 log.Println("Error sending UDP", err)