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

randombit / botan / 5079590438

25 May 2023 12:28PM UTC coverage: 92.228% (+0.5%) from 91.723%
5079590438

Pull #3502

github

Pull Request #3502: Apply clang-format to the codebase

75589 of 81959 relevant lines covered (92.23%)

12139530.51 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/rng.h>
12
#include <botan/tls_callbacks.h>
13
#include <botan/tls_policy.h>
14

15
namespace Botan::TLS {
16

17
Session_Manager::Session_Manager(const std::shared_ptr<RandomNumberGenerator>& rng) : m_rng(rng) {
9,205✔
18
   BOTAN_ASSERT_NONNULL(m_rng);
9,205✔
19
}
9,205✔
20

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

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

31
   Session_Handle handle(id.value_or(m_rng->random_vec<Session_ID>(32)));
711✔
32
   store(session, handle);
237✔
33
   return handle;
237✔
34
}
237✔
35

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

43
   auto session = retrieve_one(handle);
501✔
44
   if(!session.has_value())
501✔
45
      return std::nullopt;
97✔
46

47
   // A value of '0' means: No policy restrictions.
48
   const std::chrono::seconds policy_lifetime =
404✔
49
      (policy.session_ticket_lifetime().count() > 0) ? policy.session_ticket_lifetime() : std::chrono::seconds::max();
404✔
50

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

73
   if(expired) {
404✔
74
      remove(handle);
10✔
75
      return std::nullopt;
10✔
76
   } else {
77
      return session;
895✔
78
   }
79
}
501✔
80

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

89
   const size_t max_sessions_hint = std::max(policy.maximum_session_tickets_per_client_hello(), size_t(1));
3,563✔
90
   const auto now = callbacks.tls_current_timestamp();
3,563✔
91

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

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

102
      // ... underlying implementation didn't find anything. Early exit.
103
      if(sessions_and_handles.empty()) {
3,572✔
104
         break;
105
      }
106

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

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

148
                           if(expired) {
841✔
149
                              remove(session.handle);
22✔
150
                           }
151

152
                           return expired;
841✔
153
                        }),
154
         sessions_and_handles.end());
421✔
155
   }
156

157
   return sessions_and_handles;
3,563✔
158
}
×
159

160
std::vector<Session_with_Handle> Session_Manager::find(const Server_Information& info,
3,563✔
161
                                                       Callbacks& callbacks,
162
                                                       const Policy& policy) {
163
   auto allow_reusing_tickets = policy.reuse_session_tickets();
3,563✔
164

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

174
   auto sessions_and_handles = find_and_filter(info, callbacks, policy);
3,563✔
175

176
   // std::vector::resize() cannot be used as the vector's members aren't
177
   // default constructible.
178
   const auto session_limit = policy.maximum_session_tickets_per_client_hello();
3,563✔
179
   while(session_limit > 0 && sessions_and_handles.size() > session_limit) {
3,947✔
180
      sessions_and_handles.pop_back();
4,331✔
181
   }
182

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

200
   return sessions_and_handles;
3,563✔
201
}
3,563✔
202

203
#if defined(BOTAN_HAS_TLS_13)
204

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

210
   for(uint16_t i = 0; const auto& ticket : tickets) {
131✔
211
      auto session = retrieve(ticket.identity(), callbacks, policy);
248✔
212
      if(session.has_value() && session->ciphersuite().prf_algo() == hash_function &&
466✔
213
         session->version().is_tls_13_or_later()) {
232✔
214
         return std::pair{std::move(session.value()), i};
106✔
215
      }
216

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

229
      ++i;
18✔
230
   }
124✔
231

232
   return std::nullopt;
7✔
233
}
234

235
#endif
236

237
}
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