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/>.
28 "github.com/agl/ed25519"
29 "github.com/agl/ed25519/extra25519"
30 "github.com/dchest/blake2b"
31 "golang.org/x/crypto/curve25519"
32 "golang.org/x/crypto/salsa20"
33 "golang.org/x/crypto/xtea"
41 type Handshake struct {
46 dsaPubH *[ed25519.PublicKeySize]byte
49 dhPriv *[32]byte // own private DH key
50 rServer *[RSize]byte // random string for authentication
52 sServer *[SSize]byte // secret string for main key calculation
56 func keyFromSecrets(server, client []byte) *[SSize]byte {
58 for i := 0; i < SSize; i++ {
59 k[i] = server[i] ^ client[i]
64 // Zero handshake's memory state
65 func (h *Handshake) Zero() {
67 SliceZero(h.rNonce[:])
70 SliceZero(h.dhPriv[:])
76 SliceZero(h.dsaPubH[:])
79 SliceZero(h.rServer[:])
82 SliceZero(h.rClient[:])
85 SliceZero(h.sServer[:])
88 SliceZero(h.sClient[:])
92 func (h *Handshake) rNonceNext(count uint64) []byte {
93 nonce := make([]byte, RSize)
94 nonceCurrent, _ := binary.Uvarint(h.rNonce[:])
95 binary.PutUvarint(nonce, nonceCurrent+count)
99 func dhKeypairGen() (*[32]byte, *[32]byte) {
100 priv := new([32]byte)
102 repr := new([32]byte)
105 if _, err := Rand.Read(priv[:]); err != nil {
106 log.Fatalln("Error reading random for DH private key:", err)
108 reprFound = extra25519.ScalarBaseMult(pub, repr, priv)
113 func dhKeyGen(priv, pub *[32]byte) *[32]byte {
115 curve25519.ScalarMult(key, priv, pub)
116 hashed := blake2b.Sum256(key[:])
120 // Create new handshake state.
121 func NewHandshake(addr string, conn io.Writer, conf *PeerConf) *Handshake {
125 LastPing: time.Now(),
128 state.dsaPubH = new([ed25519.PublicKeySize]byte)
129 copy(state.dsaPubH[:], state.Conf.Verifier.Pub[:])
130 hashed := blake2b.Sum256(state.dsaPubH[:])
131 state.dsaPubH = &hashed
135 // Generate ID tag from client identification and data.
136 func idTag(id *PeerId, data []byte) []byte {
137 ciph, err := xtea.NewCipher(id[:])
141 enc := make([]byte, xtea.BlockSize)
142 ciph.Encrypt(enc, data[:xtea.BlockSize])
146 // Start handshake's procedure from the client. It is the entry point
147 // for starting the handshake procedure. // First handshake packet
148 // will be sent immediately.
149 func HandshakeStart(addr string, conn io.Writer, conf *PeerConf) *Handshake {
150 state := NewHandshake(addr, conn, conf)
151 var dhPubRepr *[32]byte
152 state.dhPriv, dhPubRepr = dhKeypairGen()
154 state.rNonce = new([RSize]byte)
155 if _, err := Rand.Read(state.rNonce[:]); err != nil {
156 log.Fatalln("Error reading random for nonce:", err)
160 enc = make([]byte, conf.MTU-xtea.BlockSize-RSize)
162 enc = make([]byte, 32)
164 copy(enc, dhPubRepr[:])
167 enc, err = EnclessEncode(state.dsaPubH, state.rNonce[:], enc)
172 salsa20.XORKeyStream(enc, enc, state.rNonce[:], state.dsaPubH)
174 data := append(state.rNonce[:], enc...)
175 data = append(data, idTag(state.Conf.Id, state.rNonce[:])...)
176 state.conn.Write(data)
180 // Process handshake message on the server side.
181 // This function is intended to be called on server's side.
182 // If this is the final handshake message, then new Peer object
183 // will be created and used as a transport. If no mutually
184 // authenticated Peer is ready, then return nil.
185 func (h *Handshake) Server(data []byte) *Peer {
186 // R + ENC(H(DSAPub), R, El(CDHPub)) + IDtag
187 if h.rNonce == nil && ((!h.Conf.Encless && len(data) >= 48) ||
188 (h.Conf.Encless && len(data) == EnclessEnlargeSize+h.Conf.MTU)) {
189 h.rNonce = new([RSize]byte)
190 copy(h.rNonce[:], data[:RSize])
192 // Decrypt remote public key
193 cDHRepr := new([32]byte)
195 out, err := EnclessDecode(
198 data[RSize:len(data)-xtea.BlockSize],
201 log.Println("Unable to decode packet from", h.addr, err)
204 copy(cDHRepr[:], out)
206 salsa20.XORKeyStream(
208 data[RSize:RSize+32],
214 // Generate DH keypair
215 var dhPubRepr *[32]byte
216 h.dhPriv, dhPubRepr = dhKeypairGen()
218 // Compute shared key
220 extra25519.RepresentativeToPublicKey(cDH, cDHRepr)
221 h.key = dhKeyGen(h.dhPriv, cDH)
226 encPub = make([]byte, h.Conf.MTU)
227 copy(encPub, dhPubRepr[:])
228 encPub, err = EnclessEncode(h.dsaPubH, h.rNonceNext(1), encPub)
233 encPub = make([]byte, 32)
234 salsa20.XORKeyStream(encPub, dhPubRepr[:], h.rNonceNext(1), h.dsaPubH)
237 // Generate R* and encrypt them
238 h.rServer = new([RSize]byte)
239 if _, err = Rand.Read(h.rServer[:]); err != nil {
240 log.Fatalln("Error reading random for R:", err)
242 h.sServer = new([SSize]byte)
243 if _, err = Rand.Read(h.sServer[:]); err != nil {
244 log.Fatalln("Error reading random for S:", err)
247 if h.Conf.Noise && !h.Conf.Encless {
248 encRs = make([]byte, h.Conf.MTU-len(encPub)-xtea.BlockSize)
249 } else if h.Conf.Encless {
250 encRs = make([]byte, h.Conf.MTU-xtea.BlockSize)
252 encRs = make([]byte, RSize+SSize)
254 copy(encRs, append(h.rServer[:], h.sServer[:]...))
256 encRs, err = EnclessEncode(h.key, h.rNonce[:], encRs)
261 salsa20.XORKeyStream(encRs, encRs, h.rNonce[:], h.key)
264 // Send that to client
265 h.conn.Write(append(encPub, append(encRs, idTag(h.Conf.Id, encPub)...)...))
266 h.LastPing = time.Now()
268 // ENC(K, R+1, RS + RC + SC + Sign(DSAPriv, K)) + IDtag
269 if h.rClient == nil && ((!h.Conf.Encless && len(data) >= 120) ||
270 (h.Conf.Encless && len(data) == EnclessEnlargeSize+h.Conf.MTU)) {
274 dec, err = EnclessDecode(
277 data[:len(data)-xtea.BlockSize],
280 log.Println("Unable to decode packet from", h.addr, err)
283 dec = dec[:RSize+RSize+SSize+ed25519.SignatureSize]
285 dec = make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
286 salsa20.XORKeyStream(
288 data[:RSize+RSize+SSize+ed25519.SignatureSize],
293 if subtle.ConstantTimeCompare(dec[:RSize], h.rServer[:]) != 1 {
294 log.Println("Invalid server's random number with", h.addr)
297 sign := new([ed25519.SignatureSize]byte)
298 copy(sign[:], dec[RSize+RSize+SSize:])
299 if !ed25519.Verify(h.Conf.Verifier.Pub, h.key[:], sign) {
300 log.Println("Invalid signature from", h.addr)
304 // Send final answer to client
307 enc = make([]byte, h.Conf.MTU-xtea.BlockSize)
309 enc = make([]byte, RSize)
311 copy(enc, dec[RSize:RSize+RSize])
313 enc, err = EnclessEncode(h.key, h.rNonceNext(2), enc)
318 salsa20.XORKeyStream(enc, enc, h.rNonceNext(2), h.key)
320 h.conn.Write(append(enc, idTag(h.Conf.Id, enc)...))
328 keyFromSecrets(h.sServer[:], dec[RSize+RSize:RSize+RSize+SSize]))
329 h.LastPing = time.Now()
332 log.Println("Invalid handshake message from", h.addr)
337 // Process handshake message on the client side.
338 // This function is intended to be called on client's side.
339 // If this is the final handshake message, then new Peer object
340 // will be created and used as a transport. If no mutually
341 // authenticated Peer is ready, then return nil.
342 func (h *Handshake) Client(data []byte) *Peer {
343 // ENC(H(DSAPub), R+1, El(SDHPub)) + ENC(K, R, RS + SS) + IDtag
344 if h.rServer == nil && h.key == nil &&
345 ((!h.Conf.Encless && len(data) >= 80) ||
346 (h.Conf.Encless && len(data) == 2*(EnclessEnlargeSize+h.Conf.MTU))) {
347 // Decrypt remote public key
348 sDHRepr := new([32]byte)
352 tmp, err = EnclessDecode(
358 log.Println("Unable to decode packet from", h.addr, err)
361 copy(sDHRepr[:], tmp[:32])
363 salsa20.XORKeyStream(
371 // Compute shared key
373 extra25519.RepresentativeToPublicKey(sDH, sDHRepr)
374 h.key = dhKeyGen(h.dhPriv, sDH)
377 h.rServer = new([RSize]byte)
378 h.sServer = new([SSize]byte)
380 tmp, err = EnclessDecode(
383 data[len(data)/2:len(data)-xtea.BlockSize],
386 log.Println("Unable to decode packet from", h.addr, err)
389 copy(h.rServer[:], tmp[:RSize])
390 copy(h.sServer[:], tmp[RSize:RSize+SSize])
392 decRs := make([]byte, RSize+SSize)
393 salsa20.XORKeyStream(
395 data[SSize:SSize+RSize+SSize],
399 copy(h.rServer[:], decRs[:RSize])
400 copy(h.sServer[:], decRs[RSize:])
403 // Generate R* and signature and encrypt them
404 h.rClient = new([RSize]byte)
405 if _, err = Rand.Read(h.rClient[:]); err != nil {
406 log.Fatalln("Error reading random for R:", err)
408 h.sClient = new([SSize]byte)
409 if _, err = Rand.Read(h.sClient[:]); err != nil {
410 log.Fatalln("Error reading random for S:", err)
412 sign := ed25519.Sign(h.Conf.DSAPriv, h.key[:])
416 enc = make([]byte, h.Conf.MTU-xtea.BlockSize)
418 enc = make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
420 copy(enc, h.rServer[:])
421 copy(enc[RSize:], h.rClient[:])
422 copy(enc[RSize+RSize:], h.sClient[:])
423 copy(enc[RSize+RSize+SSize:], sign[:])
425 enc, err = EnclessEncode(h.key, h.rNonceNext(1), enc)
430 salsa20.XORKeyStream(enc, enc, h.rNonceNext(1), h.key)
433 // Send that to server
434 h.conn.Write(append(enc, idTag(h.Conf.Id, enc)...))
435 h.LastPing = time.Now()
437 // ENC(K, R+2, RC) + IDtag
438 if h.key != nil && ((!h.Conf.Encless && len(data) >= 16) ||
439 (h.Conf.Encless && len(data) == EnclessEnlargeSize+h.Conf.MTU)) {
444 dec, err = EnclessDecode(
447 data[:len(data)-xtea.BlockSize],
450 log.Println("Unable to decode packet from", h.addr, err)
455 dec = make([]byte, RSize)
456 salsa20.XORKeyStream(dec, data[:RSize], h.rNonceNext(2), h.key)
458 if subtle.ConstantTimeCompare(dec, h.rClient[:]) != 1 {
459 log.Println("Invalid client's random number with", h.addr)
469 keyFromSecrets(h.sServer[:], h.sClient[:]),
471 h.LastPing = time.Now()
474 log.Println("Invalid handshake stage from", h.addr)