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/curve25519"
32 "golang.org/x/crypto/salsa20"
33 "golang.org/x/crypto/salsa20/salsa"
34 "golang.org/x/crypto/xtea"
42 type Handshake struct {
47 dsaPubH *[ed25519.PublicKeySize]byte
50 dhPriv *[32]byte // own private DH key
51 rServer *[RSize]byte // random string for authentication
53 sServer *[SSize]byte // secret string for main key calculation
57 func keyFromSecrets(server, client []byte) *[SSize]byte {
59 for i := 0; i < SSize; i++ {
60 k[i] = server[i] ^ client[i]
65 // Apply HSalsa20 function for data. Used to hash public keys.
66 func HApply(data *[32]byte) {
67 salsa.HSalsa20(data, new([16]byte), data, &salsa.Sigma)
70 // Zero handshake's memory state
71 func (h *Handshake) Zero() {
73 sliceZero(h.rNonce[:])
76 sliceZero(h.dhPriv[:])
82 sliceZero(h.dsaPubH[:])
85 sliceZero(h.rServer[:])
88 sliceZero(h.rClient[:])
91 sliceZero(h.sServer[:])
94 sliceZero(h.sClient[:])
98 func (h *Handshake) rNonceNext(count uint64) []byte {
99 nonce := make([]byte, RSize)
100 nonceCurrent, _ := binary.Uvarint(h.rNonce[:])
101 binary.PutUvarint(nonce, nonceCurrent+count)
105 func randRead(b []byte) error {
108 _, err = rand.Read(b)
115 func dhKeypairGen() (*[32]byte, *[32]byte) {
116 priv := new([32]byte)
118 repr := new([32]byte)
121 if err := randRead(priv[:]); err != nil {
122 log.Fatalln("Error reading random for DH private key:", err)
124 reprFound = extra25519.ScalarBaseMult(pub, repr, priv)
129 func dhKeyGen(priv, pub *[32]byte) *[32]byte {
131 curve25519.ScalarMult(key, priv, pub)
136 // Create new handshake state.
137 func NewHandshake(addr string, conn io.Writer, conf *PeerConf) *Handshake {
141 LastPing: time.Now(),
144 state.dsaPubH = new([ed25519.PublicKeySize]byte)
145 copy(state.dsaPubH[:], state.Conf.Verifier.Pub[:])
146 HApply(state.dsaPubH)
150 // Generate ID tag from client identification and data.
151 func idTag(id *PeerId, data []byte) []byte {
152 ciph, err := xtea.NewCipher(id[:])
156 enc := make([]byte, xtea.BlockSize)
157 ciph.Encrypt(enc, data[:xtea.BlockSize])
161 // Start handshake's procedure from the client. It is the entry point
162 // for starting the handshake procedure. // First handshake packet
163 // will be sent immediately.
164 func HandshakeStart(addr string, conn io.Writer, conf *PeerConf) *Handshake {
165 state := NewHandshake(addr, conn, conf)
166 var dhPubRepr *[32]byte
167 state.dhPriv, dhPubRepr = dhKeypairGen()
169 state.rNonce = new([RSize]byte)
170 if err := randRead(state.rNonce[:]); err != nil {
171 log.Fatalln("Error reading random for nonce:", err)
175 enc = make([]byte, MTU-xtea.BlockSize-RSize)
177 enc = make([]byte, 32)
179 copy(enc, dhPubRepr[:])
180 salsa20.XORKeyStream(enc, enc, state.rNonce[:], state.dsaPubH)
181 data := append(state.rNonce[:], enc...)
182 data = append(data, idTag(state.Conf.Id, state.rNonce[:])...)
183 state.conn.Write(data)
187 // Process handshake message on the server side.
188 // This function is intended to be called on server's side.
189 // If this is the final handshake message, then new Peer object
190 // will be created and used as a transport. If no mutually
191 // authenticated Peer is ready, then return nil.
192 func (h *Handshake) Server(data []byte) *Peer {
193 // R + ENC(H(DSAPub), R, El(CDHPub)) + IDtag
194 if h.rNonce == nil && len(data) >= 48 {
195 // Generate DH keypair
196 var dhPubRepr *[32]byte
197 h.dhPriv, dhPubRepr = dhKeypairGen()
199 h.rNonce = new([RSize]byte)
200 copy(h.rNonce[:], data[:RSize])
202 // Decrypt remote public key and compute shared key
203 cDHRepr := new([32]byte)
204 salsa20.XORKeyStream(
206 data[RSize:RSize+32],
211 extra25519.RepresentativeToPublicKey(cDH, cDHRepr)
212 h.key = dhKeyGen(h.dhPriv, cDH)
214 encPub := make([]byte, 32)
215 salsa20.XORKeyStream(encPub, dhPubRepr[:], h.rNonceNext(1), h.dsaPubH)
217 // Generate R* and encrypt them
218 h.rServer = new([RSize]byte)
219 if err := randRead(h.rServer[:]); err != nil {
220 log.Fatalln("Error reading random for R:", err)
222 h.sServer = new([SSize]byte)
223 if err := randRead(h.sServer[:]); err != nil {
224 log.Fatalln("Error reading random for S:", err)
228 encRs = make([]byte, MTU-len(encPub)-xtea.BlockSize)
230 encRs = make([]byte, RSize+SSize)
232 copy(encRs, append(h.rServer[:], h.sServer[:]...))
233 salsa20.XORKeyStream(encRs, encRs, h.rNonce[:], h.key)
235 // Send that to client
236 h.conn.Write(append(encPub, append(encRs, idTag(h.Conf.Id, encPub)...)...))
237 h.LastPing = time.Now()
239 // ENC(K, R+1, RS + RC + SC + Sign(DSAPriv, K)) + IDtag
240 if h.rClient == nil && len(data) >= 120 {
241 // Decrypted Rs compare rServer
242 dec := make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
243 salsa20.XORKeyStream(
245 data[:RSize+RSize+SSize+ed25519.SignatureSize],
249 if subtle.ConstantTimeCompare(dec[:RSize], h.rServer[:]) != 1 {
250 log.Println("Invalid server's random number with", h.addr)
253 sign := new([ed25519.SignatureSize]byte)
254 copy(sign[:], dec[RSize+RSize+SSize:])
255 if !ed25519.Verify(h.Conf.Verifier.Pub, h.key[:], sign) {
256 log.Println("Invalid signature from", h.addr)
260 // Send final answer to client
263 enc = make([]byte, MTU-xtea.BlockSize)
265 enc = make([]byte, RSize)
267 copy(enc, dec[RSize:RSize+RSize])
268 salsa20.XORKeyStream(enc, enc, h.rNonceNext(2), h.key)
269 h.conn.Write(append(enc, idTag(h.Conf.Id, enc)...))
277 keyFromSecrets(h.sServer[:], dec[RSize+RSize:RSize+RSize+SSize]))
278 h.LastPing = time.Now()
281 log.Println("Invalid handshake message from", h.addr)
286 // Process handshake message on the client side.
287 // This function is intended to be called on client's side.
288 // If this is the final handshake message, then new Peer object
289 // will be created and used as a transport. If no mutually
290 // authenticated Peer is ready, then return nil.
291 func (h *Handshake) Client(data []byte) *Peer {
292 // ENC(H(DSAPub), R+1, El(SDHPub)) + ENC(K, R, RS + SS) + IDtag
293 if h.rServer == nil && h.key == nil && len(data) >= 80 {
294 // Decrypt remote public key and compute shared key
295 sDHRepr := new([32]byte)
296 salsa20.XORKeyStream(sDHRepr[:], data[:32], h.rNonceNext(1), h.dsaPubH)
298 extra25519.RepresentativeToPublicKey(sDH, sDHRepr)
299 h.key = dhKeyGen(h.dhPriv, sDH)
302 decRs := make([]byte, RSize+SSize)
303 salsa20.XORKeyStream(decRs, data[SSize:32+RSize+SSize], h.rNonce[:], h.key)
304 h.rServer = new([RSize]byte)
305 copy(h.rServer[:], decRs[:RSize])
306 h.sServer = new([SSize]byte)
307 copy(h.sServer[:], decRs[RSize:])
309 // Generate R* and signature and encrypt them
310 h.rClient = new([RSize]byte)
311 if err := randRead(h.rClient[:]); err != nil {
312 log.Fatalln("Error reading random for R:", err)
314 h.sClient = new([SSize]byte)
315 if err := randRead(h.sClient[:]); err != nil {
316 log.Fatalln("Error reading random for S:", err)
318 sign := ed25519.Sign(h.Conf.DSAPriv, h.key[:])
322 enc = make([]byte, MTU-xtea.BlockSize)
324 enc = make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
329 append(h.sClient[:], sign[:]...)...)...))
330 salsa20.XORKeyStream(enc, enc, h.rNonceNext(1), h.key)
332 // Send that to server
333 h.conn.Write(append(enc, idTag(h.Conf.Id, enc)...))
334 h.LastPing = time.Now()
336 // ENC(K, R+2, RC) + IDtag
337 if h.key != nil && len(data) >= 16 {
339 dec := make([]byte, RSize)
340 salsa20.XORKeyStream(dec, data[:RSize], h.rNonceNext(2), h.key)
341 if subtle.ConstantTimeCompare(dec, h.rClient[:]) != 1 {
342 log.Println("Invalid client's random number with", h.addr)
352 keyFromSecrets(h.sServer[:], h.sClient[:]),
354 h.LastPing = time.Now()
357 log.Println("Invalid handshake stage from", h.addr)