1 #define _POSIX_C_SOURCE 200809L
13 #include <sys/socket.h>
14 #include <arpa/inet.h>
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)
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
50 #define TLS_DH_DEFAULT_P "87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597"
51 #define TLS_DH_DEFAULT_G "3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659"
52 #define TLS_DHE_KEY_SIZE 2048
55 #define htonll(x) ((1==htonl(1)) ? (x) : ((uint64_t)htonl((x) & 0xFFFFFFFF) << 32) | htonl((x) >> 32))
59 #define ntohll(x) ((1==ntohl(1)) ? (x) : ((uint64_t)ntohl((x) & 0xFFFFFFFF) << 32) | ntohl((x) >> 32))
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]++; }
72 } KeyExchangeAlgorithm;
79 rsa_ephemeral_dh_RESERVED = 5,
80 dss_ephemeral_dh_RESERVED = 6,
81 fortezza_dms_RESERVED = 20,
85 } TLSClientCertificateType;
103 } TLSSignatureAlgorithm;
110 typedef ssize_t (*tls_recv_func)(int sockfd, void *buf, size_t len,
112 typedef ssize_t (*tls_send_func)(int sockfd, const void *buf, size_t len,
115 static const unsigned int version_id[] = { 1, 1, 1, 0 };
116 static const unsigned int pk_id[] = { 1, 1, 7, 0 };
117 static const unsigned int serial_id[] = { 1, 1, 2, 1, 0 };
118 static const unsigned int issurer_id[] = { 1, 1, 4, 0 };
119 static const unsigned int owner_id[] = { 1, 1, 6, 0 };
120 static const unsigned int validity_id[] = { 1, 1, 5, 0 };
121 static const unsigned int algorithm_id[] = { 1, 1, 3, 0 };
122 static const unsigned int sign_id[] = { 1, 3, 2, 1, 0 };
123 static const unsigned int sign_id2[] = { 1, 3, 2, 2, 0 };
124 static const unsigned int priv_id[] = { 1, 4, 0 };
125 static const unsigned int priv_der_id[] = { 1, 3, 1, 0 };
126 static const unsigned int ecc_priv_id[] = { 1, 2, 0 };
128 static const unsigned char country_oid[] = { 0x55, 0x04, 0x06, 0x00 };
129 static const unsigned char state_oid[] = { 0x55, 0x04, 0x08, 0x00 };
130 static const unsigned char location_oid[] = { 0x55, 0x04, 0x07, 0x00 };
131 static const unsigned char entity_oid[] = { 0x55, 0x04, 0x0A, 0x00 };
132 static const unsigned char subject_oid[] = { 0x55, 0x04, 0x03, 0x00 };
133 static const unsigned char san_oid[] = { 0x55, 0x1D, 0x11, 0x00 };
134 static const unsigned char ocsp_oid[] =
135 { 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x01, 0x00 };
137 static const unsigned char TLS_RSA_SIGN_RSA_OID[] =
138 { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x00 };
139 static const unsigned char TLS_RSA_SIGN_MD5_OID[] =
140 { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x04, 0x00 };
141 static const unsigned char TLS_RSA_SIGN_SHA1_OID[] =
142 { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x05, 0x00 };
143 static const unsigned char TLS_RSA_SIGN_SHA256_OID[] =
144 { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x00 };
145 static const unsigned char TLS_RSA_SIGN_SHA384_OID[] =
146 { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0C, 0x00 };
147 static const unsigned char TLS_RSA_SIGN_SHA512_OID[] =
148 { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0D, 0x00 };
151 static const unsigned char TLS_ECDSA_SIGN_SHA1_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x01, 0x05, 0x00, 0x00};
152 static const unsigned char TLS_ECDSA_SIGN_SHA224_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x01, 0x05, 0x00, 0x00};
153 static const unsigned char TLS_ECDSA_SIGN_SHA256_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02, 0x05, 0x00, 0x00};
154 static const unsigned char TLS_ECDSA_SIGN_SHA384_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x03, 0x05, 0x00, 0x00};
155 static const unsigned char TLS_ECDSA_SIGN_SHA512_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x04, 0x05, 0x00, 0x00};
158 static const unsigned char TLS_EC_PUBLIC_KEY_OID[] =
159 { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01, 0x00 };
161 static const unsigned char TLS_EC_prime192v1_OID[] =
162 { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x01, 0x00 };
163 static const unsigned char TLS_EC_prime192v2_OID[] =
164 { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x02, 0x00 };
165 static const unsigned char TLS_EC_prime192v3_OID[] =
166 { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x03, 0x00 };
167 static const unsigned char TLS_EC_prime239v1_OID[] =
168 { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x04, 0x00 };
169 static const unsigned char TLS_EC_prime239v2_OID[] =
170 { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x05, 0x00 };
171 static const unsigned char TLS_EC_prime239v3_OID[] =
172 { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x06, 0x00 };
173 static const unsigned char TLS_EC_prime256v1_OID[] =
174 { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07, 0x00 };
176 #define TLS_EC_secp256r1_OID TLS_EC_prime256v1_OID
177 static const unsigned char TLS_EC_secp224r1_OID[] =
178 { 0x2B, 0x81, 0x04, 0x00, 0x21, 0x00 };
179 static const unsigned char TLS_EC_secp384r1_OID[] =
180 { 0x2B, 0x81, 0x04, 0x00, 0x22, 0x00 };
181 static const unsigned char TLS_EC_secp521r1_OID[] =
182 { 0x2B, 0x81, 0x04, 0x00, 0x23, 0x00 };
184 int tls_random(unsigned char *key, int len);
185 void tls_destroy_packet(struct TLSPacket *packet);
186 struct TLSPacket *tls_build_hello(struct TLSContext *context,
187 int tls13_downgrade);
191 static unsigned char TLS_DSA_SIGN_SHA1_OID[] = {0x2A, 0x86, 0x52, 0xCE, 0x38, 0x04, 0x03, 0x00};
194 static uint16_t get16(const unsigned char *buf) {
197 res = ((*buf) << 8) + (*(buf+1));
201 static uint32_t get24(const unsigned char *buf) {
204 res = (buf[0] << 16) + (buf[1] << 8) + buf[2];
208 size_t tls_queue_packet(struct TLSPacket *packet) {
213 struct TLSContext *context = packet->context;
219 tls_buffer_append(&context->output_buffer, packet->buf, packet->len);
220 tls_destroy_packet(packet);
221 return context->output_buffer.len;
224 static void tls_send_change_cipher_spec(struct TLSContext *context) {
225 struct TLSPacket *packet =
226 tls_create_packet(context, TLS_CHANGE_CIPHER, context->version,
228 tls_packet_uint8(packet, 1);
229 tls_packet_update(packet);
230 context->local_sequence_number = 0;
231 tls_queue_packet(packet);
235 static void tls_send_encrypted_extensions(struct TLSContext *context) {
236 struct TLSPacket *packet =
237 tls_create_packet(context, TLS_HANDSHAKE, context->version, 3);
238 tls_packet_uint8(packet, 0x08);
240 if (context->negotiated_alpn) {
241 int alpn_negotiated_len = strlen(context->negotiated_alpn);
242 int alpn_len = alpn_negotiated_len + 1;
244 tls_packet_uint24(packet, alpn_len + 8);
245 tls_packet_uint16(packet, alpn_len + 6);
246 tls_packet_uint16(packet, 0x10);
247 tls_packet_uint16(packet, alpn_len + 2);
248 tls_packet_uint16(packet, alpn_len);
250 tls_packet_uint8(packet, alpn_negotiated_len);
251 tls_packet_append(packet, (unsigned char *) context->
252 negotiated_alpn, alpn_negotiated_len);
254 tls_packet_uint24(packet, 2);
255 tls_packet_uint16(packet, 0);
257 tls_packet_update(packet);
258 tls_queue_packet(packet);
262 static void tls_send_done(struct TLSContext *context) {
263 struct TLSPacket *packet =
264 tls_create_packet(context, TLS_HANDSHAKE, context->version, 0);
265 tls_packet_uint8(packet, 0x0E);
266 tls_packet_uint24(packet, 0);
267 tls_packet_update(packet);
268 tls_queue_packet(packet);
272 static void tls_send_certificate(struct TLSContext *context) {
274 unsigned int all_certificate_size = 0;
275 int certificates_count;
276 struct TLSCertificate **certificates;
278 if (context->is_server) {
279 certificates_count = context->certificates_count;
280 certificates = context->certificates;
282 certificates_count = context->client_certificates_count;
283 certificates = context->client_certificates;
287 if (context->tlsver == TLS_VERSION13) {
291 int is_ecdsa = tls_is_ecdsa(context);
292 /* TODO can do one loop and test for ecdsa inside loop */
294 for (i = 0; i < certificates_count; i++) {
295 struct TLSCertificate *cert = certificates[i];
296 if (cert && cert->der_len && cert->ec_algorithm) {
297 all_certificate_size += cert->der_len + delta;
301 for (i = 0; i < certificates_count; i++) {
302 struct TLSCertificate *cert = certificates[i];
303 if (cert && cert->der_len && !cert->ec_algorithm) {
304 all_certificate_size += cert->der_len + delta;
309 for (i = 0; i < certificates_count; i++) {
310 struct TLSCertificate *cert = certificates[i];
311 if (cert && cert->der_len) {
312 all_certificate_size += cert->der_len + delta;
316 if (!all_certificate_size) {
317 DEBUG_PRINT("NO CERTIFICATE SET\n");
320 struct TLSPacket *packet = tls_create_packet(context, TLS_HANDSHAKE,
321 context->version, 0);
322 tls_packet_uint8(packet, 0x0B);
324 if (all_certificate_size) {
326 if (context->tlsver == TLS_VERSION13) {
327 tls_packet_uint24(packet, all_certificate_size + 4);
328 tls_packet_uint8(packet, 0);
330 tls_packet_uint24(packet, all_certificate_size + 3);
333 tls_packet_uint24(packet, all_certificate_size);
335 for (i = 0; i < certificates_count; i++) {
336 struct TLSCertificate *cert = certificates[i];
337 if (cert && cert->der_len) {
338 /* is RSA certificate ? */
339 if (is_ecdsa && !cert->ec_algorithm) {
342 /* is ECC certificate ? */
343 if (!is_ecdsa && cert->ec_algorithm) {
346 /* 2 times -> one certificate */
347 tls_packet_uint24(packet, cert->der_len);
348 tls_packet_append(packet, cert->der_bytes,
351 if (context->tlsver == TLS_VERSION13) {
352 tls_packet_uint16(packet, 0);
357 tls_packet_uint24(packet, all_certificate_size);
358 if (context->tlsver == TLS_VERSION13) {
359 tls_packet_uint8(packet, 0);
363 tls_packet_update(packet);
364 tls_queue_packet(packet);
368 int tls_supported_version(uint16_t ver) {
374 DEBUG_PRINT("UNSUPPORTED TLS VERSION %x\n", (int)ver);
380 void tls_set_packet_length(struct TLSPacket *packet, uint32_t length) {
381 int offset = packet->payload_pos;
382 packet->buf[offset] = (length >> 16) & 0xff;
383 packet->buf[offset+1] = (length >> 8) & 0xff;
384 packet->buf[offset+2] = (length >> 0) & 0xff;
387 static void tls_init() {
388 static int loaded = 0;
393 DEBUG_PRINT("Initializing dependencies\n");
402 /* TODO remove these */
403 register_hash(&md5_desc);
404 register_hash(&sha1_desc);
406 register_hash(&sha256_desc);
407 register_hash(&sha384_desc);
408 register_hash(&sha512_desc);
410 register_prng(&sprng_desc);
412 register_cipher(&aes_desc);
414 tls_ecc_init_curves();
417 static unsigned char *decrypt_rsa(struct TLSContext *context,
418 const unsigned char *buffer,
420 unsigned int *size) {
422 if (!len || !context || !context->private_key
423 || !context->private_key->der_bytes
424 || !context->private_key->der_len) {
425 DEBUG_PRINT("No private key set\n");
430 err = rsa_import(context->private_key->der_bytes,
431 context->private_key->der_len, &key);
434 DEBUG_PRINT("Error importing RSA key (code: %i)\n", err);
438 unsigned char *out = malloc(len);
439 unsigned long out_size = len;
440 int hash_idx = find_hash("sha256");
442 err = rsa_decrypt_key_ex(buffer, len, out, &out_size, (unsigned char *)
443 "Concept", 7, hash_idx, LTC_PKCS_1_V1_5, &res, &key);
446 if (err || !out_size) {
447 DEBUG_PRINT("RSA DECRYPT ERROR\n");
451 *size = (unsigned int) out_size;
455 static int verify_rsa(struct TLSContext *context, unsigned int hash_type, const
456 unsigned char *buffer, unsigned int len, const unsigned char
457 *message, unsigned long message_len) {
462 return TLS_GENERIC_ERROR;
465 struct TLSCertificate **cert;
468 if (context->is_server) {
469 cert = context->client_certificates;
470 count = context->client_certificates_count;
472 cert = context->certificates;
473 count = context->certificates_count;
476 if (count == 0 || !cert) {
477 return TLS_GENERIC_ERROR;
480 err = rsa_import(cert[0]->der_bytes, cert[0]->der_len, &key);
483 DEBUG_PRINT("Error importing RSA certificate (code: %i)\n",
485 return TLS_GENERIC_ERROR;
488 unsigned char hash[TLS_MAX_HASH_LEN];
489 unsigned long hash_len;
490 hash_len = (unsigned long)sizeof hash;
494 hash_idx = find_hash("md5");
497 hash_idx = find_hash("sha1");
500 hash_idx = find_hash("sha256");
503 hash_idx = find_hash("sha384");
506 hash_idx = find_hash("sha512");
509 err = hash_memory(hash_idx, message, message_len, hash, &hash_len);
510 if (hash_idx < 0 || err) {
511 DEBUG_PRINT("Unsupported hash type: %i\n", hash_type);
512 return TLS_GENERIC_ERROR;
515 if (context->tlsver == TLS_VERSION13) {
516 err = rsa_verify_hash_ex(buffer, len, hash, hash_len,
517 LTC_PKCS_1_PSS, hash_idx, 0, &rsa_stat, &key);
519 err = rsa_verify_hash_ex(buffer, len, hash, hash_len,
520 LTC_PKCS_1_V1_5, hash_idx, 0, &rsa_stat, &key);
529 static int sign_rsa(struct TLSContext *context, unsigned int hash_type, const
530 unsigned char *message, unsigned int message_len, unsigned char
531 *out, unsigned long *outlen) {
535 unsigned char hash[TLS_MAX_HASH_LEN];
536 unsigned long hash_len = 0;
539 if (!outlen || !context || !out || !context->private_key
540 || !context->private_key->der_bytes
541 || !context->private_key->der_len) {
542 DEBUG_PRINT("No private key set\n");
543 return TLS_GENERIC_ERROR;
546 err = rsa_import(context->private_key->der_bytes,
547 context->private_key->der_len, &key);
550 DEBUG_PRINT("Error %d importing RSA certificate", err);
551 return TLS_GENERIC_ERROR;
556 hash_index = find_hash("sha1");
560 hash_index = find_hash("sha256");
564 hash_index = find_hash("sha384");
568 hash_index = find_hash("sha512");
573 hash_index = find_hash("md5");
578 if (hash_index < 0 || err) {
579 DEBUG_PRINT("Unsupported hash type: %i\n", hash_type);
580 return TLS_GENERIC_ERROR;
583 hash_memory(hash_index, message, message_len, hash, &hash_len);
585 if (hash_type == _md5_sha1) {
586 unsigned long hlen = 20;
587 hash_index = find_hash("sha1");
588 hash_memory(hash_index, message, message_len, hash+16, &hlen);
592 //err = hash_memory(hash_idx, message, message_len, hash, &hash_len);
594 if (context->tlsver == TLS_VERSION13) {
595 err = rsa_sign_hash_ex(hash, hash_len, out, outlen,
596 LTC_PKCS_1_PSS, NULL, find_prng("sprng"),
597 hash_index, hash_type == sha256 ? 32 : 48, &key);
599 err = rsa_sign_hash_ex(hash, hash_len, out, outlen,
600 LTC_PKCS_1_V1_5, NULL, find_prng("sprng"),
601 hash_index, 0, &key);
612 static int tls_is_point(ecc_key * key) {
613 void *prime, *b, *t1, *t2;
616 if ((err = mp_init_multi(&prime, &b, &t1, &t2, NULL)) != CRYPT_OK) {
620 /* load prime and b */
621 if ((err = mp_read_radix(prime, key->dp->prime, 16)) != CRYPT_OK) {
624 if ((err = mp_read_radix(b, key->dp->B, 16)) != CRYPT_OK) {
629 if ((err = mp_sqr(key->pubkey.y, t1)) != CRYPT_OK) {
634 if ((err = mp_sqr(key->pubkey.x, t2)) != CRYPT_OK) {
637 if ((err = mp_mod(t2, prime, t2)) != CRYPT_OK) {
640 if ((err = mp_mul(key->pubkey.x, t2, t2)) != CRYPT_OK) {
644 /* compute y^2 - x^3 */
645 if ((err = mp_sub(t1, t2, t1)) != CRYPT_OK) {
649 /* compute y^2 - x^3 + 3x */
650 if ((err = mp_add(t1, key->pubkey.x, t1)) != CRYPT_OK) {
653 if ((err = mp_add(t1, key->pubkey.x, t1)) != CRYPT_OK) {
656 if ((err = mp_add(t1, key->pubkey.x, t1)) != CRYPT_OK) {
659 if ((err = mp_mod(t1, prime, t1)) != CRYPT_OK) {
662 while (mp_cmp_d(t1, 0) == LTC_MP_LT) {
663 if ((err = mp_add(t1, prime, t1)) != CRYPT_OK) {
667 while (mp_cmp(t1, prime) != LTC_MP_LT) {
668 if ((err = mp_sub(t1, prime, t1)) != CRYPT_OK) {
674 if (mp_cmp(t1, b) != LTC_MP_EQ) {
675 err = CRYPT_INVALID_PACKET;
681 mp_clear_multi(prime, b, t1, t2, NULL);
685 static int tls_ecc_import_key(const unsigned char *private_key,
687 const unsigned char *public_key,
688 int public_len, ecc_key *key,
689 const ltc_ecc_set_type *dp) {
692 if (!key || !ltc_mp.name) {
696 key->type = PK_PRIVATE;
699 (&key->pubkey.x, &key->pubkey.y, &key->pubkey.z, &key->k,
703 if (public_len && !public_key[0]) {
707 if ((err = mp_read_unsigned_bin(key->pubkey.x,
708 (unsigned char *) public_key + 1,
709 (public_len - 1) >> 1)) != CRYPT_OK) {
710 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
715 if ((err = mp_read_unsigned_bin(key->pubkey.y,
716 (unsigned char *) public_key + 1 +
717 ((public_len - 1) >> 1),
718 (public_len - 1) >> 1)) != CRYPT_OK) {
719 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
725 mp_read_unsigned_bin(key->k, (unsigned char *) private_key,
726 private_len)) != CRYPT_OK) {
727 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
736 if ((err = mp_set(key->pubkey.z, 1)) != CRYPT_OK) {
737 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
742 /* is it a point on the curve? */
743 if ((err = tls_is_point(key)) != CRYPT_OK) {
744 DEBUG_PRINT("KEY IS NOT ON CURVE\n");
745 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
754 static int sign_ecdsa(struct TLSContext *context,
755 unsigned int hash_type,
756 const unsigned char *message,
757 unsigned int message_len, unsigned char *out,
758 unsigned long *outlen) {
759 if (!outlen || !context || !out || !outlen
760 || !context->ec_private_key
761 || !context->ec_private_key->priv
762 || !context->ec_private_key->priv_len
763 || !context->ec_private_key->pk
764 || !context->ec_private_key->pk_len) {
765 DEBUG_PRINT("No private ECDSA key set\n");
766 return TLS_GENERIC_ERROR;
769 const struct ECCCurveParameters *curve = NULL;
771 switch (context->ec_private_key->ec_algorithm) {
794 DEBUG_PRINT("UNSUPPORTED CURVE\n");
798 return TLS_GENERIC_ERROR;
804 ltc_ecc_set_type *dp = (ltc_ecc_set_type *)&curve->dp;
806 /* broken ... fix this */
807 err = tls_ecc_import_key(context->ec_private_key->priv,
808 context->ec_private_key->priv_len,
809 context->ec_private_key->pk,
810 context->ec_private_key->pk_len, &key, dp);
813 DEBUG_PRINT("Error importing ECC certificate (code: %i)\n",
815 return TLS_GENERIC_ERROR;
818 unsigned char hash[TLS_MAX_HASH_LEN];
819 unsigned long hash_len = 0;
824 hash_index = find_hash("sha1");
828 hash_index = find_hash("sha256");
832 hash_index = find_hash("sha384");
836 hash_index = find_hash("sha512");
841 hash_index = find_hash("md5");
846 hash_memory(hash_index, message, message_len, hash, &hash_len);
848 if (hash_type == _md5_sha1) {
849 unsigned long hlen = 20;
850 hash_index = find_hash("sha1");
851 hash_memory(hash_index, message, message_len, hash+16, &hlen);
856 DEBUG_PRINT("Unsupported hash type: %i\n", hash_type);
857 return TLS_GENERIC_ERROR;
859 /* "Let z be the Ln leftmost bits of e, where Ln is the bit length of
860 * the group order n." */
861 if ((int)hash_len > curve->size) {
862 hash_len = curve->size;
864 err = ecc_sign_hash(hash, hash_len, out, outlen, NULL,
865 find_prng("sprng"), &key);
866 DEBUG_DUMP_HEX_LABEL("ECC SIGNATURE", out, *outlen);
872 static void tls_send_certificate_verify(struct TLSContext *context) {
873 struct TLSPacket *packet =
874 tls_create_packet(context, TLS_HANDSHAKE, context->version, 0);
875 /* certificate verify */
876 tls_packet_uint8(packet, 0x0F);
877 tls_packet_uint24(packet, 0);
879 unsigned char out[TLS_MAX_RSA_KEY];
880 unsigned long out_len = TLS_MAX_RSA_KEY;
882 unsigned char signing_data[TLS_MAX_HASH_SIZE + 98];
883 int signing_data_len;
885 /* first 64 bytes to 0x20 (32) */
886 memset(signing_data, 0x20, 64);
887 /* context string 33 bytes */
888 if (context->is_server) {
889 memcpy(signing_data + 64, "TLS 1.3, server CertificateVerify",
892 memcpy(signing_data + 64, "TLS 1.3, client CertificateVerify",
895 /* a single 0 byte separator */
896 signing_data[97] = 0;
897 signing_data_len = 98;
899 signing_data_len += tls_get_hash(context, signing_data + 98);
900 DEBUG_DUMP_HEX_LABEL("verify data", signing_data, signing_data_len);
901 int hash_algorithm = sha256;
902 if (tls_is_ecdsa(context)) {
903 switch (context->ec_private_key->ec_algorithm) {
905 /* secp256r1 + sha256 */
906 tls_packet_uint16(packet, 0x0403);
909 /* secp384r1 + sha384 */
910 tls_packet_uint16(packet, 0x0503);
911 hash_algorithm = sha384;
914 /* secp521r1 + sha512 */
915 tls_packet_uint16(packet, 0x0603);
916 hash_algorithm = sha512;
919 DEBUG_PRINT("UNSUPPORTED CURVE (SIGNING)\n");
925 tls_packet_uint16(packet, 0x0804);
930 if (tls_is_ecdsa(context)) {
931 if (sign_ecdsa(context, hash_algorithm, signing_data,
932 signing_data_len, out, &out_len) == 1)
935 ("ECDSA signing OK! (ECDSA, length %lu)\n",
937 tls_packet_uint16(packet, out_len);
938 tls_packet_append(packet, out, out_len);
939 packet_size += out_len + 2;
941 } else if (sign_rsa(context, hash_algorithm, signing_data,
942 signing_data_len, out, &out_len) == 1) {
943 DEBUG_PRINT("RSA signing OK! (length %lu)\n", out_len);
944 tls_packet_uint16(packet, out_len);
945 tls_packet_append(packet, out, out_len);
946 packet_size += out_len + 2;
949 tls_set_packet_length(packet, packet_size);
951 tls_packet_update(packet);
952 tls_queue_packet(packet);
956 static int tls_ecc_import_pk(const unsigned char *public_key,
957 int public_len, ecc_key * key,
958 const ltc_ecc_set_type * dp) {
961 if (!key || !ltc_mp.name) {
965 key->type = PK_PUBLIC;
967 if (mp_init_multi(&key->pubkey.x, &key->pubkey.y, &key->pubkey.z,
968 &key->k, NULL) != CRYPT_OK) {
972 if (public_len && !public_key[0]) {
976 if ((err = mp_read_unsigned_bin(key->pubkey.x,
977 (unsigned char *) public_key + 1,
978 (public_len - 1) >> 1)) != CRYPT_OK) {
979 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
984 if ((err = mp_read_unsigned_bin(key->pubkey.y,
985 (unsigned char *) public_key + 1 +
986 ((public_len - 1) >> 1),
987 (public_len - 1) >> 1)) != CRYPT_OK) {
988 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
997 if ((err = mp_set(key->pubkey.z, 1)) != CRYPT_OK) {
998 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
1003 /* is it a point on the curve? */
1004 if ((err = tls_is_point(key)) != CRYPT_OK) {
1005 DEBUG_PRINT("KEY IS NOT ON CURVE\n");
1006 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
1015 static int tls_verify_ecdsa(struct TLSContext *context,
1016 unsigned int hash_type,
1017 const unsigned char *buffer,
1019 const unsigned char *message,
1020 unsigned int message_len,
1021 const struct ECCCurveParameters *curve_hint)
1027 curve_hint = context->curve;
1031 return TLS_GENERIC_ERROR;
1034 struct TLSCertificate **cert;
1037 if (context->is_server) {
1038 cert = context->client_certificates;
1039 count = context->client_certificates_count;
1041 cert = context->certificates;
1042 count = context->certificates_count;
1045 if (count == 0 || !cert || !cert[0] || !cert[0]->pk ||
1047 return TLS_GENERIC_ERROR;
1050 err = tls_ecc_import_pk(cert[0]->pk, cert[0]->pk_len, &key,
1051 (ltc_ecc_set_type *)&curve_hint->dp);
1054 DEBUG_PRINT("Error importing ECC certificate (code: %i)", err);
1055 return TLS_GENERIC_ERROR;
1059 unsigned char hash[TLS_MAX_HASH_LEN];
1060 unsigned long hash_len = 0;
1062 switch (hash_type) {
1064 hash_idx = find_hash("md5");
1068 hash_idx = find_hash("sha1");
1072 hash_idx = find_hash("sha256");
1076 hash_idx = find_hash("sha384");
1080 hash_idx = find_hash("sha512");
1085 err = hash_memory(hash_idx, message, message_len, hash, &hash_len);
1087 if (hash_idx < 0 || err) {
1088 DEBUG_PRINT("Unsupported hash type: %i\n", hash_type);
1089 return TLS_GENERIC_ERROR;
1093 err = ecc_verify_hash(buffer, len, hash, hash_len, &ecc_stat, &key);
1101 static void prf_helper(int hash_idx, unsigned long dlen,
1102 unsigned char *output, unsigned int outlen,
1103 const unsigned char *secret,
1104 const unsigned int secret_len,
1105 const unsigned char *label,
1106 unsigned int label_len, unsigned char *seed,
1107 unsigned int seed_len, unsigned char *seed_b,
1108 unsigned int seed_b_len) {
1109 unsigned char digest_out0[TLS_MAX_HASH_LEN];
1110 unsigned char digest_out1[TLS_MAX_HASH_LEN];
1114 hmac_init(&hmac, hash_idx, secret, secret_len);
1115 hmac_process(&hmac, label, label_len);
1117 hmac_process(&hmac, seed, seed_len);
1118 if (seed_b && seed_b_len) {
1119 hmac_process(&hmac, seed_b, seed_b_len);
1121 hmac_done(&hmac, digest_out0, &dlen);
1124 hmac_init(&hmac, hash_idx, secret, secret_len);
1125 hmac_process(&hmac, digest_out0, dlen);
1126 hmac_process(&hmac, label, label_len);
1127 hmac_process(&hmac, seed, seed_len);
1128 if (seed_b && seed_b_len) {
1129 hmac_process(&hmac, seed_b, seed_b_len);
1131 hmac_done(&hmac, digest_out1, &dlen);
1133 unsigned int copylen = outlen;
1134 if (copylen > dlen) {
1138 for (i = 0; i < copylen; i++) {
1139 output[idx++] ^= digest_out1[i];
1147 hmac_init(&hmac, hash_idx, secret, secret_len);
1148 hmac_process(&hmac, digest_out0, dlen);
1149 hmac_done(&hmac, digest_out0, &dlen);
1153 static void tls_prf(struct TLSContext *context,
1154 unsigned char *output, unsigned int outlen,
1155 const unsigned char *secret,
1156 const unsigned int secret_len,
1157 const unsigned char *label, unsigned int label_len,
1158 unsigned char *seed, unsigned int seed_len,
1159 unsigned char *seed_b, unsigned int seed_b_len) {
1160 if (!secret || !secret_len) {
1161 DEBUG_PRINT("NULL SECRET\n");
1165 /* TODO I don't think this is right, wouldn't use md5 for tls v1.3 */
1166 if (context->version != TLS_V12) {
1167 int md5_hash_idx = find_hash("md5");
1168 int sha1_hash_idx = find_hash("sha1");
1169 int half_secret = (secret_len + 1) / 2;
1171 memset(output, 0, outlen);
1172 prf_helper(md5_hash_idx, 16, output, outlen, secret,
1173 half_secret, label, label_len, seed, seed_len,
1174 seed_b, seed_b_len);
1175 prf_helper(sha1_hash_idx, 20, output, outlen, secret +
1176 (secret_len - half_secret), secret_len -
1177 half_secret, label, label_len, seed, seed_len,
1178 seed_b, seed_b_len);
1181 unsigned char digest_out0[TLS_MAX_HASH_LEN];
1182 unsigned char digest_out1[TLS_MAX_HASH_LEN];
1183 unsigned long dlen = 32;
1185 unsigned int mac_length = tls_mac_length(context);
1187 if (mac_length == TLS_SHA384_MAC_SIZE) {
1188 hash_idx = find_hash("sha384");
1191 hash_idx = find_hash("sha256");
1197 hmac_init(&hmac, hash_idx, secret, secret_len);
1198 hmac_process(&hmac, label, label_len);
1199 hmac_process(&hmac, seed, seed_len);
1200 if (seed_b && seed_b_len) {
1201 hmac_process(&hmac, seed_b, seed_b_len);
1203 hmac_done(&hmac, digest_out0, &dlen);
1207 hmac_init(&hmac, hash_idx, secret, secret_len);
1208 hmac_process(&hmac, digest_out0, dlen);
1209 hmac_process(&hmac, label, label_len);
1210 hmac_process(&hmac, seed, seed_len);
1211 if (seed_b && seed_b_len) {
1212 hmac_process(&hmac, seed_b, seed_b_len);
1214 hmac_done(&hmac, digest_out1, &dlen);
1216 unsigned int copylen = outlen;
1217 if (copylen > dlen) {
1218 copylen = (unsigned int) dlen;
1221 for (i = 0; i < copylen; i++) {
1222 output[idx++] = digest_out1[i];
1230 hmac_init(&hmac, hash_idx, secret, secret_len);
1231 hmac_process(&hmac, digest_out0, dlen);
1232 hmac_done(&hmac, digest_out0, &dlen);
1237 static void tls_send_finished(struct TLSContext *context) {
1238 struct TLSPacket *packet =
1239 tls_create_packet(context, TLS_HANDSHAKE, context->version,
1240 TLS_MIN_FINISHED_OPAQUE_LEN + 64);
1241 tls_packet_uint8(packet, 0x14);
1243 if (context->tlsver == TLS_VERSION13) {
1244 tls_packet_uint24(packet, tls_mac_length(context));
1246 tls_packet_uint24(packet, TLS_MIN_FINISHED_OPAQUE_LEN);
1250 unsigned char hash[TLS_MAX_HASH_SIZE];
1251 unsigned long out_size = TLS_MIN_FINISHED_OPAQUE_LEN;
1252 unsigned char out[TLS_MAX_HASH_SIZE];
1253 unsigned int hash_len;
1255 int context_is_v13 = 0;
1257 if (packet->context->tlsver == TLS_VERSION13) {
1261 /* server verifies client's message */
1262 if (context->is_server) {
1263 if (context_is_v13) {
1264 hash_len = tls_get_hash(context, hash);
1265 if (!context->finished_key || !hash_len) {
1267 ("NO FINISHED KEY COMPUTED OR NO HANDSHAKE HASH\n");
1269 /* TODO probably need to terminate */
1270 tls_destroy_packet(packet);
1274 DEBUG_DUMP_HEX_LABEL("HS HASH", hash, hash_len);
1275 DEBUG_DUMP_HEX_LABEL("HS FINISH",
1276 context->finished_key,
1279 out_size = hash_len;
1281 hmac_init(&hmac, tls_get_hash_idx(context),
1282 context->finished_key, hash_len);
1283 hmac_process(&hmac, hash, hash_len);
1284 hmac_done(&hmac, out, &out_size);
1286 hash_len = tls_done_hash(context, hash);
1287 tls_prf(context, out,
1288 TLS_MIN_FINISHED_OPAQUE_LEN,
1289 context->master_key,
1290 context->master_key_len,
1292 "server finished", 15, hash,
1294 tls_destroy_hash(context);
1298 hash_len = tls_get_hash(context, hash);
1299 tls_prf(context, out, TLS_MIN_FINISHED_OPAQUE_LEN,
1300 context->master_key,
1301 context->master_key_len,
1302 (unsigned char *) "client finished", 15,
1303 hash, hash_len, NULL, 0);
1306 tls_packet_append(packet, out, out_size);
1307 tls_packet_update(packet);
1308 DEBUG_DUMP_HEX_LABEL("VERIFY DATA", out, out_size);
1309 tls_queue_packet(packet);
1313 static int tls_key_length(struct TLSContext *context) {
1314 switch (context->cipher) {
1315 case TLS_RSA_WITH_AES_128_CBC_SHA:
1316 case TLS_RSA_WITH_AES_128_CBC_SHA256:
1317 case TLS_RSA_WITH_AES_128_GCM_SHA256:
1318 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
1319 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
1320 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
1321 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
1322 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
1323 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
1324 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
1325 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
1326 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
1327 case TLS_AES_128_GCM_SHA256:
1329 case TLS_RSA_WITH_AES_256_CBC_SHA:
1330 case TLS_RSA_WITH_AES_256_CBC_SHA256:
1331 case TLS_RSA_WITH_AES_256_GCM_SHA384:
1332 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
1333 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
1334 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
1335 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
1336 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
1337 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
1338 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
1339 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
1340 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
1341 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
1342 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
1343 case TLS_AES_256_GCM_SHA384:
1344 case TLS_CHACHA20_POLY1305_SHA256:
1350 /* 0 is none, 1 is GCM?, 2 is chacha */
1351 int tls_is_aead(struct TLSContext *context) {
1352 switch (context->cipher) {
1353 case TLS_RSA_WITH_AES_128_GCM_SHA256:
1354 case TLS_RSA_WITH_AES_256_GCM_SHA384:
1355 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
1356 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
1357 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
1358 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
1359 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
1360 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
1361 case TLS_AES_128_GCM_SHA256:
1362 case TLS_AES_256_GCM_SHA384:
1364 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
1365 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
1366 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
1367 case TLS_CHACHA20_POLY1305_SHA256:
1373 int tls_mac_length(struct TLSContext *context) {
1374 switch (context->cipher) {
1375 case TLS_RSA_WITH_AES_128_CBC_SHA:
1376 case TLS_RSA_WITH_AES_256_CBC_SHA:
1377 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
1378 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
1379 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
1380 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
1381 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
1382 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
1383 return TLS_SHA1_MAC_SIZE;
1384 case TLS_RSA_WITH_AES_128_CBC_SHA256:
1385 case TLS_RSA_WITH_AES_256_CBC_SHA256:
1386 case TLS_RSA_WITH_AES_128_GCM_SHA256:
1387 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
1388 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
1389 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
1390 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
1391 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
1392 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
1393 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
1394 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
1395 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
1396 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
1397 case TLS_AES_128_GCM_SHA256:
1398 case TLS_CHACHA20_POLY1305_SHA256:
1399 case TLS_AES_128_CCM_SHA256:
1400 case TLS_AES_128_CCM_8_SHA256:
1401 return TLS_SHA256_MAC_SIZE;
1402 case TLS_RSA_WITH_AES_256_GCM_SHA384:
1403 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
1404 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
1405 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
1406 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
1407 case TLS_AES_256_GCM_SHA384:
1408 return TLS_SHA384_MAC_SIZE;
1413 int _private_tls13_key(struct TLSContext *context, int handshake) {
1414 int key_length = tls_key_length(context);
1415 int mac_length = tls_mac_length(context);
1417 if (!context->premaster_key || !context->premaster_key_len) {
1421 if (!key_length || !mac_length) {
1423 ("KEY EXPANSION FAILED, KEY LENGTH: %i, MAC LENGTH: %i\n",
1424 key_length, mac_length);
1428 unsigned char *clientkey = NULL;
1429 unsigned char *serverkey = NULL;
1430 unsigned char *clientiv = NULL;
1431 unsigned char *serveriv = NULL;
1432 int is_aead = tls_is_aead(context);
1434 unsigned char local_keybuffer[TLS_V13_MAX_KEY_SIZE];
1435 unsigned char local_ivbuffer[TLS_V13_MAX_IV_SIZE];
1436 unsigned char remote_keybuffer[TLS_V13_MAX_KEY_SIZE];
1437 unsigned char remote_ivbuffer[TLS_V13_MAX_IV_SIZE];
1439 unsigned char prk[TLS_MAX_HASH_SIZE];
1440 unsigned char hash[TLS_MAX_HASH_SIZE];
1441 static unsigned char earlysecret[TLS_MAX_HASH_SIZE];
1443 const char *server_key = "s ap traffic";
1444 const char *client_key = "c ap traffic";
1446 server_key = "s hs traffic";
1447 client_key = "c hs traffic";
1450 unsigned char salt[TLS_MAX_HASH_SIZE];
1453 /* TODO what is the point of this ? */
1454 if (mac_length == TLS_SHA384_MAC_SIZE) {
1456 sha384_done(&md, hash);
1459 sha256_done(&md, hash);
1461 /* extract secret "early" */
1462 if (context->master_key && context->master_key_len && !handshake) {
1463 DEBUG_DUMP_HEX_LABEL("USING PREVIOUS SECRET",
1464 context->master_key,
1465 context->master_key_len);
1466 tls_hkdf_expand_label(mac_length, salt, mac_length,
1467 context->master_key, context->master_key_len,
1468 "derived", 7, hash, mac_length);
1469 DEBUG_DUMP_HEX_LABEL("salt", salt, mac_length);
1470 tls_hkdf_extract(mac_length, prk, mac_length, salt, mac_length,
1471 earlysecret, mac_length);
1473 tls_hkdf_extract(mac_length, prk, mac_length, NULL, 0,
1474 earlysecret, mac_length);
1475 /* derive secret for handshake "tls13 derived": */
1476 DEBUG_DUMP_HEX_LABEL("null hash", hash, mac_length);
1477 tls_hkdf_expand_label(mac_length, salt, mac_length, prk,
1478 mac_length, "derived", 7, hash, mac_length);
1479 /* extract secret "handshake": */
1480 DEBUG_DUMP_HEX_LABEL("salt", salt, mac_length);
1481 tls_hkdf_extract(mac_length, prk, mac_length,
1483 context->premaster_key,
1484 context->premaster_key_len);
1488 DEBUG_PRINT("KEY EXPANSION FAILED, NON AEAD CIPHER\n");
1492 unsigned char secret[TLS_MAX_MAC_SIZE];
1493 unsigned char hs_secret[TLS_MAX_HASH_SIZE];
1497 hash_size = tls_get_hash(context, hash);
1499 hash_size = tls_done_hash(context, hash);
1502 DEBUG_DUMP_HEX_LABEL("messages hash", hash, hash_size);
1504 if (context->is_server) {
1505 tls_hkdf_expand_label(mac_length, hs_secret, mac_length, prk,
1506 mac_length, server_key, 12, context->
1507 server_finished_hash ? context->
1508 server_finished_hash : hash, hash_size);
1509 DEBUG_DUMP_HEX_LABEL(server_key, hs_secret, mac_length);
1510 serverkey = local_keybuffer;
1511 serveriv = local_ivbuffer;
1512 clientkey = remote_keybuffer;
1513 clientiv = remote_ivbuffer;
1515 tls_hkdf_expand_label(mac_length, hs_secret,
1516 mac_length, prk, mac_length,
1519 server_finished_hash ?
1521 server_finished_hash : hash,
1523 serverkey = remote_keybuffer;
1524 serveriv = remote_ivbuffer;
1525 clientkey = local_keybuffer;
1526 clientiv = local_ivbuffer;
1529 int iv_length = TLS_13_AES_GCM_IV_LENGTH;
1531 iv_length = TLS_CHACHA20_IV_LENGTH;
1534 tls_hkdf_expand_label(mac_length, local_keybuffer, key_length,
1535 hs_secret, mac_length, "key", 3, NULL, 0);
1536 tls_hkdf_expand_label(mac_length, local_ivbuffer, iv_length, hs_secret,
1537 mac_length, "iv", 2, NULL, 0);
1539 tls_hkdf_expand_label(mac_length, secret,
1540 mac_length, prk, mac_length,
1541 context->is_server ? client_key : server_key,
1543 context->server_finished_hash ?
1544 context->server_finished_hash :
1548 tls_hkdf_expand_label(mac_length, remote_keybuffer, key_length, secret,
1549 mac_length, "key", 3, NULL, 0);
1550 tls_hkdf_expand_label(mac_length, remote_ivbuffer, iv_length, secret,
1551 mac_length, "iv", 2, NULL, 0);
1553 DEBUG_DUMP_HEX_LABEL("CLIENT KEY", clientkey, key_length);
1554 DEBUG_DUMP_HEX_LABEL("CLIENT IV", clientiv, iv_length);
1555 DEBUG_DUMP_HEX_LABEL("SERVER KEY", serverkey, key_length);
1556 DEBUG_DUMP_HEX_LABEL("SERVER IV", serveriv, iv_length);
1557 free(context->finished_key);
1558 free(context->remote_finished_key);
1561 context->finished_key = malloc(mac_length);
1562 context->remote_finished_key = malloc(mac_length);
1564 if (context->finished_key) {
1565 tls_hkdf_expand_label(mac_length,
1566 context->finished_key, mac_length,
1567 hs_secret, mac_length, "finished", 8,
1569 DEBUG_DUMP_HEX_LABEL("FINISHED", context->finished_key,
1573 if (context->remote_finished_key) {
1574 tls_hkdf_expand_label(mac_length,
1575 context->remote_finished_key,
1576 mac_length, secret, mac_length,
1577 "finished", 8, NULL, 0);
1578 DEBUG_DUMP_HEX_LABEL("FINISHED", context->finished_key,
1582 context->finished_key = NULL;
1583 context->remote_finished_key = NULL;
1584 free(context->server_finished_hash);
1585 context->server_finished_hash = NULL;
1588 if (context->is_server) {
1590 memcpy(context->crypto.ctx_remote_mac.remote_nonce,
1591 clientiv, iv_length);
1592 memcpy(context->crypto.ctx_local_mac.local_nonce,
1593 serveriv, iv_length);
1594 } else if (is_aead) {
1595 memcpy(context->crypto.ctx_remote_mac.remote_iv,
1596 clientiv, iv_length);
1597 memcpy(context->crypto.ctx_local_mac.local_iv,
1598 serveriv, iv_length);
1600 if (tls_crypto_create(context, key_length,
1601 serverkey, serveriv, clientkey,
1607 memcpy(context->crypto.ctx_local_mac.local_nonce,
1608 clientiv, iv_length);
1609 memcpy(context->crypto.ctx_remote_mac.remote_nonce,
1610 serveriv, iv_length);
1611 } else if (is_aead) {
1612 memcpy(context->crypto.ctx_local_mac.local_iv,
1613 clientiv, iv_length);
1614 memcpy(context->crypto.ctx_remote_mac.remote_iv,
1615 serveriv, iv_length);
1618 if (tls_crypto_create(context, key_length,
1619 clientkey, clientiv, serverkey,
1625 context->crypto.created = 1 + is_aead;
1627 free(context->master_key);
1628 context->master_key = malloc(mac_length);
1629 if (context->master_key) {
1630 memcpy(context->master_key, prk, mac_length);
1631 context->master_key_len = mac_length;
1633 context->local_sequence_number = 0;
1634 context->remote_sequence_number = 0;
1637 * extract client_mac_key(mac_key_length)
1638 * extract server_mac_key(mac_key_length)
1639 * extract client_key(enc_key_length)
1640 * extract server_key(enc_key_length)
1641 * extract client_iv(fixed_iv_lengh)
1642 * extract server_iv(fixed_iv_length)
1647 static int tls_expand_key(struct TLSContext *context) {
1648 unsigned char key[TLS_MAX_KEY_EXPANSION_SIZE];
1649 if (context->tlsver == TLS_VERSION13) {
1653 if (!context->master_key || !context->master_key_len) {
1657 int key_length = tls_key_length(context);
1658 int mac_length = tls_mac_length(context);
1660 if (!key_length || !mac_length) {
1662 ("KEY EXPANSION FAILED, KEY LENGTH: %i, MAC LENGTH: %i\n",
1663 key_length, mac_length);
1666 unsigned char *clientkey = NULL;
1667 unsigned char *serverkey = NULL;
1668 unsigned char *clientiv = NULL;
1669 unsigned char *serveriv = NULL;
1670 int iv_length = TLS_AES_IV_LENGTH;
1671 int is_aead = tls_is_aead(context);
1673 if (context->is_server) {
1674 tls_prf(context, key, sizeof(key),
1675 context->master_key, context->master_key_len,
1676 (unsigned char *) "key expansion", 13,
1677 context->local_random, TLS_SERVER_RANDOM_SIZE,
1678 context->remote_random,
1679 TLS_CLIENT_RANDOM_SIZE);
1681 tls_prf(context, key, sizeof(key),
1682 context->master_key,
1683 context->master_key_len,
1684 (unsigned char *) "key expansion", 13,
1685 context->remote_random,
1686 TLS_SERVER_RANDOM_SIZE,
1687 context->local_random,
1688 TLS_CLIENT_RANDOM_SIZE);
1691 DEBUG_DUMP_HEX_LABEL("LOCAL RANDOM ", context->local_random,
1692 TLS_SERVER_RANDOM_SIZE);
1693 DEBUG_DUMP_HEX_LABEL("REMOTE RANDOM", context->remote_random,
1694 TLS_CLIENT_RANDOM_SIZE);
1695 DEBUG_PRINT("\n=========== EXPANSION ===========\n");
1696 DEBUG_DUMP_HEX(key, TLS_MAX_KEY_EXPANSION_SIZE);
1701 iv_length = TLS_CHACHA20_IV_LENGTH;
1704 iv_length = TLS_AES_GCM_IV_LENGTH;
1706 if (context->is_server) {
1707 memcpy(context->crypto.ctx_remote_mac.remote_mac,
1708 &key[pos], mac_length);
1710 memcpy(context->crypto.ctx_local_mac.local_mac,
1711 &key[pos], mac_length);
1714 memcpy(context->crypto.ctx_local_mac.local_mac,
1715 &key[pos], mac_length);
1717 memcpy(context->crypto.ctx_remote_mac.remote_mac,
1718 &key[pos], mac_length);
1724 clientkey = &key[pos];
1726 serverkey = &key[pos];
1728 clientiv = &key[pos];
1730 serveriv = &key[pos];
1732 DEBUG_PRINT("EXPANSION %i/%i\n", (int) pos,
1733 (int) TLS_MAX_KEY_EXPANSION_SIZE);
1734 DEBUG_DUMP_HEX_LABEL("CLIENT KEY", clientkey, key_length);
1735 DEBUG_DUMP_HEX_LABEL("CLIENT IV", clientiv, iv_length);
1736 DEBUG_DUMP_HEX_LABEL("CLIENT MAC KEY",
1737 context->is_server ? context->crypto.
1738 ctx_remote_mac.remote_mac : context->
1739 crypto.ctx_local_mac.local_mac,
1741 DEBUG_DUMP_HEX_LABEL("SERVER KEY", serverkey, key_length);
1742 DEBUG_DUMP_HEX_LABEL("SERVER IV", serveriv, iv_length);
1743 DEBUG_DUMP_HEX_LABEL("SERVER MAC KEY",
1744 context->is_server ? context->crypto.
1745 ctx_local_mac.local_mac : context->crypto.
1746 ctx_remote_mac.remote_mac, mac_length);
1747 if (context->is_server) {
1749 memcpy(context->crypto.ctx_remote_mac.remote_nonce,
1750 clientiv, iv_length);
1751 memcpy(context->crypto.ctx_local_mac.local_nonce,
1752 serveriv, iv_length);
1755 memcpy(context->crypto.ctx_remote_mac.
1756 remote_aead_iv, clientiv, iv_length);
1757 memcpy(context->crypto.ctx_local_mac.local_aead_iv,
1758 serveriv, iv_length);
1762 if (tls_crypto_create(context, key_length,
1763 serverkey, serveriv, clientkey,
1769 memcpy(context->crypto.ctx_local_mac.local_nonce,
1770 clientiv, iv_length);
1771 memcpy(context->crypto.ctx_remote_mac.remote_nonce,
1772 serveriv, iv_length);
1775 memcpy(context->crypto.ctx_local_mac.local_aead_iv,
1776 clientiv, iv_length);
1777 memcpy(context->crypto.ctx_remote_mac.
1778 remote_aead_iv, serveriv, iv_length);
1782 if (tls_crypto_create(context, key_length,
1783 clientkey, clientiv, serverkey,
1790 * extract client_mac_key(mac_key_length)
1791 * extract server_mac_key(mac_key_length)
1792 * extract client_key(enc_key_length)
1793 * extract server_key(enc_key_length)
1794 * extract client_iv(fixed_iv_lengh)
1795 * extract server_iv(fixed_iv_length)
1800 int tls_compute_key(struct TLSContext *context, unsigned int key_len) {
1801 if (context->tlsver == TLS_VERSION13) {
1805 if (!context->premaster_key || !context->premaster_key_len
1807 DEBUG_PRINT("CANNOT COMPUTE MASTER SECRET\n");
1811 unsigned char master_secret_label[] = "master secret";
1812 #ifdef TLS_CHECK_PREMASTER_KEY
1813 if (!tls_cipher_is_ephemeral(context)) {
1814 uint16_t version = get16(context->premaster_key);
1815 /* this check is not true for DHE/ECDHE ciphers */
1816 if (context->version > version) {
1817 DEBUG_PRINT("Mismatch protocol version 0x(%x)\n",
1823 free(context->master_key);
1824 context->master_key_len = 0;
1825 context->master_key = NULL;
1827 context->master_key = malloc(key_len);
1828 if (!context->master_key) {
1832 context->master_key_len = key_len;
1833 if (context->is_server) {
1835 context->master_key,
1836 context->master_key_len,
1837 context->premaster_key,
1838 context->premaster_key_len,
1839 master_secret_label, 13,
1840 context->remote_random,
1841 TLS_CLIENT_RANDOM_SIZE,
1842 context->local_random,
1843 TLS_SERVER_RANDOM_SIZE);
1846 context->master_key,
1847 context->master_key_len,
1848 context->premaster_key,
1849 context->premaster_key_len,
1850 master_secret_label, 13,
1851 context->local_random,
1852 TLS_CLIENT_RANDOM_SIZE,
1853 context->remote_random,
1854 TLS_SERVER_RANDOM_SIZE);
1856 free(context->premaster_key);
1857 context->premaster_key = NULL;
1858 context->premaster_key_len = 0;
1859 DEBUG_PRINT("\n=========== Master key ===========\n");
1860 DEBUG_DUMP_HEX(context->master_key,
1861 context->master_key_len);
1863 tls_expand_key(context);
1867 int _is_oid(const unsigned char *oid, const unsigned char *compare_to,
1868 int compare_to_len) {
1870 while ((oid[i]) && (i < compare_to_len)) {
1871 if (oid[i] != compare_to[i])
1879 int _is_oid2(const unsigned char *oid, const unsigned char *compare_to,
1880 int compare_to_len, int oid_len) {
1882 if (oid_len < compare_to_len) {
1883 compare_to_len = oid_len;
1886 while (i < compare_to_len) {
1887 if (oid[i] != compare_to[i]) {
1896 struct TLSCertificate *tls_create_certificate() {
1897 struct TLSCertificate zero = { 0 };
1898 struct TLSCertificate *cert = malloc(sizeof *cert);
1902 cert->not_before[0] = 0;
1903 cert->not_after[0] = 0;
1908 int tls_certificate_valid_subject_name(const unsigned char *cert_subject,
1909 const char *subject) {
1910 /* no subjects ... */
1911 if ((!cert_subject || !cert_subject[0]) && (!subject || !subject[0])) {
1915 if (!subject || !subject[0]) {
1916 return bad_certificate;
1919 if (!cert_subject || !cert_subject[0]) {
1920 return bad_certificate;
1924 if (!strcmp((const char *) cert_subject, subject)) {
1928 const char *wildcard = strchr((const char *) cert_subject, '*');
1930 /* 6.4.3 (1) The client SHOULD NOT attempt to match a presented
1931 * identifier in which the wildcard character comprises a label
1932 * other than the left-most label
1937 * subject is [something*] .. invalid
1939 return bad_certificate;
1942 const char *match = strstr(subject, wildcard);
1943 if ((!match) && (wildcard[0] == '.')) {
1944 /* check *.domain.com against domain.com */
1946 if (!strcasecmp(subject, wildcard))
1950 unsigned long offset = (unsigned long) match -
1951 (unsigned long) subject;
1953 /* check for foo.*.domain.com against *.domain.com (invalid) */
1954 if (memchr(subject, '.', offset))
1955 return bad_certificate;
1957 /* check if exact match */
1958 if (!strcasecmp(match, wildcard)) {
1964 return bad_certificate;
1967 int tls_certificate_valid_subject(struct TLSCertificate *cert,
1968 const char *subject) {
1971 return certificate_unknown;
1974 int err = tls_certificate_valid_subject_name(cert->subject, subject);
1975 if (err && cert->san) {
1976 for (i = 0; i < cert->san_length; i++) {
1977 err = tls_certificate_valid_subject_name(cert->san[i],
1987 int tls_certificate_is_valid(struct TLSCertificate *cert) {
1989 return certificate_unknown;
1992 char ts[16]; /* YYYYMMDDHHMMSSZ */
1993 time_t t = time(NULL);
1994 struct tm *utc = gmtime(&t);
1997 strftime(ts, sizeof ts, "%Y%m%d%H%M%SZ", utc);
1999 if (strcmp(cert->not_before, ts) > 0) {
2001 ("Certificate is not yet valid, now: %s (validity: %s - %s)\n",
2002 ts, cert->not_before, cert->not_after);
2003 return certificate_expired;
2006 if (strcmp(cert->not_after, ts) < 0) {
2008 ("Expired certificate, now: %s (validity: %s - %s)\n",
2009 ts, cert->not_before, cert->not_after);
2010 return certificate_expired;
2012 DEBUG_PRINT("Valid certificate, now: %s (validity: %s - %s)\n",
2013 ts, cert->not_before,
2019 void tls_certificate_set_copy(unsigned char **member,
2020 const unsigned char *val, int len) {
2028 *member = malloc(len + 1);
2030 memcpy(*member, val, len);
2038 void tls_certificate_set_copy_date(unsigned char *member,
2039 const unsigned char *val, int len) {
2042 if (val[0] >= '5') {
2049 memcpy(member + 2, val, len);
2056 void tls_certificate_set_key(struct TLSCertificate *cert,
2057 const unsigned char *val, int len) {
2058 if (!val[0] && len % 2) {
2062 tls_certificate_set_copy(&cert->pk, val, len);
2068 void tls_certificate_set_priv(struct TLSCertificate *cert,
2069 const unsigned char *val, int len) {
2070 tls_certificate_set_copy(&cert->priv, val, len);
2072 cert->priv_len = len;
2076 void tls_certificate_set_sign_key(struct TLSCertificate *cert,
2077 const unsigned char *val, int len) {
2078 if (!val[0] && len % 2) {
2082 tls_certificate_set_copy(&cert->sign_key, val, len);
2083 if (cert->sign_key) {
2084 cert->sign_len = len;
2088 void tls_certificate_set_exponent(struct TLSCertificate *cert,
2089 const unsigned char *val, int len) {
2090 tls_certificate_set_copy(&cert->exponent, val, len);
2091 if (cert->exponent) {
2092 cert->exponent_len = len;
2096 void tls_certificate_set_serial(struct TLSCertificate *cert,
2097 const unsigned char *val, int len) {
2098 tls_certificate_set_copy(&cert->serial_number, val, len);
2099 if (cert->serial_number) {
2100 cert->serial_len = len;
2104 void tls_certificate_set_algorithm(unsigned int *algorithm,
2105 const unsigned char *val, int len) {
2106 if (len == 7 && _is_oid(val, TLS_EC_PUBLIC_KEY_OID, 7)) {
2107 *algorithm = TLS_EC_PUBLIC_KEY;
2112 if (_is_oid(val, TLS_EC_prime192v1_OID, len)) {
2113 *algorithm = TLS_EC_prime192v1;
2116 if (_is_oid(val, TLS_EC_prime192v2_OID, len)) {
2117 *algorithm = TLS_EC_prime192v2;
2120 if (_is_oid(val, TLS_EC_prime192v3_OID, len)) {
2121 *algorithm = TLS_EC_prime192v3;
2124 if (_is_oid(val, TLS_EC_prime239v1_OID, len)) {
2125 *algorithm = TLS_EC_prime239v1;
2128 if (_is_oid(val, TLS_EC_prime239v2_OID, len)) {
2129 *algorithm = TLS_EC_prime239v2;
2132 if (_is_oid(val, TLS_EC_prime239v3_OID, len)) {
2133 *algorithm = TLS_EC_prime239v3;
2136 if (_is_oid(val, TLS_EC_prime256v1_OID, len)) {
2137 *algorithm = TLS_EC_prime256v1;
2143 (val, TLS_EC_secp224r1_OID, len,
2144 sizeof(TLS_EC_secp224r1_OID) - 1)) {
2145 *algorithm = TLS_EC_secp224r1;
2149 (val, TLS_EC_secp384r1_OID, len,
2150 sizeof(TLS_EC_secp384r1_OID) - 1)) {
2151 *algorithm = TLS_EC_secp384r1;
2155 (val, TLS_EC_secp521r1_OID, len,
2156 sizeof(TLS_EC_secp521r1_OID) - 1)) {
2157 *algorithm = TLS_EC_secp521r1;
2165 if (_is_oid(val, TLS_RSA_SIGN_SHA256_OID, 9)) {
2166 *algorithm = TLS_RSA_SIGN_SHA256;
2170 if (_is_oid(val, TLS_RSA_SIGN_RSA_OID, 9)) {
2171 *algorithm = TLS_RSA_SIGN_RSA;
2175 if (_is_oid(val, TLS_RSA_SIGN_SHA1_OID, 9)) {
2176 *algorithm = TLS_RSA_SIGN_SHA1;
2180 if (_is_oid(val, TLS_RSA_SIGN_SHA512_OID, 9)) {
2181 *algorithm = TLS_RSA_SIGN_SHA512;
2185 if (_is_oid(val, TLS_RSA_SIGN_SHA384_OID, 9)) {
2186 *algorithm = TLS_RSA_SIGN_SHA384;
2190 if (_is_oid(val, TLS_RSA_SIGN_MD5_OID, 9)) {
2191 *algorithm = TLS_RSA_SIGN_MD5;
2196 void tls_destroy_certificate(struct TLSCertificate *cert) {
2199 free(cert->exponent);
2201 free(cert->issuer_country);
2202 free(cert->issuer_state);
2203 free(cert->issuer_location);
2204 free(cert->issuer_entity);
2205 free(cert->issuer_subject);
2206 free(cert->country);
2208 free(cert->location);
2209 free(cert->subject);
2210 for (i = 0; i < cert->san_length; i++) {
2215 free(cert->serial_number);
2217 cert->not_before[0] = 0;
2218 cert->not_after[0] = 0;
2219 free(cert->sign_key);
2221 free(cert->der_bytes);
2223 free(cert->fingerprint);
2228 struct TLSPacket *tls_create_packet(struct TLSContext *context,
2230 unsigned short version,
2231 int payload_size_hint) {
2232 struct TLSPacket *packet = malloc(sizeof *packet);
2237 if (payload_size_hint > 0) {
2238 packet->size = payload_size_hint + 10;
2240 packet->size = TLS_BLOB_INCREMENT;
2242 packet->buf = malloc(packet->size);
2243 memset(packet->buf, 0, packet->size);
2244 packet->context = context;
2250 packet->payload_pos = 6;
2251 packet->len = packet->payload_pos - 1;
2255 packet->buf[0] = type;
2257 /* big endian protocol version */
2258 packet->buf[1] = version >> 8;
2259 packet->buf[2] = version & 0xff;
2260 if (version == TLS_V13) {
2261 packet->buf[2] = 0x04;
2267 void tls_destroy_packet(struct TLSPacket *packet) {
2276 int tls_crypto_create(struct TLSContext *context, int key_length,
2277 unsigned char *localkey,
2278 unsigned char *localiv,
2279 unsigned char *remotekey,
2280 unsigned char *remoteiv) {
2281 if (context->crypto.created) {
2282 if (context->crypto.created == 1) {
2283 cbc_done(&context->crypto.ctx_remote.aes_remote);
2284 cbc_done(&context->crypto.ctx_local.aes_local);
2286 if (context->crypto.created == 2) {
2287 unsigned char dummy_buffer[32];
2288 unsigned long tag_len = 0;
2289 gcm_done(&context->crypto.ctx_remote.
2290 aes_gcm_remote, dummy_buffer,
2292 gcm_done(&context->crypto.ctx_local.
2293 aes_gcm_local, dummy_buffer,
2297 context->crypto.created = 0;
2299 int is_aead = tls_is_aead(context);
2300 int cipherID = find_cipher("aes");
2301 DEBUG_PRINT("Using cipher ID: %x\n", (int) context->cipher);
2303 unsigned int counter = 1;
2305 chacha_keysetup(&context->crypto.ctx_local.chacha_local,
2306 localkey, key_length * 8);
2307 chacha_ivsetup_96bitnonce(&context->crypto.ctx_local.
2308 chacha_local, localiv,
2309 (unsigned char *) &counter);
2311 chacha_keysetup(&context->crypto.ctx_remote.chacha_remote,
2312 remotekey, key_length * 8);
2313 chacha_ivsetup_96bitnonce(&context->crypto.ctx_remote.
2314 chacha_remote, remoteiv,
2315 (unsigned char *) &counter);
2317 context->crypto.created = 3;
2321 gcm_init(&context->crypto.ctx_local.aes_gcm_local,
2322 cipherID, localkey, key_length);
2324 gcm_init(&context->crypto.ctx_remote.aes_gcm_remote,
2325 cipherID, remotekey, key_length);
2328 return TLS_GENERIC_ERROR;
2330 context->crypto.created = 2;
2333 cbc_start(cipherID, localiv, localkey, key_length, 0,
2334 &context->crypto.ctx_local.aes_local);
2336 cbc_start(cipherID, remoteiv, remotekey, key_length, 0,
2337 &context->crypto.ctx_remote.aes_remote);
2340 return TLS_GENERIC_ERROR;
2342 context->crypto.created = 1;
2348 static void tls_crypto_done(struct TLSContext *context) {
2349 unsigned char dummy_buffer[32];
2350 unsigned long tag_len = 0;
2352 switch (context->crypto.created) {
2354 cbc_done(&context->crypto.ctx_remote.aes_remote);
2355 cbc_done(&context->crypto.ctx_local.aes_local);
2358 gcm_done(&context->crypto.ctx_remote.aes_gcm_remote,
2359 dummy_buffer, &tag_len);
2360 gcm_done(&context->crypto.ctx_local.aes_gcm_local,
2361 dummy_buffer, &tag_len);
2364 context->crypto.created = 0;
2367 int tls_packet_append(struct TLSPacket *packet, const unsigned char *buf,
2371 if (!packet || packet->broken) {
2379 unsigned int new_len = packet->len + len;
2381 if (new_len > packet->size) {
2382 packet->size = (new_len / TLS_BLOB_INCREMENT + 1) *
2384 new = TLS_REALLOC(packet->buf, packet->size);
2395 memcpy(packet->buf + packet->len, buf, len);
2396 packet->len = new_len;
2400 int tls_packet_uint8(struct TLSPacket *packet, unsigned char i) {
2401 return tls_packet_append(packet, &i, 1);
2404 int tls_packet_uint16(struct TLSPacket *packet, unsigned short i) {
2405 unsigned short ni = htons(i);
2406 return tls_packet_append(packet, (unsigned char *) &ni, 2);
2409 int tls_packet_uint32(struct TLSPacket *packet, unsigned int i) {
2410 unsigned int ni = htonl(i);
2411 return tls_packet_append(packet, (unsigned char *) &ni, 4);
2414 int tls_packet_uint24(struct TLSPacket *packet, unsigned int i) {
2415 unsigned char buf[3];
2416 buf[0] = (i >> 16) & 0xff;
2417 buf[1] = (i >> 8) & 0xff;
2418 buf[2] = (i >> 0) & 0xff;
2420 return tls_packet_append(packet, buf, 3);
2423 int tls_random(unsigned char *key, int len) {
2425 for (int i = 0; i < len; i++) {
2426 unsigned int v = arc4random() % 0x100;
2431 /* TODO use open and read */
2432 FILE *fp = fopen("/dev/urandom", "r");
2434 int key_len = fread(key, 1, len, fp);
2443 int tls_established(struct TLSContext *context) {
2445 if (context->critical_error) {
2449 if (context->connection_status == TLS_CONNECTED) {
2456 void tls_read_clear(struct TLSContext *context) {
2458 tls_buffer_free(&context->application_buffer);
2462 struct TLSContext *tls_create_context(int is_server, unsigned short version) {
2463 struct TLSContext zero = {0};
2465 struct TLSContext *context = 0;
2467 if (version == TLS_V13 && !is_server) {
2468 /* TLS 1.3 clients not supported */
2476 context = malloc(sizeof *context);
2482 ver = version - 0x0201;
2486 context->is_server = is_server;
2487 context->version = version;
2488 context->tlsver = ver;
2489 context->hs_index = -1;
2490 /* set up output buffer */
2491 tls_buffer_init(&context->output_buffer, 0);
2492 tls_buffer_init(&context->input_buffer, 0);
2493 tls_buffer_init(&context->cached_handshake, 0);
2494 tls_buffer_init(&context->application_buffer, 0);
2499 struct TLSContext *tls_accept(struct TLSContext *context) {
2500 if (!context || !context->is_server) {
2504 struct TLSContext *child = malloc(sizeof *child);
2506 memset(child, 0, sizeof(struct TLSContext));
2507 child->is_server = 1;
2508 child->is_child = 1;
2509 child->version = context->version;
2510 child->certificates = context->certificates;
2511 child->certificates_count = context->certificates_count;
2512 child->private_key = context->private_key;
2513 child->ec_private_key = context->ec_private_key;
2514 child->root_certificates = context->root_certificates;
2515 child->root_count = context->root_count;
2516 child->default_dhe_p = context->default_dhe_p;
2517 child->default_dhe_g = context->default_dhe_g;
2518 child->curve = context->curve;
2519 child->alpn = context->alpn;
2520 child->alpn_count = context->alpn_count;
2525 int tls_add_alpn(struct TLSContext *context, const char *alpn) {
2528 if (!context || !alpn || !alpn[0]
2529 || (context->is_server && context->is_child)) {
2530 return TLS_GENERIC_ERROR;
2533 int len = strlen(alpn);
2534 if (tls_alpn_contains(context, alpn, len)) {
2538 new = TLS_REALLOC(context->alpn, (context->alpn_count + 1) *
2541 context->alpn = new;
2543 free(context->alpn);
2545 context->alpn_count = 0;
2546 return TLS_NO_MEMORY;
2548 char *alpn_ref = malloc(len + 1);
2549 context->alpn[context->alpn_count] = alpn_ref;
2551 memcpy(alpn_ref, alpn, len);
2553 context->alpn_count++;
2555 return TLS_NO_MEMORY;
2560 int tls_alpn_contains(struct TLSContext *context, const char *alpn,
2561 unsigned char alpn_size) {
2564 if (!context || !alpn || !alpn_size || !context->alpn) {
2568 for (i = 0; i < context->alpn_count; i++) {
2569 const char *alpn_local = context->alpn[i];
2571 int len = strlen(alpn_local);
2572 if (alpn_size == len) {
2573 if (!memcmp(alpn_local, alpn, alpn_size)) {
2583 void tls_destroy_context(struct TLSContext *context) {
2590 if (!context->is_child) {
2591 if (context->certificates) {
2592 for (i = 0; i < context->certificates_count; i++) {
2593 tls_destroy_certificate(context->
2597 if (context->root_certificates) {
2598 for (i = 0; i < context->root_count; i++) {
2599 tls_destroy_certificate(context->
2600 root_certificates[i]);
2602 free(context->root_certificates);
2603 context->root_certificates = NULL;
2605 if (context->private_key) {
2606 tls_destroy_certificate(context->private_key);
2608 if (context->ec_private_key) {
2609 tls_destroy_certificate(context->ec_private_key);
2611 free(context->certificates);
2612 free(context->default_dhe_p);
2613 free(context->default_dhe_g);
2614 if (context->alpn) {
2615 for (i = 0; i < context->alpn_count; i++) {
2616 free(context->alpn[i]);
2618 free(context->alpn);
2622 if (context->client_certificates) {
2623 for (i = 0; i < context->client_certificates_count; i++) {
2624 tls_destroy_certificate(context->
2625 client_certificates[i]);
2627 free(context->client_certificates);
2630 context->client_certificates = NULL;
2631 free(context->master_key);
2632 free(context->premaster_key);
2634 if (context->crypto.created) {
2635 tls_crypto_done(context);
2638 tls_done_hash(context, NULL);
2639 tls_destroy_hash(context);
2641 tls_buffer_free(&context->output_buffer);
2642 tls_buffer_free(&context->input_buffer);
2643 tls_buffer_free(&context->application_buffer);
2644 tls_buffer_free(&context->cached_handshake);
2645 //free(context->cached_handshake);
2648 tls_dhe_free(context);
2649 tls_ecc_dhe_free(context);
2650 free(context->negotiated_alpn);
2651 free(context->finished_key);
2652 free(context->remote_finished_key);
2653 free(context->server_finished_hash);
2657 int tls_cipher_is_ephemeral(struct TLSContext *context) {
2662 switch (context->cipher) {
2663 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
2664 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
2665 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
2666 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
2667 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
2668 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
2669 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
2671 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
2672 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
2673 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
2674 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
2675 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
2676 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
2677 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
2678 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
2679 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
2680 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
2681 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
2682 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
2683 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
2685 case TLS_AES_128_GCM_SHA256:
2686 case TLS_CHACHA20_POLY1305_SHA256:
2687 case TLS_AES_128_CCM_SHA256:
2688 case TLS_AES_128_CCM_8_SHA256:
2689 case TLS_AES_256_GCM_SHA384:
2698 int tls_is_ecdsa(struct TLSContext *context) {
2703 switch (context->cipher) {
2704 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
2705 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
2706 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
2707 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
2708 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
2709 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
2710 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
2714 if (context->ec_private_key) {
2721 static void tls_send_server_key_exchange(struct TLSContext *context,
2723 if (!context->is_server) {
2725 ("CANNOT BUILD SERVER KEY EXCHANGE MESSAGE FOR CLIENTS\n");
2729 struct TLSPacket *packet =
2730 tls_create_packet(context, TLS_HANDSHAKE, context->version, 0);
2731 tls_packet_uint8(packet, 0x0C);
2732 unsigned char dummy[3];
2733 tls_packet_append(packet, dummy, 3);
2734 int start_len = packet->len;
2736 if (method == KEA_dhe_rsa) {
2737 tls_dhe_create(context);
2739 const char *default_dhe_p = context->default_dhe_p;
2740 const char *default_dhe_g = context->default_dhe_g;
2742 if (!default_dhe_p || !default_dhe_g) {
2743 default_dhe_p = TLS_DH_DEFAULT_P;
2744 default_dhe_g = TLS_DH_DEFAULT_G;
2745 key_size = TLS_DHE_KEY_SIZE / 8;
2747 key_size = strlen(default_dhe_p);
2749 if (tls_dh_make_key(key_size, context->dhe, default_dhe_p,
2750 default_dhe_g, 0, 0)) {
2751 DEBUG_PRINT("ERROR CREATING DHE KEY\n");
2754 context->dhe = NULL;
2755 /* TODO set error */
2759 unsigned char dh_Ys[0xFFF];
2760 unsigned char dh_p[0xFFF];
2761 unsigned char dh_g[0xFFF];
2762 unsigned long dh_p_len = sizeof(dh_p);
2763 unsigned long dh_g_len = sizeof(dh_g);
2764 unsigned long dh_Ys_len = sizeof(dh_Ys);
2766 if (tls_dh_export_pqY
2767 (dh_p, &dh_p_len, dh_g, &dh_g_len, dh_Ys, &dh_Ys_len,
2769 DEBUG_PRINT("ERROR EXPORTING DHE KEY\n");
2771 /* TODO set error */
2775 DEBUG_PRINT("LEN: %lu (%lu, %lu)\n", dh_Ys_len, dh_p_len,
2777 DEBUG_DUMP_HEX_LABEL("DHE PK", dh_Ys, dh_Ys_len);
2778 DEBUG_DUMP_HEX_LABEL("DHE P", dh_p, dh_p_len);
2779 DEBUG_DUMP_HEX_LABEL("DHE G", dh_g, dh_g_len);
2781 tls_packet_uint16(packet, dh_p_len);
2782 tls_packet_append(packet, dh_p, dh_p_len);
2784 tls_packet_uint16(packet, dh_g_len);
2785 tls_packet_append(packet, dh_g, dh_g_len);
2787 tls_packet_uint16(packet, dh_Ys_len);
2788 tls_packet_append(packet, dh_Ys, dh_Ys_len);
2792 } else if (method == KEA_ec_diffie_hellman) {
2793 /* 3 = named curve */
2794 if (!context->curve) {
2795 context->curve = tls_ecc_default_curve;
2797 tls_packet_uint8(packet, 3);
2798 tls_packet_uint16(packet, context->curve->iana);
2799 tls_ecc_dhe_create(context);
2801 ltc_ecc_set_type *dp =
2802 (ltc_ecc_set_type *) & context->curve->dp;
2804 if (ecc_make_key_ex(NULL, find_prng("sprng"), context->ecc_dhe,
2806 free(context->ecc_dhe);
2807 context->ecc_dhe = NULL;
2808 DEBUG_PRINT("Error generating ECC key\n");
2810 /* TODO set error */
2813 unsigned char out[TLS_MAX_RSA_KEY];
2814 unsigned long out_len = TLS_MAX_RSA_KEY;
2815 if (ecc_ansi_x963_export(context->ecc_dhe, out, &out_len)) {
2816 DEBUG_PRINT("Error exporting ECC key\n");
2821 tls_packet_uint8(packet, out_len);
2822 tls_packet_append(packet, out, out_len);
2826 DEBUG_PRINT("Unsupported ephemeral method: %i\n", method);
2831 unsigned int params_len = packet->len - start_len;
2832 unsigned int message_len =
2833 params_len + TLS_CLIENT_RANDOM_SIZE + TLS_SERVER_RANDOM_SIZE;
2834 unsigned char *message = malloc(message_len);
2836 unsigned char out[TLS_MAX_RSA_KEY];
2837 unsigned long out_len = TLS_MAX_RSA_KEY;
2841 hash_algorithm = sha256;
2843 if (tls_is_ecdsa(context)) {
2844 hash_algorithm = sha512;
2845 tls_packet_uint8(packet, hash_algorithm);
2846 tls_packet_uint8(packet, ecdsa);
2848 tls_packet_uint8(packet, hash_algorithm);
2849 tls_packet_uint8(packet, rsa_sign);
2852 memcpy(message, context->remote_random,
2853 TLS_CLIENT_RANDOM_SIZE);
2854 memcpy(message + TLS_CLIENT_RANDOM_SIZE, context->local_random,
2855 TLS_SERVER_RANDOM_SIZE);
2856 memcpy(message + TLS_CLIENT_RANDOM_SIZE +
2857 TLS_SERVER_RANDOM_SIZE, packet->buf +
2858 start_len, params_len);
2859 if (tls_is_ecdsa(context)) {
2860 if (sign_ecdsa(context, hash_algorithm, message,
2861 message_len, out, &out_len) ==
2864 ("Signing OK! (ECDSA, length %lu)\n",
2866 tls_packet_uint16(packet, out_len);
2867 tls_packet_append(packet, out, out_len);
2870 if (sign_rsa(context, hash_algorithm, message, message_len,
2871 out, &out_len) == 1) {
2872 DEBUG_PRINT("Signing OK! (length %lu)\n", out_len);
2873 tls_packet_uint16(packet, out_len);
2874 tls_packet_append(packet, out, out_len);
2878 if (!packet->broken && packet->buf) {
2879 tls_set_packet_length(packet, packet->len - start_len);
2881 tls_packet_update(packet);
2882 tls_queue_packet(packet);
2887 void _private_tls_set_session_id(struct TLSContext *context) {
2888 if (context->tlsver == TLS_VERSION13
2889 && context->session_size == TLS_MAX_SESSION_ID) {
2893 if (tls_random(context->session, TLS_MAX_SESSION_ID)) {
2894 context->session_size = TLS_MAX_SESSION_ID;
2896 context->session_size = 0;
2901 struct TLSPacket *tls_certificate_request(struct TLSContext *context) {
2902 if (!context || !context->is_server) {
2906 unsigned short packet_version = context->version;
2907 struct TLSPacket *packet =
2908 tls_create_packet(context, TLS_HANDSHAKE, packet_version, 0);
2914 /* cert request and size placeholder */
2915 unsigned char dummy[] = { 0x0d, 0, 0, 0 };
2916 tls_packet_append(packet, dummy, sizeof dummy);
2918 int start_len = packet->len;
2920 if (context->tlsver == TLS_VERSION13) {
2921 /* certificate request context */
2922 tls_packet_uint8(packet, 0);
2924 tls_packet_uint16(packet, 18);
2925 /* signature algorithms */
2926 tls_packet_uint16(packet, 0x0D);
2927 tls_packet_uint16(packet, 14);
2928 tls_packet_uint16(packet, 12);
2931 tls_packet_uint16(packet, 0x0401);
2933 tls_packet_uint16(packet, 0x0501);
2935 tls_packet_uint16(packet, 0x0601);
2938 /* ecdsa_secp256r1_sha256 */
2939 tls_packet_uint16(packet, 0x0403);
2940 /* ecdsa_secp384r1_sha384 */
2941 tls_packet_uint16(packet, 0x0503);
2942 /* ecdsa_secp521r1_sha512 */
2943 tls_packet_uint16(packet, 0x0604);
2944 /* rsa_pss_rsae_sha256 */
2945 tls_packet_uint16(packet, 0x0804);
2946 /* rsa_pss_rsae_sha384 */
2947 tls_packet_uint16(packet, 0x0805);
2948 /* rsa_pss_rsae_sha512 */
2949 tls_packet_uint16(packet, 0x0806);
2951 tls_packet_uint8(packet, 1);
2952 tls_packet_uint8(packet, rsa_sign);
2953 if (context->version == TLS_V12) {
2954 /* 10 pairs or 2 bytes */
2955 tls_packet_uint16(packet, 10);
2956 tls_packet_uint8(packet, sha256);
2957 tls_packet_uint8(packet, rsa);
2958 tls_packet_uint8(packet, sha1);
2959 tls_packet_uint8(packet, rsa);
2960 tls_packet_uint8(packet, sha384);
2961 tls_packet_uint8(packet, rsa);
2962 tls_packet_uint8(packet, sha512);
2963 tls_packet_uint8(packet, rsa);
2964 tls_packet_uint8(packet, md5);
2965 tls_packet_uint8(packet, rsa);
2967 /* no DistinguishedName yet */
2968 tls_packet_uint16(packet, 0);
2970 if (!packet->broken) {
2971 tls_set_packet_length(packet, packet->len - start_len);
2973 tls_packet_update(packet);
2977 int tls_parse_key_share(struct TLSContext *context, const unsigned char *buf,
2980 struct ECCCurveParameters *curve = 0;
2981 struct DHKey *dhkey = 0;
2982 int dhe_key_size = 0;
2983 const unsigned char *buffer = NULL;
2984 unsigned char *out2;
2985 unsigned long out_size;
2988 while (buf_len >= 4) {
2989 uint16_t named_group = get16(&buf[i]);
2993 key_size = get16(&buf[i]);
2997 if (key_size > buf_len) {
2998 return TLS_BROKEN_PACKET;
3001 switch (named_group) {
3005 DEBUG_PRINT("KEY SHARE => secp256r1\n");
3012 DEBUG_PRINT("KEY SHARE => secp384r1\n");
3020 if (key_size != 32) {
3022 ("INVALID x25519 KEY SIZE (%i)\n",
3026 curve = &curve25519;
3028 DEBUG_PRINT("KEY SHARE => x25519\n");
3038 dhe_key_size = 2048;
3042 dhe_key_size = 3072;
3046 dhe_key_size = 4096;
3050 dhe_key_size = 6144;
3054 dhe_key_size = 8192;
3058 buf_len -= key_size;
3062 context->curve = curve;
3064 if (curve == &curve25519) {
3065 if (!tls_random(context->local_random,
3066 TLS_SERVER_RANDOM_SIZE)) {
3067 return TLS_GENERIC_ERROR;
3070 unsigned char secret[32];
3071 static const unsigned char basepoint[32] = { 9 };
3073 tls_random(secret, 32);
3079 /* use finished key to store public key */
3080 free(context->finished_key);
3081 context->finished_key = malloc(32);
3082 if (!context->finished_key) {
3083 return TLS_GENERIC_ERROR;
3086 x25519(context->finished_key, secret, basepoint);
3088 free(context->premaster_key);
3089 context->premaster_key = malloc(32);
3091 if (!context->premaster_key) {
3092 return TLS_GENERIC_ERROR;
3095 x25519(context->premaster_key, secret, buffer);
3096 context->premaster_key_len = 32;
3101 tls_ecc_dhe_create(context);
3102 ltc_ecc_set_type *dp = (ltc_ecc_set_type *)&context->curve->dp;
3104 if (ecc_make_key_ex(NULL, find_prng("sprng"), context->ecc_dhe,
3106 free(context->ecc_dhe);
3107 context->ecc_dhe = NULL;
3108 DEBUG_PRINT("Error generating ECC DHE key\n");
3109 return TLS_GENERIC_ERROR;
3112 if (!tls_random(context->local_random, TLS_SERVER_RANDOM_SIZE)) {
3113 return TLS_GENERIC_ERROR;
3117 memset(&client_key, 0, sizeof client_key);
3118 if (ecc_ansi_x963_import_ex
3119 (buffer, key_size, &client_key, dp)) {
3120 DEBUG_PRINT("Error importing ECC DHE key\n");
3121 return TLS_GENERIC_ERROR;
3123 out2 = malloc(key_size);
3124 out_size = key_size;
3126 int err = ecc_shared_secret(context->ecc_dhe, &client_key,
3128 ecc_free(&client_key);
3131 DEBUG_PRINT("ECC DHE DECRYPT ERROR %i\n", err);
3133 return TLS_GENERIC_ERROR;
3136 DEBUG_PRINT("OUT_SIZE: %lu\n", out_size);
3137 DEBUG_DUMP_HEX_LABEL("ECC DHE", out2, out_size);
3139 free(context->premaster_key);
3140 context->premaster_key = out2;
3141 context->premaster_key_len = out_size;
3144 tls_dhe_create(context);
3145 if (!tls_random(context->local_random, TLS_SERVER_RANDOM_SIZE))
3147 return TLS_GENERIC_ERROR;
3150 if (tls_dh_make_key(dhe_key_size / 8, context->dhe,
3151 (const char *)dhkey->p, (const char *)dhkey->g, 0, 0)) {
3153 context->dhe = NULL;
3154 DEBUG_PRINT("Error generating DHE key\n");
3155 return TLS_GENERIC_ERROR;
3158 unsigned int dhe_out_size;
3159 out2 = tls_decrypt_dhe(context, buffer, key_size,
3162 DEBUG_PRINT("Error generating DHE shared key\n");
3163 return TLS_GENERIC_ERROR;
3166 free(context->premaster_key);
3167 context->premaster_key = out2;
3168 context->premaster_key_len = dhe_out_size;
3170 context->dhe->iana = dhkey->iana;
3174 DEBUG_PRINT("NO COMMON KEY SHARE SUPPORTED\n");
3175 return TLS_NO_COMMON_CIPHER;
3178 int tls_parse_certificate(struct TLSContext *context,
3179 const unsigned char *buf, int buf_len,
3183 return TLS_NEED_MORE_DATA;
3186 int size = get24(buf);
3188 /* not enough data, so just consume all of it */
3193 res += 3; /* skip over the size field */
3195 if (context->tlsver == TLS_VERSION13) {
3196 int context_size = buf[res];
3200 res += context_size;
3204 if (buf_len - res < size) {
3205 return TLS_NEED_MORE_DATA;
3209 int valid_certificate = 0;
3212 if (buf_len - res < 3) {
3213 return TLS_NEED_MORE_DATA;
3215 int certificate_size = get24(buf+res);
3217 if (buf_len - res < certificate_size) {
3218 return TLS_NEED_MORE_DATA;
3221 int certificates_in_chain = 0;
3223 unsigned int remaining = certificate_size;
3225 if (remaining <= 3) {
3228 certificates_in_chain++;
3229 unsigned int certificate_size2 = get24(buf+res2);
3232 if (certificate_size2 > remaining) {
3234 ("Invalid certificate size (%i from %i bytes remaining)\n",
3235 certificate_size2, remaining);
3238 remaining -= certificate_size2;
3240 struct TLSCertificate *cert = asn1_parse(context,
3246 if (certificate_size2) {
3248 malloc(certificate_size2);
3257 /* valid certificate */
3260 valid_certificate = 1;
3263 TLS_REALLOC(context->
3264 client_certificates,
3266 client_certificates_count
3275 client_certificates);
3277 client_certificates =
3279 return TLS_NO_MEMORY;
3282 context->client_certificates = new;
3285 [context->client_certificates_count]
3288 client_certificates_count++;
3292 TLS_REALLOC(context->
3304 context->certificates = 0;
3305 return TLS_NO_MEMORY;
3307 context->certificates = new;
3308 context->certificates[context->
3311 context->certificates_count++;
3312 if ((cert->pk) || (cert->priv))
3313 valid_certificate = 1;
3314 else if (!context->is_server)
3315 valid_certificate = 1;
3318 res2 += certificate_size2;
3320 if (context->tlsver == TLS_VERSION13) {
3321 if (remaining >= 2) {
3322 /* ignore extensions */
3324 uint16_t size = get16(&buf[res2]);
3325 if (size && size >= remaining) {
3331 } while (remaining > 0);
3333 DEBUG_PRINT("Extra %i bytes after certificate\n",
3336 size -= certificate_size + 3;
3337 res += certificate_size;
3339 if (!valid_certificate) {
3340 return TLS_UNSUPPORTED_CERTIFICATE;
3342 if (res != buf_len) {
3343 DEBUG_PRINT("Warning: %i bytes read from %i byte buffer\n",
3344 (int) res, (int) buf_len);
3349 static int parse_dh( const unsigned char *buf, int buf_len, const unsigned char
3350 **out, int *out_size) {
3355 return TLS_NEED_MORE_DATA;
3357 uint16_t size = get16(buf);
3359 if (buf_len - res < size) {
3360 return TLS_NEED_MORE_DATA;
3362 DEBUG_DUMP_HEX(&buf[res], size);
3369 static int tls_parse_random(struct TLSContext *context,
3370 const unsigned char *buf, int buf_len) {
3372 int ephemeral = tls_cipher_is_ephemeral(context);
3374 if (ephemeral == 2) {
3376 return TLS_NEED_MORE_DATA;
3382 return TLS_NEED_MORE_DATA;
3388 if (buf_len - res < size) {
3389 return TLS_NEED_MORE_DATA;
3391 unsigned int out_len = 0;
3392 unsigned char *random = NULL;
3393 switch (ephemeral) {
3395 random = tls_decrypt_dhe(context, &buf[res], size, &out_len,
3399 random = tls_decrypt_ecc_dhe(context, &buf[res], size,
3403 random = decrypt_rsa(context, &buf[res], size,
3407 if (random && out_len > 2) {
3408 /* *(unsigned short *)&random[0] = htons(context->version); */
3409 DEBUG_DUMP_HEX_LABEL("PRE MASTER KEY", random, out_len);
3410 free(context->premaster_key);
3411 context->premaster_key = random;
3412 context->premaster_key_len = out_len;
3413 tls_compute_key(context, 48);
3422 static const unsigned char *parse_signature(const unsigned char *buf, int
3423 buf_len, int *hash_algorithm, int *sign_algorithm, int
3424 *sig_size, int *offset) {
3429 *hash_algorithm = _md5_sha1;
3430 *sign_algorithm = rsa_sign;
3432 *hash_algorithm = buf[res];
3434 *sign_algorithm = buf[res];
3436 uint16_t size = get16(&buf[res]);
3438 if (buf_len - res < size) {
3441 DEBUG_DUMP_HEX(&buf[res], size);
3443 *offset = res + size;
3447 int tls_parse_server_key_exchange(struct TLSContext *context,
3448 const unsigned char *buf, int buf_len) {
3452 return TLS_NEED_MORE_DATA;
3454 int size = get24(buf);
3456 const unsigned char *packet_ref = buf + res;
3457 if (buf_len - res < size) {
3458 return TLS_NEED_MORE_DATA;
3465 unsigned char has_ds_params = 0;
3467 const struct ECCCurveParameters *curve = NULL;
3468 const unsigned char *pk_key = NULL;
3469 int ephemeral = tls_cipher_is_ephemeral(context);
3471 if (ephemeral == 1) {
3474 if (buf[res++] != 3) {
3476 /* any other method is not supported */
3479 if (buf_len - res < 3) {
3480 return TLS_NEED_MORE_DATA;
3482 int iana_n = get16(&buf[res]);
3484 key_size = buf[res];
3486 if (buf_len - res < key_size) {
3487 return TLS_NEED_MORE_DATA;
3489 DEBUG_PRINT("IANA CURVE NUMBER: %i\n", iana_n);
3513 DEBUG_PRINT("UNSUPPORTED CURVE\n");
3514 return TLS_GENERIC_ERROR;
3518 context->curve = curve;
3522 const unsigned char *dh_p = NULL;
3524 const unsigned char *dh_g = NULL;
3526 const unsigned char *dh_Ys = NULL;
3529 if (has_ds_params) {
3530 DEBUG_PRINT(" dh_p: ");
3531 dh_res = parse_dh(&buf[res], buf_len - res, &dh_p, &dh_p_len);
3533 return TLS_BROKEN_PACKET;
3538 DEBUG_PRINT(" dh_q: ");
3539 dh_res = parse_dh(&buf[res], buf_len - res, &dh_g, &dh_g_len);
3541 return TLS_BROKEN_PACKET;
3546 DEBUG_PRINT(" dh_Ys: ");
3547 dh_res = parse_dh(&buf[res], buf_len - res, &dh_Ys,
3550 return TLS_BROKEN_PACKET;
3558 int packet_size = res - 3;
3560 DEBUG_PRINT(" SIGNATURE (%i/%i/%i): ", packet_size,
3562 const unsigned char *signature =
3563 parse_signature(&buf[res], buf_len - res, &hash_algorithm,
3564 &sign_algorithm, &sign_size, &offset);
3566 if (sign_size <= 0 || !signature) {
3567 return TLS_BROKEN_PACKET;
3570 /* check signature */
3571 unsigned int message_len =
3572 packet_size + TLS_CLIENT_RANDOM_SIZE + TLS_SERVER_RANDOM_SIZE;
3573 unsigned char *message = malloc(message_len);
3575 memcpy(message, context->local_random, TLS_CLIENT_RANDOM_SIZE);
3576 memcpy(message + TLS_CLIENT_RANDOM_SIZE,
3577 context->remote_random, TLS_SERVER_RANDOM_SIZE);
3578 memcpy(message + TLS_CLIENT_RANDOM_SIZE +
3579 TLS_SERVER_RANDOM_SIZE, packet_ref, packet_size);
3580 if (tls_is_ecdsa(context)) {
3581 if (tls_verify_ecdsa
3582 (context, hash_algorithm, signature, sign_size,
3583 message, message_len, NULL) != 1) {
3585 ("ECC Server signature FAILED!\n");
3587 return TLS_BROKEN_PACKET;
3591 if (verify_rsa(context, hash_algorithm, signature,
3593 message_len) != 1) {
3594 DEBUG_PRINT("Server signature FAILED!\n");
3596 return TLS_BROKEN_PACKET;
3602 if (buf_len - res) {
3603 DEBUG_PRINT("EXTRA %i BYTES AT THE END OF MESSAGE\n",
3605 DEBUG_DUMP_HEX(&buf[res], buf_len - res);
3609 if (ephemeral == 1) {
3610 tls_dhe_create(context);
3611 DEBUG_DUMP_HEX_LABEL("DHP", dh_p, dh_p_len);
3612 DEBUG_DUMP_HEX_LABEL("DHG", dh_g, dh_g_len);
3613 int dhe_key_size = dh_p_len;
3614 if (dh_g_len > dh_p_len) {
3615 dhe_key_size = dh_g_len;
3618 if (tls_dh_make_key(dhe_key_size, context->dhe, (const char *)
3619 dh_p, (const char *) dh_g, dh_p_len,
3621 DEBUG_PRINT("ERROR CREATING DHE KEY\n");
3623 context->dhe = NULL;
3624 return TLS_GENERIC_ERROR;
3627 unsigned int dh_key_size = 0;
3628 unsigned char *key = tls_decrypt_dhe(context, dh_Ys, dh_Ys_len,
3630 DEBUG_DUMP_HEX_LABEL("DH COMMON SECRET", key, dh_key_size);
3631 if (key && dh_key_size) {
3632 free(context->premaster_key);
3633 context->premaster_key = key;
3634 context->premaster_key_len = dh_key_size;
3636 } else if (ephemeral == 2 && curve && pk_key && key_size) {
3637 tls_ecc_dhe_create(context);
3639 ltc_ecc_set_type *dp = (ltc_ecc_set_type *) & curve->dp;
3641 (NULL, find_prng("sprng"), context->ecc_dhe, dp)) {
3642 free(context->ecc_dhe);
3643 context->ecc_dhe = NULL;
3644 DEBUG_PRINT("Error generating ECC key\n");
3645 return TLS_GENERIC_ERROR;
3648 free(context->premaster_key);
3649 context->premaster_key_len = 0;
3651 unsigned int out_len = 0;
3652 context->premaster_key =
3653 tls_decrypt_ecc_dhe(context, pk_key, key_size,
3655 if (context->premaster_key) {
3656 context->premaster_key_len = out_len;
3663 int tls_parse_client_key_exchange(struct TLSContext *context,
3664 const unsigned char *buf, int buf_len) {
3665 if (context->connection_status != 1) {
3667 ("UNEXPECTED CLIENT KEY EXCHANGE MESSAGE (connections status: %i)\n",
3668 (int) context->connection_status);
3669 return TLS_UNEXPECTED_MESSAGE;
3675 return TLS_NEED_MORE_DATA;
3677 int size = get24(buf);
3680 if (buf_len - res < size) {
3681 return TLS_NEED_MORE_DATA;
3688 dh_res = tls_parse_random(context, &buf[res], size);
3690 DEBUG_PRINT("broken key\n");
3691 return TLS_BROKEN_PACKET;
3696 context->connection_status = 2;
3700 static int tls_parse_server_hello_done(const unsigned char *buf, int buf_len) {
3703 return TLS_NEED_MORE_DATA;
3705 int size = get24(buf);
3708 if (buf_len - res < size) {
3709 return TLS_NEED_MORE_DATA;
3716 int tls_parse_finished(struct TLSContext *context,
3717 const unsigned char *buf, int buf_len,
3718 unsigned int *write_packets) {
3719 if (context->connection_status < 2
3720 || context->connection_status == TLS_CONNECTED) {
3721 DEBUG_PRINT("UNEXPECTED FINISHED MESSAGE\n");
3722 return TLS_UNEXPECTED_MESSAGE;
3728 return TLS_NEED_MORE_DATA;
3730 int size = get24(buf);
3733 if (size < TLS_MIN_FINISHED_OPAQUE_LEN) {
3734 DEBUG_PRINT("Invalid finished packet size: %i\n", size);
3735 return TLS_BROKEN_PACKET;
3738 if (buf_len - res < size) {
3739 return TLS_NEED_MORE_DATA;
3742 unsigned char hash[TLS_MAX_SHA_SIZE];
3743 unsigned int hash_len = tls_get_hash(context, hash);
3745 if (context->tlsver == TLS_VERSION13) {
3746 unsigned char hash_out[TLS_MAX_SHA_SIZE];
3747 unsigned long out_size = TLS_MAX_SHA_SIZE;
3748 if (!context->remote_finished_key || !hash_len) {
3750 ("NO FINISHED KEY COMPUTED OR NO HANDSHAKE HASH\n");
3751 return TLS_NOT_VERIFIED;
3754 DEBUG_DUMP_HEX_LABEL("HS HASH", hash, hash_len);
3755 DEBUG_DUMP_HEX_LABEL("HS FINISH", context->remote_finished_key,
3758 out_size = hash_len;
3760 hmac_init(&hmac, tls_get_hash_idx(context),
3761 context->remote_finished_key, hash_len);
3762 hmac_process(&hmac, hash, hash_len);
3763 hmac_done(&hmac, hash_out, &out_size);
3765 if (size != (int)out_size || memcmp(hash_out, &buf[res], size)) {
3767 ("Finished validation error (sequence number, local: %i, remote: %i)\n",
3768 (int) context->local_sequence_number,
3769 (int) context->remote_sequence_number);
3770 DEBUG_DUMP_HEX_LABEL("FINISHED OPAQUE", &buf[res],
3772 DEBUG_DUMP_HEX_LABEL("VERIFY", hash_out, out_size);
3773 return TLS_NOT_VERIFIED;
3775 if (context->is_server) {
3776 context->connection_status = TLS_CONNECTED;
3778 _private_tls13_key(context, 0);
3779 context->local_sequence_number = 0;
3780 context->remote_sequence_number = 0;
3783 /* TODO client verify */
3786 unsigned char *out = malloc(size);
3788 DEBUG_PRINT("Error in malloc (%i bytes)\n",
3790 return TLS_NO_MEMORY;
3793 /* server verifies client's message */
3794 if (context->is_server) {
3795 tls_prf(context, out, size,
3796 context->master_key,
3797 context->master_key_len,
3799 "client finished", 15, hash,
3802 tls_prf(context, out, size,
3803 context->master_key,
3804 context->master_key_len,
3806 "server finished", 15, hash,
3810 if (memcmp(out, &buf[res], size)) {
3813 ("Finished validation error (sequence number, local: %i, remote: %i)\n",
3814 (int) context->local_sequence_number,
3815 (int) context->remote_sequence_number);
3816 DEBUG_DUMP_HEX_LABEL("FINISHED OPAQUE", &buf[res],
3818 DEBUG_DUMP_HEX_LABEL("VERIFY", out, size);
3819 return TLS_NOT_VERIFIED;
3824 if (context->is_server) {
3827 context->connection_status = TLS_CONNECTED;
3830 // fprintf(stderr, "set conn status = %d\n", context->connection_status);
3836 int tls_parse_verify_tls13(struct TLSContext *context,
3837 const unsigned char *buf, int buf_len) {
3839 return TLS_NEED_MORE_DATA;
3841 int size = get24(buf);
3847 unsigned char signing_data[TLS_MAX_HASH_SIZE + 98];
3848 int signing_data_len;
3850 /* first 64 bytes to 0x20 (32) */
3851 memset(signing_data, 0x20, 64);
3852 /* context string 33 bytes */
3853 if (context->is_server) {
3854 memcpy(signing_data + 64,
3855 "TLS 1.3, server CertificateVerify", 33);
3857 memcpy(signing_data + 64,
3858 "TLS 1.3, client CertificateVerify", 33);
3861 /* a single 0 byte separator */
3862 signing_data[97] = 0;
3863 signing_data_len = 98;
3865 signing_data_len += tls_get_hash(context, signing_data + 98);
3866 DEBUG_DUMP_HEX_LABEL("signature data", signing_data, signing_data_len);
3867 uint16_t signature = get16(&buf[3]);
3868 uint16_t signature_size = get16(&buf[5]);
3870 if (buf_len < size + 7) {
3871 return TLS_NEED_MORE_DATA;
3873 switch (signature) {
3875 /* secp256r1 + sha256 */
3877 tls_verify_ecdsa(context, sha256, buf + 7,
3878 signature_size, signing_data,
3883 /* secp384r1 + sha384 */
3884 valid = tls_verify_ecdsa(context, sha384, buf + 7,
3885 signature_size, signing_data,
3886 signing_data_len, &secp384r1);
3889 /* secp521r1 + sha512 */
3890 valid = tls_verify_ecdsa(context, sha512, buf + 7,
3891 signature_size, signing_data,
3892 signing_data_len, &secp521r1);
3895 valid = verify_rsa(context, sha256, buf + 7,
3896 signature_size, signing_data,
3900 DEBUG_PRINT("Unsupported signature: %x\n",
3902 return TLS_UNSUPPORTED_CERTIFICATE;
3905 DEBUG_PRINT("Signature FAILED!\n");
3906 return TLS_DECRYPTION_FAILED;
3911 int tls_parse_verify(struct TLSContext *context, const unsigned char *buf,
3913 if (context->tlsver == TLS_VERSION13) {
3914 return tls_parse_verify_tls13(context, buf, buf_len);
3918 return TLS_BAD_CERTIFICATE;
3921 int bytes_to_follow = get24(buf);
3923 if (buf_len - 3 < bytes_to_follow) {
3924 return TLS_BAD_CERTIFICATE;
3929 unsigned int hash = buf[3];
3930 unsigned int algorithm = buf[4];
3931 if (algorithm != rsa) {
3932 return TLS_UNSUPPORTED_CERTIFICATE;
3934 uint16_t size = get16(&buf[5]);
3935 if (bytes_to_follow - 4 < size) {
3936 return TLS_BAD_CERTIFICATE;
3938 DEBUG_PRINT("ALGORITHM %i/%i (%i)\n", hash, algorithm, (int) size);
3939 DEBUG_DUMP_HEX_LABEL("VERIFY", &buf[7], bytes_to_follow - 7);
3941 res = verify_rsa(context, hash, &buf[7], size,
3942 context->cached_handshake.buffer,
3943 context->cached_handshake.len);
3945 tls_buffer_free(&context->cached_handshake);
3947 DEBUG_PRINT("Signature OK\n");
3948 context->client_verified = 1;
3950 DEBUG_PRINT("Signature FAILED\n");
3951 context->client_verified = 0;
3956 /* TODO This is actually a parse a handshake message */
3957 int tls_parse_payload(struct TLSContext *context, const unsigned char *buf,
3959 int orig_len = buf_len;
3962 if (context->connection_status == TLS_CONNECTED) {
3963 if (context->version == TLS_V13) {
3964 tls_alert(context, 1, unexpected_message);
3966 tls_alert(context, 0, no_renegotiation_RESERVED);
3972 while (buf_len >= 4 && !context->critical_error) {
3973 int payload_res = 0;
3974 //unsigned char update_hash = 1;
3975 unsigned char type = buf[0];
3976 unsigned int write_packets = 0;
3977 int certificate_verify_alert = no_error;
3978 int payload_size = get24(buf+1) + 3;
3979 if (buf_len < payload_size + 1) {
3980 return TLS_NEED_MORE_DATA;
3985 CHECK_HANDSHAKE_STATE(context, 0, 1);
3987 (" => HELLO REQUEST (RENEGOTIATION?)\n");
3988 if (context->is_server) {
3989 payload_res = TLS_UNEXPECTED_MESSAGE;
3991 if (context->connection_status == TLS_CONNECTED) {
3993 payload_res = TLS_NO_RENEGOTIATION;
3995 payload_res = TLS_UNEXPECTED_MESSAGE;
4002 CHECK_HANDSHAKE_STATE(context, 1, 1);
4003 DEBUG_PRINT(" => CLIENT HELLO\n");
4004 if (context->is_server) {
4006 tls_parse_client_hello(context,
4011 payload_res = TLS_UNEXPECTED_MESSAGE;
4016 CHECK_HANDSHAKE_STATE(context, 2, 1);
4017 DEBUG_PRINT(" => SERVER HELLO\n");
4018 if (context->is_server) {
4019 payload_res = TLS_UNEXPECTED_MESSAGE;
4022 payload_res = tls_parse_server_hello(context, buf + 1, payload_size);
4026 /* hello verify request */
4027 DEBUG_PRINT(" => VERIFY REQUEST\n");
4028 CHECK_HANDSHAKE_STATE(context, 3, 1);
4029 payload_res = TLS_UNEXPECTED_MESSAGE;
4033 CHECK_HANDSHAKE_STATE(context, 4, 1);
4034 DEBUG_PRINT(" => CERTIFICATE\n");
4035 if (context->tlsver == TLS_VERSION13) {
4036 if (context->connection_status == 2) {
4038 tls_parse_certificate(context,
4043 if (context->is_server) {
4044 if (context->certificate_verify && context->client_certificates_count) {
4045 certificate_verify_alert
4047 context->certificate_verify(context,
4048 context->client_certificates,
4049 context->client_certificates_count);
4051 /* empty certificates are permitted for client */
4052 if (payload_res <= 0) {
4058 TLS_UNEXPECTED_MESSAGE;
4060 if (context->connection_status == 1) {
4061 if (context->is_server) {
4062 /* client certificate */
4064 tls_parse_certificate(context,
4068 if (context->certificate_verify && context->client_certificates_count) {
4069 certificate_verify_alert =
4070 context->certificate_verify
4073 client_certificates,
4075 client_certificates_count);
4077 /* empty certificates are permitted for client */
4078 if (payload_res <= 0)
4082 tls_parse_certificate(context,
4086 if (certificate_verify && context->certificates_count) {
4087 certificate_verify_alert =
4088 context->certificate_verify
4090 context->certificates,
4092 certificates_count);
4096 payload_res = TLS_UNEXPECTED_MESSAGE;
4100 /* server key exchange */
4101 CHECK_HANDSHAKE_STATE(context, 5, 1);
4102 DEBUG_PRINT(" => SERVER KEY EXCHANGE\n");
4103 if (context->is_server) {
4104 payload_res = TLS_UNEXPECTED_MESSAGE;
4107 tls_parse_server_key_exchange(context,
4113 /* certificate request */
4114 CHECK_HANDSHAKE_STATE(context, 6, 1);
4115 /* server to client */
4116 if (context->is_server) {
4117 payload_res = TLS_UNEXPECTED_MESSAGE;
4119 context->client_verified = 2;
4121 DEBUG_PRINT(" => CERTIFICATE REQUEST\n");
4124 /* server hello done */
4125 CHECK_HANDSHAKE_STATE(context, 7, 1);
4126 DEBUG_PRINT(" => SERVER HELLO DONE\n");
4127 if (context->is_server) {
4128 payload_res = TLS_UNEXPECTED_MESSAGE;
4131 tls_parse_server_hello_done(
4134 if (payload_res > 0) {
4140 /* certificate verify */
4141 CHECK_HANDSHAKE_STATE(context, 8, 1);
4142 DEBUG_PRINT(" => CERTIFICATE VERIFY\n");
4143 if (context->connection_status == 2) {
4145 tls_parse_verify(context, buf + 1,
4148 payload_res = TLS_UNEXPECTED_MESSAGE;
4152 /* client key exchange */
4153 CHECK_HANDSHAKE_STATE(context, 9, 1);
4154 DEBUG_PRINT(" => CLIENT KEY EXCHANGE\n");
4155 if (context->is_server) {
4157 tls_parse_client_key_exchange(context,
4161 payload_res = TLS_UNEXPECTED_MESSAGE;
4166 tls_buffer_free(&context->cached_handshake);
4167 CHECK_HANDSHAKE_STATE(context, 10, 1);
4168 DEBUG_PRINT(" => FINISHED\n");
4169 payload_res = tls_parse_finished(context,
4170 buf + 1, payload_size,
4172 if (payload_res > 0) {
4173 memset(context->hs_messages, 0,
4174 sizeof(context->hs_messages));
4179 (" => NOT UNDERSTOOD PAYLOAD TYPE: %x\n",
4181 return TLS_NOT_UNDERSTOOD;
4184 //if (type != 0x00 && update_hash) {
4186 tls_update_hash(context, buf, payload_size + 1);
4189 if (certificate_verify_alert != no_error) {
4190 tls_alert(context, 1, certificate_verify_alert);
4191 context->critical_error = 1;
4194 if (payload_res < 0) {
4195 switch (payload_res) {
4196 case TLS_UNEXPECTED_MESSAGE:
4197 tls_alert(context, 1, unexpected_message);
4199 case TLS_COMPRESSION_NOT_SUPPORTED:
4200 tls_alert(context, 1, decompression_failure_RESERVED);
4202 case TLS_BROKEN_PACKET:
4203 tls_alert(context, 1, decode_error);
4206 tls_alert(context, 1, internal_error);
4208 case TLS_NOT_VERIFIED:
4209 tls_alert(context, 1, bad_record_mac);
4211 case TLS_BAD_CERTIFICATE:
4212 if (context->is_server) {
4213 /* bad client certificate, continue */
4214 tls_alert(context, 0, bad_certificate);
4217 tls_alert(context, 1, bad_certificate);
4220 case TLS_UNSUPPORTED_CERTIFICATE:
4221 tls_alert(context, 1, unsupported_certificate);
4223 case TLS_NO_COMMON_CIPHER:
4224 tls_alert(context, 1, insufficient_security);
4226 case TLS_NOT_UNDERSTOOD:
4227 tls_alert(context, 1, internal_error);
4229 case TLS_NO_RENEGOTIATION:
4230 tls_alert(context, 0, no_renegotiation_RESERVED);
4233 case TLS_DECRYPTION_FAILED:
4234 tls_alert(context, 1, decryption_failed_RESERVED);
4237 if (payload_res < 0) {
4242 if (certificate_verify_alert != no_error) {
4243 payload_res = TLS_BAD_CERTIFICATE;
4246 /* except renegotiation */
4247 struct TLSPacket *pkt;
4248 switch (write_packets) {
4250 if (context->client_verified == 2) {
4251 DEBUG_PRINT("<= Building CERTIFICATE \n");
4252 tls_send_certificate(context);
4253 context->client_verified = 0;
4256 /* client handshake */
4257 tls_send_client_key_exchange(context);
4258 tls_send_change_cipher_spec(context);
4260 context->cipher_spec_set = 1;
4261 context->local_sequence_number = 0;
4263 tls_send_finished(context);
4265 context->cipher_spec_set = 0;
4268 /* server handshake */
4269 DEBUG_PRINT("<= SENDING SERVER HELLO\n");
4270 if (context->connection_status == 3) {
4271 context->connection_status = 2;
4273 (tls_build_hello(context, 0));
4274 tls_send_change_cipher_spec(context);
4275 _private_tls13_key(context, 1);
4276 context->cipher_spec_set = 1;
4278 ("<= SENDING ENCRYPTED EXTENSIONS\n");
4279 tls_send_encrypted_extensions(context);
4281 if (context->request_client_certificate) {
4283 ("<= SENDING CERTIFICATE REQUEST\n");
4285 (tls_certificate_request
4289 tls_send_certificate(context);
4291 tls_send_certificate_verify(context);
4293 tls_send_finished(context);
4296 free(context->server_finished_hash);
4298 context->server_finished_hash =
4299 malloc(tls_mac_length(context));
4301 if (context->server_finished_hash) {
4302 tls_get_hash(context,
4303 context->server_finished_hash);
4308 tls_queue_packet(tls_build_hello(context, 0));
4309 DEBUG_PRINT("<= SENDING CERTIFICATE\n");
4310 tls_send_certificate(context);
4312 int ephemeral_cipher =
4313 tls_cipher_is_ephemeral(context);
4314 if (ephemeral_cipher) {
4316 ("<= SENDING EPHEMERAL DH KEY\n");
4317 tls_send_server_key_exchange(context,
4318 ephemeral_cipher == 1 ?
4320 KEA_ec_diffie_hellman);
4322 if (context->request_client_certificate) {
4324 ("<= SENDING CERTIFICATE REQUEST\n");
4326 (tls_certificate_request
4329 tls_send_done(context);
4333 tls_send_change_cipher_spec(context);
4334 tls_send_finished(context);
4335 context->connection_status = TLS_CONNECTED;
4342 /* hello retry request */
4343 DEBUG_PRINT("<= SENDING HELLO RETRY REQUEST\n");
4344 pkt = tls_build_hello(context, 0);
4345 tls_queue_packet(pkt);
4349 buf += payload_size;
4350 buf_len -= payload_size;
4355 unsigned int asn1_get_len(const unsigned char *buffer, int buf_len,
4356 unsigned int *octets) {
4363 unsigned char size = buffer[0];
4366 *octets = size & 0x7F;
4367 if ((int) *octets > buf_len - 1) {
4371 unsigned int ref_octets = *octets;
4375 if ((int) *octets > buf_len - 1) {
4378 unsigned int long_size = 0;
4379 unsigned int coef = 1;
4381 for (i = ref_octets; i > 0; i--) {
4382 long_size += buffer[i] * coef;
4392 void print_index(const unsigned int *fields) {
4398 DEBUG_PRINT("%i", fields[i]);
4407 int _is_field(const unsigned int *fields, const unsigned int *prefix) {
4410 if (fields[i] != prefix[i]) {
4418 static int tls_hash_len(int algorithm) {
4419 switch (algorithm) {
4420 case TLS_RSA_SIGN_MD5:
4422 case TLS_RSA_SIGN_SHA1:
4424 case TLS_RSA_SIGN_SHA256:
4426 case TLS_RSA_SIGN_SHA384:
4428 case TLS_RSA_SIGN_SHA512:
4434 static unsigned char *tls_compute_hash(int algorithm, const unsigned char
4435 *message, unsigned int message_len) {
4436 unsigned char *hash = NULL;
4438 int hash_index = -1;
4439 unsigned long hash_len = 0;
4441 if (!message || !message_len) {
4445 switch (algorithm) {
4446 case TLS_RSA_SIGN_MD5:
4447 DEBUG_PRINT("SIGN MD5\n");
4448 hash_index = find_hash("md5");
4451 case TLS_RSA_SIGN_SHA1:
4452 DEBUG_PRINT("SIGN SHA1\n");
4453 hash_index = find_hash("sha1");
4456 case TLS_RSA_SIGN_SHA256:
4457 DEBUG_PRINT("SIGN SHA256\n");
4458 hash_index = find_hash("sha256");
4461 case TLS_RSA_SIGN_SHA384:
4462 DEBUG_PRINT("SIGN SHA384\n");
4463 hash_index = find_hash("sha384");
4466 case TLS_RSA_SIGN_SHA512:
4467 DEBUG_PRINT("SIGN SHA512\n");
4468 hash_index = find_hash("sha512");
4472 DEBUG_PRINT("UNKNOWN SIGNATURE ALGORITHM\n");
4477 hash = malloc(hash_len);
4482 err = hash_memory(hash_index, message, message_len, hash, &hash_len);
4489 int tls_certificate_verify_signature(struct TLSCertificate *cert,
4490 struct TLSCertificate *parent) {
4491 if (!cert || !parent || !cert->sign_key
4492 || !cert->fingerprint || !cert->sign_len
4493 || !parent->der_bytes || !parent->der_len) {
4494 DEBUG_PRINT("CANNOT VERIFY SIGNATURE ");
4496 DEBUG_PRINT("!cert ");
4498 if (!cert->sign_key) {
4499 DEBUG_PRINT("!cert->sign_key ");
4501 if (!cert->fingerprint) {
4502 DEBUG_PRINT("!cert->fingerprint ");
4504 if (!cert->sign_len) {
4505 DEBUG_PRINT("!cert->sign_len ");
4510 DEBUG_PRINT("!parent ");
4512 if (!parent->der_bytes) {
4513 DEBUG_PRINT("!parent->der_bytes ");
4515 if (!parent->der_len) {
4516 DEBUG_PRINT("!parent->der_len ");
4523 DEBUG_PRINT("checking alg\n");
4524 int hash_len = tls_hash_len(cert->algorithm);
4525 if (hash_len <= 0) {
4530 switch (cert->algorithm) {
4531 case TLS_RSA_SIGN_MD5:
4532 hash_index = find_hash("md5");
4534 case TLS_RSA_SIGN_SHA1:
4535 hash_index = find_hash("sha1");
4537 case TLS_RSA_SIGN_SHA256:
4538 hash_index = find_hash("sha256");
4540 case TLS_RSA_SIGN_SHA384:
4541 hash_index = find_hash("sha384");
4543 case TLS_RSA_SIGN_SHA512:
4544 hash_index = find_hash("sha512");
4547 DEBUG_PRINT("UNKNOWN SIGNATURE ALGORITHM\n");
4552 DEBUG_PRINTLN("rsa_import(%p, %d, %p)\n", parent->der_bytes,
4553 parent->der_len, &key);
4554 int err = rsa_import(parent->der_bytes, parent->der_len, &key);
4557 ("Error importing RSA certificate (code: %i)\n", err);
4558 DEBUG_PRINT("Message: %s\n", error_to_string(err));
4559 DEBUG_DUMP_HEX_LABEL("CERTIFICATE", parent->der_bytes,
4564 unsigned char *signature = cert->sign_key;
4565 int signature_len = cert->sign_len;
4566 if (!signature[0]) {
4571 err = rsa_verify_hash_ex(signature, signature_len, cert->fingerprint,
4572 hash_len, LTC_PKCS_1_V1_5, hash_index, 0, &rsa_stat,
4577 DEBUG_PRINT("HASH VERIFY ERROR %i\n", err);
4580 DEBUG_PRINT("CERTIFICATE VALIDATION: %i\n", rsa_stat);
4584 int tls_certificate_chain_is_valid(struct TLSCertificate **certificates,
4586 if (!certificates || !len) {
4587 return bad_certificate;
4591 DEBUG_PRINT("verifying %i length cert chain\n", len);
4594 /* expired certificate or not yet valid ? */
4595 if (tls_certificate_is_valid(certificates[0])) {
4596 return bad_certificate;
4600 for (i = 0; i < len; i++) {
4601 /* certificate in chain is expired ? */
4602 if (tls_certificate_is_valid(certificates[i + 1])) {
4603 return bad_certificate;
4606 if (!tls_certificate_verify_signature(certificates[i],
4607 certificates[i + 1])) {
4609 ("tls_certificate_verify_signature certs[%d], certs[%d+1] failed\n",
4611 return bad_certificate;
4618 int tls_certificate_chain_is_valid_root(struct TLSContext *context, struct
4619 TLSCertificate **certificates, int len) {
4622 if (!certificates || !len || !context->root_certificates
4623 || !context->root_count) {
4624 return bad_certificate;
4626 for (i = 0; i < len; i++) {
4627 for (j = 0; j < context->root_count; j++) {
4628 /* check if root certificate expired */
4629 if (tls_certificate_is_valid
4630 (context->root_certificates[j])) {
4633 /* if any root validates any certificate in the chain,
4634 * then is root validated */
4635 if (tls_certificate_verify_signature(certificates[i],
4636 context->root_certificates[j]))
4642 return bad_certificate;
4645 int _private_is_oid(struct OID_chain *ref_chain,
4646 const unsigned char *looked_oid, int looked_oid_len) {
4648 if (ref_chain->oid) {
4650 (ref_chain->oid, looked_oid, 16,
4655 ref_chain = (struct OID_chain *) ref_chain->top;
4660 int _private_asn1_parse(struct TLSContext *context,
4661 struct TLSCertificate *cert,
4662 const unsigned char *buffer, int size, int level,
4663 unsigned int *fields, unsigned char *has_key,
4664 int client_cert, unsigned char *top_oid,
4665 struct OID_chain *chain) {
4666 struct OID_chain local_chain;
4667 DEBUG_INDEX(fields);
4669 local_chain.top = chain;
4673 unsigned char oid[16];
4675 local_chain.oid = oid;
4679 unsigned char local_has_key = 0;
4680 const unsigned char *cert_data = NULL;
4681 unsigned int cert_len = 0;
4682 while (pos < size) {
4683 unsigned int start_pos = pos;
4684 if (size - pos < 2) {
4685 return TLS_NEED_MORE_DATA;
4687 unsigned char first = buffer[pos++];
4688 unsigned char type = first & 0x1F;
4689 unsigned char constructed = first & 0x20;
4690 unsigned char element_class = first >> 6;
4694 if (level <= TLS_ASN1_MAXLEVEL) {
4695 fields[level - 1] = idx;
4697 DEBUG_INDEX(fields);
4699 int length = asn1_get_len((unsigned char *) &buffer[pos], size
4701 DEBUG_PRINT("asn1_get_len = %u\n", length);
4702 if ((octets > 4) || (octets > size - pos)) {
4704 ("CANNOT READ CERTIFICATE octets = %d, size = %d pos = %d, size - pos = %d\n",
4705 octets, size, pos, size - pos);
4710 if (size - pos < length) {
4711 return TLS_NEED_MORE_DATA;
4714 /*DEBUG_PRINT("FIRST: %x => %x (%i)\n", (int)first, (int)type, length); */
4716 /*DEBUG_PRINT("%2i: ", level); */
4718 DEBUG_INDEX(fields);
4720 for (i1 = 1; i1 < level; i1++) {
4725 if (length && constructed) {
4728 DEBUG_PRINT("CONSTRUCTED BITSTREAM\n");
4731 DEBUG_PRINT("SEQUENCE\n");
4732 if ((level == 2) && (idx == 1)) {
4734 length + (pos - start_pos);
4735 cert_data = &buffer[start_pos];
4737 /* private key on server or public key on client */
4739 && (_is_field(fields, priv_der_id))) {
4740 free(cert->der_bytes);
4741 temp = length + (pos - start_pos);
4742 cert->der_bytes = malloc(temp);
4743 if (cert->der_bytes) {
4744 memcpy(cert->der_bytes,
4747 cert->der_len = temp;
4753 DEBUG_PRINT("EMBEDDED PDV\n");
4756 if (element_class == 0x02) {
4757 DEBUG_PRINT("CONTEXT-SPECIFIC\n");
4761 DEBUG_PRINT("CONSTRUCT TYPE %02X\n",(int)type);
4765 _private_asn1_parse(context, cert, &buffer[pos],
4766 length, level + 1, fields,
4767 &local_has_key, client_cert,
4768 top_oid, &local_chain);
4769 if (((local_has_key && context
4770 && (!context->is_server || client_cert))
4772 && (_is_field(fields, pk_id))) {
4773 free(cert->der_bytes);
4774 temp = length + (pos - start_pos);
4775 cert->der_bytes = malloc(temp);
4776 if (cert->der_bytes) {
4777 memcpy(cert->der_bytes,
4778 &buffer[start_pos], temp);
4779 cert->der_len = temp;
4787 /* end of content */
4788 DEBUG_PRINT("END OF CONTENT\n");
4794 DEBUG_PRINT("BOOLEAN: %i\n", temp);
4798 if (_is_field(fields, pk_id)) {
4804 tls_certificate_set_key
4805 (cert, &buffer[pos],
4807 } else if (idx == 2) {
4808 tls_certificate_set_exponent
4809 (cert, &buffer[pos],
4812 } else if (_is_field(fields, serial_id)) {
4813 tls_certificate_set_serial(cert,
4819 if (_is_field(fields, version_id)) {
4824 #ifdef TLS_X509_V1_SUPPORT
4832 unsigned int fields_temp[3];
4833 fields_temp[0] = fields[level - 2];
4834 fields_temp[1] = fields[level - 1];
4837 (fields_temp, priv_id)) {
4838 tls_certificate_set_priv
4839 (cert, &buffer[pos],
4843 DEBUG_PRINT("INTEGER(%i): ", length);
4844 DEBUG_DUMP_HEX(&buffer[pos], length);
4845 if ((chain) && (length > 2)) {
4848 sizeof(san_oid) - 1)) {
4852 TLS_REALLOC(cert->san,
4864 tls_certificate_set_copy
4871 (" => SUBJECT ALTERNATIVE NAME: %s",
4888 if (_is_field(fields, pk_id)) {
4893 DEBUG_PRINT("BITSTREAM(%i): ", length);
4894 DEBUG_DUMP_HEX(&buffer[pos], length);
4896 if (_is_field(fields, sign_id)
4897 || _is_field(fields, sign_id2)) {
4898 DEBUG_PRINT("set sign key\n");
4899 tls_certificate_set_sign_key(cert,
4903 } else if (cert->ec_algorithm
4904 && (_is_field(fields, pk_id))) {
4905 tls_certificate_set_key(cert,
4910 if (buffer[pos] == 0x00
4915 length - 1, level + 1,
4918 client_cert, top_oid,
4923 &buffer[pos], length,
4926 client_cert, top_oid,
4933 TLS_EC_prime256v1_OID,
4936 (TLS_EC_prime256v1) -
4944 TLS_EC_secp224r1_OID,
4947 (TLS_EC_secp224r1_OID)
4955 TLS_EC_secp384r1_OID,
4958 (TLS_EC_secp384r1_OID)
4966 TLS_EC_secp521r1_OID,
4969 (TLS_EC_secp521r1_OID)
4975 if ((cert->ec_algorithm)
4977 tls_certificate_set_key
4985 if (top_oid && _is_field(fields, ecc_priv_id)
4987 DEBUG_PRINT("BINARY STRING(%i): ",
4989 DEBUG_DUMP_HEX(&buffer[pos],
4992 tls_certificate_set_priv(cert,
4997 _private_asn1_parse(context, cert,
5009 DEBUG_PRINT("NULL\n");
5012 /* object identifier */
5013 if (_is_field(fields, pk_id)) {
5014 if (length == 8 || length == 5) {
5015 tls_certificate_set_algorithm
5016 (&cert->ec_algorithm,
5017 &buffer[pos], length);
5019 tls_certificate_set_algorithm
5020 (&cert->key_algorithm,
5021 &buffer[pos], length);
5024 if (_is_field(fields, algorithm_id))
5025 tls_certificate_set_algorithm
5027 &buffer[pos], length);
5029 DEBUG_PRINT("OBJECT IDENTIFIER(%i): ", length);
5030 DEBUG_DUMP_HEX(&buffer[pos], length);
5032 /* check previous oid */
5035 sizeof(ocsp_oid) - 1))
5036 tls_certificate_set_copy(&cert->ocsp,
5041 memcpy(oid, &buffer[pos], length);
5043 memcpy(oid, &buffer[pos], 16);
5046 memcpy(top_oid, oid, 16);
5049 DEBUG_PRINT("REAL NUMBER(%i): ", length);
5050 DEBUG_DUMP_HEX(&buffer[pos], length);
5055 DEBUG_PRINT("UTC TIME: [");
5056 DEBUG_DUMP(&buffer[pos], length);
5059 if (_is_field(fields, validity_id)) {
5061 tls_certificate_set_copy_date
5063 &buffer[pos], length);
5065 tls_certificate_set_copy_date
5067 &buffer[pos], length);
5072 /* generalized time */
5073 DEBUG_PRINT("GENERALIZED TIME: [");
5074 DEBUG_DUMP(&buffer[pos], length);
5078 /* printable string */
5089 if (_is_field(fields, issurer_id)) {
5090 if (_is_oid(oid, country_oid, 3)) {
5091 tls_certificate_set_copy
5092 (&cert->issuer_country,
5093 &buffer[pos], length);
5095 (oid, state_oid, 3)) {
5096 tls_certificate_set_copy
5097 (&cert->issuer_state,
5098 &buffer[pos], length);
5100 (oid, location_oid, 3)) {
5101 tls_certificate_set_copy
5104 &buffer[pos], length);
5106 (oid, entity_oid, 3)) {
5107 tls_certificate_set_copy
5108 (&cert->issuer_entity,
5109 &buffer[pos], length);
5111 (oid, subject_oid, 3)) {
5112 tls_certificate_set_copy
5113 (&cert->issuer_subject,
5114 &buffer[pos], length);
5116 } else if (_is_field(fields, owner_id)) {
5117 if (_is_oid(oid, country_oid, 3)) {
5118 tls_certificate_set_copy
5120 &buffer[pos], length);
5122 (oid, state_oid, 3)) {
5123 tls_certificate_set_copy
5125 &buffer[pos], length);
5127 (oid, location_oid, 3)) {
5128 tls_certificate_set_copy
5130 &buffer[pos], length);
5132 (oid, entity_oid, 3)) {
5133 tls_certificate_set_copy
5135 &buffer[pos], length);
5137 (oid, subject_oid, 3)) {
5138 tls_certificate_set_copy
5140 &buffer[pos], length);
5143 DEBUG_PRINT("STR: [");
5144 DEBUG_DUMP(&buffer[pos], length);
5148 DEBUG_PRINT("EMPTY SEQUENCE\n");
5151 DEBUG_PRINT("ENUMERATED(%i): ", length);
5152 DEBUG_DUMP_HEX(&buffer[pos], length);
5156 DEBUG_PRINT("========> NOT SUPPORTED %x\n",
5158 /* not supported / needed */
5165 if (level == 2 && cert->sign_key && cert->sign_len
5166 && cert_len && cert_data) {
5167 free(cert->fingerprint);
5168 cert->fingerprint = tls_compute_hash(cert->algorithm,
5169 cert_data, cert_len);
5171 if (cert->fingerprint) {
5172 DEBUG_DUMP_HEX_LABEL("FINGERPRINT",
5174 tls_hash_len(cert->algorithm));
5181 struct TLSCertificate *asn1_parse(struct TLSContext *context,
5182 const unsigned char *buffer, int size,
5184 unsigned int fields[TLS_ASN1_MAXLEVEL] = { 0 };
5186 struct TLSCertificate *cert = tls_create_certificate();
5189 if (client_cert < 0) {
5192 unsigned char top_oid[16];
5193 memset(top_oid, 0, sizeof(top_oid));
5194 _private_asn1_parse(context, cert, buffer, size, 1,
5195 fields, NULL, client_cert,
5198 _private_asn1_parse(context, cert, buffer, size, 1,
5199 fields, NULL, client_cert,
5206 int tls_clear_certificates(struct TLSContext *tls) {
5209 if (!tls || !tls->is_server || tls->is_child) {
5210 return TLS_GENERIC_ERROR;
5213 if (tls->root_certificates) {
5214 for (i = 0; i < tls->root_count; i++) {
5215 tls_destroy_certificate(tls->root_certificates[i]);
5218 tls->root_certificates = NULL;
5219 tls->root_count = 0;
5221 if (tls->private_key) {
5222 tls_destroy_certificate(tls->private_key);
5224 tls->private_key = NULL;
5225 if (tls->ec_private_key) {
5226 tls_destroy_certificate(tls->ec_private_key);
5228 tls->ec_private_key = NULL;
5229 free(tls->certificates);
5230 tls->certificates = NULL;
5231 tls->certificates_count = 0;
5235 /* This is just a wrapper around parse message so we don't
5236 * call read more often than necessary. IOW, if there's
5237 * more than one record in the input buffer, process them all
5239 int tls_consume_stream(struct TLSContext *context) {
5241 return TLS_GENERIC_ERROR;
5244 if (context->critical_error) {
5245 return TLS_BROKEN_CONNECTION;
5248 size_t tls_buffer_len = context->input_buffer.len;
5249 unsigned char *buffer = context->input_buffer.buffer;
5251 unsigned int index = 0;
5254 int tls_header_size;
5255 int tls_size_offset;
5257 tls_size_offset = 3;
5258 tls_header_size = 5;
5260 while (tls_buffer_len >= 5) {
5263 length = get16(buffer + index + tls_size_offset)
5266 if (length > tls_buffer_len) {
5267 /* record not complete */
5271 /* This is the only place tls_parse_message is called */
5272 int consumed = tls_parse_message(context, buffer+index, length);
5274 err_flag = consumed;
5278 tls_buffer_len -= length;
5279 if (context->critical_error) {
5280 err_flag = TLS_BROKEN_CONNECTION;
5285 if (err_flag || context->input_buffer.error) {
5286 if (!context->critical_error) {
5287 context->critical_error = 1;
5289 DEBUG_PRINT("ERROR IN CONSUME: %i\n", err_flag);
5290 tls_buffer_free(&context->input_buffer);
5293 tls_buffer_shift(&context->input_buffer, index);
5297 void tls_close_notify(struct TLSContext *context) {
5298 if (!context || context->critical_error) {
5301 context->critical_error = 1;
5302 DEBUG_PRINT("CLOSE\n");
5303 tls_alert(context, 0, close_notify);
5306 void tls_alert(struct TLSContext *context, int critical, int code) {
5311 struct TLSPacket *packet = tls_create_packet(context, TLS_ALERT,
5312 context->version, 0);
5313 tls_packet_uint8(packet, critical ? TLS_ALERT_CRITICAL :
5316 tls_packet_uint8(packet, code);
5317 tls_packet_update(packet);
5320 context->critical_error = 1;
5323 tls_queue_packet(packet);
5326 int tls_is_broken(struct TLSContext *context) {
5327 if (!context || context->critical_error) {
5333 /* TODO I don't see that this ever gets cleared */
5334 int tls_request_client_certificate(struct TLSContext *context) {
5335 if (!context || !context->is_server) {
5339 context->request_client_certificate = 1;
5343 int tls_client_verified(struct TLSContext *context) {
5344 if (!context || context->critical_error) {
5348 return context->client_verified == 1;
5351 int tls_sni_set(struct TLSContext *context, const char *sni) {
5352 if (!context || context->is_server || context->critical_error
5353 || context->connection_status != 0) {
5359 context->sni = sni ? strdup(sni) : 0;
5360 return context->sni ? 1 : 0;
5363 int tls_default_verify(struct TLSContext *context,
5364 struct TLSCertificate **certificate_chain, int len)
5369 if (certificate_chain) {
5370 for (i = 0; i < len; i++) {
5371 struct TLSCertificate *certificate =
5372 certificate_chain[i];
5373 /* check validity date */
5374 err = tls_certificate_is_valid(certificate);
5380 /* check if chain is valid */
5381 err = tls_certificate_chain_is_valid(certificate_chain, len);
5386 /* check certificate subject */
5387 if (!context->is_server && context->sni && len > 0
5388 && certificate_chain) {
5389 err = tls_certificate_valid_subject(certificate_chain[0],
5396 err = tls_certificate_chain_is_valid_root(context, certificate_chain,
5402 DEBUG_PRINT("Certificate OK\n");
5406 ssize_t tls_fsync(struct TLSContext *context) {
5409 ssize_t send_res = 0;
5411 unsigned char *buffer;
5412 tls_send_func write_cb = NULL;
5423 buffer = context->output_buffer.buffer;
5424 buflen = context->output_buffer.len;
5426 if (context->send) {
5427 write_cb = context->send;
5432 while (buflen > 0) {
5435 res = write_cb(fd, buffer+offset, buflen, 0);
5437 perror("send error");
5445 DEBUG_PRINT("sent %zd bytes\n", send_res);
5446 context->output_buffer.len = 0;
5450 void tls_free(struct TLSContext *context) {
5452 free(context->user_data);
5453 tls_destroy_context(context);
5457 int tls_set_fd(struct TLSContext *context, int socket) {
5459 return TLS_GENERIC_ERROR;
5461 context->fd = socket;
5465 int tls_load_root_file(struct TLSContext *context, const char *pem_filename) {
5476 fd = open(pem_filename, O_RDONLY);
5481 if (fstat(fd, &st) == -1) {
5486 addr = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
5487 if (addr == MAP_FAILED) {
5492 count = tls_load_root_certificates(context, addr, st.st_size);
5493 munmap(addr, st.st_size);
5499 void tls_set_verify(struct TLSContext *tls, tls_validation_function vfunc) {
5501 tls->certificate_verify = vfunc;
5505 static ssize_t tls_safe_read(struct TLSContext *tls) {
5506 tls_recv_func read_cb;
5510 if (!tls || tls->fd <= 0) {
5511 return TLS_GENERIC_ERROR;
5515 read_cb = tls->recv;
5521 bytes = read_cb(tls->fd, buffer, sizeof buffer, 0);
5523 tls_buffer_append(&tls->input_buffer, buffer, bytes);
5529 /* I think this is the server handshake */
5530 int SSL_accept(struct TLSContext *context) {
5531 ssize_t read_size = 0;
5533 if (!context || context->fd <= 0) {
5534 return TLS_GENERIC_ERROR;
5537 if (tls_established(context)) {
5542 while ((read_size = tls_safe_read(context)) > 0) {
5543 if (tls_consume_stream(context) >= 0) {
5544 ssize_t res = tls_fsync(context);
5549 if (tls_established(context)) {
5553 if (read_size <= 0) {
5554 return TLS_BROKEN_CONNECTION;
5559 /* TODO this is really do the handshake */
5560 int tls_connect(struct TLSContext *context) {
5564 if (!context || context->fd <= 0 || context->critical_error) {
5565 return TLS_GENERIC_ERROR;
5568 if (context->is_server) {
5569 return TLS_UNEXPECTED_MESSAGE;
5572 res = tls_queue_packet(tls_build_client_hello(context));
5578 res = tls_fsync(context);
5583 while ((read_size = tls_safe_read(context)) > 0) {
5584 if ((res = tls_consume_stream(context)) >= 0) {
5585 res = tls_fsync(context);
5590 if (tls_established(context)) {
5593 if (context->critical_error) {
5594 return TLS_GENERIC_ERROR;
5600 int tls_shutdown(struct TLSContext *tls) {
5601 if (!tls || tls->fd <= 0) {
5602 return TLS_GENERIC_ERROR;
5605 tls_close_notify(tls);
5609 /* TODO configure for maximum packet data length
5610 * max is 2^14 - 5 byte header - 32 byte mac - padding which depends
5611 * on the cipher (up to 255 bytes I think).
5613 ssize_t tls_write(struct TLSContext *context, const void *buf, size_t count) {
5615 return TLS_GENERIC_ERROR;
5617 if (context->connection_status != TLS_CONNECTED) {
5618 return TLS_UNEXPECTED_MESSAGE;
5620 if (count > TLS_MAXTLS_APP_SIZE) {
5621 count = TLS_MAXTLS_APP_SIZE;
5624 if (!buf || !count) {
5628 struct TLSPacket *packet = tls_create_packet(context,
5629 TLS_APPLICATION_DATA, context->version, count);
5630 tls_packet_append(packet, buf, count);
5631 tls_packet_update(packet);
5633 tls_queue_packet(packet);
5634 /* TODO think about this. context->sync with O_NONBLOCK might be a
5637 if (context->sync) {
5639 res = tls_fsync(context);
5647 static ssize_t tls_readbuf(struct TLSContext *tls, void *buf, size_t count) {
5648 if (count > tls->application_buffer.len) {
5649 count = tls->application_buffer.len;
5653 /* TODO should have a buffer read and shift */
5654 memcpy(buf, tls->application_buffer.buffer, count);
5655 tls_buffer_shift(&tls->application_buffer, count);
5661 ssize_t tls_read(struct TLSContext *context, void *buf, size_t count) {
5663 return TLS_GENERIC_ERROR;
5666 if (context->application_buffer.len) {
5667 return tls_readbuf(context, buf, count);
5670 if (context->fd <= 0 || context->critical_error) {
5671 return TLS_GENERIC_ERROR;
5674 if (tls_established(context) != 1) {
5675 return TLS_GENERIC_ERROR;
5678 if (context->application_buffer.len == 0 && !context->critical_error) {
5679 /* attempt to fill buffer, unless we're already in an error
5684 while ((read_size = tls_safe_read(context)) > 0) {
5685 if (tls_consume_stream(context) > 0) {
5689 if (context->critical_error
5690 && !context->application_buffer.len) {
5691 /* if there's a critical error, don't bail if
5692 * we managed to get some data
5694 return TLS_GENERIC_ERROR;
5698 if (read_size <= 0 && context->application_buffer.len == 0) {
5699 /* can return errors as for read(2) */
5704 return tls_readbuf(context, buf, count);