Exchange ACK records to indicate switch to new keys.
[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. (done)
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_counter_xor(&s->outcipher, plaintext + 4, sizeof ciphertext, ciphertext))
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-ecb")
153                         && cipher_open_by_name(&s->outcipher, "aes-256-ecb")
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 error(s, EIO, "Invalid ACK record length");
195
196         if(s->initiator) {
197                 bool result
198                         = cipher_set_counter_key(&s->incipher, s->key)
199                         && digest_set_key(&s->indigest, s->key + cipher_keylength(&s->incipher), digest_keylength(&s->indigest));
200                 if(!result)
201                         return false;
202         } else {
203                 bool result
204                         = cipher_set_counter_key(&s->incipher, s->key + cipher_keylength(&s->outcipher) + digest_keylength(&s->outdigest))
205                         && digest_set_key(&s->indigest, s->key + cipher_keylength(&s->outcipher) + digest_keylength(&s->outdigest) + cipher_keylength(&s->incipher), digest_keylength(&s->indigest));
206                 if(!result)
207                         return false;
208         }
209
210         free(s->key);
211         s->key = NULL;
212         s->instate = true;
213
214         return true;
215 }
216
217 // Receive a Key EXchange record, respond by sending a SIG record.
218 static bool receive_kex(sptps_t *s, const char *data, uint16_t len) {
219         // Verify length of the HELLO record
220         if(len != 1 + 32 + ECDH_SIZE)
221                 return error(s, EIO, "Invalid KEX record length");
222
223         // Ignore version number for now.
224
225         // Make a copy of the KEX message, send_sig() and receive_sig() need it
226         s->hiskex = realloc(s->hiskex, len);
227         if(!s->hiskex)
228                 return error(s, errno, strerror(errno));
229
230         memcpy(s->hiskex, data, len);
231
232         return send_sig(s);
233 }
234
235 // Receive a SIGnature record, verify it, if it passed, compute the shared secret and calculate the session keys.
236 static bool receive_sig(sptps_t *s, const char *data, uint16_t len) {
237         size_t keylen = ECDH_SIZE;
238         size_t siglen = ecdsa_size(&s->hiskey);
239
240         // Verify length of KEX record.
241         if(len != siglen)
242                 return error(s, EIO, "Invalid KEX record length");
243
244         // Concatenate both KEX messages, plus tag indicating if it is from the connection originator
245         char msg[(1 + 32 + keylen) * 2 + 1];
246
247         msg[0] = !s->initiator;
248         memcpy(msg + 1, s->hiskex, 1 + 32 + keylen);
249         memcpy(msg + 2 + 32 + keylen, s->mykex, 1 + 32 + keylen);
250
251         // Verify signature.
252         if(!ecdsa_verify(&s->hiskey, msg, sizeof msg, data))
253                 return false;
254
255         // Compute shared secret.
256         char shared[ECDH_SHARED_SIZE];
257         if(!ecdh_compute_shared(&s->ecdh, s->hiskex + 1 + 32, shared))
258                 return false;
259
260         // Generate key material from shared secret.
261         if(!generate_key_material(s, shared, sizeof shared))
262                 return false;
263
264         free(s->mykex);
265         free(s->hiskex);
266
267         s->mykex = NULL;
268         s->hiskex = NULL;
269
270         // Send cipher change record
271         if(!send_ack(s))
272                 return false;
273
274         // TODO: only set new keys after ACK has been set/received
275         if(s->initiator) {
276                 bool result
277                         = cipher_set_counter_key(&s->outcipher, s->key + cipher_keylength(&s->incipher) + digest_keylength(&s->indigest))
278                         && digest_set_key(&s->outdigest, s->key + cipher_keylength(&s->incipher) + digest_keylength(&s->indigest) + cipher_keylength(&s->outcipher), digest_keylength(&s->outdigest));
279                 if(!result)
280                         return false;
281         } else {
282                 bool result
283                         =  cipher_set_counter_key(&s->outcipher, s->key)
284                         && digest_set_key(&s->outdigest, s->key + cipher_keylength(&s->outcipher), digest_keylength(&s->outdigest));
285                 if(!result)
286                         return false;
287         }
288
289         s->outstate = true;
290
291         return true;
292 }
293
294 // Force another Key EXchange (for testing purposes).
295 bool force_kex(sptps_t *s) {
296         if(!s->outstate || s->state != SPTPS_SECONDARY_KEX)
297                 return error(s, EINVAL, "Cannot force KEX in current state");
298
299         s->state = SPTPS_KEX;
300         return send_kex(s);
301 }
302
303 // Receive a handshake record.
304 static bool receive_handshake(sptps_t *s, const char *data, uint16_t len) {
305         // Only a few states to deal with handshaking.
306         fprintf(stderr, "Received handshake message, current state %d\n", s->state);
307         switch(s->state) {
308                 case SPTPS_SECONDARY_KEX:
309                         // We receive a secondary KEX request, first respond by sending our own.
310                         if(!send_kex(s))
311                                 return false;
312                 case SPTPS_KEX:
313                         // We have sent our KEX request, we expect our peer to sent one as well.
314                         if(!receive_kex(s, data, len))
315                                 return false;
316                         s->state = SPTPS_SIG;
317                         return true;
318                 case SPTPS_SIG:
319                         // If we already sent our secondary public ECDH key, we expect the peer to send his.
320                         if(!receive_sig(s, data, len))
321                                 return false;
322                         // s->state = SPTPS_ACK;
323                         s->state = SPTPS_ACK;
324                         return true;
325                 case SPTPS_ACK:
326                         // We expect a handshake message to indicate transition to the new keys.
327                         if(!receive_ack(s, data, len))
328                                 return false;
329                         s->state = SPTPS_SECONDARY_KEX;
330                         return true;
331                 // TODO: split ACK into a VERify and ACK?
332                 default:
333                         return error(s, EIO, "Invalid session state");
334         }
335 }
336
337 // Receive incoming data. Check if it contains a complete record, if so, handle it.
338 bool receive_data(sptps_t *s, const char *data, size_t len) {
339         while(len) {
340                 // First read the 2 length bytes.
341                 if(s->buflen < 6) {
342                         size_t toread = 6 - s->buflen;
343                         if(toread > len)
344                                 toread = len;
345
346                         if(s->instate) {
347                                 if(!cipher_counter_xor(&s->incipher, data, toread, s->inbuf + s->buflen))
348                                         return false;
349                         } else {
350                                 memcpy(s->inbuf + s->buflen, data, toread);
351                         }
352
353                         s->buflen += toread;
354                         len -= toread;
355                         data += toread;
356
357                         // Exit early if we don't have the full length.
358                         if(s->buflen < 6)
359                                 return true;
360
361                         // If we have the length bytes, ensure our buffer can hold the whole request.
362                         uint16_t reclen;
363                         memcpy(&reclen, s->inbuf + 4, 2);
364                         reclen = htons(reclen);
365                         s->inbuf = realloc(s->inbuf, reclen + 23UL);
366                         if(!s->inbuf)
367                                 return error(s, errno, strerror(errno));
368
369                         // Add sequence number.
370                         uint32_t seqno = htonl(s->inseqno++);
371                         memcpy(s->inbuf, &seqno, 4);
372
373                         // Exit early if we have no more data to process.
374                         if(!len)
375                                 return true;
376                 }
377
378                 // Read up to the end of the record.
379                 uint16_t reclen;
380                 memcpy(&reclen, s->inbuf + 4, 2);
381                 reclen = htons(reclen);
382                 size_t toread = reclen + (s->instate ? 23UL : 7UL) - s->buflen;
383                 if(toread > len)
384                         toread = len;
385
386                 if(s->instate) {
387                         if(!cipher_counter_xor(&s->incipher, data, toread, s->inbuf + s->buflen))
388                                 return false;
389                 } else {
390                         memcpy(s->inbuf + s->buflen, data, toread);
391                 }
392
393                 s->buflen += toread;
394                 len -= toread;
395                 data += toread;
396
397                 // If we don't have a whole record, exit.
398                 if(s->buflen < reclen + (s->instate ? 23UL : 7UL))
399                         return true;
400
401                 // Check HMAC.
402                 if(s->instate)
403                         if(!digest_verify(&s->indigest, s->inbuf, reclen + 7UL, s->inbuf + reclen + 7UL))
404                                 error(s, EIO, "Invalid HMAC");
405
406                 uint8_t type = s->inbuf[6];
407
408                 // Handle record.
409                 if(type < SPTPS_HANDSHAKE) {
410                         if(!s->instate)
411                                 return error(s, EIO, "Application record received before handshake finished");
412                         if(!s->receive_record(s->handle, type, s->inbuf + 7, reclen))
413                                 return false;
414                 } else if(type == SPTPS_HANDSHAKE) {
415                         if(!receive_handshake(s, s->inbuf + 7, reclen))
416                                 return false;
417                 } else {
418                         return error(s, EIO, "Invalid record type");
419                 }
420
421                 s->buflen = 4;
422         }
423
424         return true;
425 }
426
427 // Start a SPTPS session.
428 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) {
429         // Initialise struct sptps
430         memset(s, 0, sizeof *s);
431
432         s->handle = handle;
433         s->initiator = initiator;
434         s->mykey = mykey;
435         s->hiskey = hiskey;
436
437         s->label = malloc(labellen);
438         if(!s->label)
439                 return error(s, errno, strerror(errno));
440
441         s->inbuf = malloc(7);
442         if(!s->inbuf)
443                 return error(s, errno, strerror(errno));
444         s->buflen = 4;
445         memset(s->inbuf, 0, 4);
446
447         memcpy(s->label, label, labellen);
448         s->labellen = labellen;
449
450         s->send_data = send_data;
451         s->receive_record = receive_record;
452
453         // Do first KEX immediately
454         s->state = SPTPS_KEX;
455         return send_kex(s);
456 }
457
458 // Stop a SPTPS session.
459 bool stop_sptps(sptps_t *s) {
460         // Clean up any resources.
461         ecdh_free(&s->ecdh);
462         free(s->inbuf);
463         free(s->mykex);
464         free(s->hiskex);
465         free(s->key);
466         free(s->label);
467         return true;
468 }