blob: 8d074c058c2be3d4e6705107957bd5d4d640c9d7 [file] [log] [blame]
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001/*
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002 * Copyright (C) 2017 Denys Vlasenko
Denys Vlasenko11d00962017-01-15 00:12:42 +01003 *
4 * Licensed under GPLv2, see file LICENSE in this source tree.
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01005 */
6//config:config TLS
Denys Vlasenko9a647c32017-01-23 01:08:16 +01007//config: bool #No description makes it a hidden option
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01008//config: default n
Denys Vlasenko71fa5b02018-12-10 16:14:58 +01009//Note:
10//Config.src also defines FEATURE_TLS_SHA1 option
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010011
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010012//kbuild:lib-$(CONFIG_TLS) += tls.o
Denys Vlasenko11d00962017-01-15 00:12:42 +010013//kbuild:lib-$(CONFIG_TLS) += tls_pstm.o
14//kbuild:lib-$(CONFIG_TLS) += tls_pstm_montgomery_reduce.o
15//kbuild:lib-$(CONFIG_TLS) += tls_pstm_mul_comba.o
16//kbuild:lib-$(CONFIG_TLS) += tls_pstm_sqr_comba.o
Denys Vlasenkob7e9ae62017-01-18 17:20:27 +010017//kbuild:lib-$(CONFIG_TLS) += tls_aes.o
Denys Vlasenko83e5c622018-11-23 17:21:38 +010018//kbuild:lib-$(CONFIG_TLS) += tls_aesgcm.o
Denys Vlasenkobddb6542018-11-13 02:16:24 +010019//kbuild:lib-$(CONFIG_TLS) += tls_rsa.o
20//kbuild:lib-$(CONFIG_TLS) += tls_fe.o
Denys Vlasenkof18a1fd2021-04-26 13:25:56 +020021//kbuild:lib-$(CONFIG_TLS) += tls_sp_c32.o
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010022
Denys Vlasenko11d00962017-01-15 00:12:42 +010023#include "tls.h"
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010024
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +020025// Usually enabled. You can disable some of them to force only
26// specific ciphers to be advertized to server.
27// (this would not exclude code to handle disabled ciphers, no code size win)
28#define ALLOW_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 1
29#define ALLOW_ECDHE_RSA_WITH_AES_128_CBC_SHA256 1
30#define ALLOW_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 1
31#define ALLOW_ECDHE_RSA_WITH_AES_128_GCM_SHA256 1
32#define ALLOW_RSA_WITH_AES_128_CBC_SHA256 1
33#define ALLOW_RSA_WITH_AES_256_CBC_SHA256 1
34#define ALLOW_RSA_WITH_AES_128_GCM_SHA256 1
35#define ALLOW_CURVE_P256 1
36#define ALLOW_CURVE_X25519 1
37
38// For testing (does everything except encrypting).
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +010039// works against "openssl s_server -cipher NULL"
40// and against wolfssl-3.9.10-stable/examples/server/server.c:
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +020041#define ALLOW_RSA_NULL_SHA256 0
Denys Vlasenko49ecee02017-01-24 16:00:54 +010042
Denys Vlasenko89193f92017-01-24 18:08:07 +010043#define TLS_DEBUG 0
44#define TLS_DEBUG_HASH 0
45#define TLS_DEBUG_DER 0
46#define TLS_DEBUG_FIXED_SECRETS 0
Denys Vlasenkob5bf1912017-01-23 16:12:17 +010047#if 0
48# define dump_raw_out(...) dump_hex(__VA_ARGS__)
49#else
50# define dump_raw_out(...) ((void)0)
51#endif
52#if 0
53# define dump_raw_in(...) dump_hex(__VA_ARGS__)
54#else
55# define dump_raw_in(...) ((void)0)
56#endif
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +010057
58#if TLS_DEBUG
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010059# define dbg(...) fprintf(stderr, __VA_ARGS__)
60#else
61# define dbg(...) ((void)0)
62#endif
63
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +010064#if TLS_DEBUG_DER
65# define dbg_der(...) fprintf(stderr, __VA_ARGS__)
66#else
67# define dbg_der(...) ((void)0)
68#endif
69
Denys Vlasenkoa33b0082018-11-25 14:28:32 +010070
71//TLS 1.2
72#define TLS_MAJ 3
73#define TLS_MIN 3
74
Denys Vlasenko98066662018-02-06 13:33:00 +010075#define RECORD_TYPE_CHANGE_CIPHER_SPEC 20 /* 0x14 */
76#define RECORD_TYPE_ALERT 21 /* 0x15 */
77#define RECORD_TYPE_HANDSHAKE 22 /* 0x16 */
78#define RECORD_TYPE_APPLICATION_DATA 23 /* 0x17 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010079
Denys Vlasenko98066662018-02-06 13:33:00 +010080#define HANDSHAKE_HELLO_REQUEST 0 /* 0x00 */
81#define HANDSHAKE_CLIENT_HELLO 1 /* 0x01 */
82#define HANDSHAKE_SERVER_HELLO 2 /* 0x02 */
83#define HANDSHAKE_HELLO_VERIFY_REQUEST 3 /* 0x03 */
84#define HANDSHAKE_NEW_SESSION_TICKET 4 /* 0x04 */
85#define HANDSHAKE_CERTIFICATE 11 /* 0x0b */
86#define HANDSHAKE_SERVER_KEY_EXCHANGE 12 /* 0x0c */
87#define HANDSHAKE_CERTIFICATE_REQUEST 13 /* 0x0d */
88#define HANDSHAKE_SERVER_HELLO_DONE 14 /* 0x0e */
89#define HANDSHAKE_CERTIFICATE_VERIFY 15 /* 0x0f */
90#define HANDSHAKE_CLIENT_KEY_EXCHANGE 16 /* 0x10 */
91#define HANDSHAKE_FINISHED 20 /* 0x14 */
Denys Vlasenko11d00962017-01-15 00:12:42 +010092
Denys Vlasenko5df3b122018-11-04 21:25:41 +010093#define TLS_EMPTY_RENEGOTIATION_INFO_SCSV 0x00FF /* not a real cipher id... */
94
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010095#define SSL_NULL_WITH_NULL_NULL 0x0000
96#define SSL_RSA_WITH_NULL_MD5 0x0001
97#define SSL_RSA_WITH_NULL_SHA 0x0002
98#define SSL_RSA_WITH_RC4_128_MD5 0x0004
99#define SSL_RSA_WITH_RC4_128_SHA 0x0005
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100100#define TLS_RSA_WITH_IDEA_CBC_SHA 0x0007 /* 7 */
Denys Vlasenko5df3b122018-11-04 21:25:41 +0100101#define SSL_RSA_WITH_3DES_EDE_CBC_SHA 0x000A /* 10 */
102
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100103#define SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA 0x0016 /* 22 */
104#define SSL_DH_anon_WITH_RC4_128_MD5 0x0018 /* 24 */
105#define SSL_DH_anon_WITH_3DES_EDE_CBC_SHA 0x001B /* 27 */
Denys Vlasenko5df3b122018-11-04 21:25:41 +0100106#define TLS_RSA_WITH_AES_128_CBC_SHA 0x002F /*SSLv3 Kx=RSA Au=RSA Enc=AES(128) Mac=SHA1 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100107#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA 0x0033 /* 51 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100108#define TLS_DH_anon_WITH_AES_128_CBC_SHA 0x0034 /* 52 */
Denys Vlasenko5df3b122018-11-04 21:25:41 +0100109#define TLS_RSA_WITH_AES_256_CBC_SHA 0x0035 /* 53 */
110#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA 0x0039 /* 57 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100111#define TLS_DH_anon_WITH_AES_256_CBC_SHA 0x003A /* 58 */
Denys Vlasenko5df3b122018-11-04 21:25:41 +0100112#define TLS_RSA_WITH_NULL_SHA256 0x003B /* 59 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100113#define TLS_RSA_WITH_AES_128_CBC_SHA256 0x003C /* 60 */
114#define TLS_RSA_WITH_AES_256_CBC_SHA256 0x003D /* 61 */
Denys Vlasenko5df3b122018-11-04 21:25:41 +0100115#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 0x0067 /* 103 */
116#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 0x006B /* 107 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100117#define TLS_PSK_WITH_AES_128_CBC_SHA 0x008C /* 140 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100118#define TLS_PSK_WITH_AES_256_CBC_SHA 0x008D /* 141 */
119#define TLS_DHE_PSK_WITH_AES_128_CBC_SHA 0x0090 /* 144 */
120#define TLS_DHE_PSK_WITH_AES_256_CBC_SHA 0x0091 /* 145 */
Denys Vlasenko5df3b122018-11-04 21:25:41 +0100121#define TLS_RSA_WITH_SEED_CBC_SHA 0x0096 /* 150 */
Denys Vlasenko330d7f52018-11-25 17:27:48 +0100122#define TLS_RSA_WITH_AES_128_GCM_SHA256 0x009C /*TLSv1.2 Kx=RSA Au=RSA Enc=AESGCM(128) Mac=AEAD */
123#define TLS_RSA_WITH_AES_256_GCM_SHA384 0x009D /*TLSv1.2 Kx=RSA Au=RSA Enc=AESGCM(256) Mac=AEAD */
124#define TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 0x009E /*TLSv1.2 Kx=DH Au=RSA Enc=AESGCM(128) Mac=AEAD */
125#define TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 0x009F /*TLSv1.2 Kx=DH Au=RSA Enc=AESGCM(256) Mac=AEAD */
Denys Vlasenko8a46c742018-11-26 17:33:17 +0100126#define TLS_DH_anon_WITH_AES_128_GCM_SHA256 0x00A6 /* RFC 5288 */
127#define TLS_DH_anon_WITH_AES_256_GCM_SHA384 0x00A7 /* RFC 5288 */
Denys Vlasenko5df3b122018-11-04 21:25:41 +0100128#define TLS_PSK_WITH_AES_128_CBC_SHA256 0x00AE /* 174 */
129#define TLS_PSK_WITH_AES_256_CBC_SHA384 0x00AF /* 175 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100130#define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0xC004 /* 49156 */
131#define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0xC005 /* 49157 */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100132#define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0xC009 /*TLSv1 Kx=ECDH Au=ECDSA Enc=AES(128) Mac=SHA1 */
133#define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0xC00A /*TLSv1 Kx=ECDH Au=ECDSA Enc=AES(256) Mac=SHA1 */
Denys Vlasenko5df3b122018-11-04 21:25:41 +0100134#define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA 0xC00E /* 49166 */
135#define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA 0xC00F /* 49167 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100136#define TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA 0xC012 /* 49170 */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100137#define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA 0xC013 /*TLSv1 Kx=ECDH Au=RSA Enc=AES(128) Mac=SHA1 */
138#define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA 0xC014 /*TLSv1 Kx=ECDH Au=RSA Enc=AES(256) Mac=SHA1 */
Denys Vlasenko8a46c742018-11-26 17:33:17 +0100139#define TLS_ECDH_anon_WITH_AES_128_CBC_SHA 0xC018 /* RFC 4492 */
140#define TLS_ECDH_anon_WITH_AES_256_CBC_SHA 0xC019 /* RFC 4492 */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100141#define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023 /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AES(128) Mac=SHA256 */
142#define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 0xC024 /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AES(256) Mac=SHA384 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100143#define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 0xC025 /* 49189 */
144#define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 0xC026 /* 49190 */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100145#define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 0xC027 /*TLSv1.2 Kx=ECDH Au=RSA Enc=AES(128) Mac=SHA256 */
146#define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 0xC028 /*TLSv1.2 Kx=ECDH Au=RSA Enc=AES(256) Mac=SHA384 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100147#define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 0xC029 /* 49193 */
148#define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 0xC02A /* 49194 */
Denys Vlasenko7a18b952017-01-23 16:37:04 +0100149/* RFC 5288 "AES Galois Counter Mode (GCM) Cipher Suites for TLS" */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100150#define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESGCM(128) Mac=AEAD */
151#define TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0xC02C /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESGCM(256) Mac=AEAD */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100152#define TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0xC02D /* 49197 */
153#define TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0xC02E /* 49198 */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100154#define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xC02F /*TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(128) Mac=AEAD */
155#define TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0xC030 /*TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(256) Mac=AEAD */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100156#define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 0xC031 /* 49201 */
157#define TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 0xC032 /* 49202 */
Denys Vlasenkodffc8ff2018-11-27 10:35:10 +0100158#define TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA 0xC035
159#define TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA 0xC036
160#define TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 0xC037
161#define TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 0xC038
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100162
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100163/* From http://wiki.mozilla.org/Security/Server_Side_TLS */
164/* and 'openssl ciphers -V -stdname' */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100165#define TLS_RSA_WITH_AES_128_CCM 0xC09C /*TLSv1.2 Kx=RSA Au=RSA Enc=AESCCM(128) Mac=AEAD */
166#define TLS_RSA_WITH_AES_256_CCM 0xC09D /*TLSv1.2 Kx=RSA Au=RSA Enc=AESCCM(256) Mac=AEAD */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100167#define TLS_DHE_RSA_WITH_AES_128_CCM 0xC09E /*TLSv1.2 Kx=DH Au=RSA Enc=AESCCM(128) Mac=AEAD */
Denys Vlasenko5df3b122018-11-04 21:25:41 +0100168#define TLS_DHE_RSA_WITH_AES_256_CCM 0xC09F /*TLSv1.2 Kx=DH Au=RSA Enc=AESCCM(256) Mac=AEAD */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100169#define TLS_RSA_WITH_AES_128_CCM_8 0xC0A0 /*TLSv1.2 Kx=RSA Au=RSA Enc=AESCCM8(128) Mac=AEAD */
170#define TLS_RSA_WITH_AES_256_CCM_8 0xC0A1 /*TLSv1.2 Kx=RSA Au=RSA Enc=AESCCM8(256) Mac=AEAD */
171#define TLS_DHE_RSA_WITH_AES_128_CCM_8 0xC0A2 /*TLSv1.2 Kx=DH Au=RSA Enc=AESCCM8(128) Mac=AEAD */
172#define TLS_DHE_RSA_WITH_AES_256_CCM_8 0xC0A3 /*TLSv1.2 Kx=DH Au=RSA Enc=AESCCM8(256) Mac=AEAD */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100173#define TLS_ECDHE_ECDSA_WITH_AES_128_CCM 0xC0AC /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESCCM(128) Mac=AEAD */
174#define TLS_ECDHE_ECDSA_WITH_AES_256_CCM 0xC0AD /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESCCM(256) Mac=AEAD */
175#define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESCCM8(128) Mac=AEAD */
176#define TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 0xC0AF /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESCCM8(256) Mac=AEAD */
Denys Vlasenkoa33b0082018-11-25 14:28:32 +0100177#define TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA8 /*TLSv1.2 Kx=ECDH Au=RSA Enc=CHACHA20/POLY1305(256) Mac=AEAD */
178#define TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA9 /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=CHACHA20/POLY1305(256) Mac=AEAD */
179#define TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCAA /*TLSv1.2 Kx=DH Au=RSA Enc=CHACHA20/POLY1305(256) Mac=AEAD */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100180
Denys Vlasenkob29d0452018-11-04 21:18:29 +0100181#define TLS_AES_128_GCM_SHA256 0x1301 /*TLSv1.3 Kx=any Au=any Enc=AESGCM(128) Mac=AEAD */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100182#define TLS_AES_256_GCM_SHA384 0x1302 /*TLSv1.3 Kx=any Au=any Enc=AESGCM(256) Mac=AEAD */
183#define TLS_CHACHA20_POLY1305_SHA256 0x1303 /*TLSv1.3 Kx=any Au=any Enc=CHACHA20/POLY1305(256) Mac=AEAD */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100184#define TLS_AES_128_CCM_SHA256 0x1304 /*TLSv1.3 Kx=any Au=any Enc=AESCCM(128) Mac=AEAD */
185
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100186/* Might go to libbb.h */
187#define TLS_MAX_CRYPTBLOCK_SIZE 16
188#define TLS_MAX_OUTBUF (1 << 14)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100189
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100190enum {
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100191 SHA_INSIZE = 64,
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100192
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100193 AES128_KEYSIZE = 16,
194 AES256_KEYSIZE = 32,
195
Denys Vlasenko38972a82017-01-20 19:11:14 +0100196 RSA_PREMASTER_SIZE = 48,
197
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100198 RECHDR_LEN = 5,
199
Denys Vlasenko38972a82017-01-20 19:11:14 +0100200 /* 8 = 3+5. 3 extra bytes result in record data being 32-bit aligned */
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100201 OUTBUF_PFX = 8 + AES_BLOCK_SIZE, /* header + IV */
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100202 OUTBUF_SFX = TLS_MAX_MAC_SIZE + TLS_MAX_CRYPTBLOCK_SIZE, /* MAC + padding */
Denys Vlasenko39161392017-01-20 20:27:06 +0100203
Denys Vlasenkod4681c72018-11-26 10:33:23 +0100204 // RFC 5246:
Denys Vlasenko39161392017-01-20 20:27:06 +0100205 // | 6.2.1. Fragmentation
206 // | The record layer fragments information blocks into TLSPlaintext
207 // | records carrying data in chunks of 2^14 bytes or less. Client
208 // | message boundaries are not preserved in the record layer (i.e.,
209 // | multiple client messages of the same ContentType MAY be coalesced
210 // | into a single TLSPlaintext record, or a single message MAY be
211 // | fragmented across several records)
212 // |...
213 // | length
214 // | The length (in bytes) of the following TLSPlaintext.fragment.
215 // | The length MUST NOT exceed 2^14.
216 // |...
217 // | 6.2.2. Record Compression and Decompression
218 // |...
219 // | Compression must be lossless and may not increase the content length
220 // | by more than 1024 bytes. If the decompression function encounters a
221 // | TLSCompressed.fragment that would decompress to a length in excess of
222 // | 2^14 bytes, it MUST report a fatal decompression failure error.
223 // |...
224 // | length
225 // | The length (in bytes) of the following TLSCompressed.fragment.
226 // | The length MUST NOT exceed 2^14 + 1024.
227 // |...
228 // | 6.2.3. Record Payload Protection
229 // | The encryption and MAC functions translate a TLSCompressed
230 // | structure into a TLSCiphertext. The decryption functions reverse
231 // | the process. The MAC of the record also includes a sequence
232 // | number so that missing, extra, or repeated messages are
233 // | detectable.
234 // |...
235 // | length
236 // | The length (in bytes) of the following TLSCiphertext.fragment.
237 // | The length MUST NOT exceed 2^14 + 2048.
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100238 MAX_INBUF = RECHDR_LEN + (1 << 14) + 2048,
Denys Vlasenkoa33b0082018-11-25 14:28:32 +0100239
240 /* Bits for tls->flags */
241 NEED_EC_KEY = 1 << 0,
242 GOT_CERT_RSA_KEY_ALG = 1 << 1,
243 GOT_CERT_ECDSA_KEY_ALG = 1 << 2, // so far unused
244 GOT_EC_KEY = 1 << 3,
Denys Vlasenkof18a1fd2021-04-26 13:25:56 +0200245 GOT_EC_CURVE_X25519 = 1 << 4, // else P256
246 ENCRYPTION_AESGCM = 1 << 5, // else AES-SHA (or NULL-SHA if ALLOW_RSA_NULL_SHA256=1)
247 ENCRYPT_ON_WRITE = 1 << 6,
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100248};
249
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100250struct record_hdr {
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100251 uint8_t type;
252 uint8_t proto_maj, proto_min;
253 uint8_t len16_hi, len16_lo;
254};
255
Denys Vlasenko9a647c32017-01-23 01:08:16 +0100256struct tls_handshake_data {
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100257 /* In bbox, md5/sha1/sha256 ctx's are the same structure */
258 md5sha_ctx_t handshake_hash_ctx;
259
Denys Vlasenko7a18b952017-01-23 16:37:04 +0100260 uint8_t client_and_server_rand32[2 * 32];
261 uint8_t master_secret[48];
Denys Vlasenkobddb6542018-11-13 02:16:24 +0100262
Denys Vlasenkodd2577f2017-01-20 22:48:41 +0100263//TODO: store just the DER key here, parse/use/delete it when sending client key
264//this way it will stay key type agnostic here.
Denys Vlasenko11d00962017-01-15 00:12:42 +0100265 psRsaKey_t server_rsa_pub_key;
Denys Vlasenkof18a1fd2021-04-26 13:25:56 +0200266
267 /* peer's elliptic curve key data */
268 /* for x25519, it contains one point in first 32 bytes */
269 /* for P256, it contains x,y point pair, each 32 bytes long */
270 uint8_t ecc_pub_key32[2 * 32];
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100271
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100272/* HANDSHAKE HASH: */
273 //unsigned saved_client_hello_size;
274 //uint8_t saved_client_hello[1];
Denys Vlasenko9a647c32017-01-23 01:08:16 +0100275};
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100276
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100277
278static unsigned get24be(const uint8_t *p)
279{
280 return 0x100*(0x100*p[0] + p[1]) + p[2];
281}
282
283#if TLS_DEBUG
Denys Vlasenkoeb53d012018-11-25 14:45:55 +0100284/* Nondestructively see the current hash value */
Denys Vlasenko838b88c2018-11-25 18:52:47 +0100285# if TLS_DEBUG_HASH
Denys Vlasenkoeb53d012018-11-25 14:45:55 +0100286static unsigned sha_peek(md5sha_ctx_t *ctx, void *buffer)
287{
288 md5sha_ctx_t ctx_copy = *ctx; /* struct copy */
289 return sha_end(&ctx_copy, buffer);
290}
Denys Vlasenko838b88c2018-11-25 18:52:47 +0100291# endif
Denys Vlasenkoeb53d012018-11-25 14:45:55 +0100292
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100293static void dump_hex(const char *fmt, const void *vp, int len)
294{
295 char hexbuf[32 * 1024 + 4];
296 const uint8_t *p = vp;
297
298 bin2hex(hexbuf, (void*)p, len)[0] = '\0';
299 dbg(fmt, hexbuf);
300}
301
302static void dump_tls_record(const void *vp, int len)
303{
304 const uint8_t *p = vp;
305
306 while (len > 0) {
307 unsigned xhdr_len;
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100308 if (len < RECHDR_LEN) {
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100309 dump_hex("< |%s|\n", p, len);
310 return;
311 }
312 xhdr_len = 0x100*p[3] + p[4];
313 dbg("< hdr_type:%u ver:%u.%u len:%u", p[0], p[1], p[2], xhdr_len);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100314 p += RECHDR_LEN;
315 len -= RECHDR_LEN;
316 if (len >= 4 && p[-RECHDR_LEN] == RECORD_TYPE_HANDSHAKE) {
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100317 unsigned len24 = get24be(p + 1);
318 dbg(" type:%u len24:%u", p[0], len24);
319 }
320 if (xhdr_len > len)
321 xhdr_len = len;
322 dump_hex(" |%s|\n", p, xhdr_len);
323 p += xhdr_len;
324 len -= xhdr_len;
325 }
326}
Denys Vlasenko38972a82017-01-20 19:11:14 +0100327#else
328# define dump_hex(...) ((void)0)
329# define dump_tls_record(...) ((void)0)
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100330#endif
331
Denys Vlasenko624066f2018-11-23 19:24:57 +0100332void FAST_FUNC tls_get_random(void *buf, unsigned len)
Denys Vlasenko11d00962017-01-15 00:12:42 +0100333{
334 if (len != open_read_close("/dev/urandom", buf, len))
335 xfunc_die();
336}
337
Denys Vlasenko941440c2018-11-24 13:51:46 +0100338static void xorbuf3(void *dst, const void *src1, const void *src2, unsigned count)
339{
340 uint8_t *d = dst;
341 const uint8_t *s1 = src1;
342 const uint8_t* s2 = src2;
343 while (count--)
344 *d++ = *s1++ ^ *s2++;
345}
346
347void FAST_FUNC xorbuf(void *dst, const void *src, unsigned count)
348{
349 xorbuf3(dst, dst, src, count);
350}
351
Denys Vlasenko03569bc2018-11-24 14:08:29 +0100352void FAST_FUNC xorbuf_aligned_AES_BLOCK_SIZE(void *dst, const void *src)
353{
354 unsigned long *d = dst;
355 const unsigned long *s = src;
356 d[0] ^= s[0];
357#if ULONG_MAX <= 0xffffffffffffffff
358 d[1] ^= s[1];
359 #if ULONG_MAX == 0xffffffff
360 d[2] ^= s[2];
361 d[3] ^= s[3];
362 #endif
363#endif
364}
365
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100366#if !TLS_DEBUG_HASH
367# define hash_handshake(tls, fmt, buffer, len) \
368 hash_handshake(tls, buffer, len)
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +0100369#endif
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100370static void hash_handshake(tls_state_t *tls, const char *fmt, const void *buffer, unsigned len)
371{
372 md5sha_hash(&tls->hsd->handshake_hash_ctx, buffer, len);
373#if TLS_DEBUG_HASH
374 {
375 uint8_t h[TLS_MAX_MAC_SIZE];
376 dump_hex(fmt, buffer, len);
377 dbg(" (%u bytes) ", (int)len);
378 len = sha_peek(&tls->hsd->handshake_hash_ctx, h);
Denys Vlasenko71fa5b02018-12-10 16:14:58 +0100379 if (ENABLE_FEATURE_TLS_SHA1 && len == SHA1_OUTSIZE)
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100380 dump_hex("sha1:%s\n", h, len);
381 else
382 if (len == SHA256_OUTSIZE)
383 dump_hex("sha256:%s\n", h, len);
384 else
385 dump_hex("sha???:%s\n", h, len);
386 }
387#endif
388}
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100389
Denys Vlasenko63bfe0e2018-12-10 16:43:53 +0100390#if !ENABLE_FEATURE_TLS_SHA1
391# define TLS_MAC_SIZE(tls) SHA256_OUTSIZE
392#else
393# define TLS_MAC_SIZE(tls) (tls)->MAC_size
394#endif
395
Denys Vlasenkod4681c72018-11-26 10:33:23 +0100396// RFC 2104:
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100397// HMAC(key, text) based on a hash H (say, sha256) is:
398// ipad = [0x36 x INSIZE]
399// opad = [0x5c x INSIZE]
400// HMAC(key, text) = H((key XOR opad) + H((key XOR ipad) + text))
401//
402// H(key XOR opad) and H(key XOR ipad) can be precomputed
403// if we often need HMAC hmac with the same key.
404//
405// text is often given in disjoint pieces.
Denys Vlasenko89193f92017-01-24 18:08:07 +0100406typedef struct hmac_precomputed {
407 md5sha_ctx_t hashed_key_xor_ipad;
408 md5sha_ctx_t hashed_key_xor_opad;
409} hmac_precomputed_t;
410
Denys Vlasenko636c3b62017-04-03 17:43:44 +0200411typedef void md5sha_begin_func(md5sha_ctx_t *ctx) FAST_FUNC;
Denys Vlasenko71fa5b02018-12-10 16:14:58 +0100412#if !ENABLE_FEATURE_TLS_SHA1
413#define hmac_begin(pre,key,key_size,begin) \
414 hmac_begin(pre,key,key_size)
415#define begin sha256_begin
416#endif
Denys Vlasenko636c3b62017-04-03 17:43:44 +0200417static void hmac_begin(hmac_precomputed_t *pre, uint8_t *key, unsigned key_size, md5sha_begin_func *begin)
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100418{
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100419 uint8_t key_xor_ipad[SHA_INSIZE];
420 uint8_t key_xor_opad[SHA_INSIZE];
Denys Vlasenkod4681c72018-11-26 10:33:23 +0100421// uint8_t tempkey[SHA1_OUTSIZE < SHA256_OUTSIZE ? SHA256_OUTSIZE : SHA1_OUTSIZE];
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100422 unsigned i;
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100423
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100424 // "The authentication key can be of any length up to INSIZE, the
425 // block length of the hash function. Applications that use keys longer
426 // than INSIZE bytes will first hash the key using H and then use the
427 // resultant OUTSIZE byte string as the actual key to HMAC."
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100428 if (key_size > SHA_INSIZE) {
James Byrne69374872019-07-02 11:35:03 +0200429 bb_simple_error_msg_and_die("HMAC key>64"); //does not happen (yet?)
Denys Vlasenkod4681c72018-11-26 10:33:23 +0100430// md5sha_ctx_t ctx;
431// begin(&ctx);
432// md5sha_hash(&ctx, key, key_size);
433// key_size = sha_end(&ctx, tempkey);
434// //key = tempkey; - right? RIGHT? why does it work without this?
435// // because SHA_INSIZE is 64, but hmac() is always called with
436// // key_size = tls->MAC_size = SHA1/256_OUTSIZE (20 or 32),
437// // and prf_hmac_sha256() -> hmac_sha256() key sizes are:
438// // - RSA_PREMASTER_SIZE is 48
439// // - CURVE25519_KEYSIZE is 32
440// // - master_secret[] is 48
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100441 }
442
443 for (i = 0; i < key_size; i++) {
444 key_xor_ipad[i] = key[i] ^ 0x36;
445 key_xor_opad[i] = key[i] ^ 0x5c;
446 }
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100447 for (; i < SHA_INSIZE; i++) {
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100448 key_xor_ipad[i] = 0x36;
449 key_xor_opad[i] = 0x5c;
450 }
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100451
Denys Vlasenko636c3b62017-04-03 17:43:44 +0200452 begin(&pre->hashed_key_xor_ipad);
453 begin(&pre->hashed_key_xor_opad);
Denys Vlasenko89193f92017-01-24 18:08:07 +0100454 md5sha_hash(&pre->hashed_key_xor_ipad, key_xor_ipad, SHA_INSIZE);
455 md5sha_hash(&pre->hashed_key_xor_opad, key_xor_opad, SHA_INSIZE);
456}
Denys Vlasenko71fa5b02018-12-10 16:14:58 +0100457#undef begin
Denys Vlasenko89193f92017-01-24 18:08:07 +0100458
Denys Vlasenkod9f6c3b2018-11-26 15:55:41 +0100459static unsigned hmac_sha_precomputed_v(
460 hmac_precomputed_t *pre,
461 uint8_t *out,
462 va_list va)
463{
464 uint8_t *text;
465 unsigned len;
466
467 /* pre->hashed_key_xor_ipad contains unclosed "H((key XOR ipad) +" state */
468 /* pre->hashed_key_xor_opad contains unclosed "H((key XOR opad) +" state */
469
470 /* calculate out = H((key XOR ipad) + text) */
471 while ((text = va_arg(va, uint8_t*)) != NULL) {
472 unsigned text_size = va_arg(va, unsigned);
473 md5sha_hash(&pre->hashed_key_xor_ipad, text, text_size);
474 }
475 len = sha_end(&pre->hashed_key_xor_ipad, out);
476
477 /* out = H((key XOR opad) + out) */
478 md5sha_hash(&pre->hashed_key_xor_opad, out, len);
479 return sha_end(&pre->hashed_key_xor_opad, out);
480}
481
482static unsigned hmac_sha_precomputed(hmac_precomputed_t *pre_init, uint8_t *out, ...)
483{
484 hmac_precomputed_t pre;
485 va_list va;
486 unsigned len;
487
488 va_start(va, out);
489 pre = *pre_init; /* struct copy */
490 len = hmac_sha_precomputed_v(&pre, out, va);
491 va_end(va);
492 return len;
493}
494
Denys Vlasenko71fa5b02018-12-10 16:14:58 +0100495#if !ENABLE_FEATURE_TLS_SHA1
496#define hmac(tls,out,key,key_size,...) \
497 hmac(out,key,key_size, __VA_ARGS__)
498#endif
Denys Vlasenko89193f92017-01-24 18:08:07 +0100499static unsigned hmac(tls_state_t *tls, uint8_t *out, uint8_t *key, unsigned key_size, ...)
500{
501 hmac_precomputed_t pre;
502 va_list va;
503 unsigned len;
504
505 va_start(va, key_size);
506
Denys Vlasenko636c3b62017-04-03 17:43:44 +0200507 hmac_begin(&pre, key, key_size,
Denys Vlasenko3a4d5a72018-12-10 19:19:38 +0100508 (ENABLE_FEATURE_TLS_SHA1 && tls->MAC_size == SHA1_OUTSIZE)
509 ? sha1_begin
510 : sha256_begin
Denys Vlasenko636c3b62017-04-03 17:43:44 +0200511 );
Denys Vlasenko89193f92017-01-24 18:08:07 +0100512 len = hmac_sha_precomputed_v(&pre, out, va);
513
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100514 va_end(va);
Denys Vlasenko89193f92017-01-24 18:08:07 +0100515 return len;
516}
517
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100518// RFC 5246:
519// 5. HMAC and the Pseudorandom Function
520//...
521// In this section, we define one PRF, based on HMAC. This PRF with the
522// SHA-256 hash function is used for all cipher suites defined in this
523// document and in TLS documents published prior to this document when
524// TLS 1.2 is negotiated.
Denys Vlasenko89193f92017-01-24 18:08:07 +0100525// ^^^^^^^^^^^^^ IMPORTANT!
Denys Vlasenkod4681c72018-11-26 10:33:23 +0100526// PRF uses sha256 regardless of cipher for all ciphers
527// defined by RFC 5246. It's not sha1 for AES_128_CBC_SHA!
528// However, for _SHA384 ciphers, it's sha384. See RFC 5288,5289.
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100529//...
530// P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
531// HMAC_hash(secret, A(2) + seed) +
532// HMAC_hash(secret, A(3) + seed) + ...
533// where + indicates concatenation.
534// A() is defined as:
535// A(0) = seed
536// A(1) = HMAC_hash(secret, A(0)) = HMAC_hash(secret, seed)
537// A(i) = HMAC_hash(secret, A(i-1))
538// P_hash can be iterated as many times as necessary to produce the
539// required quantity of data. For example, if P_SHA256 is being used to
540// create 80 bytes of data, it will have to be iterated three times
541// (through A(3)), creating 96 bytes of output data; the last 16 bytes
542// of the final iteration will then be discarded, leaving 80 bytes of
543// output data.
544//
545// TLS's PRF is created by applying P_hash to the secret as:
546//
547// PRF(secret, label, seed) = P_<hash>(secret, label + seed)
548//
549// The label is an ASCII string.
Denys Vlasenkod4681c72018-11-26 10:33:23 +0100550//
551// RFC 5288:
552// For cipher suites ending with _SHA256, the PRF is the TLS PRF
553// with SHA-256 as the hash function.
554// For cipher suites ending with _SHA384, the PRF is the TLS PRF
555// with SHA-384 as the hash function.
Denys Vlasenko89193f92017-01-24 18:08:07 +0100556static void prf_hmac_sha256(/*tls_state_t *tls,*/
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100557 uint8_t *outbuf, unsigned outbuf_size,
558 uint8_t *secret, unsigned secret_size,
559 const char *label,
560 uint8_t *seed, unsigned seed_size)
561{
Denys Vlasenkod9f6c3b2018-11-26 15:55:41 +0100562 hmac_precomputed_t pre;
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100563 uint8_t a[TLS_MAX_MAC_SIZE];
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100564 uint8_t *out_p = outbuf;
565 unsigned label_size = strlen(label);
Denys Vlasenko229d3c42017-04-03 21:53:29 +0200566 unsigned MAC_size = SHA256_OUTSIZE;
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100567
568 /* In P_hash() calculation, "seed" is "label + seed": */
569#define SEED label, label_size, seed, seed_size
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100570#define A a, MAC_size
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100571
Denys Vlasenkod9f6c3b2018-11-26 15:55:41 +0100572 hmac_begin(&pre, secret, secret_size, sha256_begin);
573
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100574 /* A(1) = HMAC_hash(secret, seed) */
Denys Vlasenkod9f6c3b2018-11-26 15:55:41 +0100575 hmac_sha_precomputed(&pre, a, SEED, NULL);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100576
Denys Vlasenko229d3c42017-04-03 21:53:29 +0200577 for (;;) {
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100578 /* HMAC_hash(secret, A(1) + seed) */
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100579 if (outbuf_size <= MAC_size) {
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100580 /* Last, possibly incomplete, block */
581 /* (use a[] as temp buffer) */
Denys Vlasenkod9f6c3b2018-11-26 15:55:41 +0100582 hmac_sha_precomputed(&pre, a, A, SEED, NULL);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100583 memcpy(out_p, a, outbuf_size);
584 return;
585 }
586 /* Not last block. Store directly to result buffer */
Denys Vlasenkod9f6c3b2018-11-26 15:55:41 +0100587 hmac_sha_precomputed(&pre, out_p, A, SEED, NULL);
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100588 out_p += MAC_size;
589 outbuf_size -= MAC_size;
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100590 /* A(2) = HMAC_hash(secret, A(1)) */
Denys Vlasenkod9f6c3b2018-11-26 15:55:41 +0100591 hmac_sha_precomputed(&pre, a, A, NULL);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100592 }
593#undef A
594#undef SECRET
595#undef SEED
596}
597
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100598static void bad_record_die(tls_state_t *tls, const char *expected, int len)
599{
Denys Vlasenko1500b3a2017-01-24 17:06:10 +0100600 bb_error_msg("got bad TLS record (len:%d) while expecting %s", len, expected);
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100601 if (len > 0) {
602 uint8_t *p = tls->inbuf;
Denys Vlasenko98066662018-02-06 13:33:00 +0100603 if (len > 99)
604 len = 99; /* don't flood, a few lines should be enough */
605 do {
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100606 fprintf(stderr, " %02x", *p++);
Denys Vlasenko1500b3a2017-01-24 17:06:10 +0100607 len--;
Denys Vlasenko98066662018-02-06 13:33:00 +0100608 } while (len != 0);
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100609 fputc('\n', stderr);
610 }
611 xfunc_die();
612}
613
Denys Vlasenko1500b3a2017-01-24 17:06:10 +0100614static void tls_error_die(tls_state_t *tls, int line)
Denys Vlasenko936e83e2017-01-16 04:25:01 +0100615{
Denys Vlasenko39161392017-01-20 20:27:06 +0100616 dump_tls_record(tls->inbuf, tls->ofs_to_buffered + tls->buffered_size);
Denys Vlasenko1500b3a2017-01-24 17:06:10 +0100617 bb_error_msg_and_die("tls error at line %d cipher:%04x", line, tls->cipher_id);
Denys Vlasenko38972a82017-01-20 19:11:14 +0100618}
Denys Vlasenko1500b3a2017-01-24 17:06:10 +0100619#define tls_error_die(tls) tls_error_die(tls, __LINE__)
Denys Vlasenko38972a82017-01-20 19:11:14 +0100620
Denys Vlasenko39161392017-01-20 20:27:06 +0100621#if 0 //UNUSED
622static void tls_free_inbuf(tls_state_t *tls)
623{
624 if (tls->buffered_size == 0) {
625 free(tls->inbuf);
626 tls->inbuf_size = 0;
627 tls->inbuf = NULL;
628 }
629}
630#endif
631
Denys Vlasenko38972a82017-01-20 19:11:14 +0100632static void tls_free_outbuf(tls_state_t *tls)
633{
634 free(tls->outbuf);
635 tls->outbuf_size = 0;
636 tls->outbuf = NULL;
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100637}
638
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100639static void *tls_get_outbuf(tls_state_t *tls, int len)
640{
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100641 if (len > TLS_MAX_OUTBUF)
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100642 xfunc_die();
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100643 len += OUTBUF_PFX + OUTBUF_SFX;
644 if (tls->outbuf_size < len) {
645 tls->outbuf_size = len;
646 tls->outbuf = xrealloc(tls->outbuf, len);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100647 }
648 return tls->outbuf + OUTBUF_PFX;
649}
650
Denys Vlasenkod5a04052018-11-13 11:58:53 +0100651static void *tls_get_zeroed_outbuf(tls_state_t *tls, int len)
652{
653 void *record = tls_get_outbuf(tls, len);
654 memset(record, 0, len);
655 return record;
656}
657
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100658static void xwrite_encrypted_and_hmac_signed(tls_state_t *tls, unsigned size, unsigned type)
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100659{
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100660 uint8_t *buf = tls->outbuf + OUTBUF_PFX;
661 struct record_hdr *xhdr;
Denys Vlasenkoe7863f32017-01-20 17:59:25 +0100662 uint8_t padding_length;
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100663
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100664 xhdr = (void*)(buf - RECHDR_LEN);
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +0100665 if (!ALLOW_RSA_NULL_SHA256 /* if "no encryption" can't be selected */
Denys Vlasenko5d561ef2017-04-04 01:41:15 +0200666 || tls->cipher_id != TLS_RSA_WITH_NULL_SHA256 /* or if it wasn't selected */
667 ) {
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100668 xhdr = (void*)(buf - RECHDR_LEN - AES_BLOCK_SIZE); /* place for IV */
Denys Vlasenko5d561ef2017-04-04 01:41:15 +0200669 }
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +0100670
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100671 xhdr->type = type;
672 xhdr->proto_maj = TLS_MAJ;
673 xhdr->proto_min = TLS_MIN;
Denys Vlasenko54b927d2017-01-20 21:19:38 +0100674 /* fake unencrypted record len for MAC calculation */
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100675 xhdr->len16_hi = size >> 8;
676 xhdr->len16_lo = size & 0xff;
677
678 /* Calculate MAC signature */
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100679 hmac(tls, buf + size, /* result */
Denys Vlasenko63bfe0e2018-12-10 16:43:53 +0100680 tls->client_write_MAC_key, TLS_MAC_SIZE(tls),
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100681 &tls->write_seq64_be, sizeof(tls->write_seq64_be),
682 xhdr, RECHDR_LEN,
683 buf, size,
684 NULL
685 );
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +0100686 tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(tls->write_seq64_be));
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100687
Denys Vlasenko63bfe0e2018-12-10 16:43:53 +0100688 size += TLS_MAC_SIZE(tls);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100689
Denys Vlasenkod4681c72018-11-26 10:33:23 +0100690 // RFC 5246:
Denys Vlasenkoe7863f32017-01-20 17:59:25 +0100691 // 6.2.3.1. Null or Standard Stream Cipher
692 //
693 // Stream ciphers (including BulkCipherAlgorithm.null; see Appendix A.6)
694 // convert TLSCompressed.fragment structures to and from stream
695 // TLSCiphertext.fragment structures.
696 //
697 // stream-ciphered struct {
698 // opaque content[TLSCompressed.length];
699 // opaque MAC[SecurityParameters.mac_length];
700 // } GenericStreamCipher;
701 //
702 // The MAC is generated as:
703 // MAC(MAC_write_key, seq_num +
704 // TLSCompressed.type +
705 // TLSCompressed.version +
706 // TLSCompressed.length +
707 // TLSCompressed.fragment);
708 // where "+" denotes concatenation.
709 // seq_num
710 // The sequence number for this record.
711 // MAC
712 // The MAC algorithm specified by SecurityParameters.mac_algorithm.
713 //
714 // Note that the MAC is computed before encryption. The stream cipher
715 // encrypts the entire block, including the MAC.
716 //...
717 // Appendix C. Cipher Suite Definitions
718 //...
719 // MAC Algorithm mac_length mac_key_length
720 // -------- ----------- ---------- --------------
721 // SHA HMAC-SHA1 20 20
722 // SHA256 HMAC-SHA256 32 32
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +0100723 if (ALLOW_RSA_NULL_SHA256
Denys Vlasenko5d561ef2017-04-04 01:41:15 +0200724 && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
725 ) {
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100726 /* No encryption, only signing */
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100727 xhdr->len16_hi = size >> 8;
728 xhdr->len16_lo = size & 0xff;
Denys Vlasenkoe7863f32017-01-20 17:59:25 +0100729 dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
Denys Vlasenko9a647c32017-01-23 01:08:16 +0100730 xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100731 dbg("wrote %u bytes (NULL crypt, SHA256 hash)\n", size);
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100732 return;
733 }
734
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100735 // 6.2.3.2. CBC Block Cipher
736 // For block ciphers (such as 3DES or AES), the encryption and MAC
737 // functions convert TLSCompressed.fragment structures to and from block
738 // TLSCiphertext.fragment structures.
739 // struct {
740 // opaque IV[SecurityParameters.record_iv_length];
741 // block-ciphered struct {
742 // opaque content[TLSCompressed.length];
743 // opaque MAC[SecurityParameters.mac_length];
744 // uint8 padding[GenericBlockCipher.padding_length];
745 // uint8 padding_length;
746 // };
747 // } GenericBlockCipher;
748 //...
749 // IV
750 // The Initialization Vector (IV) SHOULD be chosen at random, and
751 // MUST be unpredictable. Note that in versions of TLS prior to 1.1,
752 // there was no IV field (...). For block ciphers, the IV length is
753 // of length SecurityParameters.record_iv_length, which is equal to the
754 // SecurityParameters.block_size.
755 // padding
756 // Padding that is added to force the length of the plaintext to be
757 // an integral multiple of the block cipher's block length.
758 // padding_length
759 // The padding length MUST be such that the total size of the
760 // GenericBlockCipher structure is a multiple of the cipher's block
761 // length. Legal values range from zero to 255, inclusive.
762 //...
763 // Appendix C. Cipher Suite Definitions
764 //...
765 // Key IV Block
766 // Cipher Type Material Size Size
767 // ------------ ------ -------- ---- -----
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100768 // AES_128_CBC Block 16 16 16
769 // AES_256_CBC Block 32 16 16
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100770
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100771 tls_get_random(buf - AES_BLOCK_SIZE, AES_BLOCK_SIZE); /* IV */
Denys Vlasenko98066662018-02-06 13:33:00 +0100772 dbg("before crypt: 5 hdr + %u data + %u hash bytes\n",
Denys Vlasenko63bfe0e2018-12-10 16:43:53 +0100773 size - TLS_MAC_SIZE(tls), TLS_MAC_SIZE(tls));
Denys Vlasenko98066662018-02-06 13:33:00 +0100774
775 /* Fill IV and padding in outbuf */
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100776 // RFC is talking nonsense:
Denys Vlasenko7a18b952017-01-23 16:37:04 +0100777 // "Padding that is added to force the length of the plaintext to be
778 // an integral multiple of the block cipher's block length."
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100779 // WRONG. _padding+padding_length_, not just _padding_,
780 // pads the data.
781 // IOW: padding_length is the last byte of padding[] array,
782 // contrary to what RFC depicts.
783 //
784 // What actually happens is that there is always padding.
785 // If you need one byte to reach BLOCKSIZE, this byte is 0x00.
786 // If you need two bytes, they are both 0x01.
787 // If you need three, they are 0x02,0x02,0x02. And so on.
788 // If you need no bytes to reach BLOCKSIZE, you have to pad a full
789 // BLOCKSIZE with bytes of value (BLOCKSIZE-1).
790 // It's ok to have more than minimum padding, but we do minimum.
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100791 padding_length = (~size) & (AES_BLOCK_SIZE - 1);
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100792 do {
Denys Vlasenko54b927d2017-01-20 21:19:38 +0100793 buf[size++] = padding_length; /* padding */
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100794 } while ((size & (AES_BLOCK_SIZE - 1)) != 0);
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100795
796 /* Encrypt content+MAC+padding in place */
Denys Vlasenkoc31b54f2017-02-04 16:23:49 +0100797 aes_cbc_encrypt(
Denys Vlasenkod2923b32018-11-24 21:26:20 +0100798 &tls->aes_encrypt, /* selects 128/256 */
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100799 buf - AES_BLOCK_SIZE, /* IV */
Denys Vlasenkoc31b54f2017-02-04 16:23:49 +0100800 buf, size, /* plaintext */
801 buf /* ciphertext */
802 );
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100803
804 /* Write out */
805 dbg("writing 5 + %u IV + %u encrypted bytes, padding_length:0x%02x\n",
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100806 AES_BLOCK_SIZE, size, padding_length);
807 size += AES_BLOCK_SIZE; /* + IV */
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100808 xhdr->len16_hi = size >> 8;
809 xhdr->len16_lo = size & 0xff;
Denys Vlasenkoe7863f32017-01-20 17:59:25 +0100810 dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
Denys Vlasenko9a647c32017-01-23 01:08:16 +0100811 xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100812 dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100813}
814
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100815/* Example how GCM encryption combines nonce, aad, input and generates
816 * "header | exp_nonce | encrypted output | tag":
817 * nonce:0d 6a 26 31 00 00 00 00 00 00 00 01 (implicit 4 bytes (derived from master secret), then explicit 8 bytes)
818 * aad: 00 00 00 00 00 00 00 01 17 03 03 00 1c
819 * in: 47 45 54 20 2f 69 6e 64 65 78 2e 68 74 6d 6c 20 48 54 54 50 2f 31 2e 30 0d 0a 0d 0a "GET /index.html HTTP/1.0\r\n\r\n" (0x1c bytes)
820 * out: f7 8a b2 8f 78 0e f6 d5 76 17 2e b5 6d 46 59 56 8b 46 9f 0b d9 2c 35 28 13 66 19 be
821 * tag: c2 86 ce 4a 50 4a d0 aa 50 b3 76 5c 49 2a 3f 33
822 * sent: 17 03 03 00 34|00 00 00 00 00 00 00 01|f7 8a b2 8f 78 0e f6 d5 76 17 2e b5 6d 46 59 56 8b 46 9f 0b d9 2c 35 28 13 66 19 be|c2 86 ce 4a 50 4a d0 aa 50 b3 76 5c 49 2a 3f 33
823 * .............................................^^ buf points here
824 */
825static void xwrite_encrypted_aesgcm(tls_state_t *tls, unsigned size, unsigned type)
826{
Denys Vlasenkoecc90902018-11-23 18:31:26 +0100827#define COUNTER(v) (*(uint32_t*)(v + 12))
828
Denys Vlasenko03569bc2018-11-24 14:08:29 +0100829 uint8_t aad[13 + 3] ALIGNED_long; /* +3 creates [16] buffer, simplifying GHASH() */
830 uint8_t nonce[12 + 4] ALIGNED_long; /* +4 creates space for AES block counter */
831 uint8_t scratch[AES_BLOCK_SIZE] ALIGNED_long; //[16]
832 uint8_t authtag[AES_BLOCK_SIZE] ALIGNED_long; //[16]
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100833 uint8_t *buf;
834 struct record_hdr *xhdr;
835 unsigned remaining;
836 unsigned cnt;
Denys Vlasenko219c9d42018-11-23 18:48:20 +0100837 uint64_t t64;
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100838
839 buf = tls->outbuf + OUTBUF_PFX; /* see above for the byte it points to */
840 dump_hex("xwrite_encrypted_aesgcm plaintext:%s\n", buf, size);
841
842 xhdr = (void*)(buf - 8 - RECHDR_LEN);
843 xhdr->type = type; /* do it here so that "type" param no longer used */
844
845 aad[8] = type;
846 aad[9] = TLS_MAJ;
847 aad[10] = TLS_MIN;
848 aad[11] = size >> 8;
Denys Vlasenkoecc90902018-11-23 18:31:26 +0100849 /* set aad[12], and clear aad[13..15] */
850 COUNTER(aad) = SWAP_LE32(size & 0xff);
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100851
Denys Vlasenko219c9d42018-11-23 18:48:20 +0100852 memcpy(nonce, tls->client_write_IV, 4);
853 t64 = tls->write_seq64_be;
854 move_to_unaligned64(nonce + 4, t64);
855 move_to_unaligned64(aad, t64);
856 move_to_unaligned64(buf - 8, t64);
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100857 /* seq64 is not used later in this func, can increment here */
Denys Vlasenko219c9d42018-11-23 18:48:20 +0100858 tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(t64));
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100859
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100860 cnt = 1;
861 remaining = size;
862 while (remaining != 0) {
863 unsigned n;
864
865 cnt++;
866 COUNTER(nonce) = htonl(cnt); /* yes, first cnt here is 2 (!) */
867 aes_encrypt_one_block(&tls->aes_encrypt, nonce, scratch);
868 n = remaining > AES_BLOCK_SIZE ? AES_BLOCK_SIZE : remaining;
869 xorbuf(buf, scratch, n);
870 buf += n;
871 remaining -= n;
872 }
873
Denys Vlasenkoecc90902018-11-23 18:31:26 +0100874 aesgcm_GHASH(tls->H, aad, /*sizeof(aad),*/ tls->outbuf + OUTBUF_PFX, size, authtag /*, sizeof(authtag)*/);
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100875 COUNTER(nonce) = htonl(1);
876 aes_encrypt_one_block(&tls->aes_encrypt, nonce, scratch);
Denys Vlasenko03569bc2018-11-24 14:08:29 +0100877 xorbuf_aligned_AES_BLOCK_SIZE(authtag, scratch);
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100878
879 memcpy(buf, authtag, sizeof(authtag));
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100880
881 /* Write out */
882 xhdr = (void*)(tls->outbuf + OUTBUF_PFX - 8 - RECHDR_LEN);
883 size += 8 + sizeof(authtag);
884 /*xhdr->type = type; - already is */
885 xhdr->proto_maj = TLS_MAJ;
886 xhdr->proto_min = TLS_MIN;
887 xhdr->len16_hi = size >> 8;
888 xhdr->len16_lo = size & 0xff;
889 size += RECHDR_LEN;
890 dump_raw_out(">> %s\n", xhdr, size);
891 xwrite(tls->ofd, xhdr, size);
892 dbg("wrote %u bytes\n", size);
Denys Vlasenkobe5ca422018-11-25 14:03:59 +0100893#undef COUNTER
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100894}
895
896static void xwrite_encrypted(tls_state_t *tls, unsigned size, unsigned type)
897{
898 if (!(tls->flags & ENCRYPTION_AESGCM)) {
899 xwrite_encrypted_and_hmac_signed(tls, size, type);
900 return;
901 }
902 xwrite_encrypted_aesgcm(tls, size, type);
903}
904
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100905static void xwrite_handshake_record(tls_state_t *tls, unsigned size)
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100906{
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100907 uint8_t *buf = tls->outbuf + OUTBUF_PFX;
908 struct record_hdr *xhdr = (void*)(buf - RECHDR_LEN);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100909
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100910 xhdr->type = RECORD_TYPE_HANDSHAKE;
911 xhdr->proto_maj = TLS_MAJ;
912 xhdr->proto_min = TLS_MIN;
913 xhdr->len16_hi = size >> 8;
914 xhdr->len16_lo = size & 0xff;
915 dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
916 xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
917 dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100918}
919
920static void xwrite_and_update_handshake_hash(tls_state_t *tls, unsigned size)
921{
Denys Vlasenkoeb53d012018-11-25 14:45:55 +0100922 if (!(tls->flags & ENCRYPT_ON_WRITE)) {
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100923 uint8_t *buf;
924
925 xwrite_handshake_record(tls, size);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100926 /* Handshake hash does not include record headers */
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100927 buf = tls->outbuf + OUTBUF_PFX;
928 hash_handshake(tls, ">> hash:%s", buf, size);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100929 return;
930 }
931 xwrite_encrypted(tls, size, RECORD_TYPE_HANDSHAKE);
932}
933
Denys Vlasenko38972a82017-01-20 19:11:14 +0100934static int tls_has_buffered_record(tls_state_t *tls)
935{
Denys Vlasenko39161392017-01-20 20:27:06 +0100936 int buffered = tls->buffered_size;
Denys Vlasenko38972a82017-01-20 19:11:14 +0100937 struct record_hdr *xhdr;
938 int rec_size;
939
940 if (buffered < RECHDR_LEN)
941 return 0;
Denys Vlasenko39161392017-01-20 20:27:06 +0100942 xhdr = (void*)(tls->inbuf + tls->ofs_to_buffered);
Denys Vlasenko38972a82017-01-20 19:11:14 +0100943 rec_size = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
944 if (buffered < rec_size)
945 return 0;
946 return rec_size;
947}
948
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100949static const char *alert_text(int code)
950{
Denys Vlasenko9bab5802022-09-08 16:31:44 +0200951 //10 unexpected_message
952 //20 bad_record_mac
953 //21 decryption_failed
954 //22 record_overflow
955 //30 decompression_failure
956 //40 handshake_failure
957 //41 no_certificate
958 //42 bad_certificate
959 //43 unsupported_certificate
960 //44 certificate_revoked
961 //45 certificate_expired
962 //46 certificate_unknown
963 //47 illegal_parameter
964 //48 unknown_ca
965 //49 access_denied
966 //50 decode_error
967 //51 decrypt_error
968 //52 too_many_cids_requested
969 //60 export_restriction
970 //70 protocol_version
971 //71 insufficient_security
972 //80 internal_error
973 //86 inappropriate_fallback
974 //90 user_canceled
975 //100 no_renegotiation
976 //109 missing_extension
977 //110 unsupported_extension
978 //111 certificate_unobtainable
979 //112 unrecognized_name
980 //113 bad_certificate_status_response
981 //114 bad_certificate_hash_value
982 //115 unknown_psk_identity
983 //116 certificate_required
984 //120 no_application_protocol
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100985 switch (code) {
986 case 20: return "bad MAC";
987 case 50: return "decode error";
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100988 case 40: return "handshake failure";
Denys Vlasenko9bab5802022-09-08 16:31:44 +0200989 case 51: return "decrypt error";
990 case 80: return "internal error";
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100991 case 112: return "unrecognized name";
992 }
993 return itoa(code);
994}
995
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100996static void tls_aesgcm_decrypt(tls_state_t *tls, uint8_t *buf, int size)
997{
Denys Vlasenkoecc90902018-11-23 18:31:26 +0100998#define COUNTER(v) (*(uint32_t*)(v + 12))
999
Denys Vlasenko03569bc2018-11-24 14:08:29 +01001000 //uint8_t aad[13 + 3] ALIGNED_long; /* +3 creates [16] buffer, simplifying GHASH() */
1001 uint8_t nonce[12 + 4] ALIGNED_long; /* +4 creates space for AES block counter */
1002 uint8_t scratch[AES_BLOCK_SIZE] ALIGNED_long; //[16]
1003 //uint8_t authtag[AES_BLOCK_SIZE] ALIGNED_long; //[16]
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001004 unsigned remaining;
1005 unsigned cnt;
1006
Denys Vlasenko219c9d42018-11-23 18:48:20 +01001007 //memcpy(aad, buf, 8);
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001008 //aad[8] = type;
1009 //aad[9] = TLS_MAJ;
1010 //aad[10] = TLS_MIN;
1011 //aad[11] = size >> 8;
Denys Vlasenkoecc90902018-11-23 18:31:26 +01001012 ///* set aad[12], and clear aad[13..15] */
1013 //COUNTER(aad) = SWAP_LE32(size & 0xff);
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001014
1015 memcpy(nonce, tls->server_write_IV, 4);
1016 memcpy(nonce + 4, buf, 8);
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001017
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001018 cnt = 1;
1019 remaining = size;
1020 while (remaining != 0) {
1021 unsigned n;
1022
1023 cnt++;
1024 COUNTER(nonce) = htonl(cnt); /* yes, first cnt here is 2 (!) */
1025 aes_encrypt_one_block(&tls->aes_decrypt, nonce, scratch);
1026 n = remaining > AES_BLOCK_SIZE ? AES_BLOCK_SIZE : remaining;
Denys Vlasenko941440c2018-11-24 13:51:46 +01001027 xorbuf3(buf, scratch, buf + 8, n);
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001028 buf += n;
1029 remaining -= n;
1030 }
1031
Denys Vlasenko941440c2018-11-24 13:51:46 +01001032 //aesgcm_GHASH(tls->H, aad, tls->inbuf + RECHDR_LEN, size, authtag);
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001033 //COUNTER(nonce) = htonl(1);
1034 //aes_encrypt_one_block(&tls->aes_encrypt, nonce, scratch);
Denys Vlasenko03569bc2018-11-24 14:08:29 +01001035 //xorbuf_aligned_AES_BLOCK_SIZE(authtag, scratch);
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001036
1037 //memcmp(buf, authtag, sizeof(authtag)) || DIE("HASH DOES NOT MATCH!");
1038#undef COUNTER
1039}
1040
Denys Vlasenko98066662018-02-06 13:33:00 +01001041static int tls_xread_record(tls_state_t *tls, const char *expected)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001042{
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001043 struct record_hdr *xhdr;
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01001044 int sz;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001045 int total;
1046 int target;
1047
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001048 again:
Denys Vlasenko39161392017-01-20 20:27:06 +01001049 dbg("ofs_to_buffered:%u buffered_size:%u\n", tls->ofs_to_buffered, tls->buffered_size);
1050 total = tls->buffered_size;
Denys Vlasenkoe7863f32017-01-20 17:59:25 +01001051 if (total != 0) {
Denys Vlasenko39161392017-01-20 20:27:06 +01001052 memmove(tls->inbuf, tls->inbuf + tls->ofs_to_buffered, total);
1053 //dbg("<< remaining at %d [%d] ", tls->ofs_to_buffered, total);
Denys Vlasenkoe7863f32017-01-20 17:59:25 +01001054 //dump_raw_in("<< %s\n", tls->inbuf, total);
1055 }
1056 errno = 0;
Denys Vlasenko39161392017-01-20 20:27:06 +01001057 target = MAX_INBUF;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001058 for (;;) {
Denys Vlasenko39161392017-01-20 20:27:06 +01001059 int rem;
1060
1061 if (total >= RECHDR_LEN && target == MAX_INBUF) {
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001062 xhdr = (void*)tls->inbuf;
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001063 target = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
Denys Vlasenko98066662018-02-06 13:33:00 +01001064
1065 if (target > MAX_INBUF /* malformed input (too long) */
1066 || xhdr->proto_maj != TLS_MAJ
1067 || xhdr->proto_min != TLS_MIN
1068 ) {
1069 sz = total < target ? total : target;
Denys Vlasenko98066662018-02-06 13:33:00 +01001070 bad_record_die(tls, expected, sz);
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001071 }
Denys Vlasenkoe7863f32017-01-20 17:59:25 +01001072 dbg("xhdr type:%d ver:%d.%d len:%d\n",
1073 xhdr->type, xhdr->proto_maj, xhdr->proto_min,
1074 0x100 * xhdr->len16_hi + xhdr->len16_lo
1075 );
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001076 }
1077 /* if total >= target, we have a full packet (and possibly more)... */
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001078 if (total - target >= 0)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001079 break;
Denys Vlasenko39161392017-01-20 20:27:06 +01001080 /* input buffer is grown only as needed */
1081 rem = tls->inbuf_size - total;
1082 if (rem == 0) {
1083 tls->inbuf_size += MAX_INBUF / 8;
1084 if (tls->inbuf_size > MAX_INBUF)
1085 tls->inbuf_size = MAX_INBUF;
1086 dbg("inbuf_size:%d\n", tls->inbuf_size);
1087 rem = tls->inbuf_size - total;
1088 tls->inbuf = xrealloc(tls->inbuf, tls->inbuf_size);
1089 }
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001090 sz = safe_read(tls->ifd, tls->inbuf + total, rem);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001091 if (sz <= 0) {
1092 if (sz == 0 && total == 0) {
1093 /* "Abrupt" EOF, no TLS shutdown (seen from kernel.org) */
1094 dbg("EOF (without TLS shutdown) from peer\n");
Denys Vlasenko39161392017-01-20 20:27:06 +01001095 tls->buffered_size = 0;
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001096 goto end;
1097 }
1098 bb_perror_msg_and_die("short read, have only %d", total);
1099 }
Denys Vlasenkoe7863f32017-01-20 17:59:25 +01001100 dump_raw_in("<< %s\n", tls->inbuf + total, sz);
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01001101 total += sz;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001102 }
Denys Vlasenko39161392017-01-20 20:27:06 +01001103 tls->buffered_size = total - target;
1104 tls->ofs_to_buffered = target;
1105 //dbg("<< stashing at %d [%d] ", tls->ofs_to_buffered, tls->buffered_size);
1106 //dump_hex("<< %s\n", tls->inbuf + tls->ofs_to_buffered, tls->buffered_size);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001107
1108 sz = target - RECHDR_LEN;
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01001109
1110 /* Needs to be decrypted? */
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001111 if (tls->min_encrypted_len_on_read != 0) {
1112 if (sz < (int)tls->min_encrypted_len_on_read)
1113 bb_error_msg_and_die("bad encrypted len:%u", sz);
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01001114
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001115 if (tls->flags & ENCRYPTION_AESGCM) {
1116 /* AESGCM */
1117 uint8_t *p = tls->inbuf + RECHDR_LEN;
1118
1119 sz -= 8 + AES_BLOCK_SIZE; /* we will overwrite nonce, drop hash */
1120 tls_aesgcm_decrypt(tls, p, sz);
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001121 dbg("encrypted size:%u\n", sz);
1122 } else
Denys Vlasenko63bfe0e2018-12-10 16:43:53 +01001123 if (tls->min_encrypted_len_on_read > TLS_MAC_SIZE(tls)) {
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001124 /* AES+SHA */
1125 uint8_t *p = tls->inbuf + RECHDR_LEN;
1126 int padding_len;
1127
1128 if (sz & (AES_BLOCK_SIZE-1))
1129 bb_error_msg_and_die("bad encrypted len:%u", sz);
1130
1131 /* Decrypt content+MAC+padding, moving it over IV in the process */
1132 sz -= AES_BLOCK_SIZE; /* we will overwrite IV now */
1133 aes_cbc_decrypt(
Denys Vlasenko5e4236d2018-11-23 18:02:44 +01001134 &tls->aes_decrypt, /* selects 128/256 */
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001135 p, /* IV */
1136 p + AES_BLOCK_SIZE, sz, /* ciphertext */
1137 p /* plaintext */
1138 );
1139 padding_len = p[sz - 1];
1140 dbg("encrypted size:%u type:0x%02x padding_length:0x%02x\n", sz, p[0], padding_len);
1141 padding_len++;
Denys Vlasenko63bfe0e2018-12-10 16:43:53 +01001142 sz -= TLS_MAC_SIZE(tls) + padding_len; /* drop MAC and padding */
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001143 } else {
1144 /* if nonzero, then it's TLS_RSA_WITH_NULL_SHA256: drop MAC */
1145 /* else: no encryption yet on input, subtract zero = NOP */
1146 sz -= tls->min_encrypted_len_on_read;
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01001147 }
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01001148 }
Denys Vlasenko0af52652017-01-20 21:23:10 +01001149 if (sz < 0)
James Byrne69374872019-07-02 11:35:03 +02001150 bb_simple_error_msg_and_die("encrypted data too short");
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001151
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001152 //dump_hex("<< %s\n", tls->inbuf, RECHDR_LEN + sz);
1153
1154 xhdr = (void*)tls->inbuf;
1155 if (xhdr->type == RECORD_TYPE_ALERT && sz >= 2) {
1156 uint8_t *p = tls->inbuf + RECHDR_LEN;
1157 dbg("ALERT size:%d level:%d description:%d\n", sz, p[0], p[1]);
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001158 if (p[0] == 2) { /* fatal */
1159 bb_error_msg_and_die("TLS %s from peer (alert code %d): %s",
1160 "error",
1161 p[1], alert_text(p[1])
1162 );
1163 }
Denys Vlasenko54b927d2017-01-20 21:19:38 +01001164 if (p[0] == 1) { /* warning */
1165 if (p[1] == 0) { /* "close_notify" warning: it's EOF */
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001166 dbg("EOF (TLS encoded) from peer\n");
1167 sz = 0;
1168 goto end;
1169 }
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001170//This possibly needs to be cached and shown only if
1171//a fatal alert follows
1172// bb_error_msg("TLS %s from peer (alert code %d): %s",
1173// "warning",
1174// p[1], alert_text(p[1])
1175// );
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001176 /* discard it, get next record */
1177 goto again;
1178 }
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001179 /* p[0] not 1 or 2: not defined in protocol */
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001180 sz = 0;
1181 goto end;
1182 }
1183
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001184 /* RFC 5246 is not saying it explicitly, but sha256 hash
Denys Vlasenkofe0588d2017-01-17 17:04:24 +01001185 * in our FINISHED record must include data of incoming packets too!
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001186 */
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001187 if (tls->inbuf[0] == RECORD_TYPE_HANDSHAKE
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001188/* HANDSHAKE HASH: */
1189 // && do_we_know_which_hash_to_use /* server_hello() might not know it in the future! */
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001190 ) {
1191 hash_handshake(tls, "<< hash:%s", tls->inbuf + RECHDR_LEN, sz);
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001192 }
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001193 end:
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01001194 dbg("got block len:%u\n", sz);
1195 return sz;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001196}
1197
Denys Vlasenkode7b5bb2018-11-13 11:44:32 +01001198static void binary_to_pstm(pstm_int *pstm_n, uint8_t *bin_ptr, unsigned len)
1199{
1200 pstm_init_for_read_unsigned_bin(/*pool:*/ NULL, pstm_n, len);
1201 pstm_read_unsigned_bin(pstm_n, bin_ptr, len);
1202 //return bin_ptr + len;
1203}
1204
Denys Vlasenkofe0588d2017-01-17 17:04:24 +01001205/*
1206 * DER parsing routines
1207 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001208static unsigned get_der_len(uint8_t **bodyp, uint8_t *der, uint8_t *end)
1209{
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +01001210 unsigned len, len1;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001211
1212 if (end - der < 2)
1213 xfunc_die();
1214// if ((der[0] & 0x1f) == 0x1f) /* not single-byte item code? */
1215// xfunc_die();
1216
1217 len = der[1]; /* maybe it's short len */
1218 if (len >= 0x80) {
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001219 /* no, it's long */
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +01001220
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001221 if (len == 0x80 || end - der < (int)(len - 0x7e)) {
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001222 /* 0x80 is "0 bytes of len", invalid DER: must use short len if can */
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001223 /* need 3 or 4 bytes for 81, 82 */
1224 xfunc_die();
1225 }
1226
1227 len1 = der[2]; /* if (len == 0x81) it's "ii 81 xx", fetch xx */
1228 if (len > 0x82) {
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001229 /* >0x82 is "3+ bytes of len", should not happen realistically */
1230 xfunc_die();
1231 }
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001232 if (len == 0x82) { /* it's "ii 82 xx yy" */
1233 len1 = 0x100*len1 + der[3];
1234 der += 1; /* skip [yy] */
1235 }
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +01001236 der += 1; /* skip [xx] */
1237 len = len1;
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001238// if (len < 0x80)
1239// xfunc_die(); /* invalid DER: must use short len if can */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001240 }
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +01001241 der += 2; /* skip [code]+[1byte] */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001242
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +01001243 if (end - der < (int)len)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001244 xfunc_die();
1245 *bodyp = der;
1246
1247 return len;
1248}
1249
1250static uint8_t *enter_der_item(uint8_t *der, uint8_t **endp)
1251{
1252 uint8_t *new_der;
1253 unsigned len = get_der_len(&new_der, der, *endp);
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01001254 dbg_der("entered der @%p:0x%02x len:%u inner_byte @%p:0x%02x\n", der, der[0], len, new_der, new_der[0]);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001255 /* Move "end" position to cover only this item */
1256 *endp = new_der + len;
1257 return new_der;
1258}
1259
1260static uint8_t *skip_der_item(uint8_t *der, uint8_t *end)
1261{
1262 uint8_t *new_der;
1263 unsigned len = get_der_len(&new_der, der, end);
1264 /* Skip body */
1265 new_der += len;
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01001266 dbg_der("skipped der 0x%02x, next byte 0x%02x\n", der[0], new_der[0]);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001267 return new_der;
1268}
1269
Denys Vlasenko11d00962017-01-15 00:12:42 +01001270static void der_binary_to_pstm(pstm_int *pstm_n, uint8_t *der, uint8_t *end)
1271{
Denys Vlasenkof78ad092017-01-15 00:18:22 +01001272 uint8_t *bin_ptr;
1273 unsigned len = get_der_len(&bin_ptr, der, end);
Denys Vlasenko11d00962017-01-15 00:12:42 +01001274
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01001275 dbg_der("binary bytes:%u, first:0x%02x\n", len, bin_ptr[0]);
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001276 binary_to_pstm(pstm_n, bin_ptr, len);
Denys Vlasenko11d00962017-01-15 00:12:42 +01001277}
1278
1279static void find_key_in_der_cert(tls_state_t *tls, uint8_t *der, int len)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001280{
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001281/* Certificate is a DER-encoded data structure. Each DER element has a length,
1282 * which makes it easy to skip over large compound elements of any complexity
1283 * without parsing them. Example: partial decode of kernel.org certificate:
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001284 * SEQ 0x05ac/1452 bytes (Certificate): 308205ac
1285 * SEQ 0x0494/1172 bytes (tbsCertificate): 30820494
1286 * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0] 3 bytes: a003
1287 * INTEGER (version): 0201 02
1288 * INTEGER 0x11 bytes (serialNumber): 0211 00 9f85bf664b0cddafca508679501b2be4
1289 * //^^^^^^note: matrixSSL also allows [ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2] = 0x82 type
1290 * SEQ 0x0d bytes (signatureAlgo): 300d
1291 * OID 9 bytes: 0609 2a864886f70d01010b (OID_SHA256_RSA_SIG 42.134.72.134.247.13.1.1.11)
1292 * NULL: 0500
1293 * SEQ 0x5f bytes (issuer): 305f
1294 * SET 11 bytes: 310b
1295 * SEQ 9 bytes: 3009
1296 * OID 3 bytes: 0603 550406
1297 * Printable string "FR": 1302 4652
1298 * SET 14 bytes: 310e
1299 * SEQ 12 bytes: 300c
1300 * OID 3 bytes: 0603 550408
1301 * Printable string "Paris": 1305 5061726973
1302 * SET 14 bytes: 310e
1303 * SEQ 12 bytes: 300c
1304 * OID 3 bytes: 0603 550407
1305 * Printable string "Paris": 1305 5061726973
1306 * SET 14 bytes: 310e
1307 * SEQ 12 bytes: 300c
1308 * OID 3 bytes: 0603 55040a
1309 * Printable string "Gandi": 1305 47616e6469
1310 * SET 32 bytes: 3120
1311 * SEQ 30 bytes: 301e
1312 * OID 3 bytes: 0603 550403
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001313 * Printable string "Gandi Standard SSL CA 2": 1317 47616e6469205374616e646172642053534c2043412032
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001314 * SEQ 30 bytes (validity): 301e
1315 * TIME "161011000000Z": 170d 3136313031313030303030305a
1316 * TIME "191011235959Z": 170d 3139313031313233353935395a
1317 * SEQ 0x5b/91 bytes (subject): 305b //I did not decode this
1318 * 3121301f060355040b1318446f6d61696e20436f
1319 * 6e74726f6c2056616c6964617465643121301f06
1320 * 0355040b1318506f73697469766553534c204d75
1321 * 6c74692d446f6d61696e31133011060355040313
1322 * 0a6b65726e656c2e6f7267
1323 * SEQ 0x01a2/418 bytes (subjectPublicKeyInfo): 308201a2
1324 * SEQ 13 bytes (algorithm): 300d
1325 * OID 9 bytes: 0609 2a864886f70d010101 (OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1)
1326 * NULL: 0500
1327 * BITSTRING 0x018f/399 bytes (publicKey): 0382018f
1328 * ????: 00
1329 * //after the zero byte, it appears key itself uses DER encoding:
1330 * SEQ 0x018a/394 bytes: 3082018a
1331 * INTEGER 0x0181/385 bytes (modulus): 02820181
1332 * 00b1ab2fc727a3bef76780c9349bf3
1333 * ...24 more blocks of 15 bytes each...
1334 * 90e895291c6bc8693b65
1335 * INTEGER 3 bytes (exponent): 0203 010001
1336 * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0x3] 0x01e5 bytes (X509v3 extensions): a38201e5
1337 * SEQ 0x01e1 bytes: 308201e1
1338 * ...
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001339 * Certificate is a sequence of three elements:
1340 * tbsCertificate (SEQ)
1341 * signatureAlgorithm (AlgorithmIdentifier)
1342 * signatureValue (BIT STRING)
1343 *
1344 * In turn, tbsCertificate is a sequence of:
1345 * version
1346 * serialNumber
1347 * signatureAlgo (AlgorithmIdentifier)
1348 * issuer (Name, has complex structure)
1349 * validity (Validity, SEQ of two Times)
1350 * subject (Name)
1351 * subjectPublicKeyInfo (SEQ)
1352 * ...
1353 *
1354 * subjectPublicKeyInfo is a sequence of:
1355 * algorithm (AlgorithmIdentifier)
1356 * publicKey (BIT STRING)
1357 *
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001358 * We need Certificate.tbsCertificate.subjectPublicKeyInfo.publicKey
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001359 *
1360 * Example of an ECDSA key:
1361 * SEQ 0x59 bytes (subjectPublicKeyInfo): 3059
1362 * SEQ 0x13 bytes (algorithm): 3013
1363 * OID 7 bytes: 0607 2a8648ce3d0201 (OID_ECDSA_KEY_ALG 42.134.72.206.61.2.1)
1364 * OID 8 bytes: 0608 2a8648ce3d030107 (OID_EC_prime256v1 42.134.72.206.61.3.1.7)
1365 * BITSTRING 0x42 bytes (publicKey): 0342
1366 * 0004 53af f65e 50cc 7959 7e29 0171 c75c
1367 * 7335 e07d f45b 9750 b797 3a38 aebb 2ac6
1368 * 8329 2748 e77e 41cb d482 2ce6 05ec a058
1369 * f3ab d561 2f4c d845 9ad3 7252 e3de bd3b
1370 * 9012
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001371 */
1372 uint8_t *end = der + len;
1373
1374 /* enter "Certificate" item: [der, end) will be only Cert */
1375 der = enter_der_item(der, &end);
1376
1377 /* enter "tbsCertificate" item: [der, end) will be only tbsCert */
1378 der = enter_der_item(der, &end);
1379
Ivan Abrea5cb4f902018-06-24 20:04:57 +02001380 /*
1381 * Skip version field only if it is present. For a v1 certificate, the
1382 * version field won't be present since v1 is the default value for the
1383 * version field and fields with default values should be omitted (see
1384 * RFC 5280 sections 4.1 and 4.1.2.1). If the version field is present
1385 * it will have a tag class of 2 (context-specific), bit 6 as 1
1386 * (constructed), and a tag number of 0 (see ITU-T X.690 sections 8.1.2
1387 * and 8.14).
1388 */
Denys Vlasenko084bac42018-11-05 00:18:18 +01001389 /* bits 7-6: 10 */
1390 /* bit 5: 1 */
1391 /* bits 4-0: 00000 */
1392 if (der[0] == 0xa0)
Ivan Abrea5cb4f902018-06-24 20:04:57 +02001393 der = skip_der_item(der, end); /* version */
Ivan Abrea5cb4f902018-06-24 20:04:57 +02001394
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001395 /* skip up to subjectPublicKeyInfo */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001396 der = skip_der_item(der, end); /* serialNumber */
1397 der = skip_der_item(der, end); /* signatureAlgo */
1398 der = skip_der_item(der, end); /* issuer */
1399 der = skip_der_item(der, end); /* validity */
1400 der = skip_der_item(der, end); /* subject */
1401
Denys Vlasenko11d00962017-01-15 00:12:42 +01001402 /* enter subjectPublicKeyInfo */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001403 der = enter_der_item(der, &end);
Denys Vlasenko11d00962017-01-15 00:12:42 +01001404 { /* check subjectPublicKeyInfo.algorithm */
Denys Vlasenko84fc6452019-05-21 17:29:24 +02001405 static const uint8_t OID_RSA_KEY_ALG[] ALIGN1 = {
Denys Vlasenko11d00962017-01-15 00:12:42 +01001406 0x30,0x0d, // SEQ 13 bytes
Denys Vlasenkode7b5bb2018-11-13 11:44:32 +01001407 0x06,0x09, 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01, //OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1
Denys Vlasenko11d00962017-01-15 00:12:42 +01001408 //0x05,0x00, // NULL
1409 };
Denys Vlasenko84fc6452019-05-21 17:29:24 +02001410 static const uint8_t OID_ECDSA_KEY_ALG[] ALIGN1 = {
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001411 0x30,0x13, // SEQ 0x13 bytes
1412 0x06,0x07, 0x2a,0x86,0x48,0xce,0x3d,0x02,0x01, //OID_ECDSA_KEY_ALG 42.134.72.206.61.2.1
Denys Vlasenkode7b5bb2018-11-13 11:44:32 +01001413 //allow any curve code for now...
1414 // 0x06,0x08, 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x07, //OID_EC_prime256v1 42.134.72.206.61.3.1.7
1415 //RFC 3279:
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001416 //42.134.72.206.61.3 is ellipticCurve
1417 //42.134.72.206.61.3.0 is c-TwoCurve
1418 //42.134.72.206.61.3.1 is primeCurve
Denys Vlasenkode7b5bb2018-11-13 11:44:32 +01001419 //42.134.72.206.61.3.1.7 is curve_secp256r1
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001420 };
1421 if (memcmp(der, OID_RSA_KEY_ALG, sizeof(OID_RSA_KEY_ALG)) == 0) {
1422 dbg("RSA key\n");
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001423 tls->flags |= GOT_CERT_RSA_KEY_ALG;
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001424 } else
1425 if (memcmp(der, OID_ECDSA_KEY_ALG, sizeof(OID_ECDSA_KEY_ALG)) == 0) {
1426 dbg("ECDSA key\n");
Denys Vlasenkoa33b0082018-11-25 14:28:32 +01001427 //UNUSED: tls->flags |= GOT_CERT_ECDSA_KEY_ALG;
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001428 } else
James Byrne69374872019-07-02 11:35:03 +02001429 bb_simple_error_msg_and_die("not RSA or ECDSA cert");
Denys Vlasenko11d00962017-01-15 00:12:42 +01001430 }
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001431
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001432 if (tls->flags & GOT_CERT_RSA_KEY_ALG) {
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001433 /* parse RSA key: */
1434 //based on getAsnRsaPubKey(), pkcs1ParsePrivBin() is also of note
1435 /* skip subjectPublicKeyInfo.algorithm */
1436 der = skip_der_item(der, end);
1437 /* enter subjectPublicKeyInfo.publicKey */
Denys Vlasenkode7b5bb2018-11-13 11:44:32 +01001438 //die_if_not_this_der_type(der, end, 0x03); /* must be BITSTRING */
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001439 der = enter_der_item(der, &end);
1440
1441 dbg("key bytes:%u, first:0x%02x\n", (int)(end - der), der[0]);
1442 if (end - der < 14)
1443 xfunc_die();
1444 /* example format:
1445 * ignore bits: 00
1446 * SEQ 0x018a/394 bytes: 3082018a
1447 * INTEGER 0x0181/385 bytes (modulus): 02820181 XX...XXX
1448 * INTEGER 3 bytes (exponent): 0203 010001
1449 */
1450 if (*der != 0) /* "ignore bits", should be 0 */
1451 xfunc_die();
1452 der++;
1453 der = enter_der_item(der, &end); /* enter SEQ */
1454 /* memset(tls->hsd->server_rsa_pub_key, 0, sizeof(tls->hsd->server_rsa_pub_key)); - already is */
1455 der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.N, der, end); /* modulus */
1456 der = skip_der_item(der, end);
1457 der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.e, der, end); /* exponent */
1458 tls->hsd->server_rsa_pub_key.size = pstm_unsigned_bin_size(&tls->hsd->server_rsa_pub_key.N);
1459 dbg("server_rsa_pub_key.size:%d\n", tls->hsd->server_rsa_pub_key.size);
1460 }
Denys Vlasenkode7b5bb2018-11-13 11:44:32 +01001461 /* else: ECDSA key. It is not used for generating encryption keys,
1462 * it is used only to sign the EC public key (which comes in ServerKey message).
1463 * Since we do not verify cert validity, verifying signature on EC public key
1464 * wouldn't add any security. Thus, we do nothing here.
1465 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001466}
1467
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001468/*
1469 * TLS Handshake routines
1470 */
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001471static int tls_xread_handshake_block(tls_state_t *tls, int min_len)
Denys Vlasenkofe0588d2017-01-17 17:04:24 +01001472{
1473 struct record_hdr *xhdr;
Denys Vlasenko98066662018-02-06 13:33:00 +01001474 int len = tls_xread_record(tls, "handshake record");
Denys Vlasenkofe0588d2017-01-17 17:04:24 +01001475
1476 xhdr = (void*)tls->inbuf;
1477 if (len < min_len
1478 || xhdr->type != RECORD_TYPE_HANDSHAKE
Denys Vlasenkofe0588d2017-01-17 17:04:24 +01001479 ) {
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001480 bad_record_die(tls, "handshake record", len);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +01001481 }
1482 dbg("got HANDSHAKE\n");
1483 return len;
1484}
1485
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001486static ALWAYS_INLINE void fill_handshake_record_hdr(void *buf, unsigned type, unsigned len)
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001487{
1488 struct handshake_hdr {
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001489 uint8_t type;
1490 uint8_t len24_hi, len24_mid, len24_lo;
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001491 } *h = buf;
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001492
1493 len -= 4;
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001494 h->type = type;
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001495 h->len24_hi = len >> 16;
1496 h->len24_mid = len >> 8;
1497 h->len24_lo = len & 0xff;
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001498}
1499
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001500static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001501{
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001502#define NUM_CIPHERS (0 \
1503 + 4 * ENABLE_FEATURE_TLS_SHA1 \
1504 + ALLOW_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 \
1505 + ALLOW_ECDHE_RSA_WITH_AES_128_CBC_SHA256 \
1506 + ALLOW_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \
1507 + ALLOW_ECDHE_RSA_WITH_AES_128_GCM_SHA256 \
1508 + 2 * ENABLE_FEATURE_TLS_SHA1 \
1509 + ALLOW_RSA_WITH_AES_128_CBC_SHA256 \
1510 + ALLOW_RSA_WITH_AES_256_CBC_SHA256 \
1511 + ALLOW_RSA_WITH_AES_128_GCM_SHA256 \
1512 + ALLOW_RSA_NULL_SHA256 \
1513 )
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001514 static const uint8_t ciphers[] = {
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001515 0x00,2 * (1 + NUM_CIPHERS), //len16_be
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001516 0x00,0xFF, //not a cipher - TLS_EMPTY_RENEGOTIATION_INFO_SCSV
1517 /* ^^^^^^ RFC 5746 Renegotiation Indication Extension - some servers will refuse to work with us otherwise */
Denys Vlasenko71fa5b02018-12-10 16:14:58 +01001518#if ENABLE_FEATURE_TLS_SHA1
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001519 0xC0,0x09, // 1 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA - ok: wget https://is.gd/
1520 0xC0,0x0A, // 2 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA - ok: wget https://is.gd/
1521 0xC0,0x13, // 3 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA
Denys Vlasenko2eb04292018-11-26 16:39:19 +01001522 0xC0,0x14, // 4 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES256-SHA (might fail with older openssl)
Denys Vlasenko3a4d5a72018-12-10 19:19:38 +01001523 // 0xC0,0x18, // TLS_ECDH_anon_WITH_AES_128_CBC_SHA
1524 // 0xC0,0x19, // TLS_ECDH_anon_WITH_AES_256_CBC_SHA
Denys Vlasenko71fa5b02018-12-10 16:14:58 +01001525#endif
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001526#if ALLOW_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
Denys Vlasenko2eb04292018-11-26 16:39:19 +01001527 0xC0,0x23, // 5 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 - ok: wget https://is.gd/
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001528#endif
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001529 // 0xC0,0x24, // TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001530#if ALLOW_ECDHE_RSA_WITH_AES_128_CBC_SHA256
Denys Vlasenko2eb04292018-11-26 16:39:19 +01001531 0xC0,0x27, // 6 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA256
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001532#endif
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001533 // 0xC0,0x28, // TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001534#if ALLOW_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
Denys Vlasenko2eb04292018-11-26 16:39:19 +01001535 0xC0,0x2B, // 7 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - ok: wget https://is.gd/
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001536#endif
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001537 // 0xC0,0x2C, // TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - wget https://is.gd/: "TLS error from peer (alert code 20): bad MAC"
Denys Vlasenkod4681c72018-11-26 10:33:23 +01001538//TODO: GCM_SHA384 ciphers can be supported, only need sha384-based PRF?
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001539#if ALLOW_ECDHE_RSA_WITH_AES_128_GCM_SHA256
Denys Vlasenko2eb04292018-11-26 16:39:19 +01001540 0xC0,0x2F, // 8 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-GCM-SHA256
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001541#endif
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001542 // 0xC0,0x30, // TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher ECDHE-RSA-AES256-GCM-SHA384: "decryption failed or bad record mac"
1543 //possibly these too:
Denys Vlasenko71fa5b02018-12-10 16:14:58 +01001544#if ENABLE_FEATURE_TLS_SHA1
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001545 // 0xC0,0x35, // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
1546 // 0xC0,0x36, // TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA
Denys Vlasenko71fa5b02018-12-10 16:14:58 +01001547#endif
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001548 // 0xC0,0x37, // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
1549 // 0xC0,0x38, // TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
Denys Vlasenko71fa5b02018-12-10 16:14:58 +01001550#if ENABLE_FEATURE_TLS_SHA1
Denys Vlasenko2eb04292018-11-26 16:39:19 +01001551 0x00,0x2F, // 9 TLS_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher AES128-SHA
1552 0x00,0x35, //10 TLS_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher AES256-SHA
Denys Vlasenko71fa5b02018-12-10 16:14:58 +01001553#endif
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001554#if ALLOW_RSA_WITH_AES_128_CBC_SHA256
Denys Vlasenko2eb04292018-11-26 16:39:19 +01001555 0x00,0x3C, //11 TLS_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher AES128-SHA256
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001556#endif
1557#if ALLOW_RSA_WITH_AES_256_CBC_SHA256
Denys Vlasenko2eb04292018-11-26 16:39:19 +01001558 0x00,0x3D, //12 TLS_RSA_WITH_AES_256_CBC_SHA256 - ok: openssl s_server ... -cipher AES256-SHA256
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001559#endif
1560#if ALLOW_RSA_WITH_AES_128_GCM_SHA256
Denys Vlasenko2eb04292018-11-26 16:39:19 +01001561 0x00,0x9C, //13 TLS_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher AES128-GCM-SHA256
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001562#endif
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001563 // 0x00,0x9D, // TLS_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher AES256-GCM-SHA384: "decryption failed or bad record mac"
1564#if ALLOW_RSA_NULL_SHA256
1565 0x00,0x3B, // TLS_RSA_WITH_NULL_SHA256
1566#endif
1567 0x01,0x00, //not a cipher - comprtypes_len, comprtype
1568 };
Denys Vlasenkoc8c1fcd2022-09-08 16:56:54 +02001569 struct client_hello {
1570 uint8_t type;
1571 uint8_t len24_hi, len24_mid, len24_lo;
1572 uint8_t proto_maj, proto_min;
1573 uint8_t rand32[32];
1574 uint8_t session_id_len;
1575 /* uint8_t session_id[]; */
1576 uint8_t cipherid_len16_hi, cipherid_len16_lo;
1577 uint8_t cipherid[2 * (1 + NUM_CIPHERS)]; /* actually variable */
1578 uint8_t comprtypes_len;
1579 uint8_t comprtypes[1]; /* actually variable */
1580 };
Denys Vlasenko9bab5802022-09-08 16:31:44 +02001581 // https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml
1582 static const uint8_t extensions[] = {
1583 // is.gd responds with "handshake failure" to our hello if there's no supported_groups
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001584 0x00,0x0a, //extension_type: "supported_groups"
Denys Vlasenko9bab5802022-09-08 16:31:44 +02001585 0x00,2 * (1 + ALLOW_CURVE_P256 + ALLOW_CURVE_X25519), //ext len
1586 0x00,2 * (0 + ALLOW_CURVE_P256 + ALLOW_CURVE_X25519), //list len
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001587#if ALLOW_CURVE_P256
Denys Vlasenko9bab5802022-09-08 16:31:44 +02001588 0x00,0x17, //curve_secp256r1 (aka P256, aka prime256v1)
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001589#endif
Denys Vlasenko9bab5802022-09-08 16:31:44 +02001590 //0x00,0x18, //curve_secp384r1
1591 //0x00,0x19, //curve_secp521r1
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001592#if ALLOW_CURVE_X25519
Denys Vlasenko9bab5802022-09-08 16:31:44 +02001593 0x00,0x1d, //curve_x25519 (RFC 7748)
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001594#endif
Denys Vlasenko9bab5802022-09-08 16:31:44 +02001595 //0x00,0x1e, //curve_x448 (RFC 7748)
1596
1597 //0x00,0x0b,0x00,0x04,0x03,0x00,0x01,0x02, //extension_type: "ec_point_formats"
1598 //0x00,0x16,0x00,0x00, //extension_type: "encrpypt-then-mac"
1599 //0x00,0x17,0x00,0x00, //extension_type: "extended_master"
1600 //0x00,0x23,0x00,0x00, //extension_type: "session_ticket"
1601
1602 // kojipkgs.fedoraproject.org responds with alert code 80 ("internal error")
1603 // to our hello without signature_algorithms.
1604 // It is satisfied with just 0x04,0x01.
1605 0x00,0x0d, //extension_type: "signature_algorithms" (RFC5246 section 7.4.1.4.1):
1606#define SIGALGS (3 + 3 * ENABLE_FEATURE_TLS_SHA1)
1607 0x00,2 * (1 + SIGALGS), //ext len
1608 0x00,2 * (0 + SIGALGS), //list len
1609 //Format: two bytes
1610 // byte 1: 0:none,1:md5,2:sha1,3:sha224,4:sha256,5:sha384,6:sha512
1611 // byte 2: 1:rsa,2:dsa,3:ecdsa
1612 // (note that TLS 1.3 changes this, see RFC8446 section 4.2.3)
1613#if ENABLE_FEATURE_TLS_SHA1
1614 0x02,0x01, //sha1 + rsa
1615 0x02,0x02, //sha1 + dsa
1616 0x02,0x03, //sha1 + ecdsa
1617#endif
1618 0x04,0x01, //sha256 + rsa - kojipkgs.fedoraproject.org wants this
1619 0x04,0x02, //sha256 + dsa
1620 0x04,0x03, //sha256 + ecdsa
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001621// GNU Wget 1.18 to cdn.kernel.org sends these extensions:
1622// 0055
1623// 0005 0005 0100000000 - status_request
1624// 0000 0013 0011 00 000e 63646e 2e 6b65726e656c 2e 6f7267 - server_name
1625// ff01 0001 00 - renegotiation_info
1626// 0023 0000 - session_ticket
1627// 000a 0008 0006001700180019 - supported_groups
1628// 000b 0002 0100 - ec_point_formats
Denys Vlasenko98066662018-02-06 13:33:00 +01001629// 000d 0016 0014 0401 0403 0501 0503 0601 0603 0301 0303 0201 0203 - signature_algorithms
1630// wolfssl library sends this option, RFC 7627 (closes a security weakness, some servers may require it. TODO?):
1631// 0017 0000 - extended master secret
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001632 };
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001633 struct client_hello *record;
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001634 uint8_t *ptr;
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001635 int len;
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001636 int ext_len;
1637 int sni_len = sni ? strnlen(sni, 127 - 5) : 0;
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001638
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001639 ext_len = 0;
Denys Vlasenko9bab5802022-09-08 16:31:44 +02001640 ext_len += sizeof(extensions);
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001641 if (sni_len)
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001642 ext_len += 9 + sni_len;
1643
1644 /* +2 is for "len of all extensions" 2-byte field */
1645 len = sizeof(*record) + 2 + ext_len;
Denys Vlasenkod5a04052018-11-13 11:58:53 +01001646 record = tls_get_zeroed_outbuf(tls, len);
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001647
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001648 fill_handshake_record_hdr(record, HANDSHAKE_CLIENT_HELLO, len);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001649 record->proto_maj = TLS_MAJ; /* the "requested" version of the protocol, */
1650 record->proto_min = TLS_MIN; /* can be higher than one in record headers */
1651 tls_get_random(record->rand32, sizeof(record->rand32));
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001652 if (TLS_DEBUG_FIXED_SECRETS)
1653 memset(record->rand32, 0x11, sizeof(record->rand32));
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001654 /* record->session_id_len = 0; - already is */
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001655
Denys Vlasenko1f5a44d2021-10-01 14:27:10 +02001656 BUILD_BUG_ON(sizeof(ciphers) != 2 * (1 + 1 + NUM_CIPHERS + 1));
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001657 memcpy(&record->cipherid_len16_hi, ciphers, sizeof(ciphers));
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001658
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001659 ptr = (void*)(record + 1);
1660 *ptr++ = ext_len >> 8;
1661 *ptr++ = ext_len;
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001662 if (sni_len) {
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001663 //ptr[0] = 0; //
1664 //ptr[1] = 0; //extension_type
1665 //ptr[2] = 0; //
1666 ptr[3] = sni_len + 5; //list len
1667 //ptr[4] = 0; //
1668 ptr[5] = sni_len + 3; //len of 1st SNI
1669 //ptr[6] = 0; //name type
1670 //ptr[7] = 0; //
1671 ptr[8] = sni_len; //name len
1672 ptr = mempcpy(&ptr[9], sni, sni_len);
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001673 }
Denys Vlasenko9bab5802022-09-08 16:31:44 +02001674 memcpy(ptr, extensions, sizeof(extensions));
Denys Vlasenko19e695e2017-01-20 14:27:58 +01001675
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001676 tls->hsd = xzalloc(sizeof(*tls->hsd));
1677 /* HANDSHAKE HASH: ^^^ + len if need to save saved_client_hello */
1678 memcpy(tls->hsd->client_and_server_rand32, record->rand32, sizeof(record->rand32));
1679/* HANDSHAKE HASH:
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001680 tls->hsd->saved_client_hello_size = len;
1681 memcpy(tls->hsd->saved_client_hello, record, len);
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001682 */
1683 dbg(">> CLIENT_HELLO\n");
1684 /* Can hash immediately only if we know which MAC hash to use.
1685 * So far we do know: it's sha256:
1686 */
1687 sha256_begin(&tls->hsd->handshake_hash_ctx);
1688 xwrite_and_update_handshake_hash(tls, len);
1689 /* if this would become infeasible: save tls->hsd->saved_client_hello,
1690 * use "xwrite_handshake_record(tls, len)" here,
1691 * and hash saved_client_hello later.
1692 */
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001693}
1694
1695static void get_server_hello(tls_state_t *tls)
1696{
1697 struct server_hello {
1698 struct record_hdr xhdr;
1699 uint8_t type;
1700 uint8_t len24_hi, len24_mid, len24_lo;
1701 uint8_t proto_maj, proto_min;
1702 uint8_t rand32[32]; /* first 4 bytes are unix time in BE format */
1703 uint8_t session_id_len;
1704 uint8_t session_id[32];
1705 uint8_t cipherid_hi, cipherid_lo;
1706 uint8_t comprtype;
1707 /* extensions may follow, but only those which client offered in its Hello */
1708 };
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001709
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001710 struct server_hello *hp;
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001711 uint8_t *cipherid;
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001712 uint8_t cipherid1;
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001713 int len, len24;
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001714
Denys Vlasenko5b05d9d2017-02-03 18:19:59 +01001715 len = tls_xread_handshake_block(tls, 74 - 32);
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001716
1717 hp = (void*)tls->inbuf;
1718 // 74 bytes:
1719 // 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|
1720 //SvHl len=70 maj.min unixtime^^^ 28randbytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^ slen sid32bytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cipSel comprSel
1721 if (hp->type != HANDSHAKE_SERVER_HELLO
1722 || hp->len24_hi != 0
1723 || hp->len24_mid != 0
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001724 /* hp->len24_lo checked later */
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001725 || hp->proto_maj != TLS_MAJ
1726 || hp->proto_min != TLS_MIN
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001727 ) {
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001728 bad_record_die(tls, "'server hello'", len);
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001729 }
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001730
1731 cipherid = &hp->cipherid_hi;
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001732 len24 = hp->len24_lo;
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001733 if (hp->session_id_len != 32) {
1734 if (hp->session_id_len != 0)
Denys Vlasenko5b05d9d2017-02-03 18:19:59 +01001735 bad_record_die(tls, "'server hello'", len);
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001736
1737 // session_id_len == 0: no session id
1738 // "The server
1739 // may return an empty session_id to indicate that the session will
1740 // not be cached and therefore cannot be resumed."
1741 cipherid -= 32;
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001742 len24 += 32; /* what len would be if session id would be present */
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001743 }
1744
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001745 if (len24 < 70)
Denys Vlasenko5b05d9d2017-02-03 18:19:59 +01001746 bad_record_die(tls, "'server hello'", len);
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001747 dbg("<< SERVER_HELLO\n");
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001748
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001749 memcpy(tls->hsd->client_and_server_rand32 + 32, hp->rand32, sizeof(hp->rand32));
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001750
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001751 /* Set up encryption params based on selected cipher */
1752#if 0
1753 0xC0,0x09, // 1 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA - ok: wget https://is.gd/
1754 0xC0,0x0A, // 2 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA - ok: wget https://is.gd/
1755 0xC0,0x13, // 3 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA
Denys Vlasenko2eb04292018-11-26 16:39:19 +01001756 0xC0,0x14, // 4 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES256-SHA (might fail with older openssl)
Denys Vlasenko3a4d5a72018-12-10 19:19:38 +01001757 // 0xC0,0x18, // TLS_ECDH_anon_WITH_AES_128_CBC_SHA
1758 // 0xC0,0x19, // TLS_ECDH_anon_WITH_AES_256_CBC_SHA
Denys Vlasenko2eb04292018-11-26 16:39:19 +01001759 0xC0,0x23, // 5 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 - ok: wget https://is.gd/
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001760 // 0xC0,0x24, // TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
Denys Vlasenko2eb04292018-11-26 16:39:19 +01001761 0xC0,0x27, // 6 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA256
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001762 // 0xC0,0x28, // TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
Denys Vlasenko2eb04292018-11-26 16:39:19 +01001763 0xC0,0x2B, // 7 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - ok: wget https://is.gd/
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001764 // 0xC0,0x2C, // TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - wget https://is.gd/: "TLS error from peer (alert code 20): bad MAC"
Denys Vlasenko2eb04292018-11-26 16:39:19 +01001765 0xC0,0x2F, // 8 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-GCM-SHA256
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001766 // 0xC0,0x30, // TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher ECDHE-RSA-AES256-GCM-SHA384: "decryption failed or bad record mac"
1767 //possibly these too:
1768 // 0xC0,0x35, // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
1769 // 0xC0,0x36, // TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA
1770 // 0xC0,0x37, // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
1771 // 0xC0,0x38, // TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
Denys Vlasenko2eb04292018-11-26 16:39:19 +01001772 0x00,0x2F, // 9 TLS_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher AES128-SHA
1773 0x00,0x35, //10 TLS_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher AES256-SHA
1774 0x00,0x3C, //11 TLS_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher AES128-SHA256
1775 0x00,0x3D, //12 TLS_RSA_WITH_AES_256_CBC_SHA256 - ok: openssl s_server ... -cipher AES256-SHA256
1776 0x00,0x9C, //13 TLS_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher AES128-GCM-SHA256
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001777 // 0x00,0x9D, // TLS_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher AES256-GCM-SHA384: "decryption failed or bad record mac"
1778 0x00,0x3B, // TLS_RSA_WITH_NULL_SHA256
1779#endif
1780 cipherid1 = cipherid[1];
Denys Vlasenko60f78402018-11-26 16:30:22 +01001781 tls->cipher_id = 0x100 * cipherid[0] + cipherid1;
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001782 tls->key_size = AES256_KEYSIZE;
1783 tls->MAC_size = SHA256_OUTSIZE;
1784 /*tls->IV_size = 0; - already is */
1785 if (cipherid[0] == 0xC0) {
1786 /* All C0xx are ECDHE */
1787 tls->flags |= NEED_EC_KEY;
1788 if (cipherid1 & 1) {
1789 /* Odd numbered C0xx use AES128 (even ones use AES256) */
1790 tls->key_size = AES128_KEYSIZE;
1791 }
Denys Vlasenko3a4d5a72018-12-10 19:19:38 +01001792 if (ENABLE_FEATURE_TLS_SHA1 && cipherid1 <= 0x19) {
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001793 tls->MAC_size = SHA1_OUTSIZE;
1794 } else
1795 if (cipherid1 >= 0x2B && cipherid1 <= 0x30) {
1796 /* C02B,2C,2F,30 are AES-GCM */
1797 tls->flags |= ENCRYPTION_AESGCM;
1798 tls->MAC_size = 0;
1799 tls->IV_size = 4;
1800 }
1801 } else {
1802 /* All 00xx are RSA */
Denys Vlasenko71fa5b02018-12-10 16:14:58 +01001803 if ((ENABLE_FEATURE_TLS_SHA1 && cipherid1 == 0x2F)
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001804 || cipherid1 == 0x3C
1805 || cipherid1 == 0x9C
1806 ) {
1807 tls->key_size = AES128_KEYSIZE;
1808 }
Denys Vlasenko71fa5b02018-12-10 16:14:58 +01001809 if (ENABLE_FEATURE_TLS_SHA1 && cipherid1 <= 0x35) {
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001810 tls->MAC_size = SHA1_OUTSIZE;
1811 } else
Denys Vlasenko60f78402018-11-26 16:30:22 +01001812 if (cipherid1 == 0x9C /*|| cipherid1 == 0x9D*/) {
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001813 /* 009C,9D are AES-GCM */
1814 tls->flags |= ENCRYPTION_AESGCM;
1815 tls->MAC_size = 0;
1816 tls->IV_size = 4;
1817 }
1818 }
Denys Vlasenko60f78402018-11-26 16:30:22 +01001819 dbg("server chose cipher %04x\n", tls->cipher_id);
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01001820 dbg("key_size:%u MAC_size:%u IV_size:%u\n", tls->key_size, tls->MAC_size, tls->IV_size);
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001821
Denys Vlasenko89193f92017-01-24 18:08:07 +01001822 /* Handshake hash eventually destined to FINISHED record
1823 * is sha256 regardless of cipher
1824 * (at least for all ciphers defined by RFC5246).
1825 * It's not sha1 for AES_128_CBC_SHA - only MAC is sha1, not this hash.
1826 */
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001827/* HANDSHAKE HASH:
Denys Vlasenko89193f92017-01-24 18:08:07 +01001828 sha256_begin(&tls->hsd->handshake_hash_ctx);
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001829 hash_handshake(tls, ">> client hello hash:%s",
1830 tls->hsd->saved_client_hello, tls->hsd->saved_client_hello_size
1831 );
1832 hash_handshake(tls, "<< server hello hash:%s",
1833 tls->inbuf + RECHDR_LEN, len
1834 );
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001835 */
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001836}
1837
1838static void get_server_cert(tls_state_t *tls)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001839{
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001840 struct record_hdr *xhdr;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001841 uint8_t *certbuf;
1842 int len, len1;
1843
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001844 len = tls_xread_handshake_block(tls, 10);
Denys Vlasenkoc5540d62017-01-15 02:17:03 +01001845
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001846 xhdr = (void*)tls->inbuf;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001847 certbuf = (void*)(xhdr + 1);
1848 if (certbuf[0] != HANDSHAKE_CERTIFICATE)
Denys Vlasenko98066662018-02-06 13:33:00 +01001849 bad_record_die(tls, "certificate", len);
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001850 dbg("<< CERTIFICATE\n");
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001851 // 4392 bytes:
1852 // 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...
1853 //Cert len=4388 ChainLen CertLen^ DER encoded X509 starts here. openssl x509 -in FILE -inform DER -noout -text
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001854 len1 = get24be(certbuf + 1);
1855 if (len1 > len - 4) tls_error_die(tls);
1856 len = len1;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001857 len1 = get24be(certbuf + 4);
1858 if (len1 > len - 3) tls_error_die(tls);
1859 len = len1;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001860 len1 = get24be(certbuf + 7);
1861 if (len1 > len - 3) tls_error_die(tls);
1862 len = len1;
1863
1864 if (len)
Denys Vlasenko11d00962017-01-15 00:12:42 +01001865 find_key_in_der_cert(tls, certbuf + 10, len);
1866}
1867
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001868/* On input, len is known to be >= 4.
1869 * The record is known to be SERVER_KEY_EXCHANGE.
1870 */
1871static void process_server_key(tls_state_t *tls, int len)
1872{
1873 struct record_hdr *xhdr;
1874 uint8_t *keybuf;
1875 int len1;
1876 uint32_t t32;
1877
1878 xhdr = (void*)tls->inbuf;
1879 keybuf = (void*)(xhdr + 1);
1880//seen from is.gd: it selects curve_x25519:
Denys Vlasenko4e46b982018-11-18 19:50:24 +01001881// 0c 00006e //SERVER_KEY_EXCHANGE, len
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001882// 03 //curve_type: named curve
1883// 001d //curve_x25519
1884//server-chosen EC point, and then signed_params
Denys Vlasenko4e46b982018-11-18 19:50:24 +01001885// (RFC 8422: "A hash of the params, with the signature
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001886// appropriate to that hash applied. The private key corresponding
1887// to the certified public key in the server's Certificate message is
1888// used for signing.")
1889//follow. Format unclear/guessed:
1890// 20 //eccPubKeyLen
1891// 25511923d73b70dd2f60e66ba2f3fda31a9c25170963c7a3a972e481dbb2835d //eccPubKey (32bytes)
1892// 0203 //hashSigAlg: 2:SHA1 (4:SHA256 5:SHA384 6:SHA512), 3:ECDSA (1:RSA)
1893// 0046 //len (16bit)
1894// 30 44 //SEQ, len
1895// 02 20 //INTEGER, len
1896// 2e18e7c2a9badd0a70cd3059a6ab114539b9f5163568911147386cd77ed7c412 //32bytes
1897//this item ^^^^^ is sometimes 33 bytes (with all container sizes also +1)
1898// 02 20 //INTEGER, len
1899// 64523d6216cb94c43c9b20e377d8c52c55be6703fd6730a155930c705eaf3af6 //32bytes
1900//same about this item ^^^^^
Denys Vlasenko4e46b982018-11-18 19:50:24 +01001901
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001902//seen from ftp.openbsd.org
Denys Vlasenko4e46b982018-11-18 19:50:24 +01001903//(which only accepts ECDHE-RSA-AESnnn-GCM-SHAnnn and ECDHE-RSA-CHACHA20-POLY1305 ciphers):
1904// 0c 000228 //SERVER_KEY_EXCHANGE, len
1905// 03 //curve_type: named curve
1906// 001d //curve_x25519
1907// 20 //eccPubKeyLen
1908// eef7a15c43b71a4c7eaa48a39369399cc4332e569ec90a83274cc92596705c1a //eccPubKey
1909// 0401 //hashSigAlg: 4:SHA256, 1:RSA
1910// 0200 //len
1911// //0x200 bytes follow
1912
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001913 /* Get and verify length */
1914 len1 = get24be(keybuf + 1);
1915 if (len1 > len - 4) tls_error_die(tls);
1916 len = len1;
1917 if (len < (1+2+1+32)) tls_error_die(tls);
1918 keybuf += 4;
1919
Denys Vlasenkof18a1fd2021-04-26 13:25:56 +02001920#if BB_BIG_ENDIAN
1921# define _0x03001741 0x03001741
1922# define _0x03001d20 0x03001d20
1923#else
1924# define _0x03001741 0x41170003
1925# define _0x03001d20 0x201d0003
1926#endif
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001927 move_from_unaligned32(t32, keybuf);
Denys Vlasenkof18a1fd2021-04-26 13:25:56 +02001928 keybuf += 4;
1929 switch (t32) {
1930 case _0x03001d20: //curve_x25519
Denys Vlasenko446d1362021-11-27 12:03:43 +01001931 dbg("got x25519 eccPubKey\n");
Denys Vlasenkof18a1fd2021-04-26 13:25:56 +02001932 tls->flags |= GOT_EC_CURVE_X25519;
1933 memcpy(tls->hsd->ecc_pub_key32, keybuf, 32);
1934 break;
Denys Vlasenko6b69ab62021-04-26 13:46:36 +02001935 case _0x03001741: //curve_secp256r1 (aka P256)
Denys Vlasenko446d1362021-11-27 12:03:43 +01001936 dbg("got P256 eccPubKey\n");
Denys Vlasenkof18a1fd2021-04-26 13:25:56 +02001937 /* P256 point can be transmitted odd- or even-compressed
1938 * (first byte is 3 or 2) or uncompressed (4).
1939 */
1940 if (*keybuf++ != 4)
1941 bb_simple_error_msg_and_die("compressed EC points not supported");
1942 memcpy(tls->hsd->ecc_pub_key32, keybuf, 2 * 32);
1943 break;
1944 default:
1945 bb_error_msg_and_die("elliptic curve is not x25519 or P256: 0x%08x", t32);
1946 }
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001947
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001948 tls->flags |= GOT_EC_KEY;
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001949}
1950
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01001951static void send_empty_client_cert(tls_state_t *tls)
1952{
1953 struct client_empty_cert {
1954 uint8_t type;
1955 uint8_t len24_hi, len24_mid, len24_lo;
1956 uint8_t cert_chain_len24_hi, cert_chain_len24_mid, cert_chain_len24_lo;
1957 };
1958 struct client_empty_cert *record;
1959
Denys Vlasenkod5a04052018-11-13 11:58:53 +01001960 record = tls_get_zeroed_outbuf(tls, sizeof(*record));
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001961 //fill_handshake_record_hdr(record, HANDSHAKE_CERTIFICATE, sizeof(*record));
1962 //record->cert_chain_len24_hi = 0;
1963 //record->cert_chain_len24_mid = 0;
1964 //record->cert_chain_len24_lo = 0;
Denys Vlasenkode7b5bb2018-11-13 11:44:32 +01001965 // same as above:
Denys Vlasenkod5a04052018-11-13 11:58:53 +01001966 record->type = HANDSHAKE_CERTIFICATE;
1967 record->len24_lo = 3;
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01001968
1969 dbg(">> CERTIFICATE\n");
1970 xwrite_and_update_handshake_hash(tls, sizeof(*record));
1971}
1972
Denys Vlasenko11d00962017-01-15 00:12:42 +01001973static void send_client_key_exchange(tls_state_t *tls)
1974{
Denys Vlasenko11d00962017-01-15 00:12:42 +01001975 struct client_key_exchange {
Denys Vlasenko11d00962017-01-15 00:12:42 +01001976 uint8_t type;
1977 uint8_t len24_hi, len24_mid, len24_lo;
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001978 uint8_t key[2 + 4 * 1024]; // size??
Denys Vlasenko11d00962017-01-15 00:12:42 +01001979 };
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001980//FIXME: better size estimate
Denys Vlasenkod5a04052018-11-13 11:58:53 +01001981 struct client_key_exchange *record = tls_get_zeroed_outbuf(tls, sizeof(*record));
Denys Vlasenkof18a1fd2021-04-26 13:25:56 +02001982 uint8_t premaster[RSA_PREMASTER_SIZE > EC_CURVE_KEYSIZE ? RSA_PREMASTER_SIZE : EC_CURVE_KEYSIZE];
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001983 int premaster_size;
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001984 int len;
Denys Vlasenko11d00962017-01-15 00:12:42 +01001985
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001986 if (!(tls->flags & NEED_EC_KEY)) {
1987 /* RSA */
1988 if (!(tls->flags & GOT_CERT_RSA_KEY_ALG))
Denys Vlasenko934bb012021-10-01 22:03:09 +02001989 bb_simple_error_msg_and_die("server cert is not RSA");
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001990
Denys Vlasenkof18a1fd2021-04-26 13:25:56 +02001991 tls_get_random(premaster, RSA_PREMASTER_SIZE);
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001992 if (TLS_DEBUG_FIXED_SECRETS)
Denys Vlasenkof18a1fd2021-04-26 13:25:56 +02001993 memset(premaster, 0x44, RSA_PREMASTER_SIZE);
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001994 // RFC 5246
1995 // "Note: The version number in the PreMasterSecret is the version
1996 // offered by the client in the ClientHello.client_version, not the
1997 // version negotiated for the connection."
Denys Vlasenkof18a1fd2021-04-26 13:25:56 +02001998 premaster[0] = TLS_MAJ;
1999 premaster[1] = TLS_MIN;
2000 dump_hex("premaster:%s\n", premaster, sizeof(premaster));
Denys Vlasenkobddb6542018-11-13 02:16:24 +01002001 len = psRsaEncryptPub(/*pool:*/ NULL,
2002 /* psRsaKey_t* */ &tls->hsd->server_rsa_pub_key,
Denys Vlasenkof18a1fd2021-04-26 13:25:56 +02002003 premaster, /*inlen:*/ RSA_PREMASTER_SIZE,
Denys Vlasenkobddb6542018-11-13 02:16:24 +01002004 record->key + 2, sizeof(record->key) - 2,
2005 data_param_ignored
2006 );
2007 /* keylen16 exists for RSA (in TLS, not in SSL), but not for some other key types */
2008 record->key[0] = len >> 8;
2009 record->key[1] = len & 0xff;
2010 len += 2;
Denys Vlasenkof18a1fd2021-04-26 13:25:56 +02002011 premaster_size = RSA_PREMASTER_SIZE;
Denys Vlasenkof18a1fd2021-04-26 13:25:56 +02002012 } else {
Denys Vlasenko6b69ab62021-04-26 13:46:36 +02002013 /* ECDHE */
Denys Vlasenkof18a1fd2021-04-26 13:25:56 +02002014 if (!(tls->flags & GOT_EC_KEY))
2015 bb_simple_error_msg_and_die("server did not provide EC key");
2016
Denys Vlasenko6b69ab62021-04-26 13:46:36 +02002017 if (tls->flags & GOT_EC_CURVE_X25519) {
2018 /* ECDHE, curve x25519 */
2019 dbg("computing x25519_premaster\n");
2020 curve_x25519_compute_pubkey_and_premaster(
2021 record->key + 1, premaster,
2022 /*point:*/ tls->hsd->ecc_pub_key32
2023 );
2024 len = CURVE25519_KEYSIZE;
2025 //record->key[0] = len;
2026 //len++;
2027 //premaster_size = CURVE25519_KEYSIZE;
2028 } else {
2029 /* ECDHE, curve P256 */
2030 dbg("computing P256_premaster\n");
2031 curve_P256_compute_pubkey_and_premaster(
2032 record->key + 2, premaster,
2033 /*point:*/ tls->hsd->ecc_pub_key32
2034 );
2035 record->key[1] = 4; /* "uncompressed point" */
2036 len = 1 + P256_KEYSIZE * 2;
2037 }
Denys Vlasenkof18a1fd2021-04-26 13:25:56 +02002038 record->key[0] = len;
Denys Vlasenkof18a1fd2021-04-26 13:25:56 +02002039 len++;
Denys Vlasenko6b69ab62021-04-26 13:46:36 +02002040 premaster_size = P256_KEYSIZE; // = CURVE25519_KEYSIZE = 32
Denys Vlasenkobddb6542018-11-13 02:16:24 +01002041 }
2042
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002043 record->type = HANDSHAKE_CLIENT_KEY_EXCHANGE;
Denys Vlasenkod5a04052018-11-13 11:58:53 +01002044 /* record->len24_hi = 0; - already is */
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002045 record->len24_mid = len >> 8;
2046 record->len24_lo = len & 0xff;
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01002047 len += 4;
Denys Vlasenko11d00962017-01-15 00:12:42 +01002048
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01002049 dbg(">> CLIENT_KEY_EXCHANGE\n");
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002050 xwrite_and_update_handshake_hash(tls, len);
Denys Vlasenko936e83e2017-01-16 04:25:01 +01002051
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01002052 // RFC 5246
2053 // For all key exchange methods, the same algorithm is used to convert
2054 // the pre_master_secret into the master_secret. The pre_master_secret
2055 // should be deleted from memory once the master_secret has been
2056 // computed.
2057 // master_secret = PRF(pre_master_secret, "master secret",
2058 // ClientHello.random + ServerHello.random)
2059 // [0..47];
2060 // The master secret is always exactly 48 bytes in length. The length
2061 // of the premaster secret will vary depending on key exchange method.
Denys Vlasenko89193f92017-01-24 18:08:07 +01002062 prf_hmac_sha256(/*tls,*/
Denys Vlasenko9a647c32017-01-23 01:08:16 +01002063 tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
Denys Vlasenkobddb6542018-11-13 02:16:24 +01002064 premaster, premaster_size,
Denys Vlasenko936e83e2017-01-16 04:25:01 +01002065 "master secret",
Denys Vlasenko9a647c32017-01-23 01:08:16 +01002066 tls->hsd->client_and_server_rand32, sizeof(tls->hsd->client_and_server_rand32)
Denys Vlasenko936e83e2017-01-16 04:25:01 +01002067 );
Denys Vlasenko9a647c32017-01-23 01:08:16 +01002068 dump_hex("master secret:%s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01002069
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01002070 // RFC 5246
2071 // 6.3. Key Calculation
2072 //
2073 // The Record Protocol requires an algorithm to generate keys required
2074 // by the current connection state (see Appendix A.6) from the security
2075 // parameters provided by the handshake protocol.
2076 //
2077 // The master secret is expanded into a sequence of secure bytes, which
2078 // is then split to a client write MAC key, a server write MAC key, a
2079 // client write encryption key, and a server write encryption key. Each
2080 // of these is generated from the byte sequence in that order. Unused
2081 // values are empty. Some AEAD ciphers may additionally require a
2082 // client write IV and a server write IV (see Section 6.2.3.3).
2083 //
2084 // When keys and MAC keys are generated, the master secret is used as an
2085 // entropy source.
2086 //
2087 // To generate the key material, compute
2088 //
2089 // key_block = PRF(SecurityParameters.master_secret,
2090 // "key expansion",
2091 // SecurityParameters.server_random +
2092 // SecurityParameters.client_random);
2093 //
2094 // until enough output has been generated. Then, the key_block is
2095 // partitioned as follows:
2096 //
2097 // client_write_MAC_key[SecurityParameters.mac_key_length]
2098 // server_write_MAC_key[SecurityParameters.mac_key_length]
2099 // client_write_key[SecurityParameters.enc_key_length]
2100 // server_write_key[SecurityParameters.enc_key_length]
2101 // client_write_IV[SecurityParameters.fixed_iv_length]
2102 // server_write_IV[SecurityParameters.fixed_iv_length]
2103 {
2104 uint8_t tmp64[64];
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +01002105
2106 /* make "server_rand32 + client_rand32" */
Denys Vlasenko9a647c32017-01-23 01:08:16 +01002107 memcpy(&tmp64[0] , &tls->hsd->client_and_server_rand32[32], 32);
2108 memcpy(&tmp64[32], &tls->hsd->client_and_server_rand32[0] , 32);
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01002109
Denys Vlasenko89193f92017-01-24 18:08:07 +01002110 prf_hmac_sha256(/*tls,*/
Denys Vlasenko83e5c622018-11-23 17:21:38 +01002111 tls->client_write_MAC_key, 2 * (tls->MAC_size + tls->key_size + tls->IV_size),
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +01002112 // also fills:
Denys Vlasenko49ecee02017-01-24 16:00:54 +01002113 // server_write_MAC_key[]
2114 // client_write_key[]
2115 // server_write_key[]
Denys Vlasenko83e5c622018-11-23 17:21:38 +01002116 // client_write_IV[]
2117 // server_write_IV[]
Denys Vlasenko9a647c32017-01-23 01:08:16 +01002118 tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01002119 "key expansion",
2120 tmp64, 64
2121 );
Denys Vlasenko49ecee02017-01-24 16:00:54 +01002122 tls->client_write_key = tls->client_write_MAC_key + (2 * tls->MAC_size);
2123 tls->server_write_key = tls->client_write_key + tls->key_size;
Denys Vlasenko83e5c622018-11-23 17:21:38 +01002124 tls->client_write_IV = tls->server_write_key + tls->key_size;
2125 tls->server_write_IV = tls->client_write_IV + tls->IV_size;
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01002126 dump_hex("client_write_MAC_key:%s\n",
Denys Vlasenko49ecee02017-01-24 16:00:54 +01002127 tls->client_write_MAC_key, tls->MAC_size
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01002128 );
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +01002129 dump_hex("client_write_key:%s\n",
Denys Vlasenko49ecee02017-01-24 16:00:54 +01002130 tls->client_write_key, tls->key_size
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +01002131 );
Denys Vlasenko83e5c622018-11-23 17:21:38 +01002132 dump_hex("client_write_IV:%s\n",
2133 tls->client_write_IV, tls->IV_size
2134 );
Denys Vlasenko5e4236d2018-11-23 18:02:44 +01002135
Denys Vlasenko83e5c622018-11-23 17:21:38 +01002136 aes_setkey(&tls->aes_decrypt, tls->server_write_key, tls->key_size);
Denys Vlasenko5e4236d2018-11-23 18:02:44 +01002137 aes_setkey(&tls->aes_encrypt, tls->client_write_key, tls->key_size);
2138 {
2139 uint8_t iv[AES_BLOCK_SIZE];
2140 memset(iv, 0, AES_BLOCK_SIZE);
2141 aes_encrypt_one_block(&tls->aes_encrypt, iv, tls->H);
2142 }
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01002143 }
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002144}
2145
Denys Vlasenko84fc6452019-05-21 17:29:24 +02002146static const uint8_t rec_CHANGE_CIPHER_SPEC[] ALIGN1 = {
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01002147 RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
2148 01
2149};
2150
Denys Vlasenkoc5540d62017-01-15 02:17:03 +01002151static void send_change_cipher_spec(tls_state_t *tls)
2152{
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01002153 dbg(">> CHANGE_CIPHER_SPEC\n");
Denys Vlasenko9a647c32017-01-23 01:08:16 +01002154 xwrite(tls->ofd, rec_CHANGE_CIPHER_SPEC, sizeof(rec_CHANGE_CIPHER_SPEC));
Denys Vlasenkoc5540d62017-01-15 02:17:03 +01002155}
2156
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01002157// 7.4.9. Finished
2158// A Finished message is always sent immediately after a change
2159// cipher spec message to verify that the key exchange and
2160// authentication processes were successful. It is essential that a
2161// change cipher spec message be received between the other handshake
2162// messages and the Finished message.
2163//...
2164// The Finished message is the first one protected with the just
2165// negotiated algorithms, keys, and secrets. Recipients of Finished
2166// messages MUST verify that the contents are correct. Once a side
2167// has sent its Finished message and received and validated the
2168// Finished message from its peer, it may begin to send and receive
2169// application data over the connection.
2170//...
2171// struct {
2172// opaque verify_data[verify_data_length];
2173// } Finished;
2174//
2175// verify_data
2176// PRF(master_secret, finished_label, Hash(handshake_messages))
2177// [0..verify_data_length-1];
2178//
2179// finished_label
2180// For Finished messages sent by the client, the string
2181// "client finished". For Finished messages sent by the server,
2182// the string "server finished".
2183//
2184// Hash denotes a Hash of the handshake messages. For the PRF
2185// defined in Section 5, the Hash MUST be the Hash used as the basis
2186// for the PRF. Any cipher suite which defines a different PRF MUST
2187// also define the Hash to use in the Finished computation.
2188//
2189// In previous versions of TLS, the verify_data was always 12 octets
2190// long. In the current version of TLS, it depends on the cipher
2191// suite. Any cipher suite which does not explicitly specify
2192// verify_data_length has a verify_data_length equal to 12. This
2193// includes all existing cipher suites.
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01002194static void send_client_finished(tls_state_t *tls)
2195{
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01002196 struct finished {
Denys Vlasenko936e83e2017-01-16 04:25:01 +01002197 uint8_t type;
2198 uint8_t len24_hi, len24_mid, len24_lo;
2199 uint8_t prf_result[12];
2200 };
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002201 struct finished *record = tls_get_outbuf(tls, sizeof(*record));
Denys Vlasenko49ecee02017-01-24 16:00:54 +01002202 uint8_t handshake_hash[TLS_MAX_MAC_SIZE];
2203 unsigned len;
Denys Vlasenko936e83e2017-01-16 04:25:01 +01002204
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002205 fill_handshake_record_hdr(record, HANDSHAKE_FINISHED, sizeof(*record));
Denys Vlasenko936e83e2017-01-16 04:25:01 +01002206
Denys Vlasenkoeb53d012018-11-25 14:45:55 +01002207 len = sha_end(&tls->hsd->handshake_hash_ctx, handshake_hash);
2208
Denys Vlasenko89193f92017-01-24 18:08:07 +01002209 prf_hmac_sha256(/*tls,*/
Denys Vlasenko49ecee02017-01-24 16:00:54 +01002210 record->prf_result, sizeof(record->prf_result),
2211 tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
2212 "client finished",
2213 handshake_hash, len
Denys Vlasenko936e83e2017-01-16 04:25:01 +01002214 );
Denys Vlasenko9a647c32017-01-23 01:08:16 +01002215 dump_hex("from secret: %s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01002216 dump_hex("from labelSeed: %s", "client finished", sizeof("client finished")-1);
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01002217 dump_hex("%s\n", handshake_hash, sizeof(handshake_hash));
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002218 dump_hex("=> digest: %s\n", record->prf_result, sizeof(record->prf_result));
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01002219
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01002220 dbg(">> FINISHED\n");
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002221 xwrite_encrypted(tls, sizeof(*record), RECORD_TYPE_HANDSHAKE);
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01002222}
2223
Denys Vlasenko9a647c32017-01-23 01:08:16 +01002224void FAST_FUNC tls_handshake(tls_state_t *tls, const char *sni)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002225{
2226 // Client RFC 5246 Server
2227 // (*) - optional messages, not always sent
2228 //
2229 // ClientHello ------->
2230 // ServerHello
2231 // Certificate*
2232 // ServerKeyExchange*
2233 // CertificateRequest*
2234 // <------- ServerHelloDone
2235 // Certificate*
2236 // ClientKeyExchange
2237 // CertificateVerify*
2238 // [ChangeCipherSpec]
2239 // Finished ------->
2240 // [ChangeCipherSpec]
2241 // <------- Finished
2242 // Application Data <------> Application Data
2243 int len;
Denys Vlasenko98066662018-02-06 13:33:00 +01002244 int got_cert_req;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002245
Denys Vlasenko49ecee02017-01-24 16:00:54 +01002246 send_client_hello_and_alloc_hsd(tls, sni);
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01002247 get_server_hello(tls);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002248
Denys Vlasenko38972a82017-01-20 19:11:14 +01002249 // RFC 5246
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002250 // The server MUST send a Certificate message whenever the agreed-
2251 // upon key exchange method uses certificates for authentication
2252 // (this includes all key exchange methods defined in this document
2253 // except DH_anon). This message will always immediately follow the
2254 // ServerHello message.
2255 //
2256 // IOW: in practice, Certificate *always* follows.
2257 // (for example, kernel.org does not even accept DH_anon cipher id)
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01002258 get_server_cert(tls);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002259
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01002260 len = tls_xread_handshake_block(tls, 4);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01002261 if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_SERVER_KEY_EXCHANGE) {
Denys Vlasenkob1003f72017-01-14 13:57:16 +01002262 // 459 bytes:
2263 // 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...
2264 //SvKey len=455^
Denys Vlasenko11d00962017-01-15 00:12:42 +01002265 // with TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 461 bytes:
2266 // 0c 00|01|c9 03|00|17|41|04|cd|9b|b4|29|1f|f6|b0|c2|84|82|7f|29|6a|47|4e|ec|87|0b|c1|9c|69|e1|f8|c6|d0|53|e9|27|90|a5|c8|02|15|75...
Denys Vlasenkobddb6542018-11-13 02:16:24 +01002267 //
2268 // RFC 8422 5.4. Server Key Exchange
2269 // This message is sent when using the ECDHE_ECDSA, ECDHE_RSA, and
2270 // ECDH_anon key exchange algorithms.
2271 // This message is used to convey the server's ephemeral ECDH public key
2272 // (and the corresponding elliptic curve domain parameters) to the
2273 // client.
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01002274 dbg("<< SERVER_KEY_EXCHANGE len:%u\n", len);
Denys Vlasenkobddb6542018-11-13 02:16:24 +01002275 dump_raw_in("<< %s\n", tls->inbuf, RECHDR_LEN + len);
Denys Vlasenko83e5c622018-11-23 17:21:38 +01002276 if (tls->flags & NEED_EC_KEY)
Denys Vlasenkobddb6542018-11-13 02:16:24 +01002277 process_server_key(tls, len);
2278
2279 // read next handshake block
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01002280 len = tls_xread_handshake_block(tls, 4);
Denys Vlasenkoc5540d62017-01-15 02:17:03 +01002281 }
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01002282
Denys Vlasenko98066662018-02-06 13:33:00 +01002283 got_cert_req = (tls->inbuf[RECHDR_LEN] == HANDSHAKE_CERTIFICATE_REQUEST);
2284 if (got_cert_req) {
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01002285 dbg("<< CERTIFICATE_REQUEST\n");
2286 // RFC 5246: "If no suitable certificate is available,
2287 // the client MUST send a certificate message containing no
2288 // certificates. That is, the certificate_list structure has a
2289 // length of zero. ...
2290 // Client certificates are sent using the Certificate structure
2291 // defined in Section 7.4.2."
2292 // (i.e. the same format as server certs)
Denys Vlasenko98066662018-02-06 13:33:00 +01002293
2294 /*send_empty_client_cert(tls); - WRONG (breaks handshake hash calc) */
2295 /* need to hash _all_ server replies first, up to ServerHelloDone */
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01002296 len = tls_xread_handshake_block(tls, 4);
2297 }
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01002298
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01002299 if (tls->inbuf[RECHDR_LEN] != HANDSHAKE_SERVER_HELLO_DONE) {
2300 bad_record_die(tls, "'server hello done'", len);
2301 }
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01002302 // 0e 000000 (len:0)
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01002303 dbg("<< SERVER_HELLO_DONE\n");
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01002304
Denys Vlasenko98066662018-02-06 13:33:00 +01002305 if (got_cert_req)
2306 send_empty_client_cert(tls);
2307
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01002308 send_client_key_exchange(tls);
2309
2310 send_change_cipher_spec(tls);
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01002311 /* from now on we should send encrypted */
2312 /* tls->write_seq64_be = 0; - already is */
Denys Vlasenkoeb53d012018-11-25 14:45:55 +01002313 tls->flags |= ENCRYPT_ON_WRITE;
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01002314
2315 send_client_finished(tls);
2316
2317 /* Get CHANGE_CIPHER_SPEC */
Denys Vlasenko98066662018-02-06 13:33:00 +01002318 len = tls_xread_record(tls, "switch to encrypted traffic");
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01002319 if (len != 1 || memcmp(tls->inbuf, rec_CHANGE_CIPHER_SPEC, 6) != 0)
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01002320 bad_record_die(tls, "switch to encrypted traffic", len);
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01002321 dbg("<< CHANGE_CIPHER_SPEC\n");
Denys Vlasenko83e5c622018-11-23 17:21:38 +01002322
Denys Vlasenkoca7cdd42018-11-26 00:17:10 +01002323 if (ALLOW_RSA_NULL_SHA256
Denys Vlasenko5d561ef2017-04-04 01:41:15 +02002324 && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
2325 ) {
Denys Vlasenko49ecee02017-01-24 16:00:54 +01002326 tls->min_encrypted_len_on_read = tls->MAC_size;
Denys Vlasenko83e5c622018-11-23 17:21:38 +01002327 } else
2328 if (!(tls->flags & ENCRYPTION_AESGCM)) {
Denys Vlasenko63bfe0e2018-12-10 16:43:53 +01002329 unsigned mac_blocks = (unsigned)(TLS_MAC_SIZE(tls) + AES_BLOCK_SIZE-1) / AES_BLOCK_SIZE;
Denys Vlasenko89193f92017-01-24 18:08:07 +01002330 /* all incoming packets now should be encrypted and have
2331 * at least IV + (MAC padded to blocksize):
2332 */
Denys Vlasenko83e5c622018-11-23 17:21:38 +01002333 tls->min_encrypted_len_on_read = AES_BLOCK_SIZE + (mac_blocks * AES_BLOCK_SIZE);
2334 } else {
2335 tls->min_encrypted_len_on_read = 8 + AES_BLOCK_SIZE;
Denys Vlasenko89193f92017-01-24 18:08:07 +01002336 }
Denys Vlasenko83e5c622018-11-23 17:21:38 +01002337 dbg("min_encrypted_len_on_read: %u\n", tls->min_encrypted_len_on_read);
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01002338
2339 /* Get (encrypted) FINISHED from the server */
Denys Vlasenko98066662018-02-06 13:33:00 +01002340 len = tls_xread_record(tls, "'server finished'");
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01002341 if (len < 4 || tls->inbuf[RECHDR_LEN] != HANDSHAKE_FINISHED)
Denys Vlasenko98066662018-02-06 13:33:00 +01002342 bad_record_die(tls, "'server finished'", len);
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01002343 dbg("<< FINISHED\n");
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01002344 /* application data can be sent/received */
Denys Vlasenko9a647c32017-01-23 01:08:16 +01002345
2346 /* free handshake data */
Denys Vlasenkoa6192f32018-11-25 16:17:26 +01002347 psRsaKey_clear(&tls->hsd->server_rsa_pub_key);
Denys Vlasenko9a647c32017-01-23 01:08:16 +01002348// if (PARANOIA)
Denys Vlasenko49ecee02017-01-24 16:00:54 +01002349// memset(tls->hsd, 0, tls->hsd->hsd_size);
Denys Vlasenko9a647c32017-01-23 01:08:16 +01002350 free(tls->hsd);
2351 tls->hsd = NULL;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002352}
2353
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002354static void tls_xwrite(tls_state_t *tls, int len)
2355{
2356 dbg(">> DATA\n");
2357 xwrite_encrypted(tls, len, RECORD_TYPE_APPLICATION_DATA);
2358}
2359
Denys Vlasenko936e83e2017-01-16 04:25:01 +01002360// To run a test server using openssl:
Denys Vlasenko936e83e2017-01-16 04:25:01 +01002361// openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
Denys Vlasenko2eb04292018-11-26 16:39:19 +01002362// openssl s_server -key key.pem -cert server.pem -debug -tls1_2
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01002363//
2364// Unencryped SHA256 example:
2365// openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
Denys Vlasenko2eb04292018-11-26 16:39:19 +01002366// openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -cipher NULL
2367// openssl s_client -connect 127.0.0.1:4433 -debug -tls1_2 -cipher NULL-SHA256
Denys Vlasenko936e83e2017-01-16 04:25:01 +01002368
Denys Vlasenko403f2992018-02-06 15:15:08 +01002369void FAST_FUNC tls_run_copy_loop(tls_state_t *tls, unsigned flags)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002370{
Denys Vlasenko38972a82017-01-20 19:11:14 +01002371 int inbuf_size;
2372 const int INBUF_STEP = 4 * 1024;
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01002373 struct pollfd pfds[2];
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002374
Denys Vlasenko55578f22021-10-05 19:45:56 +02002375#if 0
2376// Debug aid for comparing P256 implementations.
2377// Enable this, set SP_DEBUG and FIXED_SECRET to 1,
2378// and add
2379// tls_run_copy_loop(NULL, 0);
2380// e.g. at the very beginning of wget_main()
2381//
2382{
Denys Vlasenko55578f22021-10-05 19:45:56 +02002383 uint8_t ecc_pub_key32[2 * 32];
2384 uint8_t pubkey2x32[2 * 32];
2385 uint8_t premaster32[32];
2386
2387//Fixed input key:
2388// memset(ecc_pub_key32, 0xee, sizeof(ecc_pub_key32));
2389//Fixed 000000000000000000000000000000000000ab000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
2390// memset(ecc_pub_key32, 0x00, sizeof(ecc_pub_key32));
2391// ecc_pub_key32[18] = 0xab;
2392//Random key:
Denys Vlasenko3b411eb2021-10-05 20:00:50 +02002393// tls_get_random(ecc_pub_key32, sizeof(ecc_pub_key32));
Denys Vlasenko55578f22021-10-05 19:45:56 +02002394//Biased random (almost all zeros or almost all ones):
Denys Vlasenko3b411eb2021-10-05 20:00:50 +02002395 srand(time(NULL) ^ getpid());
2396 if (rand() & 1)
2397 memset(ecc_pub_key32, 0x00, sizeof(ecc_pub_key32));
2398 else
2399 memset(ecc_pub_key32, 0xff, sizeof(ecc_pub_key32));
2400 ecc_pub_key32[rand() & 0x3f] = rand();
Denys Vlasenko55578f22021-10-05 19:45:56 +02002401
2402 xmove_fd(xopen("p256.OLD", O_WRONLY | O_CREAT | O_TRUNC), 2);
2403 curve_P256_compute_pubkey_and_premaster(
2404 pubkey2x32, premaster32,
2405 /*point:*/ ecc_pub_key32
2406 );
2407 xmove_fd(xopen("p256.NEW", O_WRONLY | O_CREAT | O_TRUNC), 2);
2408 curve_P256_compute_pubkey_and_premaster_NEW(
2409 pubkey2x32, premaster32,
2410 /*point:*/ ecc_pub_key32
2411 );
2412 exit(1);
2413}
2414#endif
2415
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01002416 pfds[0].fd = STDIN_FILENO;
2417 pfds[0].events = POLLIN;
2418 pfds[1].fd = tls->ifd;
2419 pfds[1].events = POLLIN;
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002420
Denys Vlasenko38972a82017-01-20 19:11:14 +01002421 inbuf_size = INBUF_STEP;
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002422 for (;;) {
2423 int nread;
2424
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01002425 if (safe_poll(pfds, 2, -1) < 0)
James Byrne69374872019-07-02 11:35:03 +02002426 bb_simple_perror_msg_and_die("poll");
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002427
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01002428 if (pfds[0].revents) {
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01002429 void *buf;
2430
2431 dbg("STDIN HAS DATA\n");
Denys Vlasenko38972a82017-01-20 19:11:14 +01002432 buf = tls_get_outbuf(tls, inbuf_size);
2433 nread = safe_read(STDIN_FILENO, buf, inbuf_size);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002434 if (nread < 1) {
Denys Vlasenko38972a82017-01-20 19:11:14 +01002435 /* We'd want to do this: */
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002436 /* Close outgoing half-connection so they get EOF,
Denys Vlasenko38972a82017-01-20 19:11:14 +01002437 * but leave incoming alone so we can see response
2438 */
Denys Vlasenko9a647c32017-01-23 01:08:16 +01002439 //shutdown(tls->ofd, SHUT_WR);
Denys Vlasenko38972a82017-01-20 19:11:14 +01002440 /* But TLS has no way to encode this,
2441 * doubt it's ok to do it "raw"
2442 */
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01002443 pfds[0].fd = -1;
Denys Vlasenko39161392017-01-20 20:27:06 +01002444 tls_free_outbuf(tls); /* mem usage optimization */
Denys Vlasenko403f2992018-02-06 15:15:08 +01002445 if (flags & TLSLOOP_EXIT_ON_LOCAL_EOF)
2446 break;
Denys Vlasenko38972a82017-01-20 19:11:14 +01002447 } else {
2448 if (nread == inbuf_size) {
2449 /* TLS has per record overhead, if input comes fast,
2450 * read, encrypt and send bigger chunks
2451 */
2452 inbuf_size += INBUF_STEP;
Denys Vlasenko49ecee02017-01-24 16:00:54 +01002453 if (inbuf_size > TLS_MAX_OUTBUF)
2454 inbuf_size = TLS_MAX_OUTBUF;
Denys Vlasenko38972a82017-01-20 19:11:14 +01002455 }
2456 tls_xwrite(tls, nread);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002457 }
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002458 }
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01002459 if (pfds[1].revents) {
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01002460 dbg("NETWORK HAS DATA\n");
Denys Vlasenko38972a82017-01-20 19:11:14 +01002461 read_record:
Denys Vlasenko98066662018-02-06 13:33:00 +01002462 nread = tls_xread_record(tls, "encrypted data");
Denys Vlasenko38972a82017-01-20 19:11:14 +01002463 if (nread < 1) {
2464 /* TLS protocol has no real concept of one-sided shutdowns:
2465 * if we get "TLS EOF" from the peer, writes will fail too
2466 */
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01002467 //pfds[1].fd = -1;
Denys Vlasenko38972a82017-01-20 19:11:14 +01002468 //close(STDOUT_FILENO);
Denys Vlasenko39161392017-01-20 20:27:06 +01002469 //tls_free_inbuf(tls); /* mem usage optimization */
Denys Vlasenko38972a82017-01-20 19:11:14 +01002470 //continue;
2471 break;
2472 }
2473 if (tls->inbuf[0] != RECORD_TYPE_APPLICATION_DATA)
Denys Vlasenko98066662018-02-06 13:33:00 +01002474 bad_record_die(tls, "encrypted data", nread);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01002475 xwrite(STDOUT_FILENO, tls->inbuf + RECHDR_LEN, nread);
Denys Vlasenko38972a82017-01-20 19:11:14 +01002476 /* We may already have a complete next record buffered,
2477 * can process it without network reads (and possible blocking)
2478 */
2479 if (tls_has_buffered_record(tls))
2480 goto read_record;
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002481 }
2482 }
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002483}