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