2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2017 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"
36 // RSize is size in bytes of channel binding random value
38 // SSize is size in bytes of shared secret half
42 // Handshake is state of a handshake/negotiation between client and server
43 type Handshake struct {
48 dsaPubH *[ed25519.PublicKeySize]byte
51 dhPriv *[32]byte // own private DH key
52 rServer *[RSize]byte // random string for authentication
54 sServer *[SSize]byte // secret string for main key calculation
58 func keyFromSecrets(server, client []byte) *[SSize]byte {
60 for i := 0; i < SSize; i++ {
61 k[i] = server[i] ^ client[i]
66 // Zero handshake's memory state
67 func (h *Handshake) Zero() {
69 SliceZero(h.rNonce[:])
72 SliceZero(h.dhPriv[:])
78 SliceZero(h.dsaPubH[:])
81 SliceZero(h.rServer[:])
84 SliceZero(h.rClient[:])
87 SliceZero(h.sServer[:])
90 SliceZero(h.sClient[:])
94 func (h *Handshake) rNonceNext(count uint64) *[16]byte {
95 nonce := new([16]byte)
96 nonceCurrent, _ := binary.Uvarint(h.rNonce[8:])
97 binary.PutUvarint(nonce[8:], nonceCurrent+count)
101 func dhKeypairGen() (*[32]byte, *[32]byte) {
102 priv := new([32]byte)
104 repr := new([32]byte)
107 if _, err := io.ReadFull(Rand, priv[:]); err != nil {
108 log.Fatalln("Error reading random for DH private key:", err)
110 reprFound = extra25519.ScalarBaseMult(pub, repr, priv)
115 func dhKeyGen(priv, pub *[32]byte) *[32]byte {
117 curve25519.ScalarMult(key, priv, pub)
118 hashed := blake2b.Sum256(key[:])
122 // NewHandshake creates new handshake state.
123 func NewHandshake(addr string, conn io.Writer, conf *PeerConf) *Handshake {
127 LastPing: time.Now(),
130 state.dsaPubH = new([ed25519.PublicKeySize]byte)
131 copy(state.dsaPubH[:], state.Conf.Verifier.Pub[:])
132 hashed := blake2b.Sum256(state.dsaPubH[:])
133 state.dsaPubH = &hashed
137 // Generate ID tag from client identification and data.
138 func idTag(id *PeerID, timeSync int, data []byte) []byte {
139 enc := make([]byte, 8)
141 AddTimeSync(timeSync, enc)
142 mac, err := blake2b.New256(id[:])
148 return sum[len(sum)-8:]
151 // HandshakeStarts start handshake's procedure from the client.
152 // It is the entry point for starting the handshake procedure.
153 // First handshake packet will be sent immediately.
154 func HandshakeStart(addr string, conn io.Writer, conf *PeerConf) *Handshake {
155 state := NewHandshake(addr, conn, conf)
156 var dhPubRepr *[32]byte
157 state.dhPriv, dhPubRepr = dhKeypairGen()
159 state.rNonce = new([16]byte)
160 if _, err := io.ReadFull(Rand, state.rNonce[8:]); err != nil {
161 log.Fatalln("Error reading random for nonce:", err)
165 enc = make([]byte, conf.MTU-8-RSize)
167 enc = make([]byte, 32)
169 copy(enc, dhPubRepr[:])
172 enc, err = EnclessEncode(state.dsaPubH, state.rNonce, enc)
177 chacha20.XORKeyStream(enc, enc, state.rNonce, state.dsaPubH)
179 data := append(state.rNonce[8:], enc...)
180 data = append(data, idTag(state.Conf.ID, state.Conf.TimeSync, state.rNonce[8:])...)
181 state.conn.Write(data)
185 // Server processes handshake message on the server side.
186 // This function is intended to be called on server's side.
187 // If this is the final handshake message, then new Peer object
188 // will be created and used as a transport. If no mutually
189 // authenticated Peer is ready, then return nil.
190 func (h *Handshake) Server(data []byte) *Peer {
191 // R + ENC(H(DSAPub), R, El(CDHPub)) + IDtag
192 if h.rNonce == nil && ((!h.Conf.Encless && len(data) >= 48) ||
193 (h.Conf.Encless && len(data) == EnclessEnlargeSize+h.Conf.MTU)) {
194 h.rNonce = new([16]byte)
195 copy(h.rNonce[8:], data[:RSize])
197 // Decrypt remote public key
198 cDHRepr := new([32]byte)
200 out, err := EnclessDecode(
203 data[RSize:len(data)-8],
206 log.Println("Unable to decode packet from", h.addr, err)
209 copy(cDHRepr[:], out)
211 chacha20.XORKeyStream(cDHRepr[:], data[RSize:RSize+32], h.rNonce, h.dsaPubH)
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 chacha20.XORKeyStream(encPub, dhPubRepr[:], h.rNonceNext(1), h.dsaPubH)
237 // Generate R* and encrypt them
238 h.rServer = new([RSize]byte)
239 if _, err = io.ReadFull(Rand, h.rServer[:]); err != nil {
240 log.Fatalln("Error reading random for R:", err)
242 h.sServer = new([SSize]byte)
243 if _, err = io.ReadFull(Rand, 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)-8)
249 } else if h.Conf.Encless {
250 encRs = make([]byte, h.Conf.MTU-8)
252 encRs = make([]byte, RSize+SSize)
254 copy(encRs, append(h.rServer[:], h.sServer[:]...))
256 encRs, err = EnclessEncode(h.key, h.rNonce, encRs)
261 chacha20.XORKeyStream(encRs, encRs, h.rNonce, h.key)
264 // Send that to client
265 h.conn.Write(append(encPub, append(
266 encRs, idTag(h.Conf.ID, h.Conf.TimeSync, encPub)...,
268 h.LastPing = time.Now()
270 // ENC(K, R+1, RS + RC + SC + Sign(DSAPriv, K)) + IDtag
271 if h.rClient == nil && ((!h.Conf.Encless && len(data) >= 120) ||
272 (h.Conf.Encless && len(data) == EnclessEnlargeSize+h.Conf.MTU)) {
276 dec, err = EnclessDecode(
282 log.Println("Unable to decode packet from", h.addr, err)
285 dec = dec[:RSize+RSize+SSize+ed25519.SignatureSize]
287 dec = make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
288 chacha20.XORKeyStream(
290 data[:RSize+RSize+SSize+ed25519.SignatureSize],
295 if subtle.ConstantTimeCompare(dec[:RSize], h.rServer[:]) != 1 {
296 log.Println("Invalid server's random number with", h.addr)
299 sign := new([ed25519.SignatureSize]byte)
300 copy(sign[:], dec[RSize+RSize+SSize:])
301 if !ed25519.Verify(h.Conf.Verifier.Pub, h.key[:], sign) {
302 log.Println("Invalid signature from", h.addr)
306 // Send final answer to client
309 enc = make([]byte, h.Conf.MTU-8)
311 enc = make([]byte, RSize)
313 copy(enc, dec[RSize:RSize+RSize])
315 enc, err = EnclessEncode(h.key, h.rNonceNext(2), enc)
320 chacha20.XORKeyStream(enc, enc, h.rNonceNext(2), h.key)
322 h.conn.Write(append(enc, idTag(h.Conf.ID, h.Conf.TimeSync, enc)...))
330 keyFromSecrets(h.sServer[:], dec[RSize+RSize:RSize+RSize+SSize]))
331 h.LastPing = time.Now()
334 log.Println("Invalid handshake message from", h.addr)
339 // Client processes handshake message on the client side.
340 // This function is intended to be called on client's side.
341 // If this is the final handshake message, then new Peer object
342 // will be created and used as a transport. If no mutually
343 // authenticated Peer is ready, then return nil.
344 func (h *Handshake) Client(data []byte) *Peer {
345 // ENC(H(DSAPub), R+1, El(SDHPub)) + ENC(K, R, RS + SS) + IDtag
346 if h.rServer == nil && h.key == nil &&
347 ((!h.Conf.Encless && len(data) >= 80) ||
348 (h.Conf.Encless && len(data) == 2*(EnclessEnlargeSize+h.Conf.MTU))) {
349 // Decrypt remote public key
350 sDHRepr := new([32]byte)
354 tmp, err = EnclessDecode(
360 log.Println("Unable to decode packet from", h.addr, err)
363 copy(sDHRepr[:], tmp[:32])
365 chacha20.XORKeyStream(sDHRepr[:], data[:32], h.rNonceNext(1), h.dsaPubH)
368 // Compute shared key
370 extra25519.RepresentativeToPublicKey(sDH, sDHRepr)
371 h.key = dhKeyGen(h.dhPriv, sDH)
374 h.rServer = new([RSize]byte)
375 h.sServer = new([SSize]byte)
377 tmp, err = EnclessDecode(h.key, h.rNonce, data[len(data)/2:len(data)-8])
379 log.Println("Unable to decode packet from", h.addr, err)
382 copy(h.rServer[:], tmp[:RSize])
383 copy(h.sServer[:], tmp[RSize:RSize+SSize])
385 decRs := make([]byte, RSize+SSize)
386 chacha20.XORKeyStream(decRs, data[SSize:SSize+RSize+SSize], h.rNonce, h.key)
387 copy(h.rServer[:], decRs[:RSize])
388 copy(h.sServer[:], decRs[RSize:])
391 // Generate R* and signature and encrypt them
392 h.rClient = new([RSize]byte)
393 if _, err = io.ReadFull(Rand, h.rClient[:]); err != nil {
394 log.Fatalln("Error reading random for R:", err)
396 h.sClient = new([SSize]byte)
397 if _, err = io.ReadFull(Rand, h.sClient[:]); err != nil {
398 log.Fatalln("Error reading random for S:", err)
400 sign := ed25519.Sign(h.Conf.DSAPriv, h.key[:])
404 enc = make([]byte, h.Conf.MTU-8)
406 enc = make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
408 copy(enc, h.rServer[:])
409 copy(enc[RSize:], h.rClient[:])
410 copy(enc[RSize+RSize:], h.sClient[:])
411 copy(enc[RSize+RSize+SSize:], sign[:])
413 enc, err = EnclessEncode(h.key, h.rNonceNext(1), enc)
418 chacha20.XORKeyStream(enc, enc, h.rNonceNext(1), h.key)
421 // Send that to server
422 h.conn.Write(append(enc, idTag(h.Conf.ID, h.Conf.TimeSync, enc)...))
423 h.LastPing = time.Now()
425 // ENC(K, R+2, RC) + IDtag
426 if h.key != nil && ((!h.Conf.Encless && len(data) >= 16) ||
427 (h.Conf.Encless && len(data) == EnclessEnlargeSize+h.Conf.MTU)) {
432 dec, err = EnclessDecode(h.key, h.rNonceNext(2), data[:len(data)-8])
434 log.Println("Unable to decode packet from", h.addr, err)
439 dec = make([]byte, RSize)
440 chacha20.XORKeyStream(dec, data[:RSize], h.rNonceNext(2), h.key)
442 if subtle.ConstantTimeCompare(dec, h.rClient[:]) != 1 {
443 log.Println("Invalid client's random number with", h.addr)
453 keyFromSecrets(h.sServer[:], h.sClient[:]),
455 h.LastPing = time.Now()
458 log.Println("Invalid handshake stage from", h.addr)