]> Cypherpunks.ru repositories - govpn.git/blob - src/cypherpunks.ru/govpn/identity.go
db338f0348c98b9e5593c17872664e663e9eda17
[govpn.git] / src / cypherpunks.ru / govpn / identity.go
1 /*
2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2017 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/base64"
24         "encoding/binary"
25         "encoding/hex"
26         "hash"
27         "sync"
28         "time"
29
30         "github.com/Sirupsen/logrus"
31         "github.com/pkg/errors"
32         "golang.org/x/crypto/blake2b"
33 )
34
35 // IDSize is a size of GoVPN peer's identity
36 const IDSize = 128 / 8
37
38 // PeerID is identifier of a single GoVPN peer (client)
39 type PeerID [IDSize]byte
40
41 // String returns peer's ID in stringified form
42 func (id PeerID) String() string {
43         return base64.RawStdEncoding.EncodeToString(id[:])
44 }
45
46 // MarshalJSON returns a JSON serialized peer's ID
47 func (id PeerID) MarshalJSON() ([]byte, error) {
48         return []byte(`"` + id.String() + `"`), nil
49 }
50
51 // MACAndTimeSync is a single peer MAC and timesync
52 type MACAndTimeSync struct {
53         mac hash.Hash
54         ts  int
55         l   sync.Mutex
56 }
57
58 // MACCache caches all MACAndTimeSync for peers allowed to connect
59 type MACCache struct {
60         cache map[PeerID]*MACAndTimeSync
61         l     sync.RWMutex
62 }
63
64 // Length returns size of MACCache
65 func (mc *MACCache) Length() int {
66         return len(mc.cache)
67 }
68
69 // NewMACCache returns a new MACCache instance
70 func NewMACCache() *MACCache {
71         return &MACCache{cache: make(map[PeerID]*MACAndTimeSync)}
72 }
73
74 // Update removes disappeared keys, add missing ones with initialized MACs.
75 func (mc *MACCache) Update(peers *map[PeerID]*PeerConf) error {
76         mc.l.Lock()
77         defer mc.l.Unlock()
78         fields := logrus.Fields{
79                 "func":  logFuncPrefix + "MACCache.Update",
80                 "peers": len(*peers),
81         }
82         logger.WithFields(fields).WithField("size", mc.Length()).Debug("Clean old keys")
83         for pid := range mc.cache {
84                 if _, exists := (*peers)[pid]; !exists {
85                         logger.WithFields(fields).WithField("pid", pid).Debug("Cleaning key")
86                         delete(mc.cache, pid)
87                 }
88         }
89         logger.WithFields(
90                 fields,
91         ).WithField(
92                 "size",
93                 mc.Length(),
94         ).Debug("Cleaned, add/update new key")
95         for pid, pc := range *peers {
96                 if _, exists := mc.cache[pid]; exists {
97                         logger.WithFields(fields).WithFields(
98                                 logrus.Fields{
99                                         "pid":    pid.String(),
100                                         "old_ts": mc.cache[pid].ts,
101                                         "new_ts": pc.TimeSync,
102                                 }).Debug("Rest timesync")
103                         mc.cache[pid].ts = pc.TimeSync
104                 } else {
105                         before := time.Now()
106                         mac, err := blake2b.New256(pid[:])
107                         if err != nil {
108                                 return errors.Wrap(err, wrapBlake2bNew256)
109                         }
110                         logger.WithFields(fields).WithFields(logrus.Fields{
111                                 "pid":     pid.String(),
112                                 "ts":      pc.TimeSync,
113                                 "elapsed": time.Now().Sub(before).String(),
114                         }).Debug("Adding key")
115                         mc.cache[pid] = &MACAndTimeSync{
116                                 mac: mac,
117                                 ts:  pc.TimeSync,
118                         }
119                 }
120         }
121         logger.WithFields(fields).WithField("size", mc.Length()).Debug("Finish")
122         return nil
123 }
124
125 // AddTimeSync XORs timestamp with data if timeSync > 0
126 func AddTimeSync(ts int, data []byte) {
127         fields := logrus.Fields{
128                 "func":      logFuncPrefix + "AddTimeSync",
129                 "ts":        ts,
130                 "data_size": len(data),
131                 "data":      hex.EncodeToString(data),
132         }
133         if ts == 0 {
134                 return
135         }
136         buf := make([]byte, 8)
137         binary.BigEndian.PutUint64(buf, uint64(time.Now().Unix()/int64(ts)*int64(ts)))
138         for i := 0; i < 8; i++ {
139                 data[i] ^= buf[i]
140         }
141         logger.WithFields(
142                 fields,
143         ).WithField(
144                 "after",
145                 hex.EncodeToString(data),
146         ).Debug("Done")
147 }
148
149 // Find tries to find peer's identity (that equals to MAC)
150 // by taking first blocksize sized bytes from data at the beginning
151 // as plaintext and last bytes as cyphertext.
152 func (mc *MACCache) Find(data []byte) (*PeerID, error) {
153         const minimumSize = 8 * 2
154         fields := logrus.Fields{
155                 "func": logFuncPrefix + "MACCache.Find",
156                 "data": len(data),
157                 "size": mc.Length(),
158         }
159         logger.WithFields(fields).Debug("Starting")
160         if len(data) < minimumSize {
161                 return nil, errors.Errorf("MAC is too small %d, minimum %d", len(data), minimumSize)
162         }
163         buf := make([]byte, 8)
164         sum := make([]byte, 32)
165         mc.l.RLock()
166         defer mc.l.RUnlock()
167         for pid, mt := range mc.cache {
168                 loopFields := logrus.Fields{"pid": pid.String()}
169                 logger.WithFields(loopFields).Debug("process")
170                 copy(buf, data)
171                 AddTimeSync(mt.ts, buf)
172                 mt.l.Lock()
173                 mt.mac.Reset()
174                 logger.WithFields(fields).WithField("buf", hex.EncodeToString(buf)).Debug("mt.mac.Write")
175                 if _, err := mt.mac.Write(buf); err != nil {
176                         mt.l.Unlock()
177                         return nil, errors.Wrap(err, "mt.mac.Write")
178                 }
179                 logger.WithFields(
180                         fields,
181                 ).WithField(
182                         "buf",
183                         hex.EncodeToString(buf[:0]),
184                 ).Debug("mt.mac.Sum")
185                 mt.mac.Sum(sum[:0])
186                 mt.l.Unlock()
187
188                 if subtle.ConstantTimeCompare(sum[len(sum)-8:], data[len(data)-8:]) == 1 {
189                         logger.WithFields(fields).WithFields(loopFields).Debug("Matching peer")
190                         ppid := PeerID(pid)
191                         return &ppid, nil
192                 }
193
194                 logger.WithFields(fields).WithFields(loopFields).Debug("Not matching peer")
195         }
196         logger.WithFields(fields).Debug("Can't find matching peer ID")
197         return nil, nil
198 }