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]++; }
64 //#define MARK fprintf(stderr, "%s %s:%d\n", __FILE__, __func__, __LINE__)
74 } KeyExchangeAlgorithm;
81 rsa_ephemeral_dh_RESERVED = 5,
82 dss_ephemeral_dh_RESERVED = 6,
83 fortezza_dms_RESERVED = 20,
87 } TLSClientCertificateType;
105 } TLSSignatureAlgorithm;
112 typedef ssize_t (*tls_recv_func)(int sockfd, void *buf, size_t len,
114 typedef ssize_t (*tls_send_func)(int sockfd, const void *buf, size_t len,
117 static const unsigned int version_id[] = { 1, 1, 1, 0 };
118 static const unsigned int pk_id[] = { 1, 1, 7, 0 };
119 static const unsigned int serial_id[] = { 1, 1, 2, 1, 0 };
120 static const unsigned int issurer_id[] = { 1, 1, 4, 0 };
121 static const unsigned int owner_id[] = { 1, 1, 6, 0 };
122 static const unsigned int validity_id[] = { 1, 1, 5, 0 };
123 static const unsigned int algorithm_id[] = { 1, 1, 3, 0 };
124 static const unsigned int sign_id[] = { 1, 3, 2, 1, 0 };
125 static const unsigned int sign_id2[] = { 1, 3, 2, 2, 0 };
126 static const unsigned int priv_id[] = { 1, 4, 0 };
127 static const unsigned int priv_der_id[] = { 1, 3, 1, 0 };
128 static const unsigned int ecc_priv_id[] = { 1, 2, 0 };
130 static const unsigned char country_oid[] = { 0x55, 0x04, 0x06, 0x00 };
131 static const unsigned char state_oid[] = { 0x55, 0x04, 0x08, 0x00 };
132 static const unsigned char location_oid[] = { 0x55, 0x04, 0x07, 0x00 };
133 static const unsigned char entity_oid[] = { 0x55, 0x04, 0x0A, 0x00 };
134 static const unsigned char subject_oid[] = { 0x55, 0x04, 0x03, 0x00 };
135 static const unsigned char san_oid[] = { 0x55, 0x1D, 0x11, 0x00 };
136 static const unsigned char ocsp_oid[] =
137 { 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x01, 0x00 };
139 static const unsigned char TLS_RSA_SIGN_RSA_OID[] =
140 { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x00 };
141 static const unsigned char TLS_RSA_SIGN_MD5_OID[] =
142 { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x04, 0x00 };
143 static const unsigned char TLS_RSA_SIGN_SHA1_OID[] =
144 { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x05, 0x00 };
145 static const unsigned char TLS_RSA_SIGN_SHA256_OID[] =
146 { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x00 };
147 static const unsigned char TLS_RSA_SIGN_SHA384_OID[] =
148 { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0C, 0x00 };
149 static const unsigned char TLS_RSA_SIGN_SHA512_OID[] =
150 { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0D, 0x00 };
153 static const unsigned char TLS_ECDSA_SIGN_SHA1_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x01, 0x05, 0x00, 0x00};
154 static const unsigned char TLS_ECDSA_SIGN_SHA224_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x01, 0x05, 0x00, 0x00};
155 static const unsigned char TLS_ECDSA_SIGN_SHA256_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02, 0x05, 0x00, 0x00};
156 static const unsigned char TLS_ECDSA_SIGN_SHA384_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x03, 0x05, 0x00, 0x00};
157 static const unsigned char TLS_ECDSA_SIGN_SHA512_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x04, 0x05, 0x00, 0x00};
160 static const unsigned char TLS_EC_PUBLIC_KEY_OID[] =
161 { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01, 0x00 };
163 static const unsigned char TLS_EC_prime192v1_OID[] =
164 { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x01, 0x00 };
165 static const unsigned char TLS_EC_prime192v2_OID[] =
166 { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x02, 0x00 };
167 static const unsigned char TLS_EC_prime192v3_OID[] =
168 { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x03, 0x00 };
169 static const unsigned char TLS_EC_prime239v1_OID[] =
170 { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x04, 0x00 };
171 static const unsigned char TLS_EC_prime239v2_OID[] =
172 { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x05, 0x00 };
173 static const unsigned char TLS_EC_prime239v3_OID[] =
174 { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x06, 0x00 };
175 static const unsigned char TLS_EC_prime256v1_OID[] =
176 { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07, 0x00 };
178 #define TLS_EC_secp256r1_OID TLS_EC_prime256v1_OID
179 static const unsigned char TLS_EC_secp224r1_OID[] =
180 { 0x2B, 0x81, 0x04, 0x00, 0x21, 0x00 };
181 static const unsigned char TLS_EC_secp384r1_OID[] =
182 { 0x2B, 0x81, 0x04, 0x00, 0x22, 0x00 };
183 static const unsigned char TLS_EC_secp521r1_OID[] =
184 { 0x2B, 0x81, 0x04, 0x00, 0x23, 0x00 };
186 int tls_random(unsigned char *key, int len);
187 void tls_destroy_packet(struct TLSPacket *packet);
188 struct TLSPacket *tls_build_hello(struct TLSContext *context,
189 int tls13_downgrade);
193 static unsigned char TLS_DSA_SIGN_SHA1_OID[] = {0x2A, 0x86, 0x52, 0xCE, 0x38, 0x04, 0x03, 0x00};
196 static uint16_t get16(const unsigned char *buf) {
199 res = ((*buf) << 8) + (*(buf+1));
203 static uint32_t get24(const unsigned char *buf) {
206 res = (buf[0] << 16) + (buf[1] << 8) + buf[2];
210 size_t tls_queue_packet(struct TLSPacket *packet) {
215 struct TLSContext *context = packet->context;
221 tls_buffer_append(&context->output_buffer, packet->buf, packet->len);
222 tls_destroy_packet(packet);
223 return context->output_buffer.len;
226 static void tls_send_change_cipher_spec(struct TLSContext *context) {
227 struct TLSPacket *packet =
228 tls_create_packet(context, TLS_CHANGE_CIPHER, context->version,
230 tls_packet_uint8(packet, 1);
231 tls_packet_update(packet);
232 context->local_sequence_number = 0;
233 tls_queue_packet(packet);
237 static void tls_send_encrypted_extensions(struct TLSContext *context) {
238 struct TLSPacket *packet =
239 tls_create_packet(context, TLS_HANDSHAKE, context->version, 3);
240 tls_packet_uint8(packet, 0x08);
242 if (context->negotiated_alpn) {
243 int alpn_negotiated_len = strlen(context->negotiated_alpn);
244 int alpn_len = alpn_negotiated_len + 1;
246 tls_packet_uint24(packet, alpn_len + 8);
247 tls_packet_uint16(packet, alpn_len + 6);
248 tls_packet_uint16(packet, 0x10);
249 tls_packet_uint16(packet, alpn_len + 2);
250 tls_packet_uint16(packet, alpn_len);
252 tls_packet_uint8(packet, alpn_negotiated_len);
253 tls_packet_append(packet, (unsigned char *) context->
254 negotiated_alpn, alpn_negotiated_len);
256 tls_packet_uint24(packet, 2);
257 tls_packet_uint16(packet, 0);
259 tls_packet_update(packet);
260 tls_queue_packet(packet);
264 static void tls_send_done(struct TLSContext *context) {
265 struct TLSPacket *packet =
266 tls_create_packet(context, TLS_HANDSHAKE, context->version, 0);
267 tls_packet_uint8(packet, 0x0E);
268 tls_packet_uint24(packet, 0);
269 tls_packet_update(packet);
270 tls_queue_packet(packet);
274 static void tls_send_certificate(struct TLSContext *context) {
276 unsigned int all_certificate_size = 0;
277 int certificates_count;
278 struct TLSCertificate **certificates;
280 if (context->is_server) {
281 certificates_count = context->certificates_count;
282 certificates = context->certificates;
284 certificates_count = context->client_certificates_count;
285 certificates = context->client_certificates;
289 if (context->tlsver == TLS_VERSION13) {
293 int is_ecdsa = tls_is_ecdsa(context);
294 /* TODO can do one loop and test for ecdsa inside loop */
296 for (i = 0; i < certificates_count; i++) {
297 struct TLSCertificate *cert = certificates[i];
298 if (cert && cert->der_len && cert->ec_algorithm) {
299 all_certificate_size += cert->der_len + delta;
303 for (i = 0; i < certificates_count; i++) {
304 struct TLSCertificate *cert = certificates[i];
305 if (cert && cert->der_len && !cert->ec_algorithm) {
306 all_certificate_size += cert->der_len + delta;
311 for (i = 0; i < certificates_count; i++) {
312 struct TLSCertificate *cert = certificates[i];
313 if (cert && cert->der_len) {
314 all_certificate_size += cert->der_len + delta;
318 if (!all_certificate_size) {
319 DEBUG_PRINT("NO CERTIFICATE SET\n");
322 struct TLSPacket *packet = tls_create_packet(context, TLS_HANDSHAKE,
323 context->version, 0);
324 tls_packet_uint8(packet, 0x0B);
326 if (all_certificate_size) {
328 if (context->tlsver == TLS_VERSION13) {
329 tls_packet_uint24(packet, all_certificate_size + 4);
330 tls_packet_uint8(packet, 0);
332 tls_packet_uint24(packet, all_certificate_size + 3);
335 tls_packet_uint24(packet, all_certificate_size);
337 for (i = 0; i < certificates_count; i++) {
338 struct TLSCertificate *cert = certificates[i];
339 if (cert && cert->der_len) {
340 /* is RSA certificate ? */
341 if (is_ecdsa && !cert->ec_algorithm) {
344 /* is ECC certificate ? */
345 if (!is_ecdsa && cert->ec_algorithm) {
348 /* 2 times -> one certificate */
349 tls_packet_uint24(packet, cert->der_len);
350 tls_packet_append(packet, cert->der_bytes,
353 if (context->tlsver == TLS_VERSION13) {
354 tls_packet_uint16(packet, 0);
359 tls_packet_uint24(packet, all_certificate_size);
360 if (context->tlsver == TLS_VERSION13) {
361 tls_packet_uint8(packet, 0);
365 tls_packet_update(packet);
366 tls_queue_packet(packet);
370 int tls_supported_version(uint16_t ver) {
376 DEBUG_PRINT("UNSUPPORTED TLS VERSION %x\n", (int)ver);
382 void tls_set_packet_length(struct TLSPacket *packet, uint32_t length) {
383 int offset = packet->payload_pos;
384 packet->buf[offset] = (length >> 16) & 0xff;
385 packet->buf[offset+1] = (length >> 8) & 0xff;
386 packet->buf[offset+2] = (length >> 0) & 0xff;
389 static void tls_init() {
390 static int loaded = 0;
395 DEBUG_PRINT("Initializing dependencies\n");
404 /* TODO remove these */
405 register_hash(&md5_desc);
406 register_hash(&sha1_desc);
408 register_hash(&sha256_desc);
409 register_hash(&sha384_desc);
410 register_hash(&sha512_desc);
412 register_prng(&sprng_desc);
414 register_cipher(&aes_desc);
416 tls_ecc_init_curves();
419 static unsigned char *decrypt_rsa(struct TLSContext *context,
420 const unsigned char *buffer,
422 unsigned int *size) {
424 if (!len || !context || !context->private_key
425 || !context->private_key->der_bytes
426 || !context->private_key->der_len) {
427 DEBUG_PRINT("No private key set\n");
432 err = rsa_import(context->private_key->der_bytes,
433 context->private_key->der_len, &key);
436 DEBUG_PRINT("Error importing RSA key (code: %i)\n", err);
440 unsigned char *out = malloc(len);
441 unsigned long out_size = len;
442 int hash_idx = find_hash("sha256");
444 err = rsa_decrypt_key_ex(buffer, len, out, &out_size, (unsigned char *)
445 "Concept", 7, hash_idx, LTC_PKCS_1_V1_5, &res, &key);
448 if (err || !out_size) {
449 DEBUG_PRINT("RSA DECRYPT ERROR\n");
453 *size = (unsigned int) out_size;
457 static int verify_rsa(struct TLSContext *context, unsigned int hash_type, const
458 unsigned char *buffer, unsigned int len, const unsigned char
459 *message, unsigned long message_len) {
464 return TLS_GENERIC_ERROR;
467 struct TLSCertificate **cert;
470 if (context->is_server) {
471 cert = context->client_certificates;
472 count = context->client_certificates_count;
474 cert = context->certificates;
475 count = context->certificates_count;
478 if (count == 0 || !cert) {
479 return TLS_GENERIC_ERROR;
482 err = rsa_import(cert[0]->der_bytes, cert[0]->der_len, &key);
485 DEBUG_PRINT("Error importing RSA certificate (code: %i)\n",
487 return TLS_GENERIC_ERROR;
490 unsigned char hash[TLS_MAX_HASH_LEN];
491 unsigned long hash_len;
492 hash_len = (unsigned long)sizeof hash;
496 hash_idx = find_hash("md5");
499 hash_idx = find_hash("sha1");
502 hash_idx = find_hash("sha256");
505 hash_idx = find_hash("sha384");
508 hash_idx = find_hash("sha512");
511 err = hash_memory(hash_idx, message, message_len, hash, &hash_len);
512 if (hash_idx < 0 || err) {
513 DEBUG_PRINT("Unsupported hash type: %i\n", hash_type);
514 return TLS_GENERIC_ERROR;
517 if (context->tlsver == TLS_VERSION13) {
518 err = rsa_verify_hash_ex(buffer, len, hash, hash_len,
519 LTC_PKCS_1_PSS, hash_idx, 0, &rsa_stat, &key);
521 err = rsa_verify_hash_ex(buffer, len, hash, hash_len,
522 LTC_PKCS_1_V1_5, hash_idx, 0, &rsa_stat, &key);
531 static int sign_rsa(struct TLSContext *context, unsigned int hash_type, const
532 unsigned char *message, unsigned int message_len, unsigned char
533 *out, unsigned long *outlen) {
537 unsigned char hash[TLS_MAX_HASH_LEN];
538 unsigned long hash_len = 0;
541 if (!outlen || !context || !out || !context->private_key
542 || !context->private_key->der_bytes
543 || !context->private_key->der_len) {
544 DEBUG_PRINT("No private key set\n");
545 return TLS_GENERIC_ERROR;
548 err = rsa_import(context->private_key->der_bytes,
549 context->private_key->der_len, &key);
552 DEBUG_PRINT("Error %d importing RSA certificate", err);
553 return TLS_GENERIC_ERROR;
558 hash_index = find_hash("sha1");
562 hash_index = find_hash("sha256");
566 hash_index = find_hash("sha384");
570 hash_index = find_hash("sha512");
575 hash_index = find_hash("md5");
580 if (hash_index < 0 || err) {
581 DEBUG_PRINT("Unsupported hash type: %i\n", hash_type);
582 return TLS_GENERIC_ERROR;
585 hash_memory(hash_index, message, message_len, hash, &hash_len);
587 if (hash_type == _md5_sha1) {
588 unsigned long hlen = 20;
589 hash_index = find_hash("sha1");
590 hash_memory(hash_index, message, message_len, hash+16, &hlen);
594 //err = hash_memory(hash_idx, message, message_len, hash, &hash_len);
596 if (context->tlsver == TLS_VERSION13) {
597 err = rsa_sign_hash_ex(hash, hash_len, out, outlen,
598 LTC_PKCS_1_PSS, NULL, find_prng("sprng"),
599 hash_index, hash_type == sha256 ? 32 : 48, &key);
601 err = rsa_sign_hash_ex(hash, hash_len, out, outlen,
602 LTC_PKCS_1_V1_5, NULL, find_prng("sprng"),
603 hash_index, 0, &key);
614 static int tls_is_point(ecc_key * key) {
615 void *prime, *b, *t1, *t2;
618 if ((err = mp_init_multi(&prime, &b, &t1, &t2, NULL)) != CRYPT_OK) {
622 /* load prime and b */
623 if ((err = mp_read_radix(prime, key->dp->prime, 16)) != CRYPT_OK) {
626 if ((err = mp_read_radix(b, key->dp->B, 16)) != CRYPT_OK) {
631 if ((err = mp_sqr(key->pubkey.y, t1)) != CRYPT_OK) {
636 if ((err = mp_sqr(key->pubkey.x, t2)) != CRYPT_OK) {
639 if ((err = mp_mod(t2, prime, t2)) != CRYPT_OK) {
642 if ((err = mp_mul(key->pubkey.x, t2, t2)) != CRYPT_OK) {
646 /* compute y^2 - x^3 */
647 if ((err = mp_sub(t1, t2, t1)) != CRYPT_OK) {
651 /* compute y^2 - x^3 + 3x */
652 if ((err = mp_add(t1, key->pubkey.x, t1)) != CRYPT_OK) {
655 if ((err = mp_add(t1, key->pubkey.x, t1)) != CRYPT_OK) {
658 if ((err = mp_add(t1, key->pubkey.x, t1)) != CRYPT_OK) {
661 if ((err = mp_mod(t1, prime, t1)) != CRYPT_OK) {
664 while (mp_cmp_d(t1, 0) == LTC_MP_LT) {
665 if ((err = mp_add(t1, prime, t1)) != CRYPT_OK) {
669 while (mp_cmp(t1, prime) != LTC_MP_LT) {
670 if ((err = mp_sub(t1, prime, t1)) != CRYPT_OK) {
676 if (mp_cmp(t1, b) != LTC_MP_EQ) {
677 err = CRYPT_INVALID_PACKET;
683 mp_clear_multi(prime, b, t1, t2, NULL);
687 static int tls_ecc_import_key(const unsigned char *private_key,
689 const unsigned char *public_key,
690 int public_len, ecc_key *key,
691 const ltc_ecc_set_type *dp) {
694 if (!key || !ltc_mp.name) {
698 key->type = PK_PRIVATE;
701 (&key->pubkey.x, &key->pubkey.y, &key->pubkey.z, &key->k,
705 if (public_len && !public_key[0]) {
709 if ((err = mp_read_unsigned_bin(key->pubkey.x,
710 (unsigned char *) public_key + 1,
711 (public_len - 1) >> 1)) != CRYPT_OK) {
712 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
717 if ((err = mp_read_unsigned_bin(key->pubkey.y,
718 (unsigned char *) public_key + 1 +
719 ((public_len - 1) >> 1),
720 (public_len - 1) >> 1)) != CRYPT_OK) {
721 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
727 mp_read_unsigned_bin(key->k, (unsigned char *) private_key,
728 private_len)) != CRYPT_OK) {
729 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
738 if ((err = mp_set(key->pubkey.z, 1)) != CRYPT_OK) {
739 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
744 /* is it a point on the curve? */
745 if ((err = tls_is_point(key)) != CRYPT_OK) {
746 DEBUG_PRINT("KEY IS NOT ON CURVE\n");
747 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
756 static int sign_ecdsa(struct TLSContext *context,
757 unsigned int hash_type,
758 const unsigned char *message,
759 unsigned int message_len, unsigned char *out,
760 unsigned long *outlen) {
761 if (!outlen || !context || !out || !outlen
762 || !context->ec_private_key
763 || !context->ec_private_key->priv
764 || !context->ec_private_key->priv_len
765 || !context->ec_private_key->pk
766 || !context->ec_private_key->pk_len) {
767 DEBUG_PRINT("No private ECDSA key set\n");
768 return TLS_GENERIC_ERROR;
771 const struct ECCCurveParameters *curve = NULL;
773 switch (context->ec_private_key->ec_algorithm) {
796 DEBUG_PRINT("UNSUPPORTED CURVE\n");
800 return TLS_GENERIC_ERROR;
806 ltc_ecc_set_type *dp = (ltc_ecc_set_type *)&curve->dp;
808 /* broken ... fix this */
809 err = tls_ecc_import_key(context->ec_private_key->priv,
810 context->ec_private_key->priv_len,
811 context->ec_private_key->pk,
812 context->ec_private_key->pk_len, &key, dp);
815 DEBUG_PRINT("Error importing ECC certificate (code: %i)\n",
817 return TLS_GENERIC_ERROR;
820 unsigned char hash[TLS_MAX_HASH_LEN];
821 unsigned long hash_len = 0;
826 hash_index = find_hash("sha1");
830 hash_index = find_hash("sha256");
834 hash_index = find_hash("sha384");
838 hash_index = find_hash("sha512");
843 hash_index = find_hash("md5");
848 hash_memory(hash_index, message, message_len, hash, &hash_len);
850 if (hash_type == _md5_sha1) {
851 unsigned long hlen = 20;
852 hash_index = find_hash("sha1");
853 hash_memory(hash_index, message, message_len, hash+16, &hlen);
858 DEBUG_PRINT("Unsupported hash type: %i\n", hash_type);
859 return TLS_GENERIC_ERROR;
861 /* "Let z be the Ln leftmost bits of e, where Ln is the bit length of
862 * the group order n." */
863 if ((int)hash_len > curve->size) {
864 hash_len = curve->size;
866 err = ecc_sign_hash(hash, hash_len, out, outlen, NULL,
867 find_prng("sprng"), &key);
868 DEBUG_DUMP_HEX_LABEL("ECC SIGNATURE", out, *outlen);
874 static void tls_send_certificate_verify(struct TLSContext *context) {
875 struct TLSPacket *packet =
876 tls_create_packet(context, TLS_HANDSHAKE, context->version, 0);
877 /* certificate verify */
878 tls_packet_uint8(packet, 0x0F);
879 tls_packet_uint24(packet, 0);
881 unsigned char out[TLS_MAX_RSA_KEY];
882 unsigned long out_len = TLS_MAX_RSA_KEY;
884 unsigned char signing_data[TLS_MAX_HASH_SIZE + 98];
885 int signing_data_len;
887 /* first 64 bytes to 0x20 (32) */
888 memset(signing_data, 0x20, 64);
889 /* context string 33 bytes */
890 if (context->is_server) {
891 memcpy(signing_data + 64, "TLS 1.3, server CertificateVerify",
894 memcpy(signing_data + 64, "TLS 1.3, client CertificateVerify",
897 /* a single 0 byte separator */
898 signing_data[97] = 0;
899 signing_data_len = 98;
901 signing_data_len += tls_get_hash(context, signing_data + 98);
902 DEBUG_DUMP_HEX_LABEL("verify data", signing_data, signing_data_len);
903 int hash_algorithm = sha256;
904 if (tls_is_ecdsa(context)) {
905 switch (context->ec_private_key->ec_algorithm) {
907 /* secp256r1 + sha256 */
908 tls_packet_uint16(packet, 0x0403);
911 /* secp384r1 + sha384 */
912 tls_packet_uint16(packet, 0x0503);
913 hash_algorithm = sha384;
916 /* secp521r1 + sha512 */
917 tls_packet_uint16(packet, 0x0603);
918 hash_algorithm = sha512;
921 DEBUG_PRINT("UNSUPPORTED CURVE (SIGNING)\n");
927 tls_packet_uint16(packet, 0x0804);
932 if (tls_is_ecdsa(context)) {
933 if (sign_ecdsa(context, hash_algorithm, signing_data,
934 signing_data_len, out, &out_len) == 1)
937 ("ECDSA signing OK! (ECDSA, length %lu)\n",
939 tls_packet_uint16(packet, out_len);
940 tls_packet_append(packet, out, out_len);
941 packet_size += out_len + 2;
943 } else if (sign_rsa(context, hash_algorithm, signing_data,
944 signing_data_len, out, &out_len) == 1) {
945 DEBUG_PRINT("RSA signing OK! (length %lu)\n", out_len);
946 tls_packet_uint16(packet, out_len);
947 tls_packet_append(packet, out, out_len);
948 packet_size += out_len + 2;
951 tls_set_packet_length(packet, packet_size);
953 tls_packet_update(packet);
954 tls_queue_packet(packet);
958 static int tls_ecc_import_pk(const unsigned char *public_key,
959 int public_len, ecc_key * key,
960 const ltc_ecc_set_type * dp) {
963 if (!key || !ltc_mp.name) {
967 key->type = PK_PUBLIC;
969 if (mp_init_multi(&key->pubkey.x, &key->pubkey.y, &key->pubkey.z,
970 &key->k, NULL) != CRYPT_OK) {
974 if (public_len && !public_key[0]) {
978 if ((err = mp_read_unsigned_bin(key->pubkey.x,
979 (unsigned char *) public_key + 1,
980 (public_len - 1) >> 1)) != CRYPT_OK) {
981 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
986 if ((err = mp_read_unsigned_bin(key->pubkey.y,
987 (unsigned char *) public_key + 1 +
988 ((public_len - 1) >> 1),
989 (public_len - 1) >> 1)) != CRYPT_OK) {
990 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
999 if ((err = mp_set(key->pubkey.z, 1)) != CRYPT_OK) {
1000 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
1005 /* is it a point on the curve? */
1006 if ((err = tls_is_point(key)) != CRYPT_OK) {
1007 DEBUG_PRINT("KEY IS NOT ON CURVE\n");
1008 mp_clear_multi(key->pubkey.x, key->pubkey.y, key->pubkey.z,
1017 static int tls_verify_ecdsa(struct TLSContext *context,
1018 unsigned int hash_type,
1019 const unsigned char *buffer,
1021 const unsigned char *message,
1022 unsigned int message_len,
1023 const struct ECCCurveParameters *curve_hint)
1029 curve_hint = context->curve;
1033 return TLS_GENERIC_ERROR;
1036 struct TLSCertificate **cert;
1039 if (context->is_server) {
1040 cert = context->client_certificates;
1041 count = context->client_certificates_count;
1043 cert = context->certificates;
1044 count = context->certificates_count;
1047 if (count == 0 || !cert || !cert[0] || !cert[0]->pk ||
1049 return TLS_GENERIC_ERROR;
1052 err = tls_ecc_import_pk(cert[0]->pk, cert[0]->pk_len, &key,
1053 (ltc_ecc_set_type *)&curve_hint->dp);
1056 DEBUG_PRINT("Error importing ECC certificate (code: %i)", err);
1057 return TLS_GENERIC_ERROR;
1061 unsigned char hash[TLS_MAX_HASH_LEN];
1062 unsigned long hash_len = 0;
1064 switch (hash_type) {
1066 hash_idx = find_hash("md5");
1070 hash_idx = find_hash("sha1");
1074 hash_idx = find_hash("sha256");
1078 hash_idx = find_hash("sha384");
1082 hash_idx = find_hash("sha512");
1087 err = hash_memory(hash_idx, message, message_len, hash, &hash_len);
1089 if (hash_idx < 0 || err) {
1090 DEBUG_PRINT("Unsupported hash type: %i\n", hash_type);
1091 return TLS_GENERIC_ERROR;
1095 err = ecc_verify_hash(buffer, len, hash, hash_len, &ecc_stat, &key);
1103 static void prf_helper(int hash_idx, unsigned long dlen,
1104 unsigned char *output, unsigned int outlen,
1105 const unsigned char *secret,
1106 const unsigned int secret_len,
1107 const unsigned char *label,
1108 unsigned int label_len, unsigned char *seed,
1109 unsigned int seed_len, unsigned char *seed_b,
1110 unsigned int seed_b_len) {
1111 unsigned char digest_out0[TLS_MAX_HASH_LEN];
1112 unsigned char digest_out1[TLS_MAX_HASH_LEN];
1116 hmac_init(&hmac, hash_idx, secret, secret_len);
1117 hmac_process(&hmac, label, label_len);
1119 hmac_process(&hmac, seed, seed_len);
1120 if (seed_b && seed_b_len) {
1121 hmac_process(&hmac, seed_b, seed_b_len);
1123 hmac_done(&hmac, digest_out0, &dlen);
1126 hmac_init(&hmac, hash_idx, secret, secret_len);
1127 hmac_process(&hmac, digest_out0, dlen);
1128 hmac_process(&hmac, label, label_len);
1129 hmac_process(&hmac, seed, seed_len);
1130 if (seed_b && seed_b_len) {
1131 hmac_process(&hmac, seed_b, seed_b_len);
1133 hmac_done(&hmac, digest_out1, &dlen);
1135 unsigned int copylen = outlen;
1136 if (copylen > dlen) {
1140 for (i = 0; i < copylen; i++) {
1141 output[idx++] ^= digest_out1[i];
1149 hmac_init(&hmac, hash_idx, secret, secret_len);
1150 hmac_process(&hmac, digest_out0, dlen);
1151 hmac_done(&hmac, digest_out0, &dlen);
1155 static void tls_prf(struct TLSContext *context,
1156 unsigned char *output, unsigned int outlen,
1157 const unsigned char *secret,
1158 const unsigned int secret_len,
1159 const unsigned char *label, unsigned int label_len,
1160 unsigned char *seed, unsigned int seed_len,
1161 unsigned char *seed_b, unsigned int seed_b_len) {
1162 if (!secret || !secret_len) {
1163 DEBUG_PRINT("NULL SECRET\n");
1167 /* TODO I don't think this is right, wouldn't use md5 for tls v1.3 */
1168 if (context->version != TLS_V12) {
1169 int md5_hash_idx = find_hash("md5");
1170 int sha1_hash_idx = find_hash("sha1");
1171 int half_secret = (secret_len + 1) / 2;
1173 memset(output, 0, outlen);
1174 prf_helper(md5_hash_idx, 16, output, outlen, secret,
1175 half_secret, label, label_len, seed, seed_len,
1176 seed_b, seed_b_len);
1177 prf_helper(sha1_hash_idx, 20, output, outlen, secret +
1178 (secret_len - half_secret), secret_len -
1179 half_secret, label, label_len, seed, seed_len,
1180 seed_b, seed_b_len);
1183 unsigned char digest_out0[TLS_MAX_HASH_LEN];
1184 unsigned char digest_out1[TLS_MAX_HASH_LEN];
1185 unsigned long dlen = 32;
1187 unsigned int mac_length = tls_mac_length(context);
1189 if (mac_length == TLS_SHA384_MAC_SIZE) {
1190 hash_idx = find_hash("sha384");
1193 hash_idx = find_hash("sha256");
1199 hmac_init(&hmac, hash_idx, secret, secret_len);
1200 hmac_process(&hmac, label, label_len);
1201 hmac_process(&hmac, seed, seed_len);
1202 if (seed_b && seed_b_len) {
1203 hmac_process(&hmac, seed_b, seed_b_len);
1205 hmac_done(&hmac, digest_out0, &dlen);
1209 hmac_init(&hmac, hash_idx, secret, secret_len);
1210 hmac_process(&hmac, digest_out0, dlen);
1211 hmac_process(&hmac, label, label_len);
1212 hmac_process(&hmac, seed, seed_len);
1213 if (seed_b && seed_b_len) {
1214 hmac_process(&hmac, seed_b, seed_b_len);
1216 hmac_done(&hmac, digest_out1, &dlen);
1218 unsigned int copylen = outlen;
1219 if (copylen > dlen) {
1220 copylen = (unsigned int) dlen;
1223 for (i = 0; i < copylen; i++) {
1224 output[idx++] = digest_out1[i];
1232 hmac_init(&hmac, hash_idx, secret, secret_len);
1233 hmac_process(&hmac, digest_out0, dlen);
1234 hmac_done(&hmac, digest_out0, &dlen);
1239 static void tls_send_finished(struct TLSContext *context) {
1240 struct TLSPacket *packet =
1241 tls_create_packet(context, TLS_HANDSHAKE, context->version,
1242 TLS_MIN_FINISHED_OPAQUE_LEN + 64);
1243 tls_packet_uint8(packet, 0x14);
1245 if (context->tlsver == TLS_VERSION13) {
1246 tls_packet_uint24(packet, tls_mac_length(context));
1248 tls_packet_uint24(packet, TLS_MIN_FINISHED_OPAQUE_LEN);
1252 unsigned char hash[TLS_MAX_HASH_SIZE];
1253 unsigned long out_size = TLS_MIN_FINISHED_OPAQUE_LEN;
1254 unsigned char out[TLS_MAX_HASH_SIZE];
1255 unsigned int hash_len;
1257 int context_is_v13 = 0;
1259 if (packet->context->tlsver == TLS_VERSION13) {
1263 /* server verifies client's message */
1264 if (context->is_server) {
1265 if (context_is_v13) {
1266 hash_len = tls_get_hash(context, hash);
1267 if (!context->finished_key || !hash_len) {
1269 ("NO FINISHED KEY COMPUTED OR NO HANDSHAKE HASH\n");
1271 /* TODO probably need to terminate */
1272 tls_destroy_packet(packet);
1276 DEBUG_DUMP_HEX_LABEL("HS HASH", hash, hash_len);
1277 DEBUG_DUMP_HEX_LABEL("HS FINISH",
1278 context->finished_key,
1281 out_size = hash_len;
1283 hmac_init(&hmac, tls_get_hash_idx(context),
1284 context->finished_key, hash_len);
1285 hmac_process(&hmac, hash, hash_len);
1286 hmac_done(&hmac, out, &out_size);
1288 hash_len = tls_done_hash(context, hash);
1289 tls_prf(context, out,
1290 TLS_MIN_FINISHED_OPAQUE_LEN,
1291 context->master_key,
1292 context->master_key_len,
1294 "server finished", 15, hash,
1296 tls_destroy_hash(context);
1300 hash_len = tls_get_hash(context, hash);
1301 tls_prf(context, out, TLS_MIN_FINISHED_OPAQUE_LEN,
1302 context->master_key,
1303 context->master_key_len,
1304 (unsigned char *) "client finished", 15,
1305 hash, hash_len, NULL, 0);
1308 tls_packet_append(packet, out, out_size);
1309 tls_packet_update(packet);
1310 DEBUG_DUMP_HEX_LABEL("VERIFY DATA", out, out_size);
1311 tls_queue_packet(packet);
1315 static int tls_key_length(struct TLSContext *context) {
1316 switch (context->cipher) {
1317 case TLS_RSA_WITH_AES_128_CBC_SHA:
1318 case TLS_RSA_WITH_AES_128_CBC_SHA256:
1319 case TLS_RSA_WITH_AES_128_GCM_SHA256:
1320 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
1321 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
1322 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
1323 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
1324 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
1325 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
1326 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
1327 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
1328 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
1329 case TLS_AES_128_GCM_SHA256:
1331 case TLS_RSA_WITH_AES_256_CBC_SHA:
1332 case TLS_RSA_WITH_AES_256_CBC_SHA256:
1333 case TLS_RSA_WITH_AES_256_GCM_SHA384:
1334 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
1335 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
1336 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
1337 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
1338 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
1339 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
1340 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
1341 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
1342 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
1343 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
1344 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
1345 case TLS_AES_256_GCM_SHA384:
1346 case TLS_CHACHA20_POLY1305_SHA256:
1352 /* 0 is none, 1 is GCM?, 2 is chacha */
1353 int tls_is_aead(struct TLSContext *context) {
1354 switch (context->cipher) {
1355 case TLS_RSA_WITH_AES_128_GCM_SHA256:
1356 case TLS_RSA_WITH_AES_256_GCM_SHA384:
1357 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
1358 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
1359 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
1360 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
1361 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
1362 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
1363 case TLS_AES_128_GCM_SHA256:
1364 case TLS_AES_256_GCM_SHA384:
1366 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
1367 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
1368 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
1369 case TLS_CHACHA20_POLY1305_SHA256:
1375 int tls_mac_length(struct TLSContext *context) {
1376 switch (context->cipher) {
1377 case TLS_RSA_WITH_AES_128_CBC_SHA:
1378 case TLS_RSA_WITH_AES_256_CBC_SHA:
1379 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
1380 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
1381 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
1382 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
1383 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
1384 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
1385 return TLS_SHA1_MAC_SIZE;
1386 case TLS_RSA_WITH_AES_128_CBC_SHA256:
1387 case TLS_RSA_WITH_AES_256_CBC_SHA256:
1388 case TLS_RSA_WITH_AES_128_GCM_SHA256:
1389 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
1390 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
1391 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
1392 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
1393 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
1394 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
1395 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
1396 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
1397 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
1398 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
1399 case TLS_AES_128_GCM_SHA256:
1400 case TLS_CHACHA20_POLY1305_SHA256:
1401 case TLS_AES_128_CCM_SHA256:
1402 case TLS_AES_128_CCM_8_SHA256:
1403 return TLS_SHA256_MAC_SIZE;
1404 case TLS_RSA_WITH_AES_256_GCM_SHA384:
1405 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
1406 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
1407 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
1408 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
1409 case TLS_AES_256_GCM_SHA384:
1410 return TLS_SHA384_MAC_SIZE;
1415 int _private_tls13_key(struct TLSContext *context, int handshake) {
1416 int key_length = tls_key_length(context);
1417 int mac_length = tls_mac_length(context);
1419 if (!context->premaster_key || !context->premaster_key_len) {
1423 if (!key_length || !mac_length) {
1425 ("KEY EXPANSION FAILED, KEY LENGTH: %i, MAC LENGTH: %i\n",
1426 key_length, mac_length);
1430 unsigned char *clientkey = NULL;
1431 unsigned char *serverkey = NULL;
1432 unsigned char *clientiv = NULL;
1433 unsigned char *serveriv = NULL;
1434 int is_aead = tls_is_aead(context);
1436 unsigned char local_keybuffer[TLS_V13_MAX_KEY_SIZE];
1437 unsigned char local_ivbuffer[TLS_V13_MAX_IV_SIZE];
1438 unsigned char remote_keybuffer[TLS_V13_MAX_KEY_SIZE];
1439 unsigned char remote_ivbuffer[TLS_V13_MAX_IV_SIZE];
1441 unsigned char prk[TLS_MAX_HASH_SIZE];
1442 unsigned char hash[TLS_MAX_HASH_SIZE];
1443 static unsigned char earlysecret[TLS_MAX_HASH_SIZE];
1445 const char *server_key = "s ap traffic";
1446 const char *client_key = "c ap traffic";
1448 server_key = "s hs traffic";
1449 client_key = "c hs traffic";
1452 unsigned char salt[TLS_MAX_HASH_SIZE];
1455 /* TODO what is the point of this ? */
1456 if (mac_length == TLS_SHA384_MAC_SIZE) {
1458 sha384_done(&md, hash);
1461 sha256_done(&md, hash);
1463 /* extract secret "early" */
1464 if (context->master_key && context->master_key_len && !handshake) {
1465 DEBUG_DUMP_HEX_LABEL("USING PREVIOUS SECRET",
1466 context->master_key,
1467 context->master_key_len);
1468 tls_hkdf_expand_label(mac_length, salt, mac_length,
1469 context->master_key, context->master_key_len,
1470 "derived", 7, hash, mac_length);
1471 DEBUG_DUMP_HEX_LABEL("salt", salt, mac_length);
1472 tls_hkdf_extract(mac_length, prk, mac_length, salt, mac_length,
1473 earlysecret, mac_length);
1475 tls_hkdf_extract(mac_length, prk, mac_length, NULL, 0,
1476 earlysecret, mac_length);
1477 /* derive secret for handshake "tls13 derived": */
1478 DEBUG_DUMP_HEX_LABEL("null hash", hash, mac_length);
1479 tls_hkdf_expand_label(mac_length, salt, mac_length, prk,
1480 mac_length, "derived", 7, hash, mac_length);
1481 /* extract secret "handshake": */
1482 DEBUG_DUMP_HEX_LABEL("salt", salt, mac_length);
1483 tls_hkdf_extract(mac_length, prk, mac_length,
1485 context->premaster_key,
1486 context->premaster_key_len);
1490 DEBUG_PRINT("KEY EXPANSION FAILED, NON AEAD CIPHER\n");
1494 unsigned char secret[TLS_MAX_MAC_SIZE];
1495 unsigned char hs_secret[TLS_MAX_HASH_SIZE];
1499 hash_size = tls_get_hash(context, hash);
1501 hash_size = tls_done_hash(context, hash);
1504 DEBUG_DUMP_HEX_LABEL("messages hash", hash, hash_size);
1506 if (context->is_server) {
1507 tls_hkdf_expand_label(mac_length, hs_secret, mac_length, prk,
1508 mac_length, server_key, 12, context->
1509 server_finished_hash ? context->
1510 server_finished_hash : hash, hash_size);
1511 DEBUG_DUMP_HEX_LABEL(server_key, hs_secret, mac_length);
1512 serverkey = local_keybuffer;
1513 serveriv = local_ivbuffer;
1514 clientkey = remote_keybuffer;
1515 clientiv = remote_ivbuffer;
1517 tls_hkdf_expand_label(mac_length, hs_secret,
1518 mac_length, prk, mac_length,
1521 server_finished_hash ?
1523 server_finished_hash : hash,
1525 serverkey = remote_keybuffer;
1526 serveriv = remote_ivbuffer;
1527 clientkey = local_keybuffer;
1528 clientiv = local_ivbuffer;
1531 int iv_length = TLS_13_AES_GCM_IV_LENGTH;
1533 iv_length = TLS_CHACHA20_IV_LENGTH;
1536 tls_hkdf_expand_label(mac_length, local_keybuffer, key_length,
1537 hs_secret, mac_length, "key", 3, NULL, 0);
1538 tls_hkdf_expand_label(mac_length, local_ivbuffer, iv_length, hs_secret,
1539 mac_length, "iv", 2, NULL, 0);
1541 tls_hkdf_expand_label(mac_length, secret,
1542 mac_length, prk, mac_length,
1543 context->is_server ? client_key : server_key,
1545 context->server_finished_hash ?
1546 context->server_finished_hash :
1550 tls_hkdf_expand_label(mac_length, remote_keybuffer, key_length, secret,
1551 mac_length, "key", 3, NULL, 0);
1552 tls_hkdf_expand_label(mac_length, remote_ivbuffer, iv_length, secret,
1553 mac_length, "iv", 2, NULL, 0);
1555 DEBUG_DUMP_HEX_LABEL("CLIENT KEY", clientkey, key_length);
1556 DEBUG_DUMP_HEX_LABEL("CLIENT IV", clientiv, iv_length);
1557 DEBUG_DUMP_HEX_LABEL("SERVER KEY", serverkey, key_length);
1558 DEBUG_DUMP_HEX_LABEL("SERVER IV", serveriv, iv_length);
1559 free(context->finished_key);
1560 free(context->remote_finished_key);
1563 context->finished_key = malloc(mac_length);
1564 context->remote_finished_key = malloc(mac_length);
1566 if (context->finished_key) {
1567 tls_hkdf_expand_label(mac_length,
1568 context->finished_key, mac_length,
1569 hs_secret, mac_length, "finished", 8,
1571 DEBUG_DUMP_HEX_LABEL("FINISHED", context->finished_key,
1575 if (context->remote_finished_key) {
1576 tls_hkdf_expand_label(mac_length,
1577 context->remote_finished_key,
1578 mac_length, secret, mac_length,
1579 "finished", 8, NULL, 0);
1580 DEBUG_DUMP_HEX_LABEL("FINISHED", context->finished_key,
1584 context->finished_key = NULL;
1585 context->remote_finished_key = NULL;
1586 free(context->server_finished_hash);
1587 context->server_finished_hash = NULL;
1590 if (context->is_server) {
1592 memcpy(context->crypto.ctx_remote_mac.remote_nonce,
1593 clientiv, iv_length);
1594 memcpy(context->crypto.ctx_local_mac.local_nonce,
1595 serveriv, iv_length);
1596 } else if (is_aead) {
1597 memcpy(context->crypto.ctx_remote_mac.remote_iv,
1598 clientiv, iv_length);
1599 memcpy(context->crypto.ctx_local_mac.local_iv,
1600 serveriv, iv_length);
1602 if (tls_crypto_create(context, key_length,
1603 serverkey, serveriv, clientkey,
1609 memcpy(context->crypto.ctx_local_mac.local_nonce,
1610 clientiv, iv_length);
1611 memcpy(context->crypto.ctx_remote_mac.remote_nonce,
1612 serveriv, iv_length);
1613 } else if (is_aead) {
1614 memcpy(context->crypto.ctx_local_mac.local_iv,
1615 clientiv, iv_length);
1616 memcpy(context->crypto.ctx_remote_mac.remote_iv,
1617 serveriv, iv_length);
1620 if (tls_crypto_create(context, key_length,
1621 clientkey, clientiv, serverkey,
1627 context->crypto.created = 1 + is_aead;
1629 free(context->master_key);
1630 context->master_key = malloc(mac_length);
1631 if (context->master_key) {
1632 memcpy(context->master_key, prk, mac_length);
1633 context->master_key_len = mac_length;
1635 context->local_sequence_number = 0;
1636 context->remote_sequence_number = 0;
1639 * extract client_mac_key(mac_key_length)
1640 * extract server_mac_key(mac_key_length)
1641 * extract client_key(enc_key_length)
1642 * extract server_key(enc_key_length)
1643 * extract client_iv(fixed_iv_lengh)
1644 * extract server_iv(fixed_iv_length)
1649 static int tls_expand_key(struct TLSContext *context) {
1650 unsigned char key[TLS_MAX_KEY_EXPANSION_SIZE];
1651 if (context->tlsver == TLS_VERSION13) {
1655 if (!context->master_key || !context->master_key_len) {
1659 int key_length = tls_key_length(context);
1660 int mac_length = tls_mac_length(context);
1662 if (!key_length || !mac_length) {
1664 ("KEY EXPANSION FAILED, KEY LENGTH: %i, MAC LENGTH: %i\n",
1665 key_length, mac_length);
1668 unsigned char *clientkey = NULL;
1669 unsigned char *serverkey = NULL;
1670 unsigned char *clientiv = NULL;
1671 unsigned char *serveriv = NULL;
1672 int iv_length = TLS_AES_IV_LENGTH;
1673 int is_aead = tls_is_aead(context);
1675 if (context->is_server) {
1676 tls_prf(context, key, sizeof(key),
1677 context->master_key, context->master_key_len,
1678 (unsigned char *) "key expansion", 13,
1679 context->local_random, TLS_SERVER_RANDOM_SIZE,
1680 context->remote_random,
1681 TLS_CLIENT_RANDOM_SIZE);
1683 tls_prf(context, key, sizeof(key),
1684 context->master_key,
1685 context->master_key_len,
1686 (unsigned char *) "key expansion", 13,
1687 context->remote_random,
1688 TLS_SERVER_RANDOM_SIZE,
1689 context->local_random,
1690 TLS_CLIENT_RANDOM_SIZE);
1693 DEBUG_DUMP_HEX_LABEL("LOCAL RANDOM ", context->local_random,
1694 TLS_SERVER_RANDOM_SIZE);
1695 DEBUG_DUMP_HEX_LABEL("REMOTE RANDOM", context->remote_random,
1696 TLS_CLIENT_RANDOM_SIZE);
1697 DEBUG_PRINT("\n=========== EXPANSION ===========\n");
1698 DEBUG_DUMP_HEX(key, TLS_MAX_KEY_EXPANSION_SIZE);
1703 iv_length = TLS_CHACHA20_IV_LENGTH;
1706 iv_length = TLS_AES_GCM_IV_LENGTH;
1708 if (context->is_server) {
1709 memcpy(context->crypto.ctx_remote_mac.remote_mac,
1710 &key[pos], mac_length);
1712 memcpy(context->crypto.ctx_local_mac.local_mac,
1713 &key[pos], mac_length);
1716 memcpy(context->crypto.ctx_local_mac.local_mac,
1717 &key[pos], mac_length);
1719 memcpy(context->crypto.ctx_remote_mac.remote_mac,
1720 &key[pos], mac_length);
1726 clientkey = &key[pos];
1728 serverkey = &key[pos];
1730 clientiv = &key[pos];
1732 serveriv = &key[pos];
1734 DEBUG_PRINT("EXPANSION %i/%i\n", (int) pos,
1735 (int) TLS_MAX_KEY_EXPANSION_SIZE);
1736 DEBUG_DUMP_HEX_LABEL("CLIENT KEY", clientkey, key_length);
1737 DEBUG_DUMP_HEX_LABEL("CLIENT IV", clientiv, iv_length);
1738 DEBUG_DUMP_HEX_LABEL("CLIENT MAC KEY",
1739 context->is_server ? context->crypto.
1740 ctx_remote_mac.remote_mac : context->
1741 crypto.ctx_local_mac.local_mac,
1743 DEBUG_DUMP_HEX_LABEL("SERVER KEY", serverkey, key_length);
1744 DEBUG_DUMP_HEX_LABEL("SERVER IV", serveriv, iv_length);
1745 DEBUG_DUMP_HEX_LABEL("SERVER MAC KEY",
1746 context->is_server ? context->crypto.
1747 ctx_local_mac.local_mac : context->crypto.
1748 ctx_remote_mac.remote_mac, mac_length);
1749 if (context->is_server) {
1751 memcpy(context->crypto.ctx_remote_mac.remote_nonce,
1752 clientiv, iv_length);
1753 memcpy(context->crypto.ctx_local_mac.local_nonce,
1754 serveriv, iv_length);
1757 memcpy(context->crypto.ctx_remote_mac.
1758 remote_aead_iv, clientiv, iv_length);
1759 memcpy(context->crypto.ctx_local_mac.local_aead_iv,
1760 serveriv, iv_length);
1764 if (tls_crypto_create(context, key_length,
1765 serverkey, serveriv, clientkey,
1771 memcpy(context->crypto.ctx_local_mac.local_nonce,
1772 clientiv, iv_length);
1773 memcpy(context->crypto.ctx_remote_mac.remote_nonce,
1774 serveriv, iv_length);
1777 memcpy(context->crypto.ctx_local_mac.local_aead_iv,
1778 clientiv, iv_length);
1779 memcpy(context->crypto.ctx_remote_mac.
1780 remote_aead_iv, serveriv, iv_length);
1784 if (tls_crypto_create(context, key_length,
1785 clientkey, clientiv, serverkey,
1792 * extract client_mac_key(mac_key_length)
1793 * extract server_mac_key(mac_key_length)
1794 * extract client_key(enc_key_length)
1795 * extract server_key(enc_key_length)
1796 * extract client_iv(fixed_iv_lengh)
1797 * extract server_iv(fixed_iv_length)
1802 int tls_compute_key(struct TLSContext *context, unsigned int key_len) {
1803 if (context->tlsver == TLS_VERSION13) {
1807 if (!context->premaster_key || !context->premaster_key_len
1809 DEBUG_PRINT("CANNOT COMPUTE MASTER SECRET\n");
1813 unsigned char master_secret_label[] = "master secret";
1814 #ifdef TLS_CHECK_PREMASTER_KEY
1815 if (!tls_cipher_is_ephemeral(context)) {
1816 uint16_t version = get16(context->premaster_key);
1817 /* this check is not true for DHE/ECDHE ciphers */
1818 if (context->version > version) {
1819 DEBUG_PRINT("Mismatch protocol version 0x(%x)\n",
1825 free(context->master_key);
1826 context->master_key_len = 0;
1827 context->master_key = NULL;
1829 context->master_key = malloc(key_len);
1830 if (!context->master_key) {
1834 context->master_key_len = key_len;
1835 if (context->is_server) {
1837 context->master_key,
1838 context->master_key_len,
1839 context->premaster_key,
1840 context->premaster_key_len,
1841 master_secret_label, 13,
1842 context->remote_random,
1843 TLS_CLIENT_RANDOM_SIZE,
1844 context->local_random,
1845 TLS_SERVER_RANDOM_SIZE);
1848 context->master_key,
1849 context->master_key_len,
1850 context->premaster_key,
1851 context->premaster_key_len,
1852 master_secret_label, 13,
1853 context->local_random,
1854 TLS_CLIENT_RANDOM_SIZE,
1855 context->remote_random,
1856 TLS_SERVER_RANDOM_SIZE);
1858 free(context->premaster_key);
1859 context->premaster_key = NULL;
1860 context->premaster_key_len = 0;
1861 DEBUG_PRINT("\n=========== Master key ===========\n");
1862 DEBUG_DUMP_HEX(context->master_key,
1863 context->master_key_len);
1865 tls_expand_key(context);
1869 int _is_oid(const unsigned char *oid, const unsigned char *compare_to,
1870 int compare_to_len) {
1872 while ((oid[i]) && (i < compare_to_len)) {
1873 if (oid[i] != compare_to[i])
1881 int _is_oid2(const unsigned char *oid, const unsigned char *compare_to,
1882 int compare_to_len, int oid_len) {
1884 if (oid_len < compare_to_len) {
1885 compare_to_len = oid_len;
1888 while (i < compare_to_len) {
1889 if (oid[i] != compare_to[i]) {
1898 struct TLSCertificate *tls_create_certificate() {
1899 struct TLSCertificate zero = { 0 };
1900 struct TLSCertificate *cert = malloc(sizeof *cert);
1904 cert->not_before[0] = 0;
1905 cert->not_after[0] = 0;
1910 int tls_certificate_valid_subject_name(const unsigned char *cert_subject,
1911 const char *subject) {
1912 /* no subjects ... */
1913 if ((!cert_subject || !cert_subject[0]) && (!subject || !subject[0])) {
1917 if (!subject || !subject[0]) {
1918 return bad_certificate;
1921 if (!cert_subject || !cert_subject[0]) {
1922 return bad_certificate;
1926 if (!strcmp((const char *) cert_subject, subject)) {
1930 const char *wildcard = strchr((const char *) cert_subject, '*');
1932 /* 6.4.3 (1) The client SHOULD NOT attempt to match a presented
1933 * identifier in which the wildcard character comprises a label
1934 * other than the left-most label
1939 * subject is [something*] .. invalid
1941 return bad_certificate;
1944 const char *match = strstr(subject, wildcard);
1945 if ((!match) && (wildcard[0] == '.')) {
1946 /* check *.domain.com against domain.com */
1948 if (!strcasecmp(subject, wildcard))
1952 unsigned long offset = (unsigned long) match -
1953 (unsigned long) subject;
1955 /* check for foo.*.domain.com against *.domain.com (invalid) */
1956 if (memchr(subject, '.', offset))
1957 return bad_certificate;
1959 /* check if exact match */
1960 if (!strcasecmp(match, wildcard)) {
1966 return bad_certificate;
1969 int tls_certificate_valid_subject(struct TLSCertificate *cert,
1970 const char *subject) {
1973 return certificate_unknown;
1976 int err = tls_certificate_valid_subject_name(cert->subject, subject);
1977 if (err && cert->san) {
1978 for (i = 0; i < cert->san_length; i++) {
1979 err = tls_certificate_valid_subject_name(cert->san[i],
1989 int tls_certificate_is_valid(struct TLSCertificate *cert) {
1991 return certificate_unknown;
1994 char ts[16]; /* YYYYMMDDHHMMSSZ */
1995 time_t t = time(NULL);
1996 struct tm *utc = gmtime(&t);
1999 strftime(ts, sizeof ts, "%Y%m%d%H%M%SZ", utc);
2001 if (strcmp(cert->not_before, ts) > 0) {
2003 ("Certificate is not yet valid, now: %s (validity: %s - %s)\n",
2004 ts, cert->not_before, cert->not_after);
2005 return certificate_expired;
2008 if (strcmp(cert->not_after, ts) < 0) {
2010 ("Expired certificate, now: %s (validity: %s - %s)\n",
2011 ts, cert->not_before, cert->not_after);
2012 return certificate_expired;
2014 DEBUG_PRINT("Valid certificate, now: %s (validity: %s - %s)\n",
2015 ts, cert->not_before,
2021 void tls_certificate_set_copy(unsigned char **member,
2022 const unsigned char *val, int len) {
2030 *member = malloc(len + 1);
2032 memcpy(*member, val, len);
2040 void tls_certificate_set_copy_date(unsigned char *member,
2041 const unsigned char *val, int len) {
2044 if (val[0] >= '5') {
2051 memcpy(member + 2, val, len);
2058 void tls_certificate_set_key(struct TLSCertificate *cert,
2059 const unsigned char *val, int len) {
2060 if (!val[0] && len % 2) {
2064 tls_certificate_set_copy(&cert->pk, val, len);
2070 void tls_certificate_set_priv(struct TLSCertificate *cert,
2071 const unsigned char *val, int len) {
2072 tls_certificate_set_copy(&cert->priv, val, len);
2074 cert->priv_len = len;
2078 void tls_certificate_set_sign_key(struct TLSCertificate *cert,
2079 const unsigned char *val, int len) {
2080 if (!val[0] && len % 2) {
2084 tls_certificate_set_copy(&cert->sign_key, val, len);
2085 if (cert->sign_key) {
2086 cert->sign_len = len;
2090 void tls_certificate_set_exponent(struct TLSCertificate *cert,
2091 const unsigned char *val, int len) {
2092 tls_certificate_set_copy(&cert->exponent, val, len);
2093 if (cert->exponent) {
2094 cert->exponent_len = len;
2098 void tls_certificate_set_serial(struct TLSCertificate *cert,
2099 const unsigned char *val, int len) {
2100 tls_certificate_set_copy(&cert->serial_number, val, len);
2101 if (cert->serial_number) {
2102 cert->serial_len = len;
2106 void tls_certificate_set_algorithm(unsigned int *algorithm,
2107 const unsigned char *val, int len) {
2108 if (len == 7 && _is_oid(val, TLS_EC_PUBLIC_KEY_OID, 7)) {
2109 *algorithm = TLS_EC_PUBLIC_KEY;
2114 if (_is_oid(val, TLS_EC_prime192v1_OID, len)) {
2115 *algorithm = TLS_EC_prime192v1;
2118 if (_is_oid(val, TLS_EC_prime192v2_OID, len)) {
2119 *algorithm = TLS_EC_prime192v2;
2122 if (_is_oid(val, TLS_EC_prime192v3_OID, len)) {
2123 *algorithm = TLS_EC_prime192v3;
2126 if (_is_oid(val, TLS_EC_prime239v1_OID, len)) {
2127 *algorithm = TLS_EC_prime239v1;
2130 if (_is_oid(val, TLS_EC_prime239v2_OID, len)) {
2131 *algorithm = TLS_EC_prime239v2;
2134 if (_is_oid(val, TLS_EC_prime239v3_OID, len)) {
2135 *algorithm = TLS_EC_prime239v3;
2138 if (_is_oid(val, TLS_EC_prime256v1_OID, len)) {
2139 *algorithm = TLS_EC_prime256v1;
2145 (val, TLS_EC_secp224r1_OID, len,
2146 sizeof(TLS_EC_secp224r1_OID) - 1)) {
2147 *algorithm = TLS_EC_secp224r1;
2151 (val, TLS_EC_secp384r1_OID, len,
2152 sizeof(TLS_EC_secp384r1_OID) - 1)) {
2153 *algorithm = TLS_EC_secp384r1;
2157 (val, TLS_EC_secp521r1_OID, len,
2158 sizeof(TLS_EC_secp521r1_OID) - 1)) {
2159 *algorithm = TLS_EC_secp521r1;
2167 if (_is_oid(val, TLS_RSA_SIGN_SHA256_OID, 9)) {
2168 *algorithm = TLS_RSA_SIGN_SHA256;
2172 if (_is_oid(val, TLS_RSA_SIGN_RSA_OID, 9)) {
2173 *algorithm = TLS_RSA_SIGN_RSA;
2177 if (_is_oid(val, TLS_RSA_SIGN_SHA1_OID, 9)) {
2178 *algorithm = TLS_RSA_SIGN_SHA1;
2182 if (_is_oid(val, TLS_RSA_SIGN_SHA512_OID, 9)) {
2183 *algorithm = TLS_RSA_SIGN_SHA512;
2187 if (_is_oid(val, TLS_RSA_SIGN_SHA384_OID, 9)) {
2188 *algorithm = TLS_RSA_SIGN_SHA384;
2192 if (_is_oid(val, TLS_RSA_SIGN_MD5_OID, 9)) {
2193 *algorithm = TLS_RSA_SIGN_MD5;
2198 void tls_destroy_certificate(struct TLSCertificate *cert) {
2201 free(cert->exponent);
2203 free(cert->issuer_country);
2204 free(cert->issuer_state);
2205 free(cert->issuer_location);
2206 free(cert->issuer_entity);
2207 free(cert->issuer_subject);
2208 free(cert->country);
2210 free(cert->location);
2211 free(cert->subject);
2212 for (i = 0; i < cert->san_length; i++) {
2217 free(cert->serial_number);
2219 cert->not_before[0] = 0;
2220 cert->not_after[0] = 0;
2221 free(cert->sign_key);
2223 free(cert->der_bytes);
2225 free(cert->fingerprint);
2230 struct TLSPacket *tls_create_packet(struct TLSContext *context,
2232 unsigned short version,
2233 int payload_size_hint) {
2234 struct TLSPacket *packet = malloc(sizeof *packet);
2239 if (payload_size_hint > 0) {
2240 packet->size = payload_size_hint + 10;
2242 packet->size = TLS_BLOB_INCREMENT;
2244 packet->buf = malloc(packet->size);
2245 memset(packet->buf, 0, packet->size);
2246 packet->context = context;
2252 packet->payload_pos = 6;
2253 packet->len = packet->payload_pos - 1;
2257 packet->buf[0] = type;
2259 /* big endian protocol version */
2260 packet->buf[1] = version >> 8;
2261 packet->buf[2] = version & 0xff;
2262 if (version == TLS_V13) {
2263 packet->buf[2] = 0x04;
2269 void tls_destroy_packet(struct TLSPacket *packet) {
2278 int tls_crypto_create(struct TLSContext *context, int key_length,
2279 unsigned char *localkey,
2280 unsigned char *localiv,
2281 unsigned char *remotekey,
2282 unsigned char *remoteiv) {
2283 if (context->crypto.created) {
2284 if (context->crypto.created == 1) {
2285 cbc_done(&context->crypto.ctx_remote.aes_remote);
2286 cbc_done(&context->crypto.ctx_local.aes_local);
2288 if (context->crypto.created == 2) {
2289 unsigned char dummy_buffer[32];
2290 unsigned long tag_len = 0;
2291 gcm_done(&context->crypto.ctx_remote.
2292 aes_gcm_remote, dummy_buffer,
2294 gcm_done(&context->crypto.ctx_local.
2295 aes_gcm_local, dummy_buffer,
2299 context->crypto.created = 0;
2301 int is_aead = tls_is_aead(context);
2302 int cipherID = find_cipher("aes");
2303 DEBUG_PRINT("Using cipher ID: %x\n", (int) context->cipher);
2305 unsigned int counter = 1;
2307 chacha_keysetup(&context->crypto.ctx_local.chacha_local,
2308 localkey, key_length * 8);
2309 chacha_ivsetup_96bitnonce(&context->crypto.ctx_local.
2310 chacha_local, localiv,
2311 (unsigned char *) &counter);
2313 chacha_keysetup(&context->crypto.ctx_remote.chacha_remote,
2314 remotekey, key_length * 8);
2315 chacha_ivsetup_96bitnonce(&context->crypto.ctx_remote.
2316 chacha_remote, remoteiv,
2317 (unsigned char *) &counter);
2319 context->crypto.created = 3;
2323 gcm_init(&context->crypto.ctx_local.aes_gcm_local,
2324 cipherID, localkey, key_length);
2326 gcm_init(&context->crypto.ctx_remote.aes_gcm_remote,
2327 cipherID, remotekey, key_length);
2330 return TLS_GENERIC_ERROR;
2332 context->crypto.created = 2;
2335 cbc_start(cipherID, localiv, localkey, key_length, 0,
2336 &context->crypto.ctx_local.aes_local);
2338 cbc_start(cipherID, remoteiv, remotekey, key_length, 0,
2339 &context->crypto.ctx_remote.aes_remote);
2342 return TLS_GENERIC_ERROR;
2344 context->crypto.created = 1;
2350 static void tls_crypto_done(struct TLSContext *context) {
2351 unsigned char dummy_buffer[32];
2352 unsigned long tag_len = 0;
2354 switch (context->crypto.created) {
2356 cbc_done(&context->crypto.ctx_remote.aes_remote);
2357 cbc_done(&context->crypto.ctx_local.aes_local);
2360 gcm_done(&context->crypto.ctx_remote.aes_gcm_remote,
2361 dummy_buffer, &tag_len);
2362 gcm_done(&context->crypto.ctx_local.aes_gcm_local,
2363 dummy_buffer, &tag_len);
2366 context->crypto.created = 0;
2369 int tls_packet_append(struct TLSPacket *packet, const unsigned char *buf,
2373 if (!packet || packet->broken) {
2381 unsigned int new_len = packet->len + len;
2383 if (new_len > packet->size) {
2384 packet->size = (new_len / TLS_BLOB_INCREMENT + 1) *
2386 new = TLS_REALLOC(packet->buf, packet->size);
2397 memcpy(packet->buf + packet->len, buf, len);
2398 packet->len = new_len;
2402 int tls_packet_uint8(struct TLSPacket *packet, unsigned char i) {
2403 return tls_packet_append(packet, &i, 1);
2406 int tls_packet_uint16(struct TLSPacket *packet, unsigned short i) {
2407 unsigned short ni = htons(i);
2408 return tls_packet_append(packet, (unsigned char *) &ni, 2);
2411 int tls_packet_uint32(struct TLSPacket *packet, unsigned int i) {
2412 unsigned int ni = htonl(i);
2413 return tls_packet_append(packet, (unsigned char *) &ni, 4);
2416 int tls_packet_uint24(struct TLSPacket *packet, unsigned int i) {
2417 unsigned char buf[3];
2418 buf[0] = (i >> 16) & 0xff;
2419 buf[1] = (i >> 8) & 0xff;
2420 buf[2] = (i >> 0) & 0xff;
2422 return tls_packet_append(packet, buf, 3);
2425 int tls_random(unsigned char *key, int len) {
2427 for (int i = 0; i < len; i++) {
2428 unsigned int v = arc4random() % 0x100;
2433 /* TODO use open and read */
2434 FILE *fp = fopen("/dev/urandom", "r");
2436 int key_len = fread(key, 1, len, fp);
2445 int tls_established(struct TLSContext *context) {
2446 return context && context->connection_status == TLS_CONNECTED;
2449 void tls_read_clear(struct TLSContext *context) {
2451 tls_buffer_free(&context->application_buffer);
2455 struct TLSContext *tls_create_context(int is_server, unsigned short version) {
2456 struct TLSContext zero = {0};
2458 struct TLSContext *context = 0;
2460 if (version == TLS_V13 && !is_server) {
2461 /* TLS 1.3 clients not supported */
2469 context = malloc(sizeof *context);
2475 ver = version - 0x0201;
2479 context->is_server = is_server;
2480 context->version = version;
2481 context->tlsver = ver;
2482 context->hs_index = -1;
2483 /* set up output buffer */
2484 tls_buffer_init(&context->output_buffer, 0);
2485 tls_buffer_init(&context->input_buffer, 0);
2486 tls_buffer_init(&context->cached_handshake, 0);
2487 tls_buffer_init(&context->application_buffer, 0);
2492 struct TLSContext *tls_accept(struct TLSContext *context) {
2493 if (!context || !context->is_server) {
2497 struct TLSContext *child = malloc(sizeof *child);
2499 memset(child, 0, sizeof(struct TLSContext));
2500 child->is_server = 1;
2501 child->is_child = 1;
2502 child->version = context->version;
2503 child->certificates = context->certificates;
2504 child->certificates_count = context->certificates_count;
2505 child->private_key = context->private_key;
2506 child->ec_private_key = context->ec_private_key;
2507 child->root_certificates = context->root_certificates;
2508 child->root_count = context->root_count;
2509 child->default_dhe_p = context->default_dhe_p;
2510 child->default_dhe_g = context->default_dhe_g;
2511 child->curve = context->curve;
2512 child->alpn = context->alpn;
2513 child->alpn_count = context->alpn_count;
2518 int tls_add_alpn(struct TLSContext *context, const char *alpn) {
2521 if (!context || !alpn || !alpn[0]
2522 || (context->is_server && context->is_child)) {
2523 return TLS_GENERIC_ERROR;
2526 int len = strlen(alpn);
2527 if (tls_alpn_contains(context, alpn, len)) {
2531 new = TLS_REALLOC(context->alpn, (context->alpn_count + 1) *
2534 context->alpn = new;
2536 free(context->alpn);
2538 context->alpn_count = 0;
2539 return TLS_NO_MEMORY;
2541 char *alpn_ref = malloc(len + 1);
2542 context->alpn[context->alpn_count] = alpn_ref;
2544 memcpy(alpn_ref, alpn, len);
2546 context->alpn_count++;
2548 return TLS_NO_MEMORY;
2553 int tls_alpn_contains(struct TLSContext *context, const char *alpn,
2554 unsigned char alpn_size) {
2557 if (!context || !alpn || !alpn_size || !context->alpn) {
2561 for (i = 0; i < context->alpn_count; i++) {
2562 const char *alpn_local = context->alpn[i];
2564 int len = strlen(alpn_local);
2565 if (alpn_size == len) {
2566 if (!memcmp(alpn_local, alpn, alpn_size)) {
2576 void tls_destroy_context(struct TLSContext *context) {
2583 if (!context->is_child) {
2584 if (context->certificates) {
2585 for (i = 0; i < context->certificates_count; i++) {
2586 tls_destroy_certificate(context->
2590 if (context->root_certificates) {
2591 for (i = 0; i < context->root_count; i++) {
2592 tls_destroy_certificate(context->
2593 root_certificates[i]);
2595 free(context->root_certificates);
2596 context->root_certificates = NULL;
2598 if (context->private_key) {
2599 tls_destroy_certificate(context->private_key);
2601 if (context->ec_private_key) {
2602 tls_destroy_certificate(context->ec_private_key);
2604 free(context->certificates);
2605 free(context->default_dhe_p);
2606 free(context->default_dhe_g);
2607 if (context->alpn) {
2608 for (i = 0; i < context->alpn_count; i++) {
2609 free(context->alpn[i]);
2611 free(context->alpn);
2615 if (context->client_certificates) {
2616 for (i = 0; i < context->client_certificates_count; i++) {
2617 tls_destroy_certificate(context->
2618 client_certificates[i]);
2620 free(context->client_certificates);
2623 context->client_certificates = NULL;
2624 free(context->master_key);
2625 free(context->premaster_key);
2627 if (context->crypto.created) {
2628 tls_crypto_done(context);
2631 tls_done_hash(context, NULL);
2632 tls_destroy_hash(context);
2634 tls_buffer_free(&context->output_buffer);
2635 tls_buffer_free(&context->input_buffer);
2636 tls_buffer_free(&context->application_buffer);
2637 tls_buffer_free(&context->cached_handshake);
2638 //free(context->cached_handshake);
2641 tls_dhe_free(context);
2642 tls_ecc_dhe_free(context);
2643 free(context->negotiated_alpn);
2644 free(context->finished_key);
2645 free(context->remote_finished_key);
2646 free(context->server_finished_hash);
2650 int tls_cipher_is_ephemeral(struct TLSContext *context) {
2655 switch (context->cipher) {
2656 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
2657 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
2658 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
2659 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
2660 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
2661 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
2662 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
2664 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
2665 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
2666 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
2667 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
2668 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
2669 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
2670 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
2671 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
2672 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
2673 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
2674 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
2675 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
2676 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
2678 case TLS_AES_128_GCM_SHA256:
2679 case TLS_CHACHA20_POLY1305_SHA256:
2680 case TLS_AES_128_CCM_SHA256:
2681 case TLS_AES_128_CCM_8_SHA256:
2682 case TLS_AES_256_GCM_SHA384:
2691 int tls_is_ecdsa(struct TLSContext *context) {
2696 switch (context->cipher) {
2697 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
2698 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
2699 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
2700 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
2701 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
2702 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
2703 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
2707 if (context->ec_private_key) {
2714 static void tls_send_server_key_exchange(struct TLSContext *context,
2716 if (!context->is_server) {
2718 ("CANNOT BUILD SERVER KEY EXCHANGE MESSAGE FOR CLIENTS\n");
2722 struct TLSPacket *packet =
2723 tls_create_packet(context, TLS_HANDSHAKE, context->version, 0);
2724 tls_packet_uint8(packet, 0x0C);
2725 unsigned char dummy[3];
2726 tls_packet_append(packet, dummy, 3);
2727 int start_len = packet->len;
2729 if (method == KEA_dhe_rsa) {
2730 tls_dhe_create(context);
2732 const char *default_dhe_p = context->default_dhe_p;
2733 const char *default_dhe_g = context->default_dhe_g;
2735 if (!default_dhe_p || !default_dhe_g) {
2736 default_dhe_p = TLS_DH_DEFAULT_P;
2737 default_dhe_g = TLS_DH_DEFAULT_G;
2738 key_size = TLS_DHE_KEY_SIZE / 8;
2740 key_size = strlen(default_dhe_p);
2742 if (tls_dh_make_key(key_size, context->dhe, default_dhe_p,
2743 default_dhe_g, 0, 0)) {
2744 DEBUG_PRINT("ERROR CREATING DHE KEY\n");
2747 context->dhe = NULL;
2748 /* TODO set error */
2752 unsigned char dh_Ys[0xFFF];
2753 unsigned char dh_p[0xFFF];
2754 unsigned char dh_g[0xFFF];
2755 unsigned long dh_p_len = sizeof(dh_p);
2756 unsigned long dh_g_len = sizeof(dh_g);
2757 unsigned long dh_Ys_len = sizeof(dh_Ys);
2759 if (tls_dh_export_pqY
2760 (dh_p, &dh_p_len, dh_g, &dh_g_len, dh_Ys, &dh_Ys_len,
2762 DEBUG_PRINT("ERROR EXPORTING DHE KEY\n");
2764 /* TODO set error */
2768 DEBUG_PRINT("LEN: %lu (%lu, %lu)\n", dh_Ys_len, dh_p_len,
2770 DEBUG_DUMP_HEX_LABEL("DHE PK", dh_Ys, dh_Ys_len);
2771 DEBUG_DUMP_HEX_LABEL("DHE P", dh_p, dh_p_len);
2772 DEBUG_DUMP_HEX_LABEL("DHE G", dh_g, dh_g_len);
2774 tls_packet_uint16(packet, dh_p_len);
2775 tls_packet_append(packet, dh_p, dh_p_len);
2777 tls_packet_uint16(packet, dh_g_len);
2778 tls_packet_append(packet, dh_g, dh_g_len);
2780 tls_packet_uint16(packet, dh_Ys_len);
2781 tls_packet_append(packet, dh_Ys, dh_Ys_len);
2785 } else if (method == KEA_ec_diffie_hellman) {
2786 /* 3 = named curve */
2787 if (!context->curve) {
2788 context->curve = tls_ecc_default_curve;
2790 tls_packet_uint8(packet, 3);
2791 tls_packet_uint16(packet, context->curve->iana);
2792 tls_ecc_dhe_create(context);
2794 ltc_ecc_set_type *dp =
2795 (ltc_ecc_set_type *) & context->curve->dp;
2797 if (ecc_make_key_ex(NULL, find_prng("sprng"), context->ecc_dhe,
2799 free(context->ecc_dhe);
2800 context->ecc_dhe = NULL;
2801 DEBUG_PRINT("Error generating ECC key\n");
2803 /* TODO set error */
2806 unsigned char out[TLS_MAX_RSA_KEY];
2807 unsigned long out_len = TLS_MAX_RSA_KEY;
2808 if (ecc_ansi_x963_export(context->ecc_dhe, out, &out_len)) {
2809 DEBUG_PRINT("Error exporting ECC key\n");
2814 tls_packet_uint8(packet, out_len);
2815 tls_packet_append(packet, out, out_len);
2819 DEBUG_PRINT("Unsupported ephemeral method: %i\n", method);
2824 unsigned int params_len = packet->len - start_len;
2825 unsigned int message_len =
2826 params_len + TLS_CLIENT_RANDOM_SIZE + TLS_SERVER_RANDOM_SIZE;
2827 unsigned char *message = malloc(message_len);
2829 unsigned char out[TLS_MAX_RSA_KEY];
2830 unsigned long out_len = TLS_MAX_RSA_KEY;
2834 hash_algorithm = sha256;
2836 if (tls_is_ecdsa(context)) {
2837 hash_algorithm = sha512;
2838 tls_packet_uint8(packet, hash_algorithm);
2839 tls_packet_uint8(packet, ecdsa);
2841 tls_packet_uint8(packet, hash_algorithm);
2842 tls_packet_uint8(packet, rsa_sign);
2845 memcpy(message, context->remote_random,
2846 TLS_CLIENT_RANDOM_SIZE);
2847 memcpy(message + TLS_CLIENT_RANDOM_SIZE, context->local_random,
2848 TLS_SERVER_RANDOM_SIZE);
2849 memcpy(message + TLS_CLIENT_RANDOM_SIZE +
2850 TLS_SERVER_RANDOM_SIZE, packet->buf +
2851 start_len, params_len);
2852 if (tls_is_ecdsa(context)) {
2853 if (sign_ecdsa(context, hash_algorithm, message,
2854 message_len, out, &out_len) ==
2857 ("Signing OK! (ECDSA, length %lu)\n",
2859 tls_packet_uint16(packet, out_len);
2860 tls_packet_append(packet, out, out_len);
2863 if (sign_rsa(context, hash_algorithm, message, message_len,
2864 out, &out_len) == 1) {
2865 DEBUG_PRINT("Signing OK! (length %lu)\n", out_len);
2866 tls_packet_uint16(packet, out_len);
2867 tls_packet_append(packet, out, out_len);
2871 if (!packet->broken && packet->buf) {
2872 tls_set_packet_length(packet, packet->len - start_len);
2874 tls_packet_update(packet);
2875 tls_queue_packet(packet);
2880 void _private_tls_set_session_id(struct TLSContext *context) {
2881 if (context->tlsver == TLS_VERSION13
2882 && context->session_size == TLS_MAX_SESSION_ID) {
2886 if (tls_random(context->session, TLS_MAX_SESSION_ID)) {
2887 context->session_size = TLS_MAX_SESSION_ID;
2889 context->session_size = 0;
2894 struct TLSPacket *tls_certificate_request(struct TLSContext *context) {
2895 if (!context || !context->is_server) {
2899 unsigned short packet_version = context->version;
2900 struct TLSPacket *packet =
2901 tls_create_packet(context, TLS_HANDSHAKE, packet_version, 0);
2907 /* cert request and size placeholder */
2908 unsigned char dummy[] = { 0x0d, 0, 0, 0 };
2909 tls_packet_append(packet, dummy, sizeof dummy);
2911 int start_len = packet->len;
2913 if (context->tlsver == TLS_VERSION13) {
2914 /* certificate request context */
2915 tls_packet_uint8(packet, 0);
2917 tls_packet_uint16(packet, 18);
2918 /* signature algorithms */
2919 tls_packet_uint16(packet, 0x0D);
2920 tls_packet_uint16(packet, 14);
2921 tls_packet_uint16(packet, 12);
2924 tls_packet_uint16(packet, 0x0401);
2926 tls_packet_uint16(packet, 0x0501);
2928 tls_packet_uint16(packet, 0x0601);
2931 /* ecdsa_secp256r1_sha256 */
2932 tls_packet_uint16(packet, 0x0403);
2933 /* ecdsa_secp384r1_sha384 */
2934 tls_packet_uint16(packet, 0x0503);
2935 /* ecdsa_secp521r1_sha512 */
2936 tls_packet_uint16(packet, 0x0604);
2937 /* rsa_pss_rsae_sha256 */
2938 tls_packet_uint16(packet, 0x0804);
2939 /* rsa_pss_rsae_sha384 */
2940 tls_packet_uint16(packet, 0x0805);
2941 /* rsa_pss_rsae_sha512 */
2942 tls_packet_uint16(packet, 0x0806);
2944 tls_packet_uint8(packet, 1);
2945 tls_packet_uint8(packet, rsa_sign);
2946 if (context->version == TLS_V12) {
2947 /* 10 pairs or 2 bytes */
2948 tls_packet_uint16(packet, 10);
2949 tls_packet_uint8(packet, sha256);
2950 tls_packet_uint8(packet, rsa);
2951 tls_packet_uint8(packet, sha1);
2952 tls_packet_uint8(packet, rsa);
2953 tls_packet_uint8(packet, sha384);
2954 tls_packet_uint8(packet, rsa);
2955 tls_packet_uint8(packet, sha512);
2956 tls_packet_uint8(packet, rsa);
2957 tls_packet_uint8(packet, md5);
2958 tls_packet_uint8(packet, rsa);
2960 /* no DistinguishedName yet */
2961 tls_packet_uint16(packet, 0);
2963 if (!packet->broken) {
2964 tls_set_packet_length(packet, packet->len - start_len);
2966 tls_packet_update(packet);
2970 int tls_parse_key_share(struct TLSContext *context, const unsigned char *buf,
2973 struct ECCCurveParameters *curve = 0;
2974 struct DHKey *dhkey = 0;
2975 int dhe_key_size = 0;
2976 const unsigned char *buffer = NULL;
2977 unsigned char *out2;
2978 unsigned long out_size;
2981 while (buf_len >= 4) {
2982 uint16_t named_group = get16(&buf[i]);
2986 key_size = get16(&buf[i]);
2990 if (key_size > buf_len) {
2991 return TLS_BROKEN_PACKET;
2994 switch (named_group) {
2998 DEBUG_PRINT("KEY SHARE => secp256r1\n");
3005 DEBUG_PRINT("KEY SHARE => secp384r1\n");
3013 if (key_size != 32) {
3015 ("INVALID x25519 KEY SIZE (%i)\n",
3019 curve = &curve25519;
3021 DEBUG_PRINT("KEY SHARE => x25519\n");
3031 dhe_key_size = 2048;
3035 dhe_key_size = 3072;
3039 dhe_key_size = 4096;
3043 dhe_key_size = 6144;
3047 dhe_key_size = 8192;
3051 buf_len -= key_size;
3055 context->curve = curve;
3057 if (curve == &curve25519) {
3058 if (!tls_random(context->local_random,
3059 TLS_SERVER_RANDOM_SIZE)) {
3060 return TLS_GENERIC_ERROR;
3063 unsigned char secret[32];
3064 static const unsigned char basepoint[32] = { 9 };
3066 tls_random(secret, 32);
3072 /* use finished key to store public key */
3073 free(context->finished_key);
3074 context->finished_key = malloc(32);
3075 if (!context->finished_key) {
3076 return TLS_GENERIC_ERROR;
3079 x25519(context->finished_key, secret, basepoint);
3081 free(context->premaster_key);
3082 context->premaster_key = malloc(32);
3084 if (!context->premaster_key) {
3085 return TLS_GENERIC_ERROR;
3088 x25519(context->premaster_key, secret, buffer);
3089 context->premaster_key_len = 32;
3094 tls_ecc_dhe_create(context);
3095 ltc_ecc_set_type *dp = (ltc_ecc_set_type *)&context->curve->dp;
3097 if (ecc_make_key_ex(NULL, find_prng("sprng"), context->ecc_dhe,
3099 free(context->ecc_dhe);
3100 context->ecc_dhe = NULL;
3101 DEBUG_PRINT("Error generating ECC DHE key\n");
3102 return TLS_GENERIC_ERROR;
3105 if (!tls_random(context->local_random, TLS_SERVER_RANDOM_SIZE)) {
3106 return TLS_GENERIC_ERROR;
3110 memset(&client_key, 0, sizeof client_key);
3111 if (ecc_ansi_x963_import_ex
3112 (buffer, key_size, &client_key, dp)) {
3113 DEBUG_PRINT("Error importing ECC DHE key\n");
3114 return TLS_GENERIC_ERROR;
3116 out2 = malloc(key_size);
3117 out_size = key_size;
3119 int err = ecc_shared_secret(context->ecc_dhe, &client_key,
3121 ecc_free(&client_key);
3124 DEBUG_PRINT("ECC DHE DECRYPT ERROR %i\n", err);
3126 return TLS_GENERIC_ERROR;
3129 DEBUG_PRINT("OUT_SIZE: %lu\n", out_size);
3130 DEBUG_DUMP_HEX_LABEL("ECC DHE", out2, out_size);
3132 free(context->premaster_key);
3133 context->premaster_key = out2;
3134 context->premaster_key_len = out_size;
3137 tls_dhe_create(context);
3138 if (!tls_random(context->local_random, TLS_SERVER_RANDOM_SIZE))
3140 return TLS_GENERIC_ERROR;
3143 if (tls_dh_make_key(dhe_key_size / 8, context->dhe,
3144 (const char *)dhkey->p, (const char *)dhkey->g, 0, 0)) {
3146 context->dhe = NULL;
3147 DEBUG_PRINT("Error generating DHE key\n");
3148 return TLS_GENERIC_ERROR;
3151 unsigned int dhe_out_size;
3152 out2 = tls_decrypt_dhe(context, buffer, key_size,
3155 DEBUG_PRINT("Error generating DHE shared key\n");
3156 return TLS_GENERIC_ERROR;
3159 free(context->premaster_key);
3160 context->premaster_key = out2;
3161 context->premaster_key_len = dhe_out_size;
3163 context->dhe->iana = dhkey->iana;
3167 DEBUG_PRINT("NO COMMON KEY SHARE SUPPORTED\n");
3168 return TLS_NO_COMMON_CIPHER;
3171 int tls_parse_certificate(struct TLSContext *context,
3172 const unsigned char *buf, int buf_len,
3176 return TLS_NEED_MORE_DATA;
3179 int size = get24(buf);
3181 /* not enough data, so just consume all of it */
3186 res += 3; /* skip over the size field */
3188 if (context->tlsver == TLS_VERSION13) {
3189 int context_size = buf[res];
3193 res += context_size;
3197 if (buf_len - res < size) {
3198 return TLS_NEED_MORE_DATA;
3202 int valid_certificate = 0;
3205 if (buf_len - res < 3) {
3206 return TLS_NEED_MORE_DATA;
3208 int certificate_size = get24(buf+res);
3210 if (buf_len - res < certificate_size) {
3211 return TLS_NEED_MORE_DATA;
3214 int certificates_in_chain = 0;
3216 unsigned int remaining = certificate_size;
3218 if (remaining <= 3) {
3221 certificates_in_chain++;
3222 unsigned int certificate_size2 = get24(buf+res2);
3225 if (certificate_size2 > remaining) {
3227 ("Invalid certificate size (%i from %i bytes remaining)\n",
3228 certificate_size2, remaining);
3231 remaining -= certificate_size2;
3233 struct TLSCertificate *cert = asn1_parse(context,
3239 if (certificate_size2) {
3241 malloc(certificate_size2);
3250 /* valid certificate */
3253 valid_certificate = 1;
3256 TLS_REALLOC(context->
3257 client_certificates,
3259 client_certificates_count
3268 client_certificates);
3270 client_certificates =
3272 return TLS_NO_MEMORY;
3275 context->client_certificates = new;
3278 [context->client_certificates_count]
3281 client_certificates_count++;
3285 TLS_REALLOC(context->
3297 context->certificates = 0;
3298 return TLS_NO_MEMORY;
3300 context->certificates = new;
3301 context->certificates[context->
3304 context->certificates_count++;
3305 if ((cert->pk) || (cert->priv))
3306 valid_certificate = 1;
3307 else if (!context->is_server)
3308 valid_certificate = 1;
3311 res2 += certificate_size2;
3313 if (context->tlsver == TLS_VERSION13) {
3314 if (remaining >= 2) {
3315 /* ignore extensions */
3317 uint16_t size = get16(&buf[res2]);
3318 if (size && size >= remaining) {
3324 } while (remaining > 0);
3326 DEBUG_PRINT("Extra %i bytes after certificate\n",
3329 size -= certificate_size + 3;
3330 res += certificate_size;
3332 if (!valid_certificate) {
3333 return TLS_UNSUPPORTED_CERTIFICATE;
3335 if (res != buf_len) {
3336 DEBUG_PRINT("Warning: %i bytes read from %i byte buffer\n",
3337 (int) res, (int) buf_len);
3342 static int parse_dh( const unsigned char *buf, int buf_len, const unsigned char
3343 **out, int *out_size) {
3348 return TLS_NEED_MORE_DATA;
3350 uint16_t size = get16(buf);
3352 if (buf_len - res < size) {
3353 return TLS_NEED_MORE_DATA;
3355 DEBUG_DUMP_HEX(&buf[res], size);
3362 static int tls_parse_random(struct TLSContext *context,
3363 const unsigned char *buf, int buf_len) {
3365 int ephemeral = tls_cipher_is_ephemeral(context);
3367 if (ephemeral == 2) {
3369 return TLS_NEED_MORE_DATA;
3375 return TLS_NEED_MORE_DATA;
3381 if (buf_len - res < size) {
3382 return TLS_NEED_MORE_DATA;
3384 unsigned int out_len = 0;
3385 unsigned char *random = NULL;
3386 switch (ephemeral) {
3388 random = tls_decrypt_dhe(context, &buf[res], size, &out_len,
3392 random = tls_decrypt_ecc_dhe(context, &buf[res], size,
3396 random = decrypt_rsa(context, &buf[res], size,
3400 if (random && out_len > 2) {
3401 /* *(unsigned short *)&random[0] = htons(context->version); */
3402 DEBUG_DUMP_HEX_LABEL("PRE MASTER KEY", random, out_len);
3403 free(context->premaster_key);
3404 context->premaster_key = random;
3405 context->premaster_key_len = out_len;
3406 tls_compute_key(context, 48);
3415 static const unsigned char *parse_signature(const unsigned char *buf, int
3416 buf_len, int *hash_algorithm, int *sign_algorithm, int
3417 *sig_size, int *offset) {
3422 *hash_algorithm = _md5_sha1;
3423 *sign_algorithm = rsa_sign;
3425 *hash_algorithm = buf[res];
3427 *sign_algorithm = buf[res];
3429 uint16_t size = get16(&buf[res]);
3431 if (buf_len - res < size) {
3434 DEBUG_DUMP_HEX(&buf[res], size);
3436 *offset = res + size;
3440 int tls_parse_server_key_exchange(struct TLSContext *context,
3441 const unsigned char *buf, int buf_len) {
3445 return TLS_NEED_MORE_DATA;
3447 int size = get24(buf);
3449 const unsigned char *packet_ref = buf + res;
3450 if (buf_len - res < size) {
3451 return TLS_NEED_MORE_DATA;
3458 unsigned char has_ds_params = 0;
3460 const struct ECCCurveParameters *curve = NULL;
3461 const unsigned char *pk_key = NULL;
3462 int ephemeral = tls_cipher_is_ephemeral(context);
3464 if (ephemeral == 1) {
3467 if (buf[res++] != 3) {
3469 /* any other method is not supported */
3472 if (buf_len - res < 3) {
3473 return TLS_NEED_MORE_DATA;
3475 int iana_n = get16(&buf[res]);
3477 key_size = buf[res];
3479 if (buf_len - res < key_size) {
3480 return TLS_NEED_MORE_DATA;
3482 DEBUG_PRINT("IANA CURVE NUMBER: %i\n", iana_n);
3506 DEBUG_PRINT("UNSUPPORTED CURVE\n");
3507 return TLS_GENERIC_ERROR;
3511 context->curve = curve;
3515 const unsigned char *dh_p = NULL;
3517 const unsigned char *dh_g = NULL;
3519 const unsigned char *dh_Ys = NULL;
3522 if (has_ds_params) {
3523 DEBUG_PRINT(" dh_p: ");
3524 dh_res = parse_dh(&buf[res], buf_len - res, &dh_p, &dh_p_len);
3526 return TLS_BROKEN_PACKET;
3531 DEBUG_PRINT(" dh_q: ");
3532 dh_res = parse_dh(&buf[res], buf_len - res, &dh_g, &dh_g_len);
3534 return TLS_BROKEN_PACKET;
3539 DEBUG_PRINT(" dh_Ys: ");
3540 dh_res = parse_dh(&buf[res], buf_len - res, &dh_Ys,
3543 return TLS_BROKEN_PACKET;
3551 int packet_size = res - 3;
3553 DEBUG_PRINT(" SIGNATURE (%i/%i/%i): ", packet_size,
3555 const unsigned char *signature =
3556 parse_signature(&buf[res], buf_len - res, &hash_algorithm,
3557 &sign_algorithm, &sign_size, &offset);
3559 if (sign_size <= 0 || !signature) {
3560 return TLS_BROKEN_PACKET;
3563 /* check signature */
3564 unsigned int message_len =
3565 packet_size + TLS_CLIENT_RANDOM_SIZE + TLS_SERVER_RANDOM_SIZE;
3566 unsigned char *message = malloc(message_len);
3568 memcpy(message, context->local_random, TLS_CLIENT_RANDOM_SIZE);
3569 memcpy(message + TLS_CLIENT_RANDOM_SIZE,
3570 context->remote_random, TLS_SERVER_RANDOM_SIZE);
3571 memcpy(message + TLS_CLIENT_RANDOM_SIZE +
3572 TLS_SERVER_RANDOM_SIZE, packet_ref, packet_size);
3573 if (tls_is_ecdsa(context)) {
3574 if (tls_verify_ecdsa
3575 (context, hash_algorithm, signature, sign_size,
3576 message, message_len, NULL) != 1) {
3578 ("ECC Server signature FAILED!\n");
3580 return TLS_BROKEN_PACKET;
3584 if (verify_rsa(context, hash_algorithm, signature,
3586 message_len) != 1) {
3587 DEBUG_PRINT("Server signature FAILED!\n");
3589 return TLS_BROKEN_PACKET;
3595 if (buf_len - res) {
3596 DEBUG_PRINT("EXTRA %i BYTES AT THE END OF MESSAGE\n",
3598 DEBUG_DUMP_HEX(&buf[res], buf_len - res);
3602 if (ephemeral == 1) {
3603 tls_dhe_create(context);
3604 DEBUG_DUMP_HEX_LABEL("DHP", dh_p, dh_p_len);
3605 DEBUG_DUMP_HEX_LABEL("DHG", dh_g, dh_g_len);
3606 int dhe_key_size = dh_p_len;
3607 if (dh_g_len > dh_p_len) {
3608 dhe_key_size = dh_g_len;
3611 if (tls_dh_make_key(dhe_key_size, context->dhe, (const char *)
3612 dh_p, (const char *) dh_g, dh_p_len,
3614 DEBUG_PRINT("ERROR CREATING DHE KEY\n");
3616 context->dhe = NULL;
3617 return TLS_GENERIC_ERROR;
3620 unsigned int dh_key_size = 0;
3621 unsigned char *key = tls_decrypt_dhe(context, dh_Ys, dh_Ys_len,
3623 DEBUG_DUMP_HEX_LABEL("DH COMMON SECRET", key, dh_key_size);
3624 if (key && dh_key_size) {
3625 free(context->premaster_key);
3626 context->premaster_key = key;
3627 context->premaster_key_len = dh_key_size;
3629 } else if (ephemeral == 2 && curve && pk_key && key_size) {
3630 tls_ecc_dhe_create(context);
3632 ltc_ecc_set_type *dp = (ltc_ecc_set_type *) & curve->dp;
3634 (NULL, find_prng("sprng"), context->ecc_dhe, dp)) {
3635 free(context->ecc_dhe);
3636 context->ecc_dhe = NULL;
3637 DEBUG_PRINT("Error generating ECC key\n");
3638 return TLS_GENERIC_ERROR;
3641 free(context->premaster_key);
3642 context->premaster_key_len = 0;
3644 unsigned int out_len = 0;
3645 context->premaster_key =
3646 tls_decrypt_ecc_dhe(context, pk_key, key_size,
3648 if (context->premaster_key) {
3649 context->premaster_key_len = out_len;
3656 int tls_parse_client_key_exchange(struct TLSContext *context,
3657 const unsigned char *buf, int buf_len) {
3658 if (context->connection_status != 1) {
3660 ("UNEXPECTED CLIENT KEY EXCHANGE MESSAGE (connections status: %i)\n",
3661 (int) context->connection_status);
3662 return TLS_UNEXPECTED_MESSAGE;
3668 return TLS_NEED_MORE_DATA;
3670 int size = get24(buf);
3673 if (buf_len - res < size) {
3674 return TLS_NEED_MORE_DATA;
3681 dh_res = tls_parse_random(context, &buf[res], size);
3683 DEBUG_PRINT("broken key\n");
3684 return TLS_BROKEN_PACKET;
3689 context->connection_status = 2;
3693 static int tls_parse_server_hello_done(const unsigned char *buf, int buf_len) {
3696 return TLS_NEED_MORE_DATA;
3698 int size = get24(buf);
3701 if (buf_len - res < size) {
3702 return TLS_NEED_MORE_DATA;
3709 int tls_parse_finished(struct TLSContext *context,
3710 const unsigned char *buf, int buf_len,
3711 unsigned int *write_packets) {
3712 if (context->connection_status < 2
3713 || context->connection_status == TLS_CONNECTED) {
3714 DEBUG_PRINT("UNEXPECTED FINISHED MESSAGE\n");
3715 return TLS_UNEXPECTED_MESSAGE;
3721 return TLS_NEED_MORE_DATA;
3723 int size = get24(buf);
3726 if (size < TLS_MIN_FINISHED_OPAQUE_LEN) {
3727 DEBUG_PRINT("Invalid finished packet size: %i\n", size);
3728 return TLS_BROKEN_PACKET;
3731 if (buf_len - res < size) {
3732 return TLS_NEED_MORE_DATA;
3735 unsigned char hash[TLS_MAX_SHA_SIZE];
3736 unsigned int hash_len = tls_get_hash(context, hash);
3738 if (context->tlsver == TLS_VERSION13) {
3739 unsigned char hash_out[TLS_MAX_SHA_SIZE];
3740 unsigned long out_size = TLS_MAX_SHA_SIZE;
3741 if (!context->remote_finished_key || !hash_len) {
3743 ("NO FINISHED KEY COMPUTED OR NO HANDSHAKE HASH\n");
3744 return TLS_NOT_VERIFIED;
3747 DEBUG_DUMP_HEX_LABEL("HS HASH", hash, hash_len);
3748 DEBUG_DUMP_HEX_LABEL("HS FINISH", context->remote_finished_key,
3751 out_size = hash_len;
3753 hmac_init(&hmac, tls_get_hash_idx(context),
3754 context->remote_finished_key, hash_len);
3755 hmac_process(&hmac, hash, hash_len);
3756 hmac_done(&hmac, hash_out, &out_size);
3758 if (size != (int)out_size || memcmp(hash_out, &buf[res], size)) {
3760 ("Finished validation error (sequence number, local: %i, remote: %i)\n",
3761 (int) context->local_sequence_number,
3762 (int) context->remote_sequence_number);
3763 DEBUG_DUMP_HEX_LABEL("FINISHED OPAQUE", &buf[res],
3765 DEBUG_DUMP_HEX_LABEL("VERIFY", hash_out, out_size);
3766 return TLS_NOT_VERIFIED;
3768 if (context->is_server) {
3769 context->connection_status = TLS_CONNECTED;
3771 _private_tls13_key(context, 0);
3772 context->local_sequence_number = 0;
3773 context->remote_sequence_number = 0;
3776 /* TODO client verify */
3779 unsigned char *out = malloc(size);
3781 DEBUG_PRINT("Error in malloc (%i bytes)\n",
3783 return TLS_NO_MEMORY;
3786 /* server verifies client's message */
3787 if (context->is_server) {
3788 tls_prf(context, out, size,
3789 context->master_key,
3790 context->master_key_len,
3792 "client finished", 15, hash,
3795 tls_prf(context, out, size,
3796 context->master_key,
3797 context->master_key_len,
3799 "server finished", 15, hash,
3803 if (memcmp(out, &buf[res], size)) {
3806 ("Finished validation error (sequence number, local: %i, remote: %i)\n",
3807 (int) context->local_sequence_number,
3808 (int) context->remote_sequence_number);
3809 DEBUG_DUMP_HEX_LABEL("FINISHED OPAQUE", &buf[res],
3811 DEBUG_DUMP_HEX_LABEL("VERIFY", out, size);
3812 return TLS_NOT_VERIFIED;
3817 if (context->is_server) {
3820 context->connection_status = TLS_CONNECTED;
3823 // fprintf(stderr, "set conn status = %d\n", context->connection_status);
3829 int tls_parse_verify_tls13(struct TLSContext *context,
3830 const unsigned char *buf, int buf_len) {
3832 return TLS_NEED_MORE_DATA;
3834 int size = get24(buf);
3840 unsigned char signing_data[TLS_MAX_HASH_SIZE + 98];
3841 int signing_data_len;
3843 /* first 64 bytes to 0x20 (32) */
3844 memset(signing_data, 0x20, 64);
3845 /* context string 33 bytes */
3846 if (context->is_server) {
3847 memcpy(signing_data + 64,
3848 "TLS 1.3, server CertificateVerify", 33);
3850 memcpy(signing_data + 64,
3851 "TLS 1.3, client CertificateVerify", 33);
3854 /* a single 0 byte separator */
3855 signing_data[97] = 0;
3856 signing_data_len = 98;
3858 signing_data_len += tls_get_hash(context, signing_data + 98);
3859 DEBUG_DUMP_HEX_LABEL("signature data", signing_data, signing_data_len);
3860 uint16_t signature = get16(&buf[3]);
3861 uint16_t signature_size = get16(&buf[5]);
3863 if (buf_len < size + 7) {
3864 return TLS_NEED_MORE_DATA;
3866 switch (signature) {
3868 /* secp256r1 + sha256 */
3870 tls_verify_ecdsa(context, sha256, buf + 7,
3871 signature_size, signing_data,
3876 /* secp384r1 + sha384 */
3877 valid = tls_verify_ecdsa(context, sha384, buf + 7,
3878 signature_size, signing_data,
3879 signing_data_len, &secp384r1);
3882 /* secp521r1 + sha512 */
3883 valid = tls_verify_ecdsa(context, sha512, buf + 7,
3884 signature_size, signing_data,
3885 signing_data_len, &secp521r1);
3888 valid = verify_rsa(context, sha256, buf + 7,
3889 signature_size, signing_data,
3893 DEBUG_PRINT("Unsupported signature: %x\n",
3895 return TLS_UNSUPPORTED_CERTIFICATE;
3898 DEBUG_PRINT("Signature FAILED!\n");
3899 return TLS_DECRYPTION_FAILED;
3904 int tls_parse_verify(struct TLSContext *context, const unsigned char *buf,
3906 if (context->tlsver == TLS_VERSION13) {
3907 return tls_parse_verify_tls13(context, buf, buf_len);
3911 return TLS_BAD_CERTIFICATE;
3914 int bytes_to_follow = get24(buf);
3916 if (buf_len - 3 < bytes_to_follow) {
3917 return TLS_BAD_CERTIFICATE;
3922 unsigned int hash = buf[3];
3923 unsigned int algorithm = buf[4];
3924 if (algorithm != rsa) {
3925 return TLS_UNSUPPORTED_CERTIFICATE;
3927 uint16_t size = get16(&buf[5]);
3928 if (bytes_to_follow - 4 < size) {
3929 return TLS_BAD_CERTIFICATE;
3931 DEBUG_PRINT("ALGORITHM %i/%i (%i)\n", hash, algorithm, (int) size);
3932 DEBUG_DUMP_HEX_LABEL("VERIFY", &buf[7], bytes_to_follow - 7);
3934 res = verify_rsa(context, hash, &buf[7], size,
3935 context->cached_handshake.buffer,
3936 context->cached_handshake.len);
3938 tls_buffer_free(&context->cached_handshake);
3940 DEBUG_PRINT("Signature OK\n");
3941 context->client_verified = 1;
3943 DEBUG_PRINT("Signature FAILED\n");
3944 context->client_verified = 0;
3949 /* TODO This is actually a parse a handshake message */
3950 int tls_parse_payload(struct TLSContext *context, const unsigned char *buf,
3952 int orig_len = buf_len;
3955 if (context->connection_status == TLS_CONNECTED) {
3956 if (context->version == TLS_V13) {
3957 tls_alert(context, 1, unexpected_message);
3959 tls_alert(context, 0, no_renegotiation_RESERVED);
3965 while (buf_len >= 4 && !context->critical_error) {
3966 int payload_res = 0;
3967 //unsigned char update_hash = 1;
3968 unsigned char type = buf[0];
3969 unsigned int write_packets = 0;
3970 int certificate_verify_alert = no_error;
3971 int payload_size = get24(buf+1) + 3;
3972 if (buf_len < payload_size + 1) {
3973 return TLS_NEED_MORE_DATA;
3978 CHECK_HANDSHAKE_STATE(context, 0, 1);
3980 (" => HELLO REQUEST (RENEGOTIATION?)\n");
3981 if (context->is_server) {
3982 payload_res = TLS_UNEXPECTED_MESSAGE;
3984 if (context->connection_status == TLS_CONNECTED) {
3986 payload_res = TLS_NO_RENEGOTIATION;
3988 payload_res = TLS_UNEXPECTED_MESSAGE;
3995 CHECK_HANDSHAKE_STATE(context, 1, 1);
3996 DEBUG_PRINT(" => CLIENT HELLO\n");
3997 if (context->is_server) {
3999 tls_parse_client_hello(context,
4004 payload_res = TLS_UNEXPECTED_MESSAGE;
4009 CHECK_HANDSHAKE_STATE(context, 2, 1);
4010 DEBUG_PRINT(" => SERVER HELLO\n");
4011 if (context->is_server) {
4012 payload_res = TLS_UNEXPECTED_MESSAGE;
4015 payload_res = tls_parse_server_hello(context, buf + 1, payload_size);
4019 /* hello verify request */
4020 DEBUG_PRINT(" => VERIFY REQUEST\n");
4021 CHECK_HANDSHAKE_STATE(context, 3, 1);
4022 payload_res = TLS_UNEXPECTED_MESSAGE;
4026 CHECK_HANDSHAKE_STATE(context, 4, 1);
4027 DEBUG_PRINT(" => CERTIFICATE\n");
4028 if (context->tlsver == TLS_VERSION13) {
4029 if (context->connection_status == 2) {
4031 tls_parse_certificate(context,
4036 if (context->is_server) {
4037 if (context->certificate_verify && context->client_certificates_count) {
4038 certificate_verify_alert
4040 context->certificate_verify(context,
4041 context->client_certificates,
4042 context->client_certificates_count);
4044 /* empty certificates are permitted for client */
4045 if (payload_res <= 0) {
4051 TLS_UNEXPECTED_MESSAGE;
4053 if (context->connection_status == 1) {
4054 if (context->is_server) {
4055 /* client certificate */
4057 tls_parse_certificate(context,
4061 if (context->certificate_verify && context->client_certificates_count) {
4062 certificate_verify_alert =
4063 context->certificate_verify
4066 client_certificates,
4068 client_certificates_count);
4070 /* empty certificates are permitted for client */
4071 if (payload_res <= 0)
4075 tls_parse_certificate(context,
4079 if (certificate_verify && context->certificates_count) {
4080 certificate_verify_alert =
4081 context->certificate_verify
4083 context->certificates,
4085 certificates_count);
4089 payload_res = TLS_UNEXPECTED_MESSAGE;
4093 /* server key exchange */
4094 CHECK_HANDSHAKE_STATE(context, 5, 1);
4095 DEBUG_PRINT(" => SERVER KEY EXCHANGE\n");
4096 if (context->is_server) {
4097 payload_res = TLS_UNEXPECTED_MESSAGE;
4100 tls_parse_server_key_exchange(context,
4106 /* certificate request */
4107 CHECK_HANDSHAKE_STATE(context, 6, 1);
4108 /* server to client */
4109 if (context->is_server) {
4110 payload_res = TLS_UNEXPECTED_MESSAGE;
4112 context->client_verified = 2;
4114 DEBUG_PRINT(" => CERTIFICATE REQUEST\n");
4117 /* server hello done */
4118 CHECK_HANDSHAKE_STATE(context, 7, 1);
4119 DEBUG_PRINT(" => SERVER HELLO DONE\n");
4120 if (context->is_server) {
4121 payload_res = TLS_UNEXPECTED_MESSAGE;
4124 tls_parse_server_hello_done(
4127 if (payload_res > 0) {
4133 /* certificate verify */
4134 CHECK_HANDSHAKE_STATE(context, 8, 1);
4135 DEBUG_PRINT(" => CERTIFICATE VERIFY\n");
4136 if (context->connection_status == 2) {
4138 tls_parse_verify(context, buf + 1,
4141 payload_res = TLS_UNEXPECTED_MESSAGE;
4145 /* client key exchange */
4146 CHECK_HANDSHAKE_STATE(context, 9, 1);
4147 DEBUG_PRINT(" => CLIENT KEY EXCHANGE\n");
4148 if (context->is_server) {
4150 tls_parse_client_key_exchange(context,
4154 payload_res = TLS_UNEXPECTED_MESSAGE;
4159 tls_buffer_free(&context->cached_handshake);
4160 CHECK_HANDSHAKE_STATE(context, 10, 1);
4161 DEBUG_PRINT(" => FINISHED\n");
4162 payload_res = tls_parse_finished(context,
4163 buf + 1, payload_size,
4165 if (payload_res > 0) {
4166 memset(context->hs_messages, 0,
4167 sizeof(context->hs_messages));
4172 (" => NOT UNDERSTOOD PAYLOAD TYPE: %x\n",
4174 return TLS_NOT_UNDERSTOOD;
4177 //if (type != 0x00 && update_hash) {
4179 tls_update_hash(context, buf, payload_size + 1);
4182 if (certificate_verify_alert != no_error) {
4183 tls_alert(context, 1, certificate_verify_alert);
4184 context->critical_error = 1;
4187 if (payload_res < 0) {
4188 switch (payload_res) {
4189 case TLS_UNEXPECTED_MESSAGE:
4190 tls_alert(context, 1, unexpected_message);
4192 case TLS_COMPRESSION_NOT_SUPPORTED:
4193 tls_alert(context, 1, decompression_failure_RESERVED);
4195 case TLS_BROKEN_PACKET:
4196 tls_alert(context, 1, decode_error);
4199 tls_alert(context, 1, internal_error);
4201 case TLS_NOT_VERIFIED:
4202 tls_alert(context, 1, bad_record_mac);
4204 case TLS_BAD_CERTIFICATE:
4205 if (context->is_server) {
4206 /* bad client certificate, continue */
4207 tls_alert(context, 0, bad_certificate);
4210 tls_alert(context, 1, bad_certificate);
4213 case TLS_UNSUPPORTED_CERTIFICATE:
4214 tls_alert(context, 1, unsupported_certificate);
4216 case TLS_NO_COMMON_CIPHER:
4217 tls_alert(context, 1, insufficient_security);
4219 case TLS_NOT_UNDERSTOOD:
4220 tls_alert(context, 1, internal_error);
4222 case TLS_NO_RENEGOTIATION:
4223 tls_alert(context, 0, no_renegotiation_RESERVED);
4226 case TLS_DECRYPTION_FAILED:
4227 tls_alert(context, 1, decryption_failed_RESERVED);
4230 if (payload_res < 0) {
4235 if (certificate_verify_alert != no_error) {
4236 payload_res = TLS_BAD_CERTIFICATE;
4239 /* except renegotiation */
4240 struct TLSPacket *pkt;
4241 switch (write_packets) {
4243 if (context->client_verified == 2) {
4244 DEBUG_PRINT("<= Building CERTIFICATE \n");
4245 tls_send_certificate(context);
4246 context->client_verified = 0;
4249 /* client handshake */
4250 tls_send_client_key_exchange(context);
4251 tls_send_change_cipher_spec(context);
4253 context->cipher_spec_set = 1;
4254 context->local_sequence_number = 0;
4256 tls_send_finished(context);
4258 context->cipher_spec_set = 0;
4261 /* server handshake */
4262 DEBUG_PRINT("<= SENDING SERVER HELLO\n");
4263 if (context->connection_status == 3) {
4264 context->connection_status = 2;
4266 (tls_build_hello(context, 0));
4267 tls_send_change_cipher_spec(context);
4268 _private_tls13_key(context, 1);
4269 context->cipher_spec_set = 1;
4271 ("<= SENDING ENCRYPTED EXTENSIONS\n");
4272 tls_send_encrypted_extensions(context);
4274 if (context->request_client_certificate) {
4276 ("<= SENDING CERTIFICATE REQUEST\n");
4278 (tls_certificate_request
4282 tls_send_certificate(context);
4284 tls_send_certificate_verify(context);
4286 tls_send_finished(context);
4289 free(context->server_finished_hash);
4291 context->server_finished_hash =
4292 malloc(tls_mac_length(context));
4294 if (context->server_finished_hash) {
4295 tls_get_hash(context,
4296 context->server_finished_hash);
4301 tls_queue_packet(tls_build_hello(context, 0));
4302 DEBUG_PRINT("<= SENDING CERTIFICATE\n");
4303 tls_send_certificate(context);
4305 int ephemeral_cipher =
4306 tls_cipher_is_ephemeral(context);
4307 if (ephemeral_cipher) {
4309 ("<= SENDING EPHEMERAL DH KEY\n");
4310 tls_send_server_key_exchange(context,
4311 ephemeral_cipher == 1 ?
4313 KEA_ec_diffie_hellman);
4315 if (context->request_client_certificate) {
4317 ("<= SENDING CERTIFICATE REQUEST\n");
4319 (tls_certificate_request
4322 tls_send_done(context);
4326 tls_send_change_cipher_spec(context);
4327 tls_send_finished(context);
4328 context->connection_status = TLS_CONNECTED;
4335 /* hello retry request */
4336 DEBUG_PRINT("<= SENDING HELLO RETRY REQUEST\n");
4337 pkt = tls_build_hello(context, 0);
4338 tls_queue_packet(pkt);
4342 buf += payload_size;
4343 buf_len -= payload_size;
4348 unsigned int asn1_get_len(const unsigned char *buffer, int buf_len,
4349 unsigned int *octets) {
4356 unsigned char size = buffer[0];
4359 *octets = size & 0x7F;
4360 if ((int) *octets > buf_len - 1) {
4364 unsigned int ref_octets = *octets;
4368 if ((int) *octets > buf_len - 1) {
4371 unsigned int long_size = 0;
4372 unsigned int coef = 1;
4374 for (i = ref_octets; i > 0; i--) {
4375 long_size += buffer[i] * coef;
4385 void print_index(const unsigned int *fields) {
4391 DEBUG_PRINT("%i", fields[i]);
4400 int _is_field(const unsigned int *fields, const unsigned int *prefix) {
4403 if (fields[i] != prefix[i]) {
4411 static int tls_hash_len(int algorithm) {
4412 switch (algorithm) {
4413 case TLS_RSA_SIGN_MD5:
4415 case TLS_RSA_SIGN_SHA1:
4417 case TLS_RSA_SIGN_SHA256:
4419 case TLS_RSA_SIGN_SHA384:
4421 case TLS_RSA_SIGN_SHA512:
4427 static unsigned char *tls_compute_hash(int algorithm, const unsigned char
4428 *message, unsigned int message_len) {
4429 unsigned char *hash = NULL;
4431 int hash_index = -1;
4432 unsigned long hash_len = 0;
4434 if (!message || !message_len) {
4438 switch (algorithm) {
4439 case TLS_RSA_SIGN_MD5:
4440 DEBUG_PRINT("SIGN MD5\n");
4441 hash_index = find_hash("md5");
4444 case TLS_RSA_SIGN_SHA1:
4445 DEBUG_PRINT("SIGN SHA1\n");
4446 hash_index = find_hash("sha1");
4449 case TLS_RSA_SIGN_SHA256:
4450 DEBUG_PRINT("SIGN SHA256\n");
4451 hash_index = find_hash("sha256");
4454 case TLS_RSA_SIGN_SHA384:
4455 DEBUG_PRINT("SIGN SHA384\n");
4456 hash_index = find_hash("sha384");
4459 case TLS_RSA_SIGN_SHA512:
4460 DEBUG_PRINT("SIGN SHA512\n");
4461 hash_index = find_hash("sha512");
4465 DEBUG_PRINT("UNKNOWN SIGNATURE ALGORITHM\n");
4470 hash = malloc(hash_len);
4475 err = hash_memory(hash_index, message, message_len, hash, &hash_len);
4482 int tls_certificate_verify_signature(struct TLSCertificate *cert,
4483 struct TLSCertificate *parent) {
4484 if (!cert || !parent || !cert->sign_key
4485 || !cert->fingerprint || !cert->sign_len
4486 || !parent->der_bytes || !parent->der_len) {
4487 DEBUG_PRINT("CANNOT VERIFY SIGNATURE ");
4489 DEBUG_PRINT("!cert ");
4491 if (!cert->sign_key) {
4492 DEBUG_PRINT("!cert->sign_key ");
4494 if (!cert->fingerprint) {
4495 DEBUG_PRINT("!cert->fingerprint ");
4497 if (!cert->sign_len) {
4498 DEBUG_PRINT("!cert->sign_len ");
4503 DEBUG_PRINT("!parent ");
4505 if (!parent->der_bytes) {
4506 DEBUG_PRINT("!parent->der_bytes ");
4508 if (!parent->der_len) {
4509 DEBUG_PRINT("!parent->der_len ");
4516 DEBUG_PRINT("checking alg\n");
4517 int hash_len = tls_hash_len(cert->algorithm);
4518 if (hash_len <= 0) {
4523 switch (cert->algorithm) {
4524 case TLS_RSA_SIGN_MD5:
4525 hash_index = find_hash("md5");
4527 case TLS_RSA_SIGN_SHA1:
4528 hash_index = find_hash("sha1");
4530 case TLS_RSA_SIGN_SHA256:
4531 hash_index = find_hash("sha256");
4533 case TLS_RSA_SIGN_SHA384:
4534 hash_index = find_hash("sha384");
4536 case TLS_RSA_SIGN_SHA512:
4537 hash_index = find_hash("sha512");
4540 DEBUG_PRINT("UNKNOWN SIGNATURE ALGORITHM\n");
4545 DEBUG_PRINTLN("rsa_import(%p, %d, %p)\n", parent->der_bytes,
4546 parent->der_len, &key);
4547 int err = rsa_import(parent->der_bytes, parent->der_len, &key);
4550 ("Error importing RSA certificate (code: %i)\n", err);
4551 DEBUG_PRINT("Message: %s\n", error_to_string(err));
4552 DEBUG_DUMP_HEX_LABEL("CERTIFICATE", parent->der_bytes,
4557 unsigned char *signature = cert->sign_key;
4558 int signature_len = cert->sign_len;
4559 if (!signature[0]) {
4564 err = rsa_verify_hash_ex(signature, signature_len, cert->fingerprint,
4565 hash_len, LTC_PKCS_1_V1_5, hash_index, 0, &rsa_stat,
4570 DEBUG_PRINT("HASH VERIFY ERROR %i\n", err);
4573 DEBUG_PRINT("CERTIFICATE VALIDATION: %i\n", rsa_stat);
4577 int tls_certificate_chain_is_valid(struct TLSCertificate **certificates,
4579 if (!certificates || !len) {
4580 return bad_certificate;
4584 DEBUG_PRINT("verifying %i length cert chain\n", len);
4587 /* expired certificate or not yet valid ? */
4588 if (tls_certificate_is_valid(certificates[0])) {
4589 return bad_certificate;
4593 for (i = 0; i < len; i++) {
4594 /* certificate in chain is expired ? */
4595 if (tls_certificate_is_valid(certificates[i + 1])) {
4596 return bad_certificate;
4599 if (!tls_certificate_verify_signature(certificates[i],
4600 certificates[i + 1])) {
4602 ("tls_certificate_verify_signature certs[%d], certs[%d+1] failed\n",
4604 return bad_certificate;
4611 int tls_certificate_chain_is_valid_root(struct TLSContext *context, struct
4612 TLSCertificate **certificates, int len) {
4615 if (!certificates || !len || !context->root_certificates
4616 || !context->root_count) {
4617 return bad_certificate;
4619 for (i = 0; i < len; i++) {
4620 for (j = 0; j < context->root_count; j++) {
4621 /* check if root certificate expired */
4622 if (tls_certificate_is_valid
4623 (context->root_certificates[j])) {
4626 /* if any root validates any certificate in the chain,
4627 * then is root validated */
4628 if (tls_certificate_verify_signature(certificates[i],
4629 context->root_certificates[j]))
4635 return bad_certificate;
4638 int _private_is_oid(struct OID_chain *ref_chain,
4639 const unsigned char *looked_oid, int looked_oid_len) {
4641 if (ref_chain->oid) {
4643 (ref_chain->oid, looked_oid, 16,
4648 ref_chain = (struct OID_chain *) ref_chain->top;
4653 int _private_asn1_parse(struct TLSContext *context,
4654 struct TLSCertificate *cert,
4655 const unsigned char *buffer, int size, int level,
4656 unsigned int *fields, unsigned char *has_key,
4657 int client_cert, unsigned char *top_oid,
4658 struct OID_chain *chain) {
4659 struct OID_chain local_chain;
4660 DEBUG_INDEX(fields);
4662 local_chain.top = chain;
4666 unsigned char oid[16];
4668 local_chain.oid = oid;
4672 unsigned char local_has_key = 0;
4673 const unsigned char *cert_data = NULL;
4674 unsigned int cert_len = 0;
4675 while (pos < size) {
4676 unsigned int start_pos = pos;
4677 if (size - pos < 2) {
4678 return TLS_NEED_MORE_DATA;
4680 unsigned char first = buffer[pos++];
4681 unsigned char type = first & 0x1F;
4682 unsigned char constructed = first & 0x20;
4683 unsigned char element_class = first >> 6;
4687 if (level <= TLS_ASN1_MAXLEVEL) {
4688 fields[level - 1] = idx;
4690 DEBUG_INDEX(fields);
4692 int length = asn1_get_len((unsigned char *) &buffer[pos], size
4694 DEBUG_PRINT("asn1_get_len = %u\n", length);
4695 if ((octets > 4) || (octets > size - pos)) {
4697 ("CANNOT READ CERTIFICATE octets = %d, size = %d pos = %d, size - pos = %d\n",
4698 octets, size, pos, size - pos);
4703 if (size - pos < length) {
4704 return TLS_NEED_MORE_DATA;
4707 /*DEBUG_PRINT("FIRST: %x => %x (%i)\n", (int)first, (int)type, length); */
4709 /*DEBUG_PRINT("%2i: ", level); */
4711 DEBUG_INDEX(fields);
4713 for (i1 = 1; i1 < level; i1++) {
4718 if (length && constructed) {
4721 DEBUG_PRINT("CONSTRUCTED BITSTREAM\n");
4724 DEBUG_PRINT("SEQUENCE\n");
4725 if ((level == 2) && (idx == 1)) {
4727 length + (pos - start_pos);
4728 cert_data = &buffer[start_pos];
4730 /* private key on server or public key on client */
4732 && (_is_field(fields, priv_der_id))) {
4733 free(cert->der_bytes);
4734 temp = length + (pos - start_pos);
4735 cert->der_bytes = malloc(temp);
4736 if (cert->der_bytes) {
4737 memcpy(cert->der_bytes,
4740 cert->der_len = temp;
4746 DEBUG_PRINT("EMBEDDED PDV\n");
4749 if (element_class == 0x02) {
4750 DEBUG_PRINT("CONTEXT-SPECIFIC\n");
4754 DEBUG_PRINT("CONSTRUCT TYPE %02X\n",(int)type);
4758 _private_asn1_parse(context, cert, &buffer[pos],
4759 length, level + 1, fields,
4760 &local_has_key, client_cert,
4761 top_oid, &local_chain);
4762 if (((local_has_key && context
4763 && (!context->is_server || client_cert))
4765 && (_is_field(fields, pk_id))) {
4766 free(cert->der_bytes);
4767 temp = length + (pos - start_pos);
4768 cert->der_bytes = malloc(temp);
4769 if (cert->der_bytes) {
4770 memcpy(cert->der_bytes,
4771 &buffer[start_pos], temp);
4772 cert->der_len = temp;
4780 /* end of content */
4781 DEBUG_PRINT("END OF CONTENT\n");
4787 DEBUG_PRINT("BOOLEAN: %i\n", temp);
4791 if (_is_field(fields, pk_id)) {
4797 tls_certificate_set_key
4798 (cert, &buffer[pos],
4800 } else if (idx == 2) {
4801 tls_certificate_set_exponent
4802 (cert, &buffer[pos],
4805 } else if (_is_field(fields, serial_id)) {
4806 tls_certificate_set_serial(cert,
4812 if (_is_field(fields, version_id)) {
4817 #ifdef TLS_X509_V1_SUPPORT
4825 unsigned int fields_temp[3];
4826 fields_temp[0] = fields[level - 2];
4827 fields_temp[1] = fields[level - 1];
4830 (fields_temp, priv_id)) {
4831 tls_certificate_set_priv
4832 (cert, &buffer[pos],
4836 DEBUG_PRINT("INTEGER(%i): ", length);
4837 DEBUG_DUMP_HEX(&buffer[pos], length);
4838 if ((chain) && (length > 2)) {
4841 sizeof(san_oid) - 1)) {
4845 TLS_REALLOC(cert->san,
4857 tls_certificate_set_copy
4864 (" => SUBJECT ALTERNATIVE NAME: %s",
4881 if (_is_field(fields, pk_id)) {
4886 DEBUG_PRINT("BITSTREAM(%i): ", length);
4887 DEBUG_DUMP_HEX(&buffer[pos], length);
4889 if (_is_field(fields, sign_id)
4890 || _is_field(fields, sign_id2)) {
4891 DEBUG_PRINT("set sign key\n");
4892 tls_certificate_set_sign_key(cert,
4896 } else if (cert->ec_algorithm
4897 && (_is_field(fields, pk_id))) {
4898 tls_certificate_set_key(cert,
4903 if (buffer[pos] == 0x00
4908 length - 1, level + 1,
4911 client_cert, top_oid,
4916 &buffer[pos], length,
4919 client_cert, top_oid,
4926 TLS_EC_prime256v1_OID,
4929 (TLS_EC_prime256v1) -
4937 TLS_EC_secp224r1_OID,
4940 (TLS_EC_secp224r1_OID)
4948 TLS_EC_secp384r1_OID,
4951 (TLS_EC_secp384r1_OID)
4959 TLS_EC_secp521r1_OID,
4962 (TLS_EC_secp521r1_OID)
4968 if ((cert->ec_algorithm)
4970 tls_certificate_set_key
4978 if (top_oid && _is_field(fields, ecc_priv_id)
4980 DEBUG_PRINT("BINARY STRING(%i): ",
4982 DEBUG_DUMP_HEX(&buffer[pos],
4985 tls_certificate_set_priv(cert,
4990 _private_asn1_parse(context, cert,
5002 DEBUG_PRINT("NULL\n");
5005 /* object identifier */
5006 if (_is_field(fields, pk_id)) {
5007 if (length == 8 || length == 5) {
5008 tls_certificate_set_algorithm
5009 (&cert->ec_algorithm,
5010 &buffer[pos], length);
5012 tls_certificate_set_algorithm
5013 (&cert->key_algorithm,
5014 &buffer[pos], length);
5017 if (_is_field(fields, algorithm_id))
5018 tls_certificate_set_algorithm
5020 &buffer[pos], length);
5022 DEBUG_PRINT("OBJECT IDENTIFIER(%i): ", length);
5023 DEBUG_DUMP_HEX(&buffer[pos], length);
5025 /* check previous oid */
5028 sizeof(ocsp_oid) - 1))
5029 tls_certificate_set_copy(&cert->ocsp,
5034 memcpy(oid, &buffer[pos], length);
5036 memcpy(oid, &buffer[pos], 16);
5039 memcpy(top_oid, oid, 16);
5042 DEBUG_PRINT("REAL NUMBER(%i): ", length);
5043 DEBUG_DUMP_HEX(&buffer[pos], length);
5048 DEBUG_PRINT("UTC TIME: [");
5049 DEBUG_DUMP(&buffer[pos], length);
5052 if (_is_field(fields, validity_id)) {
5054 tls_certificate_set_copy_date
5056 &buffer[pos], length);
5058 tls_certificate_set_copy_date
5060 &buffer[pos], length);
5065 /* generalized time */
5066 DEBUG_PRINT("GENERALIZED TIME: [");
5067 DEBUG_DUMP(&buffer[pos], length);
5071 /* printable string */
5082 if (_is_field(fields, issurer_id)) {
5083 if (_is_oid(oid, country_oid, 3)) {
5084 tls_certificate_set_copy
5085 (&cert->issuer_country,
5086 &buffer[pos], length);
5088 (oid, state_oid, 3)) {
5089 tls_certificate_set_copy
5090 (&cert->issuer_state,
5091 &buffer[pos], length);
5093 (oid, location_oid, 3)) {
5094 tls_certificate_set_copy
5097 &buffer[pos], length);
5099 (oid, entity_oid, 3)) {
5100 tls_certificate_set_copy
5101 (&cert->issuer_entity,
5102 &buffer[pos], length);
5104 (oid, subject_oid, 3)) {
5105 tls_certificate_set_copy
5106 (&cert->issuer_subject,
5107 &buffer[pos], length);
5109 } else if (_is_field(fields, owner_id)) {
5110 if (_is_oid(oid, country_oid, 3)) {
5111 tls_certificate_set_copy
5113 &buffer[pos], length);
5115 (oid, state_oid, 3)) {
5116 tls_certificate_set_copy
5118 &buffer[pos], length);
5120 (oid, location_oid, 3)) {
5121 tls_certificate_set_copy
5123 &buffer[pos], length);
5125 (oid, entity_oid, 3)) {
5126 tls_certificate_set_copy
5128 &buffer[pos], length);
5130 (oid, subject_oid, 3)) {
5131 tls_certificate_set_copy
5133 &buffer[pos], length);
5136 DEBUG_PRINT("STR: [");
5137 DEBUG_DUMP(&buffer[pos], length);
5141 DEBUG_PRINT("EMPTY SEQUENCE\n");
5144 DEBUG_PRINT("ENUMERATED(%i): ", length);
5145 DEBUG_DUMP_HEX(&buffer[pos], length);
5149 DEBUG_PRINT("========> NOT SUPPORTED %x\n",
5151 /* not supported / needed */
5158 if (cert_len && cert_data) {
5159 int h = find_hash("sha256");
5160 size_t len = sizeof cert->fp;
5161 hash_memory(h, cert_data,cert_len, cert->fp, &len);
5164 if (level == 2 && cert->sign_key && cert->sign_len
5165 && cert_len && cert_data) {
5166 free(cert->fingerprint);
5167 cert->fingerprint = tls_compute_hash(cert->algorithm,
5168 cert_data, cert_len);
5170 if (cert->fingerprint) {
5171 DEBUG_DUMP_HEX_LABEL("FINGERPRINT",
5173 tls_hash_len(cert->algorithm));
5180 struct TLSCertificate *asn1_parse(struct TLSContext *context,
5181 const unsigned char *buffer, int size,
5183 unsigned int fields[TLS_ASN1_MAXLEVEL] = { 0 };
5185 struct TLSCertificate *cert = tls_create_certificate();
5188 if (client_cert < 0) {
5191 unsigned char top_oid[16];
5192 memset(top_oid, 0, sizeof(top_oid));
5193 _private_asn1_parse(context, cert, buffer, size, 1,
5194 fields, NULL, client_cert,
5197 _private_asn1_parse(context, cert, buffer, size, 1,
5198 fields, NULL, client_cert,
5205 int tls_clear_certificates(struct TLSContext *tls) {
5208 if (!tls || !tls->is_server || tls->is_child) {
5209 return TLS_GENERIC_ERROR;
5212 if (tls->root_certificates) {
5213 for (i = 0; i < tls->root_count; i++) {
5214 tls_destroy_certificate(tls->root_certificates[i]);
5217 tls->root_certificates = NULL;
5218 tls->root_count = 0;
5220 if (tls->private_key) {
5221 tls_destroy_certificate(tls->private_key);
5223 tls->private_key = NULL;
5224 if (tls->ec_private_key) {
5225 tls_destroy_certificate(tls->ec_private_key);
5227 tls->ec_private_key = NULL;
5228 free(tls->certificates);
5229 tls->certificates = NULL;
5230 tls->certificates_count = 0;
5234 /* This is just a wrapper around parse message so we don't
5235 * call read more often than necessary. IOW, if there's
5236 * more than one record in the input buffer, process them all
5238 int tls_consume_stream(struct TLSContext *context) {
5240 return TLS_GENERIC_ERROR;
5243 if (context->critical_error) {
5244 return TLS_BROKEN_CONNECTION;
5247 size_t tls_buffer_len = context->input_buffer.len;
5248 unsigned char *buffer = context->input_buffer.buffer;
5250 unsigned int index = 0;
5253 int tls_header_size;
5254 int tls_size_offset;
5256 tls_size_offset = 3;
5257 tls_header_size = 5;
5259 while (tls_buffer_len >= 5) {
5262 length = get16(buffer + index + tls_size_offset)
5265 if (length > tls_buffer_len) {
5266 /* record not complete */
5270 /* This is the only place tls_parse_message is called */
5271 int consumed = tls_parse_message(context, buffer+index, length);
5273 err_flag = consumed;
5277 tls_buffer_len -= length;
5278 if (context->critical_error) {
5279 err_flag = TLS_BROKEN_CONNECTION;
5284 if (err_flag || context->input_buffer.error) {
5285 if (!context->critical_error) {
5286 context->critical_error = 1;
5288 DEBUG_PRINT("ERROR IN CONSUME: %i\n", err_flag);
5289 tls_buffer_free(&context->input_buffer);
5292 tls_buffer_shift(&context->input_buffer, index);
5296 void tls_close_notify(struct TLSContext *context) {
5297 if (!context || context->critical_error) {
5300 context->critical_error = 1;
5301 DEBUG_PRINT("CLOSE\n");
5302 tls_alert(context, 0, close_notify);
5305 void tls_alert(struct TLSContext *context, int critical, int code) {
5310 struct TLSPacket *packet = tls_create_packet(context, TLS_ALERT,
5311 context->version, 0);
5312 tls_packet_uint8(packet, critical ? TLS_ALERT_CRITICAL :
5315 tls_packet_uint8(packet, code);
5316 tls_packet_update(packet);
5319 context->critical_error = 1;
5322 tls_queue_packet(packet);
5325 int tls_is_broken(struct TLSContext *context) {
5326 if (!context || context->critical_error) {
5332 /* TODO I don't see that this ever gets cleared */
5333 int tls_request_client_certificate(struct TLSContext *context) {
5334 if (!context || !context->is_server) {
5338 context->request_client_certificate = 1;
5342 int tls_client_verified(struct TLSContext *context) {
5343 if (!context || context->critical_error) {
5347 return context->client_verified == 1;
5350 int tls_sni_set(struct TLSContext *context, const char *sni) {
5351 if (!context || context->is_server || context->critical_error
5352 || context->connection_status != 0) {
5358 context->sni = sni ? strdup(sni) : 0;
5359 return context->sni ? 1 : 0;
5362 int tls_default_verify(struct TLSContext *context,
5363 struct TLSCertificate **certificate_chain, int len)
5368 if (certificate_chain) {
5369 for (i = 0; i < len; i++) {
5370 struct TLSCertificate *certificate =
5371 certificate_chain[i];
5372 /* check validity date */
5373 err = tls_certificate_is_valid(certificate);
5379 /* check if chain is valid */
5380 err = tls_certificate_chain_is_valid(certificate_chain, len);
5385 /* check certificate subject */
5386 if (!context->is_server && context->sni && len > 0
5387 && certificate_chain) {
5388 err = tls_certificate_valid_subject(certificate_chain[0],
5395 err = tls_certificate_chain_is_valid_root(context, certificate_chain,
5401 DEBUG_PRINT("Certificate OK\n");
5405 ssize_t tls_fsync(struct TLSContext *context) {
5408 ssize_t send_res = 0;
5410 unsigned char *buffer;
5411 tls_send_func write_cb = NULL;
5422 buffer = context->output_buffer.buffer;
5423 buflen = context->output_buffer.len;
5425 if (context->send) {
5426 write_cb = context->send;
5431 while (buflen > 0) {
5434 res = write_cb(fd, buffer+offset, buflen, 0);
5436 perror("send error");
5444 DEBUG_PRINT("sent %zd bytes\n", send_res);
5445 context->output_buffer.len = 0;
5449 void tls_free(struct TLSContext *context) {
5451 free(context->user_data);
5452 tls_destroy_context(context);
5456 int tls_set_fd(struct TLSContext *context, int socket) {
5458 return TLS_GENERIC_ERROR;
5460 context->fd = socket;
5464 int tls_load_root_file(struct TLSContext *context, const char *pem_filename) {
5475 fd = open(pem_filename, O_RDONLY);
5480 if (fstat(fd, &st) == -1) {
5485 addr = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
5486 if (addr == MAP_FAILED) {
5491 count = tls_load_root_certificates(context, addr, st.st_size);
5492 munmap(addr, st.st_size);
5498 void tls_set_verify(struct TLSContext *tls, tls_validation_function vfunc) {
5500 tls->certificate_verify = vfunc;
5504 static ssize_t tls_safe_read(struct TLSContext *tls) {
5505 tls_recv_func read_cb;
5509 if (!tls || tls->fd <= 0) {
5510 return TLS_GENERIC_ERROR;
5514 read_cb = tls->recv;
5520 bytes = read_cb(tls->fd, buffer, sizeof buffer, 0);
5522 tls_buffer_append(&tls->input_buffer, buffer, bytes);
5528 /* I think this is the server handshake */
5529 int SSL_accept(struct TLSContext *context) {
5530 ssize_t read_size = 0;
5532 if (!context || context->fd <= 0) {
5533 return TLS_GENERIC_ERROR;
5536 if (tls_established(context)) {
5541 while ((read_size = tls_safe_read(context)) > 0) {
5542 if (tls_consume_stream(context) >= 0) {
5543 ssize_t res = tls_fsync(context);
5548 if (tls_established(context)) {
5552 if (read_size <= 0) {
5553 return TLS_BROKEN_CONNECTION;
5558 /* TODO this is really do the handshake */
5559 int tls_connect(struct TLSContext *context) {
5564 if (!context || context->fd < 0 || context->critical_error) {
5567 } else if (context->fd < 0) {
5573 return TLS_GENERIC_ERROR;
5577 if (context->is_server) {
5578 return TLS_UNEXPECTED_MESSAGE;
5582 res = tls_queue_packet(tls_build_client_hello(context));
5590 res = tls_fsync(context);
5596 while ((read_size = tls_safe_read(context)) > 0) {
5597 if ((res = tls_consume_stream(context)) >= 0) {
5598 res = tls_fsync(context);
5604 if (tls_established(context)) {
5608 if (context->critical_error) {
5609 fprintf(stderr, "critical error: %d\n",
5610 context->critical_error);
5611 return TLS_GENERIC_ERROR;
5618 int tls_shutdown(struct TLSContext *tls) {
5619 if (!tls || tls->fd <= 0) {
5620 return TLS_GENERIC_ERROR;
5623 tls_close_notify(tls);
5627 /* TODO configure for maximum packet data length
5628 * max is 2^14 - 5 byte header - 32 byte mac - padding which depends
5629 * on the cipher (up to 255 bytes I think).
5631 ssize_t tls_write(struct TLSContext *context, const void *buf, size_t count) {
5633 return TLS_GENERIC_ERROR;
5635 if (context->connection_status != TLS_CONNECTED) {
5636 return TLS_UNEXPECTED_MESSAGE;
5638 if (count > TLS_MAXTLS_APP_SIZE) {
5639 count = TLS_MAXTLS_APP_SIZE;
5642 if (!buf || !count) {
5646 struct TLSPacket *packet = tls_create_packet(context,
5647 TLS_APPLICATION_DATA, context->version, count);
5648 tls_packet_append(packet, buf, count);
5649 tls_packet_update(packet);
5651 tls_queue_packet(packet);
5652 /* TODO think about this. context->sync with O_NONBLOCK might be a
5655 if (context->sync) {
5657 res = tls_fsync(context);
5665 static ssize_t tls_readbuf(struct TLSContext *tls, void *buf, size_t count) {
5666 if (count > tls->application_buffer.len) {
5667 count = tls->application_buffer.len;
5671 /* TODO should have a buffer read and shift */
5672 memcpy(buf, tls->application_buffer.buffer, count);
5673 tls_buffer_shift(&tls->application_buffer, count);
5679 ssize_t tls_read(struct TLSContext *context, void *buf, size_t count) {
5681 return TLS_GENERIC_ERROR;
5684 if (context->application_buffer.len) {
5685 return tls_readbuf(context, buf, count);
5688 if (context->fd <= 0 || context->critical_error) {
5689 return TLS_GENERIC_ERROR;
5692 if (!tls_established(context)) {
5693 return TLS_GENERIC_ERROR;
5696 if (context->application_buffer.len == 0 && !context->critical_error) {
5697 /* attempt to fill buffer, unless we're already in an error
5702 while ((read_size = tls_safe_read(context)) > 0) {
5703 if (tls_consume_stream(context) > 0) {
5707 if (context->critical_error
5708 && !context->application_buffer.len) {
5709 /* if there's a critical error, don't bail if
5710 * we managed to get some data
5712 return TLS_GENERIC_ERROR;
5716 if (read_size <= 0 && context->application_buffer.len == 0) {
5717 /* can return errors as for read(2) */
5722 return tls_readbuf(context, buf, count);