forked from google/boringssl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
internal.h
3290 lines (2644 loc) · 131 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 (C) 1995-1998 Eric Young ([email protected])
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young ([email protected]).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson ([email protected]).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young ([email protected])"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson ([email protected])"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* ([email protected]). This product includes software written by Tim
* Hudson ([email protected]).
*
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
* ECC cipher suite support in OpenSSL originally developed by
* SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
*/
/* ====================================================================
* Copyright 2005 Nokia. All rights reserved.
*
* The portions of the attached software ("Contribution") is developed by
* Nokia Corporation and is licensed pursuant to the OpenSSL open source
* license.
*
* The Contribution, originally written by Mika Kousa and Pasi Eronen of
* Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
* support (see RFC 4279) to OpenSSL.
*
* No patent licenses or other rights except those expressly stated in
* the OpenSSL open source license shall be deemed granted or received
* expressly, by implication, estoppel, or otherwise.
*
* No assurances are provided by Nokia that the Contribution does not
* infringe the patent or other intellectual property rights of any third
* party or that the license provides you with all the necessary rights
* to make use of the Contribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
* ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
* SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
* OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
* OTHERWISE.
*/
#ifndef OPENSSL_HEADER_SSL_INTERNAL_H
#define OPENSSL_HEADER_SSL_INTERNAL_H
#include <openssl/base.h>
#include <stdlib.h>
#include <limits>
#include <new>
#include <type_traits>
#include <utility>
#include <openssl/aead.h>
#include <openssl/err.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"
#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) {
OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
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, typename std::enable_if<T::kAllowUniquePtr>::type> {
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)...));
}
#if defined(BORINGSSL_ALLOW_CXX_RUNTIME)
#define HAS_VIRTUAL_DESTRUCTOR
#define PURE_VIRTUAL = 0
#else
// HAS_VIRTUAL_DESTRUCTOR should be declared in any base class which defines a
// virtual destructor. This avoids a dependency on |_ZdlPv| and prevents the
// class from being used with |delete|.
#define HAS_VIRTUAL_DESTRUCTOR \
void operator delete(void *) { abort(); }
// PURE_VIRTUAL should be used instead of = 0 when defining pure-virtual
// functions. This avoids a dependency on |__cxa_pure_virtual| but loses
// compile-time checking.
#define PURE_VIRTUAL \
{ abort(); }
#endif
// CONSTEXPR_ARRAY works around a VS 2015 bug where ranged for loops don't work
// on constexpr arrays.
#if defined(_MSC_VER) && !defined(__clang__) && _MSC_VER < 1910
#define CONSTEXPR_ARRAY const
#else
#define CONSTEXPR_ARRAY constexpr
#endif
// 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 { return data_[i]; }
T &operator[](size_t i) { return data_[i]; }
T *begin() { return data_; }
const T *cbegin() const { return data_; }
T *end() { return data_ + size_; }
const T *cend() 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) {
for (size_t i = 0; i < size_; i++) {
data_[i].~T();
}
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|
// default-constructed copies of |T|. It returns true on success and false on
// error.
//
// Note that if |T| is a primitive type like |uint8_t|, it is uninitialized.
bool Init(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) {
OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
return false;
}
size_ = new_size;
for (size_t i = 0; i < size_; i++) {
new (&data_[i]) T;
}
return true;
}
// CopyFrom replaces the array with a newly-allocated copy of |in|. It returns
// true on success and false on error.
bool CopyFrom(Span<const T> in) {
if (!Init(in.size())) {
return false;
}
OPENSSL_memcpy(data_, in.data(), sizeof(T) * in.size());
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();
}
size_ = new_size;
}
private:
T *data_ = nullptr;
size_t size_ = 0;
};
// CBBFinishArray behaves like |CBB_finish| but stores the result in an Array.
OPENSSL_EXPORT bool CBBFinishArray(CBB *cbb, Array<uint8_t> *out);
// Protocol versions.
//
// Due to DTLS's historical wire version differences and to support multiple
// variants of the same protocol during development, 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. Draft TLS 1.3
// variants all map to TLS 1.3. 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(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.
bool ssl_add_supported_versions(SSL_HANDSHAKE *hs, CBB *cbb);
// 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_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);
// ssl_is_draft28 returns whether the version corresponds to a draft28 TLS 1.3
// variant.
bool ssl_is_draft28(uint16_t version);
// 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 0x00000001u
#define SSL_aECDSA 0x00000002u
// SSL_aPSK is set for both PSK and ECDHE_PSK.
#define SSL_aPSK 0x00000004u
#define SSL_aGENERIC 0x00000008u
#define SSL_aCERT (SSL_aRSA | 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_eNULL 0x00000020u
#define SSL_CHACHA20POLY1305 0x00000040u
#define SSL_AES (SSL_AES128 | SSL_AES256 | SSL_AES128GCM | SSL_AES256GCM)
// Bits for |algorithm_mac| (symmetric authentication).
#define SSL_SHA1 0x00000001u
// SSL_AEAD is set for all AEADs.
#define SSL_AEAD 0x00000002u
// Bits for |algorithm_prf| (handshake digest).
#define SSL_HANDSHAKE_MAC_DEFAULT 0x1
#define SSL_HANDSHAKE_MAC_SHA256 0x2
#define SSL_HANDSHAKE_MAC_SHA384 0x4
// 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);
UniquePtr<STACK_OF(SSL_CIPHER)> ciphers;
bool *in_group_flags = nullptr;
};
// 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, bool is_dtls);
// 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|.
bool ssl_create_cipher_list(UniquePtr<SSLCipherPreferenceList> *out_cipher_list,
const char *rule_str, bool strict);
// ssl_cipher_get_value returns the cipher suite id of |cipher|.
uint16_t ssl_cipher_get_value(const SSL_CIPHER *cipher);
// 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.
uint32_t ssl_cipher_auth_mask_for_key(const EVP_PKEY *key);
// 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);
// Transcript layer.
// SSLTranscript maintains the handshake transcript as a combination of a
// buffer and running hash.
class SSLTranscript {
public:
SSLTranscript();
~SSLTranscript();
// 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.
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();
// CopyHashContext copies the hash context into |ctx| and returns true on
// success.
bool CopyHashContext(EVP_MD_CTX *ctx);
Span<const uint8_t> buffer() {
return MakeConstSpan(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);
// 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);
private:
// 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_;
};
// 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, Span<const char> 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:
SSLAEADContext(uint16_t version, bool is_dtls, 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(bool is_dtls);
// 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 normalized
// protocol version, so DTLS 1.0 is represented as 0x0301, not 0xffef.
static UniquePtr<SSLAEADContext> Create(enum evp_aead_direction_t direction,
uint16_t version, bool is_dtls,
const SSL_CIPHER *cipher,
Span<const uint8_t> enc_key,
Span<const uint8_t> mac_key,
Span<const uint8_t> fixed_iv);
// SetVersionIfNullCipher sets the version the SSLAEADContext for the null
// cipher, to make version-specific determinations in the record layer prior
// to a cipher being selected.
void SetVersionIfNullCipher(uint16_t version);
// ProtocolVersion returns the protocol version associated with this
// SSLAEADContext. It can only be called once |version_| has been set to a
// valid value.
uint16_t ProtocolVersion() const;
// RecordVersion returns the record version that should be used with this
// SSLAEADContext for record construction and crypto.
uint16_t RecordVersion() const;
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;
// 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;
// CiphertextLen calculates the total ciphertext length written by
// |SealScatter| and writes it to |*out_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 CiphertextLen(size_t *out_len, size_t in_len, size_t extra_in_len) const;
// Open authenticates and decrypts |in| in-place. On success, it sets |*out|
// to the plaintext in |in| and returns true. Otherwise, it returns
// false. The output will always be |ExplicitNonceLen| bytes ahead of |in|.
bool Open(Span<uint8_t> *out, uint8_t type, uint16_t record_version,
const uint8_t seqnum[8], Span<const uint8_t> header,
Span<uint8_t> in);
// Seal encrypts and authenticates |in_len| bytes from |in| and writes the
// result to |out|. It returns true on success and false on error.
//
// If |in| and |out| alias then |out| + |ExplicitNonceLen| must be == |in|.
bool Seal(uint8_t *out, size_t *out_len, size_t max_out, uint8_t type,
uint16_t record_version, const uint8_t seqnum[8],
Span<const uint8_t> header, const uint8_t *in, size_t in_len);
// SealScatter encrypts and authenticates |in_len| bytes from |in| and splits
// the result between |out_prefix|, |out| and |out_suffix|. It returns one on
// success and zero on error.
//
// On successful return, exactly |ExplicitNonceLen| bytes are written to
// |out_prefix|, |in_len| bytes to |out|, and |SuffixLen| bytes to
// |out_suffix|.
//
// |extra_in| may point to an additional plaintext buffer. If present,
// |extra_in_len| additional bytes are encrypted and authenticated, and the
// ciphertext is written to the beginning of |out_suffix|. |SuffixLen| should
// be used to size |out_suffix| accordingly.
//
// If |in| and |out| alias then |out| must be == |in|. Other arguments may not
// alias anything.
bool SealScatter(uint8_t *out_prefix, uint8_t *out, uint8_t *out_suffix,
uint8_t type, uint16_t record_version,
const uint8_t seqnum[8], Span<const uint8_t> header,
const uint8_t *in, size_t in_len, const uint8_t *extra_in,
size_t extra_in_len);
bool GetIV(const uint8_t **out_iv, size_t *out_iv_len) const;
private:
// GetAdditionalData returns the additional data, writing into |storage| if
// necessary.
Span<const uint8_t> GetAdditionalData(uint8_t storage[13], uint8_t type,
uint16_t record_version,
const uint8_t seqnum[8],
size_t plaintext_len,
Span<const uint8_t> header);
const SSL_CIPHER *cipher_;
ScopedEVP_AEAD_CTX ctx_;
// fixed_nonce_ contains any bytes of the nonce that are fixed for all
// records.
uint8_t fixed_nonce_[12];
uint8_t fixed_nonce_len_ = 0, variable_nonce_len_ = 0;
// version_ is the wire version that should be used with this AEAD.
uint16_t version_;
// is_dtls_ is whether DTLS is being used with this AEAD.
bool is_dtls_;
// variable_nonce_included_in_record_ is true if the variable nonce
// for a record is included as a prefix before the ciphertext.
bool variable_nonce_included_in_record_ : 1;
// random_variable_nonce_ is true if the variable nonce is
// randomly generated, rather than derived from the sequence
// number.
bool random_variable_nonce_ : 1;
// xor_fixed_nonce_ is true if the fixed nonce should be XOR'd into the
// variable nonce rather than prepended.
bool xor_fixed_nonce_ : 1;
// omit_length_in_ad_ is true if the length should be omitted in the
// AEAD's ad parameter.
bool omit_length_in_ad_ : 1;
// omit_ad_ is true if the AEAD's ad parameter should be omitted.
bool omit_ad_ : 1;
// ad_is_header_ is true if the AEAD's ad parameter is the record header.
bool ad_is_header_ : 1;
};
// DTLS replay bitmap.
// DTLS1_BITMAP maintains a sliding window of 64 sequence numbers to detect
// replayed packets. It should be initialized by zeroing every field.
struct DTLS1_BITMAP {
// map is a bit mask of the last 64 sequence numbers. Bit
// |1<<i| corresponds to |max_seq_num - i|.
uint64_t map = 0;
// max_seq_num is the largest sequence number seen so far as a 64-bit
// integer.
uint64_t max_seq_num = 0;
};
// Record layer.
// ssl_record_sequence_update increments the sequence number in |seq|. It
// returns true on success and false on wraparound.
bool ssl_record_sequence_update(uint8_t *seq, size_t seq_len);
// ssl_record_prefix_len returns the length of the prefix before the ciphertext
// of a record for |ssl|.
//
// TODO(davidben): Expose this as part of public API once the high-level
// buffer-free APIs are available.
size_t ssl_record_prefix_len(const SSL *ssl);
enum ssl_open_record_t {
ssl_open_record_success,
ssl_open_record_discard,
ssl_open_record_partial,
ssl_open_record_close_notify,
ssl_open_record_error,
};
// tls_open_record decrypts a record from |in| in-place.
//
// If the input did not contain a complete record, it returns
// |ssl_open_record_partial|. It sets |*out_consumed| to the total number of
// bytes necessary. It is guaranteed that a successful call to |tls_open_record|
// will consume at least that many bytes.
//
// Otherwise, it sets |*out_consumed| to the number of bytes of input
// consumed. Note that input may be consumed on all return codes if a record was
// decrypted.
//
// On success, it returns |ssl_open_record_success|. It sets |*out_type| to the
// record type and |*out| to the record body in |in|. Note that |*out| may be
// empty.
//
// If a record was successfully processed but should be discarded, it returns
// |ssl_open_record_discard|.
//
// If a record was successfully processed but is a close_notify, it returns
// |ssl_open_record_close_notify|.
//
// On failure or fatal alert, it returns |ssl_open_record_error| and sets
// |*out_alert| to an alert to emit, or zero if no alert should be emitted.
enum ssl_open_record_t tls_open_record(SSL *ssl, uint8_t *out_type,
Span<uint8_t> *out, size_t *out_consumed,
uint8_t *out_alert, Span<uint8_t> in);
// dtls_open_record implements |tls_open_record| for DTLS. It only returns
// |ssl_open_record_partial| if |in| was empty and sets |*out_consumed| to
// zero. The caller should read one packet and try again.
enum ssl_open_record_t dtls_open_record(SSL *ssl, uint8_t *out_type,
Span<uint8_t> *out,
size_t *out_consumed,
uint8_t *out_alert, Span<uint8_t> in);
// ssl_seal_align_prefix_len returns the length of the prefix before the start
// of the bulk of the ciphertext when sealing a record with |ssl|. Callers may
// use this to align buffers.
//
// Note when TLS 1.0 CBC record-splitting is enabled, this includes the one byte
// record and is the offset into second record's ciphertext. Thus sealing a
// small record may result in a smaller output than this value.
//
// TODO(davidben): Is this alignment valuable? Record-splitting makes this a
// mess.
size_t ssl_seal_align_prefix_len(const SSL *ssl);
// tls_seal_record seals a new record of type |type| and body |in| and writes it
// to |out|. At most |max_out| bytes will be written. It returns true on success
// and false on error. If enabled, |tls_seal_record| implements TLS 1.0 CBC
// 1/n-1 record splitting and may write two records concatenated.
//
// For a large record, the bulk of the ciphertext will begin
// |ssl_seal_align_prefix_len| bytes into out. Aligning |out| appropriately may
// improve performance. It writes at most |in_len| + |SSL_max_seal_overhead|
// bytes to |out|.
//
// |in| and |out| may not alias.
bool tls_seal_record(SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
uint8_t type, const uint8_t *in, size_t in_len);
enum dtls1_use_epoch_t {
dtls1_use_previous_epoch,
dtls1_use_current_epoch,
};
// dtls_max_seal_overhead returns the maximum overhead, in bytes, of sealing a
// record.
size_t dtls_max_seal_overhead(const SSL *ssl, enum dtls1_use_epoch_t use_epoch);
// dtls_seal_prefix_len returns the number of bytes of prefix to reserve in
// front of the plaintext when sealing a record in-place.
size_t dtls_seal_prefix_len(const SSL *ssl, enum dtls1_use_epoch_t use_epoch);
// dtls_seal_record implements |tls_seal_record| for DTLS. |use_epoch| selects
// which epoch's cipher state to use. Unlike |tls_seal_record|, |in| and |out|
// may alias but, if they do, |in| must be exactly |dtls_seal_prefix_len| bytes
// ahead of |out|.
bool dtls_seal_record(SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
uint8_t type, const uint8_t *in, size_t in_len,
enum dtls1_use_epoch_t use_epoch);
// ssl_process_alert processes |in| as an alert and updates |ssl|'s shutdown
// state. It returns one of |ssl_open_record_discard|, |ssl_open_record_error|,
// |ssl_open_record_close_notify|, or |ssl_open_record_fatal_alert| as
// appropriate.
enum ssl_open_record_t ssl_process_alert(SSL *ssl, uint8_t *out_alert,
Span<const uint8_t> in);
// Private key operations.
// ssl_has_private_key returns whether |cfg| has a private key configured.
bool ssl_has_private_key(const SSL_CONFIG *cfg);
// ssl_private_key_* perform the corresponding operation on
// |SSL_PRIVATE_KEY_METHOD|. If there is a custom private key configured, they
// call the corresponding function or |complete| depending on whether there is a
// pending operation. Otherwise, they implement the operation with
// |EVP_PKEY|.
enum ssl_private_key_result_t ssl_private_key_sign(
SSL_HANDSHAKE *hs, uint8_t *out, size_t *out_len, size_t max_out,
uint16_t sigalg, Span<const uint8_t> in);
enum ssl_private_key_result_t ssl_private_key_decrypt(SSL_HANDSHAKE *hs,
uint8_t *out,
size_t *out_len,
size_t max_out,
Span<const uint8_t> in);
// ssl_private_key_supports_signature_algorithm returns whether |hs|'s private
// key supports |sigalg|.
bool ssl_private_key_supports_signature_algorithm(SSL_HANDSHAKE *hs,
uint16_t sigalg);
// ssl_public_key_verify verifies that the |signature| is valid for the public
// key |pkey| and input |in|, using the signature algorithm |sigalg|.
bool ssl_public_key_verify(SSL *ssl, Span<const uint8_t> signature,
uint16_t sigalg, EVP_PKEY *pkey,
Span<const uint8_t> in);
// Key shares.
// SSLKeyShare abstracts over Diffie-Hellman-like key exchanges.
class SSLKeyShare {
public:
virtual ~SSLKeyShare() {}
static constexpr bool kAllowUniquePtr = true;
HAS_VIRTUAL_DESTRUCTOR
// Create returns a SSLKeyShare instance for use with group |group_id| or
// nullptr on error.
static UniquePtr<SSLKeyShare> Create(uint16_t group_id);
// Create deserializes an SSLKeyShare instance previously serialized by
// |Serialize|.
static UniquePtr<SSLKeyShare> Create(CBS *in);
// GroupID returns the group ID.
virtual uint16_t GroupID() const PURE_VIRTUAL;
// Offer generates a keypair and writes the public value to
// |out_public_key|. It returns true on success and false on error.
virtual bool Offer(CBB *out_public_key) PURE_VIRTUAL;
// Accept performs a key exchange against the |peer_key| generated by |offer|.
// On success, it returns true, writes the public value to |out_public_key|,
// and sets |*out_secret| the shared secret. On failure, it returns false and
// sets |*out_alert| to an alert to send to the peer.
//
// The default implementation calls |Offer| and then |Finish|, assuming a key
// exchange protocol where the peers are symmetric.
virtual bool Accept(CBB *out_public_key, Array<uint8_t> *out_secret,
uint8_t *out_alert, Span<const uint8_t> peer_key);
// Finish performs a key exchange against the |peer_key| generated by
// |Accept|. On success, it returns true and sets |*out_secret| to the shared
// secret. On failure, it returns zero and sets |*out_alert| to an alert to
// send to the peer.
virtual bool Finish(Array<uint8_t> *out_secret, uint8_t *out_alert,
Span<const uint8_t> peer_key) PURE_VIRTUAL;
// Serialize writes the state of the key exchange to |out|, returning true if
// successful and false otherwise.
virtual bool Serialize(CBB *out) { return false; }
// Deserialize initializes the state of the key exchange from |in|, returning
// true if successful and false otherwise. It is called by |Create|.
virtual bool Deserialize(CBS *in) { return false; }
};
// ssl_nid_to_group_id looks up the group corresponding to |nid|. On success, it
// sets |*out_group_id| to the group ID and returns true. Otherwise, it returns
// false.
bool ssl_nid_to_group_id(uint16_t *out_group_id, int nid);
// ssl_name_to_group_id looks up the group corresponding to the |name| string of
// length |len|. On success, it sets |*out_group_id| to the group ID and returns
// true. Otherwise, it returns false.
bool ssl_name_to_group_id(uint16_t *out_group_id, const char *name, size_t len);