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/>.
29 "golang.org/x/crypto/xtea"
36 type PeerId [IDSize]byte
38 func (id PeerId) String() string {
39 return base64.RawStdEncoding.EncodeToString(id[:])
42 func (id PeerId) MarshalJSON() ([]byte, error) {
43 return []byte(`"` + id.String() + `"`), nil
46 type CipherAndTimeSync struct {
51 type CipherCache struct {
52 c map[PeerId]*CipherAndTimeSync
56 func NewCipherCache() *CipherCache {
57 return &CipherCache{c: make(map[PeerId]*CipherAndTimeSync)}
60 // Remove disappeared keys, add missing ones with initialized ciphers.
61 func (cc *CipherCache) Update(peers *map[PeerId]*PeerConf) {
63 for pid, _ := range cc.c {
64 if _, exists := (*peers)[pid]; !exists {
65 log.Println("Cleaning key:", pid)
69 for pid, pc := range *peers {
70 if _, exists := cc.c[pid]; exists {
71 cc.c[pid].t = pc.TimeSync
73 log.Println("Adding key", pid)
74 cipher, err := xtea.NewCipher(pid[:])
78 cc.c[pid] = &CipherAndTimeSync{cipher, pc.TimeSync}
84 // If timeSync > 0, then XOR timestamp with the data.
85 func AddTimeSync(ts int, data []byte) {
89 buf := make([]byte, 8)
90 binary.BigEndian.PutUint64(buf, uint64(time.Now().Unix()/int64(ts)*int64(ts)))
91 for i := 0; i < 8; i++ {
96 // Try to find peer's identity (that equals to an encryption key)
97 // by taking first blocksize sized bytes from data at the beginning
98 // as plaintext and last bytes as cyphertext.
99 func (cc *CipherCache) Find(data []byte) *PeerId {
100 if len(data) < xtea.BlockSize*2 {
103 buf := make([]byte, xtea.BlockSize)
105 for pid, ct := range cc.c {
106 ct.c.Decrypt(buf, data[len(data)-xtea.BlockSize:])
107 AddTimeSync(ct.t, buf)
108 if subtle.ConstantTimeCompare(buf, data[:xtea.BlockSize]) == 1 {