2 * Copyright (C) 2017 Denys Vlasenko
4 * Licensed under GPLv2, see file LICENSE in this source tree.
7 //config: bool "tls (debugging)"
10 //applet:IF_TLS(APPLET(tls, BB_DIR_USR_BIN, BB_SUID_DROP))
12 //kbuild:lib-$(CONFIG_TLS) += tls.o
13 //kbuild:lib-$(CONFIG_TLS) += tls_pstm.o
14 //kbuild:lib-$(CONFIG_TLS) += tls_pstm_montgomery_reduce.o
15 //kbuild:lib-$(CONFIG_TLS) += tls_pstm_mul_comba.o
16 //kbuild:lib-$(CONFIG_TLS) += tls_pstm_sqr_comba.o
17 //kbuild:lib-$(CONFIG_TLS) += tls_rsa.o
18 //kbuild:lib-$(CONFIG_TLS) += tls_aes.o
19 ////kbuild:lib-$(CONFIG_TLS) += tls_aes_gcm.o
21 //usage:#define tls_trivial_usage
22 //usage: "HOST[:PORT]"
23 //usage:#define tls_full_usage "\n\n"
26 //#include "common_bufsiz.h"
29 #define TLS_DEBUG_HASH 1
30 #define TLS_DEBUG_DER 0
31 #define TLS_DEBUG_FIXED_SECRETS 0
34 # define dbg(...) fprintf(stderr, __VA_ARGS__)
36 # define dbg(...) ((void)0)
40 # define dbg_der(...) fprintf(stderr, __VA_ARGS__)
42 # define dbg_der(...) ((void)0)
45 #define RECORD_TYPE_CHANGE_CIPHER_SPEC 20
46 #define RECORD_TYPE_ALERT 21
47 #define RECORD_TYPE_HANDSHAKE 22
48 #define RECORD_TYPE_APPLICATION_DATA 23
50 #define HANDSHAKE_HELLO_REQUEST 0
51 #define HANDSHAKE_CLIENT_HELLO 1
52 #define HANDSHAKE_SERVER_HELLO 2
53 #define HANDSHAKE_HELLO_VERIFY_REQUEST 3
54 #define HANDSHAKE_NEW_SESSION_TICKET 4
55 #define HANDSHAKE_CERTIFICATE 11
56 #define HANDSHAKE_SERVER_KEY_EXCHANGE 12
57 #define HANDSHAKE_CERTIFICATE_REQUEST 13
58 #define HANDSHAKE_SERVER_HELLO_DONE 14
59 #define HANDSHAKE_CERTIFICATE_VERIFY 15
60 #define HANDSHAKE_CLIENT_KEY_EXCHANGE 16
61 #define HANDSHAKE_FINISHED 20
63 #define SSL_HS_RANDOM_SIZE 32
64 #define SSL_HS_RSA_PREMASTER_SIZE 48
66 #define SSL_NULL_WITH_NULL_NULL 0x0000
67 #define SSL_RSA_WITH_NULL_MD5 0x0001
68 #define SSL_RSA_WITH_NULL_SHA 0x0002
69 #define SSL_RSA_WITH_RC4_128_MD5 0x0004
70 #define SSL_RSA_WITH_RC4_128_SHA 0x0005
71 #define SSL_RSA_WITH_3DES_EDE_CBC_SHA 0x000A /* 10 */
72 #define TLS_RSA_WITH_AES_128_CBC_SHA 0x002F /* 47 */
73 #define TLS_RSA_WITH_AES_256_CBC_SHA 0x0035 /* 53 */
74 #define TLS_RSA_WITH_NULL_SHA256 0x003B /* 59 */
76 #define TLS_EMPTY_RENEGOTIATION_INFO_SCSV 0x00FF
78 #define TLS_RSA_WITH_IDEA_CBC_SHA 0x0007 /* 7 */
79 #define SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA 0x0016 /* 22 */
80 #define SSL_DH_anon_WITH_RC4_128_MD5 0x0018 /* 24 */
81 #define SSL_DH_anon_WITH_3DES_EDE_CBC_SHA 0x001B /* 27 */
82 #define TLS_DHE_RSA_WITH_AES_128_CBC_SHA 0x0033 /* 51 */
83 #define TLS_DHE_RSA_WITH_AES_256_CBC_SHA 0x0039 /* 57 */
84 #define TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 0x0067 /* 103 */
85 #define TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 0x006B /* 107 */
86 #define TLS_DH_anon_WITH_AES_128_CBC_SHA 0x0034 /* 52 */
87 #define TLS_DH_anon_WITH_AES_256_CBC_SHA 0x003A /* 58 */
88 #define TLS_RSA_WITH_AES_128_CBC_SHA256 0x003C /* 60 */
89 #define TLS_RSA_WITH_AES_256_CBC_SHA256 0x003D /* 61 */
90 #define TLS_RSA_WITH_SEED_CBC_SHA 0x0096 /* 150 */
91 #define TLS_PSK_WITH_AES_128_CBC_SHA 0x008C /* 140 */
92 #define TLS_PSK_WITH_AES_128_CBC_SHA256 0x00AE /* 174 */
93 #define TLS_PSK_WITH_AES_256_CBC_SHA384 0x00AF /* 175 */
94 #define TLS_PSK_WITH_AES_256_CBC_SHA 0x008D /* 141 */
95 #define TLS_DHE_PSK_WITH_AES_128_CBC_SHA 0x0090 /* 144 */
96 #define TLS_DHE_PSK_WITH_AES_256_CBC_SHA 0x0091 /* 145 */
97 #define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0xC004 /* 49156 */
98 #define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0xC005 /* 49157 */
99 #define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0xC009 /* 49161 */
100 #define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0xC00A /* 49162 */
101 #define TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA 0xC012 /* 49170 */
102 #define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA 0xC013 /* 49171 */
103 #define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA 0xC014 /* 49172 */
104 #define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA 0xC00E /* 49166 */
105 #define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA 0xC00F /* 49167 */
106 #define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023 /* 49187 */
107 #define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 0xC024 /* 49188 */
108 #define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 0xC025 /* 49189 */
109 #define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 0xC026 /* 49190 */
110 #define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 0xC027 /* 49191 */
111 #define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 0xC028 /* 49192 */
112 #define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 0xC029 /* 49193 */
113 #define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 0xC02A /* 49194 */
115 // RFC 5288 "AES Galois Counter Mode (GCM) Cipher Suites for TLS"
116 #define TLS_RSA_WITH_AES_128_GCM_SHA256 0x009C /* 156 */
117 #define TLS_RSA_WITH_AES_256_GCM_SHA384 0x009D /* 157 */
118 #define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B /* 49195 */
119 #define TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0xC02C /* 49196 */
120 #define TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0xC02D /* 49197 */
121 #define TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0xC02E /* 49198 */
122 #define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xC02F /* 49199 */
123 #define TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0xC030 /* 49200 */
124 #define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 0xC031 /* 49201 */
125 #define TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 0xC032 /* 49202 */
127 //Tested against kernel.org:
131 //#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA // ok, recvs SERVER_KEY_EXCHANGE
135 //#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA // ok, recvs SERVER_KEY_EXCHANGE *** matrixssl uses this on my box
136 //#define CIPHER_ID TLS_RSA_WITH_AES_256_CBC_SHA256 // ok, no SERVER_KEY_EXCHANGE
138 //#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 // SSL_ALERT_HANDSHAKE_FAILURE
139 //#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
140 //#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 // ok, recvs SERVER_KEY_EXCHANGE
141 //#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
142 //#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
143 //#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
144 //#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
145 //#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
146 //#define CIPHER_ID TLS_RSA_WITH_AES_256_GCM_SHA384 // ok, no SERVER_KEY_EXCHANGE
147 //#define CIPHER_ID TLS_RSA_WITH_AES_128_GCM_SHA256 // ok, no SERVER_KEY_EXCHANGE *** select this?
148 //#define CIPHER_ID TLS_DH_anon_WITH_AES_256_CBC_SHA // SSL_ALERT_HANDSHAKE_FAILURE
149 //^^^^^^^^^^^^^^^^^^^^^^^ (tested b/c this one doesn't req server certs... no luck)
150 //test TLS_RSA_WITH_AES_128_CBC_SHA, in TLS 1.2 it's mandated to be always supported
152 // works against "openssl s_server -cipher NULL"
153 // and against wolfssl-3.9.10-stable/examples/server/server.c:
154 //#define CIPHER_ID TLS_RSA_WITH_NULL_SHA256 // for testing (does everything except encrypting)
155 // works against wolfssl-3.9.10-stable/examples/server/server.c
156 #define CIPHER_ID TLS_RSA_WITH_AES_256_CBC_SHA256 // ok, no SERVER_KEY_EXCHANGE
168 MAX_TLS_RECORD = (1 << 14),
169 OUTBUF_PFX = 8 + AES_BLOCKSIZE, /* header + IV */
170 OUTBUF_SFX = SHA256_OUTSIZE + AES_BLOCKSIZE, /* MAC + padding */
171 MAX_OTBUF = MAX_TLS_RECORD - OUTBUF_PFX - OUTBUF_SFX,
176 uint8_t proto_maj, proto_min;
177 uint8_t len16_hi, len16_lo;
180 typedef struct tls_state {
183 psRsaKey_t server_rsa_pub_key;
185 sha256_ctx_t handshake_sha256_ctx;
187 uint8_t client_and_server_rand32[2 * 32];
188 uint8_t master_secret[48];
190 uint8_t encrypt_on_write;
191 int min_encrypted_len_on_read;
192 uint8_t client_write_MAC_key[SHA256_OUTSIZE];
193 uint8_t server_write_MAC_key[SHA256_OUTSIZE];
194 uint8_t client_write_key[AES256_KEYSIZE];
195 uint8_t server_write_key[AES256_KEYSIZE];
198 // Each connection state contains a sequence number, which is
199 // maintained separately for read and write states. The sequence
200 // number MUST be set to zero whenever a connection state is made the
201 // active state. Sequence numbers are of type uint64 and may not
203 uint64_t write_seq64_be;
209 // |6.2.1. Fragmentation
210 // | The record layer fragments information blocks into TLSPlaintext
211 // | records carrying data in chunks of 2^14 bytes or less. Client
212 // | message boundaries are not preserved in the record layer (i.e.,
213 // | multiple client messages of the same ContentType MAY be coalesced
214 // | into a single TLSPlaintext record, or a single message MAY be
215 // | fragmented across several records)
218 // | The length (in bytes) of the following TLSPlaintext.fragment.
219 // | The length MUST NOT exceed 2^14.
221 // | 6.2.2. Record Compression and Decompression
223 // | Compression must be lossless and may not increase the content length
224 // | by more than 1024 bytes. If the decompression function encounters a
225 // | TLSCompressed.fragment that would decompress to a length in excess of
226 // | 2^14 bytes, it MUST report a fatal decompression failure error.
229 // | The length (in bytes) of the following TLSCompressed.fragment.
230 // | The length MUST NOT exceed 2^14 + 1024.
232 // Since our buffer also contains 5-byte headers, make it a bit bigger:
237 uint8_t inbuf[20*1024];
241 static unsigned get24be(const uint8_t *p)
243 return 0x100*(0x100*p[0] + p[1]) + p[2];
247 static void dump_hex(const char *fmt, const void *vp, int len)
249 char hexbuf[32 * 1024 + 4];
250 const uint8_t *p = vp;
252 bin2hex(hexbuf, (void*)p, len)[0] = '\0';
256 static void dump_tls_record(const void *vp, int len)
258 const uint8_t *p = vp;
262 if (len < RECHDR_LEN) {
263 dump_hex("< |%s|\n", p, len);
266 xhdr_len = 0x100*p[3] + p[4];
267 dbg("< hdr_type:%u ver:%u.%u len:%u", p[0], p[1], p[2], xhdr_len);
270 if (len >= 4 && p[-RECHDR_LEN] == RECORD_TYPE_HANDSHAKE) {
271 unsigned len24 = get24be(p + 1);
272 dbg(" type:%u len24:%u", p[0], len24);
276 dump_hex(" |%s|\n", p, xhdr_len);
283 void tls_get_random(void *buf, unsigned len)
285 if (len != open_read_close("/dev/urandom", buf, len))
289 //TODO rename this to sha256_hash, and sha256_hash -> sha256_update
290 static void hash_sha256(uint8_t out[SHA256_OUTSIZE], const void *data, unsigned size)
294 sha256_hash(&ctx, data, size);
295 sha256_end(&ctx, out);
298 /* Nondestructively see the current hash value */
299 static void sha256_peek(sha256_ctx_t *ctx, void *buffer)
301 sha256_ctx_t ctx_copy = *ctx;
302 sha256_end(&ctx_copy, buffer);
306 static void sha256_hash_dbg(const char *fmt, sha256_ctx_t *ctx, const void *buffer, size_t len)
308 uint8_t h[SHA256_OUTSIZE];
310 sha256_hash(ctx, buffer, len);
311 dump_hex(fmt, buffer, len);
312 dbg(" (%u) ", (int)len);
314 dump_hex("%s\n", h, SHA256_OUTSIZE);
317 # define sha256_hash_dbg(fmt, ctx, buffer, len) \
318 sha256_hash(ctx, buffer, len)
322 // HMAC(key, text) based on a hash H (say, sha256) is:
323 // ipad = [0x36 x INSIZE]
324 // opad = [0x5c x INSIZE]
325 // HMAC(key, text) = H((key XOR opad) + H((key XOR ipad) + text))
327 // H(key XOR opad) and H(key XOR ipad) can be precomputed
328 // if we often need HMAC hmac with the same key.
330 // text is often given in disjoint pieces.
331 static void hmac_sha256_precomputed_v(uint8_t out[SHA256_OUTSIZE],
332 sha256_ctx_t *hashed_key_xor_ipad,
333 sha256_ctx_t *hashed_key_xor_opad,
338 /* hashed_key_xor_ipad contains unclosed "H((key XOR ipad) +" state */
339 /* hashed_key_xor_opad contains unclosed "H((key XOR opad) +" state */
341 /* calculate out = H((key XOR ipad) + text) */
342 while ((text = va_arg(va, uint8_t*)) != NULL) {
343 unsigned text_size = va_arg(va, unsigned);
344 sha256_hash(hashed_key_xor_ipad, text, text_size);
346 sha256_end(hashed_key_xor_ipad, out);
348 /* out = H((key XOR opad) + out) */
349 sha256_hash(hashed_key_xor_opad, out, SHA256_OUTSIZE);
350 sha256_end(hashed_key_xor_opad, out);
353 static void hmac_sha256(uint8_t out[SHA256_OUTSIZE], uint8_t *key, unsigned key_size, ...)
355 sha256_ctx_t hashed_key_xor_ipad;
356 sha256_ctx_t hashed_key_xor_opad;
357 uint8_t key_xor_ipad[SHA256_INSIZE];
358 uint8_t key_xor_opad[SHA256_INSIZE];
359 uint8_t tempkey[SHA256_OUTSIZE];
363 va_start(va, key_size);
365 // "The authentication key can be of any length up to INSIZE, the
366 // block length of the hash function. Applications that use keys longer
367 // than INSIZE bytes will first hash the key using H and then use the
368 // resultant OUTSIZE byte string as the actual key to HMAC."
369 if (key_size > SHA256_INSIZE) {
370 hash_sha256(tempkey, key, key_size);
372 key_size = SHA256_OUTSIZE;
375 for (i = 0; i < key_size; i++) {
376 key_xor_ipad[i] = key[i] ^ 0x36;
377 key_xor_opad[i] = key[i] ^ 0x5c;
379 for (; i < SHA256_INSIZE; i++) {
380 key_xor_ipad[i] = 0x36;
381 key_xor_opad[i] = 0x5c;
383 sha256_begin(&hashed_key_xor_ipad);
384 sha256_hash(&hashed_key_xor_ipad, key_xor_ipad, SHA256_INSIZE);
385 sha256_begin(&hashed_key_xor_opad);
386 sha256_hash(&hashed_key_xor_opad, key_xor_opad, SHA256_INSIZE);
388 hmac_sha256_precomputed_v(out, &hashed_key_xor_ipad, &hashed_key_xor_opad, va);
393 // 5. HMAC and the Pseudorandom Function
395 // In this section, we define one PRF, based on HMAC. This PRF with the
396 // SHA-256 hash function is used for all cipher suites defined in this
397 // document and in TLS documents published prior to this document when
398 // TLS 1.2 is negotiated.
400 // P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
401 // HMAC_hash(secret, A(2) + seed) +
402 // HMAC_hash(secret, A(3) + seed) + ...
403 // where + indicates concatenation.
404 // A() is defined as:
406 // A(1) = HMAC_hash(secret, A(0)) = HMAC_hash(secret, seed)
407 // A(i) = HMAC_hash(secret, A(i-1))
408 // P_hash can be iterated as many times as necessary to produce the
409 // required quantity of data. For example, if P_SHA256 is being used to
410 // create 80 bytes of data, it will have to be iterated three times
411 // (through A(3)), creating 96 bytes of output data; the last 16 bytes
412 // of the final iteration will then be discarded, leaving 80 bytes of
415 // TLS's PRF is created by applying P_hash to the secret as:
417 // PRF(secret, label, seed) = P_<hash>(secret, label + seed)
419 // The label is an ASCII string.
420 static void prf_hmac_sha256(
421 uint8_t *outbuf, unsigned outbuf_size,
422 uint8_t *secret, unsigned secret_size,
424 uint8_t *seed, unsigned seed_size)
426 uint8_t a[SHA256_OUTSIZE];
427 uint8_t *out_p = outbuf;
428 unsigned label_size = strlen(label);
430 /* In P_hash() calculation, "seed" is "label + seed": */
431 #define SEED label, label_size, seed, seed_size
432 #define SECRET secret, secret_size
433 #define A a, (int)(sizeof(a))
435 /* A(1) = HMAC_hash(secret, seed) */
436 hmac_sha256(a, SECRET, SEED, NULL);
437 //TODO: convert hmac_sha256 to precomputed
440 /* HMAC_hash(secret, A(1) + seed) */
441 if (outbuf_size <= SHA256_OUTSIZE) {
442 /* Last, possibly incomplete, block */
443 /* (use a[] as temp buffer) */
444 hmac_sha256(a, SECRET, A, SEED, NULL);
445 memcpy(out_p, a, outbuf_size);
448 /* Not last block. Store directly to result buffer */
449 hmac_sha256(out_p, SECRET, A, SEED, NULL);
450 out_p += SHA256_OUTSIZE;
451 outbuf_size -= SHA256_OUTSIZE;
452 /* A(2) = HMAC_hash(secret, A(1)) */
453 hmac_sha256(a, SECRET, A, NULL);
460 static tls_state_t *new_tls_state(void)
462 tls_state_t *tls = xzalloc(sizeof(*tls));
464 sha256_begin(&tls->handshake_sha256_ctx);
468 static void tls_error_die(tls_state_t *tls)
470 dump_tls_record(tls->inbuf, tls->insize + tls->tail);
474 static void *tls_get_outbuf(tls_state_t *tls, int len)
478 if (tls->outbuf_size < len + OUTBUF_PFX + OUTBUF_SFX) {
479 tls->outbuf_size = len + OUTBUF_PFX + OUTBUF_SFX;
480 tls->outbuf = xrealloc(tls->outbuf, tls->outbuf_size);
482 return tls->outbuf + OUTBUF_PFX;
486 // 6.2.3.1. Null or Standard Stream Cipher
488 // Stream ciphers (including BulkCipherAlgorithm.null; see Appendix A.6)
489 // convert TLSCompressed.fragment structures to and from stream
490 // TLSCiphertext.fragment structures.
492 // stream-ciphered struct {
493 // opaque content[TLSCompressed.length];
494 // opaque MAC[SecurityParameters.mac_length];
495 // } GenericStreamCipher;
497 // The MAC is generated as:
498 // MAC(MAC_write_key, seq_num +
499 // TLSCompressed.type +
500 // TLSCompressed.version +
501 // TLSCompressed.length +
502 // TLSCompressed.fragment);
503 // where "+" denotes concatenation.
505 // The sequence number for this record.
507 // The MAC algorithm specified by SecurityParameters.mac_algorithm.
509 // Note that the MAC is computed before encryption. The stream cipher
510 // encrypts the entire block, including the MAC.
512 // Appendix C. Cipher Suite Definitions
515 // Cipher Type Material Size Size
516 // ------------ ------ -------- ---- -----
517 // AES_128_CBC Block 16 16 16
518 // AES_256_CBC Block 32 16 16
520 // MAC Algorithm mac_length mac_key_length
521 // -------- ----------- ---------- --------------
522 // SHA HMAC-SHA1 20 20
523 // SHA256 HMAC-SHA256 32 32
524 static void xwrite_encrypted(tls_state_t *tls, unsigned size, unsigned type)
526 uint8_t *buf = tls->outbuf + OUTBUF_PFX;
527 struct record_hdr *xhdr;
529 xhdr = (void*)(buf - RECHDR_LEN);
530 if (CIPHER_ID != TLS_RSA_WITH_NULL_SHA256)
531 xhdr = (void*)(buf - RECHDR_LEN - AES_BLOCKSIZE); /* place for IV */
534 xhdr->proto_maj = TLS_MAJ;
535 xhdr->proto_min = TLS_MIN;
536 /* fake unencrypted record header len for MAC calculation */
537 xhdr->len16_hi = size >> 8;
538 xhdr->len16_lo = size & 0xff;
540 /* Calculate MAC signature */
541 //TODO: convert hmac_sha256 to precomputed
542 hmac_sha256(buf + size,
543 tls->client_write_MAC_key, sizeof(tls->client_write_MAC_key),
544 &tls->write_seq64_be, sizeof(tls->write_seq64_be),
548 tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(tls->write_seq64_be));
550 size += SHA256_OUTSIZE;
552 if (CIPHER_ID == TLS_RSA_WITH_NULL_SHA256) {
553 /* No encryption, only signing */
554 xhdr->len16_hi = size >> 8;
555 xhdr->len16_lo = size & 0xff;
556 dump_hex(">> %s\n", xhdr, RECHDR_LEN + size);
557 xwrite(tls->fd, xhdr, RECHDR_LEN + size);
558 dbg("wrote %u bytes (NULL crypt, SHA256 hash)\n", size);
563 // 6.2.3.2. CBC Block Cipher
564 // For block ciphers (such as 3DES or AES), the encryption and MAC
565 // functions convert TLSCompressed.fragment structures to and from block
566 // TLSCiphertext.fragment structures.
568 // opaque IV[SecurityParameters.record_iv_length];
569 // block-ciphered struct {
570 // opaque content[TLSCompressed.length];
571 // opaque MAC[SecurityParameters.mac_length];
572 // uint8 padding[GenericBlockCipher.padding_length];
573 // uint8 padding_length;
575 // } GenericBlockCipher;
578 // The Initialization Vector (IV) SHOULD be chosen at random, and
579 // MUST be unpredictable. Note that in versions of TLS prior to 1.1,
580 // there was no IV field (...). For block ciphers, the IV length is
581 // of length SecurityParameters.record_iv_length, which is equal to the
582 // SecurityParameters.block_size.
584 // Padding that is added to force the length of the plaintext to be
585 // an integral multiple of the block cipher's block length.
587 // The padding length MUST be such that the total size of the
588 // GenericBlockCipher structure is a multiple of the cipher's block
589 // length. Legal values range from zero to 255, inclusive.
591 // Appendix C. Cipher Suite Definitions
594 // Cipher Type Material Size Size
595 // ------------ ------ -------- ---- -----
596 // AES_128_CBC Block 16 16 16
597 // AES_256_CBC Block 32 16 16
599 psCipherContext_t ctx;
601 uint8_t padding_length;
603 /* Build IV+content+MAC+padding in outbuf */
604 tls_get_random(buf - AES_BLOCKSIZE, AES_BLOCKSIZE); /* IV */
605 dbg("before crypt: 5 hdr + %u data + %u hash bytes\n", size, SHA256_OUTSIZE);
606 // RFC is talking nonsense:
607 // Padding that is added to force the length of the plaintext to be
608 // an integral multiple of the block cipher's block length.
609 // WRONG. _padding+padding_length_, not just _padding_,
611 // IOW: padding_length is the last byte of padding[] array,
612 // contrary to what RFC depicts.
614 // What actually happens is that there is always padding.
615 // If you need one byte to reach BLOCKSIZE, this byte is 0x00.
616 // If you need two bytes, they are both 0x01.
617 // If you need three, they are 0x02,0x02,0x02. And so on.
618 // If you need no bytes to reach BLOCKSIZE, you have to pad a full
619 // BLOCKSIZE with bytes of value (BLOCKSIZE-1).
620 // It's ok to have more than minimum padding, but we do minimum.
622 padding_length = (~size) & (AES_BLOCKSIZE - 1);
624 *p++ = padding_length; /* padding */
626 } while ((size & (AES_BLOCKSIZE - 1)) != 0);
628 /* Encrypt content+MAC+padding in place */
629 psAesInit(&ctx, buf - AES_BLOCKSIZE, /* IV */
630 tls->client_write_key, sizeof(tls->client_write_key)
634 buf, /* ciphertext */
639 dbg("writing 5 + %u IV + %u encrypted bytes, padding_length:0x%02x\n",
640 AES_BLOCKSIZE, size, padding_length);
641 size += AES_BLOCKSIZE; /* + IV */
642 xhdr->len16_hi = size >> 8;
643 xhdr->len16_lo = size & 0xff;
644 dump_hex(">> %s\n", xhdr, RECHDR_LEN + size);
645 xwrite(tls->fd, xhdr, RECHDR_LEN + size);
646 dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
650 static void xwrite_and_update_handshake_hash(tls_state_t *tls, unsigned size)
652 if (!tls->encrypt_on_write) {
653 uint8_t *buf = tls->outbuf + OUTBUF_PFX;
654 struct record_hdr *xhdr = (void*)(buf - RECHDR_LEN);
656 xhdr->type = RECORD_TYPE_HANDSHAKE;
657 xhdr->proto_maj = TLS_MAJ;
658 xhdr->proto_min = TLS_MIN;
659 xhdr->len16_hi = size >> 8;
660 xhdr->len16_lo = size & 0xff;
661 dump_hex(">> %s\n", xhdr, RECHDR_LEN + size);
662 xwrite(tls->fd, xhdr, RECHDR_LEN + size);
663 dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
664 /* Handshake hash does not include record headers */
665 sha256_hash_dbg(">> sha256:%s", &tls->handshake_sha256_ctx, buf, size);
668 xwrite_encrypted(tls, size, RECORD_TYPE_HANDSHAKE);
671 static int xread_tls_block(tls_state_t *tls)
673 struct record_hdr *xhdr;
679 dbg("insize:%u tail:%u\n", tls->insize, tls->tail);
681 memmove(tls->inbuf, tls->inbuf + tls->insize, tls->tail);
684 target = sizeof(tls->inbuf);
686 if (total >= RECHDR_LEN && target == sizeof(tls->inbuf)) {
687 xhdr = (void*)tls->inbuf;
688 target = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
689 if (target >= sizeof(tls->inbuf)) {
690 /* malformed input (too long): yell and die */
695 // can also check type/proto_maj/proto_min here
697 /* if total >= target, we have a full packet (and possibly more)... */
698 if (total - target >= 0)
700 sz = safe_read(tls->fd, tls->inbuf + total, sizeof(tls->inbuf) - total);
702 if (sz == 0 && total == 0) {
703 /* "Abrupt" EOF, no TLS shutdown (seen from kernel.org) */
704 dbg("EOF (without TLS shutdown) from peer\n");
708 bb_perror_msg_and_die("short read, have only %d", total);
710 dbg("read():%d\n", sz);
713 tls->tail = total - target;
714 tls->insize = target;
715 dbg("new insize:%u tail:%u\n", tls->insize, tls->tail);
717 sz = target - RECHDR_LEN;
719 /* Needs to be decrypted? */
720 if (tls->min_encrypted_len_on_read > SHA256_OUTSIZE) {
721 psCipherContext_t ctx;
722 uint8_t *p = tls->inbuf + RECHDR_LEN;
725 if (sz & (AES_BLOCKSIZE-1)
726 || sz < tls->min_encrypted_len_on_read
728 bb_error_msg_and_die("bad encrypted len:%u", sz);
730 /* Decrypt content+MAC+padding in place */
731 psAesInit(&ctx, p, /* IV */
732 tls->server_write_key, sizeof(tls->server_write_key)
735 p + AES_BLOCKSIZE, /* ciphertext */
736 p + AES_BLOCKSIZE, /* plaintext */
739 padding_len = p[sz - 1];
740 dbg("encrypted size:%u type:0x%02x padding_length:0x%02x\n", sz, p[AES_BLOCKSIZE], padding_len);
742 sz -= AES_BLOCKSIZE + SHA256_OUTSIZE + padding_len;
744 bb_error_msg_and_die("bad padding size:%u", padding_len);
748 memmove(tls->inbuf + RECHDR_LEN, tls->inbuf + RECHDR_LEN + AES_BLOCKSIZE, sz);
751 /* if nonzero, then it's TLS_RSA_WITH_NULL_SHA256: drop MAC */
752 /* else: no encryption yet on input, subtract zero = NOP */
753 sz -= tls->min_encrypted_len_on_read;
756 //dump_hex("<< %s\n", tls->inbuf, RECHDR_LEN + sz);
758 xhdr = (void*)tls->inbuf;
759 if (xhdr->type == RECORD_TYPE_ALERT && sz >= 2) {
760 uint8_t *p = tls->inbuf + RECHDR_LEN;
761 dbg("ALERT size:%d level:%d description:%d\n", sz, p[0], p[1]);
762 if (p[0] == 1) { /*warning */
763 if (p[1] == 0) { /* warning, close_notify: EOF */
764 dbg("EOF (TLS encoded) from peer\n");
768 /* discard it, get next record */
771 /* p[0] == 1: fatal error, others: not defined in protocol */
776 /* RFC 5246 is not saying it explicitly, but sha256 hash
777 * in our FINISHED record must include data of incoming packets too!
779 if (tls->inbuf[0] == RECORD_TYPE_HANDSHAKE) {
780 sha256_hash_dbg("<< sha256:%s", &tls->handshake_sha256_ctx, tls->inbuf + RECHDR_LEN, sz);
783 dbg("got block len:%u\n", sz);
788 * DER parsing routines
790 static unsigned get_der_len(uint8_t **bodyp, uint8_t *der, uint8_t *end)
796 // if ((der[0] & 0x1f) == 0x1f) /* not single-byte item code? */
799 len = der[1]; /* maybe it's short len */
803 if (len == 0x80 || end - der < (int)(len - 0x7e)) {
804 /* 0x80 is "0 bytes of len", invalid DER: must use short len if can */
805 /* need 3 or 4 bytes for 81, 82 */
809 len1 = der[2]; /* if (len == 0x81) it's "ii 81 xx", fetch xx */
811 /* >0x82 is "3+ bytes of len", should not happen realistically */
814 if (len == 0x82) { /* it's "ii 82 xx yy" */
815 len1 = 0x100*len1 + der[3];
816 der += 1; /* skip [yy] */
818 der += 1; /* skip [xx] */
821 // xfunc_die(); /* invalid DER: must use short len if can */
823 der += 2; /* skip [code]+[1byte] */
825 if (end - der < (int)len)
832 static uint8_t *enter_der_item(uint8_t *der, uint8_t **endp)
835 unsigned len = get_der_len(&new_der, der, *endp);
836 dbg_der("entered der @%p:0x%02x len:%u inner_byte @%p:0x%02x\n", der, der[0], len, new_der, new_der[0]);
837 /* Move "end" position to cover only this item */
838 *endp = new_der + len;
842 static uint8_t *skip_der_item(uint8_t *der, uint8_t *end)
845 unsigned len = get_der_len(&new_der, der, end);
848 dbg_der("skipped der 0x%02x, next byte 0x%02x\n", der[0], new_der[0]);
852 static void der_binary_to_pstm(pstm_int *pstm_n, uint8_t *der, uint8_t *end)
855 unsigned len = get_der_len(&bin_ptr, der, end);
857 dbg_der("binary bytes:%u, first:0x%02x\n", len, bin_ptr[0]);
858 pstm_init_for_read_unsigned_bin(/*pool:*/ NULL, pstm_n, len);
859 pstm_read_unsigned_bin(pstm_n, bin_ptr, len);
863 static void find_key_in_der_cert(tls_state_t *tls, uint8_t *der, int len)
865 /* Certificate is a DER-encoded data structure. Each DER element has a length,
866 * which makes it easy to skip over large compound elements of any complexity
867 * without parsing them. Example: partial decode of kernel.org certificate:
868 * SEQ 0x05ac/1452 bytes (Certificate): 308205ac
869 * SEQ 0x0494/1172 bytes (tbsCertificate): 30820494
870 * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0] 3 bytes: a003
871 * INTEGER (version): 0201 02
872 * INTEGER 0x11 bytes (serialNumber): 0211 00 9f85bf664b0cddafca508679501b2be4
873 * //^^^^^^note: matrixSSL also allows [ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2] = 0x82 type
874 * SEQ 0x0d bytes (signatureAlgo): 300d
875 * OID 9 bytes: 0609 2a864886f70d01010b (OID_SHA256_RSA_SIG 42.134.72.134.247.13.1.1.11)
877 * SEQ 0x5f bytes (issuer): 305f
880 * OID 3 bytes: 0603 550406
881 * Printable string "FR": 1302 4652
884 * OID 3 bytes: 0603 550408
885 * Printable string "Paris": 1305 5061726973
888 * OID 3 bytes: 0603 550407
889 * Printable string "Paris": 1305 5061726973
892 * OID 3 bytes: 0603 55040a
893 * Printable string "Gandi": 1305 47616e6469
896 * OID 3 bytes: 0603 550403
897 * Printable string "Gandi Standard SSL CA 2": 1317 47616e6469205374616e646172642053534c2043412032
898 * SEQ 30 bytes (validity): 301e
899 * TIME "161011000000Z": 170d 3136313031313030303030305a
900 * TIME "191011235959Z": 170d 3139313031313233353935395a
901 * SEQ 0x5b/91 bytes (subject): 305b //I did not decode this
902 * 3121301f060355040b1318446f6d61696e20436f
903 * 6e74726f6c2056616c6964617465643121301f06
904 * 0355040b1318506f73697469766553534c204d75
905 * 6c74692d446f6d61696e31133011060355040313
906 * 0a6b65726e656c2e6f7267
907 * SEQ 0x01a2/418 bytes (subjectPublicKeyInfo): 308201a2
908 * SEQ 13 bytes (algorithm): 300d
909 * OID 9 bytes: 0609 2a864886f70d010101 (OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1)
911 * BITSTRING 0x018f/399 bytes (publicKey): 0382018f
913 * //after the zero byte, it appears key itself uses DER encoding:
914 * SEQ 0x018a/394 bytes: 3082018a
915 * INTEGER 0x0181/385 bytes (modulus): 02820181
916 * 00b1ab2fc727a3bef76780c9349bf3
917 * ...24 more blocks of 15 bytes each...
918 * 90e895291c6bc8693b65
919 * INTEGER 3 bytes (exponent): 0203 010001
920 * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0x3] 0x01e5 bytes (X509v3 extensions): a38201e5
921 * SEQ 0x01e1 bytes: 308201e1
923 * Certificate is a sequence of three elements:
924 * tbsCertificate (SEQ)
925 * signatureAlgorithm (AlgorithmIdentifier)
926 * signatureValue (BIT STRING)
928 * In turn, tbsCertificate is a sequence of:
931 * signatureAlgo (AlgorithmIdentifier)
932 * issuer (Name, has complex structure)
933 * validity (Validity, SEQ of two Times)
935 * subjectPublicKeyInfo (SEQ)
938 * subjectPublicKeyInfo is a sequence of:
939 * algorithm (AlgorithmIdentifier)
940 * publicKey (BIT STRING)
942 * We need Certificate.tbsCertificate.subjectPublicKeyInfo.publicKey
944 uint8_t *end = der + len;
946 /* enter "Certificate" item: [der, end) will be only Cert */
947 der = enter_der_item(der, &end);
949 /* enter "tbsCertificate" item: [der, end) will be only tbsCert */
950 der = enter_der_item(der, &end);
952 /* skip up to subjectPublicKeyInfo */
953 der = skip_der_item(der, end); /* version */
954 der = skip_der_item(der, end); /* serialNumber */
955 der = skip_der_item(der, end); /* signatureAlgo */
956 der = skip_der_item(der, end); /* issuer */
957 der = skip_der_item(der, end); /* validity */
958 der = skip_der_item(der, end); /* subject */
960 /* enter subjectPublicKeyInfo */
961 der = enter_der_item(der, &end);
962 { /* check subjectPublicKeyInfo.algorithm */
963 static const uint8_t expected[] = {
964 0x30,0x0d, // SEQ 13 bytes
965 0x06,0x09, 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01, // OID RSA_KEY_ALG 42.134.72.134.247.13.1.1.1
968 if (memcmp(der, expected, sizeof(expected)) != 0)
969 bb_error_msg_and_die("not RSA key");
971 /* skip subjectPublicKeyInfo.algorithm */
972 der = skip_der_item(der, end);
973 /* enter subjectPublicKeyInfo.publicKey */
974 // die_if_not_this_der_type(der, end, 0x03); /* must be BITSTRING */
975 der = enter_der_item(der, &end);
978 //based on getAsnRsaPubKey(), pkcs1ParsePrivBin() is also of note
979 dbg("key bytes:%u, first:0x%02x\n", (int)(end - der), der[0]);
980 if (end - der < 14) xfunc_die();
983 * SEQ 0x018a/394 bytes: 3082018a
984 * INTEGER 0x0181/385 bytes (modulus): 02820181 XX...XXX
985 * INTEGER 3 bytes (exponent): 0203 010001
987 if (*der != 0) /* "ignore bits", should be 0 */
990 der = enter_der_item(der, &end); /* enter SEQ */
991 /* memset(tls->server_rsa_pub_key, 0, sizeof(tls->server_rsa_pub_key)); - already is */
992 der_binary_to_pstm(&tls->server_rsa_pub_key.N, der, end); /* modulus */
993 der = skip_der_item(der, end);
994 der_binary_to_pstm(&tls->server_rsa_pub_key.e, der, end); /* exponent */
995 tls->server_rsa_pub_key.size = pstm_unsigned_bin_size(&tls->server_rsa_pub_key.N);
996 dbg("server_rsa_pub_key.size:%d\n", tls->server_rsa_pub_key.size);
1000 * TLS Handshake routines
1002 static int xread_tls_handshake_block(tls_state_t *tls, int min_len)
1004 struct record_hdr *xhdr;
1005 int len = xread_tls_block(tls);
1007 xhdr = (void*)tls->inbuf;
1009 || xhdr->type != RECORD_TYPE_HANDSHAKE
1010 || xhdr->proto_maj != TLS_MAJ
1011 || xhdr->proto_min != TLS_MIN
1015 dbg("got HANDSHAKE\n");
1019 static ALWAYS_INLINE void fill_handshake_record_hdr(void *buf, unsigned type, unsigned len)
1021 struct handshake_hdr {
1023 uint8_t len24_hi, len24_mid, len24_lo;
1028 h->len24_hi = len >> 16;
1029 h->len24_mid = len >> 8;
1030 h->len24_lo = len & 0xff;
1033 //TODO: implement RFC 5746 (Renegotiation Indication Extension) - some servers will refuse to work with us otherwise
1034 static void send_client_hello(tls_state_t *tls)
1036 struct client_hello {
1038 uint8_t len24_hi, len24_mid, len24_lo;
1039 uint8_t proto_maj, proto_min;
1041 uint8_t session_id_len;
1042 /* uint8_t session_id[]; */
1043 uint8_t cipherid_len16_hi, cipherid_len16_lo;
1044 uint8_t cipherid[2 * 1]; /* actually variable */
1045 uint8_t comprtypes_len;
1046 uint8_t comprtypes[1]; /* actually variable */
1048 struct client_hello *record = tls_get_outbuf(tls, sizeof(*record));
1050 fill_handshake_record_hdr(record, HANDSHAKE_CLIENT_HELLO, sizeof(*record));
1051 record->proto_maj = TLS_MAJ; /* the "requested" version of the protocol, */
1052 record->proto_min = TLS_MIN; /* can be higher than one in record headers */
1053 tls_get_random(record->rand32, sizeof(record->rand32));
1054 if (TLS_DEBUG_FIXED_SECRETS)
1055 memset(record->rand32, 0x11, sizeof(record->rand32));
1056 memcpy(tls->client_and_server_rand32, record->rand32, sizeof(record->rand32));
1057 record->session_id_len = 0;
1058 record->cipherid_len16_hi = 0;
1059 record->cipherid_len16_lo = 2 * 1;
1060 record->cipherid[0] = CIPHER_ID >> 8;
1061 record->cipherid[1] = CIPHER_ID & 0xff;
1062 record->comprtypes_len = 1;
1063 record->comprtypes[0] = 0;
1065 //TODO: send options, at least SNI.
1067 dbg(">> CLIENT_HELLO\n");
1068 xwrite_and_update_handshake_hash(tls, sizeof(*record));
1071 static void get_server_hello(tls_state_t *tls)
1073 struct server_hello {
1074 struct record_hdr xhdr;
1076 uint8_t len24_hi, len24_mid, len24_lo;
1077 uint8_t proto_maj, proto_min;
1078 uint8_t rand32[32]; /* first 4 bytes are unix time in BE format */
1079 uint8_t session_id_len;
1080 uint8_t session_id[32];
1081 uint8_t cipherid_hi, cipherid_lo;
1083 /* extensions may follow, but only those which client offered in its Hello */
1085 struct server_hello *hp;
1088 xread_tls_handshake_block(tls, 74);
1090 hp = (void*)tls->inbuf;
1092 // 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|
1093 //SvHl len=70 maj.min unixtime^^^ 28randbytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^ slen sid32bytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cipSel comprSel
1094 if (hp->type != HANDSHAKE_SERVER_HELLO
1095 || hp->len24_hi != 0
1096 || hp->len24_mid != 0
1097 /* hp->len24_lo checked later */
1098 || hp->proto_maj != TLS_MAJ
1099 || hp->proto_min != TLS_MIN
1104 cipherid = &hp->cipherid_hi;
1105 if (hp->session_id_len != 32) {
1106 if (hp->session_id_len != 0)
1109 // session_id_len == 0: no session id
1111 // may return an empty session_id to indicate that the session will
1112 // not be cached and therefore cannot be resumed."
1114 hp->len24_lo += 32; /* what len would be if session id would be present */
1117 if (hp->len24_lo < 70
1118 || cipherid[0] != (CIPHER_ID >> 8)
1119 || cipherid[1] != (CIPHER_ID & 0xff)
1120 || cipherid[2] != 0 /* comprtype */
1125 dbg("<< SERVER_HELLO\n");
1126 memcpy(tls->client_and_server_rand32 + 32, hp->rand32, sizeof(hp->rand32));
1129 static void get_server_cert(tls_state_t *tls)
1131 struct record_hdr *xhdr;
1135 len = xread_tls_handshake_block(tls, 10);
1137 xhdr = (void*)tls->inbuf;
1138 certbuf = (void*)(xhdr + 1);
1139 if (certbuf[0] != HANDSHAKE_CERTIFICATE)
1141 dbg("<< CERTIFICATE\n");
1143 // 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...
1144 //Cert len=4388 ChainLen CertLen^ DER encoded X509 starts here. openssl x509 -in FILE -inform DER -noout -text
1145 len1 = get24be(certbuf + 1);
1146 if (len1 > len - 4) tls_error_die(tls);
1148 len1 = get24be(certbuf + 4);
1149 if (len1 > len - 3) tls_error_die(tls);
1151 len1 = get24be(certbuf + 7);
1152 if (len1 > len - 3) tls_error_die(tls);
1156 find_key_in_der_cert(tls, certbuf + 10, len);
1159 static void send_client_key_exchange(tls_state_t *tls)
1161 struct client_key_exchange {
1163 uint8_t len24_hi, len24_mid, len24_lo;
1164 /* keylen16 exists for RSA (in TLS, not in SSL), but not for some other key types */
1165 uint8_t keylen16_hi, keylen16_lo;
1166 uint8_t key[4 * 1024]; // size??
1168 //FIXME: better size estimate
1169 struct client_key_exchange *record = tls_get_outbuf(tls, sizeof(*record));
1170 uint8_t rsa_premaster[SSL_HS_RSA_PREMASTER_SIZE];
1173 tls_get_random(rsa_premaster, sizeof(rsa_premaster));
1174 if (TLS_DEBUG_FIXED_SECRETS)
1175 memset(rsa_premaster, 0x44, sizeof(rsa_premaster));
1177 // "Note: The version number in the PreMasterSecret is the version
1178 // offered by the client in the ClientHello.client_version, not the
1179 // version negotiated for the connection."
1180 rsa_premaster[0] = TLS_MAJ;
1181 rsa_premaster[1] = TLS_MIN;
1182 len = psRsaEncryptPub(/*pool:*/ NULL,
1183 /* psRsaKey_t* */ &tls->server_rsa_pub_key,
1184 rsa_premaster, /*inlen:*/ sizeof(rsa_premaster),
1185 record->key, sizeof(record->key),
1188 record->keylen16_hi = len >> 8;
1189 record->keylen16_lo = len & 0xff;
1191 record->type = HANDSHAKE_CLIENT_KEY_EXCHANGE;
1192 record->len24_hi = 0;
1193 record->len24_mid = len >> 8;
1194 record->len24_lo = len & 0xff;
1197 dbg(">> CLIENT_KEY_EXCHANGE\n");
1198 xwrite_and_update_handshake_hash(tls, len);
1201 // For all key exchange methods, the same algorithm is used to convert
1202 // the pre_master_secret into the master_secret. The pre_master_secret
1203 // should be deleted from memory once the master_secret has been
1205 // master_secret = PRF(pre_master_secret, "master secret",
1206 // ClientHello.random + ServerHello.random)
1208 // The master secret is always exactly 48 bytes in length. The length
1209 // of the premaster secret will vary depending on key exchange method.
1211 tls->master_secret, sizeof(tls->master_secret),
1212 rsa_premaster, sizeof(rsa_premaster),
1214 tls->client_and_server_rand32, sizeof(tls->client_and_server_rand32)
1216 dump_hex("master secret:%s\n", tls->master_secret, sizeof(tls->master_secret));
1219 // 6.3. Key Calculation
1221 // The Record Protocol requires an algorithm to generate keys required
1222 // by the current connection state (see Appendix A.6) from the security
1223 // parameters provided by the handshake protocol.
1225 // The master secret is expanded into a sequence of secure bytes, which
1226 // is then split to a client write MAC key, a server write MAC key, a
1227 // client write encryption key, and a server write encryption key. Each
1228 // of these is generated from the byte sequence in that order. Unused
1229 // values are empty. Some AEAD ciphers may additionally require a
1230 // client write IV and a server write IV (see Section 6.2.3.3).
1232 // When keys and MAC keys are generated, the master secret is used as an
1235 // To generate the key material, compute
1237 // key_block = PRF(SecurityParameters.master_secret,
1239 // SecurityParameters.server_random +
1240 // SecurityParameters.client_random);
1242 // until enough output has been generated. Then, the key_block is
1243 // partitioned as follows:
1245 // client_write_MAC_key[SecurityParameters.mac_key_length]
1246 // server_write_MAC_key[SecurityParameters.mac_key_length]
1247 // client_write_key[SecurityParameters.enc_key_length]
1248 // server_write_key[SecurityParameters.enc_key_length]
1249 // client_write_IV[SecurityParameters.fixed_iv_length]
1250 // server_write_IV[SecurityParameters.fixed_iv_length]
1254 /* make "server_rand32 + client_rand32" */
1255 memcpy(&tmp64[0] , &tls->client_and_server_rand32[32], 32);
1256 memcpy(&tmp64[32], &tls->client_and_server_rand32[0] , 32);
1259 tls->client_write_MAC_key, 2 * (SHA256_OUTSIZE + AES256_KEYSIZE),
1261 // server_write_MAC_key[SHA256_OUTSIZE]
1262 // client_write_key[AES256_KEYSIZE]
1263 // server_write_key[AES256_KEYSIZE]
1264 tls->master_secret, sizeof(tls->master_secret),
1268 dump_hex("client_write_MAC_key:%s\n",
1269 tls->client_write_MAC_key, sizeof(tls->client_write_MAC_key)
1271 dump_hex("client_write_key:%s\n",
1272 tls->client_write_key, sizeof(tls->client_write_key)
1277 static const uint8_t rec_CHANGE_CIPHER_SPEC[] = {
1278 RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
1282 static void send_change_cipher_spec(tls_state_t *tls)
1284 dbg(">> CHANGE_CIPHER_SPEC\n");
1285 xwrite(tls->fd, rec_CHANGE_CIPHER_SPEC, sizeof(rec_CHANGE_CIPHER_SPEC));
1289 // A Finished message is always sent immediately after a change
1290 // cipher spec message to verify that the key exchange and
1291 // authentication processes were successful. It is essential that a
1292 // change cipher spec message be received between the other handshake
1293 // messages and the Finished message.
1295 // The Finished message is the first one protected with the just
1296 // negotiated algorithms, keys, and secrets. Recipients of Finished
1297 // messages MUST verify that the contents are correct. Once a side
1298 // has sent its Finished message and received and validated the
1299 // Finished message from its peer, it may begin to send and receive
1300 // application data over the connection.
1303 // opaque verify_data[verify_data_length];
1307 // PRF(master_secret, finished_label, Hash(handshake_messages))
1308 // [0..verify_data_length-1];
1311 // For Finished messages sent by the client, the string
1312 // "client finished". For Finished messages sent by the server,
1313 // the string "server finished".
1315 // Hash denotes a Hash of the handshake messages. For the PRF
1316 // defined in Section 5, the Hash MUST be the Hash used as the basis
1317 // for the PRF. Any cipher suite which defines a different PRF MUST
1318 // also define the Hash to use in the Finished computation.
1320 // In previous versions of TLS, the verify_data was always 12 octets
1321 // long. In the current version of TLS, it depends on the cipher
1322 // suite. Any cipher suite which does not explicitly specify
1323 // verify_data_length has a verify_data_length equal to 12. This
1324 // includes all existing cipher suites.
1325 static void send_client_finished(tls_state_t *tls)
1329 uint8_t len24_hi, len24_mid, len24_lo;
1330 uint8_t prf_result[12];
1332 struct finished *record = tls_get_outbuf(tls, sizeof(*record));
1333 uint8_t handshake_hash[SHA256_OUTSIZE];
1335 fill_handshake_record_hdr(record, HANDSHAKE_FINISHED, sizeof(*record));
1337 sha256_peek(&tls->handshake_sha256_ctx, handshake_hash);
1338 prf_hmac_sha256(record->prf_result, sizeof(record->prf_result),
1339 tls->master_secret, sizeof(tls->master_secret),
1341 handshake_hash, sizeof(handshake_hash)
1343 dump_hex("from secret: %s\n", tls->master_secret, sizeof(tls->master_secret));
1344 dump_hex("from labelSeed: %s", "client finished", sizeof("client finished")-1);
1345 dump_hex("%s\n", handshake_hash, sizeof(handshake_hash));
1346 dump_hex("=> digest: %s\n", record->prf_result, sizeof(record->prf_result));
1348 dbg(">> FINISHED\n");
1349 xwrite_encrypted(tls, sizeof(*record), RECORD_TYPE_HANDSHAKE);
1352 static void tls_handshake(tls_state_t *tls)
1354 // Client RFC 5246 Server
1355 // (*) - optional messages, not always sent
1357 // ClientHello ------->
1360 // ServerKeyExchange*
1361 // CertificateRequest*
1362 // <------- ServerHelloDone
1364 // ClientKeyExchange
1365 // CertificateVerify*
1366 // [ChangeCipherSpec]
1367 // Finished ------->
1368 // [ChangeCipherSpec]
1369 // <------- Finished
1370 // Application Data <------> Application Data
1373 send_client_hello(tls);
1374 get_server_hello(tls);
1377 // The server MUST send a Certificate message whenever the agreed-
1378 // upon key exchange method uses certificates for authentication
1379 // (this includes all key exchange methods defined in this document
1380 // except DH_anon). This message will always immediately follow the
1381 // ServerHello message.
1383 // IOW: in practice, Certificate *always* follows.
1384 // (for example, kernel.org does not even accept DH_anon cipher id)
1385 get_server_cert(tls);
1387 len = xread_tls_handshake_block(tls, 4);
1388 if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_SERVER_KEY_EXCHANGE) {
1390 // 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...
1392 // with TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 461 bytes:
1393 // 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...
1394 dbg("<< SERVER_KEY_EXCHANGE len:%u\n", len);
1395 //probably need to save it
1396 xread_tls_handshake_block(tls, 4);
1399 // if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_CERTIFICATE_REQUEST) {
1400 // dbg("<< CERTIFICATE_REQUEST\n");
1401 //RFC 5246: (in response to this,) "If no suitable certificate is available,
1402 // the client MUST send a certificate message containing no
1403 // certificates. That is, the certificate_list structure has a
1404 // length of zero. ...
1405 // Client certificates are sent using the Certificate structure
1406 // defined in Section 7.4.2."
1407 // (i.e. the same format as server certs)
1408 // xread_tls_handshake_block(tls, 4);
1411 if (tls->inbuf[RECHDR_LEN] != HANDSHAKE_SERVER_HELLO_DONE)
1413 // 0e 000000 (len:0)
1414 dbg("<< SERVER_HELLO_DONE\n");
1416 send_client_key_exchange(tls);
1418 send_change_cipher_spec(tls);
1419 /* from now on we should send encrypted */
1420 /* tls->write_seq64_be = 0; - already is */
1421 tls->encrypt_on_write = 1;
1423 send_client_finished(tls);
1425 /* Get CHANGE_CIPHER_SPEC */
1426 len = xread_tls_block(tls);
1427 if (len != 1 || memcmp(tls->inbuf, rec_CHANGE_CIPHER_SPEC, 6) != 0)
1429 dbg("<< CHANGE_CIPHER_SPEC\n");
1430 if (CIPHER_ID == TLS_RSA_WITH_NULL_SHA256)
1431 tls->min_encrypted_len_on_read = SHA256_OUTSIZE;
1433 /* all incoming packets now should be encrypted and have IV + MAC + padding */
1434 tls->min_encrypted_len_on_read = AES_BLOCKSIZE + SHA256_OUTSIZE + AES_BLOCKSIZE;
1436 /* Get (encrypted) FINISHED from the server */
1437 len = xread_tls_block(tls);
1438 if (len < 4 || tls->inbuf[RECHDR_LEN] != HANDSHAKE_FINISHED)
1440 dbg("<< FINISHED\n");
1441 /* application data can be sent/received */
1444 static void tls_xwrite(tls_state_t *tls, int len)
1447 xwrite_encrypted(tls, len, RECORD_TYPE_APPLICATION_DATA);
1450 // To run a test server using openssl:
1451 // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
1452 // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1
1454 // Unencryped SHA256 example:
1455 // openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
1456 // openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL
1457 // openssl s_client -connect 127.0.0.1:4433 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL-SHA256
1459 // Talk to kernel.org:
1460 // printf "GET / HTTP/1.1\r\nHost: kernel.org\r\n\r\n" | ./busybox tls kernel.org
1462 int tls_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1463 int tls_main(int argc UNUSED_PARAM, char **argv)
1466 fd_set readfds, testfds;
1470 // getopt32(argv, "myopts")
1475 cfd = create_and_connect_stream_or_die(argv[1], 443);
1477 tls = new_tls_state();
1481 /* Select loop copying stdin to cfd, and cfd to stdout */
1483 FD_SET(cfd, &readfds);
1484 FD_SET(STDIN_FILENO, &readfds);
1486 //#define iobuf bb_common_bufsiz1
1487 // setup_common_bufsiz();
1493 if (select(cfd + 1, &testfds, NULL, NULL, NULL) < 0)
1494 bb_perror_msg_and_die("select");
1496 if (FD_ISSET(STDIN_FILENO, &testfds)) {
1499 dbg("STDIN HAS DATA\n");
1500 //TODO: growable buffer
1501 buf = tls_get_outbuf(tls, 4 * 1024);
1502 nread = safe_read(STDIN_FILENO, buf, 4 * 1024);
1504 //&& errno != EAGAIN
1505 /* Close outgoing half-connection so they get EOF,
1506 * but leave incoming alone so we can see response */
1507 //TLS has no way to encode this, doubt it's ok to do it "raw"
1508 // shutdown(cfd, SHUT_WR);
1509 FD_CLR(STDIN_FILENO, &readfds);
1511 tls_xwrite(tls, nread);
1513 if (FD_ISSET(cfd, &testfds)) {
1514 dbg("NETWORK HAS DATA\n");
1515 nread = xread_tls_block(tls);
1517 //TODO: if eof, just close stdout, but not exit!
1518 return EXIT_SUCCESS;
1519 xwrite(STDOUT_FILENO, tls->inbuf + RECHDR_LEN, nread);
1523 return EXIT_SUCCESS;