blob: cb6b094760c8d2df521ecbe0b2d5566311f7f387 [file] [log] [blame]
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001/*
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002 * Copyright (C) 2017 Denys Vlasenko
Denys Vlasenko11d00962017-01-15 00:12:42 +01003 *
4 * Licensed under GPLv2, see file LICENSE in this source tree.
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01005 */
6//config:config TLS
Denys Vlasenko9a647c32017-01-23 01:08:16 +01007//config: bool #No description makes it a hidden option
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01008//config: default n
9
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010010//kbuild:lib-$(CONFIG_TLS) += tls.o
Denys Vlasenko11d00962017-01-15 00:12:42 +010011//kbuild:lib-$(CONFIG_TLS) += tls_pstm.o
12//kbuild:lib-$(CONFIG_TLS) += tls_pstm_montgomery_reduce.o
13//kbuild:lib-$(CONFIG_TLS) += tls_pstm_mul_comba.o
14//kbuild:lib-$(CONFIG_TLS) += tls_pstm_sqr_comba.o
15//kbuild:lib-$(CONFIG_TLS) += tls_rsa.o
Denys Vlasenkob7e9ae62017-01-18 17:20:27 +010016//kbuild:lib-$(CONFIG_TLS) += tls_aes.o
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010017////kbuild:lib-$(CONFIG_TLS) += tls_aes_gcm.o
18
Denys Vlasenko11d00962017-01-15 00:12:42 +010019#include "tls.h"
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010020
Denys Vlasenko49ecee02017-01-24 16:00:54 +010021//Tested against kernel.org:
22//TLS 1.2
23#define TLS_MAJ 3
24#define TLS_MIN 3
25//#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA // ok, recvs SERVER_KEY_EXCHANGE *** matrixssl uses this on my box
26//#define CIPHER_ID TLS_RSA_WITH_AES_256_CBC_SHA256 // ok, no SERVER_KEY_EXCHANGE
27//#define CIPHER_ID TLS_DH_anon_WITH_AES_256_CBC_SHA // SSL_ALERT_HANDSHAKE_FAILURE
28//^^^^^^^^^^^^^^^^^^^^^^^ (tested b/c this one doesn't req server certs... no luck, server refuses it)
29//#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 // SSL_ALERT_HANDSHAKE_FAILURE
30//#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
31//#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 // ok, recvs SERVER_KEY_EXCHANGE
32//#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
33//#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
34//#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
35//#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
36//#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
37//#define CIPHER_ID TLS_RSA_WITH_AES_256_GCM_SHA384 // ok, no SERVER_KEY_EXCHANGE
38//#define CIPHER_ID TLS_RSA_WITH_AES_128_GCM_SHA256 // ok, no SERVER_KEY_EXCHANGE *** select this?
39
40// works against "openssl s_server -cipher NULL"
41// and against wolfssl-3.9.10-stable/examples/server/server.c:
42//#define CIPHER_ID TLS_RSA_WITH_NULL_SHA256 // for testing (does everything except encrypting)
43
44// works against wolfssl-3.9.10-stable/examples/server/server.c
45// works for kernel.org
46// does not work for cdn.kernel.org (e.g. downloading an actual tarball, not a web page)
47// getting alert 40 "handshake failure" at once
48// with GNU Wget 1.18, they agree on TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xC02F) cipher
49// fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES256-SHA256
50// fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES256-GCM-SHA384
51// fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES128-SHA256
52// ok: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES128-GCM-SHA256
53// ok: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES128-SHA
54// (TLS_RSA_WITH_AES_128_CBC_SHA - in TLS 1.2 it's mandated to be always supported)
55#define CIPHER_ID1 TLS_RSA_WITH_AES_256_CBC_SHA256 // no SERVER_KEY_EXCHANGE from peer
Denys Vlasenko89193f92017-01-24 18:08:07 +010056// Works with "wget https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.9.5.tar.xz"
57#define CIPHER_ID2 TLS_RSA_WITH_AES_128_CBC_SHA
Denys Vlasenko49ecee02017-01-24 16:00:54 +010058
59
Denys Vlasenko89193f92017-01-24 18:08:07 +010060#define TLS_DEBUG 0
61#define TLS_DEBUG_HASH 0
62#define TLS_DEBUG_DER 0
63#define TLS_DEBUG_FIXED_SECRETS 0
Denys Vlasenkob5bf1912017-01-23 16:12:17 +010064#if 0
65# define dump_raw_out(...) dump_hex(__VA_ARGS__)
66#else
67# define dump_raw_out(...) ((void)0)
68#endif
69#if 0
70# define dump_raw_in(...) dump_hex(__VA_ARGS__)
71#else
72# define dump_raw_in(...) ((void)0)
73#endif
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +010074
75#if TLS_DEBUG
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010076# define dbg(...) fprintf(stderr, __VA_ARGS__)
77#else
78# define dbg(...) ((void)0)
79#endif
80
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +010081#if TLS_DEBUG_DER
82# define dbg_der(...) fprintf(stderr, __VA_ARGS__)
83#else
84# define dbg_der(...) ((void)0)
85#endif
86
Denys Vlasenko11d00962017-01-15 00:12:42 +010087#define RECORD_TYPE_CHANGE_CIPHER_SPEC 20
88#define RECORD_TYPE_ALERT 21
89#define RECORD_TYPE_HANDSHAKE 22
90#define RECORD_TYPE_APPLICATION_DATA 23
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010091
Denys Vlasenko11d00962017-01-15 00:12:42 +010092#define HANDSHAKE_HELLO_REQUEST 0
93#define HANDSHAKE_CLIENT_HELLO 1
94#define HANDSHAKE_SERVER_HELLO 2
95#define HANDSHAKE_HELLO_VERIFY_REQUEST 3
96#define HANDSHAKE_NEW_SESSION_TICKET 4
97#define HANDSHAKE_CERTIFICATE 11
98#define HANDSHAKE_SERVER_KEY_EXCHANGE 12
99#define HANDSHAKE_CERTIFICATE_REQUEST 13
100#define HANDSHAKE_SERVER_HELLO_DONE 14
101#define HANDSHAKE_CERTIFICATE_VERIFY 15
102#define HANDSHAKE_CLIENT_KEY_EXCHANGE 16
103#define HANDSHAKE_FINISHED 20
104
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100105#define SSL_NULL_WITH_NULL_NULL 0x0000
106#define SSL_RSA_WITH_NULL_MD5 0x0001
107#define SSL_RSA_WITH_NULL_SHA 0x0002
108#define SSL_RSA_WITH_RC4_128_MD5 0x0004
109#define SSL_RSA_WITH_RC4_128_SHA 0x0005
110#define SSL_RSA_WITH_3DES_EDE_CBC_SHA 0x000A /* 10 */
111#define TLS_RSA_WITH_AES_128_CBC_SHA 0x002F /* 47 */
112#define TLS_RSA_WITH_AES_256_CBC_SHA 0x0035 /* 53 */
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100113#define TLS_RSA_WITH_NULL_SHA256 0x003B /* 59 */
114
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100115#define TLS_EMPTY_RENEGOTIATION_INFO_SCSV 0x00FF
116
117#define TLS_RSA_WITH_IDEA_CBC_SHA 0x0007 /* 7 */
118#define SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA 0x0016 /* 22 */
119#define SSL_DH_anon_WITH_RC4_128_MD5 0x0018 /* 24 */
120#define SSL_DH_anon_WITH_3DES_EDE_CBC_SHA 0x001B /* 27 */
121#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA 0x0033 /* 51 */
122#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA 0x0039 /* 57 */
123#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 0x0067 /* 103 */
124#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 0x006B /* 107 */
125#define TLS_DH_anon_WITH_AES_128_CBC_SHA 0x0034 /* 52 */
126#define TLS_DH_anon_WITH_AES_256_CBC_SHA 0x003A /* 58 */
127#define TLS_RSA_WITH_AES_128_CBC_SHA256 0x003C /* 60 */
128#define TLS_RSA_WITH_AES_256_CBC_SHA256 0x003D /* 61 */
129#define TLS_RSA_WITH_SEED_CBC_SHA 0x0096 /* 150 */
130#define TLS_PSK_WITH_AES_128_CBC_SHA 0x008C /* 140 */
131#define TLS_PSK_WITH_AES_128_CBC_SHA256 0x00AE /* 174 */
132#define TLS_PSK_WITH_AES_256_CBC_SHA384 0x00AF /* 175 */
133#define TLS_PSK_WITH_AES_256_CBC_SHA 0x008D /* 141 */
134#define TLS_DHE_PSK_WITH_AES_128_CBC_SHA 0x0090 /* 144 */
135#define TLS_DHE_PSK_WITH_AES_256_CBC_SHA 0x0091 /* 145 */
136#define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0xC004 /* 49156 */
137#define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0xC005 /* 49157 */
138#define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0xC009 /* 49161 */
139#define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0xC00A /* 49162 */
140#define TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA 0xC012 /* 49170 */
141#define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA 0xC013 /* 49171 */
142#define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA 0xC014 /* 49172 */
143#define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA 0xC00E /* 49166 */
144#define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA 0xC00F /* 49167 */
145#define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023 /* 49187 */
146#define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 0xC024 /* 49188 */
147#define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 0xC025 /* 49189 */
148#define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 0xC026 /* 49190 */
149#define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 0xC027 /* 49191 */
150#define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 0xC028 /* 49192 */
151#define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 0xC029 /* 49193 */
152#define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 0xC02A /* 49194 */
153
Denys Vlasenko7a18b952017-01-23 16:37:04 +0100154/* RFC 5288 "AES Galois Counter Mode (GCM) Cipher Suites for TLS" */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100155#define TLS_RSA_WITH_AES_128_GCM_SHA256 0x009C /* 156 */
156#define TLS_RSA_WITH_AES_256_GCM_SHA384 0x009D /* 157 */
157#define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B /* 49195 */
158#define TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0xC02C /* 49196 */
159#define TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0xC02D /* 49197 */
160#define TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0xC02E /* 49198 */
161#define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xC02F /* 49199 */
162#define TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0xC030 /* 49200 */
163#define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 0xC031 /* 49201 */
164#define TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 0xC032 /* 49202 */
165
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100166/* Might go to libbb.h */
167#define TLS_MAX_CRYPTBLOCK_SIZE 16
168#define TLS_MAX_OUTBUF (1 << 14)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100169
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100170enum {
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100171 SHA_INSIZE = 64,
172 SHA1_OUTSIZE = 20,
173 SHA256_OUTSIZE = 32,
174
175 AES_BLOCKSIZE = 16,
176 AES128_KEYSIZE = 16,
177 AES256_KEYSIZE = 32,
178
Denys Vlasenko38972a82017-01-20 19:11:14 +0100179 RSA_PREMASTER_SIZE = 48,
180
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100181 RECHDR_LEN = 5,
182
Denys Vlasenko38972a82017-01-20 19:11:14 +0100183 /* 8 = 3+5. 3 extra bytes result in record data being 32-bit aligned */
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100184 OUTBUF_PFX = 8 + AES_BLOCKSIZE, /* header + IV */
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100185 OUTBUF_SFX = TLS_MAX_MAC_SIZE + TLS_MAX_CRYPTBLOCK_SIZE, /* MAC + padding */
Denys Vlasenko39161392017-01-20 20:27:06 +0100186
187 // RFC 5246
188 // | 6.2.1. Fragmentation
189 // | The record layer fragments information blocks into TLSPlaintext
190 // | records carrying data in chunks of 2^14 bytes or less. Client
191 // | message boundaries are not preserved in the record layer (i.e.,
192 // | multiple client messages of the same ContentType MAY be coalesced
193 // | into a single TLSPlaintext record, or a single message MAY be
194 // | fragmented across several records)
195 // |...
196 // | length
197 // | The length (in bytes) of the following TLSPlaintext.fragment.
198 // | The length MUST NOT exceed 2^14.
199 // |...
200 // | 6.2.2. Record Compression and Decompression
201 // |...
202 // | Compression must be lossless and may not increase the content length
203 // | by more than 1024 bytes. If the decompression function encounters a
204 // | TLSCompressed.fragment that would decompress to a length in excess of
205 // | 2^14 bytes, it MUST report a fatal decompression failure error.
206 // |...
207 // | length
208 // | The length (in bytes) of the following TLSCompressed.fragment.
209 // | The length MUST NOT exceed 2^14 + 1024.
210 // |...
211 // | 6.2.3. Record Payload Protection
212 // | The encryption and MAC functions translate a TLSCompressed
213 // | structure into a TLSCiphertext. The decryption functions reverse
214 // | the process. The MAC of the record also includes a sequence
215 // | number so that missing, extra, or repeated messages are
216 // | detectable.
217 // |...
218 // | length
219 // | The length (in bytes) of the following TLSCiphertext.fragment.
220 // | The length MUST NOT exceed 2^14 + 2048.
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100221 MAX_INBUF = RECHDR_LEN + (1 << 14) + 2048,
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100222};
223
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100224struct record_hdr {
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100225 uint8_t type;
226 uint8_t proto_maj, proto_min;
227 uint8_t len16_hi, len16_lo;
228};
229
Denys Vlasenko9a647c32017-01-23 01:08:16 +0100230struct tls_handshake_data {
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100231 /* In bbox, md5/sha1/sha256 ctx's are the same structure */
232 md5sha_ctx_t handshake_hash_ctx;
233
Denys Vlasenko7a18b952017-01-23 16:37:04 +0100234 uint8_t client_and_server_rand32[2 * 32];
235 uint8_t master_secret[48];
Denys Vlasenkodd2577f2017-01-20 22:48:41 +0100236//TODO: store just the DER key here, parse/use/delete it when sending client key
237//this way it will stay key type agnostic here.
Denys Vlasenko11d00962017-01-15 00:12:42 +0100238 psRsaKey_t server_rsa_pub_key;
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100239
240 unsigned saved_client_hello_size;
241 uint8_t saved_client_hello[1];
Denys Vlasenko9a647c32017-01-23 01:08:16 +0100242};
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100243
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100244
245static unsigned get24be(const uint8_t *p)
246{
247 return 0x100*(0x100*p[0] + p[1]) + p[2];
248}
249
250#if TLS_DEBUG
251static void dump_hex(const char *fmt, const void *vp, int len)
252{
253 char hexbuf[32 * 1024 + 4];
254 const uint8_t *p = vp;
255
256 bin2hex(hexbuf, (void*)p, len)[0] = '\0';
257 dbg(fmt, hexbuf);
258}
259
260static void dump_tls_record(const void *vp, int len)
261{
262 const uint8_t *p = vp;
263
264 while (len > 0) {
265 unsigned xhdr_len;
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100266 if (len < RECHDR_LEN) {
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100267 dump_hex("< |%s|\n", p, len);
268 return;
269 }
270 xhdr_len = 0x100*p[3] + p[4];
271 dbg("< hdr_type:%u ver:%u.%u len:%u", p[0], p[1], p[2], xhdr_len);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100272 p += RECHDR_LEN;
273 len -= RECHDR_LEN;
274 if (len >= 4 && p[-RECHDR_LEN] == RECORD_TYPE_HANDSHAKE) {
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100275 unsigned len24 = get24be(p + 1);
276 dbg(" type:%u len24:%u", p[0], len24);
277 }
278 if (xhdr_len > len)
279 xhdr_len = len;
280 dump_hex(" |%s|\n", p, xhdr_len);
281 p += xhdr_len;
282 len -= xhdr_len;
283 }
284}
Denys Vlasenko38972a82017-01-20 19:11:14 +0100285#else
286# define dump_hex(...) ((void)0)
287# define dump_tls_record(...) ((void)0)
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100288#endif
289
Denys Vlasenko11d00962017-01-15 00:12:42 +0100290void tls_get_random(void *buf, unsigned len)
291{
292 if (len != open_read_close("/dev/urandom", buf, len))
293 xfunc_die();
294}
295
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100296/* Nondestructively see the current hash value */
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100297static unsigned sha_peek(md5sha_ctx_t *ctx, void *buffer)
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100298{
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100299 md5sha_ctx_t ctx_copy = *ctx; /* struct copy */
300 return sha_end(&ctx_copy, buffer);
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100301}
302
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100303static ALWAYS_INLINE unsigned get_handshake_hash(tls_state_t *tls, void *buffer)
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100304{
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100305 return sha_peek(&tls->hsd->handshake_hash_ctx, buffer);
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100306}
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100307
308#if !TLS_DEBUG_HASH
309# define hash_handshake(tls, fmt, buffer, len) \
310 hash_handshake(tls, buffer, len)
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +0100311#endif
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100312static void hash_handshake(tls_state_t *tls, const char *fmt, const void *buffer, unsigned len)
313{
314 md5sha_hash(&tls->hsd->handshake_hash_ctx, buffer, len);
315#if TLS_DEBUG_HASH
316 {
317 uint8_t h[TLS_MAX_MAC_SIZE];
318 dump_hex(fmt, buffer, len);
319 dbg(" (%u bytes) ", (int)len);
320 len = sha_peek(&tls->hsd->handshake_hash_ctx, h);
321 if (len == SHA1_OUTSIZE)
322 dump_hex("sha1:%s\n", h, len);
323 else
324 if (len == SHA256_OUTSIZE)
325 dump_hex("sha256:%s\n", h, len);
326 else
327 dump_hex("sha???:%s\n", h, len);
328 }
329#endif
330}
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100331
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100332// RFC 2104
333// HMAC(key, text) based on a hash H (say, sha256) is:
334// ipad = [0x36 x INSIZE]
335// opad = [0x5c x INSIZE]
336// HMAC(key, text) = H((key XOR opad) + H((key XOR ipad) + text))
337//
338// H(key XOR opad) and H(key XOR ipad) can be precomputed
339// if we often need HMAC hmac with the same key.
340//
341// text is often given in disjoint pieces.
Denys Vlasenko89193f92017-01-24 18:08:07 +0100342typedef struct hmac_precomputed {
343 md5sha_ctx_t hashed_key_xor_ipad;
344 md5sha_ctx_t hashed_key_xor_opad;
345} hmac_precomputed_t;
346
347static unsigned hmac_sha_precomputed_v(
348 hmac_precomputed_t *pre,
349 uint8_t *out,
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100350 va_list va)
351{
352 uint8_t *text;
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100353 unsigned len;
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100354
Denys Vlasenko89193f92017-01-24 18:08:07 +0100355 /* pre->hashed_key_xor_ipad contains unclosed "H((key XOR ipad) +" state */
356 /* pre->hashed_key_xor_opad contains unclosed "H((key XOR opad) +" state */
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100357
358 /* calculate out = H((key XOR ipad) + text) */
359 while ((text = va_arg(va, uint8_t*)) != NULL) {
360 unsigned text_size = va_arg(va, unsigned);
Denys Vlasenko89193f92017-01-24 18:08:07 +0100361 md5sha_hash(&pre->hashed_key_xor_ipad, text, text_size);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100362 }
Denys Vlasenko89193f92017-01-24 18:08:07 +0100363 len = sha_end(&pre->hashed_key_xor_ipad, out);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100364
365 /* out = H((key XOR opad) + out) */
Denys Vlasenko89193f92017-01-24 18:08:07 +0100366 md5sha_hash(&pre->hashed_key_xor_opad, out, len);
367 return sha_end(&pre->hashed_key_xor_opad, out);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100368}
369
Denys Vlasenko89193f92017-01-24 18:08:07 +0100370static void hmac_sha256_begin(hmac_precomputed_t *pre, uint8_t *key, unsigned key_size)
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100371{
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100372 uint8_t key_xor_ipad[SHA_INSIZE];
373 uint8_t key_xor_opad[SHA_INSIZE];
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100374 uint8_t tempkey[SHA256_OUTSIZE];
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100375 unsigned i;
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100376
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100377 // "The authentication key can be of any length up to INSIZE, the
378 // block length of the hash function. Applications that use keys longer
379 // than INSIZE bytes will first hash the key using H and then use the
380 // resultant OUTSIZE byte string as the actual key to HMAC."
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100381 if (key_size > SHA_INSIZE) {
382 md5sha_ctx_t ctx;
Denys Vlasenko89193f92017-01-24 18:08:07 +0100383 sha256_begin(&ctx);
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100384 md5sha_hash(&ctx, key, key_size);
385 key_size = sha_end(&ctx, tempkey);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100386 }
387
388 for (i = 0; i < key_size; i++) {
389 key_xor_ipad[i] = key[i] ^ 0x36;
390 key_xor_opad[i] = key[i] ^ 0x5c;
391 }
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100392 for (; i < SHA_INSIZE; i++) {
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100393 key_xor_ipad[i] = 0x36;
394 key_xor_opad[i] = 0x5c;
395 }
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100396
Denys Vlasenko89193f92017-01-24 18:08:07 +0100397 sha256_begin(&pre->hashed_key_xor_ipad);
398 sha256_begin(&pre->hashed_key_xor_opad);
399 md5sha_hash(&pre->hashed_key_xor_ipad, key_xor_ipad, SHA_INSIZE);
400 md5sha_hash(&pre->hashed_key_xor_opad, key_xor_opad, SHA_INSIZE);
401}
402// TODO: ^^^ vvv merge?
403static void hmac_sha1_begin(hmac_precomputed_t *pre, uint8_t *key, unsigned key_size)
404{
405 uint8_t key_xor_ipad[SHA_INSIZE];
406 uint8_t key_xor_opad[SHA_INSIZE];
407 uint8_t tempkey[SHA1_OUTSIZE];
408 unsigned i;
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100409
Denys Vlasenko89193f92017-01-24 18:08:07 +0100410 // "The authentication key can be of any length up to INSIZE, the
411 // block length of the hash function. Applications that use keys longer
412 // than INSIZE bytes will first hash the key using H and then use the
413 // resultant OUTSIZE byte string as the actual key to HMAC."
414 if (key_size > SHA_INSIZE) {
415 md5sha_ctx_t ctx;
416 sha1_begin(&ctx);
417 md5sha_hash(&ctx, key, key_size);
418 key_size = sha_end(&ctx, tempkey);
419 }
420
421 for (i = 0; i < key_size; i++) {
422 key_xor_ipad[i] = key[i] ^ 0x36;
423 key_xor_opad[i] = key[i] ^ 0x5c;
424 }
425 for (; i < SHA_INSIZE; i++) {
426 key_xor_ipad[i] = 0x36;
427 key_xor_opad[i] = 0x5c;
428 }
429
430 sha1_begin(&pre->hashed_key_xor_ipad);
431 sha1_begin(&pre->hashed_key_xor_opad);
432 md5sha_hash(&pre->hashed_key_xor_ipad, key_xor_ipad, SHA_INSIZE);
433 md5sha_hash(&pre->hashed_key_xor_opad, key_xor_opad, SHA_INSIZE);
434}
435
436static unsigned hmac(tls_state_t *tls, uint8_t *out, uint8_t *key, unsigned key_size, ...)
437{
438 hmac_precomputed_t pre;
439 va_list va;
440 unsigned len;
441
442 va_start(va, key_size);
443
444 if (tls->MAC_size == SHA256_OUTSIZE)
445 hmac_sha256_begin(&pre, key, key_size);
446 else
447 hmac_sha1_begin(&pre, key, key_size);
448
449 len = hmac_sha_precomputed_v(&pre, out, va);
450
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100451 va_end(va);
Denys Vlasenko89193f92017-01-24 18:08:07 +0100452 return len;
453}
454
455static unsigned hmac_sha256(/*tls_state_t *tls,*/ uint8_t *out, uint8_t *key, unsigned key_size, ...)
456{
457 hmac_precomputed_t pre;
458 va_list va;
459 unsigned len;
460
461 va_start(va, key_size);
462
463 hmac_sha256_begin(&pre, key, key_size);
464 len = hmac_sha_precomputed_v(&pre, out, va);
465
466 va_end(va);
467 return len;
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100468}
469
470// RFC 5246:
471// 5. HMAC and the Pseudorandom Function
472//...
473// In this section, we define one PRF, based on HMAC. This PRF with the
474// SHA-256 hash function is used for all cipher suites defined in this
475// document and in TLS documents published prior to this document when
476// TLS 1.2 is negotiated.
Denys Vlasenko89193f92017-01-24 18:08:07 +0100477// ^^^^^^^^^^^^^ IMPORTANT!
478// PRF uses sha256 regardless of cipher (at least for all ciphers
479// defined by RFC5246). It's not sha1 for AES_128_CBC_SHA!
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100480//...
481// P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
482// HMAC_hash(secret, A(2) + seed) +
483// HMAC_hash(secret, A(3) + seed) + ...
484// where + indicates concatenation.
485// A() is defined as:
486// A(0) = seed
487// A(1) = HMAC_hash(secret, A(0)) = HMAC_hash(secret, seed)
488// A(i) = HMAC_hash(secret, A(i-1))
489// P_hash can be iterated as many times as necessary to produce the
490// required quantity of data. For example, if P_SHA256 is being used to
491// create 80 bytes of data, it will have to be iterated three times
492// (through A(3)), creating 96 bytes of output data; the last 16 bytes
493// of the final iteration will then be discarded, leaving 80 bytes of
494// output data.
495//
496// TLS's PRF is created by applying P_hash to the secret as:
497//
498// PRF(secret, label, seed) = P_<hash>(secret, label + seed)
499//
500// The label is an ASCII string.
Denys Vlasenko89193f92017-01-24 18:08:07 +0100501static void prf_hmac_sha256(/*tls_state_t *tls,*/
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100502 uint8_t *outbuf, unsigned outbuf_size,
503 uint8_t *secret, unsigned secret_size,
504 const char *label,
505 uint8_t *seed, unsigned seed_size)
506{
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100507 uint8_t a[TLS_MAX_MAC_SIZE];
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100508 uint8_t *out_p = outbuf;
509 unsigned label_size = strlen(label);
Denys Vlasenko89193f92017-01-24 18:08:07 +0100510 unsigned MAC_size = SHA256_OUTSIZE;///tls->MAC_size;
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100511
512 /* In P_hash() calculation, "seed" is "label + seed": */
513#define SEED label, label_size, seed, seed_size
514#define SECRET secret, secret_size
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100515#define A a, MAC_size
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100516
517 /* A(1) = HMAC_hash(secret, seed) */
Denys Vlasenko89193f92017-01-24 18:08:07 +0100518 hmac_sha256(/*tls,*/ a, SECRET, SEED, NULL);
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100519//TODO: convert hmac to precomputed
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100520
521 for(;;) {
522 /* HMAC_hash(secret, A(1) + seed) */
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100523 if (outbuf_size <= MAC_size) {
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100524 /* Last, possibly incomplete, block */
525 /* (use a[] as temp buffer) */
Denys Vlasenko89193f92017-01-24 18:08:07 +0100526 hmac_sha256(/*tls,*/ a, SECRET, A, SEED, NULL);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100527 memcpy(out_p, a, outbuf_size);
528 return;
529 }
530 /* Not last block. Store directly to result buffer */
Denys Vlasenko89193f92017-01-24 18:08:07 +0100531 hmac_sha256(/*tls,*/ out_p, SECRET, A, SEED, NULL);
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100532 out_p += MAC_size;
533 outbuf_size -= MAC_size;
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100534 /* A(2) = HMAC_hash(secret, A(1)) */
Denys Vlasenko89193f92017-01-24 18:08:07 +0100535 hmac_sha256(/*tls,*/ a, SECRET, A, NULL);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100536 }
537#undef A
538#undef SECRET
539#undef SEED
540}
541
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100542static void bad_record_die(tls_state_t *tls, const char *expected, int len)
543{
Denys Vlasenko1500b3a2017-01-24 17:06:10 +0100544 bb_error_msg("got bad TLS record (len:%d) while expecting %s", len, expected);
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100545 if (len > 0) {
546 uint8_t *p = tls->inbuf;
Denys Vlasenko1500b3a2017-01-24 17:06:10 +0100547 while (len > 0) {
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100548 fprintf(stderr, " %02x", *p++);
Denys Vlasenko1500b3a2017-01-24 17:06:10 +0100549 len--;
550 }
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100551 fputc('\n', stderr);
552 }
553 xfunc_die();
554}
555
Denys Vlasenko1500b3a2017-01-24 17:06:10 +0100556static void tls_error_die(tls_state_t *tls, int line)
Denys Vlasenko936e83e2017-01-16 04:25:01 +0100557{
Denys Vlasenko39161392017-01-20 20:27:06 +0100558 dump_tls_record(tls->inbuf, tls->ofs_to_buffered + tls->buffered_size);
Denys Vlasenko1500b3a2017-01-24 17:06:10 +0100559 bb_error_msg_and_die("tls error at line %d cipher:%04x", line, tls->cipher_id);
Denys Vlasenko38972a82017-01-20 19:11:14 +0100560}
Denys Vlasenko1500b3a2017-01-24 17:06:10 +0100561#define tls_error_die(tls) tls_error_die(tls, __LINE__)
Denys Vlasenko38972a82017-01-20 19:11:14 +0100562
Denys Vlasenko39161392017-01-20 20:27:06 +0100563#if 0 //UNUSED
564static void tls_free_inbuf(tls_state_t *tls)
565{
566 if (tls->buffered_size == 0) {
567 free(tls->inbuf);
568 tls->inbuf_size = 0;
569 tls->inbuf = NULL;
570 }
571}
572#endif
573
Denys Vlasenko38972a82017-01-20 19:11:14 +0100574static void tls_free_outbuf(tls_state_t *tls)
575{
576 free(tls->outbuf);
577 tls->outbuf_size = 0;
578 tls->outbuf = NULL;
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100579}
580
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100581static void *tls_get_outbuf(tls_state_t *tls, int len)
582{
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100583 if (len > TLS_MAX_OUTBUF)
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100584 xfunc_die();
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100585 len += OUTBUF_PFX + OUTBUF_SFX;
586 if (tls->outbuf_size < len) {
587 tls->outbuf_size = len;
588 tls->outbuf = xrealloc(tls->outbuf, len);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100589 }
590 return tls->outbuf + OUTBUF_PFX;
591}
592
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100593static void xwrite_encrypted(tls_state_t *tls, unsigned size, unsigned type)
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100594{
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100595 uint8_t *buf = tls->outbuf + OUTBUF_PFX;
596 struct record_hdr *xhdr;
Denys Vlasenkoe7863f32017-01-20 17:59:25 +0100597 uint8_t padding_length;
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100598
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100599 xhdr = (void*)(buf - RECHDR_LEN);
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100600 if (tls->cipher_id != TLS_RSA_WITH_NULL_SHA256)
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100601 xhdr = (void*)(buf - RECHDR_LEN - AES_BLOCKSIZE); /* place for IV */
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +0100602
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100603 xhdr->type = type;
604 xhdr->proto_maj = TLS_MAJ;
605 xhdr->proto_min = TLS_MIN;
Denys Vlasenko54b927d2017-01-20 21:19:38 +0100606 /* fake unencrypted record len for MAC calculation */
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100607 xhdr->len16_hi = size >> 8;
608 xhdr->len16_lo = size & 0xff;
609
610 /* Calculate MAC signature */
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100611 hmac(tls, buf + size, /* result */
612 tls->client_write_MAC_key, tls->MAC_size,
613 &tls->write_seq64_be, sizeof(tls->write_seq64_be),
614 xhdr, RECHDR_LEN,
615 buf, size,
616 NULL
617 );
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +0100618 tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(tls->write_seq64_be));
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100619
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100620 size += tls->MAC_size;
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100621
Denys Vlasenkoe7863f32017-01-20 17:59:25 +0100622 // RFC 5246
623 // 6.2.3.1. Null or Standard Stream Cipher
624 //
625 // Stream ciphers (including BulkCipherAlgorithm.null; see Appendix A.6)
626 // convert TLSCompressed.fragment structures to and from stream
627 // TLSCiphertext.fragment structures.
628 //
629 // stream-ciphered struct {
630 // opaque content[TLSCompressed.length];
631 // opaque MAC[SecurityParameters.mac_length];
632 // } GenericStreamCipher;
633 //
634 // The MAC is generated as:
635 // MAC(MAC_write_key, seq_num +
636 // TLSCompressed.type +
637 // TLSCompressed.version +
638 // TLSCompressed.length +
639 // TLSCompressed.fragment);
640 // where "+" denotes concatenation.
641 // seq_num
642 // The sequence number for this record.
643 // MAC
644 // The MAC algorithm specified by SecurityParameters.mac_algorithm.
645 //
646 // Note that the MAC is computed before encryption. The stream cipher
647 // encrypts the entire block, including the MAC.
648 //...
649 // Appendix C. Cipher Suite Definitions
650 //...
651 // MAC Algorithm mac_length mac_key_length
652 // -------- ----------- ---------- --------------
653 // SHA HMAC-SHA1 20 20
654 // SHA256 HMAC-SHA256 32 32
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100655 if (tls->cipher_id == TLS_RSA_WITH_NULL_SHA256) {
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100656 /* No encryption, only signing */
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100657 xhdr->len16_hi = size >> 8;
658 xhdr->len16_lo = size & 0xff;
Denys Vlasenkoe7863f32017-01-20 17:59:25 +0100659 dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
Denys Vlasenko9a647c32017-01-23 01:08:16 +0100660 xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100661 dbg("wrote %u bytes (NULL crypt, SHA256 hash)\n", size);
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100662 return;
663 }
664
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100665 // 6.2.3.2. CBC Block Cipher
666 // For block ciphers (such as 3DES or AES), the encryption and MAC
667 // functions convert TLSCompressed.fragment structures to and from block
668 // TLSCiphertext.fragment structures.
669 // struct {
670 // opaque IV[SecurityParameters.record_iv_length];
671 // block-ciphered struct {
672 // opaque content[TLSCompressed.length];
673 // opaque MAC[SecurityParameters.mac_length];
674 // uint8 padding[GenericBlockCipher.padding_length];
675 // uint8 padding_length;
676 // };
677 // } GenericBlockCipher;
678 //...
679 // IV
680 // The Initialization Vector (IV) SHOULD be chosen at random, and
681 // MUST be unpredictable. Note that in versions of TLS prior to 1.1,
682 // there was no IV field (...). For block ciphers, the IV length is
683 // of length SecurityParameters.record_iv_length, which is equal to the
684 // SecurityParameters.block_size.
685 // padding
686 // Padding that is added to force the length of the plaintext to be
687 // an integral multiple of the block cipher's block length.
688 // padding_length
689 // The padding length MUST be such that the total size of the
690 // GenericBlockCipher structure is a multiple of the cipher's block
691 // length. Legal values range from zero to 255, inclusive.
692 //...
693 // Appendix C. Cipher Suite Definitions
694 //...
695 // Key IV Block
696 // Cipher Type Material Size Size
697 // ------------ ------ -------- ---- -----
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100698 // AES_128_CBC Block 16 16 16
699 // AES_256_CBC Block 32 16 16
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100700
Denys Vlasenko54b927d2017-01-20 21:19:38 +0100701 /* Fill IV and padding in outbuf */
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100702 tls_get_random(buf - AES_BLOCKSIZE, AES_BLOCKSIZE); /* IV */
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100703 dbg("before crypt: 5 hdr + %u data + %u hash bytes\n", size, tls->MAC_size);
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100704 // RFC is talking nonsense:
Denys Vlasenko7a18b952017-01-23 16:37:04 +0100705 // "Padding that is added to force the length of the plaintext to be
706 // an integral multiple of the block cipher's block length."
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100707 // WRONG. _padding+padding_length_, not just _padding_,
708 // pads the data.
709 // IOW: padding_length is the last byte of padding[] array,
710 // contrary to what RFC depicts.
711 //
712 // What actually happens is that there is always padding.
713 // If you need one byte to reach BLOCKSIZE, this byte is 0x00.
714 // If you need two bytes, they are both 0x01.
715 // If you need three, they are 0x02,0x02,0x02. And so on.
716 // If you need no bytes to reach BLOCKSIZE, you have to pad a full
717 // BLOCKSIZE with bytes of value (BLOCKSIZE-1).
718 // It's ok to have more than minimum padding, but we do minimum.
719 padding_length = (~size) & (AES_BLOCKSIZE - 1);
720 do {
Denys Vlasenko54b927d2017-01-20 21:19:38 +0100721 buf[size++] = padding_length; /* padding */
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100722 } while ((size & (AES_BLOCKSIZE - 1)) != 0);
723
724 /* Encrypt content+MAC+padding in place */
Denys Vlasenkoc31b54f2017-02-04 16:23:49 +0100725 aes_cbc_encrypt(
726 tls->client_write_key, tls->key_size, /* selects 128/256 */
727 buf - AES_BLOCKSIZE, /* IV */
728 buf, size, /* plaintext */
729 buf /* ciphertext */
730 );
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100731
732 /* Write out */
733 dbg("writing 5 + %u IV + %u encrypted bytes, padding_length:0x%02x\n",
734 AES_BLOCKSIZE, size, padding_length);
735 size += AES_BLOCKSIZE; /* + IV */
736 xhdr->len16_hi = size >> 8;
737 xhdr->len16_lo = size & 0xff;
Denys Vlasenkoe7863f32017-01-20 17:59:25 +0100738 dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
Denys Vlasenko9a647c32017-01-23 01:08:16 +0100739 xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100740 dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100741}
742
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100743static void xwrite_handshake_record(tls_state_t *tls, unsigned size)
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100744{
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100745 //if (!tls->encrypt_on_write) {
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100746 uint8_t *buf = tls->outbuf + OUTBUF_PFX;
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100747 struct record_hdr *xhdr = (void*)(buf - RECHDR_LEN);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100748
749 xhdr->type = RECORD_TYPE_HANDSHAKE;
750 xhdr->proto_maj = TLS_MAJ;
751 xhdr->proto_min = TLS_MIN;
752 xhdr->len16_hi = size >> 8;
753 xhdr->len16_lo = size & 0xff;
Denys Vlasenkoe7863f32017-01-20 17:59:25 +0100754 dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
Denys Vlasenko9a647c32017-01-23 01:08:16 +0100755 xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100756 dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100757 // return;
758 //}
759 //xwrite_encrypted(tls, size, RECORD_TYPE_HANDSHAKE);
760}
761
762static void xwrite_and_update_handshake_hash(tls_state_t *tls, unsigned size)
763{
764 if (!tls->encrypt_on_write) {
765 uint8_t *buf;
766
767 xwrite_handshake_record(tls, size);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100768 /* Handshake hash does not include record headers */
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100769 buf = tls->outbuf + OUTBUF_PFX;
770 hash_handshake(tls, ">> hash:%s", buf, size);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100771 return;
772 }
773 xwrite_encrypted(tls, size, RECORD_TYPE_HANDSHAKE);
774}
775
Denys Vlasenko38972a82017-01-20 19:11:14 +0100776static int tls_has_buffered_record(tls_state_t *tls)
777{
Denys Vlasenko39161392017-01-20 20:27:06 +0100778 int buffered = tls->buffered_size;
Denys Vlasenko38972a82017-01-20 19:11:14 +0100779 struct record_hdr *xhdr;
780 int rec_size;
781
782 if (buffered < RECHDR_LEN)
783 return 0;
Denys Vlasenko39161392017-01-20 20:27:06 +0100784 xhdr = (void*)(tls->inbuf + tls->ofs_to_buffered);
Denys Vlasenko38972a82017-01-20 19:11:14 +0100785 rec_size = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
786 if (buffered < rec_size)
787 return 0;
788 return rec_size;
789}
790
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100791static const char *alert_text(int code)
792{
793 switch (code) {
794 case 20: return "bad MAC";
795 case 50: return "decode error";
796 case 51: return "decrypt error";
797 case 40: return "handshake failure";
798 case 112: return "unrecognized name";
799 }
800 return itoa(code);
801}
802
Denys Vlasenko38972a82017-01-20 19:11:14 +0100803static int tls_xread_record(tls_state_t *tls)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100804{
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100805 struct record_hdr *xhdr;
Denys Vlasenkocccf8e72017-01-19 00:20:45 +0100806 int sz;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100807 int total;
808 int target;
809
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100810 again:
Denys Vlasenko39161392017-01-20 20:27:06 +0100811 dbg("ofs_to_buffered:%u buffered_size:%u\n", tls->ofs_to_buffered, tls->buffered_size);
812 total = tls->buffered_size;
Denys Vlasenkoe7863f32017-01-20 17:59:25 +0100813 if (total != 0) {
Denys Vlasenko39161392017-01-20 20:27:06 +0100814 memmove(tls->inbuf, tls->inbuf + tls->ofs_to_buffered, total);
815 //dbg("<< remaining at %d [%d] ", tls->ofs_to_buffered, total);
Denys Vlasenkoe7863f32017-01-20 17:59:25 +0100816 //dump_raw_in("<< %s\n", tls->inbuf, total);
817 }
818 errno = 0;
Denys Vlasenko39161392017-01-20 20:27:06 +0100819 target = MAX_INBUF;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100820 for (;;) {
Denys Vlasenko39161392017-01-20 20:27:06 +0100821 int rem;
822
823 if (total >= RECHDR_LEN && target == MAX_INBUF) {
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100824 xhdr = (void*)tls->inbuf;
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100825 target = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
Denys Vlasenko39161392017-01-20 20:27:06 +0100826 if (target > MAX_INBUF) {
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100827 /* malformed input (too long): yell and die */
Denys Vlasenko39161392017-01-20 20:27:06 +0100828 tls->buffered_size = 0;
829 tls->ofs_to_buffered = total;
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100830 tls_error_die(tls);
831 }
Denys Vlasenkoe7863f32017-01-20 17:59:25 +0100832 /* can also check type/proto_maj/proto_min here */
833 dbg("xhdr type:%d ver:%d.%d len:%d\n",
834 xhdr->type, xhdr->proto_maj, xhdr->proto_min,
835 0x100 * xhdr->len16_hi + xhdr->len16_lo
836 );
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100837 }
838 /* if total >= target, we have a full packet (and possibly more)... */
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100839 if (total - target >= 0)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100840 break;
Denys Vlasenko39161392017-01-20 20:27:06 +0100841 /* input buffer is grown only as needed */
842 rem = tls->inbuf_size - total;
843 if (rem == 0) {
844 tls->inbuf_size += MAX_INBUF / 8;
845 if (tls->inbuf_size > MAX_INBUF)
846 tls->inbuf_size = MAX_INBUF;
847 dbg("inbuf_size:%d\n", tls->inbuf_size);
848 rem = tls->inbuf_size - total;
849 tls->inbuf = xrealloc(tls->inbuf, tls->inbuf_size);
850 }
Denys Vlasenko9a647c32017-01-23 01:08:16 +0100851 sz = safe_read(tls->ifd, tls->inbuf + total, rem);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100852 if (sz <= 0) {
853 if (sz == 0 && total == 0) {
854 /* "Abrupt" EOF, no TLS shutdown (seen from kernel.org) */
855 dbg("EOF (without TLS shutdown) from peer\n");
Denys Vlasenko39161392017-01-20 20:27:06 +0100856 tls->buffered_size = 0;
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100857 goto end;
858 }
859 bb_perror_msg_and_die("short read, have only %d", total);
860 }
Denys Vlasenkoe7863f32017-01-20 17:59:25 +0100861 dump_raw_in("<< %s\n", tls->inbuf + total, sz);
Denys Vlasenkocccf8e72017-01-19 00:20:45 +0100862 total += sz;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100863 }
Denys Vlasenko39161392017-01-20 20:27:06 +0100864 tls->buffered_size = total - target;
865 tls->ofs_to_buffered = target;
866 //dbg("<< stashing at %d [%d] ", tls->ofs_to_buffered, tls->buffered_size);
867 //dump_hex("<< %s\n", tls->inbuf + tls->ofs_to_buffered, tls->buffered_size);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100868
869 sz = target - RECHDR_LEN;
Denys Vlasenkocccf8e72017-01-19 00:20:45 +0100870
871 /* Needs to be decrypted? */
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100872 if (tls->min_encrypted_len_on_read > tls->MAC_size) {
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100873 uint8_t *p = tls->inbuf + RECHDR_LEN;
Denys Vlasenkocccf8e72017-01-19 00:20:45 +0100874 int padding_len;
875
876 if (sz & (AES_BLOCKSIZE-1)
Denys Vlasenko89193f92017-01-24 18:08:07 +0100877 || sz < (int)tls->min_encrypted_len_on_read
Denys Vlasenkocccf8e72017-01-19 00:20:45 +0100878 ) {
Denys Vlasenko89193f92017-01-24 18:08:07 +0100879 bb_error_msg_and_die("bad encrypted len:%u < %u",
880 sz, tls->min_encrypted_len_on_read);
Denys Vlasenkocccf8e72017-01-19 00:20:45 +0100881 }
Denys Vlasenko54b927d2017-01-20 21:19:38 +0100882 /* Decrypt content+MAC+padding, moving it over IV in the process */
Denys Vlasenko54b927d2017-01-20 21:19:38 +0100883 sz -= AES_BLOCKSIZE; /* we will overwrite IV now */
Denys Vlasenkoc31b54f2017-02-04 16:23:49 +0100884 aes_cbc_decrypt(
885 tls->server_write_key, tls->key_size, /* selects 128/256 */
886 p, /* IV */
887 p + AES_BLOCKSIZE, sz, /* ciphertext */
888 p /* plaintext */
Denys Vlasenkocccf8e72017-01-19 00:20:45 +0100889 );
890 padding_len = p[sz - 1];
Denys Vlasenko54b927d2017-01-20 21:19:38 +0100891 dbg("encrypted size:%u type:0x%02x padding_length:0x%02x\n", sz, p[0], padding_len);
Denys Vlasenkocccf8e72017-01-19 00:20:45 +0100892 padding_len++;
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100893 sz -= tls->MAC_size + padding_len; /* drop MAC and padding */
Denys Vlasenko0af52652017-01-20 21:23:10 +0100894 //if (sz < 0)
895 // bb_error_msg_and_die("bad padding size:%u", padding_len);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100896 } else {
897 /* if nonzero, then it's TLS_RSA_WITH_NULL_SHA256: drop MAC */
898 /* else: no encryption yet on input, subtract zero = NOP */
899 sz -= tls->min_encrypted_len_on_read;
Denys Vlasenkocccf8e72017-01-19 00:20:45 +0100900 }
Denys Vlasenko0af52652017-01-20 21:23:10 +0100901 if (sz < 0)
902 bb_error_msg_and_die("encrypted data too short");
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100903
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100904 //dump_hex("<< %s\n", tls->inbuf, RECHDR_LEN + sz);
905
906 xhdr = (void*)tls->inbuf;
907 if (xhdr->type == RECORD_TYPE_ALERT && sz >= 2) {
908 uint8_t *p = tls->inbuf + RECHDR_LEN;
909 dbg("ALERT size:%d level:%d description:%d\n", sz, p[0], p[1]);
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100910 if (p[0] == 2) { /* fatal */
911 bb_error_msg_and_die("TLS %s from peer (alert code %d): %s",
912 "error",
913 p[1], alert_text(p[1])
914 );
915 }
Denys Vlasenko54b927d2017-01-20 21:19:38 +0100916 if (p[0] == 1) { /* warning */
917 if (p[1] == 0) { /* "close_notify" warning: it's EOF */
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100918 dbg("EOF (TLS encoded) from peer\n");
919 sz = 0;
920 goto end;
921 }
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100922//This possibly needs to be cached and shown only if
923//a fatal alert follows
924// bb_error_msg("TLS %s from peer (alert code %d): %s",
925// "warning",
926// p[1], alert_text(p[1])
927// );
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100928 /* discard it, get next record */
929 goto again;
930 }
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100931 /* p[0] not 1 or 2: not defined in protocol */
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100932 sz = 0;
933 goto end;
934 }
935
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100936 /* RFC 5246 is not saying it explicitly, but sha256 hash
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100937 * in our FINISHED record must include data of incoming packets too!
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100938 */
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100939 if (tls->inbuf[0] == RECORD_TYPE_HANDSHAKE
940 && tls->MAC_size != 0 /* do we know which hash to use? (server_hello() does not!) */
941 ) {
942 hash_handshake(tls, "<< hash:%s", tls->inbuf + RECHDR_LEN, sz);
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100943 }
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100944 end:
Denys Vlasenkocccf8e72017-01-19 00:20:45 +0100945 dbg("got block len:%u\n", sz);
946 return sz;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100947}
948
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100949/*
950 * DER parsing routines
951 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100952static unsigned get_der_len(uint8_t **bodyp, uint8_t *der, uint8_t *end)
953{
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +0100954 unsigned len, len1;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100955
956 if (end - der < 2)
957 xfunc_die();
958// if ((der[0] & 0x1f) == 0x1f) /* not single-byte item code? */
959// xfunc_die();
960
961 len = der[1]; /* maybe it's short len */
962 if (len >= 0x80) {
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100963 /* no, it's long */
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +0100964
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100965 if (len == 0x80 || end - der < (int)(len - 0x7e)) {
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100966 /* 0x80 is "0 bytes of len", invalid DER: must use short len if can */
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100967 /* need 3 or 4 bytes for 81, 82 */
968 xfunc_die();
969 }
970
971 len1 = der[2]; /* if (len == 0x81) it's "ii 81 xx", fetch xx */
972 if (len > 0x82) {
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100973 /* >0x82 is "3+ bytes of len", should not happen realistically */
974 xfunc_die();
975 }
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100976 if (len == 0x82) { /* it's "ii 82 xx yy" */
977 len1 = 0x100*len1 + der[3];
978 der += 1; /* skip [yy] */
979 }
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +0100980 der += 1; /* skip [xx] */
981 len = len1;
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100982// if (len < 0x80)
983// xfunc_die(); /* invalid DER: must use short len if can */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100984 }
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +0100985 der += 2; /* skip [code]+[1byte] */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100986
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +0100987 if (end - der < (int)len)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100988 xfunc_die();
989 *bodyp = der;
990
991 return len;
992}
993
994static uint8_t *enter_der_item(uint8_t *der, uint8_t **endp)
995{
996 uint8_t *new_der;
997 unsigned len = get_der_len(&new_der, der, *endp);
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +0100998 dbg_der("entered der @%p:0x%02x len:%u inner_byte @%p:0x%02x\n", der, der[0], len, new_der, new_der[0]);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100999 /* Move "end" position to cover only this item */
1000 *endp = new_der + len;
1001 return new_der;
1002}
1003
1004static uint8_t *skip_der_item(uint8_t *der, uint8_t *end)
1005{
1006 uint8_t *new_der;
1007 unsigned len = get_der_len(&new_der, der, end);
1008 /* Skip body */
1009 new_der += len;
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01001010 dbg_der("skipped der 0x%02x, next byte 0x%02x\n", der[0], new_der[0]);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001011 return new_der;
1012}
1013
Denys Vlasenko11d00962017-01-15 00:12:42 +01001014static void der_binary_to_pstm(pstm_int *pstm_n, uint8_t *der, uint8_t *end)
1015{
Denys Vlasenkof78ad092017-01-15 00:18:22 +01001016 uint8_t *bin_ptr;
1017 unsigned len = get_der_len(&bin_ptr, der, end);
Denys Vlasenko11d00962017-01-15 00:12:42 +01001018
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01001019 dbg_der("binary bytes:%u, first:0x%02x\n", len, bin_ptr[0]);
Denys Vlasenko11d00962017-01-15 00:12:42 +01001020 pstm_init_for_read_unsigned_bin(/*pool:*/ NULL, pstm_n, len);
1021 pstm_read_unsigned_bin(pstm_n, bin_ptr, len);
1022 //return bin + len;
1023}
1024
1025static void find_key_in_der_cert(tls_state_t *tls, uint8_t *der, int len)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001026{
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001027/* Certificate is a DER-encoded data structure. Each DER element has a length,
1028 * which makes it easy to skip over large compound elements of any complexity
1029 * without parsing them. Example: partial decode of kernel.org certificate:
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001030 * SEQ 0x05ac/1452 bytes (Certificate): 308205ac
1031 * SEQ 0x0494/1172 bytes (tbsCertificate): 30820494
1032 * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0] 3 bytes: a003
1033 * INTEGER (version): 0201 02
1034 * INTEGER 0x11 bytes (serialNumber): 0211 00 9f85bf664b0cddafca508679501b2be4
1035 * //^^^^^^note: matrixSSL also allows [ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2] = 0x82 type
1036 * SEQ 0x0d bytes (signatureAlgo): 300d
1037 * OID 9 bytes: 0609 2a864886f70d01010b (OID_SHA256_RSA_SIG 42.134.72.134.247.13.1.1.11)
1038 * NULL: 0500
1039 * SEQ 0x5f bytes (issuer): 305f
1040 * SET 11 bytes: 310b
1041 * SEQ 9 bytes: 3009
1042 * OID 3 bytes: 0603 550406
1043 * Printable string "FR": 1302 4652
1044 * SET 14 bytes: 310e
1045 * SEQ 12 bytes: 300c
1046 * OID 3 bytes: 0603 550408
1047 * Printable string "Paris": 1305 5061726973
1048 * SET 14 bytes: 310e
1049 * SEQ 12 bytes: 300c
1050 * OID 3 bytes: 0603 550407
1051 * Printable string "Paris": 1305 5061726973
1052 * SET 14 bytes: 310e
1053 * SEQ 12 bytes: 300c
1054 * OID 3 bytes: 0603 55040a
1055 * Printable string "Gandi": 1305 47616e6469
1056 * SET 32 bytes: 3120
1057 * SEQ 30 bytes: 301e
1058 * OID 3 bytes: 0603 550403
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001059 * Printable string "Gandi Standard SSL CA 2": 1317 47616e6469205374616e646172642053534c2043412032
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001060 * SEQ 30 bytes (validity): 301e
1061 * TIME "161011000000Z": 170d 3136313031313030303030305a
1062 * TIME "191011235959Z": 170d 3139313031313233353935395a
1063 * SEQ 0x5b/91 bytes (subject): 305b //I did not decode this
1064 * 3121301f060355040b1318446f6d61696e20436f
1065 * 6e74726f6c2056616c6964617465643121301f06
1066 * 0355040b1318506f73697469766553534c204d75
1067 * 6c74692d446f6d61696e31133011060355040313
1068 * 0a6b65726e656c2e6f7267
1069 * SEQ 0x01a2/418 bytes (subjectPublicKeyInfo): 308201a2
1070 * SEQ 13 bytes (algorithm): 300d
1071 * OID 9 bytes: 0609 2a864886f70d010101 (OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1)
1072 * NULL: 0500
1073 * BITSTRING 0x018f/399 bytes (publicKey): 0382018f
1074 * ????: 00
1075 * //after the zero byte, it appears key itself uses DER encoding:
1076 * SEQ 0x018a/394 bytes: 3082018a
1077 * INTEGER 0x0181/385 bytes (modulus): 02820181
1078 * 00b1ab2fc727a3bef76780c9349bf3
1079 * ...24 more blocks of 15 bytes each...
1080 * 90e895291c6bc8693b65
1081 * INTEGER 3 bytes (exponent): 0203 010001
1082 * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0x3] 0x01e5 bytes (X509v3 extensions): a38201e5
1083 * SEQ 0x01e1 bytes: 308201e1
1084 * ...
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001085 * Certificate is a sequence of three elements:
1086 * tbsCertificate (SEQ)
1087 * signatureAlgorithm (AlgorithmIdentifier)
1088 * signatureValue (BIT STRING)
1089 *
1090 * In turn, tbsCertificate is a sequence of:
1091 * version
1092 * serialNumber
1093 * signatureAlgo (AlgorithmIdentifier)
1094 * issuer (Name, has complex structure)
1095 * validity (Validity, SEQ of two Times)
1096 * subject (Name)
1097 * subjectPublicKeyInfo (SEQ)
1098 * ...
1099 *
1100 * subjectPublicKeyInfo is a sequence of:
1101 * algorithm (AlgorithmIdentifier)
1102 * publicKey (BIT STRING)
1103 *
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001104 * We need Certificate.tbsCertificate.subjectPublicKeyInfo.publicKey
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001105 */
1106 uint8_t *end = der + len;
1107
1108 /* enter "Certificate" item: [der, end) will be only Cert */
1109 der = enter_der_item(der, &end);
1110
1111 /* enter "tbsCertificate" item: [der, end) will be only tbsCert */
1112 der = enter_der_item(der, &end);
1113
1114 /* skip up to subjectPublicKeyInfo */
1115 der = skip_der_item(der, end); /* version */
1116 der = skip_der_item(der, end); /* serialNumber */
1117 der = skip_der_item(der, end); /* signatureAlgo */
1118 der = skip_der_item(der, end); /* issuer */
1119 der = skip_der_item(der, end); /* validity */
1120 der = skip_der_item(der, end); /* subject */
1121
Denys Vlasenko11d00962017-01-15 00:12:42 +01001122 /* enter subjectPublicKeyInfo */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001123 der = enter_der_item(der, &end);
Denys Vlasenko11d00962017-01-15 00:12:42 +01001124 { /* check subjectPublicKeyInfo.algorithm */
1125 static const uint8_t expected[] = {
1126 0x30,0x0d, // SEQ 13 bytes
1127 0x06,0x09, 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01, // OID RSA_KEY_ALG 42.134.72.134.247.13.1.1.1
1128 //0x05,0x00, // NULL
1129 };
1130 if (memcmp(der, expected, sizeof(expected)) != 0)
1131 bb_error_msg_and_die("not RSA key");
1132 }
1133 /* skip subjectPublicKeyInfo.algorithm */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001134 der = skip_der_item(der, end);
Denys Vlasenko11d00962017-01-15 00:12:42 +01001135 /* enter subjectPublicKeyInfo.publicKey */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001136// die_if_not_this_der_type(der, end, 0x03); /* must be BITSTRING */
1137 der = enter_der_item(der, &end);
1138
Denys Vlasenko11d00962017-01-15 00:12:42 +01001139 /* parse RSA key: */
1140//based on getAsnRsaPubKey(), pkcs1ParsePrivBin() is also of note
1141 dbg("key bytes:%u, first:0x%02x\n", (int)(end - der), der[0]);
1142 if (end - der < 14) xfunc_die();
1143 /* example format:
1144 * ignore bits: 00
1145 * SEQ 0x018a/394 bytes: 3082018a
1146 * INTEGER 0x0181/385 bytes (modulus): 02820181 XX...XXX
1147 * INTEGER 3 bytes (exponent): 0203 010001
1148 */
1149 if (*der != 0) /* "ignore bits", should be 0 */
1150 xfunc_die();
1151 der++;
1152 der = enter_der_item(der, &end); /* enter SEQ */
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001153 /* memset(tls->hsd->server_rsa_pub_key, 0, sizeof(tls->hsd->server_rsa_pub_key)); - already is */
1154 der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.N, der, end); /* modulus */
Denys Vlasenko11d00962017-01-15 00:12:42 +01001155 der = skip_der_item(der, end);
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001156 der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.e, der, end); /* exponent */
1157 tls->hsd->server_rsa_pub_key.size = pstm_unsigned_bin_size(&tls->hsd->server_rsa_pub_key.N);
1158 dbg("server_rsa_pub_key.size:%d\n", tls->hsd->server_rsa_pub_key.size);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001159}
1160
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001161/*
1162 * TLS Handshake routines
1163 */
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001164static int tls_xread_handshake_block(tls_state_t *tls, int min_len)
Denys Vlasenkofe0588d2017-01-17 17:04:24 +01001165{
1166 struct record_hdr *xhdr;
Denys Vlasenko38972a82017-01-20 19:11:14 +01001167 int len = tls_xread_record(tls);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +01001168
1169 xhdr = (void*)tls->inbuf;
1170 if (len < min_len
1171 || xhdr->type != RECORD_TYPE_HANDSHAKE
1172 || xhdr->proto_maj != TLS_MAJ
1173 || xhdr->proto_min != TLS_MIN
1174 ) {
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001175 bad_record_die(tls, "handshake record", len);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +01001176 }
1177 dbg("got HANDSHAKE\n");
1178 return len;
1179}
1180
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001181static ALWAYS_INLINE void fill_handshake_record_hdr(void *buf, unsigned type, unsigned len)
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001182{
1183 struct handshake_hdr {
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001184 uint8_t type;
1185 uint8_t len24_hi, len24_mid, len24_lo;
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001186 } *h = buf;
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001187
1188 len -= 4;
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001189 h->type = type;
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001190 h->len24_hi = len >> 16;
1191 h->len24_mid = len >> 8;
1192 h->len24_lo = len & 0xff;
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001193}
1194
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001195static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001196{
1197 struct client_hello {
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001198 uint8_t type;
1199 uint8_t len24_hi, len24_mid, len24_lo;
1200 uint8_t proto_maj, proto_min;
1201 uint8_t rand32[32];
1202 uint8_t session_id_len;
1203 /* uint8_t session_id[]; */
1204 uint8_t cipherid_len16_hi, cipherid_len16_lo;
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001205 uint8_t cipherid[2 * (2 + !!CIPHER_ID2)]; /* actually variable */
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001206 uint8_t comprtypes_len;
1207 uint8_t comprtypes[1]; /* actually variable */
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001208 /* Extensions (SNI shown):
1209 * hi,lo // len of all extensions
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001210 * 00,00 // extension_type: "Server Name"
1211 * 00,0e // list len (there can be more than one SNI)
1212 * 00,0c // len of 1st Server Name Indication
1213 * 00 // name type: host_name
1214 * 00,09 // name len
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001215 * "localhost" // name
1216 */
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001217// GNU Wget 1.18 to cdn.kernel.org sends these extensions:
1218// 0055
1219// 0005 0005 0100000000 - status_request
1220// 0000 0013 0011 00 000e 63646e 2e 6b65726e656c 2e 6f7267 - server_name
1221// ff01 0001 00 - renegotiation_info
1222// 0023 0000 - session_ticket
1223// 000a 0008 0006001700180019 - supported_groups
1224// 000b 0002 0100 - ec_point_formats
1225// 000d 0016 00140401040305010503060106030301030302010203 - signature_algorithms
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001226 };
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001227 struct client_hello *record;
1228 int len;
1229 int sni_len = sni ? strnlen(sni, 127) : 0;
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001230
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001231 len = sizeof(*record);
1232 if (sni_len)
1233 len += 11 + strlen(sni);
1234 record = tls_get_outbuf(tls, len);
1235 memset(record, 0, len);
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001236
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001237 fill_handshake_record_hdr(record, HANDSHAKE_CLIENT_HELLO, len);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001238 record->proto_maj = TLS_MAJ; /* the "requested" version of the protocol, */
1239 record->proto_min = TLS_MIN; /* can be higher than one in record headers */
1240 tls_get_random(record->rand32, sizeof(record->rand32));
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001241 if (TLS_DEBUG_FIXED_SECRETS)
1242 memset(record->rand32, 0x11, sizeof(record->rand32));
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001243 /* record->session_id_len = 0; - already is */
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001244
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001245 /* record->cipherid_len16_hi = 0; */
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001246 record->cipherid_len16_lo = sizeof(record->cipherid);
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001247 /* RFC 5746 Renegotiation Indication Extension - some servers will refuse to work with us otherwise */
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001248 /*record->cipherid[0] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV >> 8; - zero */
1249 record->cipherid[1] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV & 0xff;
1250 if ((CIPHER_ID1 >> 8) != 0) record->cipherid[2] = CIPHER_ID1 >> 8;
1251 /*************************/ record->cipherid[3] = CIPHER_ID1 & 0xff;
1252#if CIPHER_ID2
1253 if ((CIPHER_ID2 >> 8) != 0) record->cipherid[4] = CIPHER_ID2 >> 8;
1254 /*************************/ record->cipherid[5] = CIPHER_ID2 & 0xff;
1255#endif
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001256
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001257 record->comprtypes_len = 1;
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001258 /* record->comprtypes[0] = 0; */
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001259
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001260 if (sni_len) {
1261 uint8_t *p = (void*)(record + 1);
1262 //p[0] = 0; //
1263 p[1] = sni_len + 9; //ext_len
1264 //p[2] = 0; //
1265 //p[3] = 0; //extension_type
1266 //p[4] = 0; //
1267 p[5] = sni_len + 5; //list len
1268 //p[6] = 0; //
1269 p[7] = sni_len + 3; //len of 1st SNI
1270 //p[8] = 0; //name type
1271 //p[9] = 0; //
1272 p[10] = sni_len; //name len
1273 memcpy(&p[11], sni, sni_len);
1274 }
Denys Vlasenko19e695e2017-01-20 14:27:58 +01001275
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01001276 dbg(">> CLIENT_HELLO\n");
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001277 /* Can hash it only when we know which MAC hash to use */
1278 /*xwrite_and_update_handshake_hash(tls, len); - WRONG! */
1279 xwrite_handshake_record(tls, len);
1280
1281 tls->hsd = xzalloc(sizeof(*tls->hsd) + len);
1282 tls->hsd->saved_client_hello_size = len;
1283 memcpy(tls->hsd->saved_client_hello, record, len);
1284 memcpy(tls->hsd->client_and_server_rand32, record->rand32, sizeof(record->rand32));
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001285}
1286
1287static void get_server_hello(tls_state_t *tls)
1288{
1289 struct server_hello {
1290 struct record_hdr xhdr;
1291 uint8_t type;
1292 uint8_t len24_hi, len24_mid, len24_lo;
1293 uint8_t proto_maj, proto_min;
1294 uint8_t rand32[32]; /* first 4 bytes are unix time in BE format */
1295 uint8_t session_id_len;
1296 uint8_t session_id[32];
1297 uint8_t cipherid_hi, cipherid_lo;
1298 uint8_t comprtype;
1299 /* extensions may follow, but only those which client offered in its Hello */
1300 };
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001301
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001302 struct server_hello *hp;
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001303 uint8_t *cipherid;
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001304 unsigned cipher;
1305 int len, len24;
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001306
Denys Vlasenko5b05d9d2017-02-03 18:19:59 +01001307 len = tls_xread_handshake_block(tls, 74 - 32);
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001308
1309 hp = (void*)tls->inbuf;
1310 // 74 bytes:
1311 // 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|
1312 //SvHl len=70 maj.min unixtime^^^ 28randbytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^ slen sid32bytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cipSel comprSel
1313 if (hp->type != HANDSHAKE_SERVER_HELLO
1314 || hp->len24_hi != 0
1315 || hp->len24_mid != 0
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001316 /* hp->len24_lo checked later */
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001317 || hp->proto_maj != TLS_MAJ
1318 || hp->proto_min != TLS_MIN
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001319 ) {
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001320 bad_record_die(tls, "'server hello'", len);
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001321 }
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001322
1323 cipherid = &hp->cipherid_hi;
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001324 len24 = hp->len24_lo;
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001325 if (hp->session_id_len != 32) {
1326 if (hp->session_id_len != 0)
Denys Vlasenko5b05d9d2017-02-03 18:19:59 +01001327 bad_record_die(tls, "'server hello'", len);
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001328
1329 // session_id_len == 0: no session id
1330 // "The server
1331 // may return an empty session_id to indicate that the session will
1332 // not be cached and therefore cannot be resumed."
1333 cipherid -= 32;
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001334 len24 += 32; /* what len would be if session id would be present */
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001335 }
1336
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001337 if (len24 < 70
1338// || cipherid[0] != (CIPHER_ID >> 8)
1339// || cipherid[1] != (CIPHER_ID & 0xff)
1340// || cipherid[2] != 0 /* comprtype */
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001341 ) {
Denys Vlasenko5b05d9d2017-02-03 18:19:59 +01001342 bad_record_die(tls, "'server hello'", len);
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001343 }
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001344 dbg("<< SERVER_HELLO\n");
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001345
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001346 memcpy(tls->hsd->client_and_server_rand32 + 32, hp->rand32, sizeof(hp->rand32));
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001347
1348 tls->cipher_id = cipher = 0x100 * cipherid[0] + cipherid[1];
1349 dbg("server chose cipher %04x\n", cipher);
1350
1351 if (cipher == TLS_RSA_WITH_AES_128_CBC_SHA) {
1352 tls->key_size = AES128_KEYSIZE;
1353 tls->MAC_size = SHA1_OUTSIZE;
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001354 }
1355 else { /* TLS_RSA_WITH_AES_256_CBC_SHA256 */
1356 tls->key_size = AES256_KEYSIZE;
1357 tls->MAC_size = SHA256_OUTSIZE;
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001358 }
Denys Vlasenko89193f92017-01-24 18:08:07 +01001359 /* Handshake hash eventually destined to FINISHED record
1360 * is sha256 regardless of cipher
1361 * (at least for all ciphers defined by RFC5246).
1362 * It's not sha1 for AES_128_CBC_SHA - only MAC is sha1, not this hash.
1363 */
1364 sha256_begin(&tls->hsd->handshake_hash_ctx);
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001365 hash_handshake(tls, ">> client hello hash:%s",
1366 tls->hsd->saved_client_hello, tls->hsd->saved_client_hello_size
1367 );
1368 hash_handshake(tls, "<< server hello hash:%s",
1369 tls->inbuf + RECHDR_LEN, len
1370 );
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001371}
1372
1373static void get_server_cert(tls_state_t *tls)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001374{
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001375 struct record_hdr *xhdr;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001376 uint8_t *certbuf;
1377 int len, len1;
1378
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001379 len = tls_xread_handshake_block(tls, 10);
Denys Vlasenkoc5540d62017-01-15 02:17:03 +01001380
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001381 xhdr = (void*)tls->inbuf;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001382 certbuf = (void*)(xhdr + 1);
1383 if (certbuf[0] != HANDSHAKE_CERTIFICATE)
1384 tls_error_die(tls);
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001385 dbg("<< CERTIFICATE\n");
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001386 // 4392 bytes:
1387 // 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...
1388 //Cert len=4388 ChainLen CertLen^ DER encoded X509 starts here. openssl x509 -in FILE -inform DER -noout -text
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001389 len1 = get24be(certbuf + 1);
1390 if (len1 > len - 4) tls_error_die(tls);
1391 len = len1;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001392 len1 = get24be(certbuf + 4);
1393 if (len1 > len - 3) tls_error_die(tls);
1394 len = len1;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001395 len1 = get24be(certbuf + 7);
1396 if (len1 > len - 3) tls_error_die(tls);
1397 len = len1;
1398
1399 if (len)
Denys Vlasenko11d00962017-01-15 00:12:42 +01001400 find_key_in_der_cert(tls, certbuf + 10, len);
1401}
1402
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01001403static void send_empty_client_cert(tls_state_t *tls)
1404{
1405 struct client_empty_cert {
1406 uint8_t type;
1407 uint8_t len24_hi, len24_mid, len24_lo;
1408 uint8_t cert_chain_len24_hi, cert_chain_len24_mid, cert_chain_len24_lo;
1409 };
1410 struct client_empty_cert *record;
1411
1412 record = tls_get_outbuf(tls, sizeof(*record));
1413//FIXME: can just memcpy a ready-made one.
1414 fill_handshake_record_hdr(record, HANDSHAKE_CERTIFICATE, sizeof(*record));
1415 record->cert_chain_len24_hi = 0;
1416 record->cert_chain_len24_mid = 0;
1417 record->cert_chain_len24_lo = 0;
1418
1419 dbg(">> CERTIFICATE\n");
1420 xwrite_and_update_handshake_hash(tls, sizeof(*record));
1421}
1422
Denys Vlasenko11d00962017-01-15 00:12:42 +01001423static void send_client_key_exchange(tls_state_t *tls)
1424{
Denys Vlasenko11d00962017-01-15 00:12:42 +01001425 struct client_key_exchange {
Denys Vlasenko11d00962017-01-15 00:12:42 +01001426 uint8_t type;
1427 uint8_t len24_hi, len24_mid, len24_lo;
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001428 /* keylen16 exists for RSA (in TLS, not in SSL), but not for some other key types */
1429 uint8_t keylen16_hi, keylen16_lo;
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001430 uint8_t key[4 * 1024]; // size??
Denys Vlasenko11d00962017-01-15 00:12:42 +01001431 };
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001432//FIXME: better size estimate
1433 struct client_key_exchange *record = tls_get_outbuf(tls, sizeof(*record));
Denys Vlasenko38972a82017-01-20 19:11:14 +01001434 uint8_t rsa_premaster[RSA_PREMASTER_SIZE];
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001435 int len;
Denys Vlasenko11d00962017-01-15 00:12:42 +01001436
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001437 tls_get_random(rsa_premaster, sizeof(rsa_premaster));
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001438 if (TLS_DEBUG_FIXED_SECRETS)
1439 memset(rsa_premaster, 0x44, sizeof(rsa_premaster));
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001440 // RFC 5246
1441 // "Note: The version number in the PreMasterSecret is the version
1442 // offered by the client in the ClientHello.client_version, not the
1443 // version negotiated for the connection."
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001444 rsa_premaster[0] = TLS_MAJ;
1445 rsa_premaster[1] = TLS_MIN;
Denys Vlasenko89193f92017-01-24 18:08:07 +01001446 dump_hex("premaster:%s\n", rsa_premaster, sizeof(rsa_premaster));
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001447 len = psRsaEncryptPub(/*pool:*/ NULL,
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001448 /* psRsaKey_t* */ &tls->hsd->server_rsa_pub_key,
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001449 rsa_premaster, /*inlen:*/ sizeof(rsa_premaster),
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001450 record->key, sizeof(record->key),
Denys Vlasenko11d00962017-01-15 00:12:42 +01001451 data_param_ignored
1452 );
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001453 record->keylen16_hi = len >> 8;
1454 record->keylen16_lo = len & 0xff;
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001455 len += 2;
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001456 record->type = HANDSHAKE_CLIENT_KEY_EXCHANGE;
1457 record->len24_hi = 0;
1458 record->len24_mid = len >> 8;
1459 record->len24_lo = len & 0xff;
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001460 len += 4;
Denys Vlasenko11d00962017-01-15 00:12:42 +01001461
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01001462 dbg(">> CLIENT_KEY_EXCHANGE\n");
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001463 xwrite_and_update_handshake_hash(tls, len);
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001464
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001465 // RFC 5246
1466 // For all key exchange methods, the same algorithm is used to convert
1467 // the pre_master_secret into the master_secret. The pre_master_secret
1468 // should be deleted from memory once the master_secret has been
1469 // computed.
1470 // master_secret = PRF(pre_master_secret, "master secret",
1471 // ClientHello.random + ServerHello.random)
1472 // [0..47];
1473 // The master secret is always exactly 48 bytes in length. The length
1474 // of the premaster secret will vary depending on key exchange method.
Denys Vlasenko89193f92017-01-24 18:08:07 +01001475 prf_hmac_sha256(/*tls,*/
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001476 tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001477 rsa_premaster, sizeof(rsa_premaster),
1478 "master secret",
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001479 tls->hsd->client_and_server_rand32, sizeof(tls->hsd->client_and_server_rand32)
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001480 );
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001481 dump_hex("master secret:%s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001482
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001483 // RFC 5246
1484 // 6.3. Key Calculation
1485 //
1486 // The Record Protocol requires an algorithm to generate keys required
1487 // by the current connection state (see Appendix A.6) from the security
1488 // parameters provided by the handshake protocol.
1489 //
1490 // The master secret is expanded into a sequence of secure bytes, which
1491 // is then split to a client write MAC key, a server write MAC key, a
1492 // client write encryption key, and a server write encryption key. Each
1493 // of these is generated from the byte sequence in that order. Unused
1494 // values are empty. Some AEAD ciphers may additionally require a
1495 // client write IV and a server write IV (see Section 6.2.3.3).
1496 //
1497 // When keys and MAC keys are generated, the master secret is used as an
1498 // entropy source.
1499 //
1500 // To generate the key material, compute
1501 //
1502 // key_block = PRF(SecurityParameters.master_secret,
1503 // "key expansion",
1504 // SecurityParameters.server_random +
1505 // SecurityParameters.client_random);
1506 //
1507 // until enough output has been generated. Then, the key_block is
1508 // partitioned as follows:
1509 //
1510 // client_write_MAC_key[SecurityParameters.mac_key_length]
1511 // server_write_MAC_key[SecurityParameters.mac_key_length]
1512 // client_write_key[SecurityParameters.enc_key_length]
1513 // server_write_key[SecurityParameters.enc_key_length]
1514 // client_write_IV[SecurityParameters.fixed_iv_length]
1515 // server_write_IV[SecurityParameters.fixed_iv_length]
1516 {
1517 uint8_t tmp64[64];
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +01001518
1519 /* make "server_rand32 + client_rand32" */
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001520 memcpy(&tmp64[0] , &tls->hsd->client_and_server_rand32[32], 32);
1521 memcpy(&tmp64[32], &tls->hsd->client_and_server_rand32[0] , 32);
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001522
Denys Vlasenko89193f92017-01-24 18:08:07 +01001523 prf_hmac_sha256(/*tls,*/
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001524 tls->client_write_MAC_key, 2 * (tls->MAC_size + tls->key_size),
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +01001525 // also fills:
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001526 // server_write_MAC_key[]
1527 // client_write_key[]
1528 // server_write_key[]
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001529 tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001530 "key expansion",
1531 tmp64, 64
1532 );
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001533 tls->client_write_key = tls->client_write_MAC_key + (2 * tls->MAC_size);
1534 tls->server_write_key = tls->client_write_key + tls->key_size;
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001535 dump_hex("client_write_MAC_key:%s\n",
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001536 tls->client_write_MAC_key, tls->MAC_size
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001537 );
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +01001538 dump_hex("client_write_key:%s\n",
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001539 tls->client_write_key, tls->key_size
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +01001540 );
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001541 }
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001542}
1543
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01001544static const uint8_t rec_CHANGE_CIPHER_SPEC[] = {
1545 RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
1546 01
1547};
1548
Denys Vlasenkoc5540d62017-01-15 02:17:03 +01001549static void send_change_cipher_spec(tls_state_t *tls)
1550{
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001551 dbg(">> CHANGE_CIPHER_SPEC\n");
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001552 xwrite(tls->ofd, rec_CHANGE_CIPHER_SPEC, sizeof(rec_CHANGE_CIPHER_SPEC));
Denys Vlasenkoc5540d62017-01-15 02:17:03 +01001553}
1554
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001555// 7.4.9. Finished
1556// A Finished message is always sent immediately after a change
1557// cipher spec message to verify that the key exchange and
1558// authentication processes were successful. It is essential that a
1559// change cipher spec message be received between the other handshake
1560// messages and the Finished message.
1561//...
1562// The Finished message is the first one protected with the just
1563// negotiated algorithms, keys, and secrets. Recipients of Finished
1564// messages MUST verify that the contents are correct. Once a side
1565// has sent its Finished message and received and validated the
1566// Finished message from its peer, it may begin to send and receive
1567// application data over the connection.
1568//...
1569// struct {
1570// opaque verify_data[verify_data_length];
1571// } Finished;
1572//
1573// verify_data
1574// PRF(master_secret, finished_label, Hash(handshake_messages))
1575// [0..verify_data_length-1];
1576//
1577// finished_label
1578// For Finished messages sent by the client, the string
1579// "client finished". For Finished messages sent by the server,
1580// the string "server finished".
1581//
1582// Hash denotes a Hash of the handshake messages. For the PRF
1583// defined in Section 5, the Hash MUST be the Hash used as the basis
1584// for the PRF. Any cipher suite which defines a different PRF MUST
1585// also define the Hash to use in the Finished computation.
1586//
1587// In previous versions of TLS, the verify_data was always 12 octets
1588// long. In the current version of TLS, it depends on the cipher
1589// suite. Any cipher suite which does not explicitly specify
1590// verify_data_length has a verify_data_length equal to 12. This
1591// includes all existing cipher suites.
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001592static void send_client_finished(tls_state_t *tls)
1593{
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01001594 struct finished {
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001595 uint8_t type;
1596 uint8_t len24_hi, len24_mid, len24_lo;
1597 uint8_t prf_result[12];
1598 };
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001599 struct finished *record = tls_get_outbuf(tls, sizeof(*record));
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001600 uint8_t handshake_hash[TLS_MAX_MAC_SIZE];
1601 unsigned len;
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001602
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001603 fill_handshake_record_hdr(record, HANDSHAKE_FINISHED, sizeof(*record));
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001604
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001605 len = get_handshake_hash(tls, handshake_hash);
Denys Vlasenko89193f92017-01-24 18:08:07 +01001606 prf_hmac_sha256(/*tls,*/
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001607 record->prf_result, sizeof(record->prf_result),
1608 tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
1609 "client finished",
1610 handshake_hash, len
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001611 );
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001612 dump_hex("from secret: %s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001613 dump_hex("from labelSeed: %s", "client finished", sizeof("client finished")-1);
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01001614 dump_hex("%s\n", handshake_hash, sizeof(handshake_hash));
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001615 dump_hex("=> digest: %s\n", record->prf_result, sizeof(record->prf_result));
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001616
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01001617 dbg(">> FINISHED\n");
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001618 xwrite_encrypted(tls, sizeof(*record), RECORD_TYPE_HANDSHAKE);
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001619}
1620
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001621void FAST_FUNC tls_handshake(tls_state_t *tls, const char *sni)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001622{
1623 // Client RFC 5246 Server
1624 // (*) - optional messages, not always sent
1625 //
1626 // ClientHello ------->
1627 // ServerHello
1628 // Certificate*
1629 // ServerKeyExchange*
1630 // CertificateRequest*
1631 // <------- ServerHelloDone
1632 // Certificate*
1633 // ClientKeyExchange
1634 // CertificateVerify*
1635 // [ChangeCipherSpec]
1636 // Finished ------->
1637 // [ChangeCipherSpec]
1638 // <------- Finished
1639 // Application Data <------> Application Data
1640 int len;
1641
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001642 send_client_hello_and_alloc_hsd(tls, sni);
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001643 get_server_hello(tls);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001644
Denys Vlasenko38972a82017-01-20 19:11:14 +01001645 // RFC 5246
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001646 // The server MUST send a Certificate message whenever the agreed-
1647 // upon key exchange method uses certificates for authentication
1648 // (this includes all key exchange methods defined in this document
1649 // except DH_anon). This message will always immediately follow the
1650 // ServerHello message.
1651 //
1652 // IOW: in practice, Certificate *always* follows.
1653 // (for example, kernel.org does not even accept DH_anon cipher id)
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001654 get_server_cert(tls);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001655
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001656 len = tls_xread_handshake_block(tls, 4);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001657 if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_SERVER_KEY_EXCHANGE) {
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001658 // 459 bytes:
1659 // 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...
1660 //SvKey len=455^
Denys Vlasenko11d00962017-01-15 00:12:42 +01001661 // with TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 461 bytes:
1662 // 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...
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001663 dbg("<< SERVER_KEY_EXCHANGE len:%u\n", len);
1664//probably need to save it
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01001665 len = tls_xread_handshake_block(tls, 4);
Denys Vlasenkoc5540d62017-01-15 02:17:03 +01001666 }
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001667
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01001668 if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_CERTIFICATE_REQUEST) {
1669 dbg("<< CERTIFICATE_REQUEST\n");
1670 // RFC 5246: "If no suitable certificate is available,
1671 // the client MUST send a certificate message containing no
1672 // certificates. That is, the certificate_list structure has a
1673 // length of zero. ...
1674 // Client certificates are sent using the Certificate structure
1675 // defined in Section 7.4.2."
1676 // (i.e. the same format as server certs)
1677 send_empty_client_cert(tls);
1678 len = tls_xread_handshake_block(tls, 4);
1679 }
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001680
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01001681 if (tls->inbuf[RECHDR_LEN] != HANDSHAKE_SERVER_HELLO_DONE) {
1682 bad_record_die(tls, "'server hello done'", len);
1683 }
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01001684 // 0e 000000 (len:0)
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001685 dbg("<< SERVER_HELLO_DONE\n");
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01001686
1687 send_client_key_exchange(tls);
1688
1689 send_change_cipher_spec(tls);
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01001690 /* from now on we should send encrypted */
1691 /* tls->write_seq64_be = 0; - already is */
1692 tls->encrypt_on_write = 1;
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01001693
1694 send_client_finished(tls);
1695
1696 /* Get CHANGE_CIPHER_SPEC */
Denys Vlasenko38972a82017-01-20 19:11:14 +01001697 len = tls_xread_record(tls);
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01001698 if (len != 1 || memcmp(tls->inbuf, rec_CHANGE_CIPHER_SPEC, 6) != 0)
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01001699 bad_record_die(tls, "switch to encrypted traffic", len);
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001700 dbg("<< CHANGE_CIPHER_SPEC\n");
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001701 if (tls->cipher_id == TLS_RSA_WITH_NULL_SHA256)
1702 tls->min_encrypted_len_on_read = tls->MAC_size;
Denys Vlasenko89193f92017-01-24 18:08:07 +01001703 else {
1704 unsigned mac_blocks = (unsigned)(tls->MAC_size + AES_BLOCKSIZE-1) / AES_BLOCKSIZE;
1705 /* all incoming packets now should be encrypted and have
1706 * at least IV + (MAC padded to blocksize):
1707 */
1708 tls->min_encrypted_len_on_read = AES_BLOCKSIZE + (mac_blocks * AES_BLOCKSIZE);
1709 dbg("min_encrypted_len_on_read: %u", tls->min_encrypted_len_on_read);
1710 }
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01001711
1712 /* Get (encrypted) FINISHED from the server */
Denys Vlasenko38972a82017-01-20 19:11:14 +01001713 len = tls_xread_record(tls);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001714 if (len < 4 || tls->inbuf[RECHDR_LEN] != HANDSHAKE_FINISHED)
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01001715 tls_error_die(tls);
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001716 dbg("<< FINISHED\n");
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01001717 /* application data can be sent/received */
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001718
1719 /* free handshake data */
1720// if (PARANOIA)
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001721// memset(tls->hsd, 0, tls->hsd->hsd_size);
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001722 free(tls->hsd);
1723 tls->hsd = NULL;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001724}
1725
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001726static void tls_xwrite(tls_state_t *tls, int len)
1727{
1728 dbg(">> DATA\n");
1729 xwrite_encrypted(tls, len, RECORD_TYPE_APPLICATION_DATA);
1730}
1731
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001732// To run a test server using openssl:
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001733// openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01001734// openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1
1735//
1736// Unencryped SHA256 example:
1737// openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
1738// openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL
1739// openssl s_client -connect 127.0.0.1:4433 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL-SHA256
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001740
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001741void FAST_FUNC tls_run_copy_loop(tls_state_t *tls)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001742{
Denys Vlasenko38972a82017-01-20 19:11:14 +01001743 int inbuf_size;
1744 const int INBUF_STEP = 4 * 1024;
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01001745 struct pollfd pfds[2];
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001746
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01001747 pfds[0].fd = STDIN_FILENO;
1748 pfds[0].events = POLLIN;
1749 pfds[1].fd = tls->ifd;
1750 pfds[1].events = POLLIN;
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001751
Denys Vlasenko38972a82017-01-20 19:11:14 +01001752 inbuf_size = INBUF_STEP;
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001753 for (;;) {
1754 int nread;
1755
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01001756 if (safe_poll(pfds, 2, -1) < 0)
1757 bb_perror_msg_and_die("poll");
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001758
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01001759 if (pfds[0].revents) {
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001760 void *buf;
1761
1762 dbg("STDIN HAS DATA\n");
Denys Vlasenko38972a82017-01-20 19:11:14 +01001763 buf = tls_get_outbuf(tls, inbuf_size);
1764 nread = safe_read(STDIN_FILENO, buf, inbuf_size);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001765 if (nread < 1) {
Denys Vlasenko38972a82017-01-20 19:11:14 +01001766 /* We'd want to do this: */
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001767 /* Close outgoing half-connection so they get EOF,
Denys Vlasenko38972a82017-01-20 19:11:14 +01001768 * but leave incoming alone so we can see response
1769 */
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001770 //shutdown(tls->ofd, SHUT_WR);
Denys Vlasenko38972a82017-01-20 19:11:14 +01001771 /* But TLS has no way to encode this,
1772 * doubt it's ok to do it "raw"
1773 */
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01001774 pfds[0].fd = -1;
Denys Vlasenko39161392017-01-20 20:27:06 +01001775 tls_free_outbuf(tls); /* mem usage optimization */
Denys Vlasenko38972a82017-01-20 19:11:14 +01001776 } else {
1777 if (nread == inbuf_size) {
1778 /* TLS has per record overhead, if input comes fast,
1779 * read, encrypt and send bigger chunks
1780 */
1781 inbuf_size += INBUF_STEP;
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001782 if (inbuf_size > TLS_MAX_OUTBUF)
1783 inbuf_size = TLS_MAX_OUTBUF;
Denys Vlasenko38972a82017-01-20 19:11:14 +01001784 }
1785 tls_xwrite(tls, nread);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001786 }
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001787 }
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01001788 if (pfds[1].revents) {
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001789 dbg("NETWORK HAS DATA\n");
Denys Vlasenko38972a82017-01-20 19:11:14 +01001790 read_record:
1791 nread = tls_xread_record(tls);
1792 if (nread < 1) {
1793 /* TLS protocol has no real concept of one-sided shutdowns:
1794 * if we get "TLS EOF" from the peer, writes will fail too
1795 */
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01001796 //pfds[1].fd = -1;
Denys Vlasenko38972a82017-01-20 19:11:14 +01001797 //close(STDOUT_FILENO);
Denys Vlasenko39161392017-01-20 20:27:06 +01001798 //tls_free_inbuf(tls); /* mem usage optimization */
Denys Vlasenko38972a82017-01-20 19:11:14 +01001799 //continue;
1800 break;
1801 }
1802 if (tls->inbuf[0] != RECORD_TYPE_APPLICATION_DATA)
1803 bb_error_msg_and_die("unexpected record type %d", tls->inbuf[0]);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001804 xwrite(STDOUT_FILENO, tls->inbuf + RECHDR_LEN, nread);
Denys Vlasenko38972a82017-01-20 19:11:14 +01001805 /* We may already have a complete next record buffered,
1806 * can process it without network reads (and possible blocking)
1807 */
1808 if (tls_has_buffered_record(tls))
1809 goto read_record;
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001810 }
1811 }
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001812}