2 * Copyright (C) 2017 Denys Vlasenko
4 * Licensed under GPLv2, see file LICENSE in this source tree.
7 //config: bool "tls (debugging)"
10 //applet:IF_TLS(APPLET(tls, BB_DIR_USR_BIN, BB_SUID_DROP))
12 //kbuild:lib-$(CONFIG_TLS) += tls.o
13 //kbuild:lib-$(CONFIG_TLS) += tls_pstm.o
14 //kbuild:lib-$(CONFIG_TLS) += tls_pstm_montgomery_reduce.o
15 //kbuild:lib-$(CONFIG_TLS) += tls_pstm_mul_comba.o
16 //kbuild:lib-$(CONFIG_TLS) += tls_pstm_sqr_comba.o
17 //kbuild:lib-$(CONFIG_TLS) += tls_rsa.o
18 ////kbuild:lib-$(CONFIG_TLS) += tls_ciphers.o
19 ////kbuild:lib-$(CONFIG_TLS) += tls_aes.o
20 ////kbuild:lib-$(CONFIG_TLS) += tls_aes_gcm.o
22 //usage:#define tls_trivial_usage
23 //usage: "HOST[:PORT]"
24 //usage:#define tls_full_usage "\n\n"
31 # define dbg(...) fprintf(stderr, __VA_ARGS__)
33 # define dbg(...) ((void)0)
36 #define RECORD_TYPE_CHANGE_CIPHER_SPEC 20
37 #define RECORD_TYPE_ALERT 21
38 #define RECORD_TYPE_HANDSHAKE 22
39 #define RECORD_TYPE_APPLICATION_DATA 23
41 #define HANDSHAKE_HELLO_REQUEST 0
42 #define HANDSHAKE_CLIENT_HELLO 1
43 #define HANDSHAKE_SERVER_HELLO 2
44 #define HANDSHAKE_HELLO_VERIFY_REQUEST 3
45 #define HANDSHAKE_NEW_SESSION_TICKET 4
46 #define HANDSHAKE_CERTIFICATE 11
47 #define HANDSHAKE_SERVER_KEY_EXCHANGE 12
48 #define HANDSHAKE_CERTIFICATE_REQUEST 13
49 #define HANDSHAKE_SERVER_HELLO_DONE 14
50 #define HANDSHAKE_CERTIFICATE_VERIFY 15
51 #define HANDSHAKE_CLIENT_KEY_EXCHANGE 16
52 #define HANDSHAKE_FINISHED 20
54 #define SSL_HS_RANDOM_SIZE 32
55 #define SSL_HS_RSA_PREMASTER_SIZE 48
57 #define SSL_NULL_WITH_NULL_NULL 0x0000
58 #define SSL_RSA_WITH_NULL_MD5 0x0001
59 #define SSL_RSA_WITH_NULL_SHA 0x0002
60 #define SSL_RSA_WITH_RC4_128_MD5 0x0004
61 #define SSL_RSA_WITH_RC4_128_SHA 0x0005
62 #define SSL_RSA_WITH_3DES_EDE_CBC_SHA 0x000A /* 10 */
63 #define TLS_RSA_WITH_AES_128_CBC_SHA 0x002F /* 47 */
64 #define TLS_RSA_WITH_AES_256_CBC_SHA 0x0035 /* 53 */
65 #define TLS_RSA_WITH_NULL_SHA256 0x003B /* 59 */
67 #define TLS_EMPTY_RENEGOTIATION_INFO_SCSV 0x00FF
69 #define TLS_RSA_WITH_IDEA_CBC_SHA 0x0007 /* 7 */
70 #define SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA 0x0016 /* 22 */
71 #define SSL_DH_anon_WITH_RC4_128_MD5 0x0018 /* 24 */
72 #define SSL_DH_anon_WITH_3DES_EDE_CBC_SHA 0x001B /* 27 */
73 #define TLS_DHE_RSA_WITH_AES_128_CBC_SHA 0x0033 /* 51 */
74 #define TLS_DHE_RSA_WITH_AES_256_CBC_SHA 0x0039 /* 57 */
75 #define TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 0x0067 /* 103 */
76 #define TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 0x006B /* 107 */
77 #define TLS_DH_anon_WITH_AES_128_CBC_SHA 0x0034 /* 52 */
78 #define TLS_DH_anon_WITH_AES_256_CBC_SHA 0x003A /* 58 */
79 #define TLS_RSA_WITH_AES_128_CBC_SHA256 0x003C /* 60 */
80 #define TLS_RSA_WITH_AES_256_CBC_SHA256 0x003D /* 61 */
81 #define TLS_RSA_WITH_SEED_CBC_SHA 0x0096 /* 150 */
82 #define TLS_PSK_WITH_AES_128_CBC_SHA 0x008C /* 140 */
83 #define TLS_PSK_WITH_AES_128_CBC_SHA256 0x00AE /* 174 */
84 #define TLS_PSK_WITH_AES_256_CBC_SHA384 0x00AF /* 175 */
85 #define TLS_PSK_WITH_AES_256_CBC_SHA 0x008D /* 141 */
86 #define TLS_DHE_PSK_WITH_AES_128_CBC_SHA 0x0090 /* 144 */
87 #define TLS_DHE_PSK_WITH_AES_256_CBC_SHA 0x0091 /* 145 */
88 #define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0xC004 /* 49156 */
89 #define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0xC005 /* 49157 */
90 #define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0xC009 /* 49161 */
91 #define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0xC00A /* 49162 */
92 #define TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA 0xC012 /* 49170 */
93 #define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA 0xC013 /* 49171 */
94 #define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA 0xC014 /* 49172 */
95 #define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA 0xC00E /* 49166 */
96 #define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA 0xC00F /* 49167 */
97 #define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023 /* 49187 */
98 #define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 0xC024 /* 49188 */
99 #define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 0xC025 /* 49189 */
100 #define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 0xC026 /* 49190 */
101 #define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 0xC027 /* 49191 */
102 #define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 0xC028 /* 49192 */
103 #define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 0xC029 /* 49193 */
104 #define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 0xC02A /* 49194 */
106 // RFC 5288 "AES Galois Counter Mode (GCM) Cipher Suites for TLS"
107 #define TLS_RSA_WITH_AES_128_GCM_SHA256 0x009C /* 156 */
108 #define TLS_RSA_WITH_AES_256_GCM_SHA384 0x009D /* 157 */
109 #define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B /* 49195 */
110 #define TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0xC02C /* 49196 */
111 #define TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0xC02D /* 49197 */
112 #define TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0xC02E /* 49198 */
113 #define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xC02F /* 49199 */
114 #define TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0xC030 /* 49200 */
115 #define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 0xC031 /* 49201 */
116 #define TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 0xC032 /* 49202 */
118 //Tested against kernel.org:
122 //#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA // ok, recvs SERVER_KEY_EXCHANGE
126 //#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA // ok, recvs SERVER_KEY_EXCHANGE *** matrixssl uses this on my box
127 //#define CIPHER_ID TLS_RSA_WITH_AES_256_CBC_SHA256 // ok, no SERVER_KEY_EXCHANGE
129 //#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 // SSL_ALERT_HANDSHAKE_FAILURE
130 //#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
131 //#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 // ok, recvs SERVER_KEY_EXCHANGE
132 //#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
133 //#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
134 //#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
135 //#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
136 //#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
137 //#define CIPHER_ID TLS_RSA_WITH_AES_256_GCM_SHA384 // ok, no SERVER_KEY_EXCHANGE
138 //#define CIPHER_ID TLS_RSA_WITH_AES_128_GCM_SHA256 // ok, no SERVER_KEY_EXCHANGE *** select this?
139 #define CIPHER_ID TLS_RSA_WITH_NULL_SHA256 // for testing (does everything except encrypting)
140 //#define CIPHER_ID TLS_DH_anon_WITH_AES_256_CBC_SHA // SSL_ALERT_HANDSHAKE_FAILURE
141 //^^^^^^^^^^^^^^^^^^^^^^^ (tested b/c this one doesn't req server certs... no luck)
142 //test TLS_RSA_WITH_AES_128_CBC_SHA, in tls 1.2 it's mandated to be always supported
151 uint8_t proto_maj, proto_min;
152 uint8_t len16_hi, len16_lo;
155 typedef struct tls_state {
158 psRsaKey_t server_rsa_pub_key;
160 sha256_ctx_t handshake_sha256_ctx;
162 uint8_t client_and_server_rand32[2 * 32];
163 uint8_t master_secret[48];
165 uint8_t encrypt_on_write;
166 uint8_t decrypt_on_read;
167 uint8_t client_write_MAC_key[SHA256_OUTSIZE];
170 // Each connection state contains a sequence number, which is
171 // maintained separately for read and write states. The sequence
172 // number MUST be set to zero whenever a connection state is made the
173 // active state. Sequence numbers are of type uint64 and may not
175 uint64_t write_seq64_be;
178 // |6.2.1. Fragmentation
179 // | The record layer fragments information blocks into TLSPlaintext
180 // | records carrying data in chunks of 2^14 bytes or less. Client
181 // | message boundaries are not preserved in the record layer (i.e.,
182 // | multiple client messages of the same ContentType MAY be coalesced
183 // | into a single TLSPlaintext record, or a single message MAY be
184 // | fragmented across several records)
187 // | The length (in bytes) of the following TLSPlaintext.fragment.
188 // | The length MUST NOT exceed 2^14.
190 // | 6.2.2. Record Compression and Decompression
192 // | Compression must be lossless and may not increase the content length
193 // | by more than 1024 bytes. If the decompression function encounters a
194 // | TLSCompressed.fragment that would decompress to a length in excess of
195 // | 2^14 bytes, it MUST report a fatal decompression failure error.
198 // | The length (in bytes) of the following TLSCompressed.fragment.
199 // | The length MUST NOT exceed 2^14 + 1024.
201 // Since our buffer also contains 5-byte headers, make it a bit bigger:
204 uint8_t inbuf[18*1024];
208 static unsigned get24be(const uint8_t *p)
210 return 0x100*(0x100*p[0] + p[1]) + p[2];
214 static void dump_hex(const char *fmt, const void *vp, int len)
216 char hexbuf[32 * 1024 + 4];
217 const uint8_t *p = vp;
219 bin2hex(hexbuf, (void*)p, len)[0] = '\0';
223 static void dump_tls_record(const void *vp, int len)
225 const uint8_t *p = vp;
230 dump_hex("< |%s|\n", p, len);
233 xhdr_len = 0x100*p[3] + p[4];
234 dbg("< hdr_type:%u ver:%u.%u len:%u", p[0], p[1], p[2], xhdr_len);
237 if (len >= 4 && p[-5] == RECORD_TYPE_HANDSHAKE) {
238 unsigned len24 = get24be(p + 1);
239 dbg(" type:%u len24:%u", p[0], len24);
243 dump_hex(" |%s|\n", p, xhdr_len);
250 void tls_get_random(void *buf, unsigned len)
252 if (len != open_read_close("/dev/urandom", buf, len))
256 //TODO rename this to sha256_hash, and sha256_hash -> sha256_update
257 static void hash_sha256(uint8_t out[SHA256_OUTSIZE], const void *data, unsigned size)
261 sha256_hash(&ctx, data, size);
262 sha256_end(&ctx, out);
266 /* Nondestructively see the current hash value */
267 static void sha256_peek(sha256_ctx_t *ctx, void *buffer)
269 sha256_ctx_t ctx_copy = *ctx;
270 sha256_end(&ctx_copy, buffer);
273 static void sha256_hash_dbg(const char *fmt, sha256_ctx_t *ctx, const void *buffer, size_t len)
275 uint8_t h[SHA256_OUTSIZE];
277 sha256_hash(ctx, buffer, len);
278 dump_hex(fmt, buffer, len);
279 dbg(" (%u) ", (int)len);
281 dump_hex("%s\n", h, SHA256_OUTSIZE);
284 # define sha256_hash_dbg(fmt, ctx, buffer, len) \
285 sha256_hash(ctx, buffer, len)
286 #endif /* not TLS_DEBUG >= 2 */
289 // HMAC(key, text) based on a hash H (say, sha256) is:
290 // ipad = [0x36 x INSIZE]
291 // opad = [0x5c x INSIZE]
292 // HMAC(key, text) = H((key XOR opad) + H((key XOR ipad) + text))
294 // H(key XOR opad) and H(key XOR ipad) can be precomputed
295 // if we often need HMAC hmac with the same key.
297 // text is often given in disjoint pieces.
298 static void hmac_sha256_precomputed_v(uint8_t out[SHA256_OUTSIZE],
299 sha256_ctx_t *hashed_key_xor_ipad,
300 sha256_ctx_t *hashed_key_xor_opad,
305 /* hashed_key_xor_ipad contains unclosed "H((key XOR ipad) +" state */
306 /* hashed_key_xor_opad contains unclosed "H((key XOR opad) +" state */
308 /* calculate out = H((key XOR ipad) + text) */
309 while ((text = va_arg(va, uint8_t*)) != NULL) {
310 unsigned text_size = va_arg(va, unsigned);
311 sha256_hash(hashed_key_xor_ipad, text, text_size);
313 sha256_end(hashed_key_xor_ipad, out);
315 /* out = H((key XOR opad) + out) */
316 sha256_hash(hashed_key_xor_opad, out, SHA256_OUTSIZE);
317 sha256_end(hashed_key_xor_opad, out);
320 static void hmac_sha256(uint8_t out[SHA256_OUTSIZE], uint8_t *key, unsigned key_size, ...)
322 sha256_ctx_t hashed_key_xor_ipad;
323 sha256_ctx_t hashed_key_xor_opad;
324 uint8_t key_xor_ipad[SHA256_INSIZE];
325 uint8_t key_xor_opad[SHA256_INSIZE];
326 uint8_t tempkey[SHA256_OUTSIZE];
330 va_start(va, key_size);
332 // "The authentication key can be of any length up to INSIZE, the
333 // block length of the hash function. Applications that use keys longer
334 // than INSIZE bytes will first hash the key using H and then use the
335 // resultant OUTSIZE byte string as the actual key to HMAC."
336 if (key_size > SHA256_INSIZE) {
337 hash_sha256(tempkey, key, key_size);
339 key_size = SHA256_OUTSIZE;
342 for (i = 0; i < key_size; i++) {
343 key_xor_ipad[i] = key[i] ^ 0x36;
344 key_xor_opad[i] = key[i] ^ 0x5c;
346 for (; i < SHA256_INSIZE; i++) {
347 key_xor_ipad[i] = 0x36;
348 key_xor_opad[i] = 0x5c;
350 sha256_begin(&hashed_key_xor_ipad);
351 sha256_hash(&hashed_key_xor_ipad, key_xor_ipad, SHA256_INSIZE);
352 sha256_begin(&hashed_key_xor_opad);
353 sha256_hash(&hashed_key_xor_opad, key_xor_opad, SHA256_INSIZE);
355 hmac_sha256_precomputed_v(out, &hashed_key_xor_ipad, &hashed_key_xor_opad, va);
360 // 5. HMAC and the Pseudorandom Function
362 // In this section, we define one PRF, based on HMAC. This PRF with the
363 // SHA-256 hash function is used for all cipher suites defined in this
364 // document and in TLS documents published prior to this document when
365 // TLS 1.2 is negotiated.
367 // P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
368 // HMAC_hash(secret, A(2) + seed) +
369 // HMAC_hash(secret, A(3) + seed) + ...
370 // where + indicates concatenation.
371 // A() is defined as:
373 // A(1) = HMAC_hash(secret, A(0)) = HMAC_hash(secret, seed)
374 // A(i) = HMAC_hash(secret, A(i-1))
375 // P_hash can be iterated as many times as necessary to produce the
376 // required quantity of data. For example, if P_SHA256 is being used to
377 // create 80 bytes of data, it will have to be iterated three times
378 // (through A(3)), creating 96 bytes of output data; the last 16 bytes
379 // of the final iteration will then be discarded, leaving 80 bytes of
382 // TLS's PRF is created by applying P_hash to the secret as:
384 // PRF(secret, label, seed) = P_<hash>(secret, label + seed)
386 // The label is an ASCII string.
387 static void tls_prf_hmac_sha256(
388 uint8_t *outbuf, unsigned outbuf_size,
389 uint8_t *secret, unsigned secret_size,
391 uint8_t *seed, unsigned seed_size)
393 uint8_t a[SHA256_OUTSIZE];
394 uint8_t *out_p = outbuf;
395 unsigned label_size = strlen(label);
397 /* In P_hash() calculation, "seed" is "label + seed": */
398 #define SEED label, label_size, seed, seed_size
399 #define SECRET secret, secret_size
400 #define A a, (int)(sizeof(a))
402 /* A(1) = HMAC_hash(secret, seed) */
403 hmac_sha256(a, SECRET, SEED, NULL);
404 //TODO: convert hmac_sha256 to precomputed
407 /* HMAC_hash(secret, A(1) + seed) */
408 if (outbuf_size <= SHA256_OUTSIZE) {
409 /* Last, possibly incomplete, block */
410 /* (use a[] as temp buffer) */
411 hmac_sha256(a, SECRET, A, SEED, NULL);
412 memcpy(out_p, a, outbuf_size);
415 /* Not last block. Store directly to result buffer */
416 hmac_sha256(out_p, SECRET, A, SEED, NULL);
417 out_p += SHA256_OUTSIZE;
418 outbuf_size -= SHA256_OUTSIZE;
419 /* A(2) = HMAC_hash(secret, A(1)) */
420 hmac_sha256(a, SECRET, A, NULL);
428 tls_state_t *new_tls_state(void)
430 tls_state_t *tls = xzalloc(sizeof(*tls));
432 sha256_begin(&tls->handshake_sha256_ctx);
436 static void tls_error_die(tls_state_t *tls)
438 dump_tls_record(tls->inbuf, tls->insize + tls->tail);
443 // 6.2.3.1. Null or Standard Stream Cipher
445 // Stream ciphers (including BulkCipherAlgorithm.null; see Appendix A.6)
446 // convert TLSCompressed.fragment structures to and from stream
447 // TLSCiphertext.fragment structures.
449 // stream-ciphered struct {
450 // opaque content[TLSCompressed.length];
451 // opaque MAC[SecurityParameters.mac_length];
452 // } GenericStreamCipher;
454 // The MAC is generated as:
455 // MAC(MAC_write_key, seq_num +
456 // TLSCompressed.type +
457 // TLSCompressed.version +
458 // TLSCompressed.length +
459 // TLSCompressed.fragment);
460 // where "+" denotes concatenation.
462 // The sequence number for this record.
464 // The MAC algorithm specified by SecurityParameters.mac_algorithm.
466 // Note that the MAC is computed before encryption. The stream cipher
467 // encrypts the entire block, including the MAC.
469 // Appendix C. Cipher Suite Definitions
472 // Cipher Type Material Size Size
473 // ------------ ------ -------- ---- -----
474 // NULL Stream 0 0 N/A
475 // RC4_128 Stream 16 0 N/A
476 // 3DES_EDE_CBC Block 24 8 8
477 // AES_128_CBC Block 16 16 16
478 // AES_256_CBC Block 32 16 16
480 // MAC Algorithm mac_length mac_key_length
481 // -------- ----------- ---------- --------------
483 // MD5 HMAC-MD5 16 16
484 // SHA HMAC-SHA1 20 20
485 // SHA256 HMAC-SHA256 32 32
486 static void xwrite_and_hash(tls_state_t *tls, /*const*/ void *buf, unsigned size)
488 uint8_t mac_hash[SHA256_OUTSIZE];
489 struct record_hdr *xhdr = buf;
491 if (tls->encrypt_on_write) {
492 //TODO: convert hmac_sha256 to precomputed
493 hmac_sha256(mac_hash,
494 tls->client_write_MAC_key, sizeof(tls->client_write_MAC_key),
495 &tls->write_seq64_be, sizeof(tls->write_seq64_be),
498 tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(tls->write_seq64_be));
499 /* Temporarily change for writing */
500 xhdr->len16_lo += SHA256_OUTSIZE;
503 xwrite(tls->fd, buf, size);
504 dbg("wrote %u bytes\n", size);
506 if (tls->encrypt_on_write) {
507 xwrite(tls->fd, mac_hash, sizeof(mac_hash));
508 dbg("wrote %u bytes of hash\n", (int)sizeof(mac_hash));
509 xhdr->len16_lo -= SHA256_OUTSIZE;
512 /* Handshake hash does not include record headers */
513 if (size > 5 && xhdr->type == RECORD_TYPE_HANDSHAKE) {
514 sha256_hash_dbg(">> sha256:%s", &tls->handshake_sha256_ctx, (uint8_t*)buf + 5, size - 5);
518 static int xread_tls_block(tls_state_t *tls)
520 struct record_hdr *xhdr;
525 dbg("insize:%u tail:%u\n", tls->insize, tls->tail);
526 memmove(tls->inbuf, tls->inbuf + tls->insize, tls->tail);
529 target = sizeof(tls->inbuf);
531 if (total >= sizeof(*xhdr) && target == sizeof(tls->inbuf)) {
532 xhdr = (void*)tls->inbuf;
533 target = sizeof(*xhdr) + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
534 if (target >= sizeof(tls->inbuf)) {
535 /* malformed input (too long): yell and die */
540 // can also check type/proto_maj/proto_min here
542 /* if total >= target, we have a full packet (and possibly more)... */
543 if (total - target >= 0)
545 len = safe_read(tls->fd, tls->inbuf + total, sizeof(tls->inbuf) - total);
547 bb_perror_msg_and_die("short read");
550 tls->tail = total - target;
551 tls->insize = target;
552 target -= sizeof(*xhdr);
554 /* RFC 5246 is not saying it explicitly, but sha256 hash
555 * in our FINISHED record must include data of incoming packets too!
557 if (tls->inbuf[0] == RECORD_TYPE_HANDSHAKE) {
558 sha256_hash_dbg("<< sha256:%s", &tls->handshake_sha256_ctx, tls->inbuf + 5, target);
561 dbg("got block len:%u\n", target);
566 * DER parsing routines
568 static unsigned get_der_len(uint8_t **bodyp, uint8_t *der, uint8_t *end)
574 // if ((der[0] & 0x1f) == 0x1f) /* not single-byte item code? */
577 len = der[1]; /* maybe it's short len */
581 if (len == 0x80 || end - der < (int)(len - 0x7e)) {
582 /* 0x80 is "0 bytes of len", invalid DER: must use short len if can */
583 /* need 3 or 4 bytes for 81, 82 */
587 len1 = der[2]; /* if (len == 0x81) it's "ii 81 xx", fetch xx */
589 /* >0x82 is "3+ bytes of len", should not happen realistically */
592 if (len == 0x82) { /* it's "ii 82 xx yy" */
593 len1 = 0x100*len1 + der[3];
594 der += 1; /* skip [yy] */
596 der += 1; /* skip [xx] */
599 // xfunc_die(); /* invalid DER: must use short len if can */
601 der += 2; /* skip [code]+[1byte] */
603 if (end - der < (int)len)
610 static uint8_t *enter_der_item(uint8_t *der, uint8_t **endp)
613 unsigned len = get_der_len(&new_der, der, *endp);
614 dbg("entered der @%p:0x%02x len:%u inner_byte @%p:0x%02x\n", der, der[0], len, new_der, new_der[0]);
615 /* Move "end" position to cover only this item */
616 *endp = new_der + len;
620 static uint8_t *skip_der_item(uint8_t *der, uint8_t *end)
623 unsigned len = get_der_len(&new_der, der, end);
626 dbg("skipped der 0x%02x, next byte 0x%02x\n", der[0], new_der[0]);
630 static void der_binary_to_pstm(pstm_int *pstm_n, uint8_t *der, uint8_t *end)
633 unsigned len = get_der_len(&bin_ptr, der, end);
635 dbg("binary bytes:%u, first:0x%02x\n", len, bin_ptr[0]);
636 pstm_init_for_read_unsigned_bin(/*pool:*/ NULL, pstm_n, len);
637 pstm_read_unsigned_bin(pstm_n, bin_ptr, len);
641 static void find_key_in_der_cert(tls_state_t *tls, uint8_t *der, int len)
643 /* Certificate is a DER-encoded data structure. Each DER element has a length,
644 * which makes it easy to skip over large compound elements of any complexity
645 * without parsing them. Example: partial decode of kernel.org certificate:
646 * SEQ 0x05ac/1452 bytes (Certificate): 308205ac
647 * SEQ 0x0494/1172 bytes (tbsCertificate): 30820494
648 * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0] 3 bytes: a003
649 * INTEGER (version): 0201 02
650 * INTEGER 0x11 bytes (serialNumber): 0211 00 9f85bf664b0cddafca508679501b2be4
651 * //^^^^^^note: matrixSSL also allows [ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2] = 0x82 type
652 * SEQ 0x0d bytes (signatureAlgo): 300d
653 * OID 9 bytes: 0609 2a864886f70d01010b (OID_SHA256_RSA_SIG 42.134.72.134.247.13.1.1.11)
655 * SEQ 0x5f bytes (issuer): 305f
658 * OID 3 bytes: 0603 550406
659 * Printable string "FR": 1302 4652
662 * OID 3 bytes: 0603 550408
663 * Printable string "Paris": 1305 5061726973
666 * OID 3 bytes: 0603 550407
667 * Printable string "Paris": 1305 5061726973
670 * OID 3 bytes: 0603 55040a
671 * Printable string "Gandi": 1305 47616e6469
674 * OID 3 bytes: 0603 550403
675 * Printable string "Gandi Standard SSL CA 2": 1317 47616e6469205374616e646172642053534c2043412032
676 * SEQ 30 bytes (validity): 301e
677 * TIME "161011000000Z": 170d 3136313031313030303030305a
678 * TIME "191011235959Z": 170d 3139313031313233353935395a
679 * SEQ 0x5b/91 bytes (subject): 305b //I did not decode this
680 * 3121301f060355040b1318446f6d61696e20436f
681 * 6e74726f6c2056616c6964617465643121301f06
682 * 0355040b1318506f73697469766553534c204d75
683 * 6c74692d446f6d61696e31133011060355040313
684 * 0a6b65726e656c2e6f7267
685 * SEQ 0x01a2/418 bytes (subjectPublicKeyInfo): 308201a2
686 * SEQ 13 bytes (algorithm): 300d
687 * OID 9 bytes: 0609 2a864886f70d010101 (OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1)
689 * BITSTRING 0x018f/399 bytes (publicKey): 0382018f
691 * //after the zero byte, it appears key itself uses DER encoding:
692 * SEQ 0x018a/394 bytes: 3082018a
693 * INTEGER 0x0181/385 bytes (modulus): 02820181
694 * 00b1ab2fc727a3bef76780c9349bf3
695 * ...24 more blocks of 15 bytes each...
696 * 90e895291c6bc8693b65
697 * INTEGER 3 bytes (exponent): 0203 010001
698 * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0x3] 0x01e5 bytes (X509v3 extensions): a38201e5
699 * SEQ 0x01e1 bytes: 308201e1
701 * Certificate is a sequence of three elements:
702 * tbsCertificate (SEQ)
703 * signatureAlgorithm (AlgorithmIdentifier)
704 * signatureValue (BIT STRING)
706 * In turn, tbsCertificate is a sequence of:
709 * signatureAlgo (AlgorithmIdentifier)
710 * issuer (Name, has complex structure)
711 * validity (Validity, SEQ of two Times)
713 * subjectPublicKeyInfo (SEQ)
716 * subjectPublicKeyInfo is a sequence of:
717 * algorithm (AlgorithmIdentifier)
718 * publicKey (BIT STRING)
720 * We need Certificate.tbsCertificate.subjectPublicKeyInfo.publicKey
722 uint8_t *end = der + len;
724 /* enter "Certificate" item: [der, end) will be only Cert */
725 der = enter_der_item(der, &end);
727 /* enter "tbsCertificate" item: [der, end) will be only tbsCert */
728 der = enter_der_item(der, &end);
730 /* skip up to subjectPublicKeyInfo */
731 der = skip_der_item(der, end); /* version */
732 der = skip_der_item(der, end); /* serialNumber */
733 der = skip_der_item(der, end); /* signatureAlgo */
734 der = skip_der_item(der, end); /* issuer */
735 der = skip_der_item(der, end); /* validity */
736 der = skip_der_item(der, end); /* subject */
738 /* enter subjectPublicKeyInfo */
739 der = enter_der_item(der, &end);
740 { /* check subjectPublicKeyInfo.algorithm */
741 static const uint8_t expected[] = {
742 0x30,0x0d, // SEQ 13 bytes
743 0x06,0x09, 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01, // OID RSA_KEY_ALG 42.134.72.134.247.13.1.1.1
746 if (memcmp(der, expected, sizeof(expected)) != 0)
747 bb_error_msg_and_die("not RSA key");
749 /* skip subjectPublicKeyInfo.algorithm */
750 der = skip_der_item(der, end);
751 /* enter subjectPublicKeyInfo.publicKey */
752 // die_if_not_this_der_type(der, end, 0x03); /* must be BITSTRING */
753 der = enter_der_item(der, &end);
756 //based on getAsnRsaPubKey(), pkcs1ParsePrivBin() is also of note
757 dbg("key bytes:%u, first:0x%02x\n", (int)(end - der), der[0]);
758 if (end - der < 14) xfunc_die();
761 * SEQ 0x018a/394 bytes: 3082018a
762 * INTEGER 0x0181/385 bytes (modulus): 02820181 XX...XXX
763 * INTEGER 3 bytes (exponent): 0203 010001
765 if (*der != 0) /* "ignore bits", should be 0 */
768 der = enter_der_item(der, &end); /* enter SEQ */
769 /* memset(tls->server_rsa_pub_key, 0, sizeof(tls->server_rsa_pub_key)); - already is */
770 der_binary_to_pstm(&tls->server_rsa_pub_key.N, der, end); /* modulus */
771 der = skip_der_item(der, end);
772 der_binary_to_pstm(&tls->server_rsa_pub_key.e, der, end); /* exponent */
773 tls->server_rsa_pub_key.size = pstm_unsigned_bin_size(&tls->server_rsa_pub_key.N);
774 dbg("server_rsa_pub_key.size:%d\n", tls->server_rsa_pub_key.size);
778 * TLS Handshake routines
780 static int xread_tls_handshake_block(tls_state_t *tls, int min_len)
782 struct record_hdr *xhdr;
783 int len = xread_tls_block(tls);
785 xhdr = (void*)tls->inbuf;
787 || xhdr->type != RECORD_TYPE_HANDSHAKE
788 || xhdr->proto_maj != TLS_MAJ
789 || xhdr->proto_min != TLS_MIN
793 dbg("got HANDSHAKE\n");
797 static void send_client_hello(tls_state_t *tls)
799 struct client_hello {
800 struct record_hdr xhdr;
802 uint8_t len24_hi, len24_mid, len24_lo;
803 uint8_t proto_maj, proto_min;
805 uint8_t session_id_len;
806 /* uint8_t session_id[]; */
807 uint8_t cipherid_len16_hi, cipherid_len16_lo;
808 uint8_t cipherid[2 * 1]; /* actually variable */
809 uint8_t comprtypes_len;
810 uint8_t comprtypes[1]; /* actually variable */
812 struct client_hello hello;
814 memset(&hello, 0, sizeof(hello));
815 hello.xhdr.type = RECORD_TYPE_HANDSHAKE;
816 hello.xhdr.proto_maj = TLS_MAJ;
817 hello.xhdr.proto_min = TLS_MIN;
818 //zero: hello.xhdr.len16_hi = (sizeof(hello) - sizeof(hello.xhdr)) >> 8;
819 hello.xhdr.len16_lo = (sizeof(hello) - sizeof(hello.xhdr));
820 hello.type = HANDSHAKE_CLIENT_HELLO;
821 //hello.len24_hi = 0;
822 //zero: hello.len24_mid = (sizeof(hello) - sizeof(hello.xhdr) - 4) >> 8;
823 hello.len24_lo = (sizeof(hello) - sizeof(hello.xhdr) - 4);
824 hello.proto_maj = TLS_MAJ; /* the "requested" version of the protocol, */
825 hello.proto_min = TLS_MIN; /* can be higher than one in record headers */
826 tls_get_random(hello.rand32, sizeof(hello.rand32));
827 //hello.session_id_len = 0;
828 //hello.cipherid_len16_hi = 0;
829 hello.cipherid_len16_lo = 2 * 1;
830 hello.cipherid[0] = CIPHER_ID >> 8;
831 hello.cipherid[1] = CIPHER_ID & 0xff;
832 hello.comprtypes_len = 1;
833 //hello.comprtypes[0] = 0;
835 //dbg (make it repeatable): memset(hello.rand32, 0x11, sizeof(hello.rand32));
836 dbg(">> HANDSHAKE_CLIENT_HELLO\n");
837 xwrite_and_hash(tls, &hello, sizeof(hello));
838 memcpy(tls->client_and_server_rand32, hello.rand32, sizeof(hello.rand32));
841 static void get_server_hello(tls_state_t *tls)
843 struct server_hello {
844 struct record_hdr xhdr;
846 uint8_t len24_hi, len24_mid, len24_lo;
847 uint8_t proto_maj, proto_min;
848 uint8_t rand32[32]; /* first 4 bytes are unix time in BE format */
849 uint8_t session_id_len;
850 uint8_t session_id[32];
851 uint8_t cipherid_hi, cipherid_lo;
853 /* extensions may follow, but only those which client offered in its Hello */
855 struct server_hello *hp;
858 xread_tls_handshake_block(tls, 74);
860 hp = (void*)tls->inbuf;
862 // 02 000046 03|03 58|78|cf|c1 50|a5|49|ee|7e|29|48|71|fe|97|fa|e8|2d|19|87|72|90|84|9d|37|a3|f0|cb|6f|5f|e3|3c|2f |20 |d8|1a|78|96|52|d6|91|01|24|b3|d6|5b|b7|d0|6c|b3|e1|78|4e|3c|95|de|74|a0|ba|eb|a7|3a|ff|bd|a2|bf |00|9c |00|
863 //SvHl len=70 maj.min unixtime^^^ 28randbytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^ slen sid32bytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cipSel comprSel
864 if (hp->type != HANDSHAKE_SERVER_HELLO
866 || hp->len24_mid != 0
867 /* hp->len24_lo checked later */
868 || hp->proto_maj != TLS_MAJ
869 || hp->proto_min != TLS_MIN
874 cipherid = &hp->cipherid_hi;
875 if (hp->session_id_len != 32) {
876 if (hp->session_id_len != 0)
879 // session_id_len == 0: no session id
881 // may return an empty session_id to indicate that the session will
882 // not be cached and therefore cannot be resumed."
884 hp->len24_lo += 32; /* what len would be if session id would be present */
887 if (hp->len24_lo < 70
888 || cipherid[0] != (CIPHER_ID >> 8)
889 || cipherid[1] != (CIPHER_ID & 0xff)
890 || cipherid[2] != 0 /* comprtype */
895 dbg("got SERVER_HELLO\n");
896 memcpy(tls->client_and_server_rand32 + 32, hp->rand32, sizeof(hp->rand32));
899 static void get_server_cert(tls_state_t *tls)
901 struct record_hdr *xhdr;
905 len = xread_tls_handshake_block(tls, 10);
907 xhdr = (void*)tls->inbuf;
908 certbuf = (void*)(xhdr + 1);
909 if (certbuf[0] != HANDSHAKE_CERTIFICATE)
911 dbg("got CERTIFICATE\n");
913 // 0b 00|11|24 00|11|21 00|05|b0 30|82|05|ac|30|82|04|94|a0|03|02|01|02|02|11|00|9f|85|bf|66|4b|0c|dd|af|ca|50|86|79|50|1b|2b|e4|30|0d...
914 //Cert len=4388 ChainLen CertLen^ DER encoded X509 starts here. openssl x509 -in FILE -inform DER -noout -text
915 len1 = get24be(certbuf + 1);
916 if (len1 > len - 4) tls_error_die(tls);
918 len1 = get24be(certbuf + 4);
919 if (len1 > len - 3) tls_error_die(tls);
921 len1 = get24be(certbuf + 7);
922 if (len1 > len - 3) tls_error_die(tls);
926 find_key_in_der_cert(tls, certbuf + 10, len);
929 static void send_client_key_exchange(tls_state_t *tls)
931 struct client_key_exchange {
932 struct record_hdr xhdr;
934 uint8_t len24_hi, len24_mid, len24_lo;
935 uint8_t keylen16_hi, keylen16_lo; /* exist for RSA, but not for some other key types */
936 //had a bug when had no keylen: we:
937 //write(3, "\x16\x03\x03\x01\x84\x10\x00\x01\x80\xXX\xXX\xXX\xXX\xXX\xXX...", 393) = 393
939 //write to 0xe9a090 [0xf9ac20] (395 bytes => 395 (0x18B))
940 //0000 - 16 03 03 01 86 10 00 01 -82 01 80 xx xx xx xx xx
941 uint8_t key[4 * 1024]; // size??
943 struct client_key_exchange record;
944 uint8_t rsa_premaster[SSL_HS_RSA_PREMASTER_SIZE];
947 memset(&record, 0, sizeof(record));
948 record.xhdr.type = RECORD_TYPE_HANDSHAKE;
949 record.xhdr.proto_maj = TLS_MAJ;
950 record.xhdr.proto_min = TLS_MIN;
951 record.type = HANDSHAKE_CLIENT_KEY_EXCHANGE;
953 tls_get_random(rsa_premaster, sizeof(rsa_premaster));
955 // "Note: The version number in the PreMasterSecret is the version
956 // offered by the client in the ClientHello.client_version, not the
957 // version negotiated for the connection."
958 rsa_premaster[0] = TLS_MAJ;
959 rsa_premaster[1] = TLS_MIN;
960 len = psRsaEncryptPub(/*pool:*/ NULL,
961 /* psRsaKey_t* */ &tls->server_rsa_pub_key,
962 rsa_premaster, /*inlen:*/ sizeof(rsa_premaster),
963 record.key, sizeof(record.key),
966 record.keylen16_hi = len >> 8;
967 record.keylen16_lo = len & 0xff;
969 //record.len24_hi = 0;
970 record.len24_mid = len >> 8;
971 record.len24_lo = len & 0xff;
973 record.xhdr.len16_hi = len >> 8;
974 record.xhdr.len16_lo = len & 0xff;
976 dbg(">> HANDSHAKE_CLIENT_KEY_EXCHANGE\n");
977 xwrite_and_hash(tls, &record, sizeof(record.xhdr) + len);
980 // For all key exchange methods, the same algorithm is used to convert
981 // the pre_master_secret into the master_secret. The pre_master_secret
982 // should be deleted from memory once the master_secret has been
984 // master_secret = PRF(pre_master_secret, "master secret",
985 // ClientHello.random + ServerHello.random)
987 // The master secret is always exactly 48 bytes in length. The length
988 // of the premaster secret will vary depending on key exchange method.
990 tls->master_secret, sizeof(tls->master_secret),
991 rsa_premaster, sizeof(rsa_premaster),
993 tls->client_and_server_rand32, sizeof(tls->client_and_server_rand32)
995 dump_hex("master secret:%s\n", tls->master_secret, sizeof(tls->master_secret));
998 // 6.3. Key Calculation
1000 // The Record Protocol requires an algorithm to generate keys required
1001 // by the current connection state (see Appendix A.6) from the security
1002 // parameters provided by the handshake protocol.
1004 // The master secret is expanded into a sequence of secure bytes, which
1005 // is then split to a client write MAC key, a server write MAC key, a
1006 // client write encryption key, and a server write encryption key. Each
1007 // of these is generated from the byte sequence in that order. Unused
1008 // values are empty. Some AEAD ciphers may additionally require a
1009 // client write IV and a server write IV (see Section 6.2.3.3).
1011 // When keys and MAC keys are generated, the master secret is used as an
1014 // To generate the key material, compute
1016 // key_block = PRF(SecurityParameters.master_secret,
1018 // SecurityParameters.server_random +
1019 // SecurityParameters.client_random);
1021 // until enough output has been generated. Then, the key_block is
1022 // partitioned as follows:
1024 // client_write_MAC_key[SecurityParameters.mac_key_length]
1025 // server_write_MAC_key[SecurityParameters.mac_key_length]
1026 // client_write_key[SecurityParameters.enc_key_length]
1027 // server_write_key[SecurityParameters.enc_key_length]
1028 // client_write_IV[SecurityParameters.fixed_iv_length]
1029 // server_write_IV[SecurityParameters.fixed_iv_length]
1032 /* make server_rand32 + client_rand32 */
1033 memcpy(&tmp64[0] , &tls->client_and_server_rand32[32], 32);
1034 memcpy(&tmp64[32], &tls->client_and_server_rand32[0] , 32);
1036 tls_prf_hmac_sha256(
1037 tls->client_write_MAC_key, sizeof(tls->client_write_MAC_key),
1038 tls->master_secret, sizeof(tls->master_secret),
1042 dump_hex("client_write_MAC_key:%s\n",
1043 tls->client_write_MAC_key, sizeof(tls->client_write_MAC_key)
1048 static const uint8_t rec_CHANGE_CIPHER_SPEC[] = {
1049 RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
1053 static void send_change_cipher_spec(tls_state_t *tls)
1055 /* Not "xwrite_and_hash": this is not a handshake message */
1056 dbg(">> CHANGE_CIPHER_SPEC\n");
1057 xwrite(tls->fd, rec_CHANGE_CIPHER_SPEC, sizeof(rec_CHANGE_CIPHER_SPEC));
1059 /* tls->write_seq64_be = 0; - already is */
1060 tls->encrypt_on_write = 1;
1064 // A Finished message is always sent immediately after a change
1065 // cipher spec message to verify that the key exchange and
1066 // authentication processes were successful. It is essential that a
1067 // change cipher spec message be received between the other handshake
1068 // messages and the Finished message.
1070 // The Finished message is the first one protected with the just
1071 // negotiated algorithms, keys, and secrets. Recipients of Finished
1072 // messages MUST verify that the contents are correct. Once a side
1073 // has sent its Finished message and received and validated the
1074 // Finished message from its peer, it may begin to send and receive
1075 // application data over the connection.
1078 // opaque verify_data[verify_data_length];
1082 // PRF(master_secret, finished_label, Hash(handshake_messages))
1083 // [0..verify_data_length-1];
1086 // For Finished messages sent by the client, the string
1087 // "client finished". For Finished messages sent by the server,
1088 // the string "server finished".
1090 // Hash denotes a Hash of the handshake messages. For the PRF
1091 // defined in Section 5, the Hash MUST be the Hash used as the basis
1092 // for the PRF. Any cipher suite which defines a different PRF MUST
1093 // also define the Hash to use in the Finished computation.
1095 // In previous versions of TLS, the verify_data was always 12 octets
1096 // long. In the current version of TLS, it depends on the cipher
1097 // suite. Any cipher suite which does not explicitly specify
1098 // verify_data_length has a verify_data_length equal to 12. This
1099 // includes all existing cipher suites.
1100 static void send_client_finished(tls_state_t *tls)
1102 struct client_finished {
1103 struct record_hdr xhdr;
1105 uint8_t len24_hi, len24_mid, len24_lo;
1106 uint8_t prf_result[12];
1108 struct client_finished record;
1109 uint8_t handshake_hash[SHA256_OUTSIZE];
1112 memset(&record, 0, sizeof(record));
1113 record.xhdr.type = RECORD_TYPE_HANDSHAKE;
1114 record.xhdr.proto_maj = TLS_MAJ;
1115 record.xhdr.proto_min = TLS_MIN;
1116 record.xhdr.len16_hi = (sizeof(record) - sizeof(record.xhdr)) >> 8;
1117 record.xhdr.len16_lo = (sizeof(record) - sizeof(record.xhdr)) & 0xff;
1118 record.type = HANDSHAKE_FINISHED;
1119 //record.len24_hi = 0;
1120 record.len24_mid = (sizeof(record) - sizeof(record.xhdr) - 4) >> 8;
1121 record.len24_lo = (sizeof(record) - sizeof(record.xhdr) - 4) & 0xff;
1122 //FIXME ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this code is repeatable
1124 ctx = tls->handshake_sha256_ctx; /* struct copy */
1125 sha256_end(&ctx, handshake_hash);
1126 tls_prf_hmac_sha256(record.prf_result, sizeof(record.prf_result),
1127 tls->master_secret, sizeof(tls->master_secret),
1129 handshake_hash, sizeof(handshake_hash)
1131 dump_hex("from secret: %s\n", tls->master_secret, sizeof(tls->master_secret));
1132 dump_hex("from labelSeed: %s", "client finished", sizeof("client finished")-1);
1133 dump_hex("%s\n", handshake_hash, sizeof(handshake_hash));
1134 dump_hex("=> digest: %s\n", record.prf_result, sizeof(record.prf_result));
1136 //(1) TODO: well, this should be encrypted on send, really.
1137 //(2) do we really need to also hash it?
1139 dbg(">> HANDSHAKE_FINISHED\n");
1140 xwrite_and_hash(tls, &record, sizeof(record));
1143 static void tls_handshake(tls_state_t *tls)
1145 // Client RFC 5246 Server
1146 // (*) - optional messages, not always sent
1148 // ClientHello ------->
1151 // ServerKeyExchange*
1152 // CertificateRequest*
1153 // <------- ServerHelloDone
1155 // ClientKeyExchange
1156 // CertificateVerify*
1157 // [ChangeCipherSpec]
1158 // Finished ------->
1159 // [ChangeCipherSpec]
1160 // <------- Finished
1161 // Application Data <------> Application Data
1164 send_client_hello(tls);
1165 get_server_hello(tls);
1168 // The server MUST send a Certificate message whenever the agreed-
1169 // upon key exchange method uses certificates for authentication
1170 // (this includes all key exchange methods defined in this document
1171 // except DH_anon). This message will always immediately follow the
1172 // ServerHello message.
1174 // IOW: in practice, Certificate *always* follows.
1175 // (for example, kernel.org does not even accept DH_anon cipher id)
1176 get_server_cert(tls);
1178 len = xread_tls_handshake_block(tls, 4);
1179 if (tls->inbuf[5] == HANDSHAKE_SERVER_KEY_EXCHANGE) {
1181 // 0c 00|01|c7 03|00|17|41|04|87|94|2e|2f|68|d0|c9|f4|97|a8|2d|ef|ed|67|ea|c6|f3|b3|56|47|5d|27|b6|bd|ee|70|25|30|5e|b0|8e|f6|21|5a...
1183 // with TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 461 bytes:
1184 // 0c 00|01|c9 03|00|17|41|04|cd|9b|b4|29|1f|f6|b0|c2|84|82|7f|29|6a|47|4e|ec|87|0b|c1|9c|69|e1|f8|c6|d0|53|e9|27|90|a5|c8|02|15|75...
1185 dbg("got SERVER_KEY_EXCHANGE len:%u\n", len);
1187 xread_tls_handshake_block(tls, 4);
1189 // if (tls->inbuf[5] == HANDSHAKE_CERTIFICATE_REQUEST) {
1190 // dbg("got CERTIFICATE_REQUEST\n");
1191 //RFC 5246: (in response to this,) "If no suitable certificate is available,
1192 // the client MUST send a certificate message containing no
1193 // certificates. That is, the certificate_list structure has a
1194 // length of zero. ...
1195 // Client certificates are sent using the Certificate structure
1196 // defined in Section 7.4.2."
1197 // (i.e. the same format as server certs)
1198 // xread_tls_handshake_block(tls, 4);
1200 if (tls->inbuf[5] != HANDSHAKE_SERVER_HELLO_DONE)
1202 // 0e 000000 (len:0)
1203 dbg("got SERVER_HELLO_DONE\n");
1205 send_client_key_exchange(tls);
1207 send_change_cipher_spec(tls);
1208 /* we now should send encrypted... as soon as we grok AES. */
1210 send_client_finished(tls);
1212 /* Get CHANGE_CIPHER_SPEC */
1213 len = xread_tls_block(tls);
1214 if (len != 1 || memcmp(tls->inbuf, rec_CHANGE_CIPHER_SPEC, 6) != 0)
1216 dbg("got CHANGE_CIPHER_SPEC\n");
1217 tls->decrypt_on_read = 1;
1218 /* we now should receive encrypted */
1220 /* Get (encrypted) FINISHED from the server */
1221 len = xread_tls_block(tls);
1222 if (len < 4 || tls->inbuf[5] != HANDSHAKE_FINISHED)
1224 dbg("got FINISHED\n");
1225 /* application data can be sent/received */
1228 // To run a test server using openssl:
1229 // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1
1230 // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
1232 int tls_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1233 int tls_main(int argc UNUSED_PARAM, char **argv)
1236 len_and_sockaddr *lsa;
1240 // getopt32(argv, "myopts")
1245 lsa = xhost2sockaddr(argv[1], 443);
1246 fd = xconnect_stream(lsa);
1248 tls = new_tls_state();
1252 return EXIT_SUCCESS;
1255 //TODO: implement RFC 5746 (Renegotiation Indication Extension) - some servers will refuse to work with us otherwise
1257 /* Unencryped SHA256 example:
1258 * $ openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
1259 * $ openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL
1260 * $ openssl s_client -connect 127.0.0.1:4433 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL-SHA256
1263 write to 0x1d750b0 [0x1e6f153] (99 bytes => 99 (0x63))
1264 0000 - 16 03 01 005e 01 00005a 0303 [4d ef 5c 82 3e ....^...Z..M.\.> >> ClHello
1265 0010 - bf a6 ee f1 1e 04 d1 5c-99 20 86 13 e9 0a cf 58 .......\. .....X
1266 0020 - 75 b1 bd 7a e6 d6 44 f3-d3 a1 52] 00 0004 003b u..z..D...R....; 003b = TLS_RSA_WITH_NULL_SHA256
1267 0030 - 00ff TLS_EMPTY_RENEGOTIATION_INFO_SCSV
1269 002d, 0023 0000, 000d 0020 [00 1e .....-.#..... .. extlen, SessionTicketTLS 0 bytes, SignatureAlgorithms 32 bytes
1270 0040 - 06 01 06 02 06 03 05 01-05 02 05 03 04 01 04 02 ................
1271 0050 - 04 03 03 01 03 02 03 03-02 01 02 02 02 03] 000f ................ Heart Beat 1 byte
1274 read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
1275 0000 - 16 03 03 00 3a ....:
1276 read from 0x1d750b0 [0x1e6ac08] (58 bytes => 58 (0x3A))
1277 0000 - 02 000036 0303 [f2 61-ae c8 58 e3 51 42 32 93 ...6...a..X.QB2. << SvHello
1278 0010 - c5 62 e4 f5 06 93 81 65-aa f7 df 74 af 7c 98 b4 .b.....e...t.|..
1279 0020 - 3e a7 35 c3 25 69] 00,003b,00.................. >.5.%i..;....... - no session id! "The server
1280 may return an empty session_id to indicate that the session will
1281 not be cached and therefore cannot be resumed."
1282 003b = TLS_RSA_WITH_NULL_SHA256 accepted, 00 - no compr
1283 000e ff01 0001 extlen, 0xff01=RenegotiationInfo 1 byte
1284 0030 - 00, 0023 0000, SessionTicketTLS 0 bytes
1285 000f 0001 01 ..#....... Heart Beat 1 byte
1287 read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
1288 0000 - 16 03 03 04 0b .....
1289 read from 0x1d750b0 [0x1e6ac08] (1035 bytes => 1035 (0x40B))
1290 0000 - 0b 00 04 07 00 04 04 00-04 01 30 82 03 fd 30 82 ..........0...0. << Cert
1291 0010 - 02 65 a0 03 02 01 02 02-09 00 d9 d9 8d b8 94 ad .e..............
1292 0020 - 2e 2b 30 0d 06 09 2a 86-48 86 f7 0d 01 01 0b 05 .+0...*.H.......
1293 0030 - 00 30 14 31 12 30 10 06-03 55 04 03 0c 09 6c 6f .0.1.0...U....lo
1294 0040 - 63 61 6c 68 6f 73 74 30-20 17 0d 31 37 30 31 31 calhost0 ..17011
1295 ...".......".......".......".......".......".......".......".......".....
1296 03f0 - 11 8a cd c5 a3 0a 22 43-d5 13 f9 a5 8a 06 f9 00 ......"C........
1297 0400 - 3c f7 86 4e e8 a5 d8 5b-92 37 f5 <..N...[.7.
1298 depth=0 CN = localhost
1299 verify error:num=18:self signed certificate
1301 depth=0 CN = localhost
1304 read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
1305 0000 - 16 03 03 00 04 .....
1307 read from 0x1d750b0 [0x1e6ac08] (4 bytes => 4 (0x4)) << SvDone
1309 0004 - <SPACES/NULS>
1311 write to 0x1d750b0 [0x1e74620] (395 bytes => 395 (0x18B)) >> ClDone
1312 0000 - 16 03 03 01 86 10 00 01-82 01 80 88 f0 87 5d b0 ..............].
1313 0010 - ea df 3b 4d e2 35 f3 99-e6 d4 29 87 36 86 ea 30 ..;M.5....).6..0
1314 0020 - 38 80 c7 37 66 7f 5b e7-23 38 7e 87 24 66 82 81 8..7f.[.#8~.$f..
1315 0030 - e4 ba 6c 2a 0c 92 a8 b9-39 c1 55 16 32 88 14 cd ..l*....9.U.2...
1316 0040 - 95 8c 82 49 a1 c7 f9 9b-e5 8f f6 5e 7e ee 91 b3 ...I.......^~...
1317 0050 - 2c 92 e7 a3 02 f8 9f 56-04 45 39 df a7 d6 1a 16 ,......V.E9.....
1318 0060 - 67 5c a4 f8 87 8a c4 c8-6c 6f c6 f0 9b c9 b4 87 g\......lo......
1319 0070 - 36 43 c1 67 9f b3 aa 11-34 b0 c2 fc 1f d9 e1 ff 6C.g....4.......
1320 0080 - fb e1 89 db 91 58 ec cc-aa 16 19 9a 91 74 e2 46 .....X.......t.F
1321 0090 - 22 a7 a7 f7 9e 3c 97 82-2c e4 21 b3 fa ef ba 3f "....<..,.!....?
1322 00a0 - 57 48 e4 b2 84 b7 c2 81-92 a9 f1 03 68 f4 e6 0c WH..........h...
1323 00b0 - fd 54 87 f5 e9 a0 5d e6-5f 0e bd 80 86 27 ab 0e .T....]._....'..
1324 00c0 - cf 92 4f bd fc 24 b9 54-72 5f 58 df 6b 2b 1d 97 ..O..$.Tr_X.k+..
1325 00d0 - 00 60 fe 95 b0 aa d6 c7-c1 3a f9 2e 7c 92 a9 6d .`.......:..|..m
1326 00e0 - 28 a3 ef 3e c1 e6 2d 2d-e8 db 81 ea 51 02 3f 64 (..>..--....Q.?d
1327 00f0 - a8 66 14 c1 4b 17 1f 55-c6 5b 3b 38 c3 6a 61 a8 .f..K..U.[;8.ja.
1328 0100 - f7 ad 65 7d cb 14 6d b3-0f 76 19 25 8e ed bd 53 ..e}..m..v.%...S
1329 0110 - 35 a9 a1 34 00 9d 07 81-84 51 35 e0 83 83 e3 a6 5..4.....Q5.....
1330 0120 - c7 77 4c 61 e4 78 9c cb-f5 92 4e d6 dd c4 c2 2b .wLa.x....N....+
1331 0130 - 75 9e 72 a6 7f 81 6a 1c-fc 4a 51 91 81 b4 cc 33 u.r...j..JQ....3
1332 0140 - 1c 8b 0a b6 94 8b 16 1b-86 2f 31 5e 31 e1 57 14 ........./1^1.W.
1333 0150 - 2e b5 09 5d cf 6f ea b2-94 e9 5c cc b9 fc 24 a0 ...].o....\...$.
1334 0160 - b7 f1 f4 9d 95 46 4f 08-5c 45 c6 2f 9f 7d 76 09 .....FO.\E./.}v.
1335 0170 - 6a af 50 2c 89 76 82 5f-e8 34 d8 4b 84 b6 34 18 j.P,.v._.4.K..4.
1336 0180 - 85 95 4a 3f 0f 28 88 3a-71 32 90 ..J?.(.:q2.
1338 write to 0x1d750b0 [0x1e74620] (6 bytes => 6 (0x6))
1339 0000 - 14 03 03 00 01 01 ...... >> CHANGE_CIPHER_SPEC
1341 write to 0x1d750b0 [0x1e74620] (53 bytes => 53 (0x35))
1342 0000 - 16 03 03 0030 14 00000c [ed b9 e1 33 36 0b 76 ....0.......36.v >> FINISHED (0x14) [PRF 12 bytes|SHA256_OUTSIZE 32 bytes]
1343 0010 - c0 d1 d4 0b a3|73 ec a8-fa b5 cb 12 b6 4c 2a b1 .....s.......L*.
1344 0020 - fb 42 7f 73 0d 06 1c 87-56 f0 db df e6 6a 25 aa .B.s....V....j%.
1345 0030 - fc 42 38 cb 0b] .B8..
1347 read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
1348 0000 - 16 03 03 00 aa .....
1349 read from 0x1d750b0 [0x1e6ac08] (170 bytes => 170 (0xAA))
1350 0000 - 04 00 00 a6 00 00 1c 20-00 a0 dd f4 52 01 54 8d ....... ....R.T. << NEW_SESSION_TICKET
1351 0010 - f8 a6 f9 2d 7d 19 20 5b-14 44 d3 2d 7b f2 ca e8 ...-}. [.D.-{...
1352 0020 - 01 4e 94 7b fe 12 59 3a-00 2e 7e cf 74 43 7a f7 .N.{..Y:..~.tCz.
1353 0030 - 9e cc 70 80 70 7c e3 a5-c6 9d 85 2c 36 19 4c 5c ..p.p|.....,6.L\
1354 0040 - ba 3b c3 e5 69 dc f3 a4-47 38 11 c9 7d 1a b0 6e .;..i...G8..}..n
1355 0050 - d8 49 a0 a8 e4 de 70 a8-d0 6b e4 7a b7 65 25 df .I....p..k.z.e%.
1356 0060 - 1b 5f 64 0f 89 69 02 72-fe eb d3 7a af 51 78 0e ._d..i.r...z.Qx.
1357 0070 - de 17 06 a5 f0 47 9d e0-04 d4 b1 1e be 7e ed bd .....G.......~..
1358 0080 - 27 8f 5d e8 ac f6 45 aa-e0 12 93 41 5f a8 4b b9 '.]...E....A_.K.
1359 0090 - bd 43 8f a1 23 51 af 92-77 8f 38 23 3e 2e c2 f0 .C..#Q..w.8#>...
1360 00a0 - a3 74 fa 83 94 ce 19 8a-5b 5b .t......[[
1362 read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
1363 0000 - 14 03 03 00 01 ..... << CHANGE_CIPHER_SPEC
1364 read from 0x1d750b0 [0x1e6ac08] (1 bytes => 1 (0x1))
1367 read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
1368 0000 - 16 03 03 00 30 ....0
1369 read from 0x1d750b0 [0x1e6ac08] (48 bytes => 48 (0x30))
1370 0000 - 14 00000c [06 86 0d 5c-92 0b 63 04 cc b4 f0 00 .......\..c..... << FINISHED (0x14) [PRF 12 bytes|SHA256_OUTSIZE 32 bytes]
1371 0010 -|49 d6 dd 56 73 e3 d2 e8-22 d6 bd 61 b2 b3 af f0 I..Vs..."..a....
1372 0020 - f5 00 8a 80 82 04 33 a7-50 8e ae 3b 4c 8c cf 4a] ......3.P..;L..J
1379 -----BEGIN CERTIFICATE-----
1380 ...".......".......".......".......".......".......".......".......".....
1381 -----END CERTIFICATE-----
1382 subject=/CN=localhost
1383 issuer=/CN=localhost
1385 No client certificate CA names sent
1387 SSL handshake has read 1346 bytes and written 553 bytes
1389 New, TLSv1/SSLv3, Cipher is NULL-SHA256
1390 Server public key is 3072 bit
1391 Secure Renegotiation IS supported
1397 Cipher : NULL-SHA256
1398 Session-ID: 5D62B36950F3DEB571707CD1B815E9E275041B9DB70D7F3E25C4A6535B13B616
1400 Master-Key: 4D08108C59417E0A41656636C51BA5B83F4EFFF9F4C860987B47B31250E5D1816D00940DBCCC196C2D99C8462C889DF1
1402 Krb5 Principal: None
1404 PSK identity hint: None
1405 TLS session ticket lifetime hint: 7200 (seconds)
1407 0000 - dd f4 52 01 54 8d f8 a6-f9 2d 7d 19 20 5b 14 44 ..R.T....-}. [.D
1408 0010 - d3 2d 7b f2 ca e8 01 4e-94 7b fe 12 59 3a 00 2e .-{....N.{..Y:..
1409 0020 - 7e cf 74 43 7a f7 9e cc-70 80 70 7c e3 a5 c6 9d ~.tCz...p.p|....
1410 0030 - 85 2c 36 19 4c 5c ba 3b-c3 e5 69 dc f3 a4 47 38 .,6.L\.;..i...G8
1411 0040 - 11 c9 7d 1a b0 6e d8 49-a0 a8 e4 de 70 a8 d0 6b ..}..n.I....p..k
1412 0050 - e4 7a b7 65 25 df 1b 5f-64 0f 89 69 02 72 fe eb .z.e%.._d..i.r..
1413 0060 - d3 7a af 51 78 0e de 17-06 a5 f0 47 9d e0 04 d4 .z.Qx......G....
1414 0070 - b1 1e be 7e ed bd 27 8f-5d e8 ac f6 45 aa e0 12 ...~..'.]...E...
1415 0080 - 93 41 5f a8 4b b9 bd 43-8f a1 23 51 af 92 77 8f .A_.K..C..#Q..w.
1416 0090 - 38 23 3e 2e c2 f0 a3 74-fa 83 94 ce 19 8a 5b 5b 8#>....t......[[
1418 Start Time: 1484574330
1419 Timeout : 7200 (sec)
1420 Verify return code: 18 (self signed certificate)
1422 read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
1423 0000 - 17 03 03 00 21 ....!
1424 read from 0x1d750b0 [0x1e6ac08] (33 bytes => 33 (0x21))
1425 0000 - 0a 74 5b 50 02 13 75 a4-27 0a 40 b1 53 74 52 14 .t[P..u.'.@.StR.
1426 0010 - e7 1e 6a 6c c1 60 2e 93-7e a5 d9 43 1d 8e f6 08 ..jl.`..~..C....
1429 read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
1430 0000 - 17 03 03 00 21 ....!
1431 read from 0x1d750b0 [0x1e6ac08] (33 bytes => 33 (0x21))
1432 0000 - 0a 1b ce 44 98 4f 81 c5-28 7a cc 79 62 db d2 86 ...D.O..(z.yb...
1433 0010 - 6a 55 a4 c7 73 49 ef 3e-bd 03 99 76 df 65 2a a1 jU..sI.>...v.e*.
1436 read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
1437 0000 - 17 03 03 00 21 ....!
1438 read from 0x1d750b0 [0x1e6ac08] (33 bytes => 33 (0x21))
1439 0000 - 0a 67 66 34 ba 68 36 3c-ad 0a c1 f5 c0 5a 50 fe .gf4.h6<.....ZP.
1440 0010 - 68 cd 04 65 e9 de 6e 98-f9 e2 41 1e 0b 9b 84 06 h..e..n...A.....