blob: f337bc0c9c7e0ac07d233b8df6e3168081128d21 [file] [log] [blame]
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001/*
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002 * Copyright (C) 2017 Denys Vlasenko
Denys Vlasenko11d00962017-01-15 00:12:42 +01003 *
4 * Licensed under GPLv2, see file LICENSE in this source tree.
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01005 */
6//config:config TLS
Denys Vlasenko9a647c32017-01-23 01:08:16 +01007//config: bool #No description makes it a hidden option
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01008//config: default n
9
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010010//kbuild:lib-$(CONFIG_TLS) += tls.o
Denys Vlasenko11d00962017-01-15 00:12:42 +010011//kbuild:lib-$(CONFIG_TLS) += tls_pstm.o
12//kbuild:lib-$(CONFIG_TLS) += tls_pstm_montgomery_reduce.o
13//kbuild:lib-$(CONFIG_TLS) += tls_pstm_mul_comba.o
14//kbuild:lib-$(CONFIG_TLS) += tls_pstm_sqr_comba.o
Denys Vlasenkob7e9ae62017-01-18 17:20:27 +010015//kbuild:lib-$(CONFIG_TLS) += tls_aes.o
Denys Vlasenko83e5c622018-11-23 17:21:38 +010016//kbuild:lib-$(CONFIG_TLS) += tls_aesgcm.o
Denys Vlasenkobddb6542018-11-13 02:16:24 +010017//kbuild:lib-$(CONFIG_TLS) += tls_rsa.o
18//kbuild:lib-$(CONFIG_TLS) += tls_fe.o
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010019
Denys Vlasenko11d00962017-01-15 00:12:42 +010020#include "tls.h"
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010021
Denys Vlasenko49ecee02017-01-24 16:00:54 +010022//TLS 1.2
23#define TLS_MAJ 3
24#define TLS_MIN 3
Denys Vlasenko83e5c622018-11-23 17:21:38 +010025
26//Tested against kernel.org:
Denys Vlasenko49ecee02017-01-24 16:00:54 +010027//#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA // ok, recvs SERVER_KEY_EXCHANGE *** matrixssl uses this on my box
28//#define CIPHER_ID TLS_RSA_WITH_AES_256_CBC_SHA256 // ok, no SERVER_KEY_EXCHANGE
29//#define CIPHER_ID TLS_DH_anon_WITH_AES_256_CBC_SHA // SSL_ALERT_HANDSHAKE_FAILURE
30//^^^^^^^^^^^^^^^^^^^^^^^ (tested b/c this one doesn't req server certs... no luck, server refuses it)
31//#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 // SSL_ALERT_HANDSHAKE_FAILURE
32//#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
33//#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 // ok, recvs SERVER_KEY_EXCHANGE
34//#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
35//#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
36//#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
37//#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
38//#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
39//#define CIPHER_ID TLS_RSA_WITH_AES_256_GCM_SHA384 // ok, no SERVER_KEY_EXCHANGE
Denys Vlasenko83e5c622018-11-23 17:21:38 +010040//#define CIPHER_ID TLS_RSA_WITH_AES_128_GCM_SHA256 // ok, no SERVER_KEY_EXCHANGE
Denys Vlasenko49ecee02017-01-24 16:00:54 +010041
42// works against "openssl s_server -cipher NULL"
43// and against wolfssl-3.9.10-stable/examples/server/server.c:
Denys Vlasenko5d561ef2017-04-04 01:41:15 +020044//#define CIPHER_ID1 TLS_RSA_WITH_NULL_SHA256 // for testing (does everything except encrypting)
Denys Vlasenko49ecee02017-01-24 16:00:54 +010045
46// works against wolfssl-3.9.10-stable/examples/server/server.c
47// works for kernel.org
48// does not work for cdn.kernel.org (e.g. downloading an actual tarball, not a web page)
49// getting alert 40 "handshake failure" at once
50// with GNU Wget 1.18, they agree on TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xC02F) cipher
51// fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES256-SHA256
52// fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES256-GCM-SHA384
53// fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES128-SHA256
54// ok: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES128-GCM-SHA256
55// ok: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher AES128-SHA
56// (TLS_RSA_WITH_AES_128_CBC_SHA - in TLS 1.2 it's mandated to be always supported)
57#define CIPHER_ID1 TLS_RSA_WITH_AES_256_CBC_SHA256 // no SERVER_KEY_EXCHANGE from peer
Denys Vlasenko89193f92017-01-24 18:08:07 +010058// Works with "wget https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.9.5.tar.xz"
59#define CIPHER_ID2 TLS_RSA_WITH_AES_128_CBC_SHA
Denys Vlasenko49ecee02017-01-24 16:00:54 +010060
Denys Vlasenkod2923b32018-11-24 21:26:20 +010061// bug #11456:
Denys Vlasenko83e5c622018-11-23 17:21:38 +010062// ftp.openbsd.org only supports ECDHE-RSA-AESnnn-GCM-SHAnnn or ECDHE-RSA-CHACHA20-POLY1305
Denys Vlasenkod2923b32018-11-24 21:26:20 +010063#define CIPHER_ID3 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
64// host is.gd accepts only ECDHE-ECDSA-foo (the simplest which works: ECDHE-ECDSA-AES128-SHA 0xC009),
65// and immediately throws alert 40 "handshake failure" in response to our hello record
66// if ECDHE-ECDSA-AES-CBC-SHA is *before* ECDHE-RSA-AES-GCM cipher in the list! Server bug?
67#define CIPHER_ID4 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
Denys Vlasenko83e5c622018-11-23 17:21:38 +010068
69#define NUM_CIPHERS 4
70
Denys Vlasenko49ecee02017-01-24 16:00:54 +010071
Denys Vlasenko89193f92017-01-24 18:08:07 +010072#define TLS_DEBUG 0
73#define TLS_DEBUG_HASH 0
74#define TLS_DEBUG_DER 0
75#define TLS_DEBUG_FIXED_SECRETS 0
Denys Vlasenkob5bf1912017-01-23 16:12:17 +010076#if 0
77# define dump_raw_out(...) dump_hex(__VA_ARGS__)
78#else
79# define dump_raw_out(...) ((void)0)
80#endif
81#if 0
82# define dump_raw_in(...) dump_hex(__VA_ARGS__)
83#else
84# define dump_raw_in(...) ((void)0)
85#endif
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +010086
87#if TLS_DEBUG
Denys Vlasenkoceff6b02017-01-14 12:49:32 +010088# define dbg(...) fprintf(stderr, __VA_ARGS__)
89#else
90# define dbg(...) ((void)0)
91#endif
92
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +010093#if TLS_DEBUG_DER
94# define dbg_der(...) fprintf(stderr, __VA_ARGS__)
95#else
96# define dbg_der(...) ((void)0)
97#endif
98
Denys Vlasenko98066662018-02-06 13:33:00 +010099#define RECORD_TYPE_CHANGE_CIPHER_SPEC 20 /* 0x14 */
100#define RECORD_TYPE_ALERT 21 /* 0x15 */
101#define RECORD_TYPE_HANDSHAKE 22 /* 0x16 */
102#define RECORD_TYPE_APPLICATION_DATA 23 /* 0x17 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100103
Denys Vlasenko98066662018-02-06 13:33:00 +0100104#define HANDSHAKE_HELLO_REQUEST 0 /* 0x00 */
105#define HANDSHAKE_CLIENT_HELLO 1 /* 0x01 */
106#define HANDSHAKE_SERVER_HELLO 2 /* 0x02 */
107#define HANDSHAKE_HELLO_VERIFY_REQUEST 3 /* 0x03 */
108#define HANDSHAKE_NEW_SESSION_TICKET 4 /* 0x04 */
109#define HANDSHAKE_CERTIFICATE 11 /* 0x0b */
110#define HANDSHAKE_SERVER_KEY_EXCHANGE 12 /* 0x0c */
111#define HANDSHAKE_CERTIFICATE_REQUEST 13 /* 0x0d */
112#define HANDSHAKE_SERVER_HELLO_DONE 14 /* 0x0e */
113#define HANDSHAKE_CERTIFICATE_VERIFY 15 /* 0x0f */
114#define HANDSHAKE_CLIENT_KEY_EXCHANGE 16 /* 0x10 */
115#define HANDSHAKE_FINISHED 20 /* 0x14 */
Denys Vlasenko11d00962017-01-15 00:12:42 +0100116
Denys Vlasenko5df3b122018-11-04 21:25:41 +0100117#define TLS_EMPTY_RENEGOTIATION_INFO_SCSV 0x00FF /* not a real cipher id... */
118
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100119#define SSL_NULL_WITH_NULL_NULL 0x0000
120#define SSL_RSA_WITH_NULL_MD5 0x0001
121#define SSL_RSA_WITH_NULL_SHA 0x0002
122#define SSL_RSA_WITH_RC4_128_MD5 0x0004
123#define SSL_RSA_WITH_RC4_128_SHA 0x0005
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100124#define TLS_RSA_WITH_IDEA_CBC_SHA 0x0007 /* 7 */
Denys Vlasenko5df3b122018-11-04 21:25:41 +0100125#define SSL_RSA_WITH_3DES_EDE_CBC_SHA 0x000A /* 10 */
126
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100127#define SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA 0x0016 /* 22 */
128#define SSL_DH_anon_WITH_RC4_128_MD5 0x0018 /* 24 */
129#define SSL_DH_anon_WITH_3DES_EDE_CBC_SHA 0x001B /* 27 */
Denys Vlasenko5df3b122018-11-04 21:25:41 +0100130#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 +0100131#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA 0x0033 /* 51 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100132#define TLS_DH_anon_WITH_AES_128_CBC_SHA 0x0034 /* 52 */
Denys Vlasenko5df3b122018-11-04 21:25:41 +0100133#define TLS_RSA_WITH_AES_256_CBC_SHA 0x0035 /* 53 */
134#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA 0x0039 /* 57 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100135#define TLS_DH_anon_WITH_AES_256_CBC_SHA 0x003A /* 58 */
Denys Vlasenko5df3b122018-11-04 21:25:41 +0100136#define TLS_RSA_WITH_NULL_SHA256 0x003B /* 59 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100137#define TLS_RSA_WITH_AES_128_CBC_SHA256 0x003C /* 60 */
138#define TLS_RSA_WITH_AES_256_CBC_SHA256 0x003D /* 61 */
Denys Vlasenko5df3b122018-11-04 21:25:41 +0100139#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 0x0067 /* 103 */
140#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 0x006B /* 107 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100141#define TLS_PSK_WITH_AES_128_CBC_SHA 0x008C /* 140 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100142#define TLS_PSK_WITH_AES_256_CBC_SHA 0x008D /* 141 */
143#define TLS_DHE_PSK_WITH_AES_128_CBC_SHA 0x0090 /* 144 */
144#define TLS_DHE_PSK_WITH_AES_256_CBC_SHA 0x0091 /* 145 */
Denys Vlasenko5df3b122018-11-04 21:25:41 +0100145#define TLS_RSA_WITH_SEED_CBC_SHA 0x0096 /* 150 */
146#define TLS_PSK_WITH_AES_128_CBC_SHA256 0x00AE /* 174 */
147#define TLS_PSK_WITH_AES_256_CBC_SHA384 0x00AF /* 175 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100148#define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0xC004 /* 49156 */
149#define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0xC005 /* 49157 */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100150#define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0xC009 /*TLSv1 Kx=ECDH Au=ECDSA Enc=AES(128) Mac=SHA1 */
151#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 +0100152#define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA 0xC00E /* 49166 */
153#define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA 0xC00F /* 49167 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100154#define TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA 0xC012 /* 49170 */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100155#define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA 0xC013 /*TLSv1 Kx=ECDH Au=RSA Enc=AES(128) Mac=SHA1 */
156#define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA 0xC014 /*TLSv1 Kx=ECDH Au=RSA Enc=AES(256) Mac=SHA1 */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100157#define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023 /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AES(128) Mac=SHA256 */
158#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 +0100159#define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 0xC025 /* 49189 */
160#define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 0xC026 /* 49190 */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100161#define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 0xC027 /*TLSv1.2 Kx=ECDH Au=RSA Enc=AES(128) Mac=SHA256 */
162#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 +0100163#define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 0xC029 /* 49193 */
164#define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 0xC02A /* 49194 */
165
Denys Vlasenko7a18b952017-01-23 16:37:04 +0100166/* RFC 5288 "AES Galois Counter Mode (GCM) Cipher Suites for TLS" */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100167#define TLS_RSA_WITH_AES_128_GCM_SHA256 0x009C /*TLSv1.2 Kx=RSA Au=RSA Enc=AESGCM(128) Mac=AEAD */
168#define TLS_RSA_WITH_AES_256_GCM_SHA384 0x009D /*TLSv1.2 Kx=RSA Au=RSA Enc=AESGCM(256) Mac=AEAD */
169#define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESGCM(128) Mac=AEAD */
170#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 +0100171#define TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0xC02D /* 49197 */
172#define TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0xC02E /* 49198 */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100173#define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xC02F /*TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(128) Mac=AEAD */
174#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 +0100175#define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 0xC031 /* 49201 */
176#define TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 0xC032 /* 49202 */
177
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100178/* From http://wiki.mozilla.org/Security/Server_Side_TLS */
179/* and 'openssl ciphers -V -stdname' */
180#define TLS_RSA_WITH_ARIA_128_GCM_SHA256 0xC050 /*TLSv1.2 Kx=RSA Au=RSA Enc=ARIAGCM(128) Mac=AEAD */
Denys Vlasenko5df3b122018-11-04 21:25:41 +0100181#define TLS_RSA_WITH_ARIA_256_GCM_SHA384 0xC051 /*TLSv1.2 Kx=RSA Au=RSA Enc=ARIAGCM(256) Mac=AEAD */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100182#define TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 0xC052 /*TLSv1.2 Kx=DH Au=RSA Enc=ARIAGCM(128) Mac=AEAD */
183#define TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 0xC053 /*TLSv1.2 Kx=DH Au=RSA Enc=ARIAGCM(256) Mac=AEAD */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100184#define TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 0xC05C /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=ARIAGCM(128) Mac=AEAD */
Denys Vlasenko5df3b122018-11-04 21:25:41 +0100185#define TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 0xC05D /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=ARIAGCM(256) Mac=AEAD */
Denys Vlasenko9b0ce4d2018-11-04 20:53:54 +0100186#define TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 0xC060 /*TLSv1.2 Kx=ECDH Au=RSA Enc=ARIAGCM(128) Mac=AEAD */
187#define TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 0xC061 /*TLSv1.2 Kx=ECDH Au=RSA Enc=ARIAGCM(256) Mac=AEAD */
188#define TLS_RSA_WITH_AES_128_CCM 0xC09C /*TLSv1.2 Kx=RSA Au=RSA Enc=AESCCM(128) Mac=AEAD */
189#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 +0100190#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 +0100191#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 +0100192#define TLS_RSA_WITH_AES_128_CCM_8 0xC0A0 /*TLSv1.2 Kx=RSA Au=RSA Enc=AESCCM8(128) Mac=AEAD */
193#define TLS_RSA_WITH_AES_256_CCM_8 0xC0A1 /*TLSv1.2 Kx=RSA Au=RSA Enc=AESCCM8(256) Mac=AEAD */
194#define TLS_DHE_RSA_WITH_AES_128_CCM_8 0xC0A2 /*TLSv1.2 Kx=DH Au=RSA Enc=AESCCM8(128) Mac=AEAD */
195#define TLS_DHE_RSA_WITH_AES_256_CCM_8 0xC0A3 /*TLSv1.2 Kx=DH Au=RSA Enc=AESCCM8(256) Mac=AEAD */
196#define TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA8 /*TLSv1.2 Kx=ECDH Au=RSA Enc=CHACHA20/POLY1305(256) Mac=AEAD */
197#define TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA9 /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=CHACHA20/POLY1305(256) Mac=AEAD */
198#define TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCAA /*TLSv1.2 Kx=DH Au=RSA Enc=CHACHA20/POLY1305(256) Mac=AEAD */
199#define TLS_ECDHE_ECDSA_WITH_AES_128_CCM 0xC0AC /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESCCM(128) Mac=AEAD */
200#define TLS_ECDHE_ECDSA_WITH_AES_256_CCM 0xC0AD /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESCCM(256) Mac=AEAD */
201#define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESCCM8(128) Mac=AEAD */
202#define TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 0xC0AF /*TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESCCM8(256) Mac=AEAD */
203
Denys Vlasenkob29d0452018-11-04 21:18:29 +0100204#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 +0100205#define TLS_AES_256_GCM_SHA384 0x1302 /*TLSv1.3 Kx=any Au=any Enc=AESGCM(256) Mac=AEAD */
206#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 +0100207#define TLS_AES_128_CCM_SHA256 0x1304 /*TLSv1.3 Kx=any Au=any Enc=AESCCM(128) Mac=AEAD */
208
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100209/* Might go to libbb.h */
210#define TLS_MAX_CRYPTBLOCK_SIZE 16
211#define TLS_MAX_OUTBUF (1 << 14)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100212
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100213enum {
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100214 SHA_INSIZE = 64,
215 SHA1_OUTSIZE = 20,
216 SHA256_OUTSIZE = 32,
217
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100218 AES128_KEYSIZE = 16,
219 AES256_KEYSIZE = 32,
220
Denys Vlasenko38972a82017-01-20 19:11:14 +0100221 RSA_PREMASTER_SIZE = 48,
222
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100223 RECHDR_LEN = 5,
224
Denys Vlasenko38972a82017-01-20 19:11:14 +0100225 /* 8 = 3+5. 3 extra bytes result in record data being 32-bit aligned */
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100226 OUTBUF_PFX = 8 + AES_BLOCK_SIZE, /* header + IV */
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100227 OUTBUF_SFX = TLS_MAX_MAC_SIZE + TLS_MAX_CRYPTBLOCK_SIZE, /* MAC + padding */
Denys Vlasenko39161392017-01-20 20:27:06 +0100228
229 // RFC 5246
230 // | 6.2.1. Fragmentation
231 // | The record layer fragments information blocks into TLSPlaintext
232 // | records carrying data in chunks of 2^14 bytes or less. Client
233 // | message boundaries are not preserved in the record layer (i.e.,
234 // | multiple client messages of the same ContentType MAY be coalesced
235 // | into a single TLSPlaintext record, or a single message MAY be
236 // | fragmented across several records)
237 // |...
238 // | length
239 // | The length (in bytes) of the following TLSPlaintext.fragment.
240 // | The length MUST NOT exceed 2^14.
241 // |...
242 // | 6.2.2. Record Compression and Decompression
243 // |...
244 // | Compression must be lossless and may not increase the content length
245 // | by more than 1024 bytes. If the decompression function encounters a
246 // | TLSCompressed.fragment that would decompress to a length in excess of
247 // | 2^14 bytes, it MUST report a fatal decompression failure error.
248 // |...
249 // | length
250 // | The length (in bytes) of the following TLSCompressed.fragment.
251 // | The length MUST NOT exceed 2^14 + 1024.
252 // |...
253 // | 6.2.3. Record Payload Protection
254 // | The encryption and MAC functions translate a TLSCompressed
255 // | structure into a TLSCiphertext. The decryption functions reverse
256 // | the process. The MAC of the record also includes a sequence
257 // | number so that missing, extra, or repeated messages are
258 // | detectable.
259 // |...
260 // | length
261 // | The length (in bytes) of the following TLSCiphertext.fragment.
262 // | The length MUST NOT exceed 2^14 + 2048.
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100263 MAX_INBUF = RECHDR_LEN + (1 << 14) + 2048,
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100264};
265
Denys Vlasenkob1003f72017-01-14 13:57:16 +0100266struct record_hdr {
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100267 uint8_t type;
268 uint8_t proto_maj, proto_min;
269 uint8_t len16_hi, len16_lo;
270};
271
Denys Vlasenkobddb6542018-11-13 02:16:24 +0100272enum {
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100273 NEED_EC_KEY = 1 << 0,
274 GOT_CERT_RSA_KEY_ALG = 1 << 1,
Denys Vlasenkoecc90902018-11-23 18:31:26 +0100275 GOT_CERT_ECDSA_KEY_ALG = 1 << 2,
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100276 GOT_EC_KEY = 1 << 3,
277 ENCRYPTION_AESGCM = 1 << 4,
Denys Vlasenkobddb6542018-11-13 02:16:24 +0100278};
Denys Vlasenko9a647c32017-01-23 01:08:16 +0100279struct tls_handshake_data {
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100280 /* In bbox, md5/sha1/sha256 ctx's are the same structure */
281 md5sha_ctx_t handshake_hash_ctx;
282
Denys Vlasenko7a18b952017-01-23 16:37:04 +0100283 uint8_t client_and_server_rand32[2 * 32];
284 uint8_t master_secret[48];
Denys Vlasenkobddb6542018-11-13 02:16:24 +0100285
Denys Vlasenkodd2577f2017-01-20 22:48:41 +0100286//TODO: store just the DER key here, parse/use/delete it when sending client key
287//this way it will stay key type agnostic here.
Denys Vlasenko11d00962017-01-15 00:12:42 +0100288 psRsaKey_t server_rsa_pub_key;
Denys Vlasenkobddb6542018-11-13 02:16:24 +0100289 uint8_t ecc_pub_key32[32];
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100290
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100291/* HANDSHAKE HASH: */
292 //unsigned saved_client_hello_size;
293 //uint8_t saved_client_hello[1];
Denys Vlasenko9a647c32017-01-23 01:08:16 +0100294};
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100295
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100296
297static unsigned get24be(const uint8_t *p)
298{
299 return 0x100*(0x100*p[0] + p[1]) + p[2];
300}
301
302#if TLS_DEBUG
303static void dump_hex(const char *fmt, const void *vp, int len)
304{
305 char hexbuf[32 * 1024 + 4];
306 const uint8_t *p = vp;
307
308 bin2hex(hexbuf, (void*)p, len)[0] = '\0';
309 dbg(fmt, hexbuf);
310}
311
312static void dump_tls_record(const void *vp, int len)
313{
314 const uint8_t *p = vp;
315
316 while (len > 0) {
317 unsigned xhdr_len;
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100318 if (len < RECHDR_LEN) {
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100319 dump_hex("< |%s|\n", p, len);
320 return;
321 }
322 xhdr_len = 0x100*p[3] + p[4];
323 dbg("< hdr_type:%u ver:%u.%u len:%u", p[0], p[1], p[2], xhdr_len);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100324 p += RECHDR_LEN;
325 len -= RECHDR_LEN;
326 if (len >= 4 && p[-RECHDR_LEN] == RECORD_TYPE_HANDSHAKE) {
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100327 unsigned len24 = get24be(p + 1);
328 dbg(" type:%u len24:%u", p[0], len24);
329 }
330 if (xhdr_len > len)
331 xhdr_len = len;
332 dump_hex(" |%s|\n", p, xhdr_len);
333 p += xhdr_len;
334 len -= xhdr_len;
335 }
336}
Denys Vlasenko38972a82017-01-20 19:11:14 +0100337#else
338# define dump_hex(...) ((void)0)
339# define dump_tls_record(...) ((void)0)
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100340#endif
341
Denys Vlasenko624066f2018-11-23 19:24:57 +0100342void FAST_FUNC tls_get_random(void *buf, unsigned len)
Denys Vlasenko11d00962017-01-15 00:12:42 +0100343{
344 if (len != open_read_close("/dev/urandom", buf, len))
345 xfunc_die();
346}
347
Denys Vlasenko941440c2018-11-24 13:51:46 +0100348static void xorbuf3(void *dst, const void *src1, const void *src2, unsigned count)
349{
350 uint8_t *d = dst;
351 const uint8_t *s1 = src1;
352 const uint8_t* s2 = src2;
353 while (count--)
354 *d++ = *s1++ ^ *s2++;
355}
356
357void FAST_FUNC xorbuf(void *dst, const void *src, unsigned count)
358{
359 xorbuf3(dst, dst, src, count);
360}
361
Denys Vlasenko03569bc2018-11-24 14:08:29 +0100362void FAST_FUNC xorbuf_aligned_AES_BLOCK_SIZE(void *dst, const void *src)
363{
364 unsigned long *d = dst;
365 const unsigned long *s = src;
366 d[0] ^= s[0];
367#if ULONG_MAX <= 0xffffffffffffffff
368 d[1] ^= s[1];
369 #if ULONG_MAX == 0xffffffff
370 d[2] ^= s[2];
371 d[3] ^= s[3];
372 #endif
373#endif
374}
375
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100376/* Nondestructively see the current hash value */
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100377static unsigned sha_peek(md5sha_ctx_t *ctx, void *buffer)
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100378{
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100379 md5sha_ctx_t ctx_copy = *ctx; /* struct copy */
380 return sha_end(&ctx_copy, buffer);
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100381}
382
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100383static ALWAYS_INLINE unsigned get_handshake_hash(tls_state_t *tls, void *buffer)
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100384{
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100385 return sha_peek(&tls->hsd->handshake_hash_ctx, buffer);
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100386}
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100387
388#if !TLS_DEBUG_HASH
389# define hash_handshake(tls, fmt, buffer, len) \
390 hash_handshake(tls, buffer, len)
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +0100391#endif
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100392static void hash_handshake(tls_state_t *tls, const char *fmt, const void *buffer, unsigned len)
393{
394 md5sha_hash(&tls->hsd->handshake_hash_ctx, buffer, len);
395#if TLS_DEBUG_HASH
396 {
397 uint8_t h[TLS_MAX_MAC_SIZE];
398 dump_hex(fmt, buffer, len);
399 dbg(" (%u bytes) ", (int)len);
400 len = sha_peek(&tls->hsd->handshake_hash_ctx, h);
401 if (len == SHA1_OUTSIZE)
402 dump_hex("sha1:%s\n", h, len);
403 else
404 if (len == SHA256_OUTSIZE)
405 dump_hex("sha256:%s\n", h, len);
406 else
407 dump_hex("sha???:%s\n", h, len);
408 }
409#endif
410}
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +0100411
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100412// RFC 2104
413// HMAC(key, text) based on a hash H (say, sha256) is:
414// ipad = [0x36 x INSIZE]
415// opad = [0x5c x INSIZE]
416// HMAC(key, text) = H((key XOR opad) + H((key XOR ipad) + text))
417//
418// H(key XOR opad) and H(key XOR ipad) can be precomputed
419// if we often need HMAC hmac with the same key.
420//
421// text is often given in disjoint pieces.
Denys Vlasenko89193f92017-01-24 18:08:07 +0100422typedef struct hmac_precomputed {
423 md5sha_ctx_t hashed_key_xor_ipad;
424 md5sha_ctx_t hashed_key_xor_opad;
425} hmac_precomputed_t;
426
427static unsigned hmac_sha_precomputed_v(
428 hmac_precomputed_t *pre,
429 uint8_t *out,
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100430 va_list va)
431{
432 uint8_t *text;
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100433 unsigned len;
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100434
Denys Vlasenko89193f92017-01-24 18:08:07 +0100435 /* pre->hashed_key_xor_ipad contains unclosed "H((key XOR ipad) +" state */
436 /* pre->hashed_key_xor_opad contains unclosed "H((key XOR opad) +" state */
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100437
438 /* calculate out = H((key XOR ipad) + text) */
439 while ((text = va_arg(va, uint8_t*)) != NULL) {
440 unsigned text_size = va_arg(va, unsigned);
Denys Vlasenko89193f92017-01-24 18:08:07 +0100441 md5sha_hash(&pre->hashed_key_xor_ipad, text, text_size);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100442 }
Denys Vlasenko89193f92017-01-24 18:08:07 +0100443 len = sha_end(&pre->hashed_key_xor_ipad, out);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100444
445 /* out = H((key XOR opad) + out) */
Denys Vlasenko89193f92017-01-24 18:08:07 +0100446 md5sha_hash(&pre->hashed_key_xor_opad, out, len);
447 return sha_end(&pre->hashed_key_xor_opad, out);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100448}
449
Denys Vlasenko636c3b62017-04-03 17:43:44 +0200450typedef void md5sha_begin_func(md5sha_ctx_t *ctx) FAST_FUNC;
451static void hmac_begin(hmac_precomputed_t *pre, uint8_t *key, unsigned key_size, md5sha_begin_func *begin)
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100452{
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100453 uint8_t key_xor_ipad[SHA_INSIZE];
454 uint8_t key_xor_opad[SHA_INSIZE];
Denys Vlasenko636c3b62017-04-03 17:43:44 +0200455 uint8_t tempkey[SHA1_OUTSIZE < SHA256_OUTSIZE ? SHA256_OUTSIZE : SHA1_OUTSIZE];
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100456 unsigned i;
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100457
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100458 // "The authentication key can be of any length up to INSIZE, the
459 // block length of the hash function. Applications that use keys longer
460 // than INSIZE bytes will first hash the key using H and then use the
461 // resultant OUTSIZE byte string as the actual key to HMAC."
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100462 if (key_size > SHA_INSIZE) {
463 md5sha_ctx_t ctx;
Denys Vlasenko636c3b62017-04-03 17:43:44 +0200464 begin(&ctx);
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100465 md5sha_hash(&ctx, key, key_size);
466 key_size = sha_end(&ctx, tempkey);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100467 }
468
469 for (i = 0; i < key_size; i++) {
470 key_xor_ipad[i] = key[i] ^ 0x36;
471 key_xor_opad[i] = key[i] ^ 0x5c;
472 }
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100473 for (; i < SHA_INSIZE; i++) {
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100474 key_xor_ipad[i] = 0x36;
475 key_xor_opad[i] = 0x5c;
476 }
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100477
Denys Vlasenko636c3b62017-04-03 17:43:44 +0200478 begin(&pre->hashed_key_xor_ipad);
479 begin(&pre->hashed_key_xor_opad);
Denys Vlasenko89193f92017-01-24 18:08:07 +0100480 md5sha_hash(&pre->hashed_key_xor_ipad, key_xor_ipad, SHA_INSIZE);
481 md5sha_hash(&pre->hashed_key_xor_opad, key_xor_opad, SHA_INSIZE);
482}
483
484static unsigned hmac(tls_state_t *tls, uint8_t *out, uint8_t *key, unsigned key_size, ...)
485{
486 hmac_precomputed_t pre;
487 va_list va;
488 unsigned len;
489
490 va_start(va, key_size);
491
Denys Vlasenko636c3b62017-04-03 17:43:44 +0200492 hmac_begin(&pre, key, key_size,
493 (tls->MAC_size == SHA256_OUTSIZE)
494 ? sha256_begin
495 : sha1_begin
496 );
Denys Vlasenko89193f92017-01-24 18:08:07 +0100497 len = hmac_sha_precomputed_v(&pre, out, va);
498
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100499 va_end(va);
Denys Vlasenko89193f92017-01-24 18:08:07 +0100500 return len;
501}
502
503static unsigned hmac_sha256(/*tls_state_t *tls,*/ uint8_t *out, uint8_t *key, unsigned key_size, ...)
504{
505 hmac_precomputed_t pre;
506 va_list va;
507 unsigned len;
508
509 va_start(va, key_size);
510
Denys Vlasenko636c3b62017-04-03 17:43:44 +0200511 hmac_begin(&pre, key, key_size, sha256_begin);
Denys Vlasenko89193f92017-01-24 18:08:07 +0100512 len = hmac_sha_precomputed_v(&pre, out, va);
513
514 va_end(va);
515 return len;
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100516}
517
518// 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!
526// PRF uses sha256 regardless of cipher (at least for all ciphers
527// defined by RFC5246). It's not sha1 for AES_128_CBC_SHA!
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100528//...
529// P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
530// HMAC_hash(secret, A(2) + seed) +
531// HMAC_hash(secret, A(3) + seed) + ...
532// where + indicates concatenation.
533// A() is defined as:
534// A(0) = seed
535// A(1) = HMAC_hash(secret, A(0)) = HMAC_hash(secret, seed)
536// A(i) = HMAC_hash(secret, A(i-1))
537// P_hash can be iterated as many times as necessary to produce the
538// required quantity of data. For example, if P_SHA256 is being used to
539// create 80 bytes of data, it will have to be iterated three times
540// (through A(3)), creating 96 bytes of output data; the last 16 bytes
541// of the final iteration will then be discarded, leaving 80 bytes of
542// output data.
543//
544// TLS's PRF is created by applying P_hash to the secret as:
545//
546// PRF(secret, label, seed) = P_<hash>(secret, label + seed)
547//
548// The label is an ASCII string.
Denys Vlasenko89193f92017-01-24 18:08:07 +0100549static void prf_hmac_sha256(/*tls_state_t *tls,*/
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100550 uint8_t *outbuf, unsigned outbuf_size,
551 uint8_t *secret, unsigned secret_size,
552 const char *label,
553 uint8_t *seed, unsigned seed_size)
554{
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100555 uint8_t a[TLS_MAX_MAC_SIZE];
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100556 uint8_t *out_p = outbuf;
557 unsigned label_size = strlen(label);
Denys Vlasenko229d3c42017-04-03 21:53:29 +0200558 unsigned MAC_size = SHA256_OUTSIZE;
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100559
560 /* In P_hash() calculation, "seed" is "label + seed": */
561#define SEED label, label_size, seed, seed_size
562#define SECRET secret, secret_size
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100563#define A a, MAC_size
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100564
565 /* A(1) = HMAC_hash(secret, seed) */
Denys Vlasenko89193f92017-01-24 18:08:07 +0100566 hmac_sha256(/*tls,*/ a, SECRET, SEED, NULL);
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100567//TODO: convert hmac to precomputed
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100568
Denys Vlasenko229d3c42017-04-03 21:53:29 +0200569 for (;;) {
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100570 /* HMAC_hash(secret, A(1) + seed) */
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100571 if (outbuf_size <= MAC_size) {
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100572 /* Last, possibly incomplete, block */
573 /* (use a[] as temp buffer) */
Denys Vlasenko89193f92017-01-24 18:08:07 +0100574 hmac_sha256(/*tls,*/ a, SECRET, A, SEED, NULL);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100575 memcpy(out_p, a, outbuf_size);
576 return;
577 }
578 /* Not last block. Store directly to result buffer */
Denys Vlasenko89193f92017-01-24 18:08:07 +0100579 hmac_sha256(/*tls,*/ out_p, SECRET, A, SEED, NULL);
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100580 out_p += MAC_size;
581 outbuf_size -= MAC_size;
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100582 /* A(2) = HMAC_hash(secret, A(1)) */
Denys Vlasenko89193f92017-01-24 18:08:07 +0100583 hmac_sha256(/*tls,*/ a, SECRET, A, NULL);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100584 }
585#undef A
586#undef SECRET
587#undef SEED
588}
589
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100590static void bad_record_die(tls_state_t *tls, const char *expected, int len)
591{
Denys Vlasenko1500b3a2017-01-24 17:06:10 +0100592 bb_error_msg("got bad TLS record (len:%d) while expecting %s", len, expected);
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100593 if (len > 0) {
594 uint8_t *p = tls->inbuf;
Denys Vlasenko98066662018-02-06 13:33:00 +0100595 if (len > 99)
596 len = 99; /* don't flood, a few lines should be enough */
597 do {
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100598 fprintf(stderr, " %02x", *p++);
Denys Vlasenko1500b3a2017-01-24 17:06:10 +0100599 len--;
Denys Vlasenko98066662018-02-06 13:33:00 +0100600 } while (len != 0);
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100601 fputc('\n', stderr);
602 }
603 xfunc_die();
604}
605
Denys Vlasenko1500b3a2017-01-24 17:06:10 +0100606static void tls_error_die(tls_state_t *tls, int line)
Denys Vlasenko936e83e2017-01-16 04:25:01 +0100607{
Denys Vlasenko39161392017-01-20 20:27:06 +0100608 dump_tls_record(tls->inbuf, tls->ofs_to_buffered + tls->buffered_size);
Denys Vlasenko1500b3a2017-01-24 17:06:10 +0100609 bb_error_msg_and_die("tls error at line %d cipher:%04x", line, tls->cipher_id);
Denys Vlasenko38972a82017-01-20 19:11:14 +0100610}
Denys Vlasenko1500b3a2017-01-24 17:06:10 +0100611#define tls_error_die(tls) tls_error_die(tls, __LINE__)
Denys Vlasenko38972a82017-01-20 19:11:14 +0100612
Denys Vlasenko39161392017-01-20 20:27:06 +0100613#if 0 //UNUSED
614static void tls_free_inbuf(tls_state_t *tls)
615{
616 if (tls->buffered_size == 0) {
617 free(tls->inbuf);
618 tls->inbuf_size = 0;
619 tls->inbuf = NULL;
620 }
621}
622#endif
623
Denys Vlasenko38972a82017-01-20 19:11:14 +0100624static void tls_free_outbuf(tls_state_t *tls)
625{
626 free(tls->outbuf);
627 tls->outbuf_size = 0;
628 tls->outbuf = NULL;
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100629}
630
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100631static void *tls_get_outbuf(tls_state_t *tls, int len)
632{
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100633 if (len > TLS_MAX_OUTBUF)
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100634 xfunc_die();
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100635 len += OUTBUF_PFX + OUTBUF_SFX;
636 if (tls->outbuf_size < len) {
637 tls->outbuf_size = len;
638 tls->outbuf = xrealloc(tls->outbuf, len);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100639 }
640 return tls->outbuf + OUTBUF_PFX;
641}
642
Denys Vlasenkod5a04052018-11-13 11:58:53 +0100643static void *tls_get_zeroed_outbuf(tls_state_t *tls, int len)
644{
645 void *record = tls_get_outbuf(tls, len);
646 memset(record, 0, len);
647 return record;
648}
649
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100650static void xwrite_encrypted_and_hmac_signed(tls_state_t *tls, unsigned size, unsigned type)
Denys Vlasenkofe0588d2017-01-17 17:04:24 +0100651{
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100652 uint8_t *buf = tls->outbuf + OUTBUF_PFX;
653 struct record_hdr *xhdr;
Denys Vlasenkoe7863f32017-01-20 17:59:25 +0100654 uint8_t padding_length;
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100655
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100656 xhdr = (void*)(buf - RECHDR_LEN);
Denys Vlasenko5d561ef2017-04-04 01:41:15 +0200657 if (CIPHER_ID1 != TLS_RSA_WITH_NULL_SHA256 /* if "no encryption" can't be selected */
658 || tls->cipher_id != TLS_RSA_WITH_NULL_SHA256 /* or if it wasn't selected */
659 ) {
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100660 xhdr = (void*)(buf - RECHDR_LEN - AES_BLOCK_SIZE); /* place for IV */
Denys Vlasenko5d561ef2017-04-04 01:41:15 +0200661 }
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +0100662
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100663 xhdr->type = type;
664 xhdr->proto_maj = TLS_MAJ;
665 xhdr->proto_min = TLS_MIN;
Denys Vlasenko54b927d2017-01-20 21:19:38 +0100666 /* fake unencrypted record len for MAC calculation */
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100667 xhdr->len16_hi = size >> 8;
668 xhdr->len16_lo = size & 0xff;
669
670 /* Calculate MAC signature */
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100671 hmac(tls, buf + size, /* result */
672 tls->client_write_MAC_key, tls->MAC_size,
673 &tls->write_seq64_be, sizeof(tls->write_seq64_be),
674 xhdr, RECHDR_LEN,
675 buf, size,
676 NULL
677 );
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +0100678 tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(tls->write_seq64_be));
Denys Vlasenko9a6897a2017-01-16 23:26:33 +0100679
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100680 size += tls->MAC_size;
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100681
Denys Vlasenkoe7863f32017-01-20 17:59:25 +0100682 // RFC 5246
683 // 6.2.3.1. Null or Standard Stream Cipher
684 //
685 // Stream ciphers (including BulkCipherAlgorithm.null; see Appendix A.6)
686 // convert TLSCompressed.fragment structures to and from stream
687 // TLSCiphertext.fragment structures.
688 //
689 // stream-ciphered struct {
690 // opaque content[TLSCompressed.length];
691 // opaque MAC[SecurityParameters.mac_length];
692 // } GenericStreamCipher;
693 //
694 // The MAC is generated as:
695 // MAC(MAC_write_key, seq_num +
696 // TLSCompressed.type +
697 // TLSCompressed.version +
698 // TLSCompressed.length +
699 // TLSCompressed.fragment);
700 // where "+" denotes concatenation.
701 // seq_num
702 // The sequence number for this record.
703 // MAC
704 // The MAC algorithm specified by SecurityParameters.mac_algorithm.
705 //
706 // Note that the MAC is computed before encryption. The stream cipher
707 // encrypts the entire block, including the MAC.
708 //...
709 // Appendix C. Cipher Suite Definitions
710 //...
711 // MAC Algorithm mac_length mac_key_length
712 // -------- ----------- ---------- --------------
713 // SHA HMAC-SHA1 20 20
714 // SHA256 HMAC-SHA256 32 32
Denys Vlasenko5d561ef2017-04-04 01:41:15 +0200715 if (CIPHER_ID1 == TLS_RSA_WITH_NULL_SHA256
716 && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
717 ) {
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100718 /* No encryption, only signing */
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100719 xhdr->len16_hi = size >> 8;
720 xhdr->len16_lo = size & 0xff;
Denys Vlasenkoe7863f32017-01-20 17:59:25 +0100721 dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
Denys Vlasenko9a647c32017-01-23 01:08:16 +0100722 xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100723 dbg("wrote %u bytes (NULL crypt, SHA256 hash)\n", size);
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100724 return;
725 }
726
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100727 // 6.2.3.2. CBC Block Cipher
728 // For block ciphers (such as 3DES or AES), the encryption and MAC
729 // functions convert TLSCompressed.fragment structures to and from block
730 // TLSCiphertext.fragment structures.
731 // struct {
732 // opaque IV[SecurityParameters.record_iv_length];
733 // block-ciphered struct {
734 // opaque content[TLSCompressed.length];
735 // opaque MAC[SecurityParameters.mac_length];
736 // uint8 padding[GenericBlockCipher.padding_length];
737 // uint8 padding_length;
738 // };
739 // } GenericBlockCipher;
740 //...
741 // IV
742 // The Initialization Vector (IV) SHOULD be chosen at random, and
743 // MUST be unpredictable. Note that in versions of TLS prior to 1.1,
744 // there was no IV field (...). For block ciphers, the IV length is
745 // of length SecurityParameters.record_iv_length, which is equal to the
746 // SecurityParameters.block_size.
747 // padding
748 // Padding that is added to force the length of the plaintext to be
749 // an integral multiple of the block cipher's block length.
750 // padding_length
751 // The padding length MUST be such that the total size of the
752 // GenericBlockCipher structure is a multiple of the cipher's block
753 // length. Legal values range from zero to 255, inclusive.
754 //...
755 // Appendix C. Cipher Suite Definitions
756 //...
757 // Key IV Block
758 // Cipher Type Material Size Size
759 // ------------ ------ -------- ---- -----
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100760 // AES_128_CBC Block 16 16 16
761 // AES_256_CBC Block 32 16 16
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100762
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100763 tls_get_random(buf - AES_BLOCK_SIZE, AES_BLOCK_SIZE); /* IV */
Denys Vlasenko98066662018-02-06 13:33:00 +0100764 dbg("before crypt: 5 hdr + %u data + %u hash bytes\n",
765 size - tls->MAC_size, tls->MAC_size);
766
767 /* Fill IV and padding in outbuf */
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100768 // RFC is talking nonsense:
Denys Vlasenko7a18b952017-01-23 16:37:04 +0100769 // "Padding that is added to force the length of the plaintext to be
770 // an integral multiple of the block cipher's block length."
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100771 // WRONG. _padding+padding_length_, not just _padding_,
772 // pads the data.
773 // IOW: padding_length is the last byte of padding[] array,
774 // contrary to what RFC depicts.
775 //
776 // What actually happens is that there is always padding.
777 // If you need one byte to reach BLOCKSIZE, this byte is 0x00.
778 // If you need two bytes, they are both 0x01.
779 // If you need three, they are 0x02,0x02,0x02. And so on.
780 // If you need no bytes to reach BLOCKSIZE, you have to pad a full
781 // BLOCKSIZE with bytes of value (BLOCKSIZE-1).
782 // It's ok to have more than minimum padding, but we do minimum.
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100783 padding_length = (~size) & (AES_BLOCK_SIZE - 1);
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100784 do {
Denys Vlasenko54b927d2017-01-20 21:19:38 +0100785 buf[size++] = padding_length; /* padding */
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100786 } while ((size & (AES_BLOCK_SIZE - 1)) != 0);
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100787
788 /* Encrypt content+MAC+padding in place */
Denys Vlasenkoc31b54f2017-02-04 16:23:49 +0100789 aes_cbc_encrypt(
Denys Vlasenkod2923b32018-11-24 21:26:20 +0100790 &tls->aes_encrypt, /* selects 128/256 */
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100791 buf - AES_BLOCK_SIZE, /* IV */
Denys Vlasenkoc31b54f2017-02-04 16:23:49 +0100792 buf, size, /* plaintext */
793 buf /* ciphertext */
794 );
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100795
796 /* Write out */
797 dbg("writing 5 + %u IV + %u encrypted bytes, padding_length:0x%02x\n",
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100798 AES_BLOCK_SIZE, size, padding_length);
799 size += AES_BLOCK_SIZE; /* + IV */
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +0100800 xhdr->len16_hi = size >> 8;
801 xhdr->len16_lo = size & 0xff;
Denys Vlasenkoe7863f32017-01-20 17:59:25 +0100802 dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
Denys Vlasenko9a647c32017-01-23 01:08:16 +0100803 xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +0100804 dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100805}
806
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100807/* Example how GCM encryption combines nonce, aad, input and generates
808 * "header | exp_nonce | encrypted output | tag":
809 * nonce:0d 6a 26 31 00 00 00 00 00 00 00 01 (implicit 4 bytes (derived from master secret), then explicit 8 bytes)
810 * aad: 00 00 00 00 00 00 00 01 17 03 03 00 1c
811 * 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)
812 * 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
813 * tag: c2 86 ce 4a 50 4a d0 aa 50 b3 76 5c 49 2a 3f 33
814 * 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
815 * .............................................^^ buf points here
816 */
817static void xwrite_encrypted_aesgcm(tls_state_t *tls, unsigned size, unsigned type)
818{
Denys Vlasenkoecc90902018-11-23 18:31:26 +0100819#define COUNTER(v) (*(uint32_t*)(v + 12))
820
Denys Vlasenko03569bc2018-11-24 14:08:29 +0100821 uint8_t aad[13 + 3] ALIGNED_long; /* +3 creates [16] buffer, simplifying GHASH() */
822 uint8_t nonce[12 + 4] ALIGNED_long; /* +4 creates space for AES block counter */
823 uint8_t scratch[AES_BLOCK_SIZE] ALIGNED_long; //[16]
824 uint8_t authtag[AES_BLOCK_SIZE] ALIGNED_long; //[16]
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100825 uint8_t *buf;
826 struct record_hdr *xhdr;
827 unsigned remaining;
828 unsigned cnt;
Denys Vlasenko219c9d42018-11-23 18:48:20 +0100829 uint64_t t64;
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100830
831 buf = tls->outbuf + OUTBUF_PFX; /* see above for the byte it points to */
832 dump_hex("xwrite_encrypted_aesgcm plaintext:%s\n", buf, size);
833
834 xhdr = (void*)(buf - 8 - RECHDR_LEN);
835 xhdr->type = type; /* do it here so that "type" param no longer used */
836
837 aad[8] = type;
838 aad[9] = TLS_MAJ;
839 aad[10] = TLS_MIN;
840 aad[11] = size >> 8;
Denys Vlasenkoecc90902018-11-23 18:31:26 +0100841 /* set aad[12], and clear aad[13..15] */
842 COUNTER(aad) = SWAP_LE32(size & 0xff);
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100843
Denys Vlasenko219c9d42018-11-23 18:48:20 +0100844 memcpy(nonce, tls->client_write_IV, 4);
845 t64 = tls->write_seq64_be;
846 move_to_unaligned64(nonce + 4, t64);
847 move_to_unaligned64(aad, t64);
848 move_to_unaligned64(buf - 8, t64);
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100849 /* seq64 is not used later in this func, can increment here */
Denys Vlasenko219c9d42018-11-23 18:48:20 +0100850 tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(t64));
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100851
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100852 cnt = 1;
853 remaining = size;
854 while (remaining != 0) {
855 unsigned n;
856
857 cnt++;
858 COUNTER(nonce) = htonl(cnt); /* yes, first cnt here is 2 (!) */
859 aes_encrypt_one_block(&tls->aes_encrypt, nonce, scratch);
860 n = remaining > AES_BLOCK_SIZE ? AES_BLOCK_SIZE : remaining;
861 xorbuf(buf, scratch, n);
862 buf += n;
863 remaining -= n;
864 }
865
Denys Vlasenkoecc90902018-11-23 18:31:26 +0100866 aesgcm_GHASH(tls->H, aad, /*sizeof(aad),*/ tls->outbuf + OUTBUF_PFX, size, authtag /*, sizeof(authtag)*/);
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100867 COUNTER(nonce) = htonl(1);
868 aes_encrypt_one_block(&tls->aes_encrypt, nonce, scratch);
Denys Vlasenko03569bc2018-11-24 14:08:29 +0100869 xorbuf_aligned_AES_BLOCK_SIZE(authtag, scratch);
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100870
871 memcpy(buf, authtag, sizeof(authtag));
872#undef COUNTER
873
874 /* Write out */
875 xhdr = (void*)(tls->outbuf + OUTBUF_PFX - 8 - RECHDR_LEN);
876 size += 8 + sizeof(authtag);
877 /*xhdr->type = type; - already is */
878 xhdr->proto_maj = TLS_MAJ;
879 xhdr->proto_min = TLS_MIN;
880 xhdr->len16_hi = size >> 8;
881 xhdr->len16_lo = size & 0xff;
882 size += RECHDR_LEN;
883 dump_raw_out(">> %s\n", xhdr, size);
884 xwrite(tls->ofd, xhdr, size);
885 dbg("wrote %u bytes\n", size);
886}
887
888static void xwrite_encrypted(tls_state_t *tls, unsigned size, unsigned type)
889{
890 if (!(tls->flags & ENCRYPTION_AESGCM)) {
891 xwrite_encrypted_and_hmac_signed(tls, size, type);
892 return;
893 }
894 xwrite_encrypted_aesgcm(tls, size, type);
895}
896
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100897static void xwrite_handshake_record(tls_state_t *tls, unsigned size)
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100898{
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100899 uint8_t *buf = tls->outbuf + OUTBUF_PFX;
900 struct record_hdr *xhdr = (void*)(buf - RECHDR_LEN);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100901
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100902 xhdr->type = RECORD_TYPE_HANDSHAKE;
903 xhdr->proto_maj = TLS_MAJ;
904 xhdr->proto_min = TLS_MIN;
905 xhdr->len16_hi = size >> 8;
906 xhdr->len16_lo = size & 0xff;
907 dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
908 xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
909 dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100910}
911
912static void xwrite_and_update_handshake_hash(tls_state_t *tls, unsigned size)
913{
914 if (!tls->encrypt_on_write) {
915 uint8_t *buf;
916
917 xwrite_handshake_record(tls, size);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100918 /* Handshake hash does not include record headers */
Denys Vlasenko49ecee02017-01-24 16:00:54 +0100919 buf = tls->outbuf + OUTBUF_PFX;
920 hash_handshake(tls, ">> hash:%s", buf, size);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +0100921 return;
922 }
923 xwrite_encrypted(tls, size, RECORD_TYPE_HANDSHAKE);
924}
925
Denys Vlasenko38972a82017-01-20 19:11:14 +0100926static int tls_has_buffered_record(tls_state_t *tls)
927{
Denys Vlasenko39161392017-01-20 20:27:06 +0100928 int buffered = tls->buffered_size;
Denys Vlasenko38972a82017-01-20 19:11:14 +0100929 struct record_hdr *xhdr;
930 int rec_size;
931
932 if (buffered < RECHDR_LEN)
933 return 0;
Denys Vlasenko39161392017-01-20 20:27:06 +0100934 xhdr = (void*)(tls->inbuf + tls->ofs_to_buffered);
Denys Vlasenko38972a82017-01-20 19:11:14 +0100935 rec_size = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
936 if (buffered < rec_size)
937 return 0;
938 return rec_size;
939}
940
Denys Vlasenkob5bf1912017-01-23 16:12:17 +0100941static const char *alert_text(int code)
942{
943 switch (code) {
944 case 20: return "bad MAC";
945 case 50: return "decode error";
946 case 51: return "decrypt error";
947 case 40: return "handshake failure";
948 case 112: return "unrecognized name";
949 }
950 return itoa(code);
951}
952
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100953static void tls_aesgcm_decrypt(tls_state_t *tls, uint8_t *buf, int size)
954{
Denys Vlasenkoecc90902018-11-23 18:31:26 +0100955#define COUNTER(v) (*(uint32_t*)(v + 12))
956
Denys Vlasenko03569bc2018-11-24 14:08:29 +0100957 //uint8_t aad[13 + 3] ALIGNED_long; /* +3 creates [16] buffer, simplifying GHASH() */
958 uint8_t nonce[12 + 4] ALIGNED_long; /* +4 creates space for AES block counter */
959 uint8_t scratch[AES_BLOCK_SIZE] ALIGNED_long; //[16]
960 //uint8_t authtag[AES_BLOCK_SIZE] ALIGNED_long; //[16]
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100961 unsigned remaining;
962 unsigned cnt;
963
Denys Vlasenko219c9d42018-11-23 18:48:20 +0100964 //memcpy(aad, buf, 8);
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100965 //aad[8] = type;
966 //aad[9] = TLS_MAJ;
967 //aad[10] = TLS_MIN;
968 //aad[11] = size >> 8;
Denys Vlasenkoecc90902018-11-23 18:31:26 +0100969 ///* set aad[12], and clear aad[13..15] */
970 //COUNTER(aad) = SWAP_LE32(size & 0xff);
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100971
972 memcpy(nonce, tls->server_write_IV, 4);
973 memcpy(nonce + 4, buf, 8);
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100974
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100975 cnt = 1;
976 remaining = size;
977 while (remaining != 0) {
978 unsigned n;
979
980 cnt++;
981 COUNTER(nonce) = htonl(cnt); /* yes, first cnt here is 2 (!) */
982 aes_encrypt_one_block(&tls->aes_decrypt, nonce, scratch);
983 n = remaining > AES_BLOCK_SIZE ? AES_BLOCK_SIZE : remaining;
Denys Vlasenko941440c2018-11-24 13:51:46 +0100984 xorbuf3(buf, scratch, buf + 8, n);
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100985 buf += n;
986 remaining -= n;
987 }
988
Denys Vlasenko941440c2018-11-24 13:51:46 +0100989 //aesgcm_GHASH(tls->H, aad, tls->inbuf + RECHDR_LEN, size, authtag);
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100990 //COUNTER(nonce) = htonl(1);
991 //aes_encrypt_one_block(&tls->aes_encrypt, nonce, scratch);
Denys Vlasenko03569bc2018-11-24 14:08:29 +0100992 //xorbuf_aligned_AES_BLOCK_SIZE(authtag, scratch);
Denys Vlasenko83e5c622018-11-23 17:21:38 +0100993
994 //memcmp(buf, authtag, sizeof(authtag)) || DIE("HASH DOES NOT MATCH!");
995#undef COUNTER
996}
997
Denys Vlasenko98066662018-02-06 13:33:00 +0100998static int tls_xread_record(tls_state_t *tls, const char *expected)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +0100999{
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001000 struct record_hdr *xhdr;
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01001001 int sz;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001002 int total;
1003 int target;
1004
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001005 again:
Denys Vlasenko39161392017-01-20 20:27:06 +01001006 dbg("ofs_to_buffered:%u buffered_size:%u\n", tls->ofs_to_buffered, tls->buffered_size);
1007 total = tls->buffered_size;
Denys Vlasenkoe7863f32017-01-20 17:59:25 +01001008 if (total != 0) {
Denys Vlasenko39161392017-01-20 20:27:06 +01001009 memmove(tls->inbuf, tls->inbuf + tls->ofs_to_buffered, total);
1010 //dbg("<< remaining at %d [%d] ", tls->ofs_to_buffered, total);
Denys Vlasenkoe7863f32017-01-20 17:59:25 +01001011 //dump_raw_in("<< %s\n", tls->inbuf, total);
1012 }
1013 errno = 0;
Denys Vlasenko39161392017-01-20 20:27:06 +01001014 target = MAX_INBUF;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001015 for (;;) {
Denys Vlasenko39161392017-01-20 20:27:06 +01001016 int rem;
1017
1018 if (total >= RECHDR_LEN && target == MAX_INBUF) {
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001019 xhdr = (void*)tls->inbuf;
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001020 target = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
Denys Vlasenko98066662018-02-06 13:33:00 +01001021
1022 if (target > MAX_INBUF /* malformed input (too long) */
1023 || xhdr->proto_maj != TLS_MAJ
1024 || xhdr->proto_min != TLS_MIN
1025 ) {
1026 sz = total < target ? total : target;
Denys Vlasenko98066662018-02-06 13:33:00 +01001027 bad_record_die(tls, expected, sz);
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001028 }
Denys Vlasenkoe7863f32017-01-20 17:59:25 +01001029 dbg("xhdr type:%d ver:%d.%d len:%d\n",
1030 xhdr->type, xhdr->proto_maj, xhdr->proto_min,
1031 0x100 * xhdr->len16_hi + xhdr->len16_lo
1032 );
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001033 }
1034 /* if total >= target, we have a full packet (and possibly more)... */
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001035 if (total - target >= 0)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001036 break;
Denys Vlasenko39161392017-01-20 20:27:06 +01001037 /* input buffer is grown only as needed */
1038 rem = tls->inbuf_size - total;
1039 if (rem == 0) {
1040 tls->inbuf_size += MAX_INBUF / 8;
1041 if (tls->inbuf_size > MAX_INBUF)
1042 tls->inbuf_size = MAX_INBUF;
1043 dbg("inbuf_size:%d\n", tls->inbuf_size);
1044 rem = tls->inbuf_size - total;
1045 tls->inbuf = xrealloc(tls->inbuf, tls->inbuf_size);
1046 }
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001047 sz = safe_read(tls->ifd, tls->inbuf + total, rem);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001048 if (sz <= 0) {
1049 if (sz == 0 && total == 0) {
1050 /* "Abrupt" EOF, no TLS shutdown (seen from kernel.org) */
1051 dbg("EOF (without TLS shutdown) from peer\n");
Denys Vlasenko39161392017-01-20 20:27:06 +01001052 tls->buffered_size = 0;
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001053 goto end;
1054 }
1055 bb_perror_msg_and_die("short read, have only %d", total);
1056 }
Denys Vlasenkoe7863f32017-01-20 17:59:25 +01001057 dump_raw_in("<< %s\n", tls->inbuf + total, sz);
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01001058 total += sz;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001059 }
Denys Vlasenko39161392017-01-20 20:27:06 +01001060 tls->buffered_size = total - target;
1061 tls->ofs_to_buffered = target;
1062 //dbg("<< stashing at %d [%d] ", tls->ofs_to_buffered, tls->buffered_size);
1063 //dump_hex("<< %s\n", tls->inbuf + tls->ofs_to_buffered, tls->buffered_size);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001064
1065 sz = target - RECHDR_LEN;
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01001066
1067 /* Needs to be decrypted? */
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001068 if (tls->min_encrypted_len_on_read != 0) {
1069 if (sz < (int)tls->min_encrypted_len_on_read)
1070 bb_error_msg_and_die("bad encrypted len:%u", sz);
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01001071
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001072 if (tls->flags & ENCRYPTION_AESGCM) {
1073 /* AESGCM */
1074 uint8_t *p = tls->inbuf + RECHDR_LEN;
1075
1076 sz -= 8 + AES_BLOCK_SIZE; /* we will overwrite nonce, drop hash */
1077 tls_aesgcm_decrypt(tls, p, sz);
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001078 dbg("encrypted size:%u\n", sz);
1079 } else
1080 if (tls->min_encrypted_len_on_read > tls->MAC_size) {
1081 /* AES+SHA */
1082 uint8_t *p = tls->inbuf + RECHDR_LEN;
1083 int padding_len;
1084
1085 if (sz & (AES_BLOCK_SIZE-1))
1086 bb_error_msg_and_die("bad encrypted len:%u", sz);
1087
1088 /* Decrypt content+MAC+padding, moving it over IV in the process */
1089 sz -= AES_BLOCK_SIZE; /* we will overwrite IV now */
1090 aes_cbc_decrypt(
Denys Vlasenko5e4236d2018-11-23 18:02:44 +01001091 &tls->aes_decrypt, /* selects 128/256 */
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001092 p, /* IV */
1093 p + AES_BLOCK_SIZE, sz, /* ciphertext */
1094 p /* plaintext */
1095 );
1096 padding_len = p[sz - 1];
1097 dbg("encrypted size:%u type:0x%02x padding_length:0x%02x\n", sz, p[0], padding_len);
1098 padding_len++;
1099 sz -= tls->MAC_size + padding_len; /* drop MAC and padding */
1100 } else {
1101 /* if nonzero, then it's TLS_RSA_WITH_NULL_SHA256: drop MAC */
1102 /* else: no encryption yet on input, subtract zero = NOP */
1103 sz -= tls->min_encrypted_len_on_read;
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01001104 }
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01001105 }
Denys Vlasenko0af52652017-01-20 21:23:10 +01001106 if (sz < 0)
1107 bb_error_msg_and_die("encrypted data too short");
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001108
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001109 //dump_hex("<< %s\n", tls->inbuf, RECHDR_LEN + sz);
1110
1111 xhdr = (void*)tls->inbuf;
1112 if (xhdr->type == RECORD_TYPE_ALERT && sz >= 2) {
1113 uint8_t *p = tls->inbuf + RECHDR_LEN;
1114 dbg("ALERT size:%d level:%d description:%d\n", sz, p[0], p[1]);
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001115 if (p[0] == 2) { /* fatal */
1116 bb_error_msg_and_die("TLS %s from peer (alert code %d): %s",
1117 "error",
1118 p[1], alert_text(p[1])
1119 );
1120 }
Denys Vlasenko54b927d2017-01-20 21:19:38 +01001121 if (p[0] == 1) { /* warning */
1122 if (p[1] == 0) { /* "close_notify" warning: it's EOF */
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001123 dbg("EOF (TLS encoded) from peer\n");
1124 sz = 0;
1125 goto end;
1126 }
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001127//This possibly needs to be cached and shown only if
1128//a fatal alert follows
1129// bb_error_msg("TLS %s from peer (alert code %d): %s",
1130// "warning",
1131// p[1], alert_text(p[1])
1132// );
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001133 /* discard it, get next record */
1134 goto again;
1135 }
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001136 /* p[0] not 1 or 2: not defined in protocol */
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001137 sz = 0;
1138 goto end;
1139 }
1140
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001141 /* RFC 5246 is not saying it explicitly, but sha256 hash
Denys Vlasenkofe0588d2017-01-17 17:04:24 +01001142 * in our FINISHED record must include data of incoming packets too!
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001143 */
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001144 if (tls->inbuf[0] == RECORD_TYPE_HANDSHAKE
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001145/* HANDSHAKE HASH: */
1146 // && do_we_know_which_hash_to_use /* server_hello() might not know it in the future! */
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001147 ) {
1148 hash_handshake(tls, "<< hash:%s", tls->inbuf + RECHDR_LEN, sz);
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001149 }
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001150 end:
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01001151 dbg("got block len:%u\n", sz);
1152 return sz;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001153}
1154
Denys Vlasenkode7b5bb2018-11-13 11:44:32 +01001155static void binary_to_pstm(pstm_int *pstm_n, uint8_t *bin_ptr, unsigned len)
1156{
1157 pstm_init_for_read_unsigned_bin(/*pool:*/ NULL, pstm_n, len);
1158 pstm_read_unsigned_bin(pstm_n, bin_ptr, len);
1159 //return bin_ptr + len;
1160}
1161
Denys Vlasenkofe0588d2017-01-17 17:04:24 +01001162/*
1163 * DER parsing routines
1164 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001165static unsigned get_der_len(uint8_t **bodyp, uint8_t *der, uint8_t *end)
1166{
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +01001167 unsigned len, len1;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001168
1169 if (end - der < 2)
1170 xfunc_die();
1171// if ((der[0] & 0x1f) == 0x1f) /* not single-byte item code? */
1172// xfunc_die();
1173
1174 len = der[1]; /* maybe it's short len */
1175 if (len >= 0x80) {
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001176 /* no, it's long */
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +01001177
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001178 if (len == 0x80 || end - der < (int)(len - 0x7e)) {
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001179 /* 0x80 is "0 bytes of len", invalid DER: must use short len if can */
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001180 /* need 3 or 4 bytes for 81, 82 */
1181 xfunc_die();
1182 }
1183
1184 len1 = der[2]; /* if (len == 0x81) it's "ii 81 xx", fetch xx */
1185 if (len > 0x82) {
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001186 /* >0x82 is "3+ bytes of len", should not happen realistically */
1187 xfunc_die();
1188 }
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001189 if (len == 0x82) { /* it's "ii 82 xx yy" */
1190 len1 = 0x100*len1 + der[3];
1191 der += 1; /* skip [yy] */
1192 }
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +01001193 der += 1; /* skip [xx] */
1194 len = len1;
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001195// if (len < 0x80)
1196// xfunc_die(); /* invalid DER: must use short len if can */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001197 }
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +01001198 der += 2; /* skip [code]+[1byte] */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001199
Denys Vlasenko2a17d1f2017-01-14 22:38:25 +01001200 if (end - der < (int)len)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001201 xfunc_die();
1202 *bodyp = der;
1203
1204 return len;
1205}
1206
1207static uint8_t *enter_der_item(uint8_t *der, uint8_t **endp)
1208{
1209 uint8_t *new_der;
1210 unsigned len = get_der_len(&new_der, der, *endp);
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01001211 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 +01001212 /* Move "end" position to cover only this item */
1213 *endp = new_der + len;
1214 return new_der;
1215}
1216
1217static uint8_t *skip_der_item(uint8_t *der, uint8_t *end)
1218{
1219 uint8_t *new_der;
1220 unsigned len = get_der_len(&new_der, der, end);
1221 /* Skip body */
1222 new_der += len;
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01001223 dbg_der("skipped der 0x%02x, next byte 0x%02x\n", der[0], new_der[0]);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001224 return new_der;
1225}
1226
Denys Vlasenko11d00962017-01-15 00:12:42 +01001227static void der_binary_to_pstm(pstm_int *pstm_n, uint8_t *der, uint8_t *end)
1228{
Denys Vlasenkof78ad092017-01-15 00:18:22 +01001229 uint8_t *bin_ptr;
1230 unsigned len = get_der_len(&bin_ptr, der, end);
Denys Vlasenko11d00962017-01-15 00:12:42 +01001231
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01001232 dbg_der("binary bytes:%u, first:0x%02x\n", len, bin_ptr[0]);
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001233 binary_to_pstm(pstm_n, bin_ptr, len);
Denys Vlasenko11d00962017-01-15 00:12:42 +01001234}
1235
1236static void find_key_in_der_cert(tls_state_t *tls, uint8_t *der, int len)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001237{
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001238/* Certificate is a DER-encoded data structure. Each DER element has a length,
1239 * which makes it easy to skip over large compound elements of any complexity
1240 * without parsing them. Example: partial decode of kernel.org certificate:
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001241 * SEQ 0x05ac/1452 bytes (Certificate): 308205ac
1242 * SEQ 0x0494/1172 bytes (tbsCertificate): 30820494
1243 * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0] 3 bytes: a003
1244 * INTEGER (version): 0201 02
1245 * INTEGER 0x11 bytes (serialNumber): 0211 00 9f85bf664b0cddafca508679501b2be4
1246 * //^^^^^^note: matrixSSL also allows [ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2] = 0x82 type
1247 * SEQ 0x0d bytes (signatureAlgo): 300d
1248 * OID 9 bytes: 0609 2a864886f70d01010b (OID_SHA256_RSA_SIG 42.134.72.134.247.13.1.1.11)
1249 * NULL: 0500
1250 * SEQ 0x5f bytes (issuer): 305f
1251 * SET 11 bytes: 310b
1252 * SEQ 9 bytes: 3009
1253 * OID 3 bytes: 0603 550406
1254 * Printable string "FR": 1302 4652
1255 * SET 14 bytes: 310e
1256 * SEQ 12 bytes: 300c
1257 * OID 3 bytes: 0603 550408
1258 * Printable string "Paris": 1305 5061726973
1259 * SET 14 bytes: 310e
1260 * SEQ 12 bytes: 300c
1261 * OID 3 bytes: 0603 550407
1262 * Printable string "Paris": 1305 5061726973
1263 * SET 14 bytes: 310e
1264 * SEQ 12 bytes: 300c
1265 * OID 3 bytes: 0603 55040a
1266 * Printable string "Gandi": 1305 47616e6469
1267 * SET 32 bytes: 3120
1268 * SEQ 30 bytes: 301e
1269 * OID 3 bytes: 0603 550403
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001270 * Printable string "Gandi Standard SSL CA 2": 1317 47616e6469205374616e646172642053534c2043412032
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001271 * SEQ 30 bytes (validity): 301e
1272 * TIME "161011000000Z": 170d 3136313031313030303030305a
1273 * TIME "191011235959Z": 170d 3139313031313233353935395a
1274 * SEQ 0x5b/91 bytes (subject): 305b //I did not decode this
1275 * 3121301f060355040b1318446f6d61696e20436f
1276 * 6e74726f6c2056616c6964617465643121301f06
1277 * 0355040b1318506f73697469766553534c204d75
1278 * 6c74692d446f6d61696e31133011060355040313
1279 * 0a6b65726e656c2e6f7267
1280 * SEQ 0x01a2/418 bytes (subjectPublicKeyInfo): 308201a2
1281 * SEQ 13 bytes (algorithm): 300d
1282 * OID 9 bytes: 0609 2a864886f70d010101 (OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1)
1283 * NULL: 0500
1284 * BITSTRING 0x018f/399 bytes (publicKey): 0382018f
1285 * ????: 00
1286 * //after the zero byte, it appears key itself uses DER encoding:
1287 * SEQ 0x018a/394 bytes: 3082018a
1288 * INTEGER 0x0181/385 bytes (modulus): 02820181
1289 * 00b1ab2fc727a3bef76780c9349bf3
1290 * ...24 more blocks of 15 bytes each...
1291 * 90e895291c6bc8693b65
1292 * INTEGER 3 bytes (exponent): 0203 010001
1293 * [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0x3] 0x01e5 bytes (X509v3 extensions): a38201e5
1294 * SEQ 0x01e1 bytes: 308201e1
1295 * ...
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001296 * Certificate is a sequence of three elements:
1297 * tbsCertificate (SEQ)
1298 * signatureAlgorithm (AlgorithmIdentifier)
1299 * signatureValue (BIT STRING)
1300 *
1301 * In turn, tbsCertificate is a sequence of:
1302 * version
1303 * serialNumber
1304 * signatureAlgo (AlgorithmIdentifier)
1305 * issuer (Name, has complex structure)
1306 * validity (Validity, SEQ of two Times)
1307 * subject (Name)
1308 * subjectPublicKeyInfo (SEQ)
1309 * ...
1310 *
1311 * subjectPublicKeyInfo is a sequence of:
1312 * algorithm (AlgorithmIdentifier)
1313 * publicKey (BIT STRING)
1314 *
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001315 * We need Certificate.tbsCertificate.subjectPublicKeyInfo.publicKey
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001316 *
1317 * Example of an ECDSA key:
1318 * SEQ 0x59 bytes (subjectPublicKeyInfo): 3059
1319 * SEQ 0x13 bytes (algorithm): 3013
1320 * OID 7 bytes: 0607 2a8648ce3d0201 (OID_ECDSA_KEY_ALG 42.134.72.206.61.2.1)
1321 * OID 8 bytes: 0608 2a8648ce3d030107 (OID_EC_prime256v1 42.134.72.206.61.3.1.7)
1322 * BITSTRING 0x42 bytes (publicKey): 0342
1323 * 0004 53af f65e 50cc 7959 7e29 0171 c75c
1324 * 7335 e07d f45b 9750 b797 3a38 aebb 2ac6
1325 * 8329 2748 e77e 41cb d482 2ce6 05ec a058
1326 * f3ab d561 2f4c d845 9ad3 7252 e3de bd3b
1327 * 9012
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001328 */
1329 uint8_t *end = der + len;
1330
1331 /* enter "Certificate" item: [der, end) will be only Cert */
1332 der = enter_der_item(der, &end);
1333
1334 /* enter "tbsCertificate" item: [der, end) will be only tbsCert */
1335 der = enter_der_item(der, &end);
1336
Ivan Abrea5cb4f902018-06-24 20:04:57 +02001337 /*
1338 * Skip version field only if it is present. For a v1 certificate, the
1339 * version field won't be present since v1 is the default value for the
1340 * version field and fields with default values should be omitted (see
1341 * RFC 5280 sections 4.1 and 4.1.2.1). If the version field is present
1342 * it will have a tag class of 2 (context-specific), bit 6 as 1
1343 * (constructed), and a tag number of 0 (see ITU-T X.690 sections 8.1.2
1344 * and 8.14).
1345 */
Denys Vlasenko084bac42018-11-05 00:18:18 +01001346 /* bits 7-6: 10 */
1347 /* bit 5: 1 */
1348 /* bits 4-0: 00000 */
1349 if (der[0] == 0xa0)
Ivan Abrea5cb4f902018-06-24 20:04:57 +02001350 der = skip_der_item(der, end); /* version */
Ivan Abrea5cb4f902018-06-24 20:04:57 +02001351
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001352 /* skip up to subjectPublicKeyInfo */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001353 der = skip_der_item(der, end); /* serialNumber */
1354 der = skip_der_item(der, end); /* signatureAlgo */
1355 der = skip_der_item(der, end); /* issuer */
1356 der = skip_der_item(der, end); /* validity */
1357 der = skip_der_item(der, end); /* subject */
1358
Denys Vlasenko11d00962017-01-15 00:12:42 +01001359 /* enter subjectPublicKeyInfo */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001360 der = enter_der_item(der, &end);
Denys Vlasenko11d00962017-01-15 00:12:42 +01001361 { /* check subjectPublicKeyInfo.algorithm */
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001362 static const uint8_t OID_RSA_KEY_ALG[] = {
Denys Vlasenko11d00962017-01-15 00:12:42 +01001363 0x30,0x0d, // SEQ 13 bytes
Denys Vlasenkode7b5bb2018-11-13 11:44:32 +01001364 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 +01001365 //0x05,0x00, // NULL
1366 };
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001367 static const uint8_t OID_ECDSA_KEY_ALG[] = {
1368 0x30,0x13, // SEQ 0x13 bytes
1369 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 +01001370 //allow any curve code for now...
1371 // 0x06,0x08, 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x07, //OID_EC_prime256v1 42.134.72.206.61.3.1.7
1372 //RFC 3279:
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001373 //42.134.72.206.61.3 is ellipticCurve
1374 //42.134.72.206.61.3.0 is c-TwoCurve
1375 //42.134.72.206.61.3.1 is primeCurve
Denys Vlasenkode7b5bb2018-11-13 11:44:32 +01001376 //42.134.72.206.61.3.1.7 is curve_secp256r1
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001377 };
1378 if (memcmp(der, OID_RSA_KEY_ALG, sizeof(OID_RSA_KEY_ALG)) == 0) {
1379 dbg("RSA key\n");
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001380 tls->flags |= GOT_CERT_RSA_KEY_ALG;
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001381 } else
1382 if (memcmp(der, OID_ECDSA_KEY_ALG, sizeof(OID_ECDSA_KEY_ALG)) == 0) {
1383 dbg("ECDSA key\n");
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001384 tls->flags |= GOT_CERT_ECDSA_KEY_ALG;
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001385 } else
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001386 bb_error_msg_and_die("not RSA or ECDSA cert");
Denys Vlasenko11d00962017-01-15 00:12:42 +01001387 }
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001388
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001389 if (tls->flags & GOT_CERT_RSA_KEY_ALG) {
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001390 /* parse RSA key: */
1391 //based on getAsnRsaPubKey(), pkcs1ParsePrivBin() is also of note
1392 /* skip subjectPublicKeyInfo.algorithm */
1393 der = skip_der_item(der, end);
1394 /* enter subjectPublicKeyInfo.publicKey */
Denys Vlasenkode7b5bb2018-11-13 11:44:32 +01001395 //die_if_not_this_der_type(der, end, 0x03); /* must be BITSTRING */
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001396 der = enter_der_item(der, &end);
1397
1398 dbg("key bytes:%u, first:0x%02x\n", (int)(end - der), der[0]);
1399 if (end - der < 14)
1400 xfunc_die();
1401 /* example format:
1402 * ignore bits: 00
1403 * SEQ 0x018a/394 bytes: 3082018a
1404 * INTEGER 0x0181/385 bytes (modulus): 02820181 XX...XXX
1405 * INTEGER 3 bytes (exponent): 0203 010001
1406 */
1407 if (*der != 0) /* "ignore bits", should be 0 */
1408 xfunc_die();
1409 der++;
1410 der = enter_der_item(der, &end); /* enter SEQ */
1411 /* memset(tls->hsd->server_rsa_pub_key, 0, sizeof(tls->hsd->server_rsa_pub_key)); - already is */
1412 der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.N, der, end); /* modulus */
1413 der = skip_der_item(der, end);
1414 der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.e, der, end); /* exponent */
1415 tls->hsd->server_rsa_pub_key.size = pstm_unsigned_bin_size(&tls->hsd->server_rsa_pub_key.N);
1416 dbg("server_rsa_pub_key.size:%d\n", tls->hsd->server_rsa_pub_key.size);
1417 }
Denys Vlasenkode7b5bb2018-11-13 11:44:32 +01001418 /* else: ECDSA key. It is not used for generating encryption keys,
1419 * it is used only to sign the EC public key (which comes in ServerKey message).
1420 * Since we do not verify cert validity, verifying signature on EC public key
1421 * wouldn't add any security. Thus, we do nothing here.
1422 */
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001423}
1424
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001425/*
1426 * TLS Handshake routines
1427 */
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001428static int tls_xread_handshake_block(tls_state_t *tls, int min_len)
Denys Vlasenkofe0588d2017-01-17 17:04:24 +01001429{
1430 struct record_hdr *xhdr;
Denys Vlasenko98066662018-02-06 13:33:00 +01001431 int len = tls_xread_record(tls, "handshake record");
Denys Vlasenkofe0588d2017-01-17 17:04:24 +01001432
1433 xhdr = (void*)tls->inbuf;
1434 if (len < min_len
1435 || xhdr->type != RECORD_TYPE_HANDSHAKE
Denys Vlasenkofe0588d2017-01-17 17:04:24 +01001436 ) {
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001437 bad_record_die(tls, "handshake record", len);
Denys Vlasenkofe0588d2017-01-17 17:04:24 +01001438 }
1439 dbg("got HANDSHAKE\n");
1440 return len;
1441}
1442
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001443static ALWAYS_INLINE void fill_handshake_record_hdr(void *buf, unsigned type, unsigned len)
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001444{
1445 struct handshake_hdr {
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001446 uint8_t type;
1447 uint8_t len24_hi, len24_mid, len24_lo;
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001448 } *h = buf;
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001449
1450 len -= 4;
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001451 h->type = type;
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001452 h->len24_hi = len >> 16;
1453 h->len24_mid = len >> 8;
1454 h->len24_lo = len & 0xff;
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001455}
1456
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001457static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001458{
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001459 static const uint8_t supported_groups[] = {
1460 0x00,0x0a, //extension_type: "supported_groups"
1461 0x00,0x04, //ext len
1462 0x00,0x02, //list len
1463 0x00,0x1d, //curve_x25519 (rfc7748)
1464 //0x00,0x17, //curve_secp256r1
1465 //0x00,0x18, //curve_secp384r1
1466 //0x00,0x19, //curve_secp521r1
1467 };
1468 //static const uint8_t signature_algorithms[] = {
1469 // 000d
1470 // 0020
1471 // 001e
1472 // 0601 0602 0603 0501 0502 0503 0401 0402 0403 0301 0302 0303 0201 0202 0203
1473 //};
1474
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001475 struct client_hello {
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001476 uint8_t type;
1477 uint8_t len24_hi, len24_mid, len24_lo;
1478 uint8_t proto_maj, proto_min;
1479 uint8_t rand32[32];
1480 uint8_t session_id_len;
1481 /* uint8_t session_id[]; */
1482 uint8_t cipherid_len16_hi, cipherid_len16_lo;
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001483 uint8_t cipherid[2 * (1 + NUM_CIPHERS)]; /* actually variable */
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001484 uint8_t comprtypes_len;
1485 uint8_t comprtypes[1]; /* actually variable */
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001486 /* Extensions (SNI shown):
1487 * hi,lo // len of all extensions
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001488 * 00,00 // extension_type: "Server Name"
1489 * 00,0e // list len (there can be more than one SNI)
1490 * 00,0c // len of 1st Server Name Indication
1491 * 00 // name type: host_name
1492 * 00,09 // name len
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001493 * "localhost" // name
1494 */
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001495// GNU Wget 1.18 to cdn.kernel.org sends these extensions:
1496// 0055
1497// 0005 0005 0100000000 - status_request
1498// 0000 0013 0011 00 000e 63646e 2e 6b65726e656c 2e 6f7267 - server_name
1499// ff01 0001 00 - renegotiation_info
1500// 0023 0000 - session_ticket
1501// 000a 0008 0006001700180019 - supported_groups
1502// 000b 0002 0100 - ec_point_formats
Denys Vlasenko98066662018-02-06 13:33:00 +01001503// 000d 0016 0014 0401 0403 0501 0503 0601 0603 0301 0303 0201 0203 - signature_algorithms
1504// wolfssl library sends this option, RFC 7627 (closes a security weakness, some servers may require it. TODO?):
1505// 0017 0000 - extended master secret
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001506 };
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001507 struct client_hello *record;
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001508 uint8_t *ptr;
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001509 int len;
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001510 int ext_len;
1511 int sni_len = sni ? strnlen(sni, 127 - 5) : 0;
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001512
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001513 ext_len = 0;
1514 /* is.gd responds with "handshake failure" to our hello if there's no supported_groups element */
1515 ext_len += sizeof(supported_groups);
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001516 if (sni_len)
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001517 ext_len += 9 + sni_len;
1518
1519 /* +2 is for "len of all extensions" 2-byte field */
1520 len = sizeof(*record) + 2 + ext_len;
Denys Vlasenkod5a04052018-11-13 11:58:53 +01001521 record = tls_get_zeroed_outbuf(tls, len);
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001522
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001523 fill_handshake_record_hdr(record, HANDSHAKE_CLIENT_HELLO, len);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001524 record->proto_maj = TLS_MAJ; /* the "requested" version of the protocol, */
1525 record->proto_min = TLS_MIN; /* can be higher than one in record headers */
1526 tls_get_random(record->rand32, sizeof(record->rand32));
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01001527 if (TLS_DEBUG_FIXED_SECRETS)
1528 memset(record->rand32, 0x11, sizeof(record->rand32));
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001529 /* record->session_id_len = 0; - already is */
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001530
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001531 /* record->cipherid_len16_hi = 0; */
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001532 record->cipherid_len16_lo = sizeof(record->cipherid);
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001533 /* RFC 5746 Renegotiation Indication Extension - some servers will refuse to work with us otherwise */
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001534 /*record->cipherid[0] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV >> 8; - zero */
1535 record->cipherid[1] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV & 0xff;
1536 if ((CIPHER_ID1 >> 8) != 0) record->cipherid[2] = CIPHER_ID1 >> 8;
1537 /*************************/ record->cipherid[3] = CIPHER_ID1 & 0xff;
1538#if CIPHER_ID2
1539 if ((CIPHER_ID2 >> 8) != 0) record->cipherid[4] = CIPHER_ID2 >> 8;
1540 /*************************/ record->cipherid[5] = CIPHER_ID2 & 0xff;
1541#endif
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001542#if CIPHER_ID3
1543 if ((CIPHER_ID3 >> 8) != 0) record->cipherid[6] = CIPHER_ID3 >> 8;
1544 /*************************/ record->cipherid[7] = CIPHER_ID3 & 0xff;
1545#endif
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001546#if CIPHER_ID4
1547 if ((CIPHER_ID4 >> 8) != 0) record->cipherid[6] = CIPHER_ID4 >> 8;
1548 /*************************/ record->cipherid[7] = CIPHER_ID4 & 0xff;
1549#endif
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001550
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001551 record->comprtypes_len = 1;
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001552 /* record->comprtypes[0] = 0; */
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001553
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001554 ptr = (void*)(record + 1);
1555 *ptr++ = ext_len >> 8;
1556 *ptr++ = ext_len;
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001557 if (sni_len) {
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001558 //ptr[0] = 0; //
1559 //ptr[1] = 0; //extension_type
1560 //ptr[2] = 0; //
1561 ptr[3] = sni_len + 5; //list len
1562 //ptr[4] = 0; //
1563 ptr[5] = sni_len + 3; //len of 1st SNI
1564 //ptr[6] = 0; //name type
1565 //ptr[7] = 0; //
1566 ptr[8] = sni_len; //name len
1567 ptr = mempcpy(&ptr[9], sni, sni_len);
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001568 }
Denys Vlasenkode7b5bb2018-11-13 11:44:32 +01001569 memcpy(ptr, supported_groups, sizeof(supported_groups));
Denys Vlasenko19e695e2017-01-20 14:27:58 +01001570
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001571 tls->hsd = xzalloc(sizeof(*tls->hsd));
1572 /* HANDSHAKE HASH: ^^^ + len if need to save saved_client_hello */
1573 memcpy(tls->hsd->client_and_server_rand32, record->rand32, sizeof(record->rand32));
1574/* HANDSHAKE HASH:
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001575 tls->hsd->saved_client_hello_size = len;
1576 memcpy(tls->hsd->saved_client_hello, record, len);
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001577 */
1578 dbg(">> CLIENT_HELLO\n");
1579 /* Can hash immediately only if we know which MAC hash to use.
1580 * So far we do know: it's sha256:
1581 */
1582 sha256_begin(&tls->hsd->handshake_hash_ctx);
1583 xwrite_and_update_handshake_hash(tls, len);
1584 /* if this would become infeasible: save tls->hsd->saved_client_hello,
1585 * use "xwrite_handshake_record(tls, len)" here,
1586 * and hash saved_client_hello later.
1587 */
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001588}
1589
1590static void get_server_hello(tls_state_t *tls)
1591{
1592 struct server_hello {
1593 struct record_hdr xhdr;
1594 uint8_t type;
1595 uint8_t len24_hi, len24_mid, len24_lo;
1596 uint8_t proto_maj, proto_min;
1597 uint8_t rand32[32]; /* first 4 bytes are unix time in BE format */
1598 uint8_t session_id_len;
1599 uint8_t session_id[32];
1600 uint8_t cipherid_hi, cipherid_lo;
1601 uint8_t comprtype;
1602 /* extensions may follow, but only those which client offered in its Hello */
1603 };
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001604
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001605 struct server_hello *hp;
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001606 uint8_t *cipherid;
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001607 unsigned cipher;
1608 int len, len24;
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001609
Denys Vlasenko5b05d9d2017-02-03 18:19:59 +01001610 len = tls_xread_handshake_block(tls, 74 - 32);
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001611
1612 hp = (void*)tls->inbuf;
1613 // 74 bytes:
1614 // 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|
1615 //SvHl len=70 maj.min unixtime^^^ 28randbytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^ slen sid32bytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cipSel comprSel
1616 if (hp->type != HANDSHAKE_SERVER_HELLO
1617 || hp->len24_hi != 0
1618 || hp->len24_mid != 0
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001619 /* hp->len24_lo checked later */
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001620 || hp->proto_maj != TLS_MAJ
1621 || hp->proto_min != TLS_MIN
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001622 ) {
Denys Vlasenkob5bf1912017-01-23 16:12:17 +01001623 bad_record_die(tls, "'server hello'", len);
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001624 }
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001625
1626 cipherid = &hp->cipherid_hi;
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001627 len24 = hp->len24_lo;
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001628 if (hp->session_id_len != 32) {
1629 if (hp->session_id_len != 0)
Denys Vlasenko5b05d9d2017-02-03 18:19:59 +01001630 bad_record_die(tls, "'server hello'", len);
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001631
1632 // session_id_len == 0: no session id
1633 // "The server
1634 // may return an empty session_id to indicate that the session will
1635 // not be cached and therefore cannot be resumed."
1636 cipherid -= 32;
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001637 len24 += 32; /* what len would be if session id would be present */
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001638 }
1639
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001640 if (len24 < 70
1641// || cipherid[0] != (CIPHER_ID >> 8)
1642// || cipherid[1] != (CIPHER_ID & 0xff)
1643// || cipherid[2] != 0 /* comprtype */
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001644 ) {
Denys Vlasenko5b05d9d2017-02-03 18:19:59 +01001645 bad_record_die(tls, "'server hello'", len);
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001646 }
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001647 dbg("<< SERVER_HELLO\n");
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001648
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001649 memcpy(tls->hsd->client_and_server_rand32 + 32, hp->rand32, sizeof(hp->rand32));
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001650
1651 tls->cipher_id = cipher = 0x100 * cipherid[0] + cipherid[1];
1652 dbg("server chose cipher %04x\n", cipher);
1653
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001654 if (cipher == TLS_RSA_WITH_AES_128_CBC_SHA
1655 || cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
1656 ) {
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001657 if (cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA)
1658 tls->flags |= NEED_EC_KEY;
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001659 tls->key_size = AES128_KEYSIZE;
1660 tls->MAC_size = SHA1_OUTSIZE;
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001661 }
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001662 else
1663 if (cipher == TLS_RSA_WITH_AES_256_CBC_SHA256) {
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001664 tls->key_size = AES256_KEYSIZE;
1665 tls->MAC_size = SHA256_OUTSIZE;
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001666 }
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001667 else { /* TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 */
1668 tls->flags |= NEED_EC_KEY | ENCRYPTION_AESGCM;
1669 tls->key_size = AES128_KEYSIZE;
1670 /* tls->MAC_size = 0; */
1671 tls->IV_size = 4;
1672 }
Denys Vlasenko89193f92017-01-24 18:08:07 +01001673 /* Handshake hash eventually destined to FINISHED record
1674 * is sha256 regardless of cipher
1675 * (at least for all ciphers defined by RFC5246).
1676 * It's not sha1 for AES_128_CBC_SHA - only MAC is sha1, not this hash.
1677 */
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001678/* HANDSHAKE HASH:
Denys Vlasenko89193f92017-01-24 18:08:07 +01001679 sha256_begin(&tls->hsd->handshake_hash_ctx);
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001680 hash_handshake(tls, ">> client hello hash:%s",
1681 tls->hsd->saved_client_hello, tls->hsd->saved_client_hello_size
1682 );
1683 hash_handshake(tls, "<< server hello hash:%s",
1684 tls->inbuf + RECHDR_LEN, len
1685 );
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001686 */
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001687}
1688
1689static void get_server_cert(tls_state_t *tls)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001690{
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001691 struct record_hdr *xhdr;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001692 uint8_t *certbuf;
1693 int len, len1;
1694
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01001695 len = tls_xread_handshake_block(tls, 10);
Denys Vlasenkoc5540d62017-01-15 02:17:03 +01001696
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001697 xhdr = (void*)tls->inbuf;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001698 certbuf = (void*)(xhdr + 1);
1699 if (certbuf[0] != HANDSHAKE_CERTIFICATE)
Denys Vlasenko98066662018-02-06 13:33:00 +01001700 bad_record_die(tls, "certificate", len);
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01001701 dbg("<< CERTIFICATE\n");
Denys Vlasenkob1003f72017-01-14 13:57:16 +01001702 // 4392 bytes:
1703 // 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...
1704 //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 +01001705 len1 = get24be(certbuf + 1);
1706 if (len1 > len - 4) tls_error_die(tls);
1707 len = len1;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001708 len1 = get24be(certbuf + 4);
1709 if (len1 > len - 3) tls_error_die(tls);
1710 len = len1;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001711 len1 = get24be(certbuf + 7);
1712 if (len1 > len - 3) tls_error_die(tls);
1713 len = len1;
1714
1715 if (len)
Denys Vlasenko11d00962017-01-15 00:12:42 +01001716 find_key_in_der_cert(tls, certbuf + 10, len);
1717}
1718
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001719/* On input, len is known to be >= 4.
1720 * The record is known to be SERVER_KEY_EXCHANGE.
1721 */
1722static void process_server_key(tls_state_t *tls, int len)
1723{
1724 struct record_hdr *xhdr;
1725 uint8_t *keybuf;
1726 int len1;
1727 uint32_t t32;
1728
1729 xhdr = (void*)tls->inbuf;
1730 keybuf = (void*)(xhdr + 1);
1731//seen from is.gd: it selects curve_x25519:
Denys Vlasenko4e46b982018-11-18 19:50:24 +01001732// 0c 00006e //SERVER_KEY_EXCHANGE, len
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001733// 03 //curve_type: named curve
1734// 001d //curve_x25519
1735//server-chosen EC point, and then signed_params
Denys Vlasenko4e46b982018-11-18 19:50:24 +01001736// (RFC 8422: "A hash of the params, with the signature
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001737// appropriate to that hash applied. The private key corresponding
1738// to the certified public key in the server's Certificate message is
1739// used for signing.")
1740//follow. Format unclear/guessed:
1741// 20 //eccPubKeyLen
1742// 25511923d73b70dd2f60e66ba2f3fda31a9c25170963c7a3a972e481dbb2835d //eccPubKey (32bytes)
1743// 0203 //hashSigAlg: 2:SHA1 (4:SHA256 5:SHA384 6:SHA512), 3:ECDSA (1:RSA)
1744// 0046 //len (16bit)
1745// 30 44 //SEQ, len
1746// 02 20 //INTEGER, len
1747// 2e18e7c2a9badd0a70cd3059a6ab114539b9f5163568911147386cd77ed7c412 //32bytes
1748//this item ^^^^^ is sometimes 33 bytes (with all container sizes also +1)
1749// 02 20 //INTEGER, len
1750// 64523d6216cb94c43c9b20e377d8c52c55be6703fd6730a155930c705eaf3af6 //32bytes
1751//same about this item ^^^^^
Denys Vlasenko4e46b982018-11-18 19:50:24 +01001752
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001753//seen from ftp.openbsd.org
Denys Vlasenko4e46b982018-11-18 19:50:24 +01001754//(which only accepts ECDHE-RSA-AESnnn-GCM-SHAnnn and ECDHE-RSA-CHACHA20-POLY1305 ciphers):
1755// 0c 000228 //SERVER_KEY_EXCHANGE, len
1756// 03 //curve_type: named curve
1757// 001d //curve_x25519
1758// 20 //eccPubKeyLen
1759// eef7a15c43b71a4c7eaa48a39369399cc4332e569ec90a83274cc92596705c1a //eccPubKey
1760// 0401 //hashSigAlg: 4:SHA256, 1:RSA
1761// 0200 //len
1762// //0x200 bytes follow
1763
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001764 /* Get and verify length */
1765 len1 = get24be(keybuf + 1);
1766 if (len1 > len - 4) tls_error_die(tls);
1767 len = len1;
1768 if (len < (1+2+1+32)) tls_error_die(tls);
1769 keybuf += 4;
1770
1771 /* So far we only support curve_x25519 */
1772 move_from_unaligned32(t32, keybuf);
1773 if (t32 != htonl(0x03001d20))
Denys Vlasenkode7b5bb2018-11-13 11:44:32 +01001774 bb_error_msg_and_die("elliptic curve is not x25519");
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001775
1776 memcpy(tls->hsd->ecc_pub_key32, keybuf + 4, 32);
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001777 tls->flags |= GOT_EC_KEY;
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001778 dbg("got eccPubKey\n");
1779}
1780
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01001781static void send_empty_client_cert(tls_state_t *tls)
1782{
1783 struct client_empty_cert {
1784 uint8_t type;
1785 uint8_t len24_hi, len24_mid, len24_lo;
1786 uint8_t cert_chain_len24_hi, cert_chain_len24_mid, cert_chain_len24_lo;
1787 };
1788 struct client_empty_cert *record;
1789
Denys Vlasenkod5a04052018-11-13 11:58:53 +01001790 record = tls_get_zeroed_outbuf(tls, sizeof(*record));
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001791 //fill_handshake_record_hdr(record, HANDSHAKE_CERTIFICATE, sizeof(*record));
1792 //record->cert_chain_len24_hi = 0;
1793 //record->cert_chain_len24_mid = 0;
1794 //record->cert_chain_len24_lo = 0;
Denys Vlasenkode7b5bb2018-11-13 11:44:32 +01001795 // same as above:
Denys Vlasenkod5a04052018-11-13 11:58:53 +01001796 record->type = HANDSHAKE_CERTIFICATE;
1797 record->len24_lo = 3;
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01001798
1799 dbg(">> CERTIFICATE\n");
1800 xwrite_and_update_handshake_hash(tls, sizeof(*record));
1801}
1802
Denys Vlasenko11d00962017-01-15 00:12:42 +01001803static void send_client_key_exchange(tls_state_t *tls)
1804{
Denys Vlasenko11d00962017-01-15 00:12:42 +01001805 struct client_key_exchange {
Denys Vlasenko11d00962017-01-15 00:12:42 +01001806 uint8_t type;
1807 uint8_t len24_hi, len24_mid, len24_lo;
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001808 uint8_t key[2 + 4 * 1024]; // size??
Denys Vlasenko11d00962017-01-15 00:12:42 +01001809 };
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001810//FIXME: better size estimate
Denys Vlasenkod5a04052018-11-13 11:58:53 +01001811 struct client_key_exchange *record = tls_get_zeroed_outbuf(tls, sizeof(*record));
Denys Vlasenko38972a82017-01-20 19:11:14 +01001812 uint8_t rsa_premaster[RSA_PREMASTER_SIZE];
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001813 uint8_t x25519_premaster[CURVE25519_KEYSIZE];
1814 uint8_t *premaster;
1815 int premaster_size;
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001816 int len;
Denys Vlasenko11d00962017-01-15 00:12:42 +01001817
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001818 if (!(tls->flags & NEED_EC_KEY)) {
1819 /* RSA */
1820 if (!(tls->flags & GOT_CERT_RSA_KEY_ALG))
1821 bb_error_msg("server cert is not RSA");
1822
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001823 tls_get_random(rsa_premaster, sizeof(rsa_premaster));
1824 if (TLS_DEBUG_FIXED_SECRETS)
1825 memset(rsa_premaster, 0x44, sizeof(rsa_premaster));
1826 // RFC 5246
1827 // "Note: The version number in the PreMasterSecret is the version
1828 // offered by the client in the ClientHello.client_version, not the
1829 // version negotiated for the connection."
1830 rsa_premaster[0] = TLS_MAJ;
1831 rsa_premaster[1] = TLS_MIN;
1832 dump_hex("premaster:%s\n", rsa_premaster, sizeof(rsa_premaster));
1833 len = psRsaEncryptPub(/*pool:*/ NULL,
1834 /* psRsaKey_t* */ &tls->hsd->server_rsa_pub_key,
1835 rsa_premaster, /*inlen:*/ sizeof(rsa_premaster),
1836 record->key + 2, sizeof(record->key) - 2,
1837 data_param_ignored
1838 );
1839 /* keylen16 exists for RSA (in TLS, not in SSL), but not for some other key types */
1840 record->key[0] = len >> 8;
1841 record->key[1] = len & 0xff;
1842 len += 2;
1843 premaster = rsa_premaster;
1844 premaster_size = sizeof(rsa_premaster);
1845 } else {
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001846 /* ECDHE */
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001847 static const uint8_t basepoint9[CURVE25519_KEYSIZE] = {9};
1848 uint8_t privkey[CURVE25519_KEYSIZE]; //[32]
1849
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001850 if (!(tls->flags & GOT_EC_KEY))
1851 bb_error_msg("server did not provide EC key");
1852
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001853 /* Generate random private key, see RFC 7748 */
1854 tls_get_random(privkey, sizeof(privkey));
1855 privkey[0] &= 0xf8;
1856 privkey[CURVE25519_KEYSIZE-1] = ((privkey[CURVE25519_KEYSIZE-1] & 0x7f) | 0x40);
1857
1858 /* Compute public key */
1859 curve25519(record->key + 1, privkey, basepoint9);
1860
1861 /* Compute premaster using peer's public key */
1862 dbg("computing x25519_premaster\n");
1863 curve25519(x25519_premaster, privkey, tls->hsd->ecc_pub_key32);
1864
1865 len = CURVE25519_KEYSIZE;
1866 record->key[0] = len;
1867 len++;
1868 premaster = x25519_premaster;
1869 premaster_size = sizeof(x25519_premaster);
1870 }
1871
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001872 record->type = HANDSHAKE_CLIENT_KEY_EXCHANGE;
Denys Vlasenkod5a04052018-11-13 11:58:53 +01001873 /* record->len24_hi = 0; - already is */
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001874 record->len24_mid = len >> 8;
1875 record->len24_lo = len & 0xff;
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001876 len += 4;
Denys Vlasenko11d00962017-01-15 00:12:42 +01001877
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01001878 dbg(">> CLIENT_KEY_EXCHANGE\n");
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01001879 xwrite_and_update_handshake_hash(tls, len);
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001880
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001881 // RFC 5246
1882 // For all key exchange methods, the same algorithm is used to convert
1883 // the pre_master_secret into the master_secret. The pre_master_secret
1884 // should be deleted from memory once the master_secret has been
1885 // computed.
1886 // master_secret = PRF(pre_master_secret, "master secret",
1887 // ClientHello.random + ServerHello.random)
1888 // [0..47];
1889 // The master secret is always exactly 48 bytes in length. The length
1890 // of the premaster secret will vary depending on key exchange method.
Denys Vlasenko89193f92017-01-24 18:08:07 +01001891 prf_hmac_sha256(/*tls,*/
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001892 tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
Denys Vlasenkobddb6542018-11-13 02:16:24 +01001893 premaster, premaster_size,
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001894 "master secret",
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001895 tls->hsd->client_and_server_rand32, sizeof(tls->hsd->client_and_server_rand32)
Denys Vlasenko936e83e2017-01-16 04:25:01 +01001896 );
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001897 dump_hex("master secret:%s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001898
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001899 // RFC 5246
1900 // 6.3. Key Calculation
1901 //
1902 // The Record Protocol requires an algorithm to generate keys required
1903 // by the current connection state (see Appendix A.6) from the security
1904 // parameters provided by the handshake protocol.
1905 //
1906 // The master secret is expanded into a sequence of secure bytes, which
1907 // is then split to a client write MAC key, a server write MAC key, a
1908 // client write encryption key, and a server write encryption key. Each
1909 // of these is generated from the byte sequence in that order. Unused
1910 // values are empty. Some AEAD ciphers may additionally require a
1911 // client write IV and a server write IV (see Section 6.2.3.3).
1912 //
1913 // When keys and MAC keys are generated, the master secret is used as an
1914 // entropy source.
1915 //
1916 // To generate the key material, compute
1917 //
1918 // key_block = PRF(SecurityParameters.master_secret,
1919 // "key expansion",
1920 // SecurityParameters.server_random +
1921 // SecurityParameters.client_random);
1922 //
1923 // until enough output has been generated. Then, the key_block is
1924 // partitioned as follows:
1925 //
1926 // client_write_MAC_key[SecurityParameters.mac_key_length]
1927 // server_write_MAC_key[SecurityParameters.mac_key_length]
1928 // client_write_key[SecurityParameters.enc_key_length]
1929 // server_write_key[SecurityParameters.enc_key_length]
1930 // client_write_IV[SecurityParameters.fixed_iv_length]
1931 // server_write_IV[SecurityParameters.fixed_iv_length]
1932 {
1933 uint8_t tmp64[64];
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +01001934
1935 /* make "server_rand32 + client_rand32" */
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001936 memcpy(&tmp64[0] , &tls->hsd->client_and_server_rand32[32], 32);
1937 memcpy(&tmp64[32], &tls->hsd->client_and_server_rand32[0] , 32);
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01001938
Denys Vlasenko89193f92017-01-24 18:08:07 +01001939 prf_hmac_sha256(/*tls,*/
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001940 tls->client_write_MAC_key, 2 * (tls->MAC_size + tls->key_size + tls->IV_size),
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +01001941 // also fills:
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001942 // server_write_MAC_key[]
1943 // client_write_key[]
1944 // server_write_key[]
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001945 // client_write_IV[]
1946 // server_write_IV[]
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001947 tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001948 "key expansion",
1949 tmp64, 64
1950 );
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001951 tls->client_write_key = tls->client_write_MAC_key + (2 * tls->MAC_size);
1952 tls->server_write_key = tls->client_write_key + tls->key_size;
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001953 tls->client_write_IV = tls->server_write_key + tls->key_size;
1954 tls->server_write_IV = tls->client_write_IV + tls->IV_size;
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001955 dump_hex("client_write_MAC_key:%s\n",
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001956 tls->client_write_MAC_key, tls->MAC_size
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001957 );
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +01001958 dump_hex("client_write_key:%s\n",
Denys Vlasenko49ecee02017-01-24 16:00:54 +01001959 tls->client_write_key, tls->key_size
Denys Vlasenkob5dfc3d2017-01-18 20:37:24 +01001960 );
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001961 dump_hex("client_write_IV:%s\n",
1962 tls->client_write_IV, tls->IV_size
1963 );
Denys Vlasenko5e4236d2018-11-23 18:02:44 +01001964
Denys Vlasenko83e5c622018-11-23 17:21:38 +01001965 aes_setkey(&tls->aes_decrypt, tls->server_write_key, tls->key_size);
Denys Vlasenko5e4236d2018-11-23 18:02:44 +01001966 aes_setkey(&tls->aes_encrypt, tls->client_write_key, tls->key_size);
1967 {
1968 uint8_t iv[AES_BLOCK_SIZE];
1969 memset(iv, 0, AES_BLOCK_SIZE);
1970 aes_encrypt_one_block(&tls->aes_encrypt, iv, tls->H);
1971 }
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001972 }
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01001973}
1974
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01001975static const uint8_t rec_CHANGE_CIPHER_SPEC[] = {
1976 RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
1977 01
1978};
1979
Denys Vlasenkoc5540d62017-01-15 02:17:03 +01001980static void send_change_cipher_spec(tls_state_t *tls)
1981{
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01001982 dbg(">> CHANGE_CIPHER_SPEC\n");
Denys Vlasenko9a647c32017-01-23 01:08:16 +01001983 xwrite(tls->ofd, rec_CHANGE_CIPHER_SPEC, sizeof(rec_CHANGE_CIPHER_SPEC));
Denys Vlasenkoc5540d62017-01-15 02:17:03 +01001984}
1985
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01001986// 7.4.9. Finished
1987// A Finished message is always sent immediately after a change
1988// cipher spec message to verify that the key exchange and
1989// authentication processes were successful. It is essential that a
1990// change cipher spec message be received between the other handshake
1991// messages and the Finished message.
1992//...
1993// The Finished message is the first one protected with the just
1994// negotiated algorithms, keys, and secrets. Recipients of Finished
1995// messages MUST verify that the contents are correct. Once a side
1996// has sent its Finished message and received and validated the
1997// Finished message from its peer, it may begin to send and receive
1998// application data over the connection.
1999//...
2000// struct {
2001// opaque verify_data[verify_data_length];
2002// } Finished;
2003//
2004// verify_data
2005// PRF(master_secret, finished_label, Hash(handshake_messages))
2006// [0..verify_data_length-1];
2007//
2008// finished_label
2009// For Finished messages sent by the client, the string
2010// "client finished". For Finished messages sent by the server,
2011// the string "server finished".
2012//
2013// Hash denotes a Hash of the handshake messages. For the PRF
2014// defined in Section 5, the Hash MUST be the Hash used as the basis
2015// for the PRF. Any cipher suite which defines a different PRF MUST
2016// also define the Hash to use in the Finished computation.
2017//
2018// In previous versions of TLS, the verify_data was always 12 octets
2019// long. In the current version of TLS, it depends on the cipher
2020// suite. Any cipher suite which does not explicitly specify
2021// verify_data_length has a verify_data_length equal to 12. This
2022// includes all existing cipher suites.
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01002023static void send_client_finished(tls_state_t *tls)
2024{
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01002025 struct finished {
Denys Vlasenko936e83e2017-01-16 04:25:01 +01002026 uint8_t type;
2027 uint8_t len24_hi, len24_mid, len24_lo;
2028 uint8_t prf_result[12];
2029 };
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002030 struct finished *record = tls_get_outbuf(tls, sizeof(*record));
Denys Vlasenko49ecee02017-01-24 16:00:54 +01002031 uint8_t handshake_hash[TLS_MAX_MAC_SIZE];
2032 unsigned len;
Denys Vlasenko936e83e2017-01-16 04:25:01 +01002033
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002034 fill_handshake_record_hdr(record, HANDSHAKE_FINISHED, sizeof(*record));
Denys Vlasenko936e83e2017-01-16 04:25:01 +01002035
Denys Vlasenko49ecee02017-01-24 16:00:54 +01002036 len = get_handshake_hash(tls, handshake_hash);
Denys Vlasenko89193f92017-01-24 18:08:07 +01002037 prf_hmac_sha256(/*tls,*/
Denys Vlasenko49ecee02017-01-24 16:00:54 +01002038 record->prf_result, sizeof(record->prf_result),
2039 tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
2040 "client finished",
2041 handshake_hash, len
Denys Vlasenko936e83e2017-01-16 04:25:01 +01002042 );
Denys Vlasenko9a647c32017-01-23 01:08:16 +01002043 dump_hex("from secret: %s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
Denys Vlasenkoe2cb3b92017-01-17 16:53:36 +01002044 dump_hex("from labelSeed: %s", "client finished", sizeof("client finished")-1);
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01002045 dump_hex("%s\n", handshake_hash, sizeof(handshake_hash));
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002046 dump_hex("=> digest: %s\n", record->prf_result, sizeof(record->prf_result));
Denys Vlasenko9a6897a2017-01-16 23:26:33 +01002047
Denys Vlasenkoc8ba23b2017-01-18 06:45:50 +01002048 dbg(">> FINISHED\n");
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002049 xwrite_encrypted(tls, sizeof(*record), RECORD_TYPE_HANDSHAKE);
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01002050}
2051
Denys Vlasenko9a647c32017-01-23 01:08:16 +01002052void FAST_FUNC tls_handshake(tls_state_t *tls, const char *sni)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002053{
2054 // Client RFC 5246 Server
2055 // (*) - optional messages, not always sent
2056 //
2057 // ClientHello ------->
2058 // ServerHello
2059 // Certificate*
2060 // ServerKeyExchange*
2061 // CertificateRequest*
2062 // <------- ServerHelloDone
2063 // Certificate*
2064 // ClientKeyExchange
2065 // CertificateVerify*
2066 // [ChangeCipherSpec]
2067 // Finished ------->
2068 // [ChangeCipherSpec]
2069 // <------- Finished
2070 // Application Data <------> Application Data
2071 int len;
Denys Vlasenko98066662018-02-06 13:33:00 +01002072 int got_cert_req;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002073
Denys Vlasenko49ecee02017-01-24 16:00:54 +01002074 send_client_hello_and_alloc_hsd(tls, sni);
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01002075 get_server_hello(tls);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002076
Denys Vlasenko38972a82017-01-20 19:11:14 +01002077 // RFC 5246
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002078 // The server MUST send a Certificate message whenever the agreed-
2079 // upon key exchange method uses certificates for authentication
2080 // (this includes all key exchange methods defined in this document
2081 // except DH_anon). This message will always immediately follow the
2082 // ServerHello message.
2083 //
2084 // IOW: in practice, Certificate *always* follows.
2085 // (for example, kernel.org does not even accept DH_anon cipher id)
Denys Vlasenko3f8ecd92017-01-15 14:16:51 +01002086 get_server_cert(tls);
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002087
Denys Vlasenkodd2577f2017-01-20 22:48:41 +01002088 len = tls_xread_handshake_block(tls, 4);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01002089 if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_SERVER_KEY_EXCHANGE) {
Denys Vlasenkob1003f72017-01-14 13:57:16 +01002090 // 459 bytes:
2091 // 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...
2092 //SvKey len=455^
Denys Vlasenko11d00962017-01-15 00:12:42 +01002093 // with TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 461 bytes:
2094 // 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 +01002095 //
2096 // RFC 8422 5.4. Server Key Exchange
2097 // This message is sent when using the ECDHE_ECDSA, ECDHE_RSA, and
2098 // ECDH_anon key exchange algorithms.
2099 // This message is used to convey the server's ephemeral ECDH public key
2100 // (and the corresponding elliptic curve domain parameters) to the
2101 // client.
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01002102 dbg("<< SERVER_KEY_EXCHANGE len:%u\n", len);
Denys Vlasenkobddb6542018-11-13 02:16:24 +01002103 dump_raw_in("<< %s\n", tls->inbuf, RECHDR_LEN + len);
Denys Vlasenko83e5c622018-11-23 17:21:38 +01002104 if (tls->flags & NEED_EC_KEY)
Denys Vlasenkobddb6542018-11-13 02:16:24 +01002105 process_server_key(tls, len);
2106
2107 // read next handshake block
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01002108 len = tls_xread_handshake_block(tls, 4);
Denys Vlasenkoc5540d62017-01-15 02:17:03 +01002109 }
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01002110
Denys Vlasenko98066662018-02-06 13:33:00 +01002111 got_cert_req = (tls->inbuf[RECHDR_LEN] == HANDSHAKE_CERTIFICATE_REQUEST);
2112 if (got_cert_req) {
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01002113 dbg("<< CERTIFICATE_REQUEST\n");
2114 // RFC 5246: "If no suitable certificate is available,
2115 // the client MUST send a certificate message containing no
2116 // certificates. That is, the certificate_list structure has a
2117 // length of zero. ...
2118 // Client certificates are sent using the Certificate structure
2119 // defined in Section 7.4.2."
2120 // (i.e. the same format as server certs)
Denys Vlasenko98066662018-02-06 13:33:00 +01002121
2122 /*send_empty_client_cert(tls); - WRONG (breaks handshake hash calc) */
2123 /* need to hash _all_ server replies first, up to ServerHelloDone */
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01002124 len = tls_xread_handshake_block(tls, 4);
2125 }
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01002126
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01002127 if (tls->inbuf[RECHDR_LEN] != HANDSHAKE_SERVER_HELLO_DONE) {
2128 bad_record_die(tls, "'server hello done'", len);
2129 }
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01002130 // 0e 000000 (len:0)
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01002131 dbg("<< SERVER_HELLO_DONE\n");
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01002132
Denys Vlasenko98066662018-02-06 13:33:00 +01002133 if (got_cert_req)
2134 send_empty_client_cert(tls);
2135
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01002136 send_client_key_exchange(tls);
2137
2138 send_change_cipher_spec(tls);
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01002139 /* from now on we should send encrypted */
2140 /* tls->write_seq64_be = 0; - already is */
2141 tls->encrypt_on_write = 1;
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01002142
2143 send_client_finished(tls);
2144
2145 /* Get CHANGE_CIPHER_SPEC */
Denys Vlasenko98066662018-02-06 13:33:00 +01002146 len = tls_xread_record(tls, "switch to encrypted traffic");
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01002147 if (len != 1 || memcmp(tls->inbuf, rec_CHANGE_CIPHER_SPEC, 6) != 0)
Denys Vlasenko1500b3a2017-01-24 17:06:10 +01002148 bad_record_die(tls, "switch to encrypted traffic", len);
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01002149 dbg("<< CHANGE_CIPHER_SPEC\n");
Denys Vlasenko83e5c622018-11-23 17:21:38 +01002150
Denys Vlasenko5d561ef2017-04-04 01:41:15 +02002151 if (CIPHER_ID1 == TLS_RSA_WITH_NULL_SHA256
2152 && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
2153 ) {
Denys Vlasenko49ecee02017-01-24 16:00:54 +01002154 tls->min_encrypted_len_on_read = tls->MAC_size;
Denys Vlasenko83e5c622018-11-23 17:21:38 +01002155 } else
2156 if (!(tls->flags & ENCRYPTION_AESGCM)) {
2157 unsigned mac_blocks = (unsigned)(tls->MAC_size + AES_BLOCK_SIZE-1) / AES_BLOCK_SIZE;
Denys Vlasenko89193f92017-01-24 18:08:07 +01002158 /* all incoming packets now should be encrypted and have
2159 * at least IV + (MAC padded to blocksize):
2160 */
Denys Vlasenko83e5c622018-11-23 17:21:38 +01002161 tls->min_encrypted_len_on_read = AES_BLOCK_SIZE + (mac_blocks * AES_BLOCK_SIZE);
2162 } else {
2163 tls->min_encrypted_len_on_read = 8 + AES_BLOCK_SIZE;
Denys Vlasenko89193f92017-01-24 18:08:07 +01002164 }
Denys Vlasenko83e5c622018-11-23 17:21:38 +01002165 dbg("min_encrypted_len_on_read: %u\n", tls->min_encrypted_len_on_read);
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01002166
2167 /* Get (encrypted) FINISHED from the server */
Denys Vlasenko98066662018-02-06 13:33:00 +01002168 len = tls_xread_record(tls, "'server finished'");
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01002169 if (len < 4 || tls->inbuf[RECHDR_LEN] != HANDSHAKE_FINISHED)
Denys Vlasenko98066662018-02-06 13:33:00 +01002170 bad_record_die(tls, "'server finished'", len);
Denys Vlasenko5d1662e2017-01-17 18:17:27 +01002171 dbg("<< FINISHED\n");
Denys Vlasenkoe69d78c2017-01-17 17:24:11 +01002172 /* application data can be sent/received */
Denys Vlasenko9a647c32017-01-23 01:08:16 +01002173
2174 /* free handshake data */
2175// if (PARANOIA)
Denys Vlasenko49ecee02017-01-24 16:00:54 +01002176// memset(tls->hsd, 0, tls->hsd->hsd_size);
Denys Vlasenko9a647c32017-01-23 01:08:16 +01002177 free(tls->hsd);
2178 tls->hsd = NULL;
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002179}
2180
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002181static void tls_xwrite(tls_state_t *tls, int len)
2182{
2183 dbg(">> DATA\n");
2184 xwrite_encrypted(tls, len, RECORD_TYPE_APPLICATION_DATA);
2185}
2186
Denys Vlasenko936e83e2017-01-16 04:25:01 +01002187// To run a test server using openssl:
Denys Vlasenko936e83e2017-01-16 04:25:01 +01002188// openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
Denys Vlasenkocccf8e72017-01-19 00:20:45 +01002189// openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1
2190//
2191// Unencryped SHA256 example:
2192// openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
2193// openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL
2194// openssl s_client -connect 127.0.0.1:4433 -debug -tls1_2 -no_tls1 -no_tls1_1 -cipher NULL-SHA256
Denys Vlasenko936e83e2017-01-16 04:25:01 +01002195
Denys Vlasenko403f2992018-02-06 15:15:08 +01002196void FAST_FUNC tls_run_copy_loop(tls_state_t *tls, unsigned flags)
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002197{
Denys Vlasenko38972a82017-01-20 19:11:14 +01002198 int inbuf_size;
2199 const int INBUF_STEP = 4 * 1024;
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01002200 struct pollfd pfds[2];
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002201
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01002202 pfds[0].fd = STDIN_FILENO;
2203 pfds[0].events = POLLIN;
2204 pfds[1].fd = tls->ifd;
2205 pfds[1].events = POLLIN;
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002206
Denys Vlasenko38972a82017-01-20 19:11:14 +01002207 inbuf_size = INBUF_STEP;
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002208 for (;;) {
2209 int nread;
2210
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01002211 if (safe_poll(pfds, 2, -1) < 0)
2212 bb_perror_msg_and_die("poll");
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002213
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01002214 if (pfds[0].revents) {
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01002215 void *buf;
2216
2217 dbg("STDIN HAS DATA\n");
Denys Vlasenko38972a82017-01-20 19:11:14 +01002218 buf = tls_get_outbuf(tls, inbuf_size);
2219 nread = safe_read(STDIN_FILENO, buf, inbuf_size);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002220 if (nread < 1) {
Denys Vlasenko38972a82017-01-20 19:11:14 +01002221 /* We'd want to do this: */
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002222 /* Close outgoing half-connection so they get EOF,
Denys Vlasenko38972a82017-01-20 19:11:14 +01002223 * but leave incoming alone so we can see response
2224 */
Denys Vlasenko9a647c32017-01-23 01:08:16 +01002225 //shutdown(tls->ofd, SHUT_WR);
Denys Vlasenko38972a82017-01-20 19:11:14 +01002226 /* But TLS has no way to encode this,
2227 * doubt it's ok to do it "raw"
2228 */
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01002229 pfds[0].fd = -1;
Denys Vlasenko39161392017-01-20 20:27:06 +01002230 tls_free_outbuf(tls); /* mem usage optimization */
Denys Vlasenko403f2992018-02-06 15:15:08 +01002231 if (flags & TLSLOOP_EXIT_ON_LOCAL_EOF)
2232 break;
Denys Vlasenko38972a82017-01-20 19:11:14 +01002233 } else {
2234 if (nread == inbuf_size) {
2235 /* TLS has per record overhead, if input comes fast,
2236 * read, encrypt and send bigger chunks
2237 */
2238 inbuf_size += INBUF_STEP;
Denys Vlasenko49ecee02017-01-24 16:00:54 +01002239 if (inbuf_size > TLS_MAX_OUTBUF)
2240 inbuf_size = TLS_MAX_OUTBUF;
Denys Vlasenko38972a82017-01-20 19:11:14 +01002241 }
2242 tls_xwrite(tls, nread);
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002243 }
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002244 }
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01002245 if (pfds[1].revents) {
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01002246 dbg("NETWORK HAS DATA\n");
Denys Vlasenko38972a82017-01-20 19:11:14 +01002247 read_record:
Denys Vlasenko98066662018-02-06 13:33:00 +01002248 nread = tls_xread_record(tls, "encrypted data");
Denys Vlasenko38972a82017-01-20 19:11:14 +01002249 if (nread < 1) {
2250 /* TLS protocol has no real concept of one-sided shutdowns:
2251 * if we get "TLS EOF" from the peer, writes will fail too
2252 */
Denys Vlasenko0ec4d082017-02-16 16:27:39 +01002253 //pfds[1].fd = -1;
Denys Vlasenko38972a82017-01-20 19:11:14 +01002254 //close(STDOUT_FILENO);
Denys Vlasenko39161392017-01-20 20:27:06 +01002255 //tls_free_inbuf(tls); /* mem usage optimization */
Denys Vlasenko38972a82017-01-20 19:11:14 +01002256 //continue;
2257 break;
2258 }
2259 if (tls->inbuf[0] != RECORD_TYPE_APPLICATION_DATA)
Denys Vlasenko98066662018-02-06 13:33:00 +01002260 bad_record_die(tls, "encrypted data", nread);
Denys Vlasenkoa0aae9f2017-01-20 14:12:10 +01002261 xwrite(STDOUT_FILENO, tls->inbuf + RECHDR_LEN, nread);
Denys Vlasenko38972a82017-01-20 19:11:14 +01002262 /* We may already have a complete next record buffered,
2263 * can process it without network reads (and possible blocking)
2264 */
2265 if (tls_has_buffered_record(tls))
2266 goto read_record;
Denys Vlasenkoabbf17a2017-01-20 03:15:09 +01002267 }
2268 }
Denys Vlasenkoceff6b02017-01-14 12:49:32 +01002269}