• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

randombit / botan / 13274522654

11 Feb 2025 11:26PM UTC coverage: 91.645% (-0.007%) from 91.652%
13274522654

push

github

web-flow
Merge pull request #4647 from randombit/jack/internal-assert-and-mem-ops

Avoid using mem_ops.h or assert.h in public headers

94854 of 103501 relevant lines covered (91.65%)

11334975.77 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.59
/src/lib/tls/tls_session_manager.cpp
1
/**
2
 * TLS Session Manger base class implementations
3
 * (C) 2011-2023 Jack Lloyd
4
 *     2022-2023 René Meusel - Rohde & Schwarz Cybersecurity
5
 *
6
 * Botan is released under the Simplified BSD License (see license.txt)
7
 */
8

9
#include <botan/tls_session_manager.h>
10

11
#include <botan/assert.h>
12
#include <botan/rng.h>
13
#include <botan/tls_callbacks.h>
14
#include <botan/tls_policy.h>
15
#include <algorithm>
16

17
namespace Botan::TLS {
18

19
Session_Manager::Session_Manager(const std::shared_ptr<RandomNumberGenerator>& rng) : m_rng(rng) {
9,629✔
20
   BOTAN_ASSERT_NONNULL(m_rng);
9,629✔
21
}
9,629✔
22

23
std::optional<Session_Handle> Session_Manager::establish(const Session& session,
238✔
24
                                                         const std::optional<Session_ID>& id,
25
                                                         bool tls12_no_ticket) {
26
   // Establishing a session does not require locking at this level as
27
   // concurrent TLS instances on a server will create unique sessions.
28

29
   // By default, the session manager does not emit session tickets anyway
30
   BOTAN_UNUSED(tls12_no_ticket);
238✔
31
   BOTAN_ASSERT(session.side() == Connection_Side::Server, "Client tried to establish a session");
238✔
32

33
   Session_Handle handle(id.value_or(m_rng->random_vec<Session_ID>(32)));
714✔
34
   store(session, handle);
238✔
35
   return handle;
238✔
36
}
238✔
37

38
std::optional<Session> Session_Manager::retrieve(const Session_Handle& handle,
584✔
39
                                                 Callbacks& callbacks,
40
                                                 const Policy& policy) {
41
   // Retrieving a session for a given handle does not require locking on this
42
   // level. Concurrent threads might handle the removal of an expired ticket
43
   // more than once, but removing an already removed ticket is a harmless NOOP.
44

45
   auto session = retrieve_one(handle);
584✔
46
   if(!session.has_value()) {
584✔
47
      return std::nullopt;
185✔
48
   }
49

50
   // A value of '0' means: No policy restrictions.
51
   const std::chrono::seconds policy_lifetime =
399✔
52
      (policy.session_ticket_lifetime().count() > 0) ? policy.session_ticket_lifetime() : std::chrono::seconds::max();
399✔
53

54
   // RFC 5077 3.3 -- "Old Session Tickets"
55
   //    A server MAY treat a ticket as valid for a shorter or longer period of
56
   //    time than what is stated in the ticket_lifetime_hint.
57
   //
58
   // RFC 5246 F.1.4 -- TLS 1.2
59
   //    If either party suspects that the session may have been compromised, or
60
   //    that certificates may have expired or been revoked, it should force a
61
   //    full handshake.  An upper limit of 24 hours is suggested for session ID
62
   //    lifetimes.
63
   //
64
   // RFC 8446 4.6.1 -- TLS 1.3
65
   //    A server MAY treat a ticket as valid for a shorter period of time than
66
   //    what is stated in the ticket_lifetime.
67
   //
68
   // Note: This disregards what is stored in the session (e.g. "lifetime_hint")
69
   //       and only takes the local policy into account. The lifetime stored in
70
   //       the sessions was taken from the same policy anyways and changes by
71
   //       the application should have an immediate effect.
72
   const auto ticket_age =
399✔
73
      std::chrono::duration_cast<std::chrono::seconds>(callbacks.tls_current_timestamp() - session->start_time());
399✔
74
   const bool expired = ticket_age > policy_lifetime;
399✔
75

76
   if(expired) {
399✔
77
      remove(handle);
10✔
78
      return std::nullopt;
10✔
79
   } else {
80
      return session;
973✔
81
   }
82
}
584✔
83

84
std::vector<Session_with_Handle> Session_Manager::find_and_filter(const Server_Information& info,
3,648✔
85
                                                                  Callbacks& callbacks,
86
                                                                  const Policy& policy) {
87
   // A value of '0' means: No policy restrictions. Session ticket lifetimes as
88
   // communicated by the server apply regardless.
89
   const std::chrono::seconds policy_lifetime =
3,648✔
90
      (policy.session_ticket_lifetime().count() > 0) ? policy.session_ticket_lifetime() : std::chrono::seconds::max();
3,648✔
91

92
   const size_t max_sessions_hint = std::max(policy.maximum_session_tickets_per_client_hello(), size_t(1));
3,648✔
93
   const auto now = callbacks.tls_current_timestamp();
3,648✔
94

95
   // An arbitrary number of loop iterations to perform before giving up
96
   // to avoid a potential endless loop with a misbehaving session manager.
97
   constexpr unsigned int max_attempts = 10;
3,648✔
98
   std::vector<Session_with_Handle> sessions_and_handles;
3,648✔
99

100
   // Query the session manager implementation for new sessions until at least
101
   // one session passes the filter or no more sessions are found.
102
   for(unsigned int attempt = 0; attempt < max_attempts && sessions_and_handles.empty(); ++attempt) {
4,068✔
103
      sessions_and_handles = find_some(info, max_sessions_hint);
3,657✔
104

105
      // ... underlying implementation didn't find anything. Early exit.
106
      if(sessions_and_handles.empty()) {
3,657✔
107
         break;
108
      }
109

110
      // TODO: C++20, use std::ranges::remove_if() once XCode and Android NDK caught up.
111
      sessions_and_handles.erase(
420✔
112
         std::remove_if(sessions_and_handles.begin(),
420✔
113
                        sessions_and_handles.end(),
114
                        [&](const auto& session) {
813✔
115
                           const auto age =
116
                              std::chrono::duration_cast<std::chrono::seconds>(now - session.session.start_time());
813✔
117

118
                           // RFC 5077 3.3 -- "Old Session Tickets"
119
                           //    The ticket_lifetime_hint field contains a hint from the
120
                           //    server about how long the ticket should be stored. [...]
121
                           //    A client SHOULD delete the ticket and associated state when
122
                           //    the time expires. It MAY delete the ticket earlier based on
123
                           //    local policy.
124
                           //
125
                           // RFC 5246 F.1.4 -- TLS 1.2
126
                           //    If either party suspects that the session may have been
127
                           //    compromised, or that certificates may have expired or been
128
                           //    revoked, it should force a full handshake.  An upper limit of
129
                           //    24 hours is suggested for session ID lifetimes.
130
                           //
131
                           // RFC 8446 4.2.11.1 -- TLS 1.3
132
                           //    The client's view of the age of a ticket is the time since the
133
                           //    receipt of the NewSessionTicket message.  Clients MUST NOT
134
                           //    attempt to use tickets which have ages greater than the
135
                           //    "ticket_lifetime" value which was provided with the ticket.
136
                           //
137
                           // RFC 8446 4.6.1 -- TLS 1.3
138
                           //    Clients MUST NOT cache tickets for longer than 7 days,
139
                           //    regardless of the ticket_lifetime, and MAY delete tickets
140
                           //    earlier based on local policy.
141
                           //
142
                           // Note: TLS 1.3 tickets with a lifetime longer than 7 days are
143
                           //       rejected during parsing with an "Illegal Parameter" alert.
144
                           //       Other suggestions are left to the application via
145
                           //       Policy::session_ticket_lifetime(). Session lifetimes as
146
                           //       communicated by the server via the "lifetime_hint" are
147
                           //       obeyed regardless of the policy setting.
148
                           const auto session_lifetime_hint = session.session.lifetime_hint();
813✔
149
                           const bool expired = age > std::min(policy_lifetime, session_lifetime_hint);
1,652✔
150

151
                           if(expired) {
813✔
152
                              remove(session.handle);
22✔
153
                           }
154

155
                           return expired;
813✔
156
                        }),
157
         sessions_and_handles.end());
420✔
158
   }
159

160
   return sessions_and_handles;
3,648✔
161
}
×
162

163
std::vector<Session_with_Handle> Session_Manager::find(const Server_Information& info,
3,648✔
164
                                                       Callbacks& callbacks,
165
                                                       const Policy& policy) {
166
   auto allow_reusing_tickets = policy.reuse_session_tickets();
3,648✔
167

168
   // Session_Manager::find() must be an atomic getter if ticket reuse is not
169
   // allowed. I.e. each ticket handed to concurrently requesting threads must
170
   // be unique. In that case we must hold a lock while retrieving a ticket.
171
   // Otherwise, no locking is required on this level.
172
   std::optional<lock_guard_type<recursive_mutex_type>> lk;
3,648✔
173
   if(!allow_reusing_tickets) {
3,648✔
174
      lk.emplace(mutex());
3,625✔
175
   }
176

177
   auto sessions_and_handles = find_and_filter(info, callbacks, policy);
3,648✔
178

179
   // std::vector::resize() cannot be used as the vector's members aren't
180
   // default constructible.
181
   const auto session_limit = policy.maximum_session_tickets_per_client_hello();
3,648✔
182
   while(session_limit > 0 && sessions_and_handles.size() > session_limit) {
4,005✔
183
      sessions_and_handles.pop_back();
357✔
184
   }
185

186
   // RFC 8446 Appendix C.4
187
   //    Clients SHOULD NOT reuse a ticket for multiple connections. Reuse of
188
   //    a ticket allows passive observers to correlate different connections.
189
   //
190
   // When reuse of session tickets is not allowed, remove all tickets to be
191
   // returned from the implementation's internal storage.
192
   if(!allow_reusing_tickets) {
3,648✔
193
      // The lock must be held here, otherwise we cannot guarantee the
194
      // transactional retrieval of tickets to concurrently requesting clients.
195
      BOTAN_ASSERT_NOMSG(lk.has_value());
3,625✔
196
      for(const auto& [session, handle] : sessions_and_handles) {
4,023✔
197
         if(!session.version().is_pre_tls_13() || !handle.is_id()) {
398✔
198
            remove(handle);
265✔
199
         }
200
      }
201
   }
202

203
   return sessions_and_handles;
3,648✔
204
}
3,648✔
205

206
#if defined(BOTAN_HAS_TLS_13)
207

208
std::optional<std::pair<Session, uint16_t>> Session_Manager::choose_from_offered_tickets(
112✔
209
   const std::vector<PskIdentity>& tickets,
210
   std::string_view hash_function,
211
   Callbacks& callbacks,
212
   const Policy& policy) {
213
   // Note that the TLS server currently does not ensure that tickets aren't
214
   // reused. As a result, no locking is required on this level.
215

216
   for(uint16_t i = 0; const auto& ticket : tickets) {
132✔
217
      auto session = retrieve(Opaque_Session_Handle(ticket.identity()), callbacks, policy);
246✔
218
      if(session.has_value() && session->ciphersuite().prf_algo() == hash_function &&
457✔
219
         session->version().is_tls_13_or_later()) {
228✔
220
         return std::pair{std::move(session.value()), i};
103✔
221
      }
222

223
      // RFC 8446 4.2.10
224
      //    For PSKs provisioned via NewSessionTicket, a server MUST validate
225
      //    that the ticket age for the selected PSK identity [...] is within a
226
      //    small tolerance of the time since the ticket was issued.  If it is
227
      //    not, the server SHOULD proceed with the handshake but reject 0-RTT,
228
      //    and SHOULD NOT take any other action that assumes that this
229
      //    ClientHello is fresh.
230
      //
231
      // TODO: The ticket-age is currently not checked (as 0-RTT is not
232
      //       implemented) and we simply take the SHOULD at face value.
233
      //       Instead we could add a policy check letting the user decide.
234

235
      ++i;
20✔
236
   }
123✔
237

238
   return std::nullopt;
9✔
239
}
240

241
#endif
242

243
}  // namespace Botan::TLS
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc