• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright 2005 Nokia. All rights reserved.
59  *
60  * The portions of the attached software ("Contribution") is developed by
61  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
62  * license.
63  *
64  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
65  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
66  * support (see RFC 4279) to OpenSSL.
67  *
68  * No patent licenses or other rights except those expressly stated in
69  * the OpenSSL open source license shall be deemed granted or received
70  * expressly, by implication, estoppel, or otherwise.
71  *
72  * No assurances are provided by Nokia that the Contribution does not
73  * infringe the patent or other intellectual property rights of any third
74  * party or that the license provides you with all the necessary rights
75  * to make use of the Contribution.
76  *
77  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
78  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
79  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
80  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
81  * OTHERWISE. */
82 
83 /* Per C99, various stdint.h macros are unavailable in C++ unless some macros
84  * are defined. C++11 overruled this decision, but older Android NDKs still
85  * require it. */
86 #if !defined(__STDC_LIMIT_MACROS)
87 #define __STDC_LIMIT_MACROS
88 #endif
89 
90 #include <openssl/ssl.h>
91 
92 #include <limits.h>
93 #include <string.h>
94 
95 #include <openssl/buf.h>
96 #include <openssl/bytestring.h>
97 #include <openssl/err.h>
98 #include <openssl/mem.h>
99 #include <openssl/x509.h>
100 
101 #include "../crypto/internal.h"
102 #include "internal.h"
103 
104 
105 /* An SSL_SESSION is serialized as the following ASN.1 structure:
106  *
107  * SSLSession ::= SEQUENCE {
108  *     version                     INTEGER (1),  -- session structure version
109  *     sslVersion                  INTEGER,      -- protocol version number
110  *     cipher                      OCTET STRING, -- two bytes long
111  *     sessionID                   OCTET STRING,
112  *     masterKey                   OCTET STRING,
113  *     time                    [1] INTEGER, -- seconds since UNIX epoch
114  *     timeout                 [2] INTEGER, -- in seconds
115  *     peer                    [3] Certificate OPTIONAL,
116  *     sessionIDContext        [4] OCTET STRING OPTIONAL,
117  *     verifyResult            [5] INTEGER OPTIONAL,  -- one of X509_V_* codes
118  *     hostName                [6] OCTET STRING OPTIONAL,
119  *                                 -- from server_name extension
120  *     pskIdentity             [8] OCTET STRING OPTIONAL,
121  *     ticketLifetimeHint      [9] INTEGER OPTIONAL,       -- client-only
122  *     ticket                  [10] OCTET STRING OPTIONAL, -- client-only
123  *     peerSHA256              [13] OCTET STRING OPTIONAL,
124  *     originalHandshakeHash   [14] OCTET STRING OPTIONAL,
125  *     signedCertTimestampList [15] OCTET STRING OPTIONAL,
126  *                                  -- contents of SCT extension
127  *     ocspResponse            [16] OCTET STRING OPTIONAL,
128  *                                  -- stapled OCSP response from the server
129  *     extendedMasterSecret    [17] BOOLEAN OPTIONAL,
130  *     groupID                 [18] INTEGER OPTIONAL,
131  *     certChain               [19] SEQUENCE OF Certificate OPTIONAL,
132  *     ticketAgeAdd            [21] OCTET STRING OPTIONAL,
133  *     isServer                [22] BOOLEAN DEFAULT TRUE,
134  *     peerSignatureAlgorithm  [23] INTEGER OPTIONAL,
135  *     ticketMaxEarlyData      [24] INTEGER OPTIONAL,
136  *     authTimeout             [25] INTEGER OPTIONAL, -- defaults to timeout
137  *     earlyALPN               [26] OCTET STRING OPTIONAL,
138  * }
139  *
140  * Note: historically this serialization has included other optional
141  * fields. Their presence is currently treated as a parse error:
142  *
143  *     keyArg                  [0] IMPLICIT OCTET STRING OPTIONAL,
144  *     pskIdentityHint         [7] OCTET STRING OPTIONAL,
145  *     compressionMethod       [11] OCTET STRING OPTIONAL,
146  *     srpUsername             [12] OCTET STRING OPTIONAL,
147  *     ticketFlags             [20] INTEGER OPTIONAL,
148  */
149 
150 static const unsigned kVersion = 1;
151 
152 static const int kTimeTag =
153     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 1;
154 static const int kTimeoutTag =
155     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 2;
156 static const int kPeerTag =
157     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 3;
158 static const int kSessionIDContextTag =
159     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 4;
160 static const int kVerifyResultTag =
161     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 5;
162 static const int kHostNameTag =
163     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 6;
164 static const int kPSKIdentityTag =
165     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 8;
166 static const int kTicketLifetimeHintTag =
167     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 9;
168 static const int kTicketTag =
169     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 10;
170 static const int kPeerSHA256Tag =
171     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 13;
172 static const int kOriginalHandshakeHashTag =
173     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 14;
174 static const int kSignedCertTimestampListTag =
175     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 15;
176 static const int kOCSPResponseTag =
177     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 16;
178 static const int kExtendedMasterSecretTag =
179     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 17;
180 static const int kGroupIDTag =
181     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 18;
182 static const int kCertChainTag =
183     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 19;
184 static const int kTicketAgeAddTag =
185     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 21;
186 static const int kIsServerTag =
187     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 22;
188 static const int kPeerSignatureAlgorithmTag =
189     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 23;
190 static const int kTicketMaxEarlyDataTag =
191     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 24;
192 static const int kAuthTimeoutTag =
193     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 25;
194 static const int kEarlyALPNTag =
195     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 26;
196 
SSL_SESSION_to_bytes_full(const SSL_SESSION * in,uint8_t ** out_data,size_t * out_len,int for_ticket)197 static int SSL_SESSION_to_bytes_full(const SSL_SESSION *in, uint8_t **out_data,
198                                      size_t *out_len, int for_ticket) {
199   CBB cbb, session, child, child2;
200 
201   if (in == NULL || in->cipher == NULL) {
202     return 0;
203   }
204 
205   CBB_zero(&cbb);
206   if (!CBB_init(&cbb, 0) ||
207       !CBB_add_asn1(&cbb, &session, CBS_ASN1_SEQUENCE) ||
208       !CBB_add_asn1_uint64(&session, kVersion) ||
209       !CBB_add_asn1_uint64(&session, in->ssl_version) ||
210       !CBB_add_asn1(&session, &child, CBS_ASN1_OCTETSTRING) ||
211       !CBB_add_u16(&child, (uint16_t)(in->cipher->id & 0xffff)) ||
212       !CBB_add_asn1(&session, &child, CBS_ASN1_OCTETSTRING) ||
213       /* The session ID is irrelevant for a session ticket. */
214       !CBB_add_bytes(&child, in->session_id,
215                      for_ticket ? 0 : in->session_id_length) ||
216       !CBB_add_asn1(&session, &child, CBS_ASN1_OCTETSTRING) ||
217       !CBB_add_bytes(&child, in->master_key, in->master_key_length) ||
218       !CBB_add_asn1(&session, &child, kTimeTag) ||
219       !CBB_add_asn1_uint64(&child, in->time) ||
220       !CBB_add_asn1(&session, &child, kTimeoutTag) ||
221       !CBB_add_asn1_uint64(&child, in->timeout)) {
222     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
223     goto err;
224   }
225 
226   /* The peer certificate is only serialized if the SHA-256 isn't
227    * serialized instead. */
228   if (sk_CRYPTO_BUFFER_num(in->certs) > 0 && !in->peer_sha256_valid) {
229     const CRYPTO_BUFFER *buffer = sk_CRYPTO_BUFFER_value(in->certs, 0);
230     if (!CBB_add_asn1(&session, &child, kPeerTag) ||
231         !CBB_add_bytes(&child, CRYPTO_BUFFER_data(buffer),
232                        CRYPTO_BUFFER_len(buffer))) {
233       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
234       goto err;
235     }
236   }
237 
238   /* Although it is OPTIONAL and usually empty, OpenSSL has
239    * historically always encoded the sid_ctx. */
240   if (!CBB_add_asn1(&session, &child, kSessionIDContextTag) ||
241       !CBB_add_asn1(&child, &child2, CBS_ASN1_OCTETSTRING) ||
242       !CBB_add_bytes(&child2, in->sid_ctx, in->sid_ctx_length)) {
243     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
244     goto err;
245   }
246 
247   if (in->verify_result != X509_V_OK) {
248     if (!CBB_add_asn1(&session, &child, kVerifyResultTag) ||
249         !CBB_add_asn1_uint64(&child, in->verify_result)) {
250       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
251       goto err;
252     }
253   }
254 
255   if (in->tlsext_hostname) {
256     if (!CBB_add_asn1(&session, &child, kHostNameTag) ||
257         !CBB_add_asn1(&child, &child2, CBS_ASN1_OCTETSTRING) ||
258         !CBB_add_bytes(&child2, (const uint8_t *)in->tlsext_hostname,
259                        strlen(in->tlsext_hostname))) {
260       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
261       goto err;
262     }
263   }
264 
265   if (in->psk_identity) {
266     if (!CBB_add_asn1(&session, &child, kPSKIdentityTag) ||
267         !CBB_add_asn1(&child, &child2, CBS_ASN1_OCTETSTRING) ||
268         !CBB_add_bytes(&child2, (const uint8_t *)in->psk_identity,
269                        strlen(in->psk_identity))) {
270       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
271       goto err;
272     }
273   }
274 
275   if (in->tlsext_tick_lifetime_hint > 0) {
276     if (!CBB_add_asn1(&session, &child, kTicketLifetimeHintTag) ||
277         !CBB_add_asn1_uint64(&child, in->tlsext_tick_lifetime_hint)) {
278       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
279       goto err;
280     }
281   }
282 
283   if (in->tlsext_tick && !for_ticket) {
284     if (!CBB_add_asn1(&session, &child, kTicketTag) ||
285         !CBB_add_asn1(&child, &child2, CBS_ASN1_OCTETSTRING) ||
286         !CBB_add_bytes(&child2, in->tlsext_tick, in->tlsext_ticklen)) {
287       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
288       goto err;
289     }
290   }
291 
292   if (in->peer_sha256_valid) {
293     if (!CBB_add_asn1(&session, &child, kPeerSHA256Tag) ||
294         !CBB_add_asn1(&child, &child2, CBS_ASN1_OCTETSTRING) ||
295         !CBB_add_bytes(&child2, in->peer_sha256, sizeof(in->peer_sha256))) {
296       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
297       goto err;
298     }
299   }
300 
301   if (in->original_handshake_hash_len > 0) {
302     if (!CBB_add_asn1(&session, &child, kOriginalHandshakeHashTag) ||
303         !CBB_add_asn1(&child, &child2, CBS_ASN1_OCTETSTRING) ||
304         !CBB_add_bytes(&child2, in->original_handshake_hash,
305                        in->original_handshake_hash_len)) {
306       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
307       goto err;
308     }
309   }
310 
311   if (in->tlsext_signed_cert_timestamp_list_length > 0) {
312     if (!CBB_add_asn1(&session, &child, kSignedCertTimestampListTag) ||
313         !CBB_add_asn1(&child, &child2, CBS_ASN1_OCTETSTRING) ||
314         !CBB_add_bytes(&child2, in->tlsext_signed_cert_timestamp_list,
315                        in->tlsext_signed_cert_timestamp_list_length)) {
316       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
317       goto err;
318     }
319   }
320 
321   if (in->ocsp_response_length > 0) {
322     if (!CBB_add_asn1(&session, &child, kOCSPResponseTag) ||
323         !CBB_add_asn1(&child, &child2, CBS_ASN1_OCTETSTRING) ||
324         !CBB_add_bytes(&child2, in->ocsp_response, in->ocsp_response_length)) {
325       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
326       goto err;
327     }
328   }
329 
330   if (in->extended_master_secret) {
331     if (!CBB_add_asn1(&session, &child, kExtendedMasterSecretTag) ||
332         !CBB_add_asn1(&child, &child2, CBS_ASN1_BOOLEAN) ||
333         !CBB_add_u8(&child2, 0xff)) {
334       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
335       goto err;
336     }
337   }
338 
339   if (in->group_id > 0 &&
340       (!CBB_add_asn1(&session, &child, kGroupIDTag) ||
341        !CBB_add_asn1_uint64(&child, in->group_id))) {
342     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
343     goto err;
344   }
345 
346   /* The certificate chain is only serialized if the leaf's SHA-256 isn't
347    * serialized instead. */
348   if (in->certs != NULL &&
349       !in->peer_sha256_valid &&
350       sk_CRYPTO_BUFFER_num(in->certs) >= 2) {
351     if (!CBB_add_asn1(&session, &child, kCertChainTag)) {
352       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
353       goto err;
354     }
355     for (size_t i = 1; i < sk_CRYPTO_BUFFER_num(in->certs); i++) {
356       const CRYPTO_BUFFER *buffer = sk_CRYPTO_BUFFER_value(in->certs, i);
357       if (!CBB_add_bytes(&child, CRYPTO_BUFFER_data(buffer),
358                          CRYPTO_BUFFER_len(buffer))) {
359         OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
360         goto err;
361       }
362     }
363   }
364 
365   if (in->ticket_age_add_valid) {
366     if (!CBB_add_asn1(&session, &child, kTicketAgeAddTag) ||
367         !CBB_add_asn1(&child, &child2, CBS_ASN1_OCTETSTRING) ||
368         !CBB_add_u32(&child2, in->ticket_age_add)) {
369       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
370       goto err;
371     }
372   }
373 
374   if (!in->is_server) {
375     if (!CBB_add_asn1(&session, &child, kIsServerTag) ||
376         !CBB_add_asn1(&child, &child2, CBS_ASN1_BOOLEAN) ||
377         !CBB_add_u8(&child2, 0x00)) {
378       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
379       goto err;
380     }
381   }
382 
383   if (in->peer_signature_algorithm != 0 &&
384       (!CBB_add_asn1(&session, &child, kPeerSignatureAlgorithmTag) ||
385        !CBB_add_asn1_uint64(&child, in->peer_signature_algorithm))) {
386     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
387     goto err;
388   }
389 
390   if (in->ticket_max_early_data != 0 &&
391       (!CBB_add_asn1(&session, &child, kTicketMaxEarlyDataTag) ||
392        !CBB_add_asn1_uint64(&child, in->ticket_max_early_data))) {
393     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
394     goto err;
395   }
396 
397   if (in->timeout != in->auth_timeout &&
398       (!CBB_add_asn1(&session, &child, kAuthTimeoutTag) ||
399        !CBB_add_asn1_uint64(&child, in->auth_timeout))) {
400     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
401     goto err;
402   }
403 
404   if (in->early_alpn) {
405     if (!CBB_add_asn1(&session, &child, kEarlyALPNTag) ||
406         !CBB_add_asn1(&child, &child2, CBS_ASN1_OCTETSTRING) ||
407         !CBB_add_bytes(&child2, (const uint8_t *)in->early_alpn,
408                        in->early_alpn_len)) {
409       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
410       goto err;
411     }
412   }
413 
414   if (!CBB_finish(&cbb, out_data, out_len)) {
415     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
416     goto err;
417   }
418   return 1;
419 
420  err:
421   CBB_cleanup(&cbb);
422   return 0;
423 }
424 
SSL_SESSION_to_bytes(const SSL_SESSION * in,uint8_t ** out_data,size_t * out_len)425 int SSL_SESSION_to_bytes(const SSL_SESSION *in, uint8_t **out_data,
426                          size_t *out_len) {
427   if (in->not_resumable) {
428     /* If the caller has an unresumable session, e.g. if |SSL_get_session| were
429      * called on a TLS 1.3 or False Started connection, serialize with a
430      * placeholder value so it is not accidentally deserialized into a resumable
431      * one. */
432     static const char kNotResumableSession[] = "NOT RESUMABLE";
433 
434     *out_len = strlen(kNotResumableSession);
435     *out_data = (uint8_t *)BUF_memdup(kNotResumableSession, *out_len);
436     if (*out_data == NULL) {
437       return 0;
438     }
439 
440     return 1;
441   }
442 
443   return SSL_SESSION_to_bytes_full(in, out_data, out_len, 0);
444 }
445 
SSL_SESSION_to_bytes_for_ticket(const SSL_SESSION * in,uint8_t ** out_data,size_t * out_len)446 int SSL_SESSION_to_bytes_for_ticket(const SSL_SESSION *in, uint8_t **out_data,
447                                     size_t *out_len) {
448   return SSL_SESSION_to_bytes_full(in, out_data, out_len, 1);
449 }
450 
i2d_SSL_SESSION(SSL_SESSION * in,uint8_t ** pp)451 int i2d_SSL_SESSION(SSL_SESSION *in, uint8_t **pp) {
452   uint8_t *out;
453   size_t len;
454 
455   if (!SSL_SESSION_to_bytes(in, &out, &len)) {
456     return -1;
457   }
458 
459   if (len > INT_MAX) {
460     OPENSSL_free(out);
461     OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
462     return -1;
463   }
464 
465   if (pp) {
466     OPENSSL_memcpy(*pp, out, len);
467     *pp += len;
468   }
469   OPENSSL_free(out);
470 
471   return len;
472 }
473 
474 /* SSL_SESSION_parse_string gets an optional ASN.1 OCTET STRING
475  * explicitly tagged with |tag| from |cbs| and saves it in |*out|. On
476  * entry, if |*out| is not NULL, it frees the existing contents. If
477  * the element was not found, it sets |*out| to NULL. It returns one
478  * on success, whether or not the element was found, and zero on
479  * decode error. */
SSL_SESSION_parse_string(CBS * cbs,char ** out,unsigned tag)480 static int SSL_SESSION_parse_string(CBS *cbs, char **out, unsigned tag) {
481   CBS value;
482   int present;
483   if (!CBS_get_optional_asn1_octet_string(cbs, &value, &present, tag)) {
484     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
485     return 0;
486   }
487   if (present) {
488     if (CBS_contains_zero_byte(&value)) {
489       OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
490       return 0;
491     }
492     if (!CBS_strdup(&value, out)) {
493       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
494       return 0;
495     }
496   } else {
497     OPENSSL_free(*out);
498     *out = NULL;
499   }
500   return 1;
501 }
502 
503 /* SSL_SESSION_parse_string gets an optional ASN.1 OCTET STRING
504  * explicitly tagged with |tag| from |cbs| and stows it in |*out_ptr|
505  * and |*out_len|. If |*out_ptr| is not NULL, it frees the existing
506  * contents. On entry, if the element was not found, it sets
507  * |*out_ptr| to NULL. It returns one on success, whether or not the
508  * element was found, and zero on decode error. */
SSL_SESSION_parse_octet_string(CBS * cbs,uint8_t ** out_ptr,size_t * out_len,unsigned tag)509 static int SSL_SESSION_parse_octet_string(CBS *cbs, uint8_t **out_ptr,
510                                           size_t *out_len, unsigned tag) {
511   CBS value;
512   if (!CBS_get_optional_asn1_octet_string(cbs, &value, NULL, tag)) {
513     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
514     return 0;
515   }
516   if (!CBS_stow(&value, out_ptr, out_len)) {
517     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
518     return 0;
519   }
520   return 1;
521 }
522 
523 /* SSL_SESSION_parse_bounded_octet_string parses an optional ASN.1 OCTET STRING
524  * explicitly tagged with |tag| of size at most |max_out|. */
SSL_SESSION_parse_bounded_octet_string(CBS * cbs,uint8_t * out,uint8_t * out_len,uint8_t max_out,unsigned tag)525 static int SSL_SESSION_parse_bounded_octet_string(
526     CBS *cbs, uint8_t *out, uint8_t *out_len, uint8_t max_out, unsigned tag) {
527   CBS value;
528   if (!CBS_get_optional_asn1_octet_string(cbs, &value, NULL, tag) ||
529       CBS_len(&value) > max_out) {
530     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
531     return 0;
532   }
533   OPENSSL_memcpy(out, CBS_data(&value), CBS_len(&value));
534   *out_len = (uint8_t)CBS_len(&value);
535   return 1;
536 }
537 
SSL_SESSION_parse_long(CBS * cbs,long * out,unsigned tag,long default_value)538 static int SSL_SESSION_parse_long(CBS *cbs, long *out, unsigned tag,
539                                   long default_value) {
540   uint64_t value;
541   if (!CBS_get_optional_asn1_uint64(cbs, &value, tag,
542                                     (uint64_t)default_value) ||
543       value > LONG_MAX) {
544     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
545     return 0;
546   }
547   *out = (long)value;
548   return 1;
549 }
550 
SSL_SESSION_parse_u32(CBS * cbs,uint32_t * out,unsigned tag,uint32_t default_value)551 static int SSL_SESSION_parse_u32(CBS *cbs, uint32_t *out, unsigned tag,
552                                  uint32_t default_value) {
553   uint64_t value;
554   if (!CBS_get_optional_asn1_uint64(cbs, &value, tag,
555                                     (uint64_t)default_value) ||
556       value > 0xffffffff) {
557     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
558     return 0;
559   }
560   *out = (uint32_t)value;
561   return 1;
562 }
563 
SSL_SESSION_parse_u16(CBS * cbs,uint16_t * out,unsigned tag,uint16_t default_value)564 static int SSL_SESSION_parse_u16(CBS *cbs, uint16_t *out, unsigned tag,
565                                  uint16_t default_value) {
566   uint64_t value;
567   if (!CBS_get_optional_asn1_uint64(cbs, &value, tag,
568                                     (uint64_t)default_value) ||
569       value > 0xffff) {
570     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
571     return 0;
572   }
573   *out = (uint16_t)value;
574   return 1;
575 }
576 
SSL_SESSION_parse(CBS * cbs,const SSL_X509_METHOD * x509_method,CRYPTO_BUFFER_POOL * pool)577 SSL_SESSION *SSL_SESSION_parse(CBS *cbs, const SSL_X509_METHOD *x509_method,
578                                CRYPTO_BUFFER_POOL *pool) {
579   SSL_SESSION *ret = ssl_session_new(x509_method);
580   if (ret == NULL) {
581     goto err;
582   }
583 
584   CBS session;
585   uint64_t version, ssl_version;
586   uint16_t unused;
587   if (!CBS_get_asn1(cbs, &session, CBS_ASN1_SEQUENCE) ||
588       !CBS_get_asn1_uint64(&session, &version) ||
589       version != kVersion ||
590       !CBS_get_asn1_uint64(&session, &ssl_version) ||
591       /* Require sessions have versions valid in either TLS or DTLS. The session
592        * will not be used by the handshake if not applicable, but, for
593        * simplicity, never parse a session that does not pass
594        * |ssl_protocol_version_from_wire|. */
595       ssl_version > UINT16_MAX ||
596       !ssl_protocol_version_from_wire(&unused, ssl_version)) {
597     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
598     goto err;
599   }
600   ret->ssl_version = ssl_version;
601 
602   CBS cipher;
603   uint16_t cipher_value;
604   if (!CBS_get_asn1(&session, &cipher, CBS_ASN1_OCTETSTRING) ||
605       !CBS_get_u16(&cipher, &cipher_value) ||
606       CBS_len(&cipher) != 0) {
607     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
608     goto err;
609   }
610   ret->cipher = SSL_get_cipher_by_value(cipher_value);
611   if (ret->cipher == NULL) {
612     OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_CIPHER);
613     goto err;
614   }
615 
616   CBS session_id, master_key;
617   if (!CBS_get_asn1(&session, &session_id, CBS_ASN1_OCTETSTRING) ||
618       CBS_len(&session_id) > SSL3_MAX_SSL_SESSION_ID_LENGTH ||
619       !CBS_get_asn1(&session, &master_key, CBS_ASN1_OCTETSTRING) ||
620       CBS_len(&master_key) > SSL_MAX_MASTER_KEY_LENGTH) {
621     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
622     goto err;
623   }
624   OPENSSL_memcpy(ret->session_id, CBS_data(&session_id), CBS_len(&session_id));
625   ret->session_id_length = CBS_len(&session_id);
626   OPENSSL_memcpy(ret->master_key, CBS_data(&master_key), CBS_len(&master_key));
627   ret->master_key_length = CBS_len(&master_key);
628 
629   CBS child;
630   uint64_t timeout;
631   if (!CBS_get_asn1(&session, &child, kTimeTag) ||
632       !CBS_get_asn1_uint64(&child, &ret->time) ||
633       !CBS_get_asn1(&session, &child, kTimeoutTag) ||
634       !CBS_get_asn1_uint64(&child, &timeout) ||
635       timeout > UINT32_MAX) {
636     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
637     goto err;
638   }
639 
640   ret->timeout = (uint32_t)timeout;
641 
642   CBS peer;
643   int has_peer;
644   if (!CBS_get_optional_asn1(&session, &peer, &has_peer, kPeerTag) ||
645       (has_peer && CBS_len(&peer) == 0)) {
646     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
647     goto err;
648   }
649   /* |peer| is processed with the certificate chain. */
650 
651   if (!SSL_SESSION_parse_bounded_octet_string(
652           &session, ret->sid_ctx, &ret->sid_ctx_length, sizeof(ret->sid_ctx),
653           kSessionIDContextTag) ||
654       !SSL_SESSION_parse_long(&session, &ret->verify_result, kVerifyResultTag,
655                               X509_V_OK) ||
656       !SSL_SESSION_parse_string(&session, &ret->tlsext_hostname,
657                                 kHostNameTag) ||
658       !SSL_SESSION_parse_string(&session, &ret->psk_identity,
659                                 kPSKIdentityTag) ||
660       !SSL_SESSION_parse_u32(&session, &ret->tlsext_tick_lifetime_hint,
661                              kTicketLifetimeHintTag, 0) ||
662       !SSL_SESSION_parse_octet_string(&session, &ret->tlsext_tick,
663                                       &ret->tlsext_ticklen, kTicketTag)) {
664     goto err;
665   }
666 
667   if (CBS_peek_asn1_tag(&session, kPeerSHA256Tag)) {
668     CBS peer_sha256;
669     if (!CBS_get_asn1(&session, &child, kPeerSHA256Tag) ||
670         !CBS_get_asn1(&child, &peer_sha256, CBS_ASN1_OCTETSTRING) ||
671         CBS_len(&peer_sha256) != sizeof(ret->peer_sha256) ||
672         CBS_len(&child) != 0) {
673       OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
674       goto err;
675     }
676     OPENSSL_memcpy(ret->peer_sha256, CBS_data(&peer_sha256),
677                    sizeof(ret->peer_sha256));
678     ret->peer_sha256_valid = 1;
679   } else {
680     ret->peer_sha256_valid = 0;
681   }
682 
683   if (!SSL_SESSION_parse_bounded_octet_string(
684           &session, ret->original_handshake_hash,
685           &ret->original_handshake_hash_len,
686           sizeof(ret->original_handshake_hash), kOriginalHandshakeHashTag) ||
687       !SSL_SESSION_parse_octet_string(
688           &session, &ret->tlsext_signed_cert_timestamp_list,
689           &ret->tlsext_signed_cert_timestamp_list_length,
690           kSignedCertTimestampListTag) ||
691       !SSL_SESSION_parse_octet_string(
692           &session, &ret->ocsp_response, &ret->ocsp_response_length,
693           kOCSPResponseTag)) {
694     goto err;
695   }
696 
697   int extended_master_secret;
698   if (!CBS_get_optional_asn1_bool(&session, &extended_master_secret,
699                                   kExtendedMasterSecretTag,
700                                   0 /* default to false */)) {
701     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
702     goto err;
703   }
704   ret->extended_master_secret = !!extended_master_secret;
705 
706   if (!SSL_SESSION_parse_u16(&session, &ret->group_id, kGroupIDTag, 0)) {
707     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
708     goto err;
709   }
710 
711   CBS cert_chain;
712   CBS_init(&cert_chain, NULL, 0);
713   int has_cert_chain;
714   if (!CBS_get_optional_asn1(&session, &cert_chain, &has_cert_chain,
715                              kCertChainTag) ||
716       (has_cert_chain && CBS_len(&cert_chain) == 0)) {
717     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
718     goto err;
719   }
720   if (has_cert_chain && !has_peer) {
721     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
722     goto err;
723   }
724   if (has_peer || has_cert_chain) {
725     ret->certs = sk_CRYPTO_BUFFER_new_null();
726     if (ret->certs == NULL) {
727       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
728       goto err;
729     }
730 
731     if (has_peer) {
732       /* TODO(agl): this should use the |SSL_CTX|'s pool. */
733       CRYPTO_BUFFER *buffer = CRYPTO_BUFFER_new_from_CBS(&peer, pool);
734       if (buffer == NULL ||
735           !sk_CRYPTO_BUFFER_push(ret->certs, buffer)) {
736         CRYPTO_BUFFER_free(buffer);
737         OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
738         goto err;
739       }
740     }
741 
742     while (CBS_len(&cert_chain) > 0) {
743       CBS cert;
744       if (!CBS_get_any_asn1_element(&cert_chain, &cert, NULL, NULL) ||
745           CBS_len(&cert) == 0) {
746         OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
747         goto err;
748       }
749 
750       /* TODO(agl): this should use the |SSL_CTX|'s pool. */
751       CRYPTO_BUFFER *buffer = CRYPTO_BUFFER_new_from_CBS(&cert, pool);
752       if (buffer == NULL ||
753           !sk_CRYPTO_BUFFER_push(ret->certs, buffer)) {
754         CRYPTO_BUFFER_free(buffer);
755         OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
756         goto err;
757       }
758     }
759   }
760 
761   if (!x509_method->session_cache_objects(ret)) {
762     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
763     goto err;
764   }
765 
766   CBS age_add;
767   int age_add_present;
768   if (!CBS_get_optional_asn1_octet_string(&session, &age_add, &age_add_present,
769                                           kTicketAgeAddTag) ||
770       (age_add_present &&
771        !CBS_get_u32(&age_add, &ret->ticket_age_add)) ||
772       CBS_len(&age_add) != 0) {
773     goto err;
774   }
775   ret->ticket_age_add_valid = age_add_present;
776 
777   int is_server;
778   if (!CBS_get_optional_asn1_bool(&session, &is_server, kIsServerTag,
779                                   1 /* default to true */)) {
780     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
781     goto err;
782   }
783   /* TODO: in time we can include |is_server| for servers too, then we can
784      enforce that client and server sessions are never mixed up. */
785 
786   ret->is_server = is_server;
787 
788   if (!SSL_SESSION_parse_u16(&session, &ret->peer_signature_algorithm,
789                              kPeerSignatureAlgorithmTag, 0) ||
790       !SSL_SESSION_parse_u32(&session, &ret->ticket_max_early_data,
791                              kTicketMaxEarlyDataTag, 0) ||
792       !SSL_SESSION_parse_u32(&session, &ret->auth_timeout, kAuthTimeoutTag,
793                              ret->timeout) ||
794       !SSL_SESSION_parse_octet_string(&session, &ret->early_alpn,
795                                       &ret->early_alpn_len, kEarlyALPNTag) ||
796       CBS_len(&session) != 0) {
797     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
798     goto err;
799   }
800 
801   return ret;
802 
803 err:
804   SSL_SESSION_free(ret);
805   return NULL;
806 }
807 
SSL_SESSION_from_bytes(const uint8_t * in,size_t in_len,const SSL_CTX * ctx)808 SSL_SESSION *SSL_SESSION_from_bytes(const uint8_t *in, size_t in_len,
809                                     const SSL_CTX *ctx) {
810   CBS cbs;
811   CBS_init(&cbs, in, in_len);
812   SSL_SESSION *ret = SSL_SESSION_parse(&cbs, ctx->x509_method, ctx->pool);
813   if (ret == NULL) {
814     return NULL;
815   }
816   if (CBS_len(&cbs) != 0) {
817     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_SSL_SESSION);
818     SSL_SESSION_free(ret);
819     return NULL;
820   }
821   return ret;
822 }
823