2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2015 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/>.
34 "github.com/agl/ed25519"
35 "golang.org/x/crypto/xtea"
40 RefreshRate = 60 * time.Second
43 type PeerId [IDSize]byte
45 func (id PeerId) String() string {
46 return hex.EncodeToString(id[:])
49 // Return human readable name of the peer.
50 // It equals either to peers/PEER/name file contents or PEER's hex.
51 func (id PeerId) MarshalJSON() ([]byte, error) {
53 if name, err := ioutil.ReadFile(path.Join(PeersPath, result, "name")); err == nil {
54 result = strings.TrimRight(string(name), "\n")
56 return []byte(`"` + result + `"`), nil
59 type cipherCache map[PeerId]*xtea.Cipher
64 cipherCacheLock sync.RWMutex
68 // Initialize (pre-cache) available peers info.
69 func PeersInit(path string) {
71 IDsCache = make(map[PeerId]*xtea.Cipher)
75 time.Sleep(RefreshRate)
80 // Initialize dummy cache for client-side usage.
81 func PeersInitDummy(id *PeerId, conf *PeerConf) {
82 IDsCache = make(map[PeerId]*xtea.Cipher)
83 cipher, err := xtea.NewCipher(id[:])
87 IDsCache[*id] = cipher
91 // Refresh IDsCache: remove disappeared keys, add missing ones with
92 // initialized ciphers.
93 func (cc cipherCache) refresh() {
94 dir, err := os.Open(PeersPath)
98 peerIds, err := dir.Readdirnames(0)
102 available := make(map[PeerId]bool)
103 for _, peerId := range peerIds {
104 id, err := IDDecode(peerId)
108 available[*id] = true
111 cipherCacheLock.Lock()
112 // Cleanup deleted ones from cache
113 for k, _ := range cc {
114 if _, exists := available[k]; !exists {
116 log.Println("Cleaning key: ", k)
120 for peerId, _ := range available {
121 if _, exists := cc[peerId]; !exists {
122 log.Println("Adding key", peerId)
123 cipher, err := xtea.NewCipher(peerId[:])
130 cipherCacheLock.Unlock()
133 // Try to find peer's identity (that equals to an encryption key)
134 // by taking first blocksize sized bytes from data at the beginning
135 // as plaintext and last bytes as cyphertext.
136 func (cc cipherCache) Find(data []byte) *PeerId {
137 if len(data) < xtea.BlockSize*2 {
140 buf := make([]byte, xtea.BlockSize)
141 cipherCacheLock.RLock()
142 for pid, cipher := range cc {
143 cipher.Decrypt(buf, data[len(data)-xtea.BlockSize:])
144 if subtle.ConstantTimeCompare(buf, data[:xtea.BlockSize]) == 1 {
146 cipherCacheLock.RUnlock()
150 cipherCacheLock.RUnlock()
154 func readIntFromFile(path string) (int, error) {
155 data, err := ioutil.ReadFile(path)
159 val, err := strconv.Atoi(strings.TrimRight(string(data), "\n"))
166 // Get peer related configuration.
167 func (id *PeerId) Conf() *PeerConf {
168 if dummyConf != nil {
171 conf := PeerConf{Id: id, NoiseEnable: false, CPR: 0}
172 peerPath := path.Join(PeersPath, id.String())
174 verPath := path.Join(peerPath, "verifier")
175 keyData, err := ioutil.ReadFile(verPath)
177 log.Println("Unable to read verifier:", verPath)
180 if len(keyData) < ed25519.PublicKeySize*2 {
181 log.Println("Verifier must be 64 hex characters long:", verPath)
184 keyDecoded, err := hex.DecodeString(string(keyData[:ed25519.PublicKeySize*2]))
186 log.Println("Unable to decode the key:", err.Error(), verPath)
189 conf.DSAPub = new([ed25519.PublicKeySize]byte)
190 copy(conf.DSAPub[:], keyDecoded)
192 timeout := TimeoutDefault
193 if val, err := readIntFromFile(path.Join(peerPath, "timeout")); err == nil {
196 conf.Timeout = time.Second * time.Duration(timeout)
198 if val, err := readIntFromFile(path.Join(peerPath, "noise")); err == nil && val == 1 {
199 conf.NoiseEnable = true
201 if val, err := readIntFromFile(path.Join(peerPath, "cpr")); err == nil {
207 // Decode identification string.
208 // It must be 32 hexadecimal characters long.
209 func IDDecode(raw string) (*PeerId, error) {
210 if len(raw) != IDSize*2 {
211 return nil, errors.New("ID must be 32 characters long")
213 idDecoded, err := hex.DecodeString(raw)
215 return nil, errors.New("ID must contain hexadecimal characters only")
217 idP := new([IDSize]byte)
218 copy(idP[:], idDecoded)