]> Cypherpunks.ru repositories - govpn.git/blob - src/govpn/handshake.go
Configure MTU on per-user basis
[govpn.git] / src / govpn / handshake.go
1 /*
2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2016 Sergey Matveev <stargrave@stargrave.org>
4
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.
9
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.
14
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/>.
17 */
18
19 package govpn
20
21 import (
22         "crypto/subtle"
23         "encoding/binary"
24         "io"
25         "log"
26         "time"
27
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"
34 )
35
36 const (
37         RSize = 8
38         SSize = 32
39 )
40
41 type Handshake struct {
42         addr     string
43         conn     io.Writer
44         LastPing time.Time
45         Conf     *PeerConf
46         dsaPubH  *[ed25519.PublicKeySize]byte
47         key      *[32]byte
48         rNonce   *[RSize]byte
49         dhPriv   *[32]byte    // own private DH key
50         rServer  *[RSize]byte // random string for authentication
51         rClient  *[RSize]byte
52         sServer  *[SSize]byte // secret string for main key calculation
53         sClient  *[SSize]byte
54 }
55
56 func keyFromSecrets(server, client []byte) *[SSize]byte {
57         k := new([SSize]byte)
58         for i := 0; i < SSize; i++ {
59                 k[i] = server[i] ^ client[i]
60         }
61         return k
62 }
63
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)
67 }
68
69 // Zero handshake's memory state
70 func (h *Handshake) Zero() {
71         if h.rNonce != nil {
72                 SliceZero(h.rNonce[:])
73         }
74         if h.dhPriv != nil {
75                 SliceZero(h.dhPriv[:])
76         }
77         if h.key != nil {
78                 SliceZero(h.key[:])
79         }
80         if h.dsaPubH != nil {
81                 SliceZero(h.dsaPubH[:])
82         }
83         if h.rServer != nil {
84                 SliceZero(h.rServer[:])
85         }
86         if h.rClient != nil {
87                 SliceZero(h.rClient[:])
88         }
89         if h.sServer != nil {
90                 SliceZero(h.sServer[:])
91         }
92         if h.sClient != nil {
93                 SliceZero(h.sClient[:])
94         }
95 }
96
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)
101         return nonce
102 }
103
104 func dhKeypairGen() (*[32]byte, *[32]byte) {
105         priv := new([32]byte)
106         pub := new([32]byte)
107         repr := new([32]byte)
108         reprFound := false
109         for !reprFound {
110                 if _, err := Rand.Read(priv[:]); err != nil {
111                         log.Fatalln("Error reading random for DH private key:", err)
112                 }
113                 reprFound = extra25519.ScalarBaseMult(pub, repr, priv)
114         }
115         return priv, repr
116 }
117
118 func dhKeyGen(priv, pub *[32]byte) *[32]byte {
119         key := new([32]byte)
120         curve25519.ScalarMult(key, priv, pub)
121         HApply(key)
122         return key
123 }
124
125 // Create new handshake state.
126 func NewHandshake(addr string, conn io.Writer, conf *PeerConf) *Handshake {
127         state := Handshake{
128                 addr:     addr,
129                 conn:     conn,
130                 LastPing: time.Now(),
131                 Conf:     conf,
132         }
133         state.dsaPubH = new([ed25519.PublicKeySize]byte)
134         copy(state.dsaPubH[:], state.Conf.Verifier.Pub[:])
135         HApply(state.dsaPubH)
136         return &state
137 }
138
139 // Generate ID tag from client identification and data.
140 func idTag(id *PeerId, data []byte) []byte {
141         ciph, err := xtea.NewCipher(id[:])
142         if err != nil {
143                 panic(err)
144         }
145         enc := make([]byte, xtea.BlockSize)
146         ciph.Encrypt(enc, data[:xtea.BlockSize])
147         return enc
148 }
149
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()
157
158         state.rNonce = new([RSize]byte)
159         if _, err := Rand.Read(state.rNonce[:]); err != nil {
160                 log.Fatalln("Error reading random for nonce:", err)
161         }
162         var enc []byte
163         if conf.Noise {
164                 enc = make([]byte, conf.MTU-xtea.BlockSize-RSize)
165         } else {
166                 enc = make([]byte, 32)
167         }
168         copy(enc, dhPubRepr[:])
169         if conf.EncLess {
170                 var err error
171                 enc, err = EncLessEncode(state.dsaPubH, state.rNonce[:], enc)
172                 if err != err {
173                         panic(err)
174                 }
175         } else {
176                 salsa20.XORKeyStream(enc, enc, state.rNonce[:], state.dsaPubH)
177         }
178         data := append(state.rNonce[:], enc...)
179         data = append(data, idTag(state.Conf.Id, state.rNonce[:])...)
180         state.conn.Write(data)
181         return state
182 }
183
184 // Process handshake message on the server side.
185 // This function is intended to be called on server's side.
186 // If this is the final handshake message, then new Peer object
187 // will be created and used as a transport. If no mutually
188 // authenticated Peer is ready, then return nil.
189 func (h *Handshake) Server(data []byte) *Peer {
190         // R + ENC(H(DSAPub), R, El(CDHPub)) + IDtag
191         if h.rNonce == nil && ((!h.Conf.EncLess && len(data) >= 48) ||
192                 (h.Conf.EncLess && len(data) == EncLessEnlargeSize+h.Conf.MTU)) {
193                 h.rNonce = new([RSize]byte)
194                 copy(h.rNonce[:], data[:RSize])
195
196                 // Decrypt remote public key
197                 cDHRepr := new([32]byte)
198                 if h.Conf.EncLess {
199                         out, err := EncLessDecode(
200                                 h.dsaPubH,
201                                 h.rNonce[:],
202                                 data[RSize:len(data)-xtea.BlockSize],
203                         )
204                         if err != nil {
205                                 log.Println("Unable to decode packet from", h.addr, err)
206                                 return nil
207                         }
208                         copy(cDHRepr[:], out)
209                 } else {
210                         salsa20.XORKeyStream(
211                                 cDHRepr[:],
212                                 data[RSize:RSize+32],
213                                 h.rNonce[:],
214                                 h.dsaPubH,
215                         )
216                 }
217
218                 // Generate DH keypair
219                 var dhPubRepr *[32]byte
220                 h.dhPriv, dhPubRepr = dhKeypairGen()
221
222                 // Compute shared key
223                 cDH := new([32]byte)
224                 extra25519.RepresentativeToPublicKey(cDH, cDHRepr)
225                 h.key = dhKeyGen(h.dhPriv, cDH)
226
227                 var encPub []byte
228                 var err error
229                 if h.Conf.EncLess {
230                         encPub = make([]byte, h.Conf.MTU)
231                         copy(encPub, dhPubRepr[:])
232                         encPub, err = EncLessEncode(h.dsaPubH, h.rNonceNext(1), encPub)
233                         if err != nil {
234                                 panic(err)
235                         }
236                 } else {
237                         encPub = make([]byte, 32)
238                         salsa20.XORKeyStream(encPub, dhPubRepr[:], h.rNonceNext(1), h.dsaPubH)
239                 }
240
241                 // Generate R* and encrypt them
242                 h.rServer = new([RSize]byte)
243                 if _, err = Rand.Read(h.rServer[:]); err != nil {
244                         log.Fatalln("Error reading random for R:", err)
245                 }
246                 h.sServer = new([SSize]byte)
247                 if _, err = Rand.Read(h.sServer[:]); err != nil {
248                         log.Fatalln("Error reading random for S:", err)
249                 }
250                 var encRs []byte
251                 if h.Conf.Noise && !h.Conf.EncLess {
252                         encRs = make([]byte, h.Conf.MTU-len(encPub)-xtea.BlockSize)
253                 } else if h.Conf.EncLess {
254                         encRs = make([]byte, h.Conf.MTU-xtea.BlockSize)
255                 } else {
256                         encRs = make([]byte, RSize+SSize)
257                 }
258                 copy(encRs, append(h.rServer[:], h.sServer[:]...))
259                 if h.Conf.EncLess {
260                         encRs, err = EncLessEncode(h.key, h.rNonce[:], encRs)
261                         if err != nil {
262                                 panic(err)
263                         }
264                 } else {
265                         salsa20.XORKeyStream(encRs, encRs, h.rNonce[:], h.key)
266                 }
267
268                 // Send that to client
269                 h.conn.Write(append(encPub, append(encRs, idTag(h.Conf.Id, encPub)...)...))
270                 h.LastPing = time.Now()
271         } else
272         // ENC(K, R+1, RS + RC + SC + Sign(DSAPriv, K)) + IDtag
273         if h.rClient == nil && ((!h.Conf.EncLess && len(data) >= 120) ||
274                 (h.Conf.EncLess && len(data) == EncLessEnlargeSize+h.Conf.MTU)) {
275                 var dec []byte
276                 var err error
277                 if h.Conf.EncLess {
278                         dec, err = EncLessDecode(
279                                 h.key,
280                                 h.rNonceNext(1),
281                                 data[:len(data)-xtea.BlockSize],
282                         )
283                         if err != nil {
284                                 log.Println("Unable to decode packet from", h.addr, err)
285                                 return nil
286                         }
287                         dec = dec[:RSize+RSize+SSize+ed25519.SignatureSize]
288                 } else {
289                         dec = make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
290                         salsa20.XORKeyStream(
291                                 dec,
292                                 data[:RSize+RSize+SSize+ed25519.SignatureSize],
293                                 h.rNonceNext(1),
294                                 h.key,
295                         )
296                 }
297                 if subtle.ConstantTimeCompare(dec[:RSize], h.rServer[:]) != 1 {
298                         log.Println("Invalid server's random number with", h.addr)
299                         return nil
300                 }
301                 sign := new([ed25519.SignatureSize]byte)
302                 copy(sign[:], dec[RSize+RSize+SSize:])
303                 if !ed25519.Verify(h.Conf.Verifier.Pub, h.key[:], sign) {
304                         log.Println("Invalid signature from", h.addr)
305                         return nil
306                 }
307
308                 // Send final answer to client
309                 var enc []byte
310                 if h.Conf.Noise {
311                         enc = make([]byte, h.Conf.MTU-xtea.BlockSize)
312                 } else {
313                         enc = make([]byte, RSize)
314                 }
315                 copy(enc, dec[RSize:RSize+RSize])
316                 if h.Conf.EncLess {
317                         enc, err = EncLessEncode(h.key, h.rNonceNext(2), enc)
318                         if err != nil {
319                                 panic(err)
320                         }
321                 } else {
322                         salsa20.XORKeyStream(enc, enc, h.rNonceNext(2), h.key)
323                 }
324                 h.conn.Write(append(enc, idTag(h.Conf.Id, enc)...))
325
326                 // Switch peer
327                 peer := newPeer(
328                         false,
329                         h.addr,
330                         h.conn,
331                         h.Conf,
332                         keyFromSecrets(h.sServer[:], dec[RSize+RSize:RSize+RSize+SSize]))
333                 h.LastPing = time.Now()
334                 return peer
335         } else {
336                 log.Println("Invalid handshake message from", h.addr)
337         }
338         return nil
339 }
340
341 // Process handshake message on the client side.
342 // This function is intended to be called on client's side.
343 // If this is the final handshake message, then new Peer object
344 // will be created and used as a transport. If no mutually
345 // authenticated Peer is ready, then return nil.
346 func (h *Handshake) Client(data []byte) *Peer {
347         // ENC(H(DSAPub), R+1, El(SDHPub)) + ENC(K, R, RS + SS) + IDtag
348         if h.rServer == nil && h.key == nil &&
349                 ((!h.Conf.EncLess && len(data) >= 80) ||
350                         (h.Conf.EncLess && len(data) == 2*(EncLessEnlargeSize+h.Conf.MTU))) {
351                 // Decrypt remote public key
352                 sDHRepr := new([32]byte)
353                 var tmp []byte
354                 var err error
355                 if h.Conf.EncLess {
356                         tmp, err = EncLessDecode(
357                                 h.dsaPubH,
358                                 h.rNonceNext(1),
359                                 data[:len(data)/2],
360                         )
361                         if err != nil {
362                                 log.Println("Unable to decode packet from", h.addr, err)
363                                 return nil
364                         }
365                         copy(sDHRepr[:], tmp[:32])
366                 } else {
367                         salsa20.XORKeyStream(
368                                 sDHRepr[:],
369                                 data[:32],
370                                 h.rNonceNext(1),
371                                 h.dsaPubH,
372                         )
373                 }
374
375                 // Compute shared key
376                 sDH := new([32]byte)
377                 extra25519.RepresentativeToPublicKey(sDH, sDHRepr)
378                 h.key = dhKeyGen(h.dhPriv, sDH)
379
380                 // Decrypt Rs
381                 h.rServer = new([RSize]byte)
382                 h.sServer = new([SSize]byte)
383                 if h.Conf.EncLess {
384                         tmp, err = EncLessDecode(
385                                 h.key,
386                                 h.rNonce[:],
387                                 data[len(data)/2:len(data)-xtea.BlockSize],
388                         )
389                         if err != nil {
390                                 log.Println("Unable to decode packet from", h.addr, err)
391                                 return nil
392                         }
393                         copy(h.rServer[:], tmp[:RSize])
394                         copy(h.sServer[:], tmp[RSize:RSize+SSize])
395                 } else {
396                         decRs := make([]byte, RSize+SSize)
397                         salsa20.XORKeyStream(
398                                 decRs,
399                                 data[SSize:SSize+RSize+SSize],
400                                 h.rNonce[:],
401                                 h.key,
402                         )
403                         copy(h.rServer[:], decRs[:RSize])
404                         copy(h.sServer[:], decRs[RSize:])
405                 }
406
407                 // Generate R* and signature and encrypt them
408                 h.rClient = new([RSize]byte)
409                 if _, err = Rand.Read(h.rClient[:]); err != nil {
410                         log.Fatalln("Error reading random for R:", err)
411                 }
412                 h.sClient = new([SSize]byte)
413                 if _, err = Rand.Read(h.sClient[:]); err != nil {
414                         log.Fatalln("Error reading random for S:", err)
415                 }
416                 sign := ed25519.Sign(h.Conf.DSAPriv, h.key[:])
417
418                 var enc []byte
419                 if h.Conf.Noise {
420                         enc = make([]byte, h.Conf.MTU-xtea.BlockSize)
421                 } else {
422                         enc = make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
423                 }
424                 copy(enc, h.rServer[:])
425                 copy(enc[RSize:], h.rClient[:])
426                 copy(enc[RSize+RSize:], h.sClient[:])
427                 copy(enc[RSize+RSize+SSize:], sign[:])
428                 if h.Conf.EncLess {
429                         enc, err = EncLessEncode(h.key, h.rNonceNext(1), enc)
430                         if err != nil {
431                                 panic(err)
432                         }
433                 } else {
434                         salsa20.XORKeyStream(enc, enc, h.rNonceNext(1), h.key)
435                 }
436
437                 // Send that to server
438                 h.conn.Write(append(enc, idTag(h.Conf.Id, enc)...))
439                 h.LastPing = time.Now()
440         } else
441         // ENC(K, R+2, RC) + IDtag
442         if h.key != nil && ((!h.Conf.EncLess && len(data) >= 16) ||
443                 (h.Conf.EncLess && len(data) == EncLessEnlargeSize+h.Conf.MTU)) {
444                 var err error
445                 // Decrypt rClient
446                 var dec []byte
447                 if h.Conf.EncLess {
448                         dec, err = EncLessDecode(
449                                 h.key,
450                                 h.rNonceNext(2),
451                                 data[:len(data)-xtea.BlockSize],
452                         )
453                         if err != nil {
454                                 log.Println("Unable to decode packet from", h.addr, err)
455                                 return nil
456                         }
457                         dec = dec[:RSize]
458                 } else {
459                         dec = make([]byte, RSize)
460                         salsa20.XORKeyStream(dec, data[:RSize], h.rNonceNext(2), h.key)
461                 }
462                 if subtle.ConstantTimeCompare(dec, h.rClient[:]) != 1 {
463                         log.Println("Invalid client's random number with", h.addr)
464                         return nil
465                 }
466
467                 // Switch peer
468                 peer := newPeer(
469                         true,
470                         h.addr,
471                         h.conn,
472                         h.Conf,
473                         keyFromSecrets(h.sServer[:], h.sClient[:]),
474                 )
475                 h.LastPing = time.Now()
476                 return peer
477         } else {
478                 log.Println("Invalid handshake stage from", h.addr)
479         }
480         return nil
481 }