]> Cypherpunks.ru repositories - govpn.git/blob - src/govpn/handshake.go
d99154a9885717ea850db5d28b3f1ecd20250e25
[govpn.git] / src / govpn / handshake.go
1 /*
2 GoVPN -- simple secure free software virtual private network daemon
3 Copyright (C) 2014-2015 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/rand"
23         "crypto/subtle"
24         "encoding/binary"
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     RemoteConn
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 randRead(b []byte) error {
105         var err error
106         if egdPath == "" {
107                 _, err = rand.Read(b)
108         } else {
109                 err = EGDRead(b)
110         }
111         return err
112 }
113
114 func dhKeypairGen() (*[32]byte, *[32]byte) {
115         priv := new([32]byte)
116         pub := new([32]byte)
117         repr := new([32]byte)
118         reprFound := false
119         for !reprFound {
120                 if err := randRead(priv[:]); err != nil {
121                         log.Fatalln("Error reading random for DH private key:", err)
122                 }
123                 reprFound = extra25519.ScalarBaseMult(pub, repr, priv)
124         }
125         return priv, repr
126 }
127
128 func dhKeyGen(priv, pub *[32]byte) *[32]byte {
129         key := new([32]byte)
130         curve25519.ScalarMult(key, priv, pub)
131         HApply(key)
132         return key
133 }
134
135 // Create new handshake state.
136 func HandshakeNew(addr string, conn RemoteConn, conf *PeerConf) *Handshake {
137         state := Handshake{
138                 addr:     addr,
139                 conn:     conn,
140                 LastPing: time.Now(),
141                 Conf:     conf,
142         }
143         state.dsaPubH = new([ed25519.PublicKeySize]byte)
144         copy(state.dsaPubH[:], state.Conf.DSAPub[:])
145         HApply(state.dsaPubH)
146         return &state
147 }
148
149 // Generate ID tag from client identification and data.
150 func idTag(id *PeerId, data []byte) []byte {
151         ciph, err := xtea.NewCipher(id[:])
152         if err != nil {
153                 panic(err)
154         }
155         enc := make([]byte, xtea.BlockSize)
156         ciph.Encrypt(enc, data[:xtea.BlockSize])
157         return enc
158 }
159
160 // Start handshake's procedure from the client. It is the entry point
161 // for starting the handshake procedure. // First handshake packet
162 // will be sent immediately.
163 func HandshakeStart(addr string, conn RemoteConn, conf *PeerConf) *Handshake {
164         state := HandshakeNew(addr, conn, conf)
165         var dhPubRepr *[32]byte
166         state.dhPriv, dhPubRepr = dhKeypairGen()
167
168         state.rNonce = new([RSize]byte)
169         if err := randRead(state.rNonce[:]); err != nil {
170                 log.Fatalln("Error reading random for nonce:", err)
171         }
172         enc := make([]byte, 32)
173         salsa20.XORKeyStream(enc, dhPubRepr[:], state.rNonce[:], state.dsaPubH)
174         data := append(state.rNonce[:], enc...)
175         data = append(data, idTag(state.Conf.Id, state.rNonce[:])...)
176         state.conn.Write(data)
177         return state
178 }
179
180 // Process handshake message on the server side.
181 // This function is intended to be called on server's side.
182 // If this is the final handshake message, then new Peer object
183 // will be created and used as a transport. If no mutually
184 // authenticated Peer is ready, then return nil.
185 func (h *Handshake) Server(data []byte) *Peer {
186         // R + ENC(H(DSAPub), R, El(CDHPub)) + IDtag
187         if len(data) == 48 && h.rNonce == nil {
188                 // Generate DH keypair
189                 var dhPubRepr *[32]byte
190                 h.dhPriv, dhPubRepr = dhKeypairGen()
191
192                 h.rNonce = new([RSize]byte)
193                 copy(h.rNonce[:], data[:RSize])
194
195                 // Decrypt remote public key and compute shared key
196                 cDHRepr := new([32]byte)
197                 salsa20.XORKeyStream(
198                         cDHRepr[:],
199                         data[RSize:RSize+32],
200                         h.rNonce[:],
201                         h.dsaPubH,
202                 )
203                 cDH := new([32]byte)
204                 extra25519.RepresentativeToPublicKey(cDH, cDHRepr)
205                 h.key = dhKeyGen(h.dhPriv, cDH)
206
207                 encPub := make([]byte, 32)
208                 salsa20.XORKeyStream(encPub, dhPubRepr[:], h.rNonceNext(1), h.dsaPubH)
209
210                 // Generate R* and encrypt them
211                 h.rServer = new([RSize]byte)
212                 if err := randRead(h.rServer[:]); err != nil {
213                         log.Fatalln("Error reading random for R:", err)
214                 }
215                 h.sServer = new([SSize]byte)
216                 if err := randRead(h.sServer[:]); err != nil {
217                         log.Fatalln("Error reading random for S:", err)
218                 }
219                 encRs := make([]byte, RSize+SSize)
220                 salsa20.XORKeyStream(encRs, append(h.rServer[:], h.sServer[:]...), h.rNonce[:], h.key)
221
222                 // Send that to client
223                 h.conn.Write(append(encPub, append(encRs, idTag(h.Conf.Id, encPub)...)...))
224                 h.LastPing = time.Now()
225         } else
226         // ENC(K, R+1, RS + RC + SC + Sign(DSAPriv, K)) + IDtag
227         if len(data) == 120 && h.rClient == nil {
228                 // Decrypted Rs compare rServer
229                 dec := make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
230                 salsa20.XORKeyStream(
231                         dec,
232                         data[:RSize+RSize+SSize+ed25519.SignatureSize],
233                         h.rNonceNext(1),
234                         h.key,
235                 )
236                 if subtle.ConstantTimeCompare(dec[:RSize], h.rServer[:]) != 1 {
237                         log.Println("Invalid server's random number with", h.addr)
238                         return nil
239                 }
240                 sign := new([ed25519.SignatureSize]byte)
241                 copy(sign[:], dec[RSize+RSize+SSize:])
242                 if !ed25519.Verify(h.Conf.DSAPub, h.key[:], sign) {
243                         log.Println("Invalid signature from", h.addr)
244                         return nil
245                 }
246
247                 // Send final answer to client
248                 enc := make([]byte, RSize)
249                 salsa20.XORKeyStream(enc, dec[RSize:RSize+RSize], h.rNonceNext(2), h.key)
250                 h.conn.Write(append(enc, idTag(h.Conf.Id, enc)...))
251
252                 // Switch peer
253                 peer := newPeer(
254                         false,
255                         h.addr,
256                         h.conn,
257                         h.Conf,
258                         keyFromSecrets(h.sServer[:], dec[RSize+RSize:RSize+RSize+SSize]))
259                 h.LastPing = time.Now()
260                 return peer
261         } else {
262                 log.Println("Invalid handshake message from", h.addr)
263         }
264         return nil
265 }
266
267 // Process handshake message on the client side.
268 // This function is intended to be called on client's side.
269 // If this is the final handshake message, then new Peer object
270 // will be created and used as a transport. If no mutually
271 // authenticated Peer is ready, then return nil.
272 func (h *Handshake) Client(data []byte) *Peer {
273         switch len(data) {
274         case 80: // ENC(H(DSAPub), R+1, El(SDHPub)) + ENC(K, R, RS + SS) + IDtag
275                 if h.key != nil {
276                         log.Println("Invalid handshake stage from", h.addr)
277                         return nil
278                 }
279
280                 // Decrypt remote public key and compute shared key
281                 sDHRepr := new([32]byte)
282                 salsa20.XORKeyStream(sDHRepr[:], data[:32], h.rNonceNext(1), h.dsaPubH)
283                 sDH := new([32]byte)
284                 extra25519.RepresentativeToPublicKey(sDH, sDHRepr)
285                 h.key = dhKeyGen(h.dhPriv, sDH)
286
287                 // Decrypt Rs
288                 decRs := make([]byte, RSize+SSize)
289                 salsa20.XORKeyStream(decRs, data[SSize:32+RSize+SSize], h.rNonce[:], h.key)
290                 h.rServer = new([RSize]byte)
291                 copy(h.rServer[:], decRs[:RSize])
292                 h.sServer = new([SSize]byte)
293                 copy(h.sServer[:], decRs[RSize:])
294
295                 // Generate R* and signature and encrypt them
296                 h.rClient = new([RSize]byte)
297                 if err := randRead(h.rClient[:]); err != nil {
298                         log.Fatalln("Error reading random for R:", err)
299                 }
300                 h.sClient = new([SSize]byte)
301                 if err := randRead(h.sClient[:]); err != nil {
302                         log.Fatalln("Error reading random for S:", err)
303                 }
304                 sign := ed25519.Sign(h.Conf.DSAPriv, h.key[:])
305
306                 enc := make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
307                 salsa20.XORKeyStream(enc,
308                         append(h.rServer[:],
309                                 append(h.rClient[:],
310                                         append(h.sClient[:], sign[:]...)...)...), h.rNonceNext(1), h.key)
311
312                 // Send that to server
313                 h.conn.Write(append(enc, idTag(h.Conf.Id, enc)...))
314                 h.LastPing = time.Now()
315         case 16: // ENC(K, R+2, RC) + IDtag
316                 if h.key == nil {
317                         log.Println("Invalid handshake stage from", h.addr)
318                         return nil
319                 }
320
321                 // Decrypt rClient
322                 dec := make([]byte, RSize)
323                 salsa20.XORKeyStream(dec, data[:RSize], h.rNonceNext(2), h.key)
324                 if subtle.ConstantTimeCompare(dec, h.rClient[:]) != 1 {
325                         log.Println("Invalid client's random number with", h.addr)
326                         return nil
327                 }
328
329                 // Switch peer
330                 peer := newPeer(
331                         true,
332                         h.addr,
333                         h.conn,
334                         h.Conf,
335                         keyFromSecrets(h.sServer[:], h.sClient[:]),
336                 )
337                 h.LastPing = time.Now()
338                 return peer
339         default:
340                 log.Println("Invalid handshake message from", h.addr)
341         }
342         return nil
343 }