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