2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2016 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/>.
30 "golang.org/x/crypto/blake2b"
37 type PeerId [IDSize]byte
39 func (id PeerId) String() string {
40 return base64.RawStdEncoding.EncodeToString(id[:])
43 func (id PeerId) MarshalJSON() ([]byte, error) {
44 return []byte(`"` + id.String() + `"`), nil
47 type MACAndTimeSync struct {
53 type MACCache struct {
54 cache map[PeerId]*MACAndTimeSync
58 func NewMACCache() *MACCache {
59 return &MACCache{cache: make(map[PeerId]*MACAndTimeSync)}
62 // Remove disappeared keys, add missing ones with initialized MACs.
63 func (mc *MACCache) Update(peers *map[PeerId]*PeerConf) {
65 for pid, _ := range mc.cache {
66 if _, exists := (*peers)[pid]; !exists {
67 log.Println("Cleaning key:", pid)
71 for pid, pc := range *peers {
72 if _, exists := mc.cache[pid]; exists {
73 mc.cache[pid].ts = pc.TimeSync
75 log.Println("Adding key", pid)
76 mac, err := blake2b.New256(pid[:])
80 mc.cache[pid] = &MACAndTimeSync{
89 // If timeSync > 0, then XOR timestamp with the data.
90 func AddTimeSync(ts int, data []byte) {
94 buf := make([]byte, 8)
95 binary.BigEndian.PutUint64(buf, uint64(time.Now().Unix()/int64(ts)*int64(ts)))
96 for i := 0; i < 8; i++ {
101 // Try to find peer's identity (that equals to MAC)
102 // by taking first blocksize sized bytes from data at the beginning
103 // as plaintext and last bytes as cyphertext.
104 func (mc *MACCache) Find(data []byte) *PeerId {
108 buf := make([]byte, 8)
110 for pid, mt := range mc.cache {
112 AddTimeSync(mt.ts, buf)
118 if subtle.ConstantTimeCompare(buf, data[len(data)-8:]) == 1 {