1+ #include " TLSTickets.hpp"
2+ #include " HTTPSServerConstants.hpp"
3+
4+ #include " mbedtls/net_sockets.h"
5+
6+ // Low level SSL implementation on ESP32
7+ // Copied from esp-idf/components/openssl/platform/ssl_pm.c
8+ struct ssl_pm {
9+ mbedtls_net_context fd;
10+ mbedtls_net_context cl_fd;
11+ mbedtls_ssl_config conf;
12+ mbedtls_ctr_drbg_context ctr_drbg;
13+ mbedtls_ssl_context ssl;
14+ mbedtls_entropy_context entropy;
15+ };
16+
17+ namespace httpsserver {
18+
19+ int TLSTickets::hardware_random (void * p_rng, unsigned char * output, size_t output_len) {
20+ esp_fill_random (output, output_len);
21+ return 0 ;
22+ }
23+
24+ TLSTickets::TLSTickets (const char * tag, uint32_t lifetimeSeconds, bool useHWRNG) {
25+ _initOk = false ;
26+ _useHWRNG = useHWRNG;
27+
28+ // Setup TLS tickets context
29+ int ret = -1 ;
30+ if (_useHWRNG) {
31+ mbedtls_ssl_ticket_init (&_ticketCtx);
32+ ret = mbedtls_ssl_ticket_setup (
33+ &_ticketCtx,
34+ TLSTickets::hardware_random,
35+ NULL ,
36+ MBEDTLS_CIPHER_AES_256_GCM ,
37+ lifetimeSeconds
38+ );
39+ } else {
40+ mbedtls_entropy_init (&_entropy);
41+ mbedtls_ctr_drbg_init (&_ctr_drbg);
42+ mbedtls_ssl_ticket_init (&_ticketCtx);
43+ ret = mbedtls_ctr_drbg_seed (
44+ &_ctr_drbg,
45+ mbedtls_entropy_func,
46+ &_entropy,
47+ (unsigned char *)tag,
48+ strlen (tag)
49+ );
50+ if (ret == 0 ) {
51+ ret = mbedtls_ssl_ticket_setup (
52+ &_ticketCtx,
53+ mbedtls_ctr_drbg_random,
54+ &_ctr_drbg,
55+ MBEDTLS_CIPHER_AES_256_GCM ,
56+ lifetimeSeconds
57+ );
58+ }
59+ }
60+ if (ret != 0 ) return ;
61+
62+ _initOk = true ;
63+ HTTPS_LOGI (" Using TLS session tickets" );
64+ }
65+
66+ TLSTickets::~TLSTickets () {
67+ if (!_useHWRNG) {
68+ mbedtls_ctr_drbg_free (&_ctr_drbg);
69+ mbedtls_entropy_free (&_entropy);
70+ }
71+ mbedtls_ssl_ticket_free (&_ticketCtx);
72+ }
73+
74+ bool TLSTickets::enable (SSL * ssl) {
75+ bool res = false ;
76+ if (_initOk && ssl && ssl->ssl_pm ) {
77+ // Get handle of low-level mbedtls structures for the session
78+ struct ssl_pm * ssl_pm = (struct ssl_pm *) ssl->ssl_pm ;
79+ // Configure TLS ticket callbacks using default MbedTLS implementation
80+ mbedtls_ssl_conf_session_tickets_cb (
81+ &ssl_pm->conf ,
82+ mbedtls_ssl_ticket_write,
83+ mbedtls_ssl_ticket_parse,
84+ &_ticketCtx
85+ );
86+ res = true ;
87+ }
88+ return res;
89+ }
90+
91+ } /* namespace httpsserver */
0 commit comments