2 sptps.c -- Simple Peer-to-Peer Security
3 Copyright (C) 2014-2017 Guus Sliepen <guus@meshlink.io>
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.
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.
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.
22 #include "chacha-poly1305/chacha-poly1305.h"
30 unsigned int sptps_replaywin = 32;
33 Nonce MUST be exchanged first (done)
34 Signatures MUST be done over both nonces, to guarantee the signature is fresh
35 Otherwise: if ECDHE key of one side is compromised, it can be reused!
37 Add explicit tag to beginning of structure to distinguish the client and server when signing. (done)
39 Sign all handshake messages up to ECDHE kex with long-term public keys. (done)
41 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 Explicit close message needs to be added.
45 Maybe do add some alert messages to give helpful error messages? Not more than TLS sends.
47 Use counter mode instead of OFB. (done)
49 Make sure ECC operations are fixed time (aka prevent side-channel attacks).
52 void sptps_log_quiet(sptps_t *s, int s_errno, const char *format, va_list ap) {
59 void sptps_log_stderr(sptps_t *s, int s_errno, const char *format, va_list ap) {
62 vfprintf(stderr, format, ap);
66 void (*sptps_log)(sptps_t *s, int s_errno, const char *format, va_list ap) = sptps_log_quiet;
68 // Log an error message.
69 static bool error(sptps_t *s, int s_errno, const char *format, ...) {
73 sptps_log(s, s_errno, format, ap);
81 static void warning(sptps_t *s, const char *format, ...) {
84 sptps_log(s, 0, format, ap);
88 // Send a record (datagram version, accepts all record types, handles encryption and authentication).
89 static bool send_record_priv_datagram(sptps_t *s, uint8_t type, const void *data, uint16_t len) {
90 char buffer[len + 21UL];
92 // Create header with sequence number, length and record type
93 uint32_t seqno = s->outseqno++;
94 uint32_t netseqno = ntohl(seqno);
96 memcpy(buffer, &netseqno, 4);
98 memcpy(buffer + 5, data, len);
101 // If first handshake has finished, encrypt and HMAC
102 chacha_poly1305_encrypt(s->outcipher, seqno, buffer + 4, len + 1, buffer + 4, NULL);
103 return s->send_data(s->handle, type, buffer, len + 21UL);
105 // Otherwise send as plaintext
106 return s->send_data(s->handle, type, buffer, len + 5UL);
109 // Send a record (private version, accepts all record types, handles encryption and authentication).
110 static bool send_record_priv(sptps_t *s, uint8_t type, const void *data, uint16_t len) {
112 return send_record_priv_datagram(s, type, data, len);
115 char buffer[len + 19UL];
117 // Create header with sequence number, length and record type
118 uint32_t seqno = s->outseqno++;
119 uint16_t netlen = htons(len);
121 memcpy(buffer, &netlen, 2);
123 memcpy(buffer + 3, data, len);
126 // If first handshake has finished, encrypt and HMAC
127 chacha_poly1305_encrypt(s->outcipher, seqno, buffer + 2, len + 1, buffer + 2, NULL);
128 return s->send_data(s->handle, type, buffer, len + 19UL);
130 // Otherwise send as plaintext
131 return s->send_data(s->handle, type, buffer, len + 3UL);
135 // Send an application record.
136 bool sptps_send_record(sptps_t *s, uint8_t type, const void *data, uint16_t len) {
137 // Sanity checks: application cannot send data before handshake is finished,
138 // and only record types 0..127 are allowed.
140 return error(s, EINVAL, "Handshake phase not finished yet");
143 if(type >= SPTPS_HANDSHAKE) {
144 return error(s, EINVAL, "Invalid application record type");
147 return send_record_priv(s, type, data, len);
150 // Send a Key EXchange record, containing a random nonce and an ECDHE public key.
151 static bool send_kex(sptps_t *s) {
152 size_t keylen = ECDH_SIZE;
154 // Make room for our KEX message, which we will keep around since send_sig() needs it.
159 s->mykex = realloc(s->mykex, 1 + 32 + keylen);
162 return error(s, errno, strerror(errno));
165 // Set version byte to zero.
166 s->mykex[0] = SPTPS_VERSION;
168 // Create a random nonce.
169 randomize(s->mykex + 1, 32);
171 // Create a new ECDH public key.
172 if(!(s->ecdh = ecdh_generate_public(s->mykex + 1 + 32))) {
173 return error(s, EINVAL, "Failed to generate ECDH public key");
176 return send_record_priv(s, SPTPS_HANDSHAKE, s->mykex, 1 + 32 + keylen);
179 // Send a SIGnature record, containing an ECDSA signature over both KEX records.
180 static bool send_sig(sptps_t *s) {
181 size_t keylen = ECDH_SIZE;
182 size_t siglen = ecdsa_size(s->mykey);
184 // Concatenate both KEX messages, plus tag indicating if it is from the connection originator, plus label
185 char msg[(1 + 32 + keylen) * 2 + 1 + s->labellen];
188 msg[0] = s->initiator;
189 memcpy(msg + 1, s->mykex, 1 + 32 + keylen);
190 memcpy(msg + 1 + 33 + keylen, s->hiskex, 1 + 32 + keylen);
191 memcpy(msg + 1 + 2 * (33 + keylen), s->label, s->labellen);
194 if(!ecdsa_sign(s->mykey, msg, sizeof(msg), sig)) {
195 return error(s, EINVAL, "Failed to sign SIG record");
198 // Send the SIG exchange record.
199 return send_record_priv(s, SPTPS_HANDSHAKE, sig, sizeof(sig));
202 // Generate key material from the shared secret created from the ECDHE key exchange.
203 static bool generate_key_material(sptps_t *s, const char *shared, size_t len) {
204 // Initialise cipher and digest structures if necessary
206 s->incipher = chacha_poly1305_init();
207 s->outcipher = chacha_poly1305_init();
209 if(!s->incipher || !s->outcipher) {
210 return error(s, EINVAL, "Failed to open cipher");
214 // Allocate memory for key material
215 size_t keylen = 2 * CHACHA_POLY1305_KEYLEN;
217 s->key = realloc(s->key, keylen);
220 return error(s, errno, strerror(errno));
223 // Create the HMAC seed, which is "key expansion" + session label + server nonce + client nonce
224 char seed[s->labellen + 64 + 13];
225 strcpy(seed, "key expansion");
228 memcpy(seed + 13, s->mykex + 1, 32);
229 memcpy(seed + 45, s->hiskex + 1, 32);
231 memcpy(seed + 13, s->hiskex + 1, 32);
232 memcpy(seed + 45, s->mykex + 1, 32);
235 memcpy(seed + 77, s->label, s->labellen);
237 // Use PRF to generate the key material
238 if(!prf(shared, len, seed, s->labellen + 64 + 13, s->key, keylen)) {
239 return error(s, EINVAL, "Failed to generate key material");
245 // Send an ACKnowledgement record.
246 static bool send_ack(sptps_t *s) {
247 return send_record_priv(s, SPTPS_HANDSHAKE, "", 0);
250 // Receive an ACKnowledgement record.
251 static bool receive_ack(sptps_t *s, const char *data, uint16_t len) {
255 return error(s, EIO, "Invalid ACK record length");
259 if(!chacha_poly1305_set_key(s->incipher, s->key)) {
260 return error(s, EINVAL, "Failed to set counter");
263 if(!chacha_poly1305_set_key(s->incipher, s->key + CHACHA_POLY1305_KEYLEN)) {
264 return error(s, EINVAL, "Failed to set counter");
275 // Receive a Key EXchange record, respond by sending a SIG record.
276 static bool receive_kex(sptps_t *s, const char *data, uint16_t len) {
277 // Verify length of the HELLO record
278 if(len != 1 + 32 + ECDH_SIZE) {
279 return error(s, EIO, "Invalid KEX record length");
282 // Ignore version number for now.
284 // Make a copy of the KEX message, send_sig() and receive_sig() need it
286 return error(s, EINVAL, "Received a second KEX message before first has been processed");
289 s->hiskex = realloc(s->hiskex, len);
292 return error(s, errno, strerror(errno));
295 memcpy(s->hiskex, data, len);
300 // Receive a SIGnature record, verify it, if it passed, compute the shared secret and calculate the session keys.
301 static bool receive_sig(sptps_t *s, const char *data, uint16_t len) {
302 size_t keylen = ECDH_SIZE;
303 size_t siglen = ecdsa_size(s->hiskey);
305 // Verify length of KEX record.
307 return error(s, EIO, "Invalid KEX record length");
310 // Concatenate both KEX messages, plus tag indicating if it is from the connection originator
311 char msg[(1 + 32 + keylen) * 2 + 1 + s->labellen];
313 msg[0] = !s->initiator;
314 memcpy(msg + 1, s->hiskex, 1 + 32 + keylen);
315 memcpy(msg + 1 + 33 + keylen, s->mykex, 1 + 32 + keylen);
316 memcpy(msg + 1 + 2 * (33 + keylen), s->label, s->labellen);
319 if(!ecdsa_verify(s->hiskey, msg, sizeof(msg), data)) {
320 return error(s, EIO, "Failed to verify SIG record");
323 // Compute shared secret.
324 char shared[ECDH_SHARED_SIZE];
326 if(!ecdh_compute_shared(s->ecdh, s->hiskex + 1 + 32, shared)) {
327 return error(s, EINVAL, "Failed to compute ECDH shared secret");
332 // Generate key material from shared secret.
333 if(!generate_key_material(s, shared, sizeof(shared))) {
343 // Send cipher change record
344 if(s->outstate && !send_ack(s)) {
348 // TODO: only set new keys after ACK has been set/received
350 if(!chacha_poly1305_set_key(s->outcipher, s->key + CHACHA_POLY1305_KEYLEN)) {
351 return error(s, EINVAL, "Failed to set key");
354 if(!chacha_poly1305_set_key(s->outcipher, s->key)) {
355 return error(s, EINVAL, "Failed to set key");
362 // Force another Key EXchange (for testing purposes).
363 bool sptps_force_kex(sptps_t *s) {
364 if(!s->outstate || s->state != SPTPS_SECONDARY_KEX) {
365 return error(s, EINVAL, "Cannot force KEX in current state");
368 s->state = SPTPS_KEX;
372 // Receive a handshake record.
373 static bool receive_handshake(sptps_t *s, const char *data, uint16_t len) {
374 // Only a few states to deal with handshaking.
376 case SPTPS_SECONDARY_KEX:
378 // We receive a secondary KEX request, first respond by sending our own.
386 // We have sent our KEX request, we expect our peer to sent one as well.
387 if(!receive_kex(s, data, len)) {
391 s->state = SPTPS_SIG;
396 // If we already sent our secondary public ECDH key, we expect the peer to send his.
397 if(!receive_sig(s, data, len)) {
402 s->state = SPTPS_ACK;
406 if(!receive_ack(s, NULL, 0)) {
410 s->receive_record(s->handle, SPTPS_HANDSHAKE, NULL, 0);
411 s->state = SPTPS_SECONDARY_KEX;
418 // We expect a handshake message to indicate transition to the new keys.
419 if(!receive_ack(s, data, len)) {
423 s->receive_record(s->handle, SPTPS_HANDSHAKE, NULL, 0);
424 s->state = SPTPS_SECONDARY_KEX;
427 // TODO: split ACK into a VERify and ACK?
429 return error(s, EIO, "Invalid session state %d", s->state);
433 // Check datagram for valid HMAC
434 bool sptps_verify_datagram(sptps_t *s, const void *data, size_t len) {
436 return error(s, EIO, "SPTPS state not ready to verify this datagram");
440 return error(s, EIO, "Received short packet in sptps_verify_datagram");
444 memcpy(&seqno, data, 4);
445 seqno = ntohl(seqno);
446 // TODO: check whether seqno makes sense, to avoid CPU intensive decrypt
450 return chacha_poly1305_decrypt(s->incipher, seqno, (const char *)data + 4, len - 4, buffer, &outlen);
453 // Receive incoming data, datagram version.
454 static bool sptps_receive_data_datagram(sptps_t *s, const void *vdata, size_t len) {
455 const char *data = vdata;
457 if(len < (s->instate ? 21 : 5)) {
458 return error(s, EIO, "Received short packet in sptps_receive_data_datagram");
462 memcpy(&seqno, data, 4);
463 seqno = ntohl(seqno);
466 if(seqno != s->inseqno) {
467 return error(s, EIO, "Invalid packet seqno: %d != %d", seqno, s->inseqno);
470 s->inseqno = seqno + 1;
472 uint8_t type = data[4];
474 if(type != SPTPS_HANDSHAKE) {
475 return error(s, EIO, "Application record received before handshake finished");
478 return receive_handshake(s, data + 5, len - 5);
487 if(!chacha_poly1305_decrypt(s->incipher, seqno, data + 4, len - 4, buffer, &outlen)) {
488 return error(s, EIO, "Failed to decrypt and verify packet");
491 // Replay protection using a sliding window of configurable size.
492 // s->inseqno is expected sequence number
493 // seqno is received sequence number
494 // s->late[] is a circular buffer, a 1 bit means a packet has not been received yet
495 // The circular buffer contains bits for sequence numbers from s->inseqno - s->replaywin * 8 to (but excluding) s->inseqno.
497 if(seqno != s->inseqno) {
498 if(seqno >= s->inseqno + s->replaywin * 8) {
499 // TODO: Prevent packets that jump far ahead of the queue from causing many others to be dropped.
500 warning(s, "Lost %d packets\n", seqno - s->inseqno);
501 // Mark all packets in the replay window as being late.
502 memset(s->late, 255, s->replaywin);
503 } else if(seqno < s->inseqno) {
504 // If the sequence number is farther in the past than the bitmap goes, or if the packet was already received, drop it.
505 if((s->inseqno >= s->replaywin * 8 && seqno < s->inseqno - s->replaywin * 8) || !(s->late[(seqno / 8) % s->replaywin] & (1 << seqno % 8))) {
506 return error(s, EIO, "Received late or replayed packet, seqno %d, last received %d\n", seqno, s->inseqno);
509 // We missed some packets. Mark them in the bitmap as being late.
510 for(uint32_t i = s->inseqno; i < seqno; i++) {
511 s->late[(i / 8) % s->replaywin] |= 1 << i % 8;
516 // Mark the current packet as not being late.
517 s->late[(seqno / 8) % s->replaywin] &= ~(1 << seqno % 8);
520 if(seqno >= s->inseqno) {
521 s->inseqno = seqno + 1;
530 // Append a NULL byte for safety.
531 buffer[len - 20] = 0;
533 uint8_t type = buffer[0];
535 if(type < SPTPS_HANDSHAKE) {
537 return error(s, EIO, "Application record received before handshake finished");
540 if(!s->receive_record(s->handle, type, buffer + 1, len - 21)) {
543 } else if(type == SPTPS_HANDSHAKE) {
544 if(!receive_handshake(s, buffer + 1, len - 21)) {
548 return error(s, EIO, "Invalid record type %d", type);
554 // Receive incoming data. Check if it contains a complete record, if so, handle it.
555 bool sptps_receive_data(sptps_t *s, const void *data, size_t len) {
557 return error(s, EIO, "Invalid session state zero");
561 return sptps_receive_data_datagram(s, data, len);
564 const char *ptr = data;
567 // First read the 2 length bytes.
569 size_t toread = 2 - s->buflen;
575 memcpy(s->inbuf + s->buflen, ptr, toread);
581 // Exit early if we don't have the full length.
586 // Get the length bytes
588 memcpy(&s->reclen, s->inbuf, 2);
589 s->reclen = ntohs(s->reclen);
591 // If we have the length bytes, ensure our buffer can hold the whole request.
592 s->inbuf = realloc(s->inbuf, s->reclen + 19UL);
595 return error(s, errno, strerror(errno));
598 // Exit early if we have no more data to process.
604 // Read up to the end of the record.
605 size_t toread = s->reclen + (s->instate ? 19UL : 3UL) - s->buflen;
611 memcpy(s->inbuf + s->buflen, ptr, toread);
616 // If we don't have a whole record, exit.
617 if(s->buflen < s->reclen + (s->instate ? 19UL : 3UL)) {
621 // Update sequence number.
623 uint32_t seqno = s->inseqno++;
625 // Check HMAC and decrypt.
627 if(!chacha_poly1305_decrypt(s->incipher, seqno, s->inbuf + 2UL, s->reclen + 17UL, s->inbuf + 2UL, NULL)) {
628 return error(s, EINVAL, "Failed to decrypt and verify record");
632 // Append a NULL byte for safety.
633 s->inbuf[s->reclen + 3UL] = 0;
635 uint8_t type = s->inbuf[2];
637 if(type < SPTPS_HANDSHAKE) {
639 return error(s, EIO, "Application record received before handshake finished");
642 if(!s->receive_record(s->handle, type, s->inbuf + 3, s->reclen)) {
645 } else if(type == SPTPS_HANDSHAKE) {
646 if(!receive_handshake(s, s->inbuf + 3, s->reclen)) {
650 return error(s, EIO, "Invalid record type %d", type);
659 // Start a SPTPS session.
660 bool sptps_start(sptps_t *s, void *handle, bool initiator, bool datagram, ecdsa_t *mykey, ecdsa_t *hiskey, const char *label, size_t labellen, send_data_t send_data, receive_record_t receive_record) {
661 if(!s || !mykey || !hiskey || !label || !labellen || !send_data || !receive_record) {
662 return error(s, EINVAL, "Invalid argument to sptps_start()");
665 // Initialise struct sptps
666 memset(s, 0, sizeof(*s));
669 s->initiator = initiator;
670 s->datagram = datagram;
673 s->replaywin = sptps_replaywin;
676 s->late = malloc(s->replaywin);
679 return error(s, errno, strerror(errno));
682 memset(s->late, 0, s->replaywin);
685 s->label = malloc(labellen);
688 return error(s, errno, strerror(errno));
692 s->inbuf = malloc(7);
695 return error(s, errno, strerror(errno));
701 memcpy(s->label, label, labellen);
702 s->labellen = labellen;
704 s->send_data = send_data;
705 s->receive_record = receive_record;
707 // Do first KEX immediately
708 s->state = SPTPS_KEX;
712 // Stop a SPTPS session.
713 bool sptps_stop(sptps_t *s) {
714 // Clean up any resources.
715 chacha_poly1305_exit(s->incipher);
716 chacha_poly1305_exit(s->outcipher);
724 memset(s, 0, sizeof(*s));