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