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"
40 type Handshake struct {
45 dsaPubH *[ed25519.PublicKeySize]byte
48 dhPriv *[32]byte // own private DH key
49 rServer *[RSize]byte // random string for authentication
51 sServer *[SSize]byte // secret string for main key calculation
55 func keyFromSecrets(server, client []byte) *[SSize]byte {
57 for i := 0; i < SSize; i++ {
58 k[i] = server[i] ^ client[i]
63 // Zero handshake's memory state
64 func (h *Handshake) Zero() {
66 SliceZero(h.rNonce[:])
69 SliceZero(h.dhPriv[:])
75 SliceZero(h.dsaPubH[:])
78 SliceZero(h.rServer[:])
81 SliceZero(h.rClient[:])
84 SliceZero(h.sServer[:])
87 SliceZero(h.sClient[:])
91 func (h *Handshake) rNonceNext(count uint64) []byte {
92 nonce := make([]byte, RSize)
93 nonceCurrent, _ := binary.Uvarint(h.rNonce[:])
94 binary.PutUvarint(nonce, nonceCurrent+count)
98 func dhKeypairGen() (*[32]byte, *[32]byte) {
101 repr := new([32]byte)
104 if _, err := io.ReadFull(Rand, priv[:]); err != nil {
105 log.Fatalln("Error reading random for DH private key:", err)
107 reprFound = extra25519.ScalarBaseMult(pub, repr, priv)
112 func dhKeyGen(priv, pub *[32]byte) *[32]byte {
114 curve25519.ScalarMult(key, priv, pub)
115 hashed := blake2b.Sum256(key[:])
119 // Create new handshake state.
120 func NewHandshake(addr string, conn io.Writer, conf *PeerConf) *Handshake {
124 LastPing: time.Now(),
127 state.dsaPubH = new([ed25519.PublicKeySize]byte)
128 copy(state.dsaPubH[:], state.Conf.Verifier.Pub[:])
129 hashed := blake2b.Sum256(state.dsaPubH[:])
130 state.dsaPubH = &hashed
134 // Generate ID tag from client identification and data.
135 func idTag(id *PeerId, timeSync int, data []byte) []byte {
136 enc := make([]byte, 8)
138 AddTimeSync(timeSync, enc)
139 mac := blake2b.NewMAC(8, id[:])
145 // Start handshake's procedure from the client. It is the entry point
146 // for starting the handshake procedure. // First handshake packet
147 // will be sent immediately.
148 func HandshakeStart(addr string, conn io.Writer, conf *PeerConf) *Handshake {
149 state := NewHandshake(addr, conn, conf)
150 var dhPubRepr *[32]byte
151 state.dhPriv, dhPubRepr = dhKeypairGen()
153 state.rNonce = new([RSize]byte)
154 if _, err := io.ReadFull(Rand, state.rNonce[:]); err != nil {
155 log.Fatalln("Error reading random for nonce:", err)
159 enc = make([]byte, conf.MTU-8-RSize)
161 enc = make([]byte, 32)
163 copy(enc, dhPubRepr[:])
166 enc, err = EnclessEncode(state.dsaPubH, state.rNonce[:], enc)
171 salsa20.XORKeyStream(enc, enc, state.rNonce[:], state.dsaPubH)
173 data := append(state.rNonce[:], enc...)
174 data = append(data, idTag(state.Conf.Id, state.Conf.TimeSync, state.rNonce[:])...)
175 state.conn.Write(data)
179 // Process handshake message on the server side.
180 // This function is intended to be called on server's side.
181 // If this is the final handshake message, then new Peer object
182 // will be created and used as a transport. If no mutually
183 // authenticated Peer is ready, then return nil.
184 func (h *Handshake) Server(data []byte) *Peer {
185 // R + ENC(H(DSAPub), R, El(CDHPub)) + IDtag
186 if h.rNonce == nil && ((!h.Conf.Encless && len(data) >= 48) ||
187 (h.Conf.Encless && len(data) == EnclessEnlargeSize+h.Conf.MTU)) {
188 h.rNonce = new([RSize]byte)
189 copy(h.rNonce[:], data[:RSize])
191 // Decrypt remote public key
192 cDHRepr := new([32]byte)
194 out, err := EnclessDecode(
197 data[RSize:len(data)-8],
200 log.Println("Unable to decode packet from", h.addr, err)
203 copy(cDHRepr[:], out)
205 salsa20.XORKeyStream(cDHRepr[:], data[RSize:RSize+32], h.rNonce[:], h.dsaPubH)
208 // Generate DH keypair
209 var dhPubRepr *[32]byte
210 h.dhPriv, dhPubRepr = dhKeypairGen()
212 // Compute shared key
214 extra25519.RepresentativeToPublicKey(cDH, cDHRepr)
215 h.key = dhKeyGen(h.dhPriv, cDH)
220 encPub = make([]byte, h.Conf.MTU)
221 copy(encPub, dhPubRepr[:])
222 encPub, err = EnclessEncode(h.dsaPubH, h.rNonceNext(1), encPub)
227 encPub = make([]byte, 32)
228 salsa20.XORKeyStream(encPub, dhPubRepr[:], h.rNonceNext(1), h.dsaPubH)
231 // Generate R* and encrypt them
232 h.rServer = new([RSize]byte)
233 if _, err = io.ReadFull(Rand, h.rServer[:]); err != nil {
234 log.Fatalln("Error reading random for R:", err)
236 h.sServer = new([SSize]byte)
237 if _, err = io.ReadFull(Rand, h.sServer[:]); err != nil {
238 log.Fatalln("Error reading random for S:", err)
241 if h.Conf.Noise && !h.Conf.Encless {
242 encRs = make([]byte, h.Conf.MTU-len(encPub)-8)
243 } else if h.Conf.Encless {
244 encRs = make([]byte, h.Conf.MTU-8)
246 encRs = make([]byte, RSize+SSize)
248 copy(encRs, append(h.rServer[:], h.sServer[:]...))
250 encRs, err = EnclessEncode(h.key, h.rNonce[:], encRs)
255 salsa20.XORKeyStream(encRs, encRs, h.rNonce[:], h.key)
258 // Send that to client
259 h.conn.Write(append(encPub, append(
260 encRs, idTag(h.Conf.Id, h.Conf.TimeSync, encPub)...,
262 h.LastPing = time.Now()
264 // ENC(K, R+1, RS + RC + SC + Sign(DSAPriv, K)) + IDtag
265 if h.rClient == nil && ((!h.Conf.Encless && len(data) >= 120) ||
266 (h.Conf.Encless && len(data) == EnclessEnlargeSize+h.Conf.MTU)) {
270 dec, err = EnclessDecode(
276 log.Println("Unable to decode packet from", h.addr, err)
279 dec = dec[:RSize+RSize+SSize+ed25519.SignatureSize]
281 dec = make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
282 salsa20.XORKeyStream(
284 data[:RSize+RSize+SSize+ed25519.SignatureSize],
289 if subtle.ConstantTimeCompare(dec[:RSize], h.rServer[:]) != 1 {
290 log.Println("Invalid server's random number with", h.addr)
293 sign := new([ed25519.SignatureSize]byte)
294 copy(sign[:], dec[RSize+RSize+SSize:])
295 if !ed25519.Verify(h.Conf.Verifier.Pub, h.key[:], sign) {
296 log.Println("Invalid signature from", h.addr)
300 // Send final answer to client
303 enc = make([]byte, h.Conf.MTU-8)
305 enc = make([]byte, RSize)
307 copy(enc, dec[RSize:RSize+RSize])
309 enc, err = EnclessEncode(h.key, h.rNonceNext(2), enc)
314 salsa20.XORKeyStream(enc, enc, h.rNonceNext(2), h.key)
316 h.conn.Write(append(enc, idTag(h.Conf.Id, h.Conf.TimeSync, enc)...))
324 keyFromSecrets(h.sServer[:], dec[RSize+RSize:RSize+RSize+SSize]))
325 h.LastPing = time.Now()
328 log.Println("Invalid handshake message from", h.addr)
333 // Process handshake message on the client side.
334 // This function is intended to be called on client's side.
335 // If this is the final handshake message, then new Peer object
336 // will be created and used as a transport. If no mutually
337 // authenticated Peer is ready, then return nil.
338 func (h *Handshake) Client(data []byte) *Peer {
339 // ENC(H(DSAPub), R+1, El(SDHPub)) + ENC(K, R, RS + SS) + IDtag
340 if h.rServer == nil && h.key == nil &&
341 ((!h.Conf.Encless && len(data) >= 80) ||
342 (h.Conf.Encless && len(data) == 2*(EnclessEnlargeSize+h.Conf.MTU))) {
343 // Decrypt remote public key
344 sDHRepr := new([32]byte)
348 tmp, err = EnclessDecode(
354 log.Println("Unable to decode packet from", h.addr, err)
357 copy(sDHRepr[:], tmp[:32])
359 salsa20.XORKeyStream(sDHRepr[:], data[:32], h.rNonceNext(1), h.dsaPubH)
362 // Compute shared key
364 extra25519.RepresentativeToPublicKey(sDH, sDHRepr)
365 h.key = dhKeyGen(h.dhPriv, sDH)
368 h.rServer = new([RSize]byte)
369 h.sServer = new([SSize]byte)
371 tmp, err = EnclessDecode(
374 data[len(data)/2:len(data)-8],
377 log.Println("Unable to decode packet from", h.addr, err)
380 copy(h.rServer[:], tmp[:RSize])
381 copy(h.sServer[:], tmp[RSize:RSize+SSize])
383 decRs := make([]byte, RSize+SSize)
384 salsa20.XORKeyStream(decRs, data[SSize:SSize+RSize+SSize], h.rNonce[:], h.key)
385 copy(h.rServer[:], decRs[:RSize])
386 copy(h.sServer[:], decRs[RSize:])
389 // Generate R* and signature and encrypt them
390 h.rClient = new([RSize]byte)
391 if _, err = io.ReadFull(Rand, h.rClient[:]); err != nil {
392 log.Fatalln("Error reading random for R:", err)
394 h.sClient = new([SSize]byte)
395 if _, err = io.ReadFull(Rand, h.sClient[:]); err != nil {
396 log.Fatalln("Error reading random for S:", err)
398 sign := ed25519.Sign(h.Conf.DSAPriv, h.key[:])
402 enc = make([]byte, h.Conf.MTU-8)
404 enc = make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
406 copy(enc, h.rServer[:])
407 copy(enc[RSize:], h.rClient[:])
408 copy(enc[RSize+RSize:], h.sClient[:])
409 copy(enc[RSize+RSize+SSize:], sign[:])
411 enc, err = EnclessEncode(h.key, h.rNonceNext(1), enc)
416 salsa20.XORKeyStream(enc, enc, h.rNonceNext(1), h.key)
419 // Send that to server
420 h.conn.Write(append(enc, idTag(h.Conf.Id, h.Conf.TimeSync, enc)...))
421 h.LastPing = time.Now()
423 // ENC(K, R+2, RC) + IDtag
424 if h.key != nil && ((!h.Conf.Encless && len(data) >= 16) ||
425 (h.Conf.Encless && len(data) == EnclessEnlargeSize+h.Conf.MTU)) {
430 dec, err = EnclessDecode(h.key, h.rNonceNext(2), data[:len(data)-8])
432 log.Println("Unable to decode packet from", h.addr, err)
437 dec = make([]byte, RSize)
438 salsa20.XORKeyStream(dec, data[:RSize], h.rNonceNext(2), h.key)
440 if subtle.ConstantTimeCompare(dec, h.rClient[:]) != 1 {
441 log.Println("Invalid client's random number with", h.addr)
451 keyFromSecrets(h.sServer[:], h.sClient[:]),
453 h.LastPing = time.Now()
456 log.Println("Invalid handshake stage from", h.addr)