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