wget/tls: session_id of zero length is ok (arxiv.org responds with such)
[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_ID 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
88 #define RECORD_TYPE_ALERT               21
89 #define RECORD_TYPE_HANDSHAKE           22
90 #define RECORD_TYPE_APPLICATION_DATA    23
91
92 #define HANDSHAKE_HELLO_REQUEST         0
93 #define HANDSHAKE_CLIENT_HELLO          1
94 #define HANDSHAKE_SERVER_HELLO          2
95 #define HANDSHAKE_HELLO_VERIFY_REQUEST  3
96 #define HANDSHAKE_NEW_SESSION_TICKET    4
97 #define HANDSHAKE_CERTIFICATE           11
98 #define HANDSHAKE_SERVER_KEY_EXCHANGE   12
99 #define HANDSHAKE_CERTIFICATE_REQUEST   13
100 #define HANDSHAKE_SERVER_HELLO_DONE     14
101 #define HANDSHAKE_CERTIFICATE_VERIFY    15
102 #define HANDSHAKE_CLIENT_KEY_EXCHANGE   16
103 #define HANDSHAKE_FINISHED              20
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 static void hmac_sha256_begin(hmac_precomputed_t *pre, uint8_t *key, unsigned key_size)
371 {
372         uint8_t key_xor_ipad[SHA_INSIZE];
373         uint8_t key_xor_opad[SHA_INSIZE];
374         uint8_t tempkey[SHA256_OUTSIZE];
375         unsigned i;
376
377         // "The authentication key can be of any length up to INSIZE, the
378         // block length of the hash function.  Applications that use keys longer
379         // than INSIZE bytes will first hash the key using H and then use the
380         // resultant OUTSIZE byte string as the actual key to HMAC."
381         if (key_size > SHA_INSIZE) {
382                 md5sha_ctx_t ctx;
383                 sha256_begin(&ctx);
384                 md5sha_hash(&ctx, key, key_size);
385                 key_size = sha_end(&ctx, tempkey);
386         }
387
388         for (i = 0; i < key_size; i++) {
389                 key_xor_ipad[i] = key[i] ^ 0x36;
390                 key_xor_opad[i] = key[i] ^ 0x5c;
391         }
392         for (; i < SHA_INSIZE; i++) {
393                 key_xor_ipad[i] = 0x36;
394                 key_xor_opad[i] = 0x5c;
395         }
396
397         sha256_begin(&pre->hashed_key_xor_ipad);
398         sha256_begin(&pre->hashed_key_xor_opad);
399         md5sha_hash(&pre->hashed_key_xor_ipad, key_xor_ipad, SHA_INSIZE);
400         md5sha_hash(&pre->hashed_key_xor_opad, key_xor_opad, SHA_INSIZE);
401 }
402 // TODO: ^^^ vvv merge?
403 static void hmac_sha1_begin(hmac_precomputed_t *pre, uint8_t *key, unsigned key_size)
404 {
405         uint8_t key_xor_ipad[SHA_INSIZE];
406         uint8_t key_xor_opad[SHA_INSIZE];
407         uint8_t tempkey[SHA1_OUTSIZE];
408         unsigned i;
409
410         // "The authentication key can be of any length up to INSIZE, the
411         // block length of the hash function.  Applications that use keys longer
412         // than INSIZE bytes will first hash the key using H and then use the
413         // resultant OUTSIZE byte string as the actual key to HMAC."
414         if (key_size > SHA_INSIZE) {
415                 md5sha_ctx_t ctx;
416                 sha1_begin(&ctx);
417                 md5sha_hash(&ctx, key, key_size);
418                 key_size = sha_end(&ctx, tempkey);
419         }
420
421         for (i = 0; i < key_size; i++) {
422                 key_xor_ipad[i] = key[i] ^ 0x36;
423                 key_xor_opad[i] = key[i] ^ 0x5c;
424         }
425         for (; i < SHA_INSIZE; i++) {
426                 key_xor_ipad[i] = 0x36;
427                 key_xor_opad[i] = 0x5c;
428         }
429
430         sha1_begin(&pre->hashed_key_xor_ipad);
431         sha1_begin(&pre->hashed_key_xor_opad);
432         md5sha_hash(&pre->hashed_key_xor_ipad, key_xor_ipad, SHA_INSIZE);
433         md5sha_hash(&pre->hashed_key_xor_opad, key_xor_opad, SHA_INSIZE);
434 }
435
436 static unsigned hmac(tls_state_t *tls, uint8_t *out, uint8_t *key, unsigned key_size, ...)
437 {
438         hmac_precomputed_t pre;
439         va_list va;
440         unsigned len;
441
442         va_start(va, key_size);
443
444         if (tls->MAC_size == SHA256_OUTSIZE)
445                 hmac_sha256_begin(&pre, key, key_size);
446         else
447                 hmac_sha1_begin(&pre, key, key_size);
448
449         len = hmac_sha_precomputed_v(&pre, out, va);
450
451         va_end(va);
452         return len;
453 }
454
455 static unsigned hmac_sha256(/*tls_state_t *tls,*/ uint8_t *out, uint8_t *key, unsigned key_size, ...)
456 {
457         hmac_precomputed_t pre;
458         va_list va;
459         unsigned len;
460
461         va_start(va, key_size);
462
463         hmac_sha256_begin(&pre, key, key_size);
464         len = hmac_sha_precomputed_v(&pre, out, va);
465
466         va_end(va);
467         return len;
468 }
469
470 // RFC 5246:
471 // 5.  HMAC and the Pseudorandom Function
472 //...
473 // In this section, we define one PRF, based on HMAC.  This PRF with the
474 // SHA-256 hash function is used for all cipher suites defined in this
475 // document and in TLS documents published prior to this document when
476 // TLS 1.2 is negotiated.
477 // ^^^^^^^^^^^^^ IMPORTANT!
478 //               PRF uses sha256 regardless of cipher (at least for all ciphers
479 //               defined by RFC5246). It's not sha1 for AES_128_CBC_SHA!
480 //...
481 //    P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
482 //                           HMAC_hash(secret, A(2) + seed) +
483 //                           HMAC_hash(secret, A(3) + seed) + ...
484 // where + indicates concatenation.
485 // A() is defined as:
486 //    A(0) = seed
487 //    A(1) = HMAC_hash(secret, A(0)) = HMAC_hash(secret, seed)
488 //    A(i) = HMAC_hash(secret, A(i-1))
489 // P_hash can be iterated as many times as necessary to produce the
490 // required quantity of data.  For example, if P_SHA256 is being used to
491 // create 80 bytes of data, it will have to be iterated three times
492 // (through A(3)), creating 96 bytes of output data; the last 16 bytes
493 // of the final iteration will then be discarded, leaving 80 bytes of
494 // output data.
495 //
496 // TLS's PRF is created by applying P_hash to the secret as:
497 //
498 //    PRF(secret, label, seed) = P_<hash>(secret, label + seed)
499 //
500 // The label is an ASCII string.
501 static void prf_hmac_sha256(/*tls_state_t *tls,*/
502                 uint8_t *outbuf, unsigned outbuf_size,
503                 uint8_t *secret, unsigned secret_size,
504                 const char *label,
505                 uint8_t *seed, unsigned seed_size)
506 {
507         uint8_t a[TLS_MAX_MAC_SIZE];
508         uint8_t *out_p = outbuf;
509         unsigned label_size = strlen(label);
510         unsigned MAC_size = SHA256_OUTSIZE;///tls->MAC_size;
511
512         /* In P_hash() calculation, "seed" is "label + seed": */
513 #define SEED   label, label_size, seed, seed_size
514 #define SECRET secret, secret_size
515 #define A      a, MAC_size
516
517         /* A(1) = HMAC_hash(secret, seed) */
518         hmac_sha256(/*tls,*/ a, SECRET, SEED, NULL);
519 //TODO: convert hmac to precomputed
520
521         for(;;) {
522                 /* HMAC_hash(secret, A(1) + seed) */
523                 if (outbuf_size <= MAC_size) {
524                         /* Last, possibly incomplete, block */
525                         /* (use a[] as temp buffer) */
526                         hmac_sha256(/*tls,*/ a, SECRET, A, SEED, NULL);
527                         memcpy(out_p, a, outbuf_size);
528                         return;
529                 }
530                 /* Not last block. Store directly to result buffer */
531                 hmac_sha256(/*tls,*/ out_p, SECRET, A, SEED, NULL);
532                 out_p += MAC_size;
533                 outbuf_size -= MAC_size;
534                 /* A(2) = HMAC_hash(secret, A(1)) */
535                 hmac_sha256(/*tls,*/ a, SECRET, A, NULL);
536         }
537 #undef A
538 #undef SECRET
539 #undef SEED
540 }
541
542 static void bad_record_die(tls_state_t *tls, const char *expected, int len)
543 {
544         bb_error_msg("got bad TLS record (len:%d) while expecting %s", len, expected);
545         if (len > 0) {
546                 uint8_t *p = tls->inbuf;
547                 while (len > 0) {
548                         fprintf(stderr, " %02x", *p++);
549                         len--;
550                 }
551                 fputc('\n', stderr);
552         }
553         xfunc_die();
554 }
555
556 static void tls_error_die(tls_state_t *tls, int line)
557 {
558         dump_tls_record(tls->inbuf, tls->ofs_to_buffered + tls->buffered_size);
559         bb_error_msg_and_die("tls error at line %d cipher:%04x", line, tls->cipher_id);
560 }
561 #define tls_error_die(tls) tls_error_die(tls, __LINE__)
562
563 #if 0 //UNUSED
564 static void tls_free_inbuf(tls_state_t *tls)
565 {
566         if (tls->buffered_size == 0) {
567                 free(tls->inbuf);
568                 tls->inbuf_size = 0;
569                 tls->inbuf = NULL;
570         }
571 }
572 #endif
573
574 static void tls_free_outbuf(tls_state_t *tls)
575 {
576         free(tls->outbuf);
577         tls->outbuf_size = 0;
578         tls->outbuf = NULL;
579 }
580
581 static void *tls_get_outbuf(tls_state_t *tls, int len)
582 {
583         if (len > TLS_MAX_OUTBUF)
584                 xfunc_die();
585         len += OUTBUF_PFX + OUTBUF_SFX;
586         if (tls->outbuf_size < len) {
587                 tls->outbuf_size = len;
588                 tls->outbuf = xrealloc(tls->outbuf, len);
589         }
590         return tls->outbuf + OUTBUF_PFX;
591 }
592
593 static void xwrite_encrypted(tls_state_t *tls, unsigned size, unsigned type)
594 {
595         uint8_t *buf = tls->outbuf + OUTBUF_PFX;
596         struct record_hdr *xhdr;
597         uint8_t padding_length;
598
599         xhdr = (void*)(buf - RECHDR_LEN);
600         if (tls->cipher_id != TLS_RSA_WITH_NULL_SHA256)
601                 xhdr = (void*)(buf - RECHDR_LEN - AES_BLOCKSIZE); /* place for IV */
602
603         xhdr->type = type;
604         xhdr->proto_maj = TLS_MAJ;
605         xhdr->proto_min = TLS_MIN;
606         /* fake unencrypted record len for MAC calculation */
607         xhdr->len16_hi = size >> 8;
608         xhdr->len16_lo = size & 0xff;
609
610         /* Calculate MAC signature */
611         hmac(tls, buf + size, /* result */
612                 tls->client_write_MAC_key, tls->MAC_size,
613                 &tls->write_seq64_be, sizeof(tls->write_seq64_be),
614                 xhdr, RECHDR_LEN,
615                 buf, size,
616                 NULL
617         );
618         tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(tls->write_seq64_be));
619
620         size += tls->MAC_size;
621
622         // RFC 5246
623         // 6.2.3.1.  Null or Standard Stream Cipher
624         //
625         // Stream ciphers (including BulkCipherAlgorithm.null; see Appendix A.6)
626         // convert TLSCompressed.fragment structures to and from stream
627         // TLSCiphertext.fragment structures.
628         //
629         //    stream-ciphered struct {
630         //        opaque content[TLSCompressed.length];
631         //        opaque MAC[SecurityParameters.mac_length];
632         //    } GenericStreamCipher;
633         //
634         // The MAC is generated as:
635         //    MAC(MAC_write_key, seq_num +
636         //                          TLSCompressed.type +
637         //                          TLSCompressed.version +
638         //                          TLSCompressed.length +
639         //                          TLSCompressed.fragment);
640         // where "+" denotes concatenation.
641         // seq_num
642         //    The sequence number for this record.
643         // MAC
644         //    The MAC algorithm specified by SecurityParameters.mac_algorithm.
645         //
646         // Note that the MAC is computed before encryption.  The stream cipher
647         // encrypts the entire block, including the MAC.
648         //...
649         // Appendix C.  Cipher Suite Definitions
650         //...
651         // MAC       Algorithm    mac_length  mac_key_length
652         // --------  -----------  ----------  --------------
653         // SHA       HMAC-SHA1       20            20
654         // SHA256    HMAC-SHA256     32            32
655         if (tls->cipher_id == TLS_RSA_WITH_NULL_SHA256) {
656                 /* No encryption, only signing */
657                 xhdr->len16_hi = size >> 8;
658                 xhdr->len16_lo = size & 0xff;
659                 dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
660                 xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
661                 dbg("wrote %u bytes (NULL crypt, SHA256 hash)\n", size);
662                 return;
663         }
664
665         // 6.2.3.2.  CBC Block Cipher
666         // For block ciphers (such as 3DES or AES), the encryption and MAC
667         // functions convert TLSCompressed.fragment structures to and from block
668         // TLSCiphertext.fragment structures.
669         //    struct {
670         //        opaque IV[SecurityParameters.record_iv_length];
671         //        block-ciphered struct {
672         //            opaque content[TLSCompressed.length];
673         //            opaque MAC[SecurityParameters.mac_length];
674         //            uint8 padding[GenericBlockCipher.padding_length];
675         //            uint8 padding_length;
676         //        };
677         //    } GenericBlockCipher;
678         //...
679         // IV
680         //    The Initialization Vector (IV) SHOULD be chosen at random, and
681         //    MUST be unpredictable.  Note that in versions of TLS prior to 1.1,
682         //    there was no IV field (...).  For block ciphers, the IV length is
683         //    of length SecurityParameters.record_iv_length, which is equal to the
684         //    SecurityParameters.block_size.
685         // padding
686         //    Padding that is added to force the length of the plaintext to be
687         //    an integral multiple of the block cipher's block length.
688         // padding_length
689         //    The padding length MUST be such that the total size of the
690         //    GenericBlockCipher structure is a multiple of the cipher's block
691         //    length.  Legal values range from zero to 255, inclusive.
692         //...
693         // Appendix C.  Cipher Suite Definitions
694         //...
695         //                         Key      IV   Block
696         // Cipher        Type    Material  Size  Size
697         // ------------  ------  --------  ----  -----
698         // AES_128_CBC   Block      16      16     16
699         // AES_256_CBC   Block      32      16     16
700
701         /* Fill IV and padding in outbuf */
702         tls_get_random(buf - AES_BLOCKSIZE, AES_BLOCKSIZE); /* IV */
703         dbg("before crypt: 5 hdr + %u data + %u hash bytes\n", size, tls->MAC_size);
704         // RFC is talking nonsense:
705         //    "Padding that is added to force the length of the plaintext to be
706         //    an integral multiple of the block cipher's block length."
707         // WRONG. _padding+padding_length_, not just _padding_,
708         // pads the data.
709         // IOW: padding_length is the last byte of padding[] array,
710         // contrary to what RFC depicts.
711         //
712         // What actually happens is that there is always padding.
713         // If you need one byte to reach BLOCKSIZE, this byte is 0x00.
714         // If you need two bytes, they are both 0x01.
715         // If you need three, they are 0x02,0x02,0x02. And so on.
716         // If you need no bytes to reach BLOCKSIZE, you have to pad a full
717         // BLOCKSIZE with bytes of value (BLOCKSIZE-1).
718         // It's ok to have more than minimum padding, but we do minimum.
719         padding_length = (~size) & (AES_BLOCKSIZE - 1);
720         do {
721                 buf[size++] = padding_length; /* padding */
722         } while ((size & (AES_BLOCKSIZE - 1)) != 0);
723
724         /* Encrypt content+MAC+padding in place */
725         {
726                 psCipherContext_t ctx;
727                 psAesInit(&ctx, buf - AES_BLOCKSIZE, /* IV */
728                         tls->client_write_key, tls->key_size /* selects 128/256 */
729                 );
730                 psAesEncrypt(&ctx,
731                         buf, /* plaintext */
732                         buf, /* ciphertext */
733                         size
734                 );
735         }
736
737         /* Write out */
738         dbg("writing 5 + %u IV + %u encrypted bytes, padding_length:0x%02x\n",
739                         AES_BLOCKSIZE, size, padding_length);
740         size += AES_BLOCKSIZE;     /* + IV */
741         xhdr->len16_hi = size >> 8;
742         xhdr->len16_lo = size & 0xff;
743         dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
744         xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
745         dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
746 }
747
748 static void xwrite_handshake_record(tls_state_t *tls, unsigned size)
749 {
750         //if (!tls->encrypt_on_write) {
751                 uint8_t *buf = tls->outbuf + OUTBUF_PFX;
752                 struct record_hdr *xhdr = (void*)(buf - RECHDR_LEN);
753
754                 xhdr->type = RECORD_TYPE_HANDSHAKE;
755                 xhdr->proto_maj = TLS_MAJ;
756                 xhdr->proto_min = TLS_MIN;
757                 xhdr->len16_hi = size >> 8;
758                 xhdr->len16_lo = size & 0xff;
759                 dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
760                 xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
761                 dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
762         //      return;
763         //}
764         //xwrite_encrypted(tls, size, RECORD_TYPE_HANDSHAKE);
765 }
766
767 static void xwrite_and_update_handshake_hash(tls_state_t *tls, unsigned size)
768 {
769         if (!tls->encrypt_on_write) {
770                 uint8_t *buf;
771
772                 xwrite_handshake_record(tls, size);
773                 /* Handshake hash does not include record headers */
774                 buf = tls->outbuf + OUTBUF_PFX;
775                 hash_handshake(tls, ">> hash:%s", buf, size);
776                 return;
777         }
778         xwrite_encrypted(tls, size, RECORD_TYPE_HANDSHAKE);
779 }
780
781 static int tls_has_buffered_record(tls_state_t *tls)
782 {
783         int buffered = tls->buffered_size;
784         struct record_hdr *xhdr;
785         int rec_size;
786
787         if (buffered < RECHDR_LEN)
788                 return 0;
789         xhdr = (void*)(tls->inbuf + tls->ofs_to_buffered);
790         rec_size = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
791         if (buffered < rec_size)
792                 return 0;
793         return rec_size;
794 }
795
796 static const char *alert_text(int code)
797 {
798         switch (code) {
799         case 20:  return "bad MAC";
800         case 50:  return "decode error";
801         case 51:  return "decrypt error";
802         case 40:  return "handshake failure";
803         case 112: return "unrecognized name";
804         }
805         return itoa(code);
806 }
807
808 static int tls_xread_record(tls_state_t *tls)
809 {
810         struct record_hdr *xhdr;
811         int sz;
812         int total;
813         int target;
814
815  again:
816         dbg("ofs_to_buffered:%u buffered_size:%u\n", tls->ofs_to_buffered, tls->buffered_size);
817         total = tls->buffered_size;
818         if (total != 0) {
819                 memmove(tls->inbuf, tls->inbuf + tls->ofs_to_buffered, total);
820                 //dbg("<< remaining at %d [%d] ", tls->ofs_to_buffered, total);
821                 //dump_raw_in("<< %s\n", tls->inbuf, total);
822         }
823         errno = 0;
824         target = MAX_INBUF;
825         for (;;) {
826                 int rem;
827
828                 if (total >= RECHDR_LEN && target == MAX_INBUF) {
829                         xhdr = (void*)tls->inbuf;
830                         target = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
831                         if (target > MAX_INBUF) {
832                                 /* malformed input (too long): yell and die */
833                                 tls->buffered_size = 0;
834                                 tls->ofs_to_buffered = total;
835                                 tls_error_die(tls);
836                         }
837                         /* can also check type/proto_maj/proto_min here */
838                         dbg("xhdr type:%d ver:%d.%d len:%d\n",
839                                 xhdr->type, xhdr->proto_maj, xhdr->proto_min,
840                                 0x100 * xhdr->len16_hi + xhdr->len16_lo
841                         );
842                 }
843                 /* if total >= target, we have a full packet (and possibly more)... */
844                 if (total - target >= 0)
845                         break;
846                 /* input buffer is grown only as needed */
847                 rem = tls->inbuf_size - total;
848                 if (rem == 0) {
849                         tls->inbuf_size += MAX_INBUF / 8;
850                         if (tls->inbuf_size > MAX_INBUF)
851                                 tls->inbuf_size = MAX_INBUF;
852                         dbg("inbuf_size:%d\n", tls->inbuf_size);
853                         rem = tls->inbuf_size - total;
854                         tls->inbuf = xrealloc(tls->inbuf, tls->inbuf_size);
855                 }
856                 sz = safe_read(tls->ifd, tls->inbuf + total, rem);
857                 if (sz <= 0) {
858                         if (sz == 0 && total == 0) {
859                                 /* "Abrupt" EOF, no TLS shutdown (seen from kernel.org) */
860                                 dbg("EOF (without TLS shutdown) from peer\n");
861                                 tls->buffered_size = 0;
862                                 goto end;
863                         }
864                         bb_perror_msg_and_die("short read, have only %d", total);
865                 }
866                 dump_raw_in("<< %s\n", tls->inbuf + total, sz);
867                 total += sz;
868         }
869         tls->buffered_size = total - target;
870         tls->ofs_to_buffered = target;
871         //dbg("<< stashing at %d [%d] ", tls->ofs_to_buffered, tls->buffered_size);
872         //dump_hex("<< %s\n", tls->inbuf + tls->ofs_to_buffered, tls->buffered_size);
873
874         sz = target - RECHDR_LEN;
875
876         /* Needs to be decrypted? */
877         if (tls->min_encrypted_len_on_read > tls->MAC_size) {
878                 psCipherContext_t ctx;
879                 uint8_t *p = tls->inbuf + RECHDR_LEN;
880                 int padding_len;
881
882                 if (sz & (AES_BLOCKSIZE-1)
883                  || sz < (int)tls->min_encrypted_len_on_read
884                 ) {
885                         bb_error_msg_and_die("bad encrypted len:%u < %u",
886                                 sz, tls->min_encrypted_len_on_read);
887                 }
888                 /* Decrypt content+MAC+padding, moving it over IV in the process */
889                 psAesInit(&ctx, p, /* IV */
890                         tls->server_write_key, tls->key_size /* selects 128/256 */
891                 );
892                 sz -= AES_BLOCKSIZE; /* we will overwrite IV now */
893                 psAesDecrypt(&ctx,
894                         p + AES_BLOCKSIZE, /* ciphertext */
895                         p,                 /* plaintext */
896                         sz
897                 );
898                 padding_len = p[sz - 1];
899                 dbg("encrypted size:%u type:0x%02x padding_length:0x%02x\n", sz, p[0], padding_len);
900                 padding_len++;
901                 sz -= tls->MAC_size + padding_len; /* drop MAC and padding */
902                 //if (sz < 0)
903                 //      bb_error_msg_and_die("bad padding size:%u", padding_len);
904         } else {
905                 /* if nonzero, then it's TLS_RSA_WITH_NULL_SHA256: drop MAC */
906                 /* else: no encryption yet on input, subtract zero = NOP */
907                 sz -= tls->min_encrypted_len_on_read;
908         }
909         if (sz < 0)
910                 bb_error_msg_and_die("encrypted data too short");
911
912         //dump_hex("<< %s\n", tls->inbuf, RECHDR_LEN + sz);
913
914         xhdr = (void*)tls->inbuf;
915         if (xhdr->type == RECORD_TYPE_ALERT && sz >= 2) {
916                 uint8_t *p = tls->inbuf + RECHDR_LEN;
917                 dbg("ALERT size:%d level:%d description:%d\n", sz, p[0], p[1]);
918                 if (p[0] == 2) { /* fatal */
919                         bb_error_msg_and_die("TLS %s from peer (alert code %d): %s",
920                                 "error",
921                                 p[1], alert_text(p[1])
922                         );
923                 }
924                 if (p[0] == 1) { /* warning */
925                         if (p[1] == 0) { /* "close_notify" warning: it's EOF */
926                                 dbg("EOF (TLS encoded) from peer\n");
927                                 sz = 0;
928                                 goto end;
929                         }
930 //This possibly needs to be cached and shown only if
931 //a fatal alert follows
932 //                      bb_error_msg("TLS %s from peer (alert code %d): %s",
933 //                              "warning",
934 //                              p[1], alert_text(p[1])
935 //                      );
936                         /* discard it, get next record */
937                         goto again;
938                 }
939                 /* p[0] not 1 or 2: not defined in protocol */
940                 sz = 0;
941                 goto end;
942         }
943
944         /* RFC 5246 is not saying it explicitly, but sha256 hash
945          * in our FINISHED record must include data of incoming packets too!
946          */
947         if (tls->inbuf[0] == RECORD_TYPE_HANDSHAKE
948          && tls->MAC_size != 0 /* do we know which hash to use? (server_hello() does not!) */
949         ) {
950                 hash_handshake(tls, "<< hash:%s", tls->inbuf + RECHDR_LEN, sz);
951         }
952  end:
953         dbg("got block len:%u\n", sz);
954         return sz;
955 }
956
957 /*
958  * DER parsing routines
959  */
960 static unsigned get_der_len(uint8_t **bodyp, uint8_t *der, uint8_t *end)
961 {
962         unsigned len, len1;
963
964         if (end - der < 2)
965                 xfunc_die();
966 //      if ((der[0] & 0x1f) == 0x1f) /* not single-byte item code? */
967 //              xfunc_die();
968
969         len = der[1]; /* maybe it's short len */
970         if (len >= 0x80) {
971                 /* no, it's long */
972
973                 if (len == 0x80 || end - der < (int)(len - 0x7e)) {
974                         /* 0x80 is "0 bytes of len", invalid DER: must use short len if can */
975                         /* need 3 or 4 bytes for 81, 82 */
976                         xfunc_die();
977                 }
978
979                 len1 = der[2]; /* if (len == 0x81) it's "ii 81 xx", fetch xx */
980                 if (len > 0x82) {
981                         /* >0x82 is "3+ bytes of len", should not happen realistically */
982                         xfunc_die();
983                 }
984                 if (len == 0x82) { /* it's "ii 82 xx yy" */
985                         len1 = 0x100*len1 + der[3];
986                         der += 1; /* skip [yy] */
987                 }
988                 der += 1; /* skip [xx] */
989                 len = len1;
990 //              if (len < 0x80)
991 //                      xfunc_die(); /* invalid DER: must use short len if can */
992         }
993         der += 2; /* skip [code]+[1byte] */
994
995         if (end - der < (int)len)
996                 xfunc_die();
997         *bodyp = der;
998
999         return len;
1000 }
1001
1002 static uint8_t *enter_der_item(uint8_t *der, uint8_t **endp)
1003 {
1004         uint8_t *new_der;
1005         unsigned len = get_der_len(&new_der, der, *endp);
1006         dbg_der("entered der @%p:0x%02x len:%u inner_byte @%p:0x%02x\n", der, der[0], len, new_der, new_der[0]);
1007         /* Move "end" position to cover only this item */
1008         *endp = new_der + len;
1009         return new_der;
1010 }
1011
1012 static uint8_t *skip_der_item(uint8_t *der, uint8_t *end)
1013 {
1014         uint8_t *new_der;
1015         unsigned len = get_der_len(&new_der, der, end);
1016         /* Skip body */
1017         new_der += len;
1018         dbg_der("skipped der 0x%02x, next byte 0x%02x\n", der[0], new_der[0]);
1019         return new_der;
1020 }
1021
1022 static void der_binary_to_pstm(pstm_int *pstm_n, uint8_t *der, uint8_t *end)
1023 {
1024         uint8_t *bin_ptr;
1025         unsigned len = get_der_len(&bin_ptr, der, end);
1026
1027         dbg_der("binary bytes:%u, first:0x%02x\n", len, bin_ptr[0]);
1028         pstm_init_for_read_unsigned_bin(/*pool:*/ NULL, pstm_n, len);
1029         pstm_read_unsigned_bin(pstm_n, bin_ptr, len);
1030         //return bin + len;
1031 }
1032
1033 static void find_key_in_der_cert(tls_state_t *tls, uint8_t *der, int len)
1034 {
1035 /* Certificate is a DER-encoded data structure. Each DER element has a length,
1036  * which makes it easy to skip over large compound elements of any complexity
1037  * without parsing them. Example: partial decode of kernel.org certificate:
1038  *  SEQ 0x05ac/1452 bytes (Certificate): 308205ac
1039  *    SEQ 0x0494/1172 bytes (tbsCertificate): 30820494
1040  *      [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0] 3 bytes: a003
1041  *        INTEGER (version): 0201 02
1042  *      INTEGER 0x11 bytes (serialNumber): 0211 00 9f85bf664b0cddafca508679501b2be4
1043  *      //^^^^^^note: matrixSSL also allows [ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2] = 0x82 type
1044  *      SEQ 0x0d bytes (signatureAlgo): 300d
1045  *        OID 9 bytes: 0609 2a864886f70d01010b (OID_SHA256_RSA_SIG 42.134.72.134.247.13.1.1.11)
1046  *        NULL: 0500
1047  *      SEQ 0x5f bytes (issuer): 305f
1048  *        SET 11 bytes: 310b
1049  *          SEQ 9 bytes: 3009
1050  *            OID 3 bytes: 0603 550406
1051  *            Printable string "FR": 1302 4652
1052  *        SET 14 bytes: 310e
1053  *          SEQ 12 bytes: 300c
1054  *            OID 3 bytes: 0603 550408
1055  *            Printable string "Paris": 1305 5061726973
1056  *        SET 14 bytes: 310e
1057  *          SEQ 12 bytes: 300c
1058  *            OID 3 bytes: 0603 550407
1059  *            Printable string "Paris": 1305 5061726973
1060  *        SET 14 bytes: 310e
1061  *          SEQ 12 bytes: 300c
1062  *            OID 3 bytes: 0603 55040a
1063  *            Printable string "Gandi": 1305 47616e6469
1064  *        SET 32 bytes: 3120
1065  *          SEQ 30 bytes: 301e
1066  *            OID 3 bytes: 0603 550403
1067  *            Printable string "Gandi Standard SSL CA 2": 1317 47616e6469205374616e646172642053534c2043412032
1068  *      SEQ 30 bytes (validity): 301e
1069  *        TIME "161011000000Z": 170d 3136313031313030303030305a
1070  *        TIME "191011235959Z": 170d 3139313031313233353935395a
1071  *      SEQ 0x5b/91 bytes (subject): 305b //I did not decode this
1072  *          3121301f060355040b1318446f6d61696e20436f
1073  *          6e74726f6c2056616c6964617465643121301f06
1074  *          0355040b1318506f73697469766553534c204d75
1075  *          6c74692d446f6d61696e31133011060355040313
1076  *          0a6b65726e656c2e6f7267
1077  *      SEQ 0x01a2/418 bytes (subjectPublicKeyInfo): 308201a2
1078  *        SEQ 13 bytes (algorithm): 300d
1079  *          OID 9 bytes: 0609 2a864886f70d010101 (OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1)
1080  *          NULL: 0500
1081  *        BITSTRING 0x018f/399 bytes (publicKey): 0382018f
1082  *          ????: 00
1083  *          //after the zero byte, it appears key itself uses DER encoding:
1084  *          SEQ 0x018a/394 bytes: 3082018a
1085  *            INTEGER 0x0181/385 bytes (modulus): 02820181
1086  *                  00b1ab2fc727a3bef76780c9349bf3
1087  *                  ...24 more blocks of 15 bytes each...
1088  *                  90e895291c6bc8693b65
1089  *            INTEGER 3 bytes (exponent): 0203 010001
1090  *      [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0x3] 0x01e5 bytes (X509v3 extensions): a38201e5
1091  *        SEQ 0x01e1 bytes: 308201e1
1092  *        ...
1093  * Certificate is a sequence of three elements:
1094  *      tbsCertificate (SEQ)
1095  *      signatureAlgorithm (AlgorithmIdentifier)
1096  *      signatureValue (BIT STRING)
1097  *
1098  * In turn, tbsCertificate is a sequence of:
1099  *      version
1100  *      serialNumber
1101  *      signatureAlgo (AlgorithmIdentifier)
1102  *      issuer (Name, has complex structure)
1103  *      validity (Validity, SEQ of two Times)
1104  *      subject (Name)
1105  *      subjectPublicKeyInfo (SEQ)
1106  *      ...
1107  *
1108  * subjectPublicKeyInfo is a sequence of:
1109  *      algorithm (AlgorithmIdentifier)
1110  *      publicKey (BIT STRING)
1111  *
1112  * We need Certificate.tbsCertificate.subjectPublicKeyInfo.publicKey
1113  */
1114         uint8_t *end = der + len;
1115
1116         /* enter "Certificate" item: [der, end) will be only Cert */
1117         der = enter_der_item(der, &end);
1118
1119         /* enter "tbsCertificate" item: [der, end) will be only tbsCert */
1120         der = enter_der_item(der, &end);
1121
1122         /* skip up to subjectPublicKeyInfo */
1123         der = skip_der_item(der, end); /* version */
1124         der = skip_der_item(der, end); /* serialNumber */
1125         der = skip_der_item(der, end); /* signatureAlgo */
1126         der = skip_der_item(der, end); /* issuer */
1127         der = skip_der_item(der, end); /* validity */
1128         der = skip_der_item(der, end); /* subject */
1129
1130         /* enter subjectPublicKeyInfo */
1131         der = enter_der_item(der, &end);
1132         { /* check subjectPublicKeyInfo.algorithm */
1133                 static const uint8_t expected[] = {
1134                         0x30,0x0d, // SEQ 13 bytes
1135                         0x06,0x09, 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01, // OID RSA_KEY_ALG 42.134.72.134.247.13.1.1.1
1136                         //0x05,0x00, // NULL
1137                 };
1138                 if (memcmp(der, expected, sizeof(expected)) != 0)
1139                         bb_error_msg_and_die("not RSA key");
1140         }
1141         /* skip subjectPublicKeyInfo.algorithm */
1142         der = skip_der_item(der, end);
1143         /* enter subjectPublicKeyInfo.publicKey */
1144 //      die_if_not_this_der_type(der, end, 0x03); /* must be BITSTRING */
1145         der = enter_der_item(der, &end);
1146
1147         /* parse RSA key: */
1148 //based on getAsnRsaPubKey(), pkcs1ParsePrivBin() is also of note
1149         dbg("key bytes:%u, first:0x%02x\n", (int)(end - der), der[0]);
1150         if (end - der < 14) xfunc_die();
1151         /* example format:
1152          * ignore bits: 00
1153          * SEQ 0x018a/394 bytes: 3082018a
1154          *   INTEGER 0x0181/385 bytes (modulus): 02820181 XX...XXX
1155          *   INTEGER 3 bytes (exponent): 0203 010001
1156          */
1157         if (*der != 0) /* "ignore bits", should be 0 */
1158                 xfunc_die();
1159         der++;
1160         der = enter_der_item(der, &end); /* enter SEQ */
1161         /* memset(tls->hsd->server_rsa_pub_key, 0, sizeof(tls->hsd->server_rsa_pub_key)); - already is */
1162         der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.N, der, end); /* modulus */
1163         der = skip_der_item(der, end);
1164         der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.e, der, end); /* exponent */
1165         tls->hsd->server_rsa_pub_key.size = pstm_unsigned_bin_size(&tls->hsd->server_rsa_pub_key.N);
1166         dbg("server_rsa_pub_key.size:%d\n", tls->hsd->server_rsa_pub_key.size);
1167 }
1168
1169 /*
1170  * TLS Handshake routines
1171  */
1172 static int tls_xread_handshake_block(tls_state_t *tls, int min_len)
1173 {
1174         struct record_hdr *xhdr;
1175         int len = tls_xread_record(tls);
1176
1177         xhdr = (void*)tls->inbuf;
1178         if (len < min_len
1179          || xhdr->type != RECORD_TYPE_HANDSHAKE
1180          || xhdr->proto_maj != TLS_MAJ
1181          || xhdr->proto_min != TLS_MIN
1182         ) {
1183                 bad_record_die(tls, "handshake record", len);
1184         }
1185         dbg("got HANDSHAKE\n");
1186         return len;
1187 }
1188
1189 static ALWAYS_INLINE void fill_handshake_record_hdr(void *buf, unsigned type, unsigned len)
1190 {
1191         struct handshake_hdr {
1192                 uint8_t type;
1193                 uint8_t len24_hi, len24_mid, len24_lo;
1194         } *h = buf;
1195
1196         len -= 4;
1197         h->type = type;
1198         h->len24_hi  = len >> 16;
1199         h->len24_mid = len >> 8;
1200         h->len24_lo  = len & 0xff;
1201 }
1202
1203 static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
1204 {
1205         struct client_hello {
1206                 uint8_t type;
1207                 uint8_t len24_hi, len24_mid, len24_lo;
1208                 uint8_t proto_maj, proto_min;
1209                 uint8_t rand32[32];
1210                 uint8_t session_id_len;
1211                 /* uint8_t session_id[]; */
1212                 uint8_t cipherid_len16_hi, cipherid_len16_lo;
1213                 uint8_t cipherid[2 * (2 + !!CIPHER_ID2)]; /* actually variable */
1214                 uint8_t comprtypes_len;
1215                 uint8_t comprtypes[1]; /* actually variable */
1216                 /* Extensions (SNI shown):
1217                  * hi,lo // len of all extensions
1218                  *   00,00 // extension_type: "Server Name"
1219                  *   00,0e // list len (there can be more than one SNI)
1220                  *     00,0c // len of 1st Server Name Indication
1221                  *       00    // name type: host_name
1222                  *       00,09   // name len
1223                  *       "localhost" // name
1224                  */
1225 // GNU Wget 1.18 to cdn.kernel.org sends these extensions:
1226 // 0055
1227 //   0005 0005 0100000000 - status_request
1228 //   0000 0013 0011 00 000e 63646e 2e 6b65726e656c 2e 6f7267 - server_name
1229 //   ff01 0001 00 - renegotiation_info
1230 //   0023 0000 - session_ticket
1231 //   000a 0008 0006001700180019 - supported_groups
1232 //   000b 0002 0100 - ec_point_formats
1233 //   000d 0016 00140401040305010503060106030301030302010203 - signature_algorithms
1234         };
1235         struct client_hello *record;
1236         int len;
1237         int sni_len = sni ? strnlen(sni, 127) : 0;
1238
1239         len = sizeof(*record);
1240         if (sni_len)
1241                 len += 11 + strlen(sni);
1242         record = tls_get_outbuf(tls, len);
1243         memset(record, 0, len);
1244
1245         fill_handshake_record_hdr(record, HANDSHAKE_CLIENT_HELLO, len);
1246         record->proto_maj = TLS_MAJ;    /* the "requested" version of the protocol, */
1247         record->proto_min = TLS_MIN;    /* can be higher than one in record headers */
1248         tls_get_random(record->rand32, sizeof(record->rand32));
1249         if (TLS_DEBUG_FIXED_SECRETS)
1250                 memset(record->rand32, 0x11, sizeof(record->rand32));
1251         /* record->session_id_len = 0; - already is */
1252
1253         /* record->cipherid_len16_hi = 0; */
1254         record->cipherid_len16_lo = sizeof(record->cipherid);
1255         /* RFC 5746 Renegotiation Indication Extension - some servers will refuse to work with us otherwise */
1256         /*record->cipherid[0] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV >> 8; - zero */
1257         record->cipherid[1] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV & 0xff;
1258         if ((CIPHER_ID1 >> 8) != 0) record->cipherid[2] = CIPHER_ID1 >> 8;
1259         /*************************/ record->cipherid[3] = CIPHER_ID1 & 0xff;
1260 #if CIPHER_ID2
1261         if ((CIPHER_ID2 >> 8) != 0) record->cipherid[4] = CIPHER_ID2 >> 8;
1262         /*************************/ record->cipherid[5] = CIPHER_ID2 & 0xff;
1263 #endif
1264
1265         record->comprtypes_len = 1;
1266         /* record->comprtypes[0] = 0; */
1267
1268         if (sni_len) {
1269                 uint8_t *p = (void*)(record + 1);
1270                 //p[0] = 0;         //
1271                 p[1] = sni_len + 9; //ext_len
1272                 //p[2] = 0;             //
1273                 //p[3] = 0;             //extension_type
1274                 //p[4] = 0;         //
1275                 p[5] = sni_len + 5; //list len
1276                 //p[6] = 0;             //
1277                 p[7] = sni_len + 3;     //len of 1st SNI
1278                 //p[8] = 0;         //name type
1279                 //p[9] = 0;             //
1280                 p[10] = sni_len;        //name len
1281                 memcpy(&p[11], sni, sni_len);
1282         }
1283
1284         dbg(">> CLIENT_HELLO\n");
1285         /* Can hash it only when we know which MAC hash to use */
1286         /*xwrite_and_update_handshake_hash(tls, len); - WRONG! */
1287         xwrite_handshake_record(tls, len);
1288
1289         tls->hsd = xzalloc(sizeof(*tls->hsd) + len);
1290         tls->hsd->saved_client_hello_size = len;
1291         memcpy(tls->hsd->saved_client_hello, record, len);
1292         memcpy(tls->hsd->client_and_server_rand32, record->rand32, sizeof(record->rand32));
1293 }
1294
1295 static void get_server_hello(tls_state_t *tls)
1296 {
1297         struct server_hello {
1298                 struct record_hdr xhdr;
1299                 uint8_t type;
1300                 uint8_t len24_hi, len24_mid, len24_lo;
1301                 uint8_t proto_maj, proto_min;
1302                 uint8_t rand32[32]; /* first 4 bytes are unix time in BE format */
1303                 uint8_t session_id_len;
1304                 uint8_t session_id[32];
1305                 uint8_t cipherid_hi, cipherid_lo;
1306                 uint8_t comprtype;
1307                 /* extensions may follow, but only those which client offered in its Hello */
1308         };
1309
1310         struct server_hello *hp;
1311         uint8_t *cipherid;
1312         unsigned cipher;
1313         int len, len24;
1314
1315         len = tls_xread_handshake_block(tls, 74 - 32);
1316
1317         hp = (void*)tls->inbuf;
1318         // 74 bytes:
1319         // 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|
1320         //SvHl len=70 maj.min unixtime^^^ 28randbytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^ slen sid32bytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cipSel comprSel
1321         if (hp->type != HANDSHAKE_SERVER_HELLO
1322          || hp->len24_hi  != 0
1323          || hp->len24_mid != 0
1324          /* hp->len24_lo checked later */
1325          || hp->proto_maj != TLS_MAJ
1326          || hp->proto_min != TLS_MIN
1327         ) {
1328                 bad_record_die(tls, "'server hello'", len);
1329         }
1330
1331         cipherid = &hp->cipherid_hi;
1332         len24 = hp->len24_lo;
1333         if (hp->session_id_len != 32) {
1334                 if (hp->session_id_len != 0)
1335                         bad_record_die(tls, "'server hello'", len);
1336
1337                 // session_id_len == 0: no session id
1338                 // "The server
1339                 // may return an empty session_id to indicate that the session will
1340                 // not be cached and therefore cannot be resumed."
1341                 cipherid -= 32;
1342                 len24 += 32; /* what len would be if session id would be present */
1343         }
1344
1345         if (len24 < 70
1346 //       || cipherid[0]  != (CIPHER_ID >> 8)
1347 //       || cipherid[1]  != (CIPHER_ID & 0xff)
1348 //       || cipherid[2]  != 0 /* comprtype */
1349         ) {
1350                 bad_record_die(tls, "'server hello'", len);
1351         }
1352         dbg("<< SERVER_HELLO\n");
1353
1354         memcpy(tls->hsd->client_and_server_rand32 + 32, hp->rand32, sizeof(hp->rand32));
1355
1356         tls->cipher_id = cipher = 0x100 * cipherid[0] + cipherid[1];
1357         dbg("server chose cipher %04x\n", cipher);
1358
1359         if (cipher == TLS_RSA_WITH_AES_128_CBC_SHA) {
1360                 tls->key_size = AES128_KEYSIZE;
1361                 tls->MAC_size = SHA1_OUTSIZE;
1362         }
1363         else { /* TLS_RSA_WITH_AES_256_CBC_SHA256 */
1364                 tls->key_size = AES256_KEYSIZE;
1365                 tls->MAC_size = SHA256_OUTSIZE;
1366         }
1367         /* Handshake hash eventually destined to FINISHED record
1368          * is sha256 regardless of cipher
1369          * (at least for all ciphers defined by RFC5246).
1370          * It's not sha1 for AES_128_CBC_SHA - only MAC is sha1, not this hash.
1371          */
1372         sha256_begin(&tls->hsd->handshake_hash_ctx);
1373         hash_handshake(tls, ">> client hello hash:%s",
1374                 tls->hsd->saved_client_hello, tls->hsd->saved_client_hello_size
1375         );
1376         hash_handshake(tls, "<< server hello hash:%s",
1377                 tls->inbuf + RECHDR_LEN, len
1378         );
1379 }
1380
1381 static void get_server_cert(tls_state_t *tls)
1382 {
1383         struct record_hdr *xhdr;
1384         uint8_t *certbuf;
1385         int len, len1;
1386
1387         len = tls_xread_handshake_block(tls, 10);
1388
1389         xhdr = (void*)tls->inbuf;
1390         certbuf = (void*)(xhdr + 1);
1391         if (certbuf[0] != HANDSHAKE_CERTIFICATE)
1392                 tls_error_die(tls);
1393         dbg("<< CERTIFICATE\n");
1394         // 4392 bytes:
1395         // 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...
1396         //Cert len=4388 ChainLen CertLen^ DER encoded X509 starts here. openssl x509 -in FILE -inform DER -noout -text
1397         len1 = get24be(certbuf + 1);
1398         if (len1 > len - 4) tls_error_die(tls);
1399         len = len1;
1400         len1 = get24be(certbuf + 4);
1401         if (len1 > len - 3) tls_error_die(tls);
1402         len = len1;
1403         len1 = get24be(certbuf + 7);
1404         if (len1 > len - 3) tls_error_die(tls);
1405         len = len1;
1406
1407         if (len)
1408                 find_key_in_der_cert(tls, certbuf + 10, len);
1409 }
1410
1411 static void send_empty_client_cert(tls_state_t *tls)
1412 {
1413         struct client_empty_cert {
1414                 uint8_t type;
1415                 uint8_t len24_hi, len24_mid, len24_lo;
1416                 uint8_t cert_chain_len24_hi, cert_chain_len24_mid, cert_chain_len24_lo;
1417         };
1418         struct client_empty_cert *record;
1419
1420         record = tls_get_outbuf(tls, sizeof(*record));
1421 //FIXME: can just memcpy a ready-made one.
1422         fill_handshake_record_hdr(record, HANDSHAKE_CERTIFICATE, sizeof(*record));
1423         record->cert_chain_len24_hi = 0;
1424         record->cert_chain_len24_mid = 0;
1425         record->cert_chain_len24_lo = 0;
1426
1427         dbg(">> CERTIFICATE\n");
1428         xwrite_and_update_handshake_hash(tls, sizeof(*record));
1429 }
1430
1431 static void send_client_key_exchange(tls_state_t *tls)
1432 {
1433         struct client_key_exchange {
1434                 uint8_t type;
1435                 uint8_t len24_hi, len24_mid, len24_lo;
1436                 /* keylen16 exists for RSA (in TLS, not in SSL), but not for some other key types */
1437                 uint8_t keylen16_hi, keylen16_lo;
1438                 uint8_t key[4 * 1024]; // size??
1439         };
1440 //FIXME: better size estimate
1441         struct client_key_exchange *record = tls_get_outbuf(tls, sizeof(*record));
1442         uint8_t rsa_premaster[RSA_PREMASTER_SIZE];
1443         int len;
1444
1445         tls_get_random(rsa_premaster, sizeof(rsa_premaster));
1446         if (TLS_DEBUG_FIXED_SECRETS)
1447                 memset(rsa_premaster, 0x44, sizeof(rsa_premaster));
1448         // RFC 5246
1449         // "Note: The version number in the PreMasterSecret is the version
1450         // offered by the client in the ClientHello.client_version, not the
1451         // version negotiated for the connection."
1452         rsa_premaster[0] = TLS_MAJ;
1453         rsa_premaster[1] = TLS_MIN;
1454         dump_hex("premaster:%s\n", rsa_premaster, sizeof(rsa_premaster));
1455         len = psRsaEncryptPub(/*pool:*/ NULL,
1456                 /* psRsaKey_t* */ &tls->hsd->server_rsa_pub_key,
1457                 rsa_premaster, /*inlen:*/ sizeof(rsa_premaster),
1458                 record->key, sizeof(record->key),
1459                 data_param_ignored
1460         );
1461         record->keylen16_hi = len >> 8;
1462         record->keylen16_lo = len & 0xff;
1463         len += 2;
1464         record->type = HANDSHAKE_CLIENT_KEY_EXCHANGE;
1465         record->len24_hi  = 0;
1466         record->len24_mid = len >> 8;
1467         record->len24_lo  = len & 0xff;
1468         len += 4;
1469
1470         dbg(">> CLIENT_KEY_EXCHANGE\n");
1471         xwrite_and_update_handshake_hash(tls, len);
1472
1473         // RFC 5246
1474         // For all key exchange methods, the same algorithm is used to convert
1475         // the pre_master_secret into the master_secret.  The pre_master_secret
1476         // should be deleted from memory once the master_secret has been
1477         // computed.
1478         //      master_secret = PRF(pre_master_secret, "master secret",
1479         //                          ClientHello.random + ServerHello.random)
1480         //                          [0..47];
1481         // The master secret is always exactly 48 bytes in length.  The length
1482         // of the premaster secret will vary depending on key exchange method.
1483         prf_hmac_sha256(/*tls,*/
1484                 tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
1485                 rsa_premaster, sizeof(rsa_premaster),
1486                 "master secret",
1487                 tls->hsd->client_and_server_rand32, sizeof(tls->hsd->client_and_server_rand32)
1488         );
1489         dump_hex("master secret:%s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
1490
1491         // RFC 5246
1492         // 6.3.  Key Calculation
1493         //
1494         // The Record Protocol requires an algorithm to generate keys required
1495         // by the current connection state (see Appendix A.6) from the security
1496         // parameters provided by the handshake protocol.
1497         //
1498         // The master secret is expanded into a sequence of secure bytes, which
1499         // is then split to a client write MAC key, a server write MAC key, a
1500         // client write encryption key, and a server write encryption key.  Each
1501         // of these is generated from the byte sequence in that order.  Unused
1502         // values are empty.  Some AEAD ciphers may additionally require a
1503         // client write IV and a server write IV (see Section 6.2.3.3).
1504         //
1505         // When keys and MAC keys are generated, the master secret is used as an
1506         // entropy source.
1507         //
1508         // To generate the key material, compute
1509         //
1510         //    key_block = PRF(SecurityParameters.master_secret,
1511         //                    "key expansion",
1512         //                    SecurityParameters.server_random +
1513         //                    SecurityParameters.client_random);
1514         //
1515         // until enough output has been generated.  Then, the key_block is
1516         // partitioned as follows:
1517         //
1518         //    client_write_MAC_key[SecurityParameters.mac_key_length]
1519         //    server_write_MAC_key[SecurityParameters.mac_key_length]
1520         //    client_write_key[SecurityParameters.enc_key_length]
1521         //    server_write_key[SecurityParameters.enc_key_length]
1522         //    client_write_IV[SecurityParameters.fixed_iv_length]
1523         //    server_write_IV[SecurityParameters.fixed_iv_length]
1524         {
1525                 uint8_t tmp64[64];
1526
1527                 /* make "server_rand32 + client_rand32" */
1528                 memcpy(&tmp64[0] , &tls->hsd->client_and_server_rand32[32], 32);
1529                 memcpy(&tmp64[32], &tls->hsd->client_and_server_rand32[0] , 32);
1530
1531                 prf_hmac_sha256(/*tls,*/
1532                         tls->client_write_MAC_key, 2 * (tls->MAC_size + tls->key_size),
1533                         // also fills:
1534                         // server_write_MAC_key[]
1535                         // client_write_key[]
1536                         // server_write_key[]
1537                         tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
1538                         "key expansion",
1539                         tmp64, 64
1540                 );
1541                 tls->client_write_key = tls->client_write_MAC_key + (2 * tls->MAC_size);
1542                 tls->server_write_key = tls->client_write_key + tls->key_size;
1543                 dump_hex("client_write_MAC_key:%s\n",
1544                         tls->client_write_MAC_key, tls->MAC_size
1545                 );
1546                 dump_hex("client_write_key:%s\n",
1547                         tls->client_write_key, tls->key_size
1548                 );
1549         }
1550 }
1551
1552 static const uint8_t rec_CHANGE_CIPHER_SPEC[] = {
1553         RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
1554         01
1555 };
1556
1557 static void send_change_cipher_spec(tls_state_t *tls)
1558 {
1559         dbg(">> CHANGE_CIPHER_SPEC\n");
1560         xwrite(tls->ofd, rec_CHANGE_CIPHER_SPEC, sizeof(rec_CHANGE_CIPHER_SPEC));
1561 }
1562
1563 // 7.4.9.  Finished
1564 // A Finished message is always sent immediately after a change
1565 // cipher spec message to verify that the key exchange and
1566 // authentication processes were successful.  It is essential that a
1567 // change cipher spec message be received between the other handshake
1568 // messages and the Finished message.
1569 //...
1570 // The Finished message is the first one protected with the just
1571 // negotiated algorithms, keys, and secrets.  Recipients of Finished
1572 // messages MUST verify that the contents are correct.  Once a side
1573 // has sent its Finished message and received and validated the
1574 // Finished message from its peer, it may begin to send and receive
1575 // application data over the connection.
1576 //...
1577 // struct {
1578 //     opaque verify_data[verify_data_length];
1579 // } Finished;
1580 //
1581 // verify_data
1582 //    PRF(master_secret, finished_label, Hash(handshake_messages))
1583 //       [0..verify_data_length-1];
1584 //
1585 // finished_label
1586 //    For Finished messages sent by the client, the string
1587 //    "client finished".  For Finished messages sent by the server,
1588 //    the string "server finished".
1589 //
1590 // Hash denotes a Hash of the handshake messages.  For the PRF
1591 // defined in Section 5, the Hash MUST be the Hash used as the basis
1592 // for the PRF.  Any cipher suite which defines a different PRF MUST
1593 // also define the Hash to use in the Finished computation.
1594 //
1595 // In previous versions of TLS, the verify_data was always 12 octets
1596 // long.  In the current version of TLS, it depends on the cipher
1597 // suite.  Any cipher suite which does not explicitly specify
1598 // verify_data_length has a verify_data_length equal to 12.  This
1599 // includes all existing cipher suites.
1600 static void send_client_finished(tls_state_t *tls)
1601 {
1602         struct finished {
1603                 uint8_t type;
1604                 uint8_t len24_hi, len24_mid, len24_lo;
1605                 uint8_t prf_result[12];
1606         };
1607         struct finished *record = tls_get_outbuf(tls, sizeof(*record));
1608         uint8_t handshake_hash[TLS_MAX_MAC_SIZE];
1609         unsigned len;
1610
1611         fill_handshake_record_hdr(record, HANDSHAKE_FINISHED, sizeof(*record));
1612
1613         len = get_handshake_hash(tls, handshake_hash);
1614         prf_hmac_sha256(/*tls,*/
1615                 record->prf_result, sizeof(record->prf_result),
1616                 tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
1617                 "client finished",
1618                 handshake_hash, len
1619         );
1620         dump_hex("from secret: %s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
1621         dump_hex("from labelSeed: %s", "client finished", sizeof("client finished")-1);
1622         dump_hex("%s\n", handshake_hash, sizeof(handshake_hash));
1623         dump_hex("=> digest: %s\n", record->prf_result, sizeof(record->prf_result));
1624
1625         dbg(">> FINISHED\n");
1626         xwrite_encrypted(tls, sizeof(*record), RECORD_TYPE_HANDSHAKE);
1627 }
1628
1629 void FAST_FUNC tls_handshake(tls_state_t *tls, const char *sni)
1630 {
1631         // Client              RFC 5246                Server
1632         // (*) - optional messages, not always sent
1633         //
1634         // ClientHello          ------->
1635         //                                        ServerHello
1636         //                                       Certificate*
1637         //                                 ServerKeyExchange*
1638         //                                CertificateRequest*
1639         //                      <-------      ServerHelloDone
1640         // Certificate*
1641         // ClientKeyExchange
1642         // CertificateVerify*
1643         // [ChangeCipherSpec]
1644         // Finished             ------->
1645         //                                 [ChangeCipherSpec]
1646         //                      <-------             Finished
1647         // Application Data     <------>     Application Data
1648         int len;
1649
1650         send_client_hello_and_alloc_hsd(tls, sni);
1651         get_server_hello(tls);
1652
1653         // RFC 5246
1654         // The server MUST send a Certificate message whenever the agreed-
1655         // upon key exchange method uses certificates for authentication
1656         // (this includes all key exchange methods defined in this document
1657         // except DH_anon).  This message will always immediately follow the
1658         // ServerHello message.
1659         //
1660         // IOW: in practice, Certificate *always* follows.
1661         // (for example, kernel.org does not even accept DH_anon cipher id)
1662         get_server_cert(tls);
1663
1664         len = tls_xread_handshake_block(tls, 4);
1665         if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_SERVER_KEY_EXCHANGE) {
1666                 // 459 bytes:
1667                 // 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...
1668                 //SvKey len=455^
1669                 // with TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 461 bytes:
1670                 // 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...
1671                 dbg("<< SERVER_KEY_EXCHANGE len:%u\n", len);
1672 //probably need to save it
1673                 len = tls_xread_handshake_block(tls, 4);
1674         }
1675
1676         if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_CERTIFICATE_REQUEST) {
1677                 dbg("<< CERTIFICATE_REQUEST\n");
1678                 // RFC 5246: "If no suitable certificate is available,
1679                 // the client MUST send a certificate message containing no
1680                 // certificates.  That is, the certificate_list structure has a
1681                 // length of zero. ...
1682                 // Client certificates are sent using the Certificate structure
1683                 // defined in Section 7.4.2."
1684                 // (i.e. the same format as server certs)
1685                 send_empty_client_cert(tls);
1686                 len = tls_xread_handshake_block(tls, 4);
1687         }
1688
1689         if (tls->inbuf[RECHDR_LEN] != HANDSHAKE_SERVER_HELLO_DONE) {
1690                 bad_record_die(tls, "'server hello done'", len);
1691         }
1692         // 0e 000000 (len:0)
1693         dbg("<< SERVER_HELLO_DONE\n");
1694
1695         send_client_key_exchange(tls);
1696
1697         send_change_cipher_spec(tls);
1698         /* from now on we should send encrypted */
1699         /* tls->write_seq64_be = 0; - already is */
1700         tls->encrypt_on_write = 1;
1701
1702         send_client_finished(tls);
1703
1704         /* Get CHANGE_CIPHER_SPEC */
1705         len = tls_xread_record(tls);
1706         if (len != 1 || memcmp(tls->inbuf, rec_CHANGE_CIPHER_SPEC, 6) != 0)
1707                 bad_record_die(tls, "switch to encrypted traffic", len);
1708         dbg("<< CHANGE_CIPHER_SPEC\n");
1709         if (tls->cipher_id == TLS_RSA_WITH_NULL_SHA256)
1710                 tls->min_encrypted_len_on_read = tls->MAC_size;
1711         else {
1712                 unsigned mac_blocks = (unsigned)(tls->MAC_size + AES_BLOCKSIZE-1) / AES_BLOCKSIZE;
1713                 /* all incoming packets now should be encrypted and have
1714                  * at least IV + (MAC padded to blocksize):
1715                  */
1716                 tls->min_encrypted_len_on_read = AES_BLOCKSIZE + (mac_blocks * AES_BLOCKSIZE);
1717                 dbg("min_encrypted_len_on_read: %u", tls->min_encrypted_len_on_read);
1718         }
1719
1720         /* Get (encrypted) FINISHED from the server */
1721         len = tls_xread_record(tls);
1722         if (len < 4 || tls->inbuf[RECHDR_LEN] != HANDSHAKE_FINISHED)
1723                 tls_error_die(tls);
1724         dbg("<< FINISHED\n");
1725         /* application data can be sent/received */
1726
1727         /* free handshake data */
1728 //      if (PARANOIA)
1729 //              memset(tls->hsd, 0, tls->hsd->hsd_size);
1730         free(tls->hsd);
1731         tls->hsd = NULL;
1732 }
1733
1734 static void tls_xwrite(tls_state_t *tls, int len)
1735 {
1736         dbg(">> DATA\n");
1737         xwrite_encrypted(tls, len, RECORD_TYPE_APPLICATION_DATA);
1738 }
1739
1740 // To run a test server using openssl:
1741 // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
1742 // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1
1743 //
1744 // Unencryped SHA256 example:
1745 // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
1746 // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL
1747 // openssl s_client -connect 127.0.0.1:4433 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL-SHA256
1748
1749 void FAST_FUNC tls_run_copy_loop(tls_state_t *tls)
1750 {
1751         fd_set readfds;
1752         int inbuf_size;
1753         const int INBUF_STEP = 4 * 1024;
1754
1755 //TODO: convert to poll
1756         /* Select loop copying stdin to ofd, and ifd to stdout */
1757         FD_ZERO(&readfds);
1758         FD_SET(tls->ifd, &readfds);
1759         FD_SET(STDIN_FILENO, &readfds);
1760
1761         inbuf_size = INBUF_STEP;
1762         for (;;) {
1763                 fd_set testfds;
1764                 int nread;
1765
1766                 testfds = readfds;
1767                 if (select(tls->ifd + 1, &testfds, NULL, NULL, NULL) < 0)
1768                         bb_perror_msg_and_die("select");
1769
1770                 if (FD_ISSET(STDIN_FILENO, &testfds)) {
1771                         void *buf;
1772
1773                         dbg("STDIN HAS DATA\n");
1774                         buf = tls_get_outbuf(tls, inbuf_size);
1775                         nread = safe_read(STDIN_FILENO, buf, inbuf_size);
1776                         if (nread < 1) {
1777                                 /* We'd want to do this: */
1778                                 /* Close outgoing half-connection so they get EOF,
1779                                  * but leave incoming alone so we can see response
1780                                  */
1781                                 //shutdown(tls->ofd, SHUT_WR);
1782                                 /* But TLS has no way to encode this,
1783                                  * doubt it's ok to do it "raw"
1784                                  */
1785                                 FD_CLR(STDIN_FILENO, &readfds);
1786                                 tls_free_outbuf(tls); /* mem usage optimization */
1787                         } else {
1788                                 if (nread == inbuf_size) {
1789                                         /* TLS has per record overhead, if input comes fast,
1790                                          * read, encrypt and send bigger chunks
1791                                          */
1792                                         inbuf_size += INBUF_STEP;
1793                                         if (inbuf_size > TLS_MAX_OUTBUF)
1794                                                 inbuf_size = TLS_MAX_OUTBUF;
1795                                 }
1796                                 tls_xwrite(tls, nread);
1797                         }
1798                 }
1799                 if (FD_ISSET(tls->ifd, &testfds)) {
1800                         dbg("NETWORK HAS DATA\n");
1801  read_record:
1802                         nread = tls_xread_record(tls);
1803                         if (nread < 1) {
1804                                 /* TLS protocol has no real concept of one-sided shutdowns:
1805                                  * if we get "TLS EOF" from the peer, writes will fail too
1806                                  */
1807                                 //FD_CLR(tls->ifd, &readfds);
1808                                 //close(STDOUT_FILENO);
1809                                 //tls_free_inbuf(tls); /* mem usage optimization */
1810                                 //continue;
1811                                 break;
1812                         }
1813                         if (tls->inbuf[0] != RECORD_TYPE_APPLICATION_DATA)
1814                                 bb_error_msg_and_die("unexpected record type %d", tls->inbuf[0]);
1815                         xwrite(STDOUT_FILENO, tls->inbuf + RECHDR_LEN, nread);
1816                         /* We may already have a complete next record buffered,
1817                          * can process it without network reads (and possible blocking)
1818                          */
1819                         if (tls_has_buffered_record(tls))
1820                                 goto read_record;
1821                 }
1822         }
1823 }