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 {
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 panic("Can not read random for DH private key")
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 HandshakeNew(addr *net.UDPAddr, conf *PeerConf) *Handshake {
129 LastPing: time.Now(),
132 state.dsaPubH = new([ed25519.PublicKeySize]byte)
133 copy(state.dsaPubH[:], state.Conf.DSAPub[:])
134 HApply(state.dsaPubH)
138 // Generate ID tag from client identification and data.
139 func idTag(id *PeerId, data []byte) []byte {
140 ciph, err := xtea.NewCipher(id[:])
144 enc := make([]byte, xtea.BlockSize)
145 ciph.Encrypt(enc, data[:xtea.BlockSize])
149 // Start handshake's procedure from the client. It is the entry point
150 // for starting the handshake procedure. You have to specify outgoing
151 // conn address, remote's addr address, our own peer configuration.
152 // First handshake packet will be sent immediately.
153 func HandshakeStart(conf *PeerConf, conn *net.UDPConn, addr *net.UDPAddr) *Handshake {
154 state := HandshakeNew(addr, conf)
156 var dhPubRepr *[32]byte
157 state.dhPriv, dhPubRepr = dhKeypairGen()
159 state.rNonce = new([RSize]byte)
160 if _, err := rand.Read(state.rNonce[:]); err != nil {
161 panic("Can not read random for handshake nonce")
163 enc := make([]byte, 32)
164 salsa20.XORKeyStream(enc, dhPubRepr[:], state.rNonce[:], state.dsaPubH)
165 data := append(state.rNonce[:], enc...)
166 data = append(data, idTag(state.Conf.Id, state.rNonce[:])...)
167 conn.WriteToUDP(data, addr)
171 // Process handshake message on the server side.
172 // This function is intended to be called on server's side.
173 // Our outgoing conn connection and received data are required.
174 // If this is the final handshake message, then new Peer object
175 // will be created and used as a transport. If no mutually
176 // authenticated Peer is ready, then return nil.
177 func (h *Handshake) Server(conn *net.UDPConn, data []byte) *Peer {
178 // R + ENC(H(DSAPub), R, El(CDHPub)) + IDtag
179 if len(data) == 48 && h.rNonce == nil {
180 // Generate DH keypair
181 var dhPubRepr *[32]byte
182 h.dhPriv, dhPubRepr = dhKeypairGen()
184 h.rNonce = new([RSize]byte)
185 copy(h.rNonce[:], data[:RSize])
187 // Decrypt remote public key and compute shared key
188 cDHRepr := new([32]byte)
189 salsa20.XORKeyStream(
191 data[RSize:RSize+32],
196 extra25519.RepresentativeToPublicKey(cDH, cDHRepr)
197 h.key = dhKeyGen(h.dhPriv, cDH)
199 encPub := make([]byte, 32)
200 salsa20.XORKeyStream(encPub, dhPubRepr[:], h.rNonceNext(1), h.dsaPubH)
202 // Generate R* and encrypt them
203 h.rServer = new([RSize]byte)
204 if _, err := rand.Read(h.rServer[:]); err != nil {
205 panic("Can not read random for handshake random key")
207 h.sServer = new([SSize]byte)
208 if _, err := rand.Read(h.sServer[:]); err != nil {
209 panic("Can not read random for handshake shared key")
211 encRs := make([]byte, RSize+SSize)
212 salsa20.XORKeyStream(encRs, append(h.rServer[:], h.sServer[:]...), h.rNonce[:], h.key)
214 // Send that to client
215 conn.WriteToUDP(append(encPub, append(encRs, idTag(h.Conf.Id, encPub)...)...), h.addr)
216 h.LastPing = time.Now()
218 // ENC(K, R+1, RS + RC + SC + Sign(DSAPriv, K)) + IDtag
219 if len(data) == 120 && h.rClient == nil {
220 // Decrypted Rs compare rServer
221 dec := make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
222 salsa20.XORKeyStream(
224 data[:RSize+RSize+SSize+ed25519.SignatureSize],
228 if subtle.ConstantTimeCompare(dec[:RSize], h.rServer[:]) != 1 {
229 log.Println("Invalid server's random number with", h.addr)
232 sign := new([ed25519.SignatureSize]byte)
233 copy(sign[:], dec[RSize+RSize+SSize:])
234 if !ed25519.Verify(h.Conf.DSAPub, h.key[:], sign) {
235 log.Println("Invalid signature from", h.addr)
239 // Send final answer to client
240 enc := make([]byte, RSize)
241 salsa20.XORKeyStream(enc, dec[RSize:RSize+RSize], h.rNonceNext(2), h.key)
242 conn.WriteToUDP(append(enc, idTag(h.Conf.Id, enc)...), h.addr)
249 keyFromSecrets(h.sServer[:], dec[RSize+RSize:RSize+RSize+SSize]))
250 h.LastPing = time.Now()
253 log.Println("Invalid handshake message from", h.addr)
258 // Process handshake message on the client side.
259 // This function is intended to be called on client's side.
260 // Our outgoing conn connection, authentication
261 // key and received data are required.
262 // If this is the final handshake message, then new Peer object
263 // will be created and used as a transport. If no mutually
264 // authenticated Peer is ready, then return nil.
265 func (h *Handshake) Client(conn *net.UDPConn, data []byte) *Peer {
267 case 80: // ENC(H(DSAPub), R+1, El(SDHPub)) + ENC(K, R, RS + SS) + IDtag
269 log.Println("Invalid handshake stage from", h.addr)
273 // Decrypt remote public key and compute shared key
274 sDHRepr := new([32]byte)
275 salsa20.XORKeyStream(sDHRepr[:], data[:32], h.rNonceNext(1), h.dsaPubH)
277 extra25519.RepresentativeToPublicKey(sDH, sDHRepr)
278 h.key = dhKeyGen(h.dhPriv, sDH)
281 decRs := make([]byte, RSize+SSize)
282 salsa20.XORKeyStream(decRs, data[SSize:32+RSize+SSize], h.rNonce[:], h.key)
283 h.rServer = new([RSize]byte)
284 copy(h.rServer[:], decRs[:RSize])
285 h.sServer = new([SSize]byte)
286 copy(h.sServer[:], decRs[RSize:])
288 // Generate R* and signature and encrypt them
289 h.rClient = new([RSize]byte)
290 if _, err := rand.Read(h.rClient[:]); err != nil {
291 panic("Can not read random for handshake random key")
293 h.sClient = new([SSize]byte)
294 if _, err := rand.Read(h.sClient[:]); err != nil {
295 panic("Can not read random for handshake shared key")
297 sign := ed25519.Sign(h.Conf.DSAPriv, h.key[:])
299 enc := make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
300 salsa20.XORKeyStream(enc,
303 append(h.sClient[:], sign[:]...)...)...), h.rNonceNext(1), h.key)
305 // Send that to server
306 conn.WriteToUDP(append(enc, idTag(h.Conf.Id, enc)...), h.addr)
307 h.LastPing = time.Now()
308 case 16: // ENC(K, R+2, RC) + IDtag
310 log.Println("Invalid handshake stage from", h.addr)
315 dec := make([]byte, RSize)
316 salsa20.XORKeyStream(dec, data[:RSize], h.rNonceNext(2), h.key)
317 if subtle.ConstantTimeCompare(dec, h.rClient[:]) != 1 {
318 log.Println("Invalid client's random number with", h.addr)
323 peer := newPeer(h.addr, h.Conf, 1, keyFromSecrets(h.sServer[:], h.sClient[:]))
324 h.LastPing = time.Now()
327 log.Println("Invalid handshake message from", h.addr)