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/>.
29 "github.com/agl/ed25519"
30 "github.com/agl/ed25519/extra25519"
31 "golang.org/x/crypto/blake2b"
32 "golang.org/x/crypto/curve25519"
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) *[16]byte {
92 nonce := new([16]byte)
93 nonceCurrent, _ := binary.Uvarint(h.rNonce[8:])
94 binary.PutUvarint(nonce[8:], 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, err := blake2b.New256(id[:])
148 // Start handshake's procedure from the client. It is the entry point
149 // for starting the handshake procedure. // First handshake packet
150 // will be sent immediately.
151 func HandshakeStart(addr string, conn io.Writer, conf *PeerConf) *Handshake {
152 state := NewHandshake(addr, conn, conf)
153 var dhPubRepr *[32]byte
154 state.dhPriv, dhPubRepr = dhKeypairGen()
156 state.rNonce = new([16]byte)
157 if _, err := io.ReadFull(Rand, state.rNonce[8:]); err != nil {
158 log.Fatalln("Error reading random for nonce:", err)
162 enc = make([]byte, conf.MTU-8-RSize)
164 enc = make([]byte, 32)
166 copy(enc, dhPubRepr[:])
169 enc, err = EnclessEncode(state.dsaPubH, state.rNonce, enc)
174 chacha20.XORKeyStream(enc, enc, state.rNonce, state.dsaPubH)
176 data := append(state.rNonce[8:], enc...)
177 data = append(data, idTag(state.Conf.Id, state.Conf.TimeSync, state.rNonce[8:])...)
178 state.conn.Write(data)
182 // Process handshake message on the server side.
183 // This function is intended to be called on server's side.
184 // If this is the final handshake message, then new Peer object
185 // will be created and used as a transport. If no mutually
186 // authenticated Peer is ready, then return nil.
187 func (h *Handshake) Server(data []byte) *Peer {
188 // R + ENC(H(DSAPub), R, El(CDHPub)) + IDtag
189 if h.rNonce == nil && ((!h.Conf.Encless && len(data) >= 48) ||
190 (h.Conf.Encless && len(data) == EnclessEnlargeSize+h.Conf.MTU)) {
191 h.rNonce = new([16]byte)
192 copy(h.rNonce[8:], data[:RSize])
194 // Decrypt remote public key
195 cDHRepr := new([32]byte)
197 out, err := EnclessDecode(
200 data[RSize:len(data)-8],
203 log.Println("Unable to decode packet from", h.addr, err)
206 copy(cDHRepr[:], out)
208 chacha20.XORKeyStream(cDHRepr[:], data[RSize:RSize+32], h.rNonce, h.dsaPubH)
211 // Generate DH keypair
212 var dhPubRepr *[32]byte
213 h.dhPriv, dhPubRepr = dhKeypairGen()
215 // Compute shared key
217 extra25519.RepresentativeToPublicKey(cDH, cDHRepr)
218 h.key = dhKeyGen(h.dhPriv, cDH)
223 encPub = make([]byte, h.Conf.MTU)
224 copy(encPub, dhPubRepr[:])
225 encPub, err = EnclessEncode(h.dsaPubH, h.rNonceNext(1), encPub)
230 encPub = make([]byte, 32)
231 chacha20.XORKeyStream(encPub, dhPubRepr[:], h.rNonceNext(1), h.dsaPubH)
234 // Generate R* and encrypt them
235 h.rServer = new([RSize]byte)
236 if _, err = io.ReadFull(Rand, h.rServer[:]); err != nil {
237 log.Fatalln("Error reading random for R:", err)
239 h.sServer = new([SSize]byte)
240 if _, err = io.ReadFull(Rand, h.sServer[:]); err != nil {
241 log.Fatalln("Error reading random for S:", err)
244 if h.Conf.Noise && !h.Conf.Encless {
245 encRs = make([]byte, h.Conf.MTU-len(encPub)-8)
246 } else if h.Conf.Encless {
247 encRs = make([]byte, h.Conf.MTU-8)
249 encRs = make([]byte, RSize+SSize)
251 copy(encRs, append(h.rServer[:], h.sServer[:]...))
253 encRs, err = EnclessEncode(h.key, h.rNonce, encRs)
258 chacha20.XORKeyStream(encRs, encRs, h.rNonce, h.key)
261 // Send that to client
262 h.conn.Write(append(encPub, append(
263 encRs, idTag(h.Conf.Id, h.Conf.TimeSync, encPub)...,
265 h.LastPing = time.Now()
267 // ENC(K, R+1, RS + RC + SC + Sign(DSAPriv, K)) + IDtag
268 if h.rClient == nil && ((!h.Conf.Encless && len(data) >= 120) ||
269 (h.Conf.Encless && len(data) == EnclessEnlargeSize+h.Conf.MTU)) {
273 dec, err = EnclessDecode(
279 log.Println("Unable to decode packet from", h.addr, err)
282 dec = dec[:RSize+RSize+SSize+ed25519.SignatureSize]
284 dec = make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
285 chacha20.XORKeyStream(
287 data[:RSize+RSize+SSize+ed25519.SignatureSize],
292 if subtle.ConstantTimeCompare(dec[:RSize], h.rServer[:]) != 1 {
293 log.Println("Invalid server's random number with", h.addr)
296 sign := new([ed25519.SignatureSize]byte)
297 copy(sign[:], dec[RSize+RSize+SSize:])
298 if !ed25519.Verify(h.Conf.Verifier.Pub, h.key[:], sign) {
299 log.Println("Invalid signature from", h.addr)
303 // Send final answer to client
306 enc = make([]byte, h.Conf.MTU-8)
308 enc = make([]byte, RSize)
310 copy(enc, dec[RSize:RSize+RSize])
312 enc, err = EnclessEncode(h.key, h.rNonceNext(2), enc)
317 chacha20.XORKeyStream(enc, enc, h.rNonceNext(2), h.key)
319 h.conn.Write(append(enc, idTag(h.Conf.Id, h.Conf.TimeSync, enc)...))
327 keyFromSecrets(h.sServer[:], dec[RSize+RSize:RSize+RSize+SSize]))
328 h.LastPing = time.Now()
331 log.Println("Invalid handshake message from", h.addr)
336 // Process handshake message on the client side.
337 // This function is intended to be called on client's side.
338 // If this is the final handshake message, then new Peer object
339 // will be created and used as a transport. If no mutually
340 // authenticated Peer is ready, then return nil.
341 func (h *Handshake) Client(data []byte) *Peer {
342 // ENC(H(DSAPub), R+1, El(SDHPub)) + ENC(K, R, RS + SS) + IDtag
343 if h.rServer == nil && h.key == nil &&
344 ((!h.Conf.Encless && len(data) >= 80) ||
345 (h.Conf.Encless && len(data) == 2*(EnclessEnlargeSize+h.Conf.MTU))) {
346 // Decrypt remote public key
347 sDHRepr := new([32]byte)
351 tmp, err = EnclessDecode(
357 log.Println("Unable to decode packet from", h.addr, err)
360 copy(sDHRepr[:], tmp[:32])
362 chacha20.XORKeyStream(sDHRepr[:], data[:32], h.rNonceNext(1), h.dsaPubH)
365 // Compute shared key
367 extra25519.RepresentativeToPublicKey(sDH, sDHRepr)
368 h.key = dhKeyGen(h.dhPriv, sDH)
371 h.rServer = new([RSize]byte)
372 h.sServer = new([SSize]byte)
374 tmp, err = EnclessDecode(h.key, h.rNonce, data[len(data)/2:len(data)-8])
376 log.Println("Unable to decode packet from", h.addr, err)
379 copy(h.rServer[:], tmp[:RSize])
380 copy(h.sServer[:], tmp[RSize:RSize+SSize])
382 decRs := make([]byte, RSize+SSize)
383 chacha20.XORKeyStream(decRs, data[SSize:SSize+RSize+SSize], h.rNonce, h.key)
384 copy(h.rServer[:], decRs[:RSize])
385 copy(h.sServer[:], decRs[RSize:])
388 // Generate R* and signature and encrypt them
389 h.rClient = new([RSize]byte)
390 if _, err = io.ReadFull(Rand, h.rClient[:]); err != nil {
391 log.Fatalln("Error reading random for R:", err)
393 h.sClient = new([SSize]byte)
394 if _, err = io.ReadFull(Rand, h.sClient[:]); err != nil {
395 log.Fatalln("Error reading random for S:", err)
397 sign := ed25519.Sign(h.Conf.DSAPriv, h.key[:])
401 enc = make([]byte, h.Conf.MTU-8)
403 enc = make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
405 copy(enc, h.rServer[:])
406 copy(enc[RSize:], h.rClient[:])
407 copy(enc[RSize+RSize:], h.sClient[:])
408 copy(enc[RSize+RSize+SSize:], sign[:])
410 enc, err = EnclessEncode(h.key, h.rNonceNext(1), enc)
415 chacha20.XORKeyStream(enc, enc, h.rNonceNext(1), h.key)
418 // Send that to server
419 h.conn.Write(append(enc, idTag(h.Conf.Id, h.Conf.TimeSync, enc)...))
420 h.LastPing = time.Now()
422 // ENC(K, R+2, RC) + IDtag
423 if h.key != nil && ((!h.Conf.Encless && len(data) >= 16) ||
424 (h.Conf.Encless && len(data) == EnclessEnlargeSize+h.Conf.MTU)) {
429 dec, err = EnclessDecode(h.key, h.rNonceNext(2), data[:len(data)-8])
431 log.Println("Unable to decode packet from", h.addr, err)
436 dec = make([]byte, RSize)
437 chacha20.XORKeyStream(dec, data[:RSize], h.rNonceNext(2), h.key)
439 if subtle.ConstantTimeCompare(dec, h.rClient[:]) != 1 {
440 log.Println("Invalid client's random number with", h.addr)
450 keyFromSecrets(h.sServer[:], h.sClient[:]),
452 h.LastPing = time.Now()
455 log.Println("Invalid handshake stage from", h.addr)