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