]> Cypherpunks.ru repositories - govpn.git/blob - src/cypherpunks.ru/govpn/identity.go
Could -> can, for consistency
[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(fields).WithField("size", mc.Length()).Debug("Cleaned, add/update new key")
90         for pid, pc := range *peers {
91                 if _, exists := mc.cache[pid]; exists {
92                         logger.WithFields(fields).WithFields(
93                                 logrus.Fields{
94                                         "pid":    pid.String(),
95                                         "old_ts": mc.cache[pid].ts,
96                                         "new_ts": pc.TimeSync,
97                                 }).Debug("Rest timesync")
98                         mc.cache[pid].ts = pc.TimeSync
99                 } else {
100                         before := time.Now()
101                         mac, err := blake2b.New256(pid[:])
102                         if err != nil {
103                                 return errors.Wrap(err, wrapBlake2bNew256)
104                         }
105                         logger.WithFields(fields).WithFields(logrus.Fields{
106                                 "pid":     pid.String(),
107                                 "ts":      pc.TimeSync,
108                                 "elapsed": time.Now().Sub(before).String(),
109                         }).Debug("Adding key")
110                         mc.cache[pid] = &MACAndTimeSync{
111                                 mac: mac,
112                                 ts:  pc.TimeSync,
113                         }
114                 }
115         }
116         logger.WithFields(fields).WithField("size", mc.Length()).Debug("Finish")
117         return nil
118 }
119
120 // AddTimeSync XORs timestamp with data if timeSync > 0
121 func AddTimeSync(ts int, data []byte) {
122         fields := logrus.Fields{
123                 "func":      logFuncPrefix + "AddTimeSync",
124                 "ts":        ts,
125                 "data_size": len(data),
126                 "data":      hex.EncodeToString(data),
127         }
128         if ts == 0 {
129                 return
130         }
131         buf := make([]byte, 8)
132         binary.BigEndian.PutUint64(buf, uint64(time.Now().Unix()/int64(ts)*int64(ts)))
133         for i := 0; i < 8; i++ {
134                 data[i] ^= buf[i]
135         }
136         logger.WithFields(fields).WithField("after", hex.EncodeToString(data)).Debug("Done")
137 }
138
139 // Find tries to find peer's identity (that equals to MAC)
140 // by taking first blocksize sized bytes from data at the beginning
141 // as plaintext and last bytes as cyphertext.
142 func (mc *MACCache) Find(data []byte) (*PeerID, error) {
143         const minimumSize = 8 * 2
144         lenData := len(data)
145         fields := logrus.Fields{
146                 "func": logFuncPrefix + "MACCache.Find",
147                 "data": lenData,
148                 "size": mc.Length(),
149         }
150         logger.WithFields(fields).Debug("Starting")
151         if lenData < minimumSize {
152                 return nil, errors.Errorf("MAC is too small %d, minimum %d", lenData, minimumSize)
153         }
154         buf := make([]byte, 8)
155         sum := make([]byte, 32)
156         mc.l.RLock()
157         defer mc.l.RUnlock()
158         for pid, mt := range mc.cache {
159                 loopFields := logrus.Fields{"pid": pid.String()}
160                 logger.WithFields(loopFields).Debug("process")
161                 copy(buf, data)
162                 AddTimeSync(mt.ts, buf)
163                 mt.l.Lock()
164                 mt.mac.Reset()
165                 logger.WithFields(fields).WithField("buf", hex.EncodeToString(buf)).Debug("mt.mac.Write")
166                 if _, err := mt.mac.Write(buf); err != nil {
167                         mt.l.Unlock()
168                         return nil, errors.Wrap(err, "mt.mac.Write")
169                 }
170                 logger.WithFields(fields).WithField("buf", hex.EncodeToString(buf[:0])).Debug("mt.mac.Sum")
171                 mt.mac.Sum(sum[:0])
172                 mt.l.Unlock()
173
174                 if subtle.ConstantTimeCompare(sum[len(sum)-8:], data[lenData-8:]) == 1 {
175                         logger.WithFields(fields).WithFields(loopFields).Debug("Matching peer")
176                         ppid := PeerID(pid)
177                         return &ppid, nil
178                 }
179
180                 logger.WithFields(fields).WithFields(loopFields).Debug("Not matching peer")
181         }
182         logger.WithFields(fields).Debug("Can't find matching peer ID")
183         return nil, nil
184 }