]> pd.if.org Git - zpackage/blob - crypto/tlse.c
fix some todo items
[zpackage] / crypto / tlse.c
1 #define _POSIX_C_SOURCE 200809L
2
3 #include <fcntl.h>
4 #include <stdint.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <strings.h>
9 #include <sys/mman.h>
10 #include <sys/stat.h>
11 #include <time.h>
12
13 #include <sys/socket.h>
14 #include <arpa/inet.h>
15 #include <unistd.h>
16
17 #include <errno.h>
18
19 #include "tomcrypt.h"
20
21 #define mp_init(a)                           ltc_mp.init(a)
22 #define mp_init_multi                        ltc_init_multi
23 #define mp_clear(a)                          ltc_mp.deinit(a)
24 #define mp_clear_multi                       ltc_deinit_multi
25 #define mp_count_bits(a)                     ltc_mp.count_bits(a)
26 #define mp_read_radix(a, b, c)               ltc_mp.read_radix(a, b, c)
27 #define mp_unsigned_bin_size(a)              ltc_mp.unsigned_size(a)
28 #define mp_to_unsigned_bin(a, b)             ltc_mp.unsigned_write(a, b)
29 #define mp_read_unsigned_bin(a, b, c)        ltc_mp.unsigned_read(a, b, c)
30 #define mp_exptmod(a, b, c, d)               ltc_mp.exptmod(a, b, c, d)
31 #define mp_add(a, b, c)                      ltc_mp.add(a, b, c)
32 #define mp_mul(a, b, c)                      ltc_mp.mul(a, b, c)
33 #define mp_cmp(a, b)                         ltc_mp.compare(a, b)
34 #define mp_cmp_d(a, b)                       ltc_mp.compare_d(a, b)
35 #define mp_sqr(a, b)                         ltc_mp.sqr(a, b)
36 #define mp_mod(a, b, c)                      ltc_mp.mpdiv(a, b, NULL, c)
37 #define mp_sub(a, b, c)                      ltc_mp.sub(a, b, c)
38 #define mp_set(a, b)                         ltc_mp.set_int(a, b)
39
40 #if (CRYPT <= 0x0117)
41 #define LTC_PKCS_1_EMSA LTC_LTC_PKCS_1_EMSA
42 #define LTC_PKCS_1_V1_5 LTC_LTC_PKCS_1_V1_5
43 #define LTC_PKCS_1_PSS LTC_LTC_PKCS_1_PSS
44 #endif
45
46 #include "tlse.h"
47 #include "chacha.h"
48 #include "buffer.h"
49
50 #define TLS_DH_DEFAULT_P            "87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597"
51 #define TLS_DH_DEFAULT_G            "3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659"
52 #define TLS_DHE_KEY_SIZE          2048
53
54 #ifndef htonll
55 #define htonll(x) ((1==htonl(1)) ? (x) : ((uint64_t)htonl((x) & 0xFFFFFFFF) << 32) | htonl((x) >> 32))
56 #endif
57
58 #ifndef ntohll
59 #define ntohll(x) ((1==ntohl(1)) ? (x) : ((uint64_t)ntohl((x) & 0xFFFFFFFF) << 32) | ntohl((x) >> 32))
60 #endif
61
62 #define CHECK_HANDSHAKE_STATE(context, n, limit)  { if (context->hs_messages[n] >= limit) { DEBUG_PRINT("* UNEXPECTED MESSAGE (%i)\n", (int)n); payload_res = TLS_UNEXPECTED_MESSAGE; break; } context->hs_messages[n]++; }
63
64 typedef enum {
65         KEA_dhe_dss,
66         KEA_dhe_rsa,
67         KEA_dh_anon,
68         KEA_rsa,
69         KEA_dh_dss,
70         KEA_dh_rsa,
71         KEA_ec_diffie_hellman
72 } KeyExchangeAlgorithm;
73
74 typedef enum {
75         rsa_sign = 1,
76         dss_sign = 2,
77         rsa_fixed_dh = 3,
78         dss_fixed_dh = 4,
79         rsa_ephemeral_dh_RESERVED = 5,
80         dss_ephemeral_dh_RESERVED = 6,
81         fortezza_dms_RESERVED = 20,
82         ecdsa_sign = 64,
83         rsa_fixed_ecdh = 65,
84         ecdsa_fixed_ecdh = 66
85 } TLSClientCertificateType;
86
87 typedef enum {
88         none = 0,
89         md5 = 1,
90         sha1 = 2,
91         sha224 = 3,
92         sha256 = 4,
93         sha384 = 5,
94         sha512 = 6,
95         _md5_sha1 = 255
96 } TLSHashAlgorithm;
97
98 typedef enum {
99         anonymous = 0,
100         rsa = 1,
101         dsa = 2,
102         ecdsa = 3
103 } TLSSignatureAlgorithm;
104
105 struct OID_chain {
106         void *top;
107         unsigned char *oid;
108 };
109
110 typedef ssize_t (*tls_recv_func)(int sockfd, void *buf, size_t len,
111                                  int flags);
112 typedef ssize_t (*tls_send_func)(int sockfd, const void *buf, size_t len,
113                                  int flags);
114
115 static const unsigned int version_id[] = { 1, 1, 1, 0 };
116 static const unsigned int pk_id[] = { 1, 1, 7, 0 };
117 static const unsigned int serial_id[] = { 1, 1, 2, 1, 0 };
118 static const unsigned int issurer_id[] = { 1, 1, 4, 0 };
119 static const unsigned int owner_id[] = { 1, 1, 6, 0 };
120 static const unsigned int validity_id[] = { 1, 1, 5, 0 };
121 static const unsigned int algorithm_id[] = { 1, 1, 3, 0 };
122 static const unsigned int sign_id[] = { 1, 3, 2, 1, 0 };
123 static const unsigned int sign_id2[] = { 1, 3, 2, 2, 0 };
124 static const unsigned int priv_id[] = { 1, 4, 0 };
125 static const unsigned int priv_der_id[] = { 1, 3, 1, 0 };
126 static const unsigned int ecc_priv_id[] = { 1, 2, 0 };
127
128 static const unsigned char country_oid[] = { 0x55, 0x04, 0x06, 0x00 };
129 static const unsigned char state_oid[] = { 0x55, 0x04, 0x08, 0x00 };
130 static const unsigned char location_oid[] = { 0x55, 0x04, 0x07, 0x00 };
131 static const unsigned char entity_oid[] = { 0x55, 0x04, 0x0A, 0x00 };
132 static const unsigned char subject_oid[] = { 0x55, 0x04, 0x03, 0x00 };
133 static const unsigned char san_oid[] = { 0x55, 0x1D, 0x11, 0x00 };
134 static const unsigned char ocsp_oid[] =
135     { 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x01, 0x00 };
136
137 static const unsigned char TLS_RSA_SIGN_RSA_OID[] =
138     { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x00 };
139 static const unsigned char TLS_RSA_SIGN_MD5_OID[] =
140     { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x04, 0x00 };
141 static const unsigned char TLS_RSA_SIGN_SHA1_OID[] =
142     { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x05, 0x00 };
143 static const unsigned char TLS_RSA_SIGN_SHA256_OID[] =
144     { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x00 };
145 static const unsigned char TLS_RSA_SIGN_SHA384_OID[] =
146     { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0C, 0x00 };
147 static const unsigned char TLS_RSA_SIGN_SHA512_OID[] =
148     { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0D, 0x00 };
149
150 #if 0
151 static const unsigned char TLS_ECDSA_SIGN_SHA1_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x01, 0x05, 0x00, 0x00};
152 static const unsigned char TLS_ECDSA_SIGN_SHA224_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x01, 0x05, 0x00, 0x00};
153 static const unsigned char TLS_ECDSA_SIGN_SHA256_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02, 0x05, 0x00, 0x00};
154 static const unsigned char TLS_ECDSA_SIGN_SHA384_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x03, 0x05, 0x00, 0x00};
155 static const unsigned char TLS_ECDSA_SIGN_SHA512_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x04, 0x05, 0x00, 0x00};
156 #endif
157
158 static const unsigned char TLS_EC_PUBLIC_KEY_OID[] =
159     { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01, 0x00 };
160
161 static const unsigned char TLS_EC_prime192v1_OID[] =
162     { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x01, 0x00 };
163 static const unsigned char TLS_EC_prime192v2_OID[] =
164     { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x02, 0x00 };
165 static const unsigned char TLS_EC_prime192v3_OID[] =
166     { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x03, 0x00 };
167 static const unsigned char TLS_EC_prime239v1_OID[] =
168     { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x04, 0x00 };
169 static const unsigned char TLS_EC_prime239v2_OID[] =
170     { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x05, 0x00 };
171 static const unsigned char TLS_EC_prime239v3_OID[] =
172     { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x06, 0x00 };
173 static const unsigned char TLS_EC_prime256v1_OID[] =
174     { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07, 0x00 };
175
176 #define TLS_EC_secp256r1_OID    TLS_EC_prime256v1_OID
177 static const unsigned char TLS_EC_secp224r1_OID[] =
178     { 0x2B, 0x81, 0x04, 0x00, 0x21, 0x00 };
179 static const unsigned char TLS_EC_secp384r1_OID[] =
180     { 0x2B, 0x81, 0x04, 0x00, 0x22, 0x00 };
181 static const unsigned char TLS_EC_secp521r1_OID[] =
182     { 0x2B, 0x81, 0x04, 0x00, 0x23, 0x00 };
183
184 int tls_random(unsigned char *key, int len);
185 void tls_destroy_packet(struct TLSPacket *packet);
186 struct TLSPacket *tls_build_hello(struct TLSContext *context,
187                                   int tls13_downgrade);
188
189 /* not supported */
190 #if 0
191 static unsigned char TLS_DSA_SIGN_SHA1_OID[] = {0x2A, 0x86, 0x52, 0xCE, 0x38, 0x04, 0x03, 0x00};
192 #endif
193
194 static uint16_t get16(const unsigned char *buf) {
195         uint16_t res;
196
197         res = ((*buf) << 8) + (*(buf+1));
198         return res;
199 }
200
201 static uint32_t get24(const unsigned char *buf) {
202         uint32_t res;
203
204         res = (buf[0] << 16) + (buf[1] << 8) + buf[2];
205         return res;
206 }
207
208 size_t tls_queue_packet(struct TLSPacket *packet) {
209         if (!packet) {
210                 return -1;
211         }
212
213         struct TLSContext *context = packet->context;
214
215         if (!context) {
216                 return -1;
217         }
218
219         tls_buffer_append(&context->output_buffer, packet->buf, packet->len);
220         tls_destroy_packet(packet);
221         return context->output_buffer.len;
222 }
223
224 static void tls_send_change_cipher_spec(struct TLSContext *context) {
225         struct TLSPacket *packet =
226             tls_create_packet(context, TLS_CHANGE_CIPHER, context->version,
227                               64);
228         tls_packet_uint8(packet, 1);
229         tls_packet_update(packet);
230         context->local_sequence_number = 0;
231         tls_queue_packet(packet);
232         return;
233 }
234
235 static void tls_send_encrypted_extensions(struct TLSContext *context) {
236         struct TLSPacket *packet =
237             tls_create_packet(context, TLS_HANDSHAKE, context->version, 3);
238         tls_packet_uint8(packet, 0x08);
239
240         if (context->negotiated_alpn) {
241                 int alpn_negotiated_len = strlen(context->negotiated_alpn);
242                 int alpn_len = alpn_negotiated_len + 1;
243
244                 tls_packet_uint24(packet, alpn_len + 8);
245                 tls_packet_uint16(packet, alpn_len + 6);
246                 tls_packet_uint16(packet, 0x10);
247                 tls_packet_uint16(packet, alpn_len + 2);
248                 tls_packet_uint16(packet, alpn_len);
249
250                 tls_packet_uint8(packet, alpn_negotiated_len);
251                 tls_packet_append(packet, (unsigned char *) context->
252                                 negotiated_alpn, alpn_negotiated_len);
253         } else {
254                 tls_packet_uint24(packet, 2);
255                 tls_packet_uint16(packet, 0);
256         }
257         tls_packet_update(packet);
258         tls_queue_packet(packet);
259         return;
260 }
261
262 static void tls_send_done(struct TLSContext *context) {
263         struct TLSPacket *packet =
264             tls_create_packet(context, TLS_HANDSHAKE, context->version, 0);
265         tls_packet_uint8(packet, 0x0E);
266         tls_packet_uint24(packet, 0);
267         tls_packet_update(packet);
268         tls_queue_packet(packet);
269         return;
270 }
271
272 static void tls_send_certificate(struct TLSContext *context) {
273         int i;
274         unsigned int all_certificate_size = 0;
275         int certificates_count;
276         struct TLSCertificate **certificates;
277
278         if (context->is_server) {
279                 certificates_count = context->certificates_count;
280                 certificates = context->certificates;
281         } else {
282                 certificates_count = context->client_certificates_count;
283                 certificates = context->client_certificates;
284         }
285
286         int delta = 3;
287         if (context->tlsver == TLS_VERSION13) {
288                 delta = 5;
289         }
290
291         int is_ecdsa = tls_is_ecdsa(context);
292         /* TODO can do one loop and test for ecdsa inside loop */
293         if (is_ecdsa) {
294                 for (i = 0; i < certificates_count; i++) {
295                         struct TLSCertificate *cert = certificates[i];
296                         if (cert && cert->der_len && cert->ec_algorithm) {
297                                 all_certificate_size += cert->der_len + delta;
298                         }
299                 }
300         } else {
301                 for (i = 0; i < certificates_count; i++) {
302                         struct TLSCertificate *cert = certificates[i];
303                         if (cert && cert->der_len && !cert->ec_algorithm) {
304                                 all_certificate_size += cert->der_len + delta;
305                         }
306                 }
307         }
308
309         for (i = 0; i < certificates_count; i++) {
310                 struct TLSCertificate *cert = certificates[i];
311                 if (cert && cert->der_len) {
312                         all_certificate_size += cert->der_len + delta;
313                 }
314         }
315
316         if (!all_certificate_size) {
317                 DEBUG_PRINT("NO CERTIFICATE SET\n");
318         }
319
320         struct TLSPacket *packet = tls_create_packet(context, TLS_HANDSHAKE,
321                         context->version, 0);
322         tls_packet_uint8(packet, 0x0B);
323
324         if (all_certificate_size) {
325                 /* context */
326                 if (context->tlsver == TLS_VERSION13) {
327                         tls_packet_uint24(packet, all_certificate_size + 4);
328                         tls_packet_uint8(packet, 0);
329                 } else {
330                         tls_packet_uint24(packet, all_certificate_size + 3);
331                 }
332
333                 tls_packet_uint24(packet, all_certificate_size);
334
335                 for (i = 0; i < certificates_count; i++) {
336                         struct TLSCertificate *cert = certificates[i];
337                         if (cert && cert->der_len) {
338                                 /* is RSA certificate ? */
339                                 if (is_ecdsa && !cert->ec_algorithm) {
340                                         continue;
341                                 }
342                                 /* is ECC certificate ? */
343                                 if (!is_ecdsa && cert->ec_algorithm) {
344                                         continue;
345                                 }
346                                 /* 2 times -> one certificate */
347                                 tls_packet_uint24(packet, cert->der_len);
348                                 tls_packet_append(packet, cert->der_bytes,
349                                                   cert->der_len);
350                                 /* extension */
351                                 if (context->tlsver == TLS_VERSION13) {
352                                         tls_packet_uint16(packet, 0);
353                                 }
354                         }
355                 }
356         } else {
357                 tls_packet_uint24(packet, all_certificate_size);
358                 if (context->tlsver == TLS_VERSION13) {
359                         tls_packet_uint8(packet, 0);
360                 }
361
362         }
363         tls_packet_update(packet);
364         tls_queue_packet(packet);
365         return;
366 }
367
368 int tls_supported_version(uint16_t ver) {
369         switch (ver) {
370                 case TLS_V12:
371                 case TLS_V13:
372                         break;
373                 default:
374                         DEBUG_PRINT("UNSUPPORTED TLS VERSION %x\n", (int)ver);
375                         return 0;
376         }
377         return 1;
378 }
379
380 void tls_set_packet_length(struct TLSPacket *packet, uint32_t length) {
381         int offset = packet->payload_pos;
382         packet->buf[offset] = (length >> 16) & 0xff;
383         packet->buf[offset+1] = (length >> 8) & 0xff;
384         packet->buf[offset+2] = (length >> 0) & 0xff;
385 }
386
387 static void tls_init() {
388         static int loaded = 0;
389         if (loaded) {
390                 return;
391         }
392
393         DEBUG_PRINT("Initializing dependencies\n");
394         loaded = 1;
395 #ifdef LTM_DESC
396         ltc_mp = ltm_desc;
397 #else
398 #ifdef TFM_DESC
399         ltc_mp = tfm_desc;
400 #endif
401 #endif
402         /* TODO remove these */
403         register_hash(&md5_desc);
404         register_hash(&sha1_desc); 
405
406         register_hash(&sha256_desc);
407         register_hash(&sha384_desc);
408         register_hash(&sha512_desc);
409
410         register_prng(&sprng_desc);
411
412         register_cipher(&aes_desc);
413
414         tls_ecc_init_curves();
415 }
416
417 static unsigned char *decrypt_rsa(struct TLSContext *context,
418                                         const unsigned char *buffer,
419                                         unsigned int len,
420                                         unsigned int *size) {
421         *size = 0;
422         if (!len || !context || !context->private_key
423             || !context->private_key->der_bytes
424             || !context->private_key->der_len) {
425                 DEBUG_PRINT("No private key set\n");
426                 return NULL;
427         }
428         rsa_key key;
429         int err;
430         err = rsa_import(context->private_key->der_bytes,
431                         context->private_key->der_len, &key);
432
433         if (err) {
434                 DEBUG_PRINT("Error importing RSA key (code: %i)\n", err);
435                 return NULL;
436         }
437
438         unsigned char *out = malloc(len);
439         unsigned long out_size = len;
440         int hash_idx = find_hash("sha256");
441         int res = 0;
442         err = rsa_decrypt_key_ex(buffer, len, out, &out_size, (unsigned char *)
443                         "Concept", 7, hash_idx, LTC_PKCS_1_V1_5, &res, &key);
444         rsa_free(&key);
445
446         if (err || !out_size) {
447                 DEBUG_PRINT("RSA DECRYPT ERROR\n");
448                 free(out);
449                 return NULL;
450         }
451         *size = (unsigned int) out_size;
452         return out;
453 }
454
455 static int verify_rsa(struct TLSContext *context, unsigned int hash_type, const
456                 unsigned char *buffer, unsigned int len, const unsigned char
457                 *message, unsigned long message_len) {
458         rsa_key key;
459         int err;
460
461         if (len == 0) {
462                 return TLS_GENERIC_ERROR;
463         }
464
465         struct TLSCertificate **cert;
466         int count;
467
468         if (context->is_server) {
469                 cert = context->client_certificates;
470                 count = context->client_certificates_count;
471         } else {
472                 cert = context->certificates;
473                 count = context->certificates_count;
474         }
475
476         if (count == 0 || !cert) {
477                 return TLS_GENERIC_ERROR;
478         }
479
480         err = rsa_import(cert[0]->der_bytes, cert[0]->der_len, &key);
481
482         if (err) {
483                 DEBUG_PRINT("Error importing RSA certificate (code: %i)\n",
484                             err);
485                 return TLS_GENERIC_ERROR;
486         }
487         int hash_idx = -1;
488         unsigned char hash[TLS_MAX_HASH_LEN];
489         unsigned long hash_len;
490         hash_len = (unsigned long)sizeof hash;
491
492         switch (hash_type) {
493                 case md5:
494                         hash_idx = find_hash("md5");
495                         break;
496                 case sha1:
497                         hash_idx = find_hash("sha1");
498                         break;
499                 case sha256:
500                         hash_idx = find_hash("sha256");
501                         break;
502                 case sha384:
503                         hash_idx = find_hash("sha384");
504                         break;
505                 case sha512:
506                         hash_idx = find_hash("sha512");
507                         break;
508         }
509         err = hash_memory(hash_idx, message, message_len, hash, &hash_len);
510         if (hash_idx < 0 || err) {
511                 DEBUG_PRINT("Unsupported hash type: %i\n", hash_type);
512                 return TLS_GENERIC_ERROR;
513         }
514         int rsa_stat = 0;
515         if (context->tlsver == TLS_VERSION13) {
516                 err = rsa_verify_hash_ex(buffer, len, hash, hash_len,
517                                 LTC_PKCS_1_PSS, hash_idx, 0, &rsa_stat, &key);
518         } else {
519                 err = rsa_verify_hash_ex(buffer, len, hash, hash_len,
520                                 LTC_PKCS_1_V1_5, hash_idx, 0, &rsa_stat, &key);
521         }
522         rsa_free(&key);
523         if (err) {
524                 return 0;
525         }
526         return rsa_stat;
527 }
528
529 static int sign_rsa(struct TLSContext *context, unsigned int hash_type, const
530                 unsigned char *message, unsigned int message_len, unsigned char
531                 *out, unsigned long *outlen) {
532         rsa_key key;
533         int err;
534         int hash_index = -1;
535         unsigned char hash[TLS_MAX_HASH_LEN];
536         unsigned long hash_len = 0;
537         //hash_state state;
538
539         if (!outlen || !context || !out || !context->private_key
540             || !context->private_key->der_bytes
541             || !context->private_key->der_len) {
542                 DEBUG_PRINT("No private key set\n");
543                 return TLS_GENERIC_ERROR;
544         }
545
546         err = rsa_import(context->private_key->der_bytes,
547                         context->private_key->der_len, &key);
548
549         if (err) {
550                 DEBUG_PRINT("Error %d importing RSA certificate", err);
551                 return TLS_GENERIC_ERROR;
552         }
553
554         switch (hash_type) {
555                 case sha1:
556                         hash_index = find_hash("sha1");
557                         hash_len = 20;
558                         break;
559                 case sha256:
560                         hash_index = find_hash("sha256");
561                         hash_len = 32;
562                         break;
563                 case sha384:
564                         hash_index = find_hash("sha384");
565                         hash_len = 48;
566                         break;
567                 case sha512:
568                         hash_index = find_hash("sha512");
569                         hash_len = 64;
570                         break;
571                 case md5:
572                 case _md5_sha1:
573                         hash_index = find_hash("md5");
574                         hash_len = 16;
575                         break;
576         }
577
578         if (hash_index < 0 || err) {
579                 DEBUG_PRINT("Unsupported hash type: %i\n", hash_type);
580                 return TLS_GENERIC_ERROR;
581         }
582
583         hash_memory(hash_index, message, message_len, hash, &hash_len);
584
585         if (hash_type == _md5_sha1) {
586                 unsigned long hlen = 20;
587                 hash_index = find_hash("sha1");
588                 hash_memory(hash_index, message, message_len, hash+16, &hlen);
589                 hash_len += hlen;
590         }
591
592         //err = hash_memory(hash_idx, message, message_len, hash, &hash_len);
593
594         if (context->tlsver == TLS_VERSION13) {
595                 err = rsa_sign_hash_ex(hash, hash_len, out, outlen,
596                                 LTC_PKCS_1_PSS, NULL, find_prng("sprng"),
597                                 hash_index, hash_type == sha256 ? 32 : 48, &key);
598         } else {
599                 err = rsa_sign_hash_ex(hash, hash_len, out, outlen,
600                                 LTC_PKCS_1_V1_5, NULL, find_prng("sprng"),
601                                 hash_index, 0, &key);
602         }
603
604         rsa_free(&key);
605         if (err) {
606                 return 0;
607         }
608
609         return 1;
610 }
611
612 static int tls_is_point(ecc_key * key) {
613         void *prime, *b, *t1, *t2;
614         int err;
615
616         if ((err = mp_init_multi(&prime, &b, &t1, &t2, NULL)) != CRYPT_OK) {
617                 return err;
618         }
619
620         /* load prime and b */
621         if ((err = mp_read_radix(prime, key->dp->prime, 16)) != CRYPT_OK) {
622                 goto error;
623         }
624         if ((err = mp_read_radix(b, key->dp->B, 16)) != CRYPT_OK) {
625                 goto error;
626         }
627
628         /* compute y^2 */
629         if ((err = mp_sqr(key->pubkey.y, t1)) != CRYPT_OK) {
630                 goto error;
631         }
632
633         /* compute x^3 */
634         if ((err = mp_sqr(key->pubkey.x, t2)) != CRYPT_OK) {
635                 goto error;
636         }
637         if ((err = mp_mod(t2, prime, t2)) != CRYPT_OK) {
638                 goto error;
639         }
640         if ((err = mp_mul(key->pubkey.x, t2, t2)) != CRYPT_OK) {
641                 goto error;
642         }
643
644         /* compute y^2 - x^3 */
645         if ((err = mp_sub(t1, t2, t1)) != CRYPT_OK) {
646                 goto error;
647         }
648
649         /* compute y^2 - x^3 + 3x */
650         if ((err = mp_add(t1, key->pubkey.x, t1)) != CRYPT_OK) {
651                 goto error;
652         }
653         if ((err = mp_add(t1, key->pubkey.x, t1)) != CRYPT_OK) {
654                 goto error;
655         }
656         if ((err = mp_add(t1, key->pubkey.x, t1)) != CRYPT_OK) {
657                 goto error;
658         }
659         if ((err = mp_mod(t1, prime, t1)) != CRYPT_OK) {
660                 goto error;
661         }
662         while (mp_cmp_d(t1, 0) == LTC_MP_LT) {
663                 if ((err = mp_add(t1, prime, t1)) != CRYPT_OK) {
664                         goto error;
665                 }
666         }
667         while (mp_cmp(t1, prime) != LTC_MP_LT) {
668                 if ((err = mp_sub(t1, prime, t1)) != CRYPT_OK) {
669                         goto error;
670                 }
671         }
672
673         /* compare to b */
674         if (mp_cmp(t1, b) != LTC_MP_EQ) {
675                 err = CRYPT_INVALID_PACKET;
676         } else {
677                 err = CRYPT_OK;
678         }
679
680       error:
681         mp_clear_multi(prime, b, t1, t2, NULL);
682         return err;
683 }
684
685 static int tls_ecc_import_key(const unsigned char *private_key,
686                                 int private_len,
687                                 const unsigned char *public_key,
688                                 int public_len, ecc_key *key,
689                                 const ltc_ecc_set_type *dp) {
690         int err;
691
692         if (!key || !ltc_mp.name) {
693                 return CRYPT_MEM;
694         }
695
696         key->type = PK_PRIVATE;
697
698         if (mp_init_multi
699             (&key->pubkey.x, &key->pubkey.y, &key->pubkey.z, &key->k,
700              NULL) != CRYPT_OK)
701                 return CRYPT_MEM;
702
703         if (public_len && !public_key[0]) {
704                 public_key++;
705                 public_len--;
706         }
707         if ((err = mp_read_unsigned_bin(key->pubkey.x,
708                                   (unsigned char *) public_key + 1,
709                                   (public_len - 1) >> 1)) != CRYPT_OK) {
710                 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
711                                key->k, NULL);
712                 return err;
713         }
714
715         if ((err = mp_read_unsigned_bin(key->pubkey.y,
716                                   (unsigned char *) public_key + 1 +
717                                   ((public_len - 1) >> 1),
718                                   (public_len - 1) >> 1)) != CRYPT_OK) {
719                 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
720                                key->k, NULL);
721                 return err;
722         }
723
724         if ((err =
725              mp_read_unsigned_bin(key->k, (unsigned char *) private_key,
726                                   private_len)) != CRYPT_OK) {
727                 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
728                                key->k, NULL);
729                 return err;
730         }
731
732         key->idx = -1;
733         key->dp = dp;
734
735         /* set z */
736         if ((err = mp_set(key->pubkey.z, 1)) != CRYPT_OK) {
737                 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
738                                key->k, NULL);
739                 return err;
740         }
741
742         /* is it a point on the curve?  */
743         if ((err = tls_is_point(key)) != CRYPT_OK) {
744                 DEBUG_PRINT("KEY IS NOT ON CURVE\n");
745                 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
746                                key->k, NULL);
747                 return err;
748         }
749
750         /* we're good */
751         return CRYPT_OK;
752 }
753
754 static int sign_ecdsa(struct TLSContext *context,
755                             unsigned int hash_type,
756                             const unsigned char *message,
757                             unsigned int message_len, unsigned char *out,
758                             unsigned long *outlen) {
759         if (!outlen || !context || !out || !outlen
760             || !context->ec_private_key
761             || !context->ec_private_key->priv
762             || !context->ec_private_key->priv_len
763             || !context->ec_private_key->pk
764             || !context->ec_private_key->pk_len) {
765                 DEBUG_PRINT("No private ECDSA key set\n");
766                 return TLS_GENERIC_ERROR;
767         }
768
769         const struct ECCCurveParameters *curve = NULL;
770
771         switch (context->ec_private_key->ec_algorithm) {
772                 case 19:
773                         curve = &secp192r1;
774                         break;
775                 case 20:
776                         curve = &secp224k1;
777                         break;
778                 case 21:
779                         curve = &secp224r1;
780                         break;
781                 case 22:
782                         curve = &secp256k1;
783                         break;
784                 case 23:
785                         curve = &secp256r1;
786                         break;
787                 case 24:
788                         curve = &secp384r1;
789                         break;
790                 case 25:
791                         curve = &secp521r1;
792                         break;
793                 default:
794                         DEBUG_PRINT("UNSUPPORTED CURVE\n");
795         }
796
797         if (!curve) {
798                 return TLS_GENERIC_ERROR;
799         }
800
801         ecc_key key;
802         int err;
803
804         ltc_ecc_set_type *dp = (ltc_ecc_set_type *)&curve->dp;
805
806         /* broken ... fix this */
807         err = tls_ecc_import_key(context->ec_private_key->priv,
808                         context->ec_private_key->priv_len,
809                         context->ec_private_key->pk,
810                         context->ec_private_key->pk_len, &key, dp);
811
812         if (err) {
813                 DEBUG_PRINT("Error importing ECC certificate (code: %i)\n",
814                             (int) err);
815                 return TLS_GENERIC_ERROR;
816         }
817
818         unsigned char hash[TLS_MAX_HASH_LEN];
819         unsigned long hash_len = 0;
820         int hash_index;
821
822         switch (hash_type) {
823                 case sha1:
824                         hash_index = find_hash("sha1");
825                         hash_len = 20;
826                         break;
827                 case sha256:
828                         hash_index = find_hash("sha256");
829                         hash_len = 32;
830                         break;
831                 case sha384:
832                         hash_index = find_hash("sha384");
833                         hash_len = 48;
834                         break;
835                 case sha512:
836                         hash_index = find_hash("sha512");
837                         hash_len = 64;
838                         break;
839                 case md5:
840                 case _md5_sha1:
841                         hash_index = find_hash("md5");
842                         hash_len = 16;
843                         break;
844         }
845
846         hash_memory(hash_index, message, message_len, hash, &hash_len);
847
848         if (hash_type == _md5_sha1) {
849                 unsigned long hlen = 20;
850                 hash_index = find_hash("sha1");
851                 hash_memory(hash_index, message, message_len, hash+16, &hlen);
852                 hash_len += hlen;
853         }
854
855         if (err) {
856                 DEBUG_PRINT("Unsupported hash type: %i\n", hash_type);
857                 return TLS_GENERIC_ERROR;
858         }
859         /* "Let z be the Ln leftmost bits of e, where Ln is the bit length of
860          * the group order n." */
861         if ((int)hash_len > curve->size) {
862                 hash_len = curve->size;
863         }
864         err = ecc_sign_hash(hash, hash_len, out, outlen, NULL,
865                         find_prng("sprng"), &key);
866         DEBUG_DUMP_HEX_LABEL("ECC SIGNATURE", out, *outlen);
867         ecc_free(&key);
868
869         return err ? 0 : 1;
870 }
871
872 static void tls_send_certificate_verify(struct TLSContext *context) {
873         struct TLSPacket *packet =
874             tls_create_packet(context, TLS_HANDSHAKE, context->version, 0);
875         /* certificate verify */
876         tls_packet_uint8(packet, 0x0F);
877         tls_packet_uint24(packet, 0);
878
879         unsigned char out[TLS_MAX_RSA_KEY];
880         unsigned long out_len = TLS_MAX_RSA_KEY;
881
882         unsigned char signing_data[TLS_MAX_HASH_SIZE + 98];
883         int signing_data_len;
884
885         /* first 64 bytes to 0x20 (32) */
886         memset(signing_data, 0x20, 64);
887         /* context string 33 bytes */
888         if (context->is_server) {
889                 memcpy(signing_data + 64, "TLS 1.3, server CertificateVerify",
890                                 33);
891         } else {
892                 memcpy(signing_data + 64, "TLS 1.3, client CertificateVerify",
893                                 33);
894         }
895         /* a single 0 byte separator */
896         signing_data[97] = 0;
897         signing_data_len = 98;
898
899         signing_data_len += tls_get_hash(context, signing_data + 98);
900         DEBUG_DUMP_HEX_LABEL("verify data", signing_data, signing_data_len);
901         int hash_algorithm = sha256;
902         if (tls_is_ecdsa(context)) {
903                 switch (context->ec_private_key->ec_algorithm) {
904                         case 23:
905                                 /* secp256r1 + sha256 */
906                                 tls_packet_uint16(packet, 0x0403);
907                                 break;
908                         case 24:
909                                 /* secp384r1 + sha384 */
910                                 tls_packet_uint16(packet, 0x0503);
911                                 hash_algorithm = sha384;
912                                 break;
913                         case 25:
914                                 /* secp521r1 + sha512 */
915                                 tls_packet_uint16(packet, 0x0603);
916                                 hash_algorithm = sha512;
917                                 break;
918                         default:
919                                 DEBUG_PRINT("UNSUPPORTED CURVE (SIGNING)\n");
920                                 packet->broken = 1;
921                                 /* TODO error */
922                                 return;
923                 }
924         } else {
925                 tls_packet_uint16(packet, 0x0804);
926         }
927
928         int packet_size = 2;
929
930         if (tls_is_ecdsa(context)) {
931                 if (sign_ecdsa(context, hash_algorithm, signing_data,
932                                         signing_data_len, out, &out_len) == 1)
933                 {
934                         DEBUG_PRINT
935                             ("ECDSA signing OK! (ECDSA, length %lu)\n",
936                              out_len);
937                         tls_packet_uint16(packet, out_len);
938                         tls_packet_append(packet, out, out_len);
939                         packet_size += out_len + 2;
940                 }
941         } else if (sign_rsa(context, hash_algorithm, signing_data,
942                                 signing_data_len, out, &out_len) == 1) {
943                 DEBUG_PRINT("RSA signing OK! (length %lu)\n", out_len);
944                 tls_packet_uint16(packet, out_len);
945                 tls_packet_append(packet, out, out_len);
946                 packet_size += out_len + 2;
947         }
948
949         tls_set_packet_length(packet, packet_size);
950
951         tls_packet_update(packet);
952         tls_queue_packet(packet);
953         return;
954 }
955
956 static int tls_ecc_import_pk(const unsigned char *public_key,
957                                int public_len, ecc_key * key,
958                                const ltc_ecc_set_type * dp) {
959         int err;
960
961         if (!key || !ltc_mp.name) {
962                 return CRYPT_MEM;
963         }
964
965         key->type = PK_PUBLIC;
966
967         if (mp_init_multi(&key->pubkey.x, &key->pubkey.y, &key->pubkey.z,
968                                 &key->k, NULL) != CRYPT_OK) {
969                 return CRYPT_MEM;
970         }
971
972         if (public_len && !public_key[0]) {
973                 public_key++;
974                 public_len--;
975         }
976         if ((err = mp_read_unsigned_bin(key->pubkey.x,
977                                   (unsigned char *) public_key + 1,
978                                   (public_len - 1) >> 1)) != CRYPT_OK) {
979                 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
980                                key->k, NULL);
981                 return err;
982         }
983
984         if ((err = mp_read_unsigned_bin(key->pubkey.y,
985                                   (unsigned char *) public_key + 1 +
986                                   ((public_len - 1) >> 1),
987                                   (public_len - 1) >> 1)) != CRYPT_OK) {
988                 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
989                                key->k, NULL);
990                 return err;
991         }
992
993         key->idx = -1;
994         key->dp = dp;
995
996         /* set z */
997         if ((err = mp_set(key->pubkey.z, 1)) != CRYPT_OK) {
998                 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
999                                key->k, NULL);
1000                 return err;
1001         }
1002
1003         /* is it a point on the curve?  */
1004         if ((err = tls_is_point(key)) != CRYPT_OK) {
1005                 DEBUG_PRINT("KEY IS NOT ON CURVE\n");
1006                 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
1007                                key->k, NULL);
1008                 return err;
1009         }
1010
1011         /* we're good */
1012         return CRYPT_OK;
1013 }
1014
1015 static int tls_verify_ecdsa(struct TLSContext *context,
1016                               unsigned int hash_type,
1017                               const unsigned char *buffer,
1018                               unsigned int len,
1019                               const unsigned char *message,
1020                               unsigned int message_len,
1021                               const struct ECCCurveParameters *curve_hint) 
1022 {
1023         ecc_key key;
1024         int err;
1025
1026         if (!curve_hint) {
1027                 curve_hint = context->curve;
1028         }
1029
1030         if (len == 0) {
1031                 return TLS_GENERIC_ERROR;
1032         }
1033
1034         struct TLSCertificate **cert;
1035         int count;
1036
1037         if (context->is_server) {
1038                 cert = context->client_certificates;
1039                 count = context->client_certificates_count;
1040         } else {
1041                 cert = context->certificates;
1042                 count = context->certificates_count;
1043         }
1044
1045         if (count == 0 || !cert || !cert[0] || !cert[0]->pk ||
1046                         !cert[0]->pk_len) {
1047                 return TLS_GENERIC_ERROR;
1048         }
1049
1050         err = tls_ecc_import_pk(cert[0]->pk, cert[0]->pk_len, &key,
1051                         (ltc_ecc_set_type *)&curve_hint->dp);
1052
1053         if (err) {
1054                 DEBUG_PRINT("Error importing ECC certificate (code: %i)", err);
1055                 return TLS_GENERIC_ERROR;
1056         }
1057
1058         int hash_idx = -1;
1059         unsigned char hash[TLS_MAX_HASH_LEN];
1060         unsigned long hash_len = 0;
1061
1062         switch (hash_type) {
1063                 case md5:
1064                         hash_idx = find_hash("md5");
1065                         hash_len = 16;
1066                         break;
1067                 case sha1:
1068                         hash_idx = find_hash("sha1");
1069                         hash_len = 20;
1070                         break;
1071                 case sha256:
1072                         hash_idx = find_hash("sha256");
1073                         hash_len = 32;
1074                         break;
1075                 case sha384:
1076                         hash_idx = find_hash("sha384");
1077                         hash_len = 48;
1078                         break;
1079                 case sha512:
1080                         hash_idx = find_hash("sha512");
1081                         hash_len = 64;
1082                         break;
1083         }
1084
1085         err = hash_memory(hash_idx, message, message_len, hash, &hash_len);
1086
1087         if (hash_idx < 0 || err) {
1088                 DEBUG_PRINT("Unsupported hash type: %i\n", hash_type);
1089                 return TLS_GENERIC_ERROR;
1090         }
1091
1092         int ecc_stat = 0;
1093         err = ecc_verify_hash(buffer, len, hash, hash_len, &ecc_stat, &key);
1094         ecc_free(&key);
1095         if (err) {
1096                 return 0;
1097         }
1098         return ecc_stat;
1099 }
1100
1101 static void prf_helper(int hash_idx, unsigned long dlen,
1102                              unsigned char *output, unsigned int outlen,
1103                              const unsigned char *secret,
1104                              const unsigned int secret_len,
1105                              const unsigned char *label,
1106                              unsigned int label_len, unsigned char *seed,
1107                              unsigned int seed_len, unsigned char *seed_b,
1108                              unsigned int seed_b_len) {
1109         unsigned char digest_out0[TLS_MAX_HASH_LEN];
1110         unsigned char digest_out1[TLS_MAX_HASH_LEN];
1111         unsigned int i;
1112         hmac_state hmac;
1113
1114         hmac_init(&hmac, hash_idx, secret, secret_len);
1115         hmac_process(&hmac, label, label_len);
1116
1117         hmac_process(&hmac, seed, seed_len);
1118         if (seed_b && seed_b_len) {
1119                 hmac_process(&hmac, seed_b, seed_b_len);
1120         }
1121         hmac_done(&hmac, digest_out0, &dlen);
1122         int idx = 0;
1123         while (outlen) {
1124                 hmac_init(&hmac, hash_idx, secret, secret_len);
1125                 hmac_process(&hmac, digest_out0, dlen);
1126                 hmac_process(&hmac, label, label_len);
1127                 hmac_process(&hmac, seed, seed_len);
1128                 if (seed_b && seed_b_len) {
1129                         hmac_process(&hmac, seed_b, seed_b_len);
1130                 }
1131                 hmac_done(&hmac, digest_out1, &dlen);
1132
1133                 unsigned int copylen = outlen;
1134                 if (copylen > dlen) {
1135                         copylen = dlen;
1136                 }
1137
1138                 for (i = 0; i < copylen; i++) {
1139                         output[idx++] ^= digest_out1[i];
1140                         outlen--;
1141                 }
1142
1143                 if (!outlen) {
1144                         break;
1145                 }
1146
1147                 hmac_init(&hmac, hash_idx, secret, secret_len);
1148                 hmac_process(&hmac, digest_out0, dlen);
1149                 hmac_done(&hmac, digest_out0, &dlen);
1150         }
1151 }
1152
1153 static void tls_prf(struct TLSContext *context,
1154                       unsigned char *output, unsigned int outlen,
1155                       const unsigned char *secret,
1156                       const unsigned int secret_len,
1157                       const unsigned char *label, unsigned int label_len,
1158                       unsigned char *seed, unsigned int seed_len,
1159                       unsigned char *seed_b, unsigned int seed_b_len) {
1160         if (!secret || !secret_len) {
1161                 DEBUG_PRINT("NULL SECRET\n");
1162                 return;
1163         }
1164
1165         /* TODO I don't think this is right, wouldn't use md5 for tls v1.3 */
1166         if (context->version != TLS_V12) {
1167                 int md5_hash_idx = find_hash("md5");
1168                 int sha1_hash_idx = find_hash("sha1");
1169                 int half_secret = (secret_len + 1) / 2;
1170
1171                 memset(output, 0, outlen);
1172                 prf_helper(md5_hash_idx, 16, output, outlen, secret,
1173                                 half_secret, label, label_len, seed, seed_len,
1174                                 seed_b, seed_b_len);
1175                 prf_helper(sha1_hash_idx, 20, output, outlen, secret +
1176                                 (secret_len - half_secret), secret_len -
1177                                 half_secret, label, label_len, seed, seed_len,
1178                                 seed_b, seed_b_len);
1179         } else {
1180                 /* sha256_hmac */
1181                 unsigned char digest_out0[TLS_MAX_HASH_LEN];
1182                 unsigned char digest_out1[TLS_MAX_HASH_LEN];
1183                 unsigned long dlen = 32;
1184                 int hash_idx;
1185                 unsigned int mac_length = tls_mac_length(context);
1186
1187                 if (mac_length == TLS_SHA384_MAC_SIZE) {
1188                         hash_idx = find_hash("sha384");
1189                         dlen = mac_length;
1190                 } else {
1191                         hash_idx = find_hash("sha256");
1192                 }
1193
1194                 unsigned int i;
1195
1196                 hmac_state hmac;
1197                 hmac_init(&hmac, hash_idx, secret, secret_len);
1198                 hmac_process(&hmac, label, label_len);
1199                 hmac_process(&hmac, seed, seed_len);
1200                 if (seed_b && seed_b_len) {
1201                         hmac_process(&hmac, seed_b, seed_b_len);
1202                 }
1203                 hmac_done(&hmac, digest_out0, &dlen);
1204
1205                 int idx = 0;
1206                 while (outlen) {
1207                         hmac_init(&hmac, hash_idx, secret, secret_len);
1208                         hmac_process(&hmac, digest_out0, dlen);
1209                         hmac_process(&hmac, label, label_len);
1210                         hmac_process(&hmac, seed, seed_len);
1211                         if (seed_b && seed_b_len) {
1212                                 hmac_process(&hmac, seed_b, seed_b_len);
1213                         }
1214                         hmac_done(&hmac, digest_out1, &dlen);
1215
1216                         unsigned int copylen = outlen;
1217                         if (copylen > dlen) {
1218                                 copylen = (unsigned int) dlen;
1219                         }
1220
1221                         for (i = 0; i < copylen; i++) {
1222                                 output[idx++] = digest_out1[i];
1223                                 outlen--;
1224                         }
1225
1226                         if (!outlen) {
1227                                 break;
1228                         }
1229
1230                         hmac_init(&hmac, hash_idx, secret, secret_len);
1231                         hmac_process(&hmac, digest_out0, dlen);
1232                         hmac_done(&hmac, digest_out0, &dlen);
1233                 }
1234         }
1235 }
1236
1237 static void tls_send_finished(struct TLSContext *context) {
1238         struct TLSPacket *packet =
1239             tls_create_packet(context, TLS_HANDSHAKE, context->version,
1240                               TLS_MIN_FINISHED_OPAQUE_LEN + 64);
1241         tls_packet_uint8(packet, 0x14);
1242
1243         if (context->tlsver == TLS_VERSION13) {
1244                 tls_packet_uint24(packet, tls_mac_length(context));
1245         } else {
1246                 tls_packet_uint24(packet, TLS_MIN_FINISHED_OPAQUE_LEN);
1247         }
1248
1249         /* verify */
1250         unsigned char hash[TLS_MAX_HASH_SIZE];
1251         unsigned long out_size = TLS_MIN_FINISHED_OPAQUE_LEN;
1252         unsigned char out[TLS_MAX_HASH_SIZE];
1253         unsigned int hash_len;
1254
1255         int context_is_v13 = 0;
1256
1257         if (packet->context->tlsver == TLS_VERSION13) {
1258                 context_is_v13 = 1;
1259         }
1260
1261         /* server verifies client's message */
1262         if (context->is_server) {
1263                 if (context_is_v13) {
1264                         hash_len = tls_get_hash(context, hash);
1265                         if (!context->finished_key || !hash_len) {
1266                                 DEBUG_PRINT
1267                                     ("NO FINISHED KEY COMPUTED OR NO HANDSHAKE HASH\n");
1268
1269                                 /* TODO probably need to terminate */
1270                                 tls_destroy_packet(packet);
1271                                 return;
1272                         }
1273
1274                         DEBUG_DUMP_HEX_LABEL("HS HASH", hash, hash_len);
1275                         DEBUG_DUMP_HEX_LABEL("HS FINISH",
1276                                              context->finished_key,
1277                                              hash_len);
1278
1279                         out_size = hash_len;
1280                         hmac_state hmac;
1281                         hmac_init(&hmac, tls_get_hash_idx(context),
1282                                         context->finished_key, hash_len);
1283                         hmac_process(&hmac, hash, hash_len);
1284                         hmac_done(&hmac, out, &out_size);
1285                 } else {
1286                         hash_len = tls_done_hash(context, hash);
1287                         tls_prf(context, out,
1288                                          TLS_MIN_FINISHED_OPAQUE_LEN,
1289                                          context->master_key,
1290                                          context->master_key_len,
1291                                          (unsigned char *)
1292                                          "server finished", 15, hash,
1293                                          hash_len, NULL, 0);
1294                         tls_destroy_hash(context);
1295                 }
1296         } else {
1297                 /* client */
1298                 hash_len = tls_get_hash(context, hash);
1299                 tls_prf(context, out, TLS_MIN_FINISHED_OPAQUE_LEN,
1300                                  context->master_key,
1301                                  context->master_key_len,
1302                                  (unsigned char *) "client finished", 15,
1303                                  hash, hash_len, NULL, 0);
1304         }
1305
1306         tls_packet_append(packet, out, out_size);
1307         tls_packet_update(packet);
1308         DEBUG_DUMP_HEX_LABEL("VERIFY DATA", out, out_size);
1309         tls_queue_packet(packet);
1310         return;
1311 }
1312
1313 static int tls_key_length(struct TLSContext *context) {
1314         switch (context->cipher) {
1315                 case TLS_RSA_WITH_AES_128_CBC_SHA:
1316                 case TLS_RSA_WITH_AES_128_CBC_SHA256:
1317                 case TLS_RSA_WITH_AES_128_GCM_SHA256:
1318                 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
1319                 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
1320                 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
1321                 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
1322                 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
1323                 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
1324                 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
1325                 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
1326                 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
1327                 case TLS_AES_128_GCM_SHA256:
1328                         return 16;
1329                 case TLS_RSA_WITH_AES_256_CBC_SHA:
1330                 case TLS_RSA_WITH_AES_256_CBC_SHA256:
1331                 case TLS_RSA_WITH_AES_256_GCM_SHA384:
1332                 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
1333                 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
1334                 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
1335                 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
1336                 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
1337                 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
1338                 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
1339                 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
1340                 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
1341                 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
1342                 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
1343                 case TLS_AES_256_GCM_SHA384:
1344                 case TLS_CHACHA20_POLY1305_SHA256:
1345                         return 32;
1346         }
1347         return 0;
1348 }
1349
1350 /* 0 is none, 1 is GCM?, 2 is chacha */
1351 int tls_is_aead(struct TLSContext *context) {
1352         switch (context->cipher) {
1353                 case TLS_RSA_WITH_AES_128_GCM_SHA256:
1354                 case TLS_RSA_WITH_AES_256_GCM_SHA384:
1355                 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
1356                 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
1357                 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
1358                 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
1359                 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
1360                 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
1361                 case TLS_AES_128_GCM_SHA256:
1362                 case TLS_AES_256_GCM_SHA384:
1363                         return 1;
1364                 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
1365                 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
1366                 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
1367                 case TLS_CHACHA20_POLY1305_SHA256:
1368                         return 2;
1369         }
1370         return 0;
1371 }
1372
1373 int tls_mac_length(struct TLSContext *context) {
1374         switch (context->cipher) {
1375                 case TLS_RSA_WITH_AES_128_CBC_SHA:
1376                 case TLS_RSA_WITH_AES_256_CBC_SHA:
1377                 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
1378                 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
1379                 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
1380                 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
1381                 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
1382                 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
1383                         return TLS_SHA1_MAC_SIZE;
1384                 case TLS_RSA_WITH_AES_128_CBC_SHA256:
1385                 case TLS_RSA_WITH_AES_256_CBC_SHA256:
1386                 case TLS_RSA_WITH_AES_128_GCM_SHA256:
1387                 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
1388                 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
1389                 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
1390                 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
1391                 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
1392                 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
1393                 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
1394                 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
1395                 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
1396                 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
1397                 case TLS_AES_128_GCM_SHA256:
1398                 case TLS_CHACHA20_POLY1305_SHA256:
1399                 case TLS_AES_128_CCM_SHA256:
1400                 case TLS_AES_128_CCM_8_SHA256:
1401                         return TLS_SHA256_MAC_SIZE;
1402                 case TLS_RSA_WITH_AES_256_GCM_SHA384:
1403                 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
1404                 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
1405                 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
1406                 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
1407                 case TLS_AES_256_GCM_SHA384:
1408                         return TLS_SHA384_MAC_SIZE;
1409         }
1410         return 0;
1411 }
1412
1413 int _private_tls13_key(struct TLSContext *context, int handshake) {
1414         int key_length = tls_key_length(context);
1415         int mac_length = tls_mac_length(context);
1416
1417         if (!context->premaster_key || !context->premaster_key_len) {
1418                 return 0;
1419         }
1420
1421         if (!key_length || !mac_length) {
1422                 DEBUG_PRINT
1423                     ("KEY EXPANSION FAILED, KEY LENGTH: %i, MAC LENGTH: %i\n",
1424                      key_length, mac_length);
1425                 return 0;
1426         }
1427
1428         unsigned char *clientkey = NULL;
1429         unsigned char *serverkey = NULL;
1430         unsigned char *clientiv = NULL;
1431         unsigned char *serveriv = NULL;
1432         int is_aead = tls_is_aead(context);
1433
1434         unsigned char local_keybuffer[TLS_V13_MAX_KEY_SIZE];
1435         unsigned char local_ivbuffer[TLS_V13_MAX_IV_SIZE];
1436         unsigned char remote_keybuffer[TLS_V13_MAX_KEY_SIZE];
1437         unsigned char remote_ivbuffer[TLS_V13_MAX_IV_SIZE];
1438
1439         unsigned char prk[TLS_MAX_HASH_SIZE];
1440         unsigned char hash[TLS_MAX_HASH_SIZE];
1441         static unsigned char earlysecret[TLS_MAX_HASH_SIZE];
1442
1443         const char *server_key = "s ap traffic";
1444         const char *client_key = "c ap traffic";
1445         if (handshake) {
1446                 server_key = "s hs traffic";
1447                 client_key = "c hs traffic";
1448         }
1449
1450         unsigned char salt[TLS_MAX_HASH_SIZE];
1451
1452         hash_state md;
1453         /* TODO what is the point of this ? */
1454         if (mac_length == TLS_SHA384_MAC_SIZE) {
1455                 sha384_init(&md);
1456                 sha384_done(&md, hash);
1457         } else {
1458                 sha256_init(&md);
1459                 sha256_done(&md, hash);
1460         }
1461         /* extract secret "early" */
1462         if (context->master_key && context->master_key_len && !handshake) {
1463                 DEBUG_DUMP_HEX_LABEL("USING PREVIOUS SECRET",
1464                                      context->master_key,
1465                                      context->master_key_len);
1466                 tls_hkdf_expand_label(mac_length, salt, mac_length,
1467                                 context->master_key, context->master_key_len,
1468                                 "derived", 7, hash, mac_length);
1469                 DEBUG_DUMP_HEX_LABEL("salt", salt, mac_length);
1470                 tls_hkdf_extract(mac_length, prk, mac_length, salt, mac_length,
1471                                 earlysecret, mac_length);
1472         } else {
1473                 tls_hkdf_extract(mac_length, prk, mac_length, NULL, 0,
1474                                 earlysecret, mac_length);
1475                 /* derive secret for handshake "tls13 derived": */
1476                 DEBUG_DUMP_HEX_LABEL("null hash", hash, mac_length);
1477                 tls_hkdf_expand_label(mac_length, salt, mac_length, prk,
1478                                 mac_length, "derived", 7, hash, mac_length);
1479                 /* extract secret "handshake": */
1480                 DEBUG_DUMP_HEX_LABEL("salt", salt, mac_length);
1481                 tls_hkdf_extract(mac_length, prk, mac_length,
1482                                           salt, mac_length,
1483                                           context->premaster_key,
1484                                           context->premaster_key_len);
1485         }
1486
1487         if (!is_aead) {
1488                 DEBUG_PRINT("KEY EXPANSION FAILED, NON AEAD CIPHER\n");
1489                 return 0;
1490         }
1491
1492         unsigned char secret[TLS_MAX_MAC_SIZE];
1493         unsigned char hs_secret[TLS_MAX_HASH_SIZE];
1494
1495         int hash_size;
1496         if (handshake) {
1497                 hash_size = tls_get_hash(context, hash);
1498         } else {
1499                 hash_size = tls_done_hash(context, hash);
1500         }
1501
1502         DEBUG_DUMP_HEX_LABEL("messages hash", hash, hash_size);
1503
1504         if (context->is_server) {
1505                 tls_hkdf_expand_label(mac_length, hs_secret, mac_length, prk,
1506                                 mac_length, server_key, 12, context->
1507                                 server_finished_hash ?  context->
1508                                 server_finished_hash : hash, hash_size);
1509                 DEBUG_DUMP_HEX_LABEL(server_key, hs_secret, mac_length);
1510                 serverkey = local_keybuffer;
1511                 serveriv = local_ivbuffer;
1512                 clientkey = remote_keybuffer;
1513                 clientiv = remote_ivbuffer;
1514         } else {
1515                 tls_hkdf_expand_label(mac_length, hs_secret,
1516                                                mac_length, prk, mac_length,
1517                                                client_key, 12,
1518                                                context->
1519                                                server_finished_hash ?
1520                                                context->
1521                                                server_finished_hash : hash,
1522                                                hash_size);
1523                 serverkey = remote_keybuffer;
1524                 serveriv = remote_ivbuffer;
1525                 clientkey = local_keybuffer;
1526                 clientiv = local_ivbuffer;
1527         }
1528
1529         int iv_length = TLS_13_AES_GCM_IV_LENGTH;
1530         if (is_aead == 2) {
1531                 iv_length = TLS_CHACHA20_IV_LENGTH;
1532         }
1533
1534         tls_hkdf_expand_label(mac_length, local_keybuffer, key_length,
1535                         hs_secret, mac_length, "key", 3, NULL, 0);
1536         tls_hkdf_expand_label(mac_length, local_ivbuffer, iv_length, hs_secret,
1537                         mac_length, "iv", 2, NULL, 0);
1538
1539         tls_hkdf_expand_label(mac_length, secret,
1540                         mac_length, prk, mac_length,
1541                         context->is_server ? client_key : server_key,
1542                         12,
1543                         context->server_finished_hash ?
1544                         context->server_finished_hash :
1545                         hash,
1546                         hash_size);
1547
1548         tls_hkdf_expand_label(mac_length, remote_keybuffer, key_length, secret,
1549                         mac_length, "key", 3, NULL, 0);
1550         tls_hkdf_expand_label(mac_length, remote_ivbuffer, iv_length, secret,
1551                         mac_length, "iv", 2, NULL, 0);
1552
1553         DEBUG_DUMP_HEX_LABEL("CLIENT KEY", clientkey, key_length);
1554         DEBUG_DUMP_HEX_LABEL("CLIENT IV", clientiv, iv_length);
1555         DEBUG_DUMP_HEX_LABEL("SERVER KEY", serverkey, key_length);
1556         DEBUG_DUMP_HEX_LABEL("SERVER IV", serveriv, iv_length);
1557         free(context->finished_key);
1558         free(context->remote_finished_key);
1559
1560         if (handshake) {
1561                 context->finished_key = malloc(mac_length);
1562                 context->remote_finished_key = malloc(mac_length);
1563
1564                 if (context->finished_key) {
1565                         tls_hkdf_expand_label(mac_length,
1566                                         context->finished_key, mac_length,
1567                                         hs_secret, mac_length, "finished", 8,
1568                                         NULL, 0);
1569                         DEBUG_DUMP_HEX_LABEL("FINISHED", context->finished_key,
1570                                         mac_length);
1571                 }
1572
1573                 if (context->remote_finished_key) {
1574                         tls_hkdf_expand_label(mac_length,
1575                                         context->remote_finished_key,
1576                                         mac_length, secret, mac_length,
1577                                         "finished", 8, NULL, 0);
1578                         DEBUG_DUMP_HEX_LABEL("FINISHED", context->finished_key,
1579                                         mac_length);
1580                 }
1581         } else {
1582                 context->finished_key = NULL;
1583                 context->remote_finished_key = NULL;
1584                 free(context->server_finished_hash);
1585                 context->server_finished_hash = NULL;
1586         }
1587
1588         if (context->is_server) {
1589                 if (is_aead == 2) {
1590                         memcpy(context->crypto.ctx_remote_mac.remote_nonce,
1591                                         clientiv, iv_length);
1592                         memcpy(context->crypto.ctx_local_mac.local_nonce,
1593                                         serveriv, iv_length);
1594                 } else if (is_aead) {
1595                         memcpy(context->crypto.ctx_remote_mac.remote_iv,
1596                                         clientiv, iv_length);
1597                         memcpy(context->crypto.ctx_local_mac.local_iv,
1598                                         serveriv, iv_length);
1599                 }
1600                 if (tls_crypto_create(context, key_length,
1601                                         serverkey, serveriv, clientkey,
1602                                         clientiv)) {
1603                         return 0;
1604                 }
1605         } else {
1606                 if (is_aead == 2) {
1607                         memcpy(context->crypto.ctx_local_mac.local_nonce,
1608                                clientiv, iv_length);
1609                         memcpy(context->crypto.ctx_remote_mac.remote_nonce,
1610                                serveriv, iv_length);
1611                 } else if (is_aead) {
1612                         memcpy(context->crypto.ctx_local_mac.local_iv,
1613                                         clientiv, iv_length);
1614                         memcpy(context->crypto.ctx_remote_mac.remote_iv,
1615                                         serveriv, iv_length);
1616                 }
1617
1618                 if (tls_crypto_create(context, key_length,
1619                                         clientkey, clientiv, serverkey,
1620                                         serveriv)) {
1621                         return 0;
1622                 }
1623         }
1624
1625         context->crypto.created = 1 + is_aead;
1626
1627         free(context->master_key);
1628         context->master_key = malloc(mac_length);
1629         if (context->master_key) {
1630                 memcpy(context->master_key, prk, mac_length);
1631                 context->master_key_len = mac_length;
1632         }
1633         context->local_sequence_number = 0;
1634         context->remote_sequence_number = 0;
1635
1636         /*
1637          * extract client_mac_key(mac_key_length)
1638          * extract server_mac_key(mac_key_length)
1639          * extract client_key(enc_key_length)
1640          * extract server_key(enc_key_length)
1641          * extract client_iv(fixed_iv_lengh)
1642          * extract server_iv(fixed_iv_length)
1643          */
1644         return 1;
1645 }
1646
1647 static int tls_expand_key(struct TLSContext *context) {
1648         unsigned char key[TLS_MAX_KEY_EXPANSION_SIZE];
1649         if (context->tlsver == TLS_VERSION13) {
1650                 return 0;
1651         }
1652
1653         if (!context->master_key || !context->master_key_len) {
1654                 return 0;
1655         }
1656
1657         int key_length = tls_key_length(context);
1658         int mac_length = tls_mac_length(context);
1659
1660         if (!key_length || !mac_length) {
1661                 DEBUG_PRINT
1662                     ("KEY EXPANSION FAILED, KEY LENGTH: %i, MAC LENGTH: %i\n",
1663                      key_length, mac_length);
1664                 return 0;
1665         }
1666         unsigned char *clientkey = NULL;
1667         unsigned char *serverkey = NULL;
1668         unsigned char *clientiv = NULL;
1669         unsigned char *serveriv = NULL;
1670         int iv_length = TLS_AES_IV_LENGTH;
1671         int is_aead = tls_is_aead(context);
1672
1673         if (context->is_server) {
1674                 tls_prf(context, key, sizeof(key),
1675                                  context->master_key, context->master_key_len,
1676                                  (unsigned char *) "key expansion", 13,
1677                                  context->local_random, TLS_SERVER_RANDOM_SIZE,
1678                                  context->remote_random,
1679                                  TLS_CLIENT_RANDOM_SIZE);
1680         } else {
1681                 tls_prf(context, key, sizeof(key),
1682                                  context->master_key,
1683                                  context->master_key_len,
1684                                  (unsigned char *) "key expansion", 13,
1685                                  context->remote_random,
1686                                  TLS_SERVER_RANDOM_SIZE,
1687                                  context->local_random,
1688                                  TLS_CLIENT_RANDOM_SIZE);
1689         }
1690
1691         DEBUG_DUMP_HEX_LABEL("LOCAL RANDOM ", context->local_random,
1692                              TLS_SERVER_RANDOM_SIZE);
1693         DEBUG_DUMP_HEX_LABEL("REMOTE RANDOM", context->remote_random,
1694                              TLS_CLIENT_RANDOM_SIZE);
1695         DEBUG_PRINT("\n=========== EXPANSION ===========\n");
1696         DEBUG_DUMP_HEX(key, TLS_MAX_KEY_EXPANSION_SIZE);
1697         DEBUG_PRINT("\n");
1698
1699         int pos = 0;
1700         if (is_aead == 2) {
1701                 iv_length = TLS_CHACHA20_IV_LENGTH;
1702         } else {
1703                 if (is_aead) {
1704                         iv_length = TLS_AES_GCM_IV_LENGTH;
1705                 } else {
1706                         if (context->is_server) {
1707                                 memcpy(context->crypto.ctx_remote_mac.remote_mac,
1708                                                 &key[pos], mac_length);
1709                                 pos += mac_length;
1710                                 memcpy(context->crypto.ctx_local_mac.local_mac,
1711                                                 &key[pos], mac_length);
1712                                 pos += mac_length;
1713                         } else {
1714                                 memcpy(context->crypto.ctx_local_mac.local_mac,
1715                                                 &key[pos], mac_length);
1716                                 pos += mac_length;
1717                                 memcpy(context->crypto.ctx_remote_mac.remote_mac,
1718                                                 &key[pos], mac_length);
1719                                 pos += mac_length;
1720                         }
1721                 }
1722         }
1723
1724         clientkey = &key[pos];
1725         pos += key_length;
1726         serverkey = &key[pos];
1727         pos += key_length;
1728         clientiv = &key[pos];
1729         pos += iv_length;
1730         serveriv = &key[pos];
1731         pos += iv_length;
1732         DEBUG_PRINT("EXPANSION %i/%i\n", (int) pos,
1733                         (int) TLS_MAX_KEY_EXPANSION_SIZE);
1734         DEBUG_DUMP_HEX_LABEL("CLIENT KEY", clientkey, key_length);
1735         DEBUG_DUMP_HEX_LABEL("CLIENT IV", clientiv, iv_length);
1736         DEBUG_DUMP_HEX_LABEL("CLIENT MAC KEY",
1737                         context->is_server ? context->crypto.
1738                         ctx_remote_mac.remote_mac : context->
1739                         crypto.ctx_local_mac.local_mac,
1740                         mac_length);
1741         DEBUG_DUMP_HEX_LABEL("SERVER KEY", serverkey, key_length);
1742         DEBUG_DUMP_HEX_LABEL("SERVER IV", serveriv, iv_length);
1743         DEBUG_DUMP_HEX_LABEL("SERVER MAC KEY",
1744                         context->is_server ? context->crypto.
1745                         ctx_local_mac.local_mac : context->crypto.
1746                         ctx_remote_mac.remote_mac, mac_length);
1747         if (context->is_server) {
1748                 if (is_aead == 2) {
1749                         memcpy(context->crypto.ctx_remote_mac.remote_nonce,
1750                                         clientiv, iv_length);
1751                         memcpy(context->crypto.ctx_local_mac.local_nonce,
1752                                         serveriv, iv_length);
1753                 } else {
1754                         if (is_aead) {
1755                                 memcpy(context->crypto.ctx_remote_mac.
1756                                                 remote_aead_iv, clientiv, iv_length);
1757                                 memcpy(context->crypto.ctx_local_mac.local_aead_iv,
1758                                                 serveriv, iv_length);
1759                         }
1760                 }
1761
1762                 if (tls_crypto_create(context, key_length,
1763                                         serverkey, serveriv, clientkey,
1764                                         clientiv)) {
1765                         return 0;
1766                 }
1767         } else {
1768                 if (is_aead == 2) {
1769                         memcpy(context->crypto.ctx_local_mac.local_nonce,
1770                                         clientiv, iv_length);
1771                         memcpy(context->crypto.ctx_remote_mac.remote_nonce,
1772                                         serveriv, iv_length);
1773                 } else {
1774                         if (is_aead) {
1775                                 memcpy(context->crypto.ctx_local_mac.local_aead_iv,
1776                                                 clientiv, iv_length);
1777                                 memcpy(context->crypto.ctx_remote_mac.
1778                                                 remote_aead_iv, serveriv, iv_length);
1779                         }
1780                 }
1781
1782                 if (tls_crypto_create(context, key_length,
1783                                         clientkey, clientiv, serverkey,
1784                                         serveriv)) {
1785                         return 0;
1786                 }
1787         }
1788
1789         /*
1790          * extract client_mac_key(mac_key_length)
1791          * extract server_mac_key(mac_key_length)
1792          * extract client_key(enc_key_length)
1793          * extract server_key(enc_key_length)
1794          * extract client_iv(fixed_iv_lengh)
1795          * extract server_iv(fixed_iv_length)
1796          */
1797         return 1;
1798 }
1799
1800 int tls_compute_key(struct TLSContext *context, unsigned int key_len) {
1801         if (context->tlsver == TLS_VERSION13) {
1802                 return 0;
1803         }
1804
1805         if (!context->premaster_key || !context->premaster_key_len
1806             || key_len < 48) {
1807                 DEBUG_PRINT("CANNOT COMPUTE MASTER SECRET\n");
1808                 return 0;
1809         }
1810
1811         unsigned char master_secret_label[] = "master secret";
1812 #ifdef TLS_CHECK_PREMASTER_KEY
1813         if (!tls_cipher_is_ephemeral(context)) {
1814                 uint16_t version = get16(context->premaster_key);
1815                 /* this check is not true for DHE/ECDHE ciphers */
1816                 if (context->version > version) {
1817                         DEBUG_PRINT("Mismatch protocol version 0x(%x)\n",
1818                                     version);
1819                         return 0;
1820                 }
1821         }
1822 #endif
1823         free(context->master_key);
1824         context->master_key_len = 0;
1825         context->master_key = NULL;
1826
1827         context->master_key = malloc(key_len);
1828         if (!context->master_key) {
1829                 return 0;
1830         }
1831
1832         context->master_key_len = key_len;
1833         if (context->is_server) {
1834                 tls_prf(context,
1835                                 context->master_key,
1836                                 context->master_key_len,
1837                                 context->premaster_key,
1838                                 context->premaster_key_len,
1839                                 master_secret_label, 13,
1840                                 context->remote_random,
1841                                 TLS_CLIENT_RANDOM_SIZE,
1842                                 context->local_random,
1843                                 TLS_SERVER_RANDOM_SIZE);
1844         } else {
1845                 tls_prf(context,
1846                                 context->master_key,
1847                                 context->master_key_len,
1848                                 context->premaster_key,
1849                                 context->premaster_key_len,
1850                                 master_secret_label, 13,
1851                                 context->local_random,
1852                                 TLS_CLIENT_RANDOM_SIZE,
1853                                 context->remote_random,
1854                                 TLS_SERVER_RANDOM_SIZE);
1855         }
1856         free(context->premaster_key);
1857         context->premaster_key = NULL;
1858         context->premaster_key_len = 0;
1859         DEBUG_PRINT("\n=========== Master key ===========\n");
1860         DEBUG_DUMP_HEX(context->master_key,
1861                         context->master_key_len);
1862         DEBUG_PRINT("\n");
1863         tls_expand_key(context);
1864         return 1;
1865 }
1866
1867 int _is_oid(const unsigned char *oid, const unsigned char *compare_to,
1868             int compare_to_len) {
1869         int i = 0;
1870         while ((oid[i]) && (i < compare_to_len)) {
1871                 if (oid[i] != compare_to[i])
1872                         return 0;
1873
1874                 i++;
1875         }
1876         return 1;
1877 }
1878
1879 int _is_oid2(const unsigned char *oid, const unsigned char *compare_to,
1880              int compare_to_len, int oid_len) {
1881         int i = 0;
1882         if (oid_len < compare_to_len) {
1883                 compare_to_len = oid_len;
1884         }
1885
1886         while (i < compare_to_len) {
1887                 if (oid[i] != compare_to[i]) {
1888                         return 0;
1889                 }
1890
1891                 i++;
1892         }
1893         return 1;
1894 }
1895
1896 struct TLSCertificate *tls_create_certificate() {
1897         struct TLSCertificate zero = { 0 };
1898         struct TLSCertificate *cert = malloc(sizeof *cert);
1899         if (cert) {
1900                 *cert = zero;
1901         }
1902         cert->not_before[0] = 0;
1903         cert->not_after[0] = 0;
1904
1905         return cert;
1906 }
1907
1908 int tls_certificate_valid_subject_name(const unsigned char *cert_subject,
1909                                        const char *subject) {
1910         /* no subjects ... */
1911         if ((!cert_subject || !cert_subject[0]) && (!subject || !subject[0])) {
1912                 return 0;
1913         }
1914
1915         if (!subject || !subject[0]) {
1916                 return bad_certificate;
1917         }
1918
1919         if (!cert_subject || !cert_subject[0]) {
1920                 return bad_certificate;
1921         }
1922
1923         /* exact match */
1924         if (!strcmp((const char *) cert_subject, subject)) {
1925                 return 0;
1926         }
1927
1928         const char *wildcard = strchr((const char *) cert_subject, '*');
1929         if (wildcard) {
1930                 /* 6.4.3 (1) The client SHOULD NOT attempt to match a presented
1931                  * identifier in which the wildcard character comprises a label
1932                  * other than the left-most label
1933                  */
1934                 if (!wildcard[1]) {
1935                         /* subject is [*]
1936                          * or
1937                          * subject is [something*] .. invalid
1938                          */
1939                         return bad_certificate;
1940                 }
1941                 wildcard++;
1942                 const char *match = strstr(subject, wildcard);
1943                 if ((!match) && (wildcard[0] == '.')) {
1944                         /* check *.domain.com against domain.com */
1945                         wildcard++;
1946                         if (!strcasecmp(subject, wildcard))
1947                                 return 0;
1948                 }
1949                 if (match) {
1950                         unsigned long offset = (unsigned long) match -
1951                                 (unsigned long) subject;
1952                         if (offset) {
1953                                 /* check for foo.*.domain.com against *.domain.com (invalid) */
1954                                 if (memchr(subject, '.', offset))
1955                                         return bad_certificate;
1956                         }
1957                         /* check if exact match */
1958                         if (!strcasecmp(match, wildcard)) {
1959                                 return 0;
1960                         }
1961                 }
1962         }
1963
1964         return bad_certificate;
1965 }
1966
1967 int tls_certificate_valid_subject(struct TLSCertificate *cert,
1968                                   const char *subject) {
1969         int i;
1970         if (!cert) {
1971                 return certificate_unknown;
1972         }
1973
1974         int err = tls_certificate_valid_subject_name(cert->subject, subject);
1975         if (err && cert->san) {
1976                 for (i = 0; i < cert->san_length; i++) {
1977                         err = tls_certificate_valid_subject_name(cert->san[i],
1978                                         subject);
1979                         if (!err) {
1980                                 return err;
1981                         }
1982                 }
1983         }
1984         return err;
1985 }
1986
1987 int tls_certificate_is_valid(struct TLSCertificate *cert) {
1988         if (!cert) {
1989                 return certificate_unknown;
1990         }
1991
1992         char ts[16]; /* YYYYMMDDHHMMSSZ */
1993         time_t t = time(NULL);
1994         struct tm *utc = gmtime(&t);
1995
1996         if (utc) {
1997                 strftime(ts, sizeof ts, "%Y%m%d%H%M%SZ", utc);
1998
1999                 if (strcmp(cert->not_before, ts) > 0) {
2000                         DEBUG_PRINT
2001                             ("Certificate is not yet valid, now: %s (validity: %s - %s)\n",
2002                              ts, cert->not_before, cert->not_after);
2003                         return certificate_expired;
2004                 }
2005
2006                 if (strcmp(cert->not_after, ts) < 0) {
2007                         DEBUG_PRINT
2008                             ("Expired certificate, now: %s (validity: %s - %s)\n",
2009                              ts, cert->not_before, cert->not_after);
2010                         return certificate_expired;
2011                 }
2012                 DEBUG_PRINT("Valid certificate, now: %s (validity: %s - %s)\n",
2013                                 ts, cert->not_before,
2014                                 cert->not_after);
2015         }
2016         return 0;
2017 }
2018
2019 void tls_certificate_set_copy(unsigned char **member,
2020                               const unsigned char *val, int len) {
2021         if (!member) {
2022                 return;
2023         }
2024
2025         free(*member);
2026
2027         if (len) {
2028                 *member = malloc(len + 1);
2029                 if (*member) {
2030                         memcpy(*member, val, len);
2031                         (*member)[len] = 0;
2032                 }
2033         } else {
2034                 *member = NULL;
2035         }
2036 }
2037
2038 void tls_certificate_set_copy_date(unsigned char *member,
2039                                    const unsigned char *val, int len) {
2040
2041         if (len > 4) {
2042                 if (val[0] >= '5') {
2043                         member[0] = '1';
2044                         member[1] = '9';
2045                 } else {
2046                         member[0] = '2';
2047                         member[1] = '0';
2048                 }
2049                 memcpy(member + 2, val, len);
2050                 member[len] = 0;
2051         } else {
2052                 member[0] = 0;
2053         }
2054 }
2055
2056 void tls_certificate_set_key(struct TLSCertificate *cert,
2057                              const unsigned char *val, int len) {
2058         if (!val[0] && len % 2) {
2059                 val++;
2060                 len--;
2061         }
2062         tls_certificate_set_copy(&cert->pk, val, len);
2063         if (cert->pk) {
2064                 cert->pk_len = len;
2065         }
2066 }
2067
2068 void tls_certificate_set_priv(struct TLSCertificate *cert,
2069                               const unsigned char *val, int len) {
2070         tls_certificate_set_copy(&cert->priv, val, len);
2071         if (cert->priv) {
2072                 cert->priv_len = len;
2073         }
2074 }
2075
2076 void tls_certificate_set_sign_key(struct TLSCertificate *cert,
2077                                   const unsigned char *val, int len) {
2078         if (!val[0] && len % 2) {
2079                 val++;
2080                 len--;
2081         }
2082         tls_certificate_set_copy(&cert->sign_key, val, len);
2083         if (cert->sign_key) {
2084                 cert->sign_len = len;
2085         }
2086 }
2087
2088 void tls_certificate_set_exponent(struct TLSCertificate *cert,
2089                                   const unsigned char *val, int len) {
2090         tls_certificate_set_copy(&cert->exponent, val, len);
2091         if (cert->exponent) {
2092                 cert->exponent_len = len;
2093         }
2094 }
2095
2096 void tls_certificate_set_serial(struct TLSCertificate *cert,
2097                                 const unsigned char *val, int len) {
2098         tls_certificate_set_copy(&cert->serial_number, val, len);
2099         if (cert->serial_number) {
2100                 cert->serial_len = len;
2101         }
2102 }
2103
2104 void tls_certificate_set_algorithm(unsigned int *algorithm,
2105                                    const unsigned char *val, int len) {
2106         if (len == 7 && _is_oid(val, TLS_EC_PUBLIC_KEY_OID, 7)) {
2107                 *algorithm = TLS_EC_PUBLIC_KEY;
2108                 return;
2109         }
2110
2111         if (len == 8) {
2112                 if (_is_oid(val, TLS_EC_prime192v1_OID, len)) {
2113                         *algorithm = TLS_EC_prime192v1;
2114                         return;
2115                 }
2116                 if (_is_oid(val, TLS_EC_prime192v2_OID, len)) {
2117                         *algorithm = TLS_EC_prime192v2;
2118                         return;
2119                 }
2120                 if (_is_oid(val, TLS_EC_prime192v3_OID, len)) {
2121                         *algorithm = TLS_EC_prime192v3;
2122                         return;
2123                 }
2124                 if (_is_oid(val, TLS_EC_prime239v1_OID, len)) {
2125                         *algorithm = TLS_EC_prime239v1;
2126                         return;
2127                 }
2128                 if (_is_oid(val, TLS_EC_prime239v2_OID, len)) {
2129                         *algorithm = TLS_EC_prime239v2;
2130                         return;
2131                 }
2132                 if (_is_oid(val, TLS_EC_prime239v3_OID, len)) {
2133                         *algorithm = TLS_EC_prime239v3;
2134                         return;
2135                 }
2136                 if (_is_oid(val, TLS_EC_prime256v1_OID, len)) {
2137                         *algorithm = TLS_EC_prime256v1;
2138                         return;
2139                 }
2140         }
2141         if (len == 5) {
2142                 if (_is_oid2
2143                     (val, TLS_EC_secp224r1_OID, len,
2144                      sizeof(TLS_EC_secp224r1_OID) - 1)) {
2145                         *algorithm = TLS_EC_secp224r1;
2146                         return;
2147                 }
2148                 if (_is_oid2
2149                     (val, TLS_EC_secp384r1_OID, len,
2150                      sizeof(TLS_EC_secp384r1_OID) - 1)) {
2151                         *algorithm = TLS_EC_secp384r1;
2152                         return;
2153                 }
2154                 if (_is_oid2
2155                     (val, TLS_EC_secp521r1_OID, len,
2156                      sizeof(TLS_EC_secp521r1_OID) - 1)) {
2157                         *algorithm = TLS_EC_secp521r1;
2158                         return;
2159                 }
2160         }
2161         if (len != 9) {
2162                 return;
2163         }
2164
2165         if (_is_oid(val, TLS_RSA_SIGN_SHA256_OID, 9)) {
2166                 *algorithm = TLS_RSA_SIGN_SHA256;
2167                 return;
2168         }
2169
2170         if (_is_oid(val, TLS_RSA_SIGN_RSA_OID, 9)) {
2171                 *algorithm = TLS_RSA_SIGN_RSA;
2172                 return;
2173         }
2174
2175         if (_is_oid(val, TLS_RSA_SIGN_SHA1_OID, 9)) {
2176                 *algorithm = TLS_RSA_SIGN_SHA1;
2177                 return;
2178         }
2179
2180         if (_is_oid(val, TLS_RSA_SIGN_SHA512_OID, 9)) {
2181                 *algorithm = TLS_RSA_SIGN_SHA512;
2182                 return;
2183         }
2184
2185         if (_is_oid(val, TLS_RSA_SIGN_SHA384_OID, 9)) {
2186                 *algorithm = TLS_RSA_SIGN_SHA384;
2187                 return;
2188         }
2189
2190         if (_is_oid(val, TLS_RSA_SIGN_MD5_OID, 9)) {
2191                 *algorithm = TLS_RSA_SIGN_MD5;
2192                 return;
2193         }
2194 }
2195
2196 void tls_destroy_certificate(struct TLSCertificate *cert) {
2197         if (cert) {
2198                 int i;
2199                 free(cert->exponent);
2200                 free(cert->pk);
2201                 free(cert->issuer_country);
2202                 free(cert->issuer_state);
2203                 free(cert->issuer_location);
2204                 free(cert->issuer_entity);
2205                 free(cert->issuer_subject);
2206                 free(cert->country);
2207                 free(cert->state);
2208                 free(cert->location);
2209                 free(cert->subject);
2210                 for (i = 0; i < cert->san_length; i++) {
2211                         free(cert->san[i]);
2212                 }
2213                 free(cert->san);
2214                 free(cert->ocsp);
2215                 free(cert->serial_number);
2216                 free(cert->entity);
2217                 cert->not_before[0] = 0;
2218                 cert->not_after[0] = 0;
2219                 free(cert->sign_key);
2220                 free(cert->priv);
2221                 free(cert->der_bytes);
2222                 free(cert->bytes);
2223                 free(cert->fingerprint);
2224                 free(cert);
2225         }
2226 }
2227
2228 struct TLSPacket *tls_create_packet(struct TLSContext *context,
2229                                     unsigned char type,
2230                                     unsigned short version,
2231                                     int payload_size_hint) {
2232         struct TLSPacket *packet = malloc(sizeof *packet);
2233         if (!packet) {
2234                 return NULL;
2235         }
2236         packet->broken = 0;
2237         if (payload_size_hint > 0) {
2238                 packet->size = payload_size_hint + 10;
2239         } else {
2240                 packet->size = TLS_BLOB_INCREMENT;
2241         }
2242         packet->buf = malloc(packet->size);
2243         memset(packet->buf, 0, packet->size);
2244         packet->context = context;
2245         if (!packet->buf) {
2246                 free(packet);
2247                 return NULL;
2248         }
2249         if (context) {
2250                 packet->payload_pos = 6;
2251                 packet->len = packet->payload_pos - 1;
2252         } else {
2253                 packet->len = 5;
2254         }
2255         packet->buf[0] = type;
2256
2257         /* big endian protocol version */
2258         packet->buf[1] = version >> 8; 
2259         packet->buf[2] = version & 0xff;
2260         if (version == TLS_V13) {
2261                 packet->buf[2] = 0x04;
2262         }
2263
2264         return packet;
2265 }
2266
2267 void tls_destroy_packet(struct TLSPacket *packet) {
2268         if (packet) {
2269                 if (packet->buf) {
2270                         free(packet->buf);
2271                 }
2272                 free(packet);
2273         }
2274 }
2275
2276 int tls_crypto_create(struct TLSContext *context, int key_length,
2277                                unsigned char *localkey,
2278                                unsigned char *localiv,
2279                                unsigned char *remotekey,
2280                                unsigned char *remoteiv) {
2281         if (context->crypto.created) {
2282                 if (context->crypto.created == 1) {
2283                         cbc_done(&context->crypto.ctx_remote.aes_remote);
2284                         cbc_done(&context->crypto.ctx_local.aes_local);
2285                 } else {
2286                         if (context->crypto.created == 2) {
2287                                 unsigned char dummy_buffer[32];
2288                                 unsigned long tag_len = 0;
2289                                 gcm_done(&context->crypto.ctx_remote.
2290                                          aes_gcm_remote, dummy_buffer,
2291                                          &tag_len);
2292                                 gcm_done(&context->crypto.ctx_local.
2293                                          aes_gcm_local, dummy_buffer,
2294                                          &tag_len);
2295                         }
2296                 }
2297                 context->crypto.created = 0;
2298         }
2299         int is_aead = tls_is_aead(context);
2300         int cipherID = find_cipher("aes");
2301         DEBUG_PRINT("Using cipher ID: %x\n", (int) context->cipher);
2302         if (is_aead == 2) {
2303                 unsigned int counter = 1;
2304
2305                 chacha_keysetup(&context->crypto.ctx_local.chacha_local,
2306                                 localkey, key_length * 8);
2307                 chacha_ivsetup_96bitnonce(&context->crypto.ctx_local.
2308                                           chacha_local, localiv,
2309                                           (unsigned char *) &counter);
2310
2311                 chacha_keysetup(&context->crypto.ctx_remote.chacha_remote,
2312                                 remotekey, key_length * 8);
2313                 chacha_ivsetup_96bitnonce(&context->crypto.ctx_remote.
2314                                           chacha_remote, remoteiv,
2315                                           (unsigned char *) &counter);
2316
2317                 context->crypto.created = 3;
2318         } else {
2319                 if (is_aead) {
2320                         int res1 =
2321                                 gcm_init(&context->crypto.ctx_local.aes_gcm_local,
2322                                                 cipherID, localkey, key_length);
2323                         int res2 =
2324                                 gcm_init(&context->crypto.ctx_remote.aes_gcm_remote,
2325                                                 cipherID, remotekey, key_length);
2326
2327                         if (res1 || res2) {
2328                                 return TLS_GENERIC_ERROR;
2329                         }
2330                         context->crypto.created = 2;
2331                 } else {
2332                         int res1 =
2333                                 cbc_start(cipherID, localiv, localkey, key_length, 0,
2334                                                 &context->crypto.ctx_local.aes_local);
2335                         int res2 =
2336                                 cbc_start(cipherID, remoteiv, remotekey, key_length, 0,
2337                                                 &context->crypto.ctx_remote.aes_remote);
2338
2339                         if (res1 || res2) {
2340                                 return TLS_GENERIC_ERROR;
2341                         }
2342                         context->crypto.created = 1;
2343                 }
2344         }
2345         return 0;
2346 }
2347
2348 static void tls_crypto_done(struct TLSContext *context) {
2349         unsigned char dummy_buffer[32];
2350         unsigned long tag_len = 0;
2351
2352         switch (context->crypto.created) {
2353                 case 1:
2354                         cbc_done(&context->crypto.ctx_remote.aes_remote);
2355                         cbc_done(&context->crypto.ctx_local.aes_local);
2356                         break;
2357                 case 2:
2358                         gcm_done(&context->crypto.ctx_remote.aes_gcm_remote,
2359                                         dummy_buffer, &tag_len);
2360                         gcm_done(&context->crypto.ctx_local.aes_gcm_local,
2361                                         dummy_buffer, &tag_len);
2362                         break;
2363         }
2364         context->crypto.created = 0;
2365 }
2366
2367 int tls_packet_append(struct TLSPacket *packet, const unsigned char *buf,
2368                       unsigned int len) {
2369         void *new;
2370
2371         if (!packet || packet->broken) {
2372                 return -1;
2373         }
2374
2375         if (!len) {
2376                 return 0;
2377         }
2378
2379         unsigned int new_len = packet->len + len;
2380
2381         if (new_len > packet->size) {
2382                 packet->size = (new_len / TLS_BLOB_INCREMENT + 1) *
2383                         TLS_BLOB_INCREMENT;
2384                 new = TLS_REALLOC(packet->buf, packet->size);
2385                 if (new) {
2386                         packet->buf = new;
2387                 } else {
2388                         free(packet->buf);
2389                         packet->size = 0;
2390                         packet->len = 0;
2391                         packet->broken = 1;
2392                         return -1;
2393                 }
2394         }
2395         memcpy(packet->buf + packet->len, buf, len);
2396         packet->len = new_len;
2397         return new_len;
2398 }
2399
2400 int tls_packet_uint8(struct TLSPacket *packet, unsigned char i) {
2401         return tls_packet_append(packet, &i, 1);
2402 }
2403
2404 int tls_packet_uint16(struct TLSPacket *packet, unsigned short i) {
2405         unsigned short ni = htons(i);
2406         return tls_packet_append(packet, (unsigned char *) &ni, 2);
2407 }
2408
2409 int tls_packet_uint32(struct TLSPacket *packet, unsigned int i) {
2410         unsigned int ni = htonl(i);
2411         return tls_packet_append(packet, (unsigned char *) &ni, 4);
2412 }
2413
2414 int tls_packet_uint24(struct TLSPacket *packet, unsigned int i) {
2415         unsigned char buf[3];
2416         buf[0] = (i >> 16) & 0xff;
2417         buf[1] = (i >> 8) & 0xff;
2418         buf[2] = (i >> 0) & 0xff;
2419
2420         return tls_packet_append(packet, buf, 3);
2421 }
2422
2423 int tls_random(unsigned char *key, int len) {
2424 #ifdef __APPLE__
2425         for (int i = 0; i < len; i++) {
2426                 unsigned int v = arc4random() % 0x100;
2427                 key[i] = (char) v;
2428         }
2429         return 1;
2430 #else
2431         /* TODO use open and read */
2432         FILE *fp = fopen("/dev/urandom", "r");
2433         if (fp) {
2434                 int key_len = fread(key, 1, len, fp);
2435                 fclose(fp);
2436                 if (key_len == len)
2437                         return 1;
2438         }
2439 #endif
2440         return 0;
2441 }
2442
2443 int tls_established(struct TLSContext *context) {
2444         if (context) {
2445                 if (context->critical_error) {
2446                         return -1;
2447                 }
2448
2449                 if (context->connection_status == TLS_CONNECTED) {
2450                         return 1;
2451                 }
2452         }
2453         return 0;
2454 }
2455
2456 void tls_read_clear(struct TLSContext *context) {
2457         if (context) {
2458                tls_buffer_free(&context->application_buffer); 
2459         }
2460 }
2461
2462 struct TLSContext *tls_create_context(int is_server, unsigned short version) {
2463         struct TLSContext zero = {0};
2464         uint16_t ver = 0;
2465         struct TLSContext *context = 0;
2466
2467         if (version == TLS_V13 && !is_server) {
2468                 /* TLS 1.3 clients not supported */
2469                 return NULL;
2470         }
2471
2472         tls_init();
2473         switch (version) {
2474                 case TLS_V13:
2475                 case TLS_V12:
2476                         context = malloc(sizeof *context);
2477                         break;
2478                 default:
2479                         return NULL;
2480         }
2481
2482         ver = version - 0x0201;
2483
2484         if (context) {
2485                 *context = zero;
2486                 context->is_server = is_server;
2487                 context->version = version;
2488                 context->tlsver = ver;
2489                 context->hs_index = -1;
2490                 /* set up output buffer */
2491                 tls_buffer_init(&context->output_buffer, 0);
2492                 tls_buffer_init(&context->input_buffer, 0);
2493                 tls_buffer_init(&context->cached_handshake, 0);
2494                 tls_buffer_init(&context->application_buffer, 0);
2495         }
2496         return context;
2497 }
2498
2499 struct TLSContext *tls_accept(struct TLSContext *context) {
2500         if (!context || !context->is_server) {
2501                 return NULL;
2502         }
2503
2504         struct TLSContext *child = malloc(sizeof *child);
2505         if (child) {
2506                 memset(child, 0, sizeof(struct TLSContext));
2507                 child->is_server = 1;
2508                 child->is_child = 1;
2509                 child->version = context->version;
2510                 child->certificates = context->certificates;
2511                 child->certificates_count = context->certificates_count;
2512                 child->private_key = context->private_key;
2513                 child->ec_private_key = context->ec_private_key;
2514                 child->root_certificates = context->root_certificates;
2515                 child->root_count = context->root_count;
2516                 child->default_dhe_p = context->default_dhe_p;
2517                 child->default_dhe_g = context->default_dhe_g;
2518                 child->curve = context->curve;
2519                 child->alpn = context->alpn;
2520                 child->alpn_count = context->alpn_count;
2521         }
2522         return child;
2523 }
2524
2525 int tls_add_alpn(struct TLSContext *context, const char *alpn) {
2526         void *new;
2527
2528         if (!context || !alpn || !alpn[0]
2529             || (context->is_server && context->is_child)) {
2530                 return TLS_GENERIC_ERROR;
2531         }
2532
2533         int len = strlen(alpn);
2534         if (tls_alpn_contains(context, alpn, len)) {
2535                 return 0;
2536         }
2537
2538         new = TLS_REALLOC(context->alpn, (context->alpn_count + 1) *
2539                         sizeof(char *));
2540         if (new) {
2541                 context->alpn = new;
2542         } else {
2543                 free(context->alpn);
2544                 context->alpn = 0;
2545                 context->alpn_count = 0;
2546                 return TLS_NO_MEMORY;
2547         }
2548         char *alpn_ref = malloc(len + 1);
2549         context->alpn[context->alpn_count] = alpn_ref;
2550         if (alpn_ref) {
2551                 memcpy(alpn_ref, alpn, len);
2552                 alpn_ref[len] = 0;
2553                 context->alpn_count++;
2554         } else {
2555                 return TLS_NO_MEMORY;
2556         }
2557         return 0;
2558 }
2559
2560 int tls_alpn_contains(struct TLSContext *context, const char *alpn,
2561                       unsigned char alpn_size) {
2562         int i;
2563
2564         if (!context || !alpn || !alpn_size || !context->alpn) {
2565                 return 0;
2566         }
2567
2568         for (i = 0; i < context->alpn_count; i++) {
2569                 const char *alpn_local = context->alpn[i];
2570                 if (alpn_local) {
2571                         int len = strlen(alpn_local);
2572                         if (alpn_size == len) {
2573                                 if (!memcmp(alpn_local, alpn, alpn_size)) {
2574                                         return 1;
2575                                 }
2576                         }
2577                 }
2578         }
2579
2580         return 0;
2581 }
2582
2583 void tls_destroy_context(struct TLSContext *context) {
2584         int i;
2585
2586         if (!context) {
2587                 return;
2588         }
2589
2590         if (!context->is_child) {
2591                 if (context->certificates) {
2592                         for (i = 0; i < context->certificates_count; i++) {
2593                                 tls_destroy_certificate(context->
2594                                                         certificates[i]);
2595                         }
2596                 }
2597                 if (context->root_certificates) {
2598                         for (i = 0; i < context->root_count; i++) {
2599                                 tls_destroy_certificate(context->
2600                                                         root_certificates[i]);
2601                         }
2602                         free(context->root_certificates);
2603                         context->root_certificates = NULL;
2604                 }
2605                 if (context->private_key) {
2606                         tls_destroy_certificate(context->private_key);
2607                 }
2608                 if (context->ec_private_key) {
2609                         tls_destroy_certificate(context->ec_private_key);
2610                 }
2611                 free(context->certificates);
2612                 free(context->default_dhe_p);
2613                 free(context->default_dhe_g);
2614                 if (context->alpn) {
2615                         for (i = 0; i < context->alpn_count; i++) {
2616                                 free(context->alpn[i]);
2617                         }
2618                         free(context->alpn);
2619                 }
2620         }
2621
2622         if (context->client_certificates) {
2623                 for (i = 0; i < context->client_certificates_count; i++) {
2624                         tls_destroy_certificate(context->
2625                                                 client_certificates[i]);
2626                 }
2627                 free(context->client_certificates);
2628         }
2629
2630         context->client_certificates = NULL;
2631         free(context->master_key);
2632         free(context->premaster_key);
2633
2634         if (context->crypto.created) {
2635                 tls_crypto_done(context);
2636         }
2637
2638         tls_done_hash(context, NULL);
2639         tls_destroy_hash(context);
2640
2641         tls_buffer_free(&context->output_buffer);
2642         tls_buffer_free(&context->input_buffer);
2643         tls_buffer_free(&context->application_buffer);
2644         tls_buffer_free(&context->cached_handshake);
2645         //free(context->cached_handshake);
2646
2647         free(context->sni);
2648         tls_dhe_free(context);
2649         tls_ecc_dhe_free(context);
2650         free(context->negotiated_alpn);
2651         free(context->finished_key);
2652         free(context->remote_finished_key);
2653         free(context->server_finished_hash);
2654         free(context);
2655 }
2656
2657 int tls_cipher_is_ephemeral(struct TLSContext *context) {
2658         if (!context) {
2659                 return 0;
2660         }
2661
2662         switch (context->cipher) {
2663                 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
2664                 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
2665                 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
2666                 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
2667                 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
2668                 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
2669                 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
2670                         return 1;
2671                 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
2672                 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
2673                 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
2674                 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
2675                 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
2676                 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
2677                 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
2678                 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
2679                 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
2680                 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
2681                 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
2682                 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
2683                 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
2684                         return 2;
2685                 case TLS_AES_128_GCM_SHA256:
2686                 case TLS_CHACHA20_POLY1305_SHA256:
2687                 case TLS_AES_128_CCM_SHA256:
2688                 case TLS_AES_128_CCM_8_SHA256:
2689                 case TLS_AES_256_GCM_SHA384:
2690                         if (context->dhe) {
2691                                 return 1;
2692                         }
2693                         return 2;
2694         }
2695         return 0;
2696 }
2697
2698 int tls_is_ecdsa(struct TLSContext *context) {
2699         if (!context) {
2700                 return 0;
2701         }
2702
2703         switch (context->cipher) {
2704                 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
2705                 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
2706                 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
2707                 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
2708                 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
2709                 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
2710                 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
2711                         return 1;
2712         }
2713
2714         if (context->ec_private_key) {
2715                 return 1;
2716         }
2717
2718         return 0;
2719 }
2720
2721 static void tls_send_server_key_exchange(struct TLSContext *context,
2722                                                 int method) {
2723         if (!context->is_server) {
2724                 DEBUG_PRINT
2725                     ("CANNOT BUILD SERVER KEY EXCHANGE MESSAGE FOR CLIENTS\n");
2726                 return;
2727         }
2728
2729         struct TLSPacket *packet =
2730             tls_create_packet(context, TLS_HANDSHAKE, context->version, 0);
2731         tls_packet_uint8(packet, 0x0C);
2732         unsigned char dummy[3];
2733         tls_packet_append(packet, dummy, 3);
2734         int start_len = packet->len;
2735
2736         if (method == KEA_dhe_rsa) {
2737                 tls_dhe_create(context);
2738
2739                 const char *default_dhe_p = context->default_dhe_p;
2740                 const char *default_dhe_g = context->default_dhe_g;
2741                 int key_size;
2742                 if (!default_dhe_p || !default_dhe_g) {
2743                         default_dhe_p = TLS_DH_DEFAULT_P;
2744                         default_dhe_g = TLS_DH_DEFAULT_G;
2745                         key_size = TLS_DHE_KEY_SIZE / 8;
2746                 } else {
2747                         key_size = strlen(default_dhe_p);
2748                 }
2749                 if (tls_dh_make_key(key_size, context->dhe, default_dhe_p,
2750                                         default_dhe_g, 0, 0)) {
2751                         DEBUG_PRINT("ERROR CREATING DHE KEY\n");
2752                         free(packet);
2753                         free(context->dhe);
2754                         context->dhe = NULL;
2755                         /* TODO set error */
2756                         return;
2757                 }
2758
2759                 unsigned char dh_Ys[0xFFF];
2760                 unsigned char dh_p[0xFFF];
2761                 unsigned char dh_g[0xFFF];
2762                 unsigned long dh_p_len = sizeof(dh_p);
2763                 unsigned long dh_g_len = sizeof(dh_g);
2764                 unsigned long dh_Ys_len = sizeof(dh_Ys);
2765
2766                 if (tls_dh_export_pqY
2767                     (dh_p, &dh_p_len, dh_g, &dh_g_len, dh_Ys, &dh_Ys_len,
2768                      context->dhe)) {
2769                         DEBUG_PRINT("ERROR EXPORTING DHE KEY\n");
2770                         free(packet);
2771                         /* TODO set error */
2772                         return;
2773                 }
2774
2775                 DEBUG_PRINT("LEN: %lu (%lu, %lu)\n", dh_Ys_len, dh_p_len,
2776                             dh_g_len);
2777                 DEBUG_DUMP_HEX_LABEL("DHE PK", dh_Ys, dh_Ys_len);
2778                 DEBUG_DUMP_HEX_LABEL("DHE P", dh_p, dh_p_len);
2779                 DEBUG_DUMP_HEX_LABEL("DHE G", dh_g, dh_g_len);
2780
2781                 tls_packet_uint16(packet, dh_p_len);
2782                 tls_packet_append(packet, dh_p, dh_p_len);
2783
2784                 tls_packet_uint16(packet, dh_g_len);
2785                 tls_packet_append(packet, dh_g, dh_g_len);
2786
2787                 tls_packet_uint16(packet, dh_Ys_len);
2788                 tls_packet_append(packet, dh_Ys, dh_Ys_len);
2789                 /* dh_p */
2790                 /* dh_g */
2791                 /* dh_Ys */
2792         } else if (method == KEA_ec_diffie_hellman) {
2793                 /* 3 = named curve */
2794                 if (!context->curve) {
2795                         context->curve = tls_ecc_default_curve;
2796                 }
2797                 tls_packet_uint8(packet, 3);
2798                 tls_packet_uint16(packet, context->curve->iana);
2799                 tls_ecc_dhe_create(context);
2800
2801                 ltc_ecc_set_type *dp =
2802                     (ltc_ecc_set_type *) & context->curve->dp;
2803
2804                 if (ecc_make_key_ex(NULL, find_prng("sprng"), context->ecc_dhe,
2805                                         dp)) {
2806                         free(context->ecc_dhe);
2807                         context->ecc_dhe = NULL;
2808                         DEBUG_PRINT("Error generating ECC key\n");
2809                         free(packet);
2810                         /* TODO set error */
2811                         return;
2812                 }
2813                 unsigned char out[TLS_MAX_RSA_KEY];
2814                 unsigned long out_len = TLS_MAX_RSA_KEY;
2815                 if (ecc_ansi_x963_export(context->ecc_dhe, out, &out_len)) {
2816                         DEBUG_PRINT("Error exporting ECC key\n");
2817                         free(packet);
2818                         /* TODO abort */
2819                         return; 
2820                 }
2821                 tls_packet_uint8(packet, out_len);
2822                 tls_packet_append(packet, out, out_len);
2823         } else {
2824                 /* TODO abort */
2825                 free(packet);
2826                 DEBUG_PRINT("Unsupported ephemeral method: %i\n", method);
2827                 return;
2828         }
2829
2830         /* signature */
2831         unsigned int params_len = packet->len - start_len;
2832         unsigned int message_len =
2833             params_len + TLS_CLIENT_RANDOM_SIZE + TLS_SERVER_RANDOM_SIZE;
2834         unsigned char *message = malloc(message_len);
2835         if (message) {
2836                 unsigned char out[TLS_MAX_RSA_KEY];
2837                 unsigned long out_len = TLS_MAX_RSA_KEY;
2838
2839                 int hash_algorithm;
2840
2841                 hash_algorithm = sha256;
2842
2843                 if (tls_is_ecdsa(context)) {
2844                         hash_algorithm = sha512;
2845                         tls_packet_uint8(packet, hash_algorithm);
2846                         tls_packet_uint8(packet, ecdsa);
2847                 } else {
2848                         tls_packet_uint8(packet, hash_algorithm);
2849                         tls_packet_uint8(packet, rsa_sign);
2850                 }
2851
2852                 memcpy(message, context->remote_random,
2853                                 TLS_CLIENT_RANDOM_SIZE);
2854                 memcpy(message + TLS_CLIENT_RANDOM_SIZE, context->local_random,
2855                                 TLS_SERVER_RANDOM_SIZE);
2856                 memcpy(message + TLS_CLIENT_RANDOM_SIZE +
2857                                 TLS_SERVER_RANDOM_SIZE, packet->buf +
2858                                 start_len, params_len);
2859                 if (tls_is_ecdsa(context)) {
2860                         if (sign_ecdsa(context, hash_algorithm, message,
2861                                                 message_len, out, &out_len) ==
2862                                         1) {
2863                                 DEBUG_PRINT
2864                                     ("Signing OK! (ECDSA, length %lu)\n",
2865                                      out_len);
2866                                 tls_packet_uint16(packet, out_len);
2867                                 tls_packet_append(packet, out, out_len);
2868                         }
2869                 } else
2870                 if (sign_rsa(context, hash_algorithm, message, message_len,
2871                                         out, &out_len) == 1) {
2872                         DEBUG_PRINT("Signing OK! (length %lu)\n", out_len);
2873                         tls_packet_uint16(packet, out_len);
2874                         tls_packet_append(packet, out, out_len);
2875                 }
2876                 free(message);
2877         }
2878         if (!packet->broken && packet->buf) {
2879                 tls_set_packet_length(packet, packet->len - start_len);
2880         }
2881         tls_packet_update(packet);
2882         tls_queue_packet(packet);
2883         return;
2884 }
2885
2886 #if 0
2887 void _private_tls_set_session_id(struct TLSContext *context) {
2888         if (context->tlsver == TLS_VERSION13
2889                         && context->session_size == TLS_MAX_SESSION_ID) {
2890                 return;
2891         }
2892
2893         if (tls_random(context->session, TLS_MAX_SESSION_ID)) {
2894                 context->session_size = TLS_MAX_SESSION_ID;
2895         } else {
2896                 context->session_size = 0;
2897         }
2898 }
2899 #endif
2900
2901 struct TLSPacket *tls_certificate_request(struct TLSContext *context) {
2902         if (!context || !context->is_server) {
2903                 return NULL;
2904         }
2905
2906         unsigned short packet_version = context->version;
2907         struct TLSPacket *packet =
2908             tls_create_packet(context, TLS_HANDSHAKE, packet_version, 0);
2909
2910         if (!packet) {
2911                 return NULL;
2912         }
2913
2914         /* cert request and size placeholder */
2915         unsigned char dummy[] = { 0x0d, 0, 0, 0 };
2916         tls_packet_append(packet, dummy, sizeof dummy);
2917
2918         int start_len = packet->len;
2919
2920         if (context->tlsver == TLS_VERSION13) {
2921                 /* certificate request context */
2922                 tls_packet_uint8(packet, 0);
2923                 /* extensions */
2924                 tls_packet_uint16(packet, 18);
2925                 /* signature algorithms */
2926                 tls_packet_uint16(packet, 0x0D);
2927                 tls_packet_uint16(packet, 14);
2928                 tls_packet_uint16(packet, 12);
2929 #if 0
2930                 rsa_pkcs1_sha256
2931                         tls_packet_uint16(packet, 0x0401);
2932                 rsa_pkcs1_sha384
2933                         tls_packet_uint16(packet, 0x0501);
2934                 rsa_pkcs1_sha512
2935                         tls_packet_uint16(packet, 0x0601);
2936 #endif
2937
2938                 /* ecdsa_secp256r1_sha256 */
2939                 tls_packet_uint16(packet, 0x0403);
2940                 /* ecdsa_secp384r1_sha384 */
2941                 tls_packet_uint16(packet, 0x0503);
2942                 /* ecdsa_secp521r1_sha512 */
2943                 tls_packet_uint16(packet, 0x0604);
2944                 /* rsa_pss_rsae_sha256 */
2945                 tls_packet_uint16(packet, 0x0804);
2946                 /* rsa_pss_rsae_sha384 */
2947                 tls_packet_uint16(packet, 0x0805);
2948                 /* rsa_pss_rsae_sha512 */
2949                 tls_packet_uint16(packet, 0x0806);
2950         } else {
2951                 tls_packet_uint8(packet, 1);
2952                 tls_packet_uint8(packet, rsa_sign);
2953                 if (context->version == TLS_V12) {
2954                         /* 10 pairs or 2 bytes */
2955                         tls_packet_uint16(packet, 10);
2956                         tls_packet_uint8(packet, sha256);
2957                         tls_packet_uint8(packet, rsa);
2958                         tls_packet_uint8(packet, sha1);
2959                         tls_packet_uint8(packet, rsa);
2960                         tls_packet_uint8(packet, sha384);
2961                         tls_packet_uint8(packet, rsa);
2962                         tls_packet_uint8(packet, sha512);
2963                         tls_packet_uint8(packet, rsa);
2964                         tls_packet_uint8(packet, md5);
2965                         tls_packet_uint8(packet, rsa);
2966                 }
2967                 /* no DistinguishedName yet */
2968                 tls_packet_uint16(packet, 0);
2969         }
2970         if (!packet->broken) {
2971                 tls_set_packet_length(packet, packet->len - start_len);
2972         }
2973         tls_packet_update(packet);
2974         return packet;
2975 }
2976
2977 int tls_parse_key_share(struct TLSContext *context, const unsigned char *buf,
2978                 int buf_len) {
2979         int i = 0;
2980         struct ECCCurveParameters *curve = 0;
2981         struct DHKey *dhkey = 0;
2982         int dhe_key_size = 0;
2983         const unsigned char *buffer = NULL;
2984         unsigned char *out2;
2985         unsigned long out_size;
2986         uint16_t key_size;
2987
2988         while (buf_len >= 4) {
2989                 uint16_t named_group = get16(&buf[i]);
2990                 i += 2;
2991                 buf_len -= 2;
2992
2993                 key_size = get16(&buf[i]);
2994                 i += 2;
2995                 buf_len -= 2;
2996
2997                 if (key_size > buf_len) {
2998                         return TLS_BROKEN_PACKET;
2999                 }
3000
3001                 switch (named_group) {
3002                         case 0x0017:
3003                                 curve = &secp256r1;
3004                                 buffer = &buf[i];
3005                                 DEBUG_PRINT("KEY SHARE => secp256r1\n");
3006                                 buf_len = 0;
3007                                 continue;
3008                         case 0x0018:
3009                                 /* secp384r1 */
3010                                 curve = &secp384r1;
3011                                 buffer = &buf[i];
3012                                 DEBUG_PRINT("KEY SHARE => secp384r1\n");
3013                                 buf_len = 0;
3014                                 continue;
3015                         case 0x0019:
3016                                 /* secp521r1 */
3017                                 break;
3018                         case 0x001D:
3019                                 /* x25519 */
3020                                 if (key_size != 32) {
3021                                         DEBUG_PRINT
3022                                                 ("INVALID x25519 KEY SIZE (%i)\n",
3023                                                  key_size);
3024                                         continue;
3025                                 }
3026                                 curve = &curve25519;
3027                                 buffer = &buf[i];
3028                                 DEBUG_PRINT("KEY SHARE => x25519\n");
3029                                 buf_len = 0;
3030                                 continue;
3031                                 break;
3032
3033                         case 0x001E:
3034                                 /* x448 */
3035                                 break;
3036                         case 0x0100:
3037                                 dhkey = &ffdhe2048;
3038                                 dhe_key_size = 2048;
3039                                 break;
3040                         case 0x0101:
3041                                 dhkey = &ffdhe3072;
3042                                 dhe_key_size = 3072;
3043                                 break;
3044                         case 0x0102:
3045                                 dhkey = &ffdhe4096;
3046                                 dhe_key_size = 4096;
3047                                 break;
3048                         case 0x0103:
3049                                 dhkey = &ffdhe6144;
3050                                 dhe_key_size = 6144;
3051                                 break;
3052                         case 0x0104:
3053                                 dhkey = &ffdhe8192;
3054                                 dhe_key_size = 8192;
3055                                 break;
3056                 }
3057                 i += key_size;
3058                 buf_len -= key_size;
3059         }
3060
3061         if (curve) {
3062                 context->curve = curve;
3063
3064                 if (curve == &curve25519) {
3065                         if (!tls_random(context->local_random,
3066                              TLS_SERVER_RANDOM_SIZE)) {
3067                                 return TLS_GENERIC_ERROR;
3068                         }
3069
3070                         unsigned char secret[32];
3071                         static const unsigned char basepoint[32] = { 9 };
3072
3073                         tls_random(secret, 32);
3074
3075                         secret[0] &= 248;
3076                         secret[31] &= 127;
3077                         secret[31] |= 64;
3078
3079                         /* use finished key to store public key */
3080                         free(context->finished_key);
3081                         context->finished_key = malloc(32);
3082                         if (!context->finished_key) {
3083                                 return TLS_GENERIC_ERROR;
3084                         }
3085
3086                         x25519(context->finished_key, secret, basepoint);
3087
3088                         free(context->premaster_key);
3089                         context->premaster_key = malloc(32);
3090
3091                         if (!context->premaster_key) {
3092                                 return TLS_GENERIC_ERROR;
3093                         }
3094
3095                         x25519(context->premaster_key, secret, buffer);
3096                         context->premaster_key_len = 32;
3097
3098                         return 0;
3099                 }
3100
3101                 tls_ecc_dhe_create(context);
3102                 ltc_ecc_set_type *dp = (ltc_ecc_set_type *)&context->curve->dp;
3103
3104                 if (ecc_make_key_ex(NULL, find_prng("sprng"), context->ecc_dhe,
3105                                         dp)) {
3106                         free(context->ecc_dhe);
3107                         context->ecc_dhe = NULL;
3108                         DEBUG_PRINT("Error generating ECC DHE key\n");
3109                         return TLS_GENERIC_ERROR;
3110                 }
3111
3112                 if (!tls_random(context->local_random, TLS_SERVER_RANDOM_SIZE)) {
3113                         return TLS_GENERIC_ERROR;
3114                 }
3115
3116                 ecc_key client_key;
3117                 memset(&client_key, 0, sizeof client_key);
3118                 if (ecc_ansi_x963_import_ex
3119                     (buffer, key_size, &client_key, dp)) {
3120                         DEBUG_PRINT("Error importing ECC DHE key\n");
3121                         return TLS_GENERIC_ERROR;
3122                 }
3123                 out2 = malloc(key_size);
3124                 out_size = key_size;
3125
3126                 int err = ecc_shared_secret(context->ecc_dhe, &client_key,
3127                                 out2, &out_size);
3128                 ecc_free(&client_key);
3129
3130                 if (err) {
3131                         DEBUG_PRINT("ECC DHE DECRYPT ERROR %i\n", err);
3132                         free(out2);
3133                         return TLS_GENERIC_ERROR;
3134                 }
3135
3136                 DEBUG_PRINT("OUT_SIZE: %lu\n", out_size);
3137                 DEBUG_DUMP_HEX_LABEL("ECC DHE", out2, out_size);
3138
3139                 free(context->premaster_key);
3140                 context->premaster_key = out2;
3141                 context->premaster_key_len = out_size;
3142                 return 0;
3143         } else if (dhkey) {
3144                 tls_dhe_create(context);
3145                 if (!tls_random(context->local_random, TLS_SERVER_RANDOM_SIZE))
3146                 {
3147                         return TLS_GENERIC_ERROR;
3148                 }
3149
3150                 if (tls_dh_make_key(dhe_key_size / 8, context->dhe,
3151                      (const char *)dhkey->p, (const char *)dhkey->g, 0, 0)) {
3152                         free(context->dhe);
3153                         context->dhe = NULL;
3154                         DEBUG_PRINT("Error generating DHE key\n");
3155                         return TLS_GENERIC_ERROR;
3156                 }
3157
3158                 unsigned int dhe_out_size;
3159                 out2 = tls_decrypt_dhe(context, buffer, key_size,
3160                                 &dhe_out_size, 0);
3161                 if (!out2) {
3162                         DEBUG_PRINT("Error generating DHE shared key\n");
3163                         return TLS_GENERIC_ERROR;
3164                 }
3165
3166                 free(context->premaster_key);
3167                 context->premaster_key = out2;
3168                 context->premaster_key_len = dhe_out_size;
3169                 if (context->dhe) {
3170                         context->dhe->iana = dhkey->iana;
3171                 }
3172                 return 0;
3173         }
3174         DEBUG_PRINT("NO COMMON KEY SHARE SUPPORTED\n");
3175         return TLS_NO_COMMON_CIPHER;
3176 }
3177
3178 int tls_parse_certificate(struct TLSContext *context,
3179                           const unsigned char *buf, int buf_len,
3180                           int is_client) {
3181         int res = 0;
3182         if (buf_len < 3) {
3183                 return TLS_NEED_MORE_DATA;
3184         }
3185
3186         int size = get24(buf);
3187
3188         /* not enough data, so just consume all of it */
3189         if (size <= 4) {
3190                 return 3 + size;
3191         }
3192
3193         res += 3; /* skip over the size field */
3194
3195         if (context->tlsver == TLS_VERSION13) {
3196                 int context_size = buf[res];
3197                 res++;
3198                 /* must be 0 */
3199                 if (context_size) {
3200                         res += context_size;
3201                 }
3202         }
3203
3204         if (buf_len - res < size) {
3205                 return TLS_NEED_MORE_DATA;
3206         }
3207
3208         int idx = 0;
3209         int valid_certificate = 0;
3210         while (size > 0) {
3211                 idx++;
3212                 if (buf_len - res < 3) {
3213                         return TLS_NEED_MORE_DATA;
3214                 }
3215                 int certificate_size = get24(buf+res);
3216                 res += 3;
3217                 if (buf_len - res < certificate_size) {
3218                         return TLS_NEED_MORE_DATA;
3219                 }
3220                 /* load chain */
3221                 int certificates_in_chain = 0;
3222                 int res2 = res;
3223                 unsigned int remaining = certificate_size;
3224                 do {
3225                         if (remaining <= 3) {
3226                                 break;
3227                         }
3228                         certificates_in_chain++;
3229                         unsigned int certificate_size2 = get24(buf+res2);
3230                         res2 += 3;
3231                         remaining -= 3;
3232                         if (certificate_size2 > remaining) {
3233                                 DEBUG_PRINT
3234                                     ("Invalid certificate size (%i from %i bytes remaining)\n",
3235                                      certificate_size2, remaining);
3236                                 break;
3237                         }
3238                         remaining -= certificate_size2;
3239
3240                         struct TLSCertificate *cert = asn1_parse(context,
3241                                                                  &buf
3242                                                                  [res2],
3243                                                                  certificate_size2,
3244                                                                  is_client);
3245                         if (cert) {
3246                                 if (certificate_size2) {
3247                                         cert->bytes =
3248                                             malloc(certificate_size2);
3249                                         if (cert->bytes) {
3250                                                 cert->len =
3251                                                     certificate_size2;
3252                                                 memcpy(cert->bytes,
3253                                                        &buf[res2],
3254                                                        certificate_size2);
3255                                         }
3256                                 }
3257                                 /* valid certificate */
3258                                 if (is_client) {
3259                                         void *new;
3260                                         valid_certificate = 1;
3261
3262                                         new =
3263                                             TLS_REALLOC(context->
3264                                                         client_certificates,
3265                                                         (context->
3266                                                          client_certificates_count
3267                                                          +
3268                                                          1) *
3269                                                         sizeof(struct
3270                                                                TLSCertificate
3271                                                                *));
3272
3273                                         if (!new) {
3274                                                 free(context->
3275                                                          client_certificates);
3276                                                 context->
3277                                                     client_certificates =
3278                                                     0;
3279                                                 return TLS_NO_MEMORY;
3280                                         }
3281
3282                                         context->client_certificates = new;
3283                                         context->
3284                                             client_certificates
3285                                             [context->client_certificates_count]
3286                                             = cert;
3287                                         context->
3288                                             client_certificates_count++;
3289                                 } else {
3290                                         void *new;
3291                                         new =
3292                                             TLS_REALLOC(context->
3293                                                         certificates,
3294                                                         (context->
3295                                                          certificates_count
3296                                                          +
3297                                                          1) *
3298                                                         sizeof(struct
3299                                                                TLSCertificate
3300                                                                *));
3301                                         if (!new) {
3302                                                 free(context->
3303                                                          certificates);
3304                                                 context->certificates = 0;
3305                                                 return TLS_NO_MEMORY;
3306                                         }
3307                                         context->certificates = new;
3308                                         context->certificates[context->
3309                                                               certificates_count]
3310                                             = cert;
3311                                         context->certificates_count++;
3312                                         if ((cert->pk) || (cert->priv))
3313                                                 valid_certificate = 1;
3314                                         else if (!context->is_server)
3315                                                 valid_certificate = 1;
3316                                 }
3317                         }
3318                         res2 += certificate_size2;
3319                         /* extension */
3320                         if (context->tlsver == TLS_VERSION13) {
3321                                 if (remaining >= 2) {
3322                                         /* ignore extensions */
3323                                         remaining -= 2;
3324                                         uint16_t size = get16(&buf[res2]);
3325                                         if (size && size >= remaining) {
3326                                                 res2 += size;
3327                                                 remaining -= size;
3328                                         }
3329                                 }
3330                         }
3331                 } while (remaining > 0);
3332                 if (remaining) {
3333                         DEBUG_PRINT("Extra %i bytes after certificate\n",
3334                                     remaining);
3335                 }
3336                 size -= certificate_size + 3;
3337                 res += certificate_size;
3338         }
3339         if (!valid_certificate) {
3340                 return TLS_UNSUPPORTED_CERTIFICATE;
3341         }
3342         if (res != buf_len) {
3343                 DEBUG_PRINT("Warning: %i bytes read from %i byte buffer\n",
3344                             (int) res, (int) buf_len);
3345         }
3346         return res;
3347 }
3348
3349 static int parse_dh( const unsigned char *buf, int buf_len, const unsigned char
3350                 **out, int *out_size) {
3351         int res = 0;
3352         *out = NULL;
3353         *out_size = 0;
3354         if (buf_len < 2) {
3355                 return TLS_NEED_MORE_DATA;
3356         }
3357         uint16_t size = get16(buf);
3358         res += 2;
3359         if (buf_len - res < size) {
3360                 return TLS_NEED_MORE_DATA;
3361         }
3362         DEBUG_DUMP_HEX(&buf[res], size);
3363         *out = &buf[res];
3364         *out_size = size;
3365         res += size;
3366         return res;
3367 }
3368
3369 static int tls_parse_random(struct TLSContext *context,
3370                               const unsigned char *buf, int buf_len) {
3371         int res = 0;
3372         int ephemeral = tls_cipher_is_ephemeral(context);
3373         uint16_t size;
3374         if (ephemeral == 2) {
3375                 if (buf_len < 1) {
3376                         return TLS_NEED_MORE_DATA;
3377                 }
3378                 size = buf[0];
3379                 res += 1;
3380         } else {
3381                 if (buf_len < 2) {
3382                         return TLS_NEED_MORE_DATA;
3383                 }
3384                 size = get16(buf);
3385                 res += 2;
3386         }
3387
3388         if (buf_len - res < size) {
3389                 return TLS_NEED_MORE_DATA;
3390         }
3391         unsigned int out_len = 0;
3392         unsigned char *random = NULL;
3393         switch (ephemeral) {
3394                 case 1:
3395                         random = tls_decrypt_dhe(context, &buf[res], size, &out_len,
3396                                         1);
3397                         break;
3398                 case 2:
3399                         random = tls_decrypt_ecc_dhe(context, &buf[res], size,
3400                                         &out_len, 1);
3401                         break;
3402                 default:
3403                         random = decrypt_rsa(context, &buf[res], size,
3404                                         &out_len);
3405         }
3406
3407         if (random && out_len > 2) {
3408                 /* *(unsigned short *)&random[0] = htons(context->version); */
3409                 DEBUG_DUMP_HEX_LABEL("PRE MASTER KEY", random, out_len);
3410                 free(context->premaster_key);
3411                 context->premaster_key = random;
3412                 context->premaster_key_len = out_len;
3413                 tls_compute_key(context, 48);
3414         } else {
3415                 free(random);
3416                 return 0;
3417         }
3418         res += size;
3419         return res;
3420 }
3421
3422 static const unsigned char *parse_signature(const unsigned char *buf, int
3423                 buf_len, int *hash_algorithm, int *sign_algorithm, int
3424                 *sig_size, int *offset) {
3425         int res = 0;
3426         if (buf_len < 2) {
3427                 return NULL;
3428         }
3429         *hash_algorithm = _md5_sha1;
3430         *sign_algorithm = rsa_sign;
3431         *sig_size = 0;
3432         *hash_algorithm = buf[res];
3433         res++;
3434         *sign_algorithm = buf[res];
3435         res++;
3436         uint16_t size = get16(&buf[res]);
3437         res += 2;
3438         if (buf_len - res < size) {
3439                 return NULL;
3440         }
3441         DEBUG_DUMP_HEX(&buf[res], size);
3442         *sig_size = size;
3443         *offset = res + size;
3444         return &buf[res];
3445 }
3446
3447 int tls_parse_server_key_exchange(struct TLSContext *context,
3448                                   const unsigned char *buf, int buf_len) {
3449         int res = 0;
3450         int dh_res = 0;
3451         if (buf_len < 3) {
3452                 return TLS_NEED_MORE_DATA;
3453         }
3454         int size = get24(buf);
3455         res += 3;
3456         const unsigned char *packet_ref = buf + res;
3457         if (buf_len - res < size) {
3458                 return TLS_NEED_MORE_DATA;
3459         }
3460
3461         if (!size) {
3462                 return res;
3463         }
3464
3465         unsigned char has_ds_params = 0;
3466         int key_size = 0;
3467         const struct ECCCurveParameters *curve = NULL;
3468         const unsigned char *pk_key = NULL;
3469         int ephemeral = tls_cipher_is_ephemeral(context);
3470         if (ephemeral) {
3471                 if (ephemeral == 1) {
3472                         has_ds_params = 1;
3473                 } else {
3474                         if (buf[res++] != 3) {
3475                                 /* named curve */
3476                                 /* any other method is not supported */
3477                                 return 0;
3478                         }
3479                         if (buf_len - res < 3) {
3480                                 return TLS_NEED_MORE_DATA;
3481                         }
3482                         int iana_n = get16(&buf[res]);
3483                         res += 2;
3484                         key_size = buf[res];
3485                         res++;
3486                         if (buf_len - res < key_size) {
3487                                 return TLS_NEED_MORE_DATA;
3488                         }
3489                         DEBUG_PRINT("IANA CURVE NUMBER: %i\n", iana_n);
3490                         switch (iana_n) {
3491                                 case 19:
3492                                         curve = &secp192r1;
3493                                         break;
3494                                 case 20:
3495                                         curve = &secp224k1;
3496                                         break;
3497                                 case 21:
3498                                         curve = &secp224r1;
3499                                         break;
3500                                 case 22:
3501                                         curve = &secp256k1;
3502                                         break;
3503                                 case 23:
3504                                         curve = &secp256r1;
3505                                         break;
3506                                 case 24:
3507                                         curve = &secp384r1;
3508                                         break;
3509                                 case 25:
3510                                         curve = &secp521r1;
3511                                         break;
3512                                 default:
3513                                         DEBUG_PRINT("UNSUPPORTED CURVE\n");
3514                                         return TLS_GENERIC_ERROR;
3515                         }
3516                         pk_key = &buf[res];
3517                         res += key_size;
3518                         context->curve = curve;
3519                 }
3520         }
3521
3522         const unsigned char *dh_p = NULL;
3523         int dh_p_len = 0;
3524         const unsigned char *dh_g = NULL;
3525         int dh_g_len = 0;
3526         const unsigned char *dh_Ys = NULL;
3527         int dh_Ys_len = 0;
3528
3529         if (has_ds_params) {
3530                 DEBUG_PRINT("          dh_p: ");
3531                 dh_res = parse_dh(&buf[res], buf_len - res, &dh_p, &dh_p_len);
3532                 if (dh_res <= 0) {
3533                         return TLS_BROKEN_PACKET;
3534                 }
3535                 res += dh_res;
3536                 DEBUG_PRINT("\n");
3537
3538                 DEBUG_PRINT("          dh_q: ");
3539                 dh_res = parse_dh(&buf[res], buf_len - res, &dh_g, &dh_g_len);
3540                 if (dh_res <= 0) {
3541                         return TLS_BROKEN_PACKET;
3542                 }
3543                 res += dh_res;
3544                 DEBUG_PRINT("\n");
3545
3546                 DEBUG_PRINT("          dh_Ys: ");
3547                 dh_res = parse_dh(&buf[res], buf_len - res, &dh_Ys,
3548                                 &dh_Ys_len);
3549                 if (dh_res <= 0) {
3550                         return TLS_BROKEN_PACKET;
3551                 }
3552                 res += dh_res;
3553                 DEBUG_PRINT("\n");
3554         }
3555         int sign_size;
3556         int hash_algorithm;
3557         int sign_algorithm;
3558         int packet_size = res - 3;
3559         int offset = 0;
3560         DEBUG_PRINT("          SIGNATURE (%i/%i/%i): ", packet_size,
3561                     dh_res, key_size);
3562         const unsigned char *signature =
3563             parse_signature(&buf[res], buf_len - res, &hash_algorithm,
3564                             &sign_algorithm, &sign_size, &offset);
3565         DEBUG_PRINT("\n");
3566         if (sign_size <= 0 || !signature) {
3567                 return TLS_BROKEN_PACKET;
3568         }
3569         res += offset;
3570         /* check signature */
3571         unsigned int message_len =
3572             packet_size + TLS_CLIENT_RANDOM_SIZE + TLS_SERVER_RANDOM_SIZE;
3573         unsigned char *message = malloc(message_len);
3574         if (message) {
3575                 memcpy(message, context->local_random, TLS_CLIENT_RANDOM_SIZE);
3576                 memcpy(message + TLS_CLIENT_RANDOM_SIZE,
3577                        context->remote_random, TLS_SERVER_RANDOM_SIZE);
3578                 memcpy(message + TLS_CLIENT_RANDOM_SIZE +
3579                        TLS_SERVER_RANDOM_SIZE, packet_ref, packet_size);
3580                 if (tls_is_ecdsa(context)) {
3581                         if (tls_verify_ecdsa
3582                             (context, hash_algorithm, signature, sign_size,
3583                              message, message_len, NULL) != 1) {
3584                                 DEBUG_PRINT
3585                                     ("ECC Server signature FAILED!\n");
3586                                 free(message);
3587                                 return TLS_BROKEN_PACKET;
3588                         }
3589                 } else
3590                 {
3591                         if (verify_rsa(context, hash_algorithm, signature,
3592                                                 sign_size, message,
3593                                                 message_len) != 1) {
3594                                 DEBUG_PRINT("Server signature FAILED!\n");
3595                                 free(message);
3596                                 return TLS_BROKEN_PACKET;
3597                         }
3598                 }
3599                 free(message);
3600         }
3601
3602         if (buf_len - res) {
3603                 DEBUG_PRINT("EXTRA %i BYTES AT THE END OF MESSAGE\n",
3604                             buf_len - res);
3605                 DEBUG_DUMP_HEX(&buf[res], buf_len - res);
3606                 DEBUG_PRINT("\n");
3607         }
3608
3609         if (ephemeral == 1) {
3610                 tls_dhe_create(context);
3611                 DEBUG_DUMP_HEX_LABEL("DHP", dh_p, dh_p_len);
3612                 DEBUG_DUMP_HEX_LABEL("DHG", dh_g, dh_g_len);
3613                 int dhe_key_size = dh_p_len;
3614                 if (dh_g_len > dh_p_len) {
3615                         dhe_key_size = dh_g_len;
3616                 }
3617
3618                 if (tls_dh_make_key(dhe_key_size, context->dhe, (const char *)
3619                                         dh_p, (const char *) dh_g, dh_p_len,
3620                                         dh_g_len)) {
3621                         DEBUG_PRINT("ERROR CREATING DHE KEY\n");
3622                         free(context->dhe);
3623                         context->dhe = NULL;
3624                         return TLS_GENERIC_ERROR;
3625                 }
3626
3627                 unsigned int dh_key_size = 0;
3628                 unsigned char *key = tls_decrypt_dhe(context, dh_Ys, dh_Ys_len,
3629                                 &dh_key_size, 0);
3630                 DEBUG_DUMP_HEX_LABEL("DH COMMON SECRET", key, dh_key_size);
3631                 if (key && dh_key_size) {
3632                         free(context->premaster_key);
3633                         context->premaster_key = key;
3634                         context->premaster_key_len = dh_key_size;
3635                 }
3636         } else if (ephemeral == 2 && curve && pk_key && key_size) {
3637                 tls_ecc_dhe_create(context);
3638
3639                 ltc_ecc_set_type *dp = (ltc_ecc_set_type *) & curve->dp;
3640                 if (ecc_make_key_ex
3641                     (NULL, find_prng("sprng"), context->ecc_dhe, dp)) {
3642                         free(context->ecc_dhe);
3643                         context->ecc_dhe = NULL;
3644                         DEBUG_PRINT("Error generating ECC key\n");
3645                         return TLS_GENERIC_ERROR;
3646                 }
3647
3648                 free(context->premaster_key);
3649                 context->premaster_key_len = 0;
3650
3651                 unsigned int out_len = 0;
3652                 context->premaster_key =
3653                     tls_decrypt_ecc_dhe(context, pk_key, key_size,
3654                                                  &out_len, 0);
3655                 if (context->premaster_key) {
3656                         context->premaster_key_len = out_len;
3657                 }
3658         }
3659
3660         return res;
3661 }
3662
3663 int tls_parse_client_key_exchange(struct TLSContext *context,
3664                                   const unsigned char *buf, int buf_len) {
3665         if (context->connection_status != 1) {
3666                 DEBUG_PRINT
3667                     ("UNEXPECTED CLIENT KEY EXCHANGE MESSAGE (connections status: %i)\n",
3668                      (int) context->connection_status);
3669                 return TLS_UNEXPECTED_MESSAGE;
3670         }
3671
3672         int res = 0;
3673         int dh_res = 0;
3674         if (buf_len < 3) {
3675                 return TLS_NEED_MORE_DATA;
3676         }
3677         int size = get24(buf);
3678         res += 3;
3679
3680         if (buf_len - res < size) {
3681                 return TLS_NEED_MORE_DATA;
3682         }
3683
3684         if (!size) {
3685                 return res;
3686         }
3687
3688         dh_res = tls_parse_random(context, &buf[res], size);
3689         if (dh_res <= 0) {
3690                 DEBUG_PRINT("broken key\n");
3691                 return TLS_BROKEN_PACKET;
3692         }
3693         DEBUG_PRINT("\n");
3694
3695         res += size;
3696         context->connection_status = 2;
3697         return res;
3698 }
3699
3700 static int tls_parse_server_hello_done(const unsigned char *buf, int buf_len) {
3701         int res = 0;
3702         if (buf_len < 3) {
3703                 return TLS_NEED_MORE_DATA;
3704         }
3705         int size = get24(buf);
3706         res += 3;
3707
3708         if (buf_len - res < size) {
3709                 return TLS_NEED_MORE_DATA;
3710         }
3711
3712         res += size;
3713         return res;
3714 }
3715
3716 int tls_parse_finished(struct TLSContext *context,
3717                        const unsigned char *buf, int buf_len,
3718                        unsigned int *write_packets) {
3719         if (context->connection_status < 2
3720             || context->connection_status == TLS_CONNECTED) {
3721                 DEBUG_PRINT("UNEXPECTED FINISHED MESSAGE\n");
3722                 return TLS_UNEXPECTED_MESSAGE;
3723         }
3724
3725         int res = 0;
3726         *write_packets = 0;
3727         if (buf_len < 3) {
3728                 return TLS_NEED_MORE_DATA;
3729         }
3730         int size = get24(buf);
3731         res += 3;
3732
3733         if (size < TLS_MIN_FINISHED_OPAQUE_LEN) {
3734                 DEBUG_PRINT("Invalid finished packet size: %i\n", size);
3735                 return TLS_BROKEN_PACKET;
3736         }
3737
3738         if (buf_len - res < size) {
3739                 return TLS_NEED_MORE_DATA;
3740         }
3741
3742         unsigned char hash[TLS_MAX_SHA_SIZE];
3743         unsigned int hash_len = tls_get_hash(context, hash);
3744
3745         if (context->tlsver == TLS_VERSION13) {
3746                 unsigned char hash_out[TLS_MAX_SHA_SIZE];
3747                 unsigned long out_size = TLS_MAX_SHA_SIZE;
3748                 if (!context->remote_finished_key || !hash_len) {
3749                         DEBUG_PRINT
3750                             ("NO FINISHED KEY COMPUTED OR NO HANDSHAKE HASH\n");
3751                         return TLS_NOT_VERIFIED;
3752                 }
3753
3754                 DEBUG_DUMP_HEX_LABEL("HS HASH", hash, hash_len);
3755                 DEBUG_DUMP_HEX_LABEL("HS FINISH", context->remote_finished_key,
3756                                 hash_len);
3757
3758                 out_size = hash_len;
3759                 hmac_state hmac;
3760                 hmac_init(&hmac, tls_get_hash_idx(context),
3761                           context->remote_finished_key, hash_len);
3762                 hmac_process(&hmac, hash, hash_len);
3763                 hmac_done(&hmac, hash_out, &out_size);
3764
3765                 if (size != (int)out_size || memcmp(hash_out, &buf[res], size)) {
3766                         DEBUG_PRINT
3767                             ("Finished validation error (sequence number, local: %i, remote: %i)\n",
3768                              (int) context->local_sequence_number,
3769                              (int) context->remote_sequence_number);
3770                         DEBUG_DUMP_HEX_LABEL("FINISHED OPAQUE", &buf[res],
3771                                              size);
3772                         DEBUG_DUMP_HEX_LABEL("VERIFY", hash_out, out_size);
3773                         return TLS_NOT_VERIFIED;
3774                 }
3775                 if (context->is_server) {
3776                         context->connection_status = TLS_CONNECTED;
3777                         res += size;
3778                         _private_tls13_key(context, 0);
3779                         context->local_sequence_number = 0;
3780                         context->remote_sequence_number = 0;
3781                         return res;
3782                 }
3783                 /* TODO client verify */
3784         } else {
3785                 /* verify */
3786                 unsigned char *out = malloc(size);
3787                 if (!out) {
3788                         DEBUG_PRINT("Error in malloc (%i bytes)\n",
3789                                     (int) size);
3790                         return TLS_NO_MEMORY;
3791                 }
3792
3793                 /* server verifies client's message */
3794                 if (context->is_server) {
3795                         tls_prf(context, out, size,
3796                                          context->master_key,
3797                                          context->master_key_len,
3798                                          (unsigned char *)
3799                                          "client finished", 15, hash,
3800                                          hash_len, NULL, 0);
3801                 } else {
3802                         tls_prf(context, out, size,
3803                                          context->master_key,
3804                                          context->master_key_len,
3805                                          (unsigned char *)
3806                                          "server finished", 15, hash,
3807                                          hash_len, NULL, 0);
3808                 }
3809
3810                 if (memcmp(out, &buf[res], size)) {
3811                         free(out);
3812                         DEBUG_PRINT
3813                             ("Finished validation error (sequence number, local: %i, remote: %i)\n",
3814                              (int) context->local_sequence_number,
3815                              (int) context->remote_sequence_number);
3816                         DEBUG_DUMP_HEX_LABEL("FINISHED OPAQUE", &buf[res],
3817                                              size);
3818                         DEBUG_DUMP_HEX_LABEL("VERIFY", out, size);
3819                         return TLS_NOT_VERIFIED;
3820                 }
3821                 free(out);
3822         }
3823
3824         if (context->is_server) {
3825                 *write_packets = 3;
3826         } else {
3827                 context->connection_status = TLS_CONNECTED;
3828         }
3829
3830         // fprintf(stderr, "set conn status = %d\n", context->connection_status);
3831
3832         res += size;
3833         return res;
3834 }
3835
3836 int tls_parse_verify_tls13(struct TLSContext *context,
3837                            const unsigned char *buf, int buf_len) {
3838         if (buf_len < 7) {
3839                 return TLS_NEED_MORE_DATA;
3840         }
3841         int size = get24(buf);
3842
3843         if (size < 2) {
3844                 return buf_len;
3845         }
3846
3847         unsigned char signing_data[TLS_MAX_HASH_SIZE + 98];
3848         int signing_data_len;
3849
3850         /* first 64 bytes to 0x20 (32) */
3851         memset(signing_data, 0x20, 64);
3852         /* context string 33 bytes */
3853         if (context->is_server) {
3854                 memcpy(signing_data + 64,
3855                        "TLS 1.3, server CertificateVerify", 33);
3856         } else {
3857                 memcpy(signing_data + 64,
3858                        "TLS 1.3, client CertificateVerify", 33);
3859         }
3860
3861         /* a single 0 byte separator */
3862         signing_data[97] = 0;
3863         signing_data_len = 98;
3864
3865         signing_data_len += tls_get_hash(context, signing_data + 98);
3866         DEBUG_DUMP_HEX_LABEL("signature data", signing_data, signing_data_len);
3867         uint16_t signature = get16(&buf[3]);
3868         uint16_t signature_size = get16(&buf[5]);
3869         int valid = 0;
3870         if (buf_len < size + 7) {
3871                 return TLS_NEED_MORE_DATA;
3872         }
3873         switch (signature) {
3874                 case 0x0403:
3875                         /* secp256r1 + sha256 */
3876                         valid =
3877                                 tls_verify_ecdsa(context, sha256, buf + 7,
3878                                                 signature_size, signing_data,
3879                                                 signing_data_len,
3880                                                 &secp256r1);
3881                         break;
3882                 case 0x0503:
3883                         /* secp384r1 + sha384 */
3884                         valid = tls_verify_ecdsa(context, sha384, buf + 7,
3885                                         signature_size, signing_data,
3886                                         signing_data_len, &secp384r1);
3887                         break;
3888                 case 0x0603:
3889                         /* secp521r1 + sha512 */
3890                         valid = tls_verify_ecdsa(context, sha512, buf + 7,
3891                                         signature_size, signing_data,
3892                                         signing_data_len, &secp521r1);
3893                         break;
3894                 case 0x0804:
3895                         valid = verify_rsa(context, sha256, buf + 7,
3896                                         signature_size, signing_data,
3897                                         signing_data_len);
3898                         break;
3899                 default:
3900                         DEBUG_PRINT("Unsupported signature: %x\n",
3901                                         (int) signature);
3902                         return TLS_UNSUPPORTED_CERTIFICATE;
3903         }
3904         if (valid != 1) {
3905                 DEBUG_PRINT("Signature FAILED!\n");
3906                 return TLS_DECRYPTION_FAILED;
3907         }
3908         return buf_len;
3909 }
3910
3911 int tls_parse_verify(struct TLSContext *context, const unsigned char *buf,
3912                      int buf_len) {
3913         if (context->tlsver == TLS_VERSION13) {
3914                 return tls_parse_verify_tls13(context, buf, buf_len);
3915         }
3916
3917         if (buf_len < 7) {
3918                 return TLS_BAD_CERTIFICATE;
3919         }
3920
3921         int bytes_to_follow = get24(buf);
3922
3923         if (buf_len - 3 < bytes_to_follow) {
3924                 return TLS_BAD_CERTIFICATE;
3925         }
3926
3927         int res = -1;
3928
3929         unsigned int hash = buf[3];
3930         unsigned int algorithm = buf[4];
3931         if (algorithm != rsa) {
3932                 return TLS_UNSUPPORTED_CERTIFICATE;
3933         }
3934         uint16_t size = get16(&buf[5]);
3935         if (bytes_to_follow - 4 < size) {
3936                 return TLS_BAD_CERTIFICATE;
3937         }
3938         DEBUG_PRINT("ALGORITHM %i/%i (%i)\n", hash, algorithm, (int) size);
3939         DEBUG_DUMP_HEX_LABEL("VERIFY", &buf[7], bytes_to_follow - 7);
3940
3941         res = verify_rsa(context, hash, &buf[7], size,
3942                         context->cached_handshake.buffer,
3943                         context->cached_handshake.len);
3944
3945         tls_buffer_free(&context->cached_handshake);
3946         if (res == 1) {
3947                 DEBUG_PRINT("Signature OK\n");
3948                 context->client_verified = 1;
3949         } else {
3950                 DEBUG_PRINT("Signature FAILED\n");
3951                 context->client_verified = 0;
3952         }
3953         return 1;
3954 }
3955
3956 /* TODO This is actually a parse a handshake message */
3957 int tls_parse_payload(struct TLSContext *context, const unsigned char *buf,
3958                       int buf_len) {
3959         int orig_len = buf_len;
3960
3961         
3962         if (context->connection_status == TLS_CONNECTED) {
3963                 if (context->version == TLS_V13) {
3964                         tls_alert(context, 1, unexpected_message);
3965                 } else {
3966                         tls_alert(context, 0, no_renegotiation_RESERVED);
3967                 }
3968
3969                 return 1;
3970         }
3971
3972         while (buf_len >= 4 && !context->critical_error) {
3973                 int payload_res = 0;
3974                 //unsigned char update_hash = 1;
3975                 unsigned char type = buf[0];
3976                 unsigned int write_packets = 0;
3977                 int certificate_verify_alert = no_error;
3978                 int payload_size = get24(buf+1) + 3;
3979                 if (buf_len < payload_size + 1) {
3980                         return TLS_NEED_MORE_DATA;
3981                 }
3982                 switch (type) {
3983                         case 0x00:
3984                                 /* hello request */
3985                                 CHECK_HANDSHAKE_STATE(context, 0, 1);
3986                                 DEBUG_PRINT
3987                                         (" => HELLO REQUEST (RENEGOTIATION?)\n");
3988                                 if (context->is_server) {
3989                                         payload_res = TLS_UNEXPECTED_MESSAGE;
3990                                 } else {
3991                                         if (context->connection_status == TLS_CONNECTED) {
3992                                                 /* renegotiation */
3993                                                 payload_res = TLS_NO_RENEGOTIATION;
3994                                         } else {
3995                                                 payload_res = TLS_UNEXPECTED_MESSAGE;
3996                                         }
3997                                 }
3998                                 /* no payload */
3999                                 break;
4000                         case 0x01:
4001                                 /* client hello */
4002                                 CHECK_HANDSHAKE_STATE(context, 1, 1);
4003                                 DEBUG_PRINT(" => CLIENT HELLO\n");
4004                                 if (context->is_server) {
4005                                         payload_res =
4006                                                 tls_parse_client_hello(context,
4007                                                                 buf + 1,
4008                                                                 payload_size,
4009                                                                 &write_packets);
4010                                 } else {
4011                                         payload_res = TLS_UNEXPECTED_MESSAGE;
4012                                 }
4013                                 break;
4014                         case 0x02:
4015                                 /* server hello */
4016                                 CHECK_HANDSHAKE_STATE(context, 2, 1);
4017                                 DEBUG_PRINT(" => SERVER HELLO\n");
4018                                 if (context->is_server) {
4019                                         payload_res = TLS_UNEXPECTED_MESSAGE;
4020                                 } else {
4021                                         write_packets = 0;
4022                                         payload_res = tls_parse_server_hello(context, buf + 1, payload_size);
4023                                 }
4024                                 break;
4025                         case 0x03:
4026                                 /* hello verify request */
4027                                 DEBUG_PRINT(" => VERIFY REQUEST\n");
4028                                 CHECK_HANDSHAKE_STATE(context, 3, 1);
4029                                 payload_res = TLS_UNEXPECTED_MESSAGE;
4030                                 break;
4031                         case 0x0B:
4032                                 /* certificate */
4033                                 CHECK_HANDSHAKE_STATE(context, 4, 1);
4034                                 DEBUG_PRINT(" => CERTIFICATE\n");
4035                                 if (context->tlsver == TLS_VERSION13) {
4036                                         if (context->connection_status == 2) {
4037                                                 payload_res =
4038                                                         tls_parse_certificate(context,
4039                                                                         buf + 1,
4040                                                                         payload_size,
4041                                                                         context->
4042                                                                         is_server);
4043                                                 if (context->is_server) {
4044                                                         if (context->certificate_verify && context->client_certificates_count) {
4045                                                                 certificate_verify_alert
4046                                                                         =
4047                                                                         context->certificate_verify(context,
4048                                                                          context->client_certificates,
4049                                                                          context->client_certificates_count);
4050                                                         }
4051                                                         /* empty certificates are permitted for client */
4052                                                         if (payload_res <= 0) {
4053                                                                 payload_res = 1;
4054                                                         }
4055                                                 }
4056                                         } else
4057                                                 payload_res =
4058                                                         TLS_UNEXPECTED_MESSAGE;
4059                                 } else
4060                                         if (context->connection_status == 1) {
4061                                                 if (context->is_server) {
4062                                                         /* client certificate */
4063                                                         payload_res =
4064                                                                 tls_parse_certificate(context,
4065                                                                                 buf + 1,
4066                                                                                 payload_size,
4067                                                                                 1);
4068                                                         if (context->certificate_verify && context->client_certificates_count) {
4069                                                                 certificate_verify_alert =
4070                                                                         context->certificate_verify
4071                                                                         (context,
4072                                                                          context->
4073                                                                          client_certificates,
4074                                                                          context->
4075                                                                          client_certificates_count);
4076                                                         }
4077                                                         /* empty certificates are permitted for client */
4078                                                         if (payload_res <= 0)
4079                                                                 payload_res = 1;
4080                                                 } else {
4081                                                         payload_res =
4082                                                                 tls_parse_certificate(context,
4083                                                                                 buf + 1,
4084                                                                                 payload_size,
4085                                                                                 0);
4086                                                         if (certificate_verify && context->certificates_count) {
4087                                                                 certificate_verify_alert =
4088                                                                         context->certificate_verify
4089                                                                         (context,
4090                                                                          context->certificates,
4091                                                                          context->
4092                                                                          certificates_count);
4093                                                         }
4094                                                 }
4095                                         } else {
4096                                                 payload_res = TLS_UNEXPECTED_MESSAGE;
4097                                         }
4098                                 break;
4099                         case 0x0C:
4100                                 /* server key exchange */
4101                                 CHECK_HANDSHAKE_STATE(context, 5, 1);
4102                                 DEBUG_PRINT(" => SERVER KEY EXCHANGE\n");
4103                                 if (context->is_server) {
4104                                         payload_res = TLS_UNEXPECTED_MESSAGE;
4105                                 } else {
4106                                         payload_res =
4107                                                 tls_parse_server_key_exchange(context,
4108                                                                 buf + 1,
4109                                                                 payload_size);
4110                                 }
4111                                 break;
4112                         case 0x0D:
4113                                 /* certificate request */
4114                                 CHECK_HANDSHAKE_STATE(context, 6, 1);
4115                                 /* server to client */
4116                                 if (context->is_server) {
4117                                         payload_res = TLS_UNEXPECTED_MESSAGE;
4118                                 } else {
4119                                         context->client_verified = 2;
4120                                 }
4121                                 DEBUG_PRINT(" => CERTIFICATE REQUEST\n");
4122                                 break;
4123                         case 0x0E:
4124                                 /* server hello done */
4125                                 CHECK_HANDSHAKE_STATE(context, 7, 1);
4126                                 DEBUG_PRINT(" => SERVER HELLO DONE\n");
4127                                 if (context->is_server) {
4128                                         payload_res = TLS_UNEXPECTED_MESSAGE;
4129                                 } else {
4130                                         payload_res =
4131                                                 tls_parse_server_hello_done(
4132                                                                 buf + 1,
4133                                                                 payload_size);
4134                                         if (payload_res > 0) {
4135                                                 write_packets = 1;
4136                                         }
4137                                 }
4138                                 break;
4139                         case 0x0F:
4140                                 /* certificate verify */
4141                                 CHECK_HANDSHAKE_STATE(context, 8, 1);
4142                                 DEBUG_PRINT(" => CERTIFICATE VERIFY\n");
4143                                 if (context->connection_status == 2) {
4144                                         payload_res =
4145                                                 tls_parse_verify(context, buf + 1,
4146                                                                 payload_size);
4147                                 } else {
4148                                         payload_res = TLS_UNEXPECTED_MESSAGE;
4149                                 }
4150                                 break;
4151                         case 0x10:
4152                                 /* client key exchange */
4153                                 CHECK_HANDSHAKE_STATE(context, 9, 1);
4154                                 DEBUG_PRINT(" => CLIENT KEY EXCHANGE\n");
4155                                 if (context->is_server) {
4156                                         payload_res =
4157                                                 tls_parse_client_key_exchange(context,
4158                                                                 buf + 1,
4159                                                                 payload_size);
4160                                 } else {
4161                                         payload_res = TLS_UNEXPECTED_MESSAGE;
4162                                 }
4163                                 break;
4164                         case 0x14:
4165                                 /* finished */
4166                                 tls_buffer_free(&context->cached_handshake);
4167                                 CHECK_HANDSHAKE_STATE(context, 10, 1);
4168                                 DEBUG_PRINT(" => FINISHED\n");
4169                                 payload_res = tls_parse_finished(context,
4170                                                 buf + 1, payload_size,
4171                                                 &write_packets);
4172                                 if (payload_res > 0) {
4173                                         memset(context->hs_messages, 0,
4174                                                         sizeof(context->hs_messages));
4175                                 }
4176                                 break;
4177                         default:
4178                                 DEBUG_PRINT
4179                                         (" => NOT UNDERSTOOD PAYLOAD TYPE: %x\n",
4180                                          (int) type);
4181                                 return TLS_NOT_UNDERSTOOD;
4182                 }
4183
4184                 //if (type != 0x00 && update_hash) {
4185                 if (type != 0x00) {
4186                         tls_update_hash(context, buf, payload_size + 1);
4187                 }
4188
4189                 if (certificate_verify_alert != no_error) {
4190                         tls_alert(context, 1, certificate_verify_alert);
4191                         context->critical_error = 1;
4192                 }
4193
4194                 if (payload_res < 0) {
4195                         switch (payload_res) {
4196                                 case TLS_UNEXPECTED_MESSAGE:
4197                                         tls_alert(context, 1, unexpected_message);
4198                                         break;
4199                                 case TLS_COMPRESSION_NOT_SUPPORTED:
4200                                         tls_alert(context, 1, decompression_failure_RESERVED);
4201                                         break;
4202                                 case TLS_BROKEN_PACKET:
4203                                         tls_alert(context, 1, decode_error);
4204                                         break;
4205                                 case TLS_NO_MEMORY:
4206                                         tls_alert(context, 1, internal_error);
4207                                         break;
4208                                 case TLS_NOT_VERIFIED:
4209                                         tls_alert(context, 1, bad_record_mac);
4210                                         break;
4211                                 case TLS_BAD_CERTIFICATE:
4212                                         if (context->is_server) {
4213                                                 /* bad client certificate, continue */
4214                                                 tls_alert(context, 0, bad_certificate);
4215                                                 payload_res = 0;
4216                                         } else {
4217                                                 tls_alert(context, 1, bad_certificate);
4218                                         }
4219                                         break;
4220                                 case TLS_UNSUPPORTED_CERTIFICATE:
4221                                         tls_alert(context, 1, unsupported_certificate);
4222                                         break;
4223                                 case TLS_NO_COMMON_CIPHER:
4224                                         tls_alert(context, 1, insufficient_security);
4225                                         break;
4226                                 case TLS_NOT_UNDERSTOOD:
4227                                         tls_alert(context, 1, internal_error);
4228                                         break;
4229                                 case TLS_NO_RENEGOTIATION:
4230                                         tls_alert(context, 0, no_renegotiation_RESERVED);
4231                                         payload_res = 0;
4232                                         break;
4233                                 case TLS_DECRYPTION_FAILED:
4234                                         tls_alert(context, 1, decryption_failed_RESERVED);
4235                                         break;
4236                         }
4237                         if (payload_res < 0) {
4238                                 return payload_res;
4239                         }
4240                 }
4241
4242                 if (certificate_verify_alert != no_error) {
4243                         payload_res = TLS_BAD_CERTIFICATE;
4244                 }
4245
4246                 /* except renegotiation */
4247                 struct TLSPacket *pkt;
4248                 switch (write_packets) {
4249                         case 1:
4250                                 if (context->client_verified == 2) {
4251                                         DEBUG_PRINT("<= Building CERTIFICATE \n");
4252                                         tls_send_certificate(context);
4253                                         context->client_verified = 0;
4254                                 }
4255
4256                                 /* client handshake */
4257                                 tls_send_client_key_exchange(context);
4258                                 tls_send_change_cipher_spec(context);
4259
4260                                 context->cipher_spec_set = 1;
4261                                 context->local_sequence_number = 0;
4262
4263                                 tls_send_finished(context);
4264
4265                                 context->cipher_spec_set = 0;
4266                                 break;
4267                         case 2:
4268                                 /* server handshake */
4269                                 DEBUG_PRINT("<= SENDING SERVER HELLO\n");
4270                                 if (context->connection_status == 3) {
4271                                         context->connection_status = 2;
4272                                         tls_queue_packet
4273                                                 (tls_build_hello(context, 0));
4274                                         tls_send_change_cipher_spec(context);
4275                                         _private_tls13_key(context, 1);
4276                                         context->cipher_spec_set = 1;
4277                                         DEBUG_PRINT
4278                                                 ("<= SENDING ENCRYPTED EXTENSIONS\n");
4279                                         tls_send_encrypted_extensions(context);
4280
4281                                         if (context->request_client_certificate) {
4282                                                 DEBUG_PRINT
4283                                                         ("<= SENDING CERTIFICATE REQUEST\n");
4284                                                 tls_queue_packet
4285                                                         (tls_certificate_request
4286                                                          (context));
4287                                         }
4288
4289                                         tls_send_certificate(context);
4290
4291                                         tls_send_certificate_verify(context);
4292
4293                                         tls_send_finished(context);
4294
4295                                         /* new key */
4296                                         free(context->server_finished_hash);
4297
4298                                         context->server_finished_hash =
4299                                                 malloc(tls_mac_length(context));
4300
4301                                         if (context->server_finished_hash) {
4302                                                 tls_get_hash(context,
4303                                                                 context->server_finished_hash);
4304                                         }
4305
4306                                         break;
4307                                 }
4308                                 tls_queue_packet(tls_build_hello(context, 0));
4309                                 DEBUG_PRINT("<= SENDING CERTIFICATE\n");
4310                                 tls_send_certificate(context);
4311
4312                                 int ephemeral_cipher =
4313                                         tls_cipher_is_ephemeral(context);
4314                                 if (ephemeral_cipher) {
4315                                         DEBUG_PRINT
4316                                                 ("<= SENDING EPHEMERAL DH KEY\n");
4317                                         tls_send_server_key_exchange(context,
4318                                                         ephemeral_cipher == 1 ?
4319                                                         KEA_dhe_rsa :
4320                                                         KEA_ec_diffie_hellman);
4321                                 }
4322                                 if (context->request_client_certificate) {
4323                                         DEBUG_PRINT
4324                                                 ("<= SENDING CERTIFICATE REQUEST\n");
4325                                         tls_queue_packet
4326                                                 (tls_certificate_request
4327                                                  (context));
4328                                 }
4329                                 tls_send_done(context);
4330                                 break;
4331                         case 3:
4332                                 /* finished */
4333                                 tls_send_change_cipher_spec(context);
4334                                 tls_send_finished(context);
4335                                 context->connection_status = TLS_CONNECTED;
4336                                 break;
4337                         case 4:
4338                                 /* dtls only */
4339                                 /* TODO error */
4340                                 break;
4341                         case 5:
4342                                 /* hello retry request */
4343                                 DEBUG_PRINT("<= SENDING HELLO RETRY REQUEST\n");
4344                                 pkt = tls_build_hello(context, 0);
4345                                 tls_queue_packet(pkt);
4346                                 break;
4347                 }
4348                 payload_size++;
4349                 buf += payload_size;
4350                 buf_len -= payload_size;
4351         }
4352         return orig_len;
4353 }
4354
4355 unsigned int asn1_get_len(const unsigned char *buffer, int buf_len,
4356                           unsigned int *octets) {
4357         *octets = 0;
4358
4359         if (buf_len < 1) {
4360                 return 0;
4361         }
4362
4363         unsigned char size = buffer[0];
4364         int i;
4365         if (size & 0x80) {
4366                 *octets = size & 0x7F;
4367                 if ((int) *octets > buf_len - 1) {
4368                         return 0;
4369                 }
4370                 /* max 32 bits */
4371                 unsigned int ref_octets = *octets;
4372                 if (*octets > 4) {
4373                         ref_octets = 4;
4374                 }
4375                 if ((int) *octets > buf_len - 1) {
4376                         return 0;
4377                 }
4378                 unsigned int long_size = 0;
4379                 unsigned int coef = 1;
4380
4381                 for (i = ref_octets; i > 0; i--) {
4382                         long_size += buffer[i] * coef;
4383                         coef *= 0x100;
4384                 }
4385                 ++*octets;
4386                 return long_size;
4387         }
4388         ++*octets;
4389         return size;
4390 }
4391
4392 void print_index(const unsigned int *fields) {
4393         int i = 0;
4394         while (fields[i]) {
4395                 if (i) {
4396                         DEBUG_PRINT(".");
4397                 }
4398                 DEBUG_PRINT("%i", fields[i]);
4399                 i++;
4400         }
4401         while (i < 6) {
4402                 DEBUG_PRINT("  ");
4403                 i++;
4404         }
4405 }
4406
4407 int _is_field(const unsigned int *fields, const unsigned int *prefix) {
4408         int i = 0;
4409         while (prefix[i]) {
4410                 if (fields[i] != prefix[i]) {
4411                         return 0;
4412                 }
4413                 i++;
4414         }
4415         return 1;
4416 }
4417
4418 static int tls_hash_len(int algorithm) {
4419         switch (algorithm) {
4420                 case TLS_RSA_SIGN_MD5:
4421                         return 16;
4422                 case TLS_RSA_SIGN_SHA1:
4423                         return 20;
4424                 case TLS_RSA_SIGN_SHA256:
4425                         return 32;
4426                 case TLS_RSA_SIGN_SHA384:
4427                         return 48;
4428                 case TLS_RSA_SIGN_SHA512:
4429                         return 64;
4430         }
4431         return 0;
4432 }
4433
4434 static unsigned char *tls_compute_hash(int algorithm, const unsigned char
4435                 *message, unsigned int message_len) {
4436         unsigned char *hash = NULL;
4437         int err;
4438         int hash_index = -1;
4439         unsigned long hash_len = 0;
4440
4441         if (!message || !message_len) {
4442                 return hash;
4443         }
4444
4445         switch (algorithm) {
4446                 case TLS_RSA_SIGN_MD5:
4447                         DEBUG_PRINT("SIGN MD5\n");
4448                         hash_index = find_hash("md5");
4449                         hash_len = 16;
4450                         break;
4451                 case TLS_RSA_SIGN_SHA1:
4452                         DEBUG_PRINT("SIGN SHA1\n");
4453                         hash_index = find_hash("sha1");
4454                         hash_len = 20;
4455                         break;
4456                 case TLS_RSA_SIGN_SHA256:
4457                         DEBUG_PRINT("SIGN SHA256\n");
4458                         hash_index = find_hash("sha256");
4459                         hash_len = 32;
4460                         break;
4461                 case TLS_RSA_SIGN_SHA384:
4462                         DEBUG_PRINT("SIGN SHA384\n");
4463                         hash_index = find_hash("sha384");
4464                         hash_len = 48;
4465                         break;
4466                 case TLS_RSA_SIGN_SHA512:
4467                         DEBUG_PRINT("SIGN SHA512\n");
4468                         hash_index = find_hash("sha512");
4469                         hash_len = 64;
4470                         break;
4471                 default:
4472                         DEBUG_PRINT("UNKNOWN SIGNATURE ALGORITHM\n");
4473                         return NULL;
4474                         break;
4475         }
4476
4477         hash = malloc(hash_len);
4478         if (!hash) {
4479                 return NULL;
4480         }
4481
4482         err = hash_memory(hash_index, message, message_len, hash, &hash_len);
4483         if (err) {
4484                 return NULL;
4485         }
4486         return hash;
4487 }
4488
4489 int tls_certificate_verify_signature(struct TLSCertificate *cert,
4490                                      struct TLSCertificate *parent) {
4491         if (!cert || !parent || !cert->sign_key
4492             || !cert->fingerprint || !cert->sign_len
4493             || !parent->der_bytes || !parent->der_len) {
4494                 DEBUG_PRINT("CANNOT VERIFY SIGNATURE ");
4495                 if (!cert) {
4496                         DEBUG_PRINT("!cert ");
4497                 } else {
4498                         if (!cert->sign_key) {
4499                                 DEBUG_PRINT("!cert->sign_key ");
4500                         }
4501                         if (!cert->fingerprint) {
4502                                 DEBUG_PRINT("!cert->fingerprint ");
4503                         }
4504                         if (!cert->sign_len) {
4505                                 DEBUG_PRINT("!cert->sign_len ");
4506                         }
4507                 }
4508
4509                 if (!parent) {
4510                         DEBUG_PRINT("!parent ");
4511                 } else {
4512                         if (!parent->der_bytes) {
4513                                 DEBUG_PRINT("!parent->der_bytes ");
4514                         }
4515                         if (!parent->der_len) {
4516                                 DEBUG_PRINT("!parent->der_len ");
4517                         }
4518                 }
4519                 DEBUG_PRINT("\n");
4520
4521                 return 0;
4522         }
4523         DEBUG_PRINT("checking alg\n");
4524         int hash_len = tls_hash_len(cert->algorithm);
4525         if (hash_len <= 0) {
4526                 return 0;
4527         }
4528
4529         int hash_index;
4530         switch (cert->algorithm) {
4531                 case TLS_RSA_SIGN_MD5:
4532                         hash_index = find_hash("md5");
4533                         break;
4534                 case TLS_RSA_SIGN_SHA1:
4535                         hash_index = find_hash("sha1");
4536                         break;
4537                 case TLS_RSA_SIGN_SHA256:
4538                         hash_index = find_hash("sha256");
4539                         break;
4540                 case TLS_RSA_SIGN_SHA384:
4541                         hash_index = find_hash("sha384");
4542                         break;
4543                 case TLS_RSA_SIGN_SHA512:
4544                         hash_index = find_hash("sha512");
4545                         break;
4546                 default:
4547                         DEBUG_PRINT("UNKNOWN SIGNATURE ALGORITHM\n");
4548                         return 0;
4549         }
4550
4551         rsa_key key;
4552         DEBUG_PRINTLN("rsa_import(%p, %d, %p)\n", parent->der_bytes,
4553                       parent->der_len, &key);
4554         int err = rsa_import(parent->der_bytes, parent->der_len, &key);
4555         if (err) {
4556                 DEBUG_PRINTLN
4557                     ("Error importing RSA certificate (code: %i)\n", err);
4558                 DEBUG_PRINT("Message: %s\n", error_to_string(err));
4559                 DEBUG_DUMP_HEX_LABEL("CERTIFICATE", parent->der_bytes,
4560                                      parent->der_len);
4561                 return 0;
4562         }
4563         int rsa_stat = 0;
4564         unsigned char *signature = cert->sign_key;
4565         int signature_len = cert->sign_len;
4566         if (!signature[0]) {
4567                 signature++;
4568                 signature_len--;
4569         }
4570
4571         err = rsa_verify_hash_ex(signature, signature_len, cert->fingerprint,
4572                         hash_len, LTC_PKCS_1_V1_5, hash_index, 0, &rsa_stat,
4573                         &key);
4574
4575         rsa_free(&key);
4576         if (err) {
4577                 DEBUG_PRINT("HASH VERIFY ERROR %i\n", err);
4578                 return 0;
4579         }
4580         DEBUG_PRINT("CERTIFICATE VALIDATION: %i\n", rsa_stat);
4581         return rsa_stat;
4582 }
4583
4584 int tls_certificate_chain_is_valid(struct TLSCertificate **certificates,
4585                                    int len) {
4586         if (!certificates || !len) {
4587                 return bad_certificate;
4588         }
4589
4590         int i;
4591         DEBUG_PRINT("verifying %i length cert chain\n", len);
4592         len--;
4593
4594         /* expired certificate or not yet valid ? */
4595         if (tls_certificate_is_valid(certificates[0])) {
4596                 return bad_certificate;
4597         }
4598
4599         /* check */
4600         for (i = 0; i < len; i++) {
4601                 /* certificate in chain is expired ? */
4602                 if (tls_certificate_is_valid(certificates[i + 1])) {
4603                         return bad_certificate;
4604                 }
4605
4606                 if (!tls_certificate_verify_signature(certificates[i],
4607                                         certificates[i + 1])) {
4608                         DEBUG_PRINT
4609                             ("tls_certificate_verify_signature certs[%d], certs[%d+1] failed\n",
4610                              i, i);
4611                         return bad_certificate;
4612                 }
4613
4614         }
4615         return 0;
4616 }
4617
4618 int tls_certificate_chain_is_valid_root(struct TLSContext *context, struct
4619                 TLSCertificate **certificates, int len) {
4620         int i, j;
4621
4622         if (!certificates || !len || !context->root_certificates
4623             || !context->root_count) {
4624                 return bad_certificate;
4625         }
4626         for (i = 0; i < len; i++) {
4627                 for (j = 0; j < context->root_count; j++) {
4628                         /* check if root certificate expired */
4629                         if (tls_certificate_is_valid
4630                             (context->root_certificates[j])) {
4631                                 continue;
4632                         }
4633                         /* if any root validates any certificate in the chain,
4634                          * then is root validated */
4635                         if (tls_certificate_verify_signature(certificates[i],
4636                                                 context->root_certificates[j]))
4637                         {
4638                                 return 0;
4639                         }
4640                 }
4641         }
4642         return bad_certificate;
4643 }
4644
4645 int _private_is_oid(struct OID_chain *ref_chain,
4646                     const unsigned char *looked_oid, int looked_oid_len) {
4647         while (ref_chain) {
4648                 if (ref_chain->oid) {
4649                         if (_is_oid2
4650                             (ref_chain->oid, looked_oid, 16,
4651                              looked_oid_len)) {
4652                                 return 1;
4653                         }
4654                 }
4655                 ref_chain = (struct OID_chain *) ref_chain->top;
4656         }
4657         return 0;
4658 }
4659
4660 int _private_asn1_parse(struct TLSContext *context,
4661                         struct TLSCertificate *cert,
4662                         const unsigned char *buffer, int size, int level,
4663                         unsigned int *fields, unsigned char *has_key,
4664                         int client_cert, unsigned char *top_oid,
4665                         struct OID_chain *chain) {
4666         struct OID_chain local_chain;
4667         DEBUG_INDEX(fields);
4668         DEBUG_PRINT("\n");
4669         local_chain.top = chain;
4670         int pos = 0;
4671         /* X.690 */
4672         int idx = 0;
4673         unsigned char oid[16];
4674         memset(oid, 0, 16);
4675         local_chain.oid = oid;
4676         if (has_key) {
4677                 *has_key = 0;
4678         }
4679         unsigned char local_has_key = 0;
4680         const unsigned char *cert_data = NULL;
4681         unsigned int cert_len = 0;
4682         while (pos < size) {
4683                 unsigned int start_pos = pos;
4684                 if (size - pos < 2) {
4685                         return TLS_NEED_MORE_DATA;
4686                 }
4687                 unsigned char first = buffer[pos++];
4688                 unsigned char type = first & 0x1F;
4689                 unsigned char constructed = first & 0x20;
4690                 unsigned char element_class = first >> 6;
4691                 int octets = 0;
4692                 unsigned int temp;
4693                 idx++;
4694                 if (level <= TLS_ASN1_MAXLEVEL) {
4695                         fields[level - 1] = idx;
4696                 }
4697                 DEBUG_INDEX(fields);
4698                 DEBUG_PRINT("\n");
4699                 int length = asn1_get_len((unsigned char *) &buffer[pos], size
4700                                 - pos, &octets);
4701                 DEBUG_PRINT("asn1_get_len = %u\n", length);
4702                 if ((octets > 4) || (octets > size - pos)) {
4703                         DEBUG_PRINT
4704                             ("CANNOT READ CERTIFICATE octets = %d, size = %d pos = %d, size - pos = %d\n",
4705                              octets, size, pos, size - pos);
4706                         return pos;
4707                 }
4708                 pos += octets;
4709
4710                 if (size - pos < length) {
4711                         return TLS_NEED_MORE_DATA;
4712                 }
4713
4714                 /*DEBUG_PRINT("FIRST: %x => %x (%i)\n", (int)first, (int)type, length); */
4715                 /* sequence */
4716                 /*DEBUG_PRINT("%2i: ", level); */
4717 #ifdef DEBUG
4718                 DEBUG_INDEX(fields);
4719                 int i1;
4720                 for (i1 = 1; i1 < level; i1++) {
4721                         DEBUG_PRINT("  ");
4722                 }
4723 #endif
4724
4725                 if (length && constructed) {
4726                         switch (type) {
4727                                 case 0x03:
4728                                         DEBUG_PRINT("CONSTRUCTED BITSTREAM\n");
4729                                         break;
4730                                 case 0x10:
4731                                 DEBUG_PRINT("SEQUENCE\n");
4732                                 if ((level == 2) && (idx == 1)) {
4733                                         cert_len =
4734                                             length + (pos - start_pos);
4735                                         cert_data = &buffer[start_pos];
4736                                 }
4737                                 /* private key on server or public key on client */
4738                                 if (!cert->version
4739                                     && (_is_field(fields, priv_der_id))) {
4740                                         free(cert->der_bytes);
4741                                         temp = length + (pos - start_pos);
4742                                         cert->der_bytes = malloc(temp);
4743                                         if (cert->der_bytes) {
4744                                                 memcpy(cert->der_bytes,
4745                                                        &buffer[start_pos],
4746                                                        temp);
4747                                                 cert->der_len = temp;
4748                                         } else
4749                                                 cert->der_len = 0;
4750                                 }
4751                                 break;
4752                         case 0x11:
4753                                 DEBUG_PRINT("EMBEDDED PDV\n");
4754                                 break;
4755                         case 0x00:
4756                                 if (element_class == 0x02) {
4757                                         DEBUG_PRINT("CONTEXT-SPECIFIC\n");
4758                                         break;
4759                                 }
4760                         default:
4761                                 DEBUG_PRINT("CONSTRUCT TYPE %02X\n",(int)type);
4762                         }
4763
4764                         local_has_key = 0;
4765                         _private_asn1_parse(context, cert, &buffer[pos],
4766                                             length, level + 1, fields,
4767                                             &local_has_key, client_cert,
4768                                             top_oid, &local_chain);
4769                         if (((local_has_key && context
4770                               && (!context->is_server || client_cert))
4771                              || !context)
4772                             && (_is_field(fields, pk_id))) {
4773                                 free(cert->der_bytes);
4774                                 temp = length + (pos - start_pos);
4775                                 cert->der_bytes = malloc(temp);
4776                                 if (cert->der_bytes) {
4777                                         memcpy(cert->der_bytes,
4778                                                &buffer[start_pos], temp);
4779                                         cert->der_len = temp;
4780                                 } else {
4781                                         cert->der_len = 0;
4782                                 }
4783                         }
4784                 } else {
4785                         switch (type) {
4786                         case 0x00:
4787                                 /* end of content */
4788                                 DEBUG_PRINT("END OF CONTENT\n");
4789                                 return pos;
4790                                 break;
4791                         case 0x01:
4792                                 /* boolean */
4793                                 temp = buffer[pos];
4794                                 DEBUG_PRINT("BOOLEAN: %i\n", temp);
4795                                 break;
4796                         case 0x02:
4797                                 /* integer */
4798                                 if (_is_field(fields, pk_id)) {
4799                                         if (has_key) {
4800                                                 *has_key = 1;
4801                                         }
4802
4803                                         if (idx == 1) {
4804                                                 tls_certificate_set_key
4805                                                     (cert, &buffer[pos],
4806                                                      length);
4807                                         } else if (idx == 2) {
4808                                                 tls_certificate_set_exponent
4809                                                     (cert, &buffer[pos],
4810                                                      length);
4811                                         }
4812                                 } else if (_is_field(fields, serial_id)) {
4813                                         tls_certificate_set_serial(cert,
4814                                                                    &buffer
4815                                                                    [pos],
4816                                                                    length);
4817                                 }
4818
4819                                 if (_is_field(fields, version_id)) {
4820                                         if (length == 1) {
4821                                                 cert->version =
4822                                                     buffer[pos];
4823                                         }
4824 #ifdef TLS_X509_V1_SUPPORT
4825                                         else {
4826                                                 cert->version = 0;
4827                                         }
4828                                         idx++;
4829 #endif
4830                                 }
4831                                 if (level >= 2) {
4832                                         unsigned int fields_temp[3];
4833                                         fields_temp[0] = fields[level - 2];
4834                                         fields_temp[1] = fields[level - 1];
4835                                         fields_temp[2] = 0;
4836                                         if (_is_field
4837                                             (fields_temp, priv_id)) {
4838                                                 tls_certificate_set_priv
4839                                                     (cert, &buffer[pos],
4840                                                      length);
4841                                         }
4842                                 }
4843                                 DEBUG_PRINT("INTEGER(%i): ", length);
4844                                 DEBUG_DUMP_HEX(&buffer[pos], length);
4845                                 if ((chain) && (length > 2)) {
4846                                         if (_private_is_oid
4847                                             (chain, san_oid,
4848                                              sizeof(san_oid) - 1)) {
4849                                                 void *new;
4850
4851                                                 new =
4852                                                     TLS_REALLOC(cert->san,
4853                                                                 sizeof
4854                                                                 (unsigned
4855                                                                  char *) *
4856                                                                 (cert->
4857                                                                  san_length
4858                                                                  + 1));
4859                                                 if (new) {
4860                                                         cert->san = new;
4861                                                         cert->san[cert->
4862                                                                   san_length]
4863                                                             = NULL;
4864                                                         tls_certificate_set_copy
4865                                                             (&cert->
4866                                                              san[cert->
4867                                                                  san_length],
4868                                                              &buffer[pos],
4869                                                              length);
4870                                                         DEBUG_PRINT
4871                                                             (" => SUBJECT ALTERNATIVE NAME: %s",
4872                                                              cert->
4873                                                              san[cert->
4874                                                                  san_length]);
4875                                                         cert->san_length++;
4876                                                 } else {
4877                                                         free(cert->
4878                                                                  san);
4879                                                         cert->san = 0;
4880                                                         cert->san_length =
4881                                                             0;
4882                                                 }
4883                                         }
4884                                 }
4885                                 DEBUG_PRINT("\n");
4886                                 break;
4887                         case 0x03:
4888                                 if (_is_field(fields, pk_id)) {
4889                                         if (has_key)
4890                                                 *has_key = 1;
4891                                 }
4892                                 /* bitstream */
4893                                 DEBUG_PRINT("BITSTREAM(%i): ", length);
4894                                 DEBUG_DUMP_HEX(&buffer[pos], length);
4895                                 DEBUG_PRINT("\n");
4896                                 if (_is_field(fields, sign_id)
4897                                     || _is_field(fields, sign_id2)) {
4898                                         DEBUG_PRINT("set sign key\n");
4899                                         tls_certificate_set_sign_key(cert,
4900                                                                      &buffer
4901                                                                      [pos],
4902                                                                      length);
4903                                 } else if (cert->ec_algorithm
4904                                            && (_is_field(fields, pk_id))) {
4905                                         tls_certificate_set_key(cert,
4906                                                                 &buffer
4907                                                                 [pos],
4908                                                                 length);
4909                                 } else {
4910                                         if (buffer[pos] == 0x00
4911                                             && length > 256) {
4912                                                 _private_asn1_parse
4913                                                     (context, cert,
4914                                                      &buffer[pos] + 1,
4915                                                      length - 1, level + 1,
4916                                                      fields,
4917                                                      &local_has_key,
4918                                                      client_cert, top_oid,
4919                                                      &local_chain);
4920                                         } else {
4921                                                 _private_asn1_parse
4922                                                     (context, cert,
4923                                                      &buffer[pos], length,
4924                                                      level + 1, fields,
4925                                                      &local_has_key,
4926                                                      client_cert, top_oid,
4927                                                      &local_chain);
4928                                         }
4929
4930                                         if (top_oid) {
4931                                                 if (_is_oid2
4932                                                     (top_oid,
4933                                                      TLS_EC_prime256v1_OID,
4934                                                      sizeof(oid),
4935                                                      sizeof
4936                                                      (TLS_EC_prime256v1) -
4937                                                      1)) {
4938                                                         cert->
4939                                                             ec_algorithm =
4940                                                             secp256r1.iana;
4941                                                 } else
4942                                                     if (_is_oid2
4943                                                         (top_oid,
4944                                                          TLS_EC_secp224r1_OID,
4945                                                          sizeof(oid),
4946                                                          sizeof
4947                                                          (TLS_EC_secp224r1_OID)
4948                                                          - 1)) {
4949                                                         cert->
4950                                                             ec_algorithm =
4951                                                             secp224r1.iana;
4952                                                 } else
4953                                                     if (_is_oid2
4954                                                         (top_oid,
4955                                                          TLS_EC_secp384r1_OID,
4956                                                          sizeof(oid),
4957                                                          sizeof
4958                                                          (TLS_EC_secp384r1_OID)
4959                                                          - 1)) {
4960                                                         cert->
4961                                                             ec_algorithm =
4962                                                             secp384r1.iana;
4963                                                 } else
4964                                                     if (_is_oid2
4965                                                         (top_oid,
4966                                                          TLS_EC_secp521r1_OID,
4967                                                          sizeof(oid),
4968                                                          sizeof
4969                                                          (TLS_EC_secp521r1_OID)
4970                                                          - 1)) {
4971                                                         cert->
4972                                                             ec_algorithm =
4973                                                             secp521r1.iana;
4974                                                 }
4975                                                 if ((cert->ec_algorithm)
4976                                                     && (!cert->pk))
4977                                                         tls_certificate_set_key
4978                                                             (cert,
4979                                                              &buffer[pos],
4980                                                              length);
4981                                         }
4982                                 }
4983                                 break;
4984                         case 0x04:
4985                                 if (top_oid && _is_field(fields, ecc_priv_id)
4986                                                 && !cert->priv) {
4987                                         DEBUG_PRINT("BINARY STRING(%i): ",
4988                                                     length);
4989                                         DEBUG_DUMP_HEX(&buffer[pos],
4990                                                        length);
4991                                         DEBUG_PRINT("\n");
4992                                         tls_certificate_set_priv(cert,
4993                                                                  &buffer
4994                                                                  [pos],
4995                                                                  length);
4996                                 } else {
4997                                         _private_asn1_parse(context, cert,
4998                                                             &buffer[pos],
4999                                                             length,
5000                                                             level + 1,
5001                                                             fields,
5002                                                             &local_has_key,
5003                                                             client_cert,
5004                                                             top_oid,
5005                                                             &local_chain);
5006                                 }
5007                                 break;
5008                         case 0x05:
5009                                 DEBUG_PRINT("NULL\n");
5010                                 break;
5011                         case 0x06:
5012                                 /* object identifier */
5013                                 if (_is_field(fields, pk_id)) {
5014                                         if (length == 8 || length == 5) {
5015                                                 tls_certificate_set_algorithm
5016                                                     (&cert->ec_algorithm,
5017                                                      &buffer[pos], length);
5018                                         } else {
5019                                                 tls_certificate_set_algorithm
5020                                                     (&cert->key_algorithm,
5021                                                      &buffer[pos], length);
5022                                         }
5023                                 }
5024                                 if (_is_field(fields, algorithm_id))
5025                                         tls_certificate_set_algorithm
5026                                             (&cert->algorithm,
5027                                              &buffer[pos], length);
5028
5029                                 DEBUG_PRINT("OBJECT IDENTIFIER(%i): ", length);
5030                                 DEBUG_DUMP_HEX(&buffer[pos], length);
5031                                 DEBUG_PRINT("\n");
5032                                 /* check previous oid */
5033                                 if (_is_oid2
5034                                     (oid, ocsp_oid, 16,
5035                                      sizeof(ocsp_oid) - 1))
5036                                         tls_certificate_set_copy(&cert->ocsp,
5037                                                                  &buffer[pos],
5038                                                                  length);
5039
5040                                 if (length < 16) {
5041                                         memcpy(oid, &buffer[pos], length);
5042                                 } else {
5043                                         memcpy(oid, &buffer[pos], 16);
5044                                 }
5045                                 if (top_oid)
5046                                         memcpy(top_oid, oid, 16);
5047                                 break;
5048                         case 0x09:
5049                                 DEBUG_PRINT("REAL NUMBER(%i): ", length);
5050                                 DEBUG_DUMP_HEX(&buffer[pos], length);
5051                                 DEBUG_PRINT("\n");
5052                                 break;
5053                         case 0x17:
5054                                 /* utc time */
5055                                 DEBUG_PRINT("UTC TIME: [");
5056                                 DEBUG_DUMP(&buffer[pos], length);
5057                                 DEBUG_PRINT("]\n");
5058
5059                                 if (_is_field(fields, validity_id)) {
5060                                         if (idx == 1) {
5061                                                 tls_certificate_set_copy_date
5062                                                     (cert->not_before,
5063                                                      &buffer[pos], length);
5064                                         } else {
5065                                                 tls_certificate_set_copy_date
5066                                                     (cert->not_after,
5067                                                      &buffer[pos], length);
5068                                         }
5069                                 }
5070                                 break;
5071                         case 0x18:
5072                                 /* generalized time */
5073                                 DEBUG_PRINT("GENERALIZED TIME: [");
5074                                 DEBUG_DUMP(&buffer[pos], length);
5075                                 DEBUG_PRINT("]\n");
5076                                 break;
5077                         case 0x13:
5078                                 /* printable string */
5079                         case 0x0C:
5080                         case 0x14:
5081                         case 0x15:
5082                         case 0x16:
5083                         case 0x19:
5084                         case 0x1A:
5085                         case 0x1B:
5086                         case 0x1C:
5087                         case 0x1D:
5088                         case 0x1E:
5089                                 if (_is_field(fields, issurer_id)) {
5090                                         if (_is_oid(oid, country_oid, 3)) {
5091                                                 tls_certificate_set_copy
5092                                                     (&cert->issuer_country,
5093                                                      &buffer[pos], length);
5094                                         } else if (_is_oid
5095                                                  (oid, state_oid, 3)) {
5096                                                 tls_certificate_set_copy
5097                                                     (&cert->issuer_state,
5098                                                      &buffer[pos], length);
5099                                         } else if (_is_oid
5100                                                  (oid, location_oid, 3)) {
5101                                                 tls_certificate_set_copy
5102                                                     (&cert->
5103                                                      issuer_location,
5104                                                      &buffer[pos], length);
5105                                         } else if (_is_oid
5106                                                  (oid, entity_oid, 3)) {
5107                                                 tls_certificate_set_copy
5108                                                     (&cert->issuer_entity,
5109                                                      &buffer[pos], length);
5110                                         } else if (_is_oid
5111                                                  (oid, subject_oid, 3)) {
5112                                                 tls_certificate_set_copy
5113                                                     (&cert->issuer_subject,
5114                                                      &buffer[pos], length);
5115                                         }
5116                                 } else if (_is_field(fields, owner_id)) {
5117                                         if (_is_oid(oid, country_oid, 3)) {
5118                                                 tls_certificate_set_copy
5119                                                     (&cert->country,
5120                                                      &buffer[pos], length);
5121                                         } else if (_is_oid
5122                                                  (oid, state_oid, 3)) {
5123                                                 tls_certificate_set_copy
5124                                                     (&cert->state,
5125                                                      &buffer[pos], length);
5126                                         } else if (_is_oid
5127                                                  (oid, location_oid, 3)) {
5128                                                 tls_certificate_set_copy
5129                                                     (&cert->location,
5130                                                      &buffer[pos], length);
5131                                         } else if (_is_oid
5132                                                  (oid, entity_oid, 3)) {
5133                                                 tls_certificate_set_copy
5134                                                     (&cert->entity,
5135                                                      &buffer[pos], length);
5136                                         } else if (_is_oid
5137                                                  (oid, subject_oid, 3)) {
5138                                                 tls_certificate_set_copy
5139                                                     (&cert->subject,
5140                                                      &buffer[pos], length);
5141                                         }
5142                                 }
5143                                 DEBUG_PRINT("STR: [");
5144                                 DEBUG_DUMP(&buffer[pos], length);
5145                                 DEBUG_PRINT("]\n");
5146                                 break;
5147                         case 0x10:
5148                                 DEBUG_PRINT("EMPTY SEQUENCE\n");
5149                                 break;
5150                         case 0xA:
5151                                 DEBUG_PRINT("ENUMERATED(%i): ", length);
5152                                 DEBUG_DUMP_HEX(&buffer[pos], length);
5153                                 DEBUG_PRINT("\n");
5154                                 break;
5155                         default:
5156                                 DEBUG_PRINT("========> NOT SUPPORTED %x\n",
5157                                             (int) type);
5158                                 /* not supported / needed */
5159                                 break;
5160                         }
5161                 }
5162                 pos += length;
5163         }
5164
5165         if (level == 2 && cert->sign_key && cert->sign_len
5166             && cert_len && cert_data) {
5167                 free(cert->fingerprint);
5168                 cert->fingerprint = tls_compute_hash(cert->algorithm,
5169                                 cert_data, cert_len);
5170 #ifdef DEBUG
5171                 if (cert->fingerprint) {
5172                         DEBUG_DUMP_HEX_LABEL("FINGERPRINT",
5173                                              cert->fingerprint,
5174                                              tls_hash_len(cert->algorithm));
5175                 }
5176 #endif
5177         }
5178         return pos;
5179 }
5180
5181 struct TLSCertificate *asn1_parse(struct TLSContext *context,
5182                                   const unsigned char *buffer, int size,
5183                                   int client_cert) {
5184         unsigned int fields[TLS_ASN1_MAXLEVEL] = { 0 };
5185
5186         struct TLSCertificate *cert = tls_create_certificate();
5187
5188         if (cert) {
5189                 if (client_cert < 0) {
5190                         client_cert = 0;
5191                         /* private key */
5192                         unsigned char top_oid[16];
5193                         memset(top_oid, 0, sizeof(top_oid));
5194                         _private_asn1_parse(context, cert, buffer, size, 1,
5195                                             fields, NULL, client_cert,
5196                                             top_oid, NULL);
5197                 } else {
5198                         _private_asn1_parse(context, cert, buffer, size, 1,
5199                                             fields, NULL, client_cert,
5200                                             NULL, NULL);
5201                 }
5202         }
5203         return cert;
5204 }
5205
5206 int tls_clear_certificates(struct TLSContext *tls) {
5207         int i;
5208
5209         if (!tls || !tls->is_server || tls->is_child) {
5210                 return TLS_GENERIC_ERROR;
5211         }
5212
5213         if (tls->root_certificates) {
5214                 for (i = 0; i < tls->root_count; i++) {
5215                         tls_destroy_certificate(tls->root_certificates[i]);
5216                 }
5217         }
5218         tls->root_certificates = NULL;
5219         tls->root_count = 0;
5220
5221         if (tls->private_key) {
5222                 tls_destroy_certificate(tls->private_key);
5223         }
5224         tls->private_key = NULL;
5225         if (tls->ec_private_key) {
5226                 tls_destroy_certificate(tls->ec_private_key);
5227         }
5228         tls->ec_private_key = NULL;
5229         free(tls->certificates);
5230         tls->certificates = NULL;
5231         tls->certificates_count = 0;
5232         return 0;
5233 }
5234
5235 /* This is just a wrapper around parse message so we don't
5236  * call read more often than necessary.  IOW, if there's
5237  * more than one record in the input buffer, process them all
5238  */
5239 int tls_consume_stream(struct TLSContext *context) {
5240         if (!context) {
5241                 return TLS_GENERIC_ERROR;
5242         }
5243
5244         if (context->critical_error) {
5245                 return TLS_BROKEN_CONNECTION;
5246         }
5247
5248         size_t tls_buffer_len = context->input_buffer.len;
5249         unsigned char *buffer = context->input_buffer.buffer;
5250
5251         unsigned int index = 0;
5252         int err_flag = 0;
5253
5254         int tls_header_size;
5255         int tls_size_offset;
5256
5257         tls_size_offset = 3;
5258         tls_header_size = 5;
5259
5260         while (tls_buffer_len >= 5) {
5261                 uint16_t length;
5262
5263                 length = get16(buffer + index + tls_size_offset)
5264                     + tls_header_size;
5265
5266                 if (length > tls_buffer_len) {
5267                         /* record not complete */
5268                         break;
5269                 }
5270
5271                 /* This is the only place tls_parse_message is called */
5272                 int consumed = tls_parse_message(context, buffer+index, length);
5273                 if (consumed < 0) {
5274                         err_flag = consumed;
5275                         break;
5276                 }
5277                 index += length;
5278                 tls_buffer_len -= length;
5279                 if (context->critical_error) {
5280                         err_flag = TLS_BROKEN_CONNECTION;
5281                         break;
5282                 }
5283         }
5284
5285         if (err_flag || context->input_buffer.error) {
5286                 if (!context->critical_error) {
5287                         context->critical_error = 1;
5288                 }
5289                 DEBUG_PRINT("ERROR IN CONSUME: %i\n", err_flag);
5290                 tls_buffer_free(&context->input_buffer);
5291                 return err_flag;
5292         }
5293         tls_buffer_shift(&context->input_buffer, index);
5294         return index;
5295 }
5296
5297 void tls_close_notify(struct TLSContext *context) {
5298         if (!context || context->critical_error) {
5299                 return;
5300         }
5301         context->critical_error = 1;
5302         DEBUG_PRINT("CLOSE\n");
5303         tls_alert(context, 0, close_notify);
5304 }
5305
5306 void tls_alert(struct TLSContext *context, int critical, int code) {
5307         if (!context) {
5308                 return;
5309         }
5310
5311         struct TLSPacket *packet = tls_create_packet(context, TLS_ALERT,
5312                         context->version, 0);
5313         tls_packet_uint8(packet, critical ? TLS_ALERT_CRITICAL :
5314                         TLS_ALERT_WARNING);
5315
5316         tls_packet_uint8(packet, code);
5317         tls_packet_update(packet);
5318
5319         if (critical) {
5320                 context->critical_error = 1;
5321         }
5322
5323         tls_queue_packet(packet);
5324 }
5325
5326 int tls_is_broken(struct TLSContext *context) {
5327         if (!context || context->critical_error) {
5328                 return 1;
5329         }
5330         return 0;
5331 }
5332
5333 /* TODO I don't see that this ever gets cleared */
5334 int tls_request_client_certificate(struct TLSContext *context) {
5335         if (!context || !context->is_server) {
5336                 return 0;
5337         }
5338
5339         context->request_client_certificate = 1;
5340         return 1;
5341 }
5342
5343 int tls_client_verified(struct TLSContext *context) {
5344         if (!context || context->critical_error) {
5345                 return 0;
5346         }
5347
5348         return context->client_verified == 1;
5349 }
5350
5351 int tls_sni_set(struct TLSContext *context, const char *sni) {
5352         if (!context || context->is_server || context->critical_error
5353             || context->connection_status != 0) {
5354                 return 0;
5355         }
5356
5357         free(context->sni);
5358         errno = 0;
5359         context->sni = sni ? strdup(sni) : 0;
5360         return context->sni ? 1 : 0;
5361 }
5362
5363 int tls_default_verify(struct TLSContext *context,
5364                        struct TLSCertificate **certificate_chain, int len) 
5365 {
5366         int i;
5367         int err;
5368
5369         if (certificate_chain) {
5370                 for (i = 0; i < len; i++) {
5371                         struct TLSCertificate *certificate =
5372                             certificate_chain[i];
5373                         /* check validity date */
5374                         err = tls_certificate_is_valid(certificate);
5375                         if (err) {
5376                                 return err;
5377                         }
5378                 }
5379         }
5380         /* check if chain is valid */
5381         err = tls_certificate_chain_is_valid(certificate_chain, len);
5382         if (err) {
5383                 return err;
5384         }
5385
5386         /* check certificate subject */
5387         if (!context->is_server && context->sni && len > 0
5388             && certificate_chain) {
5389                 err = tls_certificate_valid_subject(certificate_chain[0],
5390                                 context->sni);
5391                 if (err) {
5392                         return err;
5393                 }
5394         }
5395
5396         err = tls_certificate_chain_is_valid_root(context, certificate_chain,
5397                                                 len);
5398         if (err) {
5399                 return err;
5400         }
5401
5402         DEBUG_PRINT("Certificate OK\n");
5403         return no_error;
5404 }
5405
5406 ssize_t tls_fsync(struct TLSContext *context) {
5407         size_t buflen = 0;
5408         size_t offset = 0;
5409         ssize_t send_res = 0;
5410         int fd;
5411         unsigned char *buffer;
5412         tls_send_func write_cb = NULL;
5413
5414         if (!context) {
5415                 return 0;
5416         }
5417
5418         fd = context->fd;
5419         if (fd < 0) {
5420                 return -1;
5421         }
5422
5423         buffer = context->output_buffer.buffer;
5424         buflen = context->output_buffer.len;
5425
5426         if (context->send) {
5427                 write_cb = context->send;
5428         } else {
5429                 write_cb = send;
5430         }
5431
5432         while (buflen > 0) {
5433                 ssize_t res;
5434                 errno = 0;
5435                 res = write_cb(fd, buffer+offset, buflen, 0);
5436                 if (res <= 0) {
5437                         perror("send error");
5438                         send_res = res;
5439                         break;
5440                 }
5441                 buflen -= res;
5442                 offset += res;
5443                 send_res += res;
5444         }
5445         DEBUG_PRINT("sent %zd bytes\n", send_res);
5446         context->output_buffer.len = 0;
5447         return send_res;
5448 }
5449
5450 void tls_free(struct TLSContext *context) {
5451         if (context) {
5452                 free(context->user_data);
5453                 tls_destroy_context(context);
5454         }
5455 }
5456
5457 int tls_set_fd(struct TLSContext *context, int socket) {
5458         if (!context) {
5459                 return TLS_GENERIC_ERROR;
5460         }
5461         context->fd = socket;
5462         return 0;
5463 }
5464
5465 int tls_load_root_file(struct TLSContext *context, const char *pem_filename) {
5466         int fd;
5467         struct stat st;
5468         void *addr;
5469
5470         if (!context) {
5471                 return -1;
5472         }
5473
5474         int count = -1;
5475
5476         fd = open(pem_filename, O_RDONLY);
5477         if (fd == -1) {
5478                 return -1;
5479         }
5480
5481         if (fstat(fd, &st) == -1) {
5482                 close(fd);
5483                 return -1;
5484         }
5485
5486         addr = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
5487         if (addr == MAP_FAILED) {
5488                 close(fd);
5489                 return -1;
5490         }
5491
5492         count = tls_load_root_certificates(context, addr, st.st_size);
5493         munmap(addr, st.st_size);
5494         close(fd);
5495
5496         return count;
5497 }
5498
5499 void tls_set_verify(struct TLSContext *tls, tls_validation_function vfunc) {
5500         if (tls) {
5501                 tls->certificate_verify = vfunc;
5502         }
5503 }
5504
5505 static ssize_t tls_safe_read(struct TLSContext *tls) {
5506         tls_recv_func read_cb;
5507         char buffer[8192];
5508         ssize_t bytes;
5509
5510         if (!tls || tls->fd <= 0) {
5511                 return TLS_GENERIC_ERROR;
5512         }
5513
5514         if (tls->recv) {
5515                 read_cb = tls->recv;
5516         } else {
5517                 read_cb = recv;
5518         }
5519
5520         errno = 0;
5521         bytes = read_cb(tls->fd, buffer, sizeof buffer, 0);
5522         if (bytes > 0) {
5523                 tls_buffer_append(&tls->input_buffer, buffer, bytes);
5524         }
5525
5526         return bytes;
5527 }
5528
5529 /* I think this is the server handshake */
5530 int SSL_accept(struct TLSContext *context) {
5531         ssize_t read_size = 0;
5532
5533         if (!context || context->fd <= 0) {
5534                 return TLS_GENERIC_ERROR;
5535         }
5536
5537         if (tls_established(context)) {
5538                 return 1;
5539         }
5540
5541         /* accept */
5542         while ((read_size = tls_safe_read(context)) > 0) {
5543                 if (tls_consume_stream(context) >= 0) {
5544                         ssize_t res = tls_fsync(context);
5545                         if (res < 0) {
5546                                 return res;
5547                         }
5548                 }
5549                 if (tls_established(context)) {
5550                         return 1;
5551                 }
5552         }
5553         if (read_size <= 0) {
5554                 return TLS_BROKEN_CONNECTION;
5555         }
5556         return 0;
5557 }
5558
5559 /* TODO this is really do the handshake */
5560 int tls_connect(struct TLSContext *context) {
5561         int res;
5562         ssize_t read_size;
5563
5564         if (!context || context->fd <= 0 || context->critical_error) {
5565                 return TLS_GENERIC_ERROR;
5566         }
5567
5568         if (context->is_server) {
5569                 return TLS_UNEXPECTED_MESSAGE;
5570         }
5571
5572         res = tls_queue_packet(tls_build_client_hello(context));
5573
5574         if (res < 0) {
5575                 return res;
5576         }
5577
5578         res = tls_fsync(context);
5579         if (res < 0) {
5580                 return res;
5581         }
5582
5583         while ((read_size = tls_safe_read(context)) > 0) {
5584                 if ((res = tls_consume_stream(context)) >= 0) {
5585                         res = tls_fsync(context);
5586                         if (res < 0) {
5587                                 return res;
5588                         }
5589                 }
5590                 if (tls_established(context)) {
5591                         return 1;
5592                 }
5593                 if (context->critical_error) {
5594                         return TLS_GENERIC_ERROR;
5595                 }
5596         }
5597         return read_size;
5598 }
5599
5600 int tls_shutdown(struct TLSContext *tls) {
5601         if (!tls || tls->fd <= 0) {
5602                 return TLS_GENERIC_ERROR;
5603         }
5604
5605         tls_close_notify(tls);
5606         return 0;
5607 }
5608
5609 /* TODO configure for maximum packet data length
5610  * max is 2^14 - 5 byte header - 32 byte mac - padding which depends
5611  * on the cipher (up to 255 bytes I think).
5612  */
5613 ssize_t tls_write(struct TLSContext *context, const void *buf, size_t count) {
5614         if (!context) {
5615                 return TLS_GENERIC_ERROR;
5616         }
5617         if (context->connection_status != TLS_CONNECTED) {
5618                 return TLS_UNEXPECTED_MESSAGE;
5619         }
5620         if (count > TLS_MAXTLS_APP_SIZE) {
5621                 count = TLS_MAXTLS_APP_SIZE;
5622         }
5623
5624         if (!buf || !count) {
5625                 return 0;
5626         }
5627
5628         struct TLSPacket *packet = tls_create_packet(context,
5629                         TLS_APPLICATION_DATA, context->version, count);
5630         tls_packet_append(packet, buf, count);
5631         tls_packet_update(packet);
5632
5633         tls_queue_packet(packet);
5634         /* TODO think about this.  context->sync with O_NONBLOCK might be a
5635          * problem
5636          */
5637         if (context->sync) {
5638                 ssize_t res;
5639                 res = tls_fsync(context);
5640                 if (res == -1) {
5641                         return res;
5642                 }
5643         }
5644         return count;
5645 }
5646
5647 static ssize_t tls_readbuf(struct TLSContext *tls, void *buf, size_t count) {
5648         if (count > tls->application_buffer.len) {
5649                 count = tls->application_buffer.len;
5650         }
5651
5652         if (count > 0) {
5653                 /* TODO should have a buffer read and shift */
5654                 memcpy(buf, tls->application_buffer.buffer, count);
5655                 tls_buffer_shift(&tls->application_buffer, count);
5656         }
5657
5658         return count;
5659 }
5660
5661 ssize_t tls_read(struct TLSContext *context, void *buf, size_t count) {
5662         if (!context) {
5663                 return TLS_GENERIC_ERROR;
5664         }
5665
5666         if (context->application_buffer.len) {
5667                 return tls_readbuf(context, buf, count);
5668         }
5669
5670         if (context->fd <= 0 || context->critical_error) {
5671                 return TLS_GENERIC_ERROR;
5672         }
5673
5674         if (tls_established(context) != 1) {
5675                 return TLS_GENERIC_ERROR;
5676         }
5677
5678         if (context->application_buffer.len == 0 && !context->critical_error) {
5679                 /* attempt to fill buffer, unless we're already in an error
5680                  * state
5681                  */
5682                 ssize_t read_size;
5683
5684                 while ((read_size = tls_safe_read(context)) > 0) {
5685                         if (tls_consume_stream(context) > 0) {
5686                                 tls_fsync(context);
5687                                 break;
5688                         }
5689                         if (context->critical_error
5690                             && !context->application_buffer.len) {
5691                                 /* if there's a critical error, don't bail if
5692                                  * we managed to get some data
5693                                  */
5694                                 return TLS_GENERIC_ERROR;
5695                         }
5696                 }
5697
5698                 if (read_size <= 0 && context->application_buffer.len == 0) {
5699                         /* can return errors as for read(2) */
5700                         return read_size;
5701                 }
5702         }
5703
5704         return tls_readbuf(context, buf, count);
5705 }