]> Cypherpunks.ru repositories - govpn.git/blob - handshake.go
a3403ea2d978755762e9a04c5aa4d5089353f1ee
[govpn.git] / handshake.go
1 /*
2 govpn -- high-performance secure virtual private network daemon
3 Copyright (C) 2014 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 package main
19
20 import (
21         "crypto/rand"
22         "crypto/subtle"
23         "encoding/binary"
24         "fmt"
25         "net"
26         "time"
27
28         "code.google.com/p/go.crypto/curve25519"
29         "code.google.com/p/go.crypto/poly1305"
30         "code.google.com/p/go.crypto/salsa20"
31         "code.google.com/p/go.crypto/salsa20/salsa"
32 )
33
34 type Handshake struct {
35         addr     *net.UDPAddr
36         lastPing time.Time
37         rNonce   *[8]byte
38         dhPriv   *[32]byte // own private DH key
39         key      *[32]byte // handshake encryption key
40         rServer  *[8]byte  // random string for authentication
41         rClient  *[8]byte
42         sServer  *[32]byte // secret string for main key calculation
43         sClient  *[32]byte
44 }
45
46 func KeyFromSecrets(server, client []byte) *[32]byte {
47         k := new([32]byte)
48         for i := 0; i < 32; i++ {
49                 k[i] = server[i] ^ client[i]
50         }
51         return k
52 }
53
54 // Check if it is valid handshake-related message
55 // Minimal size and last 16 zero bytes
56 func isValidHandshakePkt(pkt []byte) bool {
57         if len(pkt) < 24 {
58                 return false
59         }
60         for i := len(pkt) - poly1305.TagSize; i < len(pkt); i++ {
61                 if pkt[i] != '\x00' {
62                         return false
63                 }
64         }
65         return true
66 }
67
68 func (h *Handshake) rNonceNext() []byte {
69         nonce := make([]byte, 8)
70         nonceCurrent, _ := binary.Uvarint(h.rNonce[:])
71         binary.PutUvarint(nonce, nonceCurrent+1)
72         return nonce
73 }
74
75 func dhPrivGen() *[32]byte {
76         dh := new([32]byte)
77         if _, err := rand.Read(dh[:]); err != nil {
78                 panic("Can not read random for DH private key")
79         }
80         // This bitwise operations are required by Curve25519 whitepaper
81         dh[0] = dh[0] & (255 - 128 - 64 - 32) // clear first three bits
82         dh[31] = dh[31] & (255 - 1)           // clear last bit
83         dh[31] = dh[31] | 2                   // set pre-last bit
84         return dh
85 }
86
87 func dhKeyGen(priv, pub *[32]byte) *[32]byte {
88         key := new([32]byte)
89         curve25519.ScalarMult(key, priv, pub)
90         salsa.HSalsa20(key, new([16]byte), key, &salsa.Sigma)
91         return key
92 }
93
94 func HandshakeStart(conn *net.UDPConn, addr *net.UDPAddr, key *[32]byte) *Handshake {
95         state := Handshake{}
96         state.addr = addr
97         state.lastPing = time.Now()
98
99         state.dhPriv = dhPrivGen()
100         dhPub := new([32]byte)
101         curve25519.ScalarBaseMult(dhPub, state.dhPriv)
102
103         state.rNonce = new([8]byte)
104         if _, err := rand.Read(state.rNonce[:]); err != nil {
105                 panic("Can not read random for handshake nonce")
106         }
107         enc := make([]byte, 32)
108         salsa20.XORKeyStream(enc, dhPub[:], state.rNonce[:], key)
109
110         if _, err := conn.WriteTo(
111                 append(state.rNonce[:],
112                         append(enc, make([]byte, poly1305.TagSize)...)...), addr); err != nil {
113                 panic(err)
114         }
115         return &state
116 }
117
118 func (h *Handshake) Server(conn *net.UDPConn, key *[32]byte, data []byte) *Peer {
119         switch len(data) {
120         case 56: // R + ENC(PSK, dh_client_pub) + NULLs
121                 fmt.Print("[HS1]")
122                 if h.rNonce != nil {
123                         fmt.Print("[S?]")
124                         return nil
125                 }
126
127                 // Generate private DH key
128                 h.dhPriv = dhPrivGen()
129                 dhPub := new([32]byte)
130                 curve25519.ScalarBaseMult(dhPub, h.dhPriv)
131
132                 // Decrypt remote public key and compute shared key
133                 dec := new([32]byte)
134                 salsa20.XORKeyStream(dec[:], data[8:8+32], data[:8], key)
135                 h.key = dhKeyGen(h.dhPriv, dec)
136
137                 // Compute nonce and encrypt our public key
138                 h.rNonce = new([8]byte)
139                 copy(h.rNonce[:], data[:8])
140
141                 encPub := make([]byte, 32)
142                 salsa20.XORKeyStream(encPub, dhPub[:], h.rNonceNext(), key)
143
144                 // Generate R* and encrypt them
145                 h.rServer = new([8]byte)
146                 if _, err := rand.Read(h.rServer[:]); err != nil {
147                         panic("Can not read random for handshake random key")
148                 }
149                 h.sServer = new([32]byte)
150                 if _, err := rand.Read(h.sServer[:]); err != nil {
151                         panic("Can not read random for handshake shared key")
152                 }
153                 encRs := make([]byte, 8+32)
154                 salsa20.XORKeyStream(encRs, append(h.rServer[:], h.sServer[:]...), h.rNonce[:], h.key)
155
156                 // Send that to client
157                 if _, err := conn.WriteTo(
158                         append(encPub,
159                                 append(encRs, make([]byte, poly1305.TagSize)...)...), h.addr); err != nil {
160                         panic(err)
161                 }
162                 fmt.Print("[OK]")
163         case 64: // ENC(K, RS + RC + SC) + NULLs
164                 fmt.Print("[HS3]")
165                 if (h.rNonce == nil) || (h.rClient != nil) {
166                         fmt.Print("[S?]")
167                         return nil
168                 }
169
170                 // Decrypt Rs compare rServer
171                 decRs := make([]byte, 8+8+32)
172                 salsa20.XORKeyStream(decRs, data[:8+8+32], h.rNonceNext(), h.key)
173                 if res := subtle.ConstantTimeCompare(decRs[:8], h.rServer[:]); res != 1 {
174                         fmt.Print("[rS?]")
175                         return nil
176                 }
177
178                 // Send final answer to client
179                 enc := make([]byte, 8)
180                 salsa20.XORKeyStream(enc, decRs[8:8+8], make([]byte, 8), h.key)
181                 if _, err := conn.WriteTo(append(enc, make([]byte, poly1305.TagSize)...), h.addr); err != nil {
182                         panic(err)
183                 }
184
185                 // Switch peer
186                 peer := Peer{addr: h.addr, nonceOur: 0, nonceRecv: 0}
187                 peer.SetAlive()
188                 peer.key = KeyFromSecrets(h.sServer[:], decRs[8+8:])
189                 fmt.Print("[OK]")
190                 return &peer
191         default:
192                 fmt.Print("[HS?]")
193         }
194         return nil
195 }
196
197 func (h *Handshake) Client(conn *net.UDPConn, key *[32]byte, data []byte) *Peer {
198         switch len(data) {
199         case 88: // ENC(PSK, dh_server_pub) + ENC(K, RS + SS) + NULLs
200                 fmt.Print("[HS2]")
201                 if h.key != nil {
202                         fmt.Print("[S?]")
203                         return nil
204                 }
205
206                 // Decrypt remote public key and compute shared key
207                 dec := new([32]byte)
208                 salsa20.XORKeyStream(dec[:], data[:32], h.rNonceNext(), key)
209                 h.key = dhKeyGen(h.dhPriv, dec)
210
211                 // Decrypt Rs
212                 decRs := make([]byte, 8+32)
213                 salsa20.XORKeyStream(decRs, data[32:32+8+32], h.rNonce[:], h.key)
214                 h.rServer = new([8]byte)
215                 copy(h.rServer[:], decRs[:8])
216                 h.sServer = new([32]byte)
217                 copy(h.sServer[:], decRs[8:])
218
219                 // Generate R* and encrypt them
220                 h.rClient = new([8]byte)
221                 if _, err := rand.Read(h.rClient[:]); err != nil {
222                         panic("Can not read random for handshake random key")
223                 }
224                 h.sClient = new([32]byte)
225                 if _, err := rand.Read(h.sClient[:]); err != nil {
226                         panic("Can not read random for handshake shared key")
227                 }
228                 encRs := make([]byte, 8+8+32)
229                 salsa20.XORKeyStream(encRs,
230                         append(h.rServer[:],
231                                 append(h.rClient[:], h.sClient[:]...)...), h.rNonceNext(), h.key)
232
233                 // Send that to server
234                 if _, err := conn.WriteTo(append(encRs, make([]byte, poly1305.TagSize)...), h.addr); err != nil {
235                         panic(err)
236                 }
237                 fmt.Print("[OK]")
238         case 24: // ENC(K, RC) + NULLs
239                 fmt.Print("[HS4]")
240                 if h.key == nil {
241                         fmt.Print("[S?]")
242                         return nil
243                 }
244
245                 // Decrypt rClient
246                 dec := make([]byte, 8)
247                 salsa20.XORKeyStream(dec, data[:8], make([]byte, 8), h.key)
248                 if res := subtle.ConstantTimeCompare(dec, h.rClient[:]); res != 1 {
249                         fmt.Print("[rC?]")
250                         return nil
251                 }
252
253                 // Switch peer
254                 peer := Peer{addr: h.addr, nonceOur: 1, nonceRecv: 0}
255                 peer.SetAlive()
256                 peer.key = KeyFromSecrets(h.sServer[:], h.sClient[:])
257                 fmt.Print("[OK]")
258                 return &peer
259         default:
260                 fmt.Print("[HS?]")
261         }
262         return nil
263 }