]> pd.if.org Git - zpackage/blob - crypto/handshake.c
fix some todo items
[zpackage] / crypto / handshake.c
1 #define _POSIX_C_SOURCE 200809L
2
3 #include <arpa/inet.h>
4
5 #include "tlse.h"
6 #include "buffer.h"
7
8 #define TLS12_FLAG 0x01
9 #define TLS13_FLAG 0x03
10
11 static unsigned char *encrypt_rsa(struct TLSContext *context,
12                                         const unsigned char *buffer,
13                                         unsigned int len,
14                                         unsigned int *size) {
15         *size = 0;
16         if (!len || !context || !context->certificates
17             || !context->certificates_count
18             || !context->certificates[0]
19             || !context->certificates[0]->der_bytes
20             || !context->certificates[0]->der_len) {
21                 DEBUG_PRINT("No certificate set\n");
22                 return NULL;
23         }
24         rsa_key key;
25         int err;
26         err = rsa_import(context->certificates[0]->der_bytes,
27                         context->certificates[0]->der_len, &key);
28
29         if (err) {
30                 DEBUG_PRINT("Error importing RSA certificate (code: %i)\n",
31                             err);
32                 return NULL;
33         }
34         unsigned long out_size = TLS_MAX_RSA_KEY;
35         unsigned char *out = malloc(out_size);
36         int hash_idx = find_hash("sha256");
37         int prng_idx = find_prng("sprng");
38         err = rsa_encrypt_key_ex(buffer, len, out, &out_size, (unsigned char *)
39                         "Concept", 7, NULL, prng_idx, hash_idx,
40                         LTC_PKCS_1_V1_5, &key);
41         rsa_free(&key);
42         if (err || !out_size) {
43                 free(out);
44                 return NULL;
45         }
46         *size = (unsigned int) out_size;
47         return out;
48 }
49
50
51 void add_supported_versions(struct tls_buffer *buf, int versions) {
52         size_t size;
53         char version12[] = { 0x00, 0x2b, 0x00, 0x03, 0x02, 0x03, 0x03 };
54         char version13[] = { 0x00, 0x2b, 0x00, 0x03, 0x02, 0x03, 0x04 };
55         char both[] = { 0x00, 0x2b, 0x00, 0x05, 0x04, 0x03, 0x04, 0x03, 0x03 };
56         char *use;
57
58         switch (versions) {
59                 case 1:
60                         use = version12;
61                         size = sizeof version12;
62                         break;
63                 case 2:
64                         use = version13;
65                         size = sizeof version13;
66                         break;
67                 case 3:
68                         use = both;
69                         size = sizeof both;
70                         break;
71         }
72
73         tls_buffer_append(buf, use, size);
74 }
75
76 static void add_sni_extension(struct tls_buffer *buf, char *sni) {
77         size_t len;
78
79         if (!buf || !sni) {
80                 return;
81         }
82
83         len = strlen(sni);
84
85         /* server name extension id = 0x00 0x00 */
86         tls_buffer_append16(buf, 0x0000);
87         /* length of server name extension */
88         tls_buffer_append16(buf, len + 5);
89         /* length of first entry */
90         tls_buffer_append16(buf, len + 3);
91         /* DNS hostname */
92         tls_buffer_append_byte(buf, 0x00);
93         /* length of entry */
94         tls_buffer_append16(buf, len);
95         /* actual server name indication */
96         tls_buffer_append(buf, sni, len);
97
98 }
99
100
101 /*
102 00 20 - 0x20 (32) bytes of cipher suite data
103
104
105 */
106
107 static void add_cipher_suites(struct tls_buffer *buf, int suites) {
108         /* the five TLS 1.3 cipher suites in B.4 of rfc 8446 */
109         /* chacha20 preferred */
110         unsigned char tls_13_suites[] = {
111                 0x13, 0x03, 0x13, 0x01, 0x13, 0x02, 0x13, 0x04, 0x13, 0x04
112         };
113         unsigned char tls_12_suites[] = {
114                 0xcc, 0xa9, 0xc0, 0x2b, 0xc0, 0x23, 0xcc, 0xa8, 0xc0, 0x2f,
115                 0xc0, 0x27, 0x00, 0x9e, 0x00, 0x6b, 0x00, 0x67, 0xcc, 0xaa
116         };
117
118         size_t len = 0;
119
120         if (suites & 1) {
121                 len += sizeof tls_12_suites;
122         }
123         
124         if (suites & 2) {
125                 len += sizeof tls_13_suites;
126         }
127
128         tls_buffer_expand(buf, len + 2);
129         tls_buffer_append16(buf, len);
130         /* if we're including 1.3 ciphers, put them first so they're preferred
131          */
132         if (suites & 2) {
133                 tls_buffer_append(buf, tls_13_suites, sizeof tls_13_suites);
134         }
135         if (suites & 1) {
136                 tls_buffer_append(buf, tls_12_suites, sizeof tls_12_suites);
137         }
138 }
139
140 void add_signed_certificate_timestamp_extension(struct tls_buffer *buf) {
141         char sct[] = { 0x00, 0x12, 0x00, 0x00 }; /* sct id and zero bytes */
142         tls_buffer_append(buf, sct, sizeof sct);
143 }
144
145 /*
146  * 00 05 - assigned value for extension "status request"
147  * 00 05 - 0x5 (5) bytes of "status request" extension data follows
148  * 01 - assigned value for "certificate status type: OCSP"
149  * 00 00 - 0x0 (0) bytes of responderID information
150  * 00 00 - 0x0 (0) bytes of request extension information 
151  */
152 void add_status_request_extension(struct tls_buffer *buf) {
153         char sr[] = { 0x00, 0x05, 0x00, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00 };
154         tls_buffer_append(buf, sr, sizeof sr);
155 }
156
157 void add_supported_groups_extension(struct tls_buffer *buf) {
158         /* supported groups */
159         /* this specifies the curves */
160         unsigned char groups[] = {
161                 /* extension id and size in bytes */
162                 0x00, 0x0a, 0x00, 0x08,
163                 /* six bytes of groups */
164                 0x00, 0x06,
165 #if 0
166                 /* x25519, */
167                 0x00, 0x1d,
168 #endif
169                 /* secp256r1, secp384r1, secp521r1 */
170                 0x00, 0x17, 0x00, 0x18, 0x00, 0x19
171         };
172         tls_buffer_append(buf, groups, sizeof groups);
173 }
174
175 /*
176  * 00 0b - assigned value for extension "EC points format"
177  * 00 02 - 0x2 (2) bytes of "EC points format" extension data follows
178  * 01 - 0x1 (1) bytes of data are in the supported formats list
179  * 00 - assigned value for uncompressed form 
180  */
181 void add_ec_point_formats_extension(struct tls_buffer *buf) {
182         char formats[] = { 0x00, 0x0b, 0x00, 0x02, 0x01, 0x00 };
183         tls_buffer_append(buf, formats, sizeof formats);
184 }
185
186 void add_signature_algorithms_extension(struct tls_buffer *buf) {
187         char algorithms[] = {
188                 0x00, 0x0d, 0x00, 0x0e, 0x00, 0x0c, /* id and lengths */
189                 0x04, 0x01, /* RSA/PKCS1/SHA256 */
190                 0x04, 0x03, /* ECDSA/SECP256r1/SHA256 */
191                 0x05, 0x01, /* RSA/PKCS1/SHA386 */
192                 0x05, 0x03, /* ECDSA/SECP384r1/SHA384 */
193                 0x06, 0x01, /* RSA/PKCS1/SHA512 */
194                 0x06, 0x03 /* ECDSA/SECP521r1/SHA512 */
195         };
196 #if 0
197         /* TODO x25519 ? */
198         char tls13algs[] = {
199                 0x04, 0x03,
200                 0x08, 0x04, /* RSA-PSS-RSAE-SHA256 */
201                 0x04, 0x01,
202                 0x05, 0x03,
203                 0x08, 0x05, /* RSA-PSS-RSAE-SHA384 */
204                 0x05, 0x01,
205                 0x08, 0x06, /* RSA-PSS-RSAE-SHA512 */
206                 0x06, 0x01
207                         /* and 0x02, 0x01 for RSA-PKCS1-SHA1 */
208
209         };
210 #endif
211
212         tls_buffer_append(buf, algorithms, sizeof algorithms);
213 }
214
215 static void add_renegotiation_info_extension(struct tls_buffer *buf) {
216         /* two bytes id, and one byte of zero bytes of info */
217         char info[] = { 0xff, 0x01, 0x00, 0x01, 0x00 };
218
219         tls_buffer_append(buf, info, sizeof info);
220 }
221
222 /*
223  * 00 33 - assigned value for extension "Key Share"
224  * 00 26 - 0x26 (38) bytes of "Key Share" extension data follows
225  * 00 24 - 0x24 (36) bytes of key share data follows
226  * 00 1d - assigned value for x25519 (key exchange via curve25519)
227  * 00 20 - 0x20 (32) bytes of public key follows
228  * 35 80 ... 62 54 - public key from the step "Client Key Exchange Generation" 
229  */
230 static void add_key_share_extension(struct tls_buffer *buf, struct TLSContext
231                 *ctx) {
232         char kseid[] = { 0x00, 0x33, 0x00, 0x26, 0x00, 0x24, 0x00, 0x1d, 0x00,
233                 0x20 };
234         char bogus_key[32] = { 0 };
235
236         if (!ctx) {
237                 return;
238         }
239
240         /* TODO figure out where the client key share is */
241         tls_buffer_append(buf, kseid, sizeof kseid);
242         tls_buffer_append(buf, bogus_key, sizeof bogus_key);
243 }
244
245 /*
246  * 00 2d - assigned value for extension "PSK Key Exchange Modes"
247  * 00 02 - 0x2 (2) bytes of "PSK Key Exchange Modes" extension data follows
248  * 01 - 0x1 (1) bytes of exchange modes follow
249  * 01 - assigned value for "PSK with (EC)DHE key establishment" 
250  *
251  * we don't actually pre-share keys here, so ignored, but we'll send it
252  * anyway
253  */
254 /* TODO probably need to get these from the context */
255 static void add_pks_key_exchanges_modes_extension(struct tls_buffer *buf) {
256         char psk[] = { 0x00, 0x2d, 0x00, 0x02, 0x01, 0x01 };
257
258         tls_buffer_append(buf, psk, sizeof psk);
259 }
260
261 static void set_handshake_header(char *buf, int type, size_t length) {
262         buf[0] = type & 0xff;
263         buf[1] = (length >> 16) & 0xff;
264         buf[2] = (length >> 8) & 0xff;
265         buf[3] = (length >> 0) & 0xff;
266 }
267
268 int tls_client_hello(struct TLSContext *ctx, struct tls_buffer *hello) {
269         size_t hello_offset = hello->len;
270
271         /* make room for the handshake header */
272         tls_buffer_expand(hello, 4);
273         hello->len += 4;
274
275         /* actual client hello structure follows */
276
277         tls_buffer_append(hello, "\x03\x03", 2); /* legacy_version */
278         /* random not set up yet */
279         //tls_random(ctx->local_random, 32);
280         tls_buffer_append(hello, ctx->local_random, 32); /* client random */
281         tls_buffer_append(hello, "\0", 1); /* legacy_session_id */
282         /* alternatively, append a 32 (0x20) and 32 random bytes as a bogus
283          * session id */
284
285         /*
286          * cipher suites
287          * TODO need a way to only use v1.3
288          */
289         int suites = TLS12_FLAG; /* always use v1.2 suites */
290
291         if (ctx->tlsver == TLS_VERSION13) {
292                 suites |= TLS13_FLAG;
293         }
294         add_cipher_suites(hello, suites);
295
296         /* legacy_compression_methods */
297         tls_buffer_append(hello, "\1\0", 2);
298         
299         /* 
300          * extensions
301          * TODO I don't think the extension order matters, so the code below
302          * can be simplified by putting all the extensions together by version
303          */
304         size_t extensions_start = hello->len;
305         /* first two bytes are length of extensions, so make room to fill them
306          * in once we know the size
307          */
308         tls_buffer_append(hello, "\0\0", 2);
309
310         /* TODO need to track which extensions we're sending:
311          * "If a client receives an extension type in ServerHello that it did
312          * not request in the associated ClientHello, it MUST abort the
313          * handshake with an unsupported_extension fatal alert."
314          */
315         add_sni_extension(hello, ctx->sni); /* server name indicator */
316
317 #if 0
318         /* TODO not sure why 1.3 doesn't need or want this */
319         /* TODO duckduckgo.com seems to fail with this one */
320         if (ctx->tlsver == TLS_VERSION12) {
321                 add_status_request_extension(hello);
322         }
323 #endif
324
325         add_supported_groups_extension(hello);
326
327         /* v1.2 only, points are fixed in v1.3 */
328         if (ctx->tlsver == TLS_VERSION12) {
329                 add_ec_point_formats_extension(hello);
330         }
331
332         add_signature_algorithms_extension(hello);
333
334         if (ctx->tlsver == TLS_VERSION13) {
335                 add_key_share_extension(hello, ctx);
336                 add_pks_key_exchanges_modes_extension(hello);
337         }
338
339         /* v1.2 only, 1.3 doesn't support renegotiation
340          * and doesn't seem to need cert ts
341          */
342         if (ctx->tlsver == TLS_VERSION12) {
343                 add_renegotiation_info_extension(hello);
344                 add_signed_certificate_timestamp_extension(hello);
345         }
346
347         if (ctx->tlsver == TLS_VERSION13) {
348                 /* supported versions is mandatory in V1.3 */
349                 /* 1 v1.2 only, 2 = v1.3 only, 3 = both */
350                 /* TODO need a context flag to allow fallback to v1.2 */
351                 /* could probably pass this in v1.2 and the server
352                  * would ignore it */
353                 add_supported_versions(hello, 3);
354         }
355
356         /* set the extensions length */
357         size_t extensions_length = hello->len - extensions_start - 2;
358         tls_buffer_write16(hello, extensions_length, extensions_start);
359
360         /* fill in the handshake header */
361         size_t hello_length = hello->len - hello_offset - 4;
362         set_handshake_header(hello->buffer+hello_offset, client_hello,
363                         hello_length);
364
365         tls_buffer_compact(hello);
366         return hello->error;
367 }
368
369 #if 0
370 void pbytes(unsigned char *b, size_t len, char *label) {
371         size_t i;
372
373         fprintf(stderr, "%s (%zu bytes)\n", label ? label : "dumping", len);
374
375         for (i=0; i<len; i++) {
376                 fprintf(stderr, "%s%02x%s",
377                                 i % 20 ? " " : "",
378                                 b[i],
379                                 (i+1) % 20 ? "" : "\n"
380                        );
381         }
382         if (i%20) {
383                 fprintf(stderr, "\n");
384         }
385 }
386 #endif
387
388 struct TLSPacket *tls_build_client_hello(struct TLSContext *context) {
389         if (context->connection_status == 4) {
390                 unsigned char header[4] = { 0xFE, 0, 0, 0 };
391                 unsigned char hash[TLS_MAX_SHA_SIZE];
392                 static unsigned char sha256_helloretryrequest[] =
393                     { 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, 0xBE,
394                         0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91, 0xC2,
395                         0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E, 0x07,
396                         0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C
397                 };
398                 fprintf(stderr, "got hello retry request\n");
399                 memcpy(context->local_random, sha256_helloretryrequest, 32);
400                 int hash_len = tls_done_hash(context, hash);
401                 header[3] = (unsigned char) hash_len;
402                 tls_update_hash(context, header, sizeof header);
403                 tls_update_hash(context, hash, hash_len);
404         } else if (context->tlsver != TLS_VERSION13) {
405                 //fprintf(stderr, "creating local_random\n");
406                 if (!tls_random(context->local_random, TLS_SERVER_RANDOM_SIZE)) {
407                         return NULL;
408                 }
409         }
410
411         struct tls_buffer shadow;
412         char record_header[] = { 0x16, 0x03, 0x03, 0x00, 0x00 };
413
414         tls_buffer_init(&shadow, 106);
415         tls_buffer_append(&shadow, record_header, sizeof record_header);
416         tls_client_hello(context, &shadow);
417         tls_buffer_writebe(&shadow, 3, 6, shadow.len - 9);
418
419         if (shadow.error) {
420                 tls_buffer_free(&shadow);
421                 return NULL;
422         }
423
424         struct TLSPacket *packet = malloc(sizeof *packet);
425
426         if (!packet) {
427                 return NULL;
428         }
429
430         free(packet->buf);
431         packet->buf = shadow.buffer;
432         packet->len = shadow.len;
433         packet->size = shadow.size;
434         packet->payload_pos = 0;
435         packet->broken = 0;
436         packet->context = context;
437
438         tls_packet_update(packet);
439
440         return packet;
441 }
442
443 int tls_send_client_hello(struct TLSContext *ctx) {
444         return ctx ? 1 : 0;
445 }
446
447 struct TLSPacket *tls_build_hello(struct TLSContext *context,
448                                   int tls13_downgrade) {
449         if (context->connection_status == 4) {
450                 unsigned char header[4] = { 0xFE, 0, 0, 0 };
451                 unsigned char hash[TLS_MAX_SHA_SIZE];
452                 static unsigned char sha256_helloretryrequest[] =
453                     { 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, 0xBE,
454                         0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91, 0xC2,
455                         0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E, 0x07,
456                         0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C
457                 };
458                 fprintf(stderr, "got hello retry request\n");
459                 memcpy(context->local_random, sha256_helloretryrequest, 32);
460                 int hash_len = tls_done_hash(context, hash);
461                 header[3] = (unsigned char) hash_len;
462                 tls_update_hash(context, header, sizeof header);
463                 tls_update_hash(context, hash, hash_len);
464         } else if (!context->is_server || context->tlsver != TLS_VERSION13) {
465                 fprintf(stderr, "creating local_random\n");
466                 if (!tls_random(context->local_random, TLS_SERVER_RANDOM_SIZE)) {
467                         return NULL;
468                 }
469         }
470
471         if (context->is_server && tls13_downgrade) {
472                 if (tls13_downgrade == TLS_V12 || tls13_downgrade == DTLS_V12)
473                 {
474                         memcpy(context->local_random +
475                                TLS_SERVER_RANDOM_SIZE - 8, "DOWNGRD\x01",
476                                8);
477                 } else {
478                         memcpy(context->local_random +
479                                TLS_SERVER_RANDOM_SIZE - 8, "DOWNGRD\x00",
480                                8);
481                 }
482         }
483
484         if (!context->is_server) {
485                 struct tls_buffer shadow;
486                 char record_header[] = { 0x16, 0x03, 0x03, 0x00, 0x00 };
487
488                 tls_buffer_init(&shadow, 106);
489                 tls_buffer_append(&shadow, record_header, sizeof record_header);
490                 tls_client_hello(context, &shadow);
491                 tls_buffer_writebe(&shadow, 3, 6, shadow.len - 9);
492
493                 if (shadow.error) {
494                         tls_buffer_free(&shadow);
495                         return NULL;
496                 }
497
498                 struct TLSPacket *packet = malloc(sizeof *packet);
499
500                 if (!packet) {
501                         return NULL;
502                 }
503
504                 free(packet->buf);
505                 packet->buf = shadow.buffer;
506                 packet->len = shadow.len;
507                 packet->size = shadow.size;
508                 packet->payload_pos = 0;
509                 packet->broken = 0;
510                 packet->context = context;
511
512                 tls_packet_update(packet);
513
514                 fprintf(stderr, "returning packet\n");
515                 return packet;
516         }
517
518         /* context must be server from here on out */
519
520         unsigned short packet_version = context->version;
521         unsigned short version = context->version;
522
523         if (context->version == TLS_V13) {
524                 version = TLS_V12;
525         } else if (context->version == DTLS_V13) {
526                 version = DTLS_V12;
527         }
528
529         struct TLSPacket *packet =
530                 tls_create_packet(context, TLS_HANDSHAKE, packet_version, 0);
531
532         /* hello */
533         tls_packet_uint8(packet, server_hello);
534
535         tls_packet_uint24(packet, 0);
536
537         int start_len = packet->len;
538         tls_packet_uint16(packet, version);
539
540         tls_packet_append(packet, context->local_random,
541                         TLS_SERVER_RANDOM_SIZE);
542
543         /* session size, always 0, we don't support sessions */
544         tls_packet_uint8(packet, 0);
545
546         int extension_len = 0;
547         int alpn_len = 0;
548         int alpn_negotiated_len = 0;
549         unsigned char shared_key[TLS_MAX_RSA_KEY];
550         unsigned long shared_key_len = TLS_MAX_RSA_KEY;
551         unsigned short shared_key_short = 0;
552         int selected_group = 0;
553         if (context->tlsver == TLS_VERSION13) {
554                 if (context->curve == &curve25519) {
555                         extension_len += 8 + 32;
556                         shared_key_short = (unsigned short) 32;
557                         if (context->finished_key) {
558                                 memcpy(shared_key,
559                                                 context->
560                                                 finished_key, 32);
561                                 free(context->finished_key);
562                                 context->finished_key = NULL;
563                         }
564                         selected_group = context->curve->iana;
565                         /* make context->curve NULL (x25519 is a different implementation) */
566                         context->curve = NULL;
567                 } else if (context->ecc_dhe) {
568                         if (ecc_ansi_x963_export
569                                         (context->ecc_dhe, shared_key,
570                                          &shared_key_len)) {
571                                 DEBUG_PRINT
572                                         ("Error exporting ECC DHE key\n");
573                                 tls_destroy_packet(packet);
574                                 tls_alert(context, 1, internal_error);
575                                 return NULL;
576                         }
577                         tls_ecc_dhe_free(context);
578                         extension_len += 8 + shared_key_len;
579                         shared_key_short =
580                                 (uint16_t)shared_key_len;
581                         if (context->curve) {
582                                 selected_group =
583                                         context->curve->iana;
584                         }
585                 } else if (context->dhe) {
586                         selected_group = context->dhe->iana;
587                         tls_dh_export_Y(shared_key,
588                                         &shared_key_len,
589                                         context->dhe);
590                         tls_dhe_free(context);
591                         extension_len += 8 + shared_key_len;
592                         shared_key_short = shared_key_len;
593                 }
594
595                 extension_len += 6;
596         }
597
598         if (context->negotiated_alpn && context->tlsver != TLS_VERSION13) {
599                 alpn_negotiated_len = strlen(context->negotiated_alpn);
600                 alpn_len = alpn_negotiated_len + 1;
601                 extension_len += alpn_len + 6;
602         }
603
604         /* ciphers */
605         /* fallback ... this should never happen */
606         if (!context->cipher) {
607                 context->cipher = TLS_DHE_RSA_WITH_AES_128_CBC_SHA;
608         }
609
610         tls_packet_uint16(packet, context->cipher);
611         /* no compression */
612         tls_packet_uint8(packet, 0);
613
614         if (context->tlsver == TLS_VERSION13) {
615                 /* supported versions */
616                 tls_packet_uint16(packet, 0x2B);
617
618                 tls_packet_uint16(packet, 2);
619                 if (context->version == TLS_V13) {
620                         tls_packet_uint16(packet,
621                                         context-> tls13_version ?
622                                         context-> tls13_version :
623                                         TLS_V13);
624                 } else {
625                         tls_packet_uint16(packet, context->version);
626                 }
627
628                 if (context->connection_status == 4) {
629                         /* fallback to the mandatory secp256r1 */
630                         tls_packet_uint16(packet, 0x33);
631                         tls_packet_uint16(packet, 2);
632                         tls_packet_uint16(packet, (uint16_t) secp256r1.iana);
633                 }
634
635                 if (shared_key_short && selected_group) {
636                         /* key share */
637                         tls_packet_uint16(packet, 0x33);
638                         tls_packet_uint16(packet, shared_key_short + 4);
639                         tls_packet_uint16(packet, selected_group);
640                         tls_packet_uint16(packet, shared_key_short);
641                         tls_packet_append(packet, (unsigned char *) shared_key,
642                                         shared_key_short);
643                 }
644         }
645
646         if (!packet->broken && packet->buf) {
647                 tls_set_packet_length(packet, packet->len - start_len);
648         }
649
650         tls_packet_update(packet);
651
652         return packet;
653 }
654
655 struct TLSPacket *tls_buffer_packet(struct tls_buffer *b, struct TLSContext *c) {
656         struct TLSPacket *p = 0;
657
658         if (b && c) {
659                 p = tls_create_packet(c, TLS_HANDSHAKE, c->version, 0);
660
661                 if (p) {
662                         free(p->buf);
663                         p->buf = b->buffer;
664                         p->size = b->size;
665                         p->len = b->len;
666                         p->payload_pos = 0;
667                         p->broken = 0;
668                         p->context = c;
669                 } else {
670                         tls_buffer_free(b);
671                 }
672         }
673
674         return p;
675 }
676
677 static void append_dhe(struct TLSContext *ctx, struct tls_buffer *buf) {
678         unsigned char dh_Ys[0xFFF];
679         unsigned char dh_p[0xFFF];
680         unsigned char dh_g[0xFFF];
681         unsigned long dh_p_len = sizeof dh_p;
682         unsigned long dh_g_len = sizeof dh_g;
683         unsigned long dh_Ys_len = sizeof dh_Ys;
684
685         if (tls_dh_export_pqY(dh_p, &dh_p_len, dh_g, &dh_g_len, dh_Ys,
686                                 &dh_Ys_len, ctx->dhe)) {
687                 DEBUG_PRINT("ERROR EXPORTING DHE KEY %p\n", ctx->dhe);
688                 buf->error = 1;
689                 tls_dhe_free(ctx);
690                 return;
691         }
692
693         tls_dhe_free(ctx);
694
695         DEBUG_DUMP_HEX_LABEL("Yc", dh_Ys, dh_Ys_len);
696
697         tls_buffer_append24(buf, dh_Ys_len + 2);
698
699         tls_buffer_append16(buf, dh_Ys_len);
700         tls_buffer_append(buf, dh_Ys, dh_Ys_len);
701 }
702
703 static void append_ecdhe(struct TLSContext *ctx, struct tls_buffer *buf) {
704         unsigned char out[TLS_MAX_RSA_KEY];
705         unsigned long out_len = TLS_MAX_RSA_KEY;
706
707         //fprintf(stderr, "ecc dhe\n");
708
709         if (ecc_ansi_x963_export(ctx->ecc_dhe, out, &out_len)) {
710                 DEBUG_PRINT("Error exporting ECC key\n");
711                 buf->error = 1;
712         }
713
714         tls_ecc_dhe_free(ctx);
715
716         tls_buffer_append_byte(buf, 0x10);
717         tls_buffer_append24(buf, out_len + 1);
718
719         tls_buffer_append_byte(buf, out_len);
720         tls_buffer_append(buf, out, out_len);
721 }
722
723 static void set_record_size(struct tls_buffer *b) {
724         uint16_t size;
725
726         size = b->len - 5;
727         tls_buffer_write16(b, size, 3);
728 }
729
730 struct TLSPacket *tls_client_key_exchange(struct TLSContext *context) {
731         struct tls_buffer cke;
732         struct TLSPacket *p;
733
734         tls_buffer_init(&cke, 42);
735         tls_buffer_append_byte(&cke, 0x16);
736         tls_buffer_append16(&cke, 0x0303);
737         tls_buffer_append16(&cke, 0); /* record size placeholder */
738
739         if (context->ecc_dhe) {
740                 append_ecdhe(context, &cke);
741         } else {
742                 append_dhe(context, &cke);
743         }
744         set_record_size(&cke);
745
746         p = tls_buffer_packet(&cke, context);
747
748         tls_compute_key(context, 48);
749         context->connection_status = 2;
750         tls_packet_update(p);
751
752         return p;
753 }
754
755 static int tls_build_random(struct TLSPacket *packet) {
756         int res = 0;
757         unsigned char rand_bytes[48];
758         int bytes = 48;
759
760         if (!tls_random(rand_bytes, bytes)) {
761                 return TLS_GENERIC_ERROR;
762         }
763
764         /* max supported version */
765         if (packet->context->is_server) {
766                 *(unsigned short *) rand_bytes =
767                     htons(packet->context->version);
768         } else {
769                 *(unsigned short *) rand_bytes = htons(TLS_V12);
770         }
771
772         /* DEBUG_DUMP_HEX_LABEL("PREMASTER KEY", rand_bytes, bytes); */
773
774         free(packet->context->premaster_key);
775
776         packet->context->premaster_key = malloc(bytes);
777         if (!packet->context->premaster_key) {
778                 return TLS_NO_MEMORY;
779         }
780
781         packet->context->premaster_key_len = bytes;
782         memcpy(packet->context->premaster_key, rand_bytes,
783                packet->context->premaster_key_len);
784
785         unsigned int out_len;
786
787         unsigned char *random = encrypt_rsa(packet->context,
788                         packet->context->premaster_key,
789                         packet->context->premaster_key_len, &out_len);
790
791         tls_compute_key(packet->context, bytes);
792         if (random && out_len > 2) {
793                 tls_packet_uint24(packet, out_len + 2);
794                 tls_packet_uint16(packet, out_len);
795                 tls_packet_append(packet, random, out_len);
796         } else {
797                 res = TLS_GENERIC_ERROR;
798         }
799
800         free(random);
801
802         if (res) {
803                 return res;
804         }
805
806         return out_len + 2;
807 }
808
809 void tls_send_client_key_exchange(struct TLSContext *context) {
810         struct TLSPacket *packet;
811
812         int ephemeral = tls_cipher_is_ephemeral(context);
813
814         if (ephemeral && context->premaster_key && context->premaster_key_len) {
815                 //fprintf(stderr, "YYYY\n");
816                 packet = tls_client_key_exchange(context);
817                 tls_queue_packet(packet);
818                 return;
819                 if (ephemeral == 1) {
820                         /* dhe */
821                 } else if (context->ecc_dhe) {
822                         /* ecc dhe */
823                 }
824         } else {
825                 /* TODO should never happen, should always require
826                  * either DHE or ECC DHE */
827                 fprintf(stderr, "ZZZZ build random\n");
828                 return;
829                 packet = tls_create_packet(context, TLS_HANDSHAKE, context->version, 0);
830                 tls_packet_uint8(packet, 0x10);
831                 tls_build_random(packet);
832         }
833         context->connection_status = 2;
834         tls_packet_update(packet);
835         tls_queue_packet(packet);
836         return;
837 }
838
839 static uint32_t get24(const unsigned char *buf) {
840         return (*buf << 16) + (*(buf+1) << 8) + *(buf+2);
841 }
842
843 static uint16_t get16(const unsigned char *buf) {
844         return (*(buf) << 8) + *(buf+1);
845 }
846
847 int tls_hello_complete(const unsigned char *buf, size_t len) {
848         size_t more;
849
850         if (len < 3) {
851                 return 0;
852         }
853
854         more = get16(buf);
855         if (more > len - 3) {
856                 fprintf(stderr, "%s:%d\n", __func__, __LINE__);
857                 fprintf(stderr, "have %zu, want %zu\n", len, more);
858                 return 0;
859         }
860         return 1;
861 }
862
863 int tls_parse_server_hello(struct TLSContext *ctx, const unsigned char *buf, size_t len) {
864         size_t i = 0;
865         size_t more = 0;
866
867         if (ctx->connection_status != 0 && ctx->connection_status != 4) {
868                 return TLS_UNEXPECTED_MESSAGE;
869         }
870
871         if (!tls_hello_complete(buf, len)) {
872                 return TLS_NEED_MORE_DATA;
873         }
874
875         /* 3 bytes server hello data size */
876         more = get24(buf+i);
877         i+=3;
878         /* TODO check size reported vs actual */
879
880         /* two bytes server version */
881         uint16_t server_ver = get16(buf+i);
882         i+=2;
883         if (server_ver != ctx->version) {
884                 /* TODO allow (or not) downgrade to v1.2 */
885                 return TLS_UNEXPECTED_MESSAGE;
886         }
887
888         /* 32 bytes server random */
889         memcpy(ctx->remote_random, buf+i, 32);
890         i+=32;
891
892         /* 1 byte of session id length */
893         uint8_t session_len = *(buf+i);
894         i+=1;
895
896         char *session_id;
897         /* possible session id bytes */
898         /* TODO skip? we don't actually use session ids */
899         if (session_len) {
900                 session_id = malloc(session_len);
901                 if (!session_id) {
902                         return 0;
903                 }
904
905                 memcpy(session_id, buf+i, session_len);
906         }
907         i+=session_len;
908
909         /* two bytes cipher suite selected */
910         ctx->cipher = get16(buf+i);
911         i+=2;
912         if (!tls_cipher_supported(ctx, ctx->cipher)) {
913                 ctx->cipher = 0;
914                 DEBUG_PRINT("NO CIPHER SUPPORTED\n");
915                 return TLS_NO_COMMON_CIPHER;
916         }
917
918         /* one byte compression method */
919         uint8_t compression_method = *(buf+i);
920         i++;
921         if (compression_method != 0) {
922                 return 0;
923         }
924
925         if (i > 0 && ctx->connection_status != 4) {
926                 ctx->connection_status = 1;
927         }
928
929         if (i+2 > len) {
930                 /* no extensions */
931                 return 0;
932         }
933
934         /* two bytes extensions length */
935         uint16_t extensions_length = get16(buf+i);
936         i+=2;
937
938         if (extensions_length + i != len) {
939                 /* mismatch */
940                 return 0;
941         }
942
943         /* extensions */
944         while (i+5 <= len) {
945                 int etype = get16(buf+i);
946                 i+=2;
947
948                 /* TODO check that extension type is in the list of
949                  * extensions we sent, if not, abort with
950                  * unsupported_extension fatal alert
951                  */
952                 uint16_t elen = get16(buf+i);
953                 i+=2;
954                 if (elen == 0) {
955                         continue;
956                 }
957                 if (i+elen > len) {
958                         return TLS_BROKEN_PACKET;
959                 }
960
961                 uint16_t sni_len;
962                 uint16_t alpn_len;
963                 const unsigned char *alpn;
964                 unsigned char alpn_size;
965                 int alpn_pos = 0;
966                 uint16_t group_len, iana_n;
967                 int j = i;
968                 int selected = 0;
969
970                 switch (etype) {
971                         case 0x0000:
972                                 sni_len = get16(buf+i);
973                                 if (sni_len) {
974                                         ctx->sni = malloc(sni_len + 1);
975                                         memcpy(ctx->sni, buf+i+2, sni_len);
976                                         ctx->sni[sni_len] = 0;
977                                 }
978                                 break;
979                         case 0x000a: /* supported groups */
980                                 fprintf(stderr, "supported groups\n");
981                                 /* supported groups */
982                                 if (i+2 > len) {
983                                         return TLS_BROKEN_PACKET;
984                                 }
985
986                                 group_len = get16(buf+i);
987                                 for (j = i; i < i + group_len+2; i+=2) {
988                                         iana_n = get16(buf+j);
989                                         switch (iana_n) {
990                                                 case 23:
991                                                         ctx->curve = &secp256r1;
992                                                         selected = 1;
993                                                         break;
994                                                 case 24:
995                                                         ctx->curve = &secp384r1;
996                                                         selected = 1;
997                                                         break;
998                                                 case 29:
999                                                         ctx->curve = &curve25519;
1000                                                         selected = 1;
1001                                                         break;
1002                                                 case 25:
1003                                                         ctx->curve = &secp521r1;
1004                                                         selected = 1;
1005                                                         break;
1006                                         }
1007                                 }
1008                                 /* if ctx->curve */
1009                                 if (selected) {
1010                                         fprintf(stderr, "SELECTED CURVE %s\n",
1011                                                  ctx->curve->name);
1012                                 }
1013                         case 0x0010:
1014                                 if (!ctx->alpn || ctx->alpn_count == 0) {
1015                                         break;
1016                                 }
1017                                 if (i+2 > len) {
1018                                         return TLS_BROKEN_PACKET;
1019                                 }
1020
1021                                 alpn_len = get16(buf+i);
1022
1023                                 if (alpn_len == 0 || alpn_len > elen - 2) {
1024                                         /* TODO broken */
1025                                         break;
1026                                 }
1027                                 /* a server's alpn list "must contain exactly
1028                                  * one "ProtocolName"
1029                                  */
1030                                 alpn_size = buf[i + 2];
1031                                 alpn = buf + i + 3;
1032                                 if (i + alpn_size + 3 < len) {
1033                                         break;
1034                                 }
1035
1036                                 if (!tls_alpn_contains(ctx, (char *)alpn, alpn_size)) {
1037                                         break;
1038                                 }
1039                                 free(ctx->negotiated_alpn);
1040                                 ctx->negotiated_alpn = malloc(alpn_size + 1);
1041                                 if (ctx->negotiated_alpn) {
1042                                         memcpy(ctx->negotiated_alpn,
1043                                                         &alpn[alpn_pos],
1044                                                         alpn_size);
1045                                         ctx->negotiated_alpn[alpn_size] = 0;
1046                                 }
1047                                 break;
1048                         case 0xff01: /* renegotiation info */
1049                                 //fprintf(stderr, "renegotiation info\n");
1050                                 /* ignore, we don't support renegotiation */
1051                                 break;
1052                         case 0x0033: /* key share */
1053                                 /* TODO parse key share */
1054                                 fprintf(stderr, "key share info\n");
1055                                 break;
1056                         case 0x000b:
1057                                 /* signature algorithms */
1058                                 break;
1059                         case 0x002b: /* supported versions */
1060                                 /* should be two bytes of 0x00 0x02
1061                                  * indicating two bytes of server version
1062                                  * then 0x03 0x04 for v1.3
1063                                  */
1064                                 fprintf(stderr, "supported versions\n");
1065                                 break;
1066                         default:
1067                                 fprintf(stderr, "unknown extension %04x\n", etype);
1068                                 break;
1069                 }
1070                 i+=elen;
1071         }
1072
1073 #if 0
1074         if (ctx->connection_status != 4) {
1075                 ctx->connection_status = 1;
1076         }
1077 #endif
1078
1079         return 1;
1080 }