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/>.
27 "golang.org/x/crypto/xtea"
34 type PeerId [IDSize]byte
36 func (id PeerId) String() string {
37 return hex.EncodeToString(id[:])
40 func (id PeerId) MarshalJSON() ([]byte, error) {
41 return []byte(`"` + id.String() + `"`), nil
44 type CipherCache struct {
45 c map[PeerId]*xtea.Cipher
49 func NewCipherCache(peerIds []PeerId) CipherCache {
50 cc := CipherCache{c: make(map[PeerId]*xtea.Cipher, len(peerIds))}
55 // Remove disappeared keys, add missing ones with initialized ciphers.
56 func (cc CipherCache) Update(peerIds []PeerId) {
57 available := make(map[PeerId]struct{})
58 for _, peerId := range peerIds {
59 available[peerId] = struct{}{}
62 for k, _ := range cc.c {
63 if _, exists := available[k]; !exists {
64 log.Println("Cleaning key:", k)
68 for peerId, _ := range available {
69 if _, exists := cc.c[peerId]; !exists {
70 log.Println("Adding key", peerId)
71 cipher, err := xtea.NewCipher(peerId[:])
81 // Try to find peer's identity (that equals to an encryption key)
82 // by taking first blocksize sized bytes from data at the beginning
83 // as plaintext and last bytes as cyphertext.
84 func (cc CipherCache) Find(data []byte) *PeerId {
85 if len(data) < xtea.BlockSize*2 {
88 buf := make([]byte, xtea.BlockSize)
90 for pid, cipher := range cc.c {
91 cipher.Decrypt(buf, data[len(data)-xtea.BlockSize:])
92 if subtle.ConstantTimeCompare(buf, data[:xtea.BlockSize]) == 1 {