New Russian TLS 1.2 implementation
[openssl.git] / ssl / ssl_local.h
1 /*
2  * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4  * Copyright 2005 Nokia. All rights reserved.
5  *
6  * Licensed under the Apache License 2.0 (the "License").  You may not use
7  * this file except in compliance with the License.  You can obtain a copy
8  * in the file LICENSE in the source distribution or at
9  * https://www.openssl.org/source/license.html
10  */
11
12 #ifndef OSSL_SSL_LOCAL_H
13 # define OSSL_SSL_LOCAL_H
14
15 # include "e_os.h"              /* struct timeval for DTLS */
16 # include <stdlib.h>
17 # include <time.h>
18 # include <string.h>
19 # include <errno.h>
20
21 # include <openssl/buffer.h>
22 # include <openssl/comp.h>
23 # include <openssl/bio.h>
24 # include <openssl/rsa.h>
25 # include <openssl/dsa.h>
26 # include <openssl/err.h>
27 # include <openssl/ssl.h>
28 # include <openssl/async.h>
29 # include <openssl/symhacks.h>
30 # include <openssl/ct.h>
31 # include "record/record.h"
32 # include "statem/statem.h"
33 # include "internal/packet.h"
34 # include "internal/dane.h"
35 # include "internal/refcount.h"
36 # include "internal/tsan_assist.h"
37 # include "internal/bio.h"
38
39 # ifdef OPENSSL_BUILD_SHLIBSSL
40 #  undef OPENSSL_EXTERN
41 #  define OPENSSL_EXTERN OPENSSL_EXPORT
42 # endif
43
44 # define c2l(c,l)        (l = ((unsigned long)(*((c)++)))     , \
45                          l|=(((unsigned long)(*((c)++)))<< 8), \
46                          l|=(((unsigned long)(*((c)++)))<<16), \
47                          l|=(((unsigned long)(*((c)++)))<<24))
48
49 /* NOTE - c is not incremented as per c2l */
50 # define c2ln(c,l1,l2,n) { \
51                         c+=n; \
52                         l1=l2=0; \
53                         switch (n) { \
54                         case 8: l2 =((unsigned long)(*(--(c))))<<24; \
55                         case 7: l2|=((unsigned long)(*(--(c))))<<16; \
56                         case 6: l2|=((unsigned long)(*(--(c))))<< 8; \
57                         case 5: l2|=((unsigned long)(*(--(c))));     \
58                         case 4: l1 =((unsigned long)(*(--(c))))<<24; \
59                         case 3: l1|=((unsigned long)(*(--(c))))<<16; \
60                         case 2: l1|=((unsigned long)(*(--(c))))<< 8; \
61                         case 1: l1|=((unsigned long)(*(--(c))));     \
62                                 } \
63                         }
64
65 # define l2c(l,c)        (*((c)++)=(unsigned char)(((l)    )&0xff), \
66                          *((c)++)=(unsigned char)(((l)>> 8)&0xff), \
67                          *((c)++)=(unsigned char)(((l)>>16)&0xff), \
68                          *((c)++)=(unsigned char)(((l)>>24)&0xff))
69
70 # define n2l(c,l)        (l =((unsigned long)(*((c)++)))<<24, \
71                          l|=((unsigned long)(*((c)++)))<<16, \
72                          l|=((unsigned long)(*((c)++)))<< 8, \
73                          l|=((unsigned long)(*((c)++))))
74
75 # define n2l8(c,l)       (l =((uint64_t)(*((c)++)))<<56, \
76                          l|=((uint64_t)(*((c)++)))<<48, \
77                          l|=((uint64_t)(*((c)++)))<<40, \
78                          l|=((uint64_t)(*((c)++)))<<32, \
79                          l|=((uint64_t)(*((c)++)))<<24, \
80                          l|=((uint64_t)(*((c)++)))<<16, \
81                          l|=((uint64_t)(*((c)++)))<< 8, \
82                          l|=((uint64_t)(*((c)++))))
83
84
85 # define l2n(l,c)        (*((c)++)=(unsigned char)(((l)>>24)&0xff), \
86                          *((c)++)=(unsigned char)(((l)>>16)&0xff), \
87                          *((c)++)=(unsigned char)(((l)>> 8)&0xff), \
88                          *((c)++)=(unsigned char)(((l)    )&0xff))
89
90 # define l2n6(l,c)       (*((c)++)=(unsigned char)(((l)>>40)&0xff), \
91                          *((c)++)=(unsigned char)(((l)>>32)&0xff), \
92                          *((c)++)=(unsigned char)(((l)>>24)&0xff), \
93                          *((c)++)=(unsigned char)(((l)>>16)&0xff), \
94                          *((c)++)=(unsigned char)(((l)>> 8)&0xff), \
95                          *((c)++)=(unsigned char)(((l)    )&0xff))
96
97 # define l2n8(l,c)       (*((c)++)=(unsigned char)(((l)>>56)&0xff), \
98                          *((c)++)=(unsigned char)(((l)>>48)&0xff), \
99                          *((c)++)=(unsigned char)(((l)>>40)&0xff), \
100                          *((c)++)=(unsigned char)(((l)>>32)&0xff), \
101                          *((c)++)=(unsigned char)(((l)>>24)&0xff), \
102                          *((c)++)=(unsigned char)(((l)>>16)&0xff), \
103                          *((c)++)=(unsigned char)(((l)>> 8)&0xff), \
104                          *((c)++)=(unsigned char)(((l)    )&0xff))
105
106 /* NOTE - c is not incremented as per l2c */
107 # define l2cn(l1,l2,c,n) { \
108                         c+=n; \
109                         switch (n) { \
110                         case 8: *(--(c))=(unsigned char)(((l2)>>24)&0xff); \
111                         case 7: *(--(c))=(unsigned char)(((l2)>>16)&0xff); \
112                         case 6: *(--(c))=(unsigned char)(((l2)>> 8)&0xff); \
113                         case 5: *(--(c))=(unsigned char)(((l2)    )&0xff); \
114                         case 4: *(--(c))=(unsigned char)(((l1)>>24)&0xff); \
115                         case 3: *(--(c))=(unsigned char)(((l1)>>16)&0xff); \
116                         case 2: *(--(c))=(unsigned char)(((l1)>> 8)&0xff); \
117                         case 1: *(--(c))=(unsigned char)(((l1)    )&0xff); \
118                                 } \
119                         }
120
121 # define n2s(c,s)        ((s=(((unsigned int)((c)[0]))<< 8)| \
122                              (((unsigned int)((c)[1]))    )),(c)+=2)
123 # define s2n(s,c)        (((c)[0]=(unsigned char)(((s)>> 8)&0xff), \
124                            (c)[1]=(unsigned char)(((s)    )&0xff)),(c)+=2)
125
126 # define n2l3(c,l)       ((l =(((unsigned long)((c)[0]))<<16)| \
127                               (((unsigned long)((c)[1]))<< 8)| \
128                               (((unsigned long)((c)[2]))    )),(c)+=3)
129
130 # define l2n3(l,c)       (((c)[0]=(unsigned char)(((l)>>16)&0xff), \
131                            (c)[1]=(unsigned char)(((l)>> 8)&0xff), \
132                            (c)[2]=(unsigned char)(((l)    )&0xff)),(c)+=3)
133
134 # define TLS_MAX_VERSION_INTERNAL TLS1_3_VERSION
135 # define DTLS_MAX_VERSION_INTERNAL DTLS1_2_VERSION
136
137 /*
138  * DTLS version numbers are strange because they're inverted. Except for
139  * DTLS1_BAD_VER, which should be considered "lower" than the rest.
140  */
141 # define dtls_ver_ordinal(v1) (((v1) == DTLS1_BAD_VER) ? 0xff00 : (v1))
142 # define DTLS_VERSION_GT(v1, v2) (dtls_ver_ordinal(v1) < dtls_ver_ordinal(v2))
143 # define DTLS_VERSION_GE(v1, v2) (dtls_ver_ordinal(v1) <= dtls_ver_ordinal(v2))
144 # define DTLS_VERSION_LT(v1, v2) (dtls_ver_ordinal(v1) > dtls_ver_ordinal(v2))
145 # define DTLS_VERSION_LE(v1, v2) (dtls_ver_ordinal(v1) >= dtls_ver_ordinal(v2))
146
147
148 /*
149  * Define the Bitmasks for SSL_CIPHER.algorithms.
150  * This bits are used packed as dense as possible. If new methods/ciphers
151  * etc will be added, the bits a likely to change, so this information
152  * is for internal library use only, even though SSL_CIPHER.algorithms
153  * can be publicly accessed.
154  * Use the according functions for cipher management instead.
155  *
156  * The bit mask handling in the selection and sorting scheme in
157  * ssl_create_cipher_list() has only limited capabilities, reflecting
158  * that the different entities within are mutually exclusive:
159  * ONLY ONE BIT PER MASK CAN BE SET AT A TIME.
160  */
161
162 /* Bits for algorithm_mkey (key exchange algorithm) */
163 /* RSA key exchange */
164 # define SSL_kRSA                0x00000001U
165 /* tmp DH key no DH cert */
166 # define SSL_kDHE                0x00000002U
167 /* synonym */
168 # define SSL_kEDH                SSL_kDHE
169 /* ephemeral ECDH */
170 # define SSL_kECDHE              0x00000004U
171 /* synonym */
172 # define SSL_kEECDH              SSL_kECDHE
173 /* PSK */
174 # define SSL_kPSK                0x00000008U
175 /* GOST key exchange */
176 # define SSL_kGOST               0x00000010U
177 /* SRP */
178 # define SSL_kSRP                0x00000020U
179
180 # define SSL_kRSAPSK             0x00000040U
181 # define SSL_kECDHEPSK           0x00000080U
182 # define SSL_kDHEPSK             0x00000100U
183 /* GOST KDF key exchange, draft-smyshlyaev-tls12-gost-suites */
184 # define SSL_kGOST18             0x00000200U
185
186 /* all PSK */
187
188 # define SSL_PSK     (SSL_kPSK | SSL_kRSAPSK | SSL_kECDHEPSK | SSL_kDHEPSK)
189
190 /* Any appropriate key exchange algorithm (for TLS 1.3 ciphersuites) */
191 # define SSL_kANY                0x00000000U
192
193 /* Bits for algorithm_auth (server authentication) */
194 /* RSA auth */
195 # define SSL_aRSA                0x00000001U
196 /* DSS auth */
197 # define SSL_aDSS                0x00000002U
198 /* no auth (i.e. use ADH or AECDH) */
199 # define SSL_aNULL               0x00000004U
200 /* ECDSA auth*/
201 # define SSL_aECDSA              0x00000008U
202 /* PSK auth */
203 # define SSL_aPSK                0x00000010U
204 /* GOST R 34.10-2001 signature auth */
205 # define SSL_aGOST01             0x00000020U
206 /* SRP auth */
207 # define SSL_aSRP                0x00000040U
208 /* GOST R 34.10-2012 signature auth */
209 # define SSL_aGOST12             0x00000080U
210 /* Any appropriate signature auth (for TLS 1.3 ciphersuites) */
211 # define SSL_aANY                0x00000000U
212 /* All bits requiring a certificate */
213 #define SSL_aCERT \
214     (SSL_aRSA | SSL_aDSS | SSL_aECDSA | SSL_aGOST01 | SSL_aGOST12)
215
216 /* Bits for algorithm_enc (symmetric encryption) */
217 # define SSL_DES                 0x00000001U
218 # define SSL_3DES                0x00000002U
219 # define SSL_RC4                 0x00000004U
220 # define SSL_RC2                 0x00000008U
221 # define SSL_IDEA                0x00000010U
222 # define SSL_eNULL               0x00000020U
223 # define SSL_AES128              0x00000040U
224 # define SSL_AES256              0x00000080U
225 # define SSL_CAMELLIA128         0x00000100U
226 # define SSL_CAMELLIA256         0x00000200U
227 # define SSL_eGOST2814789CNT     0x00000400U
228 # define SSL_SEED                0x00000800U
229 # define SSL_AES128GCM           0x00001000U
230 # define SSL_AES256GCM           0x00002000U
231 # define SSL_AES128CCM           0x00004000U
232 # define SSL_AES256CCM           0x00008000U
233 # define SSL_AES128CCM8          0x00010000U
234 # define SSL_AES256CCM8          0x00020000U
235 # define SSL_eGOST2814789CNT12   0x00040000U
236 # define SSL_CHACHA20POLY1305    0x00080000U
237 # define SSL_ARIA128GCM          0x00100000U
238 # define SSL_ARIA256GCM          0x00200000U
239 # define SSL_MAGMA               0x00400000U
240 # define SSL_KUZNYECHIK          0x00800000U
241
242 # define SSL_AESGCM              (SSL_AES128GCM | SSL_AES256GCM)
243 # define SSL_AESCCM              (SSL_AES128CCM | SSL_AES256CCM | SSL_AES128CCM8 | SSL_AES256CCM8)
244 # define SSL_AES                 (SSL_AES128|SSL_AES256|SSL_AESGCM|SSL_AESCCM)
245 # define SSL_CAMELLIA            (SSL_CAMELLIA128|SSL_CAMELLIA256)
246 # define SSL_CHACHA20            (SSL_CHACHA20POLY1305)
247 # define SSL_ARIAGCM             (SSL_ARIA128GCM | SSL_ARIA256GCM)
248 # define SSL_ARIA                (SSL_ARIAGCM)
249
250 /* Bits for algorithm_mac (symmetric authentication) */
251
252 # define SSL_MD5                 0x00000001U
253 # define SSL_SHA1                0x00000002U
254 # define SSL_GOST94      0x00000004U
255 # define SSL_GOST89MAC   0x00000008U
256 # define SSL_SHA256              0x00000010U
257 # define SSL_SHA384              0x00000020U
258 /* Not a real MAC, just an indication it is part of cipher */
259 # define SSL_AEAD                0x00000040U
260 # define SSL_GOST12_256          0x00000080U
261 # define SSL_GOST89MAC12         0x00000100U
262 # define SSL_GOST12_512          0x00000200U
263 # define SSL_MAGMAOMAC           0x00000400U
264 # define SSL_KUZNYECHIKOMAC      0x00000800U
265
266 /*
267  * When adding new digest in the ssl_ciph.c and increment SSL_MD_NUM_IDX make
268  * sure to update this constant too
269  */
270
271 # define SSL_MD_MD5_IDX  0
272 # define SSL_MD_SHA1_IDX 1
273 # define SSL_MD_GOST94_IDX 2
274 # define SSL_MD_GOST89MAC_IDX 3
275 # define SSL_MD_SHA256_IDX 4
276 # define SSL_MD_SHA384_IDX 5
277 # define SSL_MD_GOST12_256_IDX  6
278 # define SSL_MD_GOST89MAC12_IDX 7
279 # define SSL_MD_GOST12_512_IDX  8
280 # define SSL_MD_MD5_SHA1_IDX 9
281 # define SSL_MD_SHA224_IDX 10
282 # define SSL_MD_SHA512_IDX 11
283 # define SSL_MD_MAGMAOMAC_IDX 12
284 # define SSL_MD_KUZNYECHIKOMAC_IDX 13
285 # define SSL_MAX_DIGEST 14
286
287 #define SSL_MD_NUM_IDX  SSL_MAX_DIGEST
288
289 /* Bits for algorithm2 (handshake digests and other extra flags) */
290
291 /* Bits 0-7 are handshake MAC */
292 # define SSL_HANDSHAKE_MAC_MASK  0xFF
293 # define SSL_HANDSHAKE_MAC_MD5_SHA1 SSL_MD_MD5_SHA1_IDX
294 # define SSL_HANDSHAKE_MAC_SHA256   SSL_MD_SHA256_IDX
295 # define SSL_HANDSHAKE_MAC_SHA384   SSL_MD_SHA384_IDX
296 # define SSL_HANDSHAKE_MAC_GOST94 SSL_MD_GOST94_IDX
297 # define SSL_HANDSHAKE_MAC_GOST12_256 SSL_MD_GOST12_256_IDX
298 # define SSL_HANDSHAKE_MAC_GOST12_512 SSL_MD_GOST12_512_IDX
299 # define SSL_HANDSHAKE_MAC_DEFAULT  SSL_HANDSHAKE_MAC_MD5_SHA1
300
301 /* Bits 8-15 bits are PRF */
302 # define TLS1_PRF_DGST_SHIFT 8
303 # define TLS1_PRF_SHA1_MD5 (SSL_MD_MD5_SHA1_IDX << TLS1_PRF_DGST_SHIFT)
304 # define TLS1_PRF_SHA256 (SSL_MD_SHA256_IDX << TLS1_PRF_DGST_SHIFT)
305 # define TLS1_PRF_SHA384 (SSL_MD_SHA384_IDX << TLS1_PRF_DGST_SHIFT)
306 # define TLS1_PRF_GOST94 (SSL_MD_GOST94_IDX << TLS1_PRF_DGST_SHIFT)
307 # define TLS1_PRF_GOST12_256 (SSL_MD_GOST12_256_IDX << TLS1_PRF_DGST_SHIFT)
308 # define TLS1_PRF_GOST12_512 (SSL_MD_GOST12_512_IDX << TLS1_PRF_DGST_SHIFT)
309 # define TLS1_PRF            (SSL_MD_MD5_SHA1_IDX << TLS1_PRF_DGST_SHIFT)
310
311 /*
312  * Stream MAC for GOST ciphersuites from cryptopro draft (currently this also
313  * goes into algorithm2)
314  */
315 # define TLS1_STREAM_MAC 0x10000
316 /*
317  * TLSTREE cipher/mac key derivation from draft-smyshlyaev-tls12-gost-suites
318  * (currently this also  goes into algorithm2)
319  */
320 # define TLS1_TLSTREE 0x20000
321
322 # define SSL_STRONG_MASK         0x0000001FU
323 # define SSL_DEFAULT_MASK        0X00000020U
324
325 # define SSL_STRONG_NONE         0x00000001U
326 # define SSL_LOW                 0x00000002U
327 # define SSL_MEDIUM              0x00000004U
328 # define SSL_HIGH                0x00000008U
329 # define SSL_FIPS                0x00000010U
330 # define SSL_NOT_DEFAULT         0x00000020U
331
332 /* we have used 0000003f - 26 bits left to go */
333
334 /* Flag used on OpenSSL ciphersuite ids to indicate they are for SSLv3+ */
335 # define SSL3_CK_CIPHERSUITE_FLAG                0x03000000
336
337 /* Check if an SSL structure is using DTLS */
338 # define SSL_IS_DTLS(s)  (s->method->ssl3_enc->enc_flags & SSL_ENC_FLAG_DTLS)
339
340 /* Check if we are using TLSv1.3 */
341 # define SSL_IS_TLS13(s) (!SSL_IS_DTLS(s) \
342                           && (s)->method->version >= TLS1_3_VERSION \
343                           && (s)->method->version != TLS_ANY_VERSION)
344
345 # define SSL_TREAT_AS_TLS13(s) \
346     (SSL_IS_TLS13(s) || (s)->early_data_state == SSL_EARLY_DATA_CONNECTING \
347      || (s)->early_data_state == SSL_EARLY_DATA_CONNECT_RETRY \
348      || (s)->early_data_state == SSL_EARLY_DATA_WRITING \
349      || (s)->early_data_state == SSL_EARLY_DATA_WRITE_RETRY \
350      || (s)->hello_retry_request == SSL_HRR_PENDING)
351
352 # define SSL_IS_FIRST_HANDSHAKE(S) ((s)->s3.tmp.finish_md_len == 0 \
353                                     || (s)->s3.tmp.peer_finish_md_len == 0)
354
355 /* See if we need explicit IV */
356 # define SSL_USE_EXPLICIT_IV(s)  \
357                 (s->method->ssl3_enc->enc_flags & SSL_ENC_FLAG_EXPLICIT_IV)
358 /*
359  * See if we use signature algorithms extension and signature algorithm
360  * before signatures.
361  */
362 # define SSL_USE_SIGALGS(s)      \
363                         (s->method->ssl3_enc->enc_flags & SSL_ENC_FLAG_SIGALGS)
364 /*
365  * Allow TLS 1.2 ciphersuites: applies to DTLS 1.2 as well as TLS 1.2: may
366  * apply to others in future.
367  */
368 # define SSL_USE_TLS1_2_CIPHERS(s)       \
369                 (s->method->ssl3_enc->enc_flags & SSL_ENC_FLAG_TLS1_2_CIPHERS)
370 /*
371  * Determine if a client can use TLS 1.2 ciphersuites: can't rely on method
372  * flags because it may not be set to correct version yet.
373  */
374 # define SSL_CLIENT_USE_TLS1_2_CIPHERS(s)        \
375     ((!SSL_IS_DTLS(s) && s->client_version >= TLS1_2_VERSION) || \
376      (SSL_IS_DTLS(s) && DTLS_VERSION_GE(s->client_version, DTLS1_2_VERSION)))
377 /*
378  * Determine if a client should send signature algorithms extension:
379  * as with TLS1.2 cipher we can't rely on method flags.
380  */
381 # define SSL_CLIENT_USE_SIGALGS(s)        \
382     SSL_CLIENT_USE_TLS1_2_CIPHERS(s)
383
384 # define IS_MAX_FRAGMENT_LENGTH_EXT_VALID(value) \
385     (((value) >= TLSEXT_max_fragment_length_512) && \
386      ((value) <= TLSEXT_max_fragment_length_4096))
387 # define USE_MAX_FRAGMENT_LENGTH_EXT(session) \
388     IS_MAX_FRAGMENT_LENGTH_EXT_VALID(session->ext.max_fragment_len_mode)
389 # define GET_MAX_FRAGMENT_LENGTH(session) \
390     (512U << (session->ext.max_fragment_len_mode - 1))
391
392 # define SSL_READ_ETM(s) (s->s3.flags & TLS1_FLAGS_ENCRYPT_THEN_MAC_READ)
393 # define SSL_WRITE_ETM(s) (s->s3.flags & TLS1_FLAGS_ENCRYPT_THEN_MAC_WRITE)
394
395 /* Mostly for SSLv3 */
396 # define SSL_PKEY_RSA            0
397 # define SSL_PKEY_RSA_PSS_SIGN   1
398 # define SSL_PKEY_DSA_SIGN       2
399 # define SSL_PKEY_ECC            3
400 # define SSL_PKEY_GOST01         4
401 # define SSL_PKEY_GOST12_256     5
402 # define SSL_PKEY_GOST12_512     6
403 # define SSL_PKEY_ED25519        7
404 # define SSL_PKEY_ED448          8
405 # define SSL_PKEY_NUM            9
406
407 # define SSL_ENC_DES_IDX         0
408 # define SSL_ENC_3DES_IDX        1
409 # define SSL_ENC_RC4_IDX         2
410 # define SSL_ENC_RC2_IDX         3
411 # define SSL_ENC_IDEA_IDX        4
412 # define SSL_ENC_NULL_IDX        5
413 # define SSL_ENC_AES128_IDX      6
414 # define SSL_ENC_AES256_IDX      7
415 # define SSL_ENC_CAMELLIA128_IDX 8
416 # define SSL_ENC_CAMELLIA256_IDX 9
417 # define SSL_ENC_GOST89_IDX      10
418 # define SSL_ENC_SEED_IDX        11
419 # define SSL_ENC_AES128GCM_IDX   12
420 # define SSL_ENC_AES256GCM_IDX   13
421 # define SSL_ENC_AES128CCM_IDX   14
422 # define SSL_ENC_AES256CCM_IDX   15
423 # define SSL_ENC_AES128CCM8_IDX  16
424 # define SSL_ENC_AES256CCM8_IDX  17
425 # define SSL_ENC_GOST8912_IDX    18
426 # define SSL_ENC_CHACHA_IDX      19
427 # define SSL_ENC_ARIA128GCM_IDX  20
428 # define SSL_ENC_ARIA256GCM_IDX  21
429 # define SSL_ENC_MAGMA_IDX       22
430 # define SSL_ENC_KUZNYECHIK_IDX  23
431 # define SSL_ENC_NUM_IDX         24
432
433 /*-
434  * SSL_kRSA <- RSA_ENC
435  * SSL_kDH  <- DH_ENC & (RSA_ENC | RSA_SIGN | DSA_SIGN)
436  * SSL_kDHE <- RSA_ENC | RSA_SIGN | DSA_SIGN
437  * SSL_aRSA <- RSA_ENC | RSA_SIGN
438  * SSL_aDSS <- DSA_SIGN
439  */
440
441 /*-
442 #define CERT_INVALID            0
443 #define CERT_PUBLIC_KEY         1
444 #define CERT_PRIVATE_KEY        2
445 */
446
447 /* Post-Handshake Authentication state */
448 typedef enum {
449     SSL_PHA_NONE = 0,
450     SSL_PHA_EXT_SENT,        /* client-side only: extension sent */
451     SSL_PHA_EXT_RECEIVED,    /* server-side only: extension received */
452     SSL_PHA_REQUEST_PENDING, /* server-side only: request pending */
453     SSL_PHA_REQUESTED        /* request received by client, or sent by server */
454 } SSL_PHA_STATE;
455
456 /* CipherSuite length. SSLv3 and all TLS versions. */
457 # define TLS_CIPHER_LEN 2
458 /* used to hold info on the particular ciphers used */
459 struct ssl_cipher_st {
460     uint32_t valid;
461     const char *name;           /* text name */
462     const char *stdname;        /* RFC name */
463     uint32_t id;                /* id, 4 bytes, first is version */
464     /*
465      * changed in 1.0.0: these four used to be portions of a single value
466      * 'algorithms'
467      */
468     uint32_t algorithm_mkey;    /* key exchange algorithm */
469     uint32_t algorithm_auth;    /* server authentication */
470     uint32_t algorithm_enc;     /* symmetric encryption */
471     uint32_t algorithm_mac;     /* symmetric authentication */
472     int min_tls;                /* minimum SSL/TLS protocol version */
473     int max_tls;                /* maximum SSL/TLS protocol version */
474     int min_dtls;               /* minimum DTLS protocol version */
475     int max_dtls;               /* maximum DTLS protocol version */
476     uint32_t algo_strength;     /* strength and export flags */
477     uint32_t algorithm2;        /* Extra flags */
478     int32_t strength_bits;      /* Number of bits really used */
479     uint32_t alg_bits;          /* Number of bits for algorithm */
480 };
481
482 /* Used to hold SSL/TLS functions */
483 struct ssl_method_st {
484     int version;
485     unsigned flags;
486     unsigned long mask;
487     int (*ssl_new) (SSL *s);
488     int (*ssl_clear) (SSL *s);
489     void (*ssl_free) (SSL *s);
490     int (*ssl_accept) (SSL *s);
491     int (*ssl_connect) (SSL *s);
492     int (*ssl_read) (SSL *s, void *buf, size_t len, size_t *readbytes);
493     int (*ssl_peek) (SSL *s, void *buf, size_t len, size_t *readbytes);
494     int (*ssl_write) (SSL *s, const void *buf, size_t len, size_t *written);
495     int (*ssl_shutdown) (SSL *s);
496     int (*ssl_renegotiate) (SSL *s);
497     int (*ssl_renegotiate_check) (SSL *s, int);
498     int (*ssl_read_bytes) (SSL *s, int type, int *recvd_type,
499                            unsigned char *buf, size_t len, int peek,
500                            size_t *readbytes);
501     int (*ssl_write_bytes) (SSL *s, int type, const void *buf_, size_t len,
502                             size_t *written);
503     int (*ssl_dispatch_alert) (SSL *s);
504     long (*ssl_ctrl) (SSL *s, int cmd, long larg, void *parg);
505     long (*ssl_ctx_ctrl) (SSL_CTX *ctx, int cmd, long larg, void *parg);
506     const SSL_CIPHER *(*get_cipher_by_char) (const unsigned char *ptr);
507     int (*put_cipher_by_char) (const SSL_CIPHER *cipher, WPACKET *pkt,
508                                size_t *len);
509     size_t (*ssl_pending) (const SSL *s);
510     int (*num_ciphers) (void);
511     const SSL_CIPHER *(*get_cipher) (unsigned ncipher);
512     long (*get_timeout) (void);
513     const struct ssl3_enc_method *ssl3_enc; /* Extra SSLv3/TLS stuff */
514     int (*ssl_version) (void);
515     long (*ssl_callback_ctrl) (SSL *s, int cb_id, void (*fp) (void));
516     long (*ssl_ctx_callback_ctrl) (SSL_CTX *s, int cb_id, void (*fp) (void));
517 };
518
519 /*
520  * Matches the length of PSK_MAX_PSK_LEN. We keep it the same value for
521  * consistency, even in the event of OPENSSL_NO_PSK being defined.
522  */
523 # define TLS13_MAX_RESUMPTION_PSK_LENGTH      256
524
525 /*-
526  * Lets make this into an ASN.1 type structure as follows
527  * SSL_SESSION_ID ::= SEQUENCE {
528  *      version                 INTEGER,        -- structure version number
529  *      SSLversion              INTEGER,        -- SSL version number
530  *      Cipher                  OCTET STRING,   -- the 3 byte cipher ID
531  *      Session_ID              OCTET STRING,   -- the Session ID
532  *      Master_key              OCTET STRING,   -- the master key
533  *      Key_Arg [ 0 ] IMPLICIT  OCTET STRING,   -- the optional Key argument
534  *      Time [ 1 ] EXPLICIT     INTEGER,        -- optional Start Time
535  *      Timeout [ 2 ] EXPLICIT  INTEGER,        -- optional Timeout ins seconds
536  *      Peer [ 3 ] EXPLICIT     X509,           -- optional Peer Certificate
537  *      Session_ID_context [ 4 ] EXPLICIT OCTET STRING,   -- the Session ID context
538  *      Verify_result [ 5 ] EXPLICIT INTEGER,   -- X509_V_... code for `Peer'
539  *      HostName [ 6 ] EXPLICIT OCTET STRING,   -- optional HostName from servername TLS extension
540  *      PSK_identity_hint [ 7 ] EXPLICIT OCTET STRING, -- optional PSK identity hint
541  *      PSK_identity [ 8 ] EXPLICIT OCTET STRING,  -- optional PSK identity
542  *      Ticket_lifetime_hint [9] EXPLICIT INTEGER, -- server's lifetime hint for session ticket
543  *      Ticket [10]             EXPLICIT OCTET STRING, -- session ticket (clients only)
544  *      Compression_meth [11]   EXPLICIT OCTET STRING, -- optional compression method
545  *      SRP_username [ 12 ] EXPLICIT OCTET STRING -- optional SRP username
546  *      flags [ 13 ] EXPLICIT INTEGER -- optional flags
547  *      }
548  * Look in ssl/ssl_asn1.c for more details
549  * I'm using EXPLICIT tags so I can read the damn things using asn1parse :-).
550  */
551 struct ssl_session_st {
552     int ssl_version;            /* what ssl version session info is being kept
553                                  * in here? */
554     size_t master_key_length;
555
556     /* TLSv1.3 early_secret used for external PSKs */
557     unsigned char early_secret[EVP_MAX_MD_SIZE];
558     /*
559      * For <=TLS1.2 this is the master_key. For TLS1.3 this is the resumption
560      * PSK
561      */
562     unsigned char master_key[TLS13_MAX_RESUMPTION_PSK_LENGTH];
563     /* session_id - valid? */
564     size_t session_id_length;
565     unsigned char session_id[SSL_MAX_SSL_SESSION_ID_LENGTH];
566     /*
567      * this is used to determine whether the session is being reused in the
568      * appropriate context. It is up to the application to set this, via
569      * SSL_new
570      */
571     size_t sid_ctx_length;
572     unsigned char sid_ctx[SSL_MAX_SID_CTX_LENGTH];
573 # ifndef OPENSSL_NO_PSK
574     char *psk_identity_hint;
575     char *psk_identity;
576 # endif
577     /*
578      * Used to indicate that session resumption is not allowed. Applications
579      * can also set this bit for a new session via not_resumable_session_cb
580      * to disable session caching and tickets.
581      */
582     int not_resumable;
583     /* This is the cert and type for the other end. */
584     X509 *peer;
585     int peer_type;
586     /* Certificate chain peer sent. */
587     STACK_OF(X509) *peer_chain;
588     /*
589      * when app_verify_callback accepts a session where the peer's
590      * certificate is not ok, we must remember the error for session reuse:
591      */
592     long verify_result;         /* only for servers */
593     CRYPTO_REF_COUNT references;
594     long timeout;
595     long time;
596     unsigned int compress_meth; /* Need to lookup the method */
597     const SSL_CIPHER *cipher;
598     unsigned long cipher_id;    /* when ASN.1 loaded, this needs to be used to
599                                  * load the 'cipher' structure */
600     CRYPTO_EX_DATA ex_data;     /* application specific data */
601     /*
602      * These are used to make removal of session-ids more efficient and to
603      * implement a maximum cache size.
604      */
605     struct ssl_session_st *prev, *next;
606
607     struct {
608         char *hostname;
609         /* RFC4507 info */
610         unsigned char *tick; /* Session ticket */
611         size_t ticklen;      /* Session ticket length */
612         /* Session lifetime hint in seconds */
613         unsigned long tick_lifetime_hint;
614         uint32_t tick_age_add;
615         /* Max number of bytes that can be sent as early data */
616         uint32_t max_early_data;
617         /* The ALPN protocol selected for this session */
618         unsigned char *alpn_selected;
619         size_t alpn_selected_len;
620         /*
621          * Maximum Fragment Length as per RFC 4366.
622          * If this value does not contain RFC 4366 allowed values (1-4) then
623          * either the Maximum Fragment Length Negotiation failed or was not
624          * performed at all.
625          */
626         uint8_t max_fragment_len_mode;
627     } ext;
628 # ifndef OPENSSL_NO_SRP
629     char *srp_username;
630 # endif
631     unsigned char *ticket_appdata;
632     size_t ticket_appdata_len;
633     uint32_t flags;
634     CRYPTO_RWLOCK *lock;
635 };
636
637 /* Extended master secret support */
638 # define SSL_SESS_FLAG_EXTMS             0x1
639
640 # ifndef OPENSSL_NO_SRP
641
642 typedef struct srp_ctx_st {
643     /* param for all the callbacks */
644     void *SRP_cb_arg;
645     /* set client Hello login callback */
646     int (*TLS_ext_srp_username_callback) (SSL *, int *, void *);
647     /* set SRP N/g param callback for verification */
648     int (*SRP_verify_param_callback) (SSL *, void *);
649     /* set SRP client passwd callback */
650     char *(*SRP_give_srp_client_pwd_callback) (SSL *, void *);
651     char *login;
652     BIGNUM *N, *g, *s, *B, *A;
653     BIGNUM *a, *b, *v;
654     char *info;
655     int strength;
656     unsigned long srp_Mask;
657 } SRP_CTX;
658
659 # endif
660
661 typedef enum {
662     SSL_EARLY_DATA_NONE = 0,
663     SSL_EARLY_DATA_CONNECT_RETRY,
664     SSL_EARLY_DATA_CONNECTING,
665     SSL_EARLY_DATA_WRITE_RETRY,
666     SSL_EARLY_DATA_WRITING,
667     SSL_EARLY_DATA_WRITE_FLUSH,
668     SSL_EARLY_DATA_UNAUTH_WRITING,
669     SSL_EARLY_DATA_FINISHED_WRITING,
670     SSL_EARLY_DATA_ACCEPT_RETRY,
671     SSL_EARLY_DATA_ACCEPTING,
672     SSL_EARLY_DATA_READ_RETRY,
673     SSL_EARLY_DATA_READING,
674     SSL_EARLY_DATA_FINISHED_READING
675 } SSL_EARLY_DATA_STATE;
676
677 /*
678  * We check that the amount of unreadable early data doesn't exceed
679  * max_early_data. max_early_data is given in plaintext bytes. However if it is
680  * unreadable then we only know the number of ciphertext bytes. We also don't
681  * know how much the overhead should be because it depends on the ciphersuite.
682  * We make a small allowance. We assume 5 records of actual data plus the end
683  * of early data alert record. Each record has a tag and a content type byte.
684  * The longest tag length we know of is EVP_GCM_TLS_TAG_LEN. We don't count the
685  * content of the alert record either which is 2 bytes.
686  */
687 # define EARLY_DATA_CIPHERTEXT_OVERHEAD ((6 * (EVP_GCM_TLS_TAG_LEN + 1)) + 2)
688
689 /*
690  * The allowance we have between the client's calculated ticket age and our own.
691  * We allow for 10 seconds (units are in ms). If a ticket is presented and the
692  * client's age calculation is different by more than this than our own then we
693  * do not allow that ticket for early_data.
694  */
695 # define TICKET_AGE_ALLOWANCE   (10 * 1000)
696
697 #define MAX_COMPRESSIONS_SIZE   255
698
699 struct ssl_comp_st {
700     int id;
701     const char *name;
702     COMP_METHOD *method;
703 };
704
705 typedef struct raw_extension_st {
706     /* Raw packet data for the extension */
707     PACKET data;
708     /* Set to 1 if the extension is present or 0 otherwise */
709     int present;
710     /* Set to 1 if we have already parsed the extension or 0 otherwise */
711     int parsed;
712     /* The type of this extension, i.e. a TLSEXT_TYPE_* value */
713     unsigned int type;
714     /* Track what order extensions are received in (0-based). */
715     size_t received_order;
716 } RAW_EXTENSION;
717
718 typedef struct {
719     unsigned int isv2;
720     unsigned int legacy_version;
721     unsigned char random[SSL3_RANDOM_SIZE];
722     size_t session_id_len;
723     unsigned char session_id[SSL_MAX_SSL_SESSION_ID_LENGTH];
724     size_t dtls_cookie_len;
725     unsigned char dtls_cookie[DTLS1_COOKIE_LENGTH];
726     PACKET ciphersuites;
727     size_t compressions_len;
728     unsigned char compressions[MAX_COMPRESSIONS_SIZE];
729     PACKET extensions;
730     size_t pre_proc_exts_len;
731     RAW_EXTENSION *pre_proc_exts;
732 } CLIENTHELLO_MSG;
733
734 /*
735  * Extension index values NOTE: Any updates to these defines should be mirrored
736  * with equivalent updates to ext_defs in extensions.c
737  */
738 typedef enum tlsext_index_en {
739     TLSEXT_IDX_renegotiate,
740     TLSEXT_IDX_server_name,
741     TLSEXT_IDX_max_fragment_length,
742     TLSEXT_IDX_srp,
743     TLSEXT_IDX_ec_point_formats,
744     TLSEXT_IDX_supported_groups,
745     TLSEXT_IDX_session_ticket,
746     TLSEXT_IDX_status_request,
747     TLSEXT_IDX_next_proto_neg,
748     TLSEXT_IDX_application_layer_protocol_negotiation,
749     TLSEXT_IDX_use_srtp,
750     TLSEXT_IDX_encrypt_then_mac,
751     TLSEXT_IDX_signed_certificate_timestamp,
752     TLSEXT_IDX_extended_master_secret,
753     TLSEXT_IDX_signature_algorithms_cert,
754     TLSEXT_IDX_post_handshake_auth,
755     TLSEXT_IDX_signature_algorithms,
756     TLSEXT_IDX_supported_versions,
757     TLSEXT_IDX_psk_kex_modes,
758     TLSEXT_IDX_key_share,
759     TLSEXT_IDX_cookie,
760     TLSEXT_IDX_cryptopro_bug,
761     TLSEXT_IDX_early_data,
762     TLSEXT_IDX_certificate_authorities,
763     TLSEXT_IDX_padding,
764     TLSEXT_IDX_psk,
765     /* Dummy index - must always be the last entry */
766     TLSEXT_IDX_num_builtins
767 } TLSEXT_INDEX;
768
769 DEFINE_LHASH_OF(SSL_SESSION);
770 /* Needed in ssl_cert.c */
771 DEFINE_LHASH_OF(X509_NAME);
772
773 # define TLSEXT_KEYNAME_LENGTH  16
774 # define TLSEXT_TICK_KEY_LENGTH 32
775
776 typedef struct ssl_ctx_ext_secure_st {
777     unsigned char tick_hmac_key[TLSEXT_TICK_KEY_LENGTH];
778     unsigned char tick_aes_key[TLSEXT_TICK_KEY_LENGTH];
779 } SSL_CTX_EXT_SECURE;
780
781 /*
782  * Helper function for HMAC
783  * The structure should be considered opaque, it will change once the low
784  * level deprecated calls are removed.  At that point it can be replaced
785  * by EVP_MAC_CTX and most of the functions converted to macros or inlined
786  * directly.
787  */
788 typedef struct ssl_hmac_st {
789     EVP_MAC_CTX *ctx;
790 # ifndef OPENSSL_NO_DEPRECATED_3_0
791     HMAC_CTX *old_ctx;
792 # endif
793 } SSL_HMAC;
794
795 SSL_HMAC *ssl_hmac_new(const SSL_CTX *ctx);
796 void ssl_hmac_free(SSL_HMAC *ctx);
797 # ifndef OPENSSL_NO_DEPRECATED_3_0
798 HMAC_CTX *ssl_hmac_get0_HMAC_CTX(SSL_HMAC *ctx);
799 # endif
800 EVP_MAC_CTX *ssl_hmac_get0_EVP_MAC_CTX(SSL_HMAC *ctx);
801 int ssl_hmac_init(SSL_HMAC *ctx, void *key, size_t len, char *md);
802 int ssl_hmac_update(SSL_HMAC *ctx, const unsigned char *data, size_t len);
803 int ssl_hmac_final(SSL_HMAC *ctx, unsigned char *md, size_t *len,
804                    size_t max_size);
805 size_t ssl_hmac_size(const SSL_HMAC *ctx);
806
807 struct ssl_ctx_st {
808     OPENSSL_CTX *libctx;
809
810     const SSL_METHOD *method;
811     STACK_OF(SSL_CIPHER) *cipher_list;
812     /* same as above but sorted for lookup */
813     STACK_OF(SSL_CIPHER) *cipher_list_by_id;
814     /* TLSv1.3 specific ciphersuites */
815     STACK_OF(SSL_CIPHER) *tls13_ciphersuites;
816     struct x509_store_st /* X509_STORE */ *cert_store;
817     LHASH_OF(SSL_SESSION) *sessions;
818     /*
819      * Most session-ids that will be cached, default is
820      * SSL_SESSION_CACHE_MAX_SIZE_DEFAULT. 0 is unlimited.
821      */
822     size_t session_cache_size;
823     struct ssl_session_st *session_cache_head;
824     struct ssl_session_st *session_cache_tail;
825     /*
826      * This can have one of 2 values, ored together, SSL_SESS_CACHE_CLIENT,
827      * SSL_SESS_CACHE_SERVER, Default is SSL_SESSION_CACHE_SERVER, which
828      * means only SSL_accept will cache SSL_SESSIONS.
829      */
830     uint32_t session_cache_mode;
831     /*
832      * If timeout is not 0, it is the default timeout value set when
833      * SSL_new() is called.  This has been put in to make life easier to set
834      * things up
835      */
836     long session_timeout;
837     /*
838      * If this callback is not null, it will be called each time a session id
839      * is added to the cache.  If this function returns 1, it means that the
840      * callback will do a SSL_SESSION_free() when it has finished using it.
841      * Otherwise, on 0, it means the callback has finished with it. If
842      * remove_session_cb is not null, it will be called when a session-id is
843      * removed from the cache.  After the call, OpenSSL will
844      * SSL_SESSION_free() it.
845      */
846     int (*new_session_cb) (struct ssl_st *ssl, SSL_SESSION *sess);
847     void (*remove_session_cb) (struct ssl_ctx_st *ctx, SSL_SESSION *sess);
848     SSL_SESSION *(*get_session_cb) (struct ssl_st *ssl,
849                                     const unsigned char *data, int len,
850                                     int *copy);
851     struct {
852         TSAN_QUALIFIER int sess_connect;       /* SSL new conn - started */
853         TSAN_QUALIFIER int sess_connect_renegotiate; /* SSL reneg - requested */
854         TSAN_QUALIFIER int sess_connect_good;  /* SSL new conne/reneg - finished */
855         TSAN_QUALIFIER int sess_accept;        /* SSL new accept - started */
856         TSAN_QUALIFIER int sess_accept_renegotiate; /* SSL reneg - requested */
857         TSAN_QUALIFIER int sess_accept_good;   /* SSL accept/reneg - finished */
858         TSAN_QUALIFIER int sess_miss;          /* session lookup misses */
859         TSAN_QUALIFIER int sess_timeout;       /* reuse attempt on timeouted session */
860         TSAN_QUALIFIER int sess_cache_full;    /* session removed due to full cache */
861         TSAN_QUALIFIER int sess_hit;           /* session reuse actually done */
862         TSAN_QUALIFIER int sess_cb_hit;        /* session-id that was not in
863                                                 * the cache was passed back via
864                                                 * the callback. This indicates
865                                                 * that the application is
866                                                 * supplying session-id's from
867                                                 * other processes - spooky
868                                                 * :-) */
869     } stats;
870
871     CRYPTO_REF_COUNT references;
872
873     /* if defined, these override the X509_verify_cert() calls */
874     int (*app_verify_callback) (X509_STORE_CTX *, void *);
875     void *app_verify_arg;
876     /*
877      * before OpenSSL 0.9.7, 'app_verify_arg' was ignored
878      * ('app_verify_callback' was called with just one argument)
879      */
880
881     /* Default password callback. */
882     pem_password_cb *default_passwd_callback;
883
884     /* Default password callback user data. */
885     void *default_passwd_callback_userdata;
886
887     /* get client cert callback */
888     int (*client_cert_cb) (SSL *ssl, X509 **x509, EVP_PKEY **pkey);
889
890     /* cookie generate callback */
891     int (*app_gen_cookie_cb) (SSL *ssl, unsigned char *cookie,
892                               unsigned int *cookie_len);
893
894     /* verify cookie callback */
895     int (*app_verify_cookie_cb) (SSL *ssl, const unsigned char *cookie,
896                                  unsigned int cookie_len);
897
898     /* TLS1.3 app-controlled cookie generate callback */
899     int (*gen_stateless_cookie_cb) (SSL *ssl, unsigned char *cookie,
900                                     size_t *cookie_len);
901
902     /* TLS1.3 verify app-controlled cookie callback */
903     int (*verify_stateless_cookie_cb) (SSL *ssl, const unsigned char *cookie,
904                                        size_t cookie_len);
905
906     CRYPTO_EX_DATA ex_data;
907
908     const EVP_MD *md5;          /* For SSLv3/TLSv1 'ssl3-md5' */
909     const EVP_MD *sha1;         /* For SSLv3/TLSv1 'ssl3-sha1' */
910
911     STACK_OF(X509) *extra_certs;
912     STACK_OF(SSL_COMP) *comp_methods; /* stack of SSL_COMP, SSLv3/TLSv1 */
913
914     /* Default values used when no per-SSL value is defined follow */
915
916     /* used if SSL's info_callback is NULL */
917     void (*info_callback) (const SSL *ssl, int type, int val);
918
919     /*
920      * What we put in certificate_authorities extension for TLS 1.3
921      * (ClientHello and CertificateRequest) or just client cert requests for
922      * earlier versions. If client_ca_names is populated then it is only used
923      * for client cert requests, and in preference to ca_names.
924      */
925     STACK_OF(X509_NAME) *ca_names;
926     STACK_OF(X509_NAME) *client_ca_names;
927
928     /*
929      * Default values to use in SSL structures follow (these are copied by
930      * SSL_new)
931      */
932
933     uint32_t options;
934     uint32_t mode;
935     int min_proto_version;
936     int max_proto_version;
937     size_t max_cert_list;
938
939     struct cert_st /* CERT */ *cert;
940     int read_ahead;
941
942     /* callback that allows applications to peek at protocol messages */
943     void (*msg_callback) (int write_p, int version, int content_type,
944                           const void *buf, size_t len, SSL *ssl, void *arg);
945     void *msg_callback_arg;
946
947     uint32_t verify_mode;
948     size_t sid_ctx_length;
949     unsigned char sid_ctx[SSL_MAX_SID_CTX_LENGTH];
950     /* called 'verify_callback' in the SSL */
951     int (*default_verify_callback) (int ok, X509_STORE_CTX *ctx);
952
953     /* Default generate session ID callback. */
954     GEN_SESSION_CB generate_session_id;
955
956     X509_VERIFY_PARAM *param;
957
958     int quiet_shutdown;
959
960 # ifndef OPENSSL_NO_CT
961     CTLOG_STORE *ctlog_store;   /* CT Log Store */
962     /*
963      * Validates that the SCTs (Signed Certificate Timestamps) are sufficient.
964      * If they are not, the connection should be aborted.
965      */
966     ssl_ct_validation_cb ct_validation_callback;
967     void *ct_validation_callback_arg;
968 # endif
969
970     /*
971      * If we're using more than one pipeline how should we divide the data
972      * up between the pipes?
973      */
974     size_t split_send_fragment;
975     /*
976      * Maximum amount of data to send in one fragment. actual record size can
977      * be more than this due to padding and MAC overheads.
978      */
979     size_t max_send_fragment;
980
981     /* Up to how many pipelines should we use? If 0 then 1 is assumed */
982     size_t max_pipelines;
983
984     /* The default read buffer length to use (0 means not set) */
985     size_t default_read_buf_len;
986
987 # ifndef OPENSSL_NO_ENGINE
988     /*
989      * Engine to pass requests for client certs to
990      */
991     ENGINE *client_cert_engine;
992 # endif
993
994     /* ClientHello callback.  Mostly for extensions, but not entirely. */
995     SSL_client_hello_cb_fn client_hello_cb;
996     void *client_hello_cb_arg;
997
998     /* TLS extensions. */
999     struct {
1000         /* TLS extensions servername callback */
1001         int (*servername_cb) (SSL *, int *, void *);
1002         void *servername_arg;
1003         /* RFC 4507 session ticket keys */
1004         unsigned char tick_key_name[TLSEXT_KEYNAME_LENGTH];
1005         SSL_CTX_EXT_SECURE *secure;
1006 # ifndef OPENSSL_NO_DEPRECATED_3_0
1007         /* Callback to support customisation of ticket key setting */
1008         int (*ticket_key_cb) (SSL *ssl,
1009                               unsigned char *name, unsigned char *iv,
1010                               EVP_CIPHER_CTX *ectx, HMAC_CTX *hctx, int enc);
1011 #endif
1012         int (*ticket_key_evp_cb) (SSL *ssl,
1013                                   unsigned char *name, unsigned char *iv,
1014                                   EVP_CIPHER_CTX *ectx, EVP_MAC_CTX *hctx,
1015                                   int enc);
1016
1017         /* certificate status request info */
1018         /* Callback for status request */
1019         int (*status_cb) (SSL *ssl, void *arg);
1020         void *status_arg;
1021         /* ext status type used for CSR extension (OCSP Stapling) */
1022         int status_type;
1023         /* RFC 4366 Maximum Fragment Length Negotiation */
1024         uint8_t max_fragment_len_mode;
1025
1026 # ifndef OPENSSL_NO_EC
1027         /* EC extension values inherited by SSL structure */
1028         size_t ecpointformats_len;
1029         unsigned char *ecpointformats;
1030 # endif                         /* OPENSSL_NO_EC */
1031
1032         size_t supportedgroups_len;
1033         uint16_t *supportedgroups;
1034
1035         /*
1036          * ALPN information (we are in the process of transitioning from NPN to
1037          * ALPN.)
1038          */
1039
1040         /*-
1041          * For a server, this contains a callback function that allows the
1042          * server to select the protocol for the connection.
1043          *   out: on successful return, this must point to the raw protocol
1044          *        name (without the length prefix).
1045          *   outlen: on successful return, this contains the length of |*out|.
1046          *   in: points to the client's list of supported protocols in
1047          *       wire-format.
1048          *   inlen: the length of |in|.
1049          */
1050         int (*alpn_select_cb) (SSL *s,
1051                                const unsigned char **out,
1052                                unsigned char *outlen,
1053                                const unsigned char *in,
1054                                unsigned int inlen, void *arg);
1055         void *alpn_select_cb_arg;
1056
1057         /*
1058          * For a client, this contains the list of supported protocols in wire
1059          * format.
1060          */
1061         unsigned char *alpn;
1062         size_t alpn_len;
1063
1064 # ifndef OPENSSL_NO_NEXTPROTONEG
1065         /* Next protocol negotiation information */
1066
1067         /*
1068          * For a server, this contains a callback function by which the set of
1069          * advertised protocols can be provided.
1070          */
1071         SSL_CTX_npn_advertised_cb_func npn_advertised_cb;
1072         void *npn_advertised_cb_arg;
1073         /*
1074          * For a client, this contains a callback function that selects the next
1075          * protocol from the list provided by the server.
1076          */
1077         SSL_CTX_npn_select_cb_func npn_select_cb;
1078         void *npn_select_cb_arg;
1079 # endif
1080
1081         unsigned char cookie_hmac_key[SHA256_DIGEST_LENGTH];
1082     } ext;
1083
1084 # ifndef OPENSSL_NO_PSK
1085     SSL_psk_client_cb_func psk_client_callback;
1086     SSL_psk_server_cb_func psk_server_callback;
1087 # endif
1088     SSL_psk_find_session_cb_func psk_find_session_cb;
1089     SSL_psk_use_session_cb_func psk_use_session_cb;
1090
1091 # ifndef OPENSSL_NO_SRP
1092     SRP_CTX srp_ctx;            /* ctx for SRP authentication */
1093 # endif
1094
1095     /* Shared DANE context */
1096     struct dane_ctx_st dane;
1097
1098 # ifndef OPENSSL_NO_SRTP
1099     /* SRTP profiles we are willing to do from RFC 5764 */
1100     STACK_OF(SRTP_PROTECTION_PROFILE) *srtp_profiles;
1101 # endif
1102     /*
1103      * Callback for disabling session caching and ticket support on a session
1104      * basis, depending on the chosen cipher.
1105      */
1106     int (*not_resumable_session_cb) (SSL *ssl, int is_forward_secure);
1107
1108     CRYPTO_RWLOCK *lock;
1109
1110     /*
1111      * Callback for logging key material for use with debugging tools like
1112      * Wireshark. The callback should log `line` followed by a newline.
1113      */
1114     SSL_CTX_keylog_cb_func keylog_callback;
1115
1116     /*
1117      * The maximum number of bytes advertised in session tickets that can be
1118      * sent as early data.
1119      */
1120     uint32_t max_early_data;
1121
1122     /*
1123      * The maximum number of bytes of early data that a server will tolerate
1124      * (which should be at least as much as max_early_data).
1125      */
1126     uint32_t recv_max_early_data;
1127
1128     /* TLS1.3 padding callback */
1129     size_t (*record_padding_cb)(SSL *s, int type, size_t len, void *arg);
1130     void *record_padding_arg;
1131     size_t block_padding;
1132
1133     /* Session ticket appdata */
1134     SSL_CTX_generate_session_ticket_fn generate_ticket_cb;
1135     SSL_CTX_decrypt_session_ticket_fn decrypt_ticket_cb;
1136     void *ticket_cb_data;
1137
1138     /* The number of TLS1.3 tickets to automatically send */
1139     size_t num_tickets;
1140
1141     /* Callback to determine if early_data is acceptable or not */
1142     SSL_allow_early_data_cb_fn allow_early_data_cb;
1143     void *allow_early_data_cb_data;
1144
1145     /* Do we advertise Post-handshake auth support? */
1146     int pha_enabled;
1147
1148     /* Callback for SSL async handling */
1149     SSL_async_callback_fn async_cb;
1150     void *async_cb_arg;
1151
1152     char *propq;
1153
1154     const EVP_CIPHER *ssl_cipher_methods[SSL_ENC_NUM_IDX];
1155     const EVP_MD *ssl_digest_methods[SSL_MD_NUM_IDX];
1156     size_t ssl_mac_secret_size[SSL_MD_NUM_IDX];
1157 };
1158
1159 typedef struct cert_pkey_st CERT_PKEY;
1160
1161 struct ssl_st {
1162     /*
1163      * protocol version (one of SSL2_VERSION, SSL3_VERSION, TLS1_VERSION,
1164      * DTLS1_VERSION)
1165      */
1166     int version;
1167     /* SSLv3 */
1168     const SSL_METHOD *method;
1169     /*
1170      * There are 2 BIO's even though they are normally both the same.  This
1171      * is so data can be read and written to different handlers
1172      */
1173     /* used by SSL_read */
1174     BIO *rbio;
1175     /* used by SSL_write */
1176     BIO *wbio;
1177     /* used during session-id reuse to concatenate messages */
1178     BIO *bbio;
1179     /*
1180      * This holds a variable that indicates what we were doing when a 0 or -1
1181      * is returned.  This is needed for non-blocking IO so we know what
1182      * request needs re-doing when in SSL_accept or SSL_connect
1183      */
1184     int rwstate;
1185     int (*handshake_func) (SSL *);
1186     /*
1187      * Imagine that here's a boolean member "init" that is switched as soon
1188      * as SSL_set_{accept/connect}_state is called for the first time, so
1189      * that "state" and "handshake_func" are properly initialized.  But as
1190      * handshake_func is == 0 until then, we use this test instead of an
1191      * "init" member.
1192      */
1193     /* are we the server side? */
1194     int server;
1195     /*
1196      * Generate a new session or reuse an old one.
1197      * NB: For servers, the 'new' session may actually be a previously
1198      * cached session or even the previous session unless
1199      * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is set
1200      */
1201     int new_session;
1202     /* don't send shutdown packets */
1203     int quiet_shutdown;
1204     /* we have shut things down, 0x01 sent, 0x02 for received */
1205     int shutdown;
1206     /* where we are */
1207     OSSL_STATEM statem;
1208     SSL_EARLY_DATA_STATE early_data_state;
1209     BUF_MEM *init_buf;          /* buffer used during init */
1210     void *init_msg;             /* pointer to handshake message body, set by
1211                                  * ssl3_get_message() */
1212     size_t init_num;               /* amount read/written */
1213     size_t init_off;               /* amount read/written */
1214
1215     struct {
1216         long flags;
1217         size_t read_mac_secret_size;
1218         unsigned char read_mac_secret[EVP_MAX_MD_SIZE];
1219         size_t write_mac_secret_size;
1220         unsigned char write_mac_secret[EVP_MAX_MD_SIZE];
1221         unsigned char server_random[SSL3_RANDOM_SIZE];
1222         unsigned char client_random[SSL3_RANDOM_SIZE];
1223         /* flags for countermeasure against known-IV weakness */
1224         int need_empty_fragments;
1225         int empty_fragment_done;
1226         /* used during startup, digest all incoming/outgoing packets */
1227         BIO *handshake_buffer;
1228         /*
1229          * When handshake digest is determined, buffer is hashed and
1230          * freed and MD_CTX for the required digest is stored here.
1231          */
1232         EVP_MD_CTX *handshake_dgst;
1233         /*
1234          * Set whenever an expected ChangeCipherSpec message is processed.
1235          * Unset when the peer's Finished message is received.
1236          * Unexpected ChangeCipherSpec messages trigger a fatal alert.
1237          */
1238         int change_cipher_spec;
1239         int warn_alert;
1240         int fatal_alert;
1241         /*
1242          * we allow one fatal and one warning alert to be outstanding, send close
1243          * alert via the warning alert
1244          */
1245         int alert_dispatch;
1246         unsigned char send_alert[2];
1247         /*
1248          * This flag is set when we should renegotiate ASAP, basically when there
1249          * is no more data in the read or write buffers
1250          */
1251         int renegotiate;
1252         int total_renegotiations;
1253         int num_renegotiations;
1254         int in_read_app_data;
1255         struct {
1256             /* actually only need to be 16+20 for SSLv3 and 12 for TLS */
1257             unsigned char finish_md[EVP_MAX_MD_SIZE * 2];
1258             size_t finish_md_len;
1259             unsigned char peer_finish_md[EVP_MAX_MD_SIZE * 2];
1260             size_t peer_finish_md_len;
1261             size_t message_size;
1262             int message_type;
1263             /* used to hold the new cipher we are going to use */
1264             const SSL_CIPHER *new_cipher;
1265 # if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
1266             EVP_PKEY *pkey;         /* holds short lived DH/ECDH key */
1267 # endif
1268             /* used for certificate requests */
1269             int cert_req;
1270             /* Certificate types in certificate request message. */
1271             uint8_t *ctype;
1272             size_t ctype_len;
1273             /* Certificate authorities list peer sent */
1274             STACK_OF(X509_NAME) *peer_ca_names;
1275             size_t key_block_length;
1276             unsigned char *key_block;
1277             const EVP_CIPHER *new_sym_enc;
1278             const EVP_MD *new_hash;
1279             int new_mac_pkey_type;
1280             size_t new_mac_secret_size;
1281 # ifndef OPENSSL_NO_COMP
1282             const SSL_COMP *new_compression;
1283 # else
1284             char *new_compression;
1285 # endif
1286             int cert_request;
1287             /* Raw values of the cipher list from a client */
1288             unsigned char *ciphers_raw;
1289             size_t ciphers_rawlen;
1290             /* Temporary storage for premaster secret */
1291             unsigned char *pms;
1292             size_t pmslen;
1293 # ifndef OPENSSL_NO_PSK
1294             /* Temporary storage for PSK key */
1295             unsigned char *psk;
1296             size_t psklen;
1297 # endif
1298             /* Signature algorithm we actually use */
1299             const struct sigalg_lookup_st *sigalg;
1300             /* Pointer to certificate we use */
1301             CERT_PKEY *cert;
1302             /*
1303              * signature algorithms peer reports: e.g. supported signature
1304              * algorithms extension for server or as part of a certificate
1305              * request for client.
1306              * Keep track of the algorithms for TLS and X.509 usage separately.
1307              */
1308             uint16_t *peer_sigalgs;
1309             uint16_t *peer_cert_sigalgs;
1310             /* Size of above arrays */
1311             size_t peer_sigalgslen;
1312             size_t peer_cert_sigalgslen;
1313             /* Sigalg peer actually uses */
1314             const struct sigalg_lookup_st *peer_sigalg;
1315             /*
1316              * Set if corresponding CERT_PKEY can be used with current
1317              * SSL session: e.g. appropriate curve, signature algorithms etc.
1318              * If zero it can't be used at all.
1319              */
1320             uint32_t valid_flags[SSL_PKEY_NUM];
1321             /*
1322              * For servers the following masks are for the key and auth algorithms
1323              * that are supported by the certs below. For clients they are masks of
1324              * *disabled* algorithms based on the current session.
1325              */
1326             uint32_t mask_k;
1327             uint32_t mask_a;
1328             /*
1329              * The following are used by the client to see if a cipher is allowed or
1330              * not.  It contains the minimum and maximum version the client's using
1331              * based on what it knows so far.
1332              */
1333             int min_ver;
1334             int max_ver;
1335         } tmp;
1336
1337         /* Connection binding to prevent renegotiation attacks */
1338         unsigned char previous_client_finished[EVP_MAX_MD_SIZE];
1339         size_t previous_client_finished_len;
1340         unsigned char previous_server_finished[EVP_MAX_MD_SIZE];
1341         size_t previous_server_finished_len;
1342         int send_connection_binding; /* TODOEKR */
1343
1344 # ifndef OPENSSL_NO_NEXTPROTONEG
1345         /*
1346          * Set if we saw the Next Protocol Negotiation extension from our peer.
1347          */
1348         int npn_seen;
1349 # endif
1350
1351         /*
1352          * ALPN information (we are in the process of transitioning from NPN to
1353          * ALPN.)
1354          */
1355
1356         /*
1357          * In a server these point to the selected ALPN protocol after the
1358          * ClientHello has been processed. In a client these contain the protocol
1359          * that the server selected once the ServerHello has been processed.
1360          */
1361         unsigned char *alpn_selected;
1362         size_t alpn_selected_len;
1363         /* used by the server to know what options were proposed */
1364         unsigned char *alpn_proposed;
1365         size_t alpn_proposed_len;
1366         /* used by the client to know if it actually sent alpn */
1367         int alpn_sent;
1368
1369 # ifndef OPENSSL_NO_EC
1370         /*
1371          * This is set to true if we believe that this is a version of Safari
1372          * running on OS X 10.6 or newer. We wish to know this because Safari on
1373          * 10.8 .. 10.8.3 has broken ECDHE-ECDSA support.
1374          */
1375         char is_probably_safari;
1376 # endif                         /* !OPENSSL_NO_EC */
1377
1378         /* For clients: peer temporary key */
1379 # if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
1380         /* The group_id for the DH/ECDH key */
1381         uint16_t group_id;
1382         EVP_PKEY *peer_tmp;
1383 # endif
1384
1385     } s3;
1386
1387     struct dtls1_state_st *d1;  /* DTLSv1 variables */
1388     /* callback that allows applications to peek at protocol messages */
1389     void (*msg_callback) (int write_p, int version, int content_type,
1390                           const void *buf, size_t len, SSL *ssl, void *arg);
1391     void *msg_callback_arg;
1392     int hit;                    /* reusing a previous session */
1393     X509_VERIFY_PARAM *param;
1394     /* Per connection DANE state */
1395     SSL_DANE dane;
1396     /* crypto */
1397     STACK_OF(SSL_CIPHER) *peer_ciphers;
1398     STACK_OF(SSL_CIPHER) *cipher_list;
1399     STACK_OF(SSL_CIPHER) *cipher_list_by_id;
1400     /* TLSv1.3 specific ciphersuites */
1401     STACK_OF(SSL_CIPHER) *tls13_ciphersuites;
1402     /*
1403      * These are the ones being used, the ones in SSL_SESSION are the ones to
1404      * be 'copied' into these ones
1405      */
1406     uint32_t mac_flags;
1407     /*
1408      * The TLS1.3 secrets.
1409      */
1410     unsigned char early_secret[EVP_MAX_MD_SIZE];
1411     unsigned char handshake_secret[EVP_MAX_MD_SIZE];
1412     unsigned char master_secret[EVP_MAX_MD_SIZE];
1413     unsigned char resumption_master_secret[EVP_MAX_MD_SIZE];
1414     unsigned char client_finished_secret[EVP_MAX_MD_SIZE];
1415     unsigned char server_finished_secret[EVP_MAX_MD_SIZE];
1416     unsigned char server_finished_hash[EVP_MAX_MD_SIZE];
1417     unsigned char handshake_traffic_hash[EVP_MAX_MD_SIZE];
1418     unsigned char client_app_traffic_secret[EVP_MAX_MD_SIZE];
1419     unsigned char server_app_traffic_secret[EVP_MAX_MD_SIZE];
1420     unsigned char exporter_master_secret[EVP_MAX_MD_SIZE];
1421     unsigned char early_exporter_master_secret[EVP_MAX_MD_SIZE];
1422     EVP_CIPHER_CTX *enc_read_ctx; /* cryptographic state */
1423     unsigned char read_iv[EVP_MAX_IV_LENGTH]; /* TLSv1.3 static read IV */
1424     EVP_MD_CTX *read_hash;      /* used for mac generation */
1425     COMP_CTX *compress;         /* compression */
1426     COMP_CTX *expand;           /* uncompress */
1427     EVP_CIPHER_CTX *enc_write_ctx; /* cryptographic state */
1428     unsigned char write_iv[EVP_MAX_IV_LENGTH]; /* TLSv1.3 static write IV */
1429     EVP_MD_CTX *write_hash;     /* used for mac generation */
1430     /* session info */
1431     /* client cert? */
1432     /* This is used to hold the server certificate used */
1433     struct cert_st /* CERT */ *cert;
1434
1435     /*
1436      * The hash of all messages prior to the CertificateVerify, and the length
1437      * of that hash.
1438      */
1439     unsigned char cert_verify_hash[EVP_MAX_MD_SIZE];
1440     size_t cert_verify_hash_len;
1441
1442     /* Flag to indicate whether we should send a HelloRetryRequest or not */
1443     enum {SSL_HRR_NONE = 0, SSL_HRR_PENDING, SSL_HRR_COMPLETE}
1444         hello_retry_request;
1445
1446     /*
1447      * the session_id_context is used to ensure sessions are only reused in
1448      * the appropriate context
1449      */
1450     size_t sid_ctx_length;
1451     unsigned char sid_ctx[SSL_MAX_SID_CTX_LENGTH];
1452     /* This can also be in the session once a session is established */
1453     SSL_SESSION *session;
1454     /* TLSv1.3 PSK session */
1455     SSL_SESSION *psksession;
1456     unsigned char *psksession_id;
1457     size_t psksession_id_len;
1458     /* Default generate session ID callback. */
1459     GEN_SESSION_CB generate_session_id;
1460     /*
1461      * The temporary TLSv1.3 session id. This isn't really a session id at all
1462      * but is a random value sent in the legacy session id field.
1463      */
1464     unsigned char tmp_session_id[SSL_MAX_SSL_SESSION_ID_LENGTH];
1465     size_t tmp_session_id_len;
1466     /* Used in SSL3 */
1467     /*
1468      * 0 don't care about verify failure.
1469      * 1 fail if verify fails
1470      */
1471     uint32_t verify_mode;
1472     /* fail if callback returns 0 */
1473     int (*verify_callback) (int ok, X509_STORE_CTX *ctx);
1474     /* optional informational callback */
1475     void (*info_callback) (const SSL *ssl, int type, int val);
1476     /* error bytes to be written */
1477     int error;
1478     /* actual code */
1479     int error_code;
1480 # ifndef OPENSSL_NO_PSK
1481     SSL_psk_client_cb_func psk_client_callback;
1482     SSL_psk_server_cb_func psk_server_callback;
1483 # endif
1484     SSL_psk_find_session_cb_func psk_find_session_cb;
1485     SSL_psk_use_session_cb_func psk_use_session_cb;
1486
1487     SSL_CTX *ctx;
1488     /* Verified chain of peer */
1489     STACK_OF(X509) *verified_chain;
1490     long verify_result;
1491     /* extra application data */
1492     CRYPTO_EX_DATA ex_data;
1493     /*
1494      * What we put in certificate_authorities extension for TLS 1.3
1495      * (ClientHello and CertificateRequest) or just client cert requests for
1496      * earlier versions. If client_ca_names is populated then it is only used
1497      * for client cert requests, and in preference to ca_names.
1498      */
1499     STACK_OF(X509_NAME) *ca_names;
1500     STACK_OF(X509_NAME) *client_ca_names;
1501     CRYPTO_REF_COUNT references;
1502     /* protocol behaviour */
1503     uint32_t options;
1504     /* API behaviour */
1505     uint32_t mode;
1506     int min_proto_version;
1507     int max_proto_version;
1508     size_t max_cert_list;
1509     int first_packet;
1510     /*
1511      * What was passed in ClientHello.legacy_version. Used for RSA pre-master
1512      * secret and SSLv3/TLS (<=1.2) rollback check
1513      */
1514     int client_version;
1515     /*
1516      * If we're using more than one pipeline how should we divide the data
1517      * up between the pipes?
1518      */
1519     size_t split_send_fragment;
1520     /*
1521      * Maximum amount of data to send in one fragment. actual record size can
1522      * be more than this due to padding and MAC overheads.
1523      */
1524     size_t max_send_fragment;
1525     /* Up to how many pipelines should we use? If 0 then 1 is assumed */
1526     size_t max_pipelines;
1527
1528     struct {
1529         /* Built-in extension flags */
1530         uint8_t extflags[TLSEXT_IDX_num_builtins];
1531         /* TLS extension debug callback */
1532         void (*debug_cb)(SSL *s, int client_server, int type,
1533                          const unsigned char *data, int len, void *arg);
1534         void *debug_arg;
1535         char *hostname;
1536         /* certificate status request info */
1537         /* Status type or -1 if no status type */
1538         int status_type;
1539         /* Raw extension data, if seen */
1540         unsigned char *scts;
1541         /* Length of raw extension data, if seen */
1542         uint16_t scts_len;
1543         /* Expect OCSP CertificateStatus message */
1544         int status_expected;
1545
1546         struct {
1547             /* OCSP status request only */
1548             STACK_OF(OCSP_RESPID) *ids;
1549             X509_EXTENSIONS *exts;
1550             /* OCSP response received or to be sent */
1551             unsigned char *resp;
1552             size_t resp_len;
1553         } ocsp;
1554
1555         /* RFC4507 session ticket expected to be received or sent */
1556         int ticket_expected;
1557         /* TLS 1.3 tickets requested by the application. */
1558         int extra_tickets_expected;
1559 # ifndef OPENSSL_NO_EC
1560         size_t ecpointformats_len;
1561         /* our list */
1562         unsigned char *ecpointformats;
1563
1564         size_t peer_ecpointformats_len;
1565         /* peer's list */
1566         unsigned char *peer_ecpointformats;
1567 # endif                         /* OPENSSL_NO_EC */
1568         size_t supportedgroups_len;
1569         /* our list */
1570         uint16_t *supportedgroups;
1571
1572         size_t peer_supportedgroups_len;
1573          /* peer's list */
1574         uint16_t *peer_supportedgroups;
1575
1576         /* TLS Session Ticket extension override */
1577         TLS_SESSION_TICKET_EXT *session_ticket;
1578         /* TLS Session Ticket extension callback */
1579         tls_session_ticket_ext_cb_fn session_ticket_cb;
1580         void *session_ticket_cb_arg;
1581         /* TLS pre-shared secret session resumption */
1582         tls_session_secret_cb_fn session_secret_cb;
1583         void *session_secret_cb_arg;
1584         /*
1585          * For a client, this contains the list of supported protocols in wire
1586          * format.
1587          */
1588         unsigned char *alpn;
1589         size_t alpn_len;
1590         /*
1591          * Next protocol negotiation. For the client, this is the protocol that
1592          * we sent in NextProtocol and is set when handling ServerHello
1593          * extensions. For a server, this is the client's selected_protocol from
1594          * NextProtocol and is set when handling the NextProtocol message, before
1595          * the Finished message.
1596          */
1597         unsigned char *npn;
1598         size_t npn_len;
1599
1600         /* The available PSK key exchange modes */
1601         int psk_kex_mode;
1602
1603         /* Set to one if we have negotiated ETM */
1604         int use_etm;
1605
1606         /* Are we expecting to receive early data? */
1607         int early_data;
1608         /* Is the session suitable for early data? */
1609         int early_data_ok;
1610
1611         /* May be sent by a server in HRR. Must be echoed back in ClientHello */
1612         unsigned char *tls13_cookie;
1613         size_t tls13_cookie_len;
1614         /* Have we received a cookie from the client? */
1615         int cookieok;
1616
1617         /*
1618          * Maximum Fragment Length as per RFC 4366.
1619          * If this member contains one of the allowed values (1-4)
1620          * then we should include Maximum Fragment Length Negotiation
1621          * extension in Client Hello.
1622          * Please note that value of this member does not have direct
1623          * effect. The actual (binding) value is stored in SSL_SESSION,
1624          * as this extension is optional on server side.
1625          */
1626         uint8_t max_fragment_len_mode;
1627
1628         /*
1629          * On the client side the number of ticket identities we sent in the
1630          * ClientHello. On the server side the identity of the ticket we
1631          * selected.
1632          */
1633         int tick_identity;
1634     } ext;
1635
1636     /*
1637      * Parsed form of the ClientHello, kept around across client_hello_cb
1638      * calls.
1639      */
1640     CLIENTHELLO_MSG *clienthello;
1641
1642     /*-
1643      * no further mod of servername
1644      * 0 : call the servername extension callback.
1645      * 1 : prepare 2, allow last ack just after in server callback.
1646      * 2 : don't call servername callback, no ack in server hello
1647      */
1648     int servername_done;
1649 # ifndef OPENSSL_NO_CT
1650     /*
1651      * Validates that the SCTs (Signed Certificate Timestamps) are sufficient.
1652      * If they are not, the connection should be aborted.
1653      */
1654     ssl_ct_validation_cb ct_validation_callback;
1655     /* User-supplied argument that is passed to the ct_validation_callback */
1656     void *ct_validation_callback_arg;
1657     /*
1658      * Consolidated stack of SCTs from all sources.
1659      * Lazily populated by CT_get_peer_scts(SSL*)
1660      */
1661     STACK_OF(SCT) *scts;
1662     /* Have we attempted to find/parse SCTs yet? */
1663     int scts_parsed;
1664 # endif
1665     SSL_CTX *session_ctx;       /* initial ctx, used to store sessions */
1666 # ifndef OPENSSL_NO_SRTP
1667     /* What we'll do */
1668     STACK_OF(SRTP_PROTECTION_PROFILE) *srtp_profiles;
1669     /* What's been chosen */
1670     SRTP_PROTECTION_PROFILE *srtp_profile;
1671 # endif
1672     /*-
1673      * 1 if we are renegotiating.
1674      * 2 if we are a server and are inside a handshake
1675      * (i.e. not just sending a HelloRequest)
1676      */
1677     int renegotiate;
1678     /* If sending a KeyUpdate is pending */
1679     int key_update;
1680     /* Post-handshake authentication state */
1681     SSL_PHA_STATE post_handshake_auth;
1682     int pha_enabled;
1683     uint8_t* pha_context;
1684     size_t pha_context_len;
1685     int certreqs_sent;
1686     EVP_MD_CTX *pha_dgst; /* this is just the digest through ClientFinished */
1687
1688 # ifndef OPENSSL_NO_SRP
1689     /* ctx for SRP authentication */
1690     SRP_CTX srp_ctx;
1691 # endif
1692     /*
1693      * Callback for disabling session caching and ticket support on a session
1694      * basis, depending on the chosen cipher.
1695      */
1696     int (*not_resumable_session_cb) (SSL *ssl, int is_forward_secure);
1697     RECORD_LAYER rlayer;
1698     /* Default password callback. */
1699     pem_password_cb *default_passwd_callback;
1700     /* Default password callback user data. */
1701     void *default_passwd_callback_userdata;
1702     /* Async Job info */
1703     ASYNC_JOB *job;
1704     ASYNC_WAIT_CTX *waitctx;
1705     size_t asyncrw;
1706
1707     /*
1708      * The maximum number of bytes advertised in session tickets that can be
1709      * sent as early data.
1710      */
1711     uint32_t max_early_data;
1712     /*
1713      * The maximum number of bytes of early data that a server will tolerate
1714      * (which should be at least as much as max_early_data).
1715      */
1716     uint32_t recv_max_early_data;
1717
1718     /*
1719      * The number of bytes of early data received so far. If we accepted early
1720      * data then this is a count of the plaintext bytes. If we rejected it then
1721      * this is a count of the ciphertext bytes.
1722      */
1723     uint32_t early_data_count;
1724
1725     /* TLS1.3 padding callback */
1726     size_t (*record_padding_cb)(SSL *s, int type, size_t len, void *arg);
1727     void *record_padding_arg;
1728     size_t block_padding;
1729
1730     CRYPTO_RWLOCK *lock;
1731
1732     /* The number of TLS1.3 tickets to automatically send */
1733     size_t num_tickets;
1734     /* The number of TLS1.3 tickets actually sent so far */
1735     size_t sent_tickets;
1736     /* The next nonce value to use when we send a ticket on this connection */
1737     uint64_t next_ticket_nonce;
1738
1739     /* Callback to determine if early_data is acceptable or not */
1740     SSL_allow_early_data_cb_fn allow_early_data_cb;
1741     void *allow_early_data_cb_data;
1742
1743     /* Callback for SSL async handling */
1744     SSL_async_callback_fn async_cb;
1745     void *async_cb_arg;
1746
1747     /*
1748      * Signature algorithms shared by client and server: cached because these
1749      * are used most often.
1750      */
1751     const struct sigalg_lookup_st **shared_sigalgs;
1752     size_t shared_sigalgslen;
1753 };
1754
1755 /*
1756  * Structure containing table entry of values associated with the signature
1757  * algorithms (signature scheme) extension
1758 */
1759 typedef struct sigalg_lookup_st {
1760     /* TLS 1.3 signature scheme name */
1761     const char *name;
1762     /* Raw value used in extension */
1763     uint16_t sigalg;
1764     /* NID of hash algorithm or NID_undef if no hash */
1765     int hash;
1766     /* Index of hash algorithm or -1 if no hash algorithm */
1767     int hash_idx;
1768     /* NID of signature algorithm */
1769     int sig;
1770     /* Index of signature algorithm */
1771     int sig_idx;
1772     /* Combined hash and signature NID, if any */
1773     int sigandhash;
1774     /* Required public key curve (ECDSA only) */
1775     int curve;
1776 } SIGALG_LOOKUP;
1777
1778 typedef struct tls_group_info_st {
1779     int nid;                    /* Curve NID */
1780     const char *keytype;
1781     int secbits;                /* Bits of security (from SP800-57) */
1782     uint32_t flags;             /* For group type and applicable TLS versions */
1783     uint16_t group_id;          /* Group ID */
1784 } TLS_GROUP_INFO;
1785
1786 /* flags values */
1787 # define TLS_GROUP_TYPE             0x0000000FU /* Mask for group type */
1788 # define TLS_GROUP_CURVE_PRIME      0x00000001U
1789 # define TLS_GROUP_CURVE_CHAR2      0x00000002U
1790 # define TLS_GROUP_CURVE_CUSTOM     0x00000004U
1791 # define TLS_GROUP_FFDHE            0x00000008U
1792 # define TLS_GROUP_ONLY_FOR_TLS1_3  0x00000010U
1793
1794 # define TLS_GROUP_FFDHE_FOR_TLS1_3 (TLS_GROUP_FFDHE|TLS_GROUP_ONLY_FOR_TLS1_3)
1795
1796 /*
1797  * Structure containing table entry of certificate info corresponding to
1798  * CERT_PKEY entries
1799  */
1800 typedef struct {
1801     int nid; /* NID of public key algorithm */
1802     uint32_t amask; /* authmask corresponding to key type */
1803 } SSL_CERT_LOOKUP;
1804
1805 /* DTLS structures */
1806
1807 # ifndef OPENSSL_NO_SCTP
1808 #  define DTLS1_SCTP_AUTH_LABEL   "EXPORTER_DTLS_OVER_SCTP"
1809 # endif
1810
1811 /* Max MTU overhead we know about so far is 40 for IPv6 + 8 for UDP */
1812 # define DTLS1_MAX_MTU_OVERHEAD                   48
1813
1814 /*
1815  * Flag used in message reuse to indicate the buffer contains the record
1816  * header as well as the handshake message header.
1817  */
1818 # define DTLS1_SKIP_RECORD_HEADER                 2
1819
1820 struct dtls1_retransmit_state {
1821     EVP_CIPHER_CTX *enc_write_ctx; /* cryptographic state */
1822     EVP_MD_CTX *write_hash;     /* used for mac generation */
1823     COMP_CTX *compress;         /* compression */
1824     SSL_SESSION *session;
1825     unsigned short epoch;
1826 };
1827
1828 struct hm_header_st {
1829     unsigned char type;
1830     size_t msg_len;
1831     unsigned short seq;
1832     size_t frag_off;
1833     size_t frag_len;
1834     unsigned int is_ccs;
1835     struct dtls1_retransmit_state saved_retransmit_state;
1836 };
1837
1838 struct dtls1_timeout_st {
1839     /* Number of read timeouts so far */
1840     unsigned int read_timeouts;
1841     /* Number of write timeouts so far */
1842     unsigned int write_timeouts;
1843     /* Number of alerts received so far */
1844     unsigned int num_alerts;
1845 };
1846
1847 typedef struct hm_fragment_st {
1848     struct hm_header_st msg_header;
1849     unsigned char *fragment;
1850     unsigned char *reassembly;
1851 } hm_fragment;
1852
1853 typedef struct pqueue_st pqueue;
1854 typedef struct pitem_st pitem;
1855
1856 struct pitem_st {
1857     unsigned char priority[8];  /* 64-bit value in big-endian encoding */
1858     void *data;
1859     pitem *next;
1860 };
1861
1862 typedef struct pitem_st *piterator;
1863
1864 pitem *pitem_new(unsigned char *prio64be, void *data);
1865 void pitem_free(pitem *item);
1866 pqueue *pqueue_new(void);
1867 void pqueue_free(pqueue *pq);
1868 pitem *pqueue_insert(pqueue *pq, pitem *item);
1869 pitem *pqueue_peek(pqueue *pq);
1870 pitem *pqueue_pop(pqueue *pq);
1871 pitem *pqueue_find(pqueue *pq, unsigned char *prio64be);
1872 pitem *pqueue_iterator(pqueue *pq);
1873 pitem *pqueue_next(piterator *iter);
1874 size_t pqueue_size(pqueue *pq);
1875
1876 typedef struct dtls1_state_st {
1877     unsigned char cookie[DTLS1_COOKIE_LENGTH];
1878     size_t cookie_len;
1879     unsigned int cookie_verified;
1880     /* handshake message numbers */
1881     unsigned short handshake_write_seq;
1882     unsigned short next_handshake_write_seq;
1883     unsigned short handshake_read_seq;
1884     /* Buffered handshake messages */
1885     pqueue *buffered_messages;
1886     /* Buffered (sent) handshake records */
1887     pqueue *sent_messages;
1888     size_t link_mtu;      /* max on-the-wire DTLS packet size */
1889     size_t mtu;           /* max DTLS packet size */
1890     struct hm_header_st w_msg_hdr;
1891     struct hm_header_st r_msg_hdr;
1892     struct dtls1_timeout_st timeout;
1893     /*
1894      * Indicates when the last handshake msg sent will timeout
1895      */
1896     struct timeval next_timeout;
1897     /* Timeout duration */
1898     unsigned int timeout_duration_us;
1899
1900     unsigned int retransmitting;
1901 # ifndef OPENSSL_NO_SCTP
1902     int shutdown_received;
1903 # endif
1904
1905     DTLS_timer_cb timer_cb;
1906
1907 } DTLS1_STATE;
1908
1909 # ifndef OPENSSL_NO_EC
1910 /*
1911  * From ECC-TLS draft, used in encoding the curve type in ECParameters
1912  */
1913 #  define EXPLICIT_PRIME_CURVE_TYPE  1
1914 #  define EXPLICIT_CHAR2_CURVE_TYPE  2
1915 #  define NAMED_CURVE_TYPE           3
1916 # endif                         /* OPENSSL_NO_EC */
1917
1918 struct cert_pkey_st {
1919     X509 *x509;
1920     EVP_PKEY *privatekey;
1921     /* Chain for this certificate */
1922     STACK_OF(X509) *chain;
1923     /*-
1924      * serverinfo data for this certificate.  The data is in TLS Extension
1925      * wire format, specifically it's a series of records like:
1926      *   uint16_t extension_type; // (RFC 5246, 7.4.1.4, Extension)
1927      *   uint16_t length;
1928      *   uint8_t data[length];
1929      */
1930     unsigned char *serverinfo;
1931     size_t serverinfo_length;
1932 };
1933 /* Retrieve Suite B flags */
1934 # define tls1_suiteb(s)  (s->cert->cert_flags & SSL_CERT_FLAG_SUITEB_128_LOS)
1935 /* Uses to check strict mode: suite B modes are always strict */
1936 # define SSL_CERT_FLAGS_CHECK_TLS_STRICT \
1937         (SSL_CERT_FLAG_SUITEB_128_LOS|SSL_CERT_FLAG_TLS_STRICT)
1938
1939 typedef enum {
1940     ENDPOINT_CLIENT = 0,
1941     ENDPOINT_SERVER,
1942     ENDPOINT_BOTH
1943 } ENDPOINT;
1944
1945
1946 typedef struct {
1947     unsigned short ext_type;
1948     ENDPOINT role;
1949     /* The context which this extension applies to */
1950     unsigned int context;
1951     /*
1952      * Per-connection flags relating to this extension type: not used if
1953      * part of an SSL_CTX structure.
1954      */
1955     uint32_t ext_flags;
1956     SSL_custom_ext_add_cb_ex add_cb;
1957     SSL_custom_ext_free_cb_ex free_cb;
1958     void *add_arg;
1959     SSL_custom_ext_parse_cb_ex parse_cb;
1960     void *parse_arg;
1961 } custom_ext_method;
1962
1963 /* ext_flags values */
1964
1965 /*
1966  * Indicates an extension has been received. Used to check for unsolicited or
1967  * duplicate extensions.
1968  */
1969 # define SSL_EXT_FLAG_RECEIVED   0x1
1970 /*
1971  * Indicates an extension has been sent: used to enable sending of
1972  * corresponding ServerHello extension.
1973  */
1974 # define SSL_EXT_FLAG_SENT       0x2
1975
1976 typedef struct {
1977     custom_ext_method *meths;
1978     size_t meths_count;
1979 } custom_ext_methods;
1980
1981 typedef struct cert_st {
1982     /* Current active set */
1983     /*
1984      * ALWAYS points to an element of the pkeys array
1985      * Probably it would make more sense to store
1986      * an index, not a pointer.
1987      */
1988     CERT_PKEY *key;
1989 # ifndef OPENSSL_NO_DH
1990     EVP_PKEY *dh_tmp;
1991     DH *(*dh_tmp_cb) (SSL *ssl, int is_export, int keysize);
1992     int dh_tmp_auto;
1993 # endif
1994     /* Flags related to certificates */
1995     uint32_t cert_flags;
1996     CERT_PKEY pkeys[SSL_PKEY_NUM];
1997     /* Custom certificate types sent in certificate request message. */
1998     uint8_t *ctype;
1999     size_t ctype_len;
2000     /*
2001      * supported signature algorithms. When set on a client this is sent in
2002      * the client hello as the supported signature algorithms extension. For
2003      * servers it represents the signature algorithms we are willing to use.
2004      */
2005     uint16_t *conf_sigalgs;
2006     /* Size of above array */
2007     size_t conf_sigalgslen;
2008     /*
2009      * Client authentication signature algorithms, if not set then uses
2010      * conf_sigalgs. On servers these will be the signature algorithms sent
2011      * to the client in a certificate request for TLS 1.2. On a client this
2012      * represents the signature algorithms we are willing to use for client
2013      * authentication.
2014      */
2015     uint16_t *client_sigalgs;
2016     /* Size of above array */
2017     size_t client_sigalgslen;
2018     /*
2019      * Certificate setup callback: if set is called whenever a certificate
2020      * may be required (client or server). the callback can then examine any
2021      * appropriate parameters and setup any certificates required. This
2022      * allows advanced applications to select certificates on the fly: for
2023      * example based on supported signature algorithms or curves.
2024      */
2025     int (*cert_cb) (SSL *ssl, void *arg);
2026     void *cert_cb_arg;
2027     /*
2028      * Optional X509_STORE for chain building or certificate validation If
2029      * NULL the parent SSL_CTX store is used instead.
2030      */
2031     X509_STORE *chain_store;
2032     X509_STORE *verify_store;
2033     /* Custom extensions */
2034     custom_ext_methods custext;
2035     /* Security callback */
2036     int (*sec_cb) (const SSL *s, const SSL_CTX *ctx, int op, int bits, int nid,
2037                    void *other, void *ex);
2038     /* Security level */
2039     int sec_level;
2040     void *sec_ex;
2041 # ifndef OPENSSL_NO_PSK
2042     /* If not NULL psk identity hint to use for servers */
2043     char *psk_identity_hint;
2044 # endif
2045     CRYPTO_REF_COUNT references;             /* >1 only if SSL_copy_session_id is used */
2046     CRYPTO_RWLOCK *lock;
2047 } CERT;
2048
2049 # define FP_ICC  (int (*)(const void *,const void *))
2050
2051 /*
2052  * This is for the SSLv3/TLSv1.0 differences in crypto/hash stuff It is a bit
2053  * of a mess of functions, but hell, think of it as an opaque structure :-)
2054  */
2055 typedef struct ssl3_enc_method {
2056     int (*enc) (SSL *, SSL3_RECORD *, size_t, int);
2057     int (*mac) (SSL *, SSL3_RECORD *, unsigned char *, int);
2058     int (*setup_key_block) (SSL *);
2059     int (*generate_master_secret) (SSL *, unsigned char *, unsigned char *,
2060                                    size_t, size_t *);
2061     int (*change_cipher_state) (SSL *, int);
2062     size_t (*final_finish_mac) (SSL *, const char *, size_t, unsigned char *);
2063     const char *client_finished_label;
2064     size_t client_finished_label_len;
2065     const char *server_finished_label;
2066     size_t server_finished_label_len;
2067     int (*alert_value) (int);
2068     int (*export_keying_material) (SSL *, unsigned char *, size_t,
2069                                    const char *, size_t,
2070                                    const unsigned char *, size_t,
2071                                    int use_context);
2072     /* Various flags indicating protocol version requirements */
2073     uint32_t enc_flags;
2074     /* Set the handshake header */
2075     int (*set_handshake_header) (SSL *s, WPACKET *pkt, int type);
2076     /* Close construction of the handshake message */
2077     int (*close_construct_packet) (SSL *s, WPACKET *pkt, int htype);
2078     /* Write out handshake message */
2079     int (*do_write) (SSL *s);
2080 } SSL3_ENC_METHOD;
2081
2082 # define ssl_set_handshake_header(s, pkt, htype) \
2083         s->method->ssl3_enc->set_handshake_header((s), (pkt), (htype))
2084 # define ssl_close_construct_packet(s, pkt, htype) \
2085         s->method->ssl3_enc->close_construct_packet((s), (pkt), (htype))
2086 # define ssl_do_write(s)  s->method->ssl3_enc->do_write(s)
2087
2088 /* Values for enc_flags */
2089
2090 /* Uses explicit IV for CBC mode */
2091 # define SSL_ENC_FLAG_EXPLICIT_IV        0x1
2092 /* Uses signature algorithms extension */
2093 # define SSL_ENC_FLAG_SIGALGS            0x2
2094 /* Uses SHA256 default PRF */
2095 # define SSL_ENC_FLAG_SHA256_PRF         0x4
2096 /* Is DTLS */
2097 # define SSL_ENC_FLAG_DTLS               0x8
2098 /*
2099  * Allow TLS 1.2 ciphersuites: applies to DTLS 1.2 as well as TLS 1.2: may
2100  * apply to others in future.
2101  */
2102 # define SSL_ENC_FLAG_TLS1_2_CIPHERS     0x10
2103
2104 # ifndef OPENSSL_NO_COMP
2105 /* Used for holding the relevant compression methods loaded into SSL_CTX */
2106 typedef struct ssl3_comp_st {
2107     int comp_id;                /* The identifier byte for this compression
2108                                  * type */
2109     char *name;                 /* Text name used for the compression type */
2110     COMP_METHOD *method;        /* The method :-) */
2111 } SSL3_COMP;
2112 # endif
2113
2114 typedef enum downgrade_en {
2115     DOWNGRADE_NONE,
2116     DOWNGRADE_TO_1_2,
2117     DOWNGRADE_TO_1_1
2118 } DOWNGRADE;
2119
2120 /*
2121  * Dummy status type for the status_type extension. Indicates no status type
2122  * set
2123  */
2124 #define TLSEXT_STATUSTYPE_nothing  -1
2125
2126 /* Sigalgs values */
2127 #define TLSEXT_SIGALG_ecdsa_secp256r1_sha256                    0x0403
2128 #define TLSEXT_SIGALG_ecdsa_secp384r1_sha384                    0x0503
2129 #define TLSEXT_SIGALG_ecdsa_secp521r1_sha512                    0x0603
2130 #define TLSEXT_SIGALG_ecdsa_sha224                              0x0303
2131 #define TLSEXT_SIGALG_ecdsa_sha1                                0x0203
2132 #define TLSEXT_SIGALG_rsa_pss_rsae_sha256                       0x0804
2133 #define TLSEXT_SIGALG_rsa_pss_rsae_sha384                       0x0805
2134 #define TLSEXT_SIGALG_rsa_pss_rsae_sha512                       0x0806
2135 #define TLSEXT_SIGALG_rsa_pss_pss_sha256                        0x0809
2136 #define TLSEXT_SIGALG_rsa_pss_pss_sha384                        0x080a
2137 #define TLSEXT_SIGALG_rsa_pss_pss_sha512                        0x080b
2138 #define TLSEXT_SIGALG_rsa_pkcs1_sha256                          0x0401
2139 #define TLSEXT_SIGALG_rsa_pkcs1_sha384                          0x0501
2140 #define TLSEXT_SIGALG_rsa_pkcs1_sha512                          0x0601
2141 #define TLSEXT_SIGALG_rsa_pkcs1_sha224                          0x0301
2142 #define TLSEXT_SIGALG_rsa_pkcs1_sha1                            0x0201
2143 #define TLSEXT_SIGALG_dsa_sha256                                0x0402
2144 #define TLSEXT_SIGALG_dsa_sha384                                0x0502
2145 #define TLSEXT_SIGALG_dsa_sha512                                0x0602
2146 #define TLSEXT_SIGALG_dsa_sha224                                0x0302
2147 #define TLSEXT_SIGALG_dsa_sha1                                  0x0202
2148 #define TLSEXT_SIGALG_gostr34102012_256_intrinsic               0x0840
2149 #define TLSEXT_SIGALG_gostr34102012_512_intrinsic               0x0841
2150 #define TLSEXT_SIGALG_gostr34102012_256_gostr34112012_256       0xeeee
2151 #define TLSEXT_SIGALG_gostr34102012_512_gostr34112012_512       0xefef
2152 #define TLSEXT_SIGALG_gostr34102001_gostr3411                   0xeded
2153
2154 #define TLSEXT_SIGALG_ed25519                                   0x0807
2155 #define TLSEXT_SIGALG_ed448                                     0x0808
2156
2157 /* Known PSK key exchange modes */
2158 #define TLSEXT_KEX_MODE_KE                                      0x00
2159 #define TLSEXT_KEX_MODE_KE_DHE                                  0x01
2160
2161 /*
2162  * Internal representations of key exchange modes
2163  */
2164 #define TLSEXT_KEX_MODE_FLAG_NONE                               0
2165 #define TLSEXT_KEX_MODE_FLAG_KE                                 1
2166 #define TLSEXT_KEX_MODE_FLAG_KE_DHE                             2
2167
2168 #define SSL_USE_PSS(s) (s->s3.tmp.peer_sigalg != NULL && \
2169                         s->s3.tmp.peer_sigalg->sig == EVP_PKEY_RSA_PSS)
2170
2171 /* A dummy signature value not valid for TLSv1.2 signature algs */
2172 #define TLSEXT_signature_rsa_pss                                0x0101
2173
2174 /* TLSv1.3 downgrade protection sentinel values */
2175 extern const unsigned char tls11downgrade[8];
2176 extern const unsigned char tls12downgrade[8];
2177
2178 extern SSL3_ENC_METHOD ssl3_undef_enc_method;
2179
2180 __owur const SSL_METHOD *ssl_bad_method(int ver);
2181 __owur const SSL_METHOD *sslv3_method(void);
2182 __owur const SSL_METHOD *sslv3_server_method(void);
2183 __owur const SSL_METHOD *sslv3_client_method(void);
2184 __owur const SSL_METHOD *tlsv1_method(void);
2185 __owur const SSL_METHOD *tlsv1_server_method(void);
2186 __owur const SSL_METHOD *tlsv1_client_method(void);
2187 __owur const SSL_METHOD *tlsv1_1_method(void);
2188 __owur const SSL_METHOD *tlsv1_1_server_method(void);
2189 __owur const SSL_METHOD *tlsv1_1_client_method(void);
2190 __owur const SSL_METHOD *tlsv1_2_method(void);
2191 __owur const SSL_METHOD *tlsv1_2_server_method(void);
2192 __owur const SSL_METHOD *tlsv1_2_client_method(void);
2193 __owur const SSL_METHOD *tlsv1_3_method(void);
2194 __owur const SSL_METHOD *tlsv1_3_server_method(void);
2195 __owur const SSL_METHOD *tlsv1_3_client_method(void);
2196 __owur const SSL_METHOD *dtlsv1_method(void);
2197 __owur const SSL_METHOD *dtlsv1_server_method(void);
2198 __owur const SSL_METHOD *dtlsv1_client_method(void);
2199 __owur const SSL_METHOD *dtls_bad_ver_client_method(void);
2200 __owur const SSL_METHOD *dtlsv1_2_method(void);
2201 __owur const SSL_METHOD *dtlsv1_2_server_method(void);
2202 __owur const SSL_METHOD *dtlsv1_2_client_method(void);
2203
2204 extern const SSL3_ENC_METHOD TLSv1_enc_data;
2205 extern const SSL3_ENC_METHOD TLSv1_1_enc_data;
2206 extern const SSL3_ENC_METHOD TLSv1_2_enc_data;
2207 extern const SSL3_ENC_METHOD TLSv1_3_enc_data;
2208 extern const SSL3_ENC_METHOD SSLv3_enc_data;
2209 extern const SSL3_ENC_METHOD DTLSv1_enc_data;
2210 extern const SSL3_ENC_METHOD DTLSv1_2_enc_data;
2211
2212 /*
2213  * Flags for SSL methods
2214  */
2215 # define SSL_METHOD_NO_FIPS      (1U<<0)
2216 # define SSL_METHOD_NO_SUITEB    (1U<<1)
2217
2218 # define IMPLEMENT_tls_meth_func(version, flags, mask, func_name, s_accept, \
2219                                  s_connect, enc_data) \
2220 const SSL_METHOD *func_name(void)  \
2221         { \
2222         static const SSL_METHOD func_name##_data= { \
2223                 version, \
2224                 flags, \
2225                 mask, \
2226                 tls1_new, \
2227                 tls1_clear, \
2228                 tls1_free, \
2229                 s_accept, \
2230                 s_connect, \
2231                 ssl3_read, \
2232                 ssl3_peek, \
2233                 ssl3_write, \
2234                 ssl3_shutdown, \
2235                 ssl3_renegotiate, \
2236                 ssl3_renegotiate_check, \
2237                 ssl3_read_bytes, \
2238                 ssl3_write_bytes, \
2239                 ssl3_dispatch_alert, \
2240                 ssl3_ctrl, \
2241                 ssl3_ctx_ctrl, \
2242                 ssl3_get_cipher_by_char, \
2243                 ssl3_put_cipher_by_char, \
2244                 ssl3_pending, \
2245                 ssl3_num_ciphers, \
2246                 ssl3_get_cipher, \
2247                 tls1_default_timeout, \
2248                 &enc_data, \
2249                 ssl_undefined_void_function, \
2250                 ssl3_callback_ctrl, \
2251                 ssl3_ctx_callback_ctrl, \
2252         }; \
2253         return &func_name##_data; \
2254         }
2255
2256 # define IMPLEMENT_ssl3_meth_func(func_name, s_accept, s_connect) \
2257 const SSL_METHOD *func_name(void)  \
2258         { \
2259         static const SSL_METHOD func_name##_data= { \
2260                 SSL3_VERSION, \
2261                 SSL_METHOD_NO_FIPS | SSL_METHOD_NO_SUITEB, \
2262                 SSL_OP_NO_SSLv3, \
2263                 ssl3_new, \
2264                 ssl3_clear, \
2265                 ssl3_free, \
2266                 s_accept, \
2267                 s_connect, \
2268                 ssl3_read, \
2269                 ssl3_peek, \
2270                 ssl3_write, \
2271                 ssl3_shutdown, \
2272                 ssl3_renegotiate, \
2273                 ssl3_renegotiate_check, \
2274                 ssl3_read_bytes, \
2275                 ssl3_write_bytes, \
2276                 ssl3_dispatch_alert, \
2277                 ssl3_ctrl, \
2278                 ssl3_ctx_ctrl, \
2279                 ssl3_get_cipher_by_char, \
2280                 ssl3_put_cipher_by_char, \
2281                 ssl3_pending, \
2282                 ssl3_num_ciphers, \
2283                 ssl3_get_cipher, \
2284                 ssl3_default_timeout, \
2285                 &SSLv3_enc_data, \
2286                 ssl_undefined_void_function, \
2287                 ssl3_callback_ctrl, \
2288                 ssl3_ctx_callback_ctrl, \
2289         }; \
2290         return &func_name##_data; \
2291         }
2292
2293 # define IMPLEMENT_dtls1_meth_func(version, flags, mask, func_name, s_accept, \
2294                                         s_connect, enc_data) \
2295 const SSL_METHOD *func_name(void)  \
2296         { \
2297         static const SSL_METHOD func_name##_data= { \
2298                 version, \
2299                 flags, \
2300                 mask, \
2301                 dtls1_new, \
2302                 dtls1_clear, \
2303                 dtls1_free, \
2304                 s_accept, \
2305                 s_connect, \
2306                 ssl3_read, \
2307                 ssl3_peek, \
2308                 ssl3_write, \
2309                 dtls1_shutdown, \
2310                 ssl3_renegotiate, \
2311                 ssl3_renegotiate_check, \
2312                 dtls1_read_bytes, \
2313                 dtls1_write_app_data_bytes, \
2314                 dtls1_dispatch_alert, \
2315                 dtls1_ctrl, \
2316                 ssl3_ctx_ctrl, \
2317                 ssl3_get_cipher_by_char, \
2318                 ssl3_put_cipher_by_char, \
2319                 ssl3_pending, \
2320                 ssl3_num_ciphers, \
2321                 ssl3_get_cipher, \
2322                 dtls1_default_timeout, \
2323                 &enc_data, \
2324                 ssl_undefined_void_function, \
2325                 ssl3_callback_ctrl, \
2326                 ssl3_ctx_callback_ctrl, \
2327         }; \
2328         return &func_name##_data; \
2329         }
2330
2331 struct openssl_ssl_test_functions {
2332     int (*p_ssl_init_wbio_buffer) (SSL *s);
2333     int (*p_ssl3_setup_buffers) (SSL *s);
2334 };
2335
2336 const char *ssl_protocol_to_string(int version);
2337
2338 /* Returns true if certificate and private key for 'idx' are present */
2339 static ossl_inline int ssl_has_cert(const SSL *s, int idx)
2340 {
2341     if (idx < 0 || idx >= SSL_PKEY_NUM)
2342         return 0;
2343     return s->cert->pkeys[idx].x509 != NULL
2344         && s->cert->pkeys[idx].privatekey != NULL;
2345 }
2346
2347 static ossl_inline void tls1_get_peer_groups(SSL *s, const uint16_t **pgroups,
2348                                              size_t *pgroupslen)
2349 {
2350     *pgroups = s->ext.peer_supportedgroups;
2351     *pgroupslen = s->ext.peer_supportedgroups_len;
2352 }
2353
2354 # ifndef OPENSSL_UNIT_TEST
2355
2356 __owur int ssl_read_internal(SSL *s, void *buf, size_t num, size_t *readbytes);
2357 __owur int ssl_write_internal(SSL *s, const void *buf, size_t num, size_t *written);
2358 void ssl_clear_cipher_ctx(SSL *s);
2359 int ssl_clear_bad_session(SSL *s);
2360 __owur CERT *ssl_cert_new(void);
2361 __owur CERT *ssl_cert_dup(CERT *cert);
2362 void ssl_cert_clear_certs(CERT *c);
2363 void ssl_cert_free(CERT *c);
2364 __owur int ssl_generate_session_id(SSL *s, SSL_SESSION *ss);
2365 __owur int ssl_get_new_session(SSL *s, int session);
2366 __owur SSL_SESSION *lookup_sess_in_cache(SSL *s, const unsigned char *sess_id,
2367                                          size_t sess_id_len);
2368 __owur int ssl_get_prev_session(SSL *s, CLIENTHELLO_MSG *hello);
2369 __owur SSL_SESSION *ssl_session_dup(const SSL_SESSION *src, int ticket);
2370 __owur int ssl_cipher_id_cmp(const SSL_CIPHER *a, const SSL_CIPHER *b);
2371 DECLARE_OBJ_BSEARCH_GLOBAL_CMP_FN(SSL_CIPHER, SSL_CIPHER, ssl_cipher_id);
2372 __owur int ssl_cipher_ptr_id_cmp(const SSL_CIPHER *const *ap,
2373                                  const SSL_CIPHER *const *bp);
2374 __owur STACK_OF(SSL_CIPHER) *ssl_create_cipher_list(const SSL_METHOD *ssl_method,
2375                                                     STACK_OF(SSL_CIPHER) *tls13_ciphersuites,
2376                                                     STACK_OF(SSL_CIPHER) **cipher_list,
2377                                                     STACK_OF(SSL_CIPHER) **cipher_list_by_id,
2378                                                     const char *rule_str,
2379                                                     CERT *c);
2380 __owur int ssl_cache_cipherlist(SSL *s, PACKET *cipher_suites, int sslv2format);
2381 __owur int bytes_to_cipher_list(SSL *s, PACKET *cipher_suites,
2382                                 STACK_OF(SSL_CIPHER) **skp,
2383                                 STACK_OF(SSL_CIPHER) **scsvs, int sslv2format,
2384                                 int fatal);
2385 void ssl_update_cache(SSL *s, int mode);
2386 __owur int ssl_cipher_get_evp_cipher(SSL_CTX *ctx, const SSL_CIPHER *sslc,
2387                                      const EVP_CIPHER **enc);
2388 __owur int ssl_cipher_get_evp(SSL_CTX *ctxc, const SSL_SESSION *s,
2389                               const EVP_CIPHER **enc, const EVP_MD **md,
2390                               int *mac_pkey_type, size_t *mac_secret_size,
2391                               SSL_COMP **comp, int use_etm);
2392 __owur int ssl_cipher_get_overhead(const SSL_CIPHER *c, size_t *mac_overhead,
2393                                    size_t *int_overhead, size_t *blocksize,
2394                                    size_t *ext_overhead);
2395 __owur int ssl_cert_is_disabled(size_t idx);
2396 __owur const SSL_CIPHER *ssl_get_cipher_by_char(SSL *ssl,
2397                                                 const unsigned char *ptr,
2398                                                 int all);
2399 __owur int ssl_cert_set0_chain(SSL *s, SSL_CTX *ctx, STACK_OF(X509) *chain);
2400 __owur int ssl_cert_set1_chain(SSL *s, SSL_CTX *ctx, STACK_OF(X509) *chain);
2401 __owur int ssl_cert_add0_chain_cert(SSL *s, SSL_CTX *ctx, X509 *x);
2402 __owur int ssl_cert_add1_chain_cert(SSL *s, SSL_CTX *ctx, X509 *x);
2403 __owur int ssl_cert_select_current(CERT *c, X509 *x);
2404 __owur int ssl_cert_set_current(CERT *c, long arg);
2405 void ssl_cert_set_cert_cb(CERT *c, int (*cb) (SSL *ssl, void *arg), void *arg);
2406
2407 __owur int ssl_verify_cert_chain(SSL *s, STACK_OF(X509) *sk);
2408 __owur int ssl_build_cert_chain(SSL *s, SSL_CTX *ctx, int flags);
2409 __owur int ssl_cert_set_cert_store(CERT *c, X509_STORE *store, int chain,
2410                                    int ref);
2411
2412 __owur int ssl_security(const SSL *s, int op, int bits, int nid, void *other);
2413 __owur int ssl_ctx_security(const SSL_CTX *ctx, int op, int bits, int nid,
2414                             void *other);
2415
2416 __owur int ssl_cert_lookup_by_nid(int nid, size_t *pidx);
2417 __owur const SSL_CERT_LOOKUP *ssl_cert_lookup_by_pkey(const EVP_PKEY *pk,
2418                                                       size_t *pidx);
2419 __owur const SSL_CERT_LOOKUP *ssl_cert_lookup_by_idx(size_t idx);
2420
2421 int ssl_undefined_function(SSL *s);
2422 __owur int ssl_undefined_void_function(void);
2423 __owur int ssl_undefined_const_function(const SSL *s);
2424 __owur int ssl_get_server_cert_serverinfo(SSL *s,
2425                                           const unsigned char **serverinfo,
2426                                           size_t *serverinfo_length);
2427 void ssl_set_masks(SSL *s);
2428 __owur STACK_OF(SSL_CIPHER) *ssl_get_ciphers_by_id(SSL *s);
2429 __owur int ssl_x509err2alert(int type);
2430 void ssl_sort_cipher_list(void);
2431 int ssl_load_ciphers(SSL_CTX *ctx);
2432 __owur int ssl_fill_hello_random(SSL *s, int server, unsigned char *field,
2433                                  size_t len, DOWNGRADE dgrd);
2434 __owur int ssl_generate_master_secret(SSL *s, unsigned char *pms, size_t pmslen,
2435                                       int free_pms);
2436 __owur EVP_PKEY *ssl_generate_pkey(SSL *s, EVP_PKEY *pm);
2437 __owur int ssl_derive(SSL *s, EVP_PKEY *privkey, EVP_PKEY *pubkey,
2438                       int genmaster);
2439 __owur EVP_PKEY *ssl_dh_to_pkey(DH *dh);
2440 __owur unsigned int ssl_get_max_send_fragment(const SSL *ssl);
2441 __owur unsigned int ssl_get_split_send_fragment(const SSL *ssl);
2442
2443 __owur const SSL_CIPHER *ssl3_get_cipher_by_id(uint32_t id);
2444 __owur const SSL_CIPHER *ssl3_get_cipher_by_std_name(const char *stdname);
2445 __owur const SSL_CIPHER *ssl3_get_cipher_by_char(const unsigned char *p);
2446 __owur int ssl3_put_cipher_by_char(const SSL_CIPHER *c, WPACKET *pkt,
2447                                    size_t *len);
2448 int ssl3_init_finished_mac(SSL *s);
2449 __owur int ssl3_setup_key_block(SSL *s);
2450 __owur int ssl3_change_cipher_state(SSL *s, int which);
2451 void ssl3_cleanup_key_block(SSL *s);
2452 __owur int ssl3_do_write(SSL *s, int type);
2453 int ssl3_send_alert(SSL *s, int level, int desc);
2454 __owur int ssl3_generate_master_secret(SSL *s, unsigned char *out,
2455                                        unsigned char *p, size_t len,
2456                                        size_t *secret_size);
2457 __owur int ssl3_get_req_cert_type(SSL *s, WPACKET *pkt);
2458 __owur int ssl3_num_ciphers(void);
2459 __owur const SSL_CIPHER *ssl3_get_cipher(unsigned int u);
2460 int ssl3_renegotiate(SSL *ssl);
2461 int ssl3_renegotiate_check(SSL *ssl, int initok);
2462 void ssl3_digest_master_key_set_params(const SSL_SESSION *session,
2463                                        OSSL_PARAM params[]);
2464 __owur int ssl3_dispatch_alert(SSL *s);
2465 __owur size_t ssl3_final_finish_mac(SSL *s, const char *sender, size_t slen,
2466                                     unsigned char *p);
2467 __owur int ssl3_finish_mac(SSL *s, const unsigned char *buf, size_t len);
2468 void ssl3_free_digest_list(SSL *s);
2469 __owur unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt,
2470                                             CERT_PKEY *cpk);
2471 __owur const SSL_CIPHER *ssl3_choose_cipher(SSL *ssl,
2472                                             STACK_OF(SSL_CIPHER) *clnt,
2473                                             STACK_OF(SSL_CIPHER) *srvr);
2474 __owur int ssl3_digest_cached_records(SSL *s, int keep);
2475 __owur int ssl3_new(SSL *s);
2476 void ssl3_free(SSL *s);
2477 __owur int ssl3_read(SSL *s, void *buf, size_t len, size_t *readbytes);
2478 __owur int ssl3_peek(SSL *s, void *buf, size_t len, size_t *readbytes);
2479 __owur int ssl3_write(SSL *s, const void *buf, size_t len, size_t *written);
2480 __owur int ssl3_shutdown(SSL *s);
2481 int ssl3_clear(SSL *s);
2482 __owur long ssl3_ctrl(SSL *s, int cmd, long larg, void *parg);
2483 __owur long ssl3_ctx_ctrl(SSL_CTX *s, int cmd, long larg, void *parg);
2484 __owur long ssl3_callback_ctrl(SSL *s, int cmd, void (*fp) (void));
2485 __owur long ssl3_ctx_callback_ctrl(SSL_CTX *s, int cmd, void (*fp) (void));
2486
2487 __owur int ssl3_do_change_cipher_spec(SSL *ssl);
2488 __owur long ssl3_default_timeout(void);
2489
2490 __owur int ssl3_set_handshake_header(SSL *s, WPACKET *pkt, int htype);
2491 __owur int tls_close_construct_packet(SSL *s, WPACKET *pkt, int htype);
2492 __owur int tls_setup_handshake(SSL *s);
2493 __owur int dtls1_set_handshake_header(SSL *s, WPACKET *pkt, int htype);
2494 __owur int dtls1_close_construct_packet(SSL *s, WPACKET *pkt, int htype);
2495 __owur int ssl3_handshake_write(SSL *s);
2496
2497 __owur int ssl_allow_compression(SSL *s);
2498
2499 __owur int ssl_version_supported(const SSL *s, int version,
2500                                  const SSL_METHOD **meth);
2501
2502 __owur int ssl_set_client_hello_version(SSL *s);
2503 __owur int ssl_check_version_downgrade(SSL *s);
2504 __owur int ssl_set_version_bound(int method_version, int version, int *bound);
2505 __owur int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello,
2506                                      DOWNGRADE *dgrd);
2507 __owur int ssl_choose_client_version(SSL *s, int version,
2508                                      RAW_EXTENSION *extensions);
2509 __owur int ssl_get_min_max_version(const SSL *s, int *min_version,
2510                                    int *max_version, int *real_max);
2511
2512 __owur long tls1_default_timeout(void);
2513 __owur int dtls1_do_write(SSL *s, int type);
2514 void dtls1_set_message_header(SSL *s,
2515                               unsigned char mt,
2516                               size_t len,
2517                               size_t frag_off, size_t frag_len);
2518
2519 int dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, size_t len,
2520                                size_t *written);
2521
2522 __owur int dtls1_read_failed(SSL *s, int code);
2523 __owur int dtls1_buffer_message(SSL *s, int ccs);
2524 __owur int dtls1_retransmit_message(SSL *s, unsigned short seq, int *found);
2525 __owur int dtls1_get_queue_priority(unsigned short seq, int is_ccs);
2526 int dtls1_retransmit_buffered_messages(SSL *s);
2527 void dtls1_clear_received_buffer(SSL *s);
2528 void dtls1_clear_sent_buffer(SSL *s);
2529 void dtls1_get_message_header(unsigned char *data,
2530                               struct hm_header_st *msg_hdr);
2531 __owur long dtls1_default_timeout(void);
2532 __owur struct timeval *dtls1_get_timeout(SSL *s, struct timeval *timeleft);
2533 __owur int dtls1_check_timeout_num(SSL *s);
2534 __owur int dtls1_handle_timeout(SSL *s);
2535 void dtls1_start_timer(SSL *s);
2536 void dtls1_stop_timer(SSL *s);
2537 __owur int dtls1_is_timer_expired(SSL *s);
2538 void dtls1_double_timeout(SSL *s);
2539 __owur int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie,
2540                                          size_t cookie_len);
2541 __owur size_t dtls1_min_mtu(SSL *s);
2542 void dtls1_hm_fragment_free(hm_fragment *frag);
2543 __owur int dtls1_query_mtu(SSL *s);
2544
2545 __owur int tls1_new(SSL *s);
2546 void tls1_free(SSL *s);
2547 int tls1_clear(SSL *s);
2548
2549 __owur int dtls1_new(SSL *s);
2550 void dtls1_free(SSL *s);
2551 int dtls1_clear(SSL *s);
2552 long dtls1_ctrl(SSL *s, int cmd, long larg, void *parg);
2553 __owur int dtls1_shutdown(SSL *s);
2554
2555 __owur int dtls1_dispatch_alert(SSL *s);
2556
2557 __owur int ssl_init_wbio_buffer(SSL *s);
2558 int ssl_free_wbio_buffer(SSL *s);
2559
2560 __owur int tls1_change_cipher_state(SSL *s, int which);
2561 __owur int tls1_setup_key_block(SSL *s);
2562 __owur size_t tls1_final_finish_mac(SSL *s, const char *str, size_t slen,
2563                                     unsigned char *p);
2564 __owur int tls1_generate_master_secret(SSL *s, unsigned char *out,
2565                                        unsigned char *p, size_t len,
2566                                        size_t *secret_size);
2567 __owur int tls13_setup_key_block(SSL *s);
2568 __owur size_t tls13_final_finish_mac(SSL *s, const char *str, size_t slen,
2569                                      unsigned char *p);
2570 __owur int tls13_change_cipher_state(SSL *s, int which);
2571 __owur int tls13_update_key(SSL *s, int send);
2572 __owur int tls13_hkdf_expand(SSL *s, const EVP_MD *md,
2573                              const unsigned char *secret,
2574                              const unsigned char *label, size_t labellen,
2575                              const unsigned char *data, size_t datalen,
2576                              unsigned char *out, size_t outlen, int fatal);
2577 __owur int tls13_derive_key(SSL *s, const EVP_MD *md,
2578                             const unsigned char *secret, unsigned char *key,
2579                             size_t keylen);
2580 __owur int tls13_derive_iv(SSL *s, const EVP_MD *md,
2581                            const unsigned char *secret, unsigned char *iv,
2582                            size_t ivlen);
2583 __owur int tls13_derive_finishedkey(SSL *s, const EVP_MD *md,
2584                                     const unsigned char *secret,
2585                                     unsigned char *fin, size_t finlen);
2586 int tls13_generate_secret(SSL *s, const EVP_MD *md,
2587                           const unsigned char *prevsecret,
2588                           const unsigned char *insecret,
2589                           size_t insecretlen,
2590                           unsigned char *outsecret);
2591 __owur int tls13_generate_handshake_secret(SSL *s,
2592                                            const unsigned char *insecret,
2593                                            size_t insecretlen);
2594 __owur int tls13_generate_master_secret(SSL *s, unsigned char *out,
2595                                         unsigned char *prev, size_t prevlen,
2596                                         size_t *secret_size);
2597 __owur int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
2598                                        const char *label, size_t llen,
2599                                        const unsigned char *p, size_t plen,
2600                                        int use_context);
2601 __owur int tls13_export_keying_material(SSL *s, unsigned char *out, size_t olen,
2602                                         const char *label, size_t llen,
2603                                         const unsigned char *context,
2604                                         size_t contextlen, int use_context);
2605 __owur int tls13_export_keying_material_early(SSL *s, unsigned char *out,
2606                                               size_t olen, const char *label,
2607                                               size_t llen,
2608                                               const unsigned char *context,
2609                                               size_t contextlen);
2610 __owur int tls1_alert_code(int code);
2611 __owur int tls13_alert_code(int code);
2612 __owur int ssl3_alert_code(int code);
2613
2614 #  ifndef OPENSSL_NO_EC
2615 __owur int ssl_check_srvr_ecc_cert_and_alg(X509 *x, SSL *s);
2616 #  endif
2617
2618 SSL_COMP *ssl3_comp_find(STACK_OF(SSL_COMP) *sk, int n);
2619
2620 __owur const TLS_GROUP_INFO *tls1_group_id_lookup(uint16_t curve_id);
2621 __owur int tls1_group_id2nid(uint16_t group_id);
2622 __owur int tls1_check_group_id(SSL *s, uint16_t group_id, int check_own_curves);
2623 __owur uint16_t tls1_shared_group(SSL *s, int nmatch);
2624 __owur int tls1_set_groups(uint16_t **pext, size_t *pextlen,
2625                            int *curves, size_t ncurves);
2626 __owur int tls1_set_groups_list(uint16_t **pext, size_t *pextlen,
2627                                 const char *str);
2628 __owur EVP_PKEY *ssl_generate_pkey_group(SSL *s, uint16_t id);
2629 __owur int tls_valid_group(SSL *s, uint16_t group_id, int version);
2630 __owur EVP_PKEY *ssl_generate_param_group(SSL *s, uint16_t id);
2631 #  ifndef OPENSSL_NO_EC
2632 void tls1_get_formatlist(SSL *s, const unsigned char **pformats,
2633                          size_t *num_formats);
2634 __owur int tls1_check_ec_tmp_key(SSL *s, unsigned long id);
2635 #  endif                        /* OPENSSL_NO_EC */
2636
2637 __owur int tls_group_allowed(SSL *s, uint16_t curve, int op);
2638 void tls1_get_supported_groups(SSL *s, const uint16_t **pgroups,
2639                                size_t *pgroupslen);
2640
2641 __owur int tls1_set_server_sigalgs(SSL *s);
2642
2643 __owur SSL_TICKET_STATUS tls_get_ticket_from_client(SSL *s, CLIENTHELLO_MSG *hello,
2644                                                     SSL_SESSION **ret);
2645 __owur SSL_TICKET_STATUS tls_decrypt_ticket(SSL *s, const unsigned char *etick,
2646                                             size_t eticklen,
2647                                             const unsigned char *sess_id,
2648                                             size_t sesslen, SSL_SESSION **psess);
2649
2650 __owur int tls_use_ticket(SSL *s);
2651
2652 void ssl_set_sig_mask(uint32_t *pmask_a, SSL *s, int op);
2653
2654 __owur int tls1_set_sigalgs_list(CERT *c, const char *str, int client);
2655 __owur int tls1_set_raw_sigalgs(CERT *c, const uint16_t *psigs, size_t salglen,
2656                                 int client);
2657 __owur int tls1_set_sigalgs(CERT *c, const int *salg, size_t salglen,
2658                             int client);
2659 int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
2660                      int idx);
2661 void tls1_set_cert_validity(SSL *s);
2662
2663 #  ifndef OPENSSL_NO_CT
2664 __owur int ssl_validate_ct(SSL *s);
2665 #  endif
2666
2667 #  ifndef OPENSSL_NO_DH
2668 __owur DH *ssl_get_auto_dh(SSL *s);
2669 #  endif
2670
2671 __owur int ssl_security_cert(SSL *s, SSL_CTX *ctx, X509 *x, int vfy, int is_ee);
2672 __owur int ssl_security_cert_chain(SSL *s, STACK_OF(X509) *sk, X509 *ex,
2673                                    int vfy);
2674
2675 int tls_choose_sigalg(SSL *s, int fatalerrs);
2676
2677 __owur EVP_MD_CTX *ssl_replace_hash(EVP_MD_CTX **hash, const EVP_MD *md);
2678 void ssl_clear_hash_ctx(EVP_MD_CTX **hash);
2679 __owur long ssl_get_algorithm2(SSL *s);
2680 __owur int tls12_copy_sigalgs(SSL *s, WPACKET *pkt,
2681                               const uint16_t *psig, size_t psiglen);
2682 __owur int tls1_save_u16(PACKET *pkt, uint16_t **pdest, size_t *pdestlen);
2683 __owur int tls1_save_sigalgs(SSL *s, PACKET *pkt, int cert);
2684 __owur int tls1_process_sigalgs(SSL *s);
2685 __owur int tls1_set_peer_legacy_sigalg(SSL *s, const EVP_PKEY *pkey);
2686 __owur int tls1_lookup_md(SSL_CTX *ctx, const SIGALG_LOOKUP *lu,
2687                           const EVP_MD **pmd);
2688 __owur size_t tls12_get_psigalgs(SSL *s, int sent, const uint16_t **psigs);
2689 #  ifndef OPENSSL_NO_EC
2690 __owur int tls_check_sigalg_curve(const SSL *s, int curve);
2691 #  endif
2692 __owur int tls12_check_peer_sigalg(SSL *s, uint16_t, EVP_PKEY *pkey);
2693 __owur int ssl_set_client_disabled(SSL *s);
2694 __owur int ssl_cipher_disabled(const SSL *s, const SSL_CIPHER *c, int op, int echde);
2695
2696 __owur int ssl_handshake_hash(SSL *s, unsigned char *out, size_t outlen,
2697                                  size_t *hashlen);
2698 __owur const EVP_MD *ssl_md(SSL_CTX *ctx, int idx);
2699 __owur const EVP_MD *ssl_handshake_md(SSL *s);
2700 __owur const EVP_MD *ssl_prf_md(SSL *s);
2701
2702 /*
2703  * ssl_log_rsa_client_key_exchange logs |premaster| to the SSL_CTX associated
2704  * with |ssl|, if logging is enabled. It returns one on success and zero on
2705  * failure. The entry is identified by the first 8 bytes of
2706  * |encrypted_premaster|.
2707  */
2708 __owur int ssl_log_rsa_client_key_exchange(SSL *ssl,
2709                                            const uint8_t *encrypted_premaster,
2710                                            size_t encrypted_premaster_len,
2711                                            const uint8_t *premaster,
2712                                            size_t premaster_len);
2713
2714 /*
2715  * ssl_log_secret logs |secret| to the SSL_CTX associated with |ssl|, if
2716  * logging is available. It returns one on success and zero on failure. It tags
2717  * the entry with |label|.
2718  */
2719 __owur int ssl_log_secret(SSL *ssl, const char *label,
2720                           const uint8_t *secret, size_t secret_len);
2721
2722 #define MASTER_SECRET_LABEL "CLIENT_RANDOM"
2723 #define CLIENT_EARLY_LABEL "CLIENT_EARLY_TRAFFIC_SECRET"
2724 #define CLIENT_HANDSHAKE_LABEL "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
2725 #define SERVER_HANDSHAKE_LABEL "SERVER_HANDSHAKE_TRAFFIC_SECRET"
2726 #define CLIENT_APPLICATION_LABEL "CLIENT_TRAFFIC_SECRET_0"
2727 #define SERVER_APPLICATION_LABEL "SERVER_TRAFFIC_SECRET_0"
2728 #define EARLY_EXPORTER_SECRET_LABEL "EARLY_EXPORTER_SECRET"
2729 #define EXPORTER_SECRET_LABEL "EXPORTER_SECRET"
2730
2731 /* s3_cbc.c */
2732 __owur char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx);
2733 __owur int ssl3_cbc_digest_record(SSL *s,
2734                                   const EVP_MD_CTX *ctx,
2735                                   unsigned char *md_out,
2736                                   size_t *md_out_size,
2737                                   const unsigned char header[13],
2738                                   const unsigned char *data,
2739                                   size_t data_plus_mac_size,
2740                                   size_t data_plus_mac_plus_padding_size,
2741                                   const unsigned char *mac_secret,
2742                                   size_t mac_secret_length, char is_sslv3);
2743
2744 __owur int srp_generate_server_master_secret(SSL *s);
2745 __owur int srp_generate_client_master_secret(SSL *s);
2746 __owur int srp_verify_server_param(SSL *s);
2747
2748 /* statem/statem_srvr.c */
2749
2750 __owur int send_certificate_request(SSL *s);
2751
2752 /* statem/extensions_cust.c */
2753
2754 custom_ext_method *custom_ext_find(const custom_ext_methods *exts,
2755                                    ENDPOINT role, unsigned int ext_type,
2756                                    size_t *idx);
2757
2758 void custom_ext_init(custom_ext_methods *meths);
2759
2760 __owur int custom_ext_parse(SSL *s, unsigned int context, unsigned int ext_type,
2761                             const unsigned char *ext_data, size_t ext_size,
2762                             X509 *x, size_t chainidx);
2763 __owur int custom_ext_add(SSL *s, int context, WPACKET *pkt, X509 *x,
2764                           size_t chainidx, int maxversion);
2765
2766 __owur int custom_exts_copy(custom_ext_methods *dst,
2767                             const custom_ext_methods *src);
2768 __owur int custom_exts_copy_flags(custom_ext_methods *dst,
2769                                   const custom_ext_methods *src);
2770 void custom_exts_free(custom_ext_methods *exts);
2771
2772 void ssl_comp_free_compression_methods_int(void);
2773
2774 /* ssl_mcnf.c */
2775 void ssl_ctx_system_config(SSL_CTX *ctx);
2776
2777 const EVP_CIPHER *ssl_evp_cipher_fetch(OPENSSL_CTX *libctx,
2778                                        int nid,
2779                                        const char *properties);
2780 int ssl_evp_cipher_up_ref(const EVP_CIPHER *cipher);
2781 void ssl_evp_cipher_free(const EVP_CIPHER *cipher);
2782 const EVP_MD *ssl_evp_md_fetch(OPENSSL_CTX *libctx,
2783                                int nid,
2784                                const char *properties);
2785 int ssl_evp_md_up_ref(const EVP_MD *md);
2786 void ssl_evp_md_free(const EVP_MD *md);
2787
2788
2789 # else /* OPENSSL_UNIT_TEST */
2790
2791 #  define ssl_init_wbio_buffer SSL_test_functions()->p_ssl_init_wbio_buffer
2792 #  define ssl3_setup_buffers SSL_test_functions()->p_ssl3_setup_buffers
2793
2794 # endif
2795 #endif