Update SPTPS protocol.
[tinc] / src / sptps.c
1 /*
2     sptps.c -- Simple Peer-to-Peer Security
3     Copyright (C) 2011 Guus Sliepen <guus@tinc-vpn.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 2 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 along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "system.h"
21
22 #include "cipher.h"
23 #include "crypto.h"
24 #include "digest.h"
25 #include "ecdh.h"
26 #include "ecdsa.h"
27 #include "prf.h"
28 #include "sptps.h"
29
30 char *logfilename;
31 #include "utils.c"
32
33 /*
34    Nonce MUST be exchanged first (done)
35    Signatures MUST be done over both nonces, to guarantee the signature is fresh
36    Otherwise: if ECDHE key of one side is compromised, it can be reused!
37
38    Add explicit tag to beginning of structure to distinguish the client and server when signing. (done)
39
40    Sign all handshake messages up to ECDHE kex with long-term public keys. (done)
41
42    HMACed KEX finished message to prevent downgrade attacks and prove you have the right key material (done by virtue of ECDSA over the whole ECDHE exchange?)
43
44    Explicit close message needs to be added.
45
46    Maybe do add some alert messages to give helpful error messages? Not more than TLS sends.
47
48    Use counter mode instead of OFB.
49
50    Make sure ECC operations are fixed time (aka prevent side-channel attacks).
51 */
52
53 // Log an error message.
54 static bool error(sptps_t *s, int s_errno, const char *msg) {
55         fprintf(stderr, "SPTPS error: %s\n", msg);
56         errno = s_errno;
57         return false;
58 }
59
60 // Send a record (private version, accepts all record types, handles encryption and authentication).
61 static bool send_record_priv(sptps_t *s, uint8_t type, const char *data, uint16_t len) {
62         char plaintext[len + 23];
63         char ciphertext[len + 19];
64
65         // Create header with sequence number, length and record type
66         uint32_t seqno = htonl(s->outseqno++);
67         uint16_t netlen = htons(len);
68
69         memcpy(plaintext, &seqno, 4);
70         memcpy(plaintext + 4, &netlen, 2);
71         plaintext[6] = type;
72
73         // Add plaintext (TODO: avoid unnecessary copy)
74         memcpy(plaintext + 7, data, len);
75
76         if(s->outstate) {
77                 // If first handshake has finished, encrypt and HMAC
78                 if(!digest_create(&s->outdigest, plaintext, len + 7, plaintext + 7 + len))
79                         return false;
80
81                 if(!cipher_encrypt(&s->outcipher, plaintext + 4, sizeof ciphertext, ciphertext, NULL, false))
82                         return false;
83
84                 return s->send_data(s->handle, ciphertext, len + 19);
85         } else {
86                 // Otherwise send as plaintext
87                 return s->send_data(s->handle, plaintext + 4, len + 3);
88         }
89 }
90
91 // Send an application record.
92 bool send_record(sptps_t *s, uint8_t type, const char *data, uint16_t len) {
93         // Sanity checks: application cannot send data before handshake is finished,
94         // and only record types 0..127 are allowed.
95         if(!s->outstate)
96                 return error(s, EINVAL, "Handshake phase not finished yet");
97
98         if(type >= SPTPS_HANDSHAKE)
99                 return error(s, EINVAL, "Invalid application record type");
100
101         return send_record_priv(s, type, data, len);
102 }
103
104 // Send a Key EXchange record, containing a random nonce and an ECDHE public key.
105 static bool send_kex(sptps_t *s) {
106         size_t keylen = ECDH_SIZE;
107
108         // Make room for our KEX message, which we will keep around since send_sig() needs it.
109         s->mykex = realloc(s->mykex, 1 + 32 + keylen);
110         if(!s->mykex)
111                 return error(s, errno, strerror(errno));
112
113         // Set version byte to zero.
114         s->mykex[0] = SPTPS_VERSION;
115
116         // Create a random nonce.
117         randomize(s->mykex + 1, 32);
118
119         // Create a new ECDH public key.
120         if(!ecdh_generate_public(&s->ecdh, s->mykex + 1 + 32))
121                 return false;
122
123         return send_record_priv(s, SPTPS_HANDSHAKE, s->mykex, 1 + 32 + keylen);
124 }
125
126 // Send a SIGnature record, containing an ECDSA signature over both KEX records.
127 static bool send_sig(sptps_t *s) {
128         size_t keylen = ECDH_SIZE;
129         size_t siglen = ecdsa_size(&s->mykey);
130
131         // Concatenate both KEX messages, plus tag indicating if it is from the connection originator
132         char msg[(1 + 32 + keylen) * 2 + 1];
133         char sig[siglen];
134
135         msg[0] = s->initiator;
136         memcpy(msg + 1, s->mykex, 1 + 32 + keylen);
137         memcpy(msg + 2 + 32 + keylen, s->hiskex, 1 + 32 + keylen);
138
139         // Sign the result.
140         if(!ecdsa_sign(&s->mykey, msg, sizeof msg, sig))
141                 return false;
142
143         // Send the SIG exchange record.
144         return send_record_priv(s, SPTPS_HANDSHAKE, sig, sizeof sig);
145 }
146
147 // Generate key material from the shared secret created from the ECDHE key exchange.
148 static bool generate_key_material(sptps_t *s, const char *shared, size_t len) {
149         // Initialise cipher and digest structures if necessary
150         if(!s->outstate) {
151                 bool result
152                         =  cipher_open_by_name(&s->incipher, "aes-256-ofb")
153                         && cipher_open_by_name(&s->outcipher, "aes-256-ofb")
154                         && digest_open_by_name(&s->indigest, "sha256", 16)
155                         && digest_open_by_name(&s->outdigest, "sha256", 16);
156                 if(!result)
157                         return false;
158         }
159
160         // Allocate memory for key material
161         size_t keylen = digest_keylength(&s->indigest) + digest_keylength(&s->outdigest) + cipher_keylength(&s->incipher) + cipher_keylength(&s->outcipher);
162
163         s->key = realloc(s->key, keylen);
164         if(!s->key)
165                 return error(s, errno, strerror(errno));
166
167         // Create the HMAC seed, which is "key expansion" + session label + server nonce + client nonce
168         char seed[s->labellen + 64 + 13];
169         strcpy(seed, "key expansion");
170         if(s->initiator) {
171                 memcpy(seed + 13, s->mykex + 1, 32);
172                 memcpy(seed + 45, s->hiskex + 1, 32);
173         } else {
174                 memcpy(seed + 13, s->hiskex + 1, 32);
175                 memcpy(seed + 45, s->mykex + 1, 32);
176         }
177         memcpy(seed + 78, s->label, s->labellen);
178
179         // Use PRF to generate the key material
180         if(!prf(shared, len, seed, s->labellen + 64 + 13, s->key, keylen))
181                 return false;
182
183         return true;
184 }
185
186 // Send an ACKnowledgement record.
187 static bool send_ack(sptps_t *s) {
188         return send_record_priv(s, SPTPS_HANDSHAKE, "", 0);
189 }
190
191 // Receive an ACKnowledgement record.
192 static bool receive_ack(sptps_t *s, const char *data, uint16_t len) {
193         if(len)
194                 return false;
195
196         // TODO: set cipher/digest keys
197         return error(s, ENOSYS, "receive_ack() not completely implemented yet");
198 }
199
200 // Receive a Key EXchange record, respond by sending a SIG record.
201 static bool receive_kex(sptps_t *s, const char *data, uint16_t len) {
202         // Verify length of the HELLO record
203         if(len != 1 + 32 + ECDH_SIZE)
204                 return error(s, EIO, "Invalid KEX record length");
205
206         // Ignore version number for now.
207
208         // Make a copy of the KEX message, send_sig() and receive_sig() need it
209         s->hiskex = realloc(s->hiskex, len);
210         if(!s->hiskex)
211                 return error(s, errno, strerror(errno));
212
213         memcpy(s->hiskex, data, len);
214
215         return send_sig(s);
216 }
217
218 // Receive a SIGnature record, verify it, if it passed, compute the shared secret and calculate the session keys.
219 static bool receive_sig(sptps_t *s, const char *data, uint16_t len) {
220         size_t keylen = ECDH_SIZE;
221         size_t siglen = ecdsa_size(&s->hiskey);
222
223         // Verify length of KEX record.
224         if(len != siglen)
225                 return error(s, EIO, "Invalid KEX record length");
226
227         // Concatenate both KEX messages, plus tag indicating if it is from the connection originator
228         char msg[(1 + 32 + keylen) * 2 + 1];
229
230         msg[0] = !s->initiator;
231         memcpy(msg + 1, s->hiskex, 1 + 32 + keylen);
232         memcpy(msg + 2 + 32 + keylen, s->mykex, 1 + 32 + keylen);
233
234         // Verify signature.
235         if(!ecdsa_verify(&s->hiskey, msg, sizeof msg, data))
236                 return false;
237
238         // Compute shared secret.
239         char shared[ECDH_SHARED_SIZE];
240         if(!ecdh_compute_shared(&s->ecdh, s->hiskex + 1 + 32, shared))
241                 return false;
242
243         // Generate key material from shared secret.
244         if(!generate_key_material(s, shared, sizeof shared))
245                 return false;
246
247         // Send cipher change record if necessary
248         //if(s->outstate && !send_ack(s))
249         //      return false;
250
251         // TODO: only set new keys after ACK has been set/received
252         if(s->initiator) {
253                 bool result
254                         =  cipher_set_key(&s->incipher, s->key, false)
255                         && digest_set_key(&s->indigest, s->key + cipher_keylength(&s->incipher), digest_keylength(&s->indigest))
256                         && cipher_set_key(&s->outcipher, s->key + cipher_keylength(&s->incipher) + digest_keylength(&s->indigest), true)
257                         && digest_set_key(&s->outdigest, s->key + cipher_keylength(&s->incipher) + digest_keylength(&s->indigest) + cipher_keylength(&s->outcipher), digest_keylength(&s->outdigest));
258                 if(!result)
259                         return false;
260         } else {
261                 bool result
262                         =  cipher_set_key(&s->outcipher, s->key, true)
263                         && digest_set_key(&s->outdigest, s->key + cipher_keylength(&s->outcipher), digest_keylength(&s->outdigest))
264                         && cipher_set_key(&s->incipher, s->key + cipher_keylength(&s->outcipher) + digest_keylength(&s->outdigest), false)
265                         && digest_set_key(&s->indigest, s->key + cipher_keylength(&s->outcipher) + digest_keylength(&s->outdigest) + cipher_keylength(&s->incipher), digest_keylength(&s->indigest));
266                 if(!result)
267                         return false;
268         }
269
270         s->outstate = true;
271         s->instate = true;
272
273         return true;
274 }
275
276 // Force another Key EXchange (for testing purposes).
277 bool force_kex(sptps_t *s) {
278         if(!s->outstate || s->state != SPTPS_SECONDARY_KEX)
279                 return error(s, EINVAL, "Cannot force KEX in current state");
280
281         s->state = SPTPS_KEX;
282         return send_kex(s);
283 }
284
285 // Receive a handshake record.
286 static bool receive_handshake(sptps_t *s, const char *data, uint16_t len) {
287         // Only a few states to deal with handshaking.
288         fprintf(stderr, "Received handshake message, current state %d\n", s->state);
289         switch(s->state) {
290                 case SPTPS_SECONDARY_KEX:
291                         // We receive a secondary KEX request, first respond by sending our own.
292                         if(!send_kex(s))
293                                 return false;
294                 case SPTPS_KEX:
295                         // We have sent our KEX request, we expect our peer to sent one as well.
296                         if(!receive_kex(s, data, len))
297                                 return false;
298                         s->state = SPTPS_SIG;
299                         return true;
300                 case SPTPS_SIG:
301                         // If we already sent our secondary public ECDH key, we expect the peer to send his.
302                         if(!receive_sig(s, data, len))
303                                 return false;
304                         // s->state = SPTPS_ACK;
305                         s->state = SPTPS_SECONDARY_KEX;
306                         return true;
307                 case SPTPS_ACK:
308                         // We expect a handshake message to indicate transition to the new keys.
309                         if(!receive_ack(s, data, len))
310                                 return false;
311                         s->state = SPTPS_SECONDARY_KEX;
312                         return true;
313                 // TODO: split ACK into a VERify and ACK?
314                 default:
315                         return error(s, EIO, "Invalid session state");
316         }
317 }
318
319 // Receive incoming data. Check if it contains a complete record, if so, handle it.
320 bool receive_data(sptps_t *s, const char *data, size_t len) {
321         while(len) {
322                 // First read the 2 length bytes.
323                 if(s->buflen < 6) {
324                         size_t toread = 6 - s->buflen;
325                         if(toread > len)
326                                 toread = len;
327
328                         if(s->instate) {
329                                 if(!cipher_decrypt(&s->incipher, data, toread, s->inbuf + s->buflen, NULL, false))
330                                         return false;
331                         } else {
332                                 memcpy(s->inbuf + s->buflen, data, toread);
333                         }
334
335                         s->buflen += toread;
336                         len -= toread;
337                         data += toread;
338
339                         // Exit early if we don't have the full length.
340                         if(s->buflen < 6)
341                                 return true;
342
343                         // If we have the length bytes, ensure our buffer can hold the whole request.
344                         uint16_t reclen;
345                         memcpy(&reclen, s->inbuf + 4, 2);
346                         reclen = htons(reclen);
347                         s->inbuf = realloc(s->inbuf, reclen + 23UL);
348                         if(!s->inbuf)
349                                 return error(s, errno, strerror(errno));
350
351                         // Add sequence number.
352                         uint32_t seqno = htonl(s->inseqno++);
353                         memcpy(s->inbuf, &seqno, 4);
354
355                         // Exit early if we have no more data to process.
356                         if(!len)
357                                 return true;
358                 }
359
360                 // Read up to the end of the record.
361                 uint16_t reclen;
362                 memcpy(&reclen, s->inbuf + 4, 2);
363                 reclen = htons(reclen);
364                 size_t toread = reclen + (s->instate ? 23UL : 7UL) - s->buflen;
365                 if(toread > len)
366                         toread = len;
367
368                 if(s->instate) {
369                         if(!cipher_decrypt(&s->incipher, data, toread, s->inbuf + s->buflen, NULL, false))
370                                 return false;
371                 } else {
372                         memcpy(s->inbuf + s->buflen, data, toread);
373                 }
374
375                 s->buflen += toread;
376                 len -= toread;
377                 data += toread;
378
379                 // If we don't have a whole record, exit.
380                 if(s->buflen < reclen + (s->instate ? 23UL : 7UL))
381                         return true;
382
383                 // Check HMAC.
384                 if(s->instate)
385                         if(!digest_verify(&s->indigest, s->inbuf, reclen + 7UL, s->inbuf + reclen + 7UL))
386                                 error(s, EIO, "Invalid HMAC");
387
388                 uint8_t type = s->inbuf[6];
389
390                 // Handle record.
391                 if(type < SPTPS_HANDSHAKE) {
392                         if(!s->receive_record(s->handle, type, s->inbuf + 7, reclen))
393                                 return false;
394                 } else if(type == SPTPS_HANDSHAKE) {
395                         if(!receive_handshake(s, s->inbuf + 7, reclen))
396                                 return false;
397                 } else {
398                         return error(s, EIO, "Invalid record type");
399                 }
400
401                 s->buflen = 4;
402         }
403
404         return true;
405 }
406
407 // Start a SPTPS session.
408 bool start_sptps(sptps_t *s, void *handle, bool initiator, ecdsa_t mykey, ecdsa_t hiskey, const char *label, size_t labellen, send_data_t send_data, receive_record_t receive_record) {
409         // Initialise struct sptps
410         memset(s, 0, sizeof *s);
411
412         s->handle = handle;
413         s->initiator = initiator;
414         s->mykey = mykey;
415         s->hiskey = hiskey;
416
417         s->label = malloc(labellen);
418         if(!s->label)
419                 return error(s, errno, strerror(errno));
420
421         s->inbuf = malloc(7);
422         if(!s->inbuf)
423                 return error(s, errno, strerror(errno));
424         s->buflen = 4;
425         memset(s->inbuf, 0, 4);
426
427         memcpy(s->label, label, labellen);
428         s->labellen = labellen;
429
430         s->send_data = send_data;
431         s->receive_record = receive_record;
432
433         // Do first KEX immediately
434         s->state = SPTPS_KEX;
435         return send_kex(s);
436 }
437
438 // Stop a SPTPS session.
439 bool stop_sptps(sptps_t *s) {
440         // Clean up any resources.
441         ecdh_free(&s->ecdh);
442         free(s->inbuf);
443         free(s->mykex);
444         free(s->hiskex);
445         free(s->key);
446         free(s->label);
447         return true;
448 }