busybox/networking/tls.c
<<
>>
Prefs
   1/*
   2 * Copyright (C) 2017 Denys Vlasenko
   3 *
   4 * Licensed under GPLv2, see file LICENSE in this source tree.
   5 */
   6//config:config TLS
   7//config:       bool #No description makes it a hidden option
   8//config:       default n
   9//Note:
  10//Config.src also defines FEATURE_TLS_SHA1 option
  11
  12//kbuild:lib-$(CONFIG_TLS) += tls.o
  13//kbuild:lib-$(CONFIG_TLS) += tls_pstm.o
  14//kbuild:lib-$(CONFIG_TLS) += tls_pstm_montgomery_reduce.o
  15//kbuild:lib-$(CONFIG_TLS) += tls_pstm_mul_comba.o
  16//kbuild:lib-$(CONFIG_TLS) += tls_pstm_sqr_comba.o
  17//kbuild:lib-$(CONFIG_TLS) += tls_aes.o
  18//kbuild:lib-$(CONFIG_TLS) += tls_aesgcm.o
  19//kbuild:lib-$(CONFIG_TLS) += tls_rsa.o
  20//kbuild:lib-$(CONFIG_TLS) += tls_fe.o
  21
  22#include "tls.h"
  23
  24// works against "openssl s_server -cipher NULL"
  25// and against wolfssl-3.9.10-stable/examples/server/server.c:
  26#define ALLOW_RSA_NULL_SHA256  0  // for testing (does everything except encrypting)
  27
  28//Tested against kernel.org:
  29//#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA // ok, recvs SERVER_KEY_EXCHANGE *** matrixssl uses this on my box
  30//#define CIPHER_ID TLS_RSA_WITH_AES_256_CBC_SHA256 // ok, no SERVER_KEY_EXCHANGE
  31//#define CIPHER_ID TLS_DH_anon_WITH_AES_256_CBC_SHA // SSL_ALERT_HANDSHAKE_FAILURE
  32//^^^^^^^^^^^^^^^^^^^^^^^ (tested b/c this one doesn't req server certs... no luck, server refuses it)
  33//#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 // SSL_ALERT_HANDSHAKE_FAILURE
  34//#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
  35//#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 // ok, recvs SERVER_KEY_EXCHANGE
  36//#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  37//#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
  38//#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
  39//#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
  40//#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
  41//#define CIPHER_ID TLS_RSA_WITH_AES_256_GCM_SHA384 // ok, no SERVER_KEY_EXCHANGE
  42//#define CIPHER_ID TLS_RSA_WITH_AES_128_GCM_SHA256 // ok, no SERVER_KEY_EXCHANGE
  43
  44// works against wolfssl-3.9.10-stable/examples/server/server.c
  45// works for kernel.org
  46// does not work for cdn.kernel.org (e.g. downloading an actual tarball, not a web page)
  47//  getting alert 40 "handshake failure" at once
  48//  with GNU Wget 1.18, they agree on TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xC02F) cipher
  49//  fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -cipher AES256-SHA256
  50//  fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -cipher AES256-GCM-SHA384
  51//  fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -cipher AES128-SHA256
  52//  ok:   openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -cipher AES128-GCM-SHA256
  53//  ok:   openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -cipher AES128-SHA
  54//        (TLS_RSA_WITH_AES_128_CBC_SHA - in TLS 1.2 it's mandated to be always supported)
  55//#define CIPHER_ID1  TLS_RSA_WITH_AES_256_CBC_SHA256 //0x003D
  56// Works with "wget https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.9.5.tar.xz"
  57//#define CIPHER_ID2  TLS_RSA_WITH_AES_128_CBC_SHA    //0x002F
  58
  59// bug #11456:
  60// ftp.openbsd.org only supports ECDHE-RSA-AESnnn-GCM-SHAnnn or ECDHE-RSA-CHACHA20-POLY1305
  61//#define CIPHER_ID3  TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 //0xC02F
  62// host is.gd accepts only ECDHE-ECDSA-foo (the simplest which works: ECDHE-ECDSA-AES128-SHA 0xC009)
  63//#define CIPHER_ID4  TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA  //0xC009
  64
  65
  66#define TLS_DEBUG      0
  67#define TLS_DEBUG_HASH 0
  68#define TLS_DEBUG_DER  0
  69#define TLS_DEBUG_FIXED_SECRETS 0
  70#if 0
  71# define dump_raw_out(...) dump_hex(__VA_ARGS__)
  72#else
  73# define dump_raw_out(...) ((void)0)
  74#endif
  75#if 0
  76# define dump_raw_in(...) dump_hex(__VA_ARGS__)
  77#else
  78# define dump_raw_in(...) ((void)0)
  79#endif
  80
  81#if TLS_DEBUG
  82# define dbg(...) fprintf(stderr, __VA_ARGS__)
  83#else
  84# define dbg(...) ((void)0)
  85#endif
  86
  87#if TLS_DEBUG_DER
  88# define dbg_der(...) fprintf(stderr, __VA_ARGS__)
  89#else
  90# define dbg_der(...) ((void)0)
  91#endif
  92
  93
  94//TLS 1.2
  95#define TLS_MAJ 3
  96#define TLS_MIN 3
  97
  98#define RECORD_TYPE_CHANGE_CIPHER_SPEC  20 /* 0x14 */
  99#define RECORD_TYPE_ALERT               21 /* 0x15 */
 100#define RECORD_TYPE_HANDSHAKE           22 /* 0x16 */
 101#define RECORD_TYPE_APPLICATION_DATA    23 /* 0x17 */
 102
 103#define HANDSHAKE_HELLO_REQUEST         0  /* 0x00 */
 104#define HANDSHAKE_CLIENT_HELLO          1  /* 0x01 */
 105#define HANDSHAKE_SERVER_HELLO          2  /* 0x02 */
 106#define HANDSHAKE_HELLO_VERIFY_REQUEST  3  /* 0x03 */
 107#define HANDSHAKE_NEW_SESSION_TICKET    4  /* 0x04 */
 108#define HANDSHAKE_CERTIFICATE           11 /* 0x0b */
 109#define HANDSHAKE_SERVER_KEY_EXCHANGE   12 /* 0x0c */
 110#define HANDSHAKE_CERTIFICATE_REQUEST   13 /* 0x0d */
 111#define HANDSHAKE_SERVER_HELLO_DONE     14 /* 0x0e */
 112#define HANDSHAKE_CERTIFICATE_VERIFY    15 /* 0x0f */
 113#define HANDSHAKE_CLIENT_KEY_EXCHANGE   16 /* 0x10 */
 114#define HANDSHAKE_FINISHED              20 /* 0x14 */
 115
 116#define TLS_EMPTY_RENEGOTIATION_INFO_SCSV       0x00FF /* not a real cipher id... */
 117
 118#define SSL_NULL_WITH_NULL_NULL                 0x0000
 119#define SSL_RSA_WITH_NULL_MD5                   0x0001
 120#define SSL_RSA_WITH_NULL_SHA                   0x0002
 121#define SSL_RSA_WITH_RC4_128_MD5                0x0004
 122#define SSL_RSA_WITH_RC4_128_SHA                0x0005
 123#define TLS_RSA_WITH_IDEA_CBC_SHA               0x0007  /* 7 */
 124#define SSL_RSA_WITH_3DES_EDE_CBC_SHA           0x000A  /* 10 */
 125
 126#define SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA       0x0016  /* 22 */
 127#define SSL_DH_anon_WITH_RC4_128_MD5            0x0018  /* 24 */
 128#define SSL_DH_anon_WITH_3DES_EDE_CBC_SHA       0x001B  /* 27 */
 129#define TLS_RSA_WITH_AES_128_CBC_SHA            0x002F  /*SSLv3   Kx=RSA   Au=RSA   Enc=AES(128) Mac=SHA1 */
 130#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA        0x0033  /* 51 */
 131#define TLS_DH_anon_WITH_AES_128_CBC_SHA        0x0034  /* 52 */
 132#define TLS_RSA_WITH_AES_256_CBC_SHA            0x0035  /* 53 */
 133#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA        0x0039  /* 57 */
 134#define TLS_DH_anon_WITH_AES_256_CBC_SHA        0x003A  /* 58 */
 135#define TLS_RSA_WITH_NULL_SHA256                0x003B  /* 59 */
 136#define TLS_RSA_WITH_AES_128_CBC_SHA256         0x003C  /* 60 */
 137#define TLS_RSA_WITH_AES_256_CBC_SHA256         0x003D  /* 61 */
 138#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA256     0x0067  /* 103 */
 139#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA256     0x006B  /* 107 */
 140#define TLS_PSK_WITH_AES_128_CBC_SHA            0x008C  /* 140 */
 141#define TLS_PSK_WITH_AES_256_CBC_SHA            0x008D  /* 141 */
 142#define TLS_DHE_PSK_WITH_AES_128_CBC_SHA        0x0090  /* 144 */
 143#define TLS_DHE_PSK_WITH_AES_256_CBC_SHA        0x0091  /* 145 */
 144#define TLS_RSA_WITH_SEED_CBC_SHA               0x0096  /* 150 */
 145#define TLS_RSA_WITH_AES_128_GCM_SHA256         0x009C  /*TLSv1.2 Kx=RSA   Au=RSA   Enc=AESGCM(128) Mac=AEAD */
 146#define TLS_RSA_WITH_AES_256_GCM_SHA384         0x009D  /*TLSv1.2 Kx=RSA   Au=RSA   Enc=AESGCM(256) Mac=AEAD */
 147#define TLS_DHE_RSA_WITH_AES_128_GCM_SHA256     0x009E  /*TLSv1.2 Kx=DH    Au=RSA   Enc=AESGCM(128) Mac=AEAD */
 148#define TLS_DHE_RSA_WITH_AES_256_GCM_SHA384     0x009F  /*TLSv1.2 Kx=DH    Au=RSA   Enc=AESGCM(256) Mac=AEAD */
 149#define TLS_DH_anon_WITH_AES_128_GCM_SHA256     0x00A6  /* RFC 5288 */
 150#define TLS_DH_anon_WITH_AES_256_GCM_SHA384     0x00A7  /* RFC 5288 */
 151#define TLS_PSK_WITH_AES_128_CBC_SHA256         0x00AE  /* 174 */
 152#define TLS_PSK_WITH_AES_256_CBC_SHA384         0x00AF  /* 175 */
 153#define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA     0xC004  /* 49156 */
 154#define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA     0xC005  /* 49157 */
 155#define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA    0xC009  /*TLSv1   Kx=ECDH  Au=ECDSA Enc=AES(128) Mac=SHA1 */
 156#define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA    0xC00A  /*TLSv1   Kx=ECDH  Au=ECDSA Enc=AES(256) Mac=SHA1 */
 157#define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA       0xC00E  /* 49166 */
 158#define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA       0xC00F  /* 49167 */
 159#define TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA     0xC012  /* 49170 */
 160#define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA      0xC013  /*TLSv1   Kx=ECDH  Au=RSA   Enc=AES(128) Mac=SHA1 */
 161#define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA      0xC014  /*TLSv1   Kx=ECDH  Au=RSA   Enc=AES(256) Mac=SHA1 */
 162#define TLS_ECDH_anon_WITH_AES_128_CBC_SHA      0xC018  /* RFC 4492 */
 163#define TLS_ECDH_anon_WITH_AES_256_CBC_SHA      0xC019  /* RFC 4492 */
 164#define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023  /*TLSv1.2 Kx=ECDH  Au=ECDSA Enc=AES(128) Mac=SHA256 */
 165#define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 0xC024  /*TLSv1.2 Kx=ECDH  Au=ECDSA Enc=AES(256) Mac=SHA384 */
 166#define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256  0xC025  /* 49189 */
 167#define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384  0xC026  /* 49190 */
 168#define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256   0xC027  /*TLSv1.2 Kx=ECDH  Au=RSA   Enc=AES(128) Mac=SHA256 */
 169#define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384   0xC028  /*TLSv1.2 Kx=ECDH  Au=RSA   Enc=AES(256) Mac=SHA384 */
 170#define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256    0xC029  /* 49193 */
 171#define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384    0xC02A  /* 49194 */
 172/* RFC 5288 "AES Galois Counter Mode (GCM) Cipher Suites for TLS" */
 173#define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B  /*TLSv1.2 Kx=ECDH  Au=ECDSA Enc=AESGCM(128) Mac=AEAD */
 174#define TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0xC02C  /*TLSv1.2 Kx=ECDH  Au=ECDSA Enc=AESGCM(256) Mac=AEAD */
 175#define TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256  0xC02D  /* 49197 */
 176#define TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384  0xC02E  /* 49198 */
 177#define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256   0xC02F  /*TLSv1.2 Kx=ECDH  Au=RSA   Enc=AESGCM(128) Mac=AEAD */
 178#define TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384   0xC030  /*TLSv1.2 Kx=ECDH  Au=RSA   Enc=AESGCM(256) Mac=AEAD */
 179#define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256    0xC031  /* 49201 */
 180#define TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384    0xC032  /* 49202 */
 181#define TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA      0xC035
 182#define TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA      0xC036
 183#define TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256   0xC037
 184#define TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384   0xC038
 185
 186/* From http://wiki.mozilla.org/Security/Server_Side_TLS */
 187/* and 'openssl ciphers -V -stdname' */
 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 */
 190#define TLS_DHE_RSA_WITH_AES_128_CCM                  0xC09E /*TLSv1.2 Kx=DH    Au=RSA   Enc=AESCCM(128) Mac=AEAD */
 191#define TLS_DHE_RSA_WITH_AES_256_CCM                  0xC09F /*TLSv1.2 Kx=DH    Au=RSA   Enc=AESCCM(256) Mac=AEAD */
 192#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_ECDSA_WITH_AES_128_CCM              0xC0AC /*TLSv1.2 Kx=ECDH  Au=ECDSA Enc=AESCCM(128) Mac=AEAD */
 197#define TLS_ECDHE_ECDSA_WITH_AES_256_CCM              0xC0AD /*TLSv1.2 Kx=ECDH  Au=ECDSA Enc=AESCCM(256) Mac=AEAD */
 198#define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8            0xC0AE /*TLSv1.2 Kx=ECDH  Au=ECDSA Enc=AESCCM8(128) Mac=AEAD */
 199#define TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8            0xC0AF /*TLSv1.2 Kx=ECDH  Au=ECDSA Enc=AESCCM8(256) Mac=AEAD */
 200#define TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256   0xCCA8 /*TLSv1.2 Kx=ECDH  Au=RSA   Enc=CHACHA20/POLY1305(256) Mac=AEAD */
 201#define TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA9 /*TLSv1.2 Kx=ECDH  Au=ECDSA Enc=CHACHA20/POLY1305(256) Mac=AEAD */
 202#define TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256     0xCCAA /*TLSv1.2 Kx=DH    Au=RSA   Enc=CHACHA20/POLY1305(256) Mac=AEAD */
 203
 204#define TLS_AES_128_GCM_SHA256                        0x1301 /*TLSv1.3 Kx=any   Au=any   Enc=AESGCM(128) Mac=AEAD */
 205#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 */
 207#define TLS_AES_128_CCM_SHA256                        0x1304 /*TLSv1.3 Kx=any   Au=any   Enc=AESCCM(128) Mac=AEAD */
 208
 209/* Might go to libbb.h */
 210#define TLS_MAX_CRYPTBLOCK_SIZE 16
 211#define TLS_MAX_OUTBUF          (1 << 14)
 212
 213enum {
 214        SHA_INSIZE     = 64,
 215        SHA1_OUTSIZE   = 20,
 216        SHA256_OUTSIZE = 32,
 217
 218        AES128_KEYSIZE = 16,
 219        AES256_KEYSIZE = 32,
 220
 221        RSA_PREMASTER_SIZE = 48,
 222
 223        RECHDR_LEN = 5,
 224
 225        /* 8 = 3+5. 3 extra bytes result in record data being 32-bit aligned */
 226        OUTBUF_PFX = 8 + AES_BLOCK_SIZE, /* header + IV */
 227        OUTBUF_SFX = TLS_MAX_MAC_SIZE + TLS_MAX_CRYPTBLOCK_SIZE, /* MAC + padding */
 228
 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.
 263        MAX_INBUF = RECHDR_LEN + (1 << 14) + 2048,
 264
 265        /* Bits for tls->flags */
 266        NEED_EC_KEY            = 1 << 0,
 267        GOT_CERT_RSA_KEY_ALG   = 1 << 1,
 268        GOT_CERT_ECDSA_KEY_ALG = 1 << 2, // so far unused
 269        GOT_EC_KEY             = 1 << 3,
 270        ENCRYPTION_AESGCM      = 1 << 4, // else AES-SHA (or NULL-SHA if ALLOW_RSA_NULL_SHA256=1)
 271        ENCRYPT_ON_WRITE       = 1 << 5,
 272};
 273
 274struct record_hdr {
 275        uint8_t type;
 276        uint8_t proto_maj, proto_min;
 277        uint8_t len16_hi, len16_lo;
 278};
 279
 280struct tls_handshake_data {
 281        /* In bbox, md5/sha1/sha256 ctx's are the same structure */
 282        md5sha_ctx_t handshake_hash_ctx;
 283
 284        uint8_t client_and_server_rand32[2 * 32];
 285        uint8_t master_secret[48];
 286
 287//TODO: store just the DER key here, parse/use/delete it when sending client key
 288//this way it will stay key type agnostic here.
 289        psRsaKey_t server_rsa_pub_key;
 290        uint8_t ecc_pub_key32[32];
 291
 292/* HANDSHAKE HASH: */
 293        //unsigned saved_client_hello_size;
 294        //uint8_t saved_client_hello[1];
 295};
 296
 297
 298static unsigned get24be(const uint8_t *p)
 299{
 300        return 0x100*(0x100*p[0] + p[1]) + p[2];
 301}
 302
 303#if TLS_DEBUG
 304/* Nondestructively see the current hash value */
 305# if TLS_DEBUG_HASH
 306static unsigned sha_peek(md5sha_ctx_t *ctx, void *buffer)
 307{
 308        md5sha_ctx_t ctx_copy = *ctx; /* struct copy */
 309        return sha_end(&ctx_copy, buffer);
 310}
 311# endif
 312
 313static void dump_hex(const char *fmt, const void *vp, int len)
 314{
 315        char hexbuf[32 * 1024 + 4];
 316        const uint8_t *p = vp;
 317
 318        bin2hex(hexbuf, (void*)p, len)[0] = '\0';
 319        dbg(fmt, hexbuf);
 320}
 321
 322static void dump_tls_record(const void *vp, int len)
 323{
 324        const uint8_t *p = vp;
 325
 326        while (len > 0) {
 327                unsigned xhdr_len;
 328                if (len < RECHDR_LEN) {
 329                        dump_hex("< |%s|\n", p, len);
 330                        return;
 331                }
 332                xhdr_len = 0x100*p[3] + p[4];
 333                dbg("< hdr_type:%u ver:%u.%u len:%u", p[0], p[1], p[2], xhdr_len);
 334                p += RECHDR_LEN;
 335                len -= RECHDR_LEN;
 336                if (len >= 4 && p[-RECHDR_LEN] == RECORD_TYPE_HANDSHAKE) {
 337                        unsigned len24 = get24be(p + 1);
 338                        dbg(" type:%u len24:%u", p[0], len24);
 339                }
 340                if (xhdr_len > len)
 341                        xhdr_len = len;
 342                dump_hex(" |%s|\n", p, xhdr_len);
 343                p += xhdr_len;
 344                len -= xhdr_len;
 345        }
 346}
 347#else
 348# define dump_hex(...) ((void)0)
 349# define dump_tls_record(...) ((void)0)
 350#endif
 351
 352void FAST_FUNC tls_get_random(void *buf, unsigned len)
 353{
 354        if (len != open_read_close("/dev/urandom", buf, len))
 355                xfunc_die();
 356}
 357
 358static void xorbuf3(void *dst, const void *src1, const void *src2, unsigned count)
 359{
 360        uint8_t *d = dst;
 361        const uint8_t *s1 = src1;
 362        const uint8_t* s2 = src2;
 363        while (count--)
 364                *d++ = *s1++ ^ *s2++;
 365}
 366
 367void FAST_FUNC xorbuf(void *dst, const void *src, unsigned count)
 368{
 369        xorbuf3(dst, dst, src, count);
 370}
 371
 372void FAST_FUNC xorbuf_aligned_AES_BLOCK_SIZE(void *dst, const void *src)
 373{
 374        unsigned long *d = dst;
 375        const unsigned long *s = src;
 376        d[0] ^= s[0];
 377#if ULONG_MAX <= 0xffffffffffffffff
 378        d[1] ^= s[1];
 379 #if ULONG_MAX == 0xffffffff
 380        d[2] ^= s[2];
 381        d[3] ^= s[3];
 382 #endif
 383#endif
 384}
 385
 386#if !TLS_DEBUG_HASH
 387# define hash_handshake(tls, fmt, buffer, len) \
 388         hash_handshake(tls, buffer, len)
 389#endif
 390static void hash_handshake(tls_state_t *tls, const char *fmt, const void *buffer, unsigned len)
 391{
 392        md5sha_hash(&tls->hsd->handshake_hash_ctx, buffer, len);
 393#if TLS_DEBUG_HASH
 394        {
 395                uint8_t h[TLS_MAX_MAC_SIZE];
 396                dump_hex(fmt, buffer, len);
 397                dbg(" (%u bytes) ", (int)len);
 398                len = sha_peek(&tls->hsd->handshake_hash_ctx, h);
 399                if (ENABLE_FEATURE_TLS_SHA1 && len == SHA1_OUTSIZE)
 400                        dump_hex("sha1:%s\n", h, len);
 401                else
 402                if (len == SHA256_OUTSIZE)
 403                        dump_hex("sha256:%s\n", h, len);
 404                else
 405                        dump_hex("sha???:%s\n", h, len);
 406        }
 407#endif
 408}
 409
 410#if !ENABLE_FEATURE_TLS_SHA1
 411# define TLS_MAC_SIZE(tls) SHA256_OUTSIZE
 412#else
 413# define TLS_MAC_SIZE(tls) (tls)->MAC_size
 414#endif
 415
 416// RFC 2104:
 417// HMAC(key, text) based on a hash H (say, sha256) is:
 418// ipad = [0x36 x INSIZE]
 419// opad = [0x5c x INSIZE]
 420// HMAC(key, text) = H((key XOR opad) + H((key XOR ipad) + text))
 421//
 422// H(key XOR opad) and H(key XOR ipad) can be precomputed
 423// if we often need HMAC hmac with the same key.
 424//
 425// text is often given in disjoint pieces.
 426typedef struct hmac_precomputed {
 427        md5sha_ctx_t hashed_key_xor_ipad;
 428        md5sha_ctx_t hashed_key_xor_opad;
 429} hmac_precomputed_t;
 430
 431typedef void md5sha_begin_func(md5sha_ctx_t *ctx) FAST_FUNC;
 432#if !ENABLE_FEATURE_TLS_SHA1
 433#define hmac_begin(pre,key,key_size,begin) \
 434        hmac_begin(pre,key,key_size)
 435#define begin sha256_begin
 436#endif
 437static void hmac_begin(hmac_precomputed_t *pre, uint8_t *key, unsigned key_size, md5sha_begin_func *begin)
 438{
 439        uint8_t key_xor_ipad[SHA_INSIZE];
 440        uint8_t key_xor_opad[SHA_INSIZE];
 441//      uint8_t tempkey[SHA1_OUTSIZE < SHA256_OUTSIZE ? SHA256_OUTSIZE : SHA1_OUTSIZE];
 442        unsigned i;
 443
 444        // "The authentication key can be of any length up to INSIZE, the
 445        // block length of the hash function.  Applications that use keys longer
 446        // than INSIZE bytes will first hash the key using H and then use the
 447        // resultant OUTSIZE byte string as the actual key to HMAC."
 448        if (key_size > SHA_INSIZE) {
 449                bb_error_msg_and_die("HMAC key>64"); //does not happen (yet?)
 450//              md5sha_ctx_t ctx;
 451//              begin(&ctx);
 452//              md5sha_hash(&ctx, key, key_size);
 453//              key_size = sha_end(&ctx, tempkey);
 454//              //key = tempkey; - right? RIGHT? why does it work without this?
 455//              // because SHA_INSIZE is 64, but hmac() is always called with
 456//              // key_size = tls->MAC_size = SHA1/256_OUTSIZE (20 or 32),
 457//              // and prf_hmac_sha256() -> hmac_sha256() key sizes are:
 458//              // - RSA_PREMASTER_SIZE is 48
 459//              // - CURVE25519_KEYSIZE is 32
 460//              // - master_secret[] is 48
 461        }
 462
 463        for (i = 0; i < key_size; i++) {
 464                key_xor_ipad[i] = key[i] ^ 0x36;
 465                key_xor_opad[i] = key[i] ^ 0x5c;
 466        }
 467        for (; i < SHA_INSIZE; i++) {
 468                key_xor_ipad[i] = 0x36;
 469                key_xor_opad[i] = 0x5c;
 470        }
 471
 472        begin(&pre->hashed_key_xor_ipad);
 473        begin(&pre->hashed_key_xor_opad);
 474        md5sha_hash(&pre->hashed_key_xor_ipad, key_xor_ipad, SHA_INSIZE);
 475        md5sha_hash(&pre->hashed_key_xor_opad, key_xor_opad, SHA_INSIZE);
 476}
 477#undef begin
 478
 479static unsigned hmac_sha_precomputed_v(
 480                hmac_precomputed_t *pre,
 481                uint8_t *out,
 482                va_list va)
 483{
 484        uint8_t *text;
 485        unsigned len;
 486
 487        /* pre->hashed_key_xor_ipad contains unclosed "H((key XOR ipad) +" state */
 488        /* pre->hashed_key_xor_opad contains unclosed "H((key XOR opad) +" state */
 489
 490        /* calculate out = H((key XOR ipad) + text) */
 491        while ((text = va_arg(va, uint8_t*)) != NULL) {
 492                unsigned text_size = va_arg(va, unsigned);
 493                md5sha_hash(&pre->hashed_key_xor_ipad, text, text_size);
 494        }
 495        len = sha_end(&pre->hashed_key_xor_ipad, out);
 496
 497        /* out = H((key XOR opad) + out) */
 498        md5sha_hash(&pre->hashed_key_xor_opad, out, len);
 499        return sha_end(&pre->hashed_key_xor_opad, out);
 500}
 501
 502static unsigned hmac_sha_precomputed(hmac_precomputed_t *pre_init, uint8_t *out, ...)
 503{
 504        hmac_precomputed_t pre;
 505        va_list va;
 506        unsigned len;
 507
 508        va_start(va, out);
 509        pre = *pre_init; /* struct copy */
 510        len = hmac_sha_precomputed_v(&pre, out, va);
 511        va_end(va);
 512        return len;
 513}
 514
 515#if !ENABLE_FEATURE_TLS_SHA1
 516#define hmac(tls,out,key,key_size,...) \
 517        hmac(out,key,key_size, __VA_ARGS__)
 518#endif
 519static unsigned hmac(tls_state_t *tls, uint8_t *out, uint8_t *key, unsigned key_size, ...)
 520{
 521        hmac_precomputed_t pre;
 522        va_list va;
 523        unsigned len;
 524
 525        va_start(va, key_size);
 526
 527        hmac_begin(&pre, key, key_size,
 528                        (ENABLE_FEATURE_TLS_SHA1 && tls->MAC_size == SHA1_OUTSIZE)
 529                                ? sha1_begin
 530                                : sha256_begin
 531        );
 532        len = hmac_sha_precomputed_v(&pre, out, va);
 533
 534        va_end(va);
 535        return len;
 536}
 537
 538// RFC 5246:
 539// 5.  HMAC and the Pseudorandom Function
 540//...
 541// In this section, we define one PRF, based on HMAC.  This PRF with the
 542// SHA-256 hash function is used for all cipher suites defined in this
 543// document and in TLS documents published prior to this document when
 544// TLS 1.2 is negotiated.
 545// ^^^^^^^^^^^^^ IMPORTANT!
 546//               PRF uses sha256 regardless of cipher for all ciphers
 547//               defined by RFC 5246. It's not sha1 for AES_128_CBC_SHA!
 548//               However, for _SHA384 ciphers, it's sha384. See RFC 5288,5289.
 549//...
 550//    P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
 551//                           HMAC_hash(secret, A(2) + seed) +
 552//                           HMAC_hash(secret, A(3) + seed) + ...
 553// where + indicates concatenation.
 554// A() is defined as:
 555//    A(0) = seed
 556//    A(1) = HMAC_hash(secret, A(0)) = HMAC_hash(secret, seed)
 557//    A(i) = HMAC_hash(secret, A(i-1))
 558// P_hash can be iterated as many times as necessary to produce the
 559// required quantity of data.  For example, if P_SHA256 is being used to
 560// create 80 bytes of data, it will have to be iterated three times
 561// (through A(3)), creating 96 bytes of output data; the last 16 bytes
 562// of the final iteration will then be discarded, leaving 80 bytes of
 563// output data.
 564//
 565// TLS's PRF is created by applying P_hash to the secret as:
 566//
 567//    PRF(secret, label, seed) = P_<hash>(secret, label + seed)
 568//
 569// The label is an ASCII string.
 570//
 571// RFC 5288:
 572// For cipher suites ending with _SHA256, the PRF is the TLS PRF
 573// with SHA-256 as the hash function.
 574// For cipher suites ending with _SHA384, the PRF is the TLS PRF
 575// with SHA-384 as the hash function.
 576static void prf_hmac_sha256(/*tls_state_t *tls,*/
 577                uint8_t *outbuf, unsigned outbuf_size,
 578                uint8_t *secret, unsigned secret_size,
 579                const char *label,
 580                uint8_t *seed, unsigned seed_size)
 581{
 582        hmac_precomputed_t pre;
 583        uint8_t a[TLS_MAX_MAC_SIZE];
 584        uint8_t *out_p = outbuf;
 585        unsigned label_size = strlen(label);
 586        unsigned MAC_size = SHA256_OUTSIZE;
 587
 588        /* In P_hash() calculation, "seed" is "label + seed": */
 589#define SEED   label, label_size, seed, seed_size
 590#define A      a, MAC_size
 591
 592        hmac_begin(&pre, secret, secret_size, sha256_begin);
 593
 594        /* A(1) = HMAC_hash(secret, seed) */
 595        hmac_sha_precomputed(&pre, a, SEED, NULL);
 596
 597        for (;;) {
 598                /* HMAC_hash(secret, A(1) + seed) */
 599                if (outbuf_size <= MAC_size) {
 600                        /* Last, possibly incomplete, block */
 601                        /* (use a[] as temp buffer) */
 602                        hmac_sha_precomputed(&pre, a, A, SEED, NULL);
 603                        memcpy(out_p, a, outbuf_size);
 604                        return;
 605                }
 606                /* Not last block. Store directly to result buffer */
 607                hmac_sha_precomputed(&pre, out_p, A, SEED, NULL);
 608                out_p += MAC_size;
 609                outbuf_size -= MAC_size;
 610                /* A(2) = HMAC_hash(secret, A(1)) */
 611                hmac_sha_precomputed(&pre, a, A, NULL);
 612        }
 613#undef A
 614#undef SECRET
 615#undef SEED
 616}
 617
 618static void bad_record_die(tls_state_t *tls, const char *expected, int len)
 619{
 620        bb_error_msg("got bad TLS record (len:%d) while expecting %s", len, expected);
 621        if (len > 0) {
 622                uint8_t *p = tls->inbuf;
 623                if (len > 99)
 624                        len = 99; /* don't flood, a few lines should be enough */
 625                do {
 626                        fprintf(stderr, " %02x", *p++);
 627                        len--;
 628                } while (len != 0);
 629                fputc('\n', stderr);
 630        }
 631        xfunc_die();
 632}
 633
 634static void tls_error_die(tls_state_t *tls, int line)
 635{
 636        dump_tls_record(tls->inbuf, tls->ofs_to_buffered + tls->buffered_size);
 637        bb_error_msg_and_die("tls error at line %d cipher:%04x", line, tls->cipher_id);
 638}
 639#define tls_error_die(tls) tls_error_die(tls, __LINE__)
 640
 641#if 0 //UNUSED
 642static void tls_free_inbuf(tls_state_t *tls)
 643{
 644        if (tls->buffered_size == 0) {
 645                free(tls->inbuf);
 646                tls->inbuf_size = 0;
 647                tls->inbuf = NULL;
 648        }
 649}
 650#endif
 651
 652static void tls_free_outbuf(tls_state_t *tls)
 653{
 654        free(tls->outbuf);
 655        tls->outbuf_size = 0;
 656        tls->outbuf = NULL;
 657}
 658
 659static void *tls_get_outbuf(tls_state_t *tls, int len)
 660{
 661        if (len > TLS_MAX_OUTBUF)
 662                xfunc_die();
 663        len += OUTBUF_PFX + OUTBUF_SFX;
 664        if (tls->outbuf_size < len) {
 665                tls->outbuf_size = len;
 666                tls->outbuf = xrealloc(tls->outbuf, len);
 667        }
 668        return tls->outbuf + OUTBUF_PFX;
 669}
 670
 671static void *tls_get_zeroed_outbuf(tls_state_t *tls, int len)
 672{
 673        void *record = tls_get_outbuf(tls, len);
 674        memset(record, 0, len);
 675        return record;
 676}
 677
 678static void xwrite_encrypted_and_hmac_signed(tls_state_t *tls, unsigned size, unsigned type)
 679{
 680        uint8_t *buf = tls->outbuf + OUTBUF_PFX;
 681        struct record_hdr *xhdr;
 682        uint8_t padding_length;
 683
 684        xhdr = (void*)(buf - RECHDR_LEN);
 685        if (!ALLOW_RSA_NULL_SHA256 /* if "no encryption" can't be selected */
 686         || tls->cipher_id != TLS_RSA_WITH_NULL_SHA256 /* or if it wasn't selected */
 687        ) {
 688                xhdr = (void*)(buf - RECHDR_LEN - AES_BLOCK_SIZE); /* place for IV */
 689        }
 690
 691        xhdr->type = type;
 692        xhdr->proto_maj = TLS_MAJ;
 693        xhdr->proto_min = TLS_MIN;
 694        /* fake unencrypted record len for MAC calculation */
 695        xhdr->len16_hi = size >> 8;
 696        xhdr->len16_lo = size & 0xff;
 697
 698        /* Calculate MAC signature */
 699        hmac(tls, buf + size, /* result */
 700                tls->client_write_MAC_key, TLS_MAC_SIZE(tls),
 701                &tls->write_seq64_be, sizeof(tls->write_seq64_be),
 702                xhdr, RECHDR_LEN,
 703                buf, size,
 704                NULL
 705        );
 706        tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(tls->write_seq64_be));
 707
 708        size += TLS_MAC_SIZE(tls);
 709
 710        // RFC 5246:
 711        // 6.2.3.1.  Null or Standard Stream Cipher
 712        //
 713        // Stream ciphers (including BulkCipherAlgorithm.null; see Appendix A.6)
 714        // convert TLSCompressed.fragment structures to and from stream
 715        // TLSCiphertext.fragment structures.
 716        //
 717        //    stream-ciphered struct {
 718        //        opaque content[TLSCompressed.length];
 719        //        opaque MAC[SecurityParameters.mac_length];
 720        //    } GenericStreamCipher;
 721        //
 722        // The MAC is generated as:
 723        //    MAC(MAC_write_key, seq_num +
 724        //                          TLSCompressed.type +
 725        //                          TLSCompressed.version +
 726        //                          TLSCompressed.length +
 727        //                          TLSCompressed.fragment);
 728        // where "+" denotes concatenation.
 729        // seq_num
 730        //    The sequence number for this record.
 731        // MAC
 732        //    The MAC algorithm specified by SecurityParameters.mac_algorithm.
 733        //
 734        // Note that the MAC is computed before encryption.  The stream cipher
 735        // encrypts the entire block, including the MAC.
 736        //...
 737        // Appendix C.  Cipher Suite Definitions
 738        //...
 739        // MAC       Algorithm    mac_length  mac_key_length
 740        // --------  -----------  ----------  --------------
 741        // SHA       HMAC-SHA1       20            20
 742        // SHA256    HMAC-SHA256     32            32
 743        if (ALLOW_RSA_NULL_SHA256
 744         && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
 745        ) {
 746                /* No encryption, only signing */
 747                xhdr->len16_hi = size >> 8;
 748                xhdr->len16_lo = size & 0xff;
 749                dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
 750                xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
 751                dbg("wrote %u bytes (NULL crypt, SHA256 hash)\n", size);
 752                return;
 753        }
 754
 755        // 6.2.3.2.  CBC Block Cipher
 756        // For block ciphers (such as 3DES or AES), the encryption and MAC
 757        // functions convert TLSCompressed.fragment structures to and from block
 758        // TLSCiphertext.fragment structures.
 759        //    struct {
 760        //        opaque IV[SecurityParameters.record_iv_length];
 761        //        block-ciphered struct {
 762        //            opaque content[TLSCompressed.length];
 763        //            opaque MAC[SecurityParameters.mac_length];
 764        //            uint8 padding[GenericBlockCipher.padding_length];
 765        //            uint8 padding_length;
 766        //        };
 767        //    } GenericBlockCipher;
 768        //...
 769        // IV
 770        //    The Initialization Vector (IV) SHOULD be chosen at random, and
 771        //    MUST be unpredictable.  Note that in versions of TLS prior to 1.1,
 772        //    there was no IV field (...).  For block ciphers, the IV length is
 773        //    of length SecurityParameters.record_iv_length, which is equal to the
 774        //    SecurityParameters.block_size.
 775        // padding
 776        //    Padding that is added to force the length of the plaintext to be
 777        //    an integral multiple of the block cipher's block length.
 778        // padding_length
 779        //    The padding length MUST be such that the total size of the
 780        //    GenericBlockCipher structure is a multiple of the cipher's block
 781        //    length.  Legal values range from zero to 255, inclusive.
 782        //...
 783        // Appendix C.  Cipher Suite Definitions
 784        //...
 785        //                         Key      IV   Block
 786        // Cipher        Type    Material  Size  Size
 787        // ------------  ------  --------  ----  -----
 788        // AES_128_CBC   Block      16      16     16
 789        // AES_256_CBC   Block      32      16     16
 790
 791        tls_get_random(buf - AES_BLOCK_SIZE, AES_BLOCK_SIZE); /* IV */
 792        dbg("before crypt: 5 hdr + %u data + %u hash bytes\n",
 793                        size - TLS_MAC_SIZE(tls), TLS_MAC_SIZE(tls));
 794
 795        /* Fill IV and padding in outbuf */
 796        // RFC is talking nonsense:
 797        //    "Padding that is added to force the length of the plaintext to be
 798        //    an integral multiple of the block cipher's block length."
 799        // WRONG. _padding+padding_length_, not just _padding_,
 800        // pads the data.
 801        // IOW: padding_length is the last byte of padding[] array,
 802        // contrary to what RFC depicts.
 803        //
 804        // What actually happens is that there is always padding.
 805        // If you need one byte to reach BLOCKSIZE, this byte is 0x00.
 806        // If you need two bytes, they are both 0x01.
 807        // If you need three, they are 0x02,0x02,0x02. And so on.
 808        // If you need no bytes to reach BLOCKSIZE, you have to pad a full
 809        // BLOCKSIZE with bytes of value (BLOCKSIZE-1).
 810        // It's ok to have more than minimum padding, but we do minimum.
 811        padding_length = (~size) & (AES_BLOCK_SIZE - 1);
 812        do {
 813                buf[size++] = padding_length; /* padding */
 814        } while ((size & (AES_BLOCK_SIZE - 1)) != 0);
 815
 816        /* Encrypt content+MAC+padding in place */
 817        aes_cbc_encrypt(
 818                &tls->aes_encrypt, /* selects 128/256 */
 819                buf - AES_BLOCK_SIZE, /* IV */
 820                buf, size, /* plaintext */
 821                buf /* ciphertext */
 822        );
 823
 824        /* Write out */
 825        dbg("writing 5 + %u IV + %u encrypted bytes, padding_length:0x%02x\n",
 826                        AES_BLOCK_SIZE, size, padding_length);
 827        size += AES_BLOCK_SIZE;     /* + IV */
 828        xhdr->len16_hi = size >> 8;
 829        xhdr->len16_lo = size & 0xff;
 830        dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
 831        xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
 832        dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
 833}
 834
 835/* Example how GCM encryption combines nonce, aad, input and generates
 836 * "header | exp_nonce | encrypted output | tag":
 837 * nonce:0d 6a 26 31 00 00 00 00 00 00 00 01 (implicit 4 bytes (derived from master secret), then explicit 8 bytes)
 838 * aad:  00 00 00 00 00 00 00 01 17 03 03 00 1c
 839 * 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)
 840 * 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
 841 * tag:  c2 86 ce 4a 50 4a d0 aa 50 b3 76 5c 49 2a 3f 33
 842 * 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
 843 * .............................................^^ buf points here
 844 */
 845static void xwrite_encrypted_aesgcm(tls_state_t *tls, unsigned size, unsigned type)
 846{
 847#define COUNTER(v) (*(uint32_t*)(v + 12))
 848
 849        uint8_t aad[13 + 3] ALIGNED_long;   /* +3 creates [16] buffer, simplifying GHASH() */
 850        uint8_t nonce[12 + 4] ALIGNED_long; /* +4 creates space for AES block counter */
 851        uint8_t scratch[AES_BLOCK_SIZE] ALIGNED_long; //[16]
 852        uint8_t authtag[AES_BLOCK_SIZE] ALIGNED_long; //[16]
 853        uint8_t *buf;
 854        struct record_hdr *xhdr;
 855        unsigned remaining;
 856        unsigned cnt;
 857        uint64_t t64;
 858
 859        buf = tls->outbuf + OUTBUF_PFX; /* see above for the byte it points to */
 860        dump_hex("xwrite_encrypted_aesgcm plaintext:%s\n", buf, size);
 861
 862        xhdr = (void*)(buf - 8 - RECHDR_LEN);
 863        xhdr->type = type; /* do it here so that "type" param no longer used */
 864
 865        aad[8] = type;
 866        aad[9] = TLS_MAJ;
 867        aad[10] = TLS_MIN;
 868        aad[11] = size >> 8;
 869        /* set aad[12], and clear aad[13..15] */
 870        COUNTER(aad) = SWAP_LE32(size & 0xff);
 871
 872        memcpy(nonce, tls->client_write_IV, 4);
 873        t64 = tls->write_seq64_be;
 874        move_to_unaligned64(nonce + 4, t64);
 875        move_to_unaligned64(aad,       t64);
 876        move_to_unaligned64(buf - 8,   t64);
 877        /* seq64 is not used later in this func, can increment here */
 878        tls->write_seq64_be = SWAP_BE64(1 + SWAP_BE64(t64));
 879
 880        cnt = 1;
 881        remaining = size;
 882        while (remaining != 0) {
 883                unsigned n;
 884
 885                cnt++;
 886                COUNTER(nonce) = htonl(cnt); /* yes, first cnt here is 2 (!) */
 887                aes_encrypt_one_block(&tls->aes_encrypt, nonce, scratch);
 888                n = remaining > AES_BLOCK_SIZE ? AES_BLOCK_SIZE : remaining;
 889                xorbuf(buf, scratch, n);
 890                buf += n;
 891                remaining -= n;
 892        }
 893
 894        aesgcm_GHASH(tls->H, aad, /*sizeof(aad),*/ tls->outbuf + OUTBUF_PFX, size, authtag /*, sizeof(authtag)*/);
 895        COUNTER(nonce) = htonl(1);
 896        aes_encrypt_one_block(&tls->aes_encrypt, nonce, scratch);
 897        xorbuf_aligned_AES_BLOCK_SIZE(authtag, scratch);
 898
 899        memcpy(buf, authtag, sizeof(authtag));
 900
 901        /* Write out */
 902        xhdr = (void*)(tls->outbuf + OUTBUF_PFX - 8 - RECHDR_LEN);
 903        size += 8 + sizeof(authtag);
 904        /*xhdr->type = type; - already is */
 905        xhdr->proto_maj = TLS_MAJ;
 906        xhdr->proto_min = TLS_MIN;
 907        xhdr->len16_hi = size >> 8;
 908        xhdr->len16_lo = size & 0xff;
 909        size += RECHDR_LEN;
 910        dump_raw_out(">> %s\n", xhdr, size);
 911        xwrite(tls->ofd, xhdr, size);
 912        dbg("wrote %u bytes\n", size);
 913#undef COUNTER
 914}
 915
 916static void xwrite_encrypted(tls_state_t *tls, unsigned size, unsigned type)
 917{
 918        if (!(tls->flags & ENCRYPTION_AESGCM)) {
 919                xwrite_encrypted_and_hmac_signed(tls, size, type);
 920                return;
 921        }
 922        xwrite_encrypted_aesgcm(tls, size, type);
 923}
 924
 925static void xwrite_handshake_record(tls_state_t *tls, unsigned size)
 926{
 927        uint8_t *buf = tls->outbuf + OUTBUF_PFX;
 928        struct record_hdr *xhdr = (void*)(buf - RECHDR_LEN);
 929
 930        xhdr->type = RECORD_TYPE_HANDSHAKE;
 931        xhdr->proto_maj = TLS_MAJ;
 932        xhdr->proto_min = TLS_MIN;
 933        xhdr->len16_hi = size >> 8;
 934        xhdr->len16_lo = size & 0xff;
 935        dump_raw_out(">> %s\n", xhdr, RECHDR_LEN + size);
 936        xwrite(tls->ofd, xhdr, RECHDR_LEN + size);
 937        dbg("wrote %u bytes\n", (int)RECHDR_LEN + size);
 938}
 939
 940static void xwrite_and_update_handshake_hash(tls_state_t *tls, unsigned size)
 941{
 942        if (!(tls->flags & ENCRYPT_ON_WRITE)) {
 943                uint8_t *buf;
 944
 945                xwrite_handshake_record(tls, size);
 946                /* Handshake hash does not include record headers */
 947                buf = tls->outbuf + OUTBUF_PFX;
 948                hash_handshake(tls, ">> hash:%s", buf, size);
 949                return;
 950        }
 951        xwrite_encrypted(tls, size, RECORD_TYPE_HANDSHAKE);
 952}
 953
 954static int tls_has_buffered_record(tls_state_t *tls)
 955{
 956        int buffered = tls->buffered_size;
 957        struct record_hdr *xhdr;
 958        int rec_size;
 959
 960        if (buffered < RECHDR_LEN)
 961                return 0;
 962        xhdr = (void*)(tls->inbuf + tls->ofs_to_buffered);
 963        rec_size = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
 964        if (buffered < rec_size)
 965                return 0;
 966        return rec_size;
 967}
 968
 969static const char *alert_text(int code)
 970{
 971        switch (code) {
 972        case 20:  return "bad MAC";
 973        case 50:  return "decode error";
 974        case 51:  return "decrypt error";
 975        case 40:  return "handshake failure";
 976        case 112: return "unrecognized name";
 977        }
 978        return itoa(code);
 979}
 980
 981static void tls_aesgcm_decrypt(tls_state_t *tls, uint8_t *buf, int size)
 982{
 983#define COUNTER(v) (*(uint32_t*)(v + 12))
 984
 985        //uint8_t aad[13 + 3] ALIGNED_long; /* +3 creates [16] buffer, simplifying GHASH() */
 986        uint8_t nonce[12 + 4] ALIGNED_long; /* +4 creates space for AES block counter */
 987        uint8_t scratch[AES_BLOCK_SIZE] ALIGNED_long; //[16]
 988        //uint8_t authtag[AES_BLOCK_SIZE] ALIGNED_long; //[16]
 989        unsigned remaining;
 990        unsigned cnt;
 991
 992        //memcpy(aad, buf, 8);
 993        //aad[8] = type;
 994        //aad[9] = TLS_MAJ;
 995        //aad[10] = TLS_MIN;
 996        //aad[11] = size >> 8;
 997        ///* set aad[12], and clear aad[13..15] */
 998        //COUNTER(aad) = SWAP_LE32(size & 0xff);
 999
1000        memcpy(nonce,     tls->server_write_IV, 4);
1001        memcpy(nonce + 4, buf, 8);
1002
1003        cnt = 1;
1004        remaining = size;
1005        while (remaining != 0) {
1006                unsigned n;
1007
1008                cnt++;
1009                COUNTER(nonce) = htonl(cnt); /* yes, first cnt here is 2 (!) */
1010                aes_encrypt_one_block(&tls->aes_decrypt, nonce, scratch);
1011                n = remaining > AES_BLOCK_SIZE ? AES_BLOCK_SIZE : remaining;
1012                xorbuf3(buf, scratch, buf + 8, n);
1013                buf += n;
1014                remaining -= n;
1015        }
1016
1017        //aesgcm_GHASH(tls->H, aad, tls->inbuf + RECHDR_LEN, size, authtag);
1018        //COUNTER(nonce) = htonl(1);
1019        //aes_encrypt_one_block(&tls->aes_encrypt, nonce, scratch);
1020        //xorbuf_aligned_AES_BLOCK_SIZE(authtag, scratch);
1021
1022        //memcmp(buf, authtag, sizeof(authtag)) || DIE("HASH DOES NOT MATCH!");
1023#undef COUNTER
1024}
1025
1026static int tls_xread_record(tls_state_t *tls, const char *expected)
1027{
1028        struct record_hdr *xhdr;
1029        int sz;
1030        int total;
1031        int target;
1032
1033 again:
1034        dbg("ofs_to_buffered:%u buffered_size:%u\n", tls->ofs_to_buffered, tls->buffered_size);
1035        total = tls->buffered_size;
1036        if (total != 0) {
1037                memmove(tls->inbuf, tls->inbuf + tls->ofs_to_buffered, total);
1038                //dbg("<< remaining at %d [%d] ", tls->ofs_to_buffered, total);
1039                //dump_raw_in("<< %s\n", tls->inbuf, total);
1040        }
1041        errno = 0;
1042        target = MAX_INBUF;
1043        for (;;) {
1044                int rem;
1045
1046                if (total >= RECHDR_LEN && target == MAX_INBUF) {
1047                        xhdr = (void*)tls->inbuf;
1048                        target = RECHDR_LEN + (0x100 * xhdr->len16_hi + xhdr->len16_lo);
1049
1050                        if (target > MAX_INBUF /* malformed input (too long) */
1051                         || xhdr->proto_maj != TLS_MAJ
1052                         || xhdr->proto_min != TLS_MIN
1053                        ) {
1054                                sz = total < target ? total : target;
1055                                bad_record_die(tls, expected, sz);
1056                        }
1057                        dbg("xhdr type:%d ver:%d.%d len:%d\n",
1058                                xhdr->type, xhdr->proto_maj, xhdr->proto_min,
1059                                0x100 * xhdr->len16_hi + xhdr->len16_lo
1060                        );
1061                }
1062                /* if total >= target, we have a full packet (and possibly more)... */
1063                if (total - target >= 0)
1064                        break;
1065                /* input buffer is grown only as needed */
1066                rem = tls->inbuf_size - total;
1067                if (rem == 0) {
1068                        tls->inbuf_size += MAX_INBUF / 8;
1069                        if (tls->inbuf_size > MAX_INBUF)
1070                                tls->inbuf_size = MAX_INBUF;
1071                        dbg("inbuf_size:%d\n", tls->inbuf_size);
1072                        rem = tls->inbuf_size - total;
1073                        tls->inbuf = xrealloc(tls->inbuf, tls->inbuf_size);
1074                }
1075                sz = safe_read(tls->ifd, tls->inbuf + total, rem);
1076                if (sz <= 0) {
1077                        if (sz == 0 && total == 0) {
1078                                /* "Abrupt" EOF, no TLS shutdown (seen from kernel.org) */
1079                                dbg("EOF (without TLS shutdown) from peer\n");
1080                                tls->buffered_size = 0;
1081                                goto end;
1082                        }
1083                        bb_perror_msg_and_die("short read, have only %d", total);
1084                }
1085                dump_raw_in("<< %s\n", tls->inbuf + total, sz);
1086                total += sz;
1087        }
1088        tls->buffered_size = total - target;
1089        tls->ofs_to_buffered = target;
1090        //dbg("<< stashing at %d [%d] ", tls->ofs_to_buffered, tls->buffered_size);
1091        //dump_hex("<< %s\n", tls->inbuf + tls->ofs_to_buffered, tls->buffered_size);
1092
1093        sz = target - RECHDR_LEN;
1094
1095        /* Needs to be decrypted? */
1096        if (tls->min_encrypted_len_on_read != 0) {
1097                if (sz < (int)tls->min_encrypted_len_on_read)
1098                        bb_error_msg_and_die("bad encrypted len:%u", sz);
1099
1100                if (tls->flags & ENCRYPTION_AESGCM) {
1101                        /* AESGCM */
1102                        uint8_t *p = tls->inbuf + RECHDR_LEN;
1103
1104                        sz -= 8 + AES_BLOCK_SIZE; /* we will overwrite nonce, drop hash */
1105                        tls_aesgcm_decrypt(tls, p, sz);
1106                        dbg("encrypted size:%u\n", sz);
1107                } else
1108                if (tls->min_encrypted_len_on_read > TLS_MAC_SIZE(tls)) {
1109                        /* AES+SHA */
1110                        uint8_t *p = tls->inbuf + RECHDR_LEN;
1111                        int padding_len;
1112
1113                        if (sz & (AES_BLOCK_SIZE-1))
1114                                bb_error_msg_and_die("bad encrypted len:%u", sz);
1115
1116                        /* Decrypt content+MAC+padding, moving it over IV in the process */
1117                        sz -= AES_BLOCK_SIZE; /* we will overwrite IV now */
1118                        aes_cbc_decrypt(
1119                                &tls->aes_decrypt, /* selects 128/256 */
1120                                p, /* IV */
1121                                p + AES_BLOCK_SIZE, sz, /* ciphertext */
1122                                p /* plaintext */
1123                        );
1124                        padding_len = p[sz - 1];
1125                        dbg("encrypted size:%u type:0x%02x padding_length:0x%02x\n", sz, p[0], padding_len);
1126                        padding_len++;
1127                        sz -= TLS_MAC_SIZE(tls) + padding_len; /* drop MAC and padding */
1128                } else {
1129                        /* if nonzero, then it's TLS_RSA_WITH_NULL_SHA256: drop MAC */
1130                        /* else: no encryption yet on input, subtract zero = NOP */
1131                        sz -= tls->min_encrypted_len_on_read;
1132                }
1133        }
1134        if (sz < 0)
1135                bb_error_msg_and_die("encrypted data too short");
1136
1137        //dump_hex("<< %s\n", tls->inbuf, RECHDR_LEN + sz);
1138
1139        xhdr = (void*)tls->inbuf;
1140        if (xhdr->type == RECORD_TYPE_ALERT && sz >= 2) {
1141                uint8_t *p = tls->inbuf + RECHDR_LEN;
1142                dbg("ALERT size:%d level:%d description:%d\n", sz, p[0], p[1]);
1143                if (p[0] == 2) { /* fatal */
1144                        bb_error_msg_and_die("TLS %s from peer (alert code %d): %s",
1145                                "error",
1146                                p[1], alert_text(p[1])
1147                        );
1148                }
1149                if (p[0] == 1) { /* warning */
1150                        if (p[1] == 0) { /* "close_notify" warning: it's EOF */
1151                                dbg("EOF (TLS encoded) from peer\n");
1152                                sz = 0;
1153                                goto end;
1154                        }
1155//This possibly needs to be cached and shown only if
1156//a fatal alert follows
1157//                      bb_error_msg("TLS %s from peer (alert code %d): %s",
1158//                              "warning",
1159//                              p[1], alert_text(p[1])
1160//                      );
1161                        /* discard it, get next record */
1162                        goto again;
1163                }
1164                /* p[0] not 1 or 2: not defined in protocol */
1165                sz = 0;
1166                goto end;
1167        }
1168
1169        /* RFC 5246 is not saying it explicitly, but sha256 hash
1170         * in our FINISHED record must include data of incoming packets too!
1171         */
1172        if (tls->inbuf[0] == RECORD_TYPE_HANDSHAKE
1173/* HANDSHAKE HASH: */
1174        // && do_we_know_which_hash_to_use /* server_hello() might not know it in the future! */
1175        ) {
1176                hash_handshake(tls, "<< hash:%s", tls->inbuf + RECHDR_LEN, sz);
1177        }
1178 end:
1179        dbg("got block len:%u\n", sz);
1180        return sz;
1181}
1182
1183static void binary_to_pstm(pstm_int *pstm_n, uint8_t *bin_ptr, unsigned len)
1184{
1185        pstm_init_for_read_unsigned_bin(/*pool:*/ NULL, pstm_n, len);
1186        pstm_read_unsigned_bin(pstm_n, bin_ptr, len);
1187        //return bin_ptr + len;
1188}
1189
1190/*
1191 * DER parsing routines
1192 */
1193static unsigned get_der_len(uint8_t **bodyp, uint8_t *der, uint8_t *end)
1194{
1195        unsigned len, len1;
1196
1197        if (end - der < 2)
1198                xfunc_die();
1199//      if ((der[0] & 0x1f) == 0x1f) /* not single-byte item code? */
1200//              xfunc_die();
1201
1202        len = der[1]; /* maybe it's short len */
1203        if (len >= 0x80) {
1204                /* no, it's long */
1205
1206                if (len == 0x80 || end - der < (int)(len - 0x7e)) {
1207                        /* 0x80 is "0 bytes of len", invalid DER: must use short len if can */
1208                        /* need 3 or 4 bytes for 81, 82 */
1209                        xfunc_die();
1210                }
1211
1212                len1 = der[2]; /* if (len == 0x81) it's "ii 81 xx", fetch xx */
1213                if (len > 0x82) {
1214                        /* >0x82 is "3+ bytes of len", should not happen realistically */
1215                        xfunc_die();
1216                }
1217                if (len == 0x82) { /* it's "ii 82 xx yy" */
1218                        len1 = 0x100*len1 + der[3];
1219                        der += 1; /* skip [yy] */
1220                }
1221                der += 1; /* skip [xx] */
1222                len = len1;
1223//              if (len < 0x80)
1224//                      xfunc_die(); /* invalid DER: must use short len if can */
1225        }
1226        der += 2; /* skip [code]+[1byte] */
1227
1228        if (end - der < (int)len)
1229                xfunc_die();
1230        *bodyp = der;
1231
1232        return len;
1233}
1234
1235static uint8_t *enter_der_item(uint8_t *der, uint8_t **endp)
1236{
1237        uint8_t *new_der;
1238        unsigned len = get_der_len(&new_der, der, *endp);
1239        dbg_der("entered der @%p:0x%02x len:%u inner_byte @%p:0x%02x\n", der, der[0], len, new_der, new_der[0]);
1240        /* Move "end" position to cover only this item */
1241        *endp = new_der + len;
1242        return new_der;
1243}
1244
1245static uint8_t *skip_der_item(uint8_t *der, uint8_t *end)
1246{
1247        uint8_t *new_der;
1248        unsigned len = get_der_len(&new_der, der, end);
1249        /* Skip body */
1250        new_der += len;
1251        dbg_der("skipped der 0x%02x, next byte 0x%02x\n", der[0], new_der[0]);
1252        return new_der;
1253}
1254
1255static void der_binary_to_pstm(pstm_int *pstm_n, uint8_t *der, uint8_t *end)
1256{
1257        uint8_t *bin_ptr;
1258        unsigned len = get_der_len(&bin_ptr, der, end);
1259
1260        dbg_der("binary bytes:%u, first:0x%02x\n", len, bin_ptr[0]);
1261        binary_to_pstm(pstm_n, bin_ptr, len);
1262}
1263
1264static void find_key_in_der_cert(tls_state_t *tls, uint8_t *der, int len)
1265{
1266/* Certificate is a DER-encoded data structure. Each DER element has a length,
1267 * which makes it easy to skip over large compound elements of any complexity
1268 * without parsing them. Example: partial decode of kernel.org certificate:
1269 *  SEQ 0x05ac/1452 bytes (Certificate): 308205ac
1270 *    SEQ 0x0494/1172 bytes (tbsCertificate): 30820494
1271 *      [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0] 3 bytes: a003
1272 *        INTEGER (version): 0201 02
1273 *      INTEGER 0x11 bytes (serialNumber): 0211 00 9f85bf664b0cddafca508679501b2be4
1274 *      //^^^^^^note: matrixSSL also allows [ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2] = 0x82 type
1275 *      SEQ 0x0d bytes (signatureAlgo): 300d
1276 *        OID 9 bytes: 0609 2a864886f70d01010b (OID_SHA256_RSA_SIG 42.134.72.134.247.13.1.1.11)
1277 *        NULL: 0500
1278 *      SEQ 0x5f bytes (issuer): 305f
1279 *        SET 11 bytes: 310b
1280 *          SEQ 9 bytes: 3009
1281 *            OID 3 bytes: 0603 550406
1282 *            Printable string "FR": 1302 4652
1283 *        SET 14 bytes: 310e
1284 *          SEQ 12 bytes: 300c
1285 *            OID 3 bytes: 0603 550408
1286 *            Printable string "Paris": 1305 5061726973
1287 *        SET 14 bytes: 310e
1288 *          SEQ 12 bytes: 300c
1289 *            OID 3 bytes: 0603 550407
1290 *            Printable string "Paris": 1305 5061726973
1291 *        SET 14 bytes: 310e
1292 *          SEQ 12 bytes: 300c
1293 *            OID 3 bytes: 0603 55040a
1294 *            Printable string "Gandi": 1305 47616e6469
1295 *        SET 32 bytes: 3120
1296 *          SEQ 30 bytes: 301e
1297 *            OID 3 bytes: 0603 550403
1298 *            Printable string "Gandi Standard SSL CA 2": 1317 47616e6469205374616e646172642053534c2043412032
1299 *      SEQ 30 bytes (validity): 301e
1300 *        TIME "161011000000Z": 170d 3136313031313030303030305a
1301 *        TIME "191011235959Z": 170d 3139313031313233353935395a
1302 *      SEQ 0x5b/91 bytes (subject): 305b //I did not decode this
1303 *          3121301f060355040b1318446f6d61696e20436f
1304 *          6e74726f6c2056616c6964617465643121301f06
1305 *          0355040b1318506f73697469766553534c204d75
1306 *          6c74692d446f6d61696e31133011060355040313
1307 *          0a6b65726e656c2e6f7267
1308 *      SEQ 0x01a2/418 bytes (subjectPublicKeyInfo): 308201a2
1309 *        SEQ 13 bytes (algorithm): 300d
1310 *          OID 9 bytes: 0609 2a864886f70d010101 (OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1)
1311 *          NULL: 0500
1312 *        BITSTRING 0x018f/399 bytes (publicKey): 0382018f
1313 *          ????: 00
1314 *          //after the zero byte, it appears key itself uses DER encoding:
1315 *          SEQ 0x018a/394 bytes: 3082018a
1316 *            INTEGER 0x0181/385 bytes (modulus): 02820181
1317 *                  00b1ab2fc727a3bef76780c9349bf3
1318 *                  ...24 more blocks of 15 bytes each...
1319 *                  90e895291c6bc8693b65
1320 *            INTEGER 3 bytes (exponent): 0203 010001
1321 *      [ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0x3] 0x01e5 bytes (X509v3 extensions): a38201e5
1322 *        SEQ 0x01e1 bytes: 308201e1
1323 *        ...
1324 * Certificate is a sequence of three elements:
1325 *      tbsCertificate (SEQ)
1326 *      signatureAlgorithm (AlgorithmIdentifier)
1327 *      signatureValue (BIT STRING)
1328 *
1329 * In turn, tbsCertificate is a sequence of:
1330 *      version
1331 *      serialNumber
1332 *      signatureAlgo (AlgorithmIdentifier)
1333 *      issuer (Name, has complex structure)
1334 *      validity (Validity, SEQ of two Times)
1335 *      subject (Name)
1336 *      subjectPublicKeyInfo (SEQ)
1337 *      ...
1338 *
1339 * subjectPublicKeyInfo is a sequence of:
1340 *      algorithm (AlgorithmIdentifier)
1341 *      publicKey (BIT STRING)
1342 *
1343 * We need Certificate.tbsCertificate.subjectPublicKeyInfo.publicKey
1344 *
1345 * Example of an ECDSA key:
1346 *      SEQ 0x59 bytes (subjectPublicKeyInfo): 3059
1347 *        SEQ 0x13 bytes (algorithm): 3013
1348 *          OID 7 bytes: 0607 2a8648ce3d0201   (OID_ECDSA_KEY_ALG 42.134.72.206.61.2.1)
1349 *          OID 8 bytes: 0608 2a8648ce3d030107 (OID_EC_prime256v1 42.134.72.206.61.3.1.7)
1350 *        BITSTRING 0x42 bytes (publicKey): 0342
1351 *          0004 53af f65e 50cc 7959 7e29 0171 c75c
1352 *          7335 e07d f45b 9750 b797 3a38 aebb 2ac6
1353 *          8329 2748 e77e 41cb d482 2ce6 05ec a058
1354 *          f3ab d561 2f4c d845 9ad3 7252 e3de bd3b
1355 *          9012
1356 */
1357        uint8_t *end = der + len;
1358
1359        /* enter "Certificate" item: [der, end) will be only Cert */
1360        der = enter_der_item(der, &end);
1361
1362        /* enter "tbsCertificate" item: [der, end) will be only tbsCert */
1363        der = enter_der_item(der, &end);
1364
1365        /*
1366         * Skip version field only if it is present. For a v1 certificate, the
1367         * version field won't be present since v1 is the default value for the
1368         * version field and fields with default values should be omitted (see
1369         * RFC 5280 sections 4.1 and 4.1.2.1). If the version field is present
1370         * it will have a tag class of 2 (context-specific), bit 6 as 1
1371         * (constructed), and a tag number of 0 (see ITU-T X.690 sections 8.1.2
1372         * and 8.14).
1373         */
1374        /* bits 7-6: 10 */
1375        /* bit 5: 1 */
1376        /* bits 4-0: 00000 */
1377        if (der[0] == 0xa0)
1378                der = skip_der_item(der, end); /* version */
1379
1380        /* skip up to subjectPublicKeyInfo */
1381        der = skip_der_item(der, end); /* serialNumber */
1382        der = skip_der_item(der, end); /* signatureAlgo */
1383        der = skip_der_item(der, end); /* issuer */
1384        der = skip_der_item(der, end); /* validity */
1385        der = skip_der_item(der, end); /* subject */
1386
1387        /* enter subjectPublicKeyInfo */
1388        der = enter_der_item(der, &end);
1389        { /* check subjectPublicKeyInfo.algorithm */
1390                static const uint8_t OID_RSA_KEY_ALG[] ALIGN1 = {
1391                        0x30,0x0d, // SEQ 13 bytes
1392                        0x06,0x09, 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01, //OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1
1393                        //0x05,0x00, // NULL
1394                };
1395                static const uint8_t OID_ECDSA_KEY_ALG[] ALIGN1 = {
1396                        0x30,0x13, // SEQ 0x13 bytes
1397                        0x06,0x07, 0x2a,0x86,0x48,0xce,0x3d,0x02,0x01,      //OID_ECDSA_KEY_ALG 42.134.72.206.61.2.1
1398                //allow any curve code for now...
1399                //      0x06,0x08, 0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x07, //OID_EC_prime256v1 42.134.72.206.61.3.1.7
1400                        //RFC 3279:
1401                        //42.134.72.206.61.3     is ellipticCurve
1402                        //42.134.72.206.61.3.0   is c-TwoCurve
1403                        //42.134.72.206.61.3.1   is primeCurve
1404                        //42.134.72.206.61.3.1.7 is curve_secp256r1
1405                };
1406                if (memcmp(der, OID_RSA_KEY_ALG, sizeof(OID_RSA_KEY_ALG)) == 0) {
1407                        dbg("RSA key\n");
1408                        tls->flags |= GOT_CERT_RSA_KEY_ALG;
1409                } else
1410                if (memcmp(der, OID_ECDSA_KEY_ALG, sizeof(OID_ECDSA_KEY_ALG)) == 0) {
1411                        dbg("ECDSA key\n");
1412                        //UNUSED: tls->flags |= GOT_CERT_ECDSA_KEY_ALG;
1413                } else
1414                        bb_error_msg_and_die("not RSA or ECDSA cert");
1415        }
1416
1417        if (tls->flags & GOT_CERT_RSA_KEY_ALG) {
1418                /* parse RSA key: */
1419        //based on getAsnRsaPubKey(), pkcs1ParsePrivBin() is also of note
1420                /* skip subjectPublicKeyInfo.algorithm */
1421                der = skip_der_item(der, end);
1422                /* enter subjectPublicKeyInfo.publicKey */
1423                //die_if_not_this_der_type(der, end, 0x03); /* must be BITSTRING */
1424                der = enter_der_item(der, &end);
1425
1426                dbg("key bytes:%u, first:0x%02x\n", (int)(end - der), der[0]);
1427                if (end - der < 14)
1428                        xfunc_die();
1429                /* example format:
1430                 * ignore bits: 00
1431                 * SEQ 0x018a/394 bytes: 3082018a
1432                 *   INTEGER 0x0181/385 bytes (modulus): 02820181 XX...XXX
1433                 *   INTEGER 3 bytes (exponent): 0203 010001
1434                 */
1435                if (*der != 0) /* "ignore bits", should be 0 */
1436                        xfunc_die();
1437                der++;
1438                der = enter_der_item(der, &end); /* enter SEQ */
1439                /* memset(tls->hsd->server_rsa_pub_key, 0, sizeof(tls->hsd->server_rsa_pub_key)); - already is */
1440                der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.N, der, end); /* modulus */
1441                der = skip_der_item(der, end);
1442                der_binary_to_pstm(&tls->hsd->server_rsa_pub_key.e, der, end); /* exponent */
1443                tls->hsd->server_rsa_pub_key.size = pstm_unsigned_bin_size(&tls->hsd->server_rsa_pub_key.N);
1444                dbg("server_rsa_pub_key.size:%d\n", tls->hsd->server_rsa_pub_key.size);
1445        }
1446        /* else: ECDSA key. It is not used for generating encryption keys,
1447         * it is used only to sign the EC public key (which comes in ServerKey message).
1448         * Since we do not verify cert validity, verifying signature on EC public key
1449         * wouldn't add any security. Thus, we do nothing here.
1450         */
1451}
1452
1453/*
1454 * TLS Handshake routines
1455 */
1456static int tls_xread_handshake_block(tls_state_t *tls, int min_len)
1457{
1458        struct record_hdr *xhdr;
1459        int len = tls_xread_record(tls, "handshake record");
1460
1461        xhdr = (void*)tls->inbuf;
1462        if (len < min_len
1463         || xhdr->type != RECORD_TYPE_HANDSHAKE
1464        ) {
1465                bad_record_die(tls, "handshake record", len);
1466        }
1467        dbg("got HANDSHAKE\n");
1468        return len;
1469}
1470
1471static ALWAYS_INLINE void fill_handshake_record_hdr(void *buf, unsigned type, unsigned len)
1472{
1473        struct handshake_hdr {
1474                uint8_t type;
1475                uint8_t len24_hi, len24_mid, len24_lo;
1476        } *h = buf;
1477
1478        len -= 4;
1479        h->type = type;
1480        h->len24_hi  = len >> 16;
1481        h->len24_mid = len >> 8;
1482        h->len24_lo  = len & 0xff;
1483}
1484
1485static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
1486{
1487#define NUM_CIPHERS (7 + 6 * ENABLE_FEATURE_TLS_SHA1 + ALLOW_RSA_NULL_SHA256)
1488        static const uint8_t ciphers[] = {
1489                0x00,2 + NUM_CIPHERS*2, //len16_be
1490                0x00,0xFF, //not a cipher - TLS_EMPTY_RENEGOTIATION_INFO_SCSV
1491                /* ^^^^^^ RFC 5746 Renegotiation Indication Extension - some servers will refuse to work with us otherwise */
1492#if ENABLE_FEATURE_TLS_SHA1
1493                0xC0,0x09, // 1 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA - ok: wget https://is.gd/
1494                0xC0,0x0A, // 2 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA - ok: wget https://is.gd/
1495                0xC0,0x13, // 3 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA
1496                0xC0,0x14, // 4 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES256-SHA (might fail with older openssl)
1497        //      0xC0,0x18, //   TLS_ECDH_anon_WITH_AES_128_CBC_SHA
1498        //      0xC0,0x19, //   TLS_ECDH_anon_WITH_AES_256_CBC_SHA
1499#endif
1500                0xC0,0x23, // 5 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 - ok: wget https://is.gd/
1501        //      0xC0,0x24, //   TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
1502                0xC0,0x27, // 6 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA256
1503        //      0xC0,0x28, //   TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
1504                0xC0,0x2B, // 7 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - ok: wget https://is.gd/
1505        //      0xC0,0x2C, //   TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - wget https://is.gd/: "TLS error from peer (alert code 20): bad MAC"
1506//TODO: GCM_SHA384 ciphers can be supported, only need sha384-based PRF?
1507                0xC0,0x2F, // 8 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-GCM-SHA256
1508        //      0xC0,0x30, //   TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher ECDHE-RSA-AES256-GCM-SHA384: "decryption failed or bad record mac"
1509        //possibly these too:
1510#if ENABLE_FEATURE_TLS_SHA1
1511        //      0xC0,0x35, //   TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
1512        //      0xC0,0x36, //   TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA
1513#endif
1514        //      0xC0,0x37, //   TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
1515        //      0xC0,0x38, //   TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
1516#if ENABLE_FEATURE_TLS_SHA1
1517                0x00,0x2F, // 9 TLS_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher AES128-SHA
1518                0x00,0x35, //10 TLS_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher AES256-SHA
1519#endif
1520                0x00,0x3C, //11 TLS_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher AES128-SHA256
1521                0x00,0x3D, //12 TLS_RSA_WITH_AES_256_CBC_SHA256 - ok: openssl s_server ... -cipher AES256-SHA256
1522                0x00,0x9C, //13 TLS_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher AES128-GCM-SHA256
1523        //      0x00,0x9D, //   TLS_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher AES256-GCM-SHA384: "decryption failed or bad record mac"
1524#if ALLOW_RSA_NULL_SHA256
1525                0x00,0x3B, //   TLS_RSA_WITH_NULL_SHA256
1526#endif
1527                0x01,0x00, //not a cipher - comprtypes_len, comprtype
1528        };
1529        static const uint8_t supported_groups[] = {
1530                0x00,0x0a, //extension_type: "supported_groups"
1531                0x00,0x04, //ext len
1532                0x00,0x02, //list len
1533                0x00,0x1d, //curve_x25519 (RFC 7748)
1534                //0x00,0x1e, //curve_x448 (RFC 7748)
1535                //0x00,0x17, //curve_secp256r1
1536                //0x00,0x18, //curve_secp384r1
1537                //0x00,0x19, //curve_secp521r1
1538//TODO: implement secp256r1 (at least): dl.fedoraproject.org immediately aborts
1539//if only x25519/x448 are advertised, seems to support only secpNNNr1 curves:
1540// openssl s_client -connect dl.fedoraproject.org:443 -debug -tls1_2 -cipher ECDHE-RSA-AES128-GCM-SHA256
1541//Peer signing digest: SHA512
1542//Peer signature type: RSA
1543//Server Temp Key: ECDH, P-256, 256 bits
1544//TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256
1545        };
1546        //static const uint8_t signature_algorithms[] = {
1547        //      000d
1548        //      0020
1549        //      001e
1550        //      0601 0602 0603 0501 0502 0503 0401 0402 0403 0301 0302 0303 0201 0202 0203
1551        //};
1552
1553        struct client_hello {
1554                uint8_t type;
1555                uint8_t len24_hi, len24_mid, len24_lo;
1556                uint8_t proto_maj, proto_min;
1557                uint8_t rand32[32];
1558                uint8_t session_id_len;
1559                /* uint8_t session_id[]; */
1560                uint8_t cipherid_len16_hi, cipherid_len16_lo;
1561                uint8_t cipherid[2 + NUM_CIPHERS*2]; /* actually variable */
1562                uint8_t comprtypes_len;
1563                uint8_t comprtypes[1]; /* actually variable */
1564                /* Extensions (SNI shown):
1565                 * hi,lo // len of all extensions
1566                 *   00,00 // extension_type: "Server Name"
1567                 *   00,0e // list len (there can be more than one SNI)
1568                 *     00,0c // len of 1st Server Name Indication
1569                 *       00    // name type: host_name
1570                 *       00,09   // name len
1571                 *       "localhost" // name
1572                 */
1573// GNU Wget 1.18 to cdn.kernel.org sends these extensions:
1574// 0055
1575//   0005 0005 0100000000 - status_request
1576//   0000 0013 0011 00 000e 63646e 2e 6b65726e656c 2e 6f7267 - server_name
1577//   ff01 0001 00 - renegotiation_info
1578//   0023 0000 - session_ticket
1579//   000a 0008 0006001700180019 - supported_groups
1580//   000b 0002 0100 - ec_point_formats
1581//   000d 0016 0014 0401 0403 0501 0503 0601 0603 0301 0303 0201 0203 - signature_algorithms
1582// wolfssl library sends this option, RFC 7627 (closes a security weakness, some servers may require it. TODO?):
1583//   0017 0000 - extended master secret
1584        };
1585        struct client_hello *record;
1586        uint8_t *ptr;
1587        int len;
1588        int ext_len;
1589        int sni_len = sni ? strnlen(sni, 127 - 5) : 0;
1590
1591        ext_len = 0;
1592        /* is.gd responds with "handshake failure" to our hello if there's no supported_groups element */
1593        ext_len += sizeof(supported_groups);
1594        if (sni_len)
1595                ext_len += 9 + sni_len;
1596
1597        /* +2 is for "len of all extensions" 2-byte field */
1598        len = sizeof(*record) + 2 + ext_len;
1599        record = tls_get_zeroed_outbuf(tls, len);
1600
1601        fill_handshake_record_hdr(record, HANDSHAKE_CLIENT_HELLO, len);
1602        record->proto_maj = TLS_MAJ;    /* the "requested" version of the protocol, */
1603        record->proto_min = TLS_MIN;    /* can be higher than one in record headers */
1604        tls_get_random(record->rand32, sizeof(record->rand32));
1605        if (TLS_DEBUG_FIXED_SECRETS)
1606                memset(record->rand32, 0x11, sizeof(record->rand32));
1607        /* record->session_id_len = 0; - already is */
1608
1609        BUILD_BUG_ON(sizeof(ciphers) != 2 + 2 + NUM_CIPHERS*2 + 2);
1610        memcpy(&record->cipherid_len16_hi, ciphers, sizeof(ciphers));
1611
1612        ptr = (void*)(record + 1);
1613        *ptr++ = ext_len >> 8;
1614        *ptr++ = ext_len;
1615        if (sni_len) {
1616                //ptr[0] = 0;             //
1617                //ptr[1] = 0;             //extension_type
1618                //ptr[2] = 0;         //
1619                ptr[3] = sni_len + 5; //list len
1620                //ptr[4] = 0;             //
1621                ptr[5] = sni_len + 3;     //len of 1st SNI
1622                //ptr[6] = 0;         //name type
1623                //ptr[7] = 0;             //
1624                ptr[8] = sni_len;         //name len
1625                ptr = mempcpy(&ptr[9], sni, sni_len);
1626        }
1627        memcpy(ptr, supported_groups, sizeof(supported_groups));
1628
1629        tls->hsd = xzalloc(sizeof(*tls->hsd));
1630        /* HANDSHAKE HASH: ^^^ + len if need to save saved_client_hello */
1631        memcpy(tls->hsd->client_and_server_rand32, record->rand32, sizeof(record->rand32));
1632/* HANDSHAKE HASH:
1633        tls->hsd->saved_client_hello_size = len;
1634        memcpy(tls->hsd->saved_client_hello, record, len);
1635 */
1636        dbg(">> CLIENT_HELLO\n");
1637        /* Can hash immediately only if we know which MAC hash to use.
1638         * So far we do know: it's sha256:
1639         */
1640        sha256_begin(&tls->hsd->handshake_hash_ctx);
1641        xwrite_and_update_handshake_hash(tls, len);
1642        /* if this would become infeasible: save tls->hsd->saved_client_hello,
1643         * use "xwrite_handshake_record(tls, len)" here,
1644         * and hash saved_client_hello later.
1645         */
1646}
1647
1648static void get_server_hello(tls_state_t *tls)
1649{
1650        struct server_hello {
1651                struct record_hdr xhdr;
1652                uint8_t type;
1653                uint8_t len24_hi, len24_mid, len24_lo;
1654                uint8_t proto_maj, proto_min;
1655                uint8_t rand32[32]; /* first 4 bytes are unix time in BE format */
1656                uint8_t session_id_len;
1657                uint8_t session_id[32];
1658                uint8_t cipherid_hi, cipherid_lo;
1659                uint8_t comprtype;
1660                /* extensions may follow, but only those which client offered in its Hello */
1661        };
1662
1663        struct server_hello *hp;
1664        uint8_t *cipherid;
1665        uint8_t cipherid1;
1666        int len, len24;
1667
1668        len = tls_xread_handshake_block(tls, 74 - 32);
1669
1670        hp = (void*)tls->inbuf;
1671        // 74 bytes:
1672        // 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|
1673        //SvHl len=70 maj.min unixtime^^^ 28randbytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_^^^ slen sid32bytes^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cipSel comprSel
1674        if (hp->type != HANDSHAKE_SERVER_HELLO
1675         || hp->len24_hi  != 0
1676         || hp->len24_mid != 0
1677         /* hp->len24_lo checked later */
1678         || hp->proto_maj != TLS_MAJ
1679         || hp->proto_min != TLS_MIN
1680        ) {
1681                bad_record_die(tls, "'server hello'", len);
1682        }
1683
1684        cipherid = &hp->cipherid_hi;
1685        len24 = hp->len24_lo;
1686        if (hp->session_id_len != 32) {
1687                if (hp->session_id_len != 0)
1688                        bad_record_die(tls, "'server hello'", len);
1689
1690                // session_id_len == 0: no session id
1691                // "The server
1692                // may return an empty session_id to indicate that the session will
1693                // not be cached and therefore cannot be resumed."
1694                cipherid -= 32;
1695                len24 += 32; /* what len would be if session id would be present */
1696        }
1697
1698        if (len24 < 70)
1699                bad_record_die(tls, "'server hello'", len);
1700        dbg("<< SERVER_HELLO\n");
1701
1702        memcpy(tls->hsd->client_and_server_rand32 + 32, hp->rand32, sizeof(hp->rand32));
1703
1704        /* Set up encryption params based on selected cipher */
1705#if 0
1706#if ENABLE_FEATURE_TLS_SHA1
1707                0xC0,0x09, // 1 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA - ok: wget https://is.gd/
1708                0xC0,0x0A, // 2 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA - ok: wget https://is.gd/
1709                0xC0,0x13, // 3 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA
1710                0xC0,0x14, // 4 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES256-SHA (might fail with older openssl)
1711        //      0xC0,0x18, //   TLS_ECDH_anon_WITH_AES_128_CBC_SHA
1712        //      0xC0,0x19, //   TLS_ECDH_anon_WITH_AES_256_CBC_SHA
1713#endif
1714                0xC0,0x23, // 5 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 - ok: wget https://is.gd/
1715        //      0xC0,0x24, //   TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
1716                0xC0,0x27, // 6 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA256
1717        //      0xC0,0x28, //   TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
1718                0xC0,0x2B, // 7 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - ok: wget https://is.gd/
1719        //      0xC0,0x2C, //   TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - wget https://is.gd/: "TLS error from peer (alert code 20): bad MAC"
1720//TODO: GCM_SHA384 ciphers can be supported, only need sha384-based PRF?
1721                0xC0,0x2F, // 8 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-GCM-SHA256
1722        //      0xC0,0x30, //   TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher ECDHE-RSA-AES256-GCM-SHA384: "decryption failed or bad record mac"
1723        //possibly these too:
1724#if ENABLE_FEATURE_TLS_SHA1
1725        //      0xC0,0x35, //   TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
1726        //      0xC0,0x36, //   TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA
1727#endif
1728        //      0xC0,0x37, //   TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
1729        //      0xC0,0x38, //   TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
1730#if ENABLE_FEATURE_TLS_SHA1
1731                0x00,0x2F, // 9 TLS_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher AES128-SHA
1732                0x00,0x35, //10 TLS_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher AES256-SHA
1733#endif
1734                0x00,0x3C, //11 TLS_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher AES128-SHA256
1735                0x00,0x3D, //12 TLS_RSA_WITH_AES_256_CBC_SHA256 - ok: openssl s_server ... -cipher AES256-SHA256
1736                0x00,0x9C, //13 TLS_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher AES128-GCM-SHA256
1737        //      0x00,0x9D, //   TLS_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher AES256-GCM-SHA384: "decryption failed or bad record mac"
1738#if ALLOW_RSA_NULL_SHA256
1739                0x00,0x3B, //   TLS_RSA_WITH_NULL_SHA256
1740#endif
1741#endif
1742        cipherid1 = cipherid[1];
1743        tls->cipher_id = 0x100 * cipherid[0] + cipherid1;
1744        tls->key_size = AES256_KEYSIZE;
1745        tls->MAC_size = SHA256_OUTSIZE;
1746        /*tls->IV_size = 0; - already is */
1747        if (cipherid[0] == 0xC0) {
1748                /* All C0xx are ECDHE */
1749                tls->flags |= NEED_EC_KEY;
1750                if (cipherid1 & 1) {
1751                        /* Odd numbered C0xx use AES128 (even ones use AES256) */
1752                        tls->key_size = AES128_KEYSIZE;
1753                }
1754                if (ENABLE_FEATURE_TLS_SHA1 && cipherid1 <= 0x19) {
1755                        tls->MAC_size = SHA1_OUTSIZE;
1756                } else
1757                if (cipherid1 >= 0x2B && cipherid1 <= 0x30) {
1758                        /* C02B,2C,2F,30 are AES-GCM */
1759                        tls->flags |= ENCRYPTION_AESGCM;
1760                        tls->MAC_size = 0;
1761                        tls->IV_size = 4;
1762                }
1763        } else {
1764                /* All 00xx are RSA */
1765                if ((ENABLE_FEATURE_TLS_SHA1 && cipherid1 == 0x2F)
1766                 || cipherid1 == 0x3C
1767                 || cipherid1 == 0x9C
1768                ) {
1769                        tls->key_size = AES128_KEYSIZE;
1770                }
1771                if (ENABLE_FEATURE_TLS_SHA1 && cipherid1 <= 0x35) {
1772                        tls->MAC_size = SHA1_OUTSIZE;
1773                } else
1774                if (cipherid1 == 0x9C /*|| cipherid1 == 0x9D*/) {
1775                        /* 009C,9D are AES-GCM */
1776                        tls->flags |= ENCRYPTION_AESGCM;
1777                        tls->MAC_size = 0;
1778                        tls->IV_size = 4;
1779                }
1780        }
1781        dbg("server chose cipher %04x\n", tls->cipher_id);
1782        dbg("key_size:%u MAC_size:%u IV_size:%u\n", tls->key_size, tls->MAC_size, tls->IV_size);
1783
1784        /* Handshake hash eventually destined to FINISHED record
1785         * is sha256 regardless of cipher
1786         * (at least for all ciphers defined by RFC5246).
1787         * It's not sha1 for AES_128_CBC_SHA - only MAC is sha1, not this hash.
1788         */
1789/* HANDSHAKE HASH:
1790        sha256_begin(&tls->hsd->handshake_hash_ctx);
1791        hash_handshake(tls, ">> client hello hash:%s",
1792                tls->hsd->saved_client_hello, tls->hsd->saved_client_hello_size
1793        );
1794        hash_handshake(tls, "<< server hello hash:%s",
1795                tls->inbuf + RECHDR_LEN, len
1796        );
1797 */
1798}
1799
1800static void get_server_cert(tls_state_t *tls)
1801{
1802        struct record_hdr *xhdr;
1803        uint8_t *certbuf;
1804        int len, len1;
1805
1806        len = tls_xread_handshake_block(tls, 10);
1807
1808        xhdr = (void*)tls->inbuf;
1809        certbuf = (void*)(xhdr + 1);
1810        if (certbuf[0] != HANDSHAKE_CERTIFICATE)
1811                bad_record_die(tls, "certificate", len);
1812        dbg("<< CERTIFICATE\n");
1813        // 4392 bytes:
1814        // 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...
1815        //Cert len=4388 ChainLen CertLen^ DER encoded X509 starts here. openssl x509 -in FILE -inform DER -noout -text
1816        len1 = get24be(certbuf + 1);
1817        if (len1 > len - 4) tls_error_die(tls);
1818        len = len1;
1819        len1 = get24be(certbuf + 4);
1820        if (len1 > len - 3) tls_error_die(tls);
1821        len = len1;
1822        len1 = get24be(certbuf + 7);
1823        if (len1 > len - 3) tls_error_die(tls);
1824        len = len1;
1825
1826        if (len)
1827                find_key_in_der_cert(tls, certbuf + 10, len);
1828}
1829
1830/* On input, len is known to be >= 4.
1831 * The record is known to be SERVER_KEY_EXCHANGE.
1832 */
1833static void process_server_key(tls_state_t *tls, int len)
1834{
1835        struct record_hdr *xhdr;
1836        uint8_t *keybuf;
1837        int len1;
1838        uint32_t t32;
1839
1840        xhdr = (void*)tls->inbuf;
1841        keybuf = (void*)(xhdr + 1);
1842//seen from is.gd: it selects curve_x25519:
1843//  0c 00006e //SERVER_KEY_EXCHANGE, len
1844//    03 //curve_type: named curve
1845//    001d //curve_x25519
1846//server-chosen EC point, and then signed_params
1847//      (RFC 8422: "A hash of the params, with the signature
1848//      appropriate to that hash applied.  The private key corresponding
1849//      to the certified public key in the server's Certificate message is
1850//      used for signing.")
1851//follow. Format unclear/guessed:
1852//    20 //eccPubKeyLen
1853//      25511923d73b70dd2f60e66ba2f3fda31a9c25170963c7a3a972e481dbb2835d //eccPubKey (32bytes)
1854//    0203 //hashSigAlg: 2:SHA1 (4:SHA256 5:SHA384 6:SHA512), 3:ECDSA (1:RSA)
1855//    0046 //len (16bit)
1856//      30 44 //SEQ, len
1857//        02 20 //INTEGER, len
1858//          2e18e7c2a9badd0a70cd3059a6ab114539b9f5163568911147386cd77ed7c412 //32bytes
1859//this item ^^^^^ is sometimes 33 bytes (with all container sizes also +1)
1860//        02 20 //INTEGER, len
1861//          64523d6216cb94c43c9b20e377d8c52c55be6703fd6730a155930c705eaf3af6 //32bytes
1862//same about this item ^^^^^
1863
1864//seen from ftp.openbsd.org
1865//(which only accepts ECDHE-RSA-AESnnn-GCM-SHAnnn and ECDHE-RSA-CHACHA20-POLY1305 ciphers):
1866//  0c 000228 //SERVER_KEY_EXCHANGE, len
1867//    03 //curve_type: named curve
1868//    001d //curve_x25519
1869//    20 //eccPubKeyLen
1870//      eef7a15c43b71a4c7eaa48a39369399cc4332e569ec90a83274cc92596705c1a //eccPubKey
1871//    0401 //hashSigAlg: 4:SHA256, 1:RSA
1872//    0200 //len
1873//      //0x200 bytes follow
1874
1875        /* Get and verify length */
1876        len1 = get24be(keybuf + 1);
1877        if (len1 > len - 4) tls_error_die(tls);
1878        len = len1;
1879        if (len < (1+2+1+32)) tls_error_die(tls);
1880        keybuf += 4;
1881
1882        /* So far we only support curve_x25519 */
1883        move_from_unaligned32(t32, keybuf);
1884        if (t32 != htonl(0x03001d20))
1885                bb_error_msg_and_die("elliptic curve is not x25519");
1886
1887        memcpy(tls->hsd->ecc_pub_key32, keybuf + 4, 32);
1888        tls->flags |= GOT_EC_KEY;
1889        dbg("got eccPubKey\n");
1890}
1891
1892static void send_empty_client_cert(tls_state_t *tls)
1893{
1894        struct client_empty_cert {
1895                uint8_t type;
1896                uint8_t len24_hi, len24_mid, len24_lo;
1897                uint8_t cert_chain_len24_hi, cert_chain_len24_mid, cert_chain_len24_lo;
1898        };
1899        struct client_empty_cert *record;
1900
1901        record = tls_get_zeroed_outbuf(tls, sizeof(*record));
1902        //fill_handshake_record_hdr(record, HANDSHAKE_CERTIFICATE, sizeof(*record));
1903        //record->cert_chain_len24_hi = 0;
1904        //record->cert_chain_len24_mid = 0;
1905        //record->cert_chain_len24_lo = 0;
1906        // same as above:
1907        record->type = HANDSHAKE_CERTIFICATE;
1908        record->len24_lo = 3;
1909
1910        dbg(">> CERTIFICATE\n");
1911        xwrite_and_update_handshake_hash(tls, sizeof(*record));
1912}
1913
1914static void send_client_key_exchange(tls_state_t *tls)
1915{
1916        struct client_key_exchange {
1917                uint8_t type;
1918                uint8_t len24_hi, len24_mid, len24_lo;
1919                uint8_t key[2 + 4 * 1024]; // size??
1920        };
1921//FIXME: better size estimate
1922        struct client_key_exchange *record = tls_get_zeroed_outbuf(tls, sizeof(*record));
1923        uint8_t rsa_premaster[RSA_PREMASTER_SIZE];
1924        uint8_t x25519_premaster[CURVE25519_KEYSIZE];
1925        uint8_t *premaster;
1926        int premaster_size;
1927        int len;
1928
1929        if (!(tls->flags & NEED_EC_KEY)) {
1930                /* RSA */
1931                if (!(tls->flags & GOT_CERT_RSA_KEY_ALG))
1932                        bb_error_msg("server cert is not RSA");
1933
1934                tls_get_random(rsa_premaster, sizeof(rsa_premaster));
1935                if (TLS_DEBUG_FIXED_SECRETS)
1936                        memset(rsa_premaster, 0x44, sizeof(rsa_premaster));
1937                // RFC 5246
1938                // "Note: The version number in the PreMasterSecret is the version
1939                // offered by the client in the ClientHello.client_version, not the
1940                // version negotiated for the connection."
1941                rsa_premaster[0] = TLS_MAJ;
1942                rsa_premaster[1] = TLS_MIN;
1943                dump_hex("premaster:%s\n", rsa_premaster, sizeof(rsa_premaster));
1944                len = psRsaEncryptPub(/*pool:*/ NULL,
1945                        /* psRsaKey_t* */ &tls->hsd->server_rsa_pub_key,
1946                        rsa_premaster, /*inlen:*/ sizeof(rsa_premaster),
1947                        record->key + 2, sizeof(record->key) - 2,
1948                        data_param_ignored
1949                );
1950                /* keylen16 exists for RSA (in TLS, not in SSL), but not for some other key types */
1951                record->key[0] = len >> 8;
1952                record->key[1] = len & 0xff;
1953                len += 2;
1954                premaster = rsa_premaster;
1955                premaster_size = sizeof(rsa_premaster);
1956        } else {
1957                /* ECDHE */
1958                static const uint8_t basepoint9[CURVE25519_KEYSIZE] = {9};
1959                uint8_t privkey[CURVE25519_KEYSIZE]; //[32]
1960
1961                if (!(tls->flags & GOT_EC_KEY))
1962                        bb_error_msg("server did not provide EC key");
1963
1964                /* Generate random private key, see RFC 7748 */
1965                tls_get_random(privkey, sizeof(privkey));
1966                privkey[0] &= 0xf8;
1967                privkey[CURVE25519_KEYSIZE-1] = ((privkey[CURVE25519_KEYSIZE-1] & 0x7f) | 0x40);
1968
1969                /* Compute public key */
1970                curve25519(record->key + 1, privkey, basepoint9);
1971
1972                /* Compute premaster using peer's public key */
1973                dbg("computing x25519_premaster\n");
1974                curve25519(x25519_premaster, privkey, tls->hsd->ecc_pub_key32);
1975
1976                len = CURVE25519_KEYSIZE;
1977                record->key[0] = len;
1978                len++;
1979                premaster = x25519_premaster;
1980                premaster_size = sizeof(x25519_premaster);
1981        }
1982
1983        record->type = HANDSHAKE_CLIENT_KEY_EXCHANGE;
1984        /* record->len24_hi = 0; - already is */
1985        record->len24_mid = len >> 8;
1986        record->len24_lo  = len & 0xff;
1987        len += 4;
1988
1989        dbg(">> CLIENT_KEY_EXCHANGE\n");
1990        xwrite_and_update_handshake_hash(tls, len);
1991
1992        // RFC 5246
1993        // For all key exchange methods, the same algorithm is used to convert
1994        // the pre_master_secret into the master_secret.  The pre_master_secret
1995        // should be deleted from memory once the master_secret has been
1996        // computed.
1997        //      master_secret = PRF(pre_master_secret, "master secret",
1998        //                          ClientHello.random + ServerHello.random)
1999        //                          [0..47];
2000        // The master secret is always exactly 48 bytes in length.  The length
2001        // of the premaster secret will vary depending on key exchange method.
2002        prf_hmac_sha256(/*tls,*/
2003                tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
2004                premaster, premaster_size,
2005                "master secret",
2006                tls->hsd->client_and_server_rand32, sizeof(tls->hsd->client_and_server_rand32)
2007        );
2008        dump_hex("master secret:%s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
2009
2010        // RFC 5246
2011        // 6.3.  Key Calculation
2012        //
2013        // The Record Protocol requires an algorithm to generate keys required
2014        // by the current connection state (see Appendix A.6) from the security
2015        // parameters provided by the handshake protocol.
2016        //
2017        // The master secret is expanded into a sequence of secure bytes, which
2018        // is then split to a client write MAC key, a server write MAC key, a
2019        // client write encryption key, and a server write encryption key.  Each
2020        // of these is generated from the byte sequence in that order.  Unused
2021        // values are empty.  Some AEAD ciphers may additionally require a
2022        // client write IV and a server write IV (see Section 6.2.3.3).
2023        //
2024        // When keys and MAC keys are generated, the master secret is used as an
2025        // entropy source.
2026        //
2027        // To generate the key material, compute
2028        //
2029        //    key_block = PRF(SecurityParameters.master_secret,
2030        //                    "key expansion",
2031        //                    SecurityParameters.server_random +
2032        //                    SecurityParameters.client_random);
2033        //
2034        // until enough output has been generated.  Then, the key_block is
2035        // partitioned as follows:
2036        //
2037        //    client_write_MAC_key[SecurityParameters.mac_key_length]
2038        //    server_write_MAC_key[SecurityParameters.mac_key_length]
2039        //    client_write_key[SecurityParameters.enc_key_length]
2040        //    server_write_key[SecurityParameters.enc_key_length]
2041        //    client_write_IV[SecurityParameters.fixed_iv_length]
2042        //    server_write_IV[SecurityParameters.fixed_iv_length]
2043        {
2044                uint8_t tmp64[64];
2045
2046                /* make "server_rand32 + client_rand32" */
2047                memcpy(&tmp64[0] , &tls->hsd->client_and_server_rand32[32], 32);
2048                memcpy(&tmp64[32], &tls->hsd->client_and_server_rand32[0] , 32);
2049
2050                prf_hmac_sha256(/*tls,*/
2051                        tls->client_write_MAC_key, 2 * (tls->MAC_size + tls->key_size + tls->IV_size),
2052                        // also fills:
2053                        // server_write_MAC_key[]
2054                        // client_write_key[]
2055                        // server_write_key[]
2056                        // client_write_IV[]
2057                        // server_write_IV[]
2058                        tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
2059                        "key expansion",
2060                        tmp64, 64
2061                );
2062                tls->client_write_key = tls->client_write_MAC_key + (2 * tls->MAC_size);
2063                tls->server_write_key = tls->client_write_key + tls->key_size;
2064                tls->client_write_IV = tls->server_write_key + tls->key_size;
2065                tls->server_write_IV = tls->client_write_IV + tls->IV_size;
2066                dump_hex("client_write_MAC_key:%s\n",
2067                        tls->client_write_MAC_key, tls->MAC_size
2068                );
2069                dump_hex("client_write_key:%s\n",
2070                        tls->client_write_key, tls->key_size
2071                );
2072                dump_hex("client_write_IV:%s\n",
2073                        tls->client_write_IV, tls->IV_size
2074                );
2075
2076                aes_setkey(&tls->aes_decrypt, tls->server_write_key, tls->key_size);
2077                aes_setkey(&tls->aes_encrypt, tls->client_write_key, tls->key_size);
2078                {
2079                        uint8_t iv[AES_BLOCK_SIZE];
2080                        memset(iv, 0, AES_BLOCK_SIZE);
2081                        aes_encrypt_one_block(&tls->aes_encrypt, iv, tls->H);
2082                }
2083        }
2084}
2085
2086static const uint8_t rec_CHANGE_CIPHER_SPEC[] ALIGN1 = {
2087        RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
2088        01
2089};
2090
2091static void send_change_cipher_spec(tls_state_t *tls)
2092{
2093        dbg(">> CHANGE_CIPHER_SPEC\n");
2094        xwrite(tls->ofd, rec_CHANGE_CIPHER_SPEC, sizeof(rec_CHANGE_CIPHER_SPEC));
2095}
2096
2097// 7.4.9.  Finished
2098// A Finished message is always sent immediately after a change
2099// cipher spec message to verify that the key exchange and
2100// authentication processes were successful.  It is essential that a
2101// change cipher spec message be received between the other handshake
2102// messages and the Finished message.
2103//...
2104// The Finished message is the first one protected with the just
2105// negotiated algorithms, keys, and secrets.  Recipients of Finished
2106// messages MUST verify that the contents are correct.  Once a side
2107// has sent its Finished message and received and validated the
2108// Finished message from its peer, it may begin to send and receive
2109// application data over the connection.
2110//...
2111// struct {
2112//     opaque verify_data[verify_data_length];
2113// } Finished;
2114//
2115// verify_data
2116//    PRF(master_secret, finished_label, Hash(handshake_messages))
2117//       [0..verify_data_length-1];
2118//
2119// finished_label
2120//    For Finished messages sent by the client, the string
2121//    "client finished".  For Finished messages sent by the server,
2122//    the string "server finished".
2123//
2124// Hash denotes a Hash of the handshake messages.  For the PRF
2125// defined in Section 5, the Hash MUST be the Hash used as the basis
2126// for the PRF.  Any cipher suite which defines a different PRF MUST
2127// also define the Hash to use in the Finished computation.
2128//
2129// In previous versions of TLS, the verify_data was always 12 octets
2130// long.  In the current version of TLS, it depends on the cipher
2131// suite.  Any cipher suite which does not explicitly specify
2132// verify_data_length has a verify_data_length equal to 12.  This
2133// includes all existing cipher suites.
2134static void send_client_finished(tls_state_t *tls)
2135{
2136        struct finished {
2137                uint8_t type;
2138                uint8_t len24_hi, len24_mid, len24_lo;
2139                uint8_t prf_result[12];
2140        };
2141        struct finished *record = tls_get_outbuf(tls, sizeof(*record));
2142        uint8_t handshake_hash[TLS_MAX_MAC_SIZE];
2143        unsigned len;
2144
2145        fill_handshake_record_hdr(record, HANDSHAKE_FINISHED, sizeof(*record));
2146
2147        len = sha_end(&tls->hsd->handshake_hash_ctx, handshake_hash);
2148
2149        prf_hmac_sha256(/*tls,*/
2150                record->prf_result, sizeof(record->prf_result),
2151                tls->hsd->master_secret, sizeof(tls->hsd->master_secret),
2152                "client finished",
2153                handshake_hash, len
2154        );
2155        dump_hex("from secret: %s\n", tls->hsd->master_secret, sizeof(tls->hsd->master_secret));
2156        dump_hex("from labelSeed: %s", "client finished", sizeof("client finished")-1);
2157        dump_hex("%s\n", handshake_hash, sizeof(handshake_hash));
2158        dump_hex("=> digest: %s\n", record->prf_result, sizeof(record->prf_result));
2159
2160        dbg(">> FINISHED\n");
2161        xwrite_encrypted(tls, sizeof(*record), RECORD_TYPE_HANDSHAKE);
2162}
2163
2164void FAST_FUNC tls_handshake(tls_state_t *tls, const char *sni)
2165{
2166        // Client              RFC 5246                Server
2167        // (*) - optional messages, not always sent
2168        //
2169        // ClientHello          ------->
2170        //                                        ServerHello
2171        //                                       Certificate*
2172        //                                 ServerKeyExchange*
2173        //                                CertificateRequest*
2174        //                      <-------      ServerHelloDone
2175        // Certificate*
2176        // ClientKeyExchange
2177        // CertificateVerify*
2178        // [ChangeCipherSpec]
2179        // Finished             ------->
2180        //                                 [ChangeCipherSpec]
2181        //                      <-------             Finished
2182        // Application Data     <------>     Application Data
2183        int len;
2184        int got_cert_req;
2185
2186        send_client_hello_and_alloc_hsd(tls, sni);
2187        get_server_hello(tls);
2188
2189        // RFC 5246
2190        // The server MUST send a Certificate message whenever the agreed-
2191        // upon key exchange method uses certificates for authentication
2192        // (this includes all key exchange methods defined in this document
2193        // except DH_anon).  This message will always immediately follow the
2194        // ServerHello message.
2195        //
2196        // IOW: in practice, Certificate *always* follows.
2197        // (for example, kernel.org does not even accept DH_anon cipher id)
2198        get_server_cert(tls);
2199
2200        len = tls_xread_handshake_block(tls, 4);
2201        if (tls->inbuf[RECHDR_LEN] == HANDSHAKE_SERVER_KEY_EXCHANGE) {
2202                // 459 bytes:
2203                // 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...
2204                //SvKey len=455^
2205                // with TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 461 bytes:
2206                // 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...
2207                //
2208                // RFC 8422 5.4. Server Key Exchange
2209                // This message is sent when using the ECDHE_ECDSA, ECDHE_RSA, and
2210                // ECDH_anon key exchange algorithms.
2211                // This message is used to convey the server's ephemeral ECDH public key
2212                // (and the corresponding elliptic curve domain parameters) to the
2213                // client.
2214                dbg("<< SERVER_KEY_EXCHANGE len:%u\n", len);
2215                dump_raw_in("<< %s\n", tls->inbuf, RECHDR_LEN + len);
2216                if (tls->flags & NEED_EC_KEY)
2217                        process_server_key(tls, len);
2218
2219                // read next handshake block
2220                len = tls_xread_handshake_block(tls, 4);
2221        }
2222
2223        got_cert_req = (tls->inbuf[RECHDR_LEN] == HANDSHAKE_CERTIFICATE_REQUEST);
2224        if (got_cert_req) {
2225                dbg("<< CERTIFICATE_REQUEST\n");
2226                // RFC 5246: "If no suitable certificate is available,
2227                // the client MUST send a certificate message containing no
2228                // certificates.  That is, the certificate_list structure has a
2229                // length of zero. ...
2230                // Client certificates are sent using the Certificate structure
2231                // defined in Section 7.4.2."
2232                // (i.e. the same format as server certs)
2233
2234                /*send_empty_client_cert(tls); - WRONG (breaks handshake hash calc) */
2235                /* need to hash _all_ server replies first, up to ServerHelloDone */
2236                len = tls_xread_handshake_block(tls, 4);
2237        }
2238
2239        if (tls->inbuf[RECHDR_LEN] != HANDSHAKE_SERVER_HELLO_DONE) {
2240                bad_record_die(tls, "'server hello done'", len);
2241        }
2242        // 0e 000000 (len:0)
2243        dbg("<< SERVER_HELLO_DONE\n");
2244
2245        if (got_cert_req)
2246                send_empty_client_cert(tls);
2247
2248        send_client_key_exchange(tls);
2249
2250        send_change_cipher_spec(tls);
2251        /* from now on we should send encrypted */
2252        /* tls->write_seq64_be = 0; - already is */
2253        tls->flags |= ENCRYPT_ON_WRITE;
2254
2255        send_client_finished(tls);
2256
2257        /* Get CHANGE_CIPHER_SPEC */
2258        len = tls_xread_record(tls, "switch to encrypted traffic");
2259        if (len != 1 || memcmp(tls->inbuf, rec_CHANGE_CIPHER_SPEC, 6) != 0)
2260                bad_record_die(tls, "switch to encrypted traffic", len);
2261        dbg("<< CHANGE_CIPHER_SPEC\n");
2262
2263        if (ALLOW_RSA_NULL_SHA256
2264         && tls->cipher_id == TLS_RSA_WITH_NULL_SHA256
2265        ) {
2266                tls->min_encrypted_len_on_read = tls->MAC_size;
2267        } else
2268        if (!(tls->flags & ENCRYPTION_AESGCM)) {
2269                unsigned mac_blocks = (unsigned)(TLS_MAC_SIZE(tls) + AES_BLOCK_SIZE-1) / AES_BLOCK_SIZE;
2270                /* all incoming packets now should be encrypted and have
2271                 * at least IV + (MAC padded to blocksize):
2272                 */
2273                tls->min_encrypted_len_on_read = AES_BLOCK_SIZE + (mac_blocks * AES_BLOCK_SIZE);
2274        } else {
2275                tls->min_encrypted_len_on_read = 8 + AES_BLOCK_SIZE;
2276        }
2277        dbg("min_encrypted_len_on_read: %u\n", tls->min_encrypted_len_on_read);
2278
2279        /* Get (encrypted) FINISHED from the server */
2280        len = tls_xread_record(tls, "'server finished'");
2281        if (len < 4 || tls->inbuf[RECHDR_LEN] != HANDSHAKE_FINISHED)
2282                bad_record_die(tls, "'server finished'", len);
2283        dbg("<< FINISHED\n");
2284        /* application data can be sent/received */
2285
2286        /* free handshake data */
2287        psRsaKey_clear(&tls->hsd->server_rsa_pub_key);
2288//      if (PARANOIA)
2289//              memset(tls->hsd, 0, tls->hsd->hsd_size);
2290        free(tls->hsd);
2291        tls->hsd = NULL;
2292}
2293
2294static void tls_xwrite(tls_state_t *tls, int len)
2295{
2296        dbg(">> DATA\n");
2297        xwrite_encrypted(tls, len, RECORD_TYPE_APPLICATION_DATA);
2298}
2299
2300// To run a test server using openssl:
2301// openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
2302// openssl s_server -key key.pem -cert server.pem -debug -tls1_2
2303//
2304// Unencryped SHA256 example:
2305// openssl req -x509 -newkey rsa:$((4096/4*3)) -keyout key.pem -out server.pem -nodes -days 99999 -subj '/CN=localhost'
2306// openssl s_server -key key.pem -cert server.pem -debug -tls1_2 -cipher NULL
2307// openssl s_client -connect 127.0.0.1:4433 -debug -tls1_2 -cipher NULL-SHA256
2308
2309void FAST_FUNC tls_run_copy_loop(tls_state_t *tls, unsigned flags)
2310{
2311        int inbuf_size;
2312        const int INBUF_STEP = 4 * 1024;
2313        struct pollfd pfds[2];
2314
2315        pfds[0].fd = STDIN_FILENO;
2316        pfds[0].events = POLLIN;
2317        pfds[1].fd = tls->ifd;
2318        pfds[1].events = POLLIN;
2319
2320        inbuf_size = INBUF_STEP;
2321        for (;;) {
2322                int nread;
2323
2324                if (safe_poll(pfds, 2, -1) < 0)
2325                        bb_perror_msg_and_die("poll");
2326
2327                if (pfds[0].revents) {
2328                        void *buf;
2329
2330                        dbg("STDIN HAS DATA\n");
2331                        buf = tls_get_outbuf(tls, inbuf_size);
2332                        nread = safe_read(STDIN_FILENO, buf, inbuf_size);
2333                        if (nread < 1) {
2334                                /* We'd want to do this: */
2335                                /* Close outgoing half-connection so they get EOF,
2336                                 * but leave incoming alone so we can see response
2337                                 */
2338                                //shutdown(tls->ofd, SHUT_WR);
2339                                /* But TLS has no way to encode this,
2340                                 * doubt it's ok to do it "raw"
2341                                 */
2342                                pfds[0].fd = -1;
2343                                tls_free_outbuf(tls); /* mem usage optimization */
2344                                if (flags & TLSLOOP_EXIT_ON_LOCAL_EOF)
2345                                        break;
2346                        } else {
2347                                if (nread == inbuf_size) {
2348                                        /* TLS has per record overhead, if input comes fast,
2349                                         * read, encrypt and send bigger chunks
2350                                         */
2351                                        inbuf_size += INBUF_STEP;
2352                                        if (inbuf_size > TLS_MAX_OUTBUF)
2353                                                inbuf_size = TLS_MAX_OUTBUF;
2354                                }
2355                                tls_xwrite(tls, nread);
2356                        }
2357                }
2358                if (pfds[1].revents) {
2359                        dbg("NETWORK HAS DATA\n");
2360 read_record:
2361                        nread = tls_xread_record(tls, "encrypted data");
2362                        if (nread < 1) {
2363                                /* TLS protocol has no real concept of one-sided shutdowns:
2364                                 * if we get "TLS EOF" from the peer, writes will fail too
2365                                 */
2366                                //pfds[1].fd = -1;
2367                                //close(STDOUT_FILENO);
2368                                //tls_free_inbuf(tls); /* mem usage optimization */
2369                                //continue;
2370                                break;
2371                        }
2372                        if (tls->inbuf[0] != RECORD_TYPE_APPLICATION_DATA)
2373                                bad_record_die(tls, "encrypted data", nread);
2374                        xwrite(STDOUT_FILENO, tls->inbuf + RECHDR_LEN, nread);
2375                        /* We may already have a complete next record buffered,
2376                         * can process it without network reads (and possible blocking)
2377                         */
2378                        if (tls_has_buffered_record(tls))
2379                                goto read_record;
2380                }
2381        }
2382}
2383