2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2019 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, version 3 of the License.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 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/blake2b"
31 "golang.org/x/crypto/curve25519"
39 type Handshake struct {
44 dsaPubH *[ed25519.PublicKeySize]byte
47 dhPriv *[32]byte // own private DH key
48 rServer *[RSize]byte // random string for authentication
50 sServer *[SSize]byte // secret string for main key calculation
54 func keyFromSecrets(server, client []byte) *[SSize]byte {
56 for i := 0; i < SSize; i++ {
57 k[i] = server[i] ^ client[i]
62 // Zero handshake's memory state
63 func (h *Handshake) Zero() {
65 SliceZero(h.rNonce[:])
68 SliceZero(h.dhPriv[:])
74 SliceZero(h.dsaPubH[:])
77 SliceZero(h.rServer[:])
80 SliceZero(h.rClient[:])
83 SliceZero(h.sServer[:])
86 SliceZero(h.sClient[:])
90 func (h *Handshake) rNonceNext(count uint64) *[16]byte {
91 nonce := new([16]byte)
92 nonceCurrent, _ := binary.Uvarint(h.rNonce[8:])
93 binary.PutUvarint(nonce[8:], nonceCurrent+count)
97 func dhKeypairGen() (*[32]byte, *[32]byte) {
100 repr := new([32]byte)
103 if _, err := io.ReadFull(Rand, priv[:]); err != nil {
104 log.Fatalln("Error reading random for DH private key:", err)
106 reprFound = extra25519.ScalarBaseMult(pub, repr, priv)
111 func dhKeyGen(priv, pub *[32]byte) *[32]byte {
113 curve25519.ScalarMult(key, priv, pub)
114 hashed := blake2b.Sum256(key[:])
118 // Create new handshake state.
119 func NewHandshake(addr string, conn io.Writer, conf *PeerConf) *Handshake {
123 LastPing: time.Now(),
126 state.dsaPubH = new([ed25519.PublicKeySize]byte)
127 copy(state.dsaPubH[:], state.Conf.Verifier.Pub[:])
128 hashed := blake2b.Sum256(state.dsaPubH[:])
129 state.dsaPubH = &hashed
133 // Generate ID tag from client identification and data.
134 func idTag(id *PeerID, timeSync int, data []byte) []byte {
135 enc := make([]byte, 8)
137 AddTimeSync(timeSync, enc)
138 mac, err := blake2b.New256(id[:])
144 return sum[len(sum)-8:]
147 // Start handshake's procedure from the client. It is the entry point
148 // for starting the handshake procedure.
149 // First handshake packet will be sent immediately.
150 func HandshakeStart(addr string, conn io.Writer, conf *PeerConf) *Handshake {
151 state := NewHandshake(addr, conn, conf)
152 var dhPubRepr *[32]byte
153 state.dhPriv, dhPubRepr = dhKeypairGen()
155 state.rNonce = new([16]byte)
156 if _, err := io.ReadFull(Rand, state.rNonce[8:]); err != nil {
157 log.Fatalln("Error reading random for nonce:", err)
161 enc = make([]byte, conf.MTU-8-RSize)
163 enc = make([]byte, 32)
165 copy(enc, dhPubRepr[:])
168 enc, err = EnclessEncode(state.dsaPubH, state.rNonce, enc)
173 chacha20.XORKeyStream(enc, enc, state.rNonce, state.dsaPubH)
175 data := append(state.rNonce[8:], enc...)
176 data = append(data, idTag(state.Conf.ID, state.Conf.TimeSync, state.rNonce[8:])...)
177 state.conn.Write(data)
181 // Process handshake message on the server side.
182 // This function is intended to be called on server's side.
183 // If this is the final handshake message, then new Peer object
184 // will be created and used as a transport. If no mutually
185 // authenticated Peer is ready, then return nil.
186 func (h *Handshake) Server(data []byte) *Peer {
187 // R + ENC(H(DSAPub), R, El(CDHPub)) + IDtag
188 if h.rNonce == nil && ((!h.Conf.Encless && len(data) >= 48) ||
189 (h.Conf.Encless && len(data) == EnclessEnlargeSize+h.Conf.MTU)) {
190 h.rNonce = new([16]byte)
191 copy(h.rNonce[8:], data[:RSize])
193 // Decrypt remote public key
194 cDHRepr := new([32]byte)
196 out, err := EnclessDecode(
199 data[RSize:len(data)-8],
202 log.Println("Unable to decode packet from", h.addr, err)
205 copy(cDHRepr[:], out)
207 chacha20.XORKeyStream(cDHRepr[:], data[RSize:RSize+32], h.rNonce, h.dsaPubH)
210 // Generate DH keypair
211 var dhPubRepr *[32]byte
212 h.dhPriv, dhPubRepr = dhKeypairGen()
214 // Compute shared key
216 extra25519.RepresentativeToPublicKey(cDH, cDHRepr)
217 h.key = dhKeyGen(h.dhPriv, cDH)
222 encPub = make([]byte, h.Conf.MTU)
223 copy(encPub, dhPubRepr[:])
224 encPub, err = EnclessEncode(h.dsaPubH, h.rNonceNext(1), encPub)
229 encPub = make([]byte, 32)
230 chacha20.XORKeyStream(encPub, dhPubRepr[:], h.rNonceNext(1), h.dsaPubH)
233 // Generate R* and encrypt them
234 h.rServer = new([RSize]byte)
235 if _, err = io.ReadFull(Rand, h.rServer[:]); err != nil {
236 log.Fatalln("Error reading random for R:", err)
238 h.sServer = new([SSize]byte)
239 if _, err = io.ReadFull(Rand, h.sServer[:]); err != nil {
240 log.Fatalln("Error reading random for S:", err)
243 if h.Conf.Noise && !h.Conf.Encless {
244 encRs = make([]byte, h.Conf.MTU-len(encPub)-8)
245 } else if h.Conf.Encless {
246 encRs = make([]byte, h.Conf.MTU-8)
248 encRs = make([]byte, RSize+SSize)
250 copy(encRs, append(h.rServer[:], h.sServer[:]...))
252 encRs, err = EnclessEncode(h.key, h.rNonce, encRs)
257 chacha20.XORKeyStream(encRs, encRs, h.rNonce, h.key)
260 // Send that to client
261 h.conn.Write(append(encPub, append(
262 encRs, idTag(h.Conf.ID, h.Conf.TimeSync, encPub)...,
264 h.LastPing = time.Now()
266 // ENC(K, R+1, RS + RC + SC + Sign(DSAPriv, K)) + IDtag
267 if h.rClient == nil && ((!h.Conf.Encless && len(data) >= 120) ||
268 (h.Conf.Encless && len(data) == EnclessEnlargeSize+h.Conf.MTU)) {
272 dec, err = EnclessDecode(
278 log.Println("Unable to decode packet from", h.addr, err)
281 dec = dec[:RSize+RSize+SSize+ed25519.SignatureSize]
283 dec = make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
284 chacha20.XORKeyStream(
286 data[:RSize+RSize+SSize+ed25519.SignatureSize],
291 if subtle.ConstantTimeCompare(dec[:RSize], h.rServer[:]) != 1 {
292 log.Println("Invalid server's random number with", h.addr)
295 sign := new([ed25519.SignatureSize]byte)
296 copy(sign[:], dec[RSize+RSize+SSize:])
297 if !ed25519.Verify(h.Conf.Verifier.Pub, h.key[:], sign) {
298 log.Println("Invalid signature from", h.addr)
302 // Send final answer to client
305 enc = make([]byte, h.Conf.MTU-8)
307 enc = make([]byte, RSize)
309 copy(enc, dec[RSize:RSize+RSize])
311 enc, err = EnclessEncode(h.key, h.rNonceNext(2), enc)
316 chacha20.XORKeyStream(enc, enc, h.rNonceNext(2), h.key)
318 h.conn.Write(append(enc, idTag(h.Conf.ID, h.Conf.TimeSync, enc)...))
326 keyFromSecrets(h.sServer[:], dec[RSize+RSize:RSize+RSize+SSize]))
327 h.LastPing = time.Now()
330 log.Println("Invalid handshake message from", h.addr)
335 // Process handshake message on the client side.
336 // This function is intended to be called on client's side.
337 // If this is the final handshake message, then new Peer object
338 // will be created and used as a transport. If no mutually
339 // authenticated Peer is ready, then return nil.
340 func (h *Handshake) Client(data []byte) *Peer {
341 // ENC(H(DSAPub), R+1, El(SDHPub)) + ENC(K, R, RS + SS) + IDtag
342 if h.rServer == nil && h.key == nil &&
343 ((!h.Conf.Encless && len(data) >= 80) ||
344 (h.Conf.Encless && len(data) == 2*(EnclessEnlargeSize+h.Conf.MTU))) {
345 // Decrypt remote public key
346 sDHRepr := new([32]byte)
350 tmp, err = EnclessDecode(
356 log.Println("Unable to decode packet from", h.addr, err)
359 copy(sDHRepr[:], tmp[:32])
361 chacha20.XORKeyStream(sDHRepr[:], data[:32], h.rNonceNext(1), h.dsaPubH)
364 // Compute shared key
366 extra25519.RepresentativeToPublicKey(sDH, sDHRepr)
367 h.key = dhKeyGen(h.dhPriv, sDH)
370 h.rServer = new([RSize]byte)
371 h.sServer = new([SSize]byte)
373 tmp, err = EnclessDecode(h.key, h.rNonce, data[len(data)/2:len(data)-8])
375 log.Println("Unable to decode packet from", h.addr, err)
378 copy(h.rServer[:], tmp[:RSize])
379 copy(h.sServer[:], tmp[RSize:RSize+SSize])
381 decRs := make([]byte, RSize+SSize)
382 chacha20.XORKeyStream(decRs, data[SSize:SSize+RSize+SSize], h.rNonce, h.key)
383 copy(h.rServer[:], decRs[:RSize])
384 copy(h.sServer[:], decRs[RSize:])
387 // Generate R* and signature and encrypt them
388 h.rClient = new([RSize]byte)
389 if _, err = io.ReadFull(Rand, h.rClient[:]); err != nil {
390 log.Fatalln("Error reading random for R:", err)
392 h.sClient = new([SSize]byte)
393 if _, err = io.ReadFull(Rand, h.sClient[:]); err != nil {
394 log.Fatalln("Error reading random for S:", err)
396 sign := ed25519.Sign(h.Conf.DSAPriv, h.key[:])
400 enc = make([]byte, h.Conf.MTU-8)
402 enc = make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
404 copy(enc, h.rServer[:])
405 copy(enc[RSize:], h.rClient[:])
406 copy(enc[RSize+RSize:], h.sClient[:])
407 copy(enc[RSize+RSize+SSize:], sign[:])
409 enc, err = EnclessEncode(h.key, h.rNonceNext(1), enc)
414 chacha20.XORKeyStream(enc, enc, h.rNonceNext(1), h.key)
417 // Send that to server
418 h.conn.Write(append(enc, idTag(h.Conf.ID, h.Conf.TimeSync, enc)...))
419 h.LastPing = time.Now()
421 // ENC(K, R+2, RC) + IDtag
422 if h.key != nil && ((!h.Conf.Encless && len(data) >= 16) ||
423 (h.Conf.Encless && len(data) == EnclessEnlargeSize+h.Conf.MTU)) {
428 dec, err = EnclessDecode(h.key, h.rNonceNext(2), data[:len(data)-8])
430 log.Println("Unable to decode packet from", h.addr, err)
435 dec = make([]byte, RSize)
436 chacha20.XORKeyStream(dec, data[:RSize], h.rNonceNext(2), h.key)
438 if subtle.ConstantTimeCompare(dec, h.rClient[:]) != 1 {
439 log.Println("Invalid client's random number with", h.addr)
449 keyFromSecrets(h.sServer[:], h.sClient[:]),
451 h.LastPing = time.Now()
454 log.Println("Invalid handshake stage from", h.addr)