tls: reorder tls_handshake_data fields for smaller size, tweak comments
[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 #No description makes it a hidden option
8 //config:       default n
9
10 //kbuild:lib-$(CONFIG_TLS) += tls.o
11 //kbuild:lib-$(CONFIG_TLS) += tls_pstm.o
12 //kbuild:lib-$(CONFIG_TLS) += tls_pstm_montgomery_reduce.o
13 //kbuild:lib-$(CONFIG_TLS) += tls_pstm_mul_comba.o
14 //kbuild:lib-$(CONFIG_TLS) += tls_pstm_sqr_comba.o
15 //kbuild:lib-$(CONFIG_TLS) += tls_rsa.o
16 //kbuild:lib-$(CONFIG_TLS) += tls_aes.o
17 ////kbuild:lib-$(CONFIG_TLS) += tls_aes_gcm.o
18
19 #include "tls.h"
20
21 #define TLS_DEBUG      0
22 #define TLS_DEBUG_HASH 0
23 #define TLS_DEBUG_DER  0
24 #define TLS_DEBUG_FIXED_SECRETS 0
25 #if 0
26 # define dump_raw_out(...) dump_hex(__VA_ARGS__)
27 #else
28 # define dump_raw_out(...) ((void)0)
29 #endif
30 #if 0
31 # define dump_raw_in(...) dump_hex(__VA_ARGS__)
32 #else
33 # define dump_raw_in(...) ((void)0)
34 #endif
35
36 #if TLS_DEBUG
37 # define dbg(...) fprintf(stderr, __VA_ARGS__)
38 #else
39 # define dbg(...) ((void)0)
40 #endif
41
42 #if TLS_DEBUG_DER
43 # define dbg_der(...) fprintf(stderr, __VA_ARGS__)
44 #else
45 # define dbg_der(...) ((void)0)
46 #endif
47
48 #define RECORD_TYPE_CHANGE_CIPHER_SPEC  20
49 #define RECORD_TYPE_ALERT               21
50 #define RECORD_TYPE_HANDSHAKE           22
51 #define RECORD_TYPE_APPLICATION_DATA    23
52
53 #define HANDSHAKE_HELLO_REQUEST         0
54 #define HANDSHAKE_CLIENT_HELLO          1
55 #define HANDSHAKE_SERVER_HELLO          2
56 #define HANDSHAKE_HELLO_VERIFY_REQUEST  3
57 #define HANDSHAKE_NEW_SESSION_TICKET    4
58 #define HANDSHAKE_CERTIFICATE           11
59 #define HANDSHAKE_SERVER_KEY_EXCHANGE   12
60 #define HANDSHAKE_CERTIFICATE_REQUEST   13
61 #define HANDSHAKE_SERVER_HELLO_DONE     14
62 #define HANDSHAKE_CERTIFICATE_VERIFY    15
63 #define HANDSHAKE_CLIENT_KEY_EXCHANGE   16
64 #define HANDSHAKE_FINISHED              20
65
66 #define SSL_NULL_WITH_NULL_NULL                 0x0000
67 #define SSL_RSA_WITH_NULL_MD5                   0x0001
68 #define SSL_RSA_WITH_NULL_SHA                   0x0002
69 #define SSL_RSA_WITH_RC4_128_MD5                0x0004
70 #define SSL_RSA_WITH_RC4_128_SHA                0x0005
71 #define SSL_RSA_WITH_3DES_EDE_CBC_SHA           0x000A  /* 10 */
72 #define TLS_RSA_WITH_AES_128_CBC_SHA            0x002F  /* 47 */
73 #define TLS_RSA_WITH_AES_256_CBC_SHA            0x0035  /* 53 */
74 #define TLS_RSA_WITH_NULL_SHA256                0x003B  /* 59 */
75
76 #define TLS_EMPTY_RENEGOTIATION_INFO_SCSV       0x00FF
77
78 #define TLS_RSA_WITH_IDEA_CBC_SHA               0x0007  /* 7 */
79 #define SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA       0x0016  /* 22 */
80 #define SSL_DH_anon_WITH_RC4_128_MD5            0x0018  /* 24 */
81 #define SSL_DH_anon_WITH_3DES_EDE_CBC_SHA       0x001B  /* 27 */
82 #define TLS_DHE_RSA_WITH_AES_128_CBC_SHA        0x0033  /* 51 */
83 #define TLS_DHE_RSA_WITH_AES_256_CBC_SHA        0x0039  /* 57 */
84 #define TLS_DHE_RSA_WITH_AES_128_CBC_SHA256     0x0067  /* 103 */
85 #define TLS_DHE_RSA_WITH_AES_256_CBC_SHA256     0x006B  /* 107 */
86 #define TLS_DH_anon_WITH_AES_128_CBC_SHA        0x0034  /* 52 */
87 #define TLS_DH_anon_WITH_AES_256_CBC_SHA        0x003A  /* 58 */
88 #define TLS_RSA_WITH_AES_128_CBC_SHA256         0x003C  /* 60 */
89 #define TLS_RSA_WITH_AES_256_CBC_SHA256         0x003D  /* 61 */
90 #define TLS_RSA_WITH_SEED_CBC_SHA               0x0096  /* 150 */
91 #define TLS_PSK_WITH_AES_128_CBC_SHA            0x008C  /* 140 */
92 #define TLS_PSK_WITH_AES_128_CBC_SHA256         0x00AE  /* 174 */
93 #define TLS_PSK_WITH_AES_256_CBC_SHA384         0x00AF  /* 175 */
94 #define TLS_PSK_WITH_AES_256_CBC_SHA            0x008D  /* 141 */
95 #define TLS_DHE_PSK_WITH_AES_128_CBC_SHA        0x0090  /* 144 */
96 #define TLS_DHE_PSK_WITH_AES_256_CBC_SHA        0x0091  /* 145 */
97 #define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA     0xC004  /* 49156 */
98 #define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA     0xC005  /* 49157 */
99 #define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA    0xC009  /* 49161 */
100 #define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA    0xC00A  /* 49162 */
101 #define TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA     0xC012  /* 49170 */
102 #define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA      0xC013  /* 49171 */
103 #define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA      0xC014  /* 49172 */
104 #define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA       0xC00E  /* 49166 */
105 #define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA       0xC00F  /* 49167 */
106 #define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023  /* 49187 */
107 #define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 0xC024  /* 49188 */
108 #define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256  0xC025  /* 49189 */
109 #define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384  0xC026  /* 49190 */
110 #define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256   0xC027  /* 49191 */
111 #define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384   0xC028  /* 49192 */
112 #define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256    0xC029  /* 49193 */
113 #define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384    0xC02A  /* 49194 */
114
115 /* RFC 5288 "AES Galois Counter Mode (GCM) Cipher Suites for TLS" */
116 #define TLS_RSA_WITH_AES_128_GCM_SHA256         0x009C  /* 156 */
117 #define TLS_RSA_WITH_AES_256_GCM_SHA384         0x009D  /* 157 */
118 #define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B  /* 49195 */
119 #define TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0xC02C  /* 49196 */
120 #define TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256  0xC02D  /* 49197 */
121 #define TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384  0xC02E  /* 49198 */
122 #define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256   0xC02F  /* 49199 */
123 #define TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384   0xC030  /* 49200 */
124 #define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256    0xC031  /* 49201 */
125 #define TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384    0xC032  /* 49202 */
126
127 //Tested against kernel.org:
128 //TLS 1.2
129 #define TLS_MAJ 3
130 #define TLS_MIN 3
131 //#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA // ok, recvs SERVER_KEY_EXCHANGE *** matrixssl uses this on my box
132 //#define CIPHER_ID TLS_RSA_WITH_AES_256_CBC_SHA256 // ok, no SERVER_KEY_EXCHANGE
133 //#define CIPHER_ID TLS_DH_anon_WITH_AES_256_CBC_SHA // SSL_ALERT_HANDSHAKE_FAILURE
134 //^^^^^^^^^^^^^^^^^^^^^^^ (tested b/c this one doesn't req server certs... no luck, server refuses it)
135 //#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 // SSL_ALERT_HANDSHAKE_FAILURE
136 //#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
137 //#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 // ok, recvs SERVER_KEY_EXCHANGE
138 //#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
139 //#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
140 //#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
141 //#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
142 //#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
143 //#define CIPHER_ID TLS_RSA_WITH_AES_256_GCM_SHA384 // ok, no SERVER_KEY_EXCHANGE
144 //#define CIPHER_ID TLS_RSA_WITH_AES_128_GCM_SHA256 // ok, no SERVER_KEY_EXCHANGE *** select this?
145
146 // works against "openssl s_server -cipher NULL"
147 // and against wolfssl-3.9.10-stable/examples/server/server.c:
148 //#define CIPHER_ID TLS_RSA_WITH_NULL_SHA256 // for testing (does everything except encrypting)
149
150 // works against wolfssl-3.9.10-stable/examples/server/server.c
151 // works for kernel.org
152 // does not work for cdn.kernel.org (e.g. downloading an actual tarball, not a web page)
153 //  getting alert 40 "handshake failure" at once
154 //  with GNU Wget 1.18, they agree on TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xC02F) cipher
155 //  fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES256-SHA256
156 //  fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES256-GCM-SHA384
157 //  fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES128-SHA256
158 //  ok:   openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES128-GCM-SHA256
159 //  ok:   openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES128-SHA
160 //        (TLS_RSA_WITH_AES_128_CBC_SHA - in TLS 1.2 it's mandated to be always supported)
161 #define CIPHER_ID TLS_RSA_WITH_AES_256_CBC_SHA256 // no SERVER_KEY_EXCHANGE from peer
162
163 enum {
164         RSA_PREMASTER_SIZE = 48,
165
166         RECHDR_LEN = 5,
167
168         MAX_TLS_RECORD = (1 << 14),
169         /* 8 = 3+5. 3 extra bytes result in record data being 32-bit aligned */
170         OUTBUF_PFX = 8 + AES_BLOCKSIZE, /* header + IV */
171         OUTBUF_SFX = SHA256_OUTSIZE + AES_BLOCKSIZE, /* MAC + padding */
172         MAX_OUTBUF = MAX_TLS_RECORD - OUTBUF_PFX - OUTBUF_SFX,
173
174         // RFC 5246
175         // | 6.2.1. Fragmentation
176         // |  The record layer fragments information blocks into TLSPlaintext
177         // |  records carrying data in chunks of 2^14 bytes or less.  Client
178         // |  message boundaries are not preserved in the record layer (i.e.,
179         // |  multiple client messages of the same ContentType MAY be coalesced
180         // |  into a single TLSPlaintext record, or a single message MAY be
181         // |  fragmented across several records)
182         // |...
183         // |  length
184         // |    The length (in bytes) of the following TLSPlaintext.fragment.
185         // |    The length MUST NOT exceed 2^14.
186         // |...
187         // | 6.2.2. Record Compression and Decompression
188         // |...
189         // |  Compression must be lossless and may not increase the content length
190         // |  by more than 1024 bytes.  If the decompression function encounters a
191         // |  TLSCompressed.fragment that would decompress to a length in excess of
192         // |  2^14 bytes, it MUST report a fatal decompression failure error.
193         // |...
194         // |  length
195         // |    The length (in bytes) of the following TLSCompressed.fragment.
196         // |    The length MUST NOT exceed 2^14 + 1024.
197         // |...
198         // | 6.2.3.  Record Payload Protection
199         // |  The encryption and MAC functions translate a TLSCompressed
200         // |  structure into a TLSCiphertext.  The decryption functions reverse
201         // |  the process.  The MAC of the record also includes a sequence
202         // |  number so that missing, extra, or repeated messages are
203         // |  detectable.
204         // |...
205         // |  length
206         // |    The length (in bytes) of the following TLSCiphertext.fragment.
207         // |    The length MUST NOT exceed 2^14 + 2048.
208         MAX_INBUF = (1 << 14) + 2048,
209 };
210
211 struct record_hdr {
212         uint8_t type;
213         uint8_t proto_maj, proto_min;
214         uint8_t len16_hi, len16_lo;
215 };
216
217 struct tls_handshake_data {
218         sha256_ctx_t handshake_sha256_ctx;
219         uint8_t client_and_server_rand32[2 * 32];
220         uint8_t master_secret[48];
221 //TODO: store just the DER key here, parse/use/delete it when sending client key
222 //this way it will stay key type agnostic here.
223         psRsaKey_t server_rsa_pub_key;
224 };
225
226
227 static unsigned get24be(const uint8_t *p)
228 {
229         return 0x100*(0x100*p[0] + p[1]) + p[2];
230 }
231
232 #if TLS_DEBUG
233 static void dump_hex(const char *fmt, const void *vp, int len)
234 {
235         char hexbuf[32 * 1024 + 4];
236         const uint8_t *p = vp;
237
238         bin2hex(hexbuf, (void*)p, len)[0] = '\0';
239         dbg(fmt, hexbuf);
240 }
241
242 static void dump_tls_record(const void *vp, int len)
243 {
244         const uint8_t *p = vp;
245
246         while (len > 0) {
247                 unsigned xhdr_len;
248                 if (len < RECHDR_LEN) {
249                         dump_hex("< |%s|\n", p, len);
250                         return;
251                 }
252                 xhdr_len = 0x100*p[3] + p[4];
253                 dbg("< hdr_type:%u ver:%u.%u len:%u", p[0], p[1], p[2], xhdr_len);
254                 p += RECHDR_LEN;
255                 len -= RECHDR_LEN;
256                 if (len >= 4 && p[-RECHDR_LEN] == RECORD_TYPE_HANDSHAKE) {
257                         unsigned len24 = get24be(p + 1);
258                         dbg(" type:%u len24:%u", p[0], len24);
259                 }
260                 if (xhdr_len > len)
261                         xhdr_len = len;
262                 dump_hex(" |%s|\n", p, xhdr_len);
263                 p += xhdr_len;
264                 len -= xhdr_len;
265         }
266 }
267 #else
268 # define dump_hex(...) ((void)0)
269 # define dump_tls_record(...) ((void)0)
270 #endif
271
272 void tls_get_random(void *buf, unsigned len)
273 {
274         if (len != open_read_close("/dev/urandom", buf, len))
275                 xfunc_die();
276 }
277
278 //TODO rename this to sha256_hash, and sha256_hash -> sha256_update
279 static void hash_sha256(uint8_t out[SHA256_OUTSIZE], const void *data, unsigned size)
280 {
281         sha256_ctx_t ctx;
282         sha256_begin(&ctx);
283         sha256_hash(&ctx, data, size);
284         sha256_end(&ctx, out);
285 }
286
287 /* Nondestructively see the current hash value */
288 static void sha256_peek(sha256_ctx_t *ctx, void *buffer)
289 {
290         sha256_ctx_t ctx_copy = *ctx;
291         sha256_end(&ctx_copy, buffer);
292 }
293
294 #if TLS_DEBUG_HASH
295 static void sha256_hash_dbg(const char *fmt, sha256_ctx_t *ctx, const void *buffer, size_t len)
296 {
297         uint8_t h[SHA256_OUTSIZE];
298
299         sha256_hash(ctx, buffer, len);
300         dump_hex(fmt, buffer, len);
301         dbg(" (%u) ", (int)len);
302         sha256_peek(ctx, h);
303         dump_hex("%s\n", h, SHA256_OUTSIZE);
304 }
305 #else
306 # define sha256_hash_dbg(fmt, ctx, buffer, len) \
307          sha256_hash(ctx, buffer, len)
308 #endif
309
310 // RFC 2104
311 // HMAC(key, text) based on a hash H (say, sha256) is:
312 // ipad = [0x36 x INSIZE]
313 // opad = [0x5c x INSIZE]
314 // HMAC(key, text) = H((key XOR opad) + H((key XOR ipad) + text))
315 //
316 // H(key XOR opad) and H(key XOR ipad) can be precomputed
317 // if we often need HMAC hmac with the same key.
318 //
319 // text is often given in disjoint pieces.
320 static void hmac_sha256_precomputed_v(uint8_t out[SHA256_OUTSIZE],
321                 sha256_ctx_t *hashed_key_xor_ipad,
322                 sha256_ctx_t *hashed_key_xor_opad,
323                 va_list va)
324 {
325         uint8_t *text;
326
327         /* hashed_key_xor_ipad contains unclosed "H((key XOR ipad) +" state */
328         /* hashed_key_xor_opad contains unclosed "H((key XOR opad) +" state */
329
330         /* calculate out = H((key XOR ipad) + text) */
331         while ((text = va_arg(va, uint8_t*)) != NULL) {
332                 unsigned text_size = va_arg(va, unsigned);
333                 sha256_hash(hashed_key_xor_ipad, text, text_size);
334         }
335         sha256_end(hashed_key_xor_ipad, out);
336
337         /* out = H((key XOR opad) + out) */
338         sha256_hash(hashed_key_xor_opad, out, SHA256_OUTSIZE);
339         sha256_end(hashed_key_xor_opad, out);
340 }
341
342 static void hmac_sha256(uint8_t out[SHA256_OUTSIZE], uint8_t *key, unsigned key_size, ...)
343 {
344         sha256_ctx_t hashed_key_xor_ipad;
345         sha256_ctx_t hashed_key_xor_opad;
346         uint8_t key_xor_ipad[SHA256_INSIZE];
347         uint8_t key_xor_opad[SHA256_INSIZE];
348         uint8_t tempkey[SHA256_OUTSIZE];
349         va_list va;
350         int i;
351
352         va_start(va, key_size);
353
354         // "The authentication key can be of any length up to INSIZE, the
355         // block length of the hash function.  Applications that use keys longer
356         // than INSIZE bytes will first hash the key using H and then use the
357         // resultant OUTSIZE byte string as the actual key to HMAC."
358         if (key_size > SHA256_INSIZE) {
359                 hash_sha256(tempkey, key, key_size);
360                 key = tempkey;
361                 key_size = SHA256_OUTSIZE;
362         }
363
364         for (i = 0; i < key_size; i++) {
365                 key_xor_ipad[i] = key[i] ^ 0x36;
366                 key_xor_opad[i] = key[i] ^ 0x5c;
367         }
368         for (; i < SHA256_INSIZE; i++) {
369                 key_xor_ipad[i] = 0x36;
370                 key_xor_opad[i] = 0x5c;
371         }
372         sha256_begin(&hashed_key_xor_ipad);
373         sha256_hash(&hashed_key_xor_ipad, key_xor_ipad, SHA256_INSIZE);
374         sha256_begin(&hashed_key_xor_opad);
375         sha256_hash(&hashed_key_xor_opad, key_xor_opad, SHA256_INSIZE);
376
377         hmac_sha256_precomputed_v(out, &hashed_key_xor_ipad, &hashed_key_xor_opad, va);
378         va_end(va);
379 }
380
381 // RFC 5246:
382 // 5.  HMAC and the Pseudorandom Function
383 //...
384 // In this section, we define one PRF, based on HMAC.  This PRF with the
385 // SHA-256 hash function is used for all cipher suites defined in this
386 // document and in TLS documents published prior to this document when
387 // TLS 1.2 is negotiated.
388 //...
389 //    P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
390 //                           HMAC_hash(secret, A(2) + seed) +
391 //                           HMAC_hash(secret, A(3) + seed) + ...
392 // where + indicates concatenation.
393 // A() is defined as:
394 //    A(0) = seed
395 //    A(1) = HMAC_hash(secret, A(0)) = HMAC_hash(secret, seed)
396 //    A(i) = HMAC_hash(secret, A(i-1))
397 // P_hash can be iterated as many times as necessary to produce the
398 // required quantity of data.  For example, if P_SHA256 is being used to
399 // create 80 bytes of data, it will have to be iterated three times
400 // (through A(3)), creating 96 bytes of output data; the last 16 bytes
401 // of the final iteration will then be discarded, leaving 80 bytes of
402 // output data.
403 //
404 // TLS's PRF is created by applying P_hash to the secret as:
405 //
406 //    PRF(secret, label, seed) = P_<hash>(secret, label + seed)
407 //
408 // The label is an ASCII string.
409 static void prf_hmac_sha256(
410                 uint8_t *outbuf, unsigned outbuf_size,
411                 uint8_t *secret, unsigned secret_size,
412                 const char *label,
413                 uint8_t *seed, unsigned seed_size)
414 {
415         uint8_t a[SHA256_OUTSIZE];
416         uint8_t *out_p = outbuf;
417         unsigned label_size = strlen(label);
418
419         /* In P_hash() calculation, "seed" is "label + seed": */
420 #define SEED   label, label_size, seed, seed_size
421 #define SECRET secret, secret_size
422 #define A      a, (int)(sizeof(a))
423
424         /* A(1) = HMAC_hash(secret, seed) */
425         hmac_sha256(a, SECRET, SEED, NULL);
426 //TODO: convert hmac_sha256 to precomputed
427
428         for(;;) {
429                 /* HMAC_hash(secret, A(1) + seed) */
430                 if (outbuf_size <= SHA256_OUTSIZE) {
431                         /* Last, possibly incomplete, block */
432                         /* (use a[] as temp buffer) */
433                         hmac_sha256(a, SECRET, A, SEED, NULL);
434                         memcpy(out_p, a, outbuf_size);
435                         return;
436                 }
437                 /* Not last block. Store directly to result buffer */
438                 hmac_sha256(out_p, SECRET, A, SEED, NULL);
439                 out_p += SHA256_OUTSIZE;
440                 outbuf_size -= SHA256_OUTSIZE;
441                 /* A(2) = HMAC_hash(secret, A(1)) */
442                 hmac_sha256(a, SECRET, A, NULL);
443         }
444 #undef A
445 #undef SECRET
446 #undef SEED
447 }
448
449 static void bad_record_die(tls_state_t *tls, const char *expected, int len)
450 {
451         bb_error_msg_and_die("got bad TLS record (len:%d) while expecting %s", len, expected);
452         if (len > 0) {
453                 uint8_t *p = tls->inbuf;
454                 while (len > 0)
455                         fprintf(stderr, " %02x", *p++);
456                 fputc('\n', stderr);
457         }
458         xfunc_die();
459 }
460
461 static void tls_error_die(tls_state_t *tls)
462 {
463         dump_tls_record(tls->inbuf, tls->ofs_to_buffered + tls->buffered_size);
464         bb_error_msg_and_die("TODO: useful diagnostic about %p", tls);
465 }
466
467 #if 0 //UNUSED
468 static void tls_free_inbuf(tls_state_t *tls)
469 {
470         if (tls->buffered_size == 0) {
471                 free(tls->inbuf);
472                 tls->inbuf_size = 0;
473                 tls->inbuf = NULL;
474         }
475 }
476 #endif
477
478 static void tls_free_outbuf(tls_state_t *tls)
479 {
480         free(tls->outbuf);
481         tls->outbuf_size = 0;
482         tls->outbuf = NULL;
483 }
484
485 static void *tls_get_outbuf(tls_state_t *tls, int len)
486 {
487         if (len > MAX_OUTBUF)
488                 xfunc_die();
489         if (tls->outbuf_size < len + OUTBUF_PFX + OUTBUF_SFX) {
490                 tls->outbuf_size = len + OUTBUF_PFX + OUTBUF_SFX;
491                 tls->outbuf = xrealloc(tls->outbuf, tls->outbuf_size);
492         }
493         return tls->outbuf + OUTBUF_PFX;
494 }
495
496 static void xwrite_encrypted(tls_state_t *tls, unsigned size, unsigned type)
497 {
498         uint8_t *buf = tls->outbuf + OUTBUF_PFX;
499         struct record_hdr *xhdr;
500         uint8_t padding_length;
501
502         xhdr = (void*)(buf - RECHDR_LEN);
503         if (CIPHER_ID != TLS_RSA_WITH_NULL_SHA256)
504                 xhdr = (void*)(buf - RECHDR_LEN - AES_BLOCKSIZE); /* place for IV */
505
506         xhdr->type = type;
507         xhdr->proto_maj = TLS_MAJ;
508         xhdr->proto_min = TLS_MIN;
509         /* fake unencrypted record len for MAC calculation */
510         xhdr->len16_hi = size >> 8;
511         xhdr->len16_lo = size & 0xff;
512
513         /* Calculate MAC signature */
514 //TODO: convert hmac_sha256 to precomputed
515         hmac_sha256(buf + size,
516                         tls->client_write_MAC_key, sizeof(tls->client_write_MAC_key),
517                         &tls->write_seq64_be, sizeof(tls->write_seq64_be),
518                         xhdr, RECHDR_LEN,
519                         buf, size,
520                         NULL);
521         tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(tls->write_seq64_be));
522
523         size += SHA256_OUTSIZE;
524
525         // RFC 5246
526         // 6.2.3.1.  Null or Standard Stream Cipher
527         //
528         // Stream ciphers (including BulkCipherAlgorithm.null; see Appendix A.6)
529         // convert TLSCompressed.fragment structures to and from stream
530         // TLSCiphertext.fragment structures.
531         //
532         //    stream-ciphered struct {
533         //        opaque content[TLSCompressed.length];
534         //        opaque MAC[SecurityParameters.mac_length];
535         //    } GenericStreamCipher;
536         //
537         // The MAC is generated as:
538         //    MAC(MAC_write_key, seq_num +
539         //                          TLSCompressed.type +
540         //                          TLSCompressed.version +
541         //                          TLSCompressed.length +
542         //                          TLSCompressed.fragment);
543         // where "+" denotes concatenation.
544         // seq_num
545         //    The sequence number for this record.
546         // MAC
547         //    The MAC algorithm specified by SecurityParameters.mac_algorithm.
548         //
549         // Note that the MAC is computed before encryption.  The stream cipher
550         // encrypts the entire block, including the MAC.
551         //...
552         // Appendix C.  Cipher Suite Definitions
553         //...
554         // MAC       Algorithm    mac_length  mac_key_length
555         // --------  -----------  ----------  --------------
556         // SHA       HMAC-SHA1       20            20
557         // SHA256    HMAC-SHA256     32            32
558         if (CIPHER_ID == TLS_RSA_WITH_NULL_SHA256) {
559                 /* No encryption, only signing */
560                 xhdr->len16_hi = size >> 8;
561                 xhdr->len16_lo = size & 0xff;
562                 dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
563                 xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
564                 dbg("wrote %u bytes (NULL crypt, SHA256 hash)\n", size);
565                 return;
566         }
567
568         // 6.2.3.2.  CBC Block Cipher
569         // For block ciphers (such as 3DES or AES), the encryption and MAC
570         // functions convert TLSCompressed.fragment structures to and from block
571         // TLSCiphertext.fragment structures.
572         //    struct {
573         //        opaque IV[SecurityParameters.record_iv_length];
574         //        block-ciphered struct {
575         //            opaque content[TLSCompressed.length];
576         //            opaque MAC[SecurityParameters.mac_length];
577         //            uint8 padding[GenericBlockCipher.padding_length];
578         //            uint8 padding_length;
579         //        };
580         //    } GenericBlockCipher;
581         //...
582         // IV
583         //    The Initialization Vector (IV) SHOULD be chosen at random, and
584         //    MUST be unpredictable.  Note that in versions of TLS prior to 1.1,
585         //    there was no IV field (...).  For block ciphers, the IV length is
586         //    of length SecurityParameters.record_iv_length, which is equal to the
587         //    SecurityParameters.block_size.
588         // padding
589         //    Padding that is added to force the length of the plaintext to be
590         //    an integral multiple of the block cipher's block length.
591         // padding_length
592         //    The padding length MUST be such that the total size of the
593         //    GenericBlockCipher structure is a multiple of the cipher's block
594         //    length.  Legal values range from zero to 255, inclusive.
595         //...
596         // Appendix C.  Cipher Suite Definitions
597         //...
598         //                         Key      IV   Block
599         // Cipher        Type    Material  Size  Size
600         // ------------  ------  --------  ----  -----
601         // AES_128_CBC   Block      16      16     16
602         // AES_256_CBC   Block      32      16     16
603
604         /* Fill IV and padding in outbuf */
605         tls_get_random(buf - AES_BLOCKSIZE, AES_BLOCKSIZE); /* IV */
606         dbg("before crypt: 5 hdr + %u data + %u hash bytes\n", size, SHA256_OUTSIZE);
607         // RFC is talking nonsense:
608         //    "Padding that is added to force the length of the plaintext to be
609         //    an integral multiple of the block cipher's block length."
610         // WRONG. _padding+padding_length_, not just _padding_,
611         // pads the data.
612         // IOW: padding_length is the last byte of padding[] array,
613         // contrary to what RFC depicts.
614         //
615         // What actually happens is that there is always padding.
616         // If you need one byte to reach BLOCKSIZE, this byte is 0x00.
617         // If you need two bytes, they are both 0x01.
618         // If you need three, they are 0x02,0x02,0x02. And so on.
619         // If you need no bytes to reach BLOCKSIZE, you have to pad a full
620         // BLOCKSIZE with bytes of value (BLOCKSIZE-1).
621         // It's ok to have more than minimum padding, but we do minimum.
622         padding_length = (~size) & (AES_BLOCKSIZE - 1);
623         do {
624                 buf[size++] = padding_length; /* padding */
625         } while ((size & (AES_BLOCKSIZE - 1)) != 0);
626
627         /* Encrypt content+MAC+padding in place */
628         {
629                 psCipherContext_t ctx;
630                 psAesInit(&ctx, buf - AES_BLOCKSIZE, /* IV */
631                         tls->client_write_key, sizeof(tls->client_write_key)
632                 );
633                 psAesEncrypt(&ctx,
634                         buf, /* plaintext */
635                         buf, /* ciphertext */
636                         size
637                 );
638         }
639
640         /* Write out */
641         dbg("writing 5 + %u IV + %u encrypted bytes, padding_length:0x%02x\n",
642                         AES_BLOCKSIZE, size, padding_length);
643         size += AES_BLOCKSIZE;     /* + IV */
644         xhdr->len16_hi = size >> 8;
645         xhdr->len16_lo = size & 0xff;
646         dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
647         xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
648         dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
649 }
650
651 static void xwrite_and_update_handshake_hash(tls_state_t *tls, unsigned size)
652 {
653         if (!tls->encrypt_on_write) {
654                 uint8_t *buf = tls->outbuf + OUTBUF_PFX;
655                 struct record_hdr *xhdr = (void*)(buf - RECHDR_LEN);
656
657                 xhdr->type = RECORD_TYPE_HANDSHAKE;
658                 xhdr->proto_maj = TLS_MAJ;
659                 xhdr->proto_min = TLS_MIN;
660                 xhdr->len16_hi = size >> 8;
661                 xhdr->len16_lo = size & 0xff;
662                 dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
663                 xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
664                 dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
665                 /* Handshake hash does not include record headers */
666                 sha256_hash_dbg(">> sha256:%s", &tls->hsd->handshake_sha256_ctx, buf, size);
667                 return;
668         }
669         xwrite_encrypted(tls, size, RECORD_TYPE_HANDSHAKE);
670 }
671
672 static int tls_has_buffered_record(tls_state_t *tls)
673 {
674         int buffered = tls->buffered_size;
675         struct record_hdr *xhdr;
676         int rec_size;
677
678         if (buffered < RECHDR_LEN)
679                 return 0;
680         xhdr = (void*)(tls->inbuf + tls->ofs_to_buffered);
681         rec_size = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
682         if (buffered < rec_size)
683                 return 0;
684         return rec_size;
685 }
686
687 static const char *alert_text(int code)
688 {
689         switch (code) {
690         case 20:  return "bad MAC";
691         case 50:  return "decode error";
692         case 51:  return "decrypt error";
693         case 40:  return "handshake failure";
694         case 112: return "unrecognized name";
695         }
696         return itoa(code);
697 }
698
699 static int tls_xread_record(tls_state_t *tls)
700 {
701         struct record_hdr *xhdr;
702         int sz;
703         int total;
704         int target;
705
706  again:
707         dbg("ofs_to_buffered:%u buffered_size:%u\n", tls->ofs_to_buffered, tls->buffered_size);
708         total = tls->buffered_size;
709         if (total != 0) {
710                 memmove(tls->inbuf, tls->inbuf + tls->ofs_to_buffered, total);
711                 //dbg("<< remaining at %d [%d] ", tls->ofs_to_buffered, total);
712                 //dump_raw_in("<< %s\n", tls->inbuf, total);
713         }
714         errno = 0;
715         target = MAX_INBUF;
716         for (;;) {
717                 int rem;
718
719                 if (total >= RECHDR_LEN && target == MAX_INBUF) {
720                         xhdr = (void*)tls->inbuf;
721                         target = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
722                         if (target > MAX_INBUF) {
723                                 /* malformed input (too long): yell and die */
724                                 tls->buffered_size = 0;
725                                 tls->ofs_to_buffered = total;
726                                 tls_error_die(tls);
727                         }
728                         /* can also check type/proto_maj/proto_min here */
729                         dbg("xhdr type:%d ver:%d.%d len:%d\n",
730                                 xhdr->type, xhdr->proto_maj, xhdr->proto_min,
731                                 0x100 * xhdr->len16_hi + xhdr->len16_lo
732                         );
733                 }
734                 /* if total >= target, we have a full packet (and possibly more)... */
735                 if (total - target >= 0)
736                         break;
737                 /* input buffer is grown only as needed */
738                 rem = tls->inbuf_size - total;
739                 if (rem == 0) {
740                         tls->inbuf_size += MAX_INBUF / 8;
741                         if (tls->inbuf_size > MAX_INBUF)
742                                 tls->inbuf_size = MAX_INBUF;
743                         dbg("inbuf_size:%d\n", tls->inbuf_size);
744                         rem = tls->inbuf_size - total;
745                         tls->inbuf = xrealloc(tls->inbuf, tls->inbuf_size);
746                 }
747                 sz = safe_read(tls->ifd, tls->inbuf + total, rem);
748                 if (sz <= 0) {
749                         if (sz == 0 && total == 0) {
750                                 /* "Abrupt" EOF, no TLS shutdown (seen from kernel.org) */
751                                 dbg("EOF (without TLS shutdown) from peer\n");
752                                 tls->buffered_size = 0;
753                                 goto end;
754                         }
755                         bb_perror_msg_and_die("short read, have only %d", total);
756                 }
757                 dump_raw_in("<< %s\n", tls->inbuf + total, sz);
758                 total += sz;
759         }
760         tls->buffered_size = total - target;
761         tls->ofs_to_buffered = target;
762         //dbg("<< stashing at %d [%d] ", tls->ofs_to_buffered, tls->buffered_size);
763         //dump_hex("<< %s\n", tls->inbuf + tls->ofs_to_buffered, tls->buffered_size);
764
765         sz = target - RECHDR_LEN;
766
767         /* Needs to be decrypted? */
768         if (tls->min_encrypted_len_on_read > SHA256_OUTSIZE) {
769                 psCipherContext_t ctx;
770                 uint8_t *p = tls->inbuf + RECHDR_LEN;
771                 int padding_len;
772
773                 if (sz & (AES_BLOCKSIZE-1)
774                  || sz < tls->min_encrypted_len_on_read
775                 ) {
776                         bb_error_msg_and_die("bad encrypted len:%u", sz);
777                 }
778                 /* Decrypt content+MAC+padding, moving it over IV in the process */
779                 psAesInit(&ctx, p, /* IV */
780                         tls->server_write_key, sizeof(tls->server_write_key)
781                 );
782                 sz -= AES_BLOCKSIZE; /* we will overwrite IV now */
783                 psAesDecrypt(&ctx,
784                         p + AES_BLOCKSIZE, /* ciphertext */
785                         p,                 /* plaintext */
786                         sz
787                 );
788                 padding_len = p[sz - 1];
789                 dbg("encrypted size:%u type:0x%02x padding_length:0x%02x\n", sz, p[0], padding_len);
790                 padding_len++;
791                 sz -= SHA256_OUTSIZE + padding_len; /* drop MAC and padding */
792                 //if (sz < 0)
793                 //      bb_error_msg_and_die("bad padding size:%u", padding_len);
794         } else {
795                 /* if nonzero, then it's TLS_RSA_WITH_NULL_SHA256: drop MAC */
796                 /* else: no encryption yet on input, subtract zero = NOP */
797                 sz -= tls->min_encrypted_len_on_read;
798         }
799         if (sz < 0)
800                 bb_error_msg_and_die("encrypted data too short");
801
802         //dump_hex("<< %s\n", tls->inbuf, RECHDR_LEN + sz);
803
804         xhdr = (void*)tls->inbuf;
805         if (xhdr->type == RECORD_TYPE_ALERT && sz >= 2) {
806                 uint8_t *p = tls->inbuf + RECHDR_LEN;
807                 dbg("ALERT size:%d level:%d description:%d\n", sz, p[0], p[1]);
808                 if (p[0] == 2) { /* fatal */
809                         bb_error_msg_and_die("TLS %s from peer (alert code %d): %s",
810                                 "error",
811                                 p[1], alert_text(p[1])
812                         );
813                 }
814                 if (p[0] == 1) { /* warning */
815                         if (p[1] == 0) { /* "close_notify" warning: it's EOF */
816                                 dbg("EOF (TLS encoded) from peer\n");
817                                 sz = 0;
818                                 goto end;
819                         }
820 //This possibly needs to be cached and shown only if
821 //a fatal alert follows
822 //                      bb_error_msg("TLS %s from peer (alert code %d): %s",
823 //                              "warning",
824 //                              p[1], alert_text(p[1])
825 //                      );
826                         /* discard it, get next record */
827                         goto again;
828                 }
829                 /* p[0] not 1 or 2: not defined in protocol */
830                 sz = 0;
831                 goto end;
832         }
833
834         /* RFC 5246 is not saying it explicitly, but sha256 hash
835          * in our FINISHED record must include data of incoming packets too!
836          */
837         if (tls->inbuf[0] == RECORD_TYPE_HANDSHAKE) {
838                 sha256_hash_dbg("<< sha256:%s", &tls->hsd->handshake_sha256_ctx, tls->inbuf + RECHDR_LEN, sz);
839         }
840  end:
841         dbg("got block len:%u\n", sz);
842         return sz;
843 }
844
845 /*
846  * DER parsing routines
847  */
848 static unsigned get_der_len(uint8_t **bodyp, uint8_t *der, uint8_t *end)
849 {
850         unsigned len, len1;
851
852         if (end - der < 2)
853                 xfunc_die();
854 //      if ((der[0] & 0x1f) == 0x1f) /* not single-byte item code? */
855 //              xfunc_die();
856
857         len = der[1]; /* maybe it's short len */
858         if (len >= 0x80) {
859                 /* no, it's long */
860
861                 if (len == 0x80 || end - der < (int)(len - 0x7e)) {
862                         /* 0x80 is "0 bytes of len", invalid DER: must use short len if can */
863                         /* need 3 or 4 bytes for 81, 82 */
864                         xfunc_die();
865                 }
866
867                 len1 = der[2]; /* if (len == 0x81) it's "ii 81 xx", fetch xx */
868                 if (len > 0x82) {
869                         /* >0x82 is "3+ bytes of len", should not happen realistically */
870                         xfunc_die();
871                 }
872                 if (len == 0x82) { /* it's "ii 82 xx yy" */
873                         len1 = 0x100*len1 + der[3];
874                         der += 1; /* skip [yy] */
875                 }
876                 der += 1; /* skip [xx] */
877                 len = len1;
878 //              if (len < 0x80)
879 //                      xfunc_die(); /* invalid DER: must use short len if can */
880         }
881         der += 2; /* skip [code]+[1byte] */
882
883         if (end - der < (int)len)
884                 xfunc_die();
885         *bodyp = der;
886
887         return len;
888 }
889
890 static uint8_t *enter_der_item(uint8_t *der, uint8_t **endp)
891 {
892         uint8_t *new_der;
893         unsigned len = get_der_len(&new_der, der, *endp);
894         dbg_der("entered der @%p:0x%02x len:%u inner_byte @%p:0x%02x\n", der, der[0], len, new_der, new_der[0]);
895         /* Move "end" position to cover only this item */
896         *endp = new_der + len;
897         return new_der;
898 }
899
900 static uint8_t *skip_der_item(uint8_t *der, uint8_t *end)
901 {
902         uint8_t *new_der;
903         unsigned len = get_der_len(&new_der, der, end);
904         /* Skip body */
905         new_der += len;
906         dbg_der("skipped der 0x%02x, next byte 0x%02x\n", der[0], new_der[0]);
907         return new_der;
908 }
909
910 static void der_binary_to_pstm(pstm_int *pstm_n, uint8_t *der, uint8_t *end)
911 {
912         uint8_t *bin_ptr;
913         unsigned len = get_der_len(&bin_ptr, der, end);
914
915         dbg_der("binary bytes:%u, first:0x%02x\n", len, bin_ptr[0]);
916         pstm_init_for_read_unsigned_bin(/*pool:*/ NULL, pstm_n, len);
917         pstm_read_unsigned_bin(pstm_n, bin_ptr, len);
918         //return bin + len;
919 }
920
921 static void find_key_in_der_cert(tls_state_t *tls, uint8_t *der, int len)
922 {
923 /* Certificate is a DER-encoded data structure. Each DER element has a length,
924  * which makes it easy to skip over large compound elements of any complexity
925  * without parsing them. Example: partial decode of kernel.org certificate:
926  *  SEQ 0x05ac/1452 bytes (Certificate): 308205ac
927  *    SEQ 0x0494/1172 bytes (tbsCertificate): 30820494
928  *      [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0] 3 bytes: a003
929  *        INTEGER (version): 0201 02
930  *      INTEGER 0x11 bytes (serialNumber): 0211 00 9f85bf664b0cddafca508679501b2be4
931  *      //^^^^^^note: matrixSSL also allows [ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2] = 0x82 type
932  *      SEQ 0x0d bytes (signatureAlgo): 300d
933  *        OID 9 bytes: 0609 2a864886f70d01010b (OID_SHA256_RSA_SIG 42.134.72.134.247.13.1.1.11)
934  *        NULL: 0500
935  *      SEQ 0x5f bytes (issuer): 305f
936  *        SET 11 bytes: 310b
937  *          SEQ 9 bytes: 3009
938  *            OID 3 bytes: 0603 550406
939  *            Printable string "FR": 1302 4652
940  *        SET 14 bytes: 310e
941  *          SEQ 12 bytes: 300c
942  *            OID 3 bytes: 0603 550408
943  *            Printable string "Paris": 1305 5061726973
944  *        SET 14 bytes: 310e
945  *          SEQ 12 bytes: 300c
946  *            OID 3 bytes: 0603 550407
947  *            Printable string "Paris": 1305 5061726973
948  *        SET 14 bytes: 310e
949  *          SEQ 12 bytes: 300c
950  *            OID 3 bytes: 0603 55040a
951  *            Printable string "Gandi": 1305 47616e6469
952  *        SET 32 bytes: 3120
953  *          SEQ 30 bytes: 301e
954  *            OID 3 bytes: 0603 550403
955  *            Printable string "Gandi Standard SSL CA 2": 1317 47616e6469205374616e646172642053534c2043412032
956  *      SEQ 30 bytes (validity): 301e
957  *        TIME "161011000000Z": 170d 3136313031313030303030305a
958  *        TIME "191011235959Z": 170d 3139313031313233353935395a
959  *      SEQ 0x5b/91 bytes (subject): 305b //I did not decode this
960  *          3121301f060355040b1318446f6d61696e20436f
961  *          6e74726f6c2056616c6964617465643121301f06
962  *          0355040b1318506f73697469766553534c204d75
963  *          6c74692d446f6d61696e31133011060355040313
964  *          0a6b65726e656c2e6f7267
965  *      SEQ 0x01a2/418 bytes (subjectPublicKeyInfo): 308201a2
966  *        SEQ 13 bytes (algorithm): 300d
967  *          OID 9 bytes: 0609 2a864886f70d010101 (OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1)
968  *          NULL: 0500
969  *        BITSTRING 0x018f/399 bytes (publicKey): 0382018f
970  *          ????: 00
971  *          //after the zero byte, it appears key itself uses DER encoding:
972  *          SEQ 0x018a/394 bytes: 3082018a
973  *            INTEGER 0x0181/385 bytes (modulus): 02820181
974  *                  00b1ab2fc727a3bef76780c9349bf3
975  *                  ...24 more blocks of 15 bytes each...
976  *                  90e895291c6bc8693b65
977  *            INTEGER 3 bytes (exponent): 0203 010001
978  *      [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0x3] 0x01e5 bytes (X509v3 extensions): a38201e5
979  *        SEQ 0x01e1 bytes: 308201e1
980  *        ...
981  * Certificate is a sequence of three elements:
982  *      tbsCertificate (SEQ)
983  *      signatureAlgorithm (AlgorithmIdentifier)
984  *      signatureValue (BIT STRING)
985  *
986  * In turn, tbsCertificate is a sequence of:
987  *      version
988  *      serialNumber
989  *      signatureAlgo (AlgorithmIdentifier)
990  *      issuer (Name, has complex structure)
991  *      validity (Validity, SEQ of two Times)
992  *      subject (Name)
993  *      subjectPublicKeyInfo (SEQ)
994  *      ...
995  *
996  * subjectPublicKeyInfo is a sequence of:
997  *      algorithm (AlgorithmIdentifier)
998  *      publicKey (BIT STRING)
999  *
1000  * We need Certificate.tbsCertificate.subjectPublicKeyInfo.publicKey
1001  */
1002         uint8_t *end = der + len;
1003
1004         /* enter "Certificate" item: [der, end) will be only Cert */
1005         der = enter_der_item(der, &end);
1006
1007         /* enter "tbsCertificate" item: [der, end) will be only tbsCert */
1008         der = enter_der_item(der, &end);
1009
1010         /* skip up to subjectPublicKeyInfo */
1011         der = skip_der_item(der, end); /* version */
1012         der = skip_der_item(der, end); /* serialNumber */
1013         der = skip_der_item(der, end); /* signatureAlgo */
1014         der = skip_der_item(der, end); /* issuer */
1015         der = skip_der_item(der, end); /* validity */
1016         der = skip_der_item(der, end); /* subject */
1017
1018         /* enter subjectPublicKeyInfo */
1019         der = enter_der_item(der, &end);
1020         { /* check subjectPublicKeyInfo.algorithm */
1021                 static const uint8_t expected[] = {
1022                         0x30,0x0d, // SEQ 13 bytes
1023                         0x06,0x09, 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01, // OID RSA_KEY_ALG 42.134.72.134.247.13.1.1.1
1024                         //0x05,0x00, // NULL
1025                 };
1026                 if (memcmp(der, expected, sizeof(expected)) != 0)
1027                         bb_error_msg_and_die("not RSA key");
1028         }
1029         /* skip subjectPublicKeyInfo.algorithm */
1030         der = skip_der_item(der, end);
1031         /* enter subjectPublicKeyInfo.publicKey */
1032 //      die_if_not_this_der_type(der, end, 0x03); /* must be BITSTRING */
1033         der = enter_der_item(der, &end);
1034
1035         /* parse RSA key: */
1036 //based on getAsnRsaPubKey(), pkcs1ParsePrivBin() is also of note
1037         dbg("key bytes:%u, first:0x%02x\n", (int)(end - der), der[0]);
1038         if (end - der < 14) xfunc_die();
1039         /* example format:
1040          * ignore bits: 00
1041          * SEQ 0x018a/394 bytes: 3082018a
1042          *   INTEGER 0x0181/385 bytes (modulus): 02820181 XX...XXX
1043          *   INTEGER 3 bytes (exponent): 0203 010001
1044          */
1045         if (*der != 0) /* "ignore bits", should be 0 */
1046                 xfunc_die();
1047         der++;
1048         der = enter_der_item(der, &end); /* enter SEQ */
1049         /* memset(tls->hsd->server_rsa_pub_key, 0, sizeof(tls->hsd->server_rsa_pub_key)); - already is */
1050         der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.N, der, end); /* modulus */
1051         der = skip_der_item(der, end);
1052         der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.e, der, end); /* exponent */
1053         tls->hsd->server_rsa_pub_key.size = pstm_unsigned_bin_size(&tls->hsd->server_rsa_pub_key.N);
1054         dbg("server_rsa_pub_key.size:%d\n", tls->hsd->server_rsa_pub_key.size);
1055 }
1056
1057 /*
1058  * TLS Handshake routines
1059  */
1060 static int tls_xread_handshake_block(tls_state_t *tls, int min_len)
1061 {
1062         struct record_hdr *xhdr;
1063         int len = tls_xread_record(tls);
1064
1065         xhdr = (void*)tls->inbuf;
1066         if (len < min_len
1067          || xhdr->type != RECORD_TYPE_HANDSHAKE
1068          || xhdr->proto_maj != TLS_MAJ
1069          || xhdr->proto_min != TLS_MIN
1070         ) {
1071                 bad_record_die(tls, "handshake record", len);
1072         }
1073         dbg("got HANDSHAKE\n");
1074         return len;
1075 }
1076
1077 static ALWAYS_INLINE void fill_handshake_record_hdr(void *buf, unsigned type, unsigned len)
1078 {
1079         struct handshake_hdr {
1080                 uint8_t type;
1081                 uint8_t len24_hi, len24_mid, len24_lo;
1082         } *h = buf;
1083
1084         len -= 4;
1085         h->type = type;
1086         h->len24_hi  = len >> 16;
1087         h->len24_mid = len >> 8;
1088         h->len24_lo  = len & 0xff;
1089 }
1090
1091 static void send_client_hello(tls_state_t *tls, const char *sni)
1092 {
1093         struct client_hello {
1094                 uint8_t type;
1095                 uint8_t len24_hi, len24_mid, len24_lo;
1096                 uint8_t proto_maj, proto_min;
1097                 uint8_t rand32[32];
1098                 uint8_t session_id_len;
1099                 /* uint8_t session_id[]; */
1100                 uint8_t cipherid_len16_hi, cipherid_len16_lo;
1101                 uint8_t cipherid[2 * 2]; /* actually variable */
1102                 uint8_t comprtypes_len;
1103                 uint8_t comprtypes[1]; /* actually variable */
1104                 /* Extensions (SNI shown):
1105                  * hi,lo // len of all extensions
1106                  *   00,00 // extension_type: "Server Name"
1107                  *   00,0e // list len (there can be more than one SNI)
1108                  *     00,0c // len of 1st Server Name Indication
1109                  *       00    // name type: host_name
1110                  *       00,09   // name len
1111                  *       "localhost" // name
1112                  */
1113 // GNU Wget 1.18 to cdn.kernel.org sends these extensions:
1114 // 0055
1115 //   0005 0005 0100000000 - status_request
1116 //   0000 0013 0011 00 000e 63646e 2e 6b65726e656c 2e 6f7267 - server_name
1117 //   ff01 0001 00 - renegotiation_info
1118 //   0023 0000 - session_ticket
1119 //   000a 0008 0006001700180019 - supported_groups
1120 //   000b 0002 0100 - ec_point_formats
1121 //   000d 0016 00140401040305010503060106030301030302010203 - signature_algorithms
1122         };
1123         struct client_hello *record;
1124         int len;
1125         int sni_len = sni ? strnlen(sni, 127) : 0;
1126
1127         len = sizeof(*record);
1128         if (sni_len)
1129                 len += 11 + strlen(sni);
1130         record = tls_get_outbuf(tls, len);
1131         memset(record, 0, len);
1132
1133         fill_handshake_record_hdr(record, HANDSHAKE_CLIENT_HELLO, len);
1134         record->proto_maj = TLS_MAJ;    /* the "requested" version of the protocol, */
1135         record->proto_min = TLS_MIN;    /* can be higher than one in record headers */
1136         tls_get_random(record->rand32, sizeof(record->rand32));
1137         if (TLS_DEBUG_FIXED_SECRETS)
1138                 memset(record->rand32, 0x11, sizeof(record->rand32));
1139         memcpy(tls->hsd->client_and_server_rand32, record->rand32, sizeof(record->rand32));
1140         /* record->session_id_len = 0; - already is */
1141
1142         /* record->cipherid_len16_hi = 0; */
1143         record->cipherid_len16_lo = 2 * 2;
1144         if ((CIPHER_ID >> 8) != 0)
1145                 record->cipherid[0] = CIPHER_ID >> 8;
1146         record->cipherid[1] = CIPHER_ID & 0xff;
1147         /* RFC 5746 Renegotiation Indication Extension - some servers will refuse to work with us otherwise */
1148         /*record->cipherid[2] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV >> 8; - zero */
1149         record->cipherid[3] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV & 0xff;
1150
1151         record->comprtypes_len = 1;
1152         /* record->comprtypes[0] = 0; */
1153
1154         if (sni_len) {
1155                 uint8_t *p = (void*)(record + 1);
1156                 //p[0] = 0;         //
1157                 p[1] = sni_len + 9; //ext_len
1158                 //p[2] = 0;             //
1159                 //p[3] = 0;             //extension_type
1160                 //p[4] = 0;         //
1161                 p[5] = sni_len + 5; //list len
1162                 //p[6] = 0;             //
1163                 p[7] = sni_len + 3;     //len of 1st SNI
1164                 //p[8] = 0;         //name type
1165                 //p[9] = 0;             //
1166                 p[10] = sni_len;        //name len
1167                 memcpy(&p[11], sni, sni_len);
1168         }
1169
1170         dbg(">> CLIENT_HELLO\n");
1171         xwrite_and_update_handshake_hash(tls, len);
1172 }
1173
1174 static void get_server_hello(tls_state_t *tls)
1175 {
1176         struct server_hello {
1177                 struct record_hdr xhdr;
1178                 uint8_t type;
1179                 uint8_t len24_hi, len24_mid, len24_lo;
1180                 uint8_t proto_maj, proto_min;
1181                 uint8_t rand32[32]; /* first 4 bytes are unix time in BE format */
1182                 uint8_t session_id_len;
1183                 uint8_t session_id[32];
1184                 uint8_t cipherid_hi, cipherid_lo;
1185                 uint8_t comprtype;
1186                 /* extensions may follow, but only those which client offered in its Hello */
1187         };
1188
1189         struct server_hello *hp;
1190         uint8_t *cipherid;
1191         int len;
1192
1193         len = tls_xread_handshake_block(tls, 74);
1194
1195         hp = (void*)tls->inbuf;
1196         // 74 bytes:
1197         // 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|
1198         //SvHl len=70 maj.min unixtime^^^ 28randbytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^ slen sid32bytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cipSel comprSel
1199         if (hp->type != HANDSHAKE_SERVER_HELLO
1200          || hp->len24_hi  != 0
1201          || hp->len24_mid != 0
1202          /* hp->len24_lo checked later */
1203          || hp->proto_maj != TLS_MAJ
1204          || hp->proto_min != TLS_MIN
1205         ) {
1206                 bad_record_die(tls, "'server hello'", len);
1207         }
1208
1209         cipherid = &hp->cipherid_hi;
1210         if (hp->session_id_len != 32) {
1211                 if (hp->session_id_len != 0)
1212                         tls_error_die(tls);
1213
1214                 // session_id_len == 0: no session id
1215                 // "The server
1216                 // may return an empty session_id to indicate that the session will
1217                 // not be cached and therefore cannot be resumed."
1218                 cipherid -= 32;
1219                 hp->len24_lo += 32; /* what len would be if session id would be present */
1220         }
1221
1222         if (hp->len24_lo < 70
1223          || cipherid[0]  != (CIPHER_ID >> 8)
1224          || cipherid[1]  != (CIPHER_ID & 0xff)
1225          || cipherid[2]  != 0 /* comprtype */
1226         ) {
1227                 tls_error_die(tls);
1228         }
1229
1230         dbg("<< SERVER_HELLO\n");
1231         memcpy(tls->hsd->client_and_server_rand32 + 32, hp->rand32, sizeof(hp->rand32));
1232 }
1233
1234 static void get_server_cert(tls_state_t *tls)
1235 {
1236         struct record_hdr *xhdr;
1237         uint8_t *certbuf;
1238         int len, len1;
1239
1240         len = tls_xread_handshake_block(tls, 10);
1241
1242         xhdr = (void*)tls->inbuf;
1243         certbuf = (void*)(xhdr + 1);
1244         if (certbuf[0] != HANDSHAKE_CERTIFICATE)
1245                 tls_error_die(tls);
1246         dbg("<< CERTIFICATE\n");
1247         // 4392 bytes:
1248         // 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...
1249         //Cert len=4388 ChainLen CertLen^ DER encoded X509 starts here. openssl x509 -in FILE -inform DER -noout -text
1250         len1 = get24be(certbuf + 1);
1251         if (len1 > len - 4) tls_error_die(tls);
1252         len = len1;
1253         len1 = get24be(certbuf + 4);
1254         if (len1 > len - 3) tls_error_die(tls);
1255         len = len1;
1256         len1 = get24be(certbuf + 7);
1257         if (len1 > len - 3) tls_error_die(tls);
1258         len = len1;
1259
1260         if (len)
1261                 find_key_in_der_cert(tls, certbuf + 10, len);
1262 }
1263
1264 static void send_client_key_exchange(tls_state_t *tls)
1265 {
1266         struct client_key_exchange {
1267                 uint8_t type;
1268                 uint8_t len24_hi, len24_mid, len24_lo;
1269                 /* keylen16 exists for RSA (in TLS, not in SSL), but not for some other key types */
1270                 uint8_t keylen16_hi, keylen16_lo;
1271                 uint8_t key[4 * 1024]; // size??
1272         };
1273 //FIXME: better size estimate
1274         struct client_key_exchange *record = tls_get_outbuf(tls, sizeof(*record));
1275         uint8_t rsa_premaster[RSA_PREMASTER_SIZE];
1276         int len;
1277
1278         tls_get_random(rsa_premaster, sizeof(rsa_premaster));
1279         if (TLS_DEBUG_FIXED_SECRETS)
1280                 memset(rsa_premaster, 0x44, sizeof(rsa_premaster));
1281         // RFC 5246
1282         // "Note: The version number in the PreMasterSecret is the version
1283         // offered by the client in the ClientHello.client_version, not the
1284         // version negotiated for the connection."
1285         rsa_premaster[0] = TLS_MAJ;
1286         rsa_premaster[1] = TLS_MIN;
1287         len = psRsaEncryptPub(/*pool:*/ NULL,
1288                 /* psRsaKey_t* */ &tls->hsd->server_rsa_pub_key,
1289                 rsa_premaster, /*inlen:*/ sizeof(rsa_premaster),
1290                 record->key, sizeof(record->key),
1291                 data_param_ignored
1292         );
1293         record->keylen16_hi = len >> 8;
1294         record->keylen16_lo = len & 0xff;
1295         len += 2;
1296         record->type = HANDSHAKE_CLIENT_KEY_EXCHANGE;
1297         record->len24_hi  = 0;
1298         record->len24_mid = len >> 8;
1299         record->len24_lo  = len & 0xff;
1300         len += 4;
1301
1302         dbg(">> CLIENT_KEY_EXCHANGE\n");
1303         xwrite_and_update_handshake_hash(tls, len);
1304
1305         // RFC 5246
1306         // For all key exchange methods, the same algorithm is used to convert
1307         // the pre_master_secret into the master_secret.  The pre_master_secret
1308         // should be deleted from memory once the master_secret has been
1309         // computed.
1310         //      master_secret = PRF(pre_master_secret, "master secret",
1311         //                          ClientHello.random + ServerHello.random)
1312         //                          [0..47];
1313         // The master secret is always exactly 48 bytes in length.  The length
1314         // of the premaster secret will vary depending on key exchange method.
1315         prf_hmac_sha256(
1316                 tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
1317                 rsa_premaster, sizeof(rsa_premaster),
1318                 "master secret",
1319                 tls->hsd->client_and_server_rand32, sizeof(tls->hsd->client_and_server_rand32)
1320         );
1321         dump_hex("master secret:%s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
1322
1323         // RFC 5246
1324         // 6.3.  Key Calculation
1325         //
1326         // The Record Protocol requires an algorithm to generate keys required
1327         // by the current connection state (see Appendix A.6) from the security
1328         // parameters provided by the handshake protocol.
1329         //
1330         // The master secret is expanded into a sequence of secure bytes, which
1331         // is then split to a client write MAC key, a server write MAC key, a
1332         // client write encryption key, and a server write encryption key.  Each
1333         // of these is generated from the byte sequence in that order.  Unused
1334         // values are empty.  Some AEAD ciphers may additionally require a
1335         // client write IV and a server write IV (see Section 6.2.3.3).
1336         //
1337         // When keys and MAC keys are generated, the master secret is used as an
1338         // entropy source.
1339         //
1340         // To generate the key material, compute
1341         //
1342         //    key_block = PRF(SecurityParameters.master_secret,
1343         //                    "key expansion",
1344         //                    SecurityParameters.server_random +
1345         //                    SecurityParameters.client_random);
1346         //
1347         // until enough output has been generated.  Then, the key_block is
1348         // partitioned as follows:
1349         //
1350         //    client_write_MAC_key[SecurityParameters.mac_key_length]
1351         //    server_write_MAC_key[SecurityParameters.mac_key_length]
1352         //    client_write_key[SecurityParameters.enc_key_length]
1353         //    server_write_key[SecurityParameters.enc_key_length]
1354         //    client_write_IV[SecurityParameters.fixed_iv_length]
1355         //    server_write_IV[SecurityParameters.fixed_iv_length]
1356         {
1357                 uint8_t tmp64[64];
1358
1359                 /* make "server_rand32 + client_rand32" */
1360                 memcpy(&tmp64[0] , &tls->hsd->client_and_server_rand32[32], 32);
1361                 memcpy(&tmp64[32], &tls->hsd->client_and_server_rand32[0] , 32);
1362
1363                 prf_hmac_sha256(
1364                         tls->client_write_MAC_key, 2 * (SHA256_OUTSIZE + AES256_KEYSIZE),
1365                         // also fills:
1366                         // server_write_MAC_key[SHA256_OUTSIZE]
1367                         // client_write_key[AES256_KEYSIZE]
1368                         // server_write_key[AES256_KEYSIZE]
1369                         tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
1370                         "key expansion",
1371                         tmp64, 64
1372                 );
1373                 dump_hex("client_write_MAC_key:%s\n",
1374                         tls->client_write_MAC_key, sizeof(tls->client_write_MAC_key)
1375                 );
1376                 dump_hex("client_write_key:%s\n",
1377                         tls->client_write_key, sizeof(tls->client_write_key)
1378                 );
1379         }
1380 }
1381
1382 static const uint8_t rec_CHANGE_CIPHER_SPEC[] = {
1383         RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
1384         01
1385 };
1386
1387 static void send_change_cipher_spec(tls_state_t *tls)
1388 {
1389         dbg(">> CHANGE_CIPHER_SPEC\n");
1390         xwrite(tls->ofd, rec_CHANGE_CIPHER_SPEC, sizeof(rec_CHANGE_CIPHER_SPEC));
1391 }
1392
1393 // 7.4.9.  Finished
1394 // A Finished message is always sent immediately after a change
1395 // cipher spec message to verify that the key exchange and
1396 // authentication processes were successful.  It is essential that a
1397 // change cipher spec message be received between the other handshake
1398 // messages and the Finished message.
1399 //...
1400 // The Finished message is the first one protected with the just
1401 // negotiated algorithms, keys, and secrets.  Recipients of Finished
1402 // messages MUST verify that the contents are correct.  Once a side
1403 // has sent its Finished message and received and validated the
1404 // Finished message from its peer, it may begin to send and receive
1405 // application data over the connection.
1406 //...
1407 // struct {
1408 //     opaque verify_data[verify_data_length];
1409 // } Finished;
1410 //
1411 // verify_data
1412 //    PRF(master_secret, finished_label, Hash(handshake_messages))
1413 //       [0..verify_data_length-1];
1414 //
1415 // finished_label
1416 //    For Finished messages sent by the client, the string
1417 //    "client finished".  For Finished messages sent by the server,
1418 //    the string "server finished".
1419 //
1420 // Hash denotes a Hash of the handshake messages.  For the PRF
1421 // defined in Section 5, the Hash MUST be the Hash used as the basis
1422 // for the PRF.  Any cipher suite which defines a different PRF MUST
1423 // also define the Hash to use in the Finished computation.
1424 //
1425 // In previous versions of TLS, the verify_data was always 12 octets
1426 // long.  In the current version of TLS, it depends on the cipher
1427 // suite.  Any cipher suite which does not explicitly specify
1428 // verify_data_length has a verify_data_length equal to 12.  This
1429 // includes all existing cipher suites.
1430 static void send_client_finished(tls_state_t *tls)
1431 {
1432         struct finished {
1433                 uint8_t type;
1434                 uint8_t len24_hi, len24_mid, len24_lo;
1435                 uint8_t prf_result[12];
1436         };
1437         struct finished *record = tls_get_outbuf(tls, sizeof(*record));
1438         uint8_t handshake_hash[SHA256_OUTSIZE];
1439
1440         fill_handshake_record_hdr(record, HANDSHAKE_FINISHED, sizeof(*record));
1441
1442         sha256_peek(&tls->hsd->handshake_sha256_ctx, handshake_hash);
1443         prf_hmac_sha256(record->prf_result, sizeof(record->prf_result),
1444                         tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
1445                         "client finished",
1446                         handshake_hash, sizeof(handshake_hash)
1447         );
1448         dump_hex("from secret: %s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
1449         dump_hex("from labelSeed: %s", "client finished", sizeof("client finished")-1);
1450         dump_hex("%s\n", handshake_hash, sizeof(handshake_hash));
1451         dump_hex("=> digest: %s\n", record->prf_result, sizeof(record->prf_result));
1452
1453         dbg(">> FINISHED\n");
1454         xwrite_encrypted(tls, sizeof(*record), RECORD_TYPE_HANDSHAKE);
1455 }
1456
1457 void FAST_FUNC tls_handshake(tls_state_t *tls, const char *sni)
1458 {
1459         // Client              RFC 5246                Server
1460         // (*) - optional messages, not always sent
1461         //
1462         // ClientHello          ------->
1463         //                                        ServerHello
1464         //                                       Certificate*
1465         //                                 ServerKeyExchange*
1466         //                                CertificateRequest*
1467         //                      <-------      ServerHelloDone
1468         // Certificate*
1469         // ClientKeyExchange
1470         // CertificateVerify*
1471         // [ChangeCipherSpec]
1472         // Finished             ------->
1473         //                                 [ChangeCipherSpec]
1474         //                      <-------             Finished
1475         // Application Data     <------>     Application Data
1476         int len;
1477
1478         tls->hsd = xzalloc(sizeof(*tls->hsd));
1479         sha256_begin(&tls->hsd->handshake_sha256_ctx);
1480
1481         send_client_hello(tls, sni);
1482         get_server_hello(tls);
1483
1484         // RFC 5246
1485         // The server MUST send a Certificate message whenever the agreed-
1486         // upon key exchange method uses certificates for authentication
1487         // (this includes all key exchange methods defined in this document
1488         // except DH_anon).  This message will always immediately follow the
1489         // ServerHello message.
1490         //
1491         // IOW: in practice, Certificate *always* follows.
1492         // (for example, kernel.org does not even accept DH_anon cipher id)
1493         get_server_cert(tls);
1494
1495         len = tls_xread_handshake_block(tls, 4);
1496         if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_SERVER_KEY_EXCHANGE) {
1497                 // 459 bytes:
1498                 // 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...
1499                 //SvKey len=455^
1500                 // with TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 461 bytes:
1501                 // 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...
1502                 dbg("<< SERVER_KEY_EXCHANGE len:%u\n", len);
1503 //probably need to save it
1504                 tls_xread_handshake_block(tls, 4);
1505         }
1506
1507 //      if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_CERTIFICATE_REQUEST) {
1508 //              dbg("<< CERTIFICATE_REQUEST\n");
1509 // RFC 5246: (in response to this,) "If no suitable certificate is available,
1510 // the client MUST send a certificate message containing no
1511 // certificates.  That is, the certificate_list structure has a
1512 // length of zero. ...
1513 // Client certificates are sent using the Certificate structure
1514 // defined in Section 7.4.2."
1515 // (i.e. the same format as server certs)
1516 //              tls_xread_handshake_block(tls, 4);
1517 //      }
1518
1519         if (tls->inbuf[RECHDR_LEN] != HANDSHAKE_SERVER_HELLO_DONE)
1520                 tls_error_die(tls);
1521         // 0e 000000 (len:0)
1522         dbg("<< SERVER_HELLO_DONE\n");
1523
1524         send_client_key_exchange(tls);
1525
1526         send_change_cipher_spec(tls);
1527         /* from now on we should send encrypted */
1528         /* tls->write_seq64_be = 0; - already is */
1529         tls->encrypt_on_write = 1;
1530
1531         send_client_finished(tls);
1532
1533         /* Get CHANGE_CIPHER_SPEC */
1534         len = tls_xread_record(tls);
1535         if (len != 1 || memcmp(tls->inbuf, rec_CHANGE_CIPHER_SPEC, 6) != 0)
1536                 tls_error_die(tls);
1537         dbg("<< CHANGE_CIPHER_SPEC\n");
1538         if (CIPHER_ID == TLS_RSA_WITH_NULL_SHA256)
1539                 tls->min_encrypted_len_on_read = SHA256_OUTSIZE;
1540         else
1541                 /* all incoming packets now should be encrypted and have IV + MAC + padding */
1542                 tls->min_encrypted_len_on_read = AES_BLOCKSIZE + SHA256_OUTSIZE + AES_BLOCKSIZE;
1543
1544         /* Get (encrypted) FINISHED from the server */
1545         len = tls_xread_record(tls);
1546         if (len < 4 || tls->inbuf[RECHDR_LEN] != HANDSHAKE_FINISHED)
1547                 tls_error_die(tls);
1548         dbg("<< FINISHED\n");
1549         /* application data can be sent/received */
1550
1551         /* free handshake data */
1552 //      if (PARANOIA)
1553 //              memset(tls->hsd, 0, sizeof(*tls->hsd));
1554         free(tls->hsd);
1555         tls->hsd = NULL;
1556 }
1557
1558 static void tls_xwrite(tls_state_t *tls, int len)
1559 {
1560         dbg(">> DATA\n");
1561         xwrite_encrypted(tls, len, RECORD_TYPE_APPLICATION_DATA);
1562 }
1563
1564 // To run a test server using openssl:
1565 // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
1566 // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1
1567 //
1568 // Unencryped SHA256 example:
1569 // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
1570 // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL
1571 // openssl s_client -connect 127.0.0.1:4433 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL-SHA256
1572
1573 void FAST_FUNC tls_run_copy_loop(tls_state_t *tls)
1574 {
1575         fd_set readfds;
1576         int inbuf_size;
1577         const int INBUF_STEP = 4 * 1024;
1578
1579 //TODO: convert to poll
1580         /* Select loop copying stdin to ofd, and ifd to stdout */
1581         FD_ZERO(&readfds);
1582         FD_SET(tls->ifd, &readfds);
1583         FD_SET(STDIN_FILENO, &readfds);
1584
1585         inbuf_size = INBUF_STEP;
1586         for (;;) {
1587                 fd_set testfds;
1588                 int nread;
1589
1590                 testfds = readfds;
1591                 if (select(tls->ifd + 1, &testfds, NULL, NULL, NULL) < 0)
1592                         bb_perror_msg_and_die("select");
1593
1594                 if (FD_ISSET(STDIN_FILENO, &testfds)) {
1595                         void *buf;
1596
1597                         dbg("STDIN HAS DATA\n");
1598                         buf = tls_get_outbuf(tls, inbuf_size);
1599                         nread = safe_read(STDIN_FILENO, buf, inbuf_size);
1600                         if (nread < 1) {
1601                                 /* We'd want to do this: */
1602                                 /* Close outgoing half-connection so they get EOF,
1603                                  * but leave incoming alone so we can see response
1604                                  */
1605                                 //shutdown(tls->ofd, SHUT_WR);
1606                                 /* But TLS has no way to encode this,
1607                                  * doubt it's ok to do it "raw"
1608                                  */
1609                                 FD_CLR(STDIN_FILENO, &readfds);
1610                                 tls_free_outbuf(tls); /* mem usage optimization */
1611                         } else {
1612                                 if (nread == inbuf_size) {
1613                                         /* TLS has per record overhead, if input comes fast,
1614                                          * read, encrypt and send bigger chunks
1615                                          */
1616                                         inbuf_size += INBUF_STEP;
1617                                         if (inbuf_size > MAX_OUTBUF)
1618                                                 inbuf_size = MAX_OUTBUF;
1619                                 }
1620                                 tls_xwrite(tls, nread);
1621                         }
1622                 }
1623                 if (FD_ISSET(tls->ifd, &testfds)) {
1624                         dbg("NETWORK HAS DATA\n");
1625  read_record:
1626                         nread = tls_xread_record(tls);
1627                         if (nread < 1) {
1628                                 /* TLS protocol has no real concept of one-sided shutdowns:
1629                                  * if we get "TLS EOF" from the peer, writes will fail too
1630                                  */
1631                                 //FD_CLR(tls->ifd, &readfds);
1632                                 //close(STDOUT_FILENO);
1633                                 //tls_free_inbuf(tls); /* mem usage optimization */
1634                                 //continue;
1635                                 break;
1636                         }
1637                         if (tls->inbuf[0] != RECORD_TYPE_APPLICATION_DATA)
1638                                 bb_error_msg_and_die("unexpected record type %d", tls->inbuf[0]);
1639                         xwrite(STDOUT_FILENO, tls->inbuf + RECHDR_LEN, nread);
1640                         /* We may already have a complete next record buffered,
1641                          * can process it without network reads (and possible blocking)
1642                          */
1643                         if (tls_has_buffered_record(tls))
1644                                 goto read_record;
1645                 }
1646         }
1647 }