Don't assume sa.sa_family is a short int.
[tinc] / src / sptps.c
1 /*
2     sptps.c -- Simple Peer-to-Peer Security
3     Copyright (C) 2011-2015 Guus Sliepen <guus@tinc-vpn.org>,
4                   2010      Brandon L. Black <blblack@gmail.com>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License along
17     with this program; if not, write to the Free Software Foundation, Inc.,
18     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "system.h"
22
23 #include "chacha-poly1305/chacha-poly1305.h"
24 #include "crypto.h"
25 #include "ecdh.h"
26 #include "ecdsa.h"
27 #include "logger.h"
28 #include "prf.h"
29 #include "sptps.h"
30
31 unsigned int sptps_replaywin = 16;
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 Ed25519 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 void sptps_log_quiet(sptps_t *s, int s_errno, const char *format, va_list ap) {
54 }
55
56 void sptps_log_stderr(sptps_t *s, int s_errno, const char *format, va_list ap) {
57         vfprintf(stderr, format, ap);
58         fputc('\n', stderr);
59 }
60
61 void (*sptps_log)(sptps_t *s, int s_errno, const char *format, va_list ap) = sptps_log_stderr;
62
63 // Log an error message.
64 static bool error(sptps_t *s, int s_errno, const char *format, ...) {
65         if(format) {
66                 va_list ap;
67                 va_start(ap, format);
68                 sptps_log(s, s_errno, format, ap);
69                 va_end(ap);
70         }
71
72         errno = s_errno;
73         return false;
74 }
75
76 static void warning(sptps_t *s, const char *format, ...) {
77         va_list ap;
78         va_start(ap, format);
79         sptps_log(s, 0, format, ap);
80         va_end(ap);
81 }
82
83 // Send a record (datagram version, accepts all record types, handles encryption and authentication).
84 static bool send_record_priv_datagram(sptps_t *s, uint8_t type, const void *data, uint16_t len) {
85         char buffer[len + 21UL];
86
87         // Create header with sequence number, length and record type
88         uint32_t seqno = s->outseqno++;
89         uint32_t netseqno = ntohl(seqno);
90
91         memcpy(buffer, &netseqno, 4);
92         buffer[4] = type;
93         memcpy(buffer + 5, data, len);
94
95         if(s->outstate) {
96                 // If first handshake has finished, encrypt and HMAC
97                 chacha_poly1305_encrypt(s->outcipher, seqno, buffer + 4, len + 1, buffer + 4, NULL);
98                 return s->send_data(s->handle, type, buffer, len + 21UL);
99         } else {
100                 // Otherwise send as plaintext
101                 return s->send_data(s->handle, type, buffer, len + 5UL);
102         }
103 }
104 // Send a record (private version, accepts all record types, handles encryption and authentication).
105 static bool send_record_priv(sptps_t *s, uint8_t type, const void *data, uint16_t len) {
106         if(s->datagram)
107                 return send_record_priv_datagram(s, type, data, len);
108
109         char buffer[len + 19UL];
110
111         // Create header with sequence number, length and record type
112         uint32_t seqno = s->outseqno++;
113         uint16_t netlen = htons(len);
114
115         memcpy(buffer, &netlen, 2);
116         buffer[2] = type;
117         memcpy(buffer + 3, data, len);
118
119         if(s->outstate) {
120                 // If first handshake has finished, encrypt and HMAC
121                 chacha_poly1305_encrypt(s->outcipher, seqno, buffer + 2, len + 1, buffer + 2, NULL);
122                 return s->send_data(s->handle, type, buffer, len + 19UL);
123         } else {
124                 // Otherwise send as plaintext
125                 return s->send_data(s->handle, type, buffer, len + 3UL);
126         }
127 }
128
129 // Send an application record.
130 bool sptps_send_record(sptps_t *s, uint8_t type, const void *data, uint16_t len) {
131         // Sanity checks: application cannot send data before handshake is finished,
132         // and only record types 0..127 are allowed.
133         if(!s->outstate)
134                 return error(s, EINVAL, "Handshake phase not finished yet");
135
136         if(type >= SPTPS_HANDSHAKE)
137                 return error(s, EINVAL, "Invalid application record type");
138
139         return send_record_priv(s, type, data, len);
140 }
141
142 // Send a Key EXchange record, containing a random nonce and an ECDHE public key.
143 static bool send_kex(sptps_t *s) {
144         size_t keylen = ECDH_SIZE;
145
146         // Make room for our KEX message, which we will keep around since send_sig() needs it.
147         if(s->mykex)
148                 return false;
149         s->mykex = realloc(s->mykex, 1 + 32 + keylen);
150         if(!s->mykex)
151                 return error(s, errno, strerror(errno));
152
153         // Set version byte to zero.
154         s->mykex[0] = SPTPS_VERSION;
155
156         // Create a random nonce.
157         randomize(s->mykex + 1, 32);
158
159         // Create a new ECDH public key.
160         if(!(s->ecdh = ecdh_generate_public(s->mykex + 1 + 32)))
161                 return error(s, EINVAL, "Failed to generate ECDH public key");
162
163         return send_record_priv(s, SPTPS_HANDSHAKE, s->mykex, 1 + 32 + keylen);
164 }
165
166 // Send a SIGnature record, containing an Ed25519 signature over both KEX records.
167 static bool send_sig(sptps_t *s) {
168         size_t keylen = ECDH_SIZE;
169         size_t siglen = ecdsa_size(s->mykey);
170
171         // Concatenate both KEX messages, plus tag indicating if it is from the connection originator, plus label
172         char msg[(1 + 32 + keylen) * 2 + 1 + s->labellen];
173         char sig[siglen];
174
175         msg[0] = s->initiator;
176         memcpy(msg + 1, s->mykex, 1 + 32 + keylen);
177         memcpy(msg + 1 + 33 + keylen, s->hiskex, 1 + 32 + keylen);
178         memcpy(msg + 1 + 2 * (33 + keylen), s->label, s->labellen);
179
180         // Sign the result.
181         if(!ecdsa_sign(s->mykey, msg, sizeof msg, sig))
182                 return error(s, EINVAL, "Failed to sign SIG record");
183
184         // Send the SIG exchange record.
185         return send_record_priv(s, SPTPS_HANDSHAKE, sig, sizeof sig);
186 }
187
188 // Generate key material from the shared secret created from the ECDHE key exchange.
189 static bool generate_key_material(sptps_t *s, const char *shared, size_t len) {
190         // Initialise cipher and digest structures if necessary
191         if(!s->outstate) {
192                 s->incipher = chacha_poly1305_init();
193                 s->outcipher = chacha_poly1305_init();
194                 if(!s->incipher || !s->outcipher)
195                         return error(s, EINVAL, "Failed to open cipher");
196         }
197
198         // Allocate memory for key material
199         size_t keylen = 2 * CHACHA_POLY1305_KEYLEN;
200
201         s->key = realloc(s->key, keylen);
202         if(!s->key)
203                 return error(s, errno, strerror(errno));
204
205         // Create the HMAC seed, which is "key expansion" + session label + server nonce + client nonce
206         char seed[s->labellen + 64 + 13];
207         strcpy(seed, "key expansion");
208         if(s->initiator) {
209                 memcpy(seed + 13, s->mykex + 1, 32);
210                 memcpy(seed + 45, s->hiskex + 1, 32);
211         } else {
212                 memcpy(seed + 13, s->hiskex + 1, 32);
213                 memcpy(seed + 45, s->mykex + 1, 32);
214         }
215         memcpy(seed + 77, s->label, s->labellen);
216
217         // Use PRF to generate the key material
218         if(!prf(shared, len, seed, s->labellen + 64 + 13, s->key, keylen))
219                 return error(s, EINVAL, "Failed to generate key material");
220
221         return true;
222 }
223
224 // Send an ACKnowledgement record.
225 static bool send_ack(sptps_t *s) {
226         return send_record_priv(s, SPTPS_HANDSHAKE, "", 0);
227 }
228
229 // Receive an ACKnowledgement record.
230 static bool receive_ack(sptps_t *s, const char *data, uint16_t len) {
231         if(len)
232                 return error(s, EIO, "Invalid ACK record length");
233
234         if(s->initiator) {
235                 if(!chacha_poly1305_set_key(s->incipher, s->key))
236                         return error(s, EINVAL, "Failed to set counter");
237         } else {
238                 if(!chacha_poly1305_set_key(s->incipher, s->key + CHACHA_POLY1305_KEYLEN))
239                         return error(s, EINVAL, "Failed to set counter");
240         }
241
242         free(s->key);
243         s->key = NULL;
244         s->instate = true;
245
246         return true;
247 }
248
249 // Receive a Key EXchange record, respond by sending a SIG record.
250 static bool receive_kex(sptps_t *s, const char *data, uint16_t len) {
251         // Verify length of the HELLO record
252         if(len != 1 + 32 + ECDH_SIZE)
253                 return error(s, EIO, "Invalid KEX record length");
254
255         // Ignore version number for now.
256
257         // Make a copy of the KEX message, send_sig() and receive_sig() need it
258         if(s->hiskex)
259                 return error(s, EINVAL, "Received a second KEX message before first has been processed");
260         s->hiskex = realloc(s->hiskex, len);
261         if(!s->hiskex)
262                 return error(s, errno, strerror(errno));
263
264         memcpy(s->hiskex, data, len);
265
266         return send_sig(s);
267 }
268
269 // Receive a SIGnature record, verify it, if it passed, compute the shared secret and calculate the session keys.
270 static bool receive_sig(sptps_t *s, const char *data, uint16_t len) {
271         size_t keylen = ECDH_SIZE;
272         size_t siglen = ecdsa_size(s->hiskey);
273
274         // Verify length of KEX record.
275         if(len != siglen)
276                 return error(s, EIO, "Invalid KEX record length");
277
278         // Concatenate both KEX messages, plus tag indicating if it is from the connection originator
279         char msg[(1 + 32 + keylen) * 2 + 1 + s->labellen];
280
281         msg[0] = !s->initiator;
282         memcpy(msg + 1, s->hiskex, 1 + 32 + keylen);
283         memcpy(msg + 1 + 33 + keylen, s->mykex, 1 + 32 + keylen);
284         memcpy(msg + 1 + 2 * (33 + keylen), s->label, s->labellen);
285
286         // Verify signature.
287         if(!ecdsa_verify(s->hiskey, msg, sizeof msg, data))
288                 return error(s, EIO, "Failed to verify SIG record");
289
290         // Compute shared secret.
291         char shared[ECDH_SHARED_SIZE];
292         if(!ecdh_compute_shared(s->ecdh, s->hiskex + 1 + 32, shared))
293                 return error(s, EINVAL, "Failed to compute ECDH shared secret");
294         s->ecdh = NULL;
295
296         // Generate key material from shared secret.
297         if(!generate_key_material(s, shared, sizeof shared))
298                 return false;
299
300         free(s->mykex);
301         free(s->hiskex);
302
303         s->mykex = NULL;
304         s->hiskex = NULL;
305
306         // Send cipher change record
307         if(s->outstate && !send_ack(s))
308                 return false;
309
310         // TODO: only set new keys after ACK has been set/received
311         if(s->initiator) {
312                 if(!chacha_poly1305_set_key(s->outcipher, s->key + CHACHA_POLY1305_KEYLEN))
313                         return error(s, EINVAL, "Failed to set key");
314         } else {
315                 if(!chacha_poly1305_set_key(s->outcipher, s->key))
316                         return error(s, EINVAL, "Failed to set key");
317         }
318
319         return true;
320 }
321
322 // Force another Key EXchange (for testing purposes).
323 bool sptps_force_kex(sptps_t *s) {
324         if(!s->outstate || s->state != SPTPS_SECONDARY_KEX)
325                 return error(s, EINVAL, "Cannot force KEX in current state");
326
327         s->state = SPTPS_KEX;
328         return send_kex(s);
329 }
330
331 // Receive a handshake record.
332 static bool receive_handshake(sptps_t *s, const char *data, uint16_t len) {
333         // Only a few states to deal with handshaking.
334         switch(s->state) {
335                 case SPTPS_SECONDARY_KEX:
336                         // We receive a secondary KEX request, first respond by sending our own.
337                         if(!send_kex(s))
338                                 return false;
339                 case SPTPS_KEX:
340                         // We have sent our KEX request, we expect our peer to sent one as well.
341                         if(!receive_kex(s, data, len))
342                                 return false;
343                         s->state = SPTPS_SIG;
344                         return true;
345                 case SPTPS_SIG:
346                         // If we already sent our secondary public ECDH key, we expect the peer to send his.
347                         if(!receive_sig(s, data, len))
348                                 return false;
349                         if(s->outstate)
350                                 s->state = SPTPS_ACK;
351                         else {
352                                 s->outstate = true;
353                                 if(!receive_ack(s, NULL, 0))
354                                         return false;
355                                 s->receive_record(s->handle, SPTPS_HANDSHAKE, NULL, 0);
356                                 s->state = SPTPS_SECONDARY_KEX;
357                         }
358
359                         return true;
360                 case SPTPS_ACK:
361                         // We expect a handshake message to indicate transition to the new keys.
362                         if(!receive_ack(s, data, len))
363                                 return false;
364                         s->receive_record(s->handle, SPTPS_HANDSHAKE, NULL, 0);
365                         s->state = SPTPS_SECONDARY_KEX;
366                         return true;
367                 // TODO: split ACK into a VERify and ACK?
368                 default:
369                         return error(s, EIO, "Invalid session state %d", s->state);
370         }
371 }
372
373 static bool sptps_check_seqno(sptps_t *s, uint32_t seqno, bool update_state) {
374         // Replay protection using a sliding window of configurable size.
375         // s->inseqno is expected sequence number
376         // seqno is received sequence number
377         // s->late[] is a circular buffer, a 1 bit means a packet has not been received yet
378         // The circular buffer contains bits for sequence numbers from s->inseqno - s->replaywin * 8 to (but excluding) s->inseqno.
379         if(s->replaywin) {
380                 if(seqno != s->inseqno) {
381                         if(seqno >= s->inseqno + s->replaywin * 8) {
382                                 // Prevent packets that jump far ahead of the queue from causing many others to be dropped.
383                                 bool farfuture = s->farfuture < s->replaywin >> 2;
384                                 if (update_state)
385                                         s->farfuture++;
386                                 if(farfuture)
387                                         return update_state ? error(s, EIO, "Packet is %d seqs in the future, dropped (%u)\n", seqno - s->inseqno, s->farfuture) : false;
388
389                                 // Unless we have seen lots of them, in which case we consider the others lost.
390                                 if(update_state)
391                                         warning(s, "Lost %d packets\n", seqno - s->inseqno);
392                                 if (update_state) {
393                                         // Mark all packets in the replay window as being late.
394                                         memset(s->late, 255, s->replaywin);
395                                 }
396                         } else if (seqno < s->inseqno) {
397                                 // If the sequence number is farther in the past than the bitmap goes, or if the packet was already received, drop it.
398                                 if((s->inseqno >= s->replaywin * 8 && seqno < s->inseqno - s->replaywin * 8) || !(s->late[(seqno / 8) % s->replaywin] & (1 << seqno % 8)))
399                                         return update_state ? error(s, EIO, "Received late or replayed packet, seqno %d, last received %d\n", seqno, s->inseqno) : false;
400                         } else if (update_state) {
401                                 // We missed some packets. Mark them in the bitmap as being late.
402                                 for(int i = s->inseqno; i < seqno; i++)
403                                         s->late[(i / 8) % s->replaywin] |= 1 << i % 8;
404                         }
405                 }
406
407                 if (update_state) {
408                         // Mark the current packet as not being late.
409                         s->late[(seqno / 8) % s->replaywin] &= ~(1 << seqno % 8);
410                         s->farfuture = 0;
411                 }
412         }
413
414         if (update_state) {
415                 if(seqno >= s->inseqno)
416                         s->inseqno = seqno + 1;
417
418                 if(!s->inseqno)
419                         s->received = 0;
420                 else
421                         s->received++;
422         }
423
424         return true;
425 }
426
427 // Check datagram for valid HMAC
428 bool sptps_verify_datagram(sptps_t *s, const void *data, size_t len) {
429         if(!s->instate || len < 21)
430                 return error(s, EIO, "Received short packet");
431
432         uint32_t seqno;
433         memcpy(&seqno, data, 4);
434         seqno = ntohl(seqno);
435         if (!sptps_check_seqno(s, seqno, false))
436                 return false;
437
438         char buffer[len];
439         size_t outlen;
440         return chacha_poly1305_decrypt(s->incipher, seqno, data + 4, len - 4, buffer, &outlen);
441 }
442
443 // Receive incoming data, datagram version.
444 static bool sptps_receive_data_datagram(sptps_t *s, const char *data, size_t len) {
445         if(len < (s->instate ? 21 : 5))
446                 return error(s, EIO, "Received short packet");
447
448         uint32_t seqno;
449         memcpy(&seqno, data, 4);
450         seqno = ntohl(seqno);
451         data += 4; len -= 4;
452
453         if(!s->instate) {
454                 if(seqno != s->inseqno)
455                         return error(s, EIO, "Invalid packet seqno: %d != %d", seqno, s->inseqno);
456
457                 s->inseqno = seqno + 1;
458
459                 uint8_t type = *(data++); len--;
460
461                 if(type != SPTPS_HANDSHAKE)
462                         return error(s, EIO, "Application record received before handshake finished");
463
464                 return receive_handshake(s, data, len);
465         }
466
467         // Decrypt
468
469         char buffer[len];
470         size_t outlen;
471         if(!chacha_poly1305_decrypt(s->incipher, seqno, data, len, buffer, &outlen))
472                 return error(s, EIO, "Failed to decrypt and verify packet");
473
474         if(!sptps_check_seqno(s, seqno, true))
475                 return false;
476
477         // Append a NULL byte for safety.
478         buffer[outlen] = 0;
479
480         data = buffer;
481         len = outlen;
482
483         uint8_t type = *(data++); len--;
484
485         if(type < SPTPS_HANDSHAKE) {
486                 if(!s->instate)
487                         return error(s, EIO, "Application record received before handshake finished");
488                 if(!s->receive_record(s->handle, type, data, len))
489                         return false;
490         } else if(type == SPTPS_HANDSHAKE) {
491                 if(!receive_handshake(s, data, len))
492                         return false;
493         } else {
494                 return error(s, EIO, "Invalid record type %d", type);
495         }
496
497         return true;
498 }
499
500 // Receive incoming data. Check if it contains a complete record, if so, handle it.
501 size_t sptps_receive_data(sptps_t *s, const void *data, size_t len) {
502         size_t total_read = 0;
503
504         if(!s->state)
505                 return error(s, EIO, "Invalid session state zero");
506
507         if(s->datagram)
508                 return sptps_receive_data_datagram(s, data, len) ? len : false;
509
510         // First read the 2 length bytes.
511         if(s->buflen < 2) {
512                 size_t toread = 2 - s->buflen;
513                 if(toread > len)
514                         toread = len;
515
516                 memcpy(s->inbuf + s->buflen, data, toread);
517
518                 total_read += toread;
519                 s->buflen += toread;
520                 len -= toread;
521                 data += toread;
522
523                 // Exit early if we don't have the full length.
524                 if(s->buflen < 2)
525                         return total_read;
526
527                 // Get the length bytes
528
529                 memcpy(&s->reclen, s->inbuf, 2);
530                 s->reclen = ntohs(s->reclen);
531
532                 // If we have the length bytes, ensure our buffer can hold the whole request.
533                 s->inbuf = realloc(s->inbuf, s->reclen + 19UL);
534                 if(!s->inbuf)
535                         return error(s, errno, strerror(errno));
536
537                 // Exit early if we have no more data to process.
538                 if(!len)
539                         return total_read;
540         }
541
542         // Read up to the end of the record.
543         size_t toread = s->reclen + (s->instate ? 19UL : 3UL) - s->buflen;
544         if(toread > len)
545                 toread = len;
546
547         memcpy(s->inbuf + s->buflen, data, toread);
548         total_read += toread;
549         s->buflen += toread;
550         len -= toread;
551         data += toread;
552
553         // If we don't have a whole record, exit.
554         if(s->buflen < s->reclen + (s->instate ? 19UL : 3UL))
555                 return total_read;
556
557         // Update sequence number.
558
559         uint32_t seqno = s->inseqno++;
560
561         // Check HMAC and decrypt.
562         if(s->instate) {
563                 if(!chacha_poly1305_decrypt(s->incipher, seqno, s->inbuf + 2UL, s->reclen + 17UL, s->inbuf + 2UL, NULL))
564                         return error(s, EINVAL, "Failed to decrypt and verify record");
565         }
566
567         // Append a NULL byte for safety.
568         s->inbuf[s->reclen + 3UL] = 0;
569
570         uint8_t type = s->inbuf[2];
571
572         if(type < SPTPS_HANDSHAKE) {
573                 if(!s->instate)
574                         return error(s, EIO, "Application record received before handshake finished");
575                 if(!s->receive_record(s->handle, type, s->inbuf + 3, s->reclen))
576                         return false;
577         } else if(type == SPTPS_HANDSHAKE) {
578                 if(!receive_handshake(s, s->inbuf + 3, s->reclen))
579                         return false;
580         } else {
581                 return error(s, EIO, "Invalid record type %d", type);
582         }
583
584         s->buflen = 0;
585
586         return total_read;
587 }
588
589 // Start a SPTPS session.
590 bool sptps_start(sptps_t *s, void *handle, bool initiator, bool datagram, ecdsa_t *mykey, ecdsa_t *hiskey, const void *label, size_t labellen, send_data_t send_data, receive_record_t receive_record) {
591         // Initialise struct sptps
592         memset(s, 0, sizeof *s);
593
594         s->handle = handle;
595         s->initiator = initiator;
596         s->datagram = datagram;
597         s->mykey = mykey;
598         s->hiskey = hiskey;
599         s->replaywin = sptps_replaywin;
600         if(s->replaywin) {
601                 s->late = malloc(s->replaywin);
602                 if(!s->late)
603                         return error(s, errno, strerror(errno));
604                 memset(s->late, 0, s->replaywin);
605         }
606
607         s->label = malloc(labellen);
608         if(!s->label)
609                 return error(s, errno, strerror(errno));
610
611         if(!datagram) {
612                 s->inbuf = malloc(7);
613                 if(!s->inbuf)
614                         return error(s, errno, strerror(errno));
615                 s->buflen = 0;
616         }
617
618         memcpy(s->label, label, labellen);
619         s->labellen = labellen;
620
621         s->send_data = send_data;
622         s->receive_record = receive_record;
623
624         // Do first KEX immediately
625         s->state = SPTPS_KEX;
626         return send_kex(s);
627 }
628
629 // Stop a SPTPS session.
630 bool sptps_stop(sptps_t *s) {
631         // Clean up any resources.
632         chacha_poly1305_exit(s->incipher);
633         chacha_poly1305_exit(s->outcipher);
634         ecdh_free(s->ecdh);
635         free(s->inbuf);
636         free(s->mykex);
637         free(s->hiskex);
638         free(s->key);
639         free(s->label);
640         free(s->late);
641         memset(s, 0, sizeof *s);
642         return true;
643 }