]> Cypherpunks.ru repositories - govpn.git/blob - src/govpn/identify.go
c7675b6368b48cc62e7eef3180e8515ac1421e1b
[govpn.git] / src / govpn / identify.go
1 /*
2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2015 Sergey Matveev <stargrave@stargrave.org>
4
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.
9
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.
14
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/>.
17 */
18
19 package govpn
20
21 import (
22         "crypto/subtle"
23         "encoding/hex"
24         "errors"
25         "io/ioutil"
26         "log"
27         "os"
28         "path"
29         "strconv"
30         "strings"
31         "sync"
32         "time"
33
34         "github.com/agl/ed25519"
35         "golang.org/x/crypto/xtea"
36 )
37
38 const (
39         IDSize      = 128 / 8
40         RefreshRate = 60 * time.Second
41 )
42
43 type PeerId [IDSize]byte
44
45 func (id PeerId) String() string {
46         return hex.EncodeToString(id[:])
47 }
48
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) {
52         result := id.String()
53         if name, err := ioutil.ReadFile(path.Join(PeersPath, result, "name")); err == nil {
54                 result = strings.TrimRight(string(name), "\n")
55         }
56         return []byte(`"` + result + `"`), nil
57 }
58
59 type PeerConf struct {
60         Id          *PeerId
61         Timeout     time.Duration
62         NoiseEnable bool
63         CPR         int
64         // This is passphrase verifier
65         DSAPub *[ed25519.PublicKeySize]byte
66         // This field exists only in dummy configuration on client's side
67         DSAPriv *[ed25519.PrivateKeySize]byte
68 }
69
70 type cipherCache map[PeerId]*xtea.Cipher
71
72 var (
73         PeersPath       string
74         IDsCache        cipherCache
75         cipherCacheLock sync.RWMutex
76         dummyConf       *PeerConf
77 )
78
79 // Initialize (pre-cache) available peers info.
80 func PeersInit(path string) {
81         PeersPath = path
82         IDsCache = make(map[PeerId]*xtea.Cipher)
83         go func() {
84                 for {
85                         IDsCache.refresh()
86                         time.Sleep(RefreshRate)
87                 }
88         }()
89 }
90
91 // Initialize dummy cache for client-side usage.
92 func PeersInitDummy(id *PeerId, conf *PeerConf) {
93         IDsCache = make(map[PeerId]*xtea.Cipher)
94         cipher, err := xtea.NewCipher(id[:])
95         if err != nil {
96                 panic(err)
97         }
98         IDsCache[*id] = cipher
99         dummyConf = conf
100 }
101
102 // Refresh IDsCache: remove disappeared keys, add missing ones with
103 // initialized ciphers.
104 func (cc cipherCache) refresh() {
105         dir, err := os.Open(PeersPath)
106         if err != nil {
107                 panic(err)
108         }
109         peerIds, err := dir.Readdirnames(0)
110         if err != nil {
111                 panic(err)
112         }
113         available := make(map[PeerId]bool)
114         for _, peerId := range peerIds {
115                 id, err := IDDecode(peerId)
116                 if err != nil {
117                         continue
118                 }
119                 available[*id] = true
120         }
121
122         cipherCacheLock.Lock()
123         // Cleanup deleted ones from cache
124         for k, _ := range cc {
125                 if _, exists := available[k]; !exists {
126                         delete(cc, k)
127                         log.Println("Cleaning key: ", k)
128                 }
129         }
130         // Add missing ones
131         for peerId, _ := range available {
132                 if _, exists := cc[peerId]; !exists {
133                         log.Println("Adding key", peerId)
134                         cipher, err := xtea.NewCipher(peerId[:])
135                         if err != nil {
136                                 panic(err)
137                         }
138                         cc[peerId] = cipher
139                 }
140         }
141         cipherCacheLock.Unlock()
142 }
143
144 // Try to find peer's identity (that equals to an encryption key)
145 // by taking first blocksize sized bytes from data at the beginning
146 // as plaintext and last bytes as cyphertext.
147 func (cc cipherCache) Find(data []byte) *PeerId {
148         if len(data) < xtea.BlockSize*2 {
149                 return nil
150         }
151         buf := make([]byte, xtea.BlockSize)
152         cipherCacheLock.RLock()
153         for pid, cipher := range cc {
154                 cipher.Decrypt(buf, data[len(data)-xtea.BlockSize:])
155                 if subtle.ConstantTimeCompare(buf, data[:xtea.BlockSize]) == 1 {
156                         ppid := PeerId(pid)
157                         cipherCacheLock.RUnlock()
158                         return &ppid
159                 }
160         }
161         cipherCacheLock.RUnlock()
162         return nil
163 }
164
165 func readIntFromFile(path string) (int, error) {
166         data, err := ioutil.ReadFile(path)
167         if err != nil {
168                 return 0, err
169         }
170         val, err := strconv.Atoi(strings.TrimRight(string(data), "\n"))
171         if err != nil {
172                 return 0, err
173         }
174         return val, nil
175 }
176
177 // Get peer related configuration.
178 func (id *PeerId) Conf() *PeerConf {
179         if dummyConf != nil {
180                 return dummyConf
181         }
182         conf := PeerConf{Id: id, NoiseEnable: false, CPR: 0}
183         peerPath := path.Join(PeersPath, id.String())
184
185         verPath := path.Join(peerPath, "verifier")
186         keyData, err := ioutil.ReadFile(verPath)
187         if err != nil {
188                 log.Println("Unable to read verifier:", verPath)
189                 return nil
190         }
191         if len(keyData) < ed25519.PublicKeySize*2 {
192                 log.Println("Verifier must be 64 hex characters long:", verPath)
193                 return nil
194         }
195         keyDecoded, err := hex.DecodeString(string(keyData[:ed25519.PublicKeySize*2]))
196         if err != nil {
197                 log.Println("Unable to decode the key:", err.Error(), verPath)
198                 return nil
199         }
200         conf.DSAPub = new([ed25519.PublicKeySize]byte)
201         copy(conf.DSAPub[:], keyDecoded)
202
203         timeout := TimeoutDefault
204         if val, err := readIntFromFile(path.Join(peerPath, "timeout")); err == nil {
205                 timeout = val
206         }
207         conf.Timeout = time.Second * time.Duration(timeout)
208
209         if val, err := readIntFromFile(path.Join(peerPath, "noise")); err == nil && val == 1 {
210                 conf.NoiseEnable = true
211         }
212         if val, err := readIntFromFile(path.Join(peerPath, "cpr")); err == nil {
213                 conf.CPR = val
214         }
215         return &conf
216 }
217
218 // Decode identification string.
219 // It must be 32 hexadecimal characters long.
220 func IDDecode(raw string) (*PeerId, error) {
221         if len(raw) != IDSize*2 {
222                 return nil, errors.New("ID must be 32 characters long")
223         }
224         idDecoded, err := hex.DecodeString(raw)
225         if err != nil {
226                 return nil, errors.New("ID must contain hexadecimal characters only")
227         }
228         idP := new([IDSize]byte)
229         copy(idP[:], idDecoded)
230         id := PeerId(*idP)
231         return &id, nil
232 }