Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / third_party / mbedtls / repo / library / ssl_ticket.c
1 /*
2  *  TLS server tickets callbacks implementation
3  *
4  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
5  *  SPDX-License-Identifier: Apache-2.0
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8  *  not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *  http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *
19  *  This file is part of mbed TLS (https://tls.mbed.org)
20  */
21
22 #if !defined(MBEDTLS_CONFIG_FILE)
23 #include "mbedtls/config.h"
24 #else
25 #include MBEDTLS_CONFIG_FILE
26 #endif
27
28 #if defined(MBEDTLS_SSL_TICKET_C)
29
30 #if defined(MBEDTLS_PLATFORM_C)
31 #include "mbedtls/platform.h"
32 #else
33 #include <stdlib.h>
34 #define mbedtls_calloc    calloc
35 #define mbedtls_free      free
36 #endif
37
38 #include "mbedtls/ssl_ticket.h"
39 #include "mbedtls/platform_util.h"
40
41 #include <string.h>
42
43 /*
44  * Initialze context
45  */
46 void mbedtls_ssl_ticket_init( mbedtls_ssl_ticket_context *ctx )
47 {
48     memset( ctx, 0, sizeof( mbedtls_ssl_ticket_context ) );
49
50 #if defined(MBEDTLS_THREADING_C)
51     mbedtls_mutex_init( &ctx->mutex );
52 #endif
53 }
54
55 #define MAX_KEY_BYTES 32    /* 256 bits */
56
57 #define TICKET_KEY_NAME_BYTES    4
58 #define TICKET_IV_BYTES         12
59 #define TICKET_CRYPT_LEN_BYTES   2
60 #define TICKET_AUTH_TAG_BYTES   16
61
62 #define TICKET_MIN_LEN ( TICKET_KEY_NAME_BYTES  +        \
63                          TICKET_IV_BYTES        +        \
64                          TICKET_CRYPT_LEN_BYTES +        \
65                          TICKET_AUTH_TAG_BYTES )
66 #define TICKET_ADD_DATA_LEN ( TICKET_KEY_NAME_BYTES  +        \
67                               TICKET_IV_BYTES        +        \
68                               TICKET_CRYPT_LEN_BYTES )
69
70 /*
71  * Generate/update a key
72  */
73 static int ssl_ticket_gen_key( mbedtls_ssl_ticket_context *ctx,
74                                unsigned char index )
75 {
76     int ret;
77     unsigned char buf[MAX_KEY_BYTES];
78     mbedtls_ssl_ticket_key *key = ctx->keys + index;
79
80 #if defined(MBEDTLS_HAVE_TIME)
81     key->generation_time = (uint32_t) mbedtls_time( NULL );
82 #endif
83
84     if( ( ret = ctx->f_rng( ctx->p_rng, key->name, sizeof( key->name ) ) ) != 0 )
85         return( ret );
86
87     if( ( ret = ctx->f_rng( ctx->p_rng, buf, sizeof( buf ) ) ) != 0 )
88         return( ret );
89
90     /* With GCM and CCM, same context can encrypt & decrypt */
91     ret = mbedtls_cipher_setkey( &key->ctx, buf,
92                                  mbedtls_cipher_get_key_bitlen( &key->ctx ),
93                                  MBEDTLS_ENCRYPT );
94
95     mbedtls_platform_zeroize( buf, sizeof( buf ) );
96
97     return( ret );
98 }
99
100 /*
101  * Rotate/generate keys if necessary
102  */
103 static int ssl_ticket_update_keys( mbedtls_ssl_ticket_context *ctx )
104 {
105 #if !defined(MBEDTLS_HAVE_TIME)
106     ((void) ctx);
107 #else
108     if( ctx->ticket_lifetime != 0 )
109     {
110         uint32_t current_time = (uint32_t) mbedtls_time( NULL );
111         uint32_t key_time = ctx->keys[ctx->active].generation_time;
112
113         if( current_time >= key_time &&
114             current_time - key_time < ctx->ticket_lifetime )
115         {
116             return( 0 );
117         }
118
119         ctx->active = 1 - ctx->active;
120
121         return( ssl_ticket_gen_key( ctx, ctx->active ) );
122     }
123     else
124 #endif /* MBEDTLS_HAVE_TIME */
125         return( 0 );
126 }
127
128 /*
129  * Setup context for actual use
130  */
131 int mbedtls_ssl_ticket_setup( mbedtls_ssl_ticket_context *ctx,
132     int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
133     mbedtls_cipher_type_t cipher,
134     uint32_t lifetime )
135 {
136     int ret;
137     const mbedtls_cipher_info_t *cipher_info;
138
139     ctx->f_rng = f_rng;
140     ctx->p_rng = p_rng;
141
142     ctx->ticket_lifetime = lifetime;
143
144     cipher_info = mbedtls_cipher_info_from_type( cipher);
145     if( cipher_info == NULL )
146         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
147
148     if( cipher_info->mode != MBEDTLS_MODE_GCM &&
149         cipher_info->mode != MBEDTLS_MODE_CCM )
150     {
151         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
152     }
153
154     if( cipher_info->key_bitlen > 8 * MAX_KEY_BYTES )
155         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
156
157 #if defined(MBEDTLS_USE_PSA_CRYPTO)
158     ret = mbedtls_cipher_setup_psa( &ctx->keys[0].ctx,
159                                     cipher_info, TICKET_AUTH_TAG_BYTES );
160     if( ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE )
161         return( ret );
162     /* We don't yet expect to support all ciphers through PSA,
163      * so allow fallback to ordinary mbedtls_cipher_setup(). */
164     if( ret == MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE )
165 #endif /* MBEDTLS_USE_PSA_CRYPTO */
166     if( ( ret = mbedtls_cipher_setup( &ctx->keys[0].ctx, cipher_info ) ) != 0 )
167         return( ret );
168
169 #if defined(MBEDTLS_USE_PSA_CRYPTO)
170     ret = mbedtls_cipher_setup_psa( &ctx->keys[1].ctx,
171                                     cipher_info, TICKET_AUTH_TAG_BYTES );
172     if( ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE )
173         return( ret );
174     if( ret == MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE )
175 #endif /* MBEDTLS_USE_PSA_CRYPTO */
176     if( ( ret = mbedtls_cipher_setup( &ctx->keys[1].ctx, cipher_info ) ) != 0 )
177         return( ret );
178
179     if( ( ret = ssl_ticket_gen_key( ctx, 0 ) ) != 0 ||
180         ( ret = ssl_ticket_gen_key( ctx, 1 ) ) != 0 )
181     {
182         return( ret );
183     }
184
185     return( 0 );
186 }
187
188 /*
189  * Serialize a session in the following format:
190  *
191  * - If MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is enabled:
192  *    0       .   n-1   session structure, n = sizeof(mbedtls_ssl_session)
193  *    n       .   n+2   peer_cert length = m (0 if no certificate)
194  *    n+3     .   n+2+m peer cert ASN.1
195  *
196  * - If MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is disabled:
197  *    0       .   n-1   session structure, n = sizeof(mbedtls_ssl_session)
198  *    n       .   n     length of peer certificate digest = k (0 if no digest)
199  *    n+1     .   n+k   peer certificate digest (digest type encoded in session)
200  */
201 static int ssl_save_session( const mbedtls_ssl_session *session,
202                              unsigned char *buf, size_t buf_len,
203                              size_t *olen )
204 {
205     unsigned char *p = buf;
206     size_t left = buf_len;
207 #if defined(MBEDTLS_X509_CRT_PARSE_C)
208 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
209     size_t cert_len;
210 #else
211     size_t cert_digest_len;
212 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
213 #endif /* MBEDTLS_X509_CRT_PARSE_C */
214
215     if( left < sizeof( mbedtls_ssl_session ) )
216         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
217
218     /* This also copies the values of pointer fields in the
219      * session to be serialized, but they'll be ignored when
220      * loading the session through ssl_load_session(). */
221     memcpy( p, session, sizeof( mbedtls_ssl_session ) );
222     p += sizeof( mbedtls_ssl_session );
223     left -= sizeof( mbedtls_ssl_session );
224
225 #if defined(MBEDTLS_X509_CRT_PARSE_C)
226 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
227     if( session->peer_cert == NULL )
228         cert_len = 0;
229     else
230         cert_len = session->peer_cert->raw.len;
231
232     if( left < 3 + cert_len )
233         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
234
235     *p++ = (unsigned char)( ( cert_len >> 16 ) & 0xFF );
236     *p++ = (unsigned char)( ( cert_len >>  8 ) & 0xFF );
237     *p++ = (unsigned char)( ( cert_len       ) & 0xFF );
238     left -= 3;
239
240     if( session->peer_cert != NULL )
241         memcpy( p, session->peer_cert->raw.p, cert_len );
242
243     p += cert_len;
244     left -= cert_len;
245 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
246     if( session->peer_cert_digest != NULL )
247         cert_digest_len = 0;
248     else
249         cert_digest_len = session->peer_cert_digest_len;
250
251     if( left < 1 + cert_digest_len )
252         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
253
254     *p++ = (unsigned char) cert_digest_len;
255     left--;
256
257     if( session->peer_cert_digest != NULL )
258         memcpy( p, session->peer_cert_digest, cert_digest_len );
259
260     p    += cert_digest_len;
261     left -= cert_digest_len;
262 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
263 #endif /* MBEDTLS_X509_CRT_PARSE_C */
264
265     *olen = p - buf;
266
267     return( 0 );
268 }
269
270 /*
271  * Unserialise session, see ssl_save_session()
272  */
273 static int ssl_load_session( mbedtls_ssl_session *session,
274                              const unsigned char *buf, size_t len )
275 {
276     const unsigned char *p = buf;
277     const unsigned char * const end = buf + len;
278 #if defined(MBEDTLS_X509_CRT_PARSE_C)
279 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
280     size_t cert_len;
281 #else
282     size_t cert_digest_len;
283 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
284 #endif /* MBEDTLS_X509_CRT_PARSE_C */
285
286     if( sizeof( mbedtls_ssl_session ) > (size_t)( end - p ) )
287         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
288
289     memcpy( session, p, sizeof( mbedtls_ssl_session ) );
290     p += sizeof( mbedtls_ssl_session );
291
292     /* Non-NULL pointer fields of `session` are meaningless
293      * and potentially harmful. Zeroize them for safety. */
294 #if defined(MBEDTLS_X509_CRT_PARSE_C)
295 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
296     session->peer_cert = NULL;
297 #else
298     session->peer_cert_digest = NULL;
299 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
300 #endif /* MBEDTLS_X509_CRT_PARSE_C */
301 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
302     session->ticket = NULL;
303 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
304
305 #if defined(MBEDTLS_X509_CRT_PARSE_C)
306 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
307     /* Deserialize CRT from the end of the ticket. */
308     if( 3 > (size_t)( end - p ) )
309         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
310
311     cert_len = ( p[0] << 16 ) | ( p[1] << 8 ) | p[2];
312     p += 3;
313
314     if( cert_len != 0 )
315     {
316         int ret;
317
318         if( cert_len > (size_t)( end - p ) )
319             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
320
321         session->peer_cert = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) );
322
323         if( session->peer_cert == NULL )
324             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
325
326         mbedtls_x509_crt_init( session->peer_cert );
327
328         if( ( ret = mbedtls_x509_crt_parse_der( session->peer_cert,
329                                                 p, cert_len ) ) != 0 )
330         {
331             mbedtls_x509_crt_free( session->peer_cert );
332             mbedtls_free( session->peer_cert );
333             session->peer_cert = NULL;
334             return( ret );
335         }
336
337         p += cert_len;
338     }
339 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
340     /* Deserialize CRT digest from the end of the ticket. */
341     if( 1 > (size_t)( end - p ) )
342         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
343
344     cert_digest_len = (size_t) p[0];
345     p++;
346
347     if( cert_digest_len != 0 )
348     {
349         if( cert_digest_len > (size_t)( end - p ) ||
350             cert_digest_len != session->peer_cert_digest_len )
351         {
352             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
353         }
354
355         session->peer_cert_digest = mbedtls_calloc( 1, cert_digest_len );
356         if( session->peer_cert_digest == NULL )
357             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
358
359         memcpy( session->peer_cert_digest, p, cert_digest_len );
360         p += cert_digest_len;
361     }
362 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
363 #endif /* MBEDTLS_X509_CRT_PARSE_C */
364
365     if( p != end )
366         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
367
368     return( 0 );
369 }
370
371 /*
372  * Create session ticket, with the following structure:
373  *
374  *    struct {
375  *        opaque key_name[4];
376  *        opaque iv[12];
377  *        opaque encrypted_state<0..2^16-1>;
378  *        opaque tag[16];
379  *    } ticket;
380  *
381  * The key_name, iv, and length of encrypted_state are the additional
382  * authenticated data.
383  */
384
385 int mbedtls_ssl_ticket_write( void *p_ticket,
386                               const mbedtls_ssl_session *session,
387                               unsigned char *start,
388                               const unsigned char *end,
389                               size_t *tlen,
390                               uint32_t *ticket_lifetime )
391 {
392     int ret;
393     mbedtls_ssl_ticket_context *ctx = p_ticket;
394     mbedtls_ssl_ticket_key *key;
395     unsigned char *key_name = start;
396     unsigned char *iv = start + TICKET_KEY_NAME_BYTES;
397     unsigned char *state_len_bytes = iv + TICKET_IV_BYTES;
398     unsigned char *state = state_len_bytes + TICKET_CRYPT_LEN_BYTES;
399     unsigned char *tag;
400     size_t clear_len, ciph_len;
401
402     *tlen = 0;
403
404     if( ctx == NULL || ctx->f_rng == NULL )
405         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
406
407     /* We need at least 4 bytes for key_name, 12 for IV, 2 for len 16 for tag,
408      * in addition to session itself, that will be checked when writing it. */
409     if( end - start < TICKET_MIN_LEN )
410         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
411
412 #if defined(MBEDTLS_THREADING_C)
413     if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
414         return( ret );
415 #endif
416
417     if( ( ret = ssl_ticket_update_keys( ctx ) ) != 0 )
418         goto cleanup;
419
420     key = &ctx->keys[ctx->active];
421
422     *ticket_lifetime = ctx->ticket_lifetime;
423
424     memcpy( key_name, key->name, TICKET_KEY_NAME_BYTES );
425
426     if( ( ret = ctx->f_rng( ctx->p_rng, iv, TICKET_IV_BYTES ) ) != 0 )
427         goto cleanup;
428
429     /* Dump session state */
430     if( ( ret = ssl_save_session( session,
431                                   state, end - state, &clear_len ) ) != 0 ||
432         (unsigned long) clear_len > 65535 )
433     {
434          goto cleanup;
435     }
436     state_len_bytes[0] = ( clear_len >> 8 ) & 0xff;
437     state_len_bytes[1] = ( clear_len      ) & 0xff;
438
439     /* Encrypt and authenticate */
440     tag = state + clear_len;
441     if( ( ret = mbedtls_cipher_auth_encrypt( &key->ctx,
442                     iv, TICKET_IV_BYTES,
443                     /* Additional data: key name, IV and length */
444                     key_name, TICKET_ADD_DATA_LEN,
445                     state, clear_len, state, &ciph_len,
446                     tag, TICKET_AUTH_TAG_BYTES ) ) != 0 )
447     {
448         goto cleanup;
449     }
450     if( ciph_len != clear_len )
451     {
452         ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
453         goto cleanup;
454     }
455
456     *tlen = TICKET_MIN_LEN + ciph_len;
457
458 cleanup:
459 #if defined(MBEDTLS_THREADING_C)
460     if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
461         return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
462 #endif
463
464     return( ret );
465 }
466
467 /*
468  * Select key based on name
469  */
470 static mbedtls_ssl_ticket_key *ssl_ticket_select_key(
471         mbedtls_ssl_ticket_context *ctx,
472         const unsigned char name[4] )
473 {
474     unsigned char i;
475
476     for( i = 0; i < sizeof( ctx->keys ) / sizeof( *ctx->keys ); i++ )
477         if( memcmp( name, ctx->keys[i].name, 4 ) == 0 )
478             return( &ctx->keys[i] );
479
480     return( NULL );
481 }
482
483 /*
484  * Load session ticket (see mbedtls_ssl_ticket_write for structure)
485  */
486 int mbedtls_ssl_ticket_parse( void *p_ticket,
487                               mbedtls_ssl_session *session,
488                               unsigned char *buf,
489                               size_t len )
490 {
491     int ret;
492     mbedtls_ssl_ticket_context *ctx = p_ticket;
493     mbedtls_ssl_ticket_key *key;
494     unsigned char *key_name = buf;
495     unsigned char *iv = buf + TICKET_KEY_NAME_BYTES;
496     unsigned char *enc_len_p = iv + TICKET_IV_BYTES;
497     unsigned char *ticket = enc_len_p + TICKET_CRYPT_LEN_BYTES;
498     unsigned char *tag;
499     size_t enc_len, clear_len;
500
501     if( ctx == NULL || ctx->f_rng == NULL )
502         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
503
504     if( len < TICKET_MIN_LEN )
505         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
506
507 #if defined(MBEDTLS_THREADING_C)
508     if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
509         return( ret );
510 #endif
511
512     if( ( ret = ssl_ticket_update_keys( ctx ) ) != 0 )
513         goto cleanup;
514
515     enc_len = ( enc_len_p[0] << 8 ) | enc_len_p[1];
516     tag = ticket + enc_len;
517
518     if( len != TICKET_MIN_LEN + enc_len )
519     {
520         ret = MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
521         goto cleanup;
522     }
523
524     /* Select key */
525     if( ( key = ssl_ticket_select_key( ctx, key_name ) ) == NULL )
526     {
527         /* We can't know for sure but this is a likely option unless we're
528          * under attack - this is only informative anyway */
529         ret = MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED;
530         goto cleanup;
531     }
532
533     /* Decrypt and authenticate */
534     if( ( ret = mbedtls_cipher_auth_decrypt( &key->ctx,
535                     iv, TICKET_IV_BYTES,
536                     /* Additional data: key name, IV and length */
537                     key_name, TICKET_ADD_DATA_LEN,
538                     ticket, enc_len,
539                     ticket, &clear_len,
540                     tag, TICKET_AUTH_TAG_BYTES ) ) != 0 )
541     {
542         if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED )
543             ret = MBEDTLS_ERR_SSL_INVALID_MAC;
544
545         goto cleanup;
546     }
547     if( clear_len != enc_len )
548     {
549         ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
550         goto cleanup;
551     }
552
553     /* Actually load session */
554     if( ( ret = ssl_load_session( session, ticket, clear_len ) ) != 0 )
555         goto cleanup;
556
557 #if defined(MBEDTLS_HAVE_TIME)
558     {
559         /* Check for expiration */
560         mbedtls_time_t current_time = mbedtls_time( NULL );
561
562         if( current_time < session->start ||
563             (uint32_t)( current_time - session->start ) > ctx->ticket_lifetime )
564         {
565             ret = MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED;
566             goto cleanup;
567         }
568     }
569 #endif
570
571 cleanup:
572 #if defined(MBEDTLS_THREADING_C)
573     if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
574         return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
575 #endif
576
577     return( ret );
578 }
579
580 /*
581  * Free context
582  */
583 void mbedtls_ssl_ticket_free( mbedtls_ssl_ticket_context *ctx )
584 {
585     mbedtls_cipher_free( &ctx->keys[0].ctx );
586     mbedtls_cipher_free( &ctx->keys[1].ctx );
587
588 #if defined(MBEDTLS_THREADING_C)
589     mbedtls_mutex_free( &ctx->mutex );
590 #endif
591
592     mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ssl_ticket_context ) );
593 }
594
595 #endif /* MBEDTLS_SSL_TICKET_C */