tls: add ECDHE_PSK and remove ARIA cipher ids
[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_aes.o
16 //kbuild:lib-$(CONFIG_TLS) += tls_aesgcm.o
17 //kbuild:lib-$(CONFIG_TLS) += tls_rsa.o
18 //kbuild:lib-$(CONFIG_TLS) += tls_fe.o
19
20 #include "tls.h"
21
22 // works against "openssl s_server -cipher NULL"
23 // and against wolfssl-3.9.10-stable/examples/server/server.c:
24 #define ALLOW_RSA_NULL_SHA256  0  // for testing (does everything except encrypting)
25
26 //Tested against kernel.org:
27 //#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA // ok, recvs SERVER_KEY_EXCHANGE *** matrixssl uses this on my box
28 //#define CIPHER_ID TLS_RSA_WITH_AES_256_CBC_SHA256 // ok, no SERVER_KEY_EXCHANGE
29 //#define CIPHER_ID TLS_DH_anon_WITH_AES_256_CBC_SHA // SSL_ALERT_HANDSHAKE_FAILURE
30 //^^^^^^^^^^^^^^^^^^^^^^^ (tested b/c this one doesn't req server certs... no luck, server refuses it)
31 //#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 // SSL_ALERT_HANDSHAKE_FAILURE
32 //#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
33 //#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 // ok, recvs SERVER_KEY_EXCHANGE
34 //#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
35 //#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
36 //#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
37 //#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
38 //#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
39 //#define CIPHER_ID TLS_RSA_WITH_AES_256_GCM_SHA384 // ok, no SERVER_KEY_EXCHANGE
40 //#define CIPHER_ID TLS_RSA_WITH_AES_128_GCM_SHA256 // ok, no SERVER_KEY_EXCHANGE
41
42 // works against wolfssl-3.9.10-stable/examples/server/server.c
43 // works for kernel.org
44 // does not work for cdn.kernel.org (e.g. downloading an actual tarball, not a web page)
45 //  getting alert 40 "handshake failure" at once
46 //  with GNU Wget 1.18, they agree on TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xC02F) cipher
47 //  fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -cipher AES256-SHA256
48 //  fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -cipher AES256-GCM-SHA384
49 //  fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -cipher AES128-SHA256
50 //  ok:   openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -cipher AES128-GCM-SHA256
51 //  ok:   openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -cipher AES128-SHA
52 //        (TLS_RSA_WITH_AES_128_CBC_SHA - in TLS 1.2 it's mandated to be always supported)
53 //#define CIPHER_ID1  TLS_RSA_WITH_AES_256_CBC_SHA256 //0x003D
54 // Works with "wget https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.9.5.tar.xz"
55 //#define CIPHER_ID2  TLS_RSA_WITH_AES_128_CBC_SHA    //0x002F
56
57 // bug #11456:
58 // ftp.openbsd.org only supports ECDHE-RSA-AESnnn-GCM-SHAnnn or ECDHE-RSA-CHACHA20-POLY1305
59 //#define CIPHER_ID3  TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 //0xC02F
60 // host is.gd accepts only ECDHE-ECDSA-foo (the simplest which works: ECDHE-ECDSA-AES128-SHA 0xC009)
61 //#define CIPHER_ID4  TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA  //0xC009
62
63
64 #define TLS_DEBUG      0
65 #define TLS_DEBUG_HASH 0
66 #define TLS_DEBUG_DER  0
67 #define TLS_DEBUG_FIXED_SECRETS 0
68 #if 0
69 # define dump_raw_out(...) dump_hex(__VA_ARGS__)
70 #else
71 # define dump_raw_out(...) ((void)0)
72 #endif
73 #if 0
74 # define dump_raw_in(...) dump_hex(__VA_ARGS__)
75 #else
76 # define dump_raw_in(...) ((void)0)
77 #endif
78
79 #if TLS_DEBUG
80 # define dbg(...) fprintf(stderr, __VA_ARGS__)
81 #else
82 # define dbg(...) ((void)0)
83 #endif
84
85 #if TLS_DEBUG_DER
86 # define dbg_der(...) fprintf(stderr, __VA_ARGS__)
87 #else
88 # define dbg_der(...) ((void)0)
89 #endif
90
91
92 //TLS 1.2
93 #define TLS_MAJ 3
94 #define TLS_MIN 3
95
96 #define RECORD_TYPE_CHANGE_CIPHER_SPEC  20 /* 0x14 */
97 #define RECORD_TYPE_ALERT               21 /* 0x15 */
98 #define RECORD_TYPE_HANDSHAKE           22 /* 0x16 */
99 #define RECORD_TYPE_APPLICATION_DATA    23 /* 0x17 */
100
101 #define HANDSHAKE_HELLO_REQUEST         0  /* 0x00 */
102 #define HANDSHAKE_CLIENT_HELLO          1  /* 0x01 */
103 #define HANDSHAKE_SERVER_HELLO          2  /* 0x02 */
104 #define HANDSHAKE_HELLO_VERIFY_REQUEST  3  /* 0x03 */
105 #define HANDSHAKE_NEW_SESSION_TICKET    4  /* 0x04 */
106 #define HANDSHAKE_CERTIFICATE           11 /* 0x0b */
107 #define HANDSHAKE_SERVER_KEY_EXCHANGE   12 /* 0x0c */
108 #define HANDSHAKE_CERTIFICATE_REQUEST   13 /* 0x0d */
109 #define HANDSHAKE_SERVER_HELLO_DONE     14 /* 0x0e */
110 #define HANDSHAKE_CERTIFICATE_VERIFY    15 /* 0x0f */
111 #define HANDSHAKE_CLIENT_KEY_EXCHANGE   16 /* 0x10 */
112 #define HANDSHAKE_FINISHED              20 /* 0x14 */
113
114 #define TLS_EMPTY_RENEGOTIATION_INFO_SCSV       0x00FF /* not a real cipher id... */
115
116 #define SSL_NULL_WITH_NULL_NULL                 0x0000
117 #define SSL_RSA_WITH_NULL_MD5                   0x0001
118 #define SSL_RSA_WITH_NULL_SHA                   0x0002
119 #define SSL_RSA_WITH_RC4_128_MD5                0x0004
120 #define SSL_RSA_WITH_RC4_128_SHA                0x0005
121 #define TLS_RSA_WITH_IDEA_CBC_SHA               0x0007  /* 7 */
122 #define SSL_RSA_WITH_3DES_EDE_CBC_SHA           0x000A  /* 10 */
123
124 #define SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA       0x0016  /* 22 */
125 #define SSL_DH_anon_WITH_RC4_128_MD5            0x0018  /* 24 */
126 #define SSL_DH_anon_WITH_3DES_EDE_CBC_SHA       0x001B  /* 27 */
127 #define TLS_RSA_WITH_AES_128_CBC_SHA            0x002F  /*SSLv3   Kx=RSA   Au=RSA   Enc=AES(128) Mac=SHA1 */
128 #define TLS_DHE_RSA_WITH_AES_128_CBC_SHA        0x0033  /* 51 */
129 #define TLS_DH_anon_WITH_AES_128_CBC_SHA        0x0034  /* 52 */
130 #define TLS_RSA_WITH_AES_256_CBC_SHA            0x0035  /* 53 */
131 #define TLS_DHE_RSA_WITH_AES_256_CBC_SHA        0x0039  /* 57 */
132 #define TLS_DH_anon_WITH_AES_256_CBC_SHA        0x003A  /* 58 */
133 #define TLS_RSA_WITH_NULL_SHA256                0x003B  /* 59 */
134 #define TLS_RSA_WITH_AES_128_CBC_SHA256         0x003C  /* 60 */
135 #define TLS_RSA_WITH_AES_256_CBC_SHA256         0x003D  /* 61 */
136 #define TLS_DHE_RSA_WITH_AES_128_CBC_SHA256     0x0067  /* 103 */
137 #define TLS_DHE_RSA_WITH_AES_256_CBC_SHA256     0x006B  /* 107 */
138 #define TLS_PSK_WITH_AES_128_CBC_SHA            0x008C  /* 140 */
139 #define TLS_PSK_WITH_AES_256_CBC_SHA            0x008D  /* 141 */
140 #define TLS_DHE_PSK_WITH_AES_128_CBC_SHA        0x0090  /* 144 */
141 #define TLS_DHE_PSK_WITH_AES_256_CBC_SHA        0x0091  /* 145 */
142 #define TLS_RSA_WITH_SEED_CBC_SHA               0x0096  /* 150 */
143 #define TLS_RSA_WITH_AES_128_GCM_SHA256         0x009C  /*TLSv1.2 Kx=RSA   Au=RSA   Enc=AESGCM(128) Mac=AEAD */
144 #define TLS_RSA_WITH_AES_256_GCM_SHA384         0x009D  /*TLSv1.2 Kx=RSA   Au=RSA   Enc=AESGCM(256) Mac=AEAD */
145 #define TLS_DHE_RSA_WITH_AES_128_GCM_SHA256     0x009E  /*TLSv1.2 Kx=DH    Au=RSA   Enc=AESGCM(128) Mac=AEAD */
146 #define TLS_DHE_RSA_WITH_AES_256_GCM_SHA384     0x009F  /*TLSv1.2 Kx=DH    Au=RSA   Enc=AESGCM(256) Mac=AEAD */
147 #define TLS_DH_anon_WITH_AES_128_GCM_SHA256     0x00A6  /* RFC 5288 */
148 #define TLS_DH_anon_WITH_AES_256_GCM_SHA384     0x00A7  /* RFC 5288 */
149 #define TLS_PSK_WITH_AES_128_CBC_SHA256         0x00AE  /* 174 */
150 #define TLS_PSK_WITH_AES_256_CBC_SHA384         0x00AF  /* 175 */
151 #define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA     0xC004  /* 49156 */
152 #define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA     0xC005  /* 49157 */
153 #define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA    0xC009  /*TLSv1   Kx=ECDH  Au=ECDSA Enc=AES(128) Mac=SHA1 */
154 #define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA    0xC00A  /*TLSv1   Kx=ECDH  Au=ECDSA Enc=AES(256) Mac=SHA1 */
155 #define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA       0xC00E  /* 49166 */
156 #define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA       0xC00F  /* 49167 */
157 #define TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA     0xC012  /* 49170 */
158 #define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA      0xC013  /*TLSv1   Kx=ECDH  Au=RSA   Enc=AES(128) Mac=SHA1 */
159 #define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA      0xC014  /*TLSv1   Kx=ECDH  Au=RSA   Enc=AES(256) Mac=SHA1 */
160 #define TLS_ECDH_anon_WITH_AES_128_CBC_SHA      0xC018  /* RFC 4492 */
161 #define TLS_ECDH_anon_WITH_AES_256_CBC_SHA      0xC019  /* RFC 4492 */
162 #define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023  /*TLSv1.2 Kx=ECDH  Au=ECDSA Enc=AES(128) Mac=SHA256 */
163 #define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 0xC024  /*TLSv1.2 Kx=ECDH  Au=ECDSA Enc=AES(256) Mac=SHA384 */
164 #define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256  0xC025  /* 49189 */
165 #define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384  0xC026  /* 49190 */
166 #define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256   0xC027  /*TLSv1.2 Kx=ECDH  Au=RSA   Enc=AES(128) Mac=SHA256 */
167 #define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384   0xC028  /*TLSv1.2 Kx=ECDH  Au=RSA   Enc=AES(256) Mac=SHA384 */
168 #define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256    0xC029  /* 49193 */
169 #define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384    0xC02A  /* 49194 */
170 /* RFC 5288 "AES Galois Counter Mode (GCM) Cipher Suites for TLS" */
171 #define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B  /*TLSv1.2 Kx=ECDH  Au=ECDSA Enc=AESGCM(128) Mac=AEAD */
172 #define TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0xC02C  /*TLSv1.2 Kx=ECDH  Au=ECDSA Enc=AESGCM(256) Mac=AEAD */
173 #define TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256  0xC02D  /* 49197 */
174 #define TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384  0xC02E  /* 49198 */
175 #define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256   0xC02F  /*TLSv1.2 Kx=ECDH  Au=RSA   Enc=AESGCM(128) Mac=AEAD */
176 #define TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384   0xC030  /*TLSv1.2 Kx=ECDH  Au=RSA   Enc=AESGCM(256) Mac=AEAD */
177 #define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256    0xC031  /* 49201 */
178 #define TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384    0xC032  /* 49202 */
179 #define TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA      0xC035
180 #define TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA      0xC036
181 #define TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256   0xC037
182 #define TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384   0xC038
183
184 /* From http://wiki.mozilla.org/Security/Server_Side_TLS */
185 /* and 'openssl ciphers -V -stdname' */
186 #define TLS_RSA_WITH_AES_128_CCM                      0xC09C /*TLSv1.2 Kx=RSA   Au=RSA   Enc=AESCCM(128) Mac=AEAD */
187 #define TLS_RSA_WITH_AES_256_CCM                      0xC09D /*TLSv1.2 Kx=RSA   Au=RSA   Enc=AESCCM(256) Mac=AEAD */
188 #define TLS_DHE_RSA_WITH_AES_128_CCM                  0xC09E /*TLSv1.2 Kx=DH    Au=RSA   Enc=AESCCM(128) Mac=AEAD */
189 #define TLS_DHE_RSA_WITH_AES_256_CCM                  0xC09F /*TLSv1.2 Kx=DH    Au=RSA   Enc=AESCCM(256) Mac=AEAD */
190 #define TLS_RSA_WITH_AES_128_CCM_8                    0xC0A0 /*TLSv1.2 Kx=RSA   Au=RSA   Enc=AESCCM8(128) Mac=AEAD */
191 #define TLS_RSA_WITH_AES_256_CCM_8                    0xC0A1 /*TLSv1.2 Kx=RSA   Au=RSA   Enc=AESCCM8(256) Mac=AEAD */
192 #define TLS_DHE_RSA_WITH_AES_128_CCM_8                0xC0A2 /*TLSv1.2 Kx=DH    Au=RSA   Enc=AESCCM8(128) Mac=AEAD */
193 #define TLS_DHE_RSA_WITH_AES_256_CCM_8                0xC0A3 /*TLSv1.2 Kx=DH    Au=RSA   Enc=AESCCM8(256) Mac=AEAD */
194 #define TLS_ECDHE_ECDSA_WITH_AES_128_CCM              0xC0AC /*TLSv1.2 Kx=ECDH  Au=ECDSA Enc=AESCCM(128) Mac=AEAD */
195 #define TLS_ECDHE_ECDSA_WITH_AES_256_CCM              0xC0AD /*TLSv1.2 Kx=ECDH  Au=ECDSA Enc=AESCCM(256) Mac=AEAD */
196 #define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8            0xC0AE /*TLSv1.2 Kx=ECDH  Au=ECDSA Enc=AESCCM8(128) Mac=AEAD */
197 #define TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8            0xC0AF /*TLSv1.2 Kx=ECDH  Au=ECDSA Enc=AESCCM8(256) Mac=AEAD */
198 #define TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256   0xCCA8 /*TLSv1.2 Kx=ECDH  Au=RSA   Enc=CHACHA20/POLY1305(256) Mac=AEAD */
199 #define TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA9 /*TLSv1.2 Kx=ECDH  Au=ECDSA Enc=CHACHA20/POLY1305(256) Mac=AEAD */
200 #define TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256     0xCCAA /*TLSv1.2 Kx=DH    Au=RSA   Enc=CHACHA20/POLY1305(256) Mac=AEAD */
201
202 #define TLS_AES_128_GCM_SHA256                        0x1301 /*TLSv1.3 Kx=any   Au=any   Enc=AESGCM(128) Mac=AEAD */
203 #define TLS_AES_256_GCM_SHA384                        0x1302 /*TLSv1.3 Kx=any   Au=any   Enc=AESGCM(256) Mac=AEAD */
204 #define TLS_CHACHA20_POLY1305_SHA256                  0x1303 /*TLSv1.3 Kx=any   Au=any   Enc=CHACHA20/POLY1305(256) Mac=AEAD */
205 #define TLS_AES_128_CCM_SHA256                        0x1304 /*TLSv1.3 Kx=any   Au=any   Enc=AESCCM(128) Mac=AEAD */
206
207 /* Might go to libbb.h */
208 #define TLS_MAX_CRYPTBLOCK_SIZE 16
209 #define TLS_MAX_OUTBUF          (1 << 14)
210
211 enum {
212         SHA_INSIZE     = 64,
213         SHA1_OUTSIZE   = 20,
214         SHA256_OUTSIZE = 32,
215
216         AES128_KEYSIZE = 16,
217         AES256_KEYSIZE = 32,
218
219         RSA_PREMASTER_SIZE = 48,
220
221         RECHDR_LEN = 5,
222
223         /* 8 = 3+5. 3 extra bytes result in record data being 32-bit aligned */
224         OUTBUF_PFX = 8 + AES_BLOCK_SIZE, /* header + IV */
225         OUTBUF_SFX = TLS_MAX_MAC_SIZE + TLS_MAX_CRYPTBLOCK_SIZE, /* MAC + padding */
226
227         // RFC 5246:
228         // | 6.2.1. Fragmentation
229         // |  The record layer fragments information blocks into TLSPlaintext
230         // |  records carrying data in chunks of 2^14 bytes or less.  Client
231         // |  message boundaries are not preserved in the record layer (i.e.,
232         // |  multiple client messages of the same ContentType MAY be coalesced
233         // |  into a single TLSPlaintext record, or a single message MAY be
234         // |  fragmented across several records)
235         // |...
236         // |  length
237         // |    The length (in bytes) of the following TLSPlaintext.fragment.
238         // |    The length MUST NOT exceed 2^14.
239         // |...
240         // | 6.2.2. Record Compression and Decompression
241         // |...
242         // |  Compression must be lossless and may not increase the content length
243         // |  by more than 1024 bytes.  If the decompression function encounters a
244         // |  TLSCompressed.fragment that would decompress to a length in excess of
245         // |  2^14 bytes, it MUST report a fatal decompression failure error.
246         // |...
247         // |  length
248         // |    The length (in bytes) of the following TLSCompressed.fragment.
249         // |    The length MUST NOT exceed 2^14 + 1024.
250         // |...
251         // | 6.2.3.  Record Payload Protection
252         // |  The encryption and MAC functions translate a TLSCompressed
253         // |  structure into a TLSCiphertext.  The decryption functions reverse
254         // |  the process.  The MAC of the record also includes a sequence
255         // |  number so that missing, extra, or repeated messages are
256         // |  detectable.
257         // |...
258         // |  length
259         // |    The length (in bytes) of the following TLSCiphertext.fragment.
260         // |    The length MUST NOT exceed 2^14 + 2048.
261         MAX_INBUF = RECHDR_LEN + (1 << 14) + 2048,
262
263         /* Bits for tls->flags */
264         NEED_EC_KEY            = 1 << 0,
265         GOT_CERT_RSA_KEY_ALG   = 1 << 1,
266         GOT_CERT_ECDSA_KEY_ALG = 1 << 2, // so far unused
267         GOT_EC_KEY             = 1 << 3,
268         ENCRYPTION_AESGCM      = 1 << 4, // else AES-SHA (or NULL-SHA if ALLOW_RSA_NULL_SHA256=1)
269         ENCRYPT_ON_WRITE       = 1 << 5,
270 };
271
272 struct record_hdr {
273         uint8_t type;
274         uint8_t proto_maj, proto_min;
275         uint8_t len16_hi, len16_lo;
276 };
277
278 struct tls_handshake_data {
279         /* In bbox, md5/sha1/sha256 ctx's are the same structure */
280         md5sha_ctx_t handshake_hash_ctx;
281
282         uint8_t client_and_server_rand32[2 * 32];
283         uint8_t master_secret[48];
284
285 //TODO: store just the DER key here, parse/use/delete it when sending client key
286 //this way it will stay key type agnostic here.
287         psRsaKey_t server_rsa_pub_key;
288         uint8_t ecc_pub_key32[32];
289
290 /* HANDSHAKE HASH: */
291         //unsigned saved_client_hello_size;
292         //uint8_t saved_client_hello[1];
293 };
294
295
296 static unsigned get24be(const uint8_t *p)
297 {
298         return 0x100*(0x100*p[0] + p[1]) + p[2];
299 }
300
301 #if TLS_DEBUG
302 /* Nondestructively see the current hash value */
303 # if TLS_DEBUG_HASH
304 static unsigned sha_peek(md5sha_ctx_t *ctx, void *buffer)
305 {
306         md5sha_ctx_t ctx_copy = *ctx; /* struct copy */
307         return sha_end(&ctx_copy, buffer);
308 }
309 # endif
310
311 static void dump_hex(const char *fmt, const void *vp, int len)
312 {
313         char hexbuf[32 * 1024 + 4];
314         const uint8_t *p = vp;
315
316         bin2hex(hexbuf, (void*)p, len)[0] = '\0';
317         dbg(fmt, hexbuf);
318 }
319
320 static void dump_tls_record(const void *vp, int len)
321 {
322         const uint8_t *p = vp;
323
324         while (len > 0) {
325                 unsigned xhdr_len;
326                 if (len < RECHDR_LEN) {
327                         dump_hex("< |%s|\n", p, len);
328                         return;
329                 }
330                 xhdr_len = 0x100*p[3] + p[4];
331                 dbg("< hdr_type:%u ver:%u.%u len:%u", p[0], p[1], p[2], xhdr_len);
332                 p += RECHDR_LEN;
333                 len -= RECHDR_LEN;
334                 if (len >= 4 && p[-RECHDR_LEN] == RECORD_TYPE_HANDSHAKE) {
335                         unsigned len24 = get24be(p + 1);
336                         dbg(" type:%u len24:%u", p[0], len24);
337                 }
338                 if (xhdr_len > len)
339                         xhdr_len = len;
340                 dump_hex(" |%s|\n", p, xhdr_len);
341                 p += xhdr_len;
342                 len -= xhdr_len;
343         }
344 }
345 #else
346 # define dump_hex(...) ((void)0)
347 # define dump_tls_record(...) ((void)0)
348 #endif
349
350 void FAST_FUNC tls_get_random(void *buf, unsigned len)
351 {
352         if (len != open_read_close("/dev/urandom", buf, len))
353                 xfunc_die();
354 }
355
356 static void xorbuf3(void *dst, const void *src1, const void *src2, unsigned count)
357 {
358         uint8_t *d = dst;
359         const uint8_t *s1 = src1;
360         const uint8_t* s2 = src2;
361         while (count--)
362                 *d++ = *s1++ ^ *s2++;
363 }
364
365 void FAST_FUNC xorbuf(void *dst, const void *src, unsigned count)
366 {
367         xorbuf3(dst, dst, src, count);
368 }
369
370 void FAST_FUNC xorbuf_aligned_AES_BLOCK_SIZE(void *dst, const void *src)
371 {
372         unsigned long *d = dst;
373         const unsigned long *s = src;
374         d[0] ^= s[0];
375 #if ULONG_MAX <= 0xffffffffffffffff
376         d[1] ^= s[1];
377  #if ULONG_MAX == 0xffffffff
378         d[2] ^= s[2];
379         d[3] ^= s[3];
380  #endif
381 #endif
382 }
383
384 #if !TLS_DEBUG_HASH
385 # define hash_handshake(tls, fmt, buffer, len) \
386          hash_handshake(tls, buffer, len)
387 #endif
388 static void hash_handshake(tls_state_t *tls, const char *fmt, const void *buffer, unsigned len)
389 {
390         md5sha_hash(&tls->hsd->handshake_hash_ctx, buffer, len);
391 #if TLS_DEBUG_HASH
392         {
393                 uint8_t h[TLS_MAX_MAC_SIZE];
394                 dump_hex(fmt, buffer, len);
395                 dbg(" (%u bytes) ", (int)len);
396                 len = sha_peek(&tls->hsd->handshake_hash_ctx, h);
397                 if (len == SHA1_OUTSIZE)
398                         dump_hex("sha1:%s\n", h, len);
399                 else
400                 if (len == SHA256_OUTSIZE)
401                         dump_hex("sha256:%s\n", h, len);
402                 else
403                         dump_hex("sha???:%s\n", h, len);
404         }
405 #endif
406 }
407
408 // RFC 2104:
409 // HMAC(key, text) based on a hash H (say, sha256) is:
410 // ipad = [0x36 x INSIZE]
411 // opad = [0x5c x INSIZE]
412 // HMAC(key, text) = H((key XOR opad) + H((key XOR ipad) + text))
413 //
414 // H(key XOR opad) and H(key XOR ipad) can be precomputed
415 // if we often need HMAC hmac with the same key.
416 //
417 // text is often given in disjoint pieces.
418 typedef struct hmac_precomputed {
419         md5sha_ctx_t hashed_key_xor_ipad;
420         md5sha_ctx_t hashed_key_xor_opad;
421 } hmac_precomputed_t;
422
423 typedef void md5sha_begin_func(md5sha_ctx_t *ctx) FAST_FUNC;
424 static void hmac_begin(hmac_precomputed_t *pre, uint8_t *key, unsigned key_size, md5sha_begin_func *begin)
425 {
426         uint8_t key_xor_ipad[SHA_INSIZE];
427         uint8_t key_xor_opad[SHA_INSIZE];
428 //      uint8_t tempkey[SHA1_OUTSIZE < SHA256_OUTSIZE ? SHA256_OUTSIZE : SHA1_OUTSIZE];
429         unsigned i;
430
431         // "The authentication key can be of any length up to INSIZE, the
432         // block length of the hash function.  Applications that use keys longer
433         // than INSIZE bytes will first hash the key using H and then use the
434         // resultant OUTSIZE byte string as the actual key to HMAC."
435         if (key_size > SHA_INSIZE) {
436                 bb_error_msg_and_die("HMAC key>64"); //does not happen (yet?)
437 //              md5sha_ctx_t ctx;
438 //              begin(&ctx);
439 //              md5sha_hash(&ctx, key, key_size);
440 //              key_size = sha_end(&ctx, tempkey);
441 //              //key = tempkey; - right? RIGHT? why does it work without this?
442 //              // because SHA_INSIZE is 64, but hmac() is always called with
443 //              // key_size = tls->MAC_size = SHA1/256_OUTSIZE (20 or 32),
444 //              // and prf_hmac_sha256() -> hmac_sha256() key sizes are:
445 //              // - RSA_PREMASTER_SIZE is 48
446 //              // - CURVE25519_KEYSIZE is 32
447 //              // - master_secret[] is 48
448         }
449
450         for (i = 0; i < key_size; i++) {
451                 key_xor_ipad[i] = key[i] ^ 0x36;
452                 key_xor_opad[i] = key[i] ^ 0x5c;
453         }
454         for (; i < SHA_INSIZE; i++) {
455                 key_xor_ipad[i] = 0x36;
456                 key_xor_opad[i] = 0x5c;
457         }
458
459         begin(&pre->hashed_key_xor_ipad);
460         begin(&pre->hashed_key_xor_opad);
461         md5sha_hash(&pre->hashed_key_xor_ipad, key_xor_ipad, SHA_INSIZE);
462         md5sha_hash(&pre->hashed_key_xor_opad, key_xor_opad, SHA_INSIZE);
463 }
464
465 static unsigned hmac_sha_precomputed_v(
466                 hmac_precomputed_t *pre,
467                 uint8_t *out,
468                 va_list va)
469 {
470         uint8_t *text;
471         unsigned len;
472
473         /* pre->hashed_key_xor_ipad contains unclosed "H((key XOR ipad) +" state */
474         /* pre->hashed_key_xor_opad contains unclosed "H((key XOR opad) +" state */
475
476         /* calculate out = H((key XOR ipad) + text) */
477         while ((text = va_arg(va, uint8_t*)) != NULL) {
478                 unsigned text_size = va_arg(va, unsigned);
479                 md5sha_hash(&pre->hashed_key_xor_ipad, text, text_size);
480         }
481         len = sha_end(&pre->hashed_key_xor_ipad, out);
482
483         /* out = H((key XOR opad) + out) */
484         md5sha_hash(&pre->hashed_key_xor_opad, out, len);
485         return sha_end(&pre->hashed_key_xor_opad, out);
486 }
487
488 static unsigned hmac_sha_precomputed(hmac_precomputed_t *pre_init, uint8_t *out, ...)
489 {
490         hmac_precomputed_t pre;
491         va_list va;
492         unsigned len;
493
494         va_start(va, out);
495         pre = *pre_init; /* struct copy */
496         len = hmac_sha_precomputed_v(&pre, out, va);
497         va_end(va);
498         return len;
499 }
500
501 static unsigned hmac(tls_state_t *tls, uint8_t *out, uint8_t *key, unsigned key_size, ...)
502 {
503         hmac_precomputed_t pre;
504         va_list va;
505         unsigned len;
506
507         va_start(va, key_size);
508
509         hmac_begin(&pre, key, key_size,
510                         (tls->MAC_size == SHA256_OUTSIZE)
511                                 ? sha256_begin
512                                 : sha1_begin
513         );
514         len = hmac_sha_precomputed_v(&pre, out, va);
515
516         va_end(va);
517         return len;
518 }
519
520 // RFC 5246:
521 // 5.  HMAC and the Pseudorandom Function
522 //...
523 // In this section, we define one PRF, based on HMAC.  This PRF with the
524 // SHA-256 hash function is used for all cipher suites defined in this
525 // document and in TLS documents published prior to this document when
526 // TLS 1.2 is negotiated.
527 // ^^^^^^^^^^^^^ IMPORTANT!
528 //               PRF uses sha256 regardless of cipher for all ciphers
529 //               defined by RFC 5246. It's not sha1 for AES_128_CBC_SHA!
530 //               However, for _SHA384 ciphers, it's sha384. See RFC 5288,5289.
531 //...
532 //    P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
533 //                           HMAC_hash(secret, A(2) + seed) +
534 //                           HMAC_hash(secret, A(3) + seed) + ...
535 // where + indicates concatenation.
536 // A() is defined as:
537 //    A(0) = seed
538 //    A(1) = HMAC_hash(secret, A(0)) = HMAC_hash(secret, seed)
539 //    A(i) = HMAC_hash(secret, A(i-1))
540 // P_hash can be iterated as many times as necessary to produce the
541 // required quantity of data.  For example, if P_SHA256 is being used to
542 // create 80 bytes of data, it will have to be iterated three times
543 // (through A(3)), creating 96 bytes of output data; the last 16 bytes
544 // of the final iteration will then be discarded, leaving 80 bytes of
545 // output data.
546 //
547 // TLS's PRF is created by applying P_hash to the secret as:
548 //
549 //    PRF(secret, label, seed) = P_<hash>(secret, label + seed)
550 //
551 // The label is an ASCII string.
552 //
553 // RFC 5288:
554 // For cipher suites ending with _SHA256, the PRF is the TLS PRF
555 // with SHA-256 as the hash function.
556 // For cipher suites ending with _SHA384, the PRF is the TLS PRF
557 // with SHA-384 as the hash function.
558 static void prf_hmac_sha256(/*tls_state_t *tls,*/
559                 uint8_t *outbuf, unsigned outbuf_size,
560                 uint8_t *secret, unsigned secret_size,
561                 const char *label,
562                 uint8_t *seed, unsigned seed_size)
563 {
564         hmac_precomputed_t pre;
565         uint8_t a[TLS_MAX_MAC_SIZE];
566         uint8_t *out_p = outbuf;
567         unsigned label_size = strlen(label);
568         unsigned MAC_size = SHA256_OUTSIZE;
569
570         /* In P_hash() calculation, "seed" is "label + seed": */
571 #define SEED   label, label_size, seed, seed_size
572 #define A      a, MAC_size
573
574         hmac_begin(&pre, secret, secret_size, sha256_begin);
575
576         /* A(1) = HMAC_hash(secret, seed) */
577         hmac_sha_precomputed(&pre, a, SEED, NULL);
578
579         for (;;) {
580                 /* HMAC_hash(secret, A(1) + seed) */
581                 if (outbuf_size <= MAC_size) {
582                         /* Last, possibly incomplete, block */
583                         /* (use a[] as temp buffer) */
584                         hmac_sha_precomputed(&pre, a, A, SEED, NULL);
585                         memcpy(out_p, a, outbuf_size);
586                         return;
587                 }
588                 /* Not last block. Store directly to result buffer */
589                 hmac_sha_precomputed(&pre, out_p, A, SEED, NULL);
590                 out_p += MAC_size;
591                 outbuf_size -= MAC_size;
592                 /* A(2) = HMAC_hash(secret, A(1)) */
593                 hmac_sha_precomputed(&pre, a, A, NULL);
594         }
595 #undef A
596 #undef SECRET
597 #undef SEED
598 }
599
600 static void bad_record_die(tls_state_t *tls, const char *expected, int len)
601 {
602         bb_error_msg("got bad TLS record (len:%d) while expecting %s", len, expected);
603         if (len > 0) {
604                 uint8_t *p = tls->inbuf;
605                 if (len > 99)
606                         len = 99; /* don't flood, a few lines should be enough */
607                 do {
608                         fprintf(stderr, " %02x", *p++);
609                         len--;
610                 } while (len != 0);
611                 fputc('\n', stderr);
612         }
613         xfunc_die();
614 }
615
616 static void tls_error_die(tls_state_t *tls, int line)
617 {
618         dump_tls_record(tls->inbuf, tls->ofs_to_buffered + tls->buffered_size);
619         bb_error_msg_and_die("tls error at line %d cipher:%04x", line, tls->cipher_id);
620 }
621 #define tls_error_die(tls) tls_error_die(tls, __LINE__)
622
623 #if 0 //UNUSED
624 static void tls_free_inbuf(tls_state_t *tls)
625 {
626         if (tls->buffered_size == 0) {
627                 free(tls->inbuf);
628                 tls->inbuf_size = 0;
629                 tls->inbuf = NULL;
630         }
631 }
632 #endif
633
634 static void tls_free_outbuf(tls_state_t *tls)
635 {
636         free(tls->outbuf);
637         tls->outbuf_size = 0;
638         tls->outbuf = NULL;
639 }
640
641 static void *tls_get_outbuf(tls_state_t *tls, int len)
642 {
643         if (len > TLS_MAX_OUTBUF)
644                 xfunc_die();
645         len += OUTBUF_PFX + OUTBUF_SFX;
646         if (tls->outbuf_size < len) {
647                 tls->outbuf_size = len;
648                 tls->outbuf = xrealloc(tls->outbuf, len);
649         }
650         return tls->outbuf + OUTBUF_PFX;
651 }
652
653 static void *tls_get_zeroed_outbuf(tls_state_t *tls, int len)
654 {
655         void *record = tls_get_outbuf(tls, len);
656         memset(record, 0, len);
657         return record;
658 }
659
660 static void xwrite_encrypted_and_hmac_signed(tls_state_t *tls, unsigned size, unsigned type)
661 {
662         uint8_t *buf = tls->outbuf + OUTBUF_PFX;
663         struct record_hdr *xhdr;
664         uint8_t padding_length;
665
666         xhdr = (void*)(buf - RECHDR_LEN);
667         if (!ALLOW_RSA_NULL_SHA256 /* if "no encryption" can't be selected */
668          || tls->cipher_id != TLS_RSA_WITH_NULL_SHA256 /* or if it wasn't selected */
669         ) {
670                 xhdr = (void*)(buf - RECHDR_LEN - AES_BLOCK_SIZE); /* place for IV */
671         }
672
673         xhdr->type = type;
674         xhdr->proto_maj = TLS_MAJ;
675         xhdr->proto_min = TLS_MIN;
676         /* fake unencrypted record len for MAC calculation */
677         xhdr->len16_hi = size >> 8;
678         xhdr->len16_lo = size & 0xff;
679
680         /* Calculate MAC signature */
681         hmac(tls, buf + size, /* result */
682                 tls->client_write_MAC_key, tls->MAC_size,
683                 &tls->write_seq64_be, sizeof(tls->write_seq64_be),
684                 xhdr, RECHDR_LEN,
685                 buf, size,
686                 NULL
687         );
688         tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(tls->write_seq64_be));
689
690         size += tls->MAC_size;
691
692         // RFC 5246:
693         // 6.2.3.1.  Null or Standard Stream Cipher
694         //
695         // Stream ciphers (including BulkCipherAlgorithm.null; see Appendix A.6)
696         // convert TLSCompressed.fragment structures to and from stream
697         // TLSCiphertext.fragment structures.
698         //
699         //    stream-ciphered struct {
700         //        opaque content[TLSCompressed.length];
701         //        opaque MAC[SecurityParameters.mac_length];
702         //    } GenericStreamCipher;
703         //
704         // The MAC is generated as:
705         //    MAC(MAC_write_key, seq_num +
706         //                          TLSCompressed.type +
707         //                          TLSCompressed.version +
708         //                          TLSCompressed.length +
709         //                          TLSCompressed.fragment);
710         // where "+" denotes concatenation.
711         // seq_num
712         //    The sequence number for this record.
713         // MAC
714         //    The MAC algorithm specified by SecurityParameters.mac_algorithm.
715         //
716         // Note that the MAC is computed before encryption.  The stream cipher
717         // encrypts the entire block, including the MAC.
718         //...
719         // Appendix C.  Cipher Suite Definitions
720         //...
721         // MAC       Algorithm    mac_length  mac_key_length
722         // --------  -----------  ----------  --------------
723         // SHA       HMAC-SHA1       20            20
724         // SHA256    HMAC-SHA256     32            32
725         if (ALLOW_RSA_NULL_SHA256
726          && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
727         ) {
728                 /* No encryption, only signing */
729                 xhdr->len16_hi = size >> 8;
730                 xhdr->len16_lo = size & 0xff;
731                 dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
732                 xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
733                 dbg("wrote %u bytes (NULL crypt, SHA256 hash)\n", size);
734                 return;
735         }
736
737         // 6.2.3.2.  CBC Block Cipher
738         // For block ciphers (such as 3DES or AES), the encryption and MAC
739         // functions convert TLSCompressed.fragment structures to and from block
740         // TLSCiphertext.fragment structures.
741         //    struct {
742         //        opaque IV[SecurityParameters.record_iv_length];
743         //        block-ciphered struct {
744         //            opaque content[TLSCompressed.length];
745         //            opaque MAC[SecurityParameters.mac_length];
746         //            uint8 padding[GenericBlockCipher.padding_length];
747         //            uint8 padding_length;
748         //        };
749         //    } GenericBlockCipher;
750         //...
751         // IV
752         //    The Initialization Vector (IV) SHOULD be chosen at random, and
753         //    MUST be unpredictable.  Note that in versions of TLS prior to 1.1,
754         //    there was no IV field (...).  For block ciphers, the IV length is
755         //    of length SecurityParameters.record_iv_length, which is equal to the
756         //    SecurityParameters.block_size.
757         // padding
758         //    Padding that is added to force the length of the plaintext to be
759         //    an integral multiple of the block cipher's block length.
760         // padding_length
761         //    The padding length MUST be such that the total size of the
762         //    GenericBlockCipher structure is a multiple of the cipher's block
763         //    length.  Legal values range from zero to 255, inclusive.
764         //...
765         // Appendix C.  Cipher Suite Definitions
766         //...
767         //                         Key      IV   Block
768         // Cipher        Type    Material  Size  Size
769         // ------------  ------  --------  ----  -----
770         // AES_128_CBC   Block      16      16     16
771         // AES_256_CBC   Block      32      16     16
772
773         tls_get_random(buf - AES_BLOCK_SIZE, AES_BLOCK_SIZE); /* IV */
774         dbg("before crypt: 5 hdr + %u data + %u hash bytes\n",
775                         size - tls->MAC_size, tls->MAC_size);
776
777         /* Fill IV and padding in outbuf */
778         // RFC is talking nonsense:
779         //    "Padding that is added to force the length of the plaintext to be
780         //    an integral multiple of the block cipher's block length."
781         // WRONG. _padding+padding_length_, not just _padding_,
782         // pads the data.
783         // IOW: padding_length is the last byte of padding[] array,
784         // contrary to what RFC depicts.
785         //
786         // What actually happens is that there is always padding.
787         // If you need one byte to reach BLOCKSIZE, this byte is 0x00.
788         // If you need two bytes, they are both 0x01.
789         // If you need three, they are 0x02,0x02,0x02. And so on.
790         // If you need no bytes to reach BLOCKSIZE, you have to pad a full
791         // BLOCKSIZE with bytes of value (BLOCKSIZE-1).
792         // It's ok to have more than minimum padding, but we do minimum.
793         padding_length = (~size) & (AES_BLOCK_SIZE - 1);
794         do {
795                 buf[size++] = padding_length; /* padding */
796         } while ((size & (AES_BLOCK_SIZE - 1)) != 0);
797
798         /* Encrypt content+MAC+padding in place */
799         aes_cbc_encrypt(
800                 &tls->aes_encrypt, /* selects 128/256 */
801                 buf - AES_BLOCK_SIZE, /* IV */
802                 buf, size, /* plaintext */
803                 buf /* ciphertext */
804         );
805
806         /* Write out */
807         dbg("writing 5 + %u IV + %u encrypted bytes, padding_length:0x%02x\n",
808                         AES_BLOCK_SIZE, size, padding_length);
809         size += AES_BLOCK_SIZE;     /* + IV */
810         xhdr->len16_hi = size >> 8;
811         xhdr->len16_lo = size & 0xff;
812         dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
813         xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
814         dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
815 }
816
817 /* Example how GCM encryption combines nonce, aad, input and generates
818  * "header | exp_nonce | encrypted output | tag":
819  * nonce:0d 6a 26 31 00 00 00 00 00 00 00 01 (implicit 4 bytes (derived from master secret), then explicit 8 bytes)
820  * aad:  00 00 00 00 00 00 00 01 17 03 03 00 1c
821  * in:   47 45 54 20 2f 69 6e 64 65 78 2e 68 74 6d 6c 20 48 54 54 50 2f 31 2e 30 0d 0a 0d 0a "GET /index.html HTTP/1.0\r\n\r\n" (0x1c bytes)
822  * out:  f7 8a b2 8f 78 0e f6 d5 76 17 2e b5 6d 46 59 56 8b 46 9f 0b d9 2c 35 28 13 66 19 be
823  * tag:  c2 86 ce 4a 50 4a d0 aa 50 b3 76 5c 49 2a 3f 33
824  * sent: 17 03 03 00 34|00 00 00 00 00 00 00 01|f7 8a b2 8f 78 0e f6 d5 76 17 2e b5 6d 46 59 56 8b 46 9f 0b d9 2c 35 28 13 66 19 be|c2 86 ce 4a 50 4a d0 aa 50 b3 76 5c 49 2a 3f 33
825  * .............................................^^ buf points here
826  */
827 static void xwrite_encrypted_aesgcm(tls_state_t *tls, unsigned size, unsigned type)
828 {
829 #define COUNTER(v) (*(uint32_t*)(v + 12))
830
831         uint8_t aad[13 + 3] ALIGNED_long;   /* +3 creates [16] buffer, simplifying GHASH() */
832         uint8_t nonce[12 + 4] ALIGNED_long; /* +4 creates space for AES block counter */
833         uint8_t scratch[AES_BLOCK_SIZE] ALIGNED_long; //[16]
834         uint8_t authtag[AES_BLOCK_SIZE] ALIGNED_long; //[16]
835         uint8_t *buf;
836         struct record_hdr *xhdr;
837         unsigned remaining;
838         unsigned cnt;
839         uint64_t t64;
840
841         buf = tls->outbuf + OUTBUF_PFX; /* see above for the byte it points to */
842         dump_hex("xwrite_encrypted_aesgcm plaintext:%s\n", buf, size);
843
844         xhdr = (void*)(buf - 8 - RECHDR_LEN);
845         xhdr->type = type; /* do it here so that "type" param no longer used */
846
847         aad[8] = type;
848         aad[9] = TLS_MAJ;
849         aad[10] = TLS_MIN;
850         aad[11] = size >> 8;
851         /* set aad[12], and clear aad[13..15] */
852         COUNTER(aad) = SWAP_LE32(size & 0xff);
853
854         memcpy(nonce, tls->client_write_IV, 4);
855         t64 = tls->write_seq64_be;
856         move_to_unaligned64(nonce + 4, t64);
857         move_to_unaligned64(aad,       t64);
858         move_to_unaligned64(buf - 8,   t64);
859         /* seq64 is not used later in this func, can increment here */
860         tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(t64));
861
862         cnt = 1;
863         remaining = size;
864         while (remaining != 0) {
865                 unsigned n;
866
867                 cnt++;
868                 COUNTER(nonce) = htonl(cnt); /* yes, first cnt here is 2 (!) */
869                 aes_encrypt_one_block(&tls->aes_encrypt, nonce, scratch);
870                 n = remaining > AES_BLOCK_SIZE ? AES_BLOCK_SIZE : remaining;
871                 xorbuf(buf, scratch, n);
872                 buf += n;
873                 remaining -= n;
874         }
875
876         aesgcm_GHASH(tls->H, aad, /*sizeof(aad),*/ tls->outbuf + OUTBUF_PFX, size, authtag /*, sizeof(authtag)*/);
877         COUNTER(nonce) = htonl(1);
878         aes_encrypt_one_block(&tls->aes_encrypt, nonce, scratch);
879         xorbuf_aligned_AES_BLOCK_SIZE(authtag, scratch);
880
881         memcpy(buf, authtag, sizeof(authtag));
882
883         /* Write out */
884         xhdr = (void*)(tls->outbuf + OUTBUF_PFX - 8 - RECHDR_LEN);
885         size += 8 + sizeof(authtag);
886         /*xhdr->type = type; - already is */
887         xhdr->proto_maj = TLS_MAJ;
888         xhdr->proto_min = TLS_MIN;
889         xhdr->len16_hi = size >> 8;
890         xhdr->len16_lo = size & 0xff;
891         size += RECHDR_LEN;
892         dump_raw_out(">> %s\n", xhdr, size);
893         xwrite(tls->ofd, xhdr, size);
894         dbg("wrote %u bytes\n", size);
895 #undef COUNTER
896 }
897
898 static void xwrite_encrypted(tls_state_t *tls, unsigned size, unsigned type)
899 {
900         if (!(tls->flags & ENCRYPTION_AESGCM)) {
901                 xwrite_encrypted_and_hmac_signed(tls, size, type);
902                 return;
903         }
904         xwrite_encrypted_aesgcm(tls, size, type);
905 }
906
907 static void xwrite_handshake_record(tls_state_t *tls, unsigned size)
908 {
909         uint8_t *buf = tls->outbuf + OUTBUF_PFX;
910         struct record_hdr *xhdr = (void*)(buf - RECHDR_LEN);
911
912         xhdr->type = RECORD_TYPE_HANDSHAKE;
913         xhdr->proto_maj = TLS_MAJ;
914         xhdr->proto_min = TLS_MIN;
915         xhdr->len16_hi = size >> 8;
916         xhdr->len16_lo = size & 0xff;
917         dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
918         xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
919         dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
920 }
921
922 static void xwrite_and_update_handshake_hash(tls_state_t *tls, unsigned size)
923 {
924         if (!(tls->flags & ENCRYPT_ON_WRITE)) {
925                 uint8_t *buf;
926
927                 xwrite_handshake_record(tls, size);
928                 /* Handshake hash does not include record headers */
929                 buf = tls->outbuf + OUTBUF_PFX;
930                 hash_handshake(tls, ">> hash:%s", buf, size);
931                 return;
932         }
933         xwrite_encrypted(tls, size, RECORD_TYPE_HANDSHAKE);
934 }
935
936 static int tls_has_buffered_record(tls_state_t *tls)
937 {
938         int buffered = tls->buffered_size;
939         struct record_hdr *xhdr;
940         int rec_size;
941
942         if (buffered < RECHDR_LEN)
943                 return 0;
944         xhdr = (void*)(tls->inbuf + tls->ofs_to_buffered);
945         rec_size = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
946         if (buffered < rec_size)
947                 return 0;
948         return rec_size;
949 }
950
951 static const char *alert_text(int code)
952 {
953         switch (code) {
954         case 20:  return "bad MAC";
955         case 50:  return "decode error";
956         case 51:  return "decrypt error";
957         case 40:  return "handshake failure";
958         case 112: return "unrecognized name";
959         }
960         return itoa(code);
961 }
962
963 static void tls_aesgcm_decrypt(tls_state_t *tls, uint8_t *buf, int size)
964 {
965 #define COUNTER(v) (*(uint32_t*)(v + 12))
966
967         //uint8_t aad[13 + 3] ALIGNED_long; /* +3 creates [16] buffer, simplifying GHASH() */
968         uint8_t nonce[12 + 4] ALIGNED_long; /* +4 creates space for AES block counter */
969         uint8_t scratch[AES_BLOCK_SIZE] ALIGNED_long; //[16]
970         //uint8_t authtag[AES_BLOCK_SIZE] ALIGNED_long; //[16]
971         unsigned remaining;
972         unsigned cnt;
973
974         //memcpy(aad, buf, 8);
975         //aad[8] = type;
976         //aad[9] = TLS_MAJ;
977         //aad[10] = TLS_MIN;
978         //aad[11] = size >> 8;
979         ///* set aad[12], and clear aad[13..15] */
980         //COUNTER(aad) = SWAP_LE32(size & 0xff);
981
982         memcpy(nonce,     tls->server_write_IV, 4);
983         memcpy(nonce + 4, buf, 8);
984
985         cnt = 1;
986         remaining = size;
987         while (remaining != 0) {
988                 unsigned n;
989
990                 cnt++;
991                 COUNTER(nonce) = htonl(cnt); /* yes, first cnt here is 2 (!) */
992                 aes_encrypt_one_block(&tls->aes_decrypt, nonce, scratch);
993                 n = remaining > AES_BLOCK_SIZE ? AES_BLOCK_SIZE : remaining;
994                 xorbuf3(buf, scratch, buf + 8, n);
995                 buf += n;
996                 remaining -= n;
997         }
998
999         //aesgcm_GHASH(tls->H, aad, tls->inbuf + RECHDR_LEN, size, authtag);
1000         //COUNTER(nonce) = htonl(1);
1001         //aes_encrypt_one_block(&tls->aes_encrypt, nonce, scratch);
1002         //xorbuf_aligned_AES_BLOCK_SIZE(authtag, scratch);
1003
1004         //memcmp(buf, authtag, sizeof(authtag)) || DIE("HASH DOES NOT MATCH!");
1005 #undef COUNTER
1006 }
1007
1008 static int tls_xread_record(tls_state_t *tls, const char *expected)
1009 {
1010         struct record_hdr *xhdr;
1011         int sz;
1012         int total;
1013         int target;
1014
1015  again:
1016         dbg("ofs_to_buffered:%u buffered_size:%u\n", tls->ofs_to_buffered, tls->buffered_size);
1017         total = tls->buffered_size;
1018         if (total != 0) {
1019                 memmove(tls->inbuf, tls->inbuf + tls->ofs_to_buffered, total);
1020                 //dbg("<< remaining at %d [%d] ", tls->ofs_to_buffered, total);
1021                 //dump_raw_in("<< %s\n", tls->inbuf, total);
1022         }
1023         errno = 0;
1024         target = MAX_INBUF;
1025         for (;;) {
1026                 int rem;
1027
1028                 if (total >= RECHDR_LEN && target == MAX_INBUF) {
1029                         xhdr = (void*)tls->inbuf;
1030                         target = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
1031
1032                         if (target > MAX_INBUF /* malformed input (too long) */
1033                          || xhdr->proto_maj != TLS_MAJ
1034                          || xhdr->proto_min != TLS_MIN
1035                         ) {
1036                                 sz = total < target ? total : target;
1037                                 bad_record_die(tls, expected, sz);
1038                         }
1039                         dbg("xhdr type:%d ver:%d.%d len:%d\n",
1040                                 xhdr->type, xhdr->proto_maj, xhdr->proto_min,
1041                                 0x100 * xhdr->len16_hi + xhdr->len16_lo
1042                         );
1043                 }
1044                 /* if total >= target, we have a full packet (and possibly more)... */
1045                 if (total - target >= 0)
1046                         break;
1047                 /* input buffer is grown only as needed */
1048                 rem = tls->inbuf_size - total;
1049                 if (rem == 0) {
1050                         tls->inbuf_size += MAX_INBUF / 8;
1051                         if (tls->inbuf_size > MAX_INBUF)
1052                                 tls->inbuf_size = MAX_INBUF;
1053                         dbg("inbuf_size:%d\n", tls->inbuf_size);
1054                         rem = tls->inbuf_size - total;
1055                         tls->inbuf = xrealloc(tls->inbuf, tls->inbuf_size);
1056                 }
1057                 sz = safe_read(tls->ifd, tls->inbuf + total, rem);
1058                 if (sz <= 0) {
1059                         if (sz == 0 && total == 0) {
1060                                 /* "Abrupt" EOF, no TLS shutdown (seen from kernel.org) */
1061                                 dbg("EOF (without TLS shutdown) from peer\n");
1062                                 tls->buffered_size = 0;
1063                                 goto end;
1064                         }
1065                         bb_perror_msg_and_die("short read, have only %d", total);
1066                 }
1067                 dump_raw_in("<< %s\n", tls->inbuf + total, sz);
1068                 total += sz;
1069         }
1070         tls->buffered_size = total - target;
1071         tls->ofs_to_buffered = target;
1072         //dbg("<< stashing at %d [%d] ", tls->ofs_to_buffered, tls->buffered_size);
1073         //dump_hex("<< %s\n", tls->inbuf + tls->ofs_to_buffered, tls->buffered_size);
1074
1075         sz = target - RECHDR_LEN;
1076
1077         /* Needs to be decrypted? */
1078         if (tls->min_encrypted_len_on_read != 0) {
1079                 if (sz < (int)tls->min_encrypted_len_on_read)
1080                         bb_error_msg_and_die("bad encrypted len:%u", sz);
1081
1082                 if (tls->flags & ENCRYPTION_AESGCM) {
1083                         /* AESGCM */
1084                         uint8_t *p = tls->inbuf + RECHDR_LEN;
1085
1086                         sz -= 8 + AES_BLOCK_SIZE; /* we will overwrite nonce, drop hash */
1087                         tls_aesgcm_decrypt(tls, p, sz);
1088                         dbg("encrypted size:%u\n", sz);
1089                 } else
1090                 if (tls->min_encrypted_len_on_read > tls->MAC_size) {
1091                         /* AES+SHA */
1092                         uint8_t *p = tls->inbuf + RECHDR_LEN;
1093                         int padding_len;
1094
1095                         if (sz & (AES_BLOCK_SIZE-1))
1096                                 bb_error_msg_and_die("bad encrypted len:%u", sz);
1097
1098                         /* Decrypt content+MAC+padding, moving it over IV in the process */
1099                         sz -= AES_BLOCK_SIZE; /* we will overwrite IV now */
1100                         aes_cbc_decrypt(
1101                                 &tls->aes_decrypt, /* selects 128/256 */
1102                                 p, /* IV */
1103                                 p + AES_BLOCK_SIZE, sz, /* ciphertext */
1104                                 p /* plaintext */
1105                         );
1106                         padding_len = p[sz - 1];
1107                         dbg("encrypted size:%u type:0x%02x padding_length:0x%02x\n", sz, p[0], padding_len);
1108                         padding_len++;
1109                         sz -= tls->MAC_size + padding_len; /* drop MAC and padding */
1110                 } else {
1111                         /* if nonzero, then it's TLS_RSA_WITH_NULL_SHA256: drop MAC */
1112                         /* else: no encryption yet on input, subtract zero = NOP */
1113                         sz -= tls->min_encrypted_len_on_read;
1114                 }
1115         }
1116         if (sz < 0)
1117                 bb_error_msg_and_die("encrypted data too short");
1118
1119         //dump_hex("<< %s\n", tls->inbuf, RECHDR_LEN + sz);
1120
1121         xhdr = (void*)tls->inbuf;
1122         if (xhdr->type == RECORD_TYPE_ALERT && sz >= 2) {
1123                 uint8_t *p = tls->inbuf + RECHDR_LEN;
1124                 dbg("ALERT size:%d level:%d description:%d\n", sz, p[0], p[1]);
1125                 if (p[0] == 2) { /* fatal */
1126                         bb_error_msg_and_die("TLS %s from peer (alert code %d): %s",
1127                                 "error",
1128                                 p[1], alert_text(p[1])
1129                         );
1130                 }
1131                 if (p[0] == 1) { /* warning */
1132                         if (p[1] == 0) { /* "close_notify" warning: it's EOF */
1133                                 dbg("EOF (TLS encoded) from peer\n");
1134                                 sz = 0;
1135                                 goto end;
1136                         }
1137 //This possibly needs to be cached and shown only if
1138 //a fatal alert follows
1139 //                      bb_error_msg("TLS %s from peer (alert code %d): %s",
1140 //                              "warning",
1141 //                              p[1], alert_text(p[1])
1142 //                      );
1143                         /* discard it, get next record */
1144                         goto again;
1145                 }
1146                 /* p[0] not 1 or 2: not defined in protocol */
1147                 sz = 0;
1148                 goto end;
1149         }
1150
1151         /* RFC 5246 is not saying it explicitly, but sha256 hash
1152          * in our FINISHED record must include data of incoming packets too!
1153          */
1154         if (tls->inbuf[0] == RECORD_TYPE_HANDSHAKE
1155 /* HANDSHAKE HASH: */
1156         // && do_we_know_which_hash_to_use /* server_hello() might not know it in the future! */
1157         ) {
1158                 hash_handshake(tls, "<< hash:%s", tls->inbuf + RECHDR_LEN, sz);
1159         }
1160  end:
1161         dbg("got block len:%u\n", sz);
1162         return sz;
1163 }
1164
1165 static void binary_to_pstm(pstm_int *pstm_n, uint8_t *bin_ptr, unsigned len)
1166 {
1167         pstm_init_for_read_unsigned_bin(/*pool:*/ NULL, pstm_n, len);
1168         pstm_read_unsigned_bin(pstm_n, bin_ptr, len);
1169         //return bin_ptr + len;
1170 }
1171
1172 /*
1173  * DER parsing routines
1174  */
1175 static unsigned get_der_len(uint8_t **bodyp, uint8_t *der, uint8_t *end)
1176 {
1177         unsigned len, len1;
1178
1179         if (end - der < 2)
1180                 xfunc_die();
1181 //      if ((der[0] & 0x1f) == 0x1f) /* not single-byte item code? */
1182 //              xfunc_die();
1183
1184         len = der[1]; /* maybe it's short len */
1185         if (len >= 0x80) {
1186                 /* no, it's long */
1187
1188                 if (len == 0x80 || end - der < (int)(len - 0x7e)) {
1189                         /* 0x80 is "0 bytes of len", invalid DER: must use short len if can */
1190                         /* need 3 or 4 bytes for 81, 82 */
1191                         xfunc_die();
1192                 }
1193
1194                 len1 = der[2]; /* if (len == 0x81) it's "ii 81 xx", fetch xx */
1195                 if (len > 0x82) {
1196                         /* >0x82 is "3+ bytes of len", should not happen realistically */
1197                         xfunc_die();
1198                 }
1199                 if (len == 0x82) { /* it's "ii 82 xx yy" */
1200                         len1 = 0x100*len1 + der[3];
1201                         der += 1; /* skip [yy] */
1202                 }
1203                 der += 1; /* skip [xx] */
1204                 len = len1;
1205 //              if (len < 0x80)
1206 //                      xfunc_die(); /* invalid DER: must use short len if can */
1207         }
1208         der += 2; /* skip [code]+[1byte] */
1209
1210         if (end - der < (int)len)
1211                 xfunc_die();
1212         *bodyp = der;
1213
1214         return len;
1215 }
1216
1217 static uint8_t *enter_der_item(uint8_t *der, uint8_t **endp)
1218 {
1219         uint8_t *new_der;
1220         unsigned len = get_der_len(&new_der, der, *endp);
1221         dbg_der("entered der @%p:0x%02x len:%u inner_byte @%p:0x%02x\n", der, der[0], len, new_der, new_der[0]);
1222         /* Move "end" position to cover only this item */
1223         *endp = new_der + len;
1224         return new_der;
1225 }
1226
1227 static uint8_t *skip_der_item(uint8_t *der, uint8_t *end)
1228 {
1229         uint8_t *new_der;
1230         unsigned len = get_der_len(&new_der, der, end);
1231         /* Skip body */
1232         new_der += len;
1233         dbg_der("skipped der 0x%02x, next byte 0x%02x\n", der[0], new_der[0]);
1234         return new_der;
1235 }
1236
1237 static void der_binary_to_pstm(pstm_int *pstm_n, uint8_t *der, uint8_t *end)
1238 {
1239         uint8_t *bin_ptr;
1240         unsigned len = get_der_len(&bin_ptr, der, end);
1241
1242         dbg_der("binary bytes:%u, first:0x%02x\n", len, bin_ptr[0]);
1243         binary_to_pstm(pstm_n, bin_ptr, len);
1244 }
1245
1246 static void find_key_in_der_cert(tls_state_t *tls, uint8_t *der, int len)
1247 {
1248 /* Certificate is a DER-encoded data structure. Each DER element has a length,
1249  * which makes it easy to skip over large compound elements of any complexity
1250  * without parsing them. Example: partial decode of kernel.org certificate:
1251  *  SEQ 0x05ac/1452 bytes (Certificate): 308205ac
1252  *    SEQ 0x0494/1172 bytes (tbsCertificate): 30820494
1253  *      [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0] 3 bytes: a003
1254  *        INTEGER (version): 0201 02
1255  *      INTEGER 0x11 bytes (serialNumber): 0211 00 9f85bf664b0cddafca508679501b2be4
1256  *      //^^^^^^note: matrixSSL also allows [ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2] = 0x82 type
1257  *      SEQ 0x0d bytes (signatureAlgo): 300d
1258  *        OID 9 bytes: 0609 2a864886f70d01010b (OID_SHA256_RSA_SIG 42.134.72.134.247.13.1.1.11)
1259  *        NULL: 0500
1260  *      SEQ 0x5f bytes (issuer): 305f
1261  *        SET 11 bytes: 310b
1262  *          SEQ 9 bytes: 3009
1263  *            OID 3 bytes: 0603 550406
1264  *            Printable string "FR": 1302 4652
1265  *        SET 14 bytes: 310e
1266  *          SEQ 12 bytes: 300c
1267  *            OID 3 bytes: 0603 550408
1268  *            Printable string "Paris": 1305 5061726973
1269  *        SET 14 bytes: 310e
1270  *          SEQ 12 bytes: 300c
1271  *            OID 3 bytes: 0603 550407
1272  *            Printable string "Paris": 1305 5061726973
1273  *        SET 14 bytes: 310e
1274  *          SEQ 12 bytes: 300c
1275  *            OID 3 bytes: 0603 55040a
1276  *            Printable string "Gandi": 1305 47616e6469
1277  *        SET 32 bytes: 3120
1278  *          SEQ 30 bytes: 301e
1279  *            OID 3 bytes: 0603 550403
1280  *            Printable string "Gandi Standard SSL CA 2": 1317 47616e6469205374616e646172642053534c2043412032
1281  *      SEQ 30 bytes (validity): 301e
1282  *        TIME "161011000000Z": 170d 3136313031313030303030305a
1283  *        TIME "191011235959Z": 170d 3139313031313233353935395a
1284  *      SEQ 0x5b/91 bytes (subject): 305b //I did not decode this
1285  *          3121301f060355040b1318446f6d61696e20436f
1286  *          6e74726f6c2056616c6964617465643121301f06
1287  *          0355040b1318506f73697469766553534c204d75
1288  *          6c74692d446f6d61696e31133011060355040313
1289  *          0a6b65726e656c2e6f7267
1290  *      SEQ 0x01a2/418 bytes (subjectPublicKeyInfo): 308201a2
1291  *        SEQ 13 bytes (algorithm): 300d
1292  *          OID 9 bytes: 0609 2a864886f70d010101 (OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1)
1293  *          NULL: 0500
1294  *        BITSTRING 0x018f/399 bytes (publicKey): 0382018f
1295  *          ????: 00
1296  *          //after the zero byte, it appears key itself uses DER encoding:
1297  *          SEQ 0x018a/394 bytes: 3082018a
1298  *            INTEGER 0x0181/385 bytes (modulus): 02820181
1299  *                  00b1ab2fc727a3bef76780c9349bf3
1300  *                  ...24 more blocks of 15 bytes each...
1301  *                  90e895291c6bc8693b65
1302  *            INTEGER 3 bytes (exponent): 0203 010001
1303  *      [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0x3] 0x01e5 bytes (X509v3 extensions): a38201e5
1304  *        SEQ 0x01e1 bytes: 308201e1
1305  *        ...
1306  * Certificate is a sequence of three elements:
1307  *      tbsCertificate (SEQ)
1308  *      signatureAlgorithm (AlgorithmIdentifier)
1309  *      signatureValue (BIT STRING)
1310  *
1311  * In turn, tbsCertificate is a sequence of:
1312  *      version
1313  *      serialNumber
1314  *      signatureAlgo (AlgorithmIdentifier)
1315  *      issuer (Name, has complex structure)
1316  *      validity (Validity, SEQ of two Times)
1317  *      subject (Name)
1318  *      subjectPublicKeyInfo (SEQ)
1319  *      ...
1320  *
1321  * subjectPublicKeyInfo is a sequence of:
1322  *      algorithm (AlgorithmIdentifier)
1323  *      publicKey (BIT STRING)
1324  *
1325  * We need Certificate.tbsCertificate.subjectPublicKeyInfo.publicKey
1326  *
1327  * Example of an ECDSA key:
1328  *      SEQ 0x59 bytes (subjectPublicKeyInfo): 3059
1329  *        SEQ 0x13 bytes (algorithm): 3013
1330  *          OID 7 bytes: 0607 2a8648ce3d0201   (OID_ECDSA_KEY_ALG 42.134.72.206.61.2.1)
1331  *          OID 8 bytes: 0608 2a8648ce3d030107 (OID_EC_prime256v1 42.134.72.206.61.3.1.7)
1332  *        BITSTRING 0x42 bytes (publicKey): 0342
1333  *          0004 53af f65e 50cc 7959 7e29 0171 c75c
1334  *          7335 e07d f45b 9750 b797 3a38 aebb 2ac6
1335  *          8329 2748 e77e 41cb d482 2ce6 05ec a058
1336  *          f3ab d561 2f4c d845 9ad3 7252 e3de bd3b
1337  *          9012
1338  */
1339         uint8_t *end = der + len;
1340
1341         /* enter "Certificate" item: [der, end) will be only Cert */
1342         der = enter_der_item(der, &end);
1343
1344         /* enter "tbsCertificate" item: [der, end) will be only tbsCert */
1345         der = enter_der_item(der, &end);
1346
1347         /*
1348          * Skip version field only if it is present. For a v1 certificate, the
1349          * version field won't be present since v1 is the default value for the
1350          * version field and fields with default values should be omitted (see
1351          * RFC 5280 sections 4.1 and 4.1.2.1). If the version field is present
1352          * it will have a tag class of 2 (context-specific), bit 6 as 1
1353          * (constructed), and a tag number of 0 (see ITU-T X.690 sections 8.1.2
1354          * and 8.14).
1355          */
1356         /* bits 7-6: 10 */
1357         /* bit 5: 1 */
1358         /* bits 4-0: 00000 */
1359         if (der[0] == 0xa0)
1360                 der = skip_der_item(der, end); /* version */
1361
1362         /* skip up to subjectPublicKeyInfo */
1363         der = skip_der_item(der, end); /* serialNumber */
1364         der = skip_der_item(der, end); /* signatureAlgo */
1365         der = skip_der_item(der, end); /* issuer */
1366         der = skip_der_item(der, end); /* validity */
1367         der = skip_der_item(der, end); /* subject */
1368
1369         /* enter subjectPublicKeyInfo */
1370         der = enter_der_item(der, &end);
1371         { /* check subjectPublicKeyInfo.algorithm */
1372                 static const uint8_t OID_RSA_KEY_ALG[] = {
1373                         0x30,0x0d, // SEQ 13 bytes
1374                         0x06,0x09, 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01, //OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1
1375                         //0x05,0x00, // NULL
1376                 };
1377                 static const uint8_t OID_ECDSA_KEY_ALG[] = {
1378                         0x30,0x13, // SEQ 0x13 bytes
1379                         0x06,0x07, 0x2a,0x86,0x48,0xce,0x3d,0x02,0x01,      //OID_ECDSA_KEY_ALG 42.134.72.206.61.2.1
1380                 //allow any curve code for now...
1381                 //      0x06,0x08, 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x07, //OID_EC_prime256v1 42.134.72.206.61.3.1.7
1382                         //RFC 3279:
1383                         //42.134.72.206.61.3     is ellipticCurve
1384                         //42.134.72.206.61.3.0   is c-TwoCurve
1385                         //42.134.72.206.61.3.1   is primeCurve
1386                         //42.134.72.206.61.3.1.7 is curve_secp256r1
1387                 };
1388                 if (memcmp(der, OID_RSA_KEY_ALG, sizeof(OID_RSA_KEY_ALG)) == 0) {
1389                         dbg("RSA key\n");
1390                         tls->flags |= GOT_CERT_RSA_KEY_ALG;
1391                 } else
1392                 if (memcmp(der, OID_ECDSA_KEY_ALG, sizeof(OID_ECDSA_KEY_ALG)) == 0) {
1393                         dbg("ECDSA key\n");
1394                         //UNUSED: tls->flags |= GOT_CERT_ECDSA_KEY_ALG;
1395                 } else
1396                         bb_error_msg_and_die("not RSA or ECDSA cert");
1397         }
1398
1399         if (tls->flags & GOT_CERT_RSA_KEY_ALG) {
1400                 /* parse RSA key: */
1401         //based on getAsnRsaPubKey(), pkcs1ParsePrivBin() is also of note
1402                 /* skip subjectPublicKeyInfo.algorithm */
1403                 der = skip_der_item(der, end);
1404                 /* enter subjectPublicKeyInfo.publicKey */
1405                 //die_if_not_this_der_type(der, end, 0x03); /* must be BITSTRING */
1406                 der = enter_der_item(der, &end);
1407
1408                 dbg("key bytes:%u, first:0x%02x\n", (int)(end - der), der[0]);
1409                 if (end - der < 14)
1410                         xfunc_die();
1411                 /* example format:
1412                  * ignore bits: 00
1413                  * SEQ 0x018a/394 bytes: 3082018a
1414                  *   INTEGER 0x0181/385 bytes (modulus): 02820181 XX...XXX
1415                  *   INTEGER 3 bytes (exponent): 0203 010001
1416                  */
1417                 if (*der != 0) /* "ignore bits", should be 0 */
1418                         xfunc_die();
1419                 der++;
1420                 der = enter_der_item(der, &end); /* enter SEQ */
1421                 /* memset(tls->hsd->server_rsa_pub_key, 0, sizeof(tls->hsd->server_rsa_pub_key)); - already is */
1422                 der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.N, der, end); /* modulus */
1423                 der = skip_der_item(der, end);
1424                 der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.e, der, end); /* exponent */
1425                 tls->hsd->server_rsa_pub_key.size = pstm_unsigned_bin_size(&tls->hsd->server_rsa_pub_key.N);
1426                 dbg("server_rsa_pub_key.size:%d\n", tls->hsd->server_rsa_pub_key.size);
1427         }
1428         /* else: ECDSA key. It is not used for generating encryption keys,
1429          * it is used only to sign the EC public key (which comes in ServerKey message).
1430          * Since we do not verify cert validity, verifying signature on EC public key
1431          * wouldn't add any security. Thus, we do nothing here.
1432          */
1433 }
1434
1435 /*
1436  * TLS Handshake routines
1437  */
1438 static int tls_xread_handshake_block(tls_state_t *tls, int min_len)
1439 {
1440         struct record_hdr *xhdr;
1441         int len = tls_xread_record(tls, "handshake record");
1442
1443         xhdr = (void*)tls->inbuf;
1444         if (len < min_len
1445          || xhdr->type != RECORD_TYPE_HANDSHAKE
1446         ) {
1447                 bad_record_die(tls, "handshake record", len);
1448         }
1449         dbg("got HANDSHAKE\n");
1450         return len;
1451 }
1452
1453 static ALWAYS_INLINE void fill_handshake_record_hdr(void *buf, unsigned type, unsigned len)
1454 {
1455         struct handshake_hdr {
1456                 uint8_t type;
1457                 uint8_t len24_hi, len24_mid, len24_lo;
1458         } *h = buf;
1459
1460         len -= 4;
1461         h->type = type;
1462         h->len24_hi  = len >> 16;
1463         h->len24_mid = len >> 8;
1464         h->len24_lo  = len & 0xff;
1465 }
1466
1467 static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
1468 {
1469 #define NUM_CIPHERS (13 + ALLOW_RSA_NULL_SHA256)
1470         static const uint8_t ciphers[] = {
1471                 0x00,(1 + NUM_CIPHERS) * 2, //len16_be
1472                 0x00,0xFF, //not a cipher - TLS_EMPTY_RENEGOTIATION_INFO_SCSV
1473                 /* ^^^^^^ RFC 5746 Renegotiation Indication Extension - some servers will refuse to work with us otherwise */
1474                 0xC0,0x09, // 1 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA - ok: wget https://is.gd/
1475                 0xC0,0x0A, // 2 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA - ok: wget https://is.gd/
1476                 0xC0,0x13, // 3 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA
1477                 0xC0,0x14, // 4 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES256-SHA (might fail with older openssl)
1478                 0xC0,0x23, // 5 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 - ok: wget https://is.gd/
1479         //      0xC0,0x24, //   TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
1480                 0xC0,0x27, // 6 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA256
1481         //      0xC0,0x28, //   TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
1482                 0xC0,0x2B, // 7 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - ok: wget https://is.gd/
1483         //      0xC0,0x2C, //   TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - wget https://is.gd/: "TLS error from peer (alert code 20): bad MAC"
1484 //TODO: GCM_SHA384 ciphers can be supported, only need sha384-based PRF?
1485                 0xC0,0x2F, // 8 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-GCM-SHA256
1486         //      0xC0,0x30, //   TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher ECDHE-RSA-AES256-GCM-SHA384: "decryption failed or bad record mac"
1487         //possibly these too:
1488         //      0xC0,0x35, //   TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
1489         //      0xC0,0x36, //   TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA
1490         //      0xC0,0x37, //   TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
1491         //      0xC0,0x38, //   TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
1492                 0x00,0x2F, // 9 TLS_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher AES128-SHA
1493                 0x00,0x35, //10 TLS_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher AES256-SHA
1494                 0x00,0x3C, //11 TLS_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher AES128-SHA256
1495                 0x00,0x3D, //12 TLS_RSA_WITH_AES_256_CBC_SHA256 - ok: openssl s_server ... -cipher AES256-SHA256
1496                 0x00,0x9C, //13 TLS_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher AES128-GCM-SHA256
1497         //      0x00,0x9D, //   TLS_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher AES256-GCM-SHA384: "decryption failed or bad record mac"
1498 #if ALLOW_RSA_NULL_SHA256
1499                 0x00,0x3B, //   TLS_RSA_WITH_NULL_SHA256
1500 #endif
1501                 0x01,0x00, //not a cipher - comprtypes_len, comprtype
1502         };
1503         static const uint8_t supported_groups[] = {
1504                 0x00,0x0a, //extension_type: "supported_groups"
1505                 0x00,0x04, //ext len
1506                 0x00,0x02, //list len
1507                 0x00,0x1d, //curve_x25519 (RFC 7748)
1508                 //0x00,0x17, //curve_secp256r1
1509                 //0x00,0x18, //curve_secp384r1
1510                 //0x00,0x19, //curve_secp521r1
1511         };
1512         //static const uint8_t signature_algorithms[] = {
1513         //      000d
1514         //      0020
1515         //      001e
1516         //      0601 0602 0603 0501 0502 0503 0401 0402 0403 0301 0302 0303 0201 0202 0203
1517         //};
1518
1519         struct client_hello {
1520                 uint8_t type;
1521                 uint8_t len24_hi, len24_mid, len24_lo;
1522                 uint8_t proto_maj, proto_min;
1523                 uint8_t rand32[32];
1524                 uint8_t session_id_len;
1525                 /* uint8_t session_id[]; */
1526                 uint8_t cipherid_len16_hi, cipherid_len16_lo;
1527                 uint8_t cipherid[(1 + NUM_CIPHERS) * 2]; /* actually variable */
1528                 uint8_t comprtypes_len;
1529                 uint8_t comprtypes[1]; /* actually variable */
1530                 /* Extensions (SNI shown):
1531                  * hi,lo // len of all extensions
1532                  *   00,00 // extension_type: "Server Name"
1533                  *   00,0e // list len (there can be more than one SNI)
1534                  *     00,0c // len of 1st Server Name Indication
1535                  *       00    // name type: host_name
1536                  *       00,09   // name len
1537                  *       "localhost" // name
1538                  */
1539 // GNU Wget 1.18 to cdn.kernel.org sends these extensions:
1540 // 0055
1541 //   0005 0005 0100000000 - status_request
1542 //   0000 0013 0011 00 000e 63646e 2e 6b65726e656c 2e 6f7267 - server_name
1543 //   ff01 0001 00 - renegotiation_info
1544 //   0023 0000 - session_ticket
1545 //   000a 0008 0006001700180019 - supported_groups
1546 //   000b 0002 0100 - ec_point_formats
1547 //   000d 0016 0014 0401 0403 0501 0503 0601 0603 0301 0303 0201 0203 - signature_algorithms
1548 // wolfssl library sends this option, RFC 7627 (closes a security weakness, some servers may require it. TODO?):
1549 //   0017 0000 - extended master secret
1550         };
1551         struct client_hello *record;
1552         uint8_t *ptr;
1553         int len;
1554         int ext_len;
1555         int sni_len = sni ? strnlen(sni, 127 - 5) : 0;
1556
1557         ext_len = 0;
1558         /* is.gd responds with "handshake failure" to our hello if there's no supported_groups element */
1559         ext_len += sizeof(supported_groups);
1560         if (sni_len)
1561                 ext_len += 9 + sni_len;
1562
1563         /* +2 is for "len of all extensions" 2-byte field */
1564         len = sizeof(*record) + 2 + ext_len;
1565         record = tls_get_zeroed_outbuf(tls, len);
1566
1567         fill_handshake_record_hdr(record, HANDSHAKE_CLIENT_HELLO, len);
1568         record->proto_maj = TLS_MAJ;    /* the "requested" version of the protocol, */
1569         record->proto_min = TLS_MIN;    /* can be higher than one in record headers */
1570         tls_get_random(record->rand32, sizeof(record->rand32));
1571         if (TLS_DEBUG_FIXED_SECRETS)
1572                 memset(record->rand32, 0x11, sizeof(record->rand32));
1573         /* record->session_id_len = 0; - already is */
1574
1575         BUILD_BUG_ON(sizeof(ciphers) != 2 + (1 + NUM_CIPHERS) * 2 + 2);
1576         memcpy(&record->cipherid_len16_hi, ciphers, sizeof(ciphers));
1577
1578         ptr = (void*)(record + 1);
1579         *ptr++ = ext_len >> 8;
1580         *ptr++ = ext_len;
1581         if (sni_len) {
1582                 //ptr[0] = 0;             //
1583                 //ptr[1] = 0;             //extension_type
1584                 //ptr[2] = 0;         //
1585                 ptr[3] = sni_len + 5; //list len
1586                 //ptr[4] = 0;             //
1587                 ptr[5] = sni_len + 3;     //len of 1st SNI
1588                 //ptr[6] = 0;         //name type
1589                 //ptr[7] = 0;             //
1590                 ptr[8] = sni_len;         //name len
1591                 ptr = mempcpy(&ptr[9], sni, sni_len);
1592         }
1593         memcpy(ptr, supported_groups, sizeof(supported_groups));
1594
1595         tls->hsd = xzalloc(sizeof(*tls->hsd));
1596         /* HANDSHAKE HASH: ^^^ + len if need to save saved_client_hello */
1597         memcpy(tls->hsd->client_and_server_rand32, record->rand32, sizeof(record->rand32));
1598 /* HANDSHAKE HASH:
1599         tls->hsd->saved_client_hello_size = len;
1600         memcpy(tls->hsd->saved_client_hello, record, len);
1601  */
1602         dbg(">> CLIENT_HELLO\n");
1603         /* Can hash immediately only if we know which MAC hash to use.
1604          * So far we do know: it's sha256:
1605          */
1606         sha256_begin(&tls->hsd->handshake_hash_ctx);
1607         xwrite_and_update_handshake_hash(tls, len);
1608         /* if this would become infeasible: save tls->hsd->saved_client_hello,
1609          * use "xwrite_handshake_record(tls, len)" here,
1610          * and hash saved_client_hello later.
1611          */
1612 }
1613
1614 static void get_server_hello(tls_state_t *tls)
1615 {
1616         struct server_hello {
1617                 struct record_hdr xhdr;
1618                 uint8_t type;
1619                 uint8_t len24_hi, len24_mid, len24_lo;
1620                 uint8_t proto_maj, proto_min;
1621                 uint8_t rand32[32]; /* first 4 bytes are unix time in BE format */
1622                 uint8_t session_id_len;
1623                 uint8_t session_id[32];
1624                 uint8_t cipherid_hi, cipherid_lo;
1625                 uint8_t comprtype;
1626                 /* extensions may follow, but only those which client offered in its Hello */
1627         };
1628
1629         struct server_hello *hp;
1630         uint8_t *cipherid;
1631         uint8_t cipherid1;
1632         int len, len24;
1633
1634         len = tls_xread_handshake_block(tls, 74 - 32);
1635
1636         hp = (void*)tls->inbuf;
1637         // 74 bytes:
1638         // 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|
1639         //SvHl len=70 maj.min unixtime^^^ 28randbytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^ slen sid32bytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cipSel comprSel
1640         if (hp->type != HANDSHAKE_SERVER_HELLO
1641          || hp->len24_hi  != 0
1642          || hp->len24_mid != 0
1643          /* hp->len24_lo checked later */
1644          || hp->proto_maj != TLS_MAJ
1645          || hp->proto_min != TLS_MIN
1646         ) {
1647                 bad_record_die(tls, "'server hello'", len);
1648         }
1649
1650         cipherid = &hp->cipherid_hi;
1651         len24 = hp->len24_lo;
1652         if (hp->session_id_len != 32) {
1653                 if (hp->session_id_len != 0)
1654                         bad_record_die(tls, "'server hello'", len);
1655
1656                 // session_id_len == 0: no session id
1657                 // "The server
1658                 // may return an empty session_id to indicate that the session will
1659                 // not be cached and therefore cannot be resumed."
1660                 cipherid -= 32;
1661                 len24 += 32; /* what len would be if session id would be present */
1662         }
1663
1664         if (len24 < 70)
1665                 bad_record_die(tls, "'server hello'", len);
1666         dbg("<< SERVER_HELLO\n");
1667
1668         memcpy(tls->hsd->client_and_server_rand32 + 32, hp->rand32, sizeof(hp->rand32));
1669
1670         /* Set up encryption params based on selected cipher */
1671 #if 0
1672                 0xC0,0x09, // 1 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA - ok: wget https://is.gd/
1673                 0xC0,0x0A, // 2 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA - ok: wget https://is.gd/
1674                 0xC0,0x13, // 3 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA
1675                 0xC0,0x14, // 4 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES256-SHA (might fail with older openssl)
1676                 0xC0,0x23, // 5 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 - ok: wget https://is.gd/
1677         //      0xC0,0x24, //   TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
1678                 0xC0,0x27, // 6 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA256
1679         //      0xC0,0x28, //   TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
1680                 0xC0,0x2B, // 7 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - ok: wget https://is.gd/
1681         //      0xC0,0x2C, //   TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - wget https://is.gd/: "TLS error from peer (alert code 20): bad MAC"
1682                 0xC0,0x2F, // 8 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-GCM-SHA256
1683         //      0xC0,0x30, //   TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher ECDHE-RSA-AES256-GCM-SHA384: "decryption failed or bad record mac"
1684         //possibly these too:
1685         //      0xC0,0x35, //   TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
1686         //      0xC0,0x36, //   TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA
1687         //      0xC0,0x37, //   TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
1688         //      0xC0,0x38, //   TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
1689                 0x00,0x2F, // 9 TLS_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher AES128-SHA
1690                 0x00,0x35, //10 TLS_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher AES256-SHA
1691                 0x00,0x3C, //11 TLS_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher AES128-SHA256
1692                 0x00,0x3D, //12 TLS_RSA_WITH_AES_256_CBC_SHA256 - ok: openssl s_server ... -cipher AES256-SHA256
1693                 0x00,0x9C, //13 TLS_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher AES128-GCM-SHA256
1694         //      0x00,0x9D, //   TLS_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher AES256-GCM-SHA384: "decryption failed or bad record mac"
1695                 0x00,0x3B, //   TLS_RSA_WITH_NULL_SHA256
1696 #endif
1697         cipherid1 = cipherid[1];
1698         tls->cipher_id = 0x100 * cipherid[0] + cipherid1;
1699         tls->key_size = AES256_KEYSIZE;
1700         tls->MAC_size = SHA256_OUTSIZE;
1701         /*tls->IV_size = 0; - already is */
1702         if (cipherid[0] == 0xC0) {
1703                 /* All C0xx are ECDHE */
1704                 tls->flags |= NEED_EC_KEY;
1705                 if (cipherid1 & 1) {
1706                         /* Odd numbered C0xx use AES128 (even ones use AES256) */
1707                         tls->key_size = AES128_KEYSIZE;
1708                 }
1709                 if (cipherid1 <= 0x14) {
1710                         tls->MAC_size = SHA1_OUTSIZE;
1711                 } else
1712                 if (cipherid1 >= 0x2B && cipherid1 <= 0x30) {
1713                         /* C02B,2C,2F,30 are AES-GCM */
1714                         tls->flags |= ENCRYPTION_AESGCM;
1715                         tls->MAC_size = 0;
1716                         tls->IV_size = 4;
1717                 }
1718         } else {
1719                 /* All 00xx are RSA */
1720                 if (cipherid1 == 0x2F
1721                  || cipherid1 == 0x3C
1722                  || cipherid1 == 0x9C
1723                 ) {
1724                         tls->key_size = AES128_KEYSIZE;
1725                 }
1726                 if (cipherid1 <= 0x35) {
1727                         tls->MAC_size = SHA1_OUTSIZE;
1728                 } else
1729                 if (cipherid1 == 0x9C /*|| cipherid1 == 0x9D*/) {
1730                         /* 009C,9D are AES-GCM */
1731                         tls->flags |= ENCRYPTION_AESGCM;
1732                         tls->MAC_size = 0;
1733                         tls->IV_size = 4;
1734                 }
1735         }
1736         dbg("server chose cipher %04x\n", tls->cipher_id);
1737         dbg("key_size:%u MAC_size:%u IV_size:%u\n", tls->key_size, tls->MAC_size, tls->IV_size);
1738
1739         /* Handshake hash eventually destined to FINISHED record
1740          * is sha256 regardless of cipher
1741          * (at least for all ciphers defined by RFC5246).
1742          * It's not sha1 for AES_128_CBC_SHA - only MAC is sha1, not this hash.
1743          */
1744 /* HANDSHAKE HASH:
1745         sha256_begin(&tls->hsd->handshake_hash_ctx);
1746         hash_handshake(tls, ">> client hello hash:%s",
1747                 tls->hsd->saved_client_hello, tls->hsd->saved_client_hello_size
1748         );
1749         hash_handshake(tls, "<< server hello hash:%s",
1750                 tls->inbuf + RECHDR_LEN, len
1751         );
1752  */
1753 }
1754
1755 static void get_server_cert(tls_state_t *tls)
1756 {
1757         struct record_hdr *xhdr;
1758         uint8_t *certbuf;
1759         int len, len1;
1760
1761         len = tls_xread_handshake_block(tls, 10);
1762
1763         xhdr = (void*)tls->inbuf;
1764         certbuf = (void*)(xhdr + 1);
1765         if (certbuf[0] != HANDSHAKE_CERTIFICATE)
1766                 bad_record_die(tls, "certificate", len);
1767         dbg("<< CERTIFICATE\n");
1768         // 4392 bytes:
1769         // 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...
1770         //Cert len=4388 ChainLen CertLen^ DER encoded X509 starts here. openssl x509 -in FILE -inform DER -noout -text
1771         len1 = get24be(certbuf + 1);
1772         if (len1 > len - 4) tls_error_die(tls);
1773         len = len1;
1774         len1 = get24be(certbuf + 4);
1775         if (len1 > len - 3) tls_error_die(tls);
1776         len = len1;
1777         len1 = get24be(certbuf + 7);
1778         if (len1 > len - 3) tls_error_die(tls);
1779         len = len1;
1780
1781         if (len)
1782                 find_key_in_der_cert(tls, certbuf + 10, len);
1783 }
1784
1785 /* On input, len is known to be >= 4.
1786  * The record is known to be SERVER_KEY_EXCHANGE.
1787  */
1788 static void process_server_key(tls_state_t *tls, int len)
1789 {
1790         struct record_hdr *xhdr;
1791         uint8_t *keybuf;
1792         int len1;
1793         uint32_t t32;
1794
1795         xhdr = (void*)tls->inbuf;
1796         keybuf = (void*)(xhdr + 1);
1797 //seen from is.gd: it selects curve_x25519:
1798 //  0c 00006e //SERVER_KEY_EXCHANGE, len
1799 //    03 //curve_type: named curve
1800 //    001d //curve_x25519
1801 //server-chosen EC point, and then signed_params
1802 //      (RFC 8422: "A hash of the params, with the signature
1803 //      appropriate to that hash applied.  The private key corresponding
1804 //      to the certified public key in the server's Certificate message is
1805 //      used for signing.")
1806 //follow. Format unclear/guessed:
1807 //    20 //eccPubKeyLen
1808 //      25511923d73b70dd2f60e66ba2f3fda31a9c25170963c7a3a972e481dbb2835d //eccPubKey (32bytes)
1809 //    0203 //hashSigAlg: 2:SHA1 (4:SHA256 5:SHA384 6:SHA512), 3:ECDSA (1:RSA)
1810 //    0046 //len (16bit)
1811 //      30 44 //SEQ, len
1812 //        02 20 //INTEGER, len
1813 //          2e18e7c2a9badd0a70cd3059a6ab114539b9f5163568911147386cd77ed7c412 //32bytes
1814 //this item ^^^^^ is sometimes 33 bytes (with all container sizes also +1)
1815 //        02 20 //INTEGER, len
1816 //          64523d6216cb94c43c9b20e377d8c52c55be6703fd6730a155930c705eaf3af6 //32bytes
1817 //same about this item ^^^^^
1818
1819 //seen from ftp.openbsd.org
1820 //(which only accepts ECDHE-RSA-AESnnn-GCM-SHAnnn and ECDHE-RSA-CHACHA20-POLY1305 ciphers):
1821 //  0c 000228 //SERVER_KEY_EXCHANGE, len
1822 //    03 //curve_type: named curve
1823 //    001d //curve_x25519
1824 //    20 //eccPubKeyLen
1825 //      eef7a15c43b71a4c7eaa48a39369399cc4332e569ec90a83274cc92596705c1a //eccPubKey
1826 //    0401 //hashSigAlg: 4:SHA256, 1:RSA
1827 //    0200 //len
1828 //      //0x200 bytes follow
1829
1830         /* Get and verify length */
1831         len1 = get24be(keybuf + 1);
1832         if (len1 > len - 4) tls_error_die(tls);
1833         len = len1;
1834         if (len < (1+2+1+32)) tls_error_die(tls);
1835         keybuf += 4;
1836
1837         /* So far we only support curve_x25519 */
1838         move_from_unaligned32(t32, keybuf);
1839         if (t32 != htonl(0x03001d20))
1840                 bb_error_msg_and_die("elliptic curve is not x25519");
1841
1842         memcpy(tls->hsd->ecc_pub_key32, keybuf + 4, 32);
1843         tls->flags |= GOT_EC_KEY;
1844         dbg("got eccPubKey\n");
1845 }
1846
1847 static void send_empty_client_cert(tls_state_t *tls)
1848 {
1849         struct client_empty_cert {
1850                 uint8_t type;
1851                 uint8_t len24_hi, len24_mid, len24_lo;
1852                 uint8_t cert_chain_len24_hi, cert_chain_len24_mid, cert_chain_len24_lo;
1853         };
1854         struct client_empty_cert *record;
1855
1856         record = tls_get_zeroed_outbuf(tls, sizeof(*record));
1857         //fill_handshake_record_hdr(record, HANDSHAKE_CERTIFICATE, sizeof(*record));
1858         //record->cert_chain_len24_hi = 0;
1859         //record->cert_chain_len24_mid = 0;
1860         //record->cert_chain_len24_lo = 0;
1861         // same as above:
1862         record->type = HANDSHAKE_CERTIFICATE;
1863         record->len24_lo = 3;
1864
1865         dbg(">> CERTIFICATE\n");
1866         xwrite_and_update_handshake_hash(tls, sizeof(*record));
1867 }
1868
1869 static void send_client_key_exchange(tls_state_t *tls)
1870 {
1871         struct client_key_exchange {
1872                 uint8_t type;
1873                 uint8_t len24_hi, len24_mid, len24_lo;
1874                 uint8_t key[2 + 4 * 1024]; // size??
1875         };
1876 //FIXME: better size estimate
1877         struct client_key_exchange *record = tls_get_zeroed_outbuf(tls, sizeof(*record));
1878         uint8_t rsa_premaster[RSA_PREMASTER_SIZE];
1879         uint8_t x25519_premaster[CURVE25519_KEYSIZE];
1880         uint8_t *premaster;
1881         int premaster_size;
1882         int len;
1883
1884         if (!(tls->flags & NEED_EC_KEY)) {
1885                 /* RSA */
1886                 if (!(tls->flags & GOT_CERT_RSA_KEY_ALG))
1887                         bb_error_msg("server cert is not RSA");
1888
1889                 tls_get_random(rsa_premaster, sizeof(rsa_premaster));
1890                 if (TLS_DEBUG_FIXED_SECRETS)
1891                         memset(rsa_premaster, 0x44, sizeof(rsa_premaster));
1892                 // RFC 5246
1893                 // "Note: The version number in the PreMasterSecret is the version
1894                 // offered by the client in the ClientHello.client_version, not the
1895                 // version negotiated for the connection."
1896                 rsa_premaster[0] = TLS_MAJ;
1897                 rsa_premaster[1] = TLS_MIN;
1898                 dump_hex("premaster:%s\n", rsa_premaster, sizeof(rsa_premaster));
1899                 len = psRsaEncryptPub(/*pool:*/ NULL,
1900                         /* psRsaKey_t* */ &tls->hsd->server_rsa_pub_key,
1901                         rsa_premaster, /*inlen:*/ sizeof(rsa_premaster),
1902                         record->key + 2, sizeof(record->key) - 2,
1903                         data_param_ignored
1904                 );
1905                 /* keylen16 exists for RSA (in TLS, not in SSL), but not for some other key types */
1906                 record->key[0] = len >> 8;
1907                 record->key[1] = len & 0xff;
1908                 len += 2;
1909                 premaster = rsa_premaster;
1910                 premaster_size = sizeof(rsa_premaster);
1911         } else {
1912                 /* ECDHE */
1913                 static const uint8_t basepoint9[CURVE25519_KEYSIZE] = {9};
1914                 uint8_t privkey[CURVE25519_KEYSIZE]; //[32]
1915
1916                 if (!(tls->flags & GOT_EC_KEY))
1917                         bb_error_msg("server did not provide EC key");
1918
1919                 /* Generate random private key, see RFC 7748 */
1920                 tls_get_random(privkey, sizeof(privkey));
1921                 privkey[0] &= 0xf8;
1922                 privkey[CURVE25519_KEYSIZE-1] = ((privkey[CURVE25519_KEYSIZE-1] & 0x7f) | 0x40);
1923
1924                 /* Compute public key */
1925                 curve25519(record->key + 1, privkey, basepoint9);
1926
1927                 /* Compute premaster using peer's public key */
1928                 dbg("computing x25519_premaster\n");
1929                 curve25519(x25519_premaster, privkey, tls->hsd->ecc_pub_key32);
1930
1931                 len = CURVE25519_KEYSIZE;
1932                 record->key[0] = len;
1933                 len++;
1934                 premaster = x25519_premaster;
1935                 premaster_size = sizeof(x25519_premaster);
1936         }
1937
1938         record->type = HANDSHAKE_CLIENT_KEY_EXCHANGE;
1939         /* record->len24_hi = 0; - already is */
1940         record->len24_mid = len >> 8;
1941         record->len24_lo  = len & 0xff;
1942         len += 4;
1943
1944         dbg(">> CLIENT_KEY_EXCHANGE\n");
1945         xwrite_and_update_handshake_hash(tls, len);
1946
1947         // RFC 5246
1948         // For all key exchange methods, the same algorithm is used to convert
1949         // the pre_master_secret into the master_secret.  The pre_master_secret
1950         // should be deleted from memory once the master_secret has been
1951         // computed.
1952         //      master_secret = PRF(pre_master_secret, "master secret",
1953         //                          ClientHello.random + ServerHello.random)
1954         //                          [0..47];
1955         // The master secret is always exactly 48 bytes in length.  The length
1956         // of the premaster secret will vary depending on key exchange method.
1957         prf_hmac_sha256(/*tls,*/
1958                 tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
1959                 premaster, premaster_size,
1960                 "master secret",
1961                 tls->hsd->client_and_server_rand32, sizeof(tls->hsd->client_and_server_rand32)
1962         );
1963         dump_hex("master secret:%s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
1964
1965         // RFC 5246
1966         // 6.3.  Key Calculation
1967         //
1968         // The Record Protocol requires an algorithm to generate keys required
1969         // by the current connection state (see Appendix A.6) from the security
1970         // parameters provided by the handshake protocol.
1971         //
1972         // The master secret is expanded into a sequence of secure bytes, which
1973         // is then split to a client write MAC key, a server write MAC key, a
1974         // client write encryption key, and a server write encryption key.  Each
1975         // of these is generated from the byte sequence in that order.  Unused
1976         // values are empty.  Some AEAD ciphers may additionally require a
1977         // client write IV and a server write IV (see Section 6.2.3.3).
1978         //
1979         // When keys and MAC keys are generated, the master secret is used as an
1980         // entropy source.
1981         //
1982         // To generate the key material, compute
1983         //
1984         //    key_block = PRF(SecurityParameters.master_secret,
1985         //                    "key expansion",
1986         //                    SecurityParameters.server_random +
1987         //                    SecurityParameters.client_random);
1988         //
1989         // until enough output has been generated.  Then, the key_block is
1990         // partitioned as follows:
1991         //
1992         //    client_write_MAC_key[SecurityParameters.mac_key_length]
1993         //    server_write_MAC_key[SecurityParameters.mac_key_length]
1994         //    client_write_key[SecurityParameters.enc_key_length]
1995         //    server_write_key[SecurityParameters.enc_key_length]
1996         //    client_write_IV[SecurityParameters.fixed_iv_length]
1997         //    server_write_IV[SecurityParameters.fixed_iv_length]
1998         {
1999                 uint8_t tmp64[64];
2000
2001                 /* make "server_rand32 + client_rand32" */
2002                 memcpy(&tmp64[0] , &tls->hsd->client_and_server_rand32[32], 32);
2003                 memcpy(&tmp64[32], &tls->hsd->client_and_server_rand32[0] , 32);
2004
2005                 prf_hmac_sha256(/*tls,*/
2006                         tls->client_write_MAC_key, 2 * (tls->MAC_size + tls->key_size + tls->IV_size),
2007                         // also fills:
2008                         // server_write_MAC_key[]
2009                         // client_write_key[]
2010                         // server_write_key[]
2011                         // client_write_IV[]
2012                         // server_write_IV[]
2013                         tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
2014                         "key expansion",
2015                         tmp64, 64
2016                 );
2017                 tls->client_write_key = tls->client_write_MAC_key + (2 * tls->MAC_size);
2018                 tls->server_write_key = tls->client_write_key + tls->key_size;
2019                 tls->client_write_IV = tls->server_write_key + tls->key_size;
2020                 tls->server_write_IV = tls->client_write_IV + tls->IV_size;
2021                 dump_hex("client_write_MAC_key:%s\n",
2022                         tls->client_write_MAC_key, tls->MAC_size
2023                 );
2024                 dump_hex("client_write_key:%s\n",
2025                         tls->client_write_key, tls->key_size
2026                 );
2027                 dump_hex("client_write_IV:%s\n",
2028                         tls->client_write_IV, tls->IV_size
2029                 );
2030
2031                 aes_setkey(&tls->aes_decrypt, tls->server_write_key, tls->key_size);
2032                 aes_setkey(&tls->aes_encrypt, tls->client_write_key, tls->key_size);
2033                 {
2034                         uint8_t iv[AES_BLOCK_SIZE];
2035                         memset(iv, 0, AES_BLOCK_SIZE);
2036                         aes_encrypt_one_block(&tls->aes_encrypt, iv, tls->H);
2037                 }
2038         }
2039 }
2040
2041 static const uint8_t rec_CHANGE_CIPHER_SPEC[] = {
2042         RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
2043         01
2044 };
2045
2046 static void send_change_cipher_spec(tls_state_t *tls)
2047 {
2048         dbg(">> CHANGE_CIPHER_SPEC\n");
2049         xwrite(tls->ofd, rec_CHANGE_CIPHER_SPEC, sizeof(rec_CHANGE_CIPHER_SPEC));
2050 }
2051
2052 // 7.4.9.  Finished
2053 // A Finished message is always sent immediately after a change
2054 // cipher spec message to verify that the key exchange and
2055 // authentication processes were successful.  It is essential that a
2056 // change cipher spec message be received between the other handshake
2057 // messages and the Finished message.
2058 //...
2059 // The Finished message is the first one protected with the just
2060 // negotiated algorithms, keys, and secrets.  Recipients of Finished
2061 // messages MUST verify that the contents are correct.  Once a side
2062 // has sent its Finished message and received and validated the
2063 // Finished message from its peer, it may begin to send and receive
2064 // application data over the connection.
2065 //...
2066 // struct {
2067 //     opaque verify_data[verify_data_length];
2068 // } Finished;
2069 //
2070 // verify_data
2071 //    PRF(master_secret, finished_label, Hash(handshake_messages))
2072 //       [0..verify_data_length-1];
2073 //
2074 // finished_label
2075 //    For Finished messages sent by the client, the string
2076 //    "client finished".  For Finished messages sent by the server,
2077 //    the string "server finished".
2078 //
2079 // Hash denotes a Hash of the handshake messages.  For the PRF
2080 // defined in Section 5, the Hash MUST be the Hash used as the basis
2081 // for the PRF.  Any cipher suite which defines a different PRF MUST
2082 // also define the Hash to use in the Finished computation.
2083 //
2084 // In previous versions of TLS, the verify_data was always 12 octets
2085 // long.  In the current version of TLS, it depends on the cipher
2086 // suite.  Any cipher suite which does not explicitly specify
2087 // verify_data_length has a verify_data_length equal to 12.  This
2088 // includes all existing cipher suites.
2089 static void send_client_finished(tls_state_t *tls)
2090 {
2091         struct finished {
2092                 uint8_t type;
2093                 uint8_t len24_hi, len24_mid, len24_lo;
2094                 uint8_t prf_result[12];
2095         };
2096         struct finished *record = tls_get_outbuf(tls, sizeof(*record));
2097         uint8_t handshake_hash[TLS_MAX_MAC_SIZE];
2098         unsigned len;
2099
2100         fill_handshake_record_hdr(record, HANDSHAKE_FINISHED, sizeof(*record));
2101
2102         len = sha_end(&tls->hsd->handshake_hash_ctx, handshake_hash);
2103
2104         prf_hmac_sha256(/*tls,*/
2105                 record->prf_result, sizeof(record->prf_result),
2106                 tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
2107                 "client finished",
2108                 handshake_hash, len
2109         );
2110         dump_hex("from secret: %s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
2111         dump_hex("from labelSeed: %s", "client finished", sizeof("client finished")-1);
2112         dump_hex("%s\n", handshake_hash, sizeof(handshake_hash));
2113         dump_hex("=> digest: %s\n", record->prf_result, sizeof(record->prf_result));
2114
2115         dbg(">> FINISHED\n");
2116         xwrite_encrypted(tls, sizeof(*record), RECORD_TYPE_HANDSHAKE);
2117 }
2118
2119 void FAST_FUNC tls_handshake(tls_state_t *tls, const char *sni)
2120 {
2121         // Client              RFC 5246                Server
2122         // (*) - optional messages, not always sent
2123         //
2124         // ClientHello          ------->
2125         //                                        ServerHello
2126         //                                       Certificate*
2127         //                                 ServerKeyExchange*
2128         //                                CertificateRequest*
2129         //                      <-------      ServerHelloDone
2130         // Certificate*
2131         // ClientKeyExchange
2132         // CertificateVerify*
2133         // [ChangeCipherSpec]
2134         // Finished             ------->
2135         //                                 [ChangeCipherSpec]
2136         //                      <-------             Finished
2137         // Application Data     <------>     Application Data
2138         int len;
2139         int got_cert_req;
2140
2141         send_client_hello_and_alloc_hsd(tls, sni);
2142         get_server_hello(tls);
2143
2144         // RFC 5246
2145         // The server MUST send a Certificate message whenever the agreed-
2146         // upon key exchange method uses certificates for authentication
2147         // (this includes all key exchange methods defined in this document
2148         // except DH_anon).  This message will always immediately follow the
2149         // ServerHello message.
2150         //
2151         // IOW: in practice, Certificate *always* follows.
2152         // (for example, kernel.org does not even accept DH_anon cipher id)
2153         get_server_cert(tls);
2154
2155         len = tls_xread_handshake_block(tls, 4);
2156         if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_SERVER_KEY_EXCHANGE) {
2157                 // 459 bytes:
2158                 // 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...
2159                 //SvKey len=455^
2160                 // with TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 461 bytes:
2161                 // 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...
2162                 //
2163                 // RFC 8422 5.4. Server Key Exchange
2164                 // This message is sent when using the ECDHE_ECDSA, ECDHE_RSA, and
2165                 // ECDH_anon key exchange algorithms.
2166                 // This message is used to convey the server's ephemeral ECDH public key
2167                 // (and the corresponding elliptic curve domain parameters) to the
2168                 // client.
2169                 dbg("<< SERVER_KEY_EXCHANGE len:%u\n", len);
2170                 dump_raw_in("<< %s\n", tls->inbuf, RECHDR_LEN + len);
2171                 if (tls->flags & NEED_EC_KEY)
2172                         process_server_key(tls, len);
2173
2174                 // read next handshake block
2175                 len = tls_xread_handshake_block(tls, 4);
2176         }
2177
2178         got_cert_req = (tls->inbuf[RECHDR_LEN] == HANDSHAKE_CERTIFICATE_REQUEST);
2179         if (got_cert_req) {
2180                 dbg("<< CERTIFICATE_REQUEST\n");
2181                 // RFC 5246: "If no suitable certificate is available,
2182                 // the client MUST send a certificate message containing no
2183                 // certificates.  That is, the certificate_list structure has a
2184                 // length of zero. ...
2185                 // Client certificates are sent using the Certificate structure
2186                 // defined in Section 7.4.2."
2187                 // (i.e. the same format as server certs)
2188
2189                 /*send_empty_client_cert(tls); - WRONG (breaks handshake hash calc) */
2190                 /* need to hash _all_ server replies first, up to ServerHelloDone */
2191                 len = tls_xread_handshake_block(tls, 4);
2192         }
2193
2194         if (tls->inbuf[RECHDR_LEN] != HANDSHAKE_SERVER_HELLO_DONE) {
2195                 bad_record_die(tls, "'server hello done'", len);
2196         }
2197         // 0e 000000 (len:0)
2198         dbg("<< SERVER_HELLO_DONE\n");
2199
2200         if (got_cert_req)
2201                 send_empty_client_cert(tls);
2202
2203         send_client_key_exchange(tls);
2204
2205         send_change_cipher_spec(tls);
2206         /* from now on we should send encrypted */
2207         /* tls->write_seq64_be = 0; - already is */
2208         tls->flags |= ENCRYPT_ON_WRITE;
2209
2210         send_client_finished(tls);
2211
2212         /* Get CHANGE_CIPHER_SPEC */
2213         len = tls_xread_record(tls, "switch to encrypted traffic");
2214         if (len != 1 || memcmp(tls->inbuf, rec_CHANGE_CIPHER_SPEC, 6) != 0)
2215                 bad_record_die(tls, "switch to encrypted traffic", len);
2216         dbg("<< CHANGE_CIPHER_SPEC\n");
2217
2218         if (ALLOW_RSA_NULL_SHA256
2219          && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
2220         ) {
2221                 tls->min_encrypted_len_on_read = tls->MAC_size;
2222         } else
2223         if (!(tls->flags & ENCRYPTION_AESGCM)) {
2224                 unsigned mac_blocks = (unsigned)(tls->MAC_size + AES_BLOCK_SIZE-1) / AES_BLOCK_SIZE;
2225                 /* all incoming packets now should be encrypted and have
2226                  * at least IV + (MAC padded to blocksize):
2227                  */
2228                 tls->min_encrypted_len_on_read = AES_BLOCK_SIZE + (mac_blocks * AES_BLOCK_SIZE);
2229         } else {
2230                 tls->min_encrypted_len_on_read = 8 + AES_BLOCK_SIZE;
2231         }
2232         dbg("min_encrypted_len_on_read: %u\n", tls->min_encrypted_len_on_read);
2233
2234         /* Get (encrypted) FINISHED from the server */
2235         len = tls_xread_record(tls, "'server finished'");
2236         if (len < 4 || tls->inbuf[RECHDR_LEN] != HANDSHAKE_FINISHED)
2237                 bad_record_die(tls, "'server finished'", len);
2238         dbg("<< FINISHED\n");
2239         /* application data can be sent/received */
2240
2241         /* free handshake data */
2242         psRsaKey_clear(&tls->hsd->server_rsa_pub_key);
2243 //      if (PARANOIA)
2244 //              memset(tls->hsd, 0, tls->hsd->hsd_size);
2245         free(tls->hsd);
2246         tls->hsd = NULL;
2247 }
2248
2249 static void tls_xwrite(tls_state_t *tls, int len)
2250 {
2251         dbg(">> DATA\n");
2252         xwrite_encrypted(tls, len, RECORD_TYPE_APPLICATION_DATA);
2253 }
2254
2255 // To run a test server using openssl:
2256 // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
2257 // openssl s_server -key key.pem -cert server.pem -debug -tls1_2
2258 //
2259 // Unencryped SHA256 example:
2260 // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
2261 // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -cipher NULL
2262 // openssl s_client -connect 127.0.0.1:4433 -debug -tls1_2 -cipher NULL-SHA256
2263
2264 void FAST_FUNC tls_run_copy_loop(tls_state_t *tls, unsigned flags)
2265 {
2266         int inbuf_size;
2267         const int INBUF_STEP = 4 * 1024;
2268         struct pollfd pfds[2];
2269
2270         pfds[0].fd = STDIN_FILENO;
2271         pfds[0].events = POLLIN;
2272         pfds[1].fd = tls->ifd;
2273         pfds[1].events = POLLIN;
2274
2275         inbuf_size = INBUF_STEP;
2276         for (;;) {
2277                 int nread;
2278
2279                 if (safe_poll(pfds, 2, -1) < 0)
2280                         bb_perror_msg_and_die("poll");
2281
2282                 if (pfds[0].revents) {
2283                         void *buf;
2284
2285                         dbg("STDIN HAS DATA\n");
2286                         buf = tls_get_outbuf(tls, inbuf_size);
2287                         nread = safe_read(STDIN_FILENO, buf, inbuf_size);
2288                         if (nread < 1) {
2289                                 /* We'd want to do this: */
2290                                 /* Close outgoing half-connection so they get EOF,
2291                                  * but leave incoming alone so we can see response
2292                                  */
2293                                 //shutdown(tls->ofd, SHUT_WR);
2294                                 /* But TLS has no way to encode this,
2295                                  * doubt it's ok to do it "raw"
2296                                  */
2297                                 pfds[0].fd = -1;
2298                                 tls_free_outbuf(tls); /* mem usage optimization */
2299                                 if (flags & TLSLOOP_EXIT_ON_LOCAL_EOF)
2300                                         break;
2301                         } else {
2302                                 if (nread == inbuf_size) {
2303                                         /* TLS has per record overhead, if input comes fast,
2304                                          * read, encrypt and send bigger chunks
2305                                          */
2306                                         inbuf_size += INBUF_STEP;
2307                                         if (inbuf_size > TLS_MAX_OUTBUF)
2308                                                 inbuf_size = TLS_MAX_OUTBUF;
2309                                 }
2310                                 tls_xwrite(tls, nread);
2311                         }
2312                 }
2313                 if (pfds[1].revents) {
2314                         dbg("NETWORK HAS DATA\n");
2315  read_record:
2316                         nread = tls_xread_record(tls, "encrypted data");
2317                         if (nread < 1) {
2318                                 /* TLS protocol has no real concept of one-sided shutdowns:
2319                                  * if we get "TLS EOF" from the peer, writes will fail too
2320                                  */
2321                                 //pfds[1].fd = -1;
2322                                 //close(STDOUT_FILENO);
2323                                 //tls_free_inbuf(tls); /* mem usage optimization */
2324                                 //continue;
2325                                 break;
2326                         }
2327                         if (tls->inbuf[0] != RECORD_TYPE_APPLICATION_DATA)
2328                                 bad_record_die(tls, "encrypted data", nread);
2329                         xwrite(STDOUT_FILENO, tls->inbuf + RECHDR_LEN, nread);
2330                         /* We may already have a complete next record buffered,
2331                          * can process it without network reads (and possible blocking)
2332                          */
2333                         if (tls_has_buffered_record(tls))
2334                                 goto read_record;
2335                 }
2336         }
2337 }