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