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