-
Notifications
You must be signed in to change notification settings - Fork 788
/
Copy pathinternal.h
4601 lines (3727 loc) · 181 KB
/
internal.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
// Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
// Copyright 2005 Nokia. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef OPENSSL_HEADER_SSL_INTERNAL_H
#define OPENSSL_HEADER_SSL_INTERNAL_H
#include <openssl/base.h>
#include <stdlib.h>
#include <algorithm>
#include <atomic>
#include <bitset>
#include <initializer_list>
#include <limits>
#include <new>
#include <string_view>
#include <type_traits>
#include <utility>
#include <openssl/aead.h>
#include <openssl/curve25519.h>
#include <openssl/err.h>
#include <openssl/hpke.h>
#include <openssl/lhash.h>
#include <openssl/mem.h>
#include <openssl/span.h>
#include <openssl/ssl.h>
#include <openssl/stack.h>
#include "../crypto/err/internal.h"
#include "../crypto/internal.h"
#include "../crypto/lhash/internal.h"
#include "../crypto/spake2plus/internal.h"
#if defined(OPENSSL_WINDOWS)
// Windows defines struct timeval in winsock2.h.
OPENSSL_MSVC_PRAGMA(warning(push, 3))
#include <winsock2.h>
OPENSSL_MSVC_PRAGMA(warning(pop))
#else
#include <sys/time.h>
#endif
BSSL_NAMESPACE_BEGIN
struct SSL_CONFIG;
struct SSL_HANDSHAKE;
struct SSL_PROTOCOL_METHOD;
struct SSL_X509_METHOD;
// C++ utilities.
// New behaves like |new| but uses |OPENSSL_malloc| for memory allocation. It
// returns nullptr on allocation error. It only implements single-object
// allocation and not new T[n].
//
// Note: unlike |new|, this does not support non-public constructors.
template <typename T, typename... Args>
T *New(Args &&...args) {
void *t = OPENSSL_malloc(sizeof(T));
if (t == nullptr) {
return nullptr;
}
return new (t) T(std::forward<Args>(args)...);
}
// Delete behaves like |delete| but uses |OPENSSL_free| to release memory.
//
// Note: unlike |delete| this does not support non-public destructors.
template <typename T>
void Delete(T *t) {
if (t != nullptr) {
t->~T();
OPENSSL_free(t);
}
}
// All types with kAllowUniquePtr set may be used with UniquePtr. Other types
// may be C structs which require a |BORINGSSL_MAKE_DELETER| registration.
namespace internal {
template <typename T>
struct DeleterImpl<T, std::enable_if_t<T::kAllowUniquePtr>> {
static void Free(T *t) { Delete(t); }
};
} // namespace internal
// MakeUnique behaves like |std::make_unique| but returns nullptr on allocation
// error.
template <typename T, typename... Args>
UniquePtr<T> MakeUnique(Args &&...args) {
return UniquePtr<T>(New<T>(std::forward<Args>(args)...));
}
// Array<T> is an owning array of elements of |T|.
template <typename T>
class Array {
public:
// Array's default constructor creates an empty array.
Array() {}
Array(const Array &) = delete;
Array(Array &&other) { *this = std::move(other); }
~Array() { Reset(); }
Array &operator=(const Array &) = delete;
Array &operator=(Array &&other) {
Reset();
other.Release(&data_, &size_);
return *this;
}
const T *data() const { return data_; }
T *data() { return data_; }
size_t size() const { return size_; }
bool empty() const { return size_ == 0; }
const T &operator[](size_t i) const {
BSSL_CHECK(i < size_);
return data_[i];
}
T &operator[](size_t i) {
BSSL_CHECK(i < size_);
return data_[i];
}
T *begin() { return data_; }
const T *begin() const { return data_; }
T *end() { return data_ + size_; }
const T *end() const { return data_ + size_; }
void Reset() { Reset(nullptr, 0); }
// Reset releases the current contents of the array and takes ownership of the
// raw pointer supplied by the caller.
void Reset(T *new_data, size_t new_size) {
std::destroy_n(data_, size_);
OPENSSL_free(data_);
data_ = new_data;
size_ = new_size;
}
// Release releases ownership of the array to a raw pointer supplied by the
// caller.
void Release(T **out, size_t *out_size) {
*out = data_;
*out_size = size_;
data_ = nullptr;
size_ = 0;
}
// Init replaces the array with a newly-allocated array of |new_size|
// value-constructed copies of |T|. It returns true on success and false on
// error. If |T| is a primitive type like |uint8_t|, value-construction means
// it will be zero-initialized.
[[nodiscard]] bool Init(size_t new_size) {
if (!InitUninitialized(new_size)) {
return false;
}
std::uninitialized_value_construct_n(data_, size_);
return true;
}
// InitForOverwrite behaves like |Init| but it default-constructs each element
// instead. This means that, if |T| is a primitive type, the array will be
// uninitialized and thus must be filled in by the caller.
[[nodiscard]] bool InitForOverwrite(size_t new_size) {
if (!InitUninitialized(new_size)) {
return false;
}
std::uninitialized_default_construct_n(data_, size_);
return true;
}
// CopyFrom replaces the array with a newly-allocated copy of |in|. It returns
// true on success and false on error.
[[nodiscard]] bool CopyFrom(Span<const T> in) {
if (!InitUninitialized(in.size())) {
return false;
}
std::uninitialized_copy(in.begin(), in.end(), data_);
return true;
}
// Shrink shrinks the stored size of the array to |new_size|. It crashes if
// the new size is larger. Note this does not shrink the allocation itself.
void Shrink(size_t new_size) {
if (new_size > size_) {
abort();
}
std::destroy_n(data_ + new_size, size_ - new_size);
size_ = new_size;
}
private:
// InitUninitialized replaces the array with a newly-allocated array of
// |new_size| elements, but whose constructor has not yet run. On success, the
// elements must be constructed before returning control to the caller.
bool InitUninitialized(size_t new_size) {
Reset();
if (new_size == 0) {
return true;
}
if (new_size > std::numeric_limits<size_t>::max() / sizeof(T)) {
OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
return false;
}
data_ = reinterpret_cast<T *>(OPENSSL_malloc(new_size * sizeof(T)));
if (data_ == nullptr) {
return false;
}
size_ = new_size;
return true;
}
T *data_ = nullptr;
size_t size_ = 0;
};
// Vector<T> is a resizable array of elements of |T|.
template <typename T>
class Vector {
public:
Vector() = default;
Vector(const Vector &) = delete;
Vector(Vector &&other) { *this = std::move(other); }
~Vector() { clear(); }
Vector &operator=(const Vector &) = delete;
Vector &operator=(Vector &&other) {
clear();
std::swap(data_, other.data_);
std::swap(size_, other.size_);
std::swap(capacity_, other.capacity_);
return *this;
}
const T *data() const { return data_; }
T *data() { return data_; }
size_t size() const { return size_; }
bool empty() const { return size_ == 0; }
const T &operator[](size_t i) const {
BSSL_CHECK(i < size_);
return data_[i];
}
T &operator[](size_t i) {
BSSL_CHECK(i < size_);
return data_[i];
}
T *begin() { return data_; }
const T *begin() const { return data_; }
T *end() { return data_ + size_; }
const T *end() const { return data_ + size_; }
void clear() {
std::destroy_n(data_, size_);
OPENSSL_free(data_);
data_ = nullptr;
size_ = 0;
capacity_ = 0;
}
// Push adds |elem| at the end of the internal array, growing if necessary. It
// returns false when allocation fails.
[[nodiscard]] bool Push(T elem) {
if (!MaybeGrow()) {
return false;
}
new (&data_[size_]) T(std::move(elem));
size_++;
return true;
}
// CopyFrom replaces the contents of the array with a copy of |in|. It returns
// true on success and false on allocation error.
[[nodiscard]] bool CopyFrom(Span<const T> in) {
Array<T> copy;
if (!copy.CopyFrom(in)) {
return false;
}
clear();
copy.Release(&data_, &size_);
capacity_ = size_;
return true;
}
private:
// If there is no room for one more element, creates a new backing array with
// double the size of the old one and copies elements over.
bool MaybeGrow() {
// No need to grow if we have room for one more T.
if (size_ < capacity_) {
return true;
}
size_t new_capacity = kDefaultSize;
if (capacity_ > 0) {
// Double the array's size if it's safe to do so.
if (capacity_ > std::numeric_limits<size_t>::max() / 2) {
OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
return false;
}
new_capacity = capacity_ * 2;
}
if (new_capacity > std::numeric_limits<size_t>::max() / sizeof(T)) {
OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
return false;
}
T *new_data =
reinterpret_cast<T *>(OPENSSL_malloc(new_capacity * sizeof(T)));
if (new_data == nullptr) {
return false;
}
size_t new_size = size_;
std::uninitialized_move(begin(), end(), new_data);
clear();
data_ = new_data;
size_ = new_size;
capacity_ = new_capacity;
return true;
}
// data_ is a pointer to |capacity_| objects of size |T|, the first |size_| of
// which are constructed.
T *data_ = nullptr;
// |size_| is the number of elements stored in this Vector.
size_t size_ = 0;
// |capacity_| is the number of elements allocated in this Vector.
size_t capacity_ = 0;
// |kDefaultSize| is the default initial size of the backing array.
static constexpr size_t kDefaultSize = 16;
};
// A PackedSize is an integer that can store values from 0 to N, represented as
// a minimal-width integer.
template <size_t N>
using PackedSize = std::conditional_t<
N <= 0xff, uint8_t,
std::conditional_t<N <= 0xffff, uint16_t,
std::conditional_t<N <= 0xffffffff, uint32_t, size_t>>>;
// An InplaceVector is like a Vector, but stores up to N elements inline in the
// object. It is inspired by std::inplace_vector in C++26.
template <typename T, size_t N>
class InplaceVector {
public:
InplaceVector() = default;
InplaceVector(const InplaceVector &other) { *this = other; }
InplaceVector(InplaceVector &&other) { *this = std::move(other); }
~InplaceVector() { clear(); }
InplaceVector &operator=(const InplaceVector &other) {
if (this != &other) {
CopyFrom(other);
}
return *this;
}
InplaceVector &operator=(InplaceVector &&other) {
clear();
std::uninitialized_move(other.begin(), other.end(), data());
size_ = other.size();
return *this;
}
const T *data() const { return reinterpret_cast<const T *>(storage_); }
T *data() { return reinterpret_cast<T *>(storage_); }
size_t size() const { return size_; }
static constexpr size_t capacity() { return N; }
bool empty() const { return size_ == 0; }
const T &operator[](size_t i) const {
BSSL_CHECK(i < size_);
return data()[i];
}
T &operator[](size_t i) {
BSSL_CHECK(i < size_);
return data()[i];
}
T *begin() { return data(); }
const T *begin() const { return data(); }
T *end() { return data() + size_; }
const T *end() const { return data() + size_; }
void clear() { Shrink(0); }
// Shrink resizes the vector to |new_size|, which must not be larger than the
// current size. Unlike |Resize|, this can be called when |T| is not
// default-constructible.
void Shrink(size_t new_size) {
BSSL_CHECK(new_size <= size_);
std::destroy_n(data() + new_size, size_ - new_size);
size_ = static_cast<PackedSize<N>>(new_size);
}
// TryResize resizes the vector to |new_size| and returns true, or returns
// false if |new_size| is too large. Any newly-added elements are
// value-initialized.
[[nodiscard]] bool TryResize(size_t new_size) {
if (new_size <= size_) {
Shrink(new_size);
return true;
}
if (new_size > capacity()) {
return false;
}
std::uninitialized_value_construct_n(data() + size_, new_size - size_);
size_ = static_cast<PackedSize<N>>(new_size);
return true;
}
// TryResizeForOverwrite behaves like |TryResize|, but newly-added elements
// are default-initialized, so POD types may contain uninitialized values that
// the caller is responsible for filling in.
[[nodiscard]] bool TryResizeForOverwrite(size_t new_size) {
if (new_size <= size_) {
Shrink(new_size);
return true;
}
if (new_size > capacity()) {
return false;
}
std::uninitialized_default_construct_n(data() + size_, new_size - size_);
size_ = static_cast<PackedSize<N>>(new_size);
return true;
}
// TryCopyFrom sets the vector to a copy of |in| and returns true, or returns
// false if |in| is too large.
[[nodiscard]] bool TryCopyFrom(Span<const T> in) {
if (in.size() > capacity()) {
return false;
}
clear();
std::uninitialized_copy(in.begin(), in.end(), data());
size_ = in.size();
return true;
}
// TryPushBack appends |val| to the vector and returns a pointer to the
// newly-inserted value, or nullptr if the vector is at capacity.
[[nodiscard]] T *TryPushBack(T val) {
if (size() >= capacity()) {
return nullptr;
}
T *ret = &data()[size_];
new (ret) T(std::move(val));
size_++;
return ret;
}
// The following methods behave like their |Try*| counterparts, but abort the
// program on failure.
void Resize(size_t size) { BSSL_CHECK(TryResize(size)); }
void ResizeForOverwrite(size_t size) {
BSSL_CHECK(TryResizeForOverwrite(size));
}
void CopyFrom(Span<const T> in) { BSSL_CHECK(TryCopyFrom(in)); }
T &PushBack(T val) {
T *ret = TryPushBack(std::move(val));
BSSL_CHECK(ret != nullptr);
return *ret;
}
template <typename Pred>
void EraseIf(Pred pred) {
// See if anything needs to be erased at all. This avoids a self-move.
auto iter = std::find_if(begin(), end(), pred);
if (iter == end()) {
return;
}
// Elements before the first to be erased may be left as-is.
size_t new_size = iter - begin();
// Swap all subsequent elements in if they are to be kept.
for (size_t i = new_size + 1; i < size(); i++) {
if (!pred((*this)[i])) {
(*this)[new_size] = std::move((*this)[i]);
new_size++;
}
}
Shrink(new_size);
}
private:
alignas(T) char storage_[sizeof(T[N])];
PackedSize<N> size_ = 0;
};
// An MRUQueue maintains a queue of up to |N| objects of type |T|. If the queue
// is at capacity, adding to the queue pops the least recently added element.
template <typename T, size_t N>
class MRUQueue {
public:
static constexpr bool kAllowUniquePtr = true;
MRUQueue() = default;
// If we ever need to make this type movable, we could. (The defaults almost
// work except we need |start_| to be reset when moved-from.)
MRUQueue(const MRUQueue &other) = delete;
MRUQueue &operator=(const MRUQueue &other) = delete;
bool empty() const { return size() == 0; }
size_t size() const { return storage_.size(); }
T &operator[](size_t i) {
BSSL_CHECK(i < size());
return storage_[(start_ + i) % N];
}
const T &operator[](size_t i) const {
return (*const_cast<MRUQueue *>(this))[i];
}
void Clear() {
storage_.clear();
start_ = 0;
}
void PushBack(T t) {
if (storage_.size() < N) {
assert(start_ == 0);
storage_.PushBack(std::move(t));
} else {
(*this)[0] = std::move(t);
start_ = (start_ + 1) % N;
}
}
private:
InplaceVector<T, N> storage_;
PackedSize<N> start_ = 0;
};
// CBBFinishArray behaves like |CBB_finish| but stores the result in an Array.
OPENSSL_EXPORT bool CBBFinishArray(CBB *cbb, Array<uint8_t> *out);
// GetAllNames helps to implement |*_get_all_*_names| style functions. It
// writes at most |max_out| string pointers to |out| and returns the number that
// it would have liked to have written. The strings written consist of
// |fixed_names_len| strings from |fixed_names| followed by |objects_len|
// strings taken by projecting |objects| through |name|.
template <typename T, typename Name>
inline size_t GetAllNames(const char **out, size_t max_out,
Span<const char *const> fixed_names, Name(T::*name),
Span<const T> objects) {
auto span = bssl::Span(out, max_out);
for (size_t i = 0; !span.empty() && i < fixed_names.size(); i++) {
span[0] = fixed_names[i];
span = span.subspan(1);
}
span = span.subspan(0, objects.size());
for (size_t i = 0; i < span.size(); i++) {
span[i] = objects[i].*name;
}
return fixed_names.size() + objects.size();
}
// RefCounted is a common base for ref-counted types. This is an instance of the
// C++ curiously-recurring template pattern, so a type Foo must subclass
// RefCounted<Foo>. It additionally must friend RefCounted<Foo> to allow calling
// the destructor.
template <typename Derived>
class RefCounted {
public:
RefCounted(const RefCounted &) = delete;
RefCounted &operator=(const RefCounted &) = delete;
// These methods are intentionally named differently from `bssl::UpRef` to
// avoid a collision. Only the implementations of `FOO_up_ref` and `FOO_free`
// should call these.
void UpRefInternal() { CRYPTO_refcount_inc(&references_); }
void DecRefInternal() {
if (CRYPTO_refcount_dec_and_test_zero(&references_)) {
Derived *d = static_cast<Derived *>(this);
d->~Derived();
OPENSSL_free(d);
}
}
protected:
// Ensure that only `Derived`, which must inherit from `RefCounted<Derived>`,
// can call the constructor. This catches bugs where someone inherited from
// the wrong base.
class CheckSubClass {
private:
friend Derived;
CheckSubClass() = default;
};
RefCounted(CheckSubClass) {
static_assert(std::is_base_of<RefCounted, Derived>::value,
"Derived must subclass RefCounted<Derived>");
}
~RefCounted() = default;
private:
CRYPTO_refcount_t references_ = 1;
};
// Protocol versions.
//
// Due to DTLS's historical wire version differences, we maintain two notions of
// version.
//
// The "version" or "wire version" is the actual 16-bit value that appears on
// the wire. It uniquely identifies a version and is also used at API
// boundaries. The set of supported versions differs between TLS and DTLS. Wire
// versions are opaque values and may not be compared numerically.
//
// The "protocol version" identifies the high-level handshake variant being
// used. DTLS versions map to the corresponding TLS versions. Protocol versions
// are sequential and may be compared numerically.
// ssl_protocol_version_from_wire sets |*out| to the protocol version
// corresponding to wire version |version| and returns true. If |version| is not
// a valid TLS or DTLS version, it returns false.
//
// Note this simultaneously handles both DTLS and TLS. Use one of the
// higher-level functions below for most operations.
bool ssl_protocol_version_from_wire(uint16_t *out, uint16_t version);
// ssl_get_version_range sets |*out_min_version| and |*out_max_version| to the
// minimum and maximum enabled protocol versions, respectively.
bool ssl_get_version_range(const SSL_HANDSHAKE *hs, uint16_t *out_min_version,
uint16_t *out_max_version);
// ssl_supports_version returns whether |hs| supports |version|.
bool ssl_supports_version(const SSL_HANDSHAKE *hs, uint16_t version);
// ssl_method_supports_version returns whether |method| supports |version|.
bool ssl_method_supports_version(const SSL_PROTOCOL_METHOD *method,
uint16_t version);
// ssl_add_supported_versions writes the supported versions of |hs| to |cbb|, in
// decreasing preference order. The version list is filtered to those whose
// protocol version is at least |extra_min_version|.
bool ssl_add_supported_versions(const SSL_HANDSHAKE *hs, CBB *cbb,
uint16_t extra_min_version);
// ssl_negotiate_version negotiates a common version based on |hs|'s preferences
// and the peer preference list in |peer_versions|. On success, it returns true
// and sets |*out_version| to the selected version. Otherwise, it returns false
// and sets |*out_alert| to an alert to send.
bool ssl_negotiate_version(SSL_HANDSHAKE *hs, uint8_t *out_alert,
uint16_t *out_version, const CBS *peer_versions);
// ssl_has_final_version returns whether |ssl| has determined the final version.
// This may be used to distinguish the predictive 0-RTT version from the final
// one.
bool ssl_has_final_version(const SSL *ssl);
// ssl_protocol_version returns |ssl|'s protocol version. It is an error to
// call this function before the version is determined.
uint16_t ssl_protocol_version(const SSL *ssl);
// Cipher suites.
BSSL_NAMESPACE_END
struct ssl_cipher_st {
// name is the OpenSSL name for the cipher.
const char *name;
// standard_name is the IETF name for the cipher.
const char *standard_name;
// id is the cipher suite value bitwise OR-d with 0x03000000.
uint32_t id;
// algorithm_* determine the cipher suite. See constants below for the values.
uint32_t algorithm_mkey;
uint32_t algorithm_auth;
uint32_t algorithm_enc;
uint32_t algorithm_mac;
uint32_t algorithm_prf;
};
BSSL_NAMESPACE_BEGIN
// Bits for |algorithm_mkey| (key exchange algorithm).
#define SSL_kRSA 0x00000001u
#define SSL_kECDHE 0x00000002u
// SSL_kPSK is only set for plain PSK, not ECDHE_PSK.
#define SSL_kPSK 0x00000004u
#define SSL_kGENERIC 0x00000008u
// Bits for |algorithm_auth| (server authentication).
#define SSL_aRSA_SIGN 0x00000001u
#define SSL_aRSA_DECRYPT 0x00000002u
#define SSL_aECDSA 0x00000004u
// SSL_aPSK is set for both PSK and ECDHE_PSK.
#define SSL_aPSK 0x00000008u
#define SSL_aGENERIC 0x00000010u
#define SSL_aCERT (SSL_aRSA_SIGN | SSL_aRSA_DECRYPT | SSL_aECDSA)
// Bits for |algorithm_enc| (symmetric encryption).
#define SSL_3DES 0x00000001u
#define SSL_AES128 0x00000002u
#define SSL_AES256 0x00000004u
#define SSL_AES128GCM 0x00000008u
#define SSL_AES256GCM 0x00000010u
#define SSL_CHACHA20POLY1305 0x00000020u
#define SSL_AES (SSL_AES128 | SSL_AES256 | SSL_AES128GCM | SSL_AES256GCM)
// Bits for |algorithm_mac| (symmetric authentication).
#define SSL_SHA1 0x00000001u
#define SSL_SHA256 0x00000002u
// SSL_AEAD is set for all AEADs.
#define SSL_AEAD 0x00000004u
// Bits for |algorithm_prf| (handshake digest).
#define SSL_HANDSHAKE_MAC_DEFAULT 0x1
#define SSL_HANDSHAKE_MAC_SHA256 0x2
#define SSL_HANDSHAKE_MAC_SHA384 0x4
// SSL_MAX_MD_SIZE is size of the largest hash function used in TLS, SHA-384.
#define SSL_MAX_MD_SIZE 48
// An SSLCipherPreferenceList contains a list of SSL_CIPHERs with equal-
// preference groups. For TLS clients, the groups are moot because the server
// picks the cipher and groups cannot be expressed on the wire. However, for
// servers, the equal-preference groups allow the client's preferences to be
// partially respected. (This only has an effect with
// SSL_OP_CIPHER_SERVER_PREFERENCE).
//
// The equal-preference groups are expressed by grouping SSL_CIPHERs together.
// All elements of a group have the same priority: no ordering is expressed
// within a group.
//
// The values in |ciphers| are in one-to-one correspondence with
// |in_group_flags|. (That is, sk_SSL_CIPHER_num(ciphers) is the number of
// bytes in |in_group_flags|.) The bytes in |in_group_flags| are either 1, to
// indicate that the corresponding SSL_CIPHER is not the last element of a
// group, or 0 to indicate that it is.
//
// For example, if |in_group_flags| contains all zeros then that indicates a
// traditional, fully-ordered preference. Every SSL_CIPHER is the last element
// of the group (i.e. they are all in a one-element group).
//
// For a more complex example, consider:
// ciphers: A B C D E F
// in_group_flags: 1 1 0 0 1 0
//
// That would express the following, order:
//
// A E
// B -> D -> F
// C
struct SSLCipherPreferenceList {
static constexpr bool kAllowUniquePtr = true;
SSLCipherPreferenceList() = default;
~SSLCipherPreferenceList();
bool Init(UniquePtr<STACK_OF(SSL_CIPHER)> ciphers,
Span<const bool> in_group_flags);
bool Init(const SSLCipherPreferenceList &);
void Remove(const SSL_CIPHER *cipher);
UniquePtr<STACK_OF(SSL_CIPHER)> ciphers;
bool *in_group_flags = nullptr;
};
// AllCiphers returns an array of all supported ciphers, sorted by id.
Span<const SSL_CIPHER> AllCiphers();
// ssl_cipher_get_evp_aead sets |*out_aead| to point to the correct EVP_AEAD
// object for |cipher| protocol version |version|. It sets |*out_mac_secret_len|
// and |*out_fixed_iv_len| to the MAC key length and fixed IV length,
// respectively. The MAC key length is zero except for legacy block and stream
// ciphers. It returns true on success and false on error.
bool ssl_cipher_get_evp_aead(const EVP_AEAD **out_aead,
size_t *out_mac_secret_len,
size_t *out_fixed_iv_len, const SSL_CIPHER *cipher,
uint16_t version);
// ssl_get_handshake_digest returns the |EVP_MD| corresponding to |version| and
// |cipher|.
const EVP_MD *ssl_get_handshake_digest(uint16_t version,
const SSL_CIPHER *cipher);
// ssl_create_cipher_list evaluates |rule_str|. It sets |*out_cipher_list| to a
// newly-allocated |SSLCipherPreferenceList| containing the result. It returns
// true on success and false on failure. If |strict| is true, nonsense will be
// rejected. If false, nonsense will be silently ignored. An empty result is
// considered an error regardless of |strict|. |has_aes_hw| indicates if the
// list should be ordered based on having support for AES in hardware or not.
bool ssl_create_cipher_list(UniquePtr<SSLCipherPreferenceList> *out_cipher_list,
const bool has_aes_hw, const char *rule_str,
bool strict);
// ssl_cipher_auth_mask_for_key returns the mask of cipher |algorithm_auth|
// values suitable for use with |key| in TLS 1.2 and below. |sign_ok| indicates
// whether |key| may be used for signing.
uint32_t ssl_cipher_auth_mask_for_key(const EVP_PKEY *key, bool sign_ok);
// ssl_cipher_uses_certificate_auth returns whether |cipher| authenticates the
// server and, optionally, the client with a certificate.
bool ssl_cipher_uses_certificate_auth(const SSL_CIPHER *cipher);
// ssl_cipher_requires_server_key_exchange returns whether |cipher| requires a
// ServerKeyExchange message.
//
// This function may return false while still allowing |cipher| an optional
// ServerKeyExchange. This is the case for plain PSK ciphers.
bool ssl_cipher_requires_server_key_exchange(const SSL_CIPHER *cipher);
// ssl_cipher_get_record_split_len, for TLS 1.0 CBC mode ciphers, returns the
// length of an encrypted 1-byte record, for use in record-splitting. Otherwise
// it returns zero.
size_t ssl_cipher_get_record_split_len(const SSL_CIPHER *cipher);
// ssl_choose_tls13_cipher returns an |SSL_CIPHER| corresponding with the best
// available from |cipher_suites| compatible with |version| and |policy|. It
// returns NULL if there isn't a compatible cipher. |has_aes_hw| indicates if
// the choice should be made as if support for AES in hardware is available.
const SSL_CIPHER *ssl_choose_tls13_cipher(CBS cipher_suites, bool has_aes_hw,
uint16_t version,
enum ssl_compliance_policy_t policy);
// ssl_tls13_cipher_meets_policy returns true if |cipher_id| is acceptable given
// |policy|.
bool ssl_tls13_cipher_meets_policy(uint16_t cipher_id,
enum ssl_compliance_policy_t policy);
// ssl_cipher_is_deprecated returns true if |cipher| is deprecated.
OPENSSL_EXPORT bool ssl_cipher_is_deprecated(const SSL_CIPHER *cipher);
// Transcript layer.
// SSLTranscript maintains the handshake transcript as a combination of a
// buffer and running hash.
class SSLTranscript {
public:
explicit SSLTranscript(bool is_dtls);
~SSLTranscript();
SSLTranscript(SSLTranscript &&other) = default;
SSLTranscript &operator=(SSLTranscript &&other) = default;
// Init initializes the handshake transcript. If called on an existing
// transcript, it resets the transcript and hash. It returns true on success
// and false on failure.
bool Init();
// InitHash initializes the handshake hash based on the PRF and contents of
// the handshake transcript. Subsequent calls to |Update| will update the
// rolling hash. It returns one on success and zero on failure. It is an error
// to call this function after the handshake buffer is released. This may be
// called multiple times to change the hash function.
bool InitHash(uint16_t version, const SSL_CIPHER *cipher);
// UpdateForHelloRetryRequest resets the rolling hash with the
// HelloRetryRequest construction. It returns true on success and false on
// failure. It is an error to call this function before the handshake buffer
// is released.
bool UpdateForHelloRetryRequest();
// CopyToHashContext initializes |ctx| with |digest| and the data thus far in
// the transcript. It returns true on success and false on failure. If the
// handshake buffer is still present, |digest| may be any supported digest.
// Otherwise, |digest| must match the transcript hash.
bool CopyToHashContext(EVP_MD_CTX *ctx, const EVP_MD *digest) const;
Span<const uint8_t> buffer() const {
return Span(reinterpret_cast<const uint8_t *>(buffer_->data),
buffer_->length);
}
// FreeBuffer releases the handshake buffer. Subsequent calls to
// |Update| will not update the handshake buffer.
void FreeBuffer();
// DigestLen returns the length of the PRF hash.
size_t DigestLen() const;
// Digest returns the PRF hash. For TLS 1.1 and below, this is
// |EVP_md5_sha1|.
const EVP_MD *Digest() const;
// Update adds |in| to the handshake buffer and handshake hash, whichever is
// enabled. It returns true on success and false on failure.
bool Update(Span<const uint8_t> in);
// GetHash writes the handshake hash to |out| which must have room for at
// least |DigestLen| bytes. On success, it returns true and sets |*out_len| to
// the number of bytes written. Otherwise, it returns false.
bool GetHash(uint8_t *out, size_t *out_len) const;
// GetFinishedMAC computes the MAC for the Finished message into the bytes
// pointed by |out| and writes the number of bytes to |*out_len|. |out| must
// have room for |EVP_MAX_MD_SIZE| bytes. It returns true on success and false
// on failure.
bool GetFinishedMAC(uint8_t *out, size_t *out_len, const SSL_SESSION *session,
bool from_server) const;
private:
// HashBuffer initializes |ctx| to use |digest| and writes the contents of
// |buffer_| to |ctx|. If this SSLTranscript is for DTLS 1.3, the appropriate
// bytes in |buffer_| will be skipped when hashing the buffer.
bool HashBuffer(EVP_MD_CTX *ctx, const EVP_MD *digest) const;
// AddToBufferOrHash directly adds the contents of |in| to |buffer_| and/or
// |hash_|.
bool AddToBufferOrHash(Span<const uint8_t> in);
// buffer_, if non-null, contains the handshake transcript.
UniquePtr<BUF_MEM> buffer_;
// hash, if initialized with an |EVP_MD|, maintains the handshake hash.
ScopedEVP_MD_CTX hash_;
// is_dtls_ indicates whether this is a transcript for a DTLS connection.
bool is_dtls_ : 1;
// version_ contains the version for the connection (if known).
uint16_t version_ = 0;
};
// tls1_prf computes the PRF function for |ssl|. It fills |out|, using |secret|
// as the secret and |label| as the label. |seed1| and |seed2| are concatenated
// to form the seed parameter. It returns true on success and false on failure.
bool tls1_prf(const EVP_MD *digest, Span<uint8_t> out,
Span<const uint8_t> secret, std::string_view label,
Span<const uint8_t> seed1, Span<const uint8_t> seed2);
// Encryption layer.
// SSLAEADContext contains information about an AEAD that is being used to
// encrypt an SSL connection.
class SSLAEADContext {
public:
explicit SSLAEADContext(const SSL_CIPHER *cipher);
~SSLAEADContext();
static constexpr bool kAllowUniquePtr = true;
SSLAEADContext(const SSLAEADContext &&) = delete;
SSLAEADContext &operator=(const SSLAEADContext &&) = delete;
// CreateNullCipher creates an |SSLAEADContext| for the null cipher.
static UniquePtr<SSLAEADContext> CreateNullCipher();
// Create creates an |SSLAEADContext| using the supplied key material. It
// returns nullptr on error. Only one of |Open| or |Seal| may be used with the
// resulting object, depending on |direction|. |version| is the wire version.
static UniquePtr<SSLAEADContext> Create(enum evp_aead_direction_t direction,
uint16_t version,
const SSL_CIPHER *cipher,
Span<const uint8_t> enc_key,
Span<const uint8_t> mac_key,
Span<const uint8_t> fixed_iv);
// CreatePlaceholderForQUIC creates a placeholder |SSLAEADContext| for the
// given cipher. The resulting object can be queried for various properties
// but cannot encrypt or decrypt data.
static UniquePtr<SSLAEADContext> CreatePlaceholderForQUIC(
const SSL_CIPHER *cipher);
const SSL_CIPHER *cipher() const { return cipher_; }
// is_null_cipher returns true if this is the null cipher.
bool is_null_cipher() const { return !cipher_; }
// ExplicitNonceLen returns the length of the explicit nonce.
size_t ExplicitNonceLen() const;
// MaxOverhead returns the maximum overhead of calling |Seal|.
size_t MaxOverhead() const;
// MaxSealInputLen returns the maximum length for |Seal| that can fit in
// |max_out| output bytes, or zero if no input may fit.
size_t MaxSealInputLen(size_t max_out) const;
// SuffixLen calculates the suffix length written by |SealScatter| and writes
// it to |*out_suffix_len|. It returns true on success and false on error.
// |in_len| and |extra_in_len| should equal the argument of the same names
// passed to |SealScatter|.
bool SuffixLen(size_t *out_suffix_len, size_t in_len,
size_t extra_in_len) const;