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, MTU-xtea.BlockSize-RSize)
166 enc = make([]byte, 32)
168 copy(enc, dhPubRepr[:])
169 salsa20.XORKeyStream(enc, enc, state.rNonce[:], state.dsaPubH)
170 data := append(state.rNonce[:], enc...)
171 data = append(data, idTag(state.Conf.Id, state.rNonce[:])...)
172 state.conn.Write(data)
176 // Process handshake message on the server side.
177 // This function is intended to be called on server's side.
178 // If this is the final handshake message, then new Peer object
179 // will be created and used as a transport. If no mutually
180 // authenticated Peer is ready, then return nil.
181 func (h *Handshake) Server(data []byte) *Peer {
182 // R + ENC(H(DSAPub), R, El(CDHPub)) + IDtag
183 if h.rNonce == nil && len(data) >= 48 {
184 // Generate DH keypair
185 var dhPubRepr *[32]byte
186 h.dhPriv, dhPubRepr = dhKeypairGen()
188 h.rNonce = new([RSize]byte)
189 copy(h.rNonce[:], data[:RSize])
191 // Decrypt remote public key and compute shared key
192 cDHRepr := new([32]byte)
193 salsa20.XORKeyStream(
195 data[RSize:RSize+32],
200 extra25519.RepresentativeToPublicKey(cDH, cDHRepr)
201 h.key = dhKeyGen(h.dhPriv, cDH)
203 encPub := make([]byte, 32)
204 salsa20.XORKeyStream(encPub, dhPubRepr[:], h.rNonceNext(1), h.dsaPubH)
206 // Generate R* and encrypt them
207 h.rServer = new([RSize]byte)
209 if _, err = Rand.Read(h.rServer[:]); err != nil {
210 log.Fatalln("Error reading random for R:", err)
212 h.sServer = new([SSize]byte)
213 if _, err = Rand.Read(h.sServer[:]); err != nil {
214 log.Fatalln("Error reading random for S:", err)
218 encRs = make([]byte, MTU-len(encPub)-xtea.BlockSize)
220 encRs = make([]byte, RSize+SSize)
222 copy(encRs, append(h.rServer[:], h.sServer[:]...))
223 salsa20.XORKeyStream(encRs, encRs, h.rNonce[:], h.key)
225 // Send that to client
226 h.conn.Write(append(encPub, append(encRs, idTag(h.Conf.Id, encPub)...)...))
227 h.LastPing = time.Now()
229 // ENC(K, R+1, RS + RC + SC + Sign(DSAPriv, K)) + IDtag
230 if h.rClient == nil && len(data) >= 120 {
231 // Decrypted Rs compare rServer
232 dec := make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
233 salsa20.XORKeyStream(
235 data[:RSize+RSize+SSize+ed25519.SignatureSize],
239 if subtle.ConstantTimeCompare(dec[:RSize], h.rServer[:]) != 1 {
240 log.Println("Invalid server's random number with", h.addr)
243 sign := new([ed25519.SignatureSize]byte)
244 copy(sign[:], dec[RSize+RSize+SSize:])
245 if !ed25519.Verify(h.Conf.Verifier.Pub, h.key[:], sign) {
246 log.Println("Invalid signature from", h.addr)
250 // Send final answer to client
253 enc = make([]byte, MTU-xtea.BlockSize)
255 enc = make([]byte, RSize)
257 copy(enc, dec[RSize:RSize+RSize])
258 salsa20.XORKeyStream(enc, enc, h.rNonceNext(2), h.key)
259 h.conn.Write(append(enc, idTag(h.Conf.Id, enc)...))
267 keyFromSecrets(h.sServer[:], dec[RSize+RSize:RSize+RSize+SSize]))
268 h.LastPing = time.Now()
271 log.Println("Invalid handshake message from", h.addr)
276 // Process handshake message on the client side.
277 // This function is intended to be called on client's side.
278 // If this is the final handshake message, then new Peer object
279 // will be created and used as a transport. If no mutually
280 // authenticated Peer is ready, then return nil.
281 func (h *Handshake) Client(data []byte) *Peer {
282 // ENC(H(DSAPub), R+1, El(SDHPub)) + ENC(K, R, RS + SS) + IDtag
283 if h.rServer == nil && h.key == nil && len(data) >= 80 {
284 // Decrypt remote public key and compute shared key
285 sDHRepr := new([32]byte)
286 salsa20.XORKeyStream(sDHRepr[:], data[:32], h.rNonceNext(1), h.dsaPubH)
288 extra25519.RepresentativeToPublicKey(sDH, sDHRepr)
289 h.key = dhKeyGen(h.dhPriv, sDH)
292 decRs := make([]byte, RSize+SSize)
293 salsa20.XORKeyStream(decRs, data[SSize:32+RSize+SSize], h.rNonce[:], h.key)
294 h.rServer = new([RSize]byte)
295 copy(h.rServer[:], decRs[:RSize])
296 h.sServer = new([SSize]byte)
297 copy(h.sServer[:], decRs[RSize:])
299 // Generate R* and signature and encrypt them
300 h.rClient = new([RSize]byte)
302 if _, err = Rand.Read(h.rClient[:]); err != nil {
303 log.Fatalln("Error reading random for R:", err)
305 h.sClient = new([SSize]byte)
306 if _, err = Rand.Read(h.sClient[:]); err != nil {
307 log.Fatalln("Error reading random for S:", err)
309 sign := ed25519.Sign(h.Conf.DSAPriv, h.key[:])
313 enc = make([]byte, MTU-xtea.BlockSize)
315 enc = make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
320 append(h.sClient[:], sign[:]...)...)...))
321 salsa20.XORKeyStream(enc, enc, h.rNonceNext(1), h.key)
323 // Send that to server
324 h.conn.Write(append(enc, idTag(h.Conf.Id, enc)...))
325 h.LastPing = time.Now()
327 // ENC(K, R+2, RC) + IDtag
328 if h.key != nil && len(data) >= 16 {
330 dec := make([]byte, RSize)
331 salsa20.XORKeyStream(dec, data[:RSize], h.rNonceNext(2), h.key)
332 if subtle.ConstantTimeCompare(dec, h.rClient[:]) != 1 {
333 log.Println("Invalid client's random number with", h.addr)
343 keyFromSecrets(h.sServer[:], h.sClient[:]),
345 h.LastPing = time.Now()
348 log.Println("Invalid handshake stage from", h.addr)