2 sptps.c -- Simple Peer-to-Peer Security
3 Copyright (C) 2011 Guus Sliepen <guus@tinc-vpn.org>,
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.
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!
38 Add explicit tag to beginning of structure to distinguish the client and server when signing. (done)
40 Sign all handshake messages up to ECDHE kex with long-term public keys. (done)
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?)
44 Explicit close message needs to be added.
46 Maybe do add some alert messages to give helpful error messages? Not more than TLS sends.
48 Use counter mode instead of OFB. (done)
50 Make sure ECC operations are fixed time (aka prevent side-channel attacks).
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);
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];
65 // Create header with sequence number, length and record type
66 uint32_t seqno = htonl(s->outseqno++);
67 uint16_t netlen = htons(len);
69 memcpy(plaintext, &seqno, 4);
70 memcpy(plaintext + 4, &netlen, 2);
73 // Add plaintext (TODO: avoid unnecessary copy)
74 memcpy(plaintext + 7, data, len);
77 // If first handshake has finished, encrypt and HMAC
78 if(!digest_create(&s->outdigest, plaintext, len + 7, plaintext + 7 + len))
81 if(!cipher_counter_xor(&s->outcipher, plaintext + 4, sizeof ciphertext, ciphertext))
84 return s->send_data(s->handle, ciphertext, len + 19);
86 // Otherwise send as plaintext
87 return s->send_data(s->handle, plaintext + 4, len + 3);
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.
96 return error(s, EINVAL, "Handshake phase not finished yet");
98 if(type >= SPTPS_HANDSHAKE)
99 return error(s, EINVAL, "Invalid application record type");
101 return send_record_priv(s, type, data, len);
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;
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);
111 return error(s, errno, strerror(errno));
113 // Set version byte to zero.
114 s->mykex[0] = SPTPS_VERSION;
116 // Create a random nonce.
117 randomize(s->mykex + 1, 32);
119 // Create a new ECDH public key.
120 if(!ecdh_generate_public(&s->ecdh, s->mykex + 1 + 32))
123 return send_record_priv(s, SPTPS_HANDSHAKE, s->mykex, 1 + 32 + keylen);
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);
131 // Concatenate both KEX messages, plus tag indicating if it is from the connection originator
132 char msg[(1 + 32 + keylen) * 2 + 1];
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);
140 if(!ecdsa_sign(&s->mykey, msg, sizeof msg, sig))
143 // Send the SIG exchange record.
144 return send_record_priv(s, SPTPS_HANDSHAKE, sig, sizeof sig);
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
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);
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);
163 s->key = realloc(s->key, keylen);
165 return error(s, errno, strerror(errno));
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");
171 memcpy(seed + 13, s->mykex + 1, 32);
172 memcpy(seed + 45, s->hiskex + 1, 32);
174 memcpy(seed + 13, s->hiskex + 1, 32);
175 memcpy(seed + 45, s->mykex + 1, 32);
177 memcpy(seed + 78, s->label, s->labellen);
179 // Use PRF to generate the key material
180 if(!prf(shared, len, seed, s->labellen + 64 + 13, s->key, keylen))
186 // Send an ACKnowledgement record.
187 static bool send_ack(sptps_t *s) {
188 return send_record_priv(s, SPTPS_HANDSHAKE, "", 0);
191 // Receive an ACKnowledgement record.
192 static bool receive_ack(sptps_t *s, const char *data, uint16_t len) {
196 // TODO: set cipher/digest keys
197 return error(s, ENOSYS, "receive_ack() not completely implemented yet");
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");
206 // Ignore version number for now.
208 // Make a copy of the KEX message, send_sig() and receive_sig() need it
209 s->hiskex = realloc(s->hiskex, len);
211 return error(s, errno, strerror(errno));
213 memcpy(s->hiskex, data, len);
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);
223 // Verify length of KEX record.
225 return error(s, EIO, "Invalid KEX record length");
227 // Concatenate both KEX messages, plus tag indicating if it is from the connection originator
228 char msg[(1 + 32 + keylen) * 2 + 1];
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);
235 if(!ecdsa_verify(&s->hiskey, msg, sizeof msg, data))
238 // Compute shared secret.
239 char shared[ECDH_SHARED_SIZE];
240 if(!ecdh_compute_shared(&s->ecdh, s->hiskex + 1 + 32, shared))
243 // Generate key material from shared secret.
244 if(!generate_key_material(s, shared, sizeof shared))
247 // Send cipher change record if necessary
248 //if(s->outstate && !send_ack(s))
251 // TODO: only set new keys after ACK has been set/received
254 = cipher_set_counter_key(&s->incipher, s->key)
255 && digest_set_key(&s->indigest, s->key + cipher_keylength(&s->incipher), digest_keylength(&s->indigest))
256 && cipher_set_counter_key(&s->outcipher, s->key + cipher_keylength(&s->incipher) + digest_keylength(&s->indigest))
257 && digest_set_key(&s->outdigest, s->key + cipher_keylength(&s->incipher) + digest_keylength(&s->indigest) + cipher_keylength(&s->outcipher), digest_keylength(&s->outdigest));
262 = cipher_set_counter_key(&s->outcipher, s->key)
263 && digest_set_key(&s->outdigest, s->key + cipher_keylength(&s->outcipher), digest_keylength(&s->outdigest))
264 && cipher_set_counter_key(&s->incipher, s->key + cipher_keylength(&s->outcipher) + digest_keylength(&s->outdigest))
265 && digest_set_key(&s->indigest, s->key + cipher_keylength(&s->outcipher) + digest_keylength(&s->outdigest) + cipher_keylength(&s->incipher), digest_keylength(&s->indigest));
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");
281 s->state = SPTPS_KEX;
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);
290 case SPTPS_SECONDARY_KEX:
291 // We receive a secondary KEX request, first respond by sending our own.
295 // We have sent our KEX request, we expect our peer to sent one as well.
296 if(!receive_kex(s, data, len))
298 s->state = 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))
304 // s->state = SPTPS_ACK;
305 s->state = SPTPS_SECONDARY_KEX;
308 // We expect a handshake message to indicate transition to the new keys.
309 if(!receive_ack(s, data, len))
311 s->state = SPTPS_SECONDARY_KEX;
313 // TODO: split ACK into a VERify and ACK?
315 return error(s, EIO, "Invalid session state");
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) {
322 // First read the 2 length bytes.
324 size_t toread = 6 - s->buflen;
329 if(!cipher_counter_xor(&s->incipher, data, toread, s->inbuf + s->buflen))
332 memcpy(s->inbuf + s->buflen, data, toread);
339 // Exit early if we don't have the full length.
343 // If we have the length bytes, ensure our buffer can hold the whole request.
345 memcpy(&reclen, s->inbuf + 4, 2);
346 reclen = htons(reclen);
347 s->inbuf = realloc(s->inbuf, reclen + 23UL);
349 return error(s, errno, strerror(errno));
351 // Add sequence number.
352 uint32_t seqno = htonl(s->inseqno++);
353 memcpy(s->inbuf, &seqno, 4);
355 // Exit early if we have no more data to process.
360 // Read up to the end of the record.
362 memcpy(&reclen, s->inbuf + 4, 2);
363 reclen = htons(reclen);
364 size_t toread = reclen + (s->instate ? 23UL : 7UL) - s->buflen;
369 if(!cipher_counter_xor(&s->incipher, data, toread, s->inbuf + s->buflen))
372 memcpy(s->inbuf + s->buflen, data, toread);
379 // If we don't have a whole record, exit.
380 if(s->buflen < reclen + (s->instate ? 23UL : 7UL))
385 if(!digest_verify(&s->indigest, s->inbuf, reclen + 7UL, s->inbuf + reclen + 7UL))
386 error(s, EIO, "Invalid HMAC");
388 uint8_t type = s->inbuf[6];
391 if(type < SPTPS_HANDSHAKE) {
392 if(!s->receive_record(s->handle, type, s->inbuf + 7, reclen))
394 } else if(type == SPTPS_HANDSHAKE) {
395 if(!receive_handshake(s, s->inbuf + 7, reclen))
398 return error(s, EIO, "Invalid record type");
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);
413 s->initiator = initiator;
417 s->label = malloc(labellen);
419 return error(s, errno, strerror(errno));
421 s->inbuf = malloc(7);
423 return error(s, errno, strerror(errno));
425 memset(s->inbuf, 0, 4);
427 memcpy(s->label, label, labellen);
428 s->labellen = labellen;
430 s->send_data = send_data;
431 s->receive_record = receive_record;
433 // Do first KEX immediately
434 s->state = SPTPS_KEX;
438 // Stop a SPTPS session.
439 bool stop_sptps(sptps_t *s) {
440 // Clean up any resources.