2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2015 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/>.
28 "golang.org/x/crypto/xtea"
35 type PeerId [IDSize]byte
37 func (id PeerId) String() string {
38 return hex.EncodeToString(id[:])
41 // Decode identification string.
42 // It must be 32 hexadecimal characters long.
43 func IDDecode(raw string) (*PeerId, error) {
44 if len(raw) != IDSize*2 {
45 return nil, errors.New("ID must be 32 characters long")
47 idDecoded, err := hex.DecodeString(raw)
49 return nil, errors.New("ID must contain hexadecimal characters only")
51 idP := new([IDSize]byte)
52 copy(idP[:], idDecoded)
57 type CipherCache struct {
58 c map[PeerId]*xtea.Cipher
62 func NewCipherCache(peerIds []PeerId) CipherCache {
63 cc := CipherCache{c: make(map[PeerId]*xtea.Cipher, len(peerIds))}
68 // Remove disappeared keys, add missing ones with initialized ciphers.
69 func (cc CipherCache) Update(peerIds []PeerId) {
70 available := make(map[PeerId]struct{})
71 for _, peerId := range peerIds {
72 available[peerId] = struct{}{}
75 for k, _ := range cc.c {
76 if _, exists := available[k]; !exists {
77 log.Println("Cleaning key:", k)
81 for peerId, _ := range available {
82 if _, exists := cc.c[peerId]; !exists {
83 log.Println("Adding key", peerId)
84 cipher, err := xtea.NewCipher(peerId[:])
94 // Try to find peer's identity (that equals to an encryption key)
95 // by taking first blocksize sized bytes from data at the beginning
96 // as plaintext and last bytes as cyphertext.
97 func (cc CipherCache) Find(data []byte) *PeerId {
98 if len(data) < xtea.BlockSize*2 {
101 buf := make([]byte, xtea.BlockSize)
103 for pid, cipher := range cc.c {
104 cipher.Decrypt(buf, data[len(data)-xtea.BlockSize:])
105 if subtle.ConstantTimeCompare(buf, data[:xtea.BlockSize]) == 1 {