2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2015 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 HandshakeNew(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.DSAPub[:])
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 := HandshakeNew(addr, conn, conf)
167 var dhPubRepr *[32]byte
168 state.dhPriv, dhPubRepr = dhKeypairGen()
170 state.rNonce = new([RSize]byte)
171 if err := randRead(state.rNonce[:]); err != nil {
172 log.Fatalln("Error reading random for nonce:", err)
174 enc := make([]byte, 32)
175 salsa20.XORKeyStream(enc, dhPubRepr[:], state.rNonce[:], state.dsaPubH)
176 data := append(state.rNonce[:], enc...)
177 data = append(data, idTag(state.Conf.Id, state.rNonce[:])...)
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 len(data) == 48 && h.rNonce == nil {
190 // Generate DH keypair
191 var dhPubRepr *[32]byte
192 h.dhPriv, dhPubRepr = dhKeypairGen()
194 h.rNonce = new([RSize]byte)
195 copy(h.rNonce[:], data[:RSize])
197 // Decrypt remote public key and compute shared key
198 cDHRepr := new([32]byte)
199 salsa20.XORKeyStream(
201 data[RSize:RSize+32],
206 extra25519.RepresentativeToPublicKey(cDH, cDHRepr)
207 h.key = dhKeyGen(h.dhPriv, cDH)
209 encPub := make([]byte, 32)
210 salsa20.XORKeyStream(encPub, dhPubRepr[:], h.rNonceNext(1), h.dsaPubH)
212 // Generate R* and encrypt them
213 h.rServer = new([RSize]byte)
214 if err := randRead(h.rServer[:]); err != nil {
215 log.Fatalln("Error reading random for R:", err)
217 h.sServer = new([SSize]byte)
218 if err := randRead(h.sServer[:]); err != nil {
219 log.Fatalln("Error reading random for S:", err)
221 encRs := make([]byte, RSize+SSize)
222 salsa20.XORKeyStream(encRs, append(h.rServer[:], h.sServer[:]...), h.rNonce[:], h.key)
224 // Send that to client
225 h.conn.Write(append(encPub, append(encRs, idTag(h.Conf.Id, encPub)...)...))
226 h.LastPing = time.Now()
228 // ENC(K, R+1, RS + RC + SC + Sign(DSAPriv, K)) + IDtag
229 if len(data) == 120 && h.rClient == nil {
230 // Decrypted Rs compare rServer
231 dec := make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
232 salsa20.XORKeyStream(
234 data[:RSize+RSize+SSize+ed25519.SignatureSize],
238 if subtle.ConstantTimeCompare(dec[:RSize], h.rServer[:]) != 1 {
239 log.Println("Invalid server's random number with", h.addr)
242 sign := new([ed25519.SignatureSize]byte)
243 copy(sign[:], dec[RSize+RSize+SSize:])
244 if !ed25519.Verify(h.Conf.DSAPub, h.key[:], sign) {
245 log.Println("Invalid signature from", h.addr)
249 // Send final answer to client
250 enc := make([]byte, RSize)
251 salsa20.XORKeyStream(enc, dec[RSize:RSize+RSize], h.rNonceNext(2), h.key)
252 h.conn.Write(append(enc, idTag(h.Conf.Id, enc)...))
260 keyFromSecrets(h.sServer[:], dec[RSize+RSize:RSize+RSize+SSize]))
261 h.LastPing = time.Now()
264 log.Println("Invalid handshake message from", h.addr)
269 // Process handshake message on the client side.
270 // This function is intended to be called on client's side.
271 // If this is the final handshake message, then new Peer object
272 // will be created and used as a transport. If no mutually
273 // authenticated Peer is ready, then return nil.
274 func (h *Handshake) Client(data []byte) *Peer {
276 case 80: // ENC(H(DSAPub), R+1, El(SDHPub)) + ENC(K, R, RS + SS) + IDtag
278 log.Println("Invalid handshake stage from", h.addr)
282 // Decrypt remote public key and compute shared key
283 sDHRepr := new([32]byte)
284 salsa20.XORKeyStream(sDHRepr[:], data[:32], h.rNonceNext(1), h.dsaPubH)
286 extra25519.RepresentativeToPublicKey(sDH, sDHRepr)
287 h.key = dhKeyGen(h.dhPriv, sDH)
290 decRs := make([]byte, RSize+SSize)
291 salsa20.XORKeyStream(decRs, data[SSize:32+RSize+SSize], h.rNonce[:], h.key)
292 h.rServer = new([RSize]byte)
293 copy(h.rServer[:], decRs[:RSize])
294 h.sServer = new([SSize]byte)
295 copy(h.sServer[:], decRs[RSize:])
297 // Generate R* and signature and encrypt them
298 h.rClient = new([RSize]byte)
299 if err := randRead(h.rClient[:]); err != nil {
300 log.Fatalln("Error reading random for R:", err)
302 h.sClient = new([SSize]byte)
303 if err := randRead(h.sClient[:]); err != nil {
304 log.Fatalln("Error reading random for S:", err)
306 sign := ed25519.Sign(h.Conf.DSAPriv, h.key[:])
308 enc := make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
309 salsa20.XORKeyStream(enc,
312 append(h.sClient[:], sign[:]...)...)...), h.rNonceNext(1), h.key)
314 // Send that to server
315 h.conn.Write(append(enc, idTag(h.Conf.Id, enc)...))
316 h.LastPing = time.Now()
317 case 16: // ENC(K, R+2, RC) + IDtag
319 log.Println("Invalid handshake stage from", h.addr)
324 dec := make([]byte, RSize)
325 salsa20.XORKeyStream(dec, data[:RSize], h.rNonceNext(2), h.key)
326 if subtle.ConstantTimeCompare(dec, h.rClient[:]) != 1 {
327 log.Println("Invalid client's random number with", h.addr)
332 peer := newPeer(h.addr, h.conn, h.Conf, 1, keyFromSecrets(h.sServer[:], h.sClient[:]))
333 h.LastPing = time.Now()
336 log.Println("Invalid handshake message from", h.addr)