]> Cypherpunks.ru repositories - govpn.git/blob - handshake.go
Merge branch 'develop'
[govpn.git] / 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 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                         panic("Can not read random for DH private key")
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 HandshakeNew(addr *net.UDPAddr, conf *PeerConf) *Handshake {
127         state := Handshake{
128                 addr:     addr,
129                 LastPing: time.Now(),
130                 Conf:     conf,
131         }
132         state.dsaPubH = new([ed25519.PublicKeySize]byte)
133         copy(state.dsaPubH[:], state.Conf.DSAPub[:])
134         HApply(state.dsaPubH)
135         return &state
136 }
137
138 // Generate ID tag from client identification and data.
139 func idTag(id *PeerId, data []byte) []byte {
140         ciph, err := xtea.NewCipher(id[:])
141         if err != nil {
142                 panic(err)
143         }
144         enc := make([]byte, xtea.BlockSize)
145         ciph.Encrypt(enc, data[:xtea.BlockSize])
146         return enc
147 }
148
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)
155
156         var dhPubRepr *[32]byte
157         state.dhPriv, dhPubRepr = dhKeypairGen()
158
159         state.rNonce = new([RSize]byte)
160         if _, err := rand.Read(state.rNonce[:]); err != nil {
161                 panic("Can not read random for handshake nonce")
162         }
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         if _, err := conn.WriteTo(data, addr); err != nil {
168                 panic(err)
169         }
170         return state
171 }
172
173 // Process handshake message on the server side.
174 // This function is intended to be called on server's side.
175 // Our outgoing conn connection and received data are required.
176 // If this is the final handshake message, then new Peer object
177 // will be created and used as a transport. If no mutually
178 // authenticated Peer is ready, then return nil.
179 func (h *Handshake) Server(conn *net.UDPConn, data []byte) *Peer {
180         // R + ENC(H(DSAPub), R, El(CDHPub)) + IDtag
181         if len(data) == 48 && h.rNonce == nil {
182                 // Generate DH keypair
183                 var dhPubRepr *[32]byte
184                 h.dhPriv, dhPubRepr = dhKeypairGen()
185
186                 h.rNonce = new([RSize]byte)
187                 copy(h.rNonce[:], data[:RSize])
188
189                 // Decrypt remote public key and compute shared key
190                 cDHRepr := new([32]byte)
191                 salsa20.XORKeyStream(
192                         cDHRepr[:],
193                         data[RSize:RSize+32],
194                         h.rNonce[:],
195                         h.dsaPubH,
196                 )
197                 cDH := new([32]byte)
198                 extra25519.RepresentativeToPublicKey(cDH, cDHRepr)
199                 h.key = dhKeyGen(h.dhPriv, cDH)
200
201                 encPub := make([]byte, 32)
202                 salsa20.XORKeyStream(encPub, dhPubRepr[:], h.rNonceNext(1), h.dsaPubH)
203
204                 // Generate R* and encrypt them
205                 h.rServer = new([RSize]byte)
206                 if _, err := rand.Read(h.rServer[:]); err != nil {
207                         panic("Can not read random for handshake random key")
208                 }
209                 h.sServer = new([SSize]byte)
210                 if _, err := rand.Read(h.sServer[:]); err != nil {
211                         panic("Can not read random for handshake shared key")
212                 }
213                 encRs := make([]byte, RSize+SSize)
214                 salsa20.XORKeyStream(encRs, append(h.rServer[:], h.sServer[:]...), h.rNonce[:], h.key)
215
216                 // Send that to client
217                 if _, err := conn.WriteTo(
218                         append(encPub, append(encRs, idTag(h.Conf.Id, encPub)...)...), h.addr); err != nil {
219                         panic(err)
220                 }
221                 h.LastPing = time.Now()
222         } else
223         // ENC(K, R+1, RS + RC + SC + Sign(DSAPriv, K)) + IDtag
224         if len(data) == 120 && h.rClient == nil {
225                 // Decrypted Rs compare rServer
226                 dec := make([]byte, RSize+RSize+SSize+ed25519.SignatureSize)
227                 salsa20.XORKeyStream(
228                         dec,
229                         data[:RSize+RSize+SSize+ed25519.SignatureSize],
230                         h.rNonceNext(1),
231                         h.key,
232                 )
233                 if subtle.ConstantTimeCompare(dec[:RSize], h.rServer[:]) != 1 {
234                         log.Println("Invalid server's random number with", h.addr)
235                         return nil
236                 }
237                 sign := new([ed25519.SignatureSize]byte)
238                 copy(sign[:], dec[RSize+RSize+SSize:])
239                 if !ed25519.Verify(h.Conf.DSAPub, h.key[:], sign) {
240                         log.Println("Invalid signature from", h.addr)
241                         return nil
242                 }
243
244                 // Send final answer to client
245                 enc := make([]byte, RSize)
246                 salsa20.XORKeyStream(enc, dec[RSize:RSize+RSize], h.rNonceNext(2), h.key)
247                 if _, err := conn.WriteTo(append(enc, idTag(h.Conf.Id, enc)...), h.addr); err != nil {
248                         panic(err)
249                 }
250
251                 // Switch peer
252                 peer := newPeer(
253                         h.addr,
254                         h.Conf,
255                         0,
256                         keyFromSecrets(h.sServer[:], dec[RSize+RSize:RSize+RSize+SSize]))
257                 h.LastPing = time.Now()
258                 return peer
259         } else {
260                 log.Println("Invalid handshake message from", h.addr)
261         }
262         return nil
263 }
264
265 // Process handshake message on the client side.
266 // This function is intended to be called on client's side.
267 // Our outgoing conn connection, authentication
268 // key and received data are required.
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(conn *net.UDPConn, 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 := rand.Read(h.rClient[:]); err != nil {
298                         panic("Can not read random for handshake random key")
299                 }
300                 h.sClient = new([SSize]byte)
301                 if _, err := rand.Read(h.sClient[:]); err != nil {
302                         panic("Can not read random for handshake shared key")
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                 if _, err := conn.WriteTo(append(enc, idTag(h.Conf.Id, enc)...), h.addr); err != nil {
314                         panic(err)
315                 }
316                 h.LastPing = time.Now()
317         case 16: // ENC(K, R+2, RC) + IDtag
318                 if h.key == nil {
319                         log.Println("Invalid handshake stage from", h.addr)
320                         return nil
321                 }
322
323                 // Decrypt rClient
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)
328                         return nil
329                 }
330
331                 // Switch peer
332                 peer := newPeer(h.addr, h.Conf, 1, keyFromSecrets(h.sServer[:], h.sClient[:]))
333                 h.LastPing = time.Now()
334                 return peer
335         default:
336                 log.Println("Invalid handshake message from", h.addr)
337         }
338         return nil
339 }