2 sptps.c -- Simple Peer-to-Peer Security
3 Copyright (C) 2014 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.
30 unsigned int sptps_replaywin = 16;
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) {
55 void sptps_log_stderr(sptps_t *s, int s_errno, const char *format, va_list ap) {
56 vfprintf(stderr, format, ap);
60 void (*sptps_log)(sptps_t *s, int s_errno, const char *format, va_list ap) = sptps_log_stderr;
62 // Log an error message.
63 static bool error(sptps_t *s, int s_errno, const char *format, ...) {
67 sptps_log(s, s_errno, format, ap);
75 static void warning(sptps_t *s, const char *format, ...) {
78 sptps_log(s, 0, format, ap);
82 // Send a record (datagram version, accepts all record types, handles encryption and authentication).
83 static bool send_record_priv_datagram(sptps_t *s, uint8_t type, const char *data, uint16_t len) {
84 char buffer[len + 21UL];
86 // Create header with sequence number, length and record type
87 uint32_t seqno = htonl(s->outseqno++);
89 memcpy(buffer, &seqno, 4);
93 // If first handshake has finished, encrypt and HMAC
94 if(!cipher_set_counter(s->outcipher, &seqno, sizeof seqno))
95 return error(s, EINVAL, "Failed to set counter");
97 if(!cipher_gcm_encrypt_start(s->outcipher, buffer + 4, 1, buffer + 4, NULL))
98 return error(s, EINVAL, "Error encrypting record");
100 if(!cipher_gcm_encrypt_finish(s->outcipher, data, len, buffer + 5, NULL))
101 return error(s, EINVAL, "Error encrypting record");
103 return s->send_data(s->handle, type, buffer, len + 21UL);
105 // Otherwise send as plaintext
106 memcpy(buffer + 5, data, len);
107 return s->send_data(s->handle, type, buffer, len + 5UL);
110 // Send a record (private version, accepts all record types, handles encryption and authentication).
111 static bool send_record_priv(sptps_t *s, uint8_t type, const char *data, uint16_t len) {
113 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 = htonl(s->outseqno++);
119 uint16_t netlen = htons(len);
121 memcpy(buffer, &netlen, 2);
125 // If first handshake has finished, encrypt and HMAC
126 if(!cipher_set_counter(s->outcipher, &seqno, 4))
127 return error(s, EINVAL, "Failed to set counter");
129 if(!cipher_gcm_encrypt_start(s->outcipher, buffer, 3, buffer, NULL))
130 return error(s, EINVAL, "Error encrypting record");
132 if(!cipher_gcm_encrypt_finish(s->outcipher, data, len, buffer + 3, NULL))
133 return error(s, EINVAL, "Error encrypting record");
135 return s->send_data(s->handle, type, buffer, len + 19UL);
137 // Otherwise send as plaintext
138 memcpy(buffer + 3, data, len);
139 return s->send_data(s->handle, type, buffer, len + 3UL);
143 // Send an application record.
144 bool sptps_send_record(sptps_t *s, uint8_t type, const char *data, uint16_t len) {
145 // Sanity checks: application cannot send data before handshake is finished,
146 // and only record types 0..127 are allowed.
148 return error(s, EINVAL, "Handshake phase not finished yet");
150 if(type >= SPTPS_HANDSHAKE)
151 return error(s, EINVAL, "Invalid application record type");
153 return send_record_priv(s, type, data, len);
156 // Send a Key EXchange record, containing a random nonce and an ECDHE public key.
157 static bool send_kex(sptps_t *s) {
158 size_t keylen = ECDH_SIZE;
160 // Make room for our KEX message, which we will keep around since send_sig() needs it.
163 s->mykex = realloc(s->mykex, 1 + 32 + keylen);
165 return error(s, errno, strerror(errno));
167 // Set version byte to zero.
168 s->mykex[0] = SPTPS_VERSION;
170 // Create a random nonce.
171 randomize(s->mykex + 1, 32);
173 // Create a new ECDH public key.
174 if(!(s->ecdh = ecdh_generate_public(s->mykex + 1 + 32)))
175 return error(s, EINVAL, "Failed to generate ECDH public key");
177 return send_record_priv(s, SPTPS_HANDSHAKE, s->mykex, 1 + 32 + keylen);
180 // Send a SIGnature record, containing an ECDSA signature over both KEX records.
181 static bool send_sig(sptps_t *s) {
182 size_t keylen = ECDH_SIZE;
183 size_t siglen = ecdsa_size(s->mykey);
185 // Concatenate both KEX messages, plus tag indicating if it is from the connection originator, plus label
186 char msg[(1 + 32 + keylen) * 2 + 1 + s->labellen];
189 msg[0] = s->initiator;
190 memcpy(msg + 1, s->mykex, 1 + 32 + keylen);
191 memcpy(msg + 1 + 33 + keylen, s->hiskex, 1 + 32 + keylen);
192 memcpy(msg + 1 + 2 * (33 + keylen), s->label, s->labellen);
195 if(!ecdsa_sign(s->mykey, msg, sizeof msg, sig))
196 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 = cipher_open_by_name("aes-256-gcm");
207 s->outcipher = cipher_open_by_name("aes-256-gcm");
208 if(!s->incipher || !s->outcipher)
209 return error(s, EINVAL, "Failed to open cipher");
212 // Allocate memory for key material
213 size_t keylen = cipher_keylength(s->incipher) + cipher_keylength(s->outcipher);
215 s->key = realloc(s->key, keylen);
217 return error(s, errno, strerror(errno));
219 // Create the HMAC seed, which is "key expansion" + session label + server nonce + client nonce
220 char seed[s->labellen + 64 + 13];
221 strcpy(seed, "key expansion");
223 memcpy(seed + 13, s->mykex + 1, 32);
224 memcpy(seed + 45, s->hiskex + 1, 32);
226 memcpy(seed + 13, s->hiskex + 1, 32);
227 memcpy(seed + 45, s->mykex + 1, 32);
229 memcpy(seed + 77, s->label, s->labellen);
231 // Use PRF to generate the key material
232 if(!prf(shared, len, seed, s->labellen + 64 + 13, s->key, keylen))
233 return error(s, EINVAL, "Failed to generate key material");
238 // Send an ACKnowledgement record.
239 static bool send_ack(sptps_t *s) {
240 return send_record_priv(s, SPTPS_HANDSHAKE, "", 0);
243 // Receive an ACKnowledgement record.
244 static bool receive_ack(sptps_t *s, const char *data, uint16_t len) {
246 return error(s, EIO, "Invalid ACK record length");
249 if(!cipher_set_counter_key(s->incipher, s->key))
250 return error(s, EINVAL, "Failed to set counter");
252 if(!cipher_set_counter_key(s->incipher, s->key + cipher_keylength(s->outcipher)))
253 return error(s, EINVAL, "Failed to set counter");
263 // Receive a Key EXchange record, respond by sending a SIG record.
264 static bool receive_kex(sptps_t *s, const char *data, uint16_t len) {
265 // Verify length of the HELLO record
266 if(len != 1 + 32 + ECDH_SIZE)
267 return error(s, EIO, "Invalid KEX record length");
269 // Ignore version number for now.
271 // Make a copy of the KEX message, send_sig() and receive_sig() need it
273 return error(s, EINVAL, "Received a second KEX message before first has been processed");
274 s->hiskex = realloc(s->hiskex, len);
276 return error(s, errno, strerror(errno));
278 memcpy(s->hiskex, data, len);
283 // Receive a SIGnature record, verify it, if it passed, compute the shared secret and calculate the session keys.
284 static bool receive_sig(sptps_t *s, const char *data, uint16_t len) {
285 size_t keylen = ECDH_SIZE;
286 size_t siglen = ecdsa_size(s->hiskey);
288 // Verify length of KEX record.
290 return error(s, EIO, "Invalid KEX record length");
292 // Concatenate both KEX messages, plus tag indicating if it is from the connection originator
293 char msg[(1 + 32 + keylen) * 2 + 1 + s->labellen];
295 msg[0] = !s->initiator;
296 memcpy(msg + 1, s->hiskex, 1 + 32 + keylen);
297 memcpy(msg + 1 + 33 + keylen, s->mykex, 1 + 32 + keylen);
298 memcpy(msg + 1 + 2 * (33 + keylen), s->label, s->labellen);
301 if(!ecdsa_verify(s->hiskey, msg, sizeof msg, data))
302 return error(s, EIO, "Failed to verify SIG record");
304 // Compute shared secret.
305 char shared[ECDH_SHARED_SIZE];
306 if(!ecdh_compute_shared(s->ecdh, s->hiskex + 1 + 32, shared))
307 return error(s, EINVAL, "Failed to compute ECDH shared secret");
310 // Generate key material from shared secret.
311 if(!generate_key_material(s, shared, sizeof shared))
320 // Send cipher change record
321 if(s->outstate && !send_ack(s))
324 // TODO: only set new keys after ACK has been set/received
326 if(!cipher_set_counter_key(s->outcipher, s->key + cipher_keylength(s->incipher)))
327 return error(s, EINVAL, "Failed to set counter");
329 if(!cipher_set_counter_key(s->outcipher, s->key))
330 return error(s, EINVAL, "Failed to set counter");
336 // Force another Key EXchange (for testing purposes).
337 bool sptps_force_kex(sptps_t *s) {
338 if(!s->outstate || s->state != SPTPS_SECONDARY_KEX)
339 return error(s, EINVAL, "Cannot force KEX in current state");
341 s->state = SPTPS_KEX;
345 // Receive a handshake record.
346 static bool receive_handshake(sptps_t *s, const char *data, uint16_t len) {
347 // Only a few states to deal with handshaking.
349 case SPTPS_SECONDARY_KEX:
350 // We receive a secondary KEX request, first respond by sending our own.
354 // We have sent our KEX request, we expect our peer to sent one as well.
355 if(!receive_kex(s, data, len))
357 s->state = SPTPS_SIG;
360 // If we already sent our secondary public ECDH key, we expect the peer to send his.
361 if(!receive_sig(s, data, len))
364 s->state = SPTPS_ACK;
367 if(!receive_ack(s, NULL, 0))
369 s->receive_record(s->handle, SPTPS_HANDSHAKE, NULL, 0);
370 s->state = SPTPS_SECONDARY_KEX;
375 // We expect a handshake message to indicate transition to the new keys.
376 if(!receive_ack(s, data, len))
378 s->receive_record(s->handle, SPTPS_HANDSHAKE, NULL, 0);
379 s->state = SPTPS_SECONDARY_KEX;
381 // TODO: split ACK into a VERify and ACK?
383 return error(s, EIO, "Invalid session state %d", s->state);
387 // Check datagram for valid HMAC
388 bool sptps_verify_datagram(sptps_t *s, const char *data, size_t len) {
389 if(!s->instate || len < 21)
390 return error(s, EIO, "Received short packet");
392 // TODO: just decrypt without updating the replay window
397 // Receive incoming data, datagram version.
398 static bool sptps_receive_data_datagram(sptps_t *s, const char *data, size_t len) {
399 if(len < (s->instate ? 21 : 5))
400 return error(s, EIO, "Received short packet");
403 memcpy(&seqno, data, 4);
404 seqno = ntohl(seqno);
407 if(seqno != s->inseqno)
408 return error(s, EIO, "Invalid packet seqno: %d != %d", seqno, s->inseqno);
410 s->inseqno = seqno + 1;
412 uint8_t type = data[4];
414 if(type != SPTPS_HANDSHAKE)
415 return error(s, EIO, "Application record received before handshake finished");
417 return receive_handshake(s, data + 5, len - 5);
424 if(!cipher_set_counter(s->incipher, data, sizeof seqno))
425 return error(s, EINVAL, "Failed to set counter");
428 if(!cipher_gcm_decrypt(s->incipher, data + 4, len - 4, buffer, &outlen))
429 return error(s, EIO, "Failed to decrypt and verify packet");
431 // Replay protection using a sliding window of configurable size.
432 // s->inseqno is expected sequence number
433 // seqno is received sequence number
434 // s->late[] is a circular buffer, a 1 bit means a packet has not been received yet
435 // The circular buffer contains bits for sequence numbers from s->inseqno - s->replaywin * 8 to (but excluding) s->inseqno.
437 if(seqno != s->inseqno) {
438 if(seqno >= s->inseqno + s->replaywin * 8) {
439 // TODO: Prevent packets that jump far ahead of the queue from causing many others to be dropped.
440 warning(s, "Lost %d packets\n", seqno - s->inseqno);
441 // Mark all packets in the replay window as being late.
442 memset(s->late, 255, s->replaywin);
443 } else if (seqno < s->inseqno) {
444 // If the sequence number is farther in the past than the bitmap goes, or if the packet was already received, drop it.
445 if((s->inseqno >= s->replaywin * 8 && seqno < s->inseqno - s->replaywin * 8) || !(s->late[(seqno / 8) % s->replaywin] & (1 << seqno % 8)))
446 return error(s, EIO, "Received late or replayed packet, seqno %d, last received %d\n", seqno, s->inseqno);
448 // We missed some packets. Mark them in the bitmap as being late.
449 for(int i = s->inseqno; i < seqno; i++)
450 s->late[(i / 8) % s->replaywin] |= 1 << i % 8;
454 // Mark the current packet as not being late.
455 s->late[(seqno / 8) % s->replaywin] &= ~(1 << seqno % 8);
458 if(seqno >= s->inseqno)
459 s->inseqno = seqno + 1;
466 // Append a NULL byte for safety.
467 buffer[len - 20] = 0;
469 uint8_t type = buffer[0];
471 if(type < SPTPS_HANDSHAKE) {
473 return error(s, EIO, "Application record received before handshake finished");
474 if(!s->receive_record(s->handle, type, buffer + 1, len - 21))
476 } else if(type == SPTPS_HANDSHAKE) {
477 if(!receive_handshake(s, buffer + 1, len - 21))
480 return error(s, EIO, "Invalid record type %d", type);
486 // Receive incoming data. Check if it contains a complete record, if so, handle it.
487 bool sptps_receive_data(sptps_t *s, const char *data, size_t len) {
489 return error(s, EIO, "Invalid session state zero");
492 return sptps_receive_data_datagram(s, data, len);
495 // First read the 2 length bytes.
497 size_t toread = 2 - s->buflen;
501 memcpy(s->inbuf + s->buflen, data, toread);
507 // Exit early if we don't have the full length.
511 // Update sequence number.
513 uint32_t seqno = htonl(s->inseqno++);
515 // Decrypt the length bytes
518 if(!cipher_set_counter(s->incipher, &seqno, 4))
519 return error(s, EINVAL, "Failed to set counter");
521 if(!cipher_gcm_decrypt_start(s->incipher, s->inbuf, 2, &s->reclen, NULL))
522 return error(s, EINVAL, "Failed to decrypt record");
524 memcpy(&s->reclen, s->inbuf, 2);
527 s->reclen = ntohs(s->reclen);
529 // If we have the length bytes, ensure our buffer can hold the whole request.
530 s->inbuf = realloc(s->inbuf, s->reclen + 19UL);
532 return error(s, errno, strerror(errno));
534 // Exit early if we have no more data to process.
539 // Read up to the end of the record.
540 size_t toread = s->reclen + (s->instate ? 19UL : 3UL) - s->buflen;
544 memcpy(s->inbuf + s->buflen, data, toread);
549 // If we don't have a whole record, exit.
550 if(s->buflen < s->reclen + (s->instate ? 19UL : 3UL))
553 // Check HMAC and decrypt.
555 if(!cipher_gcm_decrypt_finish(s->incipher, s->inbuf + 2UL, s->reclen + 17UL, s->inbuf + 2UL, NULL))
556 return error(s, EINVAL, "Failed to decrypt and verify record");
559 // Append a NULL byte for safety.
560 s->inbuf[s->reclen + 3UL] = 0;
562 uint8_t type = s->inbuf[2];
564 if(type < SPTPS_HANDSHAKE) {
566 return error(s, EIO, "Application record received before handshake finished");
567 if(!s->receive_record(s->handle, type, s->inbuf + 3, s->reclen))
569 } else if(type == SPTPS_HANDSHAKE) {
570 if(!receive_handshake(s, s->inbuf + 3, s->reclen))
573 return error(s, EIO, "Invalid record type %d", type);
582 // Start a SPTPS session.
583 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) {
584 // Initialise struct sptps
585 memset(s, 0, sizeof *s);
588 s->initiator = initiator;
589 s->datagram = datagram;
592 s->replaywin = sptps_replaywin;
594 s->late = malloc(s->replaywin);
596 return error(s, errno, strerror(errno));
597 memset(s->late, 0, s->replaywin);
600 s->label = malloc(labellen);
602 return error(s, errno, strerror(errno));
605 s->inbuf = malloc(7);
607 return error(s, errno, strerror(errno));
611 memcpy(s->label, label, labellen);
612 s->labellen = labellen;
614 s->send_data = send_data;
615 s->receive_record = receive_record;
617 // Do first KEX immediately
618 s->state = SPTPS_KEX;
622 // Stop a SPTPS session.
623 bool sptps_stop(sptps_t *s) {
624 // Clean up any resources.
625 cipher_close(s->incipher);
626 cipher_close(s->outcipher);
627 digest_close(s->indigest);
628 digest_close(s->outdigest);
636 memset(s, 0, sizeof *s);