]> Cypherpunks.ru repositories - govpn.git/blob - src/govpn/handshake.go
Ability to use EGD-compatible PRNGs
[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         "net"
27         "time"
28
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"
35 )
36
37 const (
38         RSize = 8
39         SSize = 32
40 )
41
42 type Handshake struct {
43         addr     *net.UDPAddr
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 *net.UDPAddr, conf *PeerConf) *Handshake {
137         state := Handshake{
138                 addr:     addr,
139                 LastPing: time.Now(),
140                 Conf:     conf,
141         }
142         state.dsaPubH = new([ed25519.PublicKeySize]byte)
143         copy(state.dsaPubH[:], state.Conf.DSAPub[:])
144         HApply(state.dsaPubH)
145         return &state
146 }
147
148 // Generate ID tag from client identification and data.
149 func idTag(id *PeerId, data []byte) []byte {
150         ciph, err := xtea.NewCipher(id[:])
151         if err != nil {
152                 panic(err)
153         }
154         enc := make([]byte, xtea.BlockSize)
155         ciph.Encrypt(enc, data[:xtea.BlockSize])
156         return enc
157 }
158
159 // Start handshake's procedure from the client. It is the entry point
160 // for starting the handshake procedure. You have to specify outgoing
161 // conn address, remote's addr address, our own peer configuration.
162 // First handshake packet will be sent immediately.
163 func HandshakeStart(conf *PeerConf, conn *net.UDPConn, addr *net.UDPAddr) *Handshake {
164         state := HandshakeNew(addr, conf)
165
166         var dhPubRepr *[32]byte
167         state.dhPriv, dhPubRepr = dhKeypairGen()
168
169         state.rNonce = new([RSize]byte)
170         if err := randRead(state.rNonce[:]); err != nil {
171                 log.Fatalln("Error reading random for nonce:", err)
172         }
173         enc := make([]byte, 32)
174         salsa20.XORKeyStream(enc, dhPubRepr[:], state.rNonce[:], state.dsaPubH)
175         data := append(state.rNonce[:], enc...)
176         data = append(data, idTag(state.Conf.Id, state.rNonce[:])...)
177         conn.WriteToUDP(data, addr)
178         return state
179 }
180
181 // Process handshake message on the server side.
182 // This function is intended to be called on server's side.
183 // Our outgoing conn connection and received data are required.
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(conn *net.UDPConn, 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()
193
194                 h.rNonce = new([RSize]byte)
195                 copy(h.rNonce[:], data[:RSize])
196
197                 // Decrypt remote public key and compute shared key
198                 cDHRepr := new([32]byte)
199                 salsa20.XORKeyStream(
200                         cDHRepr[:],
201                         data[RSize:RSize+32],
202                         h.rNonce[:],
203                         h.dsaPubH,
204                 )
205                 cDH := new([32]byte)
206                 extra25519.RepresentativeToPublicKey(cDH, cDHRepr)
207                 h.key = dhKeyGen(h.dhPriv, cDH)
208
209                 encPub := make([]byte, 32)
210                 salsa20.XORKeyStream(encPub, dhPubRepr[:], h.rNonceNext(1), h.dsaPubH)
211
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)
216                 }
217                 h.sServer = new([SSize]byte)
218                 if err := randRead(h.sServer[:]); err != nil {
219                         log.Fatalln("Error reading random for S:", err)
220                 }
221                 encRs := make([]byte, RSize+SSize)
222                 salsa20.XORKeyStream(encRs, append(h.rServer[:], h.sServer[:]...), h.rNonce[:], h.key)
223
224                 // Send that to client
225                 conn.WriteToUDP(append(encPub, append(encRs, idTag(h.Conf.Id, encPub)...)...), h.addr)
226                 h.LastPing = time.Now()
227         } else
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(
233                         dec,
234                         data[:RSize+RSize+SSize+ed25519.SignatureSize],
235                         h.rNonceNext(1),
236                         h.key,
237                 )
238                 if subtle.ConstantTimeCompare(dec[:RSize], h.rServer[:]) != 1 {
239                         log.Println("Invalid server's random number with", h.addr)
240                         return nil
241                 }
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)
246                         return nil
247                 }
248
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                 conn.WriteToUDP(append(enc, idTag(h.Conf.Id, enc)...), h.addr)
253
254                 // Switch peer
255                 peer := newPeer(
256                         h.addr,
257                         h.Conf,
258                         0,
259                         keyFromSecrets(h.sServer[:], dec[RSize+RSize:RSize+RSize+SSize]))
260                 h.LastPing = time.Now()
261                 return peer
262         } else {
263                 log.Println("Invalid handshake message from", h.addr)
264         }
265         return nil
266 }
267
268 // Process handshake message on the client side.
269 // This function is intended to be called on client's side.
270 // Our outgoing conn connection, authentication
271 // key and received data are required.
272 // If this is the final handshake message, then new Peer object
273 // will be created and used as a transport. If no mutually
274 // authenticated Peer is ready, then return nil.
275 func (h *Handshake) Client(conn *net.UDPConn, data []byte) *Peer {
276         switch len(data) {
277         case 80: // ENC(H(DSAPub), R+1, El(SDHPub)) + ENC(K, R, RS + SS) + IDtag
278                 if h.key != nil {
279                         log.Println("Invalid handshake stage from", h.addr)
280                         return nil
281                 }
282
283                 // Decrypt remote public key and compute shared key
284                 sDHRepr := new([32]byte)
285                 salsa20.XORKeyStream(sDHRepr[:], data[:32], h.rNonceNext(1), h.dsaPubH)
286                 sDH := new([32]byte)
287                 extra25519.RepresentativeToPublicKey(sDH, sDHRepr)
288                 h.key = dhKeyGen(h.dhPriv, sDH)
289
290                 // Decrypt Rs
291                 decRs := make([]byte, RSize+SSize)
292                 salsa20.XORKeyStream(decRs, data[SSize:32+RSize+SSize], h.rNonce[:], h.key)
293                 h.rServer = new([RSize]byte)
294                 copy(h.rServer[:], decRs[:RSize])
295                 h.sServer = new([SSize]byte)
296                 copy(h.sServer[:], decRs[RSize:])
297
298                 // Generate R* and signature and encrypt them
299                 h.rClient = new([RSize]byte)
300                 if err := randRead(h.rClient[:]); err != nil {
301                         log.Fatalln("Error reading random for R:", err)
302                 }
303                 h.sClient = new([SSize]byte)
304                 if err := randRead(h.sClient[:]); err != nil {
305                         log.Fatalln("Error reading random for S:", err)
306                 }
307                 sign := ed25519.Sign(h.Conf.DSAPriv, h.key[:])
308
309                 enc := make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
310                 salsa20.XORKeyStream(enc,
311                         append(h.rServer[:],
312                                 append(h.rClient[:],
313                                         append(h.sClient[:], sign[:]...)...)...), h.rNonceNext(1), h.key)
314
315                 // Send that to server
316                 conn.WriteToUDP(append(enc, idTag(h.Conf.Id, enc)...), h.addr)
317                 h.LastPing = time.Now()
318         case 16: // ENC(K, R+2, RC) + IDtag
319                 if h.key == nil {
320                         log.Println("Invalid handshake stage from", h.addr)
321                         return nil
322                 }
323
324                 // Decrypt rClient
325                 dec := make([]byte, RSize)
326                 salsa20.XORKeyStream(dec, data[:RSize], h.rNonceNext(2), h.key)
327                 if subtle.ConstantTimeCompare(dec, h.rClient[:]) != 1 {
328                         log.Println("Invalid client's random number with", h.addr)
329                         return nil
330                 }
331
332                 // Switch peer
333                 peer := newPeer(h.addr, h.Conf, 1, keyFromSecrets(h.sServer[:], h.sClient[:]))
334                 h.LastPing = time.Now()
335                 return peer
336         default:
337                 log.Println("Invalid handshake message from", h.addr)
338         }
339         return nil
340 }