| // you may not use this file except in compliance with the License. |
| 7 | // You may obtain a copy of the License at |
| 8 | // |
| 9 | // https://www.apache.org/licenses/LICENSE-2.0 |
| 10 | // |
| 11 | // Unless required by applicable law or agreed to in writing, software |
| 12 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | // See the License for the specific language governing permissions and |
| 15 | // limitations under the License. |
| 16 |
| 17 | #ifndef OPENSSL_HEADER_SSL_INTERNAL_H |
| 18 | #define OPENSSL_HEADER_SSL_INTERNAL_H |
| 19 |
| 20 | #include <openssl/base.h> |
| 21 |
| 22 | #include <stdlib.h> |
| 23 |
| 24 | #include <algorithm> |
| 25 | #include <atomic> |
| 26 | #include <bitset> |
| 27 | #include <initializer_list> |
| 28 | #include <limits> |
| 29 | #include <new> |
| 30 | #include <optional> |
| 31 | #include <string_view> |
| 32 | #include <type_traits> |
| 33 | #include <utility> |
| 34 |
| 35 | #include <openssl/aead.h> |
| 36 | #include <openssl/curve25519.h> |
| 37 | #include <openssl/err.h> |
| 38 | #include <openssl/hpke.h> |
| 39 | #include <openssl/lhash.h> |
| 40 | #include <openssl/mem.h> |
| 41 | #include <openssl/span.h> |
| 42 | #include <openssl/ssl.h> |
| 43 | #include <openssl/stack.h> |
| 44 |
| 45 | #include "../crypto/err/internal.h" |
| 46 | #include "../crypto/internal.h" |
| 47 | #include "../crypto/lhash/internal.h" |
| 48 | #include "../crypto/spake2plus/internal.h" |
| 49 |
| 50 |
| 51 | #if defined(OPENSSL_WINDOWS) |
| 52 | // Windows defines struct timeval in winsock2.h. |
| 53 | #include <winsock2.h> |
| 54 | #else |
| 55 | #include <sys/time.h> |
| 56 | #endif |
| 57 |
| 58 |
| 59 | BSSL_NAMESPACE_BEGIN |
| 60 |
| 61 | struct SSL_CONFIG; |
| 62 | struct SSL_HANDSHAKE; |
| 63 | struct SSL_PROTOCOL_METHOD; |
| 64 | struct SSL_X509_METHOD; |
| 65 |
| 66 | // C++ utilities. |
| 67 |
| 68 | // New behaves like |new| but uses |OPENSSL_malloc| for memory allocation. It |
| 69 | // returns nullptr on allocation error. It only implements single-object |
| 70 | // allocation and not new T[n]. |
| 71 | // |
| 72 | // Note: unlike |new|, this does not support non-public constructors. |
| 73 | template <typename T, typename... Args> |
| 74 | T *New(Args &&...args) { |
| 75 | void *t = OPENSSL_malloc(sizeof(T)); |
| 76 | if (t == nullptr) { |
| 77 | return nullptr; |
| 78 | } |
| 79 | return new (t) T(std::forward<Args>(args)...); |
| 80 | } |
| 81 |
| 82 | // Delete behaves like |delete| but uses |OPENSSL_free| to release memory. |
| 83 | // |
| 84 | // Note: unlike |delete| this does not support non-public destructors. |
| 85 | template <typename T> |
| 86 | void Delete(T *t) { |
| 87 | if (t != nullptr) { |
| 88 | t->~T(); |
| 89 | OPENSSL_free(t); |
| 90 | } |
| 91 | } |
| 92 |
| 93 | // All types with kAllowUniquePtr set may be used with UniquePtr. Other types |
| 94 | // may be C structs which require a |BORINGSSL_MAKE_DELETER| registration. |
| 95 | namespace internal { |
| 96 | template <typename T> |
| 97 | struct DeleterImpl<T, std::enable_if_t<T::kAllowUniquePtr>> { |
| 98 | static void Free(T *t) { Delete(t); } |
| 99 | }; |
| 100 | } // namespace internal |
| 101 |
| 102 | // MakeUnique behaves like |std::make_unique| but returns nullptr on allocation |
| 103 | // error. |
| 104 | template <typename T, typename... Args> |
| 105 | UniquePtr<T> MakeUnique(Args &&...args) { |
| 106 | return UniquePtr<T>(New<T>(std::forward<Args>(args)...)); |
| 107 | } |
| 108 |
| 109 | // Array<T> is an owning array of elements of |T|. |
| 110 | template <typename T> |
| 111 | class Array { |
| 112 | public: |
| 113 | // Array's default constructor creates an empty array. |
| 114 | Array() {} |
| 115 | Array(const Array &) = delete; |
| 116 | Array(Array &&other) { *this = std::move(other); } |
| 117 |
| 118 | ~Array() { Reset(); } |
| 119 |
| 120 | Array &operator=(const Array &) = delete; |
| 121 | Array &operator=(Array &&other) { |
| 122 | Reset(); |
| 123 | other.Release(&data_, &size_); |
| 124 | return *this; |
| 125 | } |
| 126 |
| 127 | const T *data() const { return data_; } |
| 128 | T *data() { return data_; } |
| 129 | size_t size() const { return size_; } |
| 130 | bool empty() const { return size_ == 0; } |
| 131 |
| 132 | const T &operator[](size_t i) const { |
| 133 | BSSL_CHECK(i < size_); |
| 134 | return data_[i]; |
| 135 | } |
| 136 | T &operator[](size_t i) { |
| 137 | BSSL_CHECK(i < size_); |
| 138 | return data_[i]; |
| 139 | } |
| 140 |
| 141 | T *begin() { return data_; } |
| 142 | const T *begin() const { return data_; } |
| 143 | T *end() { return data_ + size_; } |
| 144 | const T *end() const { return data_ + size_; } |
| 145 |
| 146 | void Reset() { Reset(nullptr, 0); } |
| 147 |
| 148 | // Reset releases the current contents of the array and takes ownership of the |
| 149 | // raw pointer supplied by the caller. |
| 150 | void Reset(T *new_data, size_t new_size) { |
| 151 | std::destroy_n(data_, size_); |
| 152 | OPENSSL_free(data_); |
| 153 | data_ = new_data; |
| 154 | size_ = new_size; |
| 155 | } |
| 156 |
| 157 | // Release releases ownership of the array to a raw pointer supplied by the |
| 158 | // caller. |
| 159 | void Release(T **out, size_t *out_size) { |
| 160 | *out = data_; |
| 161 | *out_size = size_; |
| 162 | data_ = nullptr; |
| 163 | size_ = 0; |
| 164 | } |
| 165 |
| 166 | // Init replaces the array with a newly-allocated array of |new_size| |
| 167 | // value-constructed copies of |T|. It returns true on success and false on |
| 168 | // error. If |T| is a primitive type like |uint8_t|, value-construction means |
| 169 | // it will be zero-initialized. |
| 170 | [[nodiscard]] bool Init(size_t new_size) { |
| 171 | if (!InitUninitialized(new_size)) { |
| 172 | return false; |
| 173 | } |
| 174 | std::uninitialized_value_construct_n(data_, size_); |
| 175 | return true; |
| 176 | } |
| 177 |
| 178 | // InitForOverwrite behaves like |Init| but it default-constructs each element |
| 179 | // instead. This means that, if |T| is a primitive type, the array will be |
| 180 | // uninitialized and thus must be filled in by the caller. |
| 181 | [[nodiscard]] bool InitForOverwrite(size_t new_size) { |
| 182 | if (!InitUninitialized(new_size)) { |
| 183 | return false; |
| 184 | } |
| 185 | std::uninitialized_default_construct_n(data_, size_); |
| 186 | return true; |
| 187 | } |
| 188 |
| 189 | // CopyFrom replaces the array with a newly-allocated copy of |in|. It returns |
| 190 | // true on success and false on error. |
| 191 | [[nodiscard]] bool CopyFrom(Span<const T> in) { |
| 192 | if (!InitUninitialized(in.size())) { |
| 193 | return false; |
| 194 | } |
| 195 | std::uninitialized_copy(in.begin(), in.end(), data_); |
| 196 | return true; |
| 197 | } |
| 198 |
| 199 | // Shrink shrinks the stored size of the array to |new_size|. It crashes if |
| 200 | // the new size is larger. Note this does not shrink the allocation itself. |
| 201 | void Shrink(size_t new_size) { |
| 202 | if (new_size > size_) { |
| 203 | abort(); |
| 204 | } |
| 205 | std::destroy_n(data_ + new_size, size_ - new_size); |
| 206 | size_ = new_size; |
| 207 | } |
| 208 |
| 209 | private: |
| 210 | // InitUninitialized replaces the array with a newly-allocated array of |
| 211 | // |new_size| elements, but whose constructor has not yet run. On success, the |
| 212 | // elements must be constructed before returning control to the caller. |
| 213 | bool InitUninitialized(size_t new_size) { |
| 214 | Reset(); |
| 215 | if (new_size == 0) { |
| 216 | return true; |
| 217 | } |
| 218 |
| 219 | if (new_size > std::numeric_limits<size_t>::max() / sizeof(T)) { |
| 220 | OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW); |
| 221 | return false; |
| 222 | } |
| 223 | data_ = reinterpret_cast<T *>(OPENSSL_malloc(new_size * sizeof(T))); |
| 224 | if (data_ == nullptr) { |
| 225 | return false; |
| 226 | } |
| 227 | size_ = new_size; |
| 228 | return true; |
| 229 | } |
| 230 |
| 231 | T *data_ = nullptr; |
| 232 | size_t size_ = 0; |
| 233 | }; |
| 234 |
| 235 | // Vector<T> is a resizable array of elements of |T|. |
| 236 | template <typename T> |
| 237 | class Vector { |
| 238 | public: |
| 239 | Vector() = default; |
| 240 | Vector(const Vector &) = delete; |
| 241 | Vector(Vector &&other) { *this = std::move(other); } |
| 242 | ~Vector() { clear(); } |
| 243 |
| 244 | Vector &operator=(const Vector &) = delete; |
| 245 | Vector &operator=(Vector &&other) { |
| 246 | clear(); |
| 247 | std::swap(data_, other.data_); |
| 248 | std::swap(size_, other.size_); |
| 249 | std::swap(capacity_, other.capacity_); |
| 250 | return *this; |
| 251 | } |
| 252 |
| 253 | const T *data() const { return data_; } |
| 254 | T *data() { return data_; } |
| 255 | size_t size() const { return size_; } |
| 256 | bool empty() const { return size_ == 0; } |
| 257 |
| 258 | const T &operator[](size_t i) const { |
| 259 | BSSL_CHECK(i < size_); |
| 260 | return data_[i]; |
| 261 | } |
| 262 | T &operator[](size_t i) { |
| 263 | BSSL_CHECK(i < size_); |
| 264 | return data_[i]; |
| 265 | } |
| 266 |
| 267 | T *begin() { return data_; } |
| 268 | const T *begin() const { return data_; } |
| 269 | T *end() { return data_ + size_; } |
| 270 | const T *end() const { return data_ + size_; } |
| 271 |
| 272 | void clear() { |
| 273 | std::destroy_n(data_, size_); |
| 274 | OPENSSL_free(data_); |
| 275 | data_ = nullptr; |
| 276 | size_ = 0; |
| 277 | capacity_ = 0; |
| 278 | } |
| 279 |
| 280 | // Push adds |elem| at the end of the internal array, growing if necessary. It |
| 281 | // returns false when allocation fails. |
| 282 | [[nodiscard]] bool Push(T elem) { |
| 283 | if (!MaybeGrow()) { |
| 284 | return false; |
| 285 | } |
| 286 | new (&data_[size_]) T(std::move(elem)); |
| 287 | size_++; |
| 288 | return true; |
| 289 | } |
| 290 |
| 291 | // CopyFrom replaces the contents of the array with a copy of |in|. It returns |
| 292 | // true on success and false on allocation error. |
| 293 | [[nodiscard]] bool CopyFrom(Span<const T> in) { |
| 294 | Array<T> copy; |
| 295 | if (!copy.CopyFrom(in)) { |
| 296 | return false; |
| 297 | } |
| 298 |
| 299 | clear(); |
| 300 | copy.Release(&data_, &size_); |
| 301 | capacity_ = size_; |
| 302 | return true; |
| 303 | } |
| 304 |
| 305 | private: |
| 306 | // If there is no room for one more element, creates a new backing array with |
| 307 | // double the size of the old one and copies elements over. |
| 308 | bool MaybeGrow() { |
| 309 | // No need to grow if we have room for one more T. |
| 310 | if (size_ < capacity_) { |
| 311 | return true; |
| 312 | } |
| 313 | size_t new_capacity = kDefaultSize; |
| 314 | if (capacity_ > 0) { |
| 315 | // Double the array's size if it's safe to do so. |
| 316 | if (capacity_ > std::numeric_limits<size_t>::max() / 2) { |
| 317 | OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW); |
| 318 | return false; |
| 319 | } |
| 320 | new_capacity = capacity_ * 2; |
| 321 | } |
| 322 | if (new_capacity > std::numeric_limits<size_t>::max() / sizeof(T)) { |
| 323 | OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW); |
| 324 | return false; |
| 325 | } |
| 326 | T *new_data = |
| 327 | reinterpret_cast<T *>(OPENSSL_malloc(new_capacity * sizeof(T))); |
| 328 | if (new_data == nullptr) { |
| 329 | return false; |
| 330 | } |
| 331 | size_t new_size = size_; |
| 332 | std::uninitialized_move(begin(), end(), new_data); |
| 333 | clear(); |
| 334 | data_ = new_data; |
| 335 | size_ = new_size; |
| 336 | capacity_ = new_capacity; |
| 337 | return true; |
| 338 | } |
| 339 |
| 340 | // data_ is a pointer to |capacity_| objects of size |T|, the first |size_| of |
| 341 | // which are constructed. |
| 342 | T *data_ = nullptr; |
| 343 | // |size_| is the number of elements stored in this Vector. |
| 344 | size_t size_ = 0; |
| 345 | // |capacity_| is the number of elements allocated in this Vector. |
| 346 | size_t capacity_ = 0; |
| 347 | // |kDefaultSize| is the default initial size of the backing array. |
| 348 | static constexpr size_t kDefaultSize = 16; |
| 349 | }; |
| 350 |
| 351 | // A PackedSize is an integer that can store values from 0 to N, represented as |
| 352 | // a minimal-width integer. |
| 353 | template <size_t N> |
| 354 | using PackedSize = std::conditional_t< |
| 355 | N <= 0xff, uint8_t, |
| 356 | std::conditional_t<N <= 0xffff, uint16_t, |
| 357 | std::conditional_t<N <= 0xffffffff, uint32_t, size_t>>>; |
| 358 |
| 359 | // An InplaceVector is like a Vector, but stores up to N elements inline in the |
| 360 | // object. It is inspired by std::inplace_vector in C++26. |
| 361 | template <typename T, size_t N> |
| 362 | class InplaceVector { |
| 363 | public: |
| 364 | InplaceVector() = default; |
| 365 | InplaceVector(const InplaceVector &other) { *this = other; } |
| 366 | InplaceVector(InplaceVector &&other) { *this = std::move(other); } |
| 367 | ~InplaceVector() { clear(); } |
| 368 | InplaceVector &operator=(const InplaceVector &other) { |
| 369 | if (this != &other) { |
| 370 | CopyFrom(other); |
| 371 | } |
| 372 | return *this; |
| 373 | } |
| 374 | InplaceVector &operator=(InplaceVector &&other) { |
| 375 | clear(); |
| 376 | std::uninitialized_move(other.begin(), other.end(), data()); |
| 377 | size_ = other.size(); |
| 378 | return *this; |
| 379 | } |
| 380 |
| 381 | const T *data() const { return reinterpret_cast<const T *>(storage_); } |
| 382 | T *data() { return reinterpret_cast<T *>(storage_); } |
| 383 | size_t size() const { return size_; } |
| 384 | static constexpr size_t capacity() { return N; } |
| 385 | bool empty() const { return size_ == 0; } |
| 386 |
| 387 | const T &operator[](size_t i) const { |
| 388 | BSSL_CHECK(i < size_); |
| 389 | return data()[i]; |
| 390 | } |
| 391 | T &operator[](size_t i) { |
| 392 | BSSL_CHECK(i < size_); |
| 393 | return data()[i]; |
| 394 | } |
| 395 |
| 396 | T *begin() { return data(); } |
| 397 | const T *begin() const { return data(); } |
| 398 | T *end() { return data() + size_; } |
| 399 | const T *end() const { return data() + size_; } |
| 400 |
| 401 | void clear() { Shrink(0); } |
| 402 |
| 403 | // Shrink resizes the vector to |new_size|, which must not be larger than the |
| 404 | // current size. Unlike |Resize|, this can be called when |T| is not |
| 405 | // default-constructible. |
| 406 | void Shrink(size_t new_size) { |
| 407 | BSSL_CHECK(new_size <= size_); |
| 408 | std::destroy_n(data() + new_size, size_ - new_size); |
| 409 | size_ = static_cast<PackedSize<N>>(new_size); |
| 410 | } |
| 411 |
| 412 | // TryResize resizes the vector to |new_size| and returns true, or returns |
| 413 | // false if |new_size| is too large. Any newly-added elements are |
| 414 | // value-initialized. |
| 415 | [[nodiscard]] bool TryResize(size_t new_size) { |
| 416 | if (new_size <= size_) { |
| 417 | Shrink(new_size); |
| 418 | return true; |
| 419 | } |
| 420 | if (new_size > capacity()) { |
| 421 | return false; |
| 422 | } |
| 423 | std::uninitialized_value_construct_n(data() + size_, new_size - size_); |
| 424 | size_ = static_cast<PackedSize<N>>(new_size); |
| 425 | return true; |
| 426 | } |
| 427 |
| 428 | // TryResizeForOverwrite behaves like |TryResize|, but newly-added elements |
| 429 | // are default-initialized, so POD types may contain uninitialized values that |
| 430 | // the caller is responsible for filling in. |
| 431 | [[nodiscard]] bool TryResizeForOverwrite(size_t new_size) { |
| 432 | if (new_size <= size_) { |
| 433 | Shrink(new_size); |
| 434 | return true; |
| 435 | } |
| 436 | if (new_size > capacity()) { |
| 437 | return false; |
| 438 | } |
| 439 | std::uninitialized_default_construct_n(data() + size_, new_size - size_); |
| 440 | size_ = static_cast<PackedSize<N>>(new_size); |
| 441 | return true; |
| 442 | } |
| 443 |
| 444 | // TryCopyFrom sets the vector to a copy of |in| and returns true, or returns |
| 445 | // false if |in| is too large. |
| 446 | [[nodiscard]] bool TryCopyFrom(Span<const T> in) { |
| 447 | if (in.size() > capacity()) { |
| 448 | return false; |
| 449 | } |
| 450 | clear(); |
| 451 | std::uninitialized_copy(in.begin(), in.end(), data()); |
| 452 | size_ = in.size(); |
| 453 | return true; |
| 454 | } |
| 455 |
| 456 | // TryPushBack appends |val| to the vector and returns a pointer to the |
| 457 | // newly-inserted value, or nullptr if the vector is at capacity. |
| 458 | [[nodiscard]] T *TryPushBack(T val) { |
| 459 | if (size() >= capacity()) { |
| 460 | return nullptr; |
| 461 | } |
| 462 | T *ret = &data()[size_]; |
| 463 | new (ret) T(std::move(val)); |
| 464 | size_++; |
| 465 | return ret; |
| 466 | } |
| 467 |
| 468 | // The following methods behave like their |Try*| counterparts, but abort the |
| 469 | // program on failure. |
| 470 | void Resize(size_t size) { BSSL_CHECK(TryResize(size)); } |
| 471 | void ResizeForOverwrite(size_t size) { |
| 472 | BSSL_CHECK(TryResizeForOverwrite(size)); |
| 473 | } |
| 474 | void CopyFrom(Span<const T> in) { BSSL_CHECK(TryCopyFrom(in)); } |
| 475 | T &PushBack(T val) { |
| 476 | T *ret = TryPushBack(std::move(val)); |
| 477 | BSSL_CHECK(ret != nullptr); |
| 478 | return *ret; |
| 479 | } |
| 480 |
| 481 | template <typename Pred> |
| 482 | void EraseIf(Pred pred) { |
| 483 | // See if anything needs to be erased at all. This avoids a self-move. |
| 484 | auto iter = std::find_if(begin(), end(), pred); |
| 485 | if (iter == end()) { |
| 486 | return; |
| 487 | } |
| 488 |
| 489 | // Elements before the first to be erased may be left as-is. |
| 490 | size_t new_size = iter - begin(); |
| 491 | // Swap all subsequent elements in if they are to be kept. |
| 492 | for (size_t i = new_size + 1; i < size(); i++) { |
| 493 | if (!pred((*this)[i])) { |
| 494 | (*this)[new_size] = std::move((*this)[i]); |
| 495 | new_size++; |
| 496 | } |
| 497 | } |
| 498 |
| 499 | Shrink(new_size); |
| 500 | } |
| 501 |
| 502 | private: |
| 503 | alignas(T) char storage_[sizeof(T[N])]; |
| 504 | PackedSize<N> size_ = 0; |
| 505 | }; |
| 506 |
| 507 | // An MRUQueue maintains a queue of up to |N| objects of type |T|. If the queue |
| 508 | // is at capacity, adding to the queue pops the least recently added element. |
| 509 | template <typename T, size_t N> |
| 510 | class MRUQueue { |
| 511 | public: |
| 512 | static constexpr bool kAllowUniquePtr = true; |
| 513 |
| 514 | MRUQueue() = default; |
| 515 |
| 516 | // If we ever need to make this type movable, we could. (The defaults almost |
| 517 | // work except we need |start_| to be reset when moved-from.) |
| 518 | MRUQueue(const MRUQueue &other) = delete; |
| 519 | MRUQueue &operator=(const MRUQueue &other) = delete; |
| 520 |
| 521 | bool empty() const { return size() == 0; } |
| 522 | size_t size() const { return storage_.size(); } |
| 523 |
| 524 | T &operator[](size_t i) { |
| 525 | BSSL_CHECK(i < size()); |
| 526 | return storage_[(start_ + i) % N]; |
| 527 | } |
| 528 | const T &operator[](size_t i) const { |
| 529 | return (*const_cast<MRUQueue *>(this))[i]; |
| 530 | } |
| 531 |
| 532 | void Clear() { |
| 533 | storage_.clear(); |
| 534 | start_ = 0; |
| 535 | } |
| 536 |
| 537 | void PushBack(T t) { |
| 538 | if (storage_.size() < N) { |
| 539 | assert(start_ == 0); |
| 540 | storage_.PushBack(std::move(t)); |
| 541 | } else { |
| 542 | (*this)[0] = std::move(t); |
| 543 | start_ = (start_ + 1) % N; |
| 544 | } |
| 545 | } |
| 546 |
| 547 | private: |
| 548 | InplaceVector<T, N> storage_; |
| 549 | PackedSize<N> start_ = 0; |
| 550 | }; |
| 551 |
| 552 | // CBBFinishArray behaves like |CBB_finish| but stores the result in an Array. |
| 553 | OPENSSL_EXPORT bool CBBFinishArray(CBB *cbb, Array<uint8_t> *out); |
| 554 |
| 555 | // GetAllNames helps to implement |*_get_all_*_names| style functions. It |
| 556 | // writes at most |max_out| string pointers to |out| and returns the number that |
| 557 | // it would have liked to have written. The strings written consist of |
| 558 | // |fixed_names_len| strings from |fixed_names| followed by |objects_len| |
| 559 | // strings taken by projecting |objects| through |name|. |
| 560 | template <typename T, typename Name> |
| 561 | inline size_t GetAllNames(const char **out, size_t max_out, |
| 562 | Span<const char *const> fixed_names, Name(T::*name), |
| 563 | Span<const T> objects) { |
| 564 | auto span = bssl::Span(out, max_out); |
| 565 | for (size_t i = 0; !span.empty() && i < fixed_names.size(); i++) { |
| 566 | span[0] = fixed_names[i]; |
| 567 | span = span.subspan(1); |
| 568 | } |
| 569 | span = span.subspan(0, objects.size()); |
| 570 | for (size_t i = 0; i < span.size(); i++) { |
| 571 | span[i] = objects[i].*name; |
| 572 | } |
| 573 | return fixed_names.size() + objects.size(); |
| 574 | } |
| 575 |
| 576 | // RefCounted is a common base for ref-counted types. This is an instance of the |
| 577 | // C++ curiously-recurring template pattern, so a type Foo must subclass |
| 578 | // RefCounted<Foo>. It additionally must friend RefCounted<Foo> to allow calling |
| 579 | // the destructor. |
| 580 | template <typename Derived> |
| 581 | class RefCounted { |
| 582 | public: |
| 583 | RefCounted(const RefCounted &) = delete; |
| 584 | RefCounted &operator=(const RefCounted &) = delete; |
| 585 |
| 586 | // These methods are intentionally named differently from `bssl::UpRef` to |
| 587 | // avoid a collision. Only the implementations of `FOO_up_ref` and `FOO_free` |
| 588 | // should call these. |
| 589 | void UpRefInternal() { CRYPTO_refcount_inc(&references_); } |
| 590 | void DecRefInternal() { |
| 591 | if (CRYPTO_refcount_dec_and_test_zero(&references_)) { |
| 592 | Derived *d = static_cast<Derived *>(this); |
| 593 | d->~Derived(); |
| 594 | OPENSSL_free(d); |
| 595 | } |
| 596 | } |
| 597 |
| 598 | protected: |
| 599 | // Ensure that only `Derived`, which must inherit from `RefCounted<Derived>`, |
| 600 | // can call the constructor. This catches bugs where someone inherited from |
| 601 | // the wrong base. |
| 602 | class CheckSubClass { |
| 603 | private: |
| 604 | friend Derived; |
| 605 | CheckSubClass() = default; |
| 606 | }; |
| 607 | RefCounted(CheckSubClass) { |
| 608 | static_assert(std::is_base_of<RefCounted, Derived>::value, |
| 609 | "Derived must subclass RefCounted<Derived>"); |
| 610 | } |
| 611 |
| 612 | ~RefCounted() = default; |
| 613 |
| 614 | private: |
| 615 | CRYPTO_refcount_t references_ = 1; |
| 616 | }; |
| 617 |
| 618 |
| 619 | // Protocol versions. |
| 620 | // |
| 621 | // Due to DTLS's historical wire version differences, we maintain two notions of |
| 622 | // version. |
| 623 | // |
| 624 | // The "version" or "wire version" is the actual 16-bit value that appears on |
| 625 | // the wire. It uniquely identifies a version and is also used at API |
| 626 | // boundaries. The set of supported versions differs between TLS and DTLS. Wire |
| 627 | // versions are opaque values and may not be compared numerically. |
| 628 | // |
| 629 | // The "protocol version" identifies the high-level handshake variant being |
| 630 | // used. DTLS versions map to the corresponding TLS versions. Protocol versions |
| 631 | // are sequential and may be compared numerically. |
| 632 |
| 633 | // ssl_protocol_version_from_wire sets |*out| to the protocol version |
| 634 | // corresponding to wire version |version| and returns true. If |version| is not |
| 635 | // a valid TLS or DTLS version, it returns false. |
| 636 | // |
| 637 | // Note this simultaneously handles both DTLS and TLS. Use one of the |
| 638 | // higher-level functions below for most operations. |
| 639 | bool ssl_protocol_version_from_wire(uint16_t *out, uint16_t version); |
| 640 |
| 641 | // ssl_get_version_range sets |*out_min_version| and |*out_max_version| to the |
| 642 | // minimum and maximum enabled protocol versions, respectively. |
| 643 | bool ssl_get_version_range(const SSL_HANDSHAKE *hs, uint16_t *out_min_version, |
| 644 | uint16_t *out_max_version); |
| 645 |
| 646 | // ssl_supports_version returns whether |hs| supports |version|. |
| 647 | bool ssl_supports_version(const SSL_HANDSHAKE *hs, uint16_t version); |
| 648 |
| 649 | // ssl_method_supports_version returns whether |method| supports |version|. |
| 650 | bool ssl_method_supports_version(const SSL_PROTOCOL_METHOD *method, |
| 651 | uint16_t version); |
| 652 |
| 653 | // ssl_add_supported_versions writes the supported versions of |hs| to |cbb|, in |
| 654 | // decreasing preference order. The version list is filtered to those whose |
| 655 | // protocol version is at least |extra_min_version|. |
| 656 | bool ssl_add_supported_versions(const SSL_HANDSHAKE *hs, CBB *cbb, |
| 657 | uint16_t extra_min_version); |
| 658 |
| 659 | // ssl_negotiate_version negotiates a common version based on |hs|'s preferences |
| 660 | // and the peer preference list in |peer_versions|. On success, it returns true |
| 661 | // and sets |*out_version| to the selected version. Otherwise, it returns false |
| 662 | // and sets |*out_alert| to an alert to send. |
| 663 | bool ssl_negotiate_version(SSL_HANDSHAKE *hs, uint8_t *out_alert, |
| 664 | uint16_t *out_version, const CBS *peer_versions); |
| 665 |
| 666 | // ssl_has_final_version returns whether |ssl| has determined the final version. |
| 667 | // This may be used to distinguish the predictive 0-RTT version from the final |
| 668 | // one. |
| 669 | bool ssl_has_final_version(const SSL *ssl); |
| 670 |
| 671 | // ssl_protocol_version returns |ssl|'s protocol version. It is an error to |
| 672 | // call this function before the version is determined. |
| 673 | uint16_t ssl_protocol_version(const SSL *ssl); |
| 674 |
| 675 | // Cipher suites. |
| 676 |
| 677 | BSSL_NAMESPACE_END |
| 678 |
| 679 | struct ssl_cipher_st { |
| 680 | // name is the OpenSSL name for the cipher. |
| 681 | const char *name; |
| 682 | // standard_name is the IETF name for the cipher. |
| 683 | const char *standard_name; |
| 684 | // id is the cipher suite value bitwise OR-d with 0x03000000. |
| 685 | uint32_t id; |
| 686 |
| 687 | // algorithm_* determine the cipher suite. See constants below for the values. |
| 688 | uint32_t algorithm_mkey; |
| 689 | uint32_t algorithm_auth; |
| 690 | uint32_t algorithm_enc; |
| 691 | uint32_t algorithm_mac; |
| 692 | uint32_t algorithm_prf; |
| 693 | }; |
| 694 |
| 695 | BSSL_NAMESPACE_BEGIN |
| 696 |
| 697 | // Bits for |algorithm_mkey| (key exchange algorithm). |
| 698 | #define SSL_kRSA 0x00000001u |
| 699 | #define SSL_kECDHE 0x00000002u |
| 700 | // SSL_kPSK is only set for plain PSK, not ECDHE_PSK. |
| 701 | #define SSL_kPSK 0x00000004u |
| 702 | #define SSL_kGENERIC 0x00000008u |
| 703 |
| 704 | // Bits for |algorithm_auth| (server authentication). |
| 705 | #define SSL_aRSA_SIGN 0x00000001u |
| 706 | #define SSL_aRSA_DECRYPT 0x00000002u |
| 707 | #define SSL_aECDSA 0x00000004u |
| 708 | // SSL_aPSK is set for both PSK and ECDHE_PSK. |
| 709 | #define SSL_aPSK 0x00000008u |
| 710 | #define SSL_aGENERIC 0x00000010u |
| 711 |
| 712 | #define SSL_aCERT (SSL_aRSA_SIGN | SSL_aRSA_DECRYPT | SSL_aECDSA) |
| 713 |
| 714 | // Bits for |algorithm_enc| (symmetric encryption). |
| 715 | #define SSL_3DES 0x00000001u |
| 716 | #define SSL_AES128 0x00000002u |
| 717 | #define SSL_AES256 0x00000004u |
| 718 | #define SSL_AES128GCM 0x00000008u |
| 719 | #define SSL_AES256GCM 0x00000010u |
| 720 | #define SSL_CHACHA20POLY1305 0x00000020u |
| 721 |
| 722 | #define SSL_AES (SSL_AES128 | SSL_AES256 | SSL_AES128GCM | SSL_AES256GCM) |
| 723 |
| 724 | // Bits for |algorithm_mac| (symmetric authentication). |
| 725 | #define SSL_SHA1 0x00000001u |
| 726 | #define SSL_SHA256 0x00000002u |
| 727 | // SSL_AEAD is set for all AEADs. |
| 728 | #define SSL_AEAD 0x00000004u |
| 729 |
| 730 | // Bits for |algorithm_prf| (handshake digest). |
| 731 | #define SSL_HANDSHAKE_MAC_DEFAULT 0x1 |
| 732 | #define SSL_HANDSHAKE_MAC_SHA256 0x2 |
| 733 | #define SSL_HANDSHAKE_MAC_SHA384 0x4 |
| 734 |
| 735 | // SSL_MAX_MD_SIZE is size of the largest hash function used in TLS, SHA-384. |
| 736 | #define SSL_MAX_MD_SIZE 48 |
| 737 |
| 738 | // An SSLCipherPreferenceList contains a list of SSL_CIPHERs with equal- |
| 739 | // preference groups. For TLS clients, the groups are moot because the server |
| 740 | // picks the cipher and groups cannot be expressed on the wire. However, for |
| 741 | // servers, the equal-preference groups allow the client's preferences to be |
| 742 | // partially respected. (This only has an effect with |
| 743 | // SSL_OP_CIPHER_SERVER_PREFERENCE). |
| 744 | // |
| 745 | // The equal-preference groups are expressed by grouping SSL_CIPHERs together. |
| 746 | // All elements of a group have the same priority: no ordering is expressed |
| 747 | // within a group. |
| 748 | // |
| 749 | // The values in |ciphers| are in one-to-one correspondence with |
| 750 | // |in_group_flags|. (That is, sk_SSL_CIPHER_num(ciphers) is the number of |
| 751 | // bytes in |in_group_flags|.) The bytes in |in_group_flags| are either 1, to |
| 752 | // indicate that the corresponding SSL_CIPHER is not the last element of a |
| 753 | // group, or 0 to indicate that it is. |
| 754 | // |
| 755 | // For example, if |in_group_flags| contains all zeros then that indicates a |
| 756 | // traditional, fully-ordered preference. Every SSL_CIPHER is the last element |
| 757 | // of the group (i.e. they are all in a one-element group). |
| 758 | // |
| 759 | // For a more complex example, consider: |
| 760 | // ciphers: A B C D E F |
| 761 | // in_group_flags: 1 1 0 0 1 0 |
| 762 | // |
| 763 | // That would express the following, order: |
| 764 | // |
| 765 | // A E |
| 766 | // B -> D -> F |
| 767 | // C |
| 768 | struct SSLCipherPreferenceList { |
| 769 | static constexpr bool kAllowUniquePtr = true; |
| 770 |
| 771 | SSLCipherPreferenceList() = default; |
| 772 | ~SSLCipherPreferenceList(); |
| 773 |
| 774 | bool Init(UniquePtr<STACK_OF(SSL_CIPHER)> ciphers, |
| 775 | Span<const bool> in_group_flags); |
| 776 | bool Init(const SSLCipherPreferenceList &); |
| 777 |
| 778 | void Remove(const SSL_CIPHER *cipher); |
| 779 |
| 780 | UniquePtr<STACK_OF(SSL_CIPHER)> ciphers; |
| 781 | bool *in_group_flags = nullptr; |
| 782 | }; |
| 783 |
| 784 | // AllCiphers returns an array of all supported ciphers, sorted by id. |
| 785 | Span<const SSL_CIPHER> AllCiphers(); |
| 786 |
| 787 | // ssl_cipher_get_evp_aead sets |*out_aead| to point to the correct EVP_AEAD |
| 788 | // object for |cipher| protocol version |version|. It sets |*out_mac_secret_len| |
| 789 | // and |*out_fixed_iv_len| to the MAC key length and fixed IV length, |
| 790 | // respectively. The MAC key length is zero except for legacy block and stream |
| 791 | // ciphers. It returns true on success and false on error. |
| 792 | bool ssl_cipher_get_evp_aead(const EVP_AEAD **out_aead, |
| 793 | size_t *out_mac_secret_len, |
| 794 | size_t *out_fixed_iv_len, const SSL_CIPHER *cipher, |
| 795 | uint16_t version); |
| 796 |
| 797 | // ssl_get_handshake_digest returns the |EVP_MD| corresponding to |version| and |
| 798 | // |cipher|. |
| 799 | const EVP_MD *ssl_get_handshake_digest(uint16_t version, |
| 800 | const SSL_CIPHER *cipher); |
| 801 |
| 802 | // ssl_create_cipher_list evaluates |rule_str|. It sets |*out_cipher_list| to a |
| 803 | // newly-allocated |SSLCipherPreferenceList| containing the result. It returns |
| 804 | // true on success and false on failure. If |strict| is true, nonsense will be |
| 805 | // rejected. If false, nonsense will be silently ignored. An empty result is |
| 806 | // considered an error regardless of |strict|. |has_aes_hw| indicates if the |
| 807 | // list should be ordered based on having support for AES in hardware or not. |
| 808 | bool ssl_create_cipher_list(UniquePtr<SSLCipherPreferenceList> *out_cipher_list, |
| 809 | const bool has_aes_hw, const char *rule_str, |
| 810 | bool strict); |
| 811 |
| 812 | // ssl_cipher_auth_mask_for_key returns the mask of cipher |algorithm_auth| |
| 813 | // values suitable for use with |key| in TLS 1.2 and below. |sign_ok| indicates |
| 814 | // whether |key| may be used for signing. |
| 815 | uint32_t ssl_cipher_auth_mask_for_key(const EVP_PKEY *key, bool sign_ok); |
| 816 |
| 817 | // ssl_cipher_uses_certificate_auth returns whether |cipher| authenticates the |
| 818 | // server and, optionally, the client with a certificate. |
| 819 | bool ssl_cipher_uses_certificate_auth(const SSL_CIPHER *cipher); |
| 820 |
| 821 | // ssl_cipher_requires_server_key_exchange returns whether |cipher| requires a |
| 822 | // ServerKeyExchange message. |
| 823 | // |
| 824 | // This function may return false while still allowing |cipher| an optional |
| 825 | // ServerKeyExchange. This is the case for plain PSK ciphers. |
| 826 | bool ssl_cipher_requires_server_key_exchange(const SSL_CIPHER *cipher); |
| 827 |
| 828 | // ssl_cipher_get_record_split_len, for TLS 1.0 CBC mode ciphers, returns the |
| 829 | // length of an encrypted 1-byte record, for use in record-splitting. Otherwise |
| 830 | // it returns zero. |
| 831 | size_t ssl_cipher_get_record_split_len(const SSL_CIPHER *cipher); |
| 832 |
| 833 | // ssl_choose_tls13_cipher returns an |SSL_CIPHER| corresponding with the best |
| 834 | // available from |cipher_suites| compatible with |version| and |policy|. It |
| 835 | // returns NULL if there isn't a compatible cipher. |has_aes_hw| indicates if |
| 836 | // the choice should be made as if support for AES in hardware is available. |
| 837 | const SSL_CIPHER *ssl_choose_tls13_cipher(CBS cipher_suites, bool has_aes_hw, |
| 838 | uint16_t version, |
| 839 | enum ssl_compliance_policy_t policy); |
| 840 |
| 841 | // ssl_tls13_cipher_meets_policy returns true if |cipher_id| is acceptable given |
| 842 | // |policy|. |
| 843 | bool ssl_tls13_cipher_meets_policy(uint16_t cipher_id, |
| 844 | enum ssl_compliance_policy_t policy); |
| 845 |
| 846 | // ssl_cipher_is_deprecated returns true if |cipher| is deprecated. |
| 847 | OPENSSL_EXPORT bool ssl_cipher_is_deprecated(const SSL_CIPHER *cipher); |
| 848 |
| 849 |
| 850 | // Transcript layer. |
| 851 |
| 852 | // SSLTranscript maintains the handshake transcript as a combination of a |
| 853 | // buffer and running hash. |
| 854 | class SSLTranscript { |
| 855 | public: |
| 856 | explicit SSLTranscript(bool is_dtls); |
| 857 | ~SSLTranscript(); |
| 858 |
| 859 | SSLTranscript(SSLTranscript &&other) = default; |
| 860 | SSLTranscript &operator=(SSLTranscript &&other) = default; |
| 861 |
| 862 | // Init initializes the handshake transcript. If called on an existing |
| 863 | // transcript, it resets the transcript and hash. It returns true on success |
| 864 | // and false on failure. |
| 865 | bool Init(); |
| 866 |
| 867 | // InitHash initializes the handshake hash based on the PRF and contents of |
| 868 | // the handshake transcript. Subsequent calls to |Update| will update the |
| 869 | // rolling hash. It returns one on success and zero on failure. It is an error |
| 870 | // to call this function after the handshake buffer is released. This may be |
| 871 | // called multiple times to change the hash function. |
| 872 | bool InitHash(uint16_t version, const SSL_CIPHER *cipher); |
| 873 |
| 874 | // UpdateForHelloRetryRequest resets the rolling hash with the |
| 875 | // HelloRetryRequest construction. It returns true on success and false on |
| 876 | // failure. It is an error to call this function before the handshake buffer |
| 877 | // is released. |
| 878 | bool UpdateForHelloRetryRequest(); |
| 879 |
| 880 | // CopyToHashContext initializes |ctx| with |digest| and the data thus far in |
| 881 | // the transcript. It returns true on success and false on failure. If the |
| 882 | // handshake buffer is still present, |digest| may be any supported digest. |
| 883 | // Otherwise, |digest| must match the transcript hash. |
| 884 | bool CopyToHashContext(EVP_MD_CTX *ctx, const EVP_MD *digest) const; |
| 885 |
| 886 | Span<const uint8_t> buffer() const { |
| 887 | return Span(reinterpret_cast<const uint8_t *>(buffer_->data), |
| 888 | buffer_->length); |
| 889 | } |
| 890 |
| 891 | // FreeBuffer releases the handshake buffer. Subsequent calls to |
| 892 | // |Update| will not update the handshake buffer. |
| 893 | void FreeBuffer(); |
| 894 |
| 895 | // DigestLen returns the length of the PRF hash. |
| 896 | size_t DigestLen() const; |
| 897 |
| 898 | // Digest returns the PRF hash. For TLS 1.1 and below, this is |
| 899 | // |EVP_md5_sha1|. |
| 900 | const EVP_MD *Digest() const; |
| 901 |
| 902 | // Update adds |in| to the handshake buffer and handshake hash, whichever is |
| 903 | // enabled. It returns true on success and false on failure. |
| 904 | bool Update(Span<const uint8_t> in); |
| 905 |
| 906 | // GetHash writes the handshake hash to |out| which must have room for at |
| 907 | // least |DigestLen| bytes. On success, it returns true and sets |*out_len| to |
| 908 | // the number of bytes written. Otherwise, it returns false. |
| 909 | bool GetHash(uint8_t *out, size_t *out_len) const; |
| 910 |
| 911 | // GetFinishedMAC computes the MAC for the Finished message into the bytes |
| 912 | // pointed by |out| and writes the number of bytes to |*out_len|. |out| must |
| 913 | // have room for |EVP_MAX_MD_SIZE| bytes. It returns true on success and false |
| 914 | // on failure. |
| 915 | bool GetFinishedMAC(uint8_t *out, size_t *out_len, const SSL_SESSION *session, |
| 916 | bool from_server) const; |
| 917 |
| 918 | private: |
| 919 | // HashBuffer initializes |ctx| to use |digest| and writes the contents of |
| 920 | // |buffer_| to |ctx|. If this SSLTranscript is for DTLS 1.3, the appropriate |
| 921 | // bytes in |buffer_| will be skipped when hashing the buffer. |
| 922 | bool HashBuffer(EVP_MD_CTX *ctx, const EVP_MD *digest) const; |
| 923 |
| 924 | // AddToBufferOrHash directly adds the contents of |in| to |buffer_| and/or |
| 925 | // |hash_|. |
| 926 | bool AddToBufferOrHash(Span<const uint8_t> in); |
| 927 |
| 928 | // buffer_, if non-null, contains the handshake transcript. |
| 929 | UniquePtr<BUF_MEM> buffer_; |
| 930 | // hash, if initialized with an |EVP_MD|, maintains the handshake hash. |
| 931 | ScopedEVP_MD_CTX hash_; |
| 932 | // is_dtls_ indicates whether this is a transcript for a DTLS connection. |
| 933 | bool is_dtls_ : 1; |
| 934 | // version_ contains the version for the connection (if known). |
| 935 | uint16_t version_ = 0; |
| 936 | }; |
| 937 |
| 938 | // tls1_prf computes the PRF function for |ssl|. It fills |out|, using |secret| |
| 939 | // as the secret and |label| as the label. |seed1| and |seed2| are concatenated |
| 940 | // to form the seed parameter. It returns true on success and false on failure. |
| 941 | bool tls1_prf(const EVP_MD *digest, Span<uint8_t> out, |
| 942 | Span<const uint8_t> secret, std::string_view label, |
| 943 | Span<const uint8_t> seed1, Span<const uint8_t> seed2); |
| 944 |
| 945 |
| 946 | // Encryption layer. |
| 947 |
| 948 | // SSLAEADContext contains information about an AEAD that is being used to |
| 949 | // encrypt an SSL connection. |
| 950 | class SSLAEADContext { |
| 951 | public: |
| 952 | explicit SSLAEADContext(const SSL_CIPHER *cipher); |
| 953 | ~SSLAEADContext(); |
| 954 | static constexpr bool kAllowUniquePtr = true; |
| 955 |
| 956 | SSLAEADContext(const SSLAEADContext &&) = delete; |
| 957 | SSLAEADContext &operator=(const SSLAEADContext &&) = delete; |
| 958 |
| 959 | // CreateNullCipher creates an |SSLAEADContext| for the null cipher. |
| 960 | static UniquePtr<SSLAEADContext> CreateNullCipher(); |
| 961 |
| 962 | // Create creates an |SSLAEADContext| using the supplied key material. It |
| 963 | // returns nullptr on error. Only one of |Open| or |Seal| may be used with the |
| 964 | // resulting object, depending on |direction|. |version| is the wire version. |
| 965 | static UniquePtr<SSLAEADContext> Create(enum evp_aead_direction_t direction, |
| 966 | uint16_t version, |
| 967 | const SSL_CIPHER *cipher, |
| 968 | Span<const uint8_t> enc_key, |
| 969 | Span<const uint8_t> mac_key, |
| 970 | Span<const uint8_t> fixed_iv); |
| 971 |
| 972 | // CreatePlaceholderForQUIC creates a placeholder |SSLAEADContext| for the |
| 973 | // given cipher. The resulting object can be queried for various properties |
| 974 | // but cannot encrypt or decrypt data. |
| 975 | static UniquePtr<SSLAEADContext> CreatePlaceholderForQUIC( |
| 976 | const SSL_CIPHER *cipher); |
| 977 |
| 978 | const SSL_CIPHER *cipher() const { return cipher_; } |
| 979 |
| 980 | // is_null_cipher returns true if this is the null cipher. |
| 981 | bool is_null_cipher() const { return !cipher_; } |
| 982 |
| 983 | // ExplicitNonceLen returns the length of the explicit nonce. |
| 984 | size_t ExplicitNonceLen() const; |
| 985 |
| 986 | // MaxOverhead returns the maximum overhead of calling |Seal|. |
| 987 | size_t MaxOverhead() const; |
| 988 |
| 989 | // MaxSealInputLen returns the maximum length for |Seal| that can fit in |
| 990 | // |max_out| output bytes, or zero if no input may fit. |
| 991 | size_t MaxSealInputLen(size_t max_out) const; |
| 992 |
| 993 | // SuffixLen calculates the suffix length written by |SealScatter| and writes |
| 994 | // it to |*out_suffix_len|. It returns true on success and false on error. |
| 995 | // |in_len| and |extra_in_len| should equal the argument of the same names |
| 996 | // passed to |SealScatter|. |
| 997 | bool SuffixLen(size_t *out_suffix_len, size_t in_len, |
| 998 | size_t extra_in_len) const; |
| 999 |
| 1000 | // CiphertextLen calculates the total ciphertext length written by |
| 1001 | // |SealScatter| and writes it to |*out_len|. It returns true on success and |
| 1002 | // false on error. |in_len| and |extra_in_len| should equal the argument of |
| 1003 | // the same names passed to |SealScatter|. |
| 1004 | bool CiphertextLen(size_t *out_len, size_t in_len, size_t extra_in_len) const; |
| 1005 |
| 1006 | // Open authenticates and decrypts |in| in-place. On success, it sets |*out| |
| 1007 | // to the plaintext in |in| and returns true. Otherwise, it returns |
| 1008 | // false. The output will always be |ExplicitNonceLen| bytes ahead of |in|. |
| 1009 | bool Open(Span<uint8_t> *out, uint8_t type, uint16_t record_version, |
| 1010 | uint64_t seqnum, Span<const uint8_t> header, Span<uint8_t> in); |
| 1011 |
| 1012 | // Seal encrypts and authenticates |in_len| bytes from |in| and writes the |
| 1013 | // result to |out|. It returns true on success and false on error. |
| 1014 | // |
| 1015 | // If |in| and |out| alias then |out| + |ExplicitNonceLen| must be == |in|. |
| 1016 | bool Seal(uint8_t *out, size_t *out_len, size_t max_out, uint8_t type, |
| 1017 | uint16_t record_version, uint64_t seqnum, |
| 1018 | Span<const uint8_t> header, const uint8_t *in, size_t in_len); |
| 1019 |
| 1020 | // SealScatter encrypts and authenticates |in_len| bytes from |in| and splits |
| 1021 | // the result between |out_prefix|, |out| and |out_suffix|. It returns one on |
| 1022 | // success and zero on error. |
| 1023 | // |
| 1024 | // On successful return, exactly |ExplicitNonceLen| bytes are written to |
| 1025 | // |out_prefix|, |in_len| bytes to |out|, and |SuffixLen| bytes to |
| 1026 | // |out_suffix|. |
| 1027 | // |
| 1028 | // |extra_in| may point to an additional plaintext buffer. If present, |
| 1029 | // |extra_in_len| additional bytes are encrypted and authenticated, and the |
| 1030 | // ciphertext is written to the beginning of |out_suffix|. |SuffixLen| should |
| 1031 | // be used to size |out_suffix| accordingly. |
| 1032 | // |
| 1033 | // If |in| and |out| alias then |out| must be == |in|. Other arguments may not |
| 1034 | // alias anything. |
| 1035 | bool SealScatter(uint8_t *out_prefix, uint8_t *out, uint8_t *out_suffix, |
| 1036 | uint8_t type, uint16_t record_version, uint64_t seqnum, |
| 1037 | Span<const uint8_t> header, const uint8_t *in, size_t in_len, |
| 1038 | const uint8_t *extra_in, size_t extra_in_len); |
| 1039 |
| 1040 | bool GetIV(const uint8_t **out_iv, size_t *out_iv_len) const; |
| 1041 |
| 1042 | private: |
| 1043 | // GetAdditionalData returns the additional data, writing into |storage| if |
| 1044 | // necessary. |
| 1045 | Span<const uint8_t> GetAdditionalData(uint8_t storage[13], uint8_t type, |
| 1046 | uint16_t record_version, |
| 1047 | uint64_t seqnum, size_t plaintext_len, |
| 1048 | Span<const uint8_t> header); |
| 1049 |
| 1050 | const SSL_CIPHER *cipher_; |
| 1051 | ScopedEVP_AEAD_CTX ctx_; |
| 1052 | // fixed_nonce_ contains any bytes of the nonce that are fixed for all |
| 1053 | // records. |
| 1054 | InplaceVector<uint8_t, 12> fixed_nonce_; |
| 1055 | uint8_t variable_nonce_len_ = 0; |
| 1056 | // variable_nonce_included_in_record_ is true if the variable nonce |
| 1057 | // for a record is included as a prefix before the ciphertext. |
| 1058 | bool variable_nonce_included_in_record_ : 1; |
| 1059 | // random_variable_nonce_ is true if the variable nonce is |
| 1060 | // randomly generated, rather than derived from the sequence |
| 1061 | // number. |
| 1062 | bool random_variable_nonce_ : 1; |
| 1063 | // xor_fixed_nonce_ is true if the fixed nonce should be XOR'd into the |
| 1064 | // variable nonce rather than prepended. |
| 1065 | bool xor_fixed_nonce_ : 1; |
| 1066 | // omit_length_in_ad_ is true if the length should be omitted in the |
| 1067 | // AEAD's ad parameter. |
| 1068 | bool omit_length_in_ad_ : 1; |
| 1069 | // ad_is_header_ is true if the AEAD's ad parameter is the record header. |
| 1070 | bool ad_is_header_ : 1; |
| 1071 | }; |
| 1072 |
| 1073 |
| 1074 | // DTLS replay bitmap. |
| 1075 |
| 1076 | // DTLSReplayBitmap maintains a sliding window of sequence numbers to detect |
| 1077 | // replayed packets. |
| 1078 | class DTLSReplayBitmap { |
| 1079 | public: |
| 1080 | // ShouldDiscard returns true if |seq_num| has been seen in |
| 1081 | // |bitmap| or is stale. Otherwise it returns false. |
| 1082 | bool ShouldDiscard(uint64_t seqnum) const; |
| 1083 |
| 1084 | // Record updates the bitmap to record receipt of sequence number |
| 1085 | // |seq_num|. It slides the window forward if needed. It is an error to call |
| 1086 | // this function on a stale sequence number. |
| 1087 | void Record(uint64_t seqnum); |
| 1088 |
| 1089 | uint64_t max_seq_num() const { return max_seq_num_; } |
| 1090 |
| 1091 | private: |
| 1092 | // map is a bitset of sequence numbers that have been seen. Bit i corresponds |
| 1093 | // to |max_seq_num_ - i|. |
| 1094 | std::bitset<256> map_; |
| 1095 | // max_seq_num_ is the largest sequence number seen so far as a 64-bit |
| 1096 | // integer. |
| 1097 | uint64_t max_seq_num_ = 0; |
| 1098 | }; |
| 1099 |
| 1100 | // reconstruct_seqnum takes the low order bits of a record sequence number from |
| 1101 | // the wire and reconstructs the full sequence number. It does so using the |
| 1102 | // algorithm described in section 4.2.2 of RFC 9147, where |wire_seq| is the |
| 1103 | // low bits of the sequence number as seen on the wire, |seq_mask| is a bitmask |
| 1104 | // of 8 or 16 1 bits corresponding to the length of the sequence number on the |
| 1105 | // wire, and |max_valid_seqnum| is the largest sequence number of a record |
| 1106 | // successfully deprotected in this epoch. This function returns the sequence |
| 1107 | // number that is numerically closest to one plus |max_valid_seqnum| that when |
| 1108 | // bitwise and-ed with |seq_mask| equals |wire_seq|. |
| 1109 | // |
| 1110 | // |max_valid_seqnum| must be most 2^48-1, in which case the output will also be |
| 1111 | // at most 2^48-1. |
| 1112 | OPENSSL_EXPORT uint64_t reconstruct_seqnum(uint16_t wire_seq, uint64_t seq_mask, |
| 1113 | uint64_t max_valid_seqnum); |
| 1114 |
| 1115 |
| 1116 | // Record layer. |
| 1117 |
| 1118 | class DTLSRecordNumber { |
| 1119 | public: |
| 1120 | static constexpr uint64_t kMaxSequence = (uint64_t{1} << 48) - 1; |
| 1121 |
| 1122 | DTLSRecordNumber() = default; |
| 1123 | DTLSRecordNumber(uint16_t epoch, uint64_t sequence) { |
| 1124 | BSSL_CHECK(sequence <= kMaxSequence); |
| 1125 | combined_ = (uint64_t{epoch} << 48) | sequence; |
| 1126 | } |
| 1127 |
| 1128 | static DTLSRecordNumber FromCombined(uint64_t combined) { |
| 1129 | return DTLSRecordNumber(combined); |
| 1130 | } |
| 1131 |
| 1132 | bool operator==(DTLSRecordNumber r) const { |
| 1133 | return combined() == r.combined(); |
| 1134 | } |
| 1135 | bool operator!=(DTLSRecordNumber r) const { return !((*this) == r); } |
| 1136 | bool operator<(DTLSRecordNumber r) const { return combined() < r.combined(); } |
| 1137 |
| 1138 | uint64_t combined() const { return combined_; } |
| 1139 | uint16_t epoch() const { return combined_ >> 48; } |
| 1140 | uint64_t sequence() const { return combined_ & kMaxSequence; } |
| 1141 |
| 1142 | bool HasNext() const { return sequence() < kMaxSequence; } |
| 1143 | DTLSRecordNumber Next() const { |
| 1144 | BSSL_CHECK(HasNext()); |
| 1145 | // This will not overflow into the epoch. |
| 1146 | return DTLSRecordNumber::FromCombined(combined_ + 1); |
| 1147 | } |
| 1148 |
| 1149 | private: |
| 1150 | explicit DTLSRecordNumber(uint64_t combined) : combined_(combined) {} |
| 1151 |
| 1152 | uint64_t combined_ = 0; |
| 1153 | }; |
| 1154 |
| 1155 | class RecordNumberEncrypter { |
| 1156 | public: |
| 1157 | static constexpr bool kAllowUniquePtr = true; |
| 1158 | static constexpr size_t kMaxKeySize = 32; |
| 1159 |
| 1160 | // Create returns a DTLS 1.3 record number encrypter for |traffic_secret|, or |
| 1161 | // nullptr on error. |
| 1162 | static UniquePtr<RecordNumberEncrypter> Create( |
| 1163 | const SSL_CIPHER *cipher, Span<const uint8_t> traffic_secret); |
| 1164 |
| 1165 | virtual ~RecordNumberEncrypter() = default; |
| 1166 | virtual size_t KeySize() = 0; |
| 1167 | virtual bool SetKey(Span<const uint8_t> key) = 0; |
| 1168 | virtual bool GenerateMask(Span<uint8_t> out, Span<const uint8_t> sample) = 0; |
| 1169 | }; |
| 1170 |
| 1171 | struct DTLSReadEpoch { |
| 1172 | static constexpr bool kAllowUniquePtr = true; |
| 1173 |
| 1174 | // TODO(davidben): This could be made slightly more compact if |bitmap| stored |
| 1175 | // a DTLSRecordNumber. |
| 1176 | uint16_t epoch = 0; |
| 1177 | UniquePtr<SSLAEADContext> aead; |
| 1178 | UniquePtr<RecordNumberEncrypter> rn_encrypter; |
| 1179 | DTLSReplayBitmap bitmap; |
| 1180 | }; |
| 1181 |
| 1182 | struct DTLSWriteEpoch { |
| 1183 | static constexpr bool kAllowUniquePtr = true; |
| 1184 |
| 1185 | uint16_t epoch() const { return next_record.epoch(); } |
| 1186 |
| 1187 | DTLSRecordNumber next_record; |
| 1188 | UniquePtr<SSLAEADContext> aead; |
| 1189 | UniquePtr<RecordNumberEncrypter> rn_encrypter; |
| 1190 | }; |
| 1191 |
| 1192 | // ssl_record_prefix_len returns the length of the prefix before the ciphertext |
| 1193 | // of a record for |ssl|. |
| 1194 | // |
| 1195 | // TODO(davidben): Expose this as part of public API once the high-level |
| 1196 | // buffer-free APIs are available. |
| 1197 | size_t ssl_record_prefix_len(const SSL *ssl); |
| 1198 |
| 1199 | enum ssl_open_record_t { |
| 1200 | ssl_open_record_success, |
| 1201 | ssl_open_record_discard, |
| 1202 | ssl_open_record_partial, |
| 1203 | ssl_open_record_close_notify, |
| 1204 | ssl_open_record_error, |
| 1205 | }; |
| 1206 |
| 1207 | // tls_open_record decrypts a record from |in| in-place. |
| 1208 | // |
| 1209 | // If the input did not contain a complete record, it returns |
| 1210 | // |ssl_open_record_partial|. It sets |*out_consumed| to the total number of |
| 1211 | // bytes necessary. It is guaranteed that a successful call to |tls_open_record| |
| 1212 | // will consume at least that many bytes. |
| 1213 | // |
| 1214 | // Otherwise, it sets |*out_consumed| to the number of bytes of input |
| 1215 | // consumed. Note that input may be consumed on all return codes if a record was |
| 1216 | // decrypted. |
| 1217 | // |
| 1218 | // On success, it returns |ssl_open_record_success|. It sets |*out_type| to the |
| 1219 | // record type and |*out| to the record body in |in|. Note that |*out| may be |
| 1220 | // empty. |
| 1221 | // |
| 1222 | // If a record was successfully processed but should be discarded, it returns |
| 1223 | // |ssl_open_record_discard|. |
| 1224 | // |
| 1225 | // If a record was successfully processed but is a close_notify, it returns |
| 1226 | // |ssl_open_record_close_notify|. |
| 1227 | // |
| 1228 | // On failure or fatal alert, it returns |ssl_open_record_error| and sets |
| 1229 | // |*out_alert| to an alert to emit, or zero if no alert should be emitted. |
| 1230 | enum ssl_open_record_t tls_open_record(SSL *ssl, uint8_t *out_type, |
| 1231 | Span<uint8_t> *out, size_t *out_consumed, |
| 1232 | uint8_t *out_alert, Span<uint8_t> in); |
| 1233 |
| 1234 | // dtls_open_record implements |tls_open_record| for DTLS. It only returns |
| 1235 | // |ssl_open_record_partial| if |in| was empty and sets |*out_consumed| to |
| 1236 | // zero. The caller should read one packet and try again. On success, |
| 1237 | // |*out_number| is set to the record number of the record. |
| 1238 | enum ssl_open_record_t dtls_open_record(SSL *ssl, uint8_t *out_type, |
| 1239 | DTLSRecordNumber *out_number, |
| 1240 | Span<uint8_t> *out, |
| 1241 | size_t *out_consumed, |
| 1242 | uint8_t *out_alert, Span<uint8_t> in); |
| 1243 |
| 1244 | // ssl_needs_record_splitting returns one if |ssl|'s current outgoing cipher |
| 1245 | // state needs record-splitting and zero otherwise. |
| 1246 | bool ssl_needs_record_splitting(const SSL *ssl); |
| 1247 |
| 1248 | // tls_seal_record seals a new record of type |type| and body |in| and writes it |
| 1249 | // to |out|. At most |max_out| bytes will be written. It returns true on success |
| 1250 | // and false on error. If enabled, |tls_seal_record| implements TLS 1.0 CBC |
| 1251 | // 1/n-1 record splitting and may write two records concatenated. |
| 1252 | // |
| 1253 | // For a large record, the bulk of the ciphertext will begin |
| 1254 | // |tls_seal_align_prefix_len| bytes into out. Aligning |out| appropriately may |
| 1255 | // improve performance. It writes at most |in_len| + |SSL_max_seal_overhead| |
| 1256 | // bytes to |out|. |
| 1257 | // |
| 1258 | // |in| and |out| may not alias. |
| 1259 | bool tls_seal_record(SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out, |
| 1260 | uint8_t type, const uint8_t *in, size_t in_len); |
| 1261 |
| 1262 | // dtls_record_header_write_len returns the length of the record header that |
| 1263 | // will be written at |epoch|. |
| 1264 | size_t dtls_record_header_write_len(const SSL *ssl, uint16_t epoch); |
| 1265 |
| 1266 | // dtls_max_seal_overhead returns the maximum overhead, in bytes, of sealing a |
| 1267 | // record. |
| 1268 | size_t dtls_max_seal_overhead(const SSL *ssl, uint16_t epoch); |
| 1269 |
| 1270 | // dtls_seal_prefix_len returns the number of bytes of prefix to reserve in |
| 1271 | // front of the plaintext when sealing a record in-place. |
| 1272 | size_t dtls_seal_prefix_len(const SSL *ssl, uint16_t epoch); |
| 1273 |
| 1274 | // dtls_seal_max_input_len returns the maximum number of input bytes that can |
| 1275 | // fit in a record of up to |max_out| bytes, or zero if none may fit. |
| 1276 | size_t dtls_seal_max_input_len(const SSL *ssl, uint16_t epoch, size_t max_out); |
| 1277 |
| 1278 | // dtls_seal_record implements |tls_seal_record| for DTLS. |epoch| selects which |
| 1279 | // epoch's cipher state to use. Unlike |tls_seal_record|, |in| and |out| may |
| 1280 | // alias but, if they do, |in| must be exactly |dtls_seal_prefix_len| bytes |
| 1281 | // ahead of |out|. On success, |*out_number| is set to the record number of the |
| 1282 | // record. |
| 1283 | bool dtls_seal_record(SSL *ssl, DTLSRecordNumber *out_number, uint8_t *out, |
| 1284 | size_t *out_len, size_t max_out, uint8_t type, |
| 1285 | const uint8_t *in, size_t in_len, uint16_t epoch); |
| 1286 |
| 1287 | // ssl_process_alert processes |in| as an alert and updates |ssl|'s shutdown |
| 1288 | // state. It returns one of |ssl_open_record_discard|, |ssl_open_record_error|, |
| 1289 | // |ssl_open_record_close_notify|, or |ssl_open_record_fatal_alert| as |
| 1290 | // appropriate. |
| 1291 | enum ssl_open_record_t ssl_process_alert(SSL *ssl, uint8_t *out_alert, |
| 1292 | Span<const uint8_t> in); |
| 1293 |
| 1294 |
| 1295 | // Private key operations. |
| 1296 |
| 1297 | // ssl_private_key_* perform the corresponding operation on |
| 1298 | // |SSL_PRIVATE_KEY_METHOD|. If there is a custom private key configured, they |
| 1299 | // call the corresponding function or |complete| depending on whether there is a |
| 1300 | // pending operation. Otherwise, they implement the operation with |
| 1301 | // |EVP_PKEY|. |
| 1302 |
| 1303 | enum ssl_private_key_result_t ssl_private_key_sign( |
| 1304 | SSL_HANDSHAKE *hs, uint8_t *out, size_t *out_len, size_t max_out, |
| 1305 | uint16_t sigalg, Span<const uint8_t> in); |
| 1306 |
| 1307 | enum ssl_private_key_result_t ssl_private_key_decrypt(SSL_HANDSHAKE *hs, |
| 1308 | uint8_t *out, |
| 1309 | size_t *out_len, |
| 1310 | size_t max_out, |
| 1311 | Span<const uint8_t> in); |
| 1312 |
| 1313 | // ssl_pkey_supports_algorithm returns whether |pkey| may be used to sign |
| 1314 | // |sigalg|. |
| 1315 | bool ssl_pkey_supports_algorithm(const SSL *ssl, EVP_PKEY *pkey, |
| 1316 | uint16_t sigalg, bool is_verify); |
| 1317 |
| 1318 | // ssl_public_key_verify verifies that the |signature| is valid for the public |
| 1319 | // key |pkey| and input |in|, using the signature algorithm |sigalg|. |
| 1320 | bool ssl_public_key_verify(SSL *ssl, Span<const uint8_t> signature, |
| 1321 | uint16_t sigalg, EVP_PKEY *pkey, |
| 1322 | Span<const uint8_t> in); |
| 1323 |
| 1324 |
| 1325 | // Key shares. |
| 1326 |
| 1327 | // SSLKeyShare abstracts over KEM-like constructions, for use with TLS 1.2 ECDHE |
| 1328 | // cipher suites and the TLS 1.3 key_share extension. |
| 1329 | // |
| 1330 | // TODO(davidben): This class is named SSLKeyShare after the TLS 1.3 key_share |
| 1331 | // extension, but it really implements a KEM abstraction. Additionally, we use |
| 1332 | // the same type for Encap, which is a one-off, stateless operation, as Generate |
| 1333 | // and Decap. Slightly tidier would be for Generate to return a new SSLKEMKey |
| 1334 | // (or we introduce EVP_KEM and EVP_KEM_KEY), with a Decap method, and for Encap |
| 1335 | // to be static function. |
| 1336 | class SSLKeyShare { |
| 1337 | public: |
| 1338 | virtual ~SSLKeyShare() {} |
| 1339 | static constexpr bool kAllowUniquePtr = true; |
| 1340 |
| 1341 | // Create returns a SSLKeyShare instance for use with group |group_id| or |
| 1342 | // nullptr on error. |
| 1343 | static UniquePtr<SSLKeyShare> Create(uint16_t group_id); |
| 1344 |
| 1345 | // GroupID returns the group ID. |
| 1346 | virtual uint16_t GroupID() const = 0; |
| 1347 |
| 1348 | // Generate generates a keypair and writes the public key to |out_public_key|. |
| 1349 | // It returns true on success and false on error. |
| 1350 | virtual bool Generate(CBB *out_public_key) = 0; |
| 1351 |
| 1352 | // Encap generates an ephemeral, symmetric secret and encapsulates it with |
| 1353 | // |peer_key|. On success, it returns true, writes the encapsulated secret to |
| 1354 | // |out_ciphertext|, and sets |*out_secret| to the shared secret. On failure, |
| 1355 | // it returns false and sets |*out_alert| to an alert to send to the peer. |
| 1356 | virtual bool Encap(CBB *out_ciphertext, Array<uint8_t> *out_secret, |
| 1357 | uint8_t *out_alert, Span<const uint8_t> peer_key) = 0; |
| 1358 |
| 1359 | // Decap decapsulates the symmetric secret in |ciphertext|. On success, it |
| 1360 | // returns true and sets |*out_secret| to the shared secret. On failure, it |
| 1361 | // returns false and sets |*out_alert| to an alert to send to the peer. |
| 1362 | virtual bool Decap(Array<uint8_t> *out_secret, uint8_t *out_alert, |
| 1363 | Span<const uint8_t> ciphertext) = 0; |
| 1364 |
| 1365 | // SerializePrivateKey writes the private key to |out|, returning true if |
| 1366 | // successful and false otherwise. It should be called after |Generate|. |
| 1367 | virtual bool SerializePrivateKey(CBB *out) { return false; } |
| 1368 |
| 1369 | // DeserializePrivateKey initializes the state of the key exchange from |in|, |
| 1370 | // returning true if successful and false otherwise. |
| 1371 | virtual bool DeserializePrivateKey(CBS *in) { return false; } |
| 1372 | }; |
| 1373 |
| 1374 | struct NamedGroup { |
| 1375 | int nid; |
| 1376 | uint16_t group_id; |
| 1377 | const char name[32], alias[32]; |
| 1378 | }; |
| 1379 |
| 1380 | // NamedGroups returns all supported groups. |
| 1381 | Span<const NamedGroup> NamedGroups(); |
| 1382 |
| 1383 | // ssl_nid_to_group_id looks up the group corresponding to |nid|. On success, it |
| 1384 | // sets |*out_group_id| to the group ID and returns true. Otherwise, it returns |
| 1385 | // false. |
| 1386 | bool ssl_nid_to_group_id(uint16_t *out_group_id, int nid); |
| 1387 |
| 1388 | // ssl_name_to_group_id looks up the group corresponding to the |name| string of |
| 1389 | // length |len|. On success, it sets |*out_group_id| to the group ID and returns |
| 1390 | // true. Otherwise, it returns false. |
| 1391 | bool ssl_name_to_group_id(uint16_t *out_group_id, const char *name, size_t len); |
| 1392 |
| 1393 | // ssl_group_id_to_nid returns the NID corresponding to |group_id| or |
| 1394 | // |NID_undef| if unknown. |
| 1395 | int ssl_group_id_to_nid(uint16_t group_id); |
| 1396 |
| 1397 |
| 1398 | // Handshake messages. |
| 1399 |
| 1400 | struct SSLMessage { |
| 1401 | bool is_v2_hello; |
| 1402 | uint8_t type; |
| 1403 | CBS body; |
| 1404 | // raw is the entire serialized handshake message, including the TLS or DTLS |
| 1405 | // message header. |
| 1406 | CBS raw; |
| 1407 | }; |
| 1408 |
| 1409 | // SSL_MAX_HANDSHAKE_FLIGHT is the number of messages, including |
| 1410 | // ChangeCipherSpec, in the longest handshake flight. Currently this is the |
| 1411 | // client's second leg in a full handshake when client certificates, NPN, and |
| 1412 | // Channel ID, are all enabled. |
| 1413 | #define SSL_MAX_HANDSHAKE_FLIGHT 7 |
| 1414 |
| 1415 | extern const uint8_t kHelloRetryRequest[SSL3_RANDOM_SIZE]; |
| 1416 | extern const uint8_t kTLS12DowngradeRandom[8]; |
| 1417 | extern const uint8_t kTLS13DowngradeRandom[8]; |
| 1418 | extern const uint8_t kJDK11DowngradeRandom[8]; |
| 1419 |
| 1420 | // ssl_max_handshake_message_len returns the maximum number of bytes permitted |
| 1421 | // in a handshake message for |ssl|. |
| 1422 | size_t ssl_max_handshake_message_len(const SSL *ssl); |
| 1423 |
| 1424 | // tls_can_accept_handshake_data returns whether |ssl| is able to accept more |
| 1425 | // data into handshake buffer. |
| 1426 | bool tls_can_accept_handshake_data(const SSL *ssl, uint8_t *out_alert); |
| 1427 |
| 1428 | // tls_has_unprocessed_handshake_data returns whether there is buffered |
| 1429 | // handshake data that has not been consumed by |get_message|. |
| 1430 | bool tls_has_unprocessed_handshake_data(const SSL *ssl); |
| 1431 |
| 1432 | // tls_append_handshake_data appends |data| to the handshake buffer. It returns |
| 1433 | // true on success and false on allocation failure. |
| 1434 | bool tls_append_handshake_data(SSL *ssl, Span<const uint8_t> data); |
| 1435 |
| 1436 | // dtls_has_unprocessed_handshake_data behaves like |
| 1437 | // |tls_has_unprocessed_handshake_data| for DTLS. |
| 1438 | bool dtls_has_unprocessed_handshake_data(const SSL *ssl); |
| 1439 |
| 1440 | // tls_flush_pending_hs_data flushes any handshake plaintext data. |
| 1441 | bool tls_flush_pending_hs_data(SSL *ssl); |
| 1442 |
| 1443 | // dtls_clear_outgoing_messages releases all buffered outgoing messages. |
| 1444 | void dtls_clear_outgoing_messages(SSL *ssl); |
| 1445 |
| 1446 | // dtls_clear_unused_write_epochs releases any write epochs that are no longer |
| 1447 | // needed. |
| 1448 | void dtls_clear_unused_write_epochs(SSL *ssl); |
| 1449 |
| 1450 |
| 1451 | // Callbacks. |
| 1452 |
| 1453 | // ssl_do_info_callback calls |ssl|'s info callback, if set. |
| 1454 | void ssl_do_info_callback(const SSL *ssl, int type, int value); |
| 1455 |
| 1456 | // ssl_do_msg_callback calls |ssl|'s message callback, if set. |
| 1457 | void ssl_do_msg_callback(const SSL *ssl, int is_write, int content_type, |
| 1458 | Span<const uint8_t> in); |
| 1459 |
| 1460 |
| 1461 | // Transport buffers. |
| 1462 |
| 1463 | class SSLBuffer { |
| 1464 | public: |
| 1465 | SSLBuffer() {} |
| 1466 | ~SSLBuffer() { Clear(); } |
| 1467 |
| 1468 | SSLBuffer(const SSLBuffer &) = delete; |
| 1469 | SSLBuffer &operator=(const SSLBuffer &) = delete; |
| 1470 |
| 1471 | uint8_t *data() { return buf_ + offset_; } |
| 1472 | size_t size() const { return size_; } |
| 1473 | bool empty() const { return size_ == 0; } |
| 1474 | size_t cap() const { return cap_; } |
| 1475 |
| 1476 | Span<uint8_t> span() { return Span(data(), size()); } |
| 1477 |
| 1478 | Span<uint8_t> remaining() { return Span(data() + size(), cap() - size()); } |
| 1479 |
| 1480 | // Clear releases the buffer. |
| 1481 | void Clear(); |
| 1482 |
| 1483 | // EnsureCap ensures the buffer has capacity at least |new_cap|, aligned such |
| 1484 | // that data written after |header_len| is aligned to a |
| 1485 | // |SSL3_ALIGN_PAYLOAD|-byte boundary. It returns true on success and false |
| 1486 | // on error. |
| 1487 | bool EnsureCap(size_t header_len, size_t new_cap); |
| 1488 |
| 1489 | // DidWrite extends the buffer by |len|. The caller must have filled in to |
| 1490 | // this point. |
| 1491 | void DidWrite(size_t len); |
| 1492 |
| 1493 | // Consume consumes |len| bytes from the front of the buffer. The memory |
| 1494 | // consumed will remain valid until the next call to |DiscardConsumed| or |
| 1495 | // |Clear|. |
| 1496 | void Consume(size_t len); |
| 1497 |
| 1498 | // DiscardConsumed discards the consumed bytes from the buffer. If the buffer |
| 1499 | // is now empty, it releases memory used by it. |
| 1500 | void DiscardConsumed(); |
| 1501 |
| 1502 | private: |
| 1503 | // buf_ is the memory allocated for this buffer. |
| 1504 | uint8_t *buf_ = nullptr; |
| 1505 | // offset_ is the offset into |buf_| which the buffer contents start at. |
| 1506 | uint16_t offset_ = 0; |
| 1507 | // size_ is the size of the buffer contents from |buf_| + |offset_|. |
| 1508 | uint16_t size_ = 0; |
| 1509 | // cap_ is how much memory beyond |buf_| + |offset_| is available. |
| 1510 | uint16_t cap_ = 0; |
| 1511 | // inline_buf_ is a static buffer for short reads. |
| 1512 | uint8_t inline_buf_[SSL3_RT_HEADER_LENGTH]; |
| 1513 | }; |
| 1514 |
| 1515 | // ssl_read_buffer_extend_to extends the read buffer to the desired length. For |
| 1516 | // TLS, it reads to the end of the buffer until the buffer is |len| bytes |
| 1517 | // long. For DTLS, it reads a new packet and ignores |len|. It returns one on |
| 1518 | // success, zero on EOF, and a negative number on error. |
| 1519 | // |
| 1520 | // It is an error to call |ssl_read_buffer_extend_to| in DTLS when the buffer is |
| 1521 | // non-empty. |
| 1522 | int ssl_read_buffer_extend_to(SSL *ssl, size_t len); |
| 1523 |
| 1524 | // ssl_handle_open_record handles the result of passing |ssl->s3->read_buffer| |
| 1525 | // to a record-processing function. If |ret| is a success or if the caller |
| 1526 | // should retry, it returns one and sets |*out_retry|. Otherwise, it returns <= |
| 1527 | // 0. |
| 1528 | int ssl_handle_open_record(SSL *ssl, bool *out_retry, ssl_open_record_t ret, |
| 1529 | size_t consumed, uint8_t alert); |
| 1530 |
| 1531 | // ssl_write_buffer_flush flushes the write buffer to the transport. It returns |
| 1532 | // one on success and <= 0 on error. For DTLS, whether or not the write |
| 1533 | // succeeds, the write buffer will be cleared. |
| 1534 | int ssl_write_buffer_flush(SSL *ssl); |
| 1535 |
| 1536 |
| 1537 | // Certificate functions. |
| 1538 |
| 1539 | // ssl_parse_cert_chain parses a certificate list from |cbs| in the format used |
| 1540 | // by a TLS Certificate message. On success, it advances |cbs| and returns |
| 1541 | // true. Otherwise, it returns false and sets |*out_alert| to an alert to send |
| 1542 | // to the peer. |
| 1543 | // |
| 1544 | // If the list is non-empty then |*out_chain| and |*out_pubkey| will be set to |
| 1545 | // the certificate chain and the leaf certificate's public key |
| 1546 | // respectively. Otherwise, both will be set to nullptr. |
| 1547 | // |
| 1548 | // If the list is non-empty and |out_leaf_sha256| is non-NULL, it writes the |
| 1549 | // SHA-256 hash of the leaf to |out_leaf_sha256|. |
| 1550 | bool ssl_parse_cert_chain(uint8_t *out_alert, |
| 1551 | UniquePtr<STACK_OF(CRYPTO_BUFFER)> *out_chain, |
| 1552 | UniquePtr<EVP_PKEY> *out_pubkey, |
| 1553 | uint8_t *out_leaf_sha256, CBS *cbs, |
| 1554 | CRYPTO_BUFFER_POOL *pool); |
| 1555 |
| 1556 | enum ssl_key_usage_t { |
| 1557 | key_usage_digital_signature = 0, |
| 1558 | key_usage_encipherment = 2, |
| 1559 | }; |
| 1560 |
| 1561 | // ssl_cert_check_key_usage parses the DER-encoded, X.509 certificate in |in| |
| 1562 | // and returns true if doesn't specify a key usage or, if it does, if it |
| 1563 | // includes |bit|. Otherwise it pushes to the error queue and returns false. |
| 1564 | OPENSSL_EXPORT bool ssl_cert_check_key_usage(const CBS *in, |
| 1565 | enum ssl_key_usage_t bit); |
| 1566 |
| 1567 | // ssl_cert_extract_issuer parses the DER-encoded, X.509 certificate in |in| |
| 1568 | // and extracts the issuer. On success it returns true and the DER encoded |
| 1569 | // issuer is in |out_dn|, otherwise it returns false. |
| 1570 | OPENSSL_EXPORT bool ssl_cert_extract_issuer(const CBS *in, CBS *out_dn); |
| 1571 |
| 1572 | // ssl_cert_matches_issuer parses the DER-encoded, X.509 certificate in |in| |
| 1573 | // and returns true if its issuer is an exact match for the DER encoded |
| 1574 | // distinguished name in |dn| |
| 1575 | bool ssl_cert_matches_issuer(const CBS *in, const CBS *dn); |
| 1576 |
| 1577 | // ssl_cert_parse_pubkey extracts the public key from the DER-encoded, X.509 |
| 1578 | // certificate in |in|. It returns an allocated |EVP_PKEY| or else returns |
| 1579 | // nullptr and pushes to the error queue. |
| 1580 | UniquePtr<EVP_PKEY> ssl_cert_parse_pubkey(const CBS *in); |
| 1581 |
| 1582 | // SSL_parse_CA_list parses a CA list from |cbs| in the format used by a TLS |
| 1583 | // CertificateRequest message and Certificate Authorities extension. On success, |
| 1584 | // it returns a newly-allocated |CRYPTO_BUFFER| list and advances |
| 1585 | // |cbs|. Otherwise, it returns nullptr and sets |*out_alert| to an alert to |
| 1586 | // send to the peer. |
| 1587 | UniquePtr<STACK_OF(CRYPTO_BUFFER)> SSL_parse_CA_list(SSL *ssl, |
| 1588 | uint8_t *out_alert, |
| 1589 | CBS *cbs); |
| 1590 |
| 1591 | // ssl_has_client_CAs returns whether there are configured CAs. |
| 1592 | bool ssl_has_client_CAs(const SSL_CONFIG *cfg); |
| 1593 |
| 1594 | // ssl_add_client_CA_list adds the configured CA list to |cbb| in the format |
| 1595 | // used by a TLS CertificateRequest message. It returns true on success and |
| 1596 | // false on error. |
| 1597 | bool ssl_add_client_CA_list(const SSL_HANDSHAKE *hs, CBB *cbb); |
| 1598 |
| 1599 | // ssl_has_CA_names returns whether there are configured CA names. |
| 1600 | bool ssl_has_CA_names(const SSL_CONFIG *cfg); |
| 1601 |
| 1602 | // ssl_add_CA_names adds the configured CA_names list to |cbb| in the format |
| 1603 | // used by a TLS Certificate Authorities extension. It returns true on success |
| 1604 | // and false on error. |
| 1605 | bool ssl_add_CA_names(const SSL_HANDSHAKE *hs, CBB *cbb); |
| 1606 |
| 1607 | // ssl_check_leaf_certificate returns one if |pkey| and |leaf| are suitable as |
| 1608 | // a server's leaf certificate for |hs|. Otherwise, it returns zero and pushes |
| 1609 | // an error on the error queue. |
| 1610 | bool ssl_check_leaf_certificate(SSL_HANDSHAKE *hs, EVP_PKEY *pkey, |
| 1611 | const CRYPTO_BUFFER *leaf); |
| 1612 |
| 1613 |
| 1614 | // TLS 1.3 key derivation. |
| 1615 |
| 1616 | // tls13_init_key_schedule initializes the handshake hash and key derivation |
| 1617 | // state, and incorporates the PSK. The cipher suite and PRF hash must have been |
| 1618 | // selected at this point. It returns true on success and false on error. |
| 1619 | bool tls13_init_key_schedule(SSL_HANDSHAKE *hs, Span<const uint8_t> psk); |
| 1620 |
| 1621 | // tls13_init_early_key_schedule initializes the handshake hash and key |
| 1622 | // derivation state from |session| for use with 0-RTT. It returns one on success |
| 1623 | // and zero on error. |
| 1624 | bool tls13_init_early_key_schedule(SSL_HANDSHAKE *hs, |
| 1625 | const SSL_SESSION *session); |
| 1626 |
| 1627 | // tls13_advance_key_schedule incorporates |in| into the key schedule with |
| 1628 | // HKDF-Extract. It returns true on success and false on error. |
| 1629 | bool tls13_advance_key_schedule(SSL_HANDSHAKE *hs, Span<const uint8_t> in); |
| 1630 |
| 1631 | // tls13_set_traffic_key sets the read or write traffic keys to |
| 1632 | // |traffic_secret|. The version and cipher suite are determined from |session|. |
| 1633 | // It returns true on success and false on error. |
| 1634 | bool tls13_set_traffic_key(SSL *ssl, enum ssl_encryption_level_t level, |
| 1635 | enum evp_aead_direction_t direction, |
| 1636 | const SSL_SESSION *session, |
| 1637 | Span<const uint8_t> traffic_secret); |
| 1638 |
| 1639 | // tls13_derive_early_secret derives the early traffic secret. It returns true |
| 1640 | // on success and false on error. |
| 1641 | bool tls13_derive_early_secret(SSL_HANDSHAKE *hs); |
| 1642 |
| 1643 | // tls13_derive_handshake_secrets derives the handshake traffic secret. It |
| 1644 | // returns true on success and false on error. |
| 1645 | bool tls13_derive_handshake_secrets(SSL_HANDSHAKE *hs); |
| 1646 |
| 1647 | // tls13_rotate_traffic_key derives the next read or write traffic secret. It |
| 1648 | // returns true on success and false on error. |
| 1649 | bool tls13_rotate_traffic_key(SSL *ssl, enum evp_aead_direction_t direction); |
| 1650 |
| 1651 | // tls13_derive_application_secrets derives the initial application data traffic |
| 1652 | // and exporter secrets based on the handshake transcripts and |master_secret|. |
| 1653 | // It returns true on success and false on error. |
| 1654 | bool tls13_derive_application_secrets(SSL_HANDSHAKE *hs); |
| 1655 |
| 1656 | // tls13_derive_resumption_secret derives the |resumption_secret|. |
| 1657 | bool tls13_derive_resumption_secret(SSL_HANDSHAKE *hs); |
| 1658 |
| 1659 | // tls13_export_keying_material provides an exporter interface to use the |
| 1660 | // |exporter_secret|. |
| 1661 | bool tls13_export_keying_material(const SSL *ssl, Span<uint8_t> out, |
| 1662 | Span<const uint8_t> secret, |
| 1663 | std::string_view label, |
| 1664 | Span<const uint8_t> context); |
| 1665 |
| 1666 | // tls13_finished_mac calculates the MAC of the handshake transcript to verify |
| 1667 | // the integrity of the Finished message, and stores the result in |out| and |
| 1668 | // length in |out_len|. |is_server| is true if this is for the Server Finished |
| 1669 | // and false for the Client Finished. |
| 1670 | bool tls13_finished_mac(SSL_HANDSHAKE *hs, uint8_t *out, size_t *out_len, |
| 1671 | bool is_server); |
| 1672 |
| 1673 | // tls13_derive_session_psk calculates the PSK for this session based on the |
| 1674 | // resumption master secret and |nonce|. It returns true on success, and false |
| 1675 | // on failure. |
| 1676 | bool tls13_derive_session_psk(SSL_SESSION *session, Span<const uint8_t> nonce, |
| 1677 | bool is_dtls); |
| 1678 |
| 1679 | // tls13_write_psk_binder calculates the PSK binder value over |transcript| and |
| 1680 | // |msg|, and replaces the last bytes of |msg| with the resulting value. It |
| 1681 | // returns true on success, and false on failure. If |out_binder_len| is |
| 1682 | // non-NULL, it sets |*out_binder_len| to the length of the value computed. |
| 1683 | bool tls13_write_psk_binder(const SSL_HANDSHAKE *hs, |
| 1684 | const SSLTranscript &transcript, Span<uint8_t> msg, |
| 1685 | size_t *out_binder_len); |
| 1686 |
| 1687 | // tls13_verify_psk_binder verifies that the handshake transcript, truncated up |
| 1688 | // to the binders has a valid signature using the value of |session|'s |
| 1689 | // resumption secret. It returns true on success, and false on failure. |
| 1690 | bool tls13_verify_psk_binder(const SSL_HANDSHAKE *hs, |
| 1691 | const SSL_SESSION *session, const SSLMessage &msg, |
| 1692 | CBS *binders); |
| 1693 |
| 1694 |
| 1695 | // Encrypted ClientHello. |
| 1696 |
| 1697 | struct ECHConfig { |
| 1698 | static constexpr bool kAllowUniquePtr = true; |
| 1699 | // raw contains the serialized ECHConfig. |
| 1700 | Array<uint8_t> raw; |
| 1701 | // The following fields alias into |raw|. |
| 1702 | Span<const uint8_t> public_key; |
| 1703 | Span<const uint8_t> public_name; |
| 1704 | Span<const uint8_t> cipher_suites; |
| 1705 | uint16_t kem_id = 0; |
| 1706 | uint8_t maximum_name_length = 0; |
| 1707 | uint8_t config_id = 0; |
| 1708 | }; |
| 1709 |
| 1710 | class ECHServerConfig { |
| 1711 | public: |
| 1712 | static constexpr bool kAllowUniquePtr = true; |
| 1713 | ECHServerConfig() = default; |
| 1714 | ECHServerConfig(const ECHServerConfig &other) = delete; |
| 1715 | ECHServerConfig &operator=(ECHServerConfig &&) = delete; |
| 1716 |
| 1717 | // Init parses |ech_config| as an ECHConfig and saves a copy of |key|. |
| 1718 | // It returns true on success and false on error. |
| 1719 | bool Init(Span<const uint8_t> ech_config, const EVP_HPKE_KEY *key, |
| 1720 | bool is_retry_config); |
| 1721 |
| 1722 | // SetupContext sets up |ctx| for a new connection, given the specified |
| 1723 | // HPKE ciphersuite and encapsulated KEM key. It returns true on success and |
| 1724 | // false on error. This function may only be called on an initialized object. |
| 1725 | bool SetupContext(EVP_HPKE_CTX *ctx, uint16_t kdf_id, uint16_t aead_id, |
| 1726 | Span<const uint8_t> enc) const; |
| 1727 |
| 1728 | const ECHConfig &ech_config() const { return ech_config_; } |
| 1729 | bool is_retry_config() const { return is_retry_config_; } |
| 1730 |
| 1731 | private: |
| 1732 | ECHConfig ech_config_; |
| 1733 | ScopedEVP_HPKE_KEY key_; |
| 1734 | bool is_retry_config_ = false; |
| 1735 | }; |
| 1736 |
| 1737 | enum ssl_client_hello_type_t { |
| 1738 | ssl_client_hello_unencrypted, |
| 1739 | ssl_client_hello_inner, |
| 1740 | ssl_client_hello_outer, |
| 1741 | }; |
| 1742 |
| 1743 | // ECH_CLIENT_* are types for the ClientHello encrypted_client_hello extension. |
| 1744 | #define ECH_CLIENT_OUTER 0 |
| 1745 | #define ECH_CLIENT_INNER 1 |
| 1746 |
| 1747 | // ssl_decode_client_hello_inner recovers the full ClientHelloInner from the |
| 1748 | // EncodedClientHelloInner |encoded_client_hello_inner| by replacing its |
| 1749 | // outer_extensions extension with the referenced extensions from the |
| 1750 | // ClientHelloOuter |client_hello_outer|. If successful, it writes the recovered |
| 1751 | // ClientHelloInner to |out_client_hello_inner|. It returns true on success and |
| 1752 | // false on failure. |
| 1753 | // |
| 1754 | // This function is exported for fuzzing. |
| 1755 | OPENSSL_EXPORT bool ssl_decode_client_hello_inner( |
| 1756 | SSL *ssl, uint8_t *out_alert, Array<uint8_t> *out_client_hello_inner, |
| 1757 | Span<const uint8_t> encoded_client_hello_inner, |
| 1758 | const SSL_CLIENT_HELLO *client_hello_outer); |
| 1759 |
| 1760 | // ssl_client_hello_decrypt attempts to decrypt and decode the |payload|. It |
| 1761 | // writes the result to |*out|. |payload| must point into |client_hello_outer|. |
| 1762 | // It returns true on success and false on error. On error, it sets |
| 1763 | // |*out_is_decrypt_error| to whether the failure was due to a bad ciphertext. |
| 1764 | bool ssl_client_hello_decrypt(SSL_HANDSHAKE *hs, uint8_t *out_alert, |
| 1765 | bool *out_is_decrypt_error, Array<uint8_t> *out, |
| 1766 | const SSL_CLIENT_HELLO *client_hello_outer, |
| 1767 | Span<const uint8_t> payload); |
| 1768 |
| 1769 | #define ECH_CONFIRMATION_SIGNAL_LEN 8 |
| 1770 |
| 1771 | // ssl_ech_confirmation_signal_hello_offset returns the offset of the ECH |
| 1772 | // confirmation signal in a ServerHello message, including the handshake header. |
| 1773 | size_t ssl_ech_confirmation_signal_hello_offset(const SSL *ssl); |
| 1774 |
| 1775 | // ssl_ech_accept_confirmation computes the server's ECH acceptance signal, |
| 1776 | // writing it to |out|. The transcript portion is the concatenation of |
| 1777 | // |transcript| with |msg|. The |ECH_CONFIRMATION_SIGNAL_LEN| bytes from |
| 1778 | // |offset| in |msg| are replaced with zeros before hashing. This function |
| 1779 | // returns true on success, and false on failure. |
| 1780 | bool ssl_ech_accept_confirmation(const SSL_HANDSHAKE *hs, Span<uint8_t> out, |
| 1781 | Span<const uint8_t> client_random, |
| 1782 | const SSLTranscript &transcript, bool is_hrr, |
| 1783 | Span<const uint8_t> msg, size_t offset); |
| 1784 |
| 1785 | // ssl_is_valid_ech_public_name returns true if |public_name| is a valid ECH |
| 1786 | // public name and false otherwise. It is exported for testing. |
| 1787 | OPENSSL_EXPORT bool ssl_is_valid_ech_public_name( |
| 1788 | Span<const uint8_t> public_name); |
| 1789 |
| 1790 | // ssl_is_valid_ech_config_list returns true if |ech_config_list| is a valid |
| 1791 | // ECHConfigList structure and false otherwise. |
| 1792 | bool ssl_is_valid_ech_config_list(Span<const uint8_t> ech_config_list); |
| 1793 |
| 1794 | // ssl_select_ech_config selects an ECHConfig and associated parameters to offer |
| 1795 | // on the client and updates |hs|. It returns true on success, whether an |
| 1796 | // ECHConfig was found or not, and false on internal error. On success, the |
| 1797 | // encapsulated key is written to |out_enc| and |*out_enc_len| is set to the |
| 1798 | // number of bytes written. If the function did not select an ECHConfig, the |
| 1799 | // encapsulated key is the empty string. |
| 1800 | bool ssl_select_ech_config(SSL_HANDSHAKE *hs, Span<uint8_t> out_enc, |
| 1801 | size_t *out_enc_len); |
| 1802 |
| 1803 | // ssl_ech_extension_body_length returns the length of the body of a ClientHello |
| 1804 | // ECH extension that encrypts |in_len| bytes with |aead| and an 'enc' value of |
| 1805 | // length |enc_len|. The result does not include the four-byte extension header. |
| 1806 | size_t ssl_ech_extension_body_length(const EVP_HPKE_AEAD *aead, size_t enc_len, |
| 1807 | size_t in_len); |
| 1808 |
| 1809 | // ssl_encrypt_client_hello constructs a new ClientHelloInner, adds it to the |
| 1810 | // inner transcript, and encrypts for inclusion in the ClientHelloOuter. |enc| |
| 1811 | // is the encapsulated key to include in the extension. It returns true on |
| 1812 | // success and false on error. If not offering ECH, |enc| is ignored and the |
| 1813 | // function will compute a GREASE ECH extension if necessary, and otherwise |
| 1814 | // return success while doing nothing. |
| 1815 | // |
| 1816 | // Encrypting the ClientHelloInner incorporates all extensions in the |
| 1817 | // ClientHelloOuter, so all other state necessary for |ssl_add_client_hello| |
| 1818 | // must already be computed. |
| 1819 | bool ssl_encrypt_client_hello(SSL_HANDSHAKE *hs, Span<const uint8_t> enc); |
| 1820 |
| 1821 |
| 1822 | // Credentials. |
| 1823 |
| 1824 | enum class SSLCredentialType { |
| 1825 | kX509, |
| 1826 | kDelegated, |
| 1827 | kSPAKE2PlusV1Client, |
| 1828 | kSPAKE2PlusV1Server, |
| 1829 | }; |
| 1830 |
| 1831 | BSSL_NAMESPACE_END |
| 1832 |
| 1833 | // SSL_CREDENTIAL is exported to C, so it must be defined outside the namespace. |
| 1834 | struct ssl_credential_st : public bssl::RefCounted<ssl_credential_st> { |
| 1835 | explicit ssl_credential_st(bssl::SSLCredentialType type); |
| 1836 | ssl_credential_st(const ssl_credential_st &) = delete; |
| 1837 | ssl_credential_st &operator=(const ssl_credential_st &) = delete; |
| 1838 |
| 1839 | // Dup returns a copy of the credential, or nullptr on error. The |ex_data| |
| 1840 | // values are not copied. This is only used on the legacy credential, whose |
| 1841 | // |ex_data| is inaccessible. |
| 1842 | bssl::UniquePtr<SSL_CREDENTIAL> Dup() const; |
| 1843 |
| 1844 | // ClearCertAndKey erases any certificate and private key on the credential. |
| 1845 | void ClearCertAndKey(); |
| 1846 |
| 1847 | // UsesX509 returns true if the credential type uses an X.509 certificate. |
| 1848 | bool UsesX509() const; |
| 1849 |
| 1850 | // UsesPrivateKey returns true if the credential type uses an asymmetric |
| 1851 | // private key. |
| 1852 | bool UsesPrivateKey() const; |
| 1853 |
| 1854 | // IsComplete returns whether all required fields in the credential have been |
| 1855 | // filled in. |
| 1856 | bool IsComplete() const; |
| 1857 |
| 1858 | // SetLeafCert sets the leaf certificate to |leaf|, leaving the remaining |
| 1859 | // certificates unmodified. It returns true on success and false on error. If |
| 1860 | // |discard_key_on_mismatch| is true and the private key is inconsistent with |
| 1861 | // the new leaf certificate, it is silently discarded. |
| 1862 | bool SetLeafCert(bssl::UniquePtr<CRYPTO_BUFFER> leaf, |
| 1863 | bool discard_key_on_mismatch); |
| 1864 |
| 1865 | // ClearIntermediateCerts clears intermediate certificates in the certificate |
| 1866 | // chain, while preserving the leaf. |
| 1867 | void ClearIntermediateCerts(); |
| 1868 |
| 1869 | // AppendIntermediateCert appends |cert| to the certificate chain. If there is |
| 1870 | // no leaf certificate configured, it leaves a placeholder null in |chain|. It |
| 1871 | // returns one on success and zero on error. |
| 1872 | bool AppendIntermediateCert(bssl::UniquePtr<CRYPTO_BUFFER> cert); |
| 1873 |
| 1874 | // ChainContainsIssuer returns true if |dn| is a byte for byte match with the |
| 1875 | // issuer of any certificate in |chain|, false otherwise. |
| 1876 | bool ChainContainsIssuer(bssl::Span<const uint8_t> dn) const; |
| 1877 |
| 1878 | // type is the credential type and determines which other fields apply. |
| 1879 | bssl::SSLCredentialType type; |
| 1880 |
| 1881 | // pubkey is the cached public key of the credential. Unlike |privkey|, it is |
| 1882 | // always present and is extracted from the certificate, delegated credential, |
| 1883 | // etc. |
| 1884 | bssl::UniquePtr<EVP_PKEY> pubkey; |
| 1885 |
| 1886 | // privkey is the private key of the credential. It may be omitted in favor of |
| 1887 | // |key_method|. |
| 1888 | bssl::UniquePtr<EVP_PKEY> privkey; |
| 1889 |
| 1890 | // key_method, if non-null, is a set of callbacks to call for private key |
| 1891 | // operations. |
| 1892 | const SSL_PRIVATE_KEY_METHOD *key_method = nullptr; |
| 1893 |
| 1894 | // sigalgs, if non-empty, is the set of signature algorithms supported by the |
| 1895 | // private key in decreasing order of preference. If empty, the default list |
| 1896 | // is used. |
| 1897 | // |
| 1898 | // In delegated credentials, this field is not configurable and is instead |
| 1899 | // computed from the dc_cert_verify_algorithm field. |
| 1900 | bssl::Array<uint16_t> sigalgs; |
| 1901 |
| 1902 | // chain contains the certificate chain, with the leaf at the beginning. The |
| 1903 | // first element of |chain| may be nullptr to indicate that the leaf |
| 1904 | // certificate has not yet been set. |
| 1905 | // If |chain| != nullptr -> len(chain) >= 1 |
| 1906 | // If |chain[0]| == nullptr -> len(chain) >= 2. |
| 1907 | // |chain[1..]| != nullptr |
| 1908 | bssl::UniquePtr<STACK_OF(CRYPTO_BUFFER)> chain; |
| 1909 |
| 1910 | // dc is the DelegatedCredential structure, if this is a delegated credential. |
| 1911 | bssl::UniquePtr<CRYPTO_BUFFER> dc; |
| 1912 |
| 1913 | // dc_algorithm is the signature scheme of the signature over the delegated |
| 1914 | // credential itself, made by the end-entity certificate's public key. |
| 1915 | uint16_t dc_algorithm = 0; |
| 1916 |
| 1917 | // Signed certificate timestamp list to be sent to the client, if requested |
| 1918 | bssl::UniquePtr<CRYPTO_BUFFER> signed_cert_timestamp_list; |
| 1919 |
| 1920 | // OCSP response to be sent to the client, if requested. |
| 1921 | bssl::UniquePtr<CRYPTO_BUFFER> ocsp_response; |
| 1922 |
| 1923 | // SPAKE2+-specific information. |
| 1924 | bssl::Array<uint8_t> pake_context; |
| 1925 | bssl::Array<uint8_t> client_identity; |
| 1926 | bssl::Array<uint8_t> server_identity; |
| 1927 | bssl::Array<uint8_t> password_verifier_w0; |
| 1928 | bssl::Array<uint8_t> password_verifier_w1; // server-only |
| 1929 | bssl::Array<uint8_t> registration_record; // client-only |
| 1930 | mutable std::atomic<uint32_t> pake_limit; |
| 1931 |
| 1932 | // Checks whether there are still permitted PAKE attempts remaining, without |
| 1933 | // changing the counter. |
| 1934 | bool HasPAKEAttempts() const; |
| 1935 |
| 1936 | // Atomically decrement |pake_limit|. Return true if successful and false if |
| 1937 | // |pake_limit| is already zero. |
| 1938 | bool ClaimPAKEAttempt() const; |
| 1939 |
| 1940 | // Atomically increment |pake_limit|. This must be paired with a |
| 1941 | // |ClaimPAKEAttempt| call. |
| 1942 | void RestorePAKEAttempt() const; |
| 1943 |
| 1944 | // trust_anchor_id, if non-empty, is the trust anchor ID for the root of the |
| 1945 | // chain in |chain|. |
| 1946 | bssl::Array<uint8_t> trust_anchor_id; |
| 1947 |
| 1948 | CRYPTO_EX_DATA ex_data; |
| 1949 |
| 1950 | // must_match_issuer is a flag indicating that this credential should be |
| 1951 | // considered only when it matches a peer request for a particular issuer via |
| 1952 | // a negotiation mechanism (such as the certificate_authorities extension). |
| 1953 | // This also implies that chain is a certificate path ending in a certificate |
| 1954 | // issued by the certificate with that trust anchor identifier. |
| 1955 | bool must_match_issuer = false; |
| 1956 |
| 1957 | private: |
| 1958 | friend RefCounted; |
| 1959 | ~ssl_credential_st(); |
| 1960 | }; |
| 1961 |
| 1962 | BSSL_NAMESPACE_BEGIN |
| 1963 |
| 1964 | // ssl_get_full_credential_list computes |hs|'s full credential list, including |
| 1965 | // the legacy credential. On success, it writes it to |*out| and returns true. |
| 1966 | // Otherwise, it returns false. The credential list may be empty, in which case |
| 1967 | // this function will successfully output an empty array. |
| 1968 | // |
| 1969 | // This function should be called at most once during the handshake and is |
| 1970 | // intended to be used for certificate-based credentials. It runs the |
| 1971 | // auto-chaining logic as part of finishing the legacy credential. Other uses of |
| 1972 | // the credential list (e.g. PAKE credentials) should iterate over |
| 1973 | // |hs->config->cert->credentials|. |
| 1974 | // |
| 1975 | // The pointers in the result are only valid until |hs| is next mutated. |
| 1976 | bool ssl_get_full_credential_list(SSL_HANDSHAKE *hs, |
| 1977 | Array<SSL_CREDENTIAL *> *out); |
| 1978 |
| 1979 | // ssl_credential_matches_requested_issuers returns true if |cred| is a |
| 1980 | // usable match for any requested issuers in |hs|, and false with an error |
| 1981 | // otherwise. |
| 1982 | bool ssl_credential_matches_requested_issuers(SSL_HANDSHAKE *hs, |
| 1983 | const SSL_CREDENTIAL *cred); |
| 1984 |
| 1985 | // Handshake functions. |
| 1986 |
| 1987 | enum ssl_hs_wait_t { |
| 1988 | ssl_hs_error, |
| 1989 | ssl_hs_ok, |
| 1990 | ssl_hs_read_server_hello, |
| 1991 | ssl_hs_read_message, |
| 1992 | ssl_hs_flush, |
| 1993 | ssl_hs_certificate_selection_pending, |
| 1994 | ssl_hs_handoff, |
| 1995 | ssl_hs_handback, |
| 1996 | ssl_hs_x509_lookup, |
| 1997 | ssl_hs_private_key_operation, |
| 1998 | ssl_hs_pending_session, |
| 1999 | ssl_hs_pending_ticket, |
| 2000 | ssl_hs_early_return, |
| 2001 | ssl_hs_early_data_rejected, |
| 2002 | ssl_hs_read_end_of_early_data, |
| 2003 | ssl_hs_read_change_cipher_spec, |
| 2004 | ssl_hs_certificate_verify, |
| 2005 | ssl_hs_hints_ready, |
| 2006 | }; |
| 2007 |
| 2008 | enum ssl_grease_index_t { |
| 2009 | ssl_grease_cipher = 0, |
| 2010 | ssl_grease_group, |
| 2011 | ssl_grease_extension1, |
| 2012 | ssl_grease_extension2, |
| 2013 | ssl_grease_version, |
| 2014 | ssl_grease_ticket_extension, |
| 2015 | ssl_grease_ech_config_id, |
| 2016 | ssl_grease_last_index = ssl_grease_ech_config_id, |
| 2017 | }; |
| 2018 |
| 2019 | enum tls12_server_hs_state_t { |
| 2020 | state12_start_accept = 0, |
| 2021 | state12_read_client_hello, |
| 2022 | state12_read_client_hello_after_ech, |
| 2023 | state12_cert_callback, |
| 2024 | state12_tls13, |
| 2025 | state12_select_parameters, |
| 2026 | state12_send_server_hello, |
| 2027 | state12_send_server_certificate, |
| 2028 | state12_send_server_key_exchange, |
| 2029 | state12_send_server_hello_done, |
| 2030 | state12_read_client_certificate, |
| 2031 | state12_verify_client_certificate, |
| 2032 | state12_read_client_key_exchange, |
| 2033 | state12_read_client_certificate_verify, |
| 2034 | state12_read_change_cipher_spec, |
| 2035 | state12_process_change_cipher_spec, |
| 2036 | state12_read_next_proto, |
| 2037 | state12_read_channel_id, |
| 2038 | state12_read_client_finished, |
| 2039 | state12_send_server_finished, |
| 2040 | state12_finish_server_handshake, |
| 2041 | state12_done, |
| 2042 | }; |
| 2043 |
| 2044 | enum tls13_server_hs_state_t { |
| 2045 | state13_select_parameters = 0, |
| 2046 | state13_select_session, |
| 2047 | state13_send_hello_retry_request, |
| 2048 | state13_read_second_client_hello, |
| 2049 | state13_send_server_hello, |
| 2050 | state13_send_server_certificate_verify, |
| 2051 | state13_send_server_finished, |
| 2052 | state13_send_half_rtt_ticket, |
| 2053 | state13_read_second_client_flight, |
| 2054 | state13_process_end_of_early_data, |
| 2055 | state13_read_client_encrypted_extensions, |
| 2056 | state13_read_client_certificate, |
| 2057 | state13_read_client_certificate_verify, |
| 2058 | state13_read_channel_id, |
| 2059 | state13_read_client_finished, |
| 2060 | state13_send_new_session_ticket, |
| 2061 | state13_done, |
| 2062 | }; |
| 2063 |
| 2064 | // handback_t lists the points in the state machine where a handback can occur. |
| 2065 | // These are the different points at which key material is no longer needed. |
| 2066 | enum handback_t { |
| 2067 | handback_after_session_resumption = 0, |
| 2068 | handback_after_ecdhe = 1, |
| 2069 | handback_after_handshake = 2, |
| 2070 | handback_tls13 = 3, |
| 2071 | handback_max_value = handback_tls13, |
| 2072 | }; |
| 2073 |
| 2074 | // SSL_HANDSHAKE_HINTS contains handshake hints for a connection. See |
| 2075 | // |SSL_request_handshake_hints| and related functions. |
| 2076 | struct SSL_HANDSHAKE_HINTS { |
| 2077 | static constexpr bool kAllowUniquePtr = true; |
| 2078 |
| 2079 | Array<uint8_t> server_random_tls12; |
| 2080 | Array<uint8_t> server_random_tls13; |
| 2081 |
| 2082 | uint16_t key_share_group_id = 0; |
| 2083 | Array<uint8_t> key_share_ciphertext; |
| 2084 | Array<uint8_t> key_share_secret; |
| 2085 |
| 2086 | uint16_t signature_algorithm = 0; |
| 2087 | Array<uint8_t> signature_input; |
| 2088 | Array<uint8_t> signature_spki; |
| 2089 | Array<uint8_t> signature; |
| 2090 |
| 2091 | Array<uint8_t> decrypted_psk; |
| 2092 | bool ignore_psk = false; |
| 2093 |
| 2094 | uint16_t cert_compression_alg_id = 0; |
| 2095 | Array<uint8_t> cert_compression_input; |
| 2096 | Array<uint8_t> cert_compression_output; |
| 2097 |
| 2098 | uint16_t ecdhe_group_id = 0; |
| 2099 | Array<uint8_t> ecdhe_public_key; |
| 2100 | Array<uint8_t> ecdhe_private_key; |
| 2101 |
| 2102 | Array<uint8_t> decrypted_ticket; |
| 2103 | bool renew_ticket = false; |
| 2104 | bool ignore_ticket = false; |
| 2105 | }; |
| 2106 |
| 2107 | struct SSLPAKEShare { |
| 2108 | static constexpr bool kAllowUniquePtr = true; |
| 2109 | uint16_t named_pake; |
| 2110 | Array<uint8_t> client_identity; |
| 2111 | Array<uint8_t> server_identity; |
| 2112 | Array<uint8_t> pake_message; |
| 2113 | }; |
| 2114 |
| 2115 | struct SSL_HANDSHAKE { |
| 2116 | explicit SSL_HANDSHAKE(SSL *ssl); |
| 2117 | ~SSL_HANDSHAKE(); |
| 2118 | static constexpr bool kAllowUniquePtr = true; |
| 2119 |
| 2120 | // ssl is a non-owning pointer to the parent |SSL| object. |
| 2121 | SSL *ssl; |
| 2122 |
| 2123 | // config is a non-owning pointer to the handshake configuration. |
| 2124 | SSL_CONFIG *config; |
| 2125 |
| 2126 | // wait contains the operation the handshake is currently blocking on or |
| 2127 | // |ssl_hs_ok| if none. |
| 2128 | enum ssl_hs_wait_t wait = ssl_hs_ok; |
| 2129 |
| 2130 | // state is the internal state for the TLS 1.2 and below handshake. Its |
| 2131 | // values depend on |do_handshake| but the starting state is always zero. |
| 2132 | int state = 0; |
| 2133 |
| 2134 | // tls13_state is the internal state for the TLS 1.3 handshake. Its values |
| 2135 | // depend on |do_handshake| but the starting state is always zero. |
| 2136 | int tls13_state = 0; |
| 2137 |
| 2138 | // min_version is the minimum accepted protocol version, taking account both |
| 2139 | // |SSL_OP_NO_*| and |SSL_CTX_set_min_proto_version| APIs. |
| 2140 | uint16_t min_version = 0; |
| 2141 |
| 2142 | // max_version is the maximum accepted protocol version, taking account both |
| 2143 | // |SSL_OP_NO_*| and |SSL_CTX_set_max_proto_version| APIs. |
| 2144 | uint16_t max_version = 0; |
| 2145 |
| 2146 | InplaceVector<uint8_t, SSL_MAX_MD_SIZE> secret; |
| 2147 | InplaceVector<uint8_t, SSL_MAX_MD_SIZE> early_traffic_secret; |
| 2148 | InplaceVector<uint8_t, SSL_MAX_MD_SIZE> client_handshake_secret; |
| 2149 | InplaceVector<uint8_t, SSL_MAX_MD_SIZE> server_handshake_secret; |
| 2150 | InplaceVector<uint8_t, SSL_MAX_MD_SIZE> client_traffic_secret_0; |
| 2151 | InplaceVector<uint8_t, SSL_MAX_MD_SIZE> server_traffic_secret_0; |
| 2152 | InplaceVector<uint8_t, SSL_MAX_MD_SIZE> expected_client_finished; |
| 2153 |
| 2154 | // GetClientHello, on the server, returns either the normal ClientHello |
| 2155 | // message or the ClientHelloInner if it has been serialized to |
| 2156 | // |ech_client_hello_buf|. This function should only be called when the |
| 2157 | // current message is a ClientHello. It returns true on success and false on |
| 2158 | // error. |
| 2159 | // |
| 2160 | // Note that fields of the returned |out_msg| and |out_client_hello| point |
| 2161 | // into a handshake-owned buffer, so their lifetimes should not exceed this |
| 2162 | // SSL_HANDSHAKE. |
| 2163 | bool GetClientHello(SSLMessage *out_msg, SSL_CLIENT_HELLO *out_client_hello); |
| 2164 |
| 2165 | union { |
| 2166 | // sent is a bitset where the bits correspond to elements of kExtensions |
| 2167 | // in extensions.cc. Each bit is set if that extension was sent in a |
| 2168 | // ClientHello. It's not used by servers. |
| 2169 | uint32_t sent = 0; |
| 2170 | // received is a bitset, like |sent|, but is used by servers to record |
| 2171 | // which extensions were received from a client. |
| 2172 | uint32_t received; |
| 2173 | } extensions; |
| 2174 |
| 2175 | // inner_extensions_sent, on clients that offer ECH, is |extensions.sent| for |
| 2176 | // the ClientHelloInner. |
| 2177 | uint32_t inner_extensions_sent = 0; |
| 2178 |
| 2179 | // error, if |wait| is |ssl_hs_error|, is the error the handshake failed on. |
| 2180 | UniquePtr<ERR_SAVE_STATE> error; |
| 2181 |
| 2182 | // key_shares are the current key exchange instances. The second is only used |
| 2183 | // as a client if we believe that we should offer two key shares in a |
| 2184 | // ClientHello. |
| 2185 | UniquePtr<SSLKeyShare> key_shares[2]; |
| 2186 |
| 2187 | // transcript is the current handshake transcript. |
| 2188 | SSLTranscript transcript; |
| 2189 |
| 2190 | // inner_transcript, on the client, is the handshake transcript for the |
| 2191 | // ClientHelloInner handshake. It is moved to |transcript| if the server |
| 2192 | // accepts ECH. |
| 2193 | SSLTranscript inner_transcript; |
| 2194 |
| 2195 | // inner_client_random is the ClientHello random value used with |
| 2196 | // ClientHelloInner. |
| 2197 | uint8_t inner_client_random[SSL3_RANDOM_SIZE] = {0}; |
| 2198 |
| 2199 | // cookie is the value of the cookie in HelloRetryRequest, or empty if none |
| 2200 | // was received. |
| 2201 | Array<uint8_t> cookie; |
| 2202 |
| 2203 | // dtls_cookie is the value of the cookie in DTLS HelloVerifyRequest. If |
| 2204 | // empty, either none was received or HelloVerifyRequest contained an empty |
| 2205 | // cookie. Check the received_hello_verify_request field to distinguish an |
| 2206 | // empty cookie from no HelloVerifyRequest message being received. |
| 2207 | Array<uint8_t> dtls_cookie; |
| 2208 |
| 2209 | // ech_client_outer contains the outer ECH extension to send in the |
| 2210 | // ClientHello, excluding the header and type byte. |
| 2211 | Array<uint8_t> ech_client_outer; |
| 2212 |
| 2213 | // ech_retry_configs, on the client, contains the retry configs from the |
| 2214 | // server as a serialized ECHConfigList. |
| 2215 | Array<uint8_t> ech_retry_configs; |
| 2216 |
| 2217 | // ech_client_hello_buf, on the server, contains the bytes of the |
| 2218 | // reconstructed ClientHelloInner message. |
| 2219 | Array<uint8_t> ech_client_hello_buf; |
| 2220 |
| 2221 | // key_share_bytes is the key_share extension that the client should send. |
| 2222 | Array<uint8_t> key_share_bytes; |
| 2223 |
| 2224 | // key_share_ciphertext, for servers, is encapsulated shared secret to be sent |
| 2225 | // to the client in the TLS 1.3 key_share extension. |
| 2226 | Array<uint8_t> key_share_ciphertext; |
| 2227 |
| 2228 | // peer_sigalgs are the signature algorithms that the peer supports. These are |
| 2229 | // taken from the contents of the signature algorithms extension for a server |
| 2230 | // or from the CertificateRequest for a client. |
| 2231 | Array<uint16_t> peer_sigalgs; |
| 2232 |
| 2233 | // peer_supported_group_list contains the supported group IDs advertised by |
| 2234 | // the peer. This is only set on the server's end. The server does not |
| 2235 | // advertise this extension to the client. |
| 2236 | Array<uint16_t> peer_supported_group_list; |
| 2237 |
| 2238 | // peer_delegated_credential_sigalgs are the signature algorithms the peer |
| 2239 | // supports with delegated credentials, or empty if the peer does not support |
| 2240 | // delegated credentials. |
| 2241 | Array<uint16_t> peer_delegated_credential_sigalgs; |
| 2242 |
| 2243 | // peer_key is the peer's ECDH key for a TLS 1.2 client. |
| 2244 | Array<uint8_t> peer_key; |
| 2245 |
| 2246 | // extension_permutation is the permutation to apply to ClientHello |
| 2247 | // extensions. It maps indices into the |kExtensions| table into other |
| 2248 | // indices. |
| 2249 | Array<uint8_t> extension_permutation; |
| 2250 |
| 2251 | // cert_compression_alg_id, for a server, contains the negotiated certificate |
| 2252 | // compression algorithm for this client. It is only valid if |
| 2253 | // |cert_compression_negotiated| is true. |
| 2254 | uint16_t cert_compression_alg_id; |
| 2255 |
| 2256 | // ech_hpke_ctx is the HPKE context used in ECH. On the server, it is |
| 2257 | // initialized if |ech_status| is |ssl_ech_accepted|. On the client, it is |
| 2258 | // initialized if |selected_ech_config| is not nullptr. |
| 2259 | ScopedEVP_HPKE_CTX ech_hpke_ctx; |
| 2260 |
| 2261 | // server_params, in a TLS 1.2 server, stores the ServerKeyExchange |
| 2262 | // parameters. It has client and server randoms prepended for signing |
| 2263 | // convenience. |
| 2264 | Array<uint8_t> server_params; |
| 2265 |
| 2266 | // peer_psk_identity_hint, on the client, is the psk_identity_hint sent by the |
| 2267 | // server when using a TLS 1.2 PSK key exchange. |
| 2268 | UniquePtr<char> peer_psk_identity_hint; |
| 2269 |
| 2270 | // ca_names contains the list of CAs received via the Certificate Authorities |
| 2271 | // extension in our peer's CertificateRequest or ClientHello message |
| 2272 | UniquePtr<STACK_OF(CRYPTO_BUFFER)> ca_names; |
| 2273 |
| 2274 | // peer_requested_trust_anchors, if not nullopt, contains the trust anchor IDs |
| 2275 | // (possibly none) the peer requested in ClientHello or CertificateRequest. If |
| 2276 | // nullopt, the peer did not send the extension. |
| 2277 | std::optional<Array<uint8_t>> peer_requested_trust_anchors; |
| 2278 |
| 2279 | // peer_available_trust_anchors, if not empty, is the list of trust anchor IDs |
| 2280 | // the peer reported as available in EncryptedExtensions. This is only sent by |
| 2281 | // servers to clients. |
| 2282 | Array<uint8_t> peer_available_trust_anchors; |
| 2283 |
| 2284 | // cached_x509_ca_names contains a cache of parsed versions of the elements of |
| 2285 | // |ca_names|. This pointer is left non-owning so only |
| 2286 | // |ssl_crypto_x509_method| needs to link against crypto/x509. |
| 2287 | STACK_OF(X509_NAME) *cached_x509_ca_names = nullptr; |
| 2288 |
| 2289 | // certificate_types, on the client, contains the set of certificate types |
| 2290 | // received in a CertificateRequest message. |
| 2291 | Array<uint8_t> certificate_types; |
| 2292 |
| 2293 | // credential is the credential we are using for the handshake. |
| 2294 | UniquePtr<SSL_CREDENTIAL> credential; |
| 2295 |
| 2296 | // peer_pubkey is the public key parsed from the peer's leaf certificate. |
| 2297 | UniquePtr<EVP_PKEY> peer_pubkey; |
| 2298 |
| 2299 | // new_session is the new mutable session being established by the current |
| 2300 | // handshake. It should not be cached. |
| 2301 | UniquePtr<SSL_SESSION> new_session; |
| 2302 |
| 2303 | // early_session is the session corresponding to the current 0-RTT state on |
| 2304 | // the client if |in_early_data| is true. |
| 2305 | UniquePtr<SSL_SESSION> early_session; |
| 2306 |
| 2307 | // ssl_ech_keys, for servers, is the set of ECH keys to use with this |
| 2308 | // handshake. This is copied from |SSL_CTX| to ensure consistent behavior as |
| 2309 | // |SSL_CTX| rotates keys. |
| 2310 | UniquePtr<SSL_ECH_KEYS> ech_keys; |
| 2311 |
| 2312 | // selected_ech_config, for clients, is the ECHConfig the client uses to offer |
| 2313 | // ECH, or nullptr if ECH is not being offered. If non-NULL, |ech_hpke_ctx| |
| 2314 | // will be initialized. |
| 2315 | UniquePtr<ECHConfig> selected_ech_config; |
| 2316 |
| 2317 | // new_cipher is the cipher being negotiated in this handshake. |
| 2318 | const SSL_CIPHER *new_cipher = nullptr; |
| 2319 |
| 2320 | // key_block is the record-layer key block for TLS 1.2 and earlier. |
| 2321 | Array<uint8_t> key_block; |
| 2322 |
| 2323 | // hints contains the handshake hints for this connection. If |
| 2324 | // |hints_requested| is true, this field is non-null and contains the pending |
| 2325 | // hints to filled as the predicted handshake progresses. Otherwise, this |
| 2326 | // field, if non-null, contains hints configured by the caller and will |
| 2327 | // influence the handshake on match. |
| 2328 | UniquePtr<SSL_HANDSHAKE_HINTS> hints; |
| 2329 |
| 2330 | // ech_is_inner, on the server, indicates whether the ClientHello contained an |
| 2331 | // inner ECH extension. |
| 2332 | bool ech_is_inner : 1; |
| 2333 |
| 2334 | // ech_authenticated_reject, on the client, indicates whether an ECH rejection |
| 2335 | // handshake has been authenticated. |
| 2336 | bool ech_authenticated_reject : 1; |
| 2337 |
| 2338 | // scts_requested is true if the SCT extension is in the ClientHello. |
| 2339 | bool scts_requested : 1; |
| 2340 |
| 2341 | // handshake_finalized is true once the handshake has completed, at which |
| 2342 | // point accessors should use the established state. |
| 2343 | bool handshake_finalized : 1; |
| 2344 |
| 2345 | // accept_psk_mode stores whether the client's PSK mode is compatible with our |
| 2346 | // preferences. |
| 2347 | bool accept_psk_mode : 1; |
| 2348 |
| 2349 | // cert_request is true if a client certificate was requested. |
| 2350 | bool cert_request : 1; |
| 2351 |
| 2352 | // certificate_status_expected is true if OCSP stapling was negotiated and the |
| 2353 | // server is expected to send a CertificateStatus message. (This is used on |
| 2354 | // both the client and server sides.) |
| 2355 | bool certificate_status_expected : 1; |
| 2356 |
| 2357 | // ocsp_stapling_requested is true if a client requested OCSP stapling. |
| 2358 | bool ocsp_stapling_requested : 1; |
| 2359 |
| 2360 | // should_ack_sni is used by a server and indicates that the SNI extension |
| 2361 | // should be echoed in the ServerHello. |
| 2362 | bool should_ack_sni : 1; |
| 2363 |
| 2364 | // in_false_start is true if there is a pending client handshake in False |
| 2365 | // Start. The client may write data at this point. |
| 2366 | bool in_false_start : 1; |
| 2367 |
| 2368 | // in_early_data is true if there is a pending handshake that has progressed |
| 2369 | // enough to send and receive early data. |
| 2370 | bool in_early_data : 1; |
| 2371 |
| 2372 | // early_data_offered is true if the client sent the early_data extension. |
| 2373 | bool early_data_offered : 1; |
| 2374 |
| 2375 | // can_early_read is true if application data may be read at this point in the |
| 2376 | // handshake. |
| 2377 | bool can_early_read : 1; |
| 2378 |
| 2379 | // can_early_write is true if application data may be written at this point in |
| 2380 | // the handshake. |
| 2381 | bool can_early_write : 1; |
| 2382 |
| 2383 | // is_early_version is true if the protocol version configured is not |
| 2384 | // necessarily the final version and is just the predicted 0-RTT version. |
| 2385 | bool is_early_version : 1; |
| 2386 |
| 2387 | // next_proto_neg_seen is one of NPN was negotiated. |
| 2388 | bool next_proto_neg_seen : 1; |
| 2389 |
| 2390 | // ticket_expected is true if a TLS 1.2 NewSessionTicket message is to be sent |
| 2391 | // or received. |
| 2392 | bool ticket_expected : 1; |
| 2393 |
| 2394 | // extended_master_secret is true if the extended master secret extension is |
| 2395 | // negotiated in this handshake. |
| 2396 | bool extended_master_secret : 1; |
| 2397 |
| 2398 | // pending_private_key_op is true if there is a pending private key operation |
| 2399 | // in progress. |
| 2400 | bool pending_private_key_op : 1; |
| 2401 |
| 2402 | // handback indicates that a server should pause the handshake after |
| 2403 | // finishing operations that require private key material, in such a way that |
| 2404 | // |SSL_get_error| returns |SSL_ERROR_HANDBACK|. It is set by |
| 2405 | // |SSL_apply_handoff|. |
| 2406 | bool handback : 1; |
| 2407 |
| 2408 | // hints_requested indicates the caller has requested handshake hints. Only |
| 2409 | // the first round-trip of the handshake will complete, after which the |
| 2410 | // |hints| structure can be serialized. |
| 2411 | bool hints_requested : 1; |
| 2412 |
| 2413 | // cert_compression_negotiated is true iff |cert_compression_alg_id| is valid. |
| 2414 | bool cert_compression_negotiated : 1; |
| 2415 |
| 2416 | // apply_jdk11_workaround is true if the peer is probably a JDK 11 client |
| 2417 | // which implemented TLS 1.3 incorrectly. |
| 2418 | bool apply_jdk11_workaround : 1; |
| 2419 |
| 2420 | // can_release_private_key is true if the private key will no longer be used |
| 2421 | // in this handshake. |
| 2422 | bool can_release_private_key : 1; |
| 2423 |
| 2424 | // channel_id_negotiated is true if Channel ID should be used in this |
| 2425 | // handshake. |
| 2426 | bool channel_id_negotiated : 1; |
| 2427 |
| 2428 | // received_hello_verify_request is true if we received a HelloVerifyRequest |
| 2429 | // message from the server. |
| 2430 | bool received_hello_verify_request : 1; |
| 2431 |
| 2432 | // matched_peer_trust_anchor indicates that we have matched a trust anchor |
| 2433 | // the peer requested in the trust anchors extension. |
| 2434 | bool matched_peer_trust_anchor : 1; |
| 2435 |
| 2436 | // peer_matched_trust_anchor is true if the peer indicated a match with one of |
| 2437 | // our requested trust anchors. |
| 2438 | bool peer_matched_trust_anchor : 1; |
| 2439 |
| 2440 | // client_version is the value sent or received in the ClientHello version. |
| 2441 | uint16_t client_version = 0; |
| 2442 |
| 2443 | // early_data_read is the amount of early data that has been read by the |
| 2444 | // record layer. |
| 2445 | uint16_t early_data_read = 0; |
| 2446 |
| 2447 | // early_data_written is the amount of early data that has been written by the |
| 2448 | // record layer. |
| 2449 | uint16_t early_data_written = 0; |
| 2450 |
| 2451 | // signature_algorithm is the signature algorithm to be used in signing with |
| 2452 | // the selected credential, or zero if not applicable or not yet selected. |
| 2453 | uint16_t signature_algorithm = 0; |
| 2454 |
| 2455 | // ech_config_id is the ECH config sent by the client. |
| 2456 | uint8_t ech_config_id = 0; |
| 2457 |
| 2458 | // session_id is the session ID in the ClientHello. |
| 2459 | InplaceVector<uint8_t, SSL_MAX_SSL_SESSION_ID_LENGTH> session_id; |
| 2460 |
| 2461 | // grease_seed is the entropy for GREASE values. |
| 2462 | uint8_t grease_seed[ssl_grease_last_index + 1] = {0}; |
| 2463 |
| 2464 | // pake_share is the PAKE message received over the wire, if any. |
| 2465 | UniquePtr<SSLPAKEShare> pake_share; |
| 2466 |
| 2467 | // pake_share_bytes are the bytes of the PAKEShare to send, if any. |
| 2468 | Array<uint8_t> pake_share_bytes; |
| 2469 |
| 2470 | // pake_prover is the PAKE context for a client. |
| 2471 | UniquePtr<spake2plus::Prover> pake_prover; |
| 2472 |
| 2473 | // pake_verifier is the PAKE context for a server. |
| 2474 | UniquePtr<spake2plus::Verifier> pake_verifier; |
| 2475 | }; |
| 2476 |
| 2477 | // kMaxTickets is the maximum number of tickets to send immediately after the |
| 2478 | // handshake. We use a one-byte ticket nonce, and there is no point in sending |
| 2479 | // so many tickets. |
| 2480 | constexpr size_t kMaxTickets = 16; |
| 2481 |
| 2482 | UniquePtr<SSL_HANDSHAKE> ssl_handshake_new(SSL *ssl); |
| 2483 |
| 2484 | // ssl_check_message_type checks if |msg| has type |type|. If so it returns |
| 2485 | // one. Otherwise, it sends an alert and returns zero. |
| 2486 | bool ssl_check_message_type(SSL *ssl, const SSLMessage &msg, int type); |
| 2487 |
| 2488 | // ssl_run_handshake runs the TLS handshake. It returns one on success and <= 0 |
| 2489 | // on error. It sets |out_early_return| to one if we've completed the handshake |
| 2490 | // early. |
| 2491 | int ssl_run_handshake(SSL_HANDSHAKE *hs, bool *out_early_return); |
| 2492 |
| 2493 | // The following are implementations of |do_handshake| for the client and |
| 2494 | // server. |
| 2495 | enum ssl_hs_wait_t ssl_client_handshake(SSL_HANDSHAKE *hs); |
| 2496 | enum ssl_hs_wait_t ssl_server_handshake(SSL_HANDSHAKE *hs); |
| 2497 | enum ssl_hs_wait_t tls13_client_handshake(SSL_HANDSHAKE *hs); |
| 2498 | enum ssl_hs_wait_t tls13_server_handshake(SSL_HANDSHAKE *hs); |
| 2499 |
| 2500 | // The following functions return human-readable representations of the TLS |
| 2501 | // handshake states for debugging. |
| 2502 | const char *ssl_client_handshake_state(SSL_HANDSHAKE *hs); |
| 2503 | const char *ssl_server_handshake_state(SSL_HANDSHAKE *hs); |
| 2504 | const char *tls13_client_handshake_state(SSL_HANDSHAKE *hs); |
| 2505 | const char *tls13_server_handshake_state(SSL_HANDSHAKE *hs); |
| 2506 |
| 2507 | // tls13_add_key_update queues a KeyUpdate message on |ssl|. |request_type| must |
| 2508 | // be one of |SSL_KEY_UPDATE_REQUESTED| or |SSL_KEY_UPDATE_NOT_REQUESTED|. |
| 2509 | bool tls13_add_key_update(SSL *ssl, int request_type); |
| 2510 |
| 2511 | // tls13_post_handshake processes a post-handshake message. It returns true on |
| 2512 | // success and false on failure. |
| 2513 | bool tls13_post_handshake(SSL *ssl, const SSLMessage &msg); |
| 2514 |
| 2515 | bool tls13_process_certificate(SSL_HANDSHAKE *hs, const SSLMessage &msg, |
| 2516 | bool allow_anonymous); |
| 2517 | bool tls13_process_certificate_verify(SSL_HANDSHAKE *hs, const SSLMessage &msg); |
| 2518 |
| 2519 | // tls13_process_finished processes |msg| as a Finished message from the |
| 2520 | // peer. If |use_saved_value| is true, the verify_data is compared against |
| 2521 | // |hs->expected_client_finished| rather than computed fresh. |
| 2522 | bool tls13_process_finished(SSL_HANDSHAKE *hs, const SSLMessage &msg, |
| 2523 | bool use_saved_value); |
| 2524 |
| 2525 | bool tls13_add_certificate(SSL_HANDSHAKE *hs); |
| 2526 |
| 2527 | // tls13_add_certificate_verify adds a TLS 1.3 CertificateVerify message to the |
| 2528 | // handshake. If it returns |ssl_private_key_retry|, it should be called again |
| 2529 | // to retry when the signing operation is completed. |
| 2530 | enum ssl_private_key_result_t tls13_add_certificate_verify(SSL_HANDSHAKE *hs); |
| 2531 |
| 2532 | bool tls13_add_finished(SSL_HANDSHAKE *hs); |
| 2533 | bool tls13_process_new_session_ticket(SSL *ssl, const SSLMessage &msg); |
| 2534 | bssl::UniquePtr<SSL_SESSION> tls13_create_session_with_ticket(SSL *ssl, |
| 2535 | CBS *body); |
| 2536 |
| 2537 | // ssl_setup_extension_permutation computes a ClientHello extension permutation |
| 2538 | // for |hs|, if applicable. It returns true on success and false on error. |
| 2539 | bool ssl_setup_extension_permutation(SSL_HANDSHAKE *hs); |
| 2540 |
| 2541 | // ssl_setup_key_shares computes client key shares and saves them in |hs|. It |
| 2542 | // returns true on success and false on failure. If |override_group_id| is zero, |
| 2543 | // it offers the default groups, including GREASE. If it is non-zero, it offers |
| 2544 | // a single key share of the specified group. |
| 2545 | bool ssl_setup_key_shares(SSL_HANDSHAKE *hs, uint16_t override_group_id); |
| 2546 |
| 2547 | // ssl_setup_pake_shares computes the client PAKE shares and saves them in |hs|. |
| 2548 | // It returns true on success and false on failure. |
| 2549 | bool ssl_setup_pake_shares(SSL_HANDSHAKE *hs); |
| 2550 |
| 2551 | bool ssl_ext_key_share_parse_serverhello(SSL_HANDSHAKE *hs, |
| 2552 | Array<uint8_t> *out_secret, |
| 2553 | uint8_t *out_alert, CBS *contents); |
| 2554 | bool ssl_ext_key_share_parse_clienthello(SSL_HANDSHAKE *hs, bool *out_found, |
| 2555 | Span<const uint8_t> *out_peer_key, |
| 2556 | uint8_t *out_alert, |
| 2557 | const SSL_CLIENT_HELLO *client_hello); |
| 2558 | bool ssl_ext_pake_add_serverhello(SSL_HANDSHAKE *hs, CBB *out); |
| 2559 | bool ssl_ext_key_share_add_serverhello(SSL_HANDSHAKE *hs, CBB *out); |
| 2560 |
| 2561 | bool ssl_ext_pake_parse_serverhello(SSL_HANDSHAKE *hs, |
| 2562 | Array<uint8_t> *out_secret, |
| 2563 | uint8_t *out_alert, CBS *contents); |
| 2564 |
| 2565 | bool ssl_ext_pre_shared_key_parse_serverhello(SSL_HANDSHAKE *hs, |
| 2566 | uint8_t *out_alert, |
| 2567 | CBS *contents); |
| 2568 | bool ssl_ext_pre_shared_key_parse_clienthello( |
| 2569 | SSL_HANDSHAKE *hs, CBS *out_ticket, CBS *out_binders, |
| 2570 | uint32_t *out_obfuscated_ticket_age, uint8_t *out_alert, |
| 2571 | const SSL_CLIENT_HELLO *client_hello, CBS *contents); |
| 2572 | bool ssl_ext_pre_shared_key_add_serverhello(SSL_HANDSHAKE *hs, CBB *out); |
| 2573 |
| 2574 | // ssl_is_sct_list_valid does a shallow parse of the SCT list in |contents| and |
| 2575 | // returns whether it's valid. |
| 2576 | bool ssl_is_sct_list_valid(const CBS *contents); |
| 2577 |
| 2578 | // ssl_write_client_hello_without_extensions writes a ClientHello to |out|, |
| 2579 | // up to the extensions field. |type| determines the type of ClientHello to |
| 2580 | // write. If |omit_session_id| is true, the session ID is empty. |
| 2581 | bool ssl_write_client_hello_without_extensions(const SSL_HANDSHAKE *hs, |
| 2582 | CBB *cbb, |
| 2583 | ssl_client_hello_type_t type, |
| 2584 | bool empty_session_id); |
| 2585 |
| 2586 | // ssl_add_client_hello constructs a ClientHello and adds it to the outgoing |
| 2587 | // flight. It returns true on success and false on error. |
| 2588 | bool ssl_add_client_hello(SSL_HANDSHAKE *hs); |
| 2589 |
| 2590 | struct ParsedServerHello { |
| 2591 | CBS raw; |
| 2592 | uint16_t legacy_version = 0; |
| 2593 | CBS random; |
| 2594 | CBS session_id; |
| 2595 | uint16_t cipher_suite = 0; |
| 2596 | uint8_t compression_method = 0; |
| 2597 | CBS extensions; |
| 2598 | }; |
| 2599 |
| 2600 | // ssl_parse_server_hello parses |msg| as a ServerHello. On success, it writes |
| 2601 | // the result to |*out| and returns true. Otherwise, it returns false and sets |
| 2602 | // |*out_alert| to an alert to send to the peer. |
| 2603 | bool ssl_parse_server_hello(ParsedServerHello *out, uint8_t *out_alert, |
| 2604 | const SSLMessage &msg); |
| 2605 |
| 2606 | enum ssl_cert_verify_context_t { |
| 2607 | ssl_cert_verify_server, |
| 2608 | ssl_cert_verify_client, |
| 2609 | ssl_cert_verify_channel_id, |
| 2610 | }; |
| 2611 |
| 2612 | // tls13_get_cert_verify_signature_input generates the message to be signed for |
| 2613 | // TLS 1.3's CertificateVerify message. |cert_verify_context| determines the |
| 2614 | // type of signature. It sets |*out| to a newly allocated buffer containing the |
| 2615 | // result. This function returns true on success and false on failure. |
| 2616 | bool tls13_get_cert_verify_signature_input( |
| 2617 | SSL_HANDSHAKE *hs, Array<uint8_t> *out, |
| 2618 | enum ssl_cert_verify_context_t cert_verify_context); |
| 2619 |
| 2620 | // ssl_is_valid_alpn_list returns whether |in| is a valid ALPN protocol list. |
| 2621 | bool ssl_is_valid_alpn_list(Span<const uint8_t> in); |
| 2622 |
| 2623 | // ssl_is_alpn_protocol_allowed returns whether |protocol| is a valid server |
| 2624 | // selection for |hs->ssl|'s client preferences. |
| 2625 | bool ssl_is_alpn_protocol_allowed(const SSL_HANDSHAKE *hs, |
| 2626 | Span<const uint8_t> protocol); |
| 2627 |
| 2628 | // ssl_alpn_list_contains_protocol returns whether |list|, a serialized ALPN |
| 2629 | // protocol list, contains |protocol|. |
| 2630 | bool ssl_alpn_list_contains_protocol(Span<const uint8_t> list, |
| 2631 | Span<const uint8_t> protocol); |
| 2632 |
| 2633 | // ssl_negotiate_alpn negotiates the ALPN extension, if applicable. It returns |
| 2634 | // true on successful negotiation or if nothing was negotiated. It returns false |
| 2635 | // and sets |*out_alert| to an alert on error. |
| 2636 | bool ssl_negotiate_alpn(SSL_HANDSHAKE *hs, uint8_t *out_alert, |
| 2637 | const SSL_CLIENT_HELLO *client_hello); |
| 2638 |
| 2639 | // ssl_get_local_application_settings looks up the configured ALPS value for |
| 2640 | // |protocol|. If found, it sets |*out_settings| to the value and returns true. |
| 2641 | // Otherwise, it returns false. |
| 2642 | bool ssl_get_local_application_settings(const SSL_HANDSHAKE *hs, |
| 2643 | Span<const uint8_t> *out_settings, |
| 2644 | Span<const uint8_t> protocol); |
| 2645 |
| 2646 | // ssl_negotiate_alps negotiates the ALPS extension, if applicable. It returns |
| 2647 | // true on successful negotiation or if nothing was negotiated. It returns false |
| 2648 | // and sets |*out_alert| to an alert on error. |
| 2649 | bool ssl_negotiate_alps(SSL_HANDSHAKE *hs, uint8_t *out_alert, |
| 2650 | const SSL_CLIENT_HELLO *client_hello); |
| 2651 |
| 2652 | // ssl_is_valid_trust_anchor_list returns whether |in| is a valid trust anchor |
| 2653 | // identifiers list. |
| 2654 | bool ssl_is_valid_trust_anchor_list(Span<const uint8_t> in); |
| 2655 |
| 2656 | struct SSLExtension { |
| 2657 | SSLExtension(uint16_t type_arg, bool allowed_arg = true) |
| 2658 | : type(type_arg), allowed(allowed_arg), present(false) { |
| 2659 | CBS_init(&data, nullptr, 0); |
| 2660 | } |
| 2661 |
| 2662 | uint16_t type; |
| 2663 | bool allowed; |
| 2664 | bool present; |
| 2665 | CBS data; |
| 2666 | }; |
| 2667 |
| 2668 | // ssl_parse_extensions parses a TLS extensions block out of |cbs| and advances |
| 2669 | // it. It writes the parsed extensions to pointers in |extensions|. On success, |
| 2670 | // it fills in the |present| and |data| fields and returns true. Otherwise, it |
| 2671 | // sets |*out_alert| to an alert to send and returns false. Unknown extensions |
| 2672 | // are rejected unless |ignore_unknown| is true. |
| 2673 | bool ssl_parse_extensions(const CBS *cbs, uint8_t *out_alert, |
| 2674 | std::initializer_list<SSLExtension *> extensions, |
| 2675 | bool ignore_unknown); |
| 2676 |
| 2677 | // ssl_verify_peer_cert verifies the peer certificate for |hs|. |
| 2678 | enum ssl_verify_result_t ssl_verify_peer_cert(SSL_HANDSHAKE *hs); |
| 2679 | // ssl_reverify_peer_cert verifies the peer certificate for |hs| when resuming a |
| 2680 | // session. |
| 2681 | enum ssl_verify_result_t ssl_reverify_peer_cert(SSL_HANDSHAKE *hs, |
| 2682 | bool send_alert); |
| 2683 |
| 2684 | enum ssl_hs_wait_t ssl_get_finished(SSL_HANDSHAKE *hs); |
| 2685 |
| 2686 | // ssl_send_finished adds a Finished message to the current flight of messages. |
| 2687 | // It returns true on success and false on error. |
| 2688 | bool ssl_send_finished(SSL_HANDSHAKE *hs); |
| 2689 |
| 2690 | // ssl_send_tls12_certificate adds a TLS 1.2 Certificate message to the current |
| 2691 | // flight of messages. It returns true on success and false on error. |
| 2692 | bool ssl_send_tls12_certificate(SSL_HANDSHAKE *hs); |
| 2693 |
| 2694 | // ssl_handshake_session returns the |SSL_SESSION| corresponding to the current |
| 2695 | // handshake. Note, in TLS 1.2 resumptions, this session is immutable. |
| 2696 | const SSL_SESSION *ssl_handshake_session(const SSL_HANDSHAKE *hs); |
| 2697 |
| 2698 | // ssl_done_writing_client_hello is called after the last ClientHello is written |
| 2699 | // by |hs|. It releases some memory that is no longer needed. |
| 2700 | void ssl_done_writing_client_hello(SSL_HANDSHAKE *hs); |
| 2701 |
| 2702 |
| 2703 | // Flags. |
| 2704 |
| 2705 | // SSLFlags is a bitmask of flags that can be encoded with the TLS flags |
| 2706 | // extension, draft-ietf-tls-tlsflags-14. For now, our in-memory representation |
| 2707 | // matches the wire representation, and we only support flags up to 32. If |
| 2708 | // higher values are needed, we can increase the size of the bitmask, or only |
| 2709 | // store the flags we implement in the bitmask. |
| 2710 | using SSLFlags = uint32_t; |
| 2711 | inline constexpr SSLFlags kSSLFlagResumptionAcrossNames = 1 << 8; |
| 2712 |
| 2713 | // ssl_add_flags_extension encodes a tls_flags extension (including the header) |
| 2714 | // containing the flags in |flags|. It returns true on success and false on |
| 2715 | // error. If |flags| is zero (no flags set), it returns true without adding |
| 2716 | // anything to |cbb|. |
| 2717 | bool ssl_add_flags_extension(CBB *cbb, SSLFlags flags); |
| 2718 |
| 2719 | // ssl_parse_flags_extension_request parses tls_flags extension value (excluding |
| 2720 | // the header) from |cbs|, for a request message (ClientHello, |
| 2721 | // CertificateRequest, or NewSessionTicket). Unrecognized flags will be ignored. |
| 2722 | // |
| 2723 | // On success, it sets |*out| to the parsed flags and returns true. On error, it |
| 2724 | // sets |*out_alert| to a TLS alert and returns false. |
| 2725 | bool ssl_parse_flags_extension_request(const CBS *cbs, SSLFlags *out, |
| 2726 | uint8_t *out_alert); |
| 2727 |
| 2728 | // ssl_parse_flags_extension_response parses tls_flags extension value |
| 2729 | // (excluding the header) from |cbs|, for a response message (HelloRetryRequest, |
| 2730 | // ServerHello, EncryptedExtensions, or Certificate). Only the flags in |
| 2731 | // |allowed_flags| may be present. |
| 2732 | // |
| 2733 | // On success, it sets |*out| to the parsed flags and returns true. On error, it |
| 2734 | // sets |*out_alert| to a TLS alert and returns false. |
| 2735 | bool ssl_parse_flags_extension_response(const CBS *cbs, SSLFlags *out, |
| 2736 | uint8_t *out_alert, |
| 2737 | SSLFlags allowed_flags); |
| 2738 |
| 2739 |
| 2740 | // SSLKEYLOGFILE functions. |
| 2741 |
| 2742 | // ssl_log_secret logs |secret| with label |label|, if logging is enabled for |
| 2743 | // |ssl|. It returns true on success and false on failure. |
| 2744 | bool ssl_log_secret(const SSL *ssl, const char *label, |
| 2745 | Span<const uint8_t> secret); |
| 2746 |
| 2747 |
| 2748 | // ClientHello functions. |
| 2749 |
| 2750 | bool ssl_parse_client_hello_with_trailing_data(const SSL *ssl, CBS *cbs, |
| 2751 | SSL_CLIENT_HELLO *out); |
| 2752 |
| 2753 | bool ssl_client_hello_get_extension(const SSL_CLIENT_HELLO *client_hello, |
| 2754 | CBS *out, uint16_t extension_type); |
| 2755 |
| 2756 | bool ssl_client_cipher_list_contains_cipher( |
| 2757 | const SSL_CLIENT_HELLO *client_hello, uint16_t id); |
| 2758 |
| 2759 |
| 2760 | // GREASE. |
| 2761 |
| 2762 | // ssl_get_grease_value returns a GREASE value for |hs|. For a given |
| 2763 | // connection, the values for each index will be deterministic. This allows the |
| 2764 | // same ClientHello be sent twice for a HelloRetryRequest or the same group be |
| 2765 | // advertised in both supported_groups and key_shares. |
| 2766 | uint16_t ssl_get_grease_value(const SSL_HANDSHAKE *hs, |
| 2767 | enum ssl_grease_index_t index); |
| 2768 |
| 2769 |
| 2770 | // Signature algorithms. |
| 2771 |
| 2772 | // tls1_parse_peer_sigalgs parses |sigalgs| as the list of peer signature |
| 2773 | // algorithms and saves them on |hs|. It returns true on success and false on |
| 2774 | // error. |
| 2775 | bool tls1_parse_peer_sigalgs(SSL_HANDSHAKE *hs, const CBS *sigalgs); |
| 2776 |
| 2777 | // tls1_get_legacy_signature_algorithm sets |*out| to the signature algorithm |
| 2778 | // that should be used with |pkey| in TLS 1.1 and earlier. It returns true on |
| 2779 | // success and false if |pkey| may not be used at those versions. |
| 2780 | bool tls1_get_legacy_signature_algorithm(uint16_t *out, const EVP_PKEY *pkey); |
| 2781 |
| 2782 | // tls1_choose_signature_algorithm sets |*out| to a signature algorithm for use |
| 2783 | // with |cred| based on the peer's preferences and the algorithms supported. It |
| 2784 | // returns true on success and false on error. |
| 2785 | bool tls1_choose_signature_algorithm(SSL_HANDSHAKE *hs, |
| 2786 | const SSL_CREDENTIAL *cred, uint16_t *out); |
| 2787 |
| 2788 | // tls12_add_verify_sigalgs adds the signature algorithms acceptable for the |
| 2789 | // peer signature to |out|. It returns true on success and false on error. |
| 2790 | bool tls12_add_verify_sigalgs(const SSL_HANDSHAKE *hs, CBB *out); |
| 2791 |
| 2792 | // tls12_check_peer_sigalg checks if |sigalg| is acceptable for the peer |
| 2793 | // signature from |pkey|. It returns true on success and false on error, setting |
| 2794 | // |*out_alert| to an alert to send. |
| 2795 | bool tls12_check_peer_sigalg(const SSL_HANDSHAKE *hs, uint8_t *out_alert, |
| 2796 | uint16_t sigalg, EVP_PKEY *pkey); |
| 2797 |
| 2798 |
| 2799 | // Underdocumented functions. |
| 2800 | // |
| 2801 | // Functions below here haven't been touched up and may be underdocumented. |
| 2802 |
| 2803 | #define TLSEXT_CHANNEL_ID_SIZE 128 |
| 2804 |
| 2805 | // From RFC 4492, used in encoding the curve type in ECParameters |
| 2806 | #define NAMED_CURVE_TYPE 3 |
| 2807 |
| 2808 | struct CERT { |
| 2809 | static constexpr bool kAllowUniquePtr = true; |
| 2810 |
| 2811 | explicit CERT(const SSL_X509_METHOD *x509_method); |
| 2812 | ~CERT(); |
| 2813 |
| 2814 | bool is_valid() const { return legacy_credential != nullptr; } |
| 2815 |
| 2816 | // credentials is the list of credentials to select between. Elements of this |
| 2817 | // array immutable. |
| 2818 | Vector<UniquePtr<SSL_CREDENTIAL>> credentials; |
| 2819 |
| 2820 | // legacy_credential is the credential configured by the legacy |
| 2821 | // non-credential-based APIs. If IsComplete() returns true, it is appended to |
| 2822 | // the list of credentials. |
| 2823 | UniquePtr<SSL_CREDENTIAL> legacy_credential; |
| 2824 |
| 2825 | // x509_method contains pointers to functions that might deal with |X509| |
| 2826 | // compatibility, or might be a no-op, depending on the application. |
| 2827 | const SSL_X509_METHOD *x509_method = nullptr; |
| 2828 |
| 2829 | // x509_chain may contain a parsed copy of |chain[1..]| from the legacy |
| 2830 | // credential. This is only used as a cache in order to implement “get0” |
| 2831 | // functions that return a non-owning pointer to the certificate chain. |
| 2832 | STACK_OF(X509) *x509_chain = nullptr; |
| 2833 |
| 2834 | // x509_leaf may contain a parsed copy of the first element of |chain| from |
| 2835 | // the legacy credential. This is only used as a cache in order to implement |
| 2836 | // “get0” functions that return a non-owning pointer to the certificate chain. |
| 2837 | X509 *x509_leaf = nullptr; |
| 2838 |
| 2839 | // x509_stash contains the last |X509| object append to the legacy |
| 2840 | // credential's chain. This is a workaround for some third-party code that |
| 2841 | // continue to use an |X509| object even after passing ownership with an |
| 2842 | // “add0” function. |
| 2843 | X509 *x509_stash = nullptr; |
| 2844 |
| 2845 | // Certificate setup callback: if set is called whenever a |
| 2846 | // certificate may be required (client or server). the callback |
| 2847 | // can then examine any appropriate parameters and setup any |
| 2848 | // certificates required. This allows advanced applications |
| 2849 | // to select certificates on the fly: for example based on |
| 2850 | // supported signature algorithms or curves. |
| 2851 | int (*cert_cb)(SSL *ssl, void *arg) = nullptr; |
| 2852 | void *cert_cb_arg = nullptr; |
| 2853 |
| 2854 | // Optional X509_STORE for certificate validation. If NULL the parent SSL_CTX |
| 2855 | // store is used instead. |
| 2856 | X509_STORE *verify_store = nullptr; |
| 2857 |
| 2858 | // sid_ctx partitions the session space within a shared session cache or |
| 2859 | // ticket key. Only sessions with a matching value will be accepted. |
| 2860 | InplaceVector<uint8_t, SSL_MAX_SID_CTX_LENGTH> sid_ctx; |
| 2861 | }; |
| 2862 |
| 2863 | // |SSL_PROTOCOL_METHOD| abstracts between TLS and DTLS. |
| 2864 | struct SSL_PROTOCOL_METHOD { |
| 2865 | bool is_dtls; |
| 2866 | bool (*ssl_new)(SSL *ssl); |
| 2867 | void (*ssl_free)(SSL *ssl); |
| 2868 | // get_message sets |*out| to the current handshake message and returns true |
| 2869 | // if one has been received. It returns false if more input is needed. |
| 2870 | bool (*get_message)(const SSL *ssl, SSLMessage *out); |
| 2871 | // next_message is called to release the current handshake message. |
| 2872 | void (*next_message)(SSL *ssl); |
| 2873 | // has_unprocessed_handshake_data returns whether there is buffered |
| 2874 | // handshake data that has not been consumed by |get_message|. |
| 2875 | bool (*has_unprocessed_handshake_data)(const SSL *ssl); |
| 2876 | // Use the |ssl_open_handshake| wrapper. |
| 2877 | ssl_open_record_t (*open_handshake)(SSL *ssl, size_t *out_consumed, |
| 2878 | uint8_t *out_alert, Span<uint8_t> in); |
| 2879 | // Use the |ssl_open_change_cipher_spec| wrapper. |
| 2880 | ssl_open_record_t (*open_change_cipher_spec)(SSL *ssl, size_t *out_consumed, |
| 2881 | uint8_t *out_alert, |
| 2882 | Span<uint8_t> in); |
| 2883 | // Use the |ssl_open_app_data| wrapper. |
| 2884 | ssl_open_record_t (*open_app_data)(SSL *ssl, Span<uint8_t> *out, |
| 2885 | size_t *out_consumed, uint8_t *out_alert, |
| 2886 | Span<uint8_t> in); |
| 2887 | // write_app_data encrypts and writes |in| as application data. On success, it |
| 2888 | // returns one and sets |*out_bytes_written| to the number of bytes of |in| |
| 2889 | // written. Otherwise, it returns <= 0 and sets |*out_needs_handshake| to |
| 2890 | // whether the operation failed because the caller needs to drive the |
| 2891 | // handshake. |
| 2892 | int (*write_app_data)(SSL *ssl, bool *out_needs_handshake, |
| 2893 | size_t *out_bytes_written, Span<const uint8_t> in); |
| 2894 | int (*dispatch_alert)(SSL *ssl); |
| 2895 | // init_message begins a new handshake message of type |type|. |cbb| is the |
| 2896 | // root CBB to be passed into |finish_message|. |*body| is set to a child CBB |
| 2897 | // the caller should write to. It returns true on success and false on error. |
| 2898 | bool (*init_message)(const SSL *ssl, CBB *cbb, CBB *body, uint8_t type); |
| 2899 | // finish_message finishes a handshake message. It sets |*out_msg| to the |
| 2900 | // serialized message. It returns true on success and false on error. |
| 2901 | bool (*finish_message)(const SSL *ssl, CBB *cbb, |
| 2902 | bssl::Array<uint8_t> *out_msg); |
| 2903 | // add_message adds a handshake message to the pending flight. It returns |
| 2904 | // true on success and false on error. |
| 2905 | bool (*add_message)(SSL *ssl, bssl::Array<uint8_t> msg); |
| 2906 | // add_change_cipher_spec adds a ChangeCipherSpec record to the pending |
| 2907 | // flight. It returns true on success and false on error. |
| 2908 | bool (*add_change_cipher_spec)(SSL *ssl); |
| 2909 | // finish_flight marks the pending flight as finished and ready to send. |
| 2910 | // |flush| must be called to write it. |
| 2911 | void (*finish_flight)(SSL *ssl); |
| 2912 | // schedule_ack schedules a DTLS 1.3 ACK to be sent, without an ACK delay. |
| 2913 | // |flush| must be called to write it. |
| 2914 | void (*schedule_ack)(SSL *ssl); |
| 2915 | // flush writes any scheduled data to the transport. It returns one on success |
| 2916 | // and <= 0 on error. |
| 2917 | int (*flush)(SSL *ssl); |
| 2918 | // on_handshake_complete is called when the handshake is complete. |
| 2919 | void (*on_handshake_complete)(SSL *ssl); |
| 2920 | // set_read_state sets |ssl|'s read cipher state and level to |aead_ctx| and |
| 2921 | // |level|. In QUIC, |aead_ctx| is a placeholder object. In TLS 1.3, |
| 2922 | // |traffic_secret| is the original traffic secret. This function returns true |
| 2923 | // on success and false on error. |
| 2924 | // |
| 2925 | // TODO(crbug.com/371998381): Take the traffic secrets as input and let the |
| 2926 | // function create the SSLAEADContext. |
| 2927 | bool (*set_read_state)(SSL *ssl, ssl_encryption_level_t level, |
| 2928 | UniquePtr<SSLAEADContext> aead_ctx, |
| 2929 | Span<const uint8_t> traffic_secret); |
| 2930 | // set_write_state sets |ssl|'s write cipher state and level to |aead_ctx| and |
| 2931 | // |level|. In QUIC, |aead_ctx| is a placeholder object In TLS 1.3, |
| 2932 | // |traffic_secret| is the original traffic secret. This function returns true |
| 2933 | // on success and false on error. |
| 2934 | // |
| 2935 | // TODO(crbug.com/371998381): Take the traffic secrets as input and let the |
| 2936 | // function create the SSLAEADContext. |
| 2937 | bool (*set_write_state)(SSL *ssl, ssl_encryption_level_t level, |
| 2938 | UniquePtr<SSLAEADContext> aead_ctx, |
| 2939 | Span<const uint8_t> traffic_secret); |
| 2940 | }; |
| 2941 |
| 2942 | // The following wrappers call |open_*| but handle |read_shutdown| correctly. |
| 2943 |
| 2944 | // ssl_open_handshake processes a record from |in| for reading a handshake |
| 2945 | // message. |
| 2946 | ssl_open_record_t ssl_open_handshake(SSL *ssl, size_t *out_consumed, |
| 2947 | uint8_t *out_alert, Span<uint8_t> in); |
| 2948 |
| 2949 | // ssl_open_change_cipher_spec processes a record from |in| for reading a |
| 2950 | // ChangeCipherSpec. |
| 2951 | ssl_open_record_t ssl_open_change_cipher_spec(SSL *ssl, size_t *out_consumed, |
| 2952 | uint8_t *out_alert, |
| 2953 | Span<uint8_t> in); |
| 2954 |
| 2955 | // ssl_open_app_data processes a record from |in| for reading application data. |
| 2956 | // On success, it returns |ssl_open_record_success| and sets |*out| to the |
| 2957 | // input. If it encounters a post-handshake message, it returns |
| 2958 | // |ssl_open_record_discard|. The caller should then retry, after processing any |
| 2959 | // messages received with |get_message|. |
| 2960 | ssl_open_record_t ssl_open_app_data(SSL *ssl, Span<uint8_t> *out, |
| 2961 | size_t *out_consumed, uint8_t *out_alert, |
| 2962 | Span<uint8_t> in); |
| 2963 |
| 2964 | struct SSL_X509_METHOD { |
| 2965 | // check_CA_list returns one if |names| is a good list of X.509 distinguished |
| 2966 | // names and zero otherwise. This is used to ensure that we can reject |
| 2967 | // unparsable values at handshake time when using crypto/x509. |
| 2968 | bool (*check_CA_list)(STACK_OF(CRYPTO_BUFFER) *names); |
| 2969 |
| 2970 | // cert_clear frees and NULLs all X509 certificate-related state. |
| 2971 | void (*cert_clear)(CERT *cert); |
| 2972 | // cert_free frees all X509-related state. |
| 2973 | void (*cert_free)(CERT *cert); |
| 2974 | // cert_flush_cached_chain drops any cached |X509|-based certificate chain |
| 2975 | // from |cert|. |
| 2976 | // cert_dup duplicates any needed fields from |cert| to |new_cert|. |
| 2977 | void (*cert_dup)(CERT *new_cert, const CERT *cert); |
| 2978 | void (*cert_flush_cached_chain)(CERT *cert); |
| 2979 | // cert_flush_cached_chain drops any cached |X509|-based leaf certificate |
| 2980 | // from |cert|. |
| 2981 | void (*cert_flush_cached_leaf)(CERT *cert); |
| 2982 |
| 2983 | // session_cache_objects fills out |sess->x509_peer| and |sess->x509_chain| |
| 2984 | // from |sess->certs| and erases |sess->x509_chain_without_leaf|. It returns |
| 2985 | // true on success or false on error. |
| 2986 | bool (*session_cache_objects)(SSL_SESSION *session); |
| 2987 | // session_dup duplicates any needed fields from |session| to |new_session|. |
| 2988 | // It returns true on success or false on error. |
| 2989 | bool (*session_dup)(SSL_SESSION *new_session, const SSL_SESSION *session); |
| 2990 | // session_clear frees any X509-related state from |session|. |
| 2991 | void (*session_clear)(SSL_SESSION *session); |
| 2992 | // session_verify_cert_chain verifies the certificate chain in |session|, |
| 2993 | // sets |session->verify_result| and returns true on success or false on |
| 2994 | // error. |
| 2995 | bool (*session_verify_cert_chain)(SSL_SESSION *session, SSL_HANDSHAKE *ssl, |
| 2996 | uint8_t *out_alert); |
| 2997 |
| 2998 | // hs_flush_cached_ca_names drops any cached |X509_NAME|s from |hs|. |
| 2999 | void (*hs_flush_cached_ca_names)(SSL_HANDSHAKE *hs); |
| 3000 | // ssl_new does any necessary initialisation of |hs|. It returns true on |
| 3001 | // success or false on error. |
| 3002 | bool (*ssl_new)(SSL_HANDSHAKE *hs); |
| 3003 | // ssl_free frees anything created by |ssl_new|. |
| 3004 | void (*ssl_config_free)(SSL_CONFIG *cfg); |
| 3005 | // ssl_flush_cached_client_CA drops any cached |X509_NAME|s from |ssl|. |
| 3006 | void (*ssl_flush_cached_client_CA)(SSL_CONFIG *cfg); |
| 3007 | // ssl_auto_chain_if_needed runs the deprecated auto-chaining logic if |
| 3008 | // necessary. On success, it updates |ssl|'s certificate configuration as |
| 3009 | // needed and returns true. Otherwise, it returns false. |
| 3010 | bool (*ssl_auto_chain_if_needed)(SSL_HANDSHAKE *hs); |
| 3011 | // ssl_ctx_new does any necessary initialisation of |ctx|. It returns true on |
| 3012 | // success or false on error. |
| 3013 | bool (*ssl_ctx_new)(SSL_CTX *ctx); |
| 3014 | // ssl_ctx_free frees anything created by |ssl_ctx_new|. |
| 3015 | void (*ssl_ctx_free)(SSL_CTX *ctx); |
| 3016 | // ssl_ctx_flush_cached_client_CA drops any cached |X509_NAME|s from |ctx|. |
| 3017 | void (*ssl_ctx_flush_cached_client_CA)(SSL_CTX *ssl); |
| 3018 | }; |
| 3019 |
| 3020 | // ssl_crypto_x509_method provides the |SSL_X509_METHOD| functions using |
| 3021 | // crypto/x509. |
| 3022 | extern const SSL_X509_METHOD ssl_crypto_x509_method; |
| 3023 |
| 3024 | // ssl_noop_x509_method provides the |SSL_X509_METHOD| functions that avoid |
| 3025 | // crypto/x509. |
| 3026 | extern const SSL_X509_METHOD ssl_noop_x509_method; |
| 3027 |
| 3028 | struct TicketKey { |
| 3029 | static constexpr bool kAllowUniquePtr = true; |
| 3030 |
| 3031 | uint8_t name[SSL_TICKET_KEY_NAME_LEN] = {0}; |
| 3032 | uint8_t hmac_key[16] = {0}; |
| 3033 | uint8_t aes_key[16] = {0}; |
| 3034 | // next_rotation_tv_sec is the time (in seconds from the epoch) when the |
| 3035 | // current key should be superseded by a new key, or the time when a previous |
| 3036 | // key should be dropped. If zero, then the key should not be automatically |
| 3037 | // rotated. |
| 3038 | uint64_t next_rotation_tv_sec = 0; |
| 3039 | }; |
| 3040 |
| 3041 | struct CertCompressionAlg { |
| 3042 | static constexpr bool kAllowUniquePtr = true; |
| 3043 |
| 3044 | ssl_cert_compression_func_t compress = nullptr; |
| 3045 | ssl_cert_decompression_func_t decompress = nullptr; |
| 3046 | uint16_t alg_id = 0; |
| 3047 | }; |
| 3048 |
| 3049 | BSSL_NAMESPACE_END |
| 3050 |
| 3051 | DEFINE_LHASH_OF(SSL_SESSION) |
| 3052 |
| 3053 | BSSL_NAMESPACE_BEGIN |
| 3054 |
| 3055 | // An ssl_shutdown_t describes the shutdown state of one end of the connection, |
| 3056 | // whether it is alive or has been shutdown via close_notify or fatal alert. |
| 3057 | enum ssl_shutdown_t { |
| 3058 | ssl_shutdown_none = 0, |
| 3059 | ssl_shutdown_close_notify = 1, |
| 3060 | ssl_shutdown_error = 2, |
| 3061 | }; |
| 3062 |
| 3063 | enum ssl_ech_status_t { |
| 3064 | // ssl_ech_none indicates ECH was not offered, or we have not gotten far |
| 3065 | // enough in the handshake to determine the status. |
| 3066 | ssl_ech_none, |
| 3067 | // ssl_ech_accepted indicates the server accepted ECH. |
| 3068 | ssl_ech_accepted, |
| 3069 | // ssl_ech_rejected indicates the server was offered ECH but rejected it. |
| 3070 | ssl_ech_rejected, |
| 3071 | }; |
| 3072 |
| 3073 | struct SSL3_STATE { |
| 3074 | static constexpr bool kAllowUniquePtr = true; |
| 3075 |
| 3076 | SSL3_STATE(); |
| 3077 | ~SSL3_STATE(); |
| 3078 |
| 3079 | uint64_t read_sequence = 0; |
| 3080 | uint64_t write_sequence = 0; |
| 3081 |
| 3082 | uint8_t server_random[SSL3_RANDOM_SIZE] = {0}; |
| 3083 | uint8_t client_random[SSL3_RANDOM_SIZE] = {0}; |
| 3084 |
| 3085 | // read_buffer holds data from the transport to be processed. |
| 3086 | SSLBuffer read_buffer; |
| 3087 | // write_buffer holds data to be written to the transport. |
| 3088 | SSLBuffer write_buffer; |
| 3089 |
| 3090 | // pending_app_data is the unconsumed application data. It points into |
| 3091 | // |read_buffer|. |
| 3092 | Span<uint8_t> pending_app_data; |
| 3093 |
| 3094 | // unreported_bytes_written is the number of bytes successfully written to the |
| 3095 | // transport, but not yet reported to the caller. The next |SSL_write| will |
| 3096 | // skip this many bytes from the input. This is used if |
| 3097 | // |SSL_MODE_ENABLE_PARTIAL_WRITE| is disabled, in which case |SSL_write| only |
| 3098 | // reports bytes written when the full caller input is written. |
| 3099 | size_t unreported_bytes_written = 0; |
| 3100 |
| 3101 | // pending_write, if |has_pending_write| is true, is the caller-supplied data |
| 3102 | // corresponding to the current pending write. This is used to check the |
| 3103 | // caller retried with a compatible buffer. |
| 3104 | Span<const uint8_t> pending_write; |
| 3105 |
| 3106 | // pending_write_type, if |has_pending_write| is true, is the record type |
| 3107 | // for the current pending write. |
| 3108 | // |
| 3109 | // TODO(davidben): Remove this when alerts are moved out of this write path. |
| 3110 | uint8_t pending_write_type = 0; |
| 3111 |
| 3112 | // read_shutdown is the shutdown state for the read half of the connection. |
| 3113 | enum ssl_shutdown_t read_shutdown = ssl_shutdown_none; |
| 3114 |
| 3115 | // write_shutdown is the shutdown state for the write half of the connection. |
| 3116 | enum ssl_shutdown_t write_shutdown = ssl_shutdown_none; |
| 3117 |
| 3118 | // read_error, if |read_shutdown| is |ssl_shutdown_error|, is the error for |
| 3119 | // the receive half of the connection. |
| 3120 | UniquePtr<ERR_SAVE_STATE> read_error; |
| 3121 |
| 3122 | int total_renegotiations = 0; |
| 3123 |
| 3124 | // This holds a variable that indicates what we were doing when a 0 or -1 is |
| 3125 | // returned. This is needed for non-blocking IO so we know what request |
| 3126 | // needs re-doing when in SSL_accept or SSL_connect |
| 3127 | int rwstate = SSL_ERROR_NONE; |
| 3128 |
| 3129 | enum ssl_encryption_level_t quic_read_level = ssl_encryption_initial; |
| 3130 | enum ssl_encryption_level_t quic_write_level = ssl_encryption_initial; |
| 3131 |
| 3132 | // version is the protocol version, or zero if the version has not yet been |
| 3133 | // set. In clients offering 0-RTT, this version will initially be set to the |
| 3134 | // early version, then switched to the final version. To distinguish these |
| 3135 | // cases, use |ssl_has_final_version|. |
| 3136 | uint16_t version = 0; |
| 3137 |
| 3138 | // early_data_skipped is the amount of early data that has been skipped by the |
| 3139 | // record layer. |
| 3140 | uint16_t early_data_skipped = 0; |
| 3141 |
| 3142 | // empty_record_count is the number of consecutive empty records received. |
| 3143 | uint8_t empty_record_count = 0; |
| 3144 |
| 3145 | // warning_alert_count is the number of consecutive warning alerts |
| 3146 | // received. |
| 3147 | uint8_t warning_alert_count = 0; |
| 3148 |
| 3149 | // key_update_count is the number of consecutive KeyUpdates received. |
| 3150 | uint8_t key_update_count = 0; |
| 3151 |
| 3152 | // ech_status indicates whether ECH was accepted by the server. |
| 3153 | ssl_ech_status_t ech_status = ssl_ech_none; |
| 3154 |
| 3155 | // skip_early_data instructs the record layer to skip unexpected early data |
| 3156 | // messages when 0RTT is rejected. |
| 3157 | bool skip_early_data : 1; |
| 3158 |
| 3159 | // v2_hello_done is true if the peer's V2ClientHello, if any, has been handled |
| 3160 | // and future messages should use the record layer. |
| 3161 | bool v2_hello_done : 1; |
| 3162 |
| 3163 | // is_v2_hello is true if the current handshake message was derived from a |
| 3164 | // V2ClientHello rather than received from the peer directly. |
| 3165 | bool is_v2_hello : 1; |
| 3166 |
| 3167 | // has_message is true if the current handshake message has been returned |
| 3168 | // at least once by |get_message| and false otherwise. |
| 3169 | bool has_message : 1; |
| 3170 |
| 3171 | // initial_handshake_complete is true if the initial handshake has |
| 3172 | // completed. |
| 3173 | bool initial_handshake_complete : 1; |
| 3174 |
| 3175 | // session_reused indicates whether a session was resumed. |
| 3176 | bool session_reused : 1; |
| 3177 |
| 3178 | bool send_connection_binding : 1; |
| 3179 |
| 3180 | // channel_id_valid is true if, on the server, the client has negotiated a |
| 3181 | // Channel ID and the |channel_id| field is filled in. |
| 3182 | bool channel_id_valid : 1; |
| 3183 |
| 3184 | // key_update_pending is true if we are in the process of sending a KeyUpdate |
| 3185 | // message. As a DoS mitigation (and a requirement in DTLS), we never send |
| 3186 | // more than one KeyUpdate at once. In DTLS, this tracks whether there is an |
| 3187 | // unACKed KeyUpdate. |
| 3188 | bool key_update_pending : 1; |
| 3189 |
| 3190 | // early_data_accepted is true if early data was accepted by the server. |
| 3191 | bool early_data_accepted : 1; |
| 3192 |
| 3193 | // alert_dispatch is true there is an alert in |send_alert| to be sent. |
| 3194 | bool alert_dispatch : 1; |
| 3195 |
| 3196 | // renegotiate_pending is whether the read half of the channel is blocked on a |
| 3197 | // HelloRequest. |
| 3198 | bool renegotiate_pending : 1; |
| 3199 |
| 3200 | // used_hello_retry_request is whether the handshake used a TLS 1.3 |
| 3201 | // HelloRetryRequest message. |
| 3202 | bool used_hello_retry_request : 1; |
| 3203 |
| 3204 | // was_key_usage_invalid is whether the handshake succeeded despite using a |
| 3205 | // TLS mode which was incompatible with the leaf certificate's keyUsage |
| 3206 | // extension. |
| 3207 | bool was_key_usage_invalid : 1; |
| 3208 |
| 3209 | // hs_buf is the buffer of handshake data to process. |
| 3210 | UniquePtr<BUF_MEM> hs_buf; |
| 3211 |
| 3212 | // pending_hs_data contains the pending handshake data that has not yet |
| 3213 | // been encrypted to |pending_flight|. This allows packing the handshake into |
| 3214 | // fewer records. |
| 3215 | UniquePtr<BUF_MEM> pending_hs_data; |
| 3216 |
| 3217 | // pending_flight is the pending outgoing flight. This is used to flush each |
| 3218 | // handshake flight in a single write. |write_buffer| must be written out |
| 3219 | // before this data. |
| 3220 | UniquePtr<BUF_MEM> pending_flight; |
| 3221 |
| 3222 | // pending_flight_offset is the number of bytes of |pending_flight| which have |
| 3223 | // been successfully written. |
| 3224 | uint32_t pending_flight_offset = 0; |
| 3225 |
| 3226 | // ticket_age_skew is the difference, in seconds, between the client-sent |
| 3227 | // ticket age and the server-computed value in TLS 1.3 server connections |
| 3228 | // which resumed a session. |
| 3229 | int32_t ticket_age_skew = 0; |
| 3230 |
| 3231 | // ssl_early_data_reason stores details on why 0-RTT was accepted or rejected. |
| 3232 | enum ssl_early_data_reason_t early_data_reason = ssl_early_data_unknown; |
| 3233 |
| 3234 | // aead_read_ctx is the current read cipher state. |
| 3235 | UniquePtr<SSLAEADContext> aead_read_ctx; |
| 3236 |
| 3237 | // aead_write_ctx is the current write cipher state. |
| 3238 | UniquePtr<SSLAEADContext> aead_write_ctx; |
| 3239 |
| 3240 | // hs is the handshake state for the current handshake or NULL if there isn't |
| 3241 | // one. |
| 3242 | UniquePtr<SSL_HANDSHAKE> hs; |
| 3243 |
| 3244 | InplaceVector<uint8_t, SSL_MAX_MD_SIZE> write_traffic_secret; |
| 3245 | InplaceVector<uint8_t, SSL_MAX_MD_SIZE> read_traffic_secret; |
| 3246 | InplaceVector<uint8_t, SSL_MAX_MD_SIZE> exporter_secret; |
| 3247 |
| 3248 | // Connection binding to prevent renegotiation attacks |
| 3249 | InplaceVector<uint8_t, 12> previous_client_finished; |
| 3250 | InplaceVector<uint8_t, 12> previous_server_finished; |
| 3251 |
| 3252 | uint8_t send_alert[2] = {0}; |
| 3253 |
| 3254 | // established_session is the session established by the connection. This |
| 3255 | // session is only filled upon the completion of the handshake and is |
| 3256 | // immutable. |
| 3257 | UniquePtr<SSL_SESSION> established_session; |
| 3258 |
| 3259 | // Next protocol negotiation. For the client, this is the protocol that we |
| 3260 | // sent in NextProtocol and is set when handling ServerHello extensions. |
| 3261 | // |
| 3262 | // For a server, this is the client's selected_protocol from NextProtocol and |
| 3263 | // is set when handling the NextProtocol message, before the Finished |
| 3264 | // message. |
| 3265 | Array<uint8_t> next_proto_negotiated; |
| 3266 |
| 3267 | // ALPN information |
| 3268 | // (we are in the process of transitioning from NPN to ALPN.) |
| 3269 |
| 3270 | // In a server these point to the selected ALPN protocol after the |
| 3271 | // ClientHello has been processed. In a client these contain the protocol |
| 3272 | // that the server selected once the ServerHello has been processed. |
| 3273 | Array<uint8_t> alpn_selected; |
| 3274 |
| 3275 | // hostname, on the server, is the value of the SNI extension. |
| 3276 | UniquePtr<char> hostname; |
| 3277 |
| 3278 | // For a server: |
| 3279 | // If |channel_id_valid| is true, then this contains the |
| 3280 | // verified Channel ID from the client: a P256 point, (x,y), where |
| 3281 | // each are big-endian values. |
| 3282 | uint8_t channel_id[64] = {0}; |
| 3283 |
| 3284 | // Contains the QUIC transport params received by the peer. |
| 3285 | Array<uint8_t> peer_quic_transport_params; |
| 3286 |
| 3287 | // srtp_profile is the selected SRTP protection profile for |
| 3288 | // DTLS-SRTP. |
| 3289 | const SRTP_PROTECTION_PROFILE *srtp_profile = nullptr; |
| 3290 | }; |
| 3291 |
| 3292 | // lengths of messages |
| 3293 | #define DTLS1_RT_MAX_HEADER_LENGTH 13 |
| 3294 |
| 3295 | // DTLS_PLAINTEXT_RECORD_HEADER_LENGTH is the length of the DTLS record header |
| 3296 | // for plaintext records (in DTLS 1.3) or DTLS versions <= 1.2. |
| 3297 | #define DTLS_PLAINTEXT_RECORD_HEADER_LENGTH 13 |
| 3298 |
| 3299 | // DTLS1_3_RECORD_HEADER_LENGTH is the length of the DTLS 1.3 record header |
| 3300 | // sent by BoringSSL for encrypted records. Note that received encrypted DTLS |
| 3301 | // 1.3 records might have a different length header. |
| 3302 | #define DTLS1_3_RECORD_HEADER_WRITE_LENGTH 5 |
| 3303 |
| 3304 | static_assert(DTLS1_RT_MAX_HEADER_LENGTH >= DTLS_PLAINTEXT_RECORD_HEADER_LENGTH, |
| 3305 | "DTLS1_RT_MAX_HEADER_LENGTH must not be smaller than defined " |
| 3306 | "record header lengths"); |
| 3307 | static_assert(DTLS1_RT_MAX_HEADER_LENGTH >= DTLS1_3_RECORD_HEADER_WRITE_LENGTH, |
| 3308 | "DTLS1_RT_MAX_HEADER_LENGTH must not be smaller than defined " |
| 3309 | "record header lengths"); |
| 3310 |
| 3311 | #define DTLS1_HM_HEADER_LENGTH 12 |
| 3312 |
| 3313 | // A DTLSMessageBitmap maintains a list of bits which may be marked to indicate |
| 3314 | // a portion of a message was received or ACKed. |
| 3315 | class DTLSMessageBitmap { |
| 3316 | public: |
| 3317 | // A Range represents a range of bits from |start|, inclusive, to |end|, |
| 3318 | // exclusive. |
| 3319 | struct Range { |
| 3320 | size_t start = 0; |
| 3321 | size_t end = 0; |
| 3322 |
| 3323 | bool empty() const { return start == end; } |
| 3324 | size_t size() const { return end - start; } |
| 3325 | bool operator==(const Range &r) const { |
| 3326 | return start == r.start && end == r.end; |
| 3327 | } |
| 3328 | bool operator!=(const Range &r) const { return !(*this == r); } |
| 3329 | }; |
| 3330 |
| 3331 | // Init initializes the structure with |num_bits| unmarked bits, from zero |
| 3332 | // to |num_bits - 1|. |
| 3333 | bool Init(size_t num_bits); |
| 3334 |
| 3335 | // MarkRange marks the bits from |start|, inclusive, to |end|, exclusive. |
| 3336 | void MarkRange(size_t start, size_t end); |
| 3337 |
| 3338 | // NextUnmarkedRange returns the next range of unmarked bits, starting from |
| 3339 | // |start|, inclusive. If all bits after |start| are marked, it returns an |
| 3340 | // empty range. |
| 3341 | Range NextUnmarkedRange(size_t start) const; |
| 3342 |
| 3343 | // IsComplete returns whether every bit in the bitmask has been marked. |
| 3344 | bool IsComplete() const { return bytes_.empty(); } |
| 3345 |
| 3346 | private: |
| 3347 | // bytes_ contains the unmarked bits. We maintain an invariant: if |bytes_| is |
| 3348 | // not empty, some bit is unset. |
| 3349 | Array<uint8_t> bytes_; |
| 3350 | // first_unmarked_byte_ is the index of first byte in |bytes_| that is not |
| 3351 | // 0xff. This is maintained to amortize checking if the message is complete. |
| 3352 | size_t first_unmarked_byte_ = 0; |
| 3353 | }; |
| 3354 |
| 3355 | struct hm_header_st { |
| 3356 | uint8_t type; |
| 3357 | uint32_t msg_len; |
| 3358 | uint16_t seq; |
| 3359 | uint32_t frag_off; |
| 3360 | uint32_t frag_len; |
| 3361 | }; |
| 3362 |
| 3363 | // An DTLSIncomingMessage is an incoming DTLS message, possibly not yet |
| 3364 | // assembled. |
| 3365 | struct DTLSIncomingMessage { |
| 3366 | static constexpr bool kAllowUniquePtr = true; |
| 3367 |
| 3368 | Span<uint8_t> msg() { return Span(data).subspan(DTLS1_HM_HEADER_LENGTH); } |
| 3369 | Span<const uint8_t> msg() const { |
| 3370 | return Span(data).subspan(DTLS1_HM_HEADER_LENGTH); |
| 3371 | } |
| 3372 | size_t msg_len() const { return msg().size(); } |
| 3373 |
| 3374 | // type is the type of the message. |
| 3375 | uint8_t type = 0; |
| 3376 | // seq is the sequence number of this message. |
| 3377 | uint16_t seq = 0; |
| 3378 | // data contains the message, including the message header of length |
| 3379 | // |DTLS1_HM_HEADER_LENGTH|. |
| 3380 | Array<uint8_t> data; |
| 3381 | // reassembly tracks which parts of the message have been received. |
| 3382 | DTLSMessageBitmap reassembly; |
| 3383 | }; |
| 3384 |
| 3385 | struct DTLSOutgoingMessage { |
| 3386 | size_t msg_len() const { |
| 3387 | assert(!is_ccs); |
| 3388 | assert(data.size() >= DTLS1_HM_HEADER_LENGTH); |
| 3389 | return data.size() - DTLS1_HM_HEADER_LENGTH; |
| 3390 | } |
| 3391 |
| 3392 | bool IsFullyAcked() const { |
| 3393 | // ACKs only exist in DTLS 1.3, which does not send ChangeCipherSpec. |
| 3394 | return !is_ccs && acked.IsComplete(); |
| 3395 | } |
| 3396 |
| 3397 | Array<uint8_t> data; |
| 3398 | uint16_t epoch = 0; |
| 3399 | bool is_ccs = false; |
| 3400 | // acked tracks which bits of the message have been ACKed by the peer. If |
| 3401 | // |msg_len| is zero, it tracks one bit for whether the header has been |
| 3402 | // received. |
| 3403 | DTLSMessageBitmap acked; |
| 3404 | }; |
| 3405 |
| 3406 | struct OPENSSL_timeval { |
| 3407 | uint64_t tv_sec; |
| 3408 | uint32_t tv_usec; |
| 3409 | }; |
| 3410 |
| 3411 | struct DTLSTimer { |
| 3412 | public: |
| 3413 | static constexpr uint64_t kNever = UINT64_MAX; |
| 3414 |
| 3415 | // StartMicroseconds schedules the timer to expire the specified number of |
| 3416 | // microseconds from |now|. |
| 3417 | void StartMicroseconds(OPENSSL_timeval now, uint64_t microseconds); |
| 3418 |
| 3419 | // Stop disables the timer. |
| 3420 | void Stop(); |
| 3421 |
| 3422 | // IsExpired returns true if the timer was set and is expired at time |now|. |
| 3423 | bool IsExpired(OPENSSL_timeval now) const; |
| 3424 |
| 3425 | // IsSet returns true if the timer is scheduled or expired, and false if it is |
| 3426 | // stopped. |
| 3427 | bool IsSet() const; |
| 3428 |
| 3429 | // MicrosecondsRemaining returns the time remaining, in microseconds, at |
| 3430 | // |now|, or |kNever| if the timer is unset. |
| 3431 | uint64_t MicrosecondsRemaining(OPENSSL_timeval now) const; |
| 3432 |
| 3433 | private: |
| 3434 | // expire_time_ is the time when the timer expires, or zero if the timer is |
| 3435 | // unset. |
| 3436 | // |
| 3437 | // TODO(crbug.com/366284846): This is an extremely inconvenient time |
| 3438 | // representation. Switch libssl to something like a 64-bit count of |
| 3439 | // microseconds. While it's decidedly past 1970 now, zero is a less obviously |
| 3440 | // sound distinguished value for the monotonic clock, so maybe we should use a |
| 3441 | // different distinguished time, like |INT64_MAX| in the microseconds |
| 3442 | // representation. |
| 3443 | OPENSSL_timeval expire_time_ = {0, 0}; |
| 3444 | }; |
| 3445 |
| 3446 | // DTLS_MAX_EXTRA_WRITE_EPOCHS is the maximum number of additional write epochs |
| 3447 | // that DTLS may need to retain. |
| 3448 | // |
| 3449 | // The maximum is, as a DTLS 1.3 server, immediately after sending Finished. At |
| 3450 | // this point, the current epoch is the application write keys (epoch 3), but we |
| 3451 | // may have ServerHello (epoch 0) and EncryptedExtensions (epoch 1) to |
| 3452 | // retransmit. KeyUpdate does not increase this count. If the server were to |
| 3453 | // initiate KeyUpdate from this state, it would not apply the new epoch until |
| 3454 | // the client's ACKs have caught up. At that point, epochs 0 and 1 can be |
| 3455 | // discarded. |
| 3456 | #define DTLS_MAX_EXTRA_WRITE_EPOCHS 2 |
| 3457 |
| 3458 | // DTLS_MAX_ACK_BUFFER is the maximum number of records worth of data we'll keep |
| 3459 | // track of with DTLS 1.3 ACKs. When we exceed this value, information about |
| 3460 | // stale records will be dropped. This will not break the connection but may |
| 3461 | // cause ACKs to perform worse and retransmit unnecessary information. |
| 3462 | #define DTLS_MAX_ACK_BUFFER 32 |
| 3463 |
| 3464 | // A DTLSSentRecord records information about a record we sent. Each record |
| 3465 | // covers all bytes from |first_msg_start| (inclusive) of |first_msg| to |
| 3466 | // |last_msg_end| (exclusive) of |last_msg|. Messages are referenced by index |
| 3467 | // into |outgoing_messages|. |last_msg_end| may be |outgoing_messages.size()| if |
| 3468 | // |last_msg_end| is zero. |
| 3469 | // |
| 3470 | // When the message is empty, |first_msg_start| and |last_msg_end| are |
| 3471 | // maintained as if there is a single bit in the message representing the |
| 3472 | // header. See |acked| in DTLSOutgoingMessage. |
| 3473 | struct DTLSSentRecord { |
| 3474 | DTLSRecordNumber number; |
| 3475 | PackedSize<SSL_MAX_HANDSHAKE_FLIGHT> first_msg = 0; |
| 3476 | PackedSize<SSL_MAX_HANDSHAKE_FLIGHT> last_msg = 0; |
| 3477 | uint32_t first_msg_start = 0; |
| 3478 | uint32_t last_msg_end = 0; |
| 3479 | }; |
| 3480 |
| 3481 | enum class QueuedKeyUpdate { |
| 3482 | kNone, |
| 3483 | kUpdateNotRequested, |
| 3484 | kUpdateRequested, |
| 3485 | }; |
| 3486 |
| 3487 | // DTLS_PREV_READ_EPOCH_EXPIRE_SECONDS is how long to retain the previous read |
| 3488 | // epoch in DTLS 1.3. This value is set based on the following: |
| 3489 | // |
| 3490 | // - Section 4.2.1 of RFC 9147 recommends retaining past read epochs for the |
| 3491 | // default TCP MSL. This accommodates packet reordering with KeyUpdate. |
| 3492 | // |
| 3493 | // - Section 5.8.1 of RFC 9147 requires being capable of ACKing the client's |
| 3494 | // final flight for at least twice the default MSL. That requires retaining |
| 3495 | // epoch 2 after the handshake. |
| 3496 | // |
| 3497 | // - Section 4 of RFC 9293 defines the MSL to be two minutes. |
| 3498 | #define DTLS_PREV_READ_EPOCH_EXPIRE_SECONDS (4 * 60) |
| 3499 |
| 3500 | struct DTLSPrevReadEpoch { |
| 3501 | static constexpr bool kAllowUniquePtr = true; |
| 3502 | DTLSReadEpoch epoch; |
| 3503 | // expire is the expiration time of the read epoch, expressed as a POSIX |
| 3504 | // timestamp in seconds. |
| 3505 | uint64_t expire; |
| 3506 | }; |
| 3507 |
| 3508 | struct DTLS1_STATE { |
| 3509 | static constexpr bool kAllowUniquePtr = true; |
| 3510 |
| 3511 | DTLS1_STATE(); |
| 3512 | ~DTLS1_STATE(); |
| 3513 |
| 3514 | bool Init(); |
| 3515 |
| 3516 | // has_change_cipher_spec is true if we have received a ChangeCipherSpec from |
| 3517 | // the peer in this epoch. |
| 3518 | bool has_change_cipher_spec : 1; |
| 3519 |
| 3520 | // outgoing_messages_complete is true if |outgoing_messages| has been |
| 3521 | // completed by an attempt to flush it. Future calls to |add_message| and |
| 3522 | // |add_change_cipher_spec| will start a new flight. |
| 3523 | bool outgoing_messages_complete : 1; |
| 3524 |
| 3525 | // flight_has_reply is true if the current outgoing flight is complete and has |
| 3526 | // processed at least one message. This is used to detect whether we or the |
| 3527 | // peer sent the final flight. |
| 3528 | bool flight_has_reply : 1; |
| 3529 |
| 3530 | // handshake_write_overflow and handshake_read_overflow are true if |
| 3531 | // handshake_write_seq and handshake_read_seq, respectively have overflowed. |
| 3532 | bool handshake_write_overflow : 1; |
| 3533 | bool handshake_read_overflow : 1; |
| 3534 |
| 3535 | // sending_flight and sending_ack are true if we are in the process of sending |
| 3536 | // a handshake flight and ACK, respectively. |
| 3537 | bool sending_flight : 1; |
| 3538 | bool sending_ack : 1; |
| 3539 |
| 3540 | // queued_key_update, if not kNone, indicates we've queued a KeyUpdate message |
| 3541 | // to send after the current flight is ACKed. |
| 3542 | QueuedKeyUpdate queued_key_update : 2; |
| 3543 |
| 3544 | uint16_t handshake_write_seq = 0; |
| 3545 | uint16_t handshake_read_seq = 0; |
| 3546 |
| 3547 | // read_epoch is the current read epoch. |
| 3548 | DTLSReadEpoch read_epoch; |
| 3549 |
| 3550 | // next_read_epoch is the next read epoch in DTLS 1.3. It will become |
| 3551 | // current once a record is received from it. |
| 3552 | UniquePtr<DTLSReadEpoch> next_read_epoch; |
| 3553 |
| 3554 | // prev_read_epoch is the previous read epoch in DTLS 1.3. |
| 3555 | UniquePtr<DTLSPrevReadEpoch> prev_read_epoch; |
| 3556 |
| 3557 | // write_epoch is the current DTLS write epoch. Non-retransmit records will |
| 3558 | // generally use this epoch. |
| 3559 | // TODO(crbug.com/381113363): 0-RTT will be the exception, when implemented. |
| 3560 | DTLSWriteEpoch write_epoch; |
| 3561 |
| 3562 | // extra_write_epochs is the collection available write epochs. |
| 3563 | InplaceVector<UniquePtr<DTLSWriteEpoch>, DTLS_MAX_EXTRA_WRITE_EPOCHS> |
| 3564 | extra_write_epochs; |
| 3565 |
| 3566 | // incoming_messages is a ring buffer of incoming handshake messages that have |
| 3567 | // yet to be processed. The front of the ring buffer is message number |
| 3568 | // |handshake_read_seq|, at position |handshake_read_seq| % |
| 3569 | // |SSL_MAX_HANDSHAKE_FLIGHT|. |
| 3570 | UniquePtr<DTLSIncomingMessage> incoming_messages[SSL_MAX_HANDSHAKE_FLIGHT]; |
| 3571 |
| 3572 | // outgoing_messages is the queue of outgoing messages from the last handshake |
| 3573 | // flight. |
| 3574 | InplaceVector<DTLSOutgoingMessage, SSL_MAX_HANDSHAKE_FLIGHT> |
| 3575 | outgoing_messages; |
| 3576 |
| 3577 | // sent_records is a queue of records we sent, for processing ACKs. To save |
| 3578 | // memory in the steady state, the structure is stored on the heap and dropped |
| 3579 | // when empty. |
| 3580 | UniquePtr<MRUQueue<DTLSSentRecord, DTLS_MAX_ACK_BUFFER>> sent_records; |
| 3581 |
| 3582 | // records_to_ack is a queue of received records that we should ACK. This is |
| 3583 | // not stored on the heap because, in the steady state, DTLS 1.3 does not |
| 3584 | // necessarily empty this list. (We probably could drop records from here once |
| 3585 | // they are sufficiently old.) |
| 3586 | MRUQueue<DTLSRecordNumber, DTLS_MAX_ACK_BUFFER> records_to_ack; |
| 3587 |
| 3588 | // outgoing_written is the number of outgoing messages that have been |
| 3589 | // written. |
| 3590 | uint8_t outgoing_written = 0; |
| 3591 | // outgoing_offset is the number of bytes of the next outgoing message have |
| 3592 | // been written. |
| 3593 | uint32_t outgoing_offset = 0; |
| 3594 |
| 3595 | unsigned mtu = 0; // max DTLS packet size |
| 3596 |
| 3597 | // num_timeouts is the number of times the retransmit timer has fired since |
| 3598 | // the last time it was reset. |
| 3599 | unsigned num_timeouts = 0; |
| 3600 |
| 3601 | // retransmit_timer tracks when to schedule the next DTLS retransmit if we do |
| 3602 | // not hear from the peer. |
| 3603 | DTLSTimer retransmit_timer; |
| 3604 |
| 3605 | // ack_timer tracks when to send an ACK. |
| 3606 | DTLSTimer ack_timer; |
| 3607 |
| 3608 | // timeout_duration_ms is the timeout duration in milliseconds. |
| 3609 | uint32_t timeout_duration_ms = 0; |
| 3610 | }; |
| 3611 |
| 3612 | // An ALPSConfig is a pair of ALPN protocol and settings value to use with ALPS. |
| 3613 | struct ALPSConfig { |
| 3614 | Array<uint8_t> protocol; |
| 3615 | Array<uint8_t> settings; |
| 3616 | }; |
| 3617 |
| 3618 | // SSL_CONFIG contains configuration bits that can be shed after the handshake |
| 3619 | // completes. Objects of this type are not shared; they are unique to a |
| 3620 | // particular |SSL|. |
| 3621 | // |
| 3622 | // See SSL_shed_handshake_config() for more about the conditions under which |
| 3623 | // configuration can be shed. |
| 3624 | struct SSL_CONFIG { |
| 3625 | static constexpr bool kAllowUniquePtr = true; |
| 3626 |
| 3627 | explicit SSL_CONFIG(SSL *ssl_arg); |
| 3628 | ~SSL_CONFIG(); |
| 3629 |
| 3630 | // ssl is a non-owning pointer to the parent |SSL| object. |
| 3631 | SSL *const ssl = nullptr; |
| 3632 |
| 3633 | // conf_max_version is the maximum acceptable version configured by |
| 3634 | // |SSL_set_max_proto_version|. Note this version is not normalized in DTLS |
| 3635 | // and is further constrained by |SSL_OP_NO_*|. |
| 3636 | uint16_t conf_max_version = 0; |
| 3637 |
| 3638 | // conf_min_version is the minimum acceptable version configured by |
| 3639 | // |SSL_set_min_proto_version|. Note this version is not normalized in DTLS |
| 3640 | // and is further constrained by |SSL_OP_NO_*|. |
| 3641 | uint16_t conf_min_version = 0; |
| 3642 |
| 3643 | X509_VERIFY_PARAM *param = nullptr; |
| 3644 |
| 3645 | // crypto |
| 3646 | UniquePtr<SSLCipherPreferenceList> cipher_list; |
| 3647 |
| 3648 | // This is used to hold the local certificate used (i.e. the server |
| 3649 | // certificate for a server or the client certificate for a client). |
| 3650 | UniquePtr<CERT> cert; |
| 3651 |
| 3652 | int (*verify_callback)(int ok, |
| 3653 | X509_STORE_CTX *ctx) = |
| 3654 | nullptr; // fail if callback returns 0 |
| 3655 |
| 3656 | enum ssl_verify_result_t (*custom_verify_callback)( |
| 3657 | SSL *ssl, uint8_t *out_alert) = nullptr; |
| 3658 | // Server-only: psk_identity_hint is the identity hint to send in |
| 3659 | // PSK-based key exchanges. |
| 3660 | UniquePtr<char> psk_identity_hint; |
| 3661 |
| 3662 | unsigned (*psk_client_callback)(SSL *ssl, const char *hint, char *identity, |
| 3663 | unsigned max_identity_len, uint8_t *psk, |
| 3664 | unsigned max_psk_len) = nullptr; |
| 3665 | unsigned (*psk_server_callback)(SSL *ssl, const char *identity, uint8_t *psk, |
| 3666 | unsigned max_psk_len) = nullptr; |
| 3667 |
| 3668 | // for server side, keep the list of CA_dn we can use |
| 3669 | UniquePtr<STACK_OF(CRYPTO_BUFFER)> client_CA; |
| 3670 |
| 3671 | // cached_x509_client_CA is a cache of parsed versions of the elements of |
| 3672 | // |client_CA|. |
| 3673 | STACK_OF(X509_NAME) *cached_x509_client_CA = nullptr; |
| 3674 |
| 3675 | // For client side, keep the list of CA distinguished names we can use |
| 3676 | // for the Certificate Authorities extension. |
| 3677 | // TODO(bbe) having this separate from the client side (above) is mildly |
| 3678 | // silly, but OpenSSL has *_client_CA API's for this exposed, and for the |
| 3679 | // moment we are not crossing those streams. |
| 3680 | UniquePtr<STACK_OF(CRYPTO_BUFFER)> CA_names; |
| 3681 |
| 3682 | // Trust anchor IDs to be requested in the trust_anchors extension. |
| 3683 | std::optional<Array<uint8_t>> requested_trust_anchors; |
| 3684 |
| 3685 | Array<uint16_t> supported_group_list; // our list |
| 3686 |
| 3687 | // channel_id_private is the client's Channel ID private key, or null if |
| 3688 | // Channel ID should not be offered on this connection. |
| 3689 | UniquePtr<EVP_PKEY> channel_id_private; |
| 3690 |
| 3691 | // For a client, this contains the list of supported protocols in wire |
| 3692 | // format. |
| 3693 | Array<uint8_t> alpn_client_proto_list; |
| 3694 |
| 3695 | // alps_configs contains the list of supported protocols to use with ALPS, |
| 3696 | // along with their corresponding ALPS values. |
| 3697 | Vector<ALPSConfig> alps_configs; |
| 3698 |
| 3699 | // Contains the QUIC transport params that this endpoint will send. |
| 3700 | Array<uint8_t> quic_transport_params; |
| 3701 |
| 3702 | // Contains the context used to decide whether to accept early data in QUIC. |
| 3703 | Array<uint8_t> quic_early_data_context; |
| 3704 |
| 3705 | // verify_sigalgs, if not empty, is the set of signature algorithms |
| 3706 | // accepted from the peer in decreasing order of preference. |
| 3707 | Array<uint16_t> verify_sigalgs; |
| 3708 |
| 3709 | // srtp_profiles is the list of configured SRTP protection profiles for |
| 3710 | // DTLS-SRTP. |
| 3711 | UniquePtr<STACK_OF(SRTP_PROTECTION_PROFILE)> srtp_profiles; |
| 3712 |
| 3713 | // client_ech_config_list, if not empty, is a serialized ECHConfigList |
| 3714 | // structure for the client to use when negotiating ECH. |
| 3715 | Array<uint8_t> client_ech_config_list; |
| 3716 |
| 3717 | // compliance_policy limits the set of ciphers that can be selected when |
| 3718 | // negotiating a TLS 1.3 connection. |
| 3719 | enum ssl_compliance_policy_t compliance_policy = ssl_compliance_policy_none; |
| 3720 |
| 3721 | // verify_mode is a bitmask of |SSL_VERIFY_*| values. |
| 3722 | uint8_t verify_mode = SSL_VERIFY_NONE; |
| 3723 |
| 3724 | // ech_grease_enabled controls whether ECH GREASE may be sent in the |
| 3725 | // ClientHello. |
| 3726 | bool ech_grease_enabled : 1; |
| 3727 |
| 3728 | // Enable signed certificate time stamps. Currently client only. |
| 3729 | bool signed_cert_timestamps_enabled : 1; |
| 3730 |
| 3731 | // ocsp_stapling_enabled is only used by client connections and indicates |
| 3732 | // whether OCSP stapling will be requested. |
| 3733 | bool ocsp_stapling_enabled : 1; |
| 3734 |
| 3735 | // channel_id_enabled is copied from the |SSL_CTX|. For a server, it means |
| 3736 | // that we'll accept Channel IDs from clients. It is ignored on the client. |
| 3737 | bool channel_id_enabled : 1; |
| 3738 |
| 3739 | // If enforce_rsa_key_usage is true, the handshake will fail if the |
| 3740 | // keyUsage extension is present and incompatible with the TLS usage. |
| 3741 | // This field is not read until after certificate verification. |
| 3742 | bool enforce_rsa_key_usage : 1; |
| 3743 |
| 3744 | // retain_only_sha256_of_client_certs is true if we should compute the SHA256 |
| 3745 | // hash of the peer's certificate and then discard it to save memory and |
| 3746 | // session space. Only effective on the server side. |
| 3747 | bool retain_only_sha256_of_client_certs : 1; |
| 3748 |
| 3749 | // handoff indicates that a server should stop after receiving the |
| 3750 | // ClientHello and pause the handshake in such a way that |SSL_get_error| |
| 3751 | // returns |SSL_ERROR_HANDOFF|. This is copied in |SSL_new| from the |SSL_CTX| |
| 3752 | // element of the same name and may be cleared if the handoff is declined. |
| 3753 | bool handoff : 1; |
| 3754 |
| 3755 | // shed_handshake_config indicates that the handshake config (this object!) |
| 3756 | // should be freed after the handshake completes. |
| 3757 | bool shed_handshake_config : 1; |
| 3758 |
| 3759 | // jdk11_workaround is whether to disable TLS 1.3 for JDK 11 clients, as a |
| 3760 | // workaround for https://bugs.openjdk.java.net/browse/JDK-8211806. |
| 3761 | bool jdk11_workaround : 1; |
| 3762 |
| 3763 | // QUIC drafts up to and including 32 used a different TLS extension |
| 3764 | // codepoint to convey QUIC's transport parameters. |
| 3765 | bool quic_use_legacy_codepoint : 1; |
| 3766 |
| 3767 | // permute_extensions is whether to permute extensions when sending messages. |
| 3768 | bool permute_extensions : 1; |
| 3769 |
| 3770 | // aes_hw_override if set indicates we should override checking for aes |
| 3771 | // hardware support, and use the value in aes_hw_override_value instead. |
| 3772 | bool aes_hw_override : 1; |
| 3773 |
| 3774 | // aes_hw_override_value is used for testing to indicate the support or lack |
| 3775 | // of support for AES hw. The value is only considered if |aes_hw_override| is |
| 3776 | // true. |
| 3777 | bool aes_hw_override_value : 1; |
| 3778 |
| 3779 | // alps_use_new_codepoint if set indicates we use new ALPS extension codepoint |
| 3780 | // to negotiate and convey application settings. |
| 3781 | bool alps_use_new_codepoint : 1; |
| 3782 | }; |
| 3783 |
| 3784 | // From RFC 8446, used in determining PSK modes. |
| 3785 | #define SSL_PSK_DHE_KE 0x1 |
| 3786 |
| 3787 | // kMaxEarlyDataAccepted is the advertised number of plaintext bytes of early |
| 3788 | // data that will be accepted. This value should be slightly below |
| 3789 | // kMaxEarlyDataSkipped in tls_record.c, which is measured in ciphertext. |
| 3790 | static const size_t kMaxEarlyDataAccepted = 14336; |
| 3791 |
| 3792 | UniquePtr<CERT> ssl_cert_dup(CERT *cert); |
| 3793 | bool ssl_set_cert(CERT *cert, UniquePtr<CRYPTO_BUFFER> buffer); |
| 3794 | bool ssl_is_key_type_supported(int key_type); |
| 3795 | // ssl_compare_public_and_private_key returns true if |pubkey| is the public |
| 3796 | // counterpart to |privkey|. Otherwise it returns false and pushes a helpful |
| 3797 | // message on the error queue. |
| 3798 | bool ssl_compare_public_and_private_key(const EVP_PKEY *pubkey, |
| 3799 | const EVP_PKEY *privkey); |
| 3800 | bool ssl_get_new_session(SSL_HANDSHAKE *hs); |
| 3801 |
| 3802 | // ssl_encrypt_ticket encrypt a ticket for |session| and writes the result to |
| 3803 | // |out|. It returns true on success and false on error. If, on success, nothing |
| 3804 | // was written to |out|, the caller should skip sending a ticket. |
| 3805 | bool ssl_encrypt_ticket(SSL_HANDSHAKE *hs, CBB *out, |
| 3806 | const SSL_SESSION *session); |
| 3807 |
| 3808 | bool ssl_ctx_rotate_ticket_encryption_key(SSL_CTX *ctx); |
| 3809 |
| 3810 | // ssl_session_new returns a newly-allocated blank |SSL_SESSION| or nullptr on |
| 3811 | // error. |
| 3812 | UniquePtr<SSL_SESSION> ssl_session_new(const SSL_X509_METHOD *x509_method); |
| 3813 |
| 3814 | // ssl_hash_session_id returns a hash of |session_id|, suitable for a hash table |
| 3815 | // keyed on session IDs. |
| 3816 | uint32_t ssl_hash_session_id(Span<const uint8_t> session_id); |
| 3817 |
| 3818 | // SSL_SESSION_parse parses an |SSL_SESSION| from |cbs| and advances |cbs| over |
| 3819 | // the parsed data. |
| 3820 | OPENSSL_EXPORT UniquePtr<SSL_SESSION> SSL_SESSION_parse( |
| 3821 | CBS *cbs, const SSL_X509_METHOD *x509_method, CRYPTO_BUFFER_POOL *pool); |
| 3822 |
| 3823 | // ssl_session_serialize writes |in| to |cbb| as if it were serialising a |
| 3824 | // session for Session-ID resumption. It returns true on success and false on |
| 3825 | // error. |
| 3826 | OPENSSL_EXPORT bool ssl_session_serialize(const SSL_SESSION *in, CBB *cbb); |
| 3827 |
| 3828 | enum class SSLSessionType { |
| 3829 | // The session is not resumable. |
| 3830 | kNotResumable, |
| 3831 | // The session uses a TLS 1.2 session ID. |
| 3832 | kID, |
| 3833 | // The session uses a TLS 1.2 ticket. |
| 3834 | kTicket, |
| 3835 | // The session uses a TLS 1.3 pre-shared key. |
| 3836 | kPreSharedKey, |
| 3837 | }; |
| 3838 |
| 3839 | // ssl_session_get_type returns the type of |session|. |
| 3840 | SSLSessionType ssl_session_get_type(const SSL_SESSION *session); |
| 3841 |
| 3842 | // ssl_session_is_context_valid returns whether |session|'s session ID context |
| 3843 | // matches the one set on |hs|. |
| 3844 | bool ssl_session_is_context_valid(const SSL_HANDSHAKE *hs, |
| 3845 | const SSL_SESSION *session); |
| 3846 |
| 3847 | // ssl_session_is_time_valid returns true if |session| is still valid and false |
| 3848 | // if it has expired. |
| 3849 | bool ssl_session_is_time_valid(const SSL *ssl, const SSL_SESSION *session); |
| 3850 |
| 3851 | // ssl_session_is_resumable returns whether |session| is resumable for |hs|. |
| 3852 | bool ssl_session_is_resumable(const SSL_HANDSHAKE *hs, |
| 3853 | const SSL_SESSION *session); |
| 3854 |
| 3855 | // ssl_session_protocol_version returns the protocol version associated with |
| 3856 | // |session|. Note that despite the name, this is not the same as |
| 3857 | // |SSL_SESSION_get_protocol_version|. The latter is based on upstream's name. |
| 3858 | uint16_t ssl_session_protocol_version(const SSL_SESSION *session); |
| 3859 |
| 3860 | // ssl_session_get_digest returns the digest used in |session|. |
| 3861 | const EVP_MD *ssl_session_get_digest(const SSL_SESSION *session); |
| 3862 |
| 3863 | void ssl_set_session(SSL *ssl, SSL_SESSION *session); |
| 3864 |
| 3865 | // ssl_get_prev_session looks up the previous session based on |client_hello|. |
| 3866 | // On success, it sets |*out_session| to the session or nullptr if none was |
| 3867 | // found. If the session could not be looked up synchronously, it returns |
| 3868 | // |ssl_hs_pending_session| and should be called again. If a ticket could not be |
| 3869 | // decrypted immediately it returns |ssl_hs_pending_ticket| and should also |
| 3870 | // be called again. Otherwise, it returns |ssl_hs_error|. |
| 3871 | enum ssl_hs_wait_t ssl_get_prev_session(SSL_HANDSHAKE *hs, |
| 3872 | UniquePtr<SSL_SESSION> *out_session, |
| 3873 | bool *out_tickets_supported, |
| 3874 | bool *out_renew_ticket, |
| 3875 | const SSL_CLIENT_HELLO *client_hello); |
| 3876 |
| 3877 | // The following flags determine which parts of the session are duplicated. |
| 3878 | #define SSL_SESSION_DUP_AUTH_ONLY 0x0 |
| 3879 | #define SSL_SESSION_INCLUDE_TICKET 0x1 |
| 3880 | #define SSL_SESSION_INCLUDE_NONAUTH 0x2 |
| 3881 | #define SSL_SESSION_DUP_ALL \ |
| 3882 | (SSL_SESSION_INCLUDE_TICKET | SSL_SESSION_INCLUDE_NONAUTH) |
| 3883 |
| 3884 | // SSL_SESSION_dup returns a newly-allocated |SSL_SESSION| with a copy of the |
| 3885 | // fields in |session| or nullptr on error. The new session is non-resumable and |
| 3886 | // must be explicitly marked resumable once it has been filled in. |
| 3887 | OPENSSL_EXPORT UniquePtr<SSL_SESSION> SSL_SESSION_dup(SSL_SESSION *session, |
| 3888 | int dup_flags); |
| 3889 |
| 3890 | // ssl_session_rebase_time updates |session|'s start time to the current time, |
| 3891 | // adjusting the timeout so the expiration time is unchanged. |
| 3892 | void ssl_session_rebase_time(SSL *ssl, SSL_SESSION *session); |
| 3893 |
| 3894 | // ssl_session_renew_timeout calls |ssl_session_rebase_time| and renews |
| 3895 | // |session|'s timeout to |timeout| (measured from the current time). The |
| 3896 | // renewal is clamped to the session's auth_timeout. |
| 3897 | void ssl_session_renew_timeout(SSL *ssl, SSL_SESSION *session, |
| 3898 | uint32_t timeout); |
| 3899 |
| 3900 | void ssl_update_cache(SSL *ssl); |
| 3901 |
| 3902 | void ssl_send_alert(SSL *ssl, int level, int desc); |
| 3903 | int ssl_send_alert_impl(SSL *ssl, int level, int desc); |
| 3904 | bool tls_get_message(const SSL *ssl, SSLMessage *out); |
| 3905 | ssl_open_record_t tls_open_handshake(SSL *ssl, size_t *out_consumed, |
| 3906 | uint8_t *out_alert, Span<uint8_t> in); |
| 3907 | void tls_next_message(SSL *ssl); |
| 3908 |
| 3909 | int tls_dispatch_alert(SSL *ssl); |
| 3910 | ssl_open_record_t tls_open_app_data(SSL *ssl, Span<uint8_t> *out, |
| 3911 | size_t *out_consumed, uint8_t *out_alert, |
| 3912 | Span<uint8_t> in); |
| 3913 | ssl_open_record_t tls_open_change_cipher_spec(SSL *ssl, size_t *out_consumed, |
| 3914 | uint8_t *out_alert, |
| 3915 | Span<uint8_t> in); |
| 3916 | int tls_write_app_data(SSL *ssl, bool *out_needs_handshake, |
| 3917 | size_t *out_bytes_written, Span<const uint8_t> in); |
| 3918 |
| 3919 | bool tls_new(SSL *ssl); |
| 3920 | void tls_free(SSL *ssl); |
| 3921 |
| 3922 | bool tls_init_message(const SSL *ssl, CBB *cbb, CBB *body, uint8_t type); |
| 3923 | bool tls_finish_message(const SSL *ssl, CBB *cbb, Array<uint8_t> *out_msg); |
| 3924 | bool tls_add_message(SSL *ssl, Array<uint8_t> msg); |
| 3925 | bool tls_add_change_cipher_spec(SSL *ssl); |
| 3926 | int tls_flush(SSL *ssl); |
| 3927 |
| 3928 | bool dtls1_init_message(const SSL *ssl, CBB *cbb, CBB *body, uint8_t type); |
| 3929 | bool dtls1_finish_message(const SSL *ssl, CBB *cbb, Array<uint8_t> *out_msg); |
| 3930 | bool dtls1_add_message(SSL *ssl, Array<uint8_t> msg); |
| 3931 | bool dtls1_add_change_cipher_spec(SSL *ssl); |
| 3932 | void dtls1_finish_flight(SSL *ssl); |
| 3933 | void dtls1_schedule_ack(SSL *ssl); |
| 3934 | int dtls1_flush(SSL *ssl); |
| 3935 |
| 3936 | // ssl_add_message_cbb finishes the handshake message in |cbb| and adds it to |
| 3937 | // the pending flight. It returns true on success and false on error. |
| 3938 | bool ssl_add_message_cbb(SSL *ssl, CBB *cbb); |
| 3939 |
| 3940 | // ssl_hash_message incorporates |msg| into the handshake hash. It returns true |
| 3941 | // on success and false on allocation failure. |
| 3942 | bool ssl_hash_message(SSL_HANDSHAKE *hs, const SSLMessage &msg); |
| 3943 |
| 3944 | ssl_open_record_t dtls1_process_ack(SSL *ssl, uint8_t *out_alert, |
| 3945 | DTLSRecordNumber ack_record_number, |
| 3946 | Span<const uint8_t> data); |
| 3947 | ssl_open_record_t dtls1_open_app_data(SSL *ssl, Span<uint8_t> *out, |
| 3948 | size_t *out_consumed, uint8_t *out_alert, |
| 3949 | Span<uint8_t> in); |
| 3950 | ssl_open_record_t dtls1_open_change_cipher_spec(SSL *ssl, size_t *out_consumed, |
| 3951 | uint8_t *out_alert, |
| 3952 | Span<uint8_t> in); |
| 3953 |
| 3954 | int dtls1_write_app_data(SSL *ssl, bool *out_needs_handshake, |
| 3955 | size_t *out_bytes_written, Span<const uint8_t> in); |
| 3956 |
| 3957 | // dtls1_write_record sends a record. It returns one on success and <= 0 on |
| 3958 | // error. |
| 3959 | int dtls1_write_record(SSL *ssl, int type, Span<const uint8_t> in, |
| 3960 | uint16_t epoch); |
| 3961 |
| 3962 | bool dtls1_parse_fragment(CBS *cbs, struct hm_header_st *out_hdr, |
| 3963 | CBS *out_body); |
| 3964 |
| 3965 | // DTLS1_MTU_TIMEOUTS is the maximum number of retransmit timeouts to expire |
| 3966 | // before starting to decrease the MTU. |
| 3967 | #define DTLS1_MTU_TIMEOUTS 2 |
| 3968 |
| 3969 | // DTLS1_MAX_TIMEOUTS is the maximum number of retransmit timeouts to expire |
| 3970 | // before failing the DTLS handshake. |
| 3971 | #define DTLS1_MAX_TIMEOUTS 12 |
| 3972 |
| 3973 | void dtls1_stop_timer(SSL *ssl); |
| 3974 |
| 3975 | unsigned int dtls1_min_mtu(void); |
| 3976 |
| 3977 | bool dtls1_new(SSL *ssl); |
| 3978 | void dtls1_free(SSL *ssl); |
| 3979 |
| 3980 | bool dtls1_process_handshake_fragments(SSL *ssl, uint8_t *out_alert, |
| 3981 | DTLSRecordNumber record_number, |
| 3982 | Span<const uint8_t> record); |
| 3983 | bool dtls1_get_message(const SSL *ssl, SSLMessage *out); |
| 3984 | ssl_open_record_t dtls1_open_handshake(SSL *ssl, size_t *out_consumed, |
| 3985 | uint8_t *out_alert, Span<uint8_t> in); |
| 3986 | void dtls1_next_message(SSL *ssl); |
| 3987 | int dtls1_dispatch_alert(SSL *ssl); |
| 3988 |
| 3989 | // tls1_configure_aead configures either the read or write direction AEAD (as |
| 3990 | // determined by |direction|) using the keys generated by the TLS KDF. The |
| 3991 | // |key_block_cache| argument is used to store the generated key block, if |
| 3992 | // empty. Otherwise it's assumed that the key block is already contained within |
| 3993 | // it. It returns true on success or false on error. |
| 3994 | bool tls1_configure_aead(SSL *ssl, evp_aead_direction_t direction, |
| 3995 | Array<uint8_t> *key_block_cache, |
| 3996 | const SSL_SESSION *session, |
| 3997 | Span<const uint8_t> iv_override); |
| 3998 |
| 3999 | bool tls1_change_cipher_state(SSL_HANDSHAKE *hs, |
| 4000 | evp_aead_direction_t direction); |
| 4001 |
| 4002 | // tls1_generate_master_secret computes the master secret from |premaster| and |
| 4003 | // writes it to |out|. |out| must have size |SSL3_MASTER_SECRET_SIZE|. |
| 4004 | bool tls1_generate_master_secret(SSL_HANDSHAKE *hs, Span<uint8_t> out, |
| 4005 | Span<const uint8_t> premaster); |
| 4006 |
| 4007 | // tls1_get_grouplist returns the locally-configured group preference list. |
| 4008 | Span<const uint16_t> tls1_get_grouplist(const SSL_HANDSHAKE *ssl); |
| 4009 |
| 4010 | // tls1_check_group_id returns whether |group_id| is consistent with locally- |
| 4011 | // configured group preferences. |
| 4012 | bool tls1_check_group_id(const SSL_HANDSHAKE *ssl, uint16_t group_id); |
| 4013 |
| 4014 | // tls1_get_shared_group sets |*out_group_id| to the first preferred shared |
| 4015 | // group between client and server preferences and returns true. If none may be |
| 4016 | // found, it returns false. |
| 4017 | bool tls1_get_shared_group(SSL_HANDSHAKE *hs, uint16_t *out_group_id); |
| 4018 |
| 4019 | // ssl_add_clienthello_tlsext writes ClientHello extensions to |out| for |type|. |
| 4020 | // It returns true on success and false on failure. The |header_len| argument is |
| 4021 | // the length of the ClientHello written so far and is used to compute the |
| 4022 | // padding length. (It does not include the record header or handshake headers.) |
| 4023 | // |
| 4024 | // If |type| is |ssl_client_hello_inner|, this function also writes the |
| 4025 | // compressed extensions to |out_encoded|. Otherwise, |out_encoded| should be |
| 4026 | // nullptr. |
| 4027 | // |
| 4028 | // On success, the function sets |*out_needs_psk_binder| to whether the last |
| 4029 | // ClientHello extension was the pre_shared_key extension and needs a PSK binder |
| 4030 | // filled in. The caller should then update |out| and, if applicable, |
| 4031 | // |out_encoded| with the binder after completing the whole message. |
| 4032 | bool ssl_add_clienthello_tlsext(SSL_HANDSHAKE *hs, CBB *out, CBB *out_encoded, |
| 4033 | bool *out_needs_psk_binder, |
| 4034 | ssl_client_hello_type_t type, |
| 4035 | size_t header_len); |
| 4036 |
| 4037 | bool ssl_add_serverhello_tlsext(SSL_HANDSHAKE *hs, CBB *out); |
| 4038 | bool ssl_parse_clienthello_tlsext(SSL_HANDSHAKE *hs, |
| 4039 | const SSL_CLIENT_HELLO *client_hello); |
| 4040 | bool ssl_parse_serverhello_tlsext(SSL_HANDSHAKE *hs, const CBS *extensions); |
| 4041 |
| 4042 | #define tlsext_tick_md EVP_sha256 |
| 4043 |
| 4044 | // ssl_process_ticket processes a session ticket from the client. It returns |
| 4045 | // one of: |
| 4046 | // |ssl_ticket_aead_success|: |*out_session| is set to the parsed session and |
| 4047 | // |*out_renew_ticket| is set to whether the ticket should be renewed. |
| 4048 | // |ssl_ticket_aead_ignore_ticket|: |*out_renew_ticket| is set to whether a |
| 4049 | // fresh ticket should be sent, but the given ticket cannot be used. |
| 4050 | // |ssl_ticket_aead_retry|: the ticket could not be immediately decrypted. |
| 4051 | // Retry later. |
| 4052 | // |ssl_ticket_aead_error|: an error occured that is fatal to the connection. |
| 4053 | enum ssl_ticket_aead_result_t ssl_process_ticket( |
| 4054 | SSL_HANDSHAKE *hs, UniquePtr<SSL_SESSION> *out_session, |
| 4055 | bool *out_renew_ticket, Span<const uint8_t> ticket, |
| 4056 | Span<const uint8_t> session_id); |
| 4057 |
| 4058 | // tls1_verify_channel_id processes |msg| as a Channel ID message, and verifies |
| 4059 | // the signature. If the key is valid, it saves the Channel ID and returns true. |
| 4060 | // Otherwise, it returns false. |
| 4061 | bool tls1_verify_channel_id(SSL_HANDSHAKE *hs, const SSLMessage &msg); |
| 4062 |
| 4063 | // tls1_write_channel_id generates a Channel ID message and puts the output in |
| 4064 | // |cbb|. |ssl->channel_id_private| must already be set before calling. This |
| 4065 | // function returns true on success and false on error. |
| 4066 | bool tls1_write_channel_id(SSL_HANDSHAKE *hs, CBB *cbb); |
| 4067 |
| 4068 | // tls1_channel_id_hash computes the hash to be signed by Channel ID and writes |
| 4069 | // it to |out|, which must contain at least |EVP_MAX_MD_SIZE| bytes. It returns |
| 4070 | // true on success and false on failure. |
| 4071 | bool tls1_channel_id_hash(SSL_HANDSHAKE *hs, uint8_t *out, size_t *out_len); |
| 4072 |
| 4073 | // tls1_record_handshake_hashes_for_channel_id records the current handshake |
| 4074 | // hashes in |hs->new_session| so that Channel ID resumptions can sign that |
| 4075 | // data. |
| 4076 | bool tls1_record_handshake_hashes_for_channel_id(SSL_HANDSHAKE *hs); |
| 4077 |
| 4078 | // ssl_can_write returns whether |ssl| is allowed to write. |
| 4079 | bool ssl_can_write(const SSL *ssl); |
| 4080 |
| 4081 | // ssl_can_read returns wheter |ssl| is allowed to read. |
| 4082 | bool ssl_can_read(const SSL *ssl); |
| 4083 |
| 4084 | OPENSSL_timeval ssl_ctx_get_current_time(const SSL_CTX *ctx); |
| 4085 |
| 4086 | // ssl_reset_error_state resets state for |SSL_get_error|. |
| 4087 | void ssl_reset_error_state(SSL *ssl); |
| 4088 |
| 4089 | // ssl_set_read_error sets |ssl|'s read half into an error state, saving the |
| 4090 | // current state of the error queue. |
| 4091 | void ssl_set_read_error(SSL *ssl); |
| 4092 |
| 4093 | BSSL_NAMESPACE_END |
| 4094 |
| 4095 |
| 4096 | // Opaque C types. |
| 4097 | // |
| 4098 | // The following types are exported to C code as public typedefs, so they must |
| 4099 | // be defined outside of the namespace. |
| 4100 |
| 4101 | // ssl_method_st backs the public |SSL_METHOD| type. It is a compatibility |
| 4102 | // structure to support the legacy version-locked methods. |
| 4103 | struct ssl_method_st { |
| 4104 | // version, if non-zero, is the only protocol version acceptable to an |
| 4105 | // SSL_CTX initialized from this method. |
| 4106 | uint16_t version; |
| 4107 | // method is the underlying SSL_PROTOCOL_METHOD that initializes the |
| 4108 | // SSL_CTX. |
| 4109 | const bssl::SSL_PROTOCOL_METHOD *method; |
| 4110 | // x509_method contains pointers to functions that might deal with |X509| |
| 4111 | // compatibility, or might be a no-op, depending on the application. |
| 4112 | const bssl::SSL_X509_METHOD *x509_method; |
| 4113 | }; |
| 4114 |
| 4115 | struct ssl_ctx_st : public bssl::RefCounted<ssl_ctx_st> { |
| 4116 | explicit ssl_ctx_st(const SSL_METHOD *ssl_method); |
| 4117 | ssl_ctx_st(const ssl_ctx_st &) = delete; |
| 4118 | ssl_ctx_st &operator=(const ssl_ctx_st &) = delete; |
| 4119 |
| 4120 | const bssl::SSL_PROTOCOL_METHOD *method = nullptr; |
| 4121 | const bssl::SSL_X509_METHOD *x509_method = nullptr; |
| 4122 |
| 4123 | // lock is used to protect various operations on this object. |
| 4124 | CRYPTO_MUTEX lock; |
| 4125 |
| 4126 | // conf_max_version is the maximum acceptable protocol version configured by |
| 4127 | // |SSL_CTX_set_max_proto_version|. Note this version is normalized in DTLS |
| 4128 | // and is further constrainted by |SSL_OP_NO_*|. |
| 4129 | uint16_t conf_max_version = 0; |
| 4130 |
| 4131 | // conf_min_version is the minimum acceptable protocol version configured by |
| 4132 | // |SSL_CTX_set_min_proto_version|. Note this version is normalized in DTLS |
| 4133 | // and is further constrainted by |SSL_OP_NO_*|. |
| 4134 | uint16_t conf_min_version = 0; |
| 4135 |
| 4136 | // num_tickets is the number of tickets to send immediately after the TLS 1.3 |
| 4137 | // handshake. TLS 1.3 recommends single-use tickets so, by default, issue two |
| 4138 | /// in case the client makes several connections before getting a renewal. |
| 4139 | uint8_t num_tickets = 2; |
| 4140 |
| 4141 | // quic_method is the method table corresponding to the QUIC hooks. |
| 4142 | const SSL_QUIC_METHOD *quic_method = nullptr; |
| 4143 |
| 4144 | bssl::UniquePtr<bssl::SSLCipherPreferenceList> cipher_list; |
| 4145 |
| 4146 | X509_STORE *cert_store = nullptr; |
| 4147 | LHASH_OF(SSL_SESSION) *sessions = nullptr; |
| 4148 | // Most session-ids that will be cached, default is |
| 4149 | // SSL_SESSION_CACHE_MAX_SIZE_DEFAULT. 0 is unlimited. |
| 4150 | unsigned long session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT; |
| 4151 | SSL_SESSION *session_cache_head = nullptr; |
| 4152 | SSL_SESSION *session_cache_tail = nullptr; |
| 4153 |
| 4154 | // handshakes_since_cache_flush is the number of successful handshakes since |
| 4155 | // the last cache flush. |
| 4156 | int handshakes_since_cache_flush = 0; |
| 4157 |
| 4158 | // This can have one of 2 values, ored together, |
| 4159 | // SSL_SESS_CACHE_CLIENT, |
| 4160 | // SSL_SESS_CACHE_SERVER, |
| 4161 | // Default is SSL_SESSION_CACHE_SERVER, which means only |
| 4162 | // SSL_accept which cache SSL_SESSIONS. |
| 4163 | int session_cache_mode = SSL_SESS_CACHE_SERVER; |
| 4164 |
| 4165 | // session_timeout is the default lifetime for new sessions in TLS 1.2 and |
| 4166 | // earlier, in seconds. |
| 4167 | uint32_t session_timeout = SSL_DEFAULT_SESSION_TIMEOUT; |
| 4168 |
| 4169 | // session_psk_dhe_timeout is the default lifetime for new sessions in TLS |
| 4170 | // 1.3, in seconds. |
| 4171 | uint32_t session_psk_dhe_timeout = SSL_DEFAULT_SESSION_PSK_DHE_TIMEOUT; |
| 4172 |
| 4173 | // If this callback is not null, it will be called each time a session id is |
| 4174 | // added to the cache. If this function returns 1, it means that the |
| 4175 | // callback will do a SSL_SESSION_free() when it has finished using it. |
| 4176 | // Otherwise, on 0, it means the callback has finished with it. If |
| 4177 | // remove_session_cb is not null, it will be called when a session-id is |
| 4178 | // removed from the cache. After the call, OpenSSL will SSL_SESSION_free() |
| 4179 | // it. |
| 4180 | int (*new_session_cb)(SSL *ssl, SSL_SESSION *sess) = nullptr; |
| 4181 | void (*remove_session_cb)(SSL_CTX *ctx, SSL_SESSION *sess) = nullptr; |
| 4182 | SSL_SESSION *(*get_session_cb)(SSL *ssl, const uint8_t *data, int len, |
| 4183 | int *copy) = nullptr; |
| 4184 |
| 4185 | // if defined, these override the X509_verify_cert() calls |
| 4186 | int (*app_verify_callback)(X509_STORE_CTX *store_ctx, void *arg) = nullptr; |
| 4187 | void *app_verify_arg = nullptr; |
| 4188 |
| 4189 | ssl_verify_result_t (*custom_verify_callback)(SSL *ssl, |
| 4190 | uint8_t *out_alert) = nullptr; |
| 4191 |
| 4192 | // Default password callback. |
| 4193 | pem_password_cb *default_passwd_callback = nullptr; |
| 4194 |
| 4195 | // Default password callback user data. |
| 4196 | void *default_passwd_callback_userdata = nullptr; |
| 4197 |
| 4198 | // get client cert callback |
| 4199 | int (*client_cert_cb)(SSL *ssl, X509 **out_x509, |
| 4200 | EVP_PKEY **out_pkey) = nullptr; |
| 4201 |
| 4202 | CRYPTO_EX_DATA ex_data; |
| 4203 |
| 4204 | // Default values used when no per-SSL value is defined follow |
| 4205 |
| 4206 | void (*info_callback)(const SSL *ssl, int type, int value) = nullptr; |
| 4207 |
| 4208 | // what we put in client cert requests |
| 4209 | bssl::UniquePtr<STACK_OF(CRYPTO_BUFFER)> client_CA; |
| 4210 |
| 4211 | // cached_x509_client_CA is a cache of parsed versions of the elements of |
| 4212 | // |client_CA|. |
| 4213 | STACK_OF(X509_NAME) *cached_x509_client_CA = nullptr; |
| 4214 |
| 4215 | // What we put in client hello in the CA extension. |
| 4216 | bssl::UniquePtr<STACK_OF(CRYPTO_BUFFER)> CA_names; |
| 4217 |
| 4218 | // What we request in the trust_anchors extension. |
| 4219 | std::optional<bssl::Array<uint8_t>> requested_trust_anchors; |
| 4220 |
| 4221 | // Default values to use in SSL structures follow (these are copied by |
| 4222 | // SSL_new) |
| 4223 |
| 4224 | uint32_t options = 0; |
| 4225 | // Disable the auto-chaining feature by default. wpa_supplicant relies on this |
| 4226 | // feature, but require callers opt into it. |
| 4227 | uint32_t mode = SSL_MODE_NO_AUTO_CHAIN; |
| 4228 | uint32_t max_cert_list = SSL_MAX_CERT_LIST_DEFAULT; |
| 4229 |
| 4230 | bssl::UniquePtr<bssl::CERT> cert; |
| 4231 |
| 4232 | // callback that allows applications to peek at protocol messages |
| 4233 | void (*msg_callback)(int is_write, int version, int content_type, |
| 4234 | const void *buf, size_t len, SSL *ssl, |
| 4235 | void *arg) = nullptr; |
| 4236 | void *msg_callback_arg = nullptr; |
| 4237 |
| 4238 | int verify_mode = SSL_VERIFY_NONE; |
| 4239 | int (*default_verify_callback)(int ok, X509_STORE_CTX *ctx) = |
| 4240 | nullptr; // called 'verify_callback' in the SSL |
| 4241 |
| 4242 | X509_VERIFY_PARAM *param = nullptr; |
| 4243 |
| 4244 | // select_certificate_cb is called before most ClientHello processing and |
| 4245 | // before the decision whether to resume a session is made. See |
| 4246 | // |ssl_select_cert_result_t| for details of the return values. |
| 4247 | ssl_select_cert_result_t (*select_certificate_cb)(const SSL_CLIENT_HELLO *) = |
| 4248 | nullptr; |
| 4249 |
| 4250 | // dos_protection_cb is called once the resumption decision for a ClientHello |
| 4251 | // has been made. It returns one to continue the handshake or zero to |
| 4252 | // abort. |
| 4253 | int (*dos_protection_cb)(const SSL_CLIENT_HELLO *) = nullptr; |
| 4254 |
| 4255 | // Controls whether to verify certificates when resuming connections. They |
| 4256 | // were already verified when the connection was first made, so the default is |
| 4257 | // false. For now, this is only respected on clients, not servers. |
| 4258 | bool reverify_on_resume = false; |
| 4259 |
| 4260 | // Maximum amount of data to send in one fragment. actual record size can be |
| 4261 | // more than this due to padding and MAC overheads. |
| 4262 | uint16_t max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH; |
| 4263 |
| 4264 | // TLS extensions servername callback |
| 4265 | int (*servername_callback)(SSL *, int *, void *) = nullptr; |
| 4266 | void *servername_arg = nullptr; |
| 4267 |
| 4268 | // RFC 4507 session ticket keys. |ticket_key_current| may be NULL before the |
| 4269 | // first handshake and |ticket_key_prev| may be NULL at any time. |
| 4270 | // Automatically generated ticket keys are rotated as needed at handshake |
| 4271 | // time. Hence, all access must be synchronized through |lock|. |
| 4272 | bssl::UniquePtr<bssl::TicketKey> ticket_key_current; |
| 4273 | bssl::UniquePtr<bssl::TicketKey> ticket_key_prev; |
| 4274 |
| 4275 | // Callback to support customisation of ticket key setting |
| 4276 | int (*ticket_key_cb)(SSL *ssl, uint8_t *name, uint8_t *iv, |
| 4277 | EVP_CIPHER_CTX *ectx, HMAC_CTX *hctx, int enc) = nullptr; |
| 4278 |
| 4279 | // Server-only: psk_identity_hint is the default identity hint to send in |
| 4280 | // PSK-based key exchanges. |
| 4281 | bssl::UniquePtr<char> psk_identity_hint; |
| 4282 |
| 4283 | unsigned (*psk_client_callback)(SSL *ssl, const char *hint, char *identity, |
| 4284 | unsigned max_identity_len, uint8_t *psk, |
| 4285 | unsigned max_psk_len) = nullptr; |
| 4286 | unsigned (*psk_server_callback)(SSL *ssl, const char *identity, uint8_t *psk, |
| 4287 | unsigned max_psk_len) = nullptr; |
| 4288 |
| 4289 |
| 4290 | // Next protocol negotiation information |
| 4291 | // (for experimental NPN extension). |
| 4292 |
| 4293 | // For a server, this contains a callback function by which the set of |
| 4294 | // advertised protocols can be provided. |
| 4295 | int (*next_protos_advertised_cb)(SSL *ssl, const uint8_t **out, |
| 4296 | unsigned *out_len, void *arg) = nullptr; |
| 4297 | void *next_protos_advertised_cb_arg = nullptr; |
| 4298 | // For a client, this contains a callback function that selects the |
| 4299 | // next protocol from the list provided by the server. |
| 4300 | int (*next_proto_select_cb)(SSL *ssl, uint8_t **out, uint8_t *out_len, |
| 4301 | const uint8_t *in, unsigned in_len, |
| 4302 | void *arg) = nullptr; |
| 4303 | void *next_proto_select_cb_arg = nullptr; |
| 4304 |
| 4305 | // ALPN information |
| 4306 | // (we are in the process of transitioning from NPN to ALPN.) |
| 4307 |
| 4308 | // For a server, this contains a callback function that allows the |
| 4309 | // server to select the protocol for the connection. |
| 4310 | // out: on successful return, this must point to the raw protocol |
| 4311 | // name (without the length prefix). |
| 4312 | // outlen: on successful return, this contains the length of |*out|. |
| 4313 | // in: points to the client's list of supported protocols in |
| 4314 | // wire-format. |
| 4315 | // inlen: the length of |in|. |
| 4316 | int (*alpn_select_cb)(SSL *ssl, const uint8_t **out, uint8_t *out_len, |
| 4317 | const uint8_t *in, unsigned in_len, |
| 4318 | void *arg) = nullptr; |
| 4319 | void *alpn_select_cb_arg = nullptr; |
| 4320 |
| 4321 | // For a client, this contains the list of supported protocols in wire |
| 4322 | // format. |
| 4323 | bssl::Array<uint8_t> alpn_client_proto_list; |
| 4324 |
| 4325 | // SRTP profiles we are willing to do from RFC 5764 |
| 4326 | bssl::UniquePtr<STACK_OF(SRTP_PROTECTION_PROFILE)> srtp_profiles; |
| 4327 |
| 4328 | // Defined compression algorithms for certificates. |
| 4329 | bssl::Vector<bssl::CertCompressionAlg> cert_compression_algs; |
| 4330 |
| 4331 | // Supported group values inherited by SSL structure |
| 4332 | bssl::Array<uint16_t> supported_group_list; |
| 4333 |
| 4334 | // channel_id_private is the client's Channel ID private key, or null if |
| 4335 | // Channel ID should not be offered on this connection. |
| 4336 | bssl::UniquePtr<EVP_PKEY> channel_id_private; |
| 4337 |
| 4338 | // ech_keys contains the server's list of ECHConfig values and associated |
| 4339 | // private keys. This list may be swapped out at any time, so all access must |
| 4340 | // be synchronized through |lock|. |
| 4341 | bssl::UniquePtr<SSL_ECH_KEYS> ech_keys; |
| 4342 |
| 4343 | // keylog_callback, if not NULL, is the key logging callback. See |
| 4344 | // |SSL_CTX_set_keylog_callback|. |
| 4345 | void (*keylog_callback)(const SSL *ssl, const char *line) = nullptr; |
| 4346 |
| 4347 | // current_time_cb, if not NULL, is the function to use to get the current |
| 4348 | // time. It sets |*out_clock| to the current time. The |ssl| argument is |
| 4349 | // always NULL. See |SSL_CTX_set_current_time_cb|. |
| 4350 | void (*current_time_cb)(const SSL *ssl, struct timeval *out_clock) = nullptr; |
| 4351 |
| 4352 | // pool is used for all |CRYPTO_BUFFER|s in case we wish to share certificate |
| 4353 | // memory. |
| 4354 | CRYPTO_BUFFER_POOL *pool = nullptr; |
| 4355 |
| 4356 | // ticket_aead_method contains function pointers for opening and sealing |
| 4357 | // session tickets. |
| 4358 | const SSL_TICKET_AEAD_METHOD *ticket_aead_method = nullptr; |
| 4359 |
| 4360 | // legacy_ocsp_callback implements an OCSP-related callback for OpenSSL |
| 4361 | // compatibility. |
| 4362 | int (*legacy_ocsp_callback)(SSL *ssl, void *arg) = nullptr; |
| 4363 | void *legacy_ocsp_callback_arg = nullptr; |
| 4364 |
| 4365 | // compliance_policy limits the set of ciphers that can be selected when |
| 4366 | // negotiating a TLS 1.3 connection. |
| 4367 | enum ssl_compliance_policy_t compliance_policy = ssl_compliance_policy_none; |
| 4368 |
| 4369 | // verify_sigalgs, if not empty, is the set of signature algorithms |
| 4370 | // accepted from the peer in decreasing order of preference. |
| 4371 | bssl::Array<uint16_t> verify_sigalgs; |
| 4372 |
| 4373 | // retain_only_sha256_of_client_certs is true if we should compute the SHA256 |
| 4374 | // hash of the peer's certificate and then discard it to save memory and |
| 4375 | // session space. Only effective on the server side. |
| 4376 | bool retain_only_sha256_of_client_certs : 1; |
| 4377 |
| 4378 | // quiet_shutdown is true if the connection should not send a close_notify on |
| 4379 | // shutdown. |
| 4380 | bool quiet_shutdown : 1; |
| 4381 |
| 4382 | // ocsp_stapling_enabled is only used by client connections and indicates |
| 4383 | // whether OCSP stapling will be requested. |
| 4384 | bool ocsp_stapling_enabled : 1; |
| 4385 |
| 4386 | // If true, a client will request certificate timestamps. |
| 4387 | bool signed_cert_timestamps_enabled : 1; |
| 4388 |
| 4389 | // channel_id_enabled is whether Channel ID is enabled. For a server, means |
| 4390 | // that we'll accept Channel IDs from clients. For a client, means that we'll |
| 4391 | // advertise support. |
| 4392 | bool channel_id_enabled : 1; |
| 4393 |
| 4394 | // grease_enabled is whether GREASE (RFC 8701) is enabled. |
| 4395 | bool grease_enabled : 1; |
| 4396 |
| 4397 | // permute_extensions is whether to permute extensions when sending messages. |
| 4398 | bool permute_extensions : 1; |
| 4399 |
| 4400 | // allow_unknown_alpn_protos is whether the client allows unsolicited ALPN |
| 4401 | // protocols from the peer. |
| 4402 | bool allow_unknown_alpn_protos : 1; |
| 4403 |
| 4404 | // false_start_allowed_without_alpn is whether False Start (if |
| 4405 | // |SSL_MODE_ENABLE_FALSE_START| is enabled) is allowed without ALPN. |
| 4406 | bool false_start_allowed_without_alpn : 1; |
| 4407 |
| 4408 | // handoff indicates that a server should stop after receiving the |
| 4409 | // ClientHello and pause the handshake in such a way that |SSL_get_error| |
| 4410 | // returns |SSL_ERROR_HANDOFF|. |
| 4411 | bool handoff : 1; |
| 4412 |
| 4413 | // If enable_early_data is true, early data can be sent and accepted. |
| 4414 | bool enable_early_data : 1; |
| 4415 |
| 4416 | // aes_hw_override if set indicates we should override checking for AES |
| 4417 | // hardware support, and use the value in aes_hw_override_value instead. |
| 4418 | bool aes_hw_override : 1; |
| 4419 |
| 4420 | // aes_hw_override_value is used for testing to indicate the support or lack |
| 4421 | // of support for AES hardware. The value is only considered if |
| 4422 | // |aes_hw_override| is true. |
| 4423 | bool aes_hw_override_value : 1; |
| 4424 |
| 4425 | // resumption_across_names_enabled indicates whether a TLS 1.3 server should |
| 4426 | // signal its sessions may be resumed across names in the server certificate. |
| 4427 | bool resumption_across_names_enabled : 1; |
| 4428 |
| 4429 | private: |
| 4430 | friend RefCounted; |
| 4431 | ~ssl_ctx_st(); |
| 4432 | }; |
| 4433 |
| 4434 | struct ssl_st { |
| 4435 | explicit ssl_st(SSL_CTX *ctx_arg); |
| 4436 | ssl_st(const ssl_st &) = delete; |
| 4437 | ssl_st &operator=(const ssl_st &) = delete; |
| 4438 | ~ssl_st(); |
| 4439 |
| 4440 | // method is the method table corresponding to the current protocol (DTLS or |
| 4441 | // TLS). |
| 4442 | const bssl::SSL_PROTOCOL_METHOD *method = nullptr; |
| 4443 |
| 4444 | // config is a container for handshake configuration. Accesses to this field |
| 4445 | // should check for nullptr, since configuration may be shed after the |
| 4446 | // handshake completes. (If you have the |SSL_HANDSHAKE| object at hand, use |
| 4447 | // that instead, and skip the null check.) |
| 4448 | bssl::UniquePtr<bssl::SSL_CONFIG> config; |
| 4449 |
| 4450 | uint16_t max_send_fragment = 0; |
| 4451 |
| 4452 | // There are 2 BIO's even though they are normally both the same. This is so |
| 4453 | // data can be read and written to different handlers |
| 4454 |
| 4455 | bssl::UniquePtr<BIO> rbio; // used by SSL_read |
| 4456 | bssl::UniquePtr<BIO> wbio; // used by SSL_write |
| 4457 |
| 4458 | // do_handshake runs the handshake. On completion, it returns |ssl_hs_ok|. |
| 4459 | // Otherwise, it returns a value corresponding to what operation is needed to |
| 4460 | // progress. |
| 4461 | bssl::ssl_hs_wait_t (*do_handshake)(bssl::SSL_HANDSHAKE *hs) = nullptr; |
| 4462 |
| 4463 | bssl::SSL3_STATE *s3 = nullptr; // TLS variables |
| 4464 | bssl::DTLS1_STATE *d1 = nullptr; // DTLS variables |
| 4465 |
| 4466 | // callback that allows applications to peek at protocol messages |
| 4467 | void (*msg_callback)(int write_p, int version, int content_type, |
| 4468 | const void *buf, size_t len, SSL *ssl, |
| 4469 | void *arg) = nullptr; |
| 4470 | void *msg_callback_arg = nullptr; |
| 4471 |
| 4472 | // session info |
| 4473 |
| 4474 | // initial_timeout_duration_ms is the default DTLS timeout duration in |
| 4475 | // milliseconds. It's used to initialize the timer any time it's restarted. We |
| 4476 | // default to RFC 9147's recommendation for real-time applications, 400ms. |
| 4477 | uint32_t initial_timeout_duration_ms = 400; |
| 4478 |
| 4479 | // session is the configured session to be offered by the client. This session |
| 4480 | // is immutable. |
| 4481 | bssl::UniquePtr<SSL_SESSION> session; |
| 4482 |
| 4483 | void (*info_callback)(const SSL *ssl, int type, int value) = nullptr; |
| 4484 |
| 4485 | bssl::UniquePtr<SSL_CTX> ctx; |
| 4486 |
| 4487 | // session_ctx is the |SSL_CTX| used for the session cache and related |
| 4488 | // settings. |
| 4489 | bssl::UniquePtr<SSL_CTX> session_ctx; |
| 4490 |
| 4491 | // extra application data |
| 4492 | CRYPTO_EX_DATA ex_data; |
| 4493 |
| 4494 | uint32_t options = 0; // protocol behaviour |
| 4495 | uint32_t mode = 0; // API behaviour |
| 4496 | uint32_t max_cert_list = 0; |
| 4497 | bssl::UniquePtr<char> hostname; |
| 4498 |
| 4499 | // quic_method is the method table corresponding to the QUIC hooks. |
| 4500 | const SSL_QUIC_METHOD *quic_method = nullptr; |
| 4501 |
| 4502 | // renegotiate_mode controls how peer renegotiation attempts are handled. |
| 4503 | ssl_renegotiate_mode_t renegotiate_mode = ssl_renegotiate_never; |
| 4504 |
| 4505 | // server is true iff the this SSL* is the server half. Note: before the SSL* |
| 4506 | // is initialized by either SSL_set_accept_state or SSL_set_connect_state, |
| 4507 | // the side is not determined. In this state, server is always false. |
| 4508 | bool server : 1; |
| 4509 |
| 4510 | // quiet_shutdown is true if the connection should not send a close_notify on |
| 4511 | // shutdown. |
| 4512 | bool quiet_shutdown : 1; |
| 4513 |
| 4514 | // If enable_early_data is true, early data can be sent and accepted. |
| 4515 | bool enable_early_data : 1; |
| 4516 |
| 4517 | // resumption_across_names_enabled indicates whether a TLS 1.3 server should |
| 4518 | // signal its sessions may be resumed across names in the server certificate. |
| 4519 | bool resumption_across_names_enabled : 1; |
| 4520 | }; |
| 4521 |
| 4522 | struct ssl_session_st : public bssl::RefCounted<ssl_session_st> { |
| 4523 | explicit ssl_session_st(const bssl::SSL_X509_METHOD *method); |
| 4524 | ssl_session_st(const ssl_session_st &) = delete; |
| 4525 | ssl_session_st &operator=(const ssl_session_st &) = delete; |
| 4526 |
| 4527 | // ssl_version is the (D)TLS version that established the session. |
| 4528 | uint16_t ssl_version = 0; |
| 4529 |
| 4530 | // group_id is the ID of the ECDH group used to establish this session or zero |
| 4531 | // if not applicable or unknown. |
| 4532 | uint16_t group_id = 0; |
| 4533 |
| 4534 | // peer_signature_algorithm is the signature algorithm used to authenticate |
| 4535 | // the peer, or zero if not applicable or unknown. |
| 4536 | uint16_t peer_signature_algorithm = 0; |
| 4537 |
| 4538 | // secret, in TLS 1.2 and below, is the master secret associated with the |
| 4539 | // session. In TLS 1.3 and up, it is the resumption PSK for sessions handed to |
| 4540 | // the caller, but it stores the resumption secret when stored on |SSL| |
| 4541 | // objects. |
| 4542 | bssl::InplaceVector<uint8_t, SSL_MAX_MASTER_KEY_LENGTH> secret; |
| 4543 |
| 4544 | bssl::InplaceVector<uint8_t, SSL_MAX_SSL_SESSION_ID_LENGTH> session_id; |
| 4545 |
| 4546 | // this is used to determine whether the session is being reused in |
| 4547 | // the appropriate context. It is up to the application to set this, |
| 4548 | // via SSL_new |
| 4549 | bssl::InplaceVector<uint8_t, SSL_MAX_SID_CTX_LENGTH> sid_ctx; |
| 4550 |
| 4551 | bssl::UniquePtr<char> psk_identity; |
| 4552 |
| 4553 | // certs contains the certificate chain from the peer, starting with the leaf |
| 4554 | // certificate. |
| 4555 | bssl::UniquePtr<STACK_OF(CRYPTO_BUFFER)> certs; |
| 4556 |
| 4557 | const bssl::SSL_X509_METHOD *x509_method = nullptr; |
| 4558 |
| 4559 | // x509_peer is the peer's certificate. |
| 4560 | X509 *x509_peer = nullptr; |
| 4561 |
| 4562 | // x509_chain is the certificate chain sent by the peer. NOTE: for historical |
| 4563 | // reasons, when a client (so the peer is a server), the chain includes |
| 4564 | // |peer|, but when a server it does not. |
| 4565 | STACK_OF(X509) *x509_chain = nullptr; |
| 4566 |
| 4567 | // x509_chain_without_leaf is a lazily constructed copy of |x509_chain| that |
| 4568 | // omits the leaf certificate. This exists because OpenSSL, historically, |
| 4569 | // didn't include the leaf certificate in the chain for a server, but did for |
| 4570 | // a client. The |x509_chain| always includes it and, if an API call requires |
| 4571 | // a chain without, it is stored here. |
| 4572 | STACK_OF(X509) *x509_chain_without_leaf = nullptr; |
| 4573 |
| 4574 | // verify_result is the result of certificate verification in the case of |
| 4575 | // non-fatal certificate errors. |
| 4576 | long verify_result = X509_V_ERR_INVALID_CALL; |
| 4577 |
| 4578 | // timeout is the lifetime of the session in seconds, measured from |time|. |
| 4579 | // This is renewable up to |auth_timeout|. |
| 4580 | uint32_t timeout = SSL_DEFAULT_SESSION_TIMEOUT; |
| 4581 |
| 4582 | // auth_timeout is the non-renewable lifetime of the session in seconds, |
| 4583 | // measured from |time|. |
| 4584 | uint32_t auth_timeout = SSL_DEFAULT_SESSION_TIMEOUT; |
| 4585 |
| 4586 | // time is the time the session was issued, measured in seconds from the UNIX |
| 4587 | // epoch. |
| 4588 | uint64_t time = 0; |
| 4589 |
| 4590 | const SSL_CIPHER *cipher = nullptr; |
| 4591 |
| 4592 | CRYPTO_EX_DATA ex_data; // application specific data |
| 4593 |
| 4594 | // These are used to make removal of session-ids more efficient and to |
| 4595 | // implement a maximum cache size. |
| 4596 | SSL_SESSION *prev = nullptr, *next = nullptr; |
| 4597 |
| 4598 | bssl::Array<uint8_t> ticket; |
| 4599 |
| 4600 | bssl::UniquePtr<CRYPTO_BUFFER> signed_cert_timestamp_list; |
| 4601 |
| 4602 | // The OCSP response that came with the session. |
| 4603 | bssl::UniquePtr<CRYPTO_BUFFER> ocsp_response; |
| 4604 |
| 4605 | // peer_sha256 contains the SHA-256 hash of the peer's certificate if |
| 4606 | // |peer_sha256_valid| is true. |
| 4607 | uint8_t peer_sha256[SHA256_DIGEST_LENGTH] = {0}; |
| 4608 |
| 4609 | // original_handshake_hash contains the handshake hash (either SHA-1+MD5 or |
| 4610 | // SHA-2, depending on TLS version) for the original, full handshake that |
| 4611 | // created a session. This is used by Channel IDs during resumption. |
| 4612 | bssl::InplaceVector<uint8_t, SSL_MAX_MD_SIZE> original_handshake_hash; |
| 4613 |
| 4614 | uint32_t ticket_lifetime_hint = 0; // Session lifetime hint in seconds |
| 4615 |
| 4616 | uint32_t ticket_age_add = 0; |
| 4617 |
| 4618 | // ticket_max_early_data is the maximum amount of data allowed to be sent as |
| 4619 | // early data. If zero, 0-RTT is disallowed. |
| 4620 | uint32_t ticket_max_early_data = 0; |
| 4621 |
| 4622 | // early_alpn is the ALPN protocol from the initial handshake. This is only |
| 4623 | // stored for TLS 1.3 and above in order to enforce ALPN matching for 0-RTT |
| 4624 | // resumptions. For the current connection's ALPN protocol, see |
| 4625 | // |alpn_selected| on |SSL3_STATE|. |
| 4626 | bssl::Array<uint8_t> early_alpn; |
| 4627 |
| 4628 | // local_application_settings, if |has_application_settings| is true, is the |
| 4629 | // local ALPS value for this connection. |
| 4630 | bssl::Array<uint8_t> local_application_settings; |
| 4631 |
| 4632 | // peer_application_settings, if |has_application_settings| is true, is the |
| 4633 | // peer ALPS value for this connection. |
| 4634 | bssl::Array<uint8_t> peer_application_settings; |
| 4635 |
| 4636 | // extended_master_secret is whether the master secret in this session was |
| 4637 | // generated using EMS and thus isn't vulnerable to the Triple Handshake |
| 4638 | // attack. |
| 4639 | bool extended_master_secret : 1; |
| 4640 |
| 4641 | // peer_sha256_valid is whether |peer_sha256| is valid. |
| 4642 | bool peer_sha256_valid : 1; // Non-zero if peer_sha256 is valid |
| 4643 |
| 4644 | // not_resumable is used to indicate that session resumption is disallowed. |
| 4645 | bool not_resumable : 1; |
| 4646 |
| 4647 | // ticket_age_add_valid is whether |ticket_age_add| is valid. |
| 4648 | bool ticket_age_add_valid : 1; |
| 4649 |
| 4650 | // is_server is whether this session was created by a server. |
| 4651 | bool is_server : 1; |
| 4652 |
| 4653 | // is_quic indicates whether this session was created using QUIC. |
| 4654 | bool is_quic : 1; |
| 4655 |
| 4656 | // has_application_settings indicates whether ALPS was negotiated in this |
| 4657 | // session. |
| 4658 | bool has_application_settings : 1; |
| 4659 |
| 4660 | // is_resumable_across_names indicates whether the session may be resumed for |
| 4661 | // any of the identities presented in the certificate. |
| 4662 | bool is_resumable_across_names : 1; |
| 4663 |
| 4664 | // quic_early_data_context is used to determine whether early data must be |
| 4665 | // rejected when performing a QUIC handshake. |
| 4666 | bssl::Array<uint8_t> quic_early_data_context; |
| 4667 |
| 4668 | private: |
| 4669 | friend RefCounted; |
| 4670 | ~ssl_session_st(); |
| 4671 | }; |
| 4672 |
| 4673 | struct ssl_ech_keys_st : public bssl::RefCounted<ssl_ech_keys_st> { |
| 4674 | ssl_ech_keys_st() : RefCounted(CheckSubClass()) {} |
| 4675 |
| 4676 | bssl::Vector<bssl::UniquePtr<bssl::ECHServerConfig>> configs; |
| 4677 |
| 4678 | private: |
| 4679 | friend RefCounted; |
| 4680 | ~ssl_ech_keys_st() = default; |
| 4681 | }; |
| 4682 |
| 4683 | #endif // OPENSSL_HEADER_SSL_INTERNAL_H |
| 4684 |