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