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/>.
29 "golang.org/x/crypto/xtea"
34 RefreshRate = 60 * time.Second
37 type PeerId [IDSize]byte
39 func (id PeerId) String() string {
40 return hex.EncodeToString(id[:])
43 type cipherCache map[PeerId]*xtea.Cipher
48 cipherCacheLock sync.RWMutex
51 // Initialize (pre-cache) available peers info.
52 func PeersInit(path string) {
54 IDsCache = make(map[PeerId]*xtea.Cipher)
58 time.Sleep(RefreshRate)
63 // Initialize dummy cache for client-side usage. It will consist only
65 func PeersInitDummy(id *PeerId) {
66 IDsCache = make(map[PeerId]*xtea.Cipher)
67 cipher, err := xtea.NewCipher(id[:])
71 IDsCache[*id] = cipher
74 // Refresh IDsCache: remove disappeared keys, add missing ones with
75 // initialized ciphers.
76 func (cc cipherCache) refresh() {
77 dir, err := os.Open(PeersPath)
81 peerIds, err := dir.Readdirnames(0)
85 available := make(map[PeerId]bool)
86 for _, peerId := range peerIds {
87 id := IDDecode(peerId)
94 cipherCacheLock.Lock()
95 // Cleanup deleted ones from cache
96 for k, _ := range cc {
97 if _, exists := available[k]; !exists {
99 log.Println("Cleaning key: ", k)
103 for peerId, _ := range available {
104 if _, exists := cc[peerId]; !exists {
105 log.Println("Adding key", peerId)
106 cipher, err := xtea.NewCipher(peerId[:])
113 cipherCacheLock.Unlock()
116 // Try to find peer's identity (that equals to an encryption key)
117 // by taking first blocksize sized bytes from data at the beginning
118 // as plaintext and last bytes as cyphertext.
119 func (cc cipherCache) Find(data []byte) *PeerId {
120 if len(data) < xtea.BlockSize*2 {
123 buf := make([]byte, xtea.BlockSize)
124 cipherCacheLock.RLock()
125 for pid, cipher := range cc {
126 cipher.Decrypt(buf, data[len(data)-xtea.BlockSize:])
127 if subtle.ConstantTimeCompare(buf, data[:xtea.BlockSize]) == 1 {
129 cipherCacheLock.RUnlock()
133 cipherCacheLock.RUnlock()
137 // Decode identification string.
138 // It must be 32 hexadecimal characters long.
139 // If it is not the valid one, then return nil.
140 func IDDecode(raw string) *PeerId {
141 if len(raw) != IDSize*2 {
144 idDecoded, err := hex.DecodeString(raw)
148 idP := new([IDSize]byte)
149 copy(idP[:], idDecoded)