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