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 "golang.org/x/crypto/curve25519"
31 "golang.org/x/crypto/salsa20"
32 "golang.org/x/crypto/salsa20/salsa"
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 // Apply HSalsa20 function for data. Used to hash public keys.
65 func HApply(data *[32]byte) {
66 salsa.HSalsa20(data, new([16]byte), data, &salsa.Sigma)
69 // Zero handshake's memory state
70 func (h *Handshake) Zero() {
72 SliceZero(h.rNonce[:])
75 SliceZero(h.dhPriv[:])
81 SliceZero(h.dsaPubH[:])
84 SliceZero(h.rServer[:])
87 SliceZero(h.rClient[:])
90 SliceZero(h.sServer[:])
93 SliceZero(h.sClient[:])
97 func (h *Handshake) rNonceNext(count uint64) []byte {
98 nonce := make([]byte, RSize)
99 nonceCurrent, _ := binary.Uvarint(h.rNonce[:])
100 binary.PutUvarint(nonce, nonceCurrent+count)
104 func dhKeypairGen() (*[32]byte, *[32]byte) {
105 priv := new([32]byte)
107 repr := new([32]byte)
110 if _, err := Rand.Read(priv[:]); err != nil {
111 log.Fatalln("Error reading random for DH private key:", err)
113 reprFound = extra25519.ScalarBaseMult(pub, repr, priv)
118 func dhKeyGen(priv, pub *[32]byte) *[32]byte {
120 curve25519.ScalarMult(key, priv, pub)
125 // Create new handshake state.
126 func NewHandshake(addr string, conn io.Writer, conf *PeerConf) *Handshake {
130 LastPing: time.Now(),
133 state.dsaPubH = new([ed25519.PublicKeySize]byte)
134 copy(state.dsaPubH[:], state.Conf.Verifier.Pub[:])
135 HApply(state.dsaPubH)
139 // Generate ID tag from client identification and data.
140 func idTag(id *PeerId, data []byte) []byte {
141 ciph, err := xtea.NewCipher(id[:])
145 enc := make([]byte, xtea.BlockSize)
146 ciph.Encrypt(enc, data[:xtea.BlockSize])
150 // Start handshake's procedure from the client. It is the entry point
151 // for starting the handshake procedure. // First handshake packet
152 // will be sent immediately.
153 func HandshakeStart(addr string, conn io.Writer, conf *PeerConf) *Handshake {
154 state := NewHandshake(addr, conn, conf)
155 var dhPubRepr *[32]byte
156 state.dhPriv, dhPubRepr = dhKeypairGen()
158 state.rNonce = new([RSize]byte)
159 if _, err := Rand.Read(state.rNonce[:]); err != nil {
160 log.Fatalln("Error reading random for nonce:", err)
164 enc = make([]byte, conf.MTU-xtea.BlockSize-RSize)
166 enc = make([]byte, 32)
168 copy(enc, dhPubRepr[:])
171 enc, err = EnclessEncode(state.dsaPubH, state.rNonce[:], enc)
176 salsa20.XORKeyStream(enc, enc, state.rNonce[:], state.dsaPubH)
178 data := append(state.rNonce[:], enc...)
179 data = append(data, idTag(state.Conf.Id, state.rNonce[:])...)
180 state.conn.Write(data)
184 // Process handshake message on the server side.
185 // This function is intended to be called on server's side.
186 // If this is the final handshake message, then new Peer object
187 // will be created and used as a transport. If no mutually
188 // authenticated Peer is ready, then return nil.
189 func (h *Handshake) Server(data []byte) *Peer {
190 // R + ENC(H(DSAPub), R, El(CDHPub)) + IDtag
191 if h.rNonce == nil && ((!h.Conf.Encless && len(data) >= 48) ||
192 (h.Conf.Encless && len(data) == EnclessEnlargeSize+h.Conf.MTU)) {
193 h.rNonce = new([RSize]byte)
194 copy(h.rNonce[:], data[:RSize])
196 // Decrypt remote public key
197 cDHRepr := new([32]byte)
199 out, err := EnclessDecode(
202 data[RSize:len(data)-xtea.BlockSize],
205 log.Println("Unable to decode packet from", h.addr, err)
208 copy(cDHRepr[:], out)
210 salsa20.XORKeyStream(
212 data[RSize:RSize+32],
218 // Generate DH keypair
219 var dhPubRepr *[32]byte
220 h.dhPriv, dhPubRepr = dhKeypairGen()
222 // Compute shared key
224 extra25519.RepresentativeToPublicKey(cDH, cDHRepr)
225 h.key = dhKeyGen(h.dhPriv, cDH)
230 encPub = make([]byte, h.Conf.MTU)
231 copy(encPub, dhPubRepr[:])
232 encPub, err = EnclessEncode(h.dsaPubH, h.rNonceNext(1), encPub)
237 encPub = make([]byte, 32)
238 salsa20.XORKeyStream(encPub, dhPubRepr[:], h.rNonceNext(1), h.dsaPubH)
241 // Generate R* and encrypt them
242 h.rServer = new([RSize]byte)
243 if _, err = Rand.Read(h.rServer[:]); err != nil {
244 log.Fatalln("Error reading random for R:", err)
246 h.sServer = new([SSize]byte)
247 if _, err = Rand.Read(h.sServer[:]); err != nil {
248 log.Fatalln("Error reading random for S:", err)
251 if h.Conf.Noise && !h.Conf.Encless {
252 encRs = make([]byte, h.Conf.MTU-len(encPub)-xtea.BlockSize)
253 } else if h.Conf.Encless {
254 encRs = make([]byte, h.Conf.MTU-xtea.BlockSize)
256 encRs = make([]byte, RSize+SSize)
258 copy(encRs, append(h.rServer[:], h.sServer[:]...))
260 encRs, err = EnclessEncode(h.key, h.rNonce[:], encRs)
265 salsa20.XORKeyStream(encRs, encRs, h.rNonce[:], h.key)
268 // Send that to client
269 h.conn.Write(append(encPub, append(encRs, idTag(h.Conf.Id, encPub)...)...))
270 h.LastPing = time.Now()
272 // ENC(K, R+1, RS + RC + SC + Sign(DSAPriv, K)) + IDtag
273 if h.rClient == nil && ((!h.Conf.Encless && len(data) >= 120) ||
274 (h.Conf.Encless && len(data) == EnclessEnlargeSize+h.Conf.MTU)) {
278 dec, err = EnclessDecode(
281 data[:len(data)-xtea.BlockSize],
284 log.Println("Unable to decode packet from", h.addr, err)
287 dec = dec[:RSize+RSize+SSize+ed25519.SignatureSize]
289 dec = make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
290 salsa20.XORKeyStream(
292 data[:RSize+RSize+SSize+ed25519.SignatureSize],
297 if subtle.ConstantTimeCompare(dec[:RSize], h.rServer[:]) != 1 {
298 log.Println("Invalid server's random number with", h.addr)
301 sign := new([ed25519.SignatureSize]byte)
302 copy(sign[:], dec[RSize+RSize+SSize:])
303 if !ed25519.Verify(h.Conf.Verifier.Pub, h.key[:], sign) {
304 log.Println("Invalid signature from", h.addr)
308 // Send final answer to client
311 enc = make([]byte, h.Conf.MTU-xtea.BlockSize)
313 enc = make([]byte, RSize)
315 copy(enc, dec[RSize:RSize+RSize])
317 enc, err = EnclessEncode(h.key, h.rNonceNext(2), enc)
322 salsa20.XORKeyStream(enc, enc, h.rNonceNext(2), h.key)
324 h.conn.Write(append(enc, idTag(h.Conf.Id, enc)...))
332 keyFromSecrets(h.sServer[:], dec[RSize+RSize:RSize+RSize+SSize]))
333 h.LastPing = time.Now()
336 log.Println("Invalid handshake message from", h.addr)
341 // Process handshake message on the client side.
342 // This function is intended to be called on client's side.
343 // If this is the final handshake message, then new Peer object
344 // will be created and used as a transport. If no mutually
345 // authenticated Peer is ready, then return nil.
346 func (h *Handshake) Client(data []byte) *Peer {
347 // ENC(H(DSAPub), R+1, El(SDHPub)) + ENC(K, R, RS + SS) + IDtag
348 if h.rServer == nil && h.key == nil &&
349 ((!h.Conf.Encless && len(data) >= 80) ||
350 (h.Conf.Encless && len(data) == 2*(EnclessEnlargeSize+h.Conf.MTU))) {
351 // Decrypt remote public key
352 sDHRepr := new([32]byte)
356 tmp, err = EnclessDecode(
362 log.Println("Unable to decode packet from", h.addr, err)
365 copy(sDHRepr[:], tmp[:32])
367 salsa20.XORKeyStream(
375 // Compute shared key
377 extra25519.RepresentativeToPublicKey(sDH, sDHRepr)
378 h.key = dhKeyGen(h.dhPriv, sDH)
381 h.rServer = new([RSize]byte)
382 h.sServer = new([SSize]byte)
384 tmp, err = EnclessDecode(
387 data[len(data)/2:len(data)-xtea.BlockSize],
390 log.Println("Unable to decode packet from", h.addr, err)
393 copy(h.rServer[:], tmp[:RSize])
394 copy(h.sServer[:], tmp[RSize:RSize+SSize])
396 decRs := make([]byte, RSize+SSize)
397 salsa20.XORKeyStream(
399 data[SSize:SSize+RSize+SSize],
403 copy(h.rServer[:], decRs[:RSize])
404 copy(h.sServer[:], decRs[RSize:])
407 // Generate R* and signature and encrypt them
408 h.rClient = new([RSize]byte)
409 if _, err = Rand.Read(h.rClient[:]); err != nil {
410 log.Fatalln("Error reading random for R:", err)
412 h.sClient = new([SSize]byte)
413 if _, err = Rand.Read(h.sClient[:]); err != nil {
414 log.Fatalln("Error reading random for S:", err)
416 sign := ed25519.Sign(h.Conf.DSAPriv, h.key[:])
420 enc = make([]byte, h.Conf.MTU-xtea.BlockSize)
422 enc = make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
424 copy(enc, h.rServer[:])
425 copy(enc[RSize:], h.rClient[:])
426 copy(enc[RSize+RSize:], h.sClient[:])
427 copy(enc[RSize+RSize+SSize:], sign[:])
429 enc, err = EnclessEncode(h.key, h.rNonceNext(1), enc)
434 salsa20.XORKeyStream(enc, enc, h.rNonceNext(1), h.key)
437 // Send that to server
438 h.conn.Write(append(enc, idTag(h.Conf.Id, enc)...))
439 h.LastPing = time.Now()
441 // ENC(K, R+2, RC) + IDtag
442 if h.key != nil && ((!h.Conf.Encless && len(data) >= 16) ||
443 (h.Conf.Encless && len(data) == EnclessEnlargeSize+h.Conf.MTU)) {
448 dec, err = EnclessDecode(
451 data[:len(data)-xtea.BlockSize],
454 log.Println("Unable to decode packet from", h.addr, err)
459 dec = make([]byte, RSize)
460 salsa20.XORKeyStream(dec, data[:RSize], h.rNonceNext(2), h.key)
462 if subtle.ConstantTimeCompare(dec, h.rClient[:]) != 1 {
463 log.Println("Invalid client's random number with", h.addr)
473 keyFromSecrets(h.sServer[:], h.sClient[:]),
475 h.LastPing = time.Now()
478 log.Println("Invalid handshake stage from", h.addr)