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