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 client_write_MAC_key[SHA256_OUTSIZE];
169 // Each connection state contains a sequence number, which is
170 // maintained separately for read and write states. The sequence
171 // number MUST be set to zero whenever a connection state is made the
172 // active state. Sequence numbers are of type uint64 and may not
174 uint64_t write_seq64_be;
177 // |6.2.1. Fragmentation
178 // | The record layer fragments information blocks into TLSPlaintext
179 // | records carrying data in chunks of 2^14 bytes or less. Client
180 // | message boundaries are not preserved in the record layer (i.e.,
181 // | multiple client messages of the same ContentType MAY be coalesced
182 // | into a single TLSPlaintext record, or a single message MAY be
183 // | fragmented across several records)
186 // | The length (in bytes) of the following TLSPlaintext.fragment.
187 // | The length MUST NOT exceed 2^14.
189 // | 6.2.2. Record Compression and Decompression
191 // | Compression must be lossless and may not increase the content length
192 // | by more than 1024 bytes. If the decompression function encounters a
193 // | TLSCompressed.fragment that would decompress to a length in excess of
194 // | 2^14 bytes, it MUST report a fatal decompression failure error.
197 // | The length (in bytes) of the following TLSCompressed.fragment.
198 // | The length MUST NOT exceed 2^14 + 1024.
200 // Since our buffer also contains 5-byte headers, make it a bit bigger:
203 uint8_t inbuf[18*1024];
207 static unsigned get24be(const uint8_t *p)
209 return 0x100*(0x100*p[0] + p[1]) + p[2];
213 static void dump_hex(const char *fmt, const void *vp, int len)
215 char hexbuf[32 * 1024 + 4];
216 const uint8_t *p = vp;
218 bin2hex(hexbuf, (void*)p, len)[0] = '\0';
222 static void dump_tls_record(const void *vp, int len)
224 const uint8_t *p = vp;
229 dump_hex("< |%s|\n", p, len);
232 xhdr_len = 0x100*p[3] + p[4];
233 dbg("< hdr_type:%u ver:%u.%u len:%u", p[0], p[1], p[2], xhdr_len);
236 if (len >= 4 && p[-5] == RECORD_TYPE_HANDSHAKE) {
237 unsigned len24 = get24be(p + 1);
238 dbg(" type:%u len24:%u", p[0], len24);
242 dump_hex(" |%s|\n", p, xhdr_len);
249 void tls_get_random(void *buf, unsigned len)
251 if (len != open_read_close("/dev/urandom", buf, len))
255 //TODO rename this to sha256_hash, and sha256_hash -> sha256_update
256 static void hash_sha256(uint8_t out[SHA256_OUTSIZE], const void *data, unsigned size)
260 sha256_hash(&ctx, data, size);
261 sha256_end(&ctx, out);
265 /* Nondestructively see the current hash value */
266 static void sha256_peek(sha256_ctx_t *ctx, void *buffer)
268 sha256_ctx_t ctx_copy = *ctx;
269 sha256_end(&ctx_copy, buffer);
272 static void sha256_hash_dbg(const char *fmt, sha256_ctx_t *ctx, const void *buffer, size_t len)
274 uint8_t h[SHA256_OUTSIZE];
276 sha256_hash(ctx, buffer, len);
277 dump_hex(fmt, buffer, len);
278 dbg(" (%u) ", (int)len);
280 dump_hex("%s\n", h, SHA256_OUTSIZE);
283 # define sha256_hash_dbg(fmt, ctx, buffer, len) \
284 sha256_hash(ctx, buffer, len)
285 #endif /* not TLS_DEBUG >= 2 */
288 tls_state_t *new_tls_state(void)
290 tls_state_t *tls = xzalloc(sizeof(*tls));
292 sha256_begin(&tls->handshake_sha256_ctx);
296 static void hmac_sha256(uint8_t out[SHA256_OUTSIZE], uint8_t *key, unsigned key_size, ...);
298 static void xwrite_and_hash(tls_state_t *tls, /*const*/ void *buf, unsigned size)
301 // 6.2.3.1. Null or Standard Stream Cipher
303 // Stream ciphers (including BulkCipherAlgorithm.null; see Appendix A.6)
304 // convert TLSCompressed.fragment structures to and from stream
305 // TLSCiphertext.fragment structures.
307 // stream-ciphered struct {
308 // opaque content[TLSCompressed.length];
309 // opaque MAC[SecurityParameters.mac_length];
310 // } GenericStreamCipher;
312 // The MAC is generated as:
314 // MAC(MAC_write_key, seq_num +
315 // TLSCompressed.type +
316 // TLSCompressed.version +
317 // TLSCompressed.length +
318 // TLSCompressed.fragment);
320 // where "+" denotes concatenation.
323 // The sequence number for this record.
326 // The MAC algorithm specified by SecurityParameters.mac_algorithm.
328 // Note that the MAC is computed before encryption. The stream cipher
329 // encrypts the entire block, including the MAC.
331 // Appendix C. Cipher Suite Definitions
334 // Cipher Type Material Size Size
335 // ------------ ------ -------- ---- -----
336 // NULL Stream 0 0 N/A
337 // RC4_128 Stream 16 0 N/A
338 // 3DES_EDE_CBC Block 24 8 8
339 // AES_128_CBC Block 16 16 16
340 // AES_256_CBC Block 32 16 16
342 // MAC Algorithm mac_length mac_key_length
343 // -------- ----------- ---------- --------------
345 // MD5 HMAC-MD5 16 16
346 // SHA HMAC-SHA1 20 20
347 // SHA256 HMAC-SHA256 32 32
349 uint8_t mac_hash[SHA256_OUTSIZE];
350 struct record_hdr *xhdr = buf;
352 if (tls->encrypt_on_write) {
353 hmac_sha256(mac_hash,
354 tls->client_write_MAC_key, sizeof(tls->client_write_MAC_key),
355 &tls->write_seq64_be, sizeof(tls->write_seq64_be),
358 tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(tls->write_seq64_be));
359 xhdr->len16_lo += SHA256_OUTSIZE;
360 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ FIXME
363 xwrite(tls->fd, buf, size);
364 dbg("wrote %u bytes\n", size);
365 if (tls->encrypt_on_write) {
366 xwrite(tls->fd, mac_hash, sizeof(mac_hash));
367 dbg("wrote %u bytes of hash\n", (int)sizeof(mac_hash));
368 xhdr->len16_lo -= SHA256_OUTSIZE;
371 /* Handshake hash does not include record headers */
372 if (size > 5 && xhdr->type == RECORD_TYPE_HANDSHAKE) {
373 sha256_hash_dbg(">> sha256:%s", &tls->handshake_sha256_ctx, (uint8_t*)buf + 5, size - 5);
377 static void tls_error_die(tls_state_t *tls)
379 dump_tls_record(tls->inbuf, tls->insize + tls->tail);
383 static int xread_tls_block(tls_state_t *tls)
385 struct record_hdr *xhdr;
390 dbg("insize:%u tail:%u\n", tls->insize, tls->tail);
391 memmove(tls->inbuf, tls->inbuf + tls->insize, tls->tail);
394 target = sizeof(tls->inbuf);
396 if (total >= sizeof(*xhdr) && target == sizeof(tls->inbuf)) {
397 xhdr = (void*)tls->inbuf;
398 target = sizeof(*xhdr) + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
399 if (target >= sizeof(tls->inbuf)) {
400 /* malformed input (too long): yell and die */
405 // can also check type/proto_maj/proto_min here
407 /* if total >= target, we have a full packet (and possibly more)... */
408 if (total - target >= 0)
410 len = safe_read(tls->fd, tls->inbuf + total, sizeof(tls->inbuf) - total);
412 bb_perror_msg_and_die("short read");
415 tls->tail = total - target;
416 tls->insize = target;
417 target -= sizeof(*xhdr);
419 /* RFC 5246 is not saying it explicitly, but sha256 hash
420 * in our FINISHED packet must include hashes of incoming packets too!
422 if (tls->inbuf[0] == RECORD_TYPE_HANDSHAKE) {
423 sha256_hash_dbg("<< sha256:%s", &tls->handshake_sha256_ctx, tls->inbuf + 5, target);
426 dbg("got block len:%u\n", target);
430 static int xread_tls_handshake_block(tls_state_t *tls, int min_len)
432 struct record_hdr *xhdr;
433 int len = xread_tls_block(tls);
435 xhdr = (void*)tls->inbuf;
437 || xhdr->type != RECORD_TYPE_HANDSHAKE
438 || xhdr->proto_maj != TLS_MAJ
439 || xhdr->proto_min != TLS_MIN
443 dbg("got HANDSHAKE\n");
447 static unsigned get_der_len(uint8_t **bodyp, uint8_t *der, uint8_t *end)
453 // if ((der[0] & 0x1f) == 0x1f) /* not single-byte item code? */
456 len = der[1]; /* maybe it's short len */
460 if (len == 0x80 || end - der < (int)(len - 0x7e)) {
461 /* 0x80 is "0 bytes of len", invalid DER: must use short len if can */
462 /* need 3 or 4 bytes for 81, 82 */
466 len1 = der[2]; /* if (len == 0x81) it's "ii 81 xx", fetch xx */
468 /* >0x82 is "3+ bytes of len", should not happen realistically */
471 if (len == 0x82) { /* it's "ii 82 xx yy" */
472 len1 = 0x100*len1 + der[3];
473 der += 1; /* skip [yy] */
475 der += 1; /* skip [xx] */
478 // xfunc_die(); /* invalid DER: must use short len if can */
480 der += 2; /* skip [code]+[1byte] */
482 if (end - der < (int)len)
489 static uint8_t *enter_der_item(uint8_t *der, uint8_t **endp)
492 unsigned len = get_der_len(&new_der, der, *endp);
493 dbg("entered der @%p:0x%02x len:%u inner_byte @%p:0x%02x\n", der, der[0], len, new_der, new_der[0]);
494 /* Move "end" position to cover only this item */
495 *endp = new_der + len;
499 static uint8_t *skip_der_item(uint8_t *der, uint8_t *end)
502 unsigned len = get_der_len(&new_der, der, end);
505 dbg("skipped der 0x%02x, next byte 0x%02x\n", der[0], new_der[0]);
509 static void der_binary_to_pstm(pstm_int *pstm_n, uint8_t *der, uint8_t *end)
512 unsigned len = get_der_len(&bin_ptr, der, end);
514 dbg("binary bytes:%u, first:0x%02x\n", len, bin_ptr[0]);
515 pstm_init_for_read_unsigned_bin(/*pool:*/ NULL, pstm_n, len);
516 pstm_read_unsigned_bin(pstm_n, bin_ptr, len);
520 static void find_key_in_der_cert(tls_state_t *tls, uint8_t *der, int len)
522 /* Certificate is a DER-encoded data structure. Each DER element has a length,
523 * which makes it easy to skip over large compound elements of any complexity
524 * without parsing them. Example: partial decode of kernel.org certificate:
525 * SEQ 0x05ac/1452 bytes (Certificate): 308205ac
526 * SEQ 0x0494/1172 bytes (tbsCertificate): 30820494
527 * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0] 3 bytes: a003
528 * INTEGER (version): 0201 02
529 * INTEGER 0x11 bytes (serialNumber): 0211 00 9f85bf664b0cddafca508679501b2be4
530 * //^^^^^^note: matrixSSL also allows [ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2] = 0x82 type
531 * SEQ 0x0d bytes (signatureAlgo): 300d
532 * OID 9 bytes: 0609 2a864886f70d01010b (OID_SHA256_RSA_SIG 42.134.72.134.247.13.1.1.11)
534 * SEQ 0x5f bytes (issuer): 305f
537 * OID 3 bytes: 0603 550406
538 * Printable string "FR": 1302 4652
541 * OID 3 bytes: 0603 550408
542 * Printable string "Paris": 1305 5061726973
545 * OID 3 bytes: 0603 550407
546 * Printable string "Paris": 1305 5061726973
549 * OID 3 bytes: 0603 55040a
550 * Printable string "Gandi": 1305 47616e6469
553 * OID 3 bytes: 0603 550403
554 * Printable string "Gandi Standard SSL CA 2": 1317 47616e6469205374616e646172642053534c2043412032
555 * SEQ 30 bytes (validity): 301e
556 * TIME "161011000000Z": 170d 3136313031313030303030305a
557 * TIME "191011235959Z": 170d 3139313031313233353935395a
558 * SEQ 0x5b/91 bytes (subject): 305b //I did not decode this
559 * 3121301f060355040b1318446f6d61696e20436f
560 * 6e74726f6c2056616c6964617465643121301f06
561 * 0355040b1318506f73697469766553534c204d75
562 * 6c74692d446f6d61696e31133011060355040313
563 * 0a6b65726e656c2e6f7267
564 * SEQ 0x01a2/418 bytes (subjectPublicKeyInfo): 308201a2
565 * SEQ 13 bytes (algorithm): 300d
566 * OID 9 bytes: 0609 2a864886f70d010101 (OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1)
568 * BITSTRING 0x018f/399 bytes (publicKey): 0382018f
570 * //after the zero byte, it appears key itself uses DER encoding:
571 * SEQ 0x018a/394 bytes: 3082018a
572 * INTEGER 0x0181/385 bytes (modulus): 02820181
573 * 00b1ab2fc727a3bef76780c9349bf3
574 * ...24 more blocks of 15 bytes each...
575 * 90e895291c6bc8693b65
576 * INTEGER 3 bytes (exponent): 0203 010001
577 * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0x3] 0x01e5 bytes (X509v3 extensions): a38201e5
578 * SEQ 0x01e1 bytes: 308201e1
580 * Certificate is a sequence of three elements:
581 * tbsCertificate (SEQ)
582 * signatureAlgorithm (AlgorithmIdentifier)
583 * signatureValue (BIT STRING)
585 * In turn, tbsCertificate is a sequence of:
588 * signatureAlgo (AlgorithmIdentifier)
589 * issuer (Name, has complex structure)
590 * validity (Validity, SEQ of two Times)
592 * subjectPublicKeyInfo (SEQ)
595 * subjectPublicKeyInfo is a sequence of:
596 * algorithm (AlgorithmIdentifier)
597 * publicKey (BIT STRING)
599 * We need Certificate.tbsCertificate.subjectPublicKeyInfo.publicKey
601 uint8_t *end = der + len;
603 /* enter "Certificate" item: [der, end) will be only Cert */
604 der = enter_der_item(der, &end);
606 /* enter "tbsCertificate" item: [der, end) will be only tbsCert */
607 der = enter_der_item(der, &end);
609 /* skip up to subjectPublicKeyInfo */
610 der = skip_der_item(der, end); /* version */
611 der = skip_der_item(der, end); /* serialNumber */
612 der = skip_der_item(der, end); /* signatureAlgo */
613 der = skip_der_item(der, end); /* issuer */
614 der = skip_der_item(der, end); /* validity */
615 der = skip_der_item(der, end); /* subject */
617 /* enter subjectPublicKeyInfo */
618 der = enter_der_item(der, &end);
619 { /* check subjectPublicKeyInfo.algorithm */
620 static const uint8_t expected[] = {
621 0x30,0x0d, // SEQ 13 bytes
622 0x06,0x09, 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01, // OID RSA_KEY_ALG 42.134.72.134.247.13.1.1.1
625 if (memcmp(der, expected, sizeof(expected)) != 0)
626 bb_error_msg_and_die("not RSA key");
628 /* skip subjectPublicKeyInfo.algorithm */
629 der = skip_der_item(der, end);
630 /* enter subjectPublicKeyInfo.publicKey */
631 // die_if_not_this_der_type(der, end, 0x03); /* must be BITSTRING */
632 der = enter_der_item(der, &end);
635 //based on getAsnRsaPubKey(), pkcs1ParsePrivBin() is also of note
636 dbg("key bytes:%u, first:0x%02x\n", (int)(end - der), der[0]);
637 if (end - der < 14) xfunc_die();
640 * SEQ 0x018a/394 bytes: 3082018a
641 * INTEGER 0x0181/385 bytes (modulus): 02820181 XX...XXX
642 * INTEGER 3 bytes (exponent): 0203 010001
644 if (*der != 0) /* "ignore bits", should be 0 */
647 der = enter_der_item(der, &end); /* enter SEQ */
648 /* memset(tls->server_rsa_pub_key, 0, sizeof(tls->server_rsa_pub_key)); - already is */
649 der_binary_to_pstm(&tls->server_rsa_pub_key.N, der, end); /* modulus */
650 der = skip_der_item(der, end);
651 der_binary_to_pstm(&tls->server_rsa_pub_key.e, der, end); /* exponent */
652 tls->server_rsa_pub_key.size = pstm_unsigned_bin_size(&tls->server_rsa_pub_key.N);
653 dbg("server_rsa_pub_key.size:%d\n", tls->server_rsa_pub_key.size);
656 // RFC 2104: HMAC(key, text) based on a hash H (say, sha256) is:
657 // ipad = [0x36 x INSIZE]
658 // opad = [0x5c x INSIZE]
659 // HMAC(key, text) = H((key XOR opad) + H((key XOR ipad) + text))
661 // H(key XOR opad) and H(key XOR ipad) can be precomputed
662 // if we often need HMAC hmac with the same key.
664 // text is often given in disjoint pieces.
665 static void hmac_sha256_precomputed_v(uint8_t out[SHA256_OUTSIZE],
666 sha256_ctx_t *hashed_key_xor_ipad,
667 sha256_ctx_t *hashed_key_xor_opad,
672 /* hashed_key_xor_ipad contains unclosed "H((key XOR ipad) +" state */
673 /* hashed_key_xor_opad contains unclosed "H((key XOR opad) +" state */
675 /* calculate out = H((key XOR ipad) + text) */
676 while ((text = va_arg(va, uint8_t*)) != NULL) {
677 unsigned text_size = va_arg(va, unsigned);
678 sha256_hash(hashed_key_xor_ipad, text, text_size);
680 sha256_end(hashed_key_xor_ipad, out);
682 /* out = H((key XOR opad) + out) */
683 sha256_hash(hashed_key_xor_opad, out, SHA256_OUTSIZE);
684 sha256_end(hashed_key_xor_opad, out);
687 static void hmac_sha256(uint8_t out[SHA256_OUTSIZE], uint8_t *key, unsigned key_size, ...)
689 sha256_ctx_t hashed_key_xor_ipad;
690 sha256_ctx_t hashed_key_xor_opad;
691 uint8_t key_xor_ipad[SHA256_INSIZE];
692 uint8_t key_xor_opad[SHA256_INSIZE];
693 uint8_t tempkey[SHA256_OUTSIZE];
697 va_start(va, key_size);
699 // "The authentication key can be of any length up to INSIZE, the
700 // block length of the hash function. Applications that use keys longer
701 // than INSIZE bytes will first hash the key using H and then use the
702 // resultant OUTSIZE byte string as the actual key to HMAC."
703 if (key_size > SHA256_INSIZE) {
704 hash_sha256(tempkey, key, key_size);
706 key_size = SHA256_OUTSIZE;
709 for (i = 0; i < key_size; i++) {
710 key_xor_ipad[i] = key[i] ^ 0x36;
711 key_xor_opad[i] = key[i] ^ 0x5c;
713 for (; i < SHA256_INSIZE; i++) {
714 key_xor_ipad[i] = 0x36;
715 key_xor_opad[i] = 0x5c;
717 sha256_begin(&hashed_key_xor_ipad);
718 sha256_hash(&hashed_key_xor_ipad, key_xor_ipad, SHA256_INSIZE);
719 sha256_begin(&hashed_key_xor_opad);
720 sha256_hash(&hashed_key_xor_opad, key_xor_opad, SHA256_INSIZE);
722 hmac_sha256_precomputed_v(out, &hashed_key_xor_ipad, &hashed_key_xor_opad, va);
727 // 5. HMAC and the Pseudorandom Function
729 // In this section, we define one PRF, based on HMAC. This PRF with the
730 // SHA-256 hash function is used for all cipher suites defined in this
731 // document and in TLS documents published prior to this document when
732 // TLS 1.2 is negotiated.
734 // P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
735 // HMAC_hash(secret, A(2) + seed) +
736 // HMAC_hash(secret, A(3) + seed) + ...
737 // where + indicates concatenation.
738 // A() is defined as:
740 // A(1) = HMAC_hash(secret, A(0)) = HMAC_hash(secret, seed)
741 // A(i) = HMAC_hash(secret, A(i-1))
742 // P_hash can be iterated as many times as necessary to produce the
743 // required quantity of data. For example, if P_SHA256 is being used to
744 // create 80 bytes of data, it will have to be iterated three times
745 // (through A(3)), creating 96 bytes of output data; the last 16 bytes
746 // of the final iteration will then be discarded, leaving 80 bytes of
749 // TLS's PRF is created by applying P_hash to the secret as:
751 // PRF(secret, label, seed) = P_<hash>(secret, label + seed)
753 // The label is an ASCII string.
754 static void tls_prf_hmac_sha256(
755 uint8_t *outbuf, unsigned outbuf_size,
756 uint8_t *secret, unsigned secret_size,
758 uint8_t *seed, unsigned seed_size)
760 uint8_t a[SHA256_OUTSIZE];
761 uint8_t *out_p = outbuf;
762 unsigned label_size = strlen(label);
764 /* In P_hash() calculation, "seed" is "label + seed": */
765 #define SEED label, label_size, seed, seed_size
766 #define SECRET secret, secret_size
767 #define A a, (int)(sizeof(a))
769 /* A(1) = HMAC_hash(secret, seed) */
770 hmac_sha256(a, SECRET, SEED, NULL);
771 //TODO: convert hmac_sha256 to precomputed
774 /* HMAC_hash(secret, A(1) + seed) */
775 if (outbuf_size <= SHA256_OUTSIZE) {
776 /* Last, possibly incomplete, block */
777 /* (use a[] as temp buffer) */
778 hmac_sha256(a, SECRET, A, SEED, NULL);
779 memcpy(out_p, a, outbuf_size);
782 /* Not last block. Store directly to result buffer */
783 hmac_sha256(out_p, SECRET, A, SEED, NULL);
784 out_p += SHA256_OUTSIZE;
785 outbuf_size -= SHA256_OUTSIZE;
786 /* A(2) = HMAC_hash(secret, A(1)) */
787 hmac_sha256(a, SECRET, A, NULL);
795 * TLS Handshake routines
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 void send_change_cipher_spec(tls_state_t *tls)
1050 static const uint8_t rec[] = {
1051 RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
1054 /* Not "xwrite_and_hash": this is not a handshake message */
1055 dbg(">> CHANGE_CIPHER_SPEC\n");
1056 xwrite(tls->fd, rec, sizeof(rec));
1058 tls->write_seq64_be = 0;
1059 tls->encrypt_on_write = 1;
1063 // A Finished message is always sent immediately after a change
1064 // cipher spec message to verify that the key exchange and
1065 // authentication processes were successful. It is essential that a
1066 // change cipher spec message be received between the other handshake
1067 // messages and the Finished message.
1069 // The Finished message is the first one protected with the just
1070 // negotiated algorithms, keys, and secrets. Recipients of Finished
1071 // messages MUST verify that the contents are correct. Once a side
1072 // has sent its Finished message and received and validated the
1073 // Finished message from its peer, it may begin to send and receive
1074 // application data over the connection.
1077 // opaque verify_data[verify_data_length];
1081 // PRF(master_secret, finished_label, Hash(handshake_messages))
1082 // [0..verify_data_length-1];
1085 // For Finished messages sent by the client, the string
1086 // "client finished". For Finished messages sent by the server,
1087 // the string "server finished".
1089 // Hash denotes a Hash of the handshake messages. For the PRF
1090 // defined in Section 5, the Hash MUST be the Hash used as the basis
1091 // for the PRF. Any cipher suite which defines a different PRF MUST
1092 // also define the Hash to use in the Finished computation.
1094 // In previous versions of TLS, the verify_data was always 12 octets
1095 // long. In the current version of TLS, it depends on the cipher
1096 // suite. Any cipher suite which does not explicitly specify
1097 // verify_data_length has a verify_data_length equal to 12. This
1098 // includes all existing cipher suites.
1099 static void send_client_finished(tls_state_t *tls)
1101 struct client_finished {
1102 struct record_hdr xhdr;
1104 uint8_t len24_hi, len24_mid, len24_lo;
1105 uint8_t prf_result[12];
1107 struct client_finished record;
1108 uint8_t handshake_hash[SHA256_OUTSIZE];
1111 memset(&record, 0, sizeof(record));
1112 record.xhdr.type = RECORD_TYPE_HANDSHAKE;
1113 record.xhdr.proto_maj = TLS_MAJ;
1114 record.xhdr.proto_min = TLS_MIN;
1115 record.xhdr.len16_hi = (sizeof(record) - sizeof(record.xhdr)) >> 8;
1116 record.xhdr.len16_lo = (sizeof(record) - sizeof(record.xhdr)) & 0xff;
1117 record.type = HANDSHAKE_FINISHED;
1118 //record.len24_hi = 0;
1119 record.len24_mid = (sizeof(record) - sizeof(record.xhdr) - 4) >> 8;
1120 record.len24_lo = (sizeof(record) - sizeof(record.xhdr) - 4) & 0xff;
1121 //FIXME ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this code is repeatable
1123 ctx = tls->handshake_sha256_ctx; /* struct copy */
1124 sha256_end(&ctx, handshake_hash);
1125 tls_prf_hmac_sha256(record.prf_result, sizeof(record.prf_result),
1126 tls->master_secret, sizeof(tls->master_secret),
1128 handshake_hash, sizeof(handshake_hash)
1130 dump_hex("from secret: %s\n", tls->master_secret, sizeof(tls->master_secret));
1131 dump_hex("from labelSeed: %s", "client finished", sizeof("client finished")-1);
1132 dump_hex("%s\n", handshake_hash, sizeof(handshake_hash));
1133 dump_hex("=> digest: %s\n", record.prf_result, sizeof(record.prf_result));
1135 //(1) TODO: well, this should be encrypted on send, really.
1136 //(2) do we really need to also hash it?
1138 dbg(">> HANDSHAKE_FINISHED\n");
1139 xwrite_and_hash(tls, &record, sizeof(record));
1142 static void get_change_cipher_spec(tls_state_t *tls)
1147 static void get_server_finished(tls_state_t *tls)
1152 static void tls_handshake(tls_state_t *tls)
1154 // Client RFC 5246 Server
1155 // (*) - optional messages, not always sent
1157 // ClientHello ------->
1160 // ServerKeyExchange*
1161 // CertificateRequest*
1162 // <------- ServerHelloDone
1164 // ClientKeyExchange
1165 // CertificateVerify*
1166 // [ChangeCipherSpec]
1167 // Finished ------->
1168 // [ChangeCipherSpec]
1169 // <------- Finished
1170 // Application Data <------> Application Data
1173 send_client_hello(tls);
1174 get_server_hello(tls);
1177 // The server MUST send a Certificate message whenever the agreed-
1178 // upon key exchange method uses certificates for authentication
1179 // (this includes all key exchange methods defined in this document
1180 // except DH_anon). This message will always immediately follow the
1181 // ServerHello message.
1183 // IOW: in practice, Certificate *always* follows.
1184 // (for example, kernel.org does not even accept DH_anon cipher id)
1185 get_server_cert(tls);
1187 len = xread_tls_handshake_block(tls, 4);
1188 if (tls->inbuf[5] == HANDSHAKE_SERVER_KEY_EXCHANGE) {
1190 // 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...
1192 // with TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 461 bytes:
1193 // 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...
1194 dbg("got SERVER_KEY_EXCHANGE len:%u\n", len);
1196 xread_tls_handshake_block(tls, 4);
1198 // if (tls->inbuf[5] == HANDSHAKE_CERTIFICATE_REQUEST) {
1199 // dbg("got CERTIFICATE_REQUEST\n");
1200 //RFC 5246: (in response to this,) "If no suitable certificate is available,
1201 // the client MUST send a certificate message containing no
1202 // certificates. That is, the certificate_list structure has a
1203 // length of zero. ...
1204 // Client certificates are sent using the Certificate structure
1205 // defined in Section 7.4.2."
1206 // (i.e. the same format as server certs)
1207 // xread_tls_handshake_block(tls, 4);
1209 if (tls->inbuf[5] == HANDSHAKE_SERVER_HELLO_DONE) {
1210 // 0e 000000 (len:0)
1211 dbg("got SERVER_HELLO_DONE\n");
1212 send_client_key_exchange(tls);
1213 send_change_cipher_spec(tls);
1214 //we now should be able to send encrypted... as soon as we grok AES.
1215 send_client_finished(tls);
1217 get_change_cipher_spec(tls);
1218 get_server_finished(tls);
1219 //we now should receive encrypted, and application data can be sent/received
1225 // To run a test server using openssl:
1226 // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1
1227 // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
1229 int tls_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1230 int tls_main(int argc UNUSED_PARAM, char **argv)
1233 len_and_sockaddr *lsa;
1237 // getopt32(argv, "myopts")
1242 lsa = xhost2sockaddr(argv[1], 443);
1243 fd = xconnect_stream(lsa);
1245 tls = new_tls_state();
1249 return EXIT_SUCCESS;
1252 //TODO: implement RFC 5746 (Renegotiation Indication Extension) - some servers will refuse to work with us otherwise
1254 /* Unencryped SHA256 example:
1255 * $ openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
1256 * $ openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL
1257 * $ openssl s_client -connect 127.0.0.1:4433 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL-SHA256
1260 write to 0x1d750b0 [0x1e6f153] (99 bytes => 99 (0x63))
1261 0000 - 16 03 01 005e 01 00005a 0303 [4d ef 5c 82 3e ....^...Z..M.\.> >> ClHello
1262 0010 - bf a6 ee f1 1e 04 d1 5c-99 20 86 13 e9 0a cf 58 .......\. .....X
1263 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
1264 0030 - 00ff TLS_EMPTY_RENEGOTIATION_INFO_SCSV
1266 002d, 0023 0000, 000d 0020 [00 1e .....-.#..... .. extlen, SessionTicketTLS 0 bytes, SignatureAlgorithms 32 bytes
1267 0040 - 06 01 06 02 06 03 05 01-05 02 05 03 04 01 04 02 ................
1268 0050 - 04 03 03 01 03 02 03 03-02 01 02 02 02 03] 000f ................ Heart Beat 1 byte
1271 read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
1272 0000 - 16 03 03 00 3a ....:
1273 read from 0x1d750b0 [0x1e6ac08] (58 bytes => 58 (0x3A))
1274 0000 - 02 000036 0303 [f2 61-ae c8 58 e3 51 42 32 93 ...6...a..X.QB2. << SvHello
1275 0010 - c5 62 e4 f5 06 93 81 65-aa f7 df 74 af 7c 98 b4 .b.....e...t.|..
1276 0020 - 3e a7 35 c3 25 69] 00,003b,00.................. >.5.%i..;....... - no session id! "The server
1277 may return an empty session_id to indicate that the session will
1278 not be cached and therefore cannot be resumed."
1279 003b = TLS_RSA_WITH_NULL_SHA256 accepted, 00 - no compr
1280 000e ff01 0001 extlen, 0xff01=RenegotiationInfo 1 byte
1281 0030 - 00, 0023 0000, SessionTicketTLS 0 bytes
1282 000f 0001 01 ..#....... Heart Beat 1 byte
1284 read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
1285 0000 - 16 03 03 04 0b .....
1286 read from 0x1d750b0 [0x1e6ac08] (1035 bytes => 1035 (0x40B))
1287 0000 - 0b 00 04 07 00 04 04 00-04 01 30 82 03 fd 30 82 ..........0...0. << Cert
1288 0010 - 02 65 a0 03 02 01 02 02-09 00 d9 d9 8d b8 94 ad .e..............
1289 0020 - 2e 2b 30 0d 06 09 2a 86-48 86 f7 0d 01 01 0b 05 .+0...*.H.......
1290 0030 - 00 30 14 31 12 30 10 06-03 55 04 03 0c 09 6c 6f .0.1.0...U....lo
1291 0040 - 63 61 6c 68 6f 73 74 30-20 17 0d 31 37 30 31 31 calhost0 ..17011
1292 ...".......".......".......".......".......".......".......".......".....
1293 03f0 - 11 8a cd c5 a3 0a 22 43-d5 13 f9 a5 8a 06 f9 00 ......"C........
1294 0400 - 3c f7 86 4e e8 a5 d8 5b-92 37 f5 <..N...[.7.
1295 depth=0 CN = localhost
1296 verify error:num=18:self signed certificate
1298 depth=0 CN = localhost
1301 read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
1302 0000 - 16 03 03 00 04 .....
1304 read from 0x1d750b0 [0x1e6ac08] (4 bytes => 4 (0x4)) << SvDone
1306 0004 - <SPACES/NULS>
1308 write to 0x1d750b0 [0x1e74620] (395 bytes => 395 (0x18B)) >> ClDone
1309 0000 - 16 03 03 01 86 10 00 01-82 01 80 88 f0 87 5d b0 ..............].
1310 0010 - ea df 3b 4d e2 35 f3 99-e6 d4 29 87 36 86 ea 30 ..;M.5....).6..0
1311 0020 - 38 80 c7 37 66 7f 5b e7-23 38 7e 87 24 66 82 81 8..7f.[.#8~.$f..
1312 0030 - e4 ba 6c 2a 0c 92 a8 b9-39 c1 55 16 32 88 14 cd ..l*....9.U.2...
1313 0040 - 95 8c 82 49 a1 c7 f9 9b-e5 8f f6 5e 7e ee 91 b3 ...I.......^~...
1314 0050 - 2c 92 e7 a3 02 f8 9f 56-04 45 39 df a7 d6 1a 16 ,......V.E9.....
1315 0060 - 67 5c a4 f8 87 8a c4 c8-6c 6f c6 f0 9b c9 b4 87 g\......lo......
1316 0070 - 36 43 c1 67 9f b3 aa 11-34 b0 c2 fc 1f d9 e1 ff 6C.g....4.......
1317 0080 - fb e1 89 db 91 58 ec cc-aa 16 19 9a 91 74 e2 46 .....X.......t.F
1318 0090 - 22 a7 a7 f7 9e 3c 97 82-2c e4 21 b3 fa ef ba 3f "....<..,.!....?
1319 00a0 - 57 48 e4 b2 84 b7 c2 81-92 a9 f1 03 68 f4 e6 0c WH..........h...
1320 00b0 - fd 54 87 f5 e9 a0 5d e6-5f 0e bd 80 86 27 ab 0e .T....]._....'..
1321 00c0 - cf 92 4f bd fc 24 b9 54-72 5f 58 df 6b 2b 1d 97 ..O..$.Tr_X.k+..
1322 00d0 - 00 60 fe 95 b0 aa d6 c7-c1 3a f9 2e 7c 92 a9 6d .`.......:..|..m
1323 00e0 - 28 a3 ef 3e c1 e6 2d 2d-e8 db 81 ea 51 02 3f 64 (..>..--....Q.?d
1324 00f0 - a8 66 14 c1 4b 17 1f 55-c6 5b 3b 38 c3 6a 61 a8 .f..K..U.[;8.ja.
1325 0100 - f7 ad 65 7d cb 14 6d b3-0f 76 19 25 8e ed bd 53 ..e}..m..v.%...S
1326 0110 - 35 a9 a1 34 00 9d 07 81-84 51 35 e0 83 83 e3 a6 5..4.....Q5.....
1327 0120 - c7 77 4c 61 e4 78 9c cb-f5 92 4e d6 dd c4 c2 2b .wLa.x....N....+
1328 0130 - 75 9e 72 a6 7f 81 6a 1c-fc 4a 51 91 81 b4 cc 33 u.r...j..JQ....3
1329 0140 - 1c 8b 0a b6 94 8b 16 1b-86 2f 31 5e 31 e1 57 14 ........./1^1.W.
1330 0150 - 2e b5 09 5d cf 6f ea b2-94 e9 5c cc b9 fc 24 a0 ...].o....\...$.
1331 0160 - b7 f1 f4 9d 95 46 4f 08-5c 45 c6 2f 9f 7d 76 09 .....FO.\E./.}v.
1332 0170 - 6a af 50 2c 89 76 82 5f-e8 34 d8 4b 84 b6 34 18 j.P,.v._.4.K..4.
1333 0180 - 85 95 4a 3f 0f 28 88 3a-71 32 90 ..J?.(.:q2.
1335 write to 0x1d750b0 [0x1e74620] (6 bytes => 6 (0x6))
1336 0000 - 14 03 03 00 01 01 ...... >> CHANGE_CIPHER_SPEC
1338 write to 0x1d750b0 [0x1e74620] (53 bytes => 53 (0x35))
1339 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]
1340 0010 - c0 d1 d4 0b a3|73 ec a8-fa b5 cb 12 b6 4c 2a b1 .....s.......L*.
1341 0020 - fb 42 7f 73 0d 06 1c 87-56 f0 db df e6 6a 25 aa .B.s....V....j%.
1342 0030 - fc 42 38 cb 0b] .B8..
1344 read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
1345 0000 - 16 03 03 00 aa .....
1346 read from 0x1d750b0 [0x1e6ac08] (170 bytes => 170 (0xAA))
1347 0000 - 04 00 00 a6 00 00 1c 20-00 a0 dd f4 52 01 54 8d ....... ....R.T. << NEW_SESSION_TICKET
1348 0010 - f8 a6 f9 2d 7d 19 20 5b-14 44 d3 2d 7b f2 ca e8 ...-}. [.D.-{...
1349 0020 - 01 4e 94 7b fe 12 59 3a-00 2e 7e cf 74 43 7a f7 .N.{..Y:..~.tCz.
1350 0030 - 9e cc 70 80 70 7c e3 a5-c6 9d 85 2c 36 19 4c 5c ..p.p|.....,6.L\
1351 0040 - ba 3b c3 e5 69 dc f3 a4-47 38 11 c9 7d 1a b0 6e .;..i...G8..}..n
1352 0050 - d8 49 a0 a8 e4 de 70 a8-d0 6b e4 7a b7 65 25 df .I....p..k.z.e%.
1353 0060 - 1b 5f 64 0f 89 69 02 72-fe eb d3 7a af 51 78 0e ._d..i.r...z.Qx.
1354 0070 - de 17 06 a5 f0 47 9d e0-04 d4 b1 1e be 7e ed bd .....G.......~..
1355 0080 - 27 8f 5d e8 ac f6 45 aa-e0 12 93 41 5f a8 4b b9 '.]...E....A_.K.
1356 0090 - bd 43 8f a1 23 51 af 92-77 8f 38 23 3e 2e c2 f0 .C..#Q..w.8#>...
1357 00a0 - a3 74 fa 83 94 ce 19 8a-5b 5b .t......[[
1359 read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
1360 0000 - 14 03 03 00 01 ..... << CHANGE_CIPHER_SPEC
1361 read from 0x1d750b0 [0x1e6ac08] (1 bytes => 1 (0x1))
1364 read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
1365 0000 - 16 03 03 00 30 ....0
1366 read from 0x1d750b0 [0x1e6ac08] (48 bytes => 48 (0x30))
1367 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]
1368 0010 -|49 d6 dd 56 73 e3 d2 e8-22 d6 bd 61 b2 b3 af f0 I..Vs..."..a....
1369 0020 - f5 00 8a 80 82 04 33 a7-50 8e ae 3b 4c 8c cf 4a] ......3.P..;L..J
1376 -----BEGIN CERTIFICATE-----
1377 ...".......".......".......".......".......".......".......".......".....
1378 -----END CERTIFICATE-----
1379 subject=/CN=localhost
1380 issuer=/CN=localhost
1382 No client certificate CA names sent
1384 SSL handshake has read 1346 bytes and written 553 bytes
1386 New, TLSv1/SSLv3, Cipher is NULL-SHA256
1387 Server public key is 3072 bit
1388 Secure Renegotiation IS supported
1394 Cipher : NULL-SHA256
1395 Session-ID: 5D62B36950F3DEB571707CD1B815E9E275041B9DB70D7F3E25C4A6535B13B616
1397 Master-Key: 4D08108C59417E0A41656636C51BA5B83F4EFFF9F4C860987B47B31250E5D1816D00940DBCCC196C2D99C8462C889DF1
1399 Krb5 Principal: None
1401 PSK identity hint: None
1402 TLS session ticket lifetime hint: 7200 (seconds)
1404 0000 - dd f4 52 01 54 8d f8 a6-f9 2d 7d 19 20 5b 14 44 ..R.T....-}. [.D
1405 0010 - d3 2d 7b f2 ca e8 01 4e-94 7b fe 12 59 3a 00 2e .-{....N.{..Y:..
1406 0020 - 7e cf 74 43 7a f7 9e cc-70 80 70 7c e3 a5 c6 9d ~.tCz...p.p|....
1407 0030 - 85 2c 36 19 4c 5c ba 3b-c3 e5 69 dc f3 a4 47 38 .,6.L\.;..i...G8
1408 0040 - 11 c9 7d 1a b0 6e d8 49-a0 a8 e4 de 70 a8 d0 6b ..}..n.I....p..k
1409 0050 - e4 7a b7 65 25 df 1b 5f-64 0f 89 69 02 72 fe eb .z.e%.._d..i.r..
1410 0060 - d3 7a af 51 78 0e de 17-06 a5 f0 47 9d e0 04 d4 .z.Qx......G....
1411 0070 - b1 1e be 7e ed bd 27 8f-5d e8 ac f6 45 aa e0 12 ...~..'.]...E...
1412 0080 - 93 41 5f a8 4b b9 bd 43-8f a1 23 51 af 92 77 8f .A_.K..C..#Q..w.
1413 0090 - 38 23 3e 2e c2 f0 a3 74-fa 83 94 ce 19 8a 5b 5b 8#>....t......[[
1415 Start Time: 1484574330
1416 Timeout : 7200 (sec)
1417 Verify return code: 18 (self signed certificate)
1419 read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
1420 0000 - 17 03 03 00 21 ....!
1421 read from 0x1d750b0 [0x1e6ac08] (33 bytes => 33 (0x21))
1422 0000 - 0a 74 5b 50 02 13 75 a4-27 0a 40 b1 53 74 52 14 .t[P..u.'.@.StR.
1423 0010 - e7 1e 6a 6c c1 60 2e 93-7e a5 d9 43 1d 8e f6 08 ..jl.`..~..C....
1426 read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
1427 0000 - 17 03 03 00 21 ....!
1428 read from 0x1d750b0 [0x1e6ac08] (33 bytes => 33 (0x21))
1429 0000 - 0a 1b ce 44 98 4f 81 c5-28 7a cc 79 62 db d2 86 ...D.O..(z.yb...
1430 0010 - 6a 55 a4 c7 73 49 ef 3e-bd 03 99 76 df 65 2a a1 jU..sI.>...v.e*.
1433 read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
1434 0000 - 17 03 03 00 21 ....!
1435 read from 0x1d750b0 [0x1e6ac08] (33 bytes => 33 (0x21))
1436 0000 - 0a 67 66 34 ba 68 36 3c-ad 0a c1 f5 c0 5a 50 fe .gf4.h6<.....ZP.
1437 0010 - 68 cd 04 65 e9 de 6e 98-f9 e2 41 1e 0b 9b 84 06 h..e..n...A.....