]> Cypherpunks.ru repositories - govpn.git/blob - identify.go
6c16da08a2a3c1cc124f0b0995b99142e24aad59
[govpn.git] / 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         "io/ioutil"
25         "log"
26         "os"
27         "path"
28         "strings"
29         "sync"
30         "time"
31
32         "golang.org/x/crypto/xtea"
33 )
34
35 const (
36         IDSize      = 128 / 8
37         RefreshRate = 60 * time.Second
38 )
39
40 type PeerId [IDSize]byte
41
42 func (id PeerId) String() string {
43         return hex.EncodeToString(id[:])
44 }
45
46 // Return human readable name of the peer.
47 // It equals either to peers/PEER/name file contents or PEER's hex.
48 func (id PeerId) MarshalJSON() ([]byte, error) {
49         result := id.String()
50         if name, err := ioutil.ReadFile(path.Join(PeersPath, result, "name")); err == nil {
51                 result = strings.TrimRight(string(name), "\n")
52         }
53         return []byte(`"` + result + `"`), nil
54 }
55
56 type cipherCache map[PeerId]*xtea.Cipher
57
58 var (
59         PeersPath       string
60         IDsCache        cipherCache
61         cipherCacheLock sync.RWMutex
62 )
63
64 // Initialize (pre-cache) available peers info.
65 func PeersInit(path string) {
66         PeersPath = path
67         IDsCache = make(map[PeerId]*xtea.Cipher)
68         go func() {
69                 for {
70                         IDsCache.refresh()
71                         time.Sleep(RefreshRate)
72                 }
73         }()
74 }
75
76 // Initialize dummy cache for client-side usage. It will consist only
77 // of single key.
78 func PeersInitDummy(id *PeerId) {
79         IDsCache = make(map[PeerId]*xtea.Cipher)
80         cipher, err := xtea.NewCipher(id[:])
81         if err != nil {
82                 panic(err)
83         }
84         IDsCache[*id] = cipher
85 }
86
87 // Refresh IDsCache: remove disappeared keys, add missing ones with
88 // initialized ciphers.
89 func (cc cipherCache) refresh() {
90         dir, err := os.Open(PeersPath)
91         if err != nil {
92                 panic(err)
93         }
94         peerIds, err := dir.Readdirnames(0)
95         if err != nil {
96                 panic(err)
97         }
98         available := make(map[PeerId]bool)
99         for _, peerId := range peerIds {
100                 id := IDDecode(peerId)
101                 if id == nil {
102                         continue
103                 }
104                 available[*id] = true
105         }
106
107         cipherCacheLock.Lock()
108         // Cleanup deleted ones from cache
109         for k, _ := range cc {
110                 if _, exists := available[k]; !exists {
111                         delete(cc, k)
112                         log.Println("Cleaning key: ", k)
113                 }
114         }
115         // Add missing ones
116         for peerId, _ := range available {
117                 if _, exists := cc[peerId]; !exists {
118                         log.Println("Adding key", peerId)
119                         cipher, err := xtea.NewCipher(peerId[:])
120                         if err != nil {
121                                 panic(err)
122                         }
123                         cc[peerId] = cipher
124                 }
125         }
126         cipherCacheLock.Unlock()
127 }
128
129 // Try to find peer's identity (that equals to an encryption key)
130 // by taking first blocksize sized bytes from data at the beginning
131 // as plaintext and last bytes as cyphertext.
132 func (cc cipherCache) Find(data []byte) *PeerId {
133         if len(data) < xtea.BlockSize*2 {
134                 return nil
135         }
136         buf := make([]byte, xtea.BlockSize)
137         cipherCacheLock.RLock()
138         for pid, cipher := range cc {
139                 cipher.Decrypt(buf, data[len(data)-xtea.BlockSize:])
140                 if subtle.ConstantTimeCompare(buf, data[:xtea.BlockSize]) == 1 {
141                         ppid := PeerId(pid)
142                         cipherCacheLock.RUnlock()
143                         return &ppid
144                 }
145         }
146         cipherCacheLock.RUnlock()
147         return nil
148 }
149
150 // Decode identification string.
151 // It must be 32 hexadecimal characters long.
152 // If it is not the valid one, then return nil.
153 func IDDecode(raw string) *PeerId {
154         if len(raw) != IDSize*2 {
155                 return nil
156         }
157         idDecoded, err := hex.DecodeString(raw)
158         if err != nil {
159                 return nil
160         }
161         idP := new([IDSize]byte)
162         copy(idP[:], idDecoded)
163         id := PeerId(*idP)
164         return &id
165 }