]> pd.if.org Git - zpackage/blob - crypto/handshake.c
ed81920629e6f6287c191cb40cd1f19a929b85ea
[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         packet->buf = shadow.buffer;
431         packet->len = shadow.len;
432         packet->size = shadow.size;
433         packet->payload_pos = 0;
434         packet->broken = 0;
435         packet->context = context;
436
437         tls_packet_update(packet);
438
439         return packet;
440 }
441
442 int tls_send_client_hello(struct TLSContext *ctx) {
443         return ctx ? 1 : 0;
444 }
445
446 struct TLSPacket *tls_build_hello(struct TLSContext *context,
447                                   int tls13_downgrade) {
448         if (context->connection_status == 4) {
449                 unsigned char header[4] = { 0xFE, 0, 0, 0 };
450                 unsigned char hash[TLS_MAX_SHA_SIZE];
451                 static unsigned char sha256_helloretryrequest[] =
452                     { 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, 0xBE,
453                         0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91, 0xC2,
454                         0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E, 0x07,
455                         0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C
456                 };
457                 fprintf(stderr, "got hello retry request\n");
458                 memcpy(context->local_random, sha256_helloretryrequest, 32);
459                 int hash_len = tls_done_hash(context, hash);
460                 header[3] = (unsigned char) hash_len;
461                 tls_update_hash(context, header, sizeof header);
462                 tls_update_hash(context, hash, hash_len);
463         } else if (!context->is_server || context->tlsver != TLS_VERSION13) {
464                 fprintf(stderr, "creating local_random\n");
465                 if (!tls_random(context->local_random, TLS_SERVER_RANDOM_SIZE)) {
466                         return NULL;
467                 }
468         }
469
470         if (context->is_server && tls13_downgrade) {
471                 if (tls13_downgrade == TLS_V12 || tls13_downgrade == DTLS_V12)
472                 {
473                         memcpy(context->local_random +
474                                TLS_SERVER_RANDOM_SIZE - 8, "DOWNGRD\x01",
475                                8);
476                 } else {
477                         memcpy(context->local_random +
478                                TLS_SERVER_RANDOM_SIZE - 8, "DOWNGRD\x00",
479                                8);
480                 }
481         }
482
483         if (!context->is_server) {
484                 struct tls_buffer shadow;
485                 char record_header[] = { 0x16, 0x03, 0x03, 0x00, 0x00 };
486
487                 tls_buffer_init(&shadow, 106);
488                 tls_buffer_append(&shadow, record_header, sizeof record_header);
489                 tls_client_hello(context, &shadow);
490                 tls_buffer_writebe(&shadow, 3, 6, shadow.len - 9);
491
492                 if (shadow.error) {
493                         tls_buffer_free(&shadow);
494                         return NULL;
495                 }
496
497                 struct TLSPacket *packet = malloc(sizeof *packet);
498
499                 if (!packet) {
500                         return NULL;
501                 }
502
503                 free(packet->buf);
504                 packet->buf = shadow.buffer;
505                 packet->len = shadow.len;
506                 packet->size = shadow.size;
507                 packet->payload_pos = 0;
508                 packet->broken = 0;
509                 packet->context = context;
510
511                 tls_packet_update(packet);
512
513                 fprintf(stderr, "returning packet\n");
514                 return packet;
515         }
516
517         /* context must be server from here on out */
518
519         unsigned short packet_version = context->version;
520         unsigned short version = context->version;
521
522         if (context->version == TLS_V13) {
523                 version = TLS_V12;
524         } else if (context->version == DTLS_V13) {
525                 version = DTLS_V12;
526         }
527
528         struct TLSPacket *packet =
529                 tls_create_packet(context, TLS_HANDSHAKE, packet_version, 0);
530
531         /* hello */
532         tls_packet_uint8(packet, server_hello);
533
534         tls_packet_uint24(packet, 0);
535
536         int start_len = packet->len;
537         tls_packet_uint16(packet, version);
538
539         tls_packet_append(packet, context->local_random,
540                         TLS_SERVER_RANDOM_SIZE);
541
542         /* session size, always 0, we don't support sessions */
543         tls_packet_uint8(packet, 0);
544
545         int extension_len = 0;
546         int alpn_len = 0;
547         int alpn_negotiated_len = 0;
548         unsigned char shared_key[TLS_MAX_RSA_KEY];
549         unsigned long shared_key_len = TLS_MAX_RSA_KEY;
550         unsigned short shared_key_short = 0;
551         int selected_group = 0;
552         if (context->tlsver == TLS_VERSION13) {
553                 if (context->curve == &curve25519) {
554                         extension_len += 8 + 32;
555                         shared_key_short = (unsigned short) 32;
556                         if (context->finished_key) {
557                                 memcpy(shared_key,
558                                                 context->
559                                                 finished_key, 32);
560                                 free(context->finished_key);
561                                 context->finished_key = NULL;
562                         }
563                         selected_group = context->curve->iana;
564                         /* make context->curve NULL (x25519 is a different implementation) */
565                         context->curve = NULL;
566                 } else if (context->ecc_dhe) {
567                         if (ecc_ansi_x963_export
568                                         (context->ecc_dhe, shared_key,
569                                          &shared_key_len)) {
570                                 DEBUG_PRINT
571                                         ("Error exporting ECC DHE key\n");
572                                 tls_destroy_packet(packet);
573                                 tls_alert(context, 1, internal_error);
574                                 return NULL;
575                         }
576                         tls_ecc_dhe_free(context);
577                         extension_len += 8 + shared_key_len;
578                         shared_key_short =
579                                 (uint16_t)shared_key_len;
580                         if (context->curve) {
581                                 selected_group =
582                                         context->curve->iana;
583                         }
584                 } else if (context->dhe) {
585                         selected_group = context->dhe->iana;
586                         tls_dh_export_Y(shared_key,
587                                         &shared_key_len,
588                                         context->dhe);
589                         tls_dhe_free(context);
590                         extension_len += 8 + shared_key_len;
591                         shared_key_short = shared_key_len;
592                 }
593
594                 extension_len += 6;
595         }
596
597         if (context->negotiated_alpn && context->tlsver != TLS_VERSION13) {
598                 alpn_negotiated_len = strlen(context->negotiated_alpn);
599                 alpn_len = alpn_negotiated_len + 1;
600                 extension_len += alpn_len + 6;
601         }
602
603         /* ciphers */
604         /* fallback ... this should never happen */
605         if (!context->cipher) {
606                 context->cipher = TLS_DHE_RSA_WITH_AES_128_CBC_SHA;
607         }
608
609         tls_packet_uint16(packet, context->cipher);
610         /* no compression */
611         tls_packet_uint8(packet, 0);
612
613         if (context->tlsver == TLS_VERSION13) {
614                 /* supported versions */
615                 tls_packet_uint16(packet, 0x2B);
616
617                 tls_packet_uint16(packet, 2);
618                 if (context->version == TLS_V13) {
619                         tls_packet_uint16(packet,
620                                         context-> tls13_version ?
621                                         context-> tls13_version :
622                                         TLS_V13);
623                 } else {
624                         tls_packet_uint16(packet, context->version);
625                 }
626
627                 if (context->connection_status == 4) {
628                         /* fallback to the mandatory secp256r1 */
629                         tls_packet_uint16(packet, 0x33);
630                         tls_packet_uint16(packet, 2);
631                         tls_packet_uint16(packet, (uint16_t) secp256r1.iana);
632                 }
633
634                 if (shared_key_short && selected_group) {
635                         /* key share */
636                         tls_packet_uint16(packet, 0x33);
637                         tls_packet_uint16(packet, shared_key_short + 4);
638                         tls_packet_uint16(packet, selected_group);
639                         tls_packet_uint16(packet, shared_key_short);
640                         tls_packet_append(packet, (unsigned char *) shared_key,
641                                         shared_key_short);
642                 }
643         }
644
645         if (!packet->broken && packet->buf) {
646                 tls_set_packet_length(packet, packet->len - start_len);
647         }
648
649         tls_packet_update(packet);
650
651         return packet;
652 }
653
654 struct TLSPacket *tls_buffer_packet(struct tls_buffer *b, struct TLSContext *c) {
655         struct TLSPacket *p = 0;
656
657         if (b && c) {
658                 p = tls_create_packet(c, TLS_HANDSHAKE, c->version, 0);
659
660                 if (p) {
661                         free(p->buf);
662                         p->buf = b->buffer;
663                         p->size = b->size;
664                         p->len = b->len;
665                         p->payload_pos = 0;
666                         p->broken = 0;
667                         p->context = c;
668                 } else {
669                         tls_buffer_free(b);
670                 }
671         }
672
673         return p;
674 }
675
676 static void append_dhe(struct TLSContext *ctx, struct tls_buffer *buf) {
677         unsigned char dh_Ys[0xFFF];
678         unsigned char dh_p[0xFFF];
679         unsigned char dh_g[0xFFF];
680         unsigned long dh_p_len = sizeof dh_p;
681         unsigned long dh_g_len = sizeof dh_g;
682         unsigned long dh_Ys_len = sizeof dh_Ys;
683
684         if (tls_dh_export_pqY(dh_p, &dh_p_len, dh_g, &dh_g_len, dh_Ys,
685                                 &dh_Ys_len, ctx->dhe)) {
686                 DEBUG_PRINT("ERROR EXPORTING DHE KEY %p\n", ctx->dhe);
687                 buf->error = 1;
688                 tls_dhe_free(ctx);
689                 return;
690         }
691
692         tls_dhe_free(ctx);
693
694         DEBUG_DUMP_HEX_LABEL("Yc", dh_Ys, dh_Ys_len);
695
696         tls_buffer_append24(buf, dh_Ys_len + 2);
697
698         tls_buffer_append16(buf, dh_Ys_len);
699         tls_buffer_append(buf, dh_Ys, dh_Ys_len);
700 }
701
702 static void append_ecdhe(struct TLSContext *ctx, struct tls_buffer *buf) {
703         unsigned char out[TLS_MAX_RSA_KEY];
704         unsigned long out_len = TLS_MAX_RSA_KEY;
705
706         //fprintf(stderr, "ecc dhe\n");
707
708         if (ecc_ansi_x963_export(ctx->ecc_dhe, out, &out_len)) {
709                 DEBUG_PRINT("Error exporting ECC key\n");
710                 buf->error = 1;
711         }
712
713         tls_ecc_dhe_free(ctx);
714
715         tls_buffer_append_byte(buf, 0x10);
716         tls_buffer_append24(buf, out_len + 1);
717
718         tls_buffer_append_byte(buf, out_len);
719         tls_buffer_append(buf, out, out_len);
720 }
721
722 static void set_record_size(struct tls_buffer *b) {
723         uint16_t size;
724
725         size = b->len - 5;
726         tls_buffer_write16(b, size, 3);
727 }
728
729 struct TLSPacket *tls_client_key_exchange(struct TLSContext *context) {
730         struct tls_buffer cke;
731         struct TLSPacket *p;
732
733         tls_buffer_init(&cke, 42);
734         tls_buffer_append_byte(&cke, 0x16);
735         tls_buffer_append16(&cke, 0x0303);
736         tls_buffer_append16(&cke, 0); /* record size placeholder */
737
738         if (context->ecc_dhe) {
739                 append_ecdhe(context, &cke);
740         } else {
741                 append_dhe(context, &cke);
742         }
743         set_record_size(&cke);
744
745         p = tls_buffer_packet(&cke, context);
746
747         tls_compute_key(context, 48);
748         context->connection_status = 2;
749         tls_packet_update(p);
750
751         return p;
752 }
753
754 static int tls_build_random(struct TLSPacket *packet) {
755         int res = 0;
756         unsigned char rand_bytes[48];
757         int bytes = 48;
758
759         if (!tls_random(rand_bytes, bytes)) {
760                 return TLS_GENERIC_ERROR;
761         }
762
763         /* max supported version */
764         if (packet->context->is_server) {
765                 *(unsigned short *) rand_bytes =
766                     htons(packet->context->version);
767         } else {
768                 *(unsigned short *) rand_bytes = htons(TLS_V12);
769         }
770
771         /* DEBUG_DUMP_HEX_LABEL("PREMASTER KEY", rand_bytes, bytes); */
772
773         free(packet->context->premaster_key);
774
775         packet->context->premaster_key = malloc(bytes);
776         if (!packet->context->premaster_key) {
777                 return TLS_NO_MEMORY;
778         }
779
780         packet->context->premaster_key_len = bytes;
781         memcpy(packet->context->premaster_key, rand_bytes,
782                packet->context->premaster_key_len);
783
784         unsigned int out_len;
785
786         unsigned char *random = encrypt_rsa(packet->context,
787                         packet->context->premaster_key,
788                         packet->context->premaster_key_len, &out_len);
789
790         tls_compute_key(packet->context, bytes);
791         if (random && out_len > 2) {
792                 tls_packet_uint24(packet, out_len + 2);
793                 tls_packet_uint16(packet, out_len);
794                 tls_packet_append(packet, random, out_len);
795         } else {
796                 res = TLS_GENERIC_ERROR;
797         }
798
799         free(random);
800
801         if (res) {
802                 return res;
803         }
804
805         return out_len + 2;
806 }
807
808 void tls_send_client_key_exchange(struct TLSContext *context) {
809         struct TLSPacket *packet;
810
811         int ephemeral = tls_cipher_is_ephemeral(context);
812
813         if (ephemeral && context->premaster_key && context->premaster_key_len) {
814                 //fprintf(stderr, "YYYY\n");
815                 packet = tls_client_key_exchange(context);
816                 tls_queue_packet(packet);
817                 return;
818                 if (ephemeral == 1) {
819                         /* dhe */
820                 } else if (context->ecc_dhe) {
821                         /* ecc dhe */
822                 }
823         } else {
824                 /* TODO should never happen, should always require
825                  * either DHE or ECC DHE */
826                 fprintf(stderr, "ZZZZ build random\n");
827                 return;
828                 packet = tls_create_packet(context, TLS_HANDSHAKE, context->version, 0);
829                 tls_packet_uint8(packet, 0x10);
830                 tls_build_random(packet);
831         }
832         context->connection_status = 2;
833         tls_packet_update(packet);
834         tls_queue_packet(packet);
835         return;
836 }
837
838 static uint32_t get24(const unsigned char *buf) {
839         return (*buf << 16) + (*(buf+1) << 8) + *(buf+2);
840 }
841
842 static uint16_t get16(const unsigned char *buf) {
843         return (*(buf) << 8) + *(buf+1);
844 }
845
846 int tls_hello_complete(const unsigned char *buf, size_t len) {
847         size_t more;
848
849         if (len < 3) {
850                 return 0;
851         }
852
853         more = get16(buf);
854         if (more > len - 3) {
855                 fprintf(stderr, "%s:%d\n", __func__, __LINE__);
856                 fprintf(stderr, "have %zu, want %zu\n", len, more);
857                 return 0;
858         }
859         return 1;
860 }
861
862 int tls_parse_server_hello(struct TLSContext *ctx, const unsigned char *buf, size_t len) {
863         size_t i = 0;
864         size_t more = 0;
865
866         if (ctx->connection_status != 0 && ctx->connection_status != 4) {
867                 return TLS_UNEXPECTED_MESSAGE;
868         }
869
870         if (!tls_hello_complete(buf, len)) {
871                 return TLS_NEED_MORE_DATA;
872         }
873
874         /* 3 bytes server hello data size */
875         more = get24(buf+i);
876         i+=3;
877         /* TODO check size reported vs actual */
878
879         /* two bytes server version */
880         uint16_t server_ver = get16(buf+i);
881         i+=2;
882         if (server_ver != ctx->version) {
883                 /* TODO allow (or not) downgrade to v1.2 */
884                 return TLS_UNEXPECTED_MESSAGE;
885         }
886
887         /* 32 bytes server random */
888         memcpy(ctx->remote_random, buf+i, 32);
889         i+=32;
890
891         /* 1 byte of session id length */
892         uint8_t session_len = *(buf+i);
893         i+=1;
894
895         char *session_id;
896         /* possible session id bytes */
897         /* TODO skip? we don't actually use session ids */
898         if (session_len) {
899                 session_id = malloc(session_len);
900                 if (!session_id) {
901                         return 0;
902                 }
903
904                 memcpy(session_id, buf+i, session_len);
905         }
906         i+=session_len;
907
908         /* two bytes cipher suite selected */
909         ctx->cipher = get16(buf+i);
910         i+=2;
911         if (!tls_cipher_supported(ctx, ctx->cipher)) {
912                 ctx->cipher = 0;
913                 DEBUG_PRINT("NO CIPHER SUPPORTED\n");
914                 return TLS_NO_COMMON_CIPHER;
915         }
916
917         /* one byte compression method */
918         uint8_t compression_method = *(buf+i);
919         i++;
920         if (compression_method != 0) {
921                 return 0;
922         }
923
924         if (i > 0 && ctx->connection_status != 4) {
925                 ctx->connection_status = 1;
926         }
927
928         if (i+2 > len) {
929                 /* no extensions */
930                 return 0;
931         }
932
933         /* two bytes extensions length */
934         uint16_t extensions_length = get16(buf+i);
935         i+=2;
936
937         if (extensions_length + i != len) {
938                 /* mismatch */
939                 return 0;
940         }
941
942         /* extensions */
943         while (i+5 <= len) {
944                 int etype = get16(buf+i);
945                 i+=2;
946
947                 /* TODO check that extension type is in the list of
948                  * extensions we sent, if not, abort with
949                  * unsupported_extension fatal alert
950                  */
951                 uint16_t elen = get16(buf+i);
952                 i+=2;
953                 if (elen == 0) {
954                         continue;
955                 }
956                 if (i+elen > len) {
957                         return TLS_BROKEN_PACKET;
958                 }
959
960                 uint16_t sni_len;
961                 uint16_t alpn_len;
962                 const unsigned char *alpn;
963                 unsigned char alpn_size;
964                 int alpn_pos = 0;
965                 uint16_t group_len, iana_n;
966                 int j = i;
967                 int selected = 0;
968
969                 switch (etype) {
970                         case 0x0000:
971                                 sni_len = get16(buf+i);
972                                 if (sni_len) {
973                                         ctx->sni = malloc(sni_len + 1);
974                                         memcpy(ctx->sni, buf+i+2, sni_len);
975                                         ctx->sni[sni_len] = 0;
976                                 }
977                                 break;
978                         case 0x000a: /* supported groups */
979                                 fprintf(stderr, "supported groups\n");
980                                 /* supported groups */
981                                 if (i+2 > len) {
982                                         return TLS_BROKEN_PACKET;
983                                 }
984
985                                 group_len = get16(buf+i);
986                                 for (j = i; i < i + group_len+2; i+=2) {
987                                         iana_n = get16(buf+j);
988                                         switch (iana_n) {
989                                                 case 23:
990                                                         ctx->curve = &secp256r1;
991                                                         selected = 1;
992                                                         break;
993                                                 case 24:
994                                                         ctx->curve = &secp384r1;
995                                                         selected = 1;
996                                                         break;
997                                                 case 29:
998                                                         ctx->curve = &curve25519;
999                                                         selected = 1;
1000                                                         break;
1001                                                 case 25:
1002                                                         ctx->curve = &secp521r1;
1003                                                         selected = 1;
1004                                                         break;
1005                                         }
1006                                 }
1007                                 /* if ctx->curve */
1008                                 if (selected) {
1009                                         fprintf(stderr, "SELECTED CURVE %s\n",
1010                                                  ctx->curve->name);
1011                                 }
1012                         case 0x0010:
1013                                 if (!ctx->alpn || ctx->alpn_count == 0) {
1014                                         break;
1015                                 }
1016                                 if (i+2 > len) {
1017                                         return TLS_BROKEN_PACKET;
1018                                 }
1019
1020                                 alpn_len = get16(buf+i);
1021
1022                                 if (alpn_len == 0 || alpn_len > elen - 2) {
1023                                         /* TODO broken */
1024                                         break;
1025                                 }
1026                                 /* a server's alpn list "must contain exactly
1027                                  * one "ProtocolName"
1028                                  */
1029                                 alpn_size = buf[i + 2];
1030                                 alpn = buf + i + 3;
1031                                 if (i + alpn_size + 3 < len) {
1032                                         break;
1033                                 }
1034
1035                                 if (!tls_alpn_contains(ctx, (char *)alpn, alpn_size)) {
1036                                         break;
1037                                 }
1038                                 free(ctx->negotiated_alpn);
1039                                 ctx->negotiated_alpn = malloc(alpn_size + 1);
1040                                 if (ctx->negotiated_alpn) {
1041                                         memcpy(ctx->negotiated_alpn,
1042                                                         &alpn[alpn_pos],
1043                                                         alpn_size);
1044                                         ctx->negotiated_alpn[alpn_size] = 0;
1045                                 }
1046                                 break;
1047                         case 0xff01: /* renegotiation info */
1048                                 //fprintf(stderr, "renegotiation info\n");
1049                                 /* ignore, we don't support renegotiation */
1050                                 break;
1051                         case 0x0033: /* key share */
1052                                 /* TODO parse key share */
1053                                 fprintf(stderr, "key share info\n");
1054                                 break;
1055                         case 0x000b:
1056                                 /* signature algorithms */
1057                                 break;
1058                         case 0x002b: /* supported versions */
1059                                 /* should be two bytes of 0x00 0x02
1060                                  * indicating two bytes of server version
1061                                  * then 0x03 0x04 for v1.3
1062                                  */
1063                                 fprintf(stderr, "supported versions\n");
1064                                 break;
1065                         default:
1066                                 fprintf(stderr, "unknown extension %04x\n", etype);
1067                                 break;
1068                 }
1069                 i+=elen;
1070         }
1071
1072 #if 0
1073         if (ctx->connection_status != 4) {
1074                 ctx->connection_status = 1;
1075         }
1076 #endif
1077
1078         return 1;
1079 }