blob: 8bcaee9a6f885abfe364fc3c7cb4fc774aa7b341 [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
7//config: bool "tls (debugging)"
8//config: default n
9
10//applet:IF_TLS(APPLET(tls, BB_DIR_USR_BIN, BB_SUID_DROP))
11
12//kbuild:lib-$(CONFIG_TLS) += tls.o
Denys Vlasenko11d00962017-01-15 00:12:42 +010013//kbuild:lib-$(CONFIG_TLS) += tls_pstm.o
14//kbuild:lib-$(CONFIG_TLS) += tls_pstm_montgomery_reduce.o
15//kbuild:lib-$(CONFIG_TLS) += tls_pstm_mul_comba.o
16//kbuild:lib-$(CONFIG_TLS) += tls_pstm_sqr_comba.o
17//kbuild:lib-$(CONFIG_TLS) += tls_rsa.o
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010018////kbuild:lib-$(CONFIG_TLS) += tls_ciphers.o
19////kbuild:lib-$(CONFIG_TLS) += tls_aes.o
20////kbuild:lib-$(CONFIG_TLS) += tls_aes_gcm.o
21
22//usage:#define tls_trivial_usage
23//usage: "HOST[:PORT]"
24//usage:#define tls_full_usage "\n\n"
25
Denys Vlasenko11d00962017-01-15 00:12:42 +010026#include "tls.h"
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010027
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +010028#define TLS_DEBUG 2
29
30#if TLS_DEBUG
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010031# define dbg(...) fprintf(stderr, __VA_ARGS__)
32#else
33# define dbg(...) ((void)0)
34#endif
35
Denys Vlasenko11d00962017-01-15 00:12:42 +010036#define RECORD_TYPE_CHANGE_CIPHER_SPEC 20
37#define RECORD_TYPE_ALERT 21
38#define RECORD_TYPE_HANDSHAKE 22
39#define RECORD_TYPE_APPLICATION_DATA 23
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010040
Denys Vlasenko11d00962017-01-15 00:12:42 +010041#define HANDSHAKE_HELLO_REQUEST 0
42#define HANDSHAKE_CLIENT_HELLO 1
43#define HANDSHAKE_SERVER_HELLO 2
44#define HANDSHAKE_HELLO_VERIFY_REQUEST 3
45#define HANDSHAKE_NEW_SESSION_TICKET 4
46#define HANDSHAKE_CERTIFICATE 11
47#define HANDSHAKE_SERVER_KEY_EXCHANGE 12
48#define HANDSHAKE_CERTIFICATE_REQUEST 13
49#define HANDSHAKE_SERVER_HELLO_DONE 14
50#define HANDSHAKE_CERTIFICATE_VERIFY 15
51#define HANDSHAKE_CLIENT_KEY_EXCHANGE 16
52#define HANDSHAKE_FINISHED 20
53
54#define SSL_HS_RANDOM_SIZE 32
55#define SSL_HS_RSA_PREMASTER_SIZE 48
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010056
57#define SSL_NULL_WITH_NULL_NULL 0x0000
58#define SSL_RSA_WITH_NULL_MD5 0x0001
59#define SSL_RSA_WITH_NULL_SHA 0x0002
60#define SSL_RSA_WITH_RC4_128_MD5 0x0004
61#define SSL_RSA_WITH_RC4_128_SHA 0x0005
62#define SSL_RSA_WITH_3DES_EDE_CBC_SHA 0x000A /* 10 */
63#define TLS_RSA_WITH_AES_128_CBC_SHA 0x002F /* 47 */
64#define TLS_RSA_WITH_AES_256_CBC_SHA 0x0035 /* 53 */
Denys Vlasenko9a6897a2017-01-16 23:26:33 +010065#define TLS_RSA_WITH_NULL_SHA256 0x003B /* 59 */
66
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010067#define TLS_EMPTY_RENEGOTIATION_INFO_SCSV 0x00FF
68
69#define TLS_RSA_WITH_IDEA_CBC_SHA 0x0007 /* 7 */
70#define SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA 0x0016 /* 22 */
71#define SSL_DH_anon_WITH_RC4_128_MD5 0x0018 /* 24 */
72#define SSL_DH_anon_WITH_3DES_EDE_CBC_SHA 0x001B /* 27 */
73#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA 0x0033 /* 51 */
74#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA 0x0039 /* 57 */
75#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 0x0067 /* 103 */
76#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 0x006B /* 107 */
77#define TLS_DH_anon_WITH_AES_128_CBC_SHA 0x0034 /* 52 */
78#define TLS_DH_anon_WITH_AES_256_CBC_SHA 0x003A /* 58 */
79#define TLS_RSA_WITH_AES_128_CBC_SHA256 0x003C /* 60 */
80#define TLS_RSA_WITH_AES_256_CBC_SHA256 0x003D /* 61 */
81#define TLS_RSA_WITH_SEED_CBC_SHA 0x0096 /* 150 */
82#define TLS_PSK_WITH_AES_128_CBC_SHA 0x008C /* 140 */
83#define TLS_PSK_WITH_AES_128_CBC_SHA256 0x00AE /* 174 */
84#define TLS_PSK_WITH_AES_256_CBC_SHA384 0x00AF /* 175 */
85#define TLS_PSK_WITH_AES_256_CBC_SHA 0x008D /* 141 */
86#define TLS_DHE_PSK_WITH_AES_128_CBC_SHA 0x0090 /* 144 */
87#define TLS_DHE_PSK_WITH_AES_256_CBC_SHA 0x0091 /* 145 */
88#define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0xC004 /* 49156 */
89#define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0xC005 /* 49157 */
90#define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0xC009 /* 49161 */
91#define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0xC00A /* 49162 */
92#define TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA 0xC012 /* 49170 */
93#define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA 0xC013 /* 49171 */
94#define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA 0xC014 /* 49172 */
95#define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA 0xC00E /* 49166 */
96#define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA 0xC00F /* 49167 */
97#define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023 /* 49187 */
98#define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 0xC024 /* 49188 */
99#define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 0xC025 /* 49189 */
100#define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 0xC026 /* 49190 */
101#define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 0xC027 /* 49191 */
102#define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 0xC028 /* 49192 */
103#define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 0xC029 /* 49193 */
104#define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 0xC02A /* 49194 */
105
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100106// RFC 5288 "AES Galois Counter Mode (GCM) Cipher Suites for TLS"
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100107#define TLS_RSA_WITH_AES_128_GCM_SHA256 0x009C /* 156 */
108#define TLS_RSA_WITH_AES_256_GCM_SHA384 0x009D /* 157 */
109#define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B /* 49195 */
110#define TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0xC02C /* 49196 */
111#define TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0xC02D /* 49197 */
112#define TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0xC02E /* 49198 */
113#define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xC02F /* 49199 */
114#define TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0xC030 /* 49200 */
115#define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 0xC031 /* 49201 */
116#define TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 0xC032 /* 49202 */
117
118//Tested against kernel.org:
119//TLS 1.1
120//#define TLS_MAJ 3
121//#define TLS_MIN 2
122//#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA // ok, recvs SERVER_KEY_EXCHANGE
123//TLS 1.2
124#define TLS_MAJ 3
125#define TLS_MIN 3
Denys Vlasenko11d00962017-01-15 00:12:42 +0100126//#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA // ok, recvs SERVER_KEY_EXCHANGE *** matrixssl uses this on my box
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100127//#define CIPHER_ID TLS_RSA_WITH_AES_256_CBC_SHA256 // ok, no SERVER_KEY_EXCHANGE
128// All GCMs:
129//#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 // SSL_ALERT_HANDSHAKE_FAILURE
130//#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
131//#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 // ok, recvs SERVER_KEY_EXCHANGE
132//#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
133//#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
134//#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
135//#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
136//#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
137//#define CIPHER_ID TLS_RSA_WITH_AES_256_GCM_SHA384 // ok, no SERVER_KEY_EXCHANGE
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100138//#define CIPHER_ID TLS_RSA_WITH_AES_128_GCM_SHA256 // ok, no SERVER_KEY_EXCHANGE *** select this?
139#define CIPHER_ID TLS_RSA_WITH_NULL_SHA256 // for testing (does everything except encrypting)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100140//#define CIPHER_ID TLS_DH_anon_WITH_AES_256_CBC_SHA // SSL_ALERT_HANDSHAKE_FAILURE
Denys Vlasenko11d00962017-01-15 00:12:42 +0100141//^^^^^^^^^^^^^^^^^^^^^^^ (tested b/c this one doesn't req server certs... no luck)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100142//test TLS_RSA_WITH_AES_128_CBC_SHA, in tls 1.2 it's mandated to be always supported
143
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100144enum {
145 SHA256_INSIZE = 64,
146 SHA256_OUTSIZE = 32,
147};
148
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100149struct record_hdr {
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100150 uint8_t type;
151 uint8_t proto_maj, proto_min;
152 uint8_t len16_hi, len16_lo;
153};
154
155typedef struct tls_state {
156 int fd;
157
Denys Vlasenko11d00962017-01-15 00:12:42 +0100158 psRsaKey_t server_rsa_pub_key;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100159
Denys Vlasenko936e83e2017-01-16 04:25:01 +0100160 sha256_ctx_t handshake_sha256_ctx;
161
162 uint8_t client_and_server_rand32[2 * 32];
163 uint8_t master_secret[48];
164
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100165 uint8_t encrypt_on_write;
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +0100166 uint8_t decrypt_on_read;
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100167 uint8_t client_write_MAC_key[SHA256_OUTSIZE];
168// RFC 5246
169// sequence number
170// Each connection state contains a sequence number, which is
171// maintained separately for read and write states. The sequence
172// number MUST be set to zero whenever a connection state is made the
173// active state. Sequence numbers are of type uint64 and may not
174// exceed 2^64-1.
175 uint64_t write_seq64_be;
176
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100177 // RFC 5246
178 // |6.2.1. Fragmentation
179 // | The record layer fragments information blocks into TLSPlaintext
180 // | records carrying data in chunks of 2^14 bytes or less. Client
181 // | message boundaries are not preserved in the record layer (i.e.,
182 // | multiple client messages of the same ContentType MAY be coalesced
183 // | into a single TLSPlaintext record, or a single message MAY be
184 // | fragmented across several records)
185 // |...
186 // | length
187 // | The length (in bytes) of the following TLSPlaintext.fragment.
188 // | The length MUST NOT exceed 2^14.
189 // |...
190 // | 6.2.2. Record Compression and Decompression
191 // |...
192 // | Compression must be lossless and may not increase the content length
193 // | by more than 1024 bytes. If the decompression function encounters a
194 // | TLSCompressed.fragment that would decompress to a length in excess of
195 // | 2^14 bytes, it MUST report a fatal decompression failure error.
196 // |...
197 // | length
198 // | The length (in bytes) of the following TLSCompressed.fragment.
199 // | The length MUST NOT exceed 2^14 + 1024.
200 //
201 // Since our buffer also contains 5-byte headers, make it a bit bigger:
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100202 int insize;
203 int tail;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100204 uint8_t inbuf[18*1024];
205} tls_state_t;
206
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100207
208static unsigned get24be(const uint8_t *p)
209{
210 return 0x100*(0x100*p[0] + p[1]) + p[2];
211}
212
213#if TLS_DEBUG
214static void dump_hex(const char *fmt, const void *vp, int len)
215{
216 char hexbuf[32 * 1024 + 4];
217 const uint8_t *p = vp;
218
219 bin2hex(hexbuf, (void*)p, len)[0] = '\0';
220 dbg(fmt, hexbuf);
221}
222
223static void dump_tls_record(const void *vp, int len)
224{
225 const uint8_t *p = vp;
226
227 while (len > 0) {
228 unsigned xhdr_len;
229 if (len < 5) {
230 dump_hex("< |%s|\n", p, len);
231 return;
232 }
233 xhdr_len = 0x100*p[3] + p[4];
234 dbg("< hdr_type:%u ver:%u.%u len:%u", p[0], p[1], p[2], xhdr_len);
235 p += 5;
236 len -= 5;
237 if (len >= 4 && p[-5] == RECORD_TYPE_HANDSHAKE) {
238 unsigned len24 = get24be(p + 1);
239 dbg(" type:%u len24:%u", p[0], len24);
240 }
241 if (xhdr_len > len)
242 xhdr_len = len;
243 dump_hex(" |%s|\n", p, xhdr_len);
244 p += xhdr_len;
245 len -= xhdr_len;
246 }
247}
248#endif
249
Denys Vlasenko11d00962017-01-15 00:12:42 +0100250void tls_get_random(void *buf, unsigned len)
251{
252 if (len != open_read_close("/dev/urandom", buf, len))
253 xfunc_die();
254}
255
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100256//TODO rename this to sha256_hash, and sha256_hash -> sha256_update
257static void hash_sha256(uint8_t out[SHA256_OUTSIZE], const void *data, unsigned size)
258{
259 sha256_ctx_t ctx;
260 sha256_begin(&ctx);
261 sha256_hash(&ctx, data, size);
262 sha256_end(&ctx, out);
263}
264
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100265/* Nondestructively see the current hash value */
266static void sha256_peek(sha256_ctx_t *ctx, void *buffer)
267{
268 sha256_ctx_t ctx_copy = *ctx;
269 sha256_end(&ctx_copy, buffer);
270}
271
Denys Vlasenko5d1662e2017-01-17 18:17:27 +0100272#if TLS_DEBUG >= 2
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100273static void sha256_hash_dbg(const char *fmt, sha256_ctx_t *ctx, const void *buffer, size_t len)
274{
275 uint8_t h[SHA256_OUTSIZE];
276
277 sha256_hash(ctx, buffer, len);
278 dump_hex(fmt, buffer, len);
279 dbg(" (%u) ", (int)len);
280 sha256_peek(ctx, h);
281 dump_hex("%s\n", h, SHA256_OUTSIZE);
282}
283#else
284# define sha256_hash_dbg(fmt, ctx, buffer, len) \
285 sha256_hash(ctx, buffer, len)
286#endif /* not TLS_DEBUG >= 2 */
287
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100288// RFC 2104
289// HMAC(key, text) based on a hash H (say, sha256) is:
290// ipad = [0x36 x INSIZE]
291// opad = [0x5c x INSIZE]
292// HMAC(key, text) = H((key XOR opad) + H((key XOR ipad) + text))
293//
294// H(key XOR opad) and H(key XOR ipad) can be precomputed
295// if we often need HMAC hmac with the same key.
296//
297// text is often given in disjoint pieces.
298static void hmac_sha256_precomputed_v(uint8_t out[SHA256_OUTSIZE],
299 sha256_ctx_t *hashed_key_xor_ipad,
300 sha256_ctx_t *hashed_key_xor_opad,
301 va_list va)
302{
303 uint8_t *text;
304
305 /* hashed_key_xor_ipad contains unclosed "H((key XOR ipad) +" state */
306 /* hashed_key_xor_opad contains unclosed "H((key XOR opad) +" state */
307
308 /* calculate out = H((key XOR ipad) + text) */
309 while ((text = va_arg(va, uint8_t*)) != NULL) {
310 unsigned text_size = va_arg(va, unsigned);
311 sha256_hash(hashed_key_xor_ipad, text, text_size);
312 }
313 sha256_end(hashed_key_xor_ipad, out);
314
315 /* out = H((key XOR opad) + out) */
316 sha256_hash(hashed_key_xor_opad, out, SHA256_OUTSIZE);
317 sha256_end(hashed_key_xor_opad, out);
318}
319
320static void hmac_sha256(uint8_t out[SHA256_OUTSIZE], uint8_t *key, unsigned key_size, ...)
321{
322 sha256_ctx_t hashed_key_xor_ipad;
323 sha256_ctx_t hashed_key_xor_opad;
324 uint8_t key_xor_ipad[SHA256_INSIZE];
325 uint8_t key_xor_opad[SHA256_INSIZE];
326 uint8_t tempkey[SHA256_OUTSIZE];
327 va_list va;
328 int i;
329
330 va_start(va, key_size);
331
332 // "The authentication key can be of any length up to INSIZE, the
333 // block length of the hash function. Applications that use keys longer
334 // than INSIZE bytes will first hash the key using H and then use the
335 // resultant OUTSIZE byte string as the actual key to HMAC."
336 if (key_size > SHA256_INSIZE) {
337 hash_sha256(tempkey, key, key_size);
338 key = tempkey;
339 key_size = SHA256_OUTSIZE;
340 }
341
342 for (i = 0; i < key_size; i++) {
343 key_xor_ipad[i] = key[i] ^ 0x36;
344 key_xor_opad[i] = key[i] ^ 0x5c;
345 }
346 for (; i < SHA256_INSIZE; i++) {
347 key_xor_ipad[i] = 0x36;
348 key_xor_opad[i] = 0x5c;
349 }
350 sha256_begin(&hashed_key_xor_ipad);
351 sha256_hash(&hashed_key_xor_ipad, key_xor_ipad, SHA256_INSIZE);
352 sha256_begin(&hashed_key_xor_opad);
353 sha256_hash(&hashed_key_xor_opad, key_xor_opad, SHA256_INSIZE);
354
355 hmac_sha256_precomputed_v(out, &hashed_key_xor_ipad, &hashed_key_xor_opad, va);
356 va_end(va);
357}
358
359// RFC 5246:
360// 5. HMAC and the Pseudorandom Function
361//...
362// In this section, we define one PRF, based on HMAC. This PRF with the
363// SHA-256 hash function is used for all cipher suites defined in this
364// document and in TLS documents published prior to this document when
365// TLS 1.2 is negotiated.
366//...
367// P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
368// HMAC_hash(secret, A(2) + seed) +
369// HMAC_hash(secret, A(3) + seed) + ...
370// where + indicates concatenation.
371// A() is defined as:
372// A(0) = seed
373// A(1) = HMAC_hash(secret, A(0)) = HMAC_hash(secret, seed)
374// A(i) = HMAC_hash(secret, A(i-1))
375// P_hash can be iterated as many times as necessary to produce the
376// required quantity of data. For example, if P_SHA256 is being used to
377// create 80 bytes of data, it will have to be iterated three times
378// (through A(3)), creating 96 bytes of output data; the last 16 bytes
379// of the final iteration will then be discarded, leaving 80 bytes of
380// output data.
381//
382// TLS's PRF is created by applying P_hash to the secret as:
383//
384// PRF(secret, label, seed) = P_<hash>(secret, label + seed)
385//
386// The label is an ASCII string.
Denys Vlasenko5d1662e2017-01-17 18:17:27 +0100387static void prf_hmac_sha256(
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100388 uint8_t *outbuf, unsigned outbuf_size,
389 uint8_t *secret, unsigned secret_size,
390 const char *label,
391 uint8_t *seed, unsigned seed_size)
392{
393 uint8_t a[SHA256_OUTSIZE];
394 uint8_t *out_p = outbuf;
395 unsigned label_size = strlen(label);
396
397 /* In P_hash() calculation, "seed" is "label + seed": */
398#define SEED label, label_size, seed, seed_size
399#define SECRET secret, secret_size
400#define A a, (int)(sizeof(a))
401
402 /* A(1) = HMAC_hash(secret, seed) */
403 hmac_sha256(a, SECRET, SEED, NULL);
404//TODO: convert hmac_sha256 to precomputed
405
406 for(;;) {
407 /* HMAC_hash(secret, A(1) + seed) */
408 if (outbuf_size <= SHA256_OUTSIZE) {
409 /* Last, possibly incomplete, block */
410 /* (use a[] as temp buffer) */
411 hmac_sha256(a, SECRET, A, SEED, NULL);
412 memcpy(out_p, a, outbuf_size);
413 return;
414 }
415 /* Not last block. Store directly to result buffer */
416 hmac_sha256(out_p, SECRET, A, SEED, NULL);
417 out_p += SHA256_OUTSIZE;
418 outbuf_size -= SHA256_OUTSIZE;
419 /* A(2) = HMAC_hash(secret, A(1)) */
420 hmac_sha256(a, SECRET, A, NULL);
421 }
422#undef A
423#undef SECRET
424#undef SEED
425}
426
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100427static
428tls_state_t *new_tls_state(void)
429{
430 tls_state_t *tls = xzalloc(sizeof(*tls));
431 tls->fd = -1;
Denys Vlasenko936e83e2017-01-16 04:25:01 +0100432 sha256_begin(&tls->handshake_sha256_ctx);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100433 return tls;
434}
435
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100436static void tls_error_die(tls_state_t *tls)
Denys Vlasenko936e83e2017-01-16 04:25:01 +0100437{
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100438 dump_tls_record(tls->inbuf, tls->insize + tls->tail);
439 xfunc_die();
440}
441
442// RFC 5246
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100443// 6.2.3.1. Null or Standard Stream Cipher
444//
445// Stream ciphers (including BulkCipherAlgorithm.null; see Appendix A.6)
446// convert TLSCompressed.fragment structures to and from stream
447// TLSCiphertext.fragment structures.
448//
449// stream-ciphered struct {
450// opaque content[TLSCompressed.length];
451// opaque MAC[SecurityParameters.mac_length];
452// } GenericStreamCipher;
453//
454// The MAC is generated as:
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100455// MAC(MAC_write_key, seq_num +
456// TLSCompressed.type +
457// TLSCompressed.version +
458// TLSCompressed.length +
459// TLSCompressed.fragment);
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100460// where "+" denotes concatenation.
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100461// seq_num
462// The sequence number for this record.
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100463// MAC
464// The MAC algorithm specified by SecurityParameters.mac_algorithm.
465//
466// Note that the MAC is computed before encryption. The stream cipher
467// encrypts the entire block, including the MAC.
468//...
469// Appendix C. Cipher Suite Definitions
470//...
471// Key IV Block
472// Cipher Type Material Size Size
473// ------------ ------ -------- ---- -----
474// NULL Stream 0 0 N/A
475// RC4_128 Stream 16 0 N/A
476// 3DES_EDE_CBC Block 24 8 8
477// AES_128_CBC Block 16 16 16
478// AES_256_CBC Block 32 16 16
479//
480// MAC Algorithm mac_length mac_key_length
481// -------- ----------- ---------- --------------
482// NULL N/A 0 0
483// MD5 HMAC-MD5 16 16
484// SHA HMAC-SHA1 20 20
485// SHA256 HMAC-SHA256 32 32
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100486static void xwrite_and_hash(tls_state_t *tls, /*const*/ void *buf, unsigned size)
487{
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100488 uint8_t mac_hash[SHA256_OUTSIZE];
489 struct record_hdr *xhdr = buf;
490
491 if (tls->encrypt_on_write) {
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100492//TODO: convert hmac_sha256 to precomputed
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100493 hmac_sha256(mac_hash,
494 tls->client_write_MAC_key, sizeof(tls->client_write_MAC_key),
495 &tls->write_seq64_be, sizeof(tls->write_seq64_be),
496 buf, size,
497 NULL);
498 tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(tls->write_seq64_be));
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100499 /* Temporarily change for writing */
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100500 xhdr->len16_lo += SHA256_OUTSIZE;
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100501 }
502
Denys Vlasenko936e83e2017-01-16 04:25:01 +0100503 xwrite(tls->fd, buf, size);
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100504 dbg("wrote %u bytes\n", size);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100505
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100506 if (tls->encrypt_on_write) {
507 xwrite(tls->fd, mac_hash, sizeof(mac_hash));
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100508 dbg("wrote %u bytes of hash\n", (int)sizeof(mac_hash));
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100509 xhdr->len16_lo -= SHA256_OUTSIZE;
510 }
511
512 /* Handshake hash does not include record headers */
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100513 if (size > 5 && xhdr->type == RECORD_TYPE_HANDSHAKE) {
514 sha256_hash_dbg(">> sha256:%s", &tls->handshake_sha256_ctx, (uint8_t*)buf + 5, size - 5);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100515 }
516}
517
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100518static int xread_tls_block(tls_state_t *tls)
519{
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100520 struct record_hdr *xhdr;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100521 int len;
522 int total;
523 int target;
524
525 dbg("insize:%u tail:%u\n", tls->insize, tls->tail);
526 memmove(tls->inbuf, tls->inbuf + tls->insize, tls->tail);
527 errno = 0;
528 total = tls->tail;
529 target = sizeof(tls->inbuf);
530 for (;;) {
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100531 if (total >= sizeof(*xhdr) && target == sizeof(tls->inbuf)) {
532 xhdr = (void*)tls->inbuf;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100533 target = sizeof(*xhdr) + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100534 if (target >= sizeof(tls->inbuf)) {
535 /* malformed input (too long): yell and die */
536 tls->tail = 0;
537 tls->insize = total;
538 tls_error_die(tls);
539 }
540 // can also check type/proto_maj/proto_min here
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100541 }
542 /* if total >= target, we have a full packet (and possibly more)... */
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100543 if (total - target >= 0)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100544 break;
545 len = safe_read(tls->fd, tls->inbuf + total, sizeof(tls->inbuf) - total);
546 if (len <= 0)
547 bb_perror_msg_and_die("short read");
548 total += len;
549 }
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100550 tls->tail = total - target;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100551 tls->insize = target;
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100552 target -= sizeof(*xhdr);
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100553
554 /* RFC 5246 is not saying it explicitly, but sha256 hash
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100555 * in our FINISHED record must include data of incoming packets too!
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100556 */
557 if (tls->inbuf[0] == RECORD_TYPE_HANDSHAKE) {
558 sha256_hash_dbg("<< sha256:%s", &tls->handshake_sha256_ctx, tls->inbuf + 5, target);
559 }
560
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100561 dbg("got block len:%u\n", target);
562 return target;
563}
564
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100565/*
566 * DER parsing routines
567 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100568static unsigned get_der_len(uint8_t **bodyp, uint8_t *der, uint8_t *end)
569{
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +0100570 unsigned len, len1;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100571
572 if (end - der < 2)
573 xfunc_die();
574// if ((der[0] & 0x1f) == 0x1f) /* not single-byte item code? */
575// xfunc_die();
576
577 len = der[1]; /* maybe it's short len */
578 if (len >= 0x80) {
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100579 /* no, it's long */
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +0100580
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100581 if (len == 0x80 || end - der < (int)(len - 0x7e)) {
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100582 /* 0x80 is "0 bytes of len", invalid DER: must use short len if can */
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100583 /* need 3 or 4 bytes for 81, 82 */
584 xfunc_die();
585 }
586
587 len1 = der[2]; /* if (len == 0x81) it's "ii 81 xx", fetch xx */
588 if (len > 0x82) {
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100589 /* >0x82 is "3+ bytes of len", should not happen realistically */
590 xfunc_die();
591 }
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100592 if (len == 0x82) { /* it's "ii 82 xx yy" */
593 len1 = 0x100*len1 + der[3];
594 der += 1; /* skip [yy] */
595 }
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +0100596 der += 1; /* skip [xx] */
597 len = len1;
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100598// if (len < 0x80)
599// xfunc_die(); /* invalid DER: must use short len if can */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100600 }
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +0100601 der += 2; /* skip [code]+[1byte] */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100602
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +0100603 if (end - der < (int)len)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100604 xfunc_die();
605 *bodyp = der;
606
607 return len;
608}
609
610static uint8_t *enter_der_item(uint8_t *der, uint8_t **endp)
611{
612 uint8_t *new_der;
613 unsigned len = get_der_len(&new_der, der, *endp);
614 dbg("entered der @%p:0x%02x len:%u inner_byte @%p:0x%02x\n", der, der[0], len, new_der, new_der[0]);
615 /* Move "end" position to cover only this item */
616 *endp = new_der + len;
617 return new_der;
618}
619
620static uint8_t *skip_der_item(uint8_t *der, uint8_t *end)
621{
622 uint8_t *new_der;
623 unsigned len = get_der_len(&new_der, der, end);
624 /* Skip body */
625 new_der += len;
626 dbg("skipped der 0x%02x, next byte 0x%02x\n", der[0], new_der[0]);
627 return new_der;
628}
629
Denys Vlasenko11d00962017-01-15 00:12:42 +0100630static void der_binary_to_pstm(pstm_int *pstm_n, uint8_t *der, uint8_t *end)
631{
Denys Vlasenkof78ad092017-01-15 00:18:22 +0100632 uint8_t *bin_ptr;
633 unsigned len = get_der_len(&bin_ptr, der, end);
Denys Vlasenko11d00962017-01-15 00:12:42 +0100634
635 dbg("binary bytes:%u, first:0x%02x\n", len, bin_ptr[0]);
636 pstm_init_for_read_unsigned_bin(/*pool:*/ NULL, pstm_n, len);
637 pstm_read_unsigned_bin(pstm_n, bin_ptr, len);
638 //return bin + len;
639}
640
641static void find_key_in_der_cert(tls_state_t *tls, uint8_t *der, int len)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100642{
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100643/* Certificate is a DER-encoded data structure. Each DER element has a length,
644 * which makes it easy to skip over large compound elements of any complexity
645 * without parsing them. Example: partial decode of kernel.org certificate:
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100646 * SEQ 0x05ac/1452 bytes (Certificate): 308205ac
647 * SEQ 0x0494/1172 bytes (tbsCertificate): 30820494
648 * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0] 3 bytes: a003
649 * INTEGER (version): 0201 02
650 * INTEGER 0x11 bytes (serialNumber): 0211 00 9f85bf664b0cddafca508679501b2be4
651 * //^^^^^^note: matrixSSL also allows [ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2] = 0x82 type
652 * SEQ 0x0d bytes (signatureAlgo): 300d
653 * OID 9 bytes: 0609 2a864886f70d01010b (OID_SHA256_RSA_SIG 42.134.72.134.247.13.1.1.11)
654 * NULL: 0500
655 * SEQ 0x5f bytes (issuer): 305f
656 * SET 11 bytes: 310b
657 * SEQ 9 bytes: 3009
658 * OID 3 bytes: 0603 550406
659 * Printable string "FR": 1302 4652
660 * SET 14 bytes: 310e
661 * SEQ 12 bytes: 300c
662 * OID 3 bytes: 0603 550408
663 * Printable string "Paris": 1305 5061726973
664 * SET 14 bytes: 310e
665 * SEQ 12 bytes: 300c
666 * OID 3 bytes: 0603 550407
667 * Printable string "Paris": 1305 5061726973
668 * SET 14 bytes: 310e
669 * SEQ 12 bytes: 300c
670 * OID 3 bytes: 0603 55040a
671 * Printable string "Gandi": 1305 47616e6469
672 * SET 32 bytes: 3120
673 * SEQ 30 bytes: 301e
674 * OID 3 bytes: 0603 550403
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100675 * Printable string "Gandi Standard SSL CA 2": 1317 47616e6469205374616e646172642053534c2043412032
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100676 * SEQ 30 bytes (validity): 301e
677 * TIME "161011000000Z": 170d 3136313031313030303030305a
678 * TIME "191011235959Z": 170d 3139313031313233353935395a
679 * SEQ 0x5b/91 bytes (subject): 305b //I did not decode this
680 * 3121301f060355040b1318446f6d61696e20436f
681 * 6e74726f6c2056616c6964617465643121301f06
682 * 0355040b1318506f73697469766553534c204d75
683 * 6c74692d446f6d61696e31133011060355040313
684 * 0a6b65726e656c2e6f7267
685 * SEQ 0x01a2/418 bytes (subjectPublicKeyInfo): 308201a2
686 * SEQ 13 bytes (algorithm): 300d
687 * OID 9 bytes: 0609 2a864886f70d010101 (OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1)
688 * NULL: 0500
689 * BITSTRING 0x018f/399 bytes (publicKey): 0382018f
690 * ????: 00
691 * //after the zero byte, it appears key itself uses DER encoding:
692 * SEQ 0x018a/394 bytes: 3082018a
693 * INTEGER 0x0181/385 bytes (modulus): 02820181
694 * 00b1ab2fc727a3bef76780c9349bf3
695 * ...24 more blocks of 15 bytes each...
696 * 90e895291c6bc8693b65
697 * INTEGER 3 bytes (exponent): 0203 010001
698 * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0x3] 0x01e5 bytes (X509v3 extensions): a38201e5
699 * SEQ 0x01e1 bytes: 308201e1
700 * ...
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100701 * Certificate is a sequence of three elements:
702 * tbsCertificate (SEQ)
703 * signatureAlgorithm (AlgorithmIdentifier)
704 * signatureValue (BIT STRING)
705 *
706 * In turn, tbsCertificate is a sequence of:
707 * version
708 * serialNumber
709 * signatureAlgo (AlgorithmIdentifier)
710 * issuer (Name, has complex structure)
711 * validity (Validity, SEQ of two Times)
712 * subject (Name)
713 * subjectPublicKeyInfo (SEQ)
714 * ...
715 *
716 * subjectPublicKeyInfo is a sequence of:
717 * algorithm (AlgorithmIdentifier)
718 * publicKey (BIT STRING)
719 *
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100720 * We need Certificate.tbsCertificate.subjectPublicKeyInfo.publicKey
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100721 */
722 uint8_t *end = der + len;
723
724 /* enter "Certificate" item: [der, end) will be only Cert */
725 der = enter_der_item(der, &end);
726
727 /* enter "tbsCertificate" item: [der, end) will be only tbsCert */
728 der = enter_der_item(der, &end);
729
730 /* skip up to subjectPublicKeyInfo */
731 der = skip_der_item(der, end); /* version */
732 der = skip_der_item(der, end); /* serialNumber */
733 der = skip_der_item(der, end); /* signatureAlgo */
734 der = skip_der_item(der, end); /* issuer */
735 der = skip_der_item(der, end); /* validity */
736 der = skip_der_item(der, end); /* subject */
737
Denys Vlasenko11d00962017-01-15 00:12:42 +0100738 /* enter subjectPublicKeyInfo */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100739 der = enter_der_item(der, &end);
Denys Vlasenko11d00962017-01-15 00:12:42 +0100740 { /* check subjectPublicKeyInfo.algorithm */
741 static const uint8_t expected[] = {
742 0x30,0x0d, // SEQ 13 bytes
743 0x06,0x09, 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01, // OID RSA_KEY_ALG 42.134.72.134.247.13.1.1.1
744 //0x05,0x00, // NULL
745 };
746 if (memcmp(der, expected, sizeof(expected)) != 0)
747 bb_error_msg_and_die("not RSA key");
748 }
749 /* skip subjectPublicKeyInfo.algorithm */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100750 der = skip_der_item(der, end);
Denys Vlasenko11d00962017-01-15 00:12:42 +0100751 /* enter subjectPublicKeyInfo.publicKey */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100752// die_if_not_this_der_type(der, end, 0x03); /* must be BITSTRING */
753 der = enter_der_item(der, &end);
754
Denys Vlasenko11d00962017-01-15 00:12:42 +0100755 /* parse RSA key: */
756//based on getAsnRsaPubKey(), pkcs1ParsePrivBin() is also of note
757 dbg("key bytes:%u, first:0x%02x\n", (int)(end - der), der[0]);
758 if (end - der < 14) xfunc_die();
759 /* example format:
760 * ignore bits: 00
761 * SEQ 0x018a/394 bytes: 3082018a
762 * INTEGER 0x0181/385 bytes (modulus): 02820181 XX...XXX
763 * INTEGER 3 bytes (exponent): 0203 010001
764 */
765 if (*der != 0) /* "ignore bits", should be 0 */
766 xfunc_die();
767 der++;
768 der = enter_der_item(der, &end); /* enter SEQ */
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100769 /* memset(tls->server_rsa_pub_key, 0, sizeof(tls->server_rsa_pub_key)); - already is */
Denys Vlasenko11d00962017-01-15 00:12:42 +0100770 der_binary_to_pstm(&tls->server_rsa_pub_key.N, der, end); /* modulus */
771 der = skip_der_item(der, end);
772 der_binary_to_pstm(&tls->server_rsa_pub_key.e, der, end); /* exponent */
773 tls->server_rsa_pub_key.size = pstm_unsigned_bin_size(&tls->server_rsa_pub_key.N);
774 dbg("server_rsa_pub_key.size:%d\n", tls->server_rsa_pub_key.size);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100775}
776
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +0100777/*
778 * TLS Handshake routines
779 */
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100780static int xread_tls_handshake_block(tls_state_t *tls, int min_len)
781{
782 struct record_hdr *xhdr;
783 int len = xread_tls_block(tls);
784
785 xhdr = (void*)tls->inbuf;
786 if (len < min_len
787 || xhdr->type != RECORD_TYPE_HANDSHAKE
788 || xhdr->proto_maj != TLS_MAJ
789 || xhdr->proto_min != TLS_MIN
790 ) {
791 tls_error_die(tls);
792 }
793 dbg("got HANDSHAKE\n");
794 return len;
795}
796
Denys Vlasenko5d1662e2017-01-17 18:17:27 +0100797static void fill_handshake_record_hdr(struct record_hdr *xhdr, unsigned len)
798{
799 struct handshake_hdr {
800 struct record_hdr xhdr;
801 uint8_t type;
802 uint8_t len24_hi, len24_mid, len24_lo;
803 } *h = (void*)xhdr;
804
805 h->xhdr.type = RECORD_TYPE_HANDSHAKE;
806 h->xhdr.proto_maj = TLS_MAJ;
807 h->xhdr.proto_min = TLS_MIN;
808 len -= 5;
809 h->xhdr.len16_hi = len >> 8;
810 // can be optimized to do one store instead of four:
811 // uint32_t v = htonl(0x100*(RECORD_TYPE_HANDSHAKE + 0x100*(TLS_MAJ + 0x100*(TLS_MIN))))
812 // | ((len >> 8) << 24); // little-endian specific, don't use in this form
813 // *(uint32_t *)xhdr = v;
814
815 h->xhdr.len16_lo = len & 0xff;
816
817 len -= 4;
818 h->len24_hi = len >> 16;
819 h->len24_mid = len >> 8;
820 h->len24_lo = len & 0xff;
821
822 memset(h + 1, 0, len);
823}
824
825//TODO: implement RFC 5746 (Renegotiation Indication Extension) - some servers will refuse to work with us otherwise
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +0100826static void send_client_hello(tls_state_t *tls)
827{
828 struct client_hello {
829 struct record_hdr xhdr;
830 uint8_t type;
831 uint8_t len24_hi, len24_mid, len24_lo;
832 uint8_t proto_maj, proto_min;
833 uint8_t rand32[32];
834 uint8_t session_id_len;
835 /* uint8_t session_id[]; */
836 uint8_t cipherid_len16_hi, cipherid_len16_lo;
837 uint8_t cipherid[2 * 1]; /* actually variable */
838 uint8_t comprtypes_len;
839 uint8_t comprtypes[1]; /* actually variable */
840 };
Denys Vlasenko5d1662e2017-01-17 18:17:27 +0100841 struct client_hello record;
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +0100842
Denys Vlasenko5d1662e2017-01-17 18:17:27 +0100843 fill_handshake_record_hdr(&record.xhdr, sizeof(record));
844 record.type = HANDSHAKE_CLIENT_HELLO;
845 record.proto_maj = TLS_MAJ; /* the "requested" version of the protocol, */
846 record.proto_min = TLS_MIN; /* can be higher than one in record headers */
847 tls_get_random(record.rand32, sizeof(record.rand32));
848 /* record.session_id_len = 0; - already is */
849 /* record.cipherid_len16_hi = 0; */
850 record.cipherid_len16_lo = 2 * 1;
851 record.cipherid[0] = CIPHER_ID >> 8;
852 record.cipherid[1] = CIPHER_ID & 0xff;
853 record.comprtypes_len = 1;
854 /* record.comprtypes[0] = 0; */
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +0100855
Denys Vlasenko5d1662e2017-01-17 18:17:27 +0100856 //dbg (make it repeatable): memset(record.rand32, 0x11, sizeof(record.rand32));
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100857 dbg(">> HANDSHAKE_CLIENT_HELLO\n");
Denys Vlasenko5d1662e2017-01-17 18:17:27 +0100858 xwrite_and_hash(tls, &record, sizeof(record));
859 memcpy(tls->client_and_server_rand32, record.rand32, sizeof(record.rand32));
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +0100860}
861
862static void get_server_hello(tls_state_t *tls)
863{
864 struct server_hello {
865 struct record_hdr xhdr;
866 uint8_t type;
867 uint8_t len24_hi, len24_mid, len24_lo;
868 uint8_t proto_maj, proto_min;
869 uint8_t rand32[32]; /* first 4 bytes are unix time in BE format */
870 uint8_t session_id_len;
871 uint8_t session_id[32];
872 uint8_t cipherid_hi, cipherid_lo;
873 uint8_t comprtype;
874 /* extensions may follow, but only those which client offered in its Hello */
875 };
876 struct server_hello *hp;
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100877 uint8_t *cipherid;
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +0100878
879 xread_tls_handshake_block(tls, 74);
880
881 hp = (void*)tls->inbuf;
882 // 74 bytes:
883 // 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|
884 //SvHl len=70 maj.min unixtime^^^ 28randbytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^ slen sid32bytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cipSel comprSel
885 if (hp->type != HANDSHAKE_SERVER_HELLO
886 || hp->len24_hi != 0
887 || hp->len24_mid != 0
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100888 /* hp->len24_lo checked later */
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +0100889 || hp->proto_maj != TLS_MAJ
890 || hp->proto_min != TLS_MIN
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +0100891 ) {
892 tls_error_die(tls);
893 }
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100894
895 cipherid = &hp->cipherid_hi;
896 if (hp->session_id_len != 32) {
897 if (hp->session_id_len != 0)
898 tls_error_die(tls);
899
900 // session_id_len == 0: no session id
901 // "The server
902 // may return an empty session_id to indicate that the session will
903 // not be cached and therefore cannot be resumed."
904 cipherid -= 32;
905 hp->len24_lo += 32; /* what len would be if session id would be present */
906 }
907
908 if (hp->len24_lo < 70
909 || cipherid[0] != (CIPHER_ID >> 8)
910 || cipherid[1] != (CIPHER_ID & 0xff)
911 || cipherid[2] != 0 /* comprtype */
912 ) {
913 tls_error_die(tls);
914 }
915
Denys Vlasenko5d1662e2017-01-17 18:17:27 +0100916 dbg("<< SERVER_HELLO\n");
Denys Vlasenko936e83e2017-01-16 04:25:01 +0100917 memcpy(tls->client_and_server_rand32 + 32, hp->rand32, sizeof(hp->rand32));
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +0100918}
919
920static void get_server_cert(tls_state_t *tls)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100921{
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100922 struct record_hdr *xhdr;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100923 uint8_t *certbuf;
924 int len, len1;
925
Denys Vlasenkoc5540d62017-01-15 02:17:03 +0100926 len = xread_tls_handshake_block(tls, 10);
927
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100928 xhdr = (void*)tls->inbuf;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100929 certbuf = (void*)(xhdr + 1);
930 if (certbuf[0] != HANDSHAKE_CERTIFICATE)
931 tls_error_die(tls);
Denys Vlasenko5d1662e2017-01-17 18:17:27 +0100932 dbg("<< CERTIFICATE\n");
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100933 // 4392 bytes:
934 // 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...
935 //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 +0100936 len1 = get24be(certbuf + 1);
937 if (len1 > len - 4) tls_error_die(tls);
938 len = len1;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100939 len1 = get24be(certbuf + 4);
940 if (len1 > len - 3) tls_error_die(tls);
941 len = len1;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100942 len1 = get24be(certbuf + 7);
943 if (len1 > len - 3) tls_error_die(tls);
944 len = len1;
945
946 if (len)
Denys Vlasenko11d00962017-01-15 00:12:42 +0100947 find_key_in_der_cert(tls, certbuf + 10, len);
948}
949
950static void send_client_key_exchange(tls_state_t *tls)
951{
Denys Vlasenko11d00962017-01-15 00:12:42 +0100952 struct client_key_exchange {
953 struct record_hdr xhdr;
954 uint8_t type;
955 uint8_t len24_hi, len24_mid, len24_lo;
Denys Vlasenko5d1662e2017-01-17 18:17:27 +0100956 /* keylen16 exists for RSA (in TLS, not in SSL), but not for some other key types */
957 uint8_t keylen16_hi, keylen16_lo;
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100958 uint8_t key[4 * 1024]; // size??
Denys Vlasenko11d00962017-01-15 00:12:42 +0100959 };
960 struct client_key_exchange record;
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +0100961 uint8_t rsa_premaster[SSL_HS_RSA_PREMASTER_SIZE];
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100962 int len;
Denys Vlasenko11d00962017-01-15 00:12:42 +0100963
Denys Vlasenko5d1662e2017-01-17 18:17:27 +0100964 fill_handshake_record_hdr(&record.xhdr, sizeof(record) - sizeof(record.key));
Denys Vlasenko11d00962017-01-15 00:12:42 +0100965 record.type = HANDSHAKE_CLIENT_KEY_EXCHANGE;
Denys Vlasenko11d00962017-01-15 00:12:42 +0100966
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +0100967 tls_get_random(rsa_premaster, sizeof(rsa_premaster));
Denys Vlasenko5d1662e2017-01-17 18:17:27 +0100968 // RFC 5246
969 // "Note: The version number in the PreMasterSecret is the version
970 // offered by the client in the ClientHello.client_version, not the
971 // version negotiated for the connection."
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +0100972 rsa_premaster[0] = TLS_MAJ;
973 rsa_premaster[1] = TLS_MIN;
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100974 len = psRsaEncryptPub(/*pool:*/ NULL,
Denys Vlasenko11d00962017-01-15 00:12:42 +0100975 /* psRsaKey_t* */ &tls->server_rsa_pub_key,
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +0100976 rsa_premaster, /*inlen:*/ sizeof(rsa_premaster),
Denys Vlasenko11d00962017-01-15 00:12:42 +0100977 record.key, sizeof(record.key),
978 data_param_ignored
979 );
Denys Vlasenko5d1662e2017-01-17 18:17:27 +0100980 /* length fields need fixing */
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100981 record.keylen16_hi = len >> 8;
982 record.keylen16_lo = len & 0xff;
983 len += 2;
Denys Vlasenko5d1662e2017-01-17 18:17:27 +0100984 /* record.len24_hi = 0; - already is */
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100985 record.len24_mid = len >> 8;
986 record.len24_lo = len & 0xff;
987 len += 4;
988 record.xhdr.len16_hi = len >> 8;
989 record.xhdr.len16_lo = len & 0xff;
Denys Vlasenko11d00962017-01-15 00:12:42 +0100990
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100991 dbg(">> HANDSHAKE_CLIENT_KEY_EXCHANGE\n");
992 xwrite_and_hash(tls, &record, sizeof(record.xhdr) + len);
Denys Vlasenko936e83e2017-01-16 04:25:01 +0100993
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100994 // RFC 5246
995 // For all key exchange methods, the same algorithm is used to convert
996 // the pre_master_secret into the master_secret. The pre_master_secret
997 // should be deleted from memory once the master_secret has been
998 // computed.
999 // master_secret = PRF(pre_master_secret, "master secret",
1000 // ClientHello.random + ServerHello.random)
1001 // [0..47];
1002 // The master secret is always exactly 48 bytes in length. The length
1003 // of the premaster secret will vary depending on key exchange method.
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001004 prf_hmac_sha256(
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001005 tls->master_secret, sizeof(tls->master_secret),
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001006 rsa_premaster, sizeof(rsa_premaster),
1007 "master secret",
1008 tls->client_and_server_rand32, sizeof(tls->client_and_server_rand32)
1009 );
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001010 dump_hex("master secret:%s\n", tls->master_secret, sizeof(tls->master_secret));
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001011
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001012 // RFC 5246
1013 // 6.3. Key Calculation
1014 //
1015 // The Record Protocol requires an algorithm to generate keys required
1016 // by the current connection state (see Appendix A.6) from the security
1017 // parameters provided by the handshake protocol.
1018 //
1019 // The master secret is expanded into a sequence of secure bytes, which
1020 // is then split to a client write MAC key, a server write MAC key, a
1021 // client write encryption key, and a server write encryption key. Each
1022 // of these is generated from the byte sequence in that order. Unused
1023 // values are empty. Some AEAD ciphers may additionally require a
1024 // client write IV and a server write IV (see Section 6.2.3.3).
1025 //
1026 // When keys and MAC keys are generated, the master secret is used as an
1027 // entropy source.
1028 //
1029 // To generate the key material, compute
1030 //
1031 // key_block = PRF(SecurityParameters.master_secret,
1032 // "key expansion",
1033 // SecurityParameters.server_random +
1034 // SecurityParameters.client_random);
1035 //
1036 // until enough output has been generated. Then, the key_block is
1037 // partitioned as follows:
1038 //
1039 // client_write_MAC_key[SecurityParameters.mac_key_length]
1040 // server_write_MAC_key[SecurityParameters.mac_key_length]
1041 // client_write_key[SecurityParameters.enc_key_length]
1042 // server_write_key[SecurityParameters.enc_key_length]
1043 // client_write_IV[SecurityParameters.fixed_iv_length]
1044 // server_write_IV[SecurityParameters.fixed_iv_length]
1045 {
1046 uint8_t tmp64[64];
1047 /* make server_rand32 + client_rand32 */
1048 memcpy(&tmp64[0] , &tls->client_and_server_rand32[32], 32);
1049 memcpy(&tmp64[32], &tls->client_and_server_rand32[0] , 32);
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001050
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001051 prf_hmac_sha256(
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001052 tls->client_write_MAC_key, sizeof(tls->client_write_MAC_key),
1053 tls->master_secret, sizeof(tls->master_secret),
1054 "key expansion",
1055 tmp64, 64
1056 );
1057 dump_hex("client_write_MAC_key:%s\n",
1058 tls->client_write_MAC_key, sizeof(tls->client_write_MAC_key)
1059 );
1060 }
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001061}
1062
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01001063static const uint8_t rec_CHANGE_CIPHER_SPEC[] = {
1064 RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
1065 01
1066};
1067
Denys Vlasenkoc5540d62017-01-15 02:17:03 +01001068static void send_change_cipher_spec(tls_state_t *tls)
1069{
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001070 /* Not "xwrite_and_hash": this is not a handshake message */
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001071 dbg(">> CHANGE_CIPHER_SPEC\n");
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01001072 xwrite(tls->fd, rec_CHANGE_CIPHER_SPEC, sizeof(rec_CHANGE_CIPHER_SPEC));
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001073
Denys Vlasenkofe0588d2017-01-17 17:04:24 +01001074 /* tls->write_seq64_be = 0; - already is */
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001075 tls->encrypt_on_write = 1;
Denys Vlasenkoc5540d62017-01-15 02:17:03 +01001076}
1077
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001078// 7.4.9. Finished
1079// A Finished message is always sent immediately after a change
1080// cipher spec message to verify that the key exchange and
1081// authentication processes were successful. It is essential that a
1082// change cipher spec message be received between the other handshake
1083// messages and the Finished message.
1084//...
1085// The Finished message is the first one protected with the just
1086// negotiated algorithms, keys, and secrets. Recipients of Finished
1087// messages MUST verify that the contents are correct. Once a side
1088// has sent its Finished message and received and validated the
1089// Finished message from its peer, it may begin to send and receive
1090// application data over the connection.
1091//...
1092// struct {
1093// opaque verify_data[verify_data_length];
1094// } Finished;
1095//
1096// verify_data
1097// PRF(master_secret, finished_label, Hash(handshake_messages))
1098// [0..verify_data_length-1];
1099//
1100// finished_label
1101// For Finished messages sent by the client, the string
1102// "client finished". For Finished messages sent by the server,
1103// the string "server finished".
1104//
1105// Hash denotes a Hash of the handshake messages. For the PRF
1106// defined in Section 5, the Hash MUST be the Hash used as the basis
1107// for the PRF. Any cipher suite which defines a different PRF MUST
1108// also define the Hash to use in the Finished computation.
1109//
1110// In previous versions of TLS, the verify_data was always 12 octets
1111// long. In the current version of TLS, it depends on the cipher
1112// suite. Any cipher suite which does not explicitly specify
1113// verify_data_length has a verify_data_length equal to 12. This
1114// includes all existing cipher suites.
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001115static void send_client_finished(tls_state_t *tls)
1116{
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001117 struct client_finished {
1118 struct record_hdr xhdr;
1119 uint8_t type;
1120 uint8_t len24_hi, len24_mid, len24_lo;
1121 uint8_t prf_result[12];
1122 };
1123 struct client_finished record;
1124 uint8_t handshake_hash[SHA256_OUTSIZE];
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001125
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001126 fill_handshake_record_hdr(&record.xhdr, sizeof(record));
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001127 record.type = HANDSHAKE_FINISHED;
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001128
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001129 sha256_peek(&tls->handshake_sha256_ctx, handshake_hash);
1130 prf_hmac_sha256(record.prf_result, sizeof(record.prf_result),
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001131 tls->master_secret, sizeof(tls->master_secret),
1132 "client finished",
1133 handshake_hash, sizeof(handshake_hash)
1134 );
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001135 dump_hex("from secret: %s\n", tls->master_secret, sizeof(tls->master_secret));
1136 dump_hex("from labelSeed: %s", "client finished", sizeof("client finished")-1);
1137 dump_hex("%s\n", handshake_hash, sizeof(handshake_hash));
1138 dump_hex("=> digest: %s\n", record.prf_result, sizeof(record.prf_result));
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001139
1140//(1) TODO: well, this should be encrypted on send, really.
1141//(2) do we really need to also hash it?
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001142
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001143 dbg(">> HANDSHAKE_FINISHED\n");
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001144 xwrite_and_hash(tls, &record, sizeof(record));
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001145}
1146
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001147static void tls_handshake(tls_state_t *tls)
1148{
1149 // Client RFC 5246 Server
1150 // (*) - optional messages, not always sent
1151 //
1152 // ClientHello ------->
1153 // ServerHello
1154 // Certificate*
1155 // ServerKeyExchange*
1156 // CertificateRequest*
1157 // <------- ServerHelloDone
1158 // Certificate*
1159 // ClientKeyExchange
1160 // CertificateVerify*
1161 // [ChangeCipherSpec]
1162 // Finished ------->
1163 // [ChangeCipherSpec]
1164 // <------- Finished
1165 // Application Data <------> Application Data
1166 int len;
1167
1168 send_client_hello(tls);
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001169 get_server_hello(tls);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001170
1171 //RFC 5246
1172 // The server MUST send a Certificate message whenever the agreed-
1173 // upon key exchange method uses certificates for authentication
1174 // (this includes all key exchange methods defined in this document
1175 // except DH_anon). This message will always immediately follow the
1176 // ServerHello message.
1177 //
1178 // IOW: in practice, Certificate *always* follows.
1179 // (for example, kernel.org does not even accept DH_anon cipher id)
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001180 get_server_cert(tls);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001181
Denys Vlasenkoc5540d62017-01-15 02:17:03 +01001182 len = xread_tls_handshake_block(tls, 4);
1183 if (tls->inbuf[5] == HANDSHAKE_SERVER_KEY_EXCHANGE) {
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001184 // 459 bytes:
1185 // 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...
1186 //SvKey len=455^
Denys Vlasenko11d00962017-01-15 00:12:42 +01001187 // with TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 461 bytes:
1188 // 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 +01001189 dbg("<< SERVER_KEY_EXCHANGE len:%u\n", len);
1190//probably need to save it
Denys Vlasenkoc5540d62017-01-15 02:17:03 +01001191 xread_tls_handshake_block(tls, 4);
1192 }
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001193
Denys Vlasenkoc5540d62017-01-15 02:17:03 +01001194// if (tls->inbuf[5] == HANDSHAKE_CERTIFICATE_REQUEST) {
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001195// dbg("<< CERTIFICATE_REQUEST\n");
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001196//RFC 5246: (in response to this,) "If no suitable certificate is available,
1197// the client MUST send a certificate message containing no
1198// certificates. That is, the certificate_list structure has a
1199// length of zero. ...
1200// Client certificates are sent using the Certificate structure
1201// defined in Section 7.4.2."
1202// (i.e. the same format as server certs)
Denys Vlasenkoc5540d62017-01-15 02:17:03 +01001203// xread_tls_handshake_block(tls, 4);
1204// }
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001205
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01001206 if (tls->inbuf[5] != HANDSHAKE_SERVER_HELLO_DONE)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001207 tls_error_die(tls);
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01001208 // 0e 000000 (len:0)
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001209 dbg("<< SERVER_HELLO_DONE\n");
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01001210
1211 send_client_key_exchange(tls);
1212
1213 send_change_cipher_spec(tls);
1214 /* we now should send encrypted... as soon as we grok AES. */
1215
1216 send_client_finished(tls);
1217
1218 /* Get CHANGE_CIPHER_SPEC */
1219 len = xread_tls_block(tls);
1220 if (len != 1 || memcmp(tls->inbuf, rec_CHANGE_CIPHER_SPEC, 6) != 0)
1221 tls_error_die(tls);
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001222 dbg("<< CHANGE_CIPHER_SPEC\n");
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01001223 tls->decrypt_on_read = 1;
1224 /* we now should receive encrypted */
1225
1226 /* Get (encrypted) FINISHED from the server */
1227 len = xread_tls_block(tls);
1228 if (len < 4 || tls->inbuf[5] != HANDSHAKE_FINISHED)
1229 tls_error_die(tls);
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001230 dbg("<< FINISHED\n");
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01001231 /* application data can be sent/received */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001232}
1233
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001234// To run a test server using openssl:
1235// openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1
1236// openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
1237
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001238int tls_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1239int tls_main(int argc UNUSED_PARAM, char **argv)
1240{
1241 tls_state_t *tls;
1242 len_and_sockaddr *lsa;
1243 int fd;
1244
1245 // INIT_G();
1246 // getopt32(argv, "myopts")
1247
1248 if (!argv[1])
1249 bb_show_usage();
1250
1251 lsa = xhost2sockaddr(argv[1], 443);
1252 fd = xconnect_stream(lsa);
1253
1254 tls = new_tls_state();
1255 tls->fd = fd;
1256 tls_handshake(tls);
1257
1258 return EXIT_SUCCESS;
1259}
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001260
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001261/* Unencryped SHA256 example:
1262 * $ openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
1263 * $ openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL
1264 * $ openssl s_client -connect 127.0.0.1:4433 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL-SHA256
1265 * s_client says:
1266
1267write to 0x1d750b0 [0x1e6f153] (99 bytes => 99 (0x63))
12680000 - 16 03 01 005e 01 00005a 0303 [4d ef 5c 82 3e ....^...Z..M.\.> >> ClHello
12690010 - bf a6 ee f1 1e 04 d1 5c-99 20 86 13 e9 0a cf 58 .......\. .....X
12700020 - 75 b1 bd 7a e6 d6 44 f3-d3 a1 52] 00 0004 003b u..z..D...R....; 003b = TLS_RSA_WITH_NULL_SHA256
12710030 - 00ff TLS_EMPTY_RENEGOTIATION_INFO_SCSV
1272 0100 compr=none
1273 002d, 0023 0000, 000d 0020 [00 1e .....-.#..... .. extlen, SessionTicketTLS 0 bytes, SignatureAlgorithms 32 bytes
12740040 - 06 01 06 02 06 03 05 01-05 02 05 03 04 01 04 02 ................
12750050 - 04 03 03 01 03 02 03 03-02 01 02 02 02 03] 000f ................ Heart Beat 1 byte
12760060 - 0001 01 ...
1277
1278read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
12790000 - 16 03 03 00 3a ....:
1280read from 0x1d750b0 [0x1e6ac08] (58 bytes => 58 (0x3A))
12810000 - 02 000036 0303 [f2 61-ae c8 58 e3 51 42 32 93 ...6...a..X.QB2. << SvHello
12820010 - c5 62 e4 f5 06 93 81 65-aa f7 df 74 af 7c 98 b4 .b.....e...t.|..
12830020 - 3e a7 35 c3 25 69] 00,003b,00.................. >.5.%i..;....... - no session id! "The server
1284 may return an empty session_id to indicate that the session will
1285 not be cached and therefore cannot be resumed."
1286 003b = TLS_RSA_WITH_NULL_SHA256 accepted, 00 - no compr
1287 000e ff01 0001 extlen, 0xff01=RenegotiationInfo 1 byte
12880030 - 00, 0023 0000, SessionTicketTLS 0 bytes
1289 000f 0001 01 ..#....... Heart Beat 1 byte
1290
1291read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
12920000 - 16 03 03 04 0b .....
1293read from 0x1d750b0 [0x1e6ac08] (1035 bytes => 1035 (0x40B))
12940000 - 0b 00 04 07 00 04 04 00-04 01 30 82 03 fd 30 82 ..........0...0. << Cert
12950010 - 02 65 a0 03 02 01 02 02-09 00 d9 d9 8d b8 94 ad .e..............
12960020 - 2e 2b 30 0d 06 09 2a 86-48 86 f7 0d 01 01 0b 05 .+0...*.H.......
12970030 - 00 30 14 31 12 30 10 06-03 55 04 03 0c 09 6c 6f .0.1.0...U....lo
12980040 - 63 61 6c 68 6f 73 74 30-20 17 0d 31 37 30 31 31 calhost0 ..17011
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001299...".......".......".......".......".......".......".......".......".....
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100130003f0 - 11 8a cd c5 a3 0a 22 43-d5 13 f9 a5 8a 06 f9 00 ......"C........
13010400 - 3c f7 86 4e e8 a5 d8 5b-92 37 f5 <..N...[.7.
1302depth=0 CN = localhost
1303verify error:num=18:self signed certificate
1304verify return:1
1305depth=0 CN = localhost
1306verify return:1
1307
1308read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
13090000 - 16 03 03 00 04 .....
1310
1311read from 0x1d750b0 [0x1e6ac08] (4 bytes => 4 (0x4)) << SvDone
13120000 - 0e .
13130004 - <SPACES/NULS>
1314
1315write to 0x1d750b0 [0x1e74620] (395 bytes => 395 (0x18B)) >> ClDone
13160000 - 16 03 03 01 86 10 00 01-82 01 80 88 f0 87 5d b0 ..............].
13170010 - ea df 3b 4d e2 35 f3 99-e6 d4 29 87 36 86 ea 30 ..;M.5....).6..0
13180020 - 38 80 c7 37 66 7f 5b e7-23 38 7e 87 24 66 82 81 8..7f.[.#8~.$f..
13190030 - e4 ba 6c 2a 0c 92 a8 b9-39 c1 55 16 32 88 14 cd ..l*....9.U.2...
13200040 - 95 8c 82 49 a1 c7 f9 9b-e5 8f f6 5e 7e ee 91 b3 ...I.......^~...
13210050 - 2c 92 e7 a3 02 f8 9f 56-04 45 39 df a7 d6 1a 16 ,......V.E9.....
13220060 - 67 5c a4 f8 87 8a c4 c8-6c 6f c6 f0 9b c9 b4 87 g\......lo......
13230070 - 36 43 c1 67 9f b3 aa 11-34 b0 c2 fc 1f d9 e1 ff 6C.g....4.......
13240080 - fb e1 89 db 91 58 ec cc-aa 16 19 9a 91 74 e2 46 .....X.......t.F
13250090 - 22 a7 a7 f7 9e 3c 97 82-2c e4 21 b3 fa ef ba 3f "....<..,.!....?
132600a0 - 57 48 e4 b2 84 b7 c2 81-92 a9 f1 03 68 f4 e6 0c WH..........h...
132700b0 - fd 54 87 f5 e9 a0 5d e6-5f 0e bd 80 86 27 ab 0e .T....]._....'..
132800c0 - cf 92 4f bd fc 24 b9 54-72 5f 58 df 6b 2b 1d 97 ..O..$.Tr_X.k+..
132900d0 - 00 60 fe 95 b0 aa d6 c7-c1 3a f9 2e 7c 92 a9 6d .`.......:..|..m
133000e0 - 28 a3 ef 3e c1 e6 2d 2d-e8 db 81 ea 51 02 3f 64 (..>..--....Q.?d
133100f0 - a8 66 14 c1 4b 17 1f 55-c6 5b 3b 38 c3 6a 61 a8 .f..K..U.[;8.ja.
13320100 - f7 ad 65 7d cb 14 6d b3-0f 76 19 25 8e ed bd 53 ..e}..m..v.%...S
13330110 - 35 a9 a1 34 00 9d 07 81-84 51 35 e0 83 83 e3 a6 5..4.....Q5.....
13340120 - c7 77 4c 61 e4 78 9c cb-f5 92 4e d6 dd c4 c2 2b .wLa.x....N....+
13350130 - 75 9e 72 a6 7f 81 6a 1c-fc 4a 51 91 81 b4 cc 33 u.r...j..JQ....3
13360140 - 1c 8b 0a b6 94 8b 16 1b-86 2f 31 5e 31 e1 57 14 ........./1^1.W.
13370150 - 2e b5 09 5d cf 6f ea b2-94 e9 5c cc b9 fc 24 a0 ...].o....\...$.
13380160 - b7 f1 f4 9d 95 46 4f 08-5c 45 c6 2f 9f 7d 76 09 .....FO.\E./.}v.
13390170 - 6a af 50 2c 89 76 82 5f-e8 34 d8 4b 84 b6 34 18 j.P,.v._.4.K..4.
13400180 - 85 95 4a 3f 0f 28 88 3a-71 32 90 ..J?.(.:q2.
1341
1342write to 0x1d750b0 [0x1e74620] (6 bytes => 6 (0x6))
13430000 - 14 03 03 00 01 01 ...... >> CHANGE_CIPHER_SPEC
1344
1345write to 0x1d750b0 [0x1e74620] (53 bytes => 53 (0x35))
13460000 - 16 03 03 0030 14 00000c [ed b9 e1 33 36 0b 76 ....0.......36.v >> FINISHED (0x14) [PRF 12 bytes|SHA256_OUTSIZE 32 bytes]
13470010 - c0 d1 d4 0b a3|73 ec a8-fa b5 cb 12 b6 4c 2a b1 .....s.......L*.
13480020 - fb 42 7f 73 0d 06 1c 87-56 f0 db df e6 6a 25 aa .B.s....V....j%.
13490030 - fc 42 38 cb 0b] .B8..
1350
1351read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
13520000 - 16 03 03 00 aa .....
1353read from 0x1d750b0 [0x1e6ac08] (170 bytes => 170 (0xAA))
13540000 - 04 00 00 a6 00 00 1c 20-00 a0 dd f4 52 01 54 8d ....... ....R.T. << NEW_SESSION_TICKET
13550010 - f8 a6 f9 2d 7d 19 20 5b-14 44 d3 2d 7b f2 ca e8 ...-}. [.D.-{...
13560020 - 01 4e 94 7b fe 12 59 3a-00 2e 7e cf 74 43 7a f7 .N.{..Y:..~.tCz.
13570030 - 9e cc 70 80 70 7c e3 a5-c6 9d 85 2c 36 19 4c 5c ..p.p|.....,6.L\
13580040 - ba 3b c3 e5 69 dc f3 a4-47 38 11 c9 7d 1a b0 6e .;..i...G8..}..n
13590050 - d8 49 a0 a8 e4 de 70 a8-d0 6b e4 7a b7 65 25 df .I....p..k.z.e%.
13600060 - 1b 5f 64 0f 89 69 02 72-fe eb d3 7a af 51 78 0e ._d..i.r...z.Qx.
13610070 - de 17 06 a5 f0 47 9d e0-04 d4 b1 1e be 7e ed bd .....G.......~..
13620080 - 27 8f 5d e8 ac f6 45 aa-e0 12 93 41 5f a8 4b b9 '.]...E....A_.K.
13630090 - bd 43 8f a1 23 51 af 92-77 8f 38 23 3e 2e c2 f0 .C..#Q..w.8#>...
136400a0 - a3 74 fa 83 94 ce 19 8a-5b 5b .t......[[
1365
1366read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
13670000 - 14 03 03 00 01 ..... << CHANGE_CIPHER_SPEC
1368read from 0x1d750b0 [0x1e6ac08] (1 bytes => 1 (0x1))
13690000 - 01 .
1370
1371read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
13720000 - 16 03 03 00 30 ....0
1373read from 0x1d750b0 [0x1e6ac08] (48 bytes => 48 (0x30))
13740000 - 14 00000c [06 86 0d 5c-92 0b 63 04 cc b4 f0 00 .......\..c..... << FINISHED (0x14) [PRF 12 bytes|SHA256_OUTSIZE 32 bytes]
13750010 -|49 d6 dd 56 73 e3 d2 e8-22 d6 bd 61 b2 b3 af f0 I..Vs..."..a....
13760020 - f5 00 8a 80 82 04 33 a7-50 8e ae 3b 4c 8c cf 4a] ......3.P..;L..J
1377---
1378Certificate chain
1379 0 s:/CN=localhost
1380 i:/CN=localhost
1381---
1382Server certificate
1383-----BEGIN CERTIFICATE-----
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001384...".......".......".......".......".......".......".......".......".....
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001385-----END CERTIFICATE-----
1386subject=/CN=localhost
1387issuer=/CN=localhost
1388---
1389No client certificate CA names sent
1390---
1391SSL handshake has read 1346 bytes and written 553 bytes
1392---
1393New, TLSv1/SSLv3, Cipher is NULL-SHA256
1394Server public key is 3072 bit
1395Secure Renegotiation IS supported
1396Compression: NONE
1397Expansion: NONE
1398No ALPN negotiated
1399SSL-Session:
1400 Protocol : TLSv1.2
1401 Cipher : NULL-SHA256
1402 Session-ID: 5D62B36950F3DEB571707CD1B815E9E275041B9DB70D7F3E25C4A6535B13B616
1403 Session-ID-ctx:
1404 Master-Key: 4D08108C59417E0A41656636C51BA5B83F4EFFF9F4C860987B47B31250E5D1816D00940DBCCC196C2D99C8462C889DF1
1405 Key-Arg : None
1406 Krb5 Principal: None
1407 PSK identity: None
1408 PSK identity hint: None
1409 TLS session ticket lifetime hint: 7200 (seconds)
1410 TLS session ticket:
1411 0000 - dd f4 52 01 54 8d f8 a6-f9 2d 7d 19 20 5b 14 44 ..R.T....-}. [.D
1412 0010 - d3 2d 7b f2 ca e8 01 4e-94 7b fe 12 59 3a 00 2e .-{....N.{..Y:..
1413 0020 - 7e cf 74 43 7a f7 9e cc-70 80 70 7c e3 a5 c6 9d ~.tCz...p.p|....
1414 0030 - 85 2c 36 19 4c 5c ba 3b-c3 e5 69 dc f3 a4 47 38 .,6.L\.;..i...G8
1415 0040 - 11 c9 7d 1a b0 6e d8 49-a0 a8 e4 de 70 a8 d0 6b ..}..n.I....p..k
1416 0050 - e4 7a b7 65 25 df 1b 5f-64 0f 89 69 02 72 fe eb .z.e%.._d..i.r..
1417 0060 - d3 7a af 51 78 0e de 17-06 a5 f0 47 9d e0 04 d4 .z.Qx......G....
1418 0070 - b1 1e be 7e ed bd 27 8f-5d e8 ac f6 45 aa e0 12 ...~..'.]...E...
1419 0080 - 93 41 5f a8 4b b9 bd 43-8f a1 23 51 af 92 77 8f .A_.K..C..#Q..w.
1420 0090 - 38 23 3e 2e c2 f0 a3 74-fa 83 94 ce 19 8a 5b 5b 8#>....t......[[
1421
1422 Start Time: 1484574330
1423 Timeout : 7200 (sec)
1424 Verify return code: 18 (self signed certificate)
1425---
1426read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
14270000 - 17 03 03 00 21 ....!
1428read from 0x1d750b0 [0x1e6ac08] (33 bytes => 33 (0x21))
14290000 - 0a 74 5b 50 02 13 75 a4-27 0a 40 b1 53 74 52 14 .t[P..u.'.@.StR.
14300010 - e7 1e 6a 6c c1 60 2e 93-7e a5 d9 43 1d 8e f6 08 ..jl.`..~..C....
14310020 - 69 i
1432
1433read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
14340000 - 17 03 03 00 21 ....!
1435read from 0x1d750b0 [0x1e6ac08] (33 bytes => 33 (0x21))
14360000 - 0a 1b ce 44 98 4f 81 c5-28 7a cc 79 62 db d2 86 ...D.O..(z.yb...
14370010 - 6a 55 a4 c7 73 49 ef 3e-bd 03 99 76 df 65 2a a1 jU..sI.>...v.e*.
14380020 - b6 .
1439
1440read from 0x1d750b0 [0x1e6ac03] (5 bytes => 5 (0x5))
14410000 - 17 03 03 00 21 ....!
1442read from 0x1d750b0 [0x1e6ac08] (33 bytes => 33 (0x21))
14430000 - 0a 67 66 34 ba 68 36 3c-ad 0a c1 f5 c0 5a 50 fe .gf4.h6<.....ZP.
14440010 - 68 cd 04 65 e9 de 6e 98-f9 e2 41 1e 0b 9b 84 06 h..e..n...A.....
14450020 - 64 d
1446*/