2 * Copyright (C) 2017 Denys Vlasenko
4 * Licensed under GPLv2, see file LICENSE in this source tree.
7 //config: bool #No description makes it a hidden option
10 //kbuild:lib-$(CONFIG_TLS) += tls.o
11 //kbuild:lib-$(CONFIG_TLS) += tls_pstm.o
12 //kbuild:lib-$(CONFIG_TLS) += tls_pstm_montgomery_reduce.o
13 //kbuild:lib-$(CONFIG_TLS) += tls_pstm_mul_comba.o
14 //kbuild:lib-$(CONFIG_TLS) += tls_pstm_sqr_comba.o
15 //kbuild:lib-$(CONFIG_TLS) += tls_rsa.o
16 //kbuild:lib-$(CONFIG_TLS) += tls_aes.o
17 ////kbuild:lib-$(CONFIG_TLS) += tls_aes_gcm.o
21 //Tested against kernel.org:
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?
40 // works against "openssl s_server -cipher NULL"
41 // and against wolfssl-3.9.10-stable/examples/server/server.c:
42 //#define CIPHER_ID1 TLS_RSA_WITH_NULL_SHA256 // for testing (does everything except encrypting)
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
56 // 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
59 // bug #11456: host is.gd accepts only ECDHE-ECDSA-foo (the simplest which works: ECDHE-ECDSA-AES128-SHA 0xC009)
63 #define TLS_DEBUG_HASH 0
64 #define TLS_DEBUG_DER 0
65 #define TLS_DEBUG_FIXED_SECRETS 0
67 # define dump_raw_out(...) dump_hex(__VA_ARGS__)
69 # define dump_raw_out(...) ((void)0)
72 # define dump_raw_in(...) dump_hex(__VA_ARGS__)
74 # define dump_raw_in(...) ((void)0)
78 # define dbg(...) fprintf(stderr, __VA_ARGS__)
80 # define dbg(...) ((void)0)
84 # define dbg_der(...) fprintf(stderr, __VA_ARGS__)
86 # define dbg_der(...) ((void)0)
89 #define RECORD_TYPE_CHANGE_CIPHER_SPEC 20 /* 0x14 */
90 #define RECORD_TYPE_ALERT 21 /* 0x15 */
91 #define RECORD_TYPE_HANDSHAKE 22 /* 0x16 */
92 #define RECORD_TYPE_APPLICATION_DATA 23 /* 0x17 */
94 #define HANDSHAKE_HELLO_REQUEST 0 /* 0x00 */
95 #define HANDSHAKE_CLIENT_HELLO 1 /* 0x01 */
96 #define HANDSHAKE_SERVER_HELLO 2 /* 0x02 */
97 #define HANDSHAKE_HELLO_VERIFY_REQUEST 3 /* 0x03 */
98 #define HANDSHAKE_NEW_SESSION_TICKET 4 /* 0x04 */
99 #define HANDSHAKE_CERTIFICATE 11 /* 0x0b */
100 #define HANDSHAKE_SERVER_KEY_EXCHANGE 12 /* 0x0c */
101 #define HANDSHAKE_CERTIFICATE_REQUEST 13 /* 0x0d */
102 #define HANDSHAKE_SERVER_HELLO_DONE 14 /* 0x0e */
103 #define HANDSHAKE_CERTIFICATE_VERIFY 15 /* 0x0f */
104 #define HANDSHAKE_CLIENT_KEY_EXCHANGE 16 /* 0x10 */
105 #define HANDSHAKE_FINISHED 20 /* 0x14 */
107 #define TLS_EMPTY_RENEGOTIATION_INFO_SCSV 0x00FF /* not a real cipher id... */
109 #define SSL_NULL_WITH_NULL_NULL 0x0000
110 #define SSL_RSA_WITH_NULL_MD5 0x0001
111 #define SSL_RSA_WITH_NULL_SHA 0x0002
112 #define SSL_RSA_WITH_RC4_128_MD5 0x0004
113 #define SSL_RSA_WITH_RC4_128_SHA 0x0005
114 #define TLS_RSA_WITH_IDEA_CBC_SHA 0x0007 /* 7 */
115 #define SSL_RSA_WITH_3DES_EDE_CBC_SHA 0x000A /* 10 */
117 #define SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA 0x0016 /* 22 */
118 #define SSL_DH_anon_WITH_RC4_128_MD5 0x0018 /* 24 */
119 #define SSL_DH_anon_WITH_3DES_EDE_CBC_SHA 0x001B /* 27 */
120 #define TLS_RSA_WITH_AES_128_CBC_SHA 0x002F /*SSLv3 Kx=RSA Au=RSA Enc=AES(128) Mac=SHA1 */
121 #define TLS_DHE_RSA_WITH_AES_128_CBC_SHA 0x0033 /* 51 */
122 #define TLS_DH_anon_WITH_AES_128_CBC_SHA 0x0034 /* 52 */
123 #define TLS_RSA_WITH_AES_256_CBC_SHA 0x0035 /* 53 */
124 #define TLS_DHE_RSA_WITH_AES_256_CBC_SHA 0x0039 /* 57 */
125 #define TLS_DH_anon_WITH_AES_256_CBC_SHA 0x003A /* 58 */
126 #define TLS_RSA_WITH_NULL_SHA256 0x003B /* 59 */
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_DHE_RSA_WITH_AES_128_CBC_SHA256 0x0067 /* 103 */
130 #define TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 0x006B /* 107 */
131 #define TLS_PSK_WITH_AES_128_CBC_SHA 0x008C /* 140 */
132 #define TLS_PSK_WITH_AES_256_CBC_SHA 0x008D /* 141 */
133 #define TLS_DHE_PSK_WITH_AES_128_CBC_SHA 0x0090 /* 144 */
134 #define TLS_DHE_PSK_WITH_AES_256_CBC_SHA 0x0091 /* 145 */
135 #define TLS_RSA_WITH_SEED_CBC_SHA 0x0096 /* 150 */
136 #define TLS_PSK_WITH_AES_128_CBC_SHA256 0x00AE /* 174 */
137 #define TLS_PSK_WITH_AES_256_CBC_SHA384 0x00AF /* 175 */
138 #define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0xC004 /* 49156 */
139 #define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0xC005 /* 49157 */
140 #define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0xC009 /*TLSv1 Kx=ECDH Au=ECDSA Enc=AES(128) Mac=SHA1 */
141 #define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0xC00A /*TLSv1 Kx=ECDH Au=ECDSA Enc=AES(256) Mac=SHA1 */
142 #define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA 0xC00E /* 49166 */
143 #define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA 0xC00F /* 49167 */
144 #define TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA 0xC012 /* 49170 */
145 #define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA 0xC013 /*TLSv1 Kx=ECDH Au=RSA Enc=AES(128) Mac=SHA1 */
146 #define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA 0xC014 /*TLSv1 Kx=ECDH Au=RSA Enc=AES(256) Mac=SHA1 */
147 #define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023 /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AES(128) Mac=SHA256 */
148 #define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 0xC024 /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AES(256) Mac=SHA384 */
149 #define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 0xC025 /* 49189 */
150 #define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 0xC026 /* 49190 */
151 #define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 0xC027 /*TLSv1.2 Kx=ECDH Au=RSA Enc=AES(128) Mac=SHA256 */
152 #define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 0xC028 /*TLSv1.2 Kx=ECDH Au=RSA Enc=AES(256) Mac=SHA384 */
153 #define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 0xC029 /* 49193 */
154 #define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 0xC02A /* 49194 */
156 /* RFC 5288 "AES Galois Counter Mode (GCM) Cipher Suites for TLS" */
157 #define TLS_RSA_WITH_AES_128_GCM_SHA256 0x009C /*TLSv1.2 Kx=RSA Au=RSA Enc=AESGCM(128) Mac=AEAD */
158 #define TLS_RSA_WITH_AES_256_GCM_SHA384 0x009D /*TLSv1.2 Kx=RSA Au=RSA Enc=AESGCM(256) Mac=AEAD */
159 #define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESGCM(128) Mac=AEAD */
160 #define TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0xC02C /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESGCM(256) Mac=AEAD */
161 #define TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0xC02D /* 49197 */
162 #define TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0xC02E /* 49198 */
163 #define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xC02F /*TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(128) Mac=AEAD */
164 #define TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0xC030 /*TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(256) Mac=AEAD */
165 #define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 0xC031 /* 49201 */
166 #define TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 0xC032 /* 49202 */
168 /* From http://wiki.mozilla.org/Security/Server_Side_TLS */
169 /* and 'openssl ciphers -V -stdname' */
170 #define TLS_RSA_WITH_ARIA_128_GCM_SHA256 0xC050 /*TLSv1.2 Kx=RSA Au=RSA Enc=ARIAGCM(128) Mac=AEAD */
171 #define TLS_RSA_WITH_ARIA_256_GCM_SHA384 0xC051 /*TLSv1.2 Kx=RSA Au=RSA Enc=ARIAGCM(256) Mac=AEAD */
172 #define TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 0xC052 /*TLSv1.2 Kx=DH Au=RSA Enc=ARIAGCM(128) Mac=AEAD */
173 #define TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 0xC053 /*TLSv1.2 Kx=DH Au=RSA Enc=ARIAGCM(256) Mac=AEAD */
174 #define TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 0xC05C /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=ARIAGCM(128) Mac=AEAD */
175 #define TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 0xC05D /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=ARIAGCM(256) Mac=AEAD */
176 #define TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 0xC060 /*TLSv1.2 Kx=ECDH Au=RSA Enc=ARIAGCM(128) Mac=AEAD */
177 #define TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 0xC061 /*TLSv1.2 Kx=ECDH Au=RSA Enc=ARIAGCM(256) Mac=AEAD */
178 #define TLS_RSA_WITH_AES_128_CCM 0xC09C /*TLSv1.2 Kx=RSA Au=RSA Enc=AESCCM(128) Mac=AEAD */
179 #define TLS_RSA_WITH_AES_256_CCM 0xC09D /*TLSv1.2 Kx=RSA Au=RSA Enc=AESCCM(256) Mac=AEAD */
180 #define TLS_DHE_RSA_WITH_AES_128_CCM 0xC09E /*TLSv1.2 Kx=DH Au=RSA Enc=AESCCM(128) Mac=AEAD */
181 #define TLS_DHE_RSA_WITH_AES_256_CCM 0xC09F /*TLSv1.2 Kx=DH Au=RSA Enc=AESCCM(256) Mac=AEAD */
182 #define TLS_RSA_WITH_AES_128_CCM_8 0xC0A0 /*TLSv1.2 Kx=RSA Au=RSA Enc=AESCCM8(128) Mac=AEAD */
183 #define TLS_RSA_WITH_AES_256_CCM_8 0xC0A1 /*TLSv1.2 Kx=RSA Au=RSA Enc=AESCCM8(256) Mac=AEAD */
184 #define TLS_DHE_RSA_WITH_AES_128_CCM_8 0xC0A2 /*TLSv1.2 Kx=DH Au=RSA Enc=AESCCM8(128) Mac=AEAD */
185 #define TLS_DHE_RSA_WITH_AES_256_CCM_8 0xC0A3 /*TLSv1.2 Kx=DH Au=RSA Enc=AESCCM8(256) Mac=AEAD */
186 #define TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA8 /*TLSv1.2 Kx=ECDH Au=RSA Enc=CHACHA20/POLY1305(256) Mac=AEAD */
187 #define TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA9 /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=CHACHA20/POLY1305(256) Mac=AEAD */
188 #define TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCAA /*TLSv1.2 Kx=DH Au=RSA Enc=CHACHA20/POLY1305(256) Mac=AEAD */
189 #define TLS_ECDHE_ECDSA_WITH_AES_128_CCM 0xC0AC /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESCCM(128) Mac=AEAD */
190 #define TLS_ECDHE_ECDSA_WITH_AES_256_CCM 0xC0AD /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESCCM(256) Mac=AEAD */
191 #define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESCCM8(128) Mac=AEAD */
192 #define TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 0xC0AF /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESCCM8(256) Mac=AEAD */
194 #define TLS_AES_128_GCM_SHA256 0x1301 /*TLSv1.3 Kx=any Au=any Enc=AESGCM(128) Mac=AEAD */
195 #define TLS_AES_256_GCM_SHA384 0x1302 /*TLSv1.3 Kx=any Au=any Enc=AESGCM(256) Mac=AEAD */
196 #define TLS_CHACHA20_POLY1305_SHA256 0x1303 /*TLSv1.3 Kx=any Au=any Enc=CHACHA20/POLY1305(256) Mac=AEAD */
197 #define TLS_AES_128_CCM_SHA256 0x1304 /*TLSv1.3 Kx=any Au=any Enc=AESCCM(128) Mac=AEAD */
199 /* Might go to libbb.h */
200 #define TLS_MAX_CRYPTBLOCK_SIZE 16
201 #define TLS_MAX_OUTBUF (1 << 14)
212 RSA_PREMASTER_SIZE = 48,
216 /* 8 = 3+5. 3 extra bytes result in record data being 32-bit aligned */
217 OUTBUF_PFX = 8 + AES_BLOCKSIZE, /* header + IV */
218 OUTBUF_SFX = TLS_MAX_MAC_SIZE + TLS_MAX_CRYPTBLOCK_SIZE, /* MAC + padding */
221 // | 6.2.1. Fragmentation
222 // | The record layer fragments information blocks into TLSPlaintext
223 // | records carrying data in chunks of 2^14 bytes or less. Client
224 // | message boundaries are not preserved in the record layer (i.e.,
225 // | multiple client messages of the same ContentType MAY be coalesced
226 // | into a single TLSPlaintext record, or a single message MAY be
227 // | fragmented across several records)
230 // | The length (in bytes) of the following TLSPlaintext.fragment.
231 // | The length MUST NOT exceed 2^14.
233 // | 6.2.2. Record Compression and Decompression
235 // | Compression must be lossless and may not increase the content length
236 // | by more than 1024 bytes. If the decompression function encounters a
237 // | TLSCompressed.fragment that would decompress to a length in excess of
238 // | 2^14 bytes, it MUST report a fatal decompression failure error.
241 // | The length (in bytes) of the following TLSCompressed.fragment.
242 // | The length MUST NOT exceed 2^14 + 1024.
244 // | 6.2.3. Record Payload Protection
245 // | The encryption and MAC functions translate a TLSCompressed
246 // | structure into a TLSCiphertext. The decryption functions reverse
247 // | the process. The MAC of the record also includes a sequence
248 // | number so that missing, extra, or repeated messages are
252 // | The length (in bytes) of the following TLSCiphertext.fragment.
253 // | The length MUST NOT exceed 2^14 + 2048.
254 MAX_INBUF = RECHDR_LEN + (1 << 14) + 2048,
259 uint8_t proto_maj, proto_min;
260 uint8_t len16_hi, len16_lo;
263 struct tls_handshake_data {
264 /* In bbox, md5/sha1/sha256 ctx's are the same structure */
265 md5sha_ctx_t handshake_hash_ctx;
267 uint8_t client_and_server_rand32[2 * 32];
268 uint8_t master_secret[48];
269 //TODO: store just the DER key here, parse/use/delete it when sending client key
270 //this way it will stay key type agnostic here.
271 psRsaKey_t server_rsa_pub_key;
273 unsigned saved_client_hello_size;
274 uint8_t saved_client_hello[1];
278 static unsigned get24be(const uint8_t *p)
280 return 0x100*(0x100*p[0] + p[1]) + p[2];
284 static void dump_hex(const char *fmt, const void *vp, int len)
286 char hexbuf[32 * 1024 + 4];
287 const uint8_t *p = vp;
289 bin2hex(hexbuf, (void*)p, len)[0] = '\0';
293 static void dump_tls_record(const void *vp, int len)
295 const uint8_t *p = vp;
299 if (len < RECHDR_LEN) {
300 dump_hex("< |%s|\n", p, len);
303 xhdr_len = 0x100*p[3] + p[4];
304 dbg("< hdr_type:%u ver:%u.%u len:%u", p[0], p[1], p[2], xhdr_len);
307 if (len >= 4 && p[-RECHDR_LEN] == RECORD_TYPE_HANDSHAKE) {
308 unsigned len24 = get24be(p + 1);
309 dbg(" type:%u len24:%u", p[0], len24);
313 dump_hex(" |%s|\n", p, xhdr_len);
319 # define dump_hex(...) ((void)0)
320 # define dump_tls_record(...) ((void)0)
323 void tls_get_random(void *buf, unsigned len)
325 if (len != open_read_close("/dev/urandom", buf, len))
329 /* Nondestructively see the current hash value */
330 static unsigned sha_peek(md5sha_ctx_t *ctx, void *buffer)
332 md5sha_ctx_t ctx_copy = *ctx; /* struct copy */
333 return sha_end(&ctx_copy, buffer);
336 static ALWAYS_INLINE unsigned get_handshake_hash(tls_state_t *tls, void *buffer)
338 return sha_peek(&tls->hsd->handshake_hash_ctx, buffer);
342 # define hash_handshake(tls, fmt, buffer, len) \
343 hash_handshake(tls, buffer, len)
345 static void hash_handshake(tls_state_t *tls, const char *fmt, const void *buffer, unsigned len)
347 md5sha_hash(&tls->hsd->handshake_hash_ctx, buffer, len);
350 uint8_t h[TLS_MAX_MAC_SIZE];
351 dump_hex(fmt, buffer, len);
352 dbg(" (%u bytes) ", (int)len);
353 len = sha_peek(&tls->hsd->handshake_hash_ctx, h);
354 if (len == SHA1_OUTSIZE)
355 dump_hex("sha1:%s\n", h, len);
357 if (len == SHA256_OUTSIZE)
358 dump_hex("sha256:%s\n", h, len);
360 dump_hex("sha???:%s\n", h, len);
366 // HMAC(key, text) based on a hash H (say, sha256) is:
367 // ipad = [0x36 x INSIZE]
368 // opad = [0x5c x INSIZE]
369 // HMAC(key, text) = H((key XOR opad) + H((key XOR ipad) + text))
371 // H(key XOR opad) and H(key XOR ipad) can be precomputed
372 // if we often need HMAC hmac with the same key.
374 // text is often given in disjoint pieces.
375 typedef struct hmac_precomputed {
376 md5sha_ctx_t hashed_key_xor_ipad;
377 md5sha_ctx_t hashed_key_xor_opad;
378 } hmac_precomputed_t;
380 static unsigned hmac_sha_precomputed_v(
381 hmac_precomputed_t *pre,
388 /* pre->hashed_key_xor_ipad contains unclosed "H((key XOR ipad) +" state */
389 /* pre->hashed_key_xor_opad contains unclosed "H((key XOR opad) +" state */
391 /* calculate out = H((key XOR ipad) + text) */
392 while ((text = va_arg(va, uint8_t*)) != NULL) {
393 unsigned text_size = va_arg(va, unsigned);
394 md5sha_hash(&pre->hashed_key_xor_ipad, text, text_size);
396 len = sha_end(&pre->hashed_key_xor_ipad, out);
398 /* out = H((key XOR opad) + out) */
399 md5sha_hash(&pre->hashed_key_xor_opad, out, len);
400 return sha_end(&pre->hashed_key_xor_opad, out);
403 typedef void md5sha_begin_func(md5sha_ctx_t *ctx) FAST_FUNC;
404 static void hmac_begin(hmac_precomputed_t *pre, uint8_t *key, unsigned key_size, md5sha_begin_func *begin)
406 uint8_t key_xor_ipad[SHA_INSIZE];
407 uint8_t key_xor_opad[SHA_INSIZE];
408 uint8_t tempkey[SHA1_OUTSIZE < SHA256_OUTSIZE ? SHA256_OUTSIZE : SHA1_OUTSIZE];
411 // "The authentication key can be of any length up to INSIZE, the
412 // block length of the hash function. Applications that use keys longer
413 // than INSIZE bytes will first hash the key using H and then use the
414 // resultant OUTSIZE byte string as the actual key to HMAC."
415 if (key_size > SHA_INSIZE) {
418 md5sha_hash(&ctx, key, key_size);
419 key_size = sha_end(&ctx, tempkey);
422 for (i = 0; i < key_size; i++) {
423 key_xor_ipad[i] = key[i] ^ 0x36;
424 key_xor_opad[i] = key[i] ^ 0x5c;
426 for (; i < SHA_INSIZE; i++) {
427 key_xor_ipad[i] = 0x36;
428 key_xor_opad[i] = 0x5c;
431 begin(&pre->hashed_key_xor_ipad);
432 begin(&pre->hashed_key_xor_opad);
433 md5sha_hash(&pre->hashed_key_xor_ipad, key_xor_ipad, SHA_INSIZE);
434 md5sha_hash(&pre->hashed_key_xor_opad, key_xor_opad, SHA_INSIZE);
437 static unsigned hmac(tls_state_t *tls, uint8_t *out, uint8_t *key, unsigned key_size, ...)
439 hmac_precomputed_t pre;
443 va_start(va, key_size);
445 hmac_begin(&pre, key, key_size,
446 (tls->MAC_size == SHA256_OUTSIZE)
450 len = hmac_sha_precomputed_v(&pre, out, va);
456 static unsigned hmac_sha256(/*tls_state_t *tls,*/ uint8_t *out, uint8_t *key, unsigned key_size, ...)
458 hmac_precomputed_t pre;
462 va_start(va, key_size);
464 hmac_begin(&pre, key, key_size, sha256_begin);
465 len = hmac_sha_precomputed_v(&pre, out, va);
472 // 5. HMAC and the Pseudorandom Function
474 // In this section, we define one PRF, based on HMAC. This PRF with the
475 // SHA-256 hash function is used for all cipher suites defined in this
476 // document and in TLS documents published prior to this document when
477 // TLS 1.2 is negotiated.
478 // ^^^^^^^^^^^^^ IMPORTANT!
479 // PRF uses sha256 regardless of cipher (at least for all ciphers
480 // defined by RFC5246). It's not sha1 for AES_128_CBC_SHA!
482 // P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
483 // HMAC_hash(secret, A(2) + seed) +
484 // HMAC_hash(secret, A(3) + seed) + ...
485 // where + indicates concatenation.
486 // A() is defined as:
488 // A(1) = HMAC_hash(secret, A(0)) = HMAC_hash(secret, seed)
489 // A(i) = HMAC_hash(secret, A(i-1))
490 // P_hash can be iterated as many times as necessary to produce the
491 // required quantity of data. For example, if P_SHA256 is being used to
492 // create 80 bytes of data, it will have to be iterated three times
493 // (through A(3)), creating 96 bytes of output data; the last 16 bytes
494 // of the final iteration will then be discarded, leaving 80 bytes of
497 // TLS's PRF is created by applying P_hash to the secret as:
499 // PRF(secret, label, seed) = P_<hash>(secret, label + seed)
501 // The label is an ASCII string.
502 static void prf_hmac_sha256(/*tls_state_t *tls,*/
503 uint8_t *outbuf, unsigned outbuf_size,
504 uint8_t *secret, unsigned secret_size,
506 uint8_t *seed, unsigned seed_size)
508 uint8_t a[TLS_MAX_MAC_SIZE];
509 uint8_t *out_p = outbuf;
510 unsigned label_size = strlen(label);
511 unsigned MAC_size = SHA256_OUTSIZE;
513 /* In P_hash() calculation, "seed" is "label + seed": */
514 #define SEED label, label_size, seed, seed_size
515 #define SECRET secret, secret_size
516 #define A a, MAC_size
518 /* A(1) = HMAC_hash(secret, seed) */
519 hmac_sha256(/*tls,*/ a, SECRET, SEED, NULL);
520 //TODO: convert hmac to precomputed
523 /* HMAC_hash(secret, A(1) + seed) */
524 if (outbuf_size <= MAC_size) {
525 /* Last, possibly incomplete, block */
526 /* (use a[] as temp buffer) */
527 hmac_sha256(/*tls,*/ a, SECRET, A, SEED, NULL);
528 memcpy(out_p, a, outbuf_size);
531 /* Not last block. Store directly to result buffer */
532 hmac_sha256(/*tls,*/ out_p, SECRET, A, SEED, NULL);
534 outbuf_size -= MAC_size;
535 /* A(2) = HMAC_hash(secret, A(1)) */
536 hmac_sha256(/*tls,*/ a, SECRET, A, NULL);
543 static void bad_record_die(tls_state_t *tls, const char *expected, int len)
545 bb_error_msg("got bad TLS record (len:%d) while expecting %s", len, expected);
547 uint8_t *p = tls->inbuf;
549 len = 99; /* don't flood, a few lines should be enough */
551 fprintf(stderr, " %02x", *p++);
559 static void tls_error_die(tls_state_t *tls, int line)
561 dump_tls_record(tls->inbuf, tls->ofs_to_buffered + tls->buffered_size);
562 bb_error_msg_and_die("tls error at line %d cipher:%04x", line, tls->cipher_id);
564 #define tls_error_die(tls) tls_error_die(tls, __LINE__)
567 static void tls_free_inbuf(tls_state_t *tls)
569 if (tls->buffered_size == 0) {
577 static void tls_free_outbuf(tls_state_t *tls)
580 tls->outbuf_size = 0;
584 static void *tls_get_outbuf(tls_state_t *tls, int len)
586 if (len > TLS_MAX_OUTBUF)
588 len += OUTBUF_PFX + OUTBUF_SFX;
589 if (tls->outbuf_size < len) {
590 tls->outbuf_size = len;
591 tls->outbuf = xrealloc(tls->outbuf, len);
593 return tls->outbuf + OUTBUF_PFX;
596 static void xwrite_encrypted(tls_state_t *tls, unsigned size, unsigned type)
598 uint8_t *buf = tls->outbuf + OUTBUF_PFX;
599 struct record_hdr *xhdr;
600 uint8_t padding_length;
602 xhdr = (void*)(buf - RECHDR_LEN);
603 if (CIPHER_ID1 != TLS_RSA_WITH_NULL_SHA256 /* if "no encryption" can't be selected */
604 || tls->cipher_id != TLS_RSA_WITH_NULL_SHA256 /* or if it wasn't selected */
606 xhdr = (void*)(buf - RECHDR_LEN - AES_BLOCKSIZE); /* place for IV */
610 xhdr->proto_maj = TLS_MAJ;
611 xhdr->proto_min = TLS_MIN;
612 /* fake unencrypted record len for MAC calculation */
613 xhdr->len16_hi = size >> 8;
614 xhdr->len16_lo = size & 0xff;
616 /* Calculate MAC signature */
617 hmac(tls, buf + size, /* result */
618 tls->client_write_MAC_key, tls->MAC_size,
619 &tls->write_seq64_be, sizeof(tls->write_seq64_be),
624 tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(tls->write_seq64_be));
626 size += tls->MAC_size;
629 // 6.2.3.1. Null or Standard Stream Cipher
631 // Stream ciphers (including BulkCipherAlgorithm.null; see Appendix A.6)
632 // convert TLSCompressed.fragment structures to and from stream
633 // TLSCiphertext.fragment structures.
635 // stream-ciphered struct {
636 // opaque content[TLSCompressed.length];
637 // opaque MAC[SecurityParameters.mac_length];
638 // } GenericStreamCipher;
640 // The MAC is generated as:
641 // MAC(MAC_write_key, seq_num +
642 // TLSCompressed.type +
643 // TLSCompressed.version +
644 // TLSCompressed.length +
645 // TLSCompressed.fragment);
646 // where "+" denotes concatenation.
648 // The sequence number for this record.
650 // The MAC algorithm specified by SecurityParameters.mac_algorithm.
652 // Note that the MAC is computed before encryption. The stream cipher
653 // encrypts the entire block, including the MAC.
655 // Appendix C. Cipher Suite Definitions
657 // MAC Algorithm mac_length mac_key_length
658 // -------- ----------- ---------- --------------
659 // SHA HMAC-SHA1 20 20
660 // SHA256 HMAC-SHA256 32 32
661 if (CIPHER_ID1 == TLS_RSA_WITH_NULL_SHA256
662 && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
664 /* No encryption, only signing */
665 xhdr->len16_hi = size >> 8;
666 xhdr->len16_lo = size & 0xff;
667 dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
668 xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
669 dbg("wrote %u bytes (NULL crypt, SHA256 hash)\n", size);
673 // 6.2.3.2. CBC Block Cipher
674 // For block ciphers (such as 3DES or AES), the encryption and MAC
675 // functions convert TLSCompressed.fragment structures to and from block
676 // TLSCiphertext.fragment structures.
678 // opaque IV[SecurityParameters.record_iv_length];
679 // block-ciphered struct {
680 // opaque content[TLSCompressed.length];
681 // opaque MAC[SecurityParameters.mac_length];
682 // uint8 padding[GenericBlockCipher.padding_length];
683 // uint8 padding_length;
685 // } GenericBlockCipher;
688 // The Initialization Vector (IV) SHOULD be chosen at random, and
689 // MUST be unpredictable. Note that in versions of TLS prior to 1.1,
690 // there was no IV field (...). For block ciphers, the IV length is
691 // of length SecurityParameters.record_iv_length, which is equal to the
692 // SecurityParameters.block_size.
694 // Padding that is added to force the length of the plaintext to be
695 // an integral multiple of the block cipher's block length.
697 // The padding length MUST be such that the total size of the
698 // GenericBlockCipher structure is a multiple of the cipher's block
699 // length. Legal values range from zero to 255, inclusive.
701 // Appendix C. Cipher Suite Definitions
704 // Cipher Type Material Size Size
705 // ------------ ------ -------- ---- -----
706 // AES_128_CBC Block 16 16 16
707 // AES_256_CBC Block 32 16 16
709 tls_get_random(buf - AES_BLOCKSIZE, AES_BLOCKSIZE); /* IV */
710 dbg("before crypt: 5 hdr + %u data + %u hash bytes\n",
711 size - tls->MAC_size, tls->MAC_size);
713 /* Fill IV and padding in outbuf */
714 // RFC is talking nonsense:
715 // "Padding that is added to force the length of the plaintext to be
716 // an integral multiple of the block cipher's block length."
717 // WRONG. _padding+padding_length_, not just _padding_,
719 // IOW: padding_length is the last byte of padding[] array,
720 // contrary to what RFC depicts.
722 // What actually happens is that there is always padding.
723 // If you need one byte to reach BLOCKSIZE, this byte is 0x00.
724 // If you need two bytes, they are both 0x01.
725 // If you need three, they are 0x02,0x02,0x02. And so on.
726 // If you need no bytes to reach BLOCKSIZE, you have to pad a full
727 // BLOCKSIZE with bytes of value (BLOCKSIZE-1).
728 // It's ok to have more than minimum padding, but we do minimum.
729 padding_length = (~size) & (AES_BLOCKSIZE - 1);
731 buf[size++] = padding_length; /* padding */
732 } while ((size & (AES_BLOCKSIZE - 1)) != 0);
734 /* Encrypt content+MAC+padding in place */
736 tls->client_write_key, tls->key_size, /* selects 128/256 */
737 buf - AES_BLOCKSIZE, /* IV */
738 buf, size, /* plaintext */
743 dbg("writing 5 + %u IV + %u encrypted bytes, padding_length:0x%02x\n",
744 AES_BLOCKSIZE, size, padding_length);
745 size += AES_BLOCKSIZE; /* + IV */
746 xhdr->len16_hi = size >> 8;
747 xhdr->len16_lo = size & 0xff;
748 dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
749 xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
750 dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
753 static void xwrite_handshake_record(tls_state_t *tls, unsigned size)
755 //if (!tls->encrypt_on_write) {
756 uint8_t *buf = tls->outbuf + OUTBUF_PFX;
757 struct record_hdr *xhdr = (void*)(buf - RECHDR_LEN);
759 xhdr->type = RECORD_TYPE_HANDSHAKE;
760 xhdr->proto_maj = TLS_MAJ;
761 xhdr->proto_min = TLS_MIN;
762 xhdr->len16_hi = size >> 8;
763 xhdr->len16_lo = size & 0xff;
764 dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
765 xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
766 dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
769 //xwrite_encrypted(tls, size, RECORD_TYPE_HANDSHAKE);
772 static void xwrite_and_update_handshake_hash(tls_state_t *tls, unsigned size)
774 if (!tls->encrypt_on_write) {
777 xwrite_handshake_record(tls, size);
778 /* Handshake hash does not include record headers */
779 buf = tls->outbuf + OUTBUF_PFX;
780 hash_handshake(tls, ">> hash:%s", buf, size);
783 xwrite_encrypted(tls, size, RECORD_TYPE_HANDSHAKE);
786 static int tls_has_buffered_record(tls_state_t *tls)
788 int buffered = tls->buffered_size;
789 struct record_hdr *xhdr;
792 if (buffered < RECHDR_LEN)
794 xhdr = (void*)(tls->inbuf + tls->ofs_to_buffered);
795 rec_size = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
796 if (buffered < rec_size)
801 static const char *alert_text(int code)
804 case 20: return "bad MAC";
805 case 50: return "decode error";
806 case 51: return "decrypt error";
807 case 40: return "handshake failure";
808 case 112: return "unrecognized name";
813 static int tls_xread_record(tls_state_t *tls, const char *expected)
815 struct record_hdr *xhdr;
821 dbg("ofs_to_buffered:%u buffered_size:%u\n", tls->ofs_to_buffered, tls->buffered_size);
822 total = tls->buffered_size;
824 memmove(tls->inbuf, tls->inbuf + tls->ofs_to_buffered, total);
825 //dbg("<< remaining at %d [%d] ", tls->ofs_to_buffered, total);
826 //dump_raw_in("<< %s\n", tls->inbuf, total);
833 if (total >= RECHDR_LEN && target == MAX_INBUF) {
834 xhdr = (void*)tls->inbuf;
835 target = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
837 if (target > MAX_INBUF /* malformed input (too long) */
838 || xhdr->proto_maj != TLS_MAJ
839 || xhdr->proto_min != TLS_MIN
841 sz = total < target ? total : target;
842 bad_record_die(tls, expected, sz);
844 dbg("xhdr type:%d ver:%d.%d len:%d\n",
845 xhdr->type, xhdr->proto_maj, xhdr->proto_min,
846 0x100 * xhdr->len16_hi + xhdr->len16_lo
849 /* if total >= target, we have a full packet (and possibly more)... */
850 if (total - target >= 0)
852 /* input buffer is grown only as needed */
853 rem = tls->inbuf_size - total;
855 tls->inbuf_size += MAX_INBUF / 8;
856 if (tls->inbuf_size > MAX_INBUF)
857 tls->inbuf_size = MAX_INBUF;
858 dbg("inbuf_size:%d\n", tls->inbuf_size);
859 rem = tls->inbuf_size - total;
860 tls->inbuf = xrealloc(tls->inbuf, tls->inbuf_size);
862 sz = safe_read(tls->ifd, tls->inbuf + total, rem);
864 if (sz == 0 && total == 0) {
865 /* "Abrupt" EOF, no TLS shutdown (seen from kernel.org) */
866 dbg("EOF (without TLS shutdown) from peer\n");
867 tls->buffered_size = 0;
870 bb_perror_msg_and_die("short read, have only %d", total);
872 dump_raw_in("<< %s\n", tls->inbuf + total, sz);
875 tls->buffered_size = total - target;
876 tls->ofs_to_buffered = target;
877 //dbg("<< stashing at %d [%d] ", tls->ofs_to_buffered, tls->buffered_size);
878 //dump_hex("<< %s\n", tls->inbuf + tls->ofs_to_buffered, tls->buffered_size);
880 sz = target - RECHDR_LEN;
882 /* Needs to be decrypted? */
883 if (tls->min_encrypted_len_on_read > tls->MAC_size) {
884 uint8_t *p = tls->inbuf + RECHDR_LEN;
887 if (sz & (AES_BLOCKSIZE-1)
888 || sz < (int)tls->min_encrypted_len_on_read
890 bb_error_msg_and_die("bad encrypted len:%u < %u",
891 sz, tls->min_encrypted_len_on_read);
893 /* Decrypt content+MAC+padding, moving it over IV in the process */
894 sz -= AES_BLOCKSIZE; /* we will overwrite IV now */
896 tls->server_write_key, tls->key_size, /* selects 128/256 */
898 p + AES_BLOCKSIZE, sz, /* ciphertext */
901 padding_len = p[sz - 1];
902 dbg("encrypted size:%u type:0x%02x padding_length:0x%02x\n", sz, p[0], padding_len);
904 sz -= tls->MAC_size + padding_len; /* drop MAC and padding */
906 // bb_error_msg_and_die("bad padding size:%u", padding_len);
908 /* if nonzero, then it's TLS_RSA_WITH_NULL_SHA256: drop MAC */
909 /* else: no encryption yet on input, subtract zero = NOP */
910 sz -= tls->min_encrypted_len_on_read;
913 bb_error_msg_and_die("encrypted data too short");
915 //dump_hex("<< %s\n", tls->inbuf, RECHDR_LEN + sz);
917 xhdr = (void*)tls->inbuf;
918 if (xhdr->type == RECORD_TYPE_ALERT && sz >= 2) {
919 uint8_t *p = tls->inbuf + RECHDR_LEN;
920 dbg("ALERT size:%d level:%d description:%d\n", sz, p[0], p[1]);
921 if (p[0] == 2) { /* fatal */
922 bb_error_msg_and_die("TLS %s from peer (alert code %d): %s",
924 p[1], alert_text(p[1])
927 if (p[0] == 1) { /* warning */
928 if (p[1] == 0) { /* "close_notify" warning: it's EOF */
929 dbg("EOF (TLS encoded) from peer\n");
933 //This possibly needs to be cached and shown only if
934 //a fatal alert follows
935 // bb_error_msg("TLS %s from peer (alert code %d): %s",
937 // p[1], alert_text(p[1])
939 /* discard it, get next record */
942 /* p[0] not 1 or 2: not defined in protocol */
947 /* RFC 5246 is not saying it explicitly, but sha256 hash
948 * in our FINISHED record must include data of incoming packets too!
950 if (tls->inbuf[0] == RECORD_TYPE_HANDSHAKE
951 && tls->MAC_size != 0 /* do we know which hash to use? (server_hello() does not!) */
953 hash_handshake(tls, "<< hash:%s", tls->inbuf + RECHDR_LEN, sz);
956 dbg("got block len:%u\n", sz);
961 * DER parsing routines
963 static unsigned get_der_len(uint8_t **bodyp, uint8_t *der, uint8_t *end)
969 // if ((der[0] & 0x1f) == 0x1f) /* not single-byte item code? */
972 len = der[1]; /* maybe it's short len */
976 if (len == 0x80 || end - der < (int)(len - 0x7e)) {
977 /* 0x80 is "0 bytes of len", invalid DER: must use short len if can */
978 /* need 3 or 4 bytes for 81, 82 */
982 len1 = der[2]; /* if (len == 0x81) it's "ii 81 xx", fetch xx */
984 /* >0x82 is "3+ bytes of len", should not happen realistically */
987 if (len == 0x82) { /* it's "ii 82 xx yy" */
988 len1 = 0x100*len1 + der[3];
989 der += 1; /* skip [yy] */
991 der += 1; /* skip [xx] */
994 // xfunc_die(); /* invalid DER: must use short len if can */
996 der += 2; /* skip [code]+[1byte] */
998 if (end - der < (int)len)
1005 static uint8_t *enter_der_item(uint8_t *der, uint8_t **endp)
1008 unsigned len = get_der_len(&new_der, der, *endp);
1009 dbg_der("entered der @%p:0x%02x len:%u inner_byte @%p:0x%02x\n", der, der[0], len, new_der, new_der[0]);
1010 /* Move "end" position to cover only this item */
1011 *endp = new_der + len;
1015 static uint8_t *skip_der_item(uint8_t *der, uint8_t *end)
1018 unsigned len = get_der_len(&new_der, der, end);
1021 dbg_der("skipped der 0x%02x, next byte 0x%02x\n", der[0], new_der[0]);
1025 static void der_binary_to_pstm(pstm_int *pstm_n, uint8_t *der, uint8_t *end)
1028 unsigned len = get_der_len(&bin_ptr, der, end);
1030 dbg_der("binary bytes:%u, first:0x%02x\n", len, bin_ptr[0]);
1031 pstm_init_for_read_unsigned_bin(/*pool:*/ NULL, pstm_n, len);
1032 pstm_read_unsigned_bin(pstm_n, bin_ptr, len);
1036 static void find_key_in_der_cert(tls_state_t *tls, uint8_t *der, int len)
1038 /* Certificate is a DER-encoded data structure. Each DER element has a length,
1039 * which makes it easy to skip over large compound elements of any complexity
1040 * without parsing them. Example: partial decode of kernel.org certificate:
1041 * SEQ 0x05ac/1452 bytes (Certificate): 308205ac
1042 * SEQ 0x0494/1172 bytes (tbsCertificate): 30820494
1043 * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0] 3 bytes: a003
1044 * INTEGER (version): 0201 02
1045 * INTEGER 0x11 bytes (serialNumber): 0211 00 9f85bf664b0cddafca508679501b2be4
1046 * //^^^^^^note: matrixSSL also allows [ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2] = 0x82 type
1047 * SEQ 0x0d bytes (signatureAlgo): 300d
1048 * OID 9 bytes: 0609 2a864886f70d01010b (OID_SHA256_RSA_SIG 42.134.72.134.247.13.1.1.11)
1050 * SEQ 0x5f bytes (issuer): 305f
1051 * SET 11 bytes: 310b
1053 * OID 3 bytes: 0603 550406
1054 * Printable string "FR": 1302 4652
1055 * SET 14 bytes: 310e
1056 * SEQ 12 bytes: 300c
1057 * OID 3 bytes: 0603 550408
1058 * Printable string "Paris": 1305 5061726973
1059 * SET 14 bytes: 310e
1060 * SEQ 12 bytes: 300c
1061 * OID 3 bytes: 0603 550407
1062 * Printable string "Paris": 1305 5061726973
1063 * SET 14 bytes: 310e
1064 * SEQ 12 bytes: 300c
1065 * OID 3 bytes: 0603 55040a
1066 * Printable string "Gandi": 1305 47616e6469
1067 * SET 32 bytes: 3120
1068 * SEQ 30 bytes: 301e
1069 * OID 3 bytes: 0603 550403
1070 * Printable string "Gandi Standard SSL CA 2": 1317 47616e6469205374616e646172642053534c2043412032
1071 * SEQ 30 bytes (validity): 301e
1072 * TIME "161011000000Z": 170d 3136313031313030303030305a
1073 * TIME "191011235959Z": 170d 3139313031313233353935395a
1074 * SEQ 0x5b/91 bytes (subject): 305b //I did not decode this
1075 * 3121301f060355040b1318446f6d61696e20436f
1076 * 6e74726f6c2056616c6964617465643121301f06
1077 * 0355040b1318506f73697469766553534c204d75
1078 * 6c74692d446f6d61696e31133011060355040313
1079 * 0a6b65726e656c2e6f7267
1080 * SEQ 0x01a2/418 bytes (subjectPublicKeyInfo): 308201a2
1081 * SEQ 13 bytes (algorithm): 300d
1082 * OID 9 bytes: 0609 2a864886f70d010101 (OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1)
1084 * BITSTRING 0x018f/399 bytes (publicKey): 0382018f
1086 * //after the zero byte, it appears key itself uses DER encoding:
1087 * SEQ 0x018a/394 bytes: 3082018a
1088 * INTEGER 0x0181/385 bytes (modulus): 02820181
1089 * 00b1ab2fc727a3bef76780c9349bf3
1090 * ...24 more blocks of 15 bytes each...
1091 * 90e895291c6bc8693b65
1092 * INTEGER 3 bytes (exponent): 0203 010001
1093 * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0x3] 0x01e5 bytes (X509v3 extensions): a38201e5
1094 * SEQ 0x01e1 bytes: 308201e1
1096 * Certificate is a sequence of three elements:
1097 * tbsCertificate (SEQ)
1098 * signatureAlgorithm (AlgorithmIdentifier)
1099 * signatureValue (BIT STRING)
1101 * In turn, tbsCertificate is a sequence of:
1104 * signatureAlgo (AlgorithmIdentifier)
1105 * issuer (Name, has complex structure)
1106 * validity (Validity, SEQ of two Times)
1108 * subjectPublicKeyInfo (SEQ)
1111 * subjectPublicKeyInfo is a sequence of:
1112 * algorithm (AlgorithmIdentifier)
1113 * publicKey (BIT STRING)
1115 * We need Certificate.tbsCertificate.subjectPublicKeyInfo.publicKey
1117 uint8_t *end = der + len;
1118 uint8_t tag_class, pc, tag_number;
1119 int version_present;
1121 /* enter "Certificate" item: [der, end) will be only Cert */
1122 der = enter_der_item(der, &end);
1124 /* enter "tbsCertificate" item: [der, end) will be only tbsCert */
1125 der = enter_der_item(der, &end);
1128 * Skip version field only if it is present. For a v1 certificate, the
1129 * version field won't be present since v1 is the default value for the
1130 * version field and fields with default values should be omitted (see
1131 * RFC 5280 sections 4.1 and 4.1.2.1). If the version field is present
1132 * it will have a tag class of 2 (context-specific), bit 6 as 1
1133 * (constructed), and a tag number of 0 (see ITU-T X.690 sections 8.1.2
1136 tag_class = der[0] >> 6; /* bits 8-7 */
1137 pc = (der[0] & 32) >> 5; /* bit 6 */
1138 tag_number = der[0] & 31; /* bits 5-1 */
1139 version_present = tag_class == 2 && pc == 1 && tag_number == 0;
1140 if (version_present) {
1141 der = skip_der_item(der, end); /* version */
1144 /* skip up to subjectPublicKeyInfo */
1145 der = skip_der_item(der, end); /* serialNumber */
1146 der = skip_der_item(der, end); /* signatureAlgo */
1147 der = skip_der_item(der, end); /* issuer */
1148 der = skip_der_item(der, end); /* validity */
1149 der = skip_der_item(der, end); /* subject */
1151 /* enter subjectPublicKeyInfo */
1152 der = enter_der_item(der, &end);
1153 { /* check subjectPublicKeyInfo.algorithm */
1154 static const uint8_t expected[] = {
1155 0x30,0x0d, // SEQ 13 bytes
1156 0x06,0x09, 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01, // OID RSA_KEY_ALG 42.134.72.134.247.13.1.1.1
1157 //0x05,0x00, // NULL
1159 if (memcmp(der, expected, sizeof(expected)) != 0)
1160 bb_error_msg_and_die("not RSA key");
1162 /* skip subjectPublicKeyInfo.algorithm */
1163 der = skip_der_item(der, end);
1164 /* enter subjectPublicKeyInfo.publicKey */
1165 // die_if_not_this_der_type(der, end, 0x03); /* must be BITSTRING */
1166 der = enter_der_item(der, &end);
1168 /* parse RSA key: */
1169 //based on getAsnRsaPubKey(), pkcs1ParsePrivBin() is also of note
1170 dbg("key bytes:%u, first:0x%02x\n", (int)(end - der), der[0]);
1171 if (end - der < 14) xfunc_die();
1174 * SEQ 0x018a/394 bytes: 3082018a
1175 * INTEGER 0x0181/385 bytes (modulus): 02820181 XX...XXX
1176 * INTEGER 3 bytes (exponent): 0203 010001
1178 if (*der != 0) /* "ignore bits", should be 0 */
1181 der = enter_der_item(der, &end); /* enter SEQ */
1182 /* memset(tls->hsd->server_rsa_pub_key, 0, sizeof(tls->hsd->server_rsa_pub_key)); - already is */
1183 der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.N, der, end); /* modulus */
1184 der = skip_der_item(der, end);
1185 der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.e, der, end); /* exponent */
1186 tls->hsd->server_rsa_pub_key.size = pstm_unsigned_bin_size(&tls->hsd->server_rsa_pub_key.N);
1187 dbg("server_rsa_pub_key.size:%d\n", tls->hsd->server_rsa_pub_key.size);
1191 * TLS Handshake routines
1193 static int tls_xread_handshake_block(tls_state_t *tls, int min_len)
1195 struct record_hdr *xhdr;
1196 int len = tls_xread_record(tls, "handshake record");
1198 xhdr = (void*)tls->inbuf;
1200 || xhdr->type != RECORD_TYPE_HANDSHAKE
1202 bad_record_die(tls, "handshake record", len);
1204 dbg("got HANDSHAKE\n");
1208 static ALWAYS_INLINE void fill_handshake_record_hdr(void *buf, unsigned type, unsigned len)
1210 struct handshake_hdr {
1212 uint8_t len24_hi, len24_mid, len24_lo;
1217 h->len24_hi = len >> 16;
1218 h->len24_mid = len >> 8;
1219 h->len24_lo = len & 0xff;
1222 static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
1224 struct client_hello {
1226 uint8_t len24_hi, len24_mid, len24_lo;
1227 uint8_t proto_maj, proto_min;
1229 uint8_t session_id_len;
1230 /* uint8_t session_id[]; */
1231 uint8_t cipherid_len16_hi, cipherid_len16_lo;
1232 uint8_t cipherid[2 * (2 + !!CIPHER_ID2)]; /* actually variable */
1233 uint8_t comprtypes_len;
1234 uint8_t comprtypes[1]; /* actually variable */
1235 /* Extensions (SNI shown):
1236 * hi,lo // len of all extensions
1237 * 00,00 // extension_type: "Server Name"
1238 * 00,0e // list len (there can be more than one SNI)
1239 * 00,0c // len of 1st Server Name Indication
1240 * 00 // name type: host_name
1242 * "localhost" // name
1244 // GNU Wget 1.18 to cdn.kernel.org sends these extensions:
1246 // 0005 0005 0100000000 - status_request
1247 // 0000 0013 0011 00 000e 63646e 2e 6b65726e656c 2e 6f7267 - server_name
1248 // ff01 0001 00 - renegotiation_info
1249 // 0023 0000 - session_ticket
1250 // 000a 0008 0006001700180019 - supported_groups
1251 // 000b 0002 0100 - ec_point_formats
1252 // 000d 0016 0014 0401 0403 0501 0503 0601 0603 0301 0303 0201 0203 - signature_algorithms
1253 // wolfssl library sends this option, RFC 7627 (closes a security weakness, some servers may require it. TODO?):
1254 // 0017 0000 - extended master secret
1256 struct client_hello *record;
1258 int sni_len = sni ? strnlen(sni, 127 - 9) : 0;
1260 len = sizeof(*record);
1262 len += 11 + sni_len;
1263 record = tls_get_outbuf(tls, len);
1264 memset(record, 0, len);
1266 fill_handshake_record_hdr(record, HANDSHAKE_CLIENT_HELLO, len);
1267 record->proto_maj = TLS_MAJ; /* the "requested" version of the protocol, */
1268 record->proto_min = TLS_MIN; /* can be higher than one in record headers */
1269 tls_get_random(record->rand32, sizeof(record->rand32));
1270 if (TLS_DEBUG_FIXED_SECRETS)
1271 memset(record->rand32, 0x11, sizeof(record->rand32));
1272 /* record->session_id_len = 0; - already is */
1274 /* record->cipherid_len16_hi = 0; */
1275 record->cipherid_len16_lo = sizeof(record->cipherid);
1276 /* RFC 5746 Renegotiation Indication Extension - some servers will refuse to work with us otherwise */
1277 /*record->cipherid[0] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV >> 8; - zero */
1278 record->cipherid[1] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV & 0xff;
1279 if ((CIPHER_ID1 >> 8) != 0) record->cipherid[2] = CIPHER_ID1 >> 8;
1280 /*************************/ record->cipherid[3] = CIPHER_ID1 & 0xff;
1282 if ((CIPHER_ID2 >> 8) != 0) record->cipherid[4] = CIPHER_ID2 >> 8;
1283 /*************************/ record->cipherid[5] = CIPHER_ID2 & 0xff;
1286 record->comprtypes_len = 1;
1287 /* record->comprtypes[0] = 0; */
1290 uint8_t *p = (void*)(record + 1);
1292 p[1] = sni_len + 9; //ext_len
1294 //p[3] = 0; //extension_type
1296 p[5] = sni_len + 5; //list len
1298 p[7] = sni_len + 3; //len of 1st SNI
1299 //p[8] = 0; //name type
1301 p[10] = sni_len; //name len
1302 memcpy(&p[11], sni, sni_len);
1305 dbg(">> CLIENT_HELLO\n");
1306 /* Can hash it only when we know which MAC hash to use */
1307 /*xwrite_and_update_handshake_hash(tls, len); - WRONG! */
1308 xwrite_handshake_record(tls, len);
1310 tls->hsd = xzalloc(sizeof(*tls->hsd) + len);
1311 tls->hsd->saved_client_hello_size = len;
1312 memcpy(tls->hsd->saved_client_hello, record, len);
1313 memcpy(tls->hsd->client_and_server_rand32, record->rand32, sizeof(record->rand32));
1316 static void get_server_hello(tls_state_t *tls)
1318 struct server_hello {
1319 struct record_hdr xhdr;
1321 uint8_t len24_hi, len24_mid, len24_lo;
1322 uint8_t proto_maj, proto_min;
1323 uint8_t rand32[32]; /* first 4 bytes are unix time in BE format */
1324 uint8_t session_id_len;
1325 uint8_t session_id[32];
1326 uint8_t cipherid_hi, cipherid_lo;
1328 /* extensions may follow, but only those which client offered in its Hello */
1331 struct server_hello *hp;
1336 len = tls_xread_handshake_block(tls, 74 - 32);
1338 hp = (void*)tls->inbuf;
1340 // 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|
1341 //SvHl len=70 maj.min unixtime^^^ 28randbytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^ slen sid32bytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cipSel comprSel
1342 if (hp->type != HANDSHAKE_SERVER_HELLO
1343 || hp->len24_hi != 0
1344 || hp->len24_mid != 0
1345 /* hp->len24_lo checked later */
1346 || hp->proto_maj != TLS_MAJ
1347 || hp->proto_min != TLS_MIN
1349 bad_record_die(tls, "'server hello'", len);
1352 cipherid = &hp->cipherid_hi;
1353 len24 = hp->len24_lo;
1354 if (hp->session_id_len != 32) {
1355 if (hp->session_id_len != 0)
1356 bad_record_die(tls, "'server hello'", len);
1358 // session_id_len == 0: no session id
1360 // may return an empty session_id to indicate that the session will
1361 // not be cached and therefore cannot be resumed."
1363 len24 += 32; /* what len would be if session id would be present */
1367 // || cipherid[0] != (CIPHER_ID >> 8)
1368 // || cipherid[1] != (CIPHER_ID & 0xff)
1369 // || cipherid[2] != 0 /* comprtype */
1371 bad_record_die(tls, "'server hello'", len);
1373 dbg("<< SERVER_HELLO\n");
1375 memcpy(tls->hsd->client_and_server_rand32 + 32, hp->rand32, sizeof(hp->rand32));
1377 tls->cipher_id = cipher = 0x100 * cipherid[0] + cipherid[1];
1378 dbg("server chose cipher %04x\n", cipher);
1380 if (cipher == TLS_RSA_WITH_AES_128_CBC_SHA) {
1381 tls->key_size = AES128_KEYSIZE;
1382 tls->MAC_size = SHA1_OUTSIZE;
1384 else { /* TLS_RSA_WITH_AES_256_CBC_SHA256 */
1385 tls->key_size = AES256_KEYSIZE;
1386 tls->MAC_size = SHA256_OUTSIZE;
1388 /* Handshake hash eventually destined to FINISHED record
1389 * is sha256 regardless of cipher
1390 * (at least for all ciphers defined by RFC5246).
1391 * It's not sha1 for AES_128_CBC_SHA - only MAC is sha1, not this hash.
1393 sha256_begin(&tls->hsd->handshake_hash_ctx);
1394 hash_handshake(tls, ">> client hello hash:%s",
1395 tls->hsd->saved_client_hello, tls->hsd->saved_client_hello_size
1397 hash_handshake(tls, "<< server hello hash:%s",
1398 tls->inbuf + RECHDR_LEN, len
1402 static void get_server_cert(tls_state_t *tls)
1404 struct record_hdr *xhdr;
1408 len = tls_xread_handshake_block(tls, 10);
1410 xhdr = (void*)tls->inbuf;
1411 certbuf = (void*)(xhdr + 1);
1412 if (certbuf[0] != HANDSHAKE_CERTIFICATE)
1413 bad_record_die(tls, "certificate", len);
1414 dbg("<< CERTIFICATE\n");
1416 // 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...
1417 //Cert len=4388 ChainLen CertLen^ DER encoded X509 starts here. openssl x509 -in FILE -inform DER -noout -text
1418 len1 = get24be(certbuf + 1);
1419 if (len1 > len - 4) tls_error_die(tls);
1421 len1 = get24be(certbuf + 4);
1422 if (len1 > len - 3) tls_error_die(tls);
1424 len1 = get24be(certbuf + 7);
1425 if (len1 > len - 3) tls_error_die(tls);
1429 find_key_in_der_cert(tls, certbuf + 10, len);
1432 static void send_empty_client_cert(tls_state_t *tls)
1434 struct client_empty_cert {
1436 uint8_t len24_hi, len24_mid, len24_lo;
1437 uint8_t cert_chain_len24_hi, cert_chain_len24_mid, cert_chain_len24_lo;
1439 struct client_empty_cert *record;
1441 record = tls_get_outbuf(tls, sizeof(*record));
1442 //FIXME: can just memcpy a ready-made one.
1443 fill_handshake_record_hdr(record, HANDSHAKE_CERTIFICATE, sizeof(*record));
1444 record->cert_chain_len24_hi = 0;
1445 record->cert_chain_len24_mid = 0;
1446 record->cert_chain_len24_lo = 0;
1448 dbg(">> CERTIFICATE\n");
1449 xwrite_and_update_handshake_hash(tls, sizeof(*record));
1452 static void send_client_key_exchange(tls_state_t *tls)
1454 struct client_key_exchange {
1456 uint8_t len24_hi, len24_mid, len24_lo;
1457 /* keylen16 exists for RSA (in TLS, not in SSL), but not for some other key types */
1458 uint8_t keylen16_hi, keylen16_lo;
1459 uint8_t key[4 * 1024]; // size??
1461 //FIXME: better size estimate
1462 struct client_key_exchange *record = tls_get_outbuf(tls, sizeof(*record));
1463 uint8_t rsa_premaster[RSA_PREMASTER_SIZE];
1466 tls_get_random(rsa_premaster, sizeof(rsa_premaster));
1467 if (TLS_DEBUG_FIXED_SECRETS)
1468 memset(rsa_premaster, 0x44, sizeof(rsa_premaster));
1470 // "Note: The version number in the PreMasterSecret is the version
1471 // offered by the client in the ClientHello.client_version, not the
1472 // version negotiated for the connection."
1473 rsa_premaster[0] = TLS_MAJ;
1474 rsa_premaster[1] = TLS_MIN;
1475 dump_hex("premaster:%s\n", rsa_premaster, sizeof(rsa_premaster));
1476 len = psRsaEncryptPub(/*pool:*/ NULL,
1477 /* psRsaKey_t* */ &tls->hsd->server_rsa_pub_key,
1478 rsa_premaster, /*inlen:*/ sizeof(rsa_premaster),
1479 record->key, sizeof(record->key),
1482 record->keylen16_hi = len >> 8;
1483 record->keylen16_lo = len & 0xff;
1485 record->type = HANDSHAKE_CLIENT_KEY_EXCHANGE;
1486 record->len24_hi = 0;
1487 record->len24_mid = len >> 8;
1488 record->len24_lo = len & 0xff;
1491 dbg(">> CLIENT_KEY_EXCHANGE\n");
1492 xwrite_and_update_handshake_hash(tls, len);
1495 // For all key exchange methods, the same algorithm is used to convert
1496 // the pre_master_secret into the master_secret. The pre_master_secret
1497 // should be deleted from memory once the master_secret has been
1499 // master_secret = PRF(pre_master_secret, "master secret",
1500 // ClientHello.random + ServerHello.random)
1502 // The master secret is always exactly 48 bytes in length. The length
1503 // of the premaster secret will vary depending on key exchange method.
1504 prf_hmac_sha256(/*tls,*/
1505 tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
1506 rsa_premaster, sizeof(rsa_premaster),
1508 tls->hsd->client_and_server_rand32, sizeof(tls->hsd->client_and_server_rand32)
1510 dump_hex("master secret:%s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
1513 // 6.3. Key Calculation
1515 // The Record Protocol requires an algorithm to generate keys required
1516 // by the current connection state (see Appendix A.6) from the security
1517 // parameters provided by the handshake protocol.
1519 // The master secret is expanded into a sequence of secure bytes, which
1520 // is then split to a client write MAC key, a server write MAC key, a
1521 // client write encryption key, and a server write encryption key. Each
1522 // of these is generated from the byte sequence in that order. Unused
1523 // values are empty. Some AEAD ciphers may additionally require a
1524 // client write IV and a server write IV (see Section 6.2.3.3).
1526 // When keys and MAC keys are generated, the master secret is used as an
1529 // To generate the key material, compute
1531 // key_block = PRF(SecurityParameters.master_secret,
1533 // SecurityParameters.server_random +
1534 // SecurityParameters.client_random);
1536 // until enough output has been generated. Then, the key_block is
1537 // partitioned as follows:
1539 // client_write_MAC_key[SecurityParameters.mac_key_length]
1540 // server_write_MAC_key[SecurityParameters.mac_key_length]
1541 // client_write_key[SecurityParameters.enc_key_length]
1542 // server_write_key[SecurityParameters.enc_key_length]
1543 // client_write_IV[SecurityParameters.fixed_iv_length]
1544 // server_write_IV[SecurityParameters.fixed_iv_length]
1548 /* make "server_rand32 + client_rand32" */
1549 memcpy(&tmp64[0] , &tls->hsd->client_and_server_rand32[32], 32);
1550 memcpy(&tmp64[32], &tls->hsd->client_and_server_rand32[0] , 32);
1552 prf_hmac_sha256(/*tls,*/
1553 tls->client_write_MAC_key, 2 * (tls->MAC_size + tls->key_size),
1555 // server_write_MAC_key[]
1556 // client_write_key[]
1557 // server_write_key[]
1558 tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
1562 tls->client_write_key = tls->client_write_MAC_key + (2 * tls->MAC_size);
1563 tls->server_write_key = tls->client_write_key + tls->key_size;
1564 dump_hex("client_write_MAC_key:%s\n",
1565 tls->client_write_MAC_key, tls->MAC_size
1567 dump_hex("client_write_key:%s\n",
1568 tls->client_write_key, tls->key_size
1573 static const uint8_t rec_CHANGE_CIPHER_SPEC[] = {
1574 RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
1578 static void send_change_cipher_spec(tls_state_t *tls)
1580 dbg(">> CHANGE_CIPHER_SPEC\n");
1581 xwrite(tls->ofd, rec_CHANGE_CIPHER_SPEC, sizeof(rec_CHANGE_CIPHER_SPEC));
1585 // A Finished message is always sent immediately after a change
1586 // cipher spec message to verify that the key exchange and
1587 // authentication processes were successful. It is essential that a
1588 // change cipher spec message be received between the other handshake
1589 // messages and the Finished message.
1591 // The Finished message is the first one protected with the just
1592 // negotiated algorithms, keys, and secrets. Recipients of Finished
1593 // messages MUST verify that the contents are correct. Once a side
1594 // has sent its Finished message and received and validated the
1595 // Finished message from its peer, it may begin to send and receive
1596 // application data over the connection.
1599 // opaque verify_data[verify_data_length];
1603 // PRF(master_secret, finished_label, Hash(handshake_messages))
1604 // [0..verify_data_length-1];
1607 // For Finished messages sent by the client, the string
1608 // "client finished". For Finished messages sent by the server,
1609 // the string "server finished".
1611 // Hash denotes a Hash of the handshake messages. For the PRF
1612 // defined in Section 5, the Hash MUST be the Hash used as the basis
1613 // for the PRF. Any cipher suite which defines a different PRF MUST
1614 // also define the Hash to use in the Finished computation.
1616 // In previous versions of TLS, the verify_data was always 12 octets
1617 // long. In the current version of TLS, it depends on the cipher
1618 // suite. Any cipher suite which does not explicitly specify
1619 // verify_data_length has a verify_data_length equal to 12. This
1620 // includes all existing cipher suites.
1621 static void send_client_finished(tls_state_t *tls)
1625 uint8_t len24_hi, len24_mid, len24_lo;
1626 uint8_t prf_result[12];
1628 struct finished *record = tls_get_outbuf(tls, sizeof(*record));
1629 uint8_t handshake_hash[TLS_MAX_MAC_SIZE];
1632 fill_handshake_record_hdr(record, HANDSHAKE_FINISHED, sizeof(*record));
1634 len = get_handshake_hash(tls, handshake_hash);
1635 prf_hmac_sha256(/*tls,*/
1636 record->prf_result, sizeof(record->prf_result),
1637 tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
1641 dump_hex("from secret: %s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
1642 dump_hex("from labelSeed: %s", "client finished", sizeof("client finished")-1);
1643 dump_hex("%s\n", handshake_hash, sizeof(handshake_hash));
1644 dump_hex("=> digest: %s\n", record->prf_result, sizeof(record->prf_result));
1646 dbg(">> FINISHED\n");
1647 xwrite_encrypted(tls, sizeof(*record), RECORD_TYPE_HANDSHAKE);
1650 void FAST_FUNC tls_handshake(tls_state_t *tls, const char *sni)
1652 // Client RFC 5246 Server
1653 // (*) - optional messages, not always sent
1655 // ClientHello ------->
1658 // ServerKeyExchange*
1659 // CertificateRequest*
1660 // <------- ServerHelloDone
1662 // ClientKeyExchange
1663 // CertificateVerify*
1664 // [ChangeCipherSpec]
1665 // Finished ------->
1666 // [ChangeCipherSpec]
1667 // <------- Finished
1668 // Application Data <------> Application Data
1672 send_client_hello_and_alloc_hsd(tls, sni);
1673 get_server_hello(tls);
1676 // The server MUST send a Certificate message whenever the agreed-
1677 // upon key exchange method uses certificates for authentication
1678 // (this includes all key exchange methods defined in this document
1679 // except DH_anon). This message will always immediately follow the
1680 // ServerHello message.
1682 // IOW: in practice, Certificate *always* follows.
1683 // (for example, kernel.org does not even accept DH_anon cipher id)
1684 get_server_cert(tls);
1686 len = tls_xread_handshake_block(tls, 4);
1687 if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_SERVER_KEY_EXCHANGE) {
1689 // 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...
1691 // with TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 461 bytes:
1692 // 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...
1693 dbg("<< SERVER_KEY_EXCHANGE len:%u\n", len);
1694 //probably need to save it
1695 len = tls_xread_handshake_block(tls, 4);
1698 got_cert_req = (tls->inbuf[RECHDR_LEN] == HANDSHAKE_CERTIFICATE_REQUEST);
1700 dbg("<< CERTIFICATE_REQUEST\n");
1701 // RFC 5246: "If no suitable certificate is available,
1702 // the client MUST send a certificate message containing no
1703 // certificates. That is, the certificate_list structure has a
1704 // length of zero. ...
1705 // Client certificates are sent using the Certificate structure
1706 // defined in Section 7.4.2."
1707 // (i.e. the same format as server certs)
1709 /*send_empty_client_cert(tls); - WRONG (breaks handshake hash calc) */
1710 /* need to hash _all_ server replies first, up to ServerHelloDone */
1711 len = tls_xread_handshake_block(tls, 4);
1714 if (tls->inbuf[RECHDR_LEN] != HANDSHAKE_SERVER_HELLO_DONE) {
1715 bad_record_die(tls, "'server hello done'", len);
1717 // 0e 000000 (len:0)
1718 dbg("<< SERVER_HELLO_DONE\n");
1721 send_empty_client_cert(tls);
1723 send_client_key_exchange(tls);
1725 send_change_cipher_spec(tls);
1726 /* from now on we should send encrypted */
1727 /* tls->write_seq64_be = 0; - already is */
1728 tls->encrypt_on_write = 1;
1730 send_client_finished(tls);
1732 /* Get CHANGE_CIPHER_SPEC */
1733 len = tls_xread_record(tls, "switch to encrypted traffic");
1734 if (len != 1 || memcmp(tls->inbuf, rec_CHANGE_CIPHER_SPEC, 6) != 0)
1735 bad_record_die(tls, "switch to encrypted traffic", len);
1736 dbg("<< CHANGE_CIPHER_SPEC\n");
1737 if (CIPHER_ID1 == TLS_RSA_WITH_NULL_SHA256
1738 && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
1740 tls->min_encrypted_len_on_read = tls->MAC_size;
1742 unsigned mac_blocks = (unsigned)(tls->MAC_size + AES_BLOCKSIZE-1) / AES_BLOCKSIZE;
1743 /* all incoming packets now should be encrypted and have
1744 * at least IV + (MAC padded to blocksize):
1746 tls->min_encrypted_len_on_read = AES_BLOCKSIZE + (mac_blocks * AES_BLOCKSIZE);
1747 dbg("min_encrypted_len_on_read: %u", tls->min_encrypted_len_on_read);
1750 /* Get (encrypted) FINISHED from the server */
1751 len = tls_xread_record(tls, "'server finished'");
1752 if (len < 4 || tls->inbuf[RECHDR_LEN] != HANDSHAKE_FINISHED)
1753 bad_record_die(tls, "'server finished'", len);
1754 dbg("<< FINISHED\n");
1755 /* application data can be sent/received */
1757 /* free handshake data */
1759 // memset(tls->hsd, 0, tls->hsd->hsd_size);
1764 static void tls_xwrite(tls_state_t *tls, int len)
1767 xwrite_encrypted(tls, len, RECORD_TYPE_APPLICATION_DATA);
1770 // To run a test server using openssl:
1771 // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
1772 // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1
1774 // Unencryped SHA256 example:
1775 // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
1776 // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL
1777 // openssl s_client -connect 127.0.0.1:4433 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL-SHA256
1779 void FAST_FUNC tls_run_copy_loop(tls_state_t *tls, unsigned flags)
1782 const int INBUF_STEP = 4 * 1024;
1783 struct pollfd pfds[2];
1785 pfds[0].fd = STDIN_FILENO;
1786 pfds[0].events = POLLIN;
1787 pfds[1].fd = tls->ifd;
1788 pfds[1].events = POLLIN;
1790 inbuf_size = INBUF_STEP;
1794 if (safe_poll(pfds, 2, -1) < 0)
1795 bb_perror_msg_and_die("poll");
1797 if (pfds[0].revents) {
1800 dbg("STDIN HAS DATA\n");
1801 buf = tls_get_outbuf(tls, inbuf_size);
1802 nread = safe_read(STDIN_FILENO, buf, inbuf_size);
1804 /* We'd want to do this: */
1805 /* Close outgoing half-connection so they get EOF,
1806 * but leave incoming alone so we can see response
1808 //shutdown(tls->ofd, SHUT_WR);
1809 /* But TLS has no way to encode this,
1810 * doubt it's ok to do it "raw"
1813 tls_free_outbuf(tls); /* mem usage optimization */
1814 if (flags & TLSLOOP_EXIT_ON_LOCAL_EOF)
1817 if (nread == inbuf_size) {
1818 /* TLS has per record overhead, if input comes fast,
1819 * read, encrypt and send bigger chunks
1821 inbuf_size += INBUF_STEP;
1822 if (inbuf_size > TLS_MAX_OUTBUF)
1823 inbuf_size = TLS_MAX_OUTBUF;
1825 tls_xwrite(tls, nread);
1828 if (pfds[1].revents) {
1829 dbg("NETWORK HAS DATA\n");
1831 nread = tls_xread_record(tls, "encrypted data");
1833 /* TLS protocol has no real concept of one-sided shutdowns:
1834 * if we get "TLS EOF" from the peer, writes will fail too
1837 //close(STDOUT_FILENO);
1838 //tls_free_inbuf(tls); /* mem usage optimization */
1842 if (tls->inbuf[0] != RECORD_TYPE_APPLICATION_DATA)
1843 bad_record_die(tls, "encrypted data", nread);
1844 xwrite(STDOUT_FILENO, tls->inbuf + RECHDR_LEN, nread);
1845 /* We may already have a complete next record buffered,
1846 * can process it without network reads (and possible blocking)
1848 if (tls_has_buffered_record(tls))