path
stringlengths
14
112
content
stringlengths
0
6.32M
size
int64
0
6.32M
max_lines
int64
1
100k
repo_name
stringclasses
2 values
autogenerated
bool
1 class
cosmopolitan/third_party/mbedtls/rando.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/nexgen32e/x86feature.h" #include "libc/stdio/rand.h" #include "libc/sysv/consts/grnd.h" #include "third_party/mbedtls/entropy_poll.h" int mbedtls_hardware_poll(void *wut, unsigned char *p, size_t n, size_t *olen) { ssize_t rc; *olen = 0; if ((rc = getrandom(p, n, 0)) == -1) return -1; *olen = rc; return 0; }
2,172
31
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/sha512.h
#ifndef MBEDTLS_SHA512_H_ #define MBEDTLS_SHA512_H_ #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/platform.h" COSMOPOLITAN_C_START_ /* clang-format off */ #define MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED -0x0039 /*< SHA-512 hardware accelerator failed */ #define MBEDTLS_ERR_SHA512_BAD_INPUT_DATA -0x0075 /*< SHA-512 input data was malformed. */ /** * \brief The SHA-512 context structure. * * The structure is used both for SHA-384 and for SHA-512 * checksum calculations. The choice between these two is * made in the call to mbedtls_sha512_starts_ret(). */ typedef struct mbedtls_sha512_context { uint64_t state[8]; /*!< The intermediate digest state. */ uint64_t total[2]; /*!< The number of Bytes processed. */ unsigned char buffer[128]; /*!< The data block being processed. */ #if !defined(MBEDTLS_SHA512_NO_SHA384) int is384; /*!< Determines which function to use: 0: Use SHA-512, or 1: Use SHA-384. */ #endif } mbedtls_sha512_context; void mbedtls_sha512_clone( mbedtls_sha512_context *, const mbedtls_sha512_context * ); int mbedtls_sha512_starts_ret( mbedtls_sha512_context *, int ); int mbedtls_sha512_update_ret( mbedtls_sha512_context *, const unsigned char *, size_t ); int mbedtls_sha512_finish_ret( mbedtls_sha512_context *, unsigned char[64] ); int mbedtls_internal_sha512_process( mbedtls_sha512_context *, const unsigned char[128] ); int mbedtls_sha512_ret( const void *, size_t, unsigned char[64], int ); int mbedtls_sha512_ret_384( const void *, size_t, unsigned char * ); int mbedtls_sha512_ret_512( const void *, size_t, unsigned char * ); int mbedtls_sha512_self_test( int ); /** * \brief This function initializes a SHA-512 context. * * \param ctx The SHA-512 context to initialize. This must * not be \c NULL. */ static inline void mbedtls_sha512_init( mbedtls_sha512_context *ctx ) { mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha512_context ) ); } /** * \brief This function clears a SHA-512 context. * * \param ctx The SHA-512 context to clear. This may be \c NULL, * in which case this function does nothing. If it * is not \c NULL, it must point to an initialized * SHA-512 context. */ static inline void mbedtls_sha512_free( mbedtls_sha512_context *ctx ) { if( !ctx ) return; mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha512_context ) ); } COSMOPOLITAN_C_END_ #endif /* MBEDTLS_SHA512_H_ */
2,627
67
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/memory_buffer_alloc.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/memory_buffer_alloc.h" #include "third_party/mbedtls/platform.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /* * Buffer-based memory allocator * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) #define MAGIC1 0xFF00AA55 #define MAGIC2 0xEE119966 #define MAX_BT 20 typedef struct _memory_header memory_header; struct _memory_header { size_t magic1; size_t size; size_t alloc; memory_header *prev; memory_header *next; memory_header *prev_free; memory_header *next_free; #if defined(MBEDTLS_MEMORY_BACKTRACE) char **trace; size_t trace_count; #endif size_t magic2; }; typedef struct { unsigned char *buf; size_t len; memory_header *first; memory_header *first_free; int verify; #if defined(MBEDTLS_MEMORY_DEBUG) size_t alloc_count; size_t free_count; size_t total_used; size_t maximum_used; size_t header_count; size_t maximum_header_count; #endif } buffer_alloc_ctx; static buffer_alloc_ctx heap; #if defined(MBEDTLS_MEMORY_DEBUG) static void debug_header( memory_header *hdr ) { #if defined(MBEDTLS_MEMORY_BACKTRACE) size_t i; #endif mbedtls_fprintf( stderr, "HDR: PTR(%10zu), PREV(%10zu), NEXT(%10zu), " "ALLOC(%zu), SIZE(%10zu)\n", (size_t) hdr, (size_t) hdr->prev, (size_t) hdr->next, hdr->alloc, hdr->size ); mbedtls_fprintf( stderr, " FPREV(%10zu), FNEXT(%10zu)\n", (size_t) hdr->prev_free, (size_t) hdr->next_free ); #if defined(MBEDTLS_MEMORY_BACKTRACE) mbedtls_fprintf( stderr, "TRACE: \n" ); for( i = 0; i < hdr->trace_count; i++ ) mbedtls_fprintf( stderr, "%s\n", hdr->trace[i] ); mbedtls_fprintf( stderr, "\n" ); #endif } static void debug_chain( void ) { memory_header *cur = heap.first; mbedtls_fprintf( stderr, "\nBlock list\n" ); while( cur != NULL ) { debug_header( cur ); cur = cur->next; } mbedtls_fprintf( stderr, "Free list\n" ); cur = heap.first_free; while( cur != NULL ) { debug_header( cur ); cur = cur->next_free; } } #endif /* MBEDTLS_MEMORY_DEBUG */ static int verify_header( memory_header *hdr ) { if( hdr->magic1 != MAGIC1 ) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf( stderr, "FATAL: MAGIC1 mismatch\n" ); #endif return( 1 ); } if( hdr->magic2 != MAGIC2 ) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf( stderr, "FATAL: MAGIC2 mismatch\n" ); #endif return( 1 ); } if( hdr->alloc > 1 ) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf( stderr, "FATAL: alloc has illegal value\n" ); #endif return( 1 ); } if( hdr->prev != NULL && hdr->prev == hdr->next ) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf( stderr, "FATAL: prev == next\n" ); #endif return( 1 ); } if( hdr->prev_free != NULL && hdr->prev_free == hdr->next_free ) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf( stderr, "FATAL: prev_free == next_free\n" ); #endif return( 1 ); } return( 0 ); } static int verify_chain( void ) { memory_header *prv = heap.first, *cur; if( prv == NULL || verify_header( prv ) != 0 ) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf( stderr, "FATAL: verification of first header " "failed\n" ); #endif return( 1 ); } if( heap.first->prev != NULL ) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf( stderr, "FATAL: verification failed: " "first->prev != NULL\n" ); #endif return( 1 ); } cur = heap.first->next; while( cur != NULL ) { if( verify_header( cur ) != 0 ) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf( stderr, "FATAL: verification of header " "failed\n" ); #endif return( 1 ); } if( cur->prev != prv ) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf( stderr, "FATAL: verification failed: " "cur->prev != prv\n" ); #endif return( 1 ); } prv = cur; cur = cur->next; } return( 0 ); } static void *buffer_alloc_calloc( size_t n, size_t size ) { memory_header *new, *cur = heap.first_free; unsigned char *p; void *ret; size_t original_len, len; #if defined(MBEDTLS_MEMORY_BACKTRACE) void *trace_buffer[MAX_BT]; size_t trace_cnt; #endif if( heap.buf == NULL || heap.first == NULL ) return( NULL ); original_len = len = n * size; if( n == 0 || size == 0 || len / n != size ) return( NULL ); else if( len > (size_t)-MBEDTLS_MEMORY_ALIGN_MULTIPLE ) return( NULL ); if( len % MBEDTLS_MEMORY_ALIGN_MULTIPLE ) { len -= len % MBEDTLS_MEMORY_ALIGN_MULTIPLE; len += MBEDTLS_MEMORY_ALIGN_MULTIPLE; } // Find block that fits // while( cur != NULL ) { if( cur->size >= len ) break; cur = cur->next_free; } if( cur == NULL ) return( NULL ); if( cur->alloc != 0 ) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf( stderr, "FATAL: block in free_list but allocated " "data\n" ); #endif mbedtls_exit( 1 ); } #if defined(MBEDTLS_MEMORY_DEBUG) heap.alloc_count++; #endif // Found location, split block if > memory_header + 4 room left // if( cur->size - len < sizeof(memory_header) + MBEDTLS_MEMORY_ALIGN_MULTIPLE ) { cur->alloc = 1; // Remove from free_list // if( cur->prev_free != NULL ) cur->prev_free->next_free = cur->next_free; else heap.first_free = cur->next_free; if( cur->next_free != NULL ) cur->next_free->prev_free = cur->prev_free; cur->prev_free = NULL; cur->next_free = NULL; #if defined(MBEDTLS_MEMORY_DEBUG) heap.total_used += cur->size; if( heap.total_used > heap.maximum_used ) heap.maximum_used = heap.total_used; #endif #if defined(MBEDTLS_MEMORY_BACKTRACE) trace_cnt = backtrace( trace_buffer, MAX_BT ); cur->trace = backtrace_symbols( trace_buffer, trace_cnt ); cur->trace_count = trace_cnt; #endif if( ( heap.verify & MBEDTLS_MEMORY_VERIFY_ALLOC ) && verify_chain() != 0 ) mbedtls_exit( 1 ); ret = (unsigned char *) cur + sizeof( memory_header ); mbedtls_platform_zeroize( ret, original_len ); return( ret ); } p = ( (unsigned char *) cur ) + sizeof(memory_header) + len; new = (memory_header *) p; new->size = cur->size - len - sizeof(memory_header); new->alloc = 0; new->prev = cur; new->next = cur->next; #if defined(MBEDTLS_MEMORY_BACKTRACE) new->trace = NULL; new->trace_count = 0; #endif new->magic1 = MAGIC1; new->magic2 = MAGIC2; if( new->next != NULL ) new->next->prev = new; // Replace cur with new in free_list // new->prev_free = cur->prev_free; new->next_free = cur->next_free; if( new->prev_free != NULL ) new->prev_free->next_free = new; else heap.first_free = new; if( new->next_free != NULL ) new->next_free->prev_free = new; cur->alloc = 1; cur->size = len; cur->next = new; cur->prev_free = NULL; cur->next_free = NULL; #if defined(MBEDTLS_MEMORY_DEBUG) heap.header_count++; if( heap.header_count > heap.maximum_header_count ) heap.maximum_header_count = heap.header_count; heap.total_used += cur->size; if( heap.total_used > heap.maximum_used ) heap.maximum_used = heap.total_used; #endif #if defined(MBEDTLS_MEMORY_BACKTRACE) trace_cnt = backtrace( trace_buffer, MAX_BT ); cur->trace = backtrace_symbols( trace_buffer, trace_cnt ); cur->trace_count = trace_cnt; #endif if( ( heap.verify & MBEDTLS_MEMORY_VERIFY_ALLOC ) && verify_chain() != 0 ) mbedtls_exit( 1 ); ret = (unsigned char *) cur + sizeof( memory_header ); mbedtls_platform_zeroize( ret, original_len ); return( ret ); } static void buffer_alloc_free( void *ptr ) { memory_header *hdr, *old = NULL; unsigned char *p = (unsigned char *) ptr; if( ptr == NULL || heap.buf == NULL || heap.first == NULL ) return; if( p < heap.buf || p >= heap.buf + heap.len ) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf( stderr, "FATAL: mbedtls_free() outside of managed " "space\n" ); #endif mbedtls_exit( 1 ); } p -= sizeof(memory_header); hdr = (memory_header *) p; if( verify_header( hdr ) != 0 ) mbedtls_exit( 1 ); if( hdr->alloc != 1 ) { #if defined(MBEDTLS_MEMORY_DEBUG) mbedtls_fprintf( stderr, "FATAL: mbedtls_free() on unallocated " "data\n" ); #endif mbedtls_exit( 1 ); } hdr->alloc = 0; #if defined(MBEDTLS_MEMORY_DEBUG) heap.free_count++; heap.total_used -= hdr->size; #endif #if defined(MBEDTLS_MEMORY_BACKTRACE) free( hdr->trace ); hdr->trace = NULL; hdr->trace_count = 0; #endif // Regroup with block before // if( hdr->prev != NULL && hdr->prev->alloc == 0 ) { #if defined(MBEDTLS_MEMORY_DEBUG) heap.header_count--; #endif hdr->prev->size += sizeof(memory_header) + hdr->size; hdr->prev->next = hdr->next; old = hdr; hdr = hdr->prev; if( hdr->next != NULL ) hdr->next->prev = hdr; mbedtls_platform_zeroize( old, sizeof(memory_header) ); } // Regroup with block after // if( hdr->next != NULL && hdr->next->alloc == 0 ) { #if defined(MBEDTLS_MEMORY_DEBUG) heap.header_count--; #endif hdr->size += sizeof(memory_header) + hdr->next->size; old = hdr->next; hdr->next = hdr->next->next; if( hdr->prev_free != NULL || hdr->next_free != NULL ) { if( hdr->prev_free != NULL ) hdr->prev_free->next_free = hdr->next_free; else heap.first_free = hdr->next_free; if( hdr->next_free != NULL ) hdr->next_free->prev_free = hdr->prev_free; } hdr->prev_free = old->prev_free; hdr->next_free = old->next_free; if( hdr->prev_free != NULL ) hdr->prev_free->next_free = hdr; else heap.first_free = hdr; if( hdr->next_free != NULL ) hdr->next_free->prev_free = hdr; if( hdr->next != NULL ) hdr->next->prev = hdr; mbedtls_platform_zeroize( old, sizeof(memory_header) ); } // Prepend to free_list if we have not merged // (Does not have to stay in same order as prev / next list) // if( old == NULL ) { hdr->next_free = heap.first_free; if( heap.first_free != NULL ) heap.first_free->prev_free = hdr; heap.first_free = hdr; } if( ( heap.verify & MBEDTLS_MEMORY_VERIFY_FREE ) && verify_chain() != 0 ) mbedtls_exit( 1 ); } void mbedtls_memory_buffer_set_verify( int verify ) { heap.verify = verify; } int mbedtls_memory_buffer_alloc_verify( void ) { return verify_chain(); } #if defined(MBEDTLS_MEMORY_DEBUG) void mbedtls_memory_buffer_alloc_status( void ) { mbedtls_fprintf( stderr, "Current use: %zu blocks / %zu bytes, max: %zu blocks / " "%zu bytes (total %zu bytes), alloc / free: %zu / %zu\n", heap.header_count, heap.total_used, heap.maximum_header_count, heap.maximum_used, heap.maximum_header_count * sizeof( memory_header ) + heap.maximum_used, heap.alloc_count, heap.free_count ); if( heap.first->next == NULL ) { mbedtls_fprintf( stderr, "All memory de-allocated in stack buffer\n" ); } else { mbedtls_fprintf( stderr, "Memory currently allocated:\n" ); debug_chain(); } } void mbedtls_memory_buffer_alloc_max_get( size_t *max_used, size_t *max_blocks ) { *max_used = heap.maximum_used; *max_blocks = heap.maximum_header_count; } void mbedtls_memory_buffer_alloc_max_reset( void ) { heap.maximum_used = 0; heap.maximum_header_count = 0; } void mbedtls_memory_buffer_alloc_cur_get( size_t *cur_used, size_t *cur_blocks ) { *cur_used = heap.total_used; *cur_blocks = heap.header_count; } #endif /* MBEDTLS_MEMORY_DEBUG */ void mbedtls_memory_buffer_alloc_init( unsigned char *buf, size_t len ) { mbedtls_platform_zeroize( &heap, sizeof( buffer_alloc_ctx ) ); mbedtls_platform_set_calloc_free( buffer_alloc_calloc, buffer_alloc_free ); if( len < sizeof( memory_header ) + MBEDTLS_MEMORY_ALIGN_MULTIPLE ) return; else if( (size_t)buf % MBEDTLS_MEMORY_ALIGN_MULTIPLE ) { /* Adjust len first since buf is used in the computation */ len -= MBEDTLS_MEMORY_ALIGN_MULTIPLE - (size_t)buf % MBEDTLS_MEMORY_ALIGN_MULTIPLE; buf += MBEDTLS_MEMORY_ALIGN_MULTIPLE - (size_t)buf % MBEDTLS_MEMORY_ALIGN_MULTIPLE; } mbedtls_platform_zeroize( buf, len ); heap.buf = buf; heap.len = len; heap.first = (memory_header *)buf; heap.first->size = len - sizeof( memory_header ); heap.first->magic1 = MAGIC1; heap.first->magic2 = MAGIC2; heap.first_free = heap.first; } void mbedtls_memory_buffer_alloc_free( void ) { mbedtls_platform_zeroize( &heap, sizeof(buffer_alloc_ctx) ); } #if defined(MBEDTLS_SELF_TEST) static int check_pointer( void *p ) { if( p == NULL ) return( -1 ); if( (size_t) p % MBEDTLS_MEMORY_ALIGN_MULTIPLE != 0 ) return( -1 ); return( 0 ); } static int check_all_free( void ) { if( #if defined(MBEDTLS_MEMORY_DEBUG) heap.total_used != 0 || #endif heap.first != heap.first_free || (void *) heap.first != (void *) heap.buf ) { return( -1 ); } return( 0 ); } #define TEST_ASSERT( condition ) \ if( ! (condition) ) \ { \ if( verbose != 0 ) \ mbedtls_printf( "failed\n" ); \ \ ret = 1; \ goto cleanup; \ } int mbedtls_memory_buffer_alloc_self_test( int verbose ) { unsigned char buf[1024]; unsigned char *p, *q, *r, *end; int ret = 0; if( verbose != 0 ) mbedtls_printf( " MBA test #1 (basic alloc-free cycle): " ); mbedtls_memory_buffer_alloc_init( buf, sizeof( buf ) ); p = mbedtls_calloc( 1, 1 ); q = mbedtls_calloc( 1, 128 ); r = mbedtls_calloc( 1, 16 ); TEST_ASSERT( check_pointer( p ) == 0 && check_pointer( q ) == 0 && check_pointer( r ) == 0 ); mbedtls_free( r ); mbedtls_free( q ); mbedtls_free( p ); TEST_ASSERT( check_all_free( ) == 0 ); /* Memorize end to compare with the next test */ end = heap.buf + heap.len; mbedtls_memory_buffer_alloc_free( ); if( verbose != 0 ) mbedtls_printf( "passed\n" ); if( verbose != 0 ) mbedtls_printf( " MBA test #2 (buf not aligned): " ); mbedtls_memory_buffer_alloc_init( buf + 1, sizeof( buf ) - 1 ); TEST_ASSERT( heap.buf + heap.len == end ); p = mbedtls_calloc( 1, 1 ); q = mbedtls_calloc( 1, 128 ); r = mbedtls_calloc( 1, 16 ); TEST_ASSERT( check_pointer( p ) == 0 && check_pointer( q ) == 0 && check_pointer( r ) == 0 ); mbedtls_free( r ); mbedtls_free( q ); mbedtls_free( p ); TEST_ASSERT( check_all_free( ) == 0 ); mbedtls_memory_buffer_alloc_free( ); if( verbose != 0 ) mbedtls_printf( "passed\n" ); if( verbose != 0 ) mbedtls_printf( " MBA test #3 (full): " ); mbedtls_memory_buffer_alloc_init( buf, sizeof( buf ) ); p = mbedtls_calloc( 1, sizeof( buf ) - sizeof( memory_header ) ); TEST_ASSERT( check_pointer( p ) == 0 ); TEST_ASSERT( mbedtls_calloc( 1, 1 ) == NULL ); mbedtls_free( p ); p = mbedtls_calloc( 1, sizeof( buf ) - 2 * sizeof( memory_header ) - 16 ); q = mbedtls_calloc( 1, 16 ); TEST_ASSERT( check_pointer( p ) == 0 && check_pointer( q ) == 0 ); TEST_ASSERT( mbedtls_calloc( 1, 1 ) == NULL ); mbedtls_free( q ); TEST_ASSERT( mbedtls_calloc( 1, 17 ) == NULL ); mbedtls_free( p ); TEST_ASSERT( check_all_free( ) == 0 ); mbedtls_memory_buffer_alloc_free( ); if( verbose != 0 ) mbedtls_printf( "passed\n" ); cleanup: mbedtls_memory_buffer_alloc_free( ); return( ret ); } #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_MEMORY_BUFFER_ALLOC_C */
19,942
719
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/ssl_tls.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/log.h" #include "third_party/mbedtls/chk.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/debug.h" #include "third_party/mbedtls/endian.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/oid.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/ssl.h" #include "third_party/mbedtls/ssl_ciphersuites.h" #include "third_party/mbedtls/ssl_internal.h" #include "third_party/mbedtls/version.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /** * @fileoverview SSLv3/TLSv1 shared functions * * The SSL 3.0 specification was drafted by Netscape in 1996, * and became an IETF standard in 1999. * * @see http://wp.netscape.com/eng/ssl3/ * @see http://www.ietf.org/rfc/rfc2246.txt * @see http://www.ietf.org/rfc/rfc4346.txt */ #if defined(MBEDTLS_SSL_TLS_C) #if defined(MBEDTLS_SSL_PROTO_DTLS) #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) /* Top-level Connection ID API */ /** * \brief Specify the length of Connection IDs for incoming * encrypted DTLS records, as well as the behaviour * on unexpected CIDs. * * By default, the CID length is set to \c 0, * and unexpected CIDs are silently ignored. * * \param conf The SSL configuration to modify. * \param len The length in Bytes of the CID fields in encrypted * DTLS records using the CID mechanism. This must * not be larger than #MBEDTLS_SSL_CID_OUT_LEN_MAX. * \param ignore_other_cids This determines the stack's behaviour when * receiving a record with an unexpected CID. * Possible values are: * - #MBEDTLS_SSL_UNEXPECTED_CID_IGNORE * In this case, the record is silently ignored. * - #MBEDTLS_SSL_UNEXPECTED_CID_FAIL * In this case, the stack fails with the specific * error code #MBEDTLS_ERR_SSL_UNEXPECTED_CID. * * \note The CID specification allows implementations to either * use a common length for all incoming connection IDs or * allow variable-length incoming IDs. Mbed TLS currently * requires a common length for all connections sharing the * same SSL configuration; this allows simpler parsing of * record headers. * * \return \c 0 on success. * \return #MBEDTLS_ERR_SSL_BAD_INPUT_DATA if \p own_cid_len * is too large. */ int mbedtls_ssl_conf_cid( mbedtls_ssl_config *conf, size_t len, int ignore_other_cid ) { if( len > MBEDTLS_SSL_CID_IN_LEN_MAX ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( ignore_other_cid != MBEDTLS_SSL_UNEXPECTED_CID_FAIL && ignore_other_cid != MBEDTLS_SSL_UNEXPECTED_CID_IGNORE ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } conf->ignore_unexpected_cid = ignore_other_cid; conf->cid_len = len; return( 0 ); } /** * \brief Configure the use of the Connection ID (CID) * extension in the next handshake. * * Reference: draft-ietf-tls-dtls-connection-id-05 * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05 * * The DTLS CID extension allows the reliable association of * DTLS records to DTLS connections across changes in the * underlying transport (changed IP and Port metadata) by * adding explicit connection identifiers (CIDs) to the * headers of encrypted DTLS records. The desired CIDs are * configured by the application layer and are exchanged in * new `ClientHello` / `ServerHello` extensions during the * handshake, where each side indicates the CID it wants the * peer to use when writing encrypted messages. The CIDs are * put to use once records get encrypted: the stack discards * any incoming records that don't include the configured CID * in their header, and adds the peer's requested CID to the * headers of outgoing messages. * * This API enables or disables the use of the CID extension * in the next handshake and sets the value of the CID to * be used for incoming messages. * * \param ssl The SSL context to configure. This must be initialized. * \param enable This value determines whether the CID extension should * be used or not. Possible values are: * - MBEDTLS_SSL_CID_ENABLED to enable the use of the CID. * - MBEDTLS_SSL_CID_DISABLED (default) to disable the use * of the CID. * \param own_cid The address of the readable buffer holding the CID we want * the peer to use when sending encrypted messages to us. * This may be \c NULL if \p own_cid_len is \c 0. * This parameter is unused if \p enabled is set to * MBEDTLS_SSL_CID_DISABLED. * \param own_cid_len The length of \p own_cid. * This parameter is unused if \p enabled is set to * MBEDTLS_SSL_CID_DISABLED. * * \note The value of \p own_cid_len must match the value of the * \c len parameter passed to mbedtls_ssl_conf_cid() * when configuring the ::mbedtls_ssl_config that \p ssl * is bound to. * * \note This CID configuration applies to subsequent handshakes * performed on the SSL context \p ssl, but does not trigger * one. You still have to call `mbedtls_ssl_handshake()` * (for the initial handshake) or `mbedtls_ssl_renegotiate()` * (for a renegotiation handshake) explicitly after a * successful call to this function to run the handshake. * * \note This call cannot guarantee that the use of the CID * will be successfully negotiated in the next handshake, * because the peer might not support it. Specifically: * - On the Client, enabling the use of the CID through * this call implies that the `ClientHello` in the next * handshake will include the CID extension, thereby * offering the use of the CID to the server. Only if * the `ServerHello` contains the CID extension, too, * the CID extension will actually be put to use. * - On the Server, enabling the use of the CID through * this call implies that that the server will look for * the CID extension in a `ClientHello` from the client, * and, if present, reply with a CID extension in its * `ServerHello`. * * \note To check whether the use of the CID was negotiated * after the subsequent handshake has completed, please * use the API mbedtls_ssl_get_peer_cid(). * * \warning If the use of the CID extension is enabled in this call * and the subsequent handshake negotiates its use, Mbed TLS * will silently drop every packet whose CID does not match * the CID configured in \p own_cid. It is the responsibility * of the user to adapt the underlying transport to take care * of CID-based demultiplexing before handing datagrams to * Mbed TLS. * * \return \c 0 on success. In this case, the CID configuration * applies to the next handshake. * \return A negative error code on failure. */ int mbedtls_ssl_set_cid( mbedtls_ssl_context *ssl, int enable, unsigned char const *own_cid, size_t own_cid_len ) { if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl->negotiate_cid = enable; if( enable == MBEDTLS_SSL_CID_DISABLED ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Disable use of CID extension." ) ); return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "Enable use of CID extension." ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "Own CID", own_cid, own_cid_len ); if( own_cid_len != ssl->conf->cid_len ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "CID length %u does not match CID length %u in config", (unsigned) own_cid_len, (unsigned) ssl->conf->cid_len ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } memcpy( ssl->own_cid, own_cid, own_cid_len ); /* Truncation is not an issue here because * MBEDTLS_SSL_CID_IN_LEN_MAX at most 255. */ ssl->own_cid_len = (uint8_t) own_cid_len; return( 0 ); } /** * \brief Get information about the use of the CID extension * in the current connection. * * \param ssl The SSL context to query. * \param enabled The address at which to store whether the CID extension * is currently in use or not. If the CID is in use, * `*enabled` is set to MBEDTLS_SSL_CID_ENABLED; * otherwise, it is set to MBEDTLS_SSL_CID_DISABLED. * \param peer_cid The address of the buffer in which to store the CID * chosen by the peer (if the CID extension is used). * This may be \c NULL in case the value of peer CID * isn't needed. If it is not \c NULL, \p peer_cid_len * must not be \c NULL. * \param peer_cid_len The address at which to store the size of the CID * chosen by the peer (if the CID extension is used). * This is also the number of Bytes in \p peer_cid that * have been written. * This may be \c NULL in case the length of the peer CID * isn't needed. If it is \c NULL, \p peer_cid must be * \c NULL, too. * * \note This applies to the state of the CID negotiated in * the last complete handshake. If a handshake is in * progress, this function will attempt to complete * the handshake first. * * \note If CID extensions have been exchanged but both client * and server chose to use an empty CID, this function * sets `*enabled` to #MBEDTLS_SSL_CID_DISABLED * (the rationale for this is that the resulting * communication is the same as if the CID extensions * hadn't been used). * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_ssl_get_peer_cid( mbedtls_ssl_context *ssl, int *enabled, unsigned char peer_cid[ MBEDTLS_SSL_CID_OUT_LEN_MAX ], size_t *peer_cid_len ) { *enabled = MBEDTLS_SSL_CID_DISABLED; if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM || ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* We report MBEDTLS_SSL_CID_DISABLED in case the CID extensions * were used, but client and server requested the empty CID. * This is indistinguishable from not using the CID extension * in the first place. */ if( ssl->transform_in->in_cid_len == 0 && ssl->transform_in->out_cid_len == 0 ) { return( 0 ); } if( peer_cid_len != NULL ) { *peer_cid_len = ssl->transform_in->out_cid_len; if( peer_cid != NULL ) { memcpy( peer_cid, ssl->transform_in->out_cid, ssl->transform_in->out_cid_len ); } } *enabled = MBEDTLS_SSL_CID_ENABLED; return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #endif /* MBEDTLS_SSL_PROTO_DTLS */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) /* * Convert max_fragment_length codes to length. * RFC 6066 says: * enum{ * 2^9(1), 2^10(2), 2^11(3), 2^12(4), (255) * } MaxFragmentLength; * and we add 0 -> extension unused */ static unsigned int ssl_mfl_code_to_length( int mfl ) { switch( mfl ) { case MBEDTLS_SSL_MAX_FRAG_LEN_NONE: return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN ); case MBEDTLS_SSL_MAX_FRAG_LEN_512: return 512; case MBEDTLS_SSL_MAX_FRAG_LEN_1024: return 1024; case MBEDTLS_SSL_MAX_FRAG_LEN_2048: return 2048; case MBEDTLS_SSL_MAX_FRAG_LEN_4096: return 4096; default: return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN ); } } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ int mbedtls_ssl_session_copy( mbedtls_ssl_session *dst, const mbedtls_ssl_session *src ) { mbedtls_ssl_session_free( dst ); memcpy( dst, src, sizeof( mbedtls_ssl_session ) ); #if defined(MBEDTLS_X509_CRT_PARSE_C) #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) if( src->peer_cert != NULL ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; dst->peer_cert = mbedtls_calloc( 1, sizeof(mbedtls_x509_crt) ); if( dst->peer_cert == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); mbedtls_x509_crt_init( dst->peer_cert ); if( ( ret = mbedtls_x509_crt_parse_der( dst->peer_cert, src->peer_cert->raw.p, src->peer_cert->raw.len ) ) != 0 ) { mbedtls_free( dst->peer_cert ); dst->peer_cert = NULL; return( ret ); } } #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( src->peer_cert_digest != NULL ) { dst->peer_cert_digest = mbedtls_calloc( 1, src->peer_cert_digest_len ); if( dst->peer_cert_digest == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); memcpy( dst->peer_cert_digest, src->peer_cert_digest, src->peer_cert_digest_len ); dst->peer_cert_digest_type = src->peer_cert_digest_type; dst->peer_cert_digest_len = src->peer_cert_digest_len; } #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C) if( src->ticket != NULL ) { dst->ticket = mbedtls_calloc( 1, src->ticket_len ); if( dst->ticket == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); memcpy( dst->ticket, src->ticket, src->ticket_len ); } #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */ return( 0 ); } #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) static int resize_buffer( unsigned char **buffer, size_t len_new, size_t *len_old ) { unsigned char* resized_buffer = mbedtls_calloc( 1, len_new ); if( resized_buffer == NULL ) return -1; /* We want to copy len_new bytes when downsizing the buffer, and * len_old bytes when upsizing, so we choose the smaller of two sizes, * to fit one buffer into another. Size checks, ensuring that no data is * lost, are done outside of this function. */ memcpy( resized_buffer, *buffer, ( len_new < *len_old ) ? len_new : *len_old ); mbedtls_platform_zeroize( *buffer, *len_old ); mbedtls_free( *buffer ); *buffer = resized_buffer; *len_old = len_new; return 0; } static void handle_buffer_resizing( mbedtls_ssl_context *ssl, int downsizing, size_t in_buf_new_len, size_t out_buf_new_len ) { int modified = 0; size_t written_in = 0, iv_offset_in = 0, len_offset_in = 0; size_t written_out = 0, iv_offset_out = 0, len_offset_out = 0; if( ssl->in_buf != NULL ) { written_in = ssl->in_msg - ssl->in_buf; iv_offset_in = ssl->in_iv - ssl->in_buf; len_offset_in = ssl->in_len - ssl->in_buf; if( downsizing ? ssl->in_buf_len > in_buf_new_len && ssl->in_left < in_buf_new_len : ssl->in_buf_len < in_buf_new_len ) { if( resize_buffer( &ssl->in_buf, in_buf_new_len, &ssl->in_buf_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "input buffer resizing failed - out of memory" ) ); } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Reallocating in_buf to %" MBEDTLS_PRINTF_SIZET, in_buf_new_len ) ); modified = 1; } } } if( ssl->out_buf != NULL ) { written_out = ssl->out_msg - ssl->out_buf; iv_offset_out = ssl->out_iv - ssl->out_buf; len_offset_out = ssl->out_len - ssl->out_buf; if( downsizing ? ssl->out_buf_len > out_buf_new_len && ssl->out_left < out_buf_new_len : ssl->out_buf_len < out_buf_new_len ) { if( resize_buffer( &ssl->out_buf, out_buf_new_len, &ssl->out_buf_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "output buffer resizing failed - out of memory" ) ); } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Reallocating out_buf to %" MBEDTLS_PRINTF_SIZET, out_buf_new_len ) ); modified = 1; } } } if( modified ) { /* Update pointers here to avoid doing it twice. */ mbedtls_ssl_reset_in_out_pointers( ssl ); /* Fields below might not be properly updated with record * splitting or with CID, so they are manually updated here. */ ssl->out_msg = ssl->out_buf + written_out; ssl->out_len = ssl->out_buf + len_offset_out; ssl->out_iv = ssl->out_buf + iv_offset_out; ssl->in_msg = ssl->in_buf + written_in; ssl->in_len = ssl->in_buf + len_offset_in; ssl->in_iv = ssl->in_buf + iv_offset_in; } } #endif /* MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH */ /* * Key material generation */ #if defined(MBEDTLS_SSL_PROTO_SSL3) static int ssl3_prf( const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { int ret = 0; size_t i; mbedtls_md5_context md5; mbedtls_sha1_context sha1; unsigned char padding[16]; unsigned char sha1sum[20]; mbedtls_md5_init( &md5 ); mbedtls_sha1_init( &sha1 ); /* * SSLv3: * block = * MD5( secret + SHA1( 'A' + secret + random ) ) + * MD5( secret + SHA1( 'BB' + secret + random ) ) + * MD5( secret + SHA1( 'CCC' + secret + random ) ) + * ... */ for( i = 0; i < dlen / 16; i++ ) { memset( padding, (unsigned char) ('A' + i), 1 + i ); MBEDTLS_CHK( mbedtls_sha1_starts_ret( &sha1 ) ); MBEDTLS_CHK( mbedtls_sha1_update_ret( &sha1, padding, 1 + i ) ); MBEDTLS_CHK( mbedtls_sha1_update_ret( &sha1, secret, slen ) ); MBEDTLS_CHK( mbedtls_sha1_update_ret( &sha1, random, rlen ) ); MBEDTLS_CHK( mbedtls_sha1_finish_ret( &sha1, sha1sum ) ); MBEDTLS_CHK( mbedtls_md5_starts_ret( &md5 ) ); MBEDTLS_CHK( mbedtls_md5_update_ret( &md5, secret, slen ) ); MBEDTLS_CHK( mbedtls_md5_update_ret( &md5, sha1sum, 20 ) ); MBEDTLS_CHK( mbedtls_md5_finish_ret( &md5, dstbuf + i * 16 ) ); } cleanup: mbedtls_md5_free( &md5 ); mbedtls_sha1_free( &sha1 ); mbedtls_platform_zeroize( padding, sizeof( padding ) ); mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) ); return( ret ); } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) static int tls1_prf( const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { size_t nb, hs; size_t i, j, k; const unsigned char *S1, *S2; unsigned char *tmp; size_t tmp_len = 0; unsigned char h_i[20]; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_md_init( &md_ctx ); tmp_len = 20 + strlen( label ) + rlen; if( !( tmp = mbedtls_calloc( 1, tmp_len ) ) ) { ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; goto exit; } hs = ( slen + 1 ) / 2; S1 = secret; S2 = secret + slen - hs; nb = strlen( label ); memcpy( tmp + 20, label, nb ); memcpy( tmp + 20 + nb, random, rlen ); nb += rlen; /* * First compute P_md5(secret,label+random)[0..dlen] */ if( !( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_MD5 ) ) ) { ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; goto exit; } if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 ) { goto exit; } mbedtls_md_hmac_starts( &md_ctx, S1, hs ); mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb ); mbedtls_md_hmac_finish( &md_ctx, 4 + tmp ); for( i = 0; i < dlen; i += 16 ) { mbedtls_md_hmac_reset ( &md_ctx ); mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 + nb ); mbedtls_md_hmac_finish( &md_ctx, h_i ); mbedtls_md_hmac_reset ( &md_ctx ); mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 ); mbedtls_md_hmac_finish( &md_ctx, 4 + tmp ); k = ( i + 16 > dlen ) ? dlen % 16 : 16; for( j = 0; j < k; j++ ) dstbuf[i + j] = h_i[j]; } mbedtls_md_free( &md_ctx ); /* * XOR out with P_sha1(secret,label+random)[0..dlen] */ if( !( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ) ) ) { ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; goto exit; } if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 ) { goto exit; } mbedtls_md_hmac_starts( &md_ctx, S2, hs ); mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb ); mbedtls_md_hmac_finish( &md_ctx, tmp ); for( i = 0; i < dlen; i += 20 ) { mbedtls_md_hmac_reset ( &md_ctx ); mbedtls_md_hmac_update( &md_ctx, tmp, 20 + nb ); mbedtls_md_hmac_finish( &md_ctx, h_i ); mbedtls_md_hmac_reset ( &md_ctx ); mbedtls_md_hmac_update( &md_ctx, tmp, 20 ); mbedtls_md_hmac_finish( &md_ctx, tmp ); k = ( i + 20 > dlen ) ? dlen % 20 : 20; for( j = 0; j < k; j++ ) dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] ); } exit: mbedtls_md_free( &md_ctx ); mbedtls_platform_zeroize( tmp, tmp_len ); mbedtls_platform_zeroize( h_i, sizeof( h_i ) ); mbedtls_free( tmp ); return( ret ); } #endif /* MBEDTLS_SSL_PROTO_TLS1) || MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) static int tls_prf_generic( mbedtls_md_type_t md_type, const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { size_t nb; size_t i, j, k, md_len; unsigned char *tmp; size_t tmp_len = 0; unsigned char h_i[MBEDTLS_MD_MAX_SIZE]; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_md_init( &md_ctx ); if( ( md_info = mbedtls_md_info_from_type( md_type ) ) == NULL ) return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); md_len = mbedtls_md_get_size( md_info ); tmp_len = md_len + strlen( label ) + rlen; tmp = mbedtls_calloc( 1, tmp_len ); if( tmp == NULL ) { ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; goto exit; } nb = strlen( label ); memcpy( tmp + md_len, label, nb ); memcpy( tmp + md_len + nb, random, rlen ); nb += rlen; /* * Compute P_<hash>(secret, label + random)[0..dlen] */ if ( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 ) goto exit; mbedtls_md_hmac_starts( &md_ctx, secret, slen ); mbedtls_md_hmac_update( &md_ctx, tmp + md_len, nb ); mbedtls_md_hmac_finish( &md_ctx, tmp ); for( i = 0; i < dlen; i += md_len ) { mbedtls_md_hmac_reset ( &md_ctx ); mbedtls_md_hmac_update( &md_ctx, tmp, md_len + nb ); mbedtls_md_hmac_finish( &md_ctx, h_i ); mbedtls_md_hmac_reset ( &md_ctx ); mbedtls_md_hmac_update( &md_ctx, tmp, md_len ); mbedtls_md_hmac_finish( &md_ctx, tmp ); k = ( i + md_len > dlen ) ? dlen % md_len : md_len; for( j = 0; j < k; j++ ) dstbuf[i + j] = h_i[j]; } exit: mbedtls_md_free( &md_ctx ); mbedtls_platform_zeroize( tmp, tmp_len ); mbedtls_platform_zeroize( h_i, sizeof( h_i ) ); mbedtls_free( tmp ); return( ret ); } #if defined(MBEDTLS_SHA256_C) static int tls_prf_sha256( const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { return( tls_prf_generic( MBEDTLS_MD_SHA256, secret, slen, label, random, rlen, dstbuf, dlen ) ); } #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) static int tls_prf_sha384( const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { return( tls_prf_generic( MBEDTLS_MD_SHA384, secret, slen, label, random, rlen, dstbuf, dlen ) ); } #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ static void ssl_update_checksum_start( mbedtls_ssl_context *, const unsigned char *, size_t ); #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *, const unsigned char *, size_t ); #endif #if defined(MBEDTLS_SSL_PROTO_SSL3) static void ssl_calc_verify_ssl( const mbedtls_ssl_context *, unsigned char *, size_t * ); static void ssl_calc_finished_ssl( mbedtls_ssl_context *, unsigned char *, int ); #endif #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) static void ssl_calc_verify_tls( const mbedtls_ssl_context *, unsigned char*, size_t * ); static void ssl_calc_finished_tls( mbedtls_ssl_context *, unsigned char *, int ); #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) static void ssl_update_checksum_sha256( mbedtls_ssl_context *, const unsigned char *, size_t ); static void ssl_calc_verify_tls_sha256( const mbedtls_ssl_context *,unsigned char*, size_t * ); static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *,unsigned char *, int ); #endif #if defined(MBEDTLS_SHA512_C) static void ssl_update_checksum_sha384( mbedtls_ssl_context *, const unsigned char *, size_t ); static void ssl_calc_verify_tls_sha384( const mbedtls_ssl_context *, unsigned char*, size_t * ); static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *, unsigned char *, int ); #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_SSL_EXPORT_KEYS) static mbedtls_tls_prf_types tls_prf_get_type( mbedtls_ssl_tls_prf_cb *tls_prf ) { #if defined(MBEDTLS_SSL_PROTO_SSL3) if( tls_prf == ssl3_prf ) { return( MBEDTLS_SSL_TLS_PRF_SSL3 ); } else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) if( tls_prf == tls1_prf ) { return( MBEDTLS_SSL_TLS_PRF_TLS1 ); } else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA512_C) if( tls_prf == tls_prf_sha384 ) { return( MBEDTLS_SSL_TLS_PRF_SHA384 ); } else #endif #if defined(MBEDTLS_SHA256_C) if( tls_prf == tls_prf_sha256 ) { return( MBEDTLS_SSL_TLS_PRF_SHA256 ); } else #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ return( MBEDTLS_SSL_TLS_PRF_NONE ); } #endif /* MBEDTLS_SSL_EXPORT_KEYS */ /** * \brief TLS-PRF function for key derivation. * * \param prf The tls_prf type funtion type to be used. * \param secret Secret for the key derivation function. * \param slen Length of the secret. * \param label String label for the key derivation function, * terminated with null character. * \param random Random bytes. * \param rlen Length of the random bytes buffer. * \param dstbuf The buffer holding the derived key. * \param dlen Length of the output buffer. * * \return 0 on sucess. An SSL specific error on failure. */ int mbedtls_ssl_tls_prf( const mbedtls_tls_prf_types prf, const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { mbedtls_ssl_tls_prf_cb *tls_prf = NULL; switch( prf ) { #if defined(MBEDTLS_SSL_PROTO_SSL3) case MBEDTLS_SSL_TLS_PRF_SSL3: tls_prf = ssl3_prf; break; #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) case MBEDTLS_SSL_TLS_PRF_TLS1: tls_prf = tls1_prf; break; #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA512_C) case MBEDTLS_SSL_TLS_PRF_SHA384: tls_prf = tls_prf_sha384; break; #endif /* MBEDTLS_SHA512_C */ #if defined(MBEDTLS_SHA256_C) case MBEDTLS_SSL_TLS_PRF_SHA256: tls_prf = tls_prf_sha256; break; #endif /* MBEDTLS_SHA256_C */ #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ default: return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } return( tls_prf( secret, slen, label, random, rlen, dstbuf, dlen ) ); } /* Type for the TLS PRF */ typedef int ssl_tls_prf_t(const unsigned char *, size_t, const char *, const unsigned char *, size_t, unsigned char *, size_t); /* * Populate a transform structure with session keys and all the other * necessary information. * * Parameters: * - [in/out]: transform: structure to populate * [in] must be just initialised with mbedtls_ssl_transform_init() * [out] fully populated, ready for use by mbedtls_ssl_{en,de}crypt_buf() * - [in] ciphersuite * - [in] master * - [in] encrypt_then_mac * - [in] trunc_hmac * - [in] compression * - [in] tls_prf: pointer to PRF to use for key derivation * - [in] randbytes: buffer holding ServerHello.random + ClientHello.random * - [in] minor_ver: SSL/TLS minor version * - [in] endpoint: client or server * - [in] ssl: optionally used for: * - MBEDTLS_SSL_HW_RECORD_ACCEL: whole context (non-const) * - MBEDTLS_SSL_EXPORT_KEYS: ssl->conf->{f,p}_export_keys * - MBEDTLS_DEBUG_C: ssl->conf->{f,p}_dbg */ static int ssl_populate_transform( mbedtls_ssl_transform *transform, int ciphersuite, const unsigned char master[48], #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) int encrypt_then_mac, #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */ #if defined(MBEDTLS_ZLIB_SUPPORT) int compression, #endif ssl_tls_prf_t tls_prf, const unsigned char randbytes[64], int minor_ver, unsigned endpoint, #if !defined(MBEDTLS_SSL_HW_RECORD_ACCEL) const #endif mbedtls_ssl_context *ssl ) { int ret = 0; unsigned char keyblk[256]; unsigned char *key1; unsigned char *key2; unsigned char *mac_enc; unsigned char *mac_dec; size_t mac_key_len = 0; size_t iv_copy_len; unsigned keylen; const mbedtls_ssl_ciphersuite_t *ciphersuite_info; const mbedtls_cipher_info_t *cipher_info; const mbedtls_md_info_t *md_info; #if !defined(MBEDTLS_SSL_HW_RECORD_ACCEL) && \ !defined(MBEDTLS_SSL_EXPORT_KEYS) && \ !defined(MBEDTLS_DEBUG_C) ssl = NULL; /* make sure we don't use it except for those cases */ (void) ssl; #endif /* * Some data just needs copying into the structure */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) && \ defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) transform->encrypt_then_mac = encrypt_then_mac; #endif transform->minor_ver = minor_ver; #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION) memcpy( transform->randbytes, randbytes, sizeof( transform->randbytes ) ); #endif /* * Get various info structures */ ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuite ); if( ciphersuite_info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "ciphersuite info for %d not found", ciphersuite ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } cipher_info = mbedtls_cipher_info_from_type( ciphersuite_info->cipher ); if( cipher_info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "cipher info for %u not found", ciphersuite_info->cipher ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } md_info = mbedtls_md_info_from_type( ciphersuite_info->mac ); if( md_info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_md info for %u not found", (unsigned) ciphersuite_info->mac ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) /* Copy own and peer's CID if the use of the CID * extension has been negotiated. */ if( ssl->handshake->cid_in_use == MBEDTLS_SSL_CID_ENABLED ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Copy CIDs into SSL transform" ) ); transform->in_cid_len = ssl->own_cid_len; memcpy( transform->in_cid, ssl->own_cid, ssl->own_cid_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "Incoming CID", transform->in_cid, transform->in_cid_len ); transform->out_cid_len = ssl->handshake->peer_cid_len; memcpy( transform->out_cid, ssl->handshake->peer_cid, ssl->handshake->peer_cid_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "Outgoing CID", transform->out_cid, transform->out_cid_len ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ /* * Compute key block using the PRF */ ret = tls_prf( master, 48, "key expansion", randbytes, 64, keyblk, 256 ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite = %s", mbedtls_ssl_get_ciphersuite_name( ciphersuite ) ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "master secret", master, 48 ); MBEDTLS_SSL_DEBUG_BUF( 4, "random bytes", randbytes, 64 ); MBEDTLS_SSL_DEBUG_BUF( 4, "key block", keyblk, 256 ); /* * Determine the appropriate key, IV and MAC length. */ keylen = cipher_info->key_bitlen / 8; #if defined(MBEDTLS_GCM_C) || \ defined(MBEDTLS_CCM_C) || \ defined(MBEDTLS_CHACHAPOLY_C) if( cipher_info->mode == MBEDTLS_MODE_GCM || cipher_info->mode == MBEDTLS_MODE_CCM || cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY ) { size_t explicit_ivlen; transform->maclen = 0; mac_key_len = 0; transform->taglen = ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16; /* All modes haves 96-bit IVs, but the length of the static parts vary * with mode and version: * - For GCM and CCM in TLS 1.2, there's a static IV of 4 Bytes * (to be concatenated with a dynamically chosen IV of 8 Bytes) * - For ChaChaPoly in TLS 1.2, and all modes in TLS 1.3, there's * a static IV of 12 Bytes (to be XOR'ed with the 8 Byte record * sequence number). */ transform->ivlen = 12; #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_4 ) { transform->fixed_ivlen = 12; } else #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ { if( cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY ) transform->fixed_ivlen = 12; else transform->fixed_ivlen = 4; } /* Minimum length of encrypted record */ explicit_ivlen = transform->ivlen - transform->fixed_ivlen; transform->minlen = explicit_ivlen + transform->taglen; } else #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */ #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) if( cipher_info->mode == MBEDTLS_MODE_STREAM || cipher_info->mode == MBEDTLS_MODE_CBC ) { /* Initialize HMAC contexts */ if( ( ret = mbedtls_md_setup( &transform->md_ctx_enc, md_info, 1 ) ) != 0 || ( ret = mbedtls_md_setup( &transform->md_ctx_dec, md_info, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret ); goto end; } /* Get MAC length */ mac_key_len = mbedtls_md_get_size( md_info ); transform->maclen = mac_key_len; /* IV length */ transform->ivlen = cipher_info->iv_size; /* Minimum length */ if( cipher_info->mode == MBEDTLS_MODE_STREAM ) transform->minlen = transform->maclen; else { /* * GenericBlockCipher: * 1. if EtM is in use: one block plus MAC * otherwise: * first multiple of blocklen greater than maclen * 2. IV except for SSL3 and TLS 1.0 */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) if( encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED ) { transform->minlen = transform->maclen + cipher_info->block_size; } else #endif { transform->minlen = transform->maclen + cipher_info->block_size - transform->maclen % cipher_info->block_size; } #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 || minor_ver == MBEDTLS_SSL_MINOR_VERSION_1 ) ; /* No need to adjust minlen */ else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_2 || minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { transform->minlen += transform->ivlen; } else #endif { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; goto end; } } } else #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "keylen: %u, minlen: %u, ivlen: %u, maclen: %u", (unsigned) keylen, (unsigned) transform->minlen, (unsigned) transform->ivlen, (unsigned) transform->maclen ) ); /* * Finally setup the cipher contexts, IVs and MAC secrets. */ #if defined(MBEDTLS_SSL_CLI_C) if( endpoint == MBEDTLS_SSL_IS_CLIENT ) { key1 = keyblk + mac_key_len * 2; key2 = keyblk + mac_key_len * 2 + keylen; mac_enc = keyblk; mac_dec = keyblk + mac_key_len; /* * This is not used in TLS v1.1. */ iv_copy_len = ( transform->fixed_ivlen ) ? transform->fixed_ivlen : transform->ivlen; memcpy( transform->iv_enc, key2 + keylen, iv_copy_len ); memcpy( transform->iv_dec, key2 + keylen + iv_copy_len, iv_copy_len ); } else #endif /* MBEDTLS_SSL_CLI_C */ #if defined(MBEDTLS_SSL_SRV_C) if( endpoint == MBEDTLS_SSL_IS_SERVER ) { key1 = keyblk + mac_key_len * 2 + keylen; key2 = keyblk + mac_key_len * 2; mac_enc = keyblk + mac_key_len; mac_dec = keyblk; /* * This is not used in TLS v1.1. */ iv_copy_len = ( transform->fixed_ivlen ) ? transform->fixed_ivlen : transform->ivlen; memcpy( transform->iv_dec, key1 + keylen, iv_copy_len ); memcpy( transform->iv_enc, key1 + keylen + iv_copy_len, iv_copy_len ); } else #endif /* MBEDTLS_SSL_SRV_C */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; goto end; } #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) #if defined(MBEDTLS_SSL_PROTO_SSL3) if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { if( mac_key_len > sizeof( transform->mac_enc ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; goto end; } memcpy( transform->mac_enc, mac_enc, mac_key_len ); memcpy( transform->mac_dec, mac_dec, mac_key_len ); } else #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 ) { /* For HMAC-based ciphersuites, initialize the HMAC transforms. For AEAD-based ciphersuites, there is nothing to do here. */ if( mac_key_len != 0 ) { mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, mac_key_len ); mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, mac_key_len ); } } else #endif { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; goto end; } #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */ #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_init != NULL ) { ret = 0; MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_init()" ) ); if( ( ret = mbedtls_ssl_hw_record_init( ssl, key1, key2, keylen, transform->iv_enc, transform->iv_dec, iv_copy_len, mac_enc, mac_dec, mac_key_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_init", ret ); ret = MBEDTLS_ERR_SSL_HW_ACCEL_FAILED; goto end; } } #else ((void) mac_dec); ((void) mac_enc); #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ #if defined(MBEDTLS_SSL_EXPORT_KEYS) if( ssl->conf->f_export_keys != NULL ) { ssl->conf->f_export_keys( ssl->conf->p_export_keys, master, keyblk, mac_key_len, keylen, iv_copy_len ); } if( ssl->conf->f_export_keys_ext != NULL ) { ssl->conf->f_export_keys_ext( ssl->conf->p_export_keys, master, keyblk, mac_key_len, keylen, iv_copy_len, randbytes + 32, randbytes, tls_prf_get_type( tls_prf ) ); } #endif if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc, cipher_info ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret ); goto end; } if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec, cipher_info ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret ); goto end; } if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_enc, key1, cipher_info->key_bitlen, MBEDTLS_ENCRYPT ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret ); goto end; } if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_dec, key2, cipher_info->key_bitlen, MBEDTLS_DECRYPT ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret ); goto end; } #if defined(MBEDTLS_CIPHER_MODE_CBC) if( cipher_info->mode == MBEDTLS_MODE_CBC ) { if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_enc, MBEDTLS_PADDING_NONE ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret ); goto end; } if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_dec, MBEDTLS_PADDING_NONE ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret ); goto end; } } #endif /* MBEDTLS_CIPHER_MODE_CBC */ /* Initialize Zlib contexts */ #if defined(MBEDTLS_ZLIB_SUPPORT) if( compression == MBEDTLS_SSL_COMPRESS_DEFLATE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) ); mbedtls_platform_zeroize( &transform->ctx_deflate, sizeof( transform->ctx_deflate ) ); mbedtls_platform_zeroize( &transform->ctx_inflate, sizeof( transform->ctx_inflate ) ); if( deflateInit( &transform->ctx_deflate, Z_DEFAULT_COMPRESSION ) != Z_OK || inflateInit( &transform->ctx_inflate ) != Z_OK ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) ); ret = MBEDTLS_ERR_SSL_COMPRESSION_FAILED; goto end; } } #endif /* MBEDTLS_ZLIB_SUPPORT */ end: mbedtls_platform_zeroize( keyblk, sizeof( keyblk ) ); return( ret ); } /* * Set appropriate PRF function and other SSL / TLS 1.0/1.1 / TLS1.2 functions * * Inputs: * - SSL/TLS minor version * - hash associated with the ciphersuite (only used by TLS 1.2) * * Outputs: * - the tls_prf, calc_verify and calc_finished members of handshake structure */ static int ssl_set_handshake_prfs( mbedtls_ssl_handshake_params *handshake, int minor_ver, mbedtls_md_type_t hash ) { #if !defined(MBEDTLS_SSL_PROTO_TLS1_2) || !defined(MBEDTLS_SHA512_C) (void) hash; #endif #if defined(MBEDTLS_SSL_PROTO_SSL3) if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { handshake->tls_prf = ssl3_prf; handshake->calc_verify = ssl_calc_verify_ssl; handshake->calc_finished = ssl_calc_finished_ssl; } else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) if( minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 ) { handshake->tls_prf = tls1_prf; handshake->calc_verify = ssl_calc_verify_tls; handshake->calc_finished = ssl_calc_finished_tls; } else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA512_C) if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 && hash == MBEDTLS_MD_SHA384 ) { handshake->tls_prf = tls_prf_sha384; handshake->calc_verify = ssl_calc_verify_tls_sha384; handshake->calc_finished = ssl_calc_finished_tls_sha384; } else #endif #if defined(MBEDTLS_SHA256_C) if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { handshake->tls_prf = tls_prf_sha256; handshake->calc_verify = ssl_calc_verify_tls_sha256; handshake->calc_finished = ssl_calc_finished_tls_sha256; } else #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ { return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } return( 0 ); } /* * Compute master secret if needed * * Parameters: * [in/out] handshake * [in] resume, premaster, extended_ms, calc_verify, tls_prf * (PSA-PSK) ciphersuite_info, psk_opaque * [out] premaster (cleared) * [out] master * [in] ssl: optionally used for debugging, EMS and PSA-PSK * debug: conf->f_dbg, conf->p_dbg * EMS: passed to calc_verify (debug + (SSL3) session_negotiate) * PSA-PSA: minor_ver, conf */ static int ssl_compute_master( mbedtls_ssl_handshake_params *handshake, unsigned char *master, const mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; /* cf. RFC 5246, Section 8.1: * "The master secret is always exactly 48 bytes in length." */ size_t const master_secret_len = 48; #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) unsigned char session_hash[48]; #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ /* The label for the KDF used for key expansion. * This is either "master secret" or "extended master secret" * depending on whether the Extended Master Secret extension * is used. */ char const *lbl = "master secret"; /* The salt for the KDF used for key expansion. * - If the Extended Master Secret extension is not used, * this is ClientHello.Random + ServerHello.Random * (see Sect. 8.1 in RFC 5246). * - If the Extended Master Secret extension is used, * this is the transcript of the handshake so far. * (see Sect. 4 in RFC 7627). */ unsigned char const *salt = handshake->randbytes; size_t salt_len = 64; #if !defined(MBEDTLS_DEBUG_C) && \ !defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) && \ !(defined(MBEDTLS_USE_PSA_CRYPTO) && \ defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)) ssl = NULL; /* make sure we don't use it except for those cases */ (void) ssl; #endif if( handshake->resume != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) if( handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED ) { lbl = "extended master secret"; salt = session_hash; handshake->calc_verify( ssl, session_hash, &salt_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "session hash for extended master secret", session_hash, salt_len ); } #endif /* MBEDTLS_SSL_EXTENDED_MS_ENABLED */ ret = handshake->tls_prf( handshake->premaster, handshake->pmslen, lbl, salt, salt_len, master, master_secret_len ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster, handshake->pmslen ); mbedtls_platform_zeroize( handshake->premaster, sizeof(handshake->premaster) ); return( 0 ); } int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; const mbedtls_ssl_ciphersuite_t * const ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> derive keys" ) ); /* Set PRF, calc_verify and calc_finished function pointers */ ret = ssl_set_handshake_prfs( ssl->handshake, ssl->minor_ver, ciphersuite_info->mac ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_set_handshake_prfs", ret ); return( ret ); } /* Compute master secret if needed */ ret = ssl_compute_master( ssl->handshake, ssl->session_negotiate->master, ssl ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compute_master", ret ); return( ret ); } /* Swap the client and server random values: * - MS derivation wanted client+server (RFC 5246 8.1) * - key derivation wants server+client (RFC 5246 6.3) */ { unsigned char tmp[64]; memcpy( tmp, ssl->handshake->randbytes, 64 ); memcpy( ssl->handshake->randbytes, tmp + 32, 32 ); memcpy( ssl->handshake->randbytes + 32, tmp, 32 ); mbedtls_platform_zeroize( tmp, sizeof( tmp ) ); } /* Populate transform structure */ ret = ssl_populate_transform( ssl->transform_negotiate, ssl->session_negotiate->ciphersuite, ssl->session_negotiate->master, #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) ssl->session_negotiate->encrypt_then_mac, #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */ #if defined(MBEDTLS_ZLIB_SUPPORT) ssl->session_negotiate->compression, #endif ssl->handshake->tls_prf, ssl->handshake->randbytes, ssl->minor_ver, ssl->conf->endpoint, ssl ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_populate_transform", ret ); return( ret ); } /* We no longer need Server/ClientHello.random values */ mbedtls_platform_zeroize( ssl->handshake->randbytes, sizeof( ssl->handshake->randbytes ) ); /* Allocate compression buffer */ #if defined(MBEDTLS_ZLIB_SUPPORT) if( ssl->session_negotiate->compression == MBEDTLS_SSL_COMPRESS_DEFLATE && ssl->compress_buf == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Allocating compression buffer" ) ); ssl->compress_buf = mbedtls_calloc( 1, MBEDTLS_SSL_COMPRESS_BUFFER_LEN ); if( ssl->compress_buf == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", MBEDTLS_SSL_COMPRESS_BUFFER_LEN ) ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } } #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= derive keys" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) void ssl_calc_verify_ssl( const mbedtls_ssl_context *ssl, unsigned char *hash, size_t *hlen ) { mbedtls_md5_context md5; mbedtls_sha1_context sha1; unsigned char pad_1[48]; unsigned char pad_2[48]; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) ); mbedtls_md5_init( &md5 ); mbedtls_sha1_init( &sha1 ); mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 ); mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 ); memset( pad_1, 0x36, 48 ); memset( pad_2, 0x5C, 48 ); mbedtls_md5_update_ret( &md5, ssl->session_negotiate->master, 48 ); mbedtls_md5_update_ret( &md5, pad_1, 48 ); mbedtls_md5_finish_ret( &md5, hash ); mbedtls_md5_starts_ret( &md5 ); mbedtls_md5_update_ret( &md5, ssl->session_negotiate->master, 48 ); mbedtls_md5_update_ret( &md5, pad_2, 48 ); mbedtls_md5_update_ret( &md5, hash, 16 ); mbedtls_md5_finish_ret( &md5, hash ); mbedtls_sha1_update_ret( &sha1, ssl->session_negotiate->master, 48 ); mbedtls_sha1_update_ret( &sha1, pad_1, 40 ); mbedtls_sha1_finish_ret( &sha1, hash + 16 ); mbedtls_sha1_starts_ret( &sha1 ); mbedtls_sha1_update_ret( &sha1, ssl->session_negotiate->master, 48 ); mbedtls_sha1_update_ret( &sha1, pad_2, 40 ); mbedtls_sha1_update_ret( &sha1, hash + 16, 20 ); mbedtls_sha1_finish_ret( &sha1, hash + 16 ); *hlen = 36; MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, *hlen ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); mbedtls_md5_free( &md5 ); mbedtls_sha1_free( &sha1 ); return; } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) void ssl_calc_verify_tls( const mbedtls_ssl_context *ssl, unsigned char *hash, size_t *hlen ) { mbedtls_md5_context md5; mbedtls_sha1_context sha1; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) ); mbedtls_md5_init( &md5 ); mbedtls_sha1_init( &sha1 ); mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 ); mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 ); mbedtls_md5_finish_ret( &md5, hash ); mbedtls_sha1_finish_ret( &sha1, hash + 16 ); *hlen = 36; MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, *hlen ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); mbedtls_md5_free( &md5 ); mbedtls_sha1_free( &sha1 ); return; } #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) void ssl_calc_verify_tls_sha256( const mbedtls_ssl_context *ssl, unsigned char *hash, size_t *hlen ) { mbedtls_sha256_context sha256; mbedtls_sha256_init( &sha256 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) ); mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 ); mbedtls_sha256_finish_ret( &sha256, hash ); *hlen = 32; MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, *hlen ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); mbedtls_sha256_free( &sha256 ); return; } #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) void ssl_calc_verify_tls_sha384( const mbedtls_ssl_context *ssl, unsigned char *hash, size_t *hlen ) { mbedtls_sha512_context sha512; mbedtls_sha512_init( &sha512 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) ); mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 ); mbedtls_sha512_finish_ret( &sha512, hash ); *hlen = 48; MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, *hlen ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); mbedtls_sha512_free( &sha512 ); return; } #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex ) { unsigned char *p = ssl->handshake->premaster; unsigned char *end = p + sizeof( ssl->handshake->premaster ); const unsigned char *psk = NULL; size_t psk_len = 0; if( mbedtls_ssl_get_psk( ssl, &psk, &psk_len ) == MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ) { /* * This should never happen because the existence of a PSK is always * checked before calling this function */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* * PMS = struct { * opaque other_secret<0..2^16-1>; * opaque psk<0..2^16-1>; * }; * with "other_secret" depending on the particular key exchange */ #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) if( key_ex == MBEDTLS_KEY_EXCHANGE_PSK ) { if( end - p < 2 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); *(p++) = (unsigned char)( psk_len >> 8 ); *(p++) = (unsigned char)( psk_len ); if( end < p || (size_t)( end - p ) < psk_len ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); mbedtls_platform_zeroize( p, psk_len ); p += psk_len; } else #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) if( key_ex == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) { /* * other_secret already set by the ClientKeyExchange message, * and is 48 bytes long */ if( end - p < 2 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); *p++ = 0; *p++ = 48; p += 48; } else #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) if( key_ex == MBEDTLS_KEY_EXCHANGE_DHE_PSK ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len; /* Write length only when we know the actual value */ if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx, p + 2, end - ( p + 2 ), &len, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret ); return( ret ); } *(p++) = (unsigned char)( len >> 8 ); *(p++) = (unsigned char)( len ); p += len; MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K ); } else #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) if( key_ex == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t zlen; if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &zlen, p + 2, end - ( p + 2 ), ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret ); return( ret ); } *(p++) = (unsigned char)( zlen >> 8 ); *(p++) = (unsigned char)( zlen ); p += zlen; MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_Z ); } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* opaque psk<0..2^16-1>; */ if( end - p < 2 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); *(p++) = (unsigned char)( psk_len >> 8 ); *(p++) = (unsigned char)( psk_len ); if( end < p || (size_t)( end - p ) < psk_len ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); memcpy( p, psk, psk_len ); p += psk_len; ssl->handshake->pmslen = p - ssl->handshake->premaster; return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION) static int ssl_write_hello_request( mbedtls_ssl_context *ssl ); #if defined(MBEDTLS_SSL_PROTO_DTLS) int mbedtls_ssl_resend_hello_request( mbedtls_ssl_context *ssl ) { /* If renegotiation is not enforced, retransmit until we would reach max * timeout if we were using the usual handshake doubling scheme */ if( ssl->conf->renego_max_records < 0 ) { uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1; unsigned char doublings = 1; while( ratio != 0 ) { ++doublings; ratio >>= 1; } if( ++ssl->renego_records_seen > doublings ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "no longer retransmitting hello request" ) ); return( 0 ); } } return( ssl_write_hello_request( ssl ) ); } #endif #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */ #if defined(MBEDTLS_X509_CRT_PARSE_C) static void ssl_clear_peer_cert( mbedtls_ssl_session *session ) { #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) if( session->peer_cert != NULL ) { mbedtls_x509_crt_free( session->peer_cert ); mbedtls_free( session->peer_cert ); session->peer_cert = NULL; } #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( session->peer_cert_digest != NULL ) { /* Zeroization is not necessary. */ mbedtls_free( session->peer_cert_digest ); session->peer_cert_digest = NULL; session->peer_cert_digest_type = MBEDTLS_MD_NONE; session->peer_cert_digest_len = 0; } #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ } #endif /* MBEDTLS_X509_CRT_PARSE_C */ /* * Handshake functions */ #if !defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /* No certificate support -> dummy functions */ int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) ); if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) ); ssl->state++; return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) ); if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); ssl->state++; return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #else /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ /* Some certificate support -> implement write and parse */ int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t i, n; const mbedtls_x509_crt *crt; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) ); if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) ); ssl->state++; return( 0 ); } #if defined(MBEDTLS_SSL_CLI_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) { if( ssl->client_auth == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) ); ssl->state++; return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) /* * If using SSLv3 and got no cert, send an Alert message * (otherwise an empty Certificate message will be sent). */ if( mbedtls_ssl_own_cert( ssl ) == NULL && ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { ssl->out_msglen = 2; ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT; ssl->out_msg[0] = MBEDTLS_SSL_ALERT_LEVEL_WARNING; ssl->out_msg[1] = MBEDTLS_SSL_ALERT_MSG_NO_CERT; MBEDTLS_SSL_DEBUG_MSG( 2, ( "got no certificate to send" ) ); goto write_msg; } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ } #endif /* MBEDTLS_SSL_CLI_C */ #if defined(MBEDTLS_SSL_SRV_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) { if( mbedtls_ssl_own_cert( ssl ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no certificate to send" ) ); return( MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED ); } } #endif MBEDTLS_SSL_DEBUG_CRT( 3, "own certificate", mbedtls_ssl_own_cert( ssl ) ); /* * 0 . 0 handshake type * 1 . 3 handshake length * 4 . 6 length of all certs * 7 . 9 length of cert. 1 * 10 . n-1 peer certificate * n . n+2 length of cert. 2 * n+3 . ... upper level cert, etc. */ i = 7; crt = mbedtls_ssl_own_cert( ssl ); while( crt != NULL ) { n = crt->raw.len; if( n > MBEDTLS_SSL_OUT_CONTENT_LEN - 3 - i ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate too large, %" MBEDTLS_PRINTF_SIZET " > %" MBEDTLS_PRINTF_SIZET, i + 3 + n, (size_t) MBEDTLS_SSL_OUT_CONTENT_LEN ) ); return( MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE ); } ssl->out_msg[i ] = (unsigned char)( n >> 16 ); ssl->out_msg[i + 1] = (unsigned char)( n >> 8 ); ssl->out_msg[i + 2] = (unsigned char)( n ); i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n ); i += n; crt = crt->next; } ssl->out_msg[4] = (unsigned char)( ( i - 7 ) >> 16 ); ssl->out_msg[5] = (unsigned char)( ( i - 7 ) >> 8 ); ssl->out_msg[6] = (unsigned char)( ( i - 7 ) ); ssl->out_msglen = i; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE; #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C) write_msg: #endif ssl->state++; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate" ) ); return( ret ); } #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C) #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) static int ssl_check_peer_crt_unchanged( mbedtls_ssl_context *ssl, unsigned char *crt_buf, size_t crt_buf_len ) { mbedtls_x509_crt const * const peer_crt = ssl->session->peer_cert; if( peer_crt == NULL ) return( -1 ); if( peer_crt->raw.len != crt_buf_len ) return( -1 ); return( timingsafe_bcmp( peer_crt->raw.p, crt_buf, peer_crt->raw.len ) ); } #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ static int ssl_check_peer_crt_unchanged( mbedtls_ssl_context *ssl, unsigned char *crt_buf, size_t crt_buf_len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char const * const peer_cert_digest = ssl->session->peer_cert_digest; mbedtls_md_type_t const peer_cert_digest_type = ssl->session->peer_cert_digest_type; mbedtls_md_info_t const * const digest_info = mbedtls_md_info_from_type( peer_cert_digest_type ); unsigned char tmp_digest[MBEDTLS_SSL_PEER_CERT_DIGEST_MAX_LEN]; size_t digest_len; if( peer_cert_digest == NULL || digest_info == NULL ) return( -1 ); digest_len = mbedtls_md_get_size( digest_info ); if( digest_len > MBEDTLS_SSL_PEER_CERT_DIGEST_MAX_LEN ) return( -1 ); ret = mbedtls_md( digest_info, crt_buf, crt_buf_len, tmp_digest ); if( ret != 0 ) return( -1 ); return( timingsafe_bcmp( tmp_digest, peer_cert_digest, digest_len ) ); } #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */ /* * Once the certificate message is read, parse it into a cert chain and * perform basic checks, but leave actual verification to the caller */ static int ssl_parse_certificate_chain( mbedtls_ssl_context *ssl, mbedtls_x509_crt *chain ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C) int crt_cnt=0; #endif size_t i, n; uint8_t alert; if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE || ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 3 + 3 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } i = mbedtls_ssl_hs_hdr_len( ssl ); /* * Same message structure as in mbedtls_ssl_write_certificate() */ n = ( ssl->in_msg[i+1] << 8 ) | ssl->in_msg[i+2]; if( ssl->in_msg[i] != 0 || ssl->in_hslen != n + 3 + mbedtls_ssl_hs_hdr_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } /* Make &ssl->in_msg[i] point to the beginning of the CRT chain. */ i += 3; /* Iterate through and parse the CRTs in the provided chain. */ while( i < ssl->in_hslen ) { /* Check that there's room for the next CRT's length fields. */ if ( i + 3 > ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } /* In theory, the CRT can be up to 2**24 Bytes, but we don't support * anything beyond 2**16 ~ 64K. */ if( ssl->in_msg[i] != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } /* Read length of the next CRT in the chain. */ n = ( (unsigned int) ssl->in_msg[i + 1] << 8 ) | (unsigned int) ssl->in_msg[i + 2]; i += 3; if( n < 128 || i + n > ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } /* Check if we're handling the first CRT in the chain. */ #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C) if( crt_cnt++ == 0 && ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT && ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { /* During client-side renegotiation, check that the server's * end-CRTs hasn't changed compared to the initial handshake, * mitigating the triple handshake attack. On success, reuse * the original end-CRT instead of parsing it again. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "Check that peer CRT hasn't changed during renegotiation" ) ); if( ssl_check_peer_crt_unchanged( ssl, &ssl->in_msg[i], n ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "new server cert during renegotiation" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } /* Now we can safely free the original chain. */ ssl_clear_peer_cert( ssl->session ); } #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */ /* Parse the next certificate in the chain. */ #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) ret = mbedtls_x509_crt_parse_der( chain, ssl->in_msg + i, n ); #else /* If we don't need to store the CRT chain permanently, parse * it in-place from the input buffer instead of making a copy. */ ret = mbedtls_x509_crt_parse_der_nocopy( chain, ssl->in_msg + i, n ); #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ switch( ret ) { case 0: /*ok*/ case MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND: /* Ignore certificate with an unknown algorithm: maybe a prior certificate was already trusted. */ break; case MBEDTLS_ERR_X509_ALLOC_FAILED: alert = MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR; goto crt_parse_der_failed; case MBEDTLS_ERR_X509_UNKNOWN_VERSION: alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT; goto crt_parse_der_failed; default: alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT; crt_parse_der_failed: mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, alert ); MBEDTLS_SSL_DEBUG_RET( 1, " mbedtls_x509_crt_parse_der", ret ); return( ret ); } i += n; } MBEDTLS_SSL_DEBUG_CRT( 3, "peer certificate", chain ); return( 0 ); } #if defined(MBEDTLS_SSL_SRV_C) static int ssl_srv_check_client_no_crt_notification( mbedtls_ssl_context *ssl ) { if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) return( -1 ); #if defined(MBEDTLS_SSL_PROTO_SSL3) /* * Check if the client sent an empty certificate */ if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { if( ssl->in_msglen == 2 && ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT && ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) ); return( 0 ); } return( -1 ); } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->in_hslen == 3 + mbedtls_ssl_hs_hdr_len( ssl ) && ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE && timingsafe_bcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), "\0\0\0", 3 ) == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) ); return( 0 ); } return( -1 ); #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ } #endif /* MBEDTLS_SSL_SRV_C */ /* Check if a certificate message is expected. * Return either * - SSL_CERTIFICATE_EXPECTED, or * - SSL_CERTIFICATE_SKIP * indicating whether a Certificate message is expected or not. */ #define SSL_CERTIFICATE_EXPECTED 0 #define SSL_CERTIFICATE_SKIP 1 static int ssl_parse_certificate_coordinate( mbedtls_ssl_context *ssl, int authmode ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) ) return( SSL_CERTIFICATE_SKIP ); #if defined(MBEDTLS_SSL_SRV_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) { if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) return( SSL_CERTIFICATE_SKIP ); if( authmode == MBEDTLS_SSL_VERIFY_NONE ) { ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_SKIP_VERIFY; return( SSL_CERTIFICATE_SKIP ); } } #else ((void) authmode); #endif /* MBEDTLS_SSL_SRV_C */ return( SSL_CERTIFICATE_EXPECTED ); } static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl, int authmode, mbedtls_x509_crt *chain, void *rs_ctx ) { int ret = 0; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; int have_ca_chain = 0; int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *); void *p_vrfy; if( authmode == MBEDTLS_SSL_VERIFY_NONE ) return( 0 ); if( ssl->f_vrfy != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use context-specific verification callback" ) ); f_vrfy = ssl->f_vrfy; p_vrfy = ssl->p_vrfy; } else { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use configuration-specific verification callback" ) ); f_vrfy = ssl->conf->f_vrfy; p_vrfy = ssl->conf->p_vrfy; } /* * Main check: verify certificate */ #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK) if( ssl->conf->f_ca_cb != NULL ) { ((void) rs_ctx); have_ca_chain = 1; MBEDTLS_SSL_DEBUG_MSG( 3, ( "use CA callback for X.509 CRT verification" ) ); ret = mbedtls_x509_crt_verify_with_ca_cb( chain, ssl->conf->f_ca_cb, ssl->conf->p_ca_cb, ssl->conf->cert_profile, ssl->hostname, &ssl->session_negotiate->verify_result, f_vrfy, p_vrfy ); } else #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */ { mbedtls_x509_crt *ca_chain; mbedtls_x509_crl *ca_crl; #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) if( ssl->handshake->sni_ca_chain != NULL ) { ca_chain = ssl->handshake->sni_ca_chain; ca_crl = ssl->handshake->sni_ca_crl; } else #endif { ca_chain = ssl->conf->ca_chain; ca_crl = ssl->conf->ca_crl; } if( ca_chain != NULL ) have_ca_chain = 1; ret = mbedtls_x509_crt_verify_restartable( chain, ca_chain, ca_crl, ssl->conf->cert_profile, ssl->hostname, &ssl->session_negotiate->verify_result, f_vrfy, p_vrfy, rs_ctx ); } if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "x509_verify_cert", ret ); } #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) return( MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS ); #endif /* * Secondary checks: always done, but change 'ret' only if it was 0 */ #if defined(MBEDTLS_ECP_C) { const mbedtls_pk_context *pk = &chain->pk; /* If certificate uses an EC key, make sure the curve is OK */ if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECKEY ) && mbedtls_ssl_check_curve( ssl, mbedtls_pk_ec( *pk )->grp.id ) != 0 ) { ssl->session_negotiate->verify_result |= MBEDTLS_X509_BADCERT_BAD_KEY; MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (EC key curve)" ) ); if( ret == 0 ) ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE; } } #endif /* MBEDTLS_ECP_C */ if( mbedtls_ssl_check_cert_usage( chain, ciphersuite_info, ! ssl->conf->endpoint, &ssl->session_negotiate->verify_result ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (usage extensions)" ) ); if( ret == 0 ) ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE; } /* mbedtls_x509_crt_verify_with_profile is supposed to report a * verification failure through MBEDTLS_ERR_X509_CERT_VERIFY_FAILED, * with details encoded in the verification flags. All other kinds * of error codes, including those from the user provided f_vrfy * functions, are treated as fatal and lead to a failure of * ssl_parse_certificate even if verification was optional. */ if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL && ( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED || ret == MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ) ) { ret = 0; } if( have_ca_chain == 0 && authmode == MBEDTLS_SSL_VERIFY_REQUIRED ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no CA chain" ) ); ret = MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED; } if( ret != 0 ) { uint8_t alert; /* The certificate may have been rejected for several reasons. Pick one and send the corresponding alert. Which alert to send may be a subject of debate in some cases. */ if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_OTHER ) alert = MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED; else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_CN_MISMATCH ) alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT; else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_KEY_USAGE ) alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT; else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXT_KEY_USAGE ) alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT; else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NS_CERT_TYPE ) alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT; else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_PK ) alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT; else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_KEY ) alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT; else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXPIRED ) alert = MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED; else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_REVOKED ) alert = MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED; else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NOT_TRUSTED ) alert = MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA; else alert = MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN; mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, alert ); } #if defined(MBEDTLS_DEBUG_C) if( ssl->session_negotiate->verify_result != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "! Certificate verification flags %08x", (unsigned int) ssl->session_negotiate->verify_result ) ); } else { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Certificate verification flags clear" ) ); } #endif /* MBEDTLS_DEBUG_C */ return( ret ); } #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) static int ssl_remember_peer_crt_digest( mbedtls_ssl_context *ssl, unsigned char *start, size_t len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; /* Remember digest of the peer's end-CRT. */ ssl->session_negotiate->peer_cert_digest = mbedtls_calloc( 1, MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN ); if( ssl->session_negotiate->peer_cert_digest == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } ret = mbedtls_md( mbedtls_md_info_from_type( MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE ), start, len, ssl->session_negotiate->peer_cert_digest ); ssl->session_negotiate->peer_cert_digest_type = MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE; ssl->session_negotiate->peer_cert_digest_len = MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN; return( ret ); } static int ssl_remember_peer_pubkey( mbedtls_ssl_context *ssl, unsigned char *start, size_t len ) { unsigned char *end = start + len; int ret = MBEDTLS_ERR_THIS_CORRUPTION; /* Make a copy of the peer's raw public key. */ mbedtls_pk_init( &ssl->handshake->peer_pubkey ); ret = mbedtls_pk_parse_subpubkey( &start, end, &ssl->handshake->peer_pubkey ); if( ret != 0 ) { /* We should have parsed the public key before. */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } return( 0 ); } #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ) { int ret = 0; int crt_expected; #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) const int authmode = ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET ? ssl->handshake->sni_authmode : ssl->conf->authmode; #else const int authmode = ssl->conf->authmode; #endif void *rs_ctx = NULL; mbedtls_x509_crt *chain = NULL; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) ); crt_expected = ssl_parse_certificate_coordinate( ssl, authmode ); if( crt_expected == SSL_CERTIFICATE_SKIP ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); goto exit; } #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled && ssl->handshake->ecrs_state == ssl_ecrs_crt_verify ) { chain = ssl->handshake->ecrs_peer_cert; ssl->handshake->ecrs_peer_cert = NULL; goto crt_verify; } #endif if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { /* mbedtls_ssl_read_record may have sent an alert already. We let it decide whether to alert. */ MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); goto exit; } #if defined(MBEDTLS_SSL_SRV_C) if( ssl_srv_check_client_no_crt_notification( ssl ) == 0 ) { ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING; if( authmode != MBEDTLS_SSL_VERIFY_OPTIONAL ) ret = MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE; goto exit; } #endif /* MBEDTLS_SSL_SRV_C */ /* Clear existing peer CRT structure in case we tried to * reuse a session but it failed, and allocate a new one. */ ssl_clear_peer_cert( ssl->session_negotiate ); chain = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) ); if( chain == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%" MBEDTLS_PRINTF_SIZET " bytes) failed", sizeof( mbedtls_x509_crt ) ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; goto exit; } mbedtls_x509_crt_init( chain ); ret = ssl_parse_certificate_chain( ssl, chain ); if( ret != 0 ) goto exit; #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled) ssl->handshake->ecrs_state = ssl_ecrs_crt_verify; crt_verify: if( ssl->handshake->ecrs_enabled) rs_ctx = &ssl->handshake->ecrs_ctx; #endif ret = ssl_parse_certificate_verify( ssl, authmode, chain, rs_ctx ); if( ret != 0 ) goto exit; #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) { unsigned char *crt_start, *pk_start; size_t crt_len, pk_len; /* We parse the CRT chain without copying, so * these pointers point into the input buffer, * and are hence still valid after freeing the * CRT chain. */ crt_start = chain->raw.p; crt_len = chain->raw.len; pk_start = chain->pk_raw.p; pk_len = chain->pk_raw.len; /* Free the CRT structures before computing * digest and copying the peer's public key. */ mbedtls_x509_crt_free( chain ); mbedtls_free( chain ); chain = NULL; ret = ssl_remember_peer_crt_digest( ssl, crt_start, crt_len ); if( ret != 0 ) goto exit; ret = ssl_remember_peer_pubkey( ssl, pk_start, pk_len ); if( ret != 0 ) goto exit; } #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ /* Pass ownership to session structure. */ ssl->session_negotiate->peer_cert = chain; chain = NULL; #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) ); exit: if( ret == 0 ) ssl->state++; #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ret == MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS ) { ssl->handshake->ecrs_peer_cert = chain; chain = NULL; } #endif if( chain != NULL ) { mbedtls_x509_crt_free( chain ); mbedtls_free( chain ); } return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl, const mbedtls_ssl_ciphersuite_t *ciphersuite_info ) { ((void) ciphersuite_info); #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 ) ssl->handshake->update_checksum = ssl_update_checksum_md5sha1; else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA512_C) if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 ) ssl->handshake->update_checksum = ssl_update_checksum_sha384; else #endif #if defined(MBEDTLS_SHA256_C) if( ciphersuite_info->mac != MBEDTLS_MD_SHA384 ) ssl->handshake->update_checksum = ssl_update_checksum_sha256; else #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return; } } void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl ) { #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) mbedtls_md5_starts_ret( &ssl->handshake->fin_md5 ); mbedtls_sha1_starts_ret( &ssl->handshake->fin_sha1 ); #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) mbedtls_sha256_starts_ret( &ssl->handshake->fin_sha256, 0 ); #endif #if defined(MBEDTLS_SHA512_C) mbedtls_sha512_starts_ret( &ssl->handshake->fin_sha512, 1 ); #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ } static void ssl_update_checksum_start( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len ); mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len ); #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len ); #endif #if defined(MBEDTLS_SHA512_C) mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len ); #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ } #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len ); mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len ); } #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) static void ssl_update_checksum_sha256( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len ); } #endif #if defined(MBEDTLS_SHA512_C) static void ssl_update_checksum_sha384( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len ); } #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) static void ssl_calc_finished_ssl( mbedtls_ssl_context *ssl, unsigned char *buf, int from ) { const char *sender; mbedtls_md5_context md5; mbedtls_sha1_context sha1; unsigned char padbuf[48]; unsigned char md5sum[16]; unsigned char sha1sum[20]; mbedtls_ssl_session *session = ssl->session_negotiate; if( !session ) session = ssl->session; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished ssl" ) ); mbedtls_md5_init( &md5 ); mbedtls_sha1_init( &sha1 ); mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 ); mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 ); /* * SSLv3: * hash = * MD5( master + pad2 + * MD5( handshake + sender + master + pad1 ) ) * + SHA1( master + pad2 + * SHA1( handshake + sender + master + pad1 ) ) */ #if !defined(MBEDTLS_MD5_ALT) MBEDTLS_SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *) md5.state, sizeof( md5.state ) ); #endif #if !defined(MBEDTLS_SHA1_ALT) MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *) sha1.state, sizeof( sha1.state ) ); #endif sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "CLNT" : "SRVR"; memset( padbuf, 0x36, 48 ); mbedtls_md5_update_ret( &md5, (const unsigned char *) sender, 4 ); mbedtls_md5_update_ret( &md5, session->master, 48 ); mbedtls_md5_update_ret( &md5, padbuf, 48 ); mbedtls_md5_finish_ret( &md5, md5sum ); mbedtls_sha1_update_ret( &sha1, (const unsigned char *) sender, 4 ); mbedtls_sha1_update_ret( &sha1, session->master, 48 ); mbedtls_sha1_update_ret( &sha1, padbuf, 40 ); mbedtls_sha1_finish_ret( &sha1, sha1sum ); memset( padbuf, 0x5C, 48 ); mbedtls_md5_starts_ret( &md5 ); mbedtls_md5_update_ret( &md5, session->master, 48 ); mbedtls_md5_update_ret( &md5, padbuf, 48 ); mbedtls_md5_update_ret( &md5, md5sum, 16 ); mbedtls_md5_finish_ret( &md5, buf ); mbedtls_sha1_starts_ret( &sha1 ); mbedtls_sha1_update_ret( &sha1, session->master, 48 ); mbedtls_sha1_update_ret( &sha1, padbuf , 40 ); mbedtls_sha1_update_ret( &sha1, sha1sum, 20 ); mbedtls_sha1_finish_ret( &sha1, buf + 16 ); MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 ); mbedtls_md5_free( &md5 ); mbedtls_sha1_free( &sha1 ); mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) ); mbedtls_platform_zeroize( md5sum, sizeof( md5sum ) ); mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) static void ssl_calc_finished_tls( mbedtls_ssl_context *ssl, unsigned char *buf, int from ) { int len = 12; const char *sender; mbedtls_md5_context md5; mbedtls_sha1_context sha1; unsigned char padbuf[36]; mbedtls_ssl_session *session = ssl->session_negotiate; if( !session ) session = ssl->session; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls" ) ); mbedtls_md5_init( &md5 ); mbedtls_sha1_init( &sha1 ); mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 ); mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 ); /* * TLSv1: * hash = PRF( master, finished_label, * MD5( handshake ) + SHA1( handshake ) )[0..11] */ #if !defined(MBEDTLS_MD5_ALT) MBEDTLS_SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *) md5.state, sizeof( md5.state ) ); #endif #if !defined(MBEDTLS_SHA1_ALT) MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *) sha1.state, sizeof( sha1.state ) ); #endif sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "client finished" : "server finished"; mbedtls_md5_finish_ret( &md5, padbuf ); mbedtls_sha1_finish_ret( &sha1, padbuf + 16 ); ssl->handshake->tls_prf( session->master, 48, sender, padbuf, 36, buf, len ); MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len ); mbedtls_md5_free( &md5 ); mbedtls_sha1_free( &sha1 ); mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *ssl, unsigned char *buf, int from ) { int len = 12; const char *sender; unsigned char padbuf[32]; mbedtls_sha256_context sha256; mbedtls_ssl_session *session = ssl->session_negotiate; if( !session ) session = ssl->session; sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "client finished" : "server finished"; mbedtls_sha256_init( &sha256 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha256" ) ); mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 ); /* * TLSv1.2: * hash = PRF( master, finished_label, * Hash( handshake ) )[0.11] */ #if !defined(MBEDTLS_SHA256_ALT) MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha2 state", (unsigned char *) sha256.state, sizeof( sha256.state ) ); #endif mbedtls_sha256_finish_ret( &sha256, padbuf ); mbedtls_sha256_free( &sha256 ); ssl->handshake->tls_prf( session->master, 48, sender, padbuf, 32, buf, len ); MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len ); mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) typedef int (*finish_sha384_t)(mbedtls_sha512_context*, unsigned char*); static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *ssl, unsigned char *buf, int from ) { int len = 12; const char *sender; unsigned char padbuf[48]; mbedtls_sha512_context sha512; mbedtls_ssl_session *session = ssl->session_negotiate; if( !session ) session = ssl->session; sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "client finished" : "server finished"; mbedtls_sha512_init( &sha512 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha384" ) ); mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 ); /* * TLSv1.2: * hash = PRF( master, finished_label, * Hash( handshake ) )[0.11] */ #if !defined(MBEDTLS_SHA512_ALT) MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha512 state", (unsigned char *) sha512.state, sizeof( sha512.state ) ); /* * For SHA-384, we can save 16 bytes by keeping padbuf 48 bytes long. * However, to avoid stringop-overflow warning in gcc, we have to cast * mbedtls_sha512_finish_ret(). */ finish_sha384_t finish = (finish_sha384_t)mbedtls_sha512_finish_ret; finish( &sha512, padbuf ); mbedtls_sha512_free( &sha512 ); #endif ssl->handshake->tls_prf( session->master, 48, sender, padbuf, 48, buf, len ); MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len ); mbedtls_platform_zeroize( padbuf, sizeof( padbuf ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ void mbedtls_ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup: final free" ) ); /* * Free our handshake params */ mbedtls_ssl_handshake_free( ssl ); mbedtls_free( ssl->handshake ); ssl->handshake = NULL; /* * Free the previous transform and swith in the current one */ if( ssl->transform ) { mbedtls_ssl_transform_free( ssl->transform ); mbedtls_free( ssl->transform ); } ssl->transform = ssl->transform_negotiate; ssl->transform_negotiate = NULL; MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup: final free" ) ); } void mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl ) { int resume = ssl->handshake->resume; MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup" ) ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_DONE; ssl->renego_records_seen = 0; } #endif /* * Free the previous session and switch in the current one */ if( ssl->session ) { #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) /* RFC 7366 3.1: keep the EtM state */ ssl->session_negotiate->encrypt_then_mac = ssl->session->encrypt_then_mac; #endif mbedtls_ssl_session_free( ssl->session ); mbedtls_free( ssl->session ); } ssl->session = ssl->session_negotiate; ssl->session_negotiate = NULL; /* * Add cache entry */ if( ssl->conf->f_set_cache != NULL && ssl->session->id_len != 0 && resume == 0 ) { if( ssl->conf->f_set_cache( ssl->conf->p_cache, ssl->session ) != 0 ) MBEDTLS_SSL_DEBUG_MSG( 1, ( "cache did not store session" ) ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake->flight != NULL ) { /* Cancel handshake timer */ mbedtls_ssl_set_timer( ssl, 0 ); /* Keep last flight around in case we need to resend it: * we need the handshake and transform structures for that */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip freeing handshake and transform" ) ); } else #endif mbedtls_ssl_handshake_wrapup_free_hs_transform( ssl ); ssl->state++; MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup" ) ); } int mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl ) { int ret, hash_len; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write finished" ) ); mbedtls_ssl_update_out_pointers( ssl, ssl->transform_negotiate ); ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->conf->endpoint ); /* * RFC 5246 7.4.9 (Page 63) says 12 is the default length and ciphersuites * may define some other value. Currently (early 2016), no defined * ciphersuite does this (and this is unlikely to change as activity has * moved to TLS 1.3 now) so we can keep the hardcoded 12 here. */ hash_len = ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) ? 36 : 12; #if defined(MBEDTLS_SSL_RENEGOTIATION) ssl->verify_data_len = hash_len; memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len ); #endif ssl->out_msglen = 4 + hash_len; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_FINISHED; /* * In case of session resuming, invert the client and server * ChangeCipherSpec messages order. */ if( ssl->handshake->resume != 0 ) { #if defined(MBEDTLS_SSL_CLI_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP; #endif #if defined(MBEDTLS_SSL_SRV_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC; #endif } else ssl->state++; /* * Switch to our negotiated transform and session parameters for outbound * data. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { unsigned char i; /* Remember current epoch settings for resending */ ssl->handshake->alt_transform_out = ssl->transform_out; memcpy( ssl->handshake->alt_out_ctr, ssl->cur_out_ctr, 8 ); /* Set sequence_number to zero */ mbedtls_platform_zeroize( ssl->cur_out_ctr + 2, 6 ); /* Increment epoch */ for( i = 2; i > 0; i-- ) if( ++ssl->cur_out_ctr[i - 1] != 0 ) break; /* The loop goes to its end iff the counter is wrapping */ if( i == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) ); return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); } } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ mbedtls_platform_zeroize( ssl->cur_out_ctr, 8 ); ssl->transform_out = ssl->transform_negotiate; ssl->session_out = ssl->session_negotiate; #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_activate != NULL ) { if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } } #endif #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_send_flight_completed( ssl ); #endif if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret ); return( ret ); } #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write finished" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) #define SSL_MAX_HASH_LEN 36 #else #define SSL_MAX_HASH_LEN 12 #endif int mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned int hash_len; unsigned char buf[SSL_MAX_HASH_LEN]; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse finished" ) ); ssl->handshake->calc_finished( ssl, buf, ssl->conf->endpoint ^ 1 ); if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } /* There is currently no ciphersuite using another length with TLS 1.2 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) hash_len = 36; else #endif hash_len = 12; if( ssl->in_msg[0] != MBEDTLS_SSL_HS_FINISHED || ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + hash_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED ); } if( timingsafe_bcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), buf, hash_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED ); } #if defined(MBEDTLS_SSL_RENEGOTIATION) ssl->verify_data_len = hash_len; memcpy( ssl->peer_verify_data, buf, hash_len ); #endif if( ssl->handshake->resume != 0 ) { #if defined(MBEDTLS_SSL_CLI_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC; #endif #if defined(MBEDTLS_SSL_SRV_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP; #endif } else ssl->state++; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_recv_flight_completed( ssl ); #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse finished" ) ); return( 0 ); } static void ssl_handshake_params_init( mbedtls_ssl_handshake_params *handshake ) { mbedtls_platform_zeroize( handshake, sizeof( mbedtls_ssl_handshake_params ) ); #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) mbedtls_md5_init( &handshake->fin_md5 ); mbedtls_sha1_init( &handshake->fin_sha1 ); mbedtls_md5_starts_ret( &handshake->fin_md5 ); mbedtls_sha1_starts_ret( &handshake->fin_sha1 ); #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) mbedtls_sha256_init( &handshake->fin_sha256 ); mbedtls_sha256_starts_ret( &handshake->fin_sha256, 0 ); #endif #if defined(MBEDTLS_SHA512_C) mbedtls_sha512_init( &handshake->fin_sha512 ); mbedtls_sha512_starts_ret( &handshake->fin_sha512, 1 ); #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ handshake->update_checksum = ssl_update_checksum_start; #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) mbedtls_ssl_sig_hash_set_init( &handshake->hash_algs ); #endif #if defined(MBEDTLS_DHM_C) mbedtls_dhm_init( &handshake->dhm_ctx ); #endif #if defined(MBEDTLS_ECDH_C) mbedtls_ecdh_init( &handshake->ecdh_ctx ); #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) mbedtls_ecjpake_init( &handshake->ecjpake_ctx ); #if defined(MBEDTLS_SSL_CLI_C) handshake->ecjpake_cache = NULL; handshake->ecjpake_cache_len = 0; #endif #endif #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) mbedtls_x509_crt_restart_init( &handshake->ecrs_ctx ); #endif #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET; #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) && \ !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) mbedtls_pk_init( &handshake->peer_pubkey ); #endif } void mbedtls_ssl_transform_init( mbedtls_ssl_transform *transform ) { mbedtls_platform_zeroize( transform, sizeof(mbedtls_ssl_transform) ); mbedtls_cipher_init( &transform->cipher_ctx_enc ); mbedtls_cipher_init( &transform->cipher_ctx_dec ); #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) mbedtls_md_init( &transform->md_ctx_enc ); mbedtls_md_init( &transform->md_ctx_dec ); #endif } /** * \brief Initialize SSL session structure * * \param session SSL session */ void mbedtls_ssl_session_init( mbedtls_ssl_session *session ) { mbedtls_platform_zeroize( session, sizeof(mbedtls_ssl_session) ); } static int ssl_handshake_init( mbedtls_ssl_context *ssl ) { /* Clear old handshake information if present */ ssl->curve = 0; if( ssl->transform_negotiate ) mbedtls_ssl_transform_free( ssl->transform_negotiate ); if( ssl->session_negotiate ) mbedtls_ssl_session_free( ssl->session_negotiate ); if( ssl->handshake ) mbedtls_ssl_handshake_free( ssl ); /* * Either the pointers are now NULL or cleared properly and can be freed. * Now allocate missing structures. */ if( ssl->transform_negotiate == NULL ) { ssl->transform_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_transform) ); } if( ssl->session_negotiate == NULL ) { ssl->session_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_session) ); } if( ssl->handshake == NULL ) { ssl->handshake = mbedtls_calloc( 1, sizeof(mbedtls_ssl_handshake_params) ); } #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) /* If the buffers are too small - reallocate */ handle_buffer_resizing( ssl, 0, MBEDTLS_SSL_IN_BUFFER_LEN, MBEDTLS_SSL_OUT_BUFFER_LEN ); #endif /* All pointers should exist and can be directly freed without issue */ if( ssl->handshake == NULL || ssl->transform_negotiate == NULL || ssl->session_negotiate == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc() of ssl sub-contexts failed" ) ); mbedtls_free( ssl->handshake ); mbedtls_free( ssl->transform_negotiate ); mbedtls_free( ssl->session_negotiate ); ssl->handshake = NULL; ssl->transform_negotiate = NULL; ssl->session_negotiate = NULL; return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } /* Initialize structures */ mbedtls_ssl_session_init( ssl->session_negotiate ); mbedtls_ssl_transform_init( ssl->transform_negotiate ); ssl_handshake_params_init( ssl->handshake ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { ssl->handshake->alt_transform_out = ssl->transform_out; if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING; else ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING; mbedtls_ssl_set_timer( ssl, 0 ); } #endif return( 0 ); } #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) /* Dummy cookie callbacks for defaults */ static int ssl_cookie_write_dummy( void *ctx, unsigned char **p, unsigned char *end, const unsigned char *cli_id, size_t cli_id_len ) { ((void) ctx); ((void) p); ((void) end); ((void) cli_id); ((void) cli_id_len); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } static int ssl_cookie_check_dummy( void *ctx, const unsigned char *cookie, size_t cookie_len, const unsigned char *cli_id, size_t cli_id_len ) { ((void) ctx); ((void) cookie); ((void) cookie_len); ((void) cli_id); ((void) cli_id_len); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */ /** * \brief Initialize an SSL context * Just makes the context ready for mbedtls_ssl_setup() or * mbedtls_ssl_free() * * \param ssl SSL context */ void mbedtls_ssl_init( mbedtls_ssl_context *ssl ) { mbedtls_platform_zeroize( ssl, sizeof( mbedtls_ssl_context ) ); } /** * \brief Set up an SSL context for use * * \note No copy of the configuration context is made, it can be * shared by many mbedtls_ssl_context structures. * * \warning The conf structure will be accessed during the session. * It must not be modified or freed as long as the session * is active. * * \warning This function must be called exactly once per context. * Calling mbedtls_ssl_setup again is not supported, even * if no session is active. * * \param ssl SSL context * \param conf SSL configuration to use * * \return 0 if successful, or MBEDTLS_ERR_SSL_ALLOC_FAILED if * memory allocation failed */ int mbedtls_ssl_setup( mbedtls_ssl_context *ssl, const mbedtls_ssl_config *conf ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN; size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN; ssl->conf = conf; /* * Prepare base structures */ /* Set to NULL in case of an error condition */ ssl->out_buf = NULL; #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) ssl->in_buf_len = in_buf_len; #endif ssl->in_buf = mbedtls_calloc( 1, in_buf_len ); if( ssl->in_buf == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%" MBEDTLS_PRINTF_SIZET " bytes) failed", in_buf_len ) ); ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; goto error; } #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) ssl->out_buf_len = out_buf_len; #endif ssl->out_buf = mbedtls_calloc( 1, out_buf_len ); if( ssl->out_buf == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%" MBEDTLS_PRINTF_SIZET " bytes) failed", out_buf_len ) ); ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; goto error; } mbedtls_ssl_reset_in_out_pointers( ssl ); #if defined(MBEDTLS_SSL_DTLS_SRTP) mbedtls_platform_zeroize( &ssl->dtls_srtp_info, sizeof(ssl->dtls_srtp_info) ); #endif if( ( ret = ssl_handshake_init( ssl ) ) != 0 ) goto error; return( 0 ); error: mbedtls_free( ssl->in_buf ); mbedtls_free( ssl->out_buf ); ssl->conf = NULL; #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) ssl->in_buf_len = 0; ssl->out_buf_len = 0; #endif ssl->in_buf = NULL; ssl->out_buf = NULL; ssl->in_hdr = NULL; ssl->in_ctr = NULL; ssl->in_len = NULL; ssl->in_iv = NULL; ssl->in_msg = NULL; ssl->out_hdr = NULL; ssl->out_ctr = NULL; ssl->out_len = NULL; ssl->out_iv = NULL; ssl->out_msg = NULL; return( ret ); } /* * Reset an initialized and used SSL context for re-use while retaining * all application-set variables, function pointers and data. * * If partial is non-zero, keep data in the input buffer and client ID. * (Use when a DTLS client reconnects from the same port.) */ int mbedtls_ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) size_t in_buf_len = ssl->in_buf_len; size_t out_buf_len = ssl->out_buf_len; #else size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN; size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN; #endif #if !defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) || \ !defined(MBEDTLS_SSL_SRV_C) ((void) partial); #endif ssl->state = MBEDTLS_SSL_HELLO_REQUEST; /* Cancel any possibly running timer */ mbedtls_ssl_set_timer( ssl, 0 ); #if defined(MBEDTLS_SSL_RENEGOTIATION) ssl->renego_status = MBEDTLS_SSL_INITIAL_HANDSHAKE; ssl->renego_records_seen = 0; ssl->verify_data_len = 0; mbedtls_platform_zeroize( ssl->own_verify_data, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN ); mbedtls_platform_zeroize( ssl->peer_verify_data, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN ); #endif ssl->secure_renegotiation = MBEDTLS_SSL_LEGACY_RENEGOTIATION; ssl->in_offt = NULL; mbedtls_ssl_reset_in_out_pointers( ssl ); ssl->in_msgtype = 0; ssl->in_msglen = 0; #if defined(MBEDTLS_SSL_PROTO_DTLS) ssl->next_record_offset = 0; ssl->in_epoch = 0; #endif #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) mbedtls_ssl_dtls_replay_reset( ssl ); #endif ssl->in_hslen = 0; ssl->nb_zero = 0; ssl->keep_current_message = 0; ssl->out_msgtype = 0; ssl->out_msglen = 0; ssl->out_left = 0; #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) if( ssl->split_done != MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED ) ssl->split_done = 0; #endif mbedtls_platform_zeroize( ssl->cur_out_ctr, sizeof( ssl->cur_out_ctr ) ); ssl->transform_in = NULL; ssl->transform_out = NULL; ssl->session_in = NULL; ssl->session_out = NULL; mbedtls_platform_zeroize( ssl->out_buf, out_buf_len ); #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C) if( partial == 0 ) #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */ { ssl->in_left = 0; mbedtls_platform_zeroize( ssl->in_buf, in_buf_len ); } #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_reset != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_reset()" ) ); if( ( ret = mbedtls_ssl_hw_record_reset( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_reset", ret ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } } #endif if( ssl->transform ) { mbedtls_ssl_transform_free( ssl->transform ); mbedtls_free( ssl->transform ); ssl->transform = NULL; } if( ssl->session ) { mbedtls_ssl_session_free( ssl->session ); mbedtls_free( ssl->session ); ssl->session = NULL; } #if defined(MBEDTLS_SSL_ALPN) ssl->alpn_chosen = NULL; #endif #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) if( partial == 0 ) #endif { mbedtls_free( ssl->cli_id ); ssl->cli_id = NULL; ssl->cli_id_len = 0; } #endif if( ( ret = ssl_handshake_init( ssl ) ) != 0 ) return( ret ); return( 0 ); } /** * \brief Reset an already initialized SSL context for re-use * while retaining application-set variables, function * pointers and data. * * \param ssl SSL context * \return 0 if successful, or MBEDTLS_ERR_SSL_ALLOC_FAILED, MBEDTLS_ERR_SSL_HW_ACCEL_FAILED or * MBEDTLS_ERR_SSL_COMPRESSION_FAILED */ int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl ) { return( mbedtls_ssl_session_reset_int( ssl, 0 ) ); } /** * \brief Set the current endpoint type * * \param conf SSL configuration * \param endpoint must be MBEDTLS_SSL_IS_CLIENT or MBEDTLS_SSL_IS_SERVER */ void mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint ) { conf->endpoint = endpoint; } /** * \brief Set the transport type (TLS or DTLS). * Default: TLS * * \note For DTLS, you must either provide a recv callback that * doesn't block, or one that handles timeouts, see * \c mbedtls_ssl_set_bio(). You also need to provide timer * callbacks with \c mbedtls_ssl_set_timer_cb(). * * \param conf SSL configuration * \param transport transport type: * MBEDTLS_SSL_TRANSPORT_STREAM for TLS, * MBEDTLS_SSL_TRANSPORT_DATAGRAM for DTLS. */ void mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport ) { conf->transport = transport; } #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) /** * \brief Enable or disable anti-replay protection for DTLS. * (DTLS only, no effect on TLS.) * Default: enabled. * * \param conf SSL configuration * \param mode MBEDTLS_SSL_ANTI_REPLAY_ENABLED or MBEDTLS_SSL_ANTI_REPLAY_DISABLED. * * \warning Disabling this is a security risk unless the application * protocol handles duplicated packets in a safe way. You * should not disable this without careful consideration. * However, if your application already detects duplicated * packets and needs information about them to adjust its * transmission strategy, then you'll want to disable this. */ void mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode ) { conf->anti_replay = mode; } #endif #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) /** * \brief Set a limit on the number of records with a bad MAC * before terminating the connection. * (DTLS only, no effect on TLS.) * Default: 0 (disabled). * * \param conf SSL configuration * \param limit Limit, or 0 to disable. * * \note If the limit is N, then the connection is terminated when * the Nth non-authentic record is seen. * * \note Records with an invalid header are not counted, only the * ones going through the authentication-decryption phase. * * \note This is a security trade-off related to the fact that it's * often relatively easy for an active attacker ot inject UDP * datagrams. On one hand, setting a low limit here makes it * easier for such an attacker to forcibly terminated a * connection. On the other hand, a high limit or no limit * might make us waste resources checking authentication on * many bogus packets. */ void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit ) { conf->badmac_limit = limit; } #endif #if defined(MBEDTLS_SSL_PROTO_DTLS) /** * \brief Allow or disallow packing of multiple handshake records * within a single datagram. * * \param ssl The SSL context to configure. * \param allow_packing This determines whether datagram packing may * be used or not. A value of \c 0 means that every * record will be sent in a separate datagram; a * value of \c 1 means that, if space permits, * multiple handshake messages (including CCS) belonging to * a single flight may be packed within a single datagram. * * \note This is enabled by default and should only be disabled * for test purposes, or if datagram packing causes * interoperability issues with peers that don't support it. * * \note Allowing datagram packing reduces the network load since * there's less overhead if multiple messages share the same * datagram. Also, it increases the handshake efficiency * since messages belonging to a single datagram will not * be reordered in transit, and so future message buffering * or flight retransmission (if no buffering is used) as * means to deal with reordering are needed less frequently. * * \note Application records are not affected by this option and * are currently always sent in separate datagrams. * */ void mbedtls_ssl_set_datagram_packing( mbedtls_ssl_context *ssl, unsigned allow_packing ) { ssl->disable_datagram_packing = !allow_packing; } /** * \brief Set retransmit timeout values for the DTLS handshake. * (DTLS only, no effect on TLS.) * * \param conf SSL configuration * \param min Initial timeout value in milliseconds. * Default: 1000 (1 second). * \param max Maximum timeout value in milliseconds. * Default: 60000 (60 seconds). * * \note Default values are from RFC 6347 section 4.2.4.1. * * \note The 'min' value should typically be slightly above the * expected round-trip time to your peer, plus whatever time * it takes for the peer to process the message. For example, * if your RTT is about 600ms and you peer needs up to 1s to * do the cryptographic operations in the handshake, then you * should set 'min' slightly above 1600. Lower values of 'min' * might cause spurious resends which waste network resources, * while larger value of 'min' will increase overall latency * on unreliable network links. * * \note The more unreliable your network connection is, the larger * your max / min ratio needs to be in order to achieve * reliable handshakes. * * \note Messages are retransmitted up to log2(ceil(max/min)) times. * For example, if min = 1s and max = 5s, the retransmit plan * goes: send ... 1s -> resend ... 2s -> resend ... 4s -> * resend ... 5s -> give up and return a timeout error. */ void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf, uint32_t min, uint32_t max ) { conf->hs_timeout_min = min; conf->hs_timeout_max = max; } #endif /* MBEDTLS_SSL_PROTO_DTLS */ /** * \brief Set the certificate verification mode * Default: NONE on server, REQUIRED on client * * \param conf SSL configuration * \param authmode can be: * * MBEDTLS_SSL_VERIFY_NONE: peer certificate is not checked * (default on server) * (insecure on client) * * MBEDTLS_SSL_VERIFY_OPTIONAL: peer certificate is checked, however the * handshake continues even if verification failed; * mbedtls_ssl_get_verify_result() can be called after the * handshake is complete. * * MBEDTLS_SSL_VERIFY_REQUIRED: peer *must* present a valid certificate, * handshake is aborted if verification failed. * (default on client) * * \note On client, MBEDTLS_SSL_VERIFY_REQUIRED is the recommended mode. * With MBEDTLS_SSL_VERIFY_OPTIONAL, the user needs to call mbedtls_ssl_get_verify_result() at * the right time(s), which may not be obvious, while REQUIRED always perform * the verification as soon as possible. For example, REQUIRED was protecting * against the "triple handshake" attack even before it was found. */ void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode ) { conf->authmode = authmode; } #if defined(MBEDTLS_X509_CRT_PARSE_C) /** * \brief Set the verification callback (Optional). * * If set, the provided verify callback is called for each * certificate in the peer's CRT chain, including the trusted * root. For more information, please see the documentation of * \c mbedtls_x509_crt_verify(). * * \note For per context callbacks and contexts, please use * mbedtls_ssl_set_verify() instead. * * \param conf The SSL configuration to use. * \param f_vrfy The verification callback to use during CRT verification. * \param p_vrfy The opaque context to be passed to the callback. */ void mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { conf->f_vrfy = f_vrfy; conf->p_vrfy = p_vrfy; } #endif /* MBEDTLS_X509_CRT_PARSE_C */ /** * \brief Set the random number generator callback * * \param conf SSL configuration * \param f_rng RNG function * \param p_rng RNG parameter */ void mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { conf->f_rng = f_rng; conf->p_rng = p_rng; } /** * \brief Set the debug callback * * The callback has the following argument: * void * opaque context for the callback * int debug level * const char * file name * int line number * const char * message * * \param conf SSL configuration * \param f_dbg debug function * \param p_dbg debug parameter */ void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf, void (*f_dbg)(void *, int, const char *, int, const char *), void *p_dbg ) { conf->f_dbg = f_dbg; conf->p_dbg = p_dbg; } /** * \brief Set the underlying BIO callbacks for write, read and * read-with-timeout. * * \param ssl SSL context * \param p_bio parameter (context) shared by BIO callbacks * \param f_send write callback * \param f_recv read callback * \param f_recv_timeout blocking read callback with timeout. * * \note One of f_recv or f_recv_timeout can be NULL, in which case * the other is used. If both are non-NULL, f_recv_timeout is * used and f_recv is ignored (as if it were NULL). * * \note The two most common use cases are: * - non-blocking I/O, f_recv != NULL, f_recv_timeout == NULL * - blocking I/O, f_recv == NULL, f_recv_timout != NULL * * \note For DTLS, you need to provide either a non-NULL * f_recv_timeout callback, or a f_recv that doesn't block. * * \note See the documentations of \c mbedtls_ssl_send_t, * \c mbedtls_ssl_recv_t and \c mbedtls_ssl_recv_timeout_t for * the conventions those callbacks must follow. * * \note On some platforms, net_sockets.c provides * \c mbedtls_net_send(), \c mbedtls_net_recv() and * \c mbedtls_net_recv_timeout() that are suitable to be used * here. */ void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl, void *p_bio, mbedtls_ssl_send_t *f_send, mbedtls_ssl_recv_t *f_recv, mbedtls_ssl_recv_timeout_t *f_recv_timeout ) { ssl->p_bio = p_bio; ssl->f_send = f_send; ssl->f_recv = f_recv; ssl->f_recv_timeout = f_recv_timeout; } #if defined(MBEDTLS_SSL_PROTO_DTLS) /** * \brief Set the Maximum Tranport Unit (MTU). * Special value: 0 means unset (no limit). * This represents the maximum size of a datagram payload * handled by the transport layer (usually UDP) as determined * by the network link and stack. In practice, this controls * the maximum size datagram the DTLS layer will pass to the * \c f_send() callback set using \c mbedtls_ssl_set_bio(). * * \note The limit on datagram size is converted to a limit on * record payload by subtracting the current overhead of * encapsulation and encryption/authentication if any. * * \note This can be called at any point during the connection, for * example when a Path Maximum Transfer Unit (PMTU) * estimate becomes available from other sources, * such as lower (or higher) protocol layers. * * \note This setting only controls the size of the packets we send, * and does not restrict the size of the datagrams we're * willing to receive. Client-side, you can request the * server to use smaller records with \c * mbedtls_ssl_conf_max_frag_len(). * * \note If both a MTU and a maximum fragment length have been * configured (or negotiated with the peer), the resulting * lower limit on record payload (see first note) is used. * * \note This can only be used to decrease the maximum size * of datagrams (hence records, see first note) sent. It * cannot be used to increase the maximum size of records over * the limit set by #MBEDTLS_SSL_OUT_CONTENT_LEN. * * \note Values lower than the current record layer expansion will * result in an error when trying to send data. * * \note Using record compression together with a non-zero MTU value * will result in an error when trying to send data. * * \param ssl SSL context * \param mtu Value of the path MTU in bytes */ void mbedtls_ssl_set_mtu( mbedtls_ssl_context *ssl, uint16_t mtu ) { ssl->mtu = mtu; } #endif /** * \brief Set the timeout period for mbedtls_ssl_read() * (Default: no timeout.) * * \param conf SSL configuration context * \param timeout Timeout value in milliseconds. * Use 0 for no timeout (default). * * \note With blocking I/O, this will only work if a non-NULL * \c f_recv_timeout was set with \c mbedtls_ssl_set_bio(). * With non-blocking I/O, this will only work if timer * callbacks were set with \c mbedtls_ssl_set_timer_cb(). * * \note With non-blocking I/O, you may also skip this function * altogether and handle timeouts at the application layer. */ void mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout ) { conf->read_timeout = timeout; } /** * \brief Set the timer callbacks (Mandatory for DTLS.) * * \param ssl SSL context * \param p_timer parameter (context) shared by timer callbacks * \param f_set_timer set timer callback * \param f_get_timer get timer callback. Must return: * * \note See the documentation of \c mbedtls_ssl_set_timer_t and * \c mbedtls_ssl_get_timer_t for the conventions this pair of * callbacks must follow. * * \note On some platforms, timing.c provides * \c mbedtls_timing_set_delay() and * \c mbedtls_timing_get_delay() that are suitable for using * here, except if using an event-driven style. * * \note See also the "DTLS tutorial" article in our knowledge base. * https://tls.mbed.org/kb/how-to/dtls-tutorial */ void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl, void *p_timer, mbedtls_ssl_set_timer_t *f_set_timer, mbedtls_ssl_get_timer_t *f_get_timer ) { ssl->p_timer = p_timer; ssl->f_set_timer = f_set_timer; ssl->f_get_timer = f_get_timer; /* Make sure we start with no timer running */ mbedtls_ssl_set_timer( ssl, 0 ); } #if defined(MBEDTLS_SSL_SRV_C) /** * \brief Set the session cache callbacks (server-side only) * If not set, no session resuming is done (except if session * tickets are enabled too). * * The session cache has the responsibility to check for stale * entries based on timeout. See RFC 5246 for recommendations. * * Warning: session.peer_cert is cleared by the SSL/TLS layer on * connection shutdown, so do not cache the pointer! Either set * it to NULL or make a full copy of the certificate. * * The get callback is called once during the initial handshake * to enable session resuming. The get function has the * following parameters: (void *parameter, mbedtls_ssl_session *session) * If a valid entry is found, it should fill the master of * the session object with the cached values and return 0, * return 1 otherwise. Optionally peer_cert can be set as well * if it is properly present in cache entry. * * The set callback is called once during the initial handshake * to enable session resuming after the entire handshake has * been finished. The set function has the following parameters: * (void *parameter, const mbedtls_ssl_session *session). The function * should create a cache entry for future retrieval based on * the data in the session structure and should keep in mind * that the mbedtls_ssl_session object presented (and all its referenced * data) is cleared by the SSL/TLS layer when the connection is * terminated. It is recommended to add metadata to determine if * an entry is still valid in the future. Return 0 if * successfully cached, return 1 otherwise. * * \param conf SSL configuration * \param p_cache parmater (context) for both callbacks * \param f_get_cache session get callback * \param f_set_cache session set callback */ void mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf, void *p_cache, int (*f_get_cache)(void *, mbedtls_ssl_session *), int (*f_set_cache)(void *, const mbedtls_ssl_session *) ) { conf->p_cache = p_cache; conf->f_get_cache = f_get_cache; conf->f_set_cache = f_set_cache; } #endif /* MBEDTLS_SSL_SRV_C */ #if defined(MBEDTLS_SSL_CLI_C) /** * \brief Request resumption of session (client-side only) * Session data is copied from presented session structure. * * \param ssl SSL context * \param session session context * * \return 0 if successful, * MBEDTLS_ERR_SSL_ALLOC_FAILED if memory allocation failed, * MBEDTLS_ERR_SSL_BAD_INPUT_DATA if used server-side or * arguments are otherwise invalid * * \sa mbedtls_ssl_get_session() */ int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( ssl == NULL || session == NULL || ssl->session_negotiate == NULL || ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } if( ( ret = mbedtls_ssl_session_copy( ssl->session_negotiate, session ) ) != 0 ) return( ret ); ssl->handshake->resume = 1; return( 0 ); } #endif /* MBEDTLS_SSL_CLI_C */ /** * \brief Set the list of allowed ciphersuites and the preference * order. First in the list has the highest preference. * (Overrides all version-specific lists) * * The ciphersuites array is not copied, and must remain * valid for the lifetime of the ssl_config. * * Note: The server uses its own preferences * over the preference of the client unless * MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE is defined! * * \param conf SSL configuration * \param ciphersuites 0-terminated list of allowed ciphersuites */ void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf, const uint16_t *ciphersuites ) { conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = ciphersuites; conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = ciphersuites; conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = ciphersuites; conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = ciphersuites; } /** * \brief Set the list of allowed ciphersuites and the * preference order for a specific version of the protocol. * (Only useful on the server side) * * The ciphersuites array is not copied, and must remain * valid for the lifetime of the ssl_config. * * \param conf SSL configuration * \param ciphersuites 0-terminated list of allowed ciphersuites * \param major Major version number (only MBEDTLS_SSL_MAJOR_VERSION_3 * supported) * \param minor Minor version number (MBEDTLS_SSL_MINOR_VERSION_0, * MBEDTLS_SSL_MINOR_VERSION_1 and MBEDTLS_SSL_MINOR_VERSION_2, * MBEDTLS_SSL_MINOR_VERSION_3 supported) * * \note With DTLS, use MBEDTLS_SSL_MINOR_VERSION_2 for DTLS 1.0 * and MBEDTLS_SSL_MINOR_VERSION_3 for DTLS 1.2 */ void mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf, const uint16_t *ciphersuites, int major, int minor ) { if( major != MBEDTLS_SSL_MAJOR_VERSION_3 ) return; if( minor < MBEDTLS_SSL_MINOR_VERSION_0 || minor > MBEDTLS_SSL_MINOR_VERSION_3 ) return; conf->ciphersuite_list[minor] = ciphersuites; } #if defined(MBEDTLS_X509_CRT_PARSE_C) /** * \brief Set the X.509 security profile used for verification * * \note The restrictions are enforced for all certificates in the * chain. However, signatures in the handshake are not covered * by this setting but by \b mbedtls_ssl_conf_sig_hashes(). * * \param conf SSL configuration * \param profile Profile to use */ void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf, const mbedtls_x509_crt_profile *profile ) { conf->cert_profile = profile; } /* Append a new keycert entry to a (possibly empty) list */ static int ssl_append_key_cert( mbedtls_ssl_key_cert **head, mbedtls_x509_crt *cert, mbedtls_pk_context *key ) { mbedtls_ssl_key_cert *new_cert; new_cert = mbedtls_calloc( 1, sizeof( mbedtls_ssl_key_cert ) ); if( new_cert == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); new_cert->cert = cert; new_cert->key = key; new_cert->next = NULL; /* Update head is the list was null, else add to the end */ if( *head == NULL ) { *head = new_cert; } else { mbedtls_ssl_key_cert *cur = *head; while( cur->next != NULL ) cur = cur->next; cur->next = new_cert; } return( 0 ); } /** * \brief Set own certificate chain and private key * * \note own_cert should contain in order from the bottom up your * certificate chain. The top certificate (self-signed) * can be omitted. * * \note On server, this function can be called multiple times to * provision more than one cert/key pair (eg one ECDSA, one * RSA with SHA-256, one RSA with SHA-1). An adequate * certificate will be selected according to the client's * advertised capabilities. In case multiple certificates are * adequate, preference is given to the one set by the first * call to this function, then second, etc. * * \note On client, only the first call has any effect. That is, * only one client certificate can be provisioned. The * server's preferences in its CertficateRequest message will * be ignored and our only cert will be sent regardless of * whether it matches those preferences - the server can then * decide what it wants to do with it. * * \note The provided \p pk_key needs to match the public key in the * first certificate in \p own_cert, or all handshakes using * that certificate will fail. It is your responsibility * to ensure that; this function will not perform any check. * You may use mbedtls_pk_check_pair() in order to perform * this check yourself, but be aware that this function can * be computationally expensive on some key types. * * \param conf SSL configuration * \param own_cert own public certificate chain * \param pk_key own private key * * \return 0 on success or MBEDTLS_ERR_SSL_ALLOC_FAILED */ int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf, mbedtls_x509_crt *own_cert, mbedtls_pk_context *pk_key ) { return( ssl_append_key_cert( &conf->key_cert, own_cert, pk_key ) ); } /** * \brief Set the data required to verify peer certificate * * \note See \c mbedtls_x509_crt_verify() for notes regarding the * parameters ca_chain (maps to trust_ca for that function) * and ca_crl. * * \param conf SSL configuration * \param ca_chain trusted CA chain (meaning all fully trusted top-level CAs) * \param ca_crl trusted CA CRLs */ void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf, mbedtls_x509_crt *ca_chain, mbedtls_x509_crl *ca_crl ) { conf->ca_chain = ca_chain; conf->ca_crl = ca_crl; #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK) /* mbedtls_ssl_conf_ca_chain() and mbedtls_ssl_conf_ca_cb() * cannot be used together. */ conf->f_ca_cb = NULL; conf->p_ca_cb = NULL; #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */ } #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK) /** * \brief Set the trusted certificate callback. * * This API allows to register the set of trusted certificates * through a callback, instead of a linked list as configured * by mbedtls_ssl_conf_ca_chain(). * * This is useful for example in contexts where a large number * of CAs are used, and the inefficiency of maintaining them * in a linked list cannot be tolerated. It is also useful when * the set of trusted CAs needs to be modified frequently. * * See the documentation of `mbedtls_x509_crt_ca_cb_t` for * more information. * * \param conf The SSL configuration to register the callback with. * \param f_ca_cb The trusted certificate callback to use when verifying * certificate chains. * \param p_ca_cb The context to be passed to \p f_ca_cb (for example, * a reference to a trusted CA database). * * \note This API is incompatible with mbedtls_ssl_conf_ca_chain(): * Any call to this function overwrites the values set through * earlier calls to mbedtls_ssl_conf_ca_chain() or * mbedtls_ssl_conf_ca_cb(). * * \note This API is incompatible with CA indication in * CertificateRequest messages: A server-side SSL context which * is bound to an SSL configuration that uses a CA callback * configured via mbedtls_ssl_conf_ca_cb(), and which requires * client authentication, will send an empty CA list in the * corresponding CertificateRequest message. * * \note This API is incompatible with mbedtls_ssl_set_hs_ca_chain(): * If an SSL context is bound to an SSL configuration which uses * CA callbacks configured via mbedtls_ssl_conf_ca_cb(), then * calls to mbedtls_ssl_set_hs_ca_chain() have no effect. * * \note The use of this API disables the use of restartable ECC * during X.509 CRT signature verification (but doesn't affect * other uses). * * \warning This API is incompatible with the use of CRLs. Any call to * mbedtls_ssl_conf_ca_cb() unsets CRLs configured through * earlier calls to mbedtls_ssl_conf_ca_chain(). * * \warning In multi-threaded environments, the callback \p f_ca_cb * must be thread-safe, and it is the user's responsibility * to guarantee this (for example through a mutex * contained in the callback context pointed to by \p p_ca_cb). */ void mbedtls_ssl_conf_ca_cb( mbedtls_ssl_config *conf, mbedtls_x509_crt_ca_cb_t f_ca_cb, void *p_ca_cb ) { conf->f_ca_cb = f_ca_cb; conf->p_ca_cb = p_ca_cb; /* mbedtls_ssl_conf_ca_chain() and mbedtls_ssl_conf_ca_cb() * cannot be used together. */ conf->ca_chain = NULL; conf->ca_crl = NULL; } #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) /** * \brief Set own certificate and key for the current handshake * * \note Same as \c mbedtls_ssl_conf_own_cert() but for use within * the SNI callback. * * \param ssl SSL context * \param own_cert own public certificate chain * \param pk_key own private key * * \return 0 on success or MBEDTLS_ERR_SSL_ALLOC_FAILED */ int mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl, mbedtls_x509_crt *own_cert, mbedtls_pk_context *pk_key ) { return( ssl_append_key_cert( &ssl->handshake->sni_key_cert, own_cert, pk_key ) ); } /** * \brief Set the data required to verify peer certificate for the * current handshake * * \note Same as \c mbedtls_ssl_conf_ca_chain() but for use within * the SNI callback. * * \param ssl SSL context * \param ca_chain trusted CA chain (meaning all fully trusted top-level CAs) * \param ca_crl trusted CA CRLs */ void mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl, mbedtls_x509_crt *ca_chain, mbedtls_x509_crl *ca_crl ) { ssl->handshake->sni_ca_chain = ca_chain; ssl->handshake->sni_ca_crl = ca_crl; } /** * \brief Set authmode for the current handshake. * * \note Same as \c mbedtls_ssl_conf_authmode() but for use within * the SNI callback. * * \param ssl SSL context * \param authmode MBEDTLS_SSL_VERIFY_NONE, MBEDTLS_SSL_VERIFY_OPTIONAL or * MBEDTLS_SSL_VERIFY_REQUIRED */ void mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl, int authmode ) { ssl->handshake->sni_authmode = authmode; } #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_X509_CRT_PARSE_C) /** * \brief Set a connection-specific verification callback (optional). * * If set, the provided verify callback is called for each * certificate in the peer's CRT chain, including the trusted * root. For more information, please see the documentation of * \c mbedtls_x509_crt_verify(). * * \note This call is analogous to mbedtls_ssl_conf_verify() but * binds the verification callback and context to an SSL context * as opposed to an SSL configuration. * If mbedtls_ssl_conf_verify() and mbedtls_ssl_set_verify() * are both used, mbedtls_ssl_set_verify() takes precedence. * * \param ssl The SSL context to use. * \param f_vrfy The verification callback to use during CRT verification. * \param p_vrfy The opaque context to be passed to the callback. */ void mbedtls_ssl_set_verify( mbedtls_ssl_context *ssl, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { ssl->f_vrfy = f_vrfy; ssl->p_vrfy = p_vrfy; } #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) /** * \brief Set the EC J-PAKE password for current handshake. * * \note An internal copy is made, and destroyed as soon as the * handshake is completed, or when the SSL context is reset or * freed. * * \note The SSL context needs to be already set up. The right place * to call this function is between \c mbedtls_ssl_setup() or * \c mbedtls_ssl_reset() and \c mbedtls_ssl_handshake(). * * \param ssl SSL context * \param pw EC J-PAKE password (pre-shared secret) * \param pw_len length of pw in bytes * * \return 0 on success, or a negative error code. */ int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl, const unsigned char *pw, size_t pw_len ) { mbedtls_ecjpake_role role; if( ssl->handshake == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) role = MBEDTLS_ECJPAKE_SERVER; else role = MBEDTLS_ECJPAKE_CLIENT; return( mbedtls_ecjpake_setup( &ssl->handshake->ecjpake_ctx, role, MBEDTLS_MD_SHA256, MBEDTLS_ECP_DP_SECP256R1, pw, pw_len ) ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) static void ssl_conf_remove_psk( mbedtls_ssl_config *conf ) { /* Remove reference to existing PSK, if any. */ if( conf->psk != NULL ) { mbedtls_platform_zeroize( conf->psk, conf->psk_len ); mbedtls_free( conf->psk ); conf->psk = NULL; conf->psk_len = 0; } /* Remove reference to PSK identity, if any. */ if( conf->psk_identity != NULL ) { mbedtls_free( conf->psk_identity ); conf->psk_identity = NULL; conf->psk_identity_len = 0; } } /* This function assumes that PSK identity in the SSL config is unset. * It checks that the provided identity is well-formed and attempts * to make a copy of it in the SSL config. * On failure, the PSK identity in the config remains unset. */ static int ssl_conf_set_psk_identity( mbedtls_ssl_config *conf, unsigned char const *psk_identity, size_t psk_identity_len ) { /* Identity len will be encoded on two bytes */ if( psk_identity == NULL || ( psk_identity_len >> 16 ) != 0 || psk_identity_len > MBEDTLS_SSL_OUT_CONTENT_LEN ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } conf->psk_identity = mbedtls_calloc( 1, psk_identity_len ); if( conf->psk_identity == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); conf->psk_identity_len = psk_identity_len; memcpy( conf->psk_identity, psk_identity, conf->psk_identity_len ); return( 0 ); } /** * \brief Configure a pre-shared key (PSK) and identity * to be used in PSK-based ciphersuites. * * \note This is mainly useful for clients. Servers will usually * want to use \c mbedtls_ssl_conf_psk_cb() instead. * * \note A PSK set by \c mbedtls_ssl_set_hs_psk() in the PSK callback * takes precedence over a PSK configured by this function. * * \warning Currently, clients can only register a single pre-shared key. * Calling this function or mbedtls_ssl_conf_psk_opaque() more * than once will overwrite values configured in previous calls. * Support for setting multiple PSKs on clients and selecting * one based on the identity hint is not a planned feature, * but feedback is welcomed. * * \param conf The SSL configuration to register the PSK with. * \param psk The pointer to the pre-shared key to use. * \param psk_len The length of the pre-shared key in bytes. * \param psk_identity The pointer to the pre-shared key identity. * \param psk_identity_len The length of the pre-shared key identity * in bytes. * * \note The PSK and its identity are copied internally and * hence need not be preserved by the caller for the lifetime * of the SSL configuration. * * \return \c 0 if successful. * \return An \c MBEDTLS_ERR_SSL_XXX error code on failure. */ int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf, const void *psk, size_t psk_len, const void *psk_identity, size_t psk_identity_len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; /* Remove opaque/raw PSK + PSK Identity */ ssl_conf_remove_psk( conf ); /* Check and set raw PSK */ if( psk == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( psk_len == 0 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( psk_len > MBEDTLS_PSK_MAX_LEN ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( ( conf->psk = mbedtls_calloc( 1, psk_len ) ) == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); conf->psk_len = psk_len; memcpy( conf->psk, psk, conf->psk_len ); /* Check and set PSK Identity */ ret = ssl_conf_set_psk_identity( conf, psk_identity, psk_identity_len ); if( ret != 0 ) ssl_conf_remove_psk( conf ); return( ret ); } static void ssl_remove_psk( mbedtls_ssl_context *ssl ) { if( ssl->handshake->psk != NULL ) { mbedtls_platform_zeroize( ssl->handshake->psk, ssl->handshake->psk_len ); mbedtls_free( ssl->handshake->psk ); ssl->handshake->psk_len = 0; } } /** * \brief Set the pre-shared Key (PSK) for the current handshake. * * \note This should only be called inside the PSK callback, * i.e. the function passed to \c mbedtls_ssl_conf_psk_cb(). * * \note A PSK set by this function takes precedence over a PSK * configured by \c mbedtls_ssl_conf_psk(). * * \param ssl The SSL context to configure a PSK for. * \param psk The pointer to the pre-shared key. * \param psk_len The length of the pre-shared key in bytes. * * \return \c 0 if successful. * \return An \c MBEDTLS_ERR_SSL_XXX error code on failure. */ int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl, const void *psk, size_t psk_len ) { if( psk == NULL || ssl->handshake == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( psk_len > MBEDTLS_PSK_MAX_LEN ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl_remove_psk( ssl ); if( ( ssl->handshake->psk = mbedtls_calloc( 1, psk_len ) ) == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); ssl->handshake->psk_len = psk_len; memcpy( ssl->handshake->psk, psk, ssl->handshake->psk_len ); return( 0 ); } /** * \brief Set the PSK callback (server-side only). * * If set, the PSK callback is called for each * handshake where a PSK-based ciphersuite was negotiated. * The caller provides the identity received and wants to * receive the actual PSK data and length. * * The callback has the following parameters: * - \c void*: The opaque pointer \p p_psk. * - \c mbedtls_ssl_context*: The SSL context to which * the operation applies. * - \c const unsigned char*: The PSK identity * selected by the client. * - \c size_t: The length of the PSK identity * selected by the client. * * If a valid PSK identity is found, the callback should use * \c mbedtls_ssl_set_hs_psk() or * \c mbedtls_ssl_set_hs_psk_opaque() * on the SSL context to set the correct PSK and return \c 0. * Any other return value will result in a denied PSK identity. * * \note A dynamic PSK (i.e. set by the PSK callback) takes * precedence over a static PSK (i.e. set by * \c mbedtls_ssl_conf_psk() or * \c mbedtls_ssl_conf_psk_opaque()). * This means that if you set a PSK callback using this * function, you don't need to set a PSK using * \c mbedtls_ssl_conf_psk() or * \c mbedtls_ssl_conf_psk_opaque()). * * \param conf The SSL configuration to register the callback with. * \param f_psk The callback for selecting and setting the PSK based * in the PSK identity chosen by the client. * \param p_psk A pointer to an opaque structure to be passed to * the callback, for example a PSK store. */ void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf, int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *, size_t), void *p_psk ) { conf->f_psk = f_psk; conf->p_psk = p_psk; } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C) /** * \brief Set the Diffie-Hellman public P and G values * from big-endian binary presentations. * (Default values: MBEDTLS_DHM_RFC3526_MODP_2048_[PG]_BIN) * * \param conf SSL configuration * \param dhm_P Diffie-Hellman-Merkle modulus in big-endian binary form * \param P_len Length of DHM modulus * \param dhm_G Diffie-Hellman-Merkle generator in big-endian binary form * \param G_len Length of DHM generator * * \return 0 if successful */ int mbedtls_ssl_conf_dh_param_bin( mbedtls_ssl_config *conf, const unsigned char *dhm_P, size_t P_len, const unsigned char *dhm_G, size_t G_len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( ( ret = mbedtls_mpi_read_binary( &conf->dhm_P, dhm_P, P_len ) ) != 0 || ( ret = mbedtls_mpi_read_binary( &conf->dhm_G, dhm_G, G_len ) ) != 0 ) { mbedtls_mpi_free( &conf->dhm_P ); mbedtls_mpi_free( &conf->dhm_G ); return( ret ); } return( 0 ); } /** * \brief Set the Diffie-Hellman public P and G values, * read from existing context (server-side only) * * \param conf SSL configuration * \param dhm_ctx Diffie-Hellman-Merkle context * * \return 0 if successful */ int mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( ( ret = mbedtls_mpi_copy( &conf->dhm_P, &dhm_ctx->P ) ) != 0 || ( ret = mbedtls_mpi_copy( &conf->dhm_G, &dhm_ctx->G ) ) != 0 ) { mbedtls_mpi_free( &conf->dhm_P ); mbedtls_mpi_free( &conf->dhm_G ); return( ret ); } return( 0 ); } #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_SRV_C */ #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C) /** * \brief Set the minimum length for Diffie-Hellman parameters. * (Client-side only.) * (Default: 1024 bits.) * * \param conf SSL configuration * \param bitlen Minimum bit length of the DHM prime */ void mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf, unsigned int bitlen ) { conf->dhm_min_bitlen = bitlen; } #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */ #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /** * \brief Set the allowed hashes for signatures during the handshake. * (Default: all available hashes except MD5.) * * \note This only affects which hashes are offered and can be used * for signatures during the handshake. Hashes for message * authentication and the TLS PRF are controlled by the * ciphersuite, see \c mbedtls_ssl_conf_ciphersuites(). Hashes * used for certificate signature are controlled by the * verification profile, see \c mbedtls_ssl_conf_cert_profile(). * * \note This list should be ordered by decreasing preference * (preferred hash first). * * \param conf SSL configuration * \param hashes Ordered list of allowed signature hashes, * terminated by \c MBEDTLS_MD_NONE. */ void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf, const uint8_t *hashes ) { conf->sig_hashes = hashes; } #endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ #if defined(MBEDTLS_ECP_C) /** * \brief Set the allowed curves in order of preference. * (Default: all defined curves.) * * On server: this only affects selection of the ECDHE curve; * the curves used for ECDH and ECDSA are determined by the * list of available certificates instead. * * On client: this affects the list of curves offered for any * use. The server can override our preference order. * * Both sides: limits the set of curves accepted for use in * ECDHE and in the peer's end-entity certificate. * * \note This has no influence on which curves are allowed inside the * certificate chains, see \c mbedtls_ssl_conf_cert_profile() * for that. For the end-entity certificate however, the key * will be accepted only if it is allowed both by this list * and by the cert profile. * * \note This list should be ordered by decreasing preference * (preferred curve first). * * \param conf SSL configuration * \param curves Ordered list of allowed curves, * terminated by MBEDTLS_ECP_DP_NONE. */ void mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf, const mbedtls_ecp_group_id *curve_list ) { conf->curve_list = curve_list; } #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_X509_CRT_PARSE_C) /** * \brief Set or reset the hostname to check against the received * server certificate. It sets the ServerName TLS extension, * too, if that extension is enabled. (client-side only) * * \param ssl SSL context * \param hostname the server hostname, may be NULL to clear hostname * * \note Maximum hostname length MBEDTLS_SSL_MAX_HOST_NAME_LEN. * * \return 0 if successful, MBEDTLS_ERR_SSL_ALLOC_FAILED on * allocation failure, MBEDTLS_ERR_SSL_BAD_INPUT_DATA on * too long input hostname. * * Hostname set to the one provided on success (cleared * when NULL). On allocation failure hostname is cleared. * On too long input failure, old hostname is unchanged. */ int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname ) { /* Initialize to suppress unnecessary compiler warning */ size_t hostname_len = 0; /* Check if new hostname is valid before * making any change to current one */ if( hostname != NULL ) { hostname_len = strlen( hostname ); if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* Now it's clear that we will overwrite the old hostname, * so we can free it safely */ if( ssl->hostname != NULL ) { mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) ); mbedtls_free( ssl->hostname ); } /* Passing NULL as hostname shall clear the old one */ if( hostname == NULL ) { ssl->hostname = NULL; } else { ssl->hostname = mbedtls_calloc( 1, hostname_len + 1 ); if( ssl->hostname == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); memcpy( ssl->hostname, hostname, hostname_len ); ssl->hostname[hostname_len] = '\0'; } return( 0 ); } #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) /** * \brief Set server side ServerName TLS extension callback * (optional, server-side only). * * If set, the ServerName callback is called whenever the * server receives a ServerName TLS extension from the client * during a handshake. The ServerName callback has the * following parameters: (void *parameter, mbedtls_ssl_context *ssl, * const unsigned char *hostname, size_t len). If a suitable * certificate is found, the callback must set the * certificate(s) and key(s) to use with \c * mbedtls_ssl_set_hs_own_cert() (can be called repeatedly), * and may optionally adjust the CA and associated CRL with \c * mbedtls_ssl_set_hs_ca_chain() as well as the client * authentication mode with \c mbedtls_ssl_set_hs_authmode(), * then must return 0. If no matching name is found, the * callback must either set a default cert, or * return non-zero to abort the handshake at this point. * * \param conf SSL configuration * \param f_sni verification function * \param p_sni verification parameter */ void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf, int (*f_sni)(void *, mbedtls_ssl_context *, const unsigned char *, size_t), void *p_sni ) { conf->f_sni = f_sni; conf->p_sni = p_sni; } #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_SSL_ALPN) /** * \brief Set the supported Application Layer Protocols. * * \param conf SSL configuration * \param protos Pointer to a NULL-terminated list of supported protocols, * in decreasing preference order. The pointer to the list is * recorded by the library for later reference as required, so * the lifetime of the table must be atleast as long as the * lifetime of the SSL configuration structure. * * \return 0 on success, or MBEDTLS_ERR_SSL_BAD_INPUT_DATA. */ int mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos ) { size_t cur_len, tot_len; const char **p; /* * RFC 7301 3.1: "Empty strings MUST NOT be included and byte strings * MUST NOT be truncated." * We check lengths now rather than later. */ tot_len = 0; for( p = protos; *p != NULL; p++ ) { cur_len = strlen( *p ); tot_len += cur_len; if( ( cur_len == 0 ) || ( cur_len > MBEDTLS_SSL_MAX_ALPN_NAME_LEN ) || ( tot_len > MBEDTLS_SSL_MAX_ALPN_LIST_LEN ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } conf->alpn_list = protos; return( 0 ); } /** * \brief Get the name of the negotiated Application Layer Protocol. * This function should be called after the handshake is * completed. * * \param ssl SSL context * * \return Protcol name, or NULL if no protocol was negotiated. */ const char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl ) { return( ssl->alpn_chosen ); } #endif /* MBEDTLS_SSL_ALPN */ #if defined(MBEDTLS_SSL_DTLS_SRTP) /** * \brief Manage support for mki(master key id) value * in use_srtp extension. * MKI is an optional part of SRTP used for key management * and re-keying. See RFC3711 section 3.1 for details. * The default value is * #MBEDTLS_SSL_DTLS_SRTP_MKI_UNSUPPORTED. * * \param conf The SSL configuration to manage mki support. * \param support_mki_value Enable or disable mki usage. Values are * #MBEDTLS_SSL_DTLS_SRTP_MKI_UNSUPPORTED * or #MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED. */ void mbedtls_ssl_conf_srtp_mki_value_supported( mbedtls_ssl_config *conf, int support_mki_value ) { conf->dtls_srtp_mki_support = support_mki_value; } int mbedtls_ssl_dtls_srtp_set_mki_value( mbedtls_ssl_context *ssl, unsigned char *mki_value, uint16_t mki_len ) { if( mki_len > MBEDTLS_TLS_SRTP_MAX_MKI_LENGTH ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } if( ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_UNSUPPORTED ) { return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } memcpy( ssl->dtls_srtp_info.mki_value, mki_value, mki_len ); ssl->dtls_srtp_info.mki_len = mki_len; return( 0 ); } /** * \brief Set the supported DTLS-SRTP protection profiles. * * \param conf SSL configuration * \param profiles Pointer to a List of MBEDTLS_TLS_SRTP_UNSET terminated * supported protection profiles * in decreasing preference order. * The pointer to the list is recorded by the library * for later reference as required, so the lifetime * of the table must be at least as long as the lifetime * of the SSL configuration structure. * The list must not hold more than * MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH elements * (excluding the terminating MBEDTLS_TLS_SRTP_UNSET). * * \return 0 on success * \return #MBEDTLS_ERR_SSL_BAD_INPUT_DATA when the list of * protection profiles is incorrect. */ int mbedtls_ssl_conf_dtls_srtp_protection_profiles( mbedtls_ssl_config *conf, const mbedtls_ssl_srtp_profile *profiles ) { const mbedtls_ssl_srtp_profile *p; size_t list_size = 0; /* check the profiles list: all entry must be valid, * its size cannot be more than the total number of supported profiles, currently 4 */ for( p = profiles; *p != MBEDTLS_TLS_SRTP_UNSET && list_size <= MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH; p++ ) { if( mbedtls_ssl_check_srtp_profile_value( *p ) != MBEDTLS_TLS_SRTP_UNSET ) { list_size++; } else { /* unsupported value, stop parsing and set the size to an error value */ list_size = MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH + 1; } } if( list_size > MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH ) { conf->dtls_srtp_profile_list = NULL; conf->dtls_srtp_profile_list_len = 0; return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } conf->dtls_srtp_profile_list = profiles; conf->dtls_srtp_profile_list_len = list_size; return( 0 ); } /** * \brief Set the mki_value for the current DTLS-SRTP session. * * \param ssl SSL context to use. * \param mki_value The MKI value to set. * \param mki_len The length of the MKI value. * * \note This function is relevant on client side only. * The server discovers the mki value during handshake. * A mki value set on server side using this function * is ignored. * * \return 0 on success * \return #MBEDTLS_ERR_SSL_BAD_INPUT_DATA * \return #MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE */ int mbedtls_ssl_dtls_srtp_set_mki_value( mbedtls_ssl_context *ssl, unsigned char *mki_value, uint16_t mki_len ); /** * \brief Get the negotiated DTLS-SRTP informations: * Protection profile and MKI value. * * \warning This function must be called after the handshake is * completed. The value returned by this function must * not be trusted or acted upon before the handshake completes. * * \param ssl The SSL context to query. * \param dtls_srtp_info The negotiated DTLS-SRTP informations: * - Protection profile in use. * A direct mapping of the iana defined value for protection * profile on an uint16_t. http://www.iana.org/assignments/srtp-protection/srtp-protection.xhtml * #MBEDTLS_TLS_SRTP_UNSET if the use of SRTP was not negotiated * or peer's Hello packet was not parsed yet. * - mki size and value( if size is > 0 ). */ void mbedtls_ssl_get_dtls_srtp_negotiation_result( const mbedtls_ssl_context *ssl, mbedtls_dtls_srtp_info *dtls_srtp_info ) { dtls_srtp_info->chosen_dtls_srtp_profile = ssl->dtls_srtp_info.chosen_dtls_srtp_profile; /* do not copy the mki value if there is no chosen profile */ if( dtls_srtp_info->chosen_dtls_srtp_profile == MBEDTLS_TLS_SRTP_UNSET ) { dtls_srtp_info->mki_len = 0; } else { dtls_srtp_info->mki_len = ssl->dtls_srtp_info.mki_len; memcpy( dtls_srtp_info->mki_value, ssl->dtls_srtp_info.mki_value, ssl->dtls_srtp_info.mki_len ); } } #endif /* MBEDTLS_SSL_DTLS_SRTP */ /** * \brief Set the maximum supported version sent from the client side * and/or accepted at the server side * (Default: MBEDTLS_SSL_MAX_MAJOR_VERSION, MBEDTLS_SSL_MAX_MINOR_VERSION) * * \note This ignores ciphersuites from higher versions. * * \note With DTLS, use MBEDTLS_SSL_MINOR_VERSION_2 for DTLS 1.0 and * MBEDTLS_SSL_MINOR_VERSION_3 for DTLS 1.2 * * \param conf SSL configuration * \param major Major version number (only MBEDTLS_SSL_MAJOR_VERSION_3 supported) * \param minor Minor version number (MBEDTLS_SSL_MINOR_VERSION_0, * MBEDTLS_SSL_MINOR_VERSION_1 and MBEDTLS_SSL_MINOR_VERSION_2, * MBEDTLS_SSL_MINOR_VERSION_3 supported) */ void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor ) { conf->max_major_ver = major; conf->max_minor_ver = minor; } /** * \brief Set the minimum accepted SSL/TLS protocol version * (Default: TLS 1.0) * * \note Input outside of the SSL_MAX_XXXXX_VERSION and * SSL_MIN_XXXXX_VERSION range is ignored. * * \note MBEDTLS_SSL_MINOR_VERSION_0 (SSL v3) should be avoided. * * \note With DTLS, use MBEDTLS_SSL_MINOR_VERSION_2 for DTLS 1.0 and * MBEDTLS_SSL_MINOR_VERSION_3 for DTLS 1.2 * * \param conf SSL configuration * \param major Major version number (only MBEDTLS_SSL_MAJOR_VERSION_3 supported) * \param minor Minor version number (MBEDTLS_SSL_MINOR_VERSION_0, * MBEDTLS_SSL_MINOR_VERSION_1 and MBEDTLS_SSL_MINOR_VERSION_2, * MBEDTLS_SSL_MINOR_VERSION_3 supported) */ void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor ) { conf->min_major_ver = major; conf->min_minor_ver = minor; } #if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C) /** * \brief Set the fallback flag (client-side only). * (Default: MBEDTLS_SSL_IS_NOT_FALLBACK). * * \note Set to MBEDTLS_SSL_IS_FALLBACK when preparing a fallback * connection, that is a connection with max_version set to a * lower value than the value you're willing to use. Such * fallback connections are not recommended but are sometimes * necessary to interoperate with buggy (version-intolerant) * servers. * * \warning You should NOT set this to MBEDTLS_SSL_IS_FALLBACK for * non-fallback connections! This would appear to work for a * while, then cause failures when the server is upgraded to * support a newer TLS version. * * \param conf SSL configuration * \param fallback MBEDTLS_SSL_IS_NOT_FALLBACK or MBEDTLS_SSL_IS_FALLBACK */ void mbedtls_ssl_conf_fallback( mbedtls_ssl_config *conf, char fallback ) { conf->fallback = fallback; } #endif #if defined(MBEDTLS_SSL_SRV_C) /** * \brief Whether to send a list of acceptable CAs in * CertificateRequest messages. * (Default: do send) * * \param conf SSL configuration * \param cert_req_ca_list MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED or * MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED */ void mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf, char cert_req_ca_list ) { conf->cert_req_ca_list = cert_req_ca_list; } #endif #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) /** * \brief Enable or disable Encrypt-then-MAC * (Default: MBEDTLS_SSL_ETM_ENABLED) * * \note This should always be enabled, it is a security * improvement, and should not cause any interoperability * issue (used only if the peer supports it too). * * \param conf SSL configuration * \param etm MBEDTLS_SSL_ETM_ENABLED or MBEDTLS_SSL_ETM_DISABLED */ void mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm ) { conf->encrypt_then_mac = etm; } #endif #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) /** * \brief Enable or disable Extended Master Secret negotiation. * (Default: MBEDTLS_SSL_EXTENDED_MS_ENABLED) * * \note This should always be enabled, it is a security fix to the * protocol, and should not cause any interoperability issue * (used only if the peer supports it too). * * \param conf SSL configuration * \param ems MBEDTLS_SSL_EXTENDED_MS_ENABLED or MBEDTLS_SSL_EXTENDED_MS_DISABLED */ void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems ) { conf->extended_ms = ems; } #endif #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) /** * \brief Set the maximum fragment length to emit and/or negotiate. * (Typical: the smaller of #MBEDTLS_SSL_IN_CONTENT_LEN and * #MBEDTLS_SSL_OUT_CONTENT_LEN, usually `2^14` bytes) * (Server: set maximum fragment length to emit, * usually negotiated by the client during handshake) * (Client: set maximum fragment length to emit *and* * negotiate with the server during handshake) * (Default: #MBEDTLS_SSL_MAX_FRAG_LEN_NONE) * * \note On the client side, the maximum fragment length extension * *will not* be used, unless the maximum fragment length has * been set via this function to a value different than * #MBEDTLS_SSL_MAX_FRAG_LEN_NONE. * * \note With TLS, this currently only affects ApplicationData (sent * with \c mbedtls_ssl_read()), not handshake messages. * With DTLS, this affects both ApplicationData and handshake. * * \note This sets the maximum length for a record's payload, * excluding record overhead that will be added to it, see * \c mbedtls_ssl_get_record_expansion(). * * \note For DTLS, it is also possible to set a limit for the total * size of daragrams passed to the transport layer, including * record overhead, see \c mbedtls_ssl_set_mtu(). * * \param conf SSL configuration * \param mfl_code Code for maximum fragment length (allowed values: * MBEDTLS_SSL_MAX_FRAG_LEN_512, MBEDTLS_SSL_MAX_FRAG_LEN_1024, * MBEDTLS_SSL_MAX_FRAG_LEN_2048, MBEDTLS_SSL_MAX_FRAG_LEN_4096) * * \return 0 if successful or MBEDTLS_ERR_SSL_BAD_INPUT_DATA */ int mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code ) { if( mfl_code >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID || ssl_mfl_code_to_length( mfl_code ) > MBEDTLS_TLS_EXT_ADV_CONTENT_LEN ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } conf->mfl_code = mfl_code; return( 0 ); } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) /** * \brief Enable / Disable 1/n-1 record splitting * (Default: MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED) * * \note Only affects SSLv3 and TLS 1.0, not higher versions. * Does not affect non-CBC ciphersuites in any version. * * \param conf SSL configuration * \param split MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED or * MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED */ void mbedtls_ssl_conf_cbc_record_splitting( mbedtls_ssl_config *conf, char split ) { conf->cbc_record_splitting = split; } #endif /** * \brief Prevent or allow legacy renegotiation. * (Default: MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION) * * MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION allows connections to * be established even if the peer does not support * secure renegotiation, but does not allow renegotiation * to take place if not secure. * (Interoperable and secure option) * * MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION allows renegotiations * with non-upgraded peers. Allowing legacy renegotiation * makes the connection vulnerable to specific man in the * middle attacks. (See RFC 5746) * (Most interoperable and least secure option) * * MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE breaks off connections * if peer does not support secure renegotiation. Results * in interoperability issues with non-upgraded peers * that do not support renegotiation altogether. * (Most secure option, interoperability issues) * * \param conf SSL configuration * \param allow_legacy Prevent or allow (SSL_NO_LEGACY_RENEGOTIATION, * SSL_ALLOW_LEGACY_RENEGOTIATION or * MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE) */ void mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy ) { conf->allow_legacy_renegotiation = allow_legacy; } #if defined(MBEDTLS_SSL_RENEGOTIATION) /** * \brief Enable / Disable renegotiation support for connection when * initiated by peer * (Default: MBEDTLS_SSL_RENEGOTIATION_DISABLED) * * \warning It is recommended to always disable renegotation unless you * know you need it and you know what you're doing. In the * past, there have been several issues associated with * renegotiation or a poor understanding of its properties. * * \note Server-side, enabling renegotiation also makes the server * susceptible to a resource DoS by a malicious client. * * \param conf SSL configuration * \param renegotiation Enable or disable (MBEDTLS_SSL_RENEGOTIATION_ENABLED or * MBEDTLS_SSL_RENEGOTIATION_DISABLED) */ void mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation ) { conf->disable_renegotiation = renegotiation; } /** * \brief Enforce renegotiation requests. * (Default: enforced, max_records = 16) * * When we request a renegotiation, the peer can comply or * ignore the request. This function allows us to decide * whether to enforce our renegotiation requests by closing * the connection if the peer doesn't comply. * * However, records could already be in transit from the peer * when the request is emitted. In order to increase * reliability, we can accept a number of records before the * expected handshake records. * * The optimal value is highly dependent on the specific usage * scenario. * * \note With DTLS and server-initiated renegotiation, the * HelloRequest is retransmited every time mbedtls_ssl_read() times * out or receives Application Data, until: * - max_records records have beens seen, if it is >= 0, or * - the number of retransmits that would happen during an * actual handshake has been reached. * Please remember the request might be lost a few times * if you consider setting max_records to a really low value. * * \warning On client, the grace period can only happen during * mbedtls_ssl_read(), as opposed to mbedtls_ssl_write() and mbedtls_ssl_renegotiate() * which always behave as if max_record was 0. The reason is, * if we receive application data from the server, we need a * place to write it, which only happens during mbedtls_ssl_read(). * * \param conf SSL configuration * \param max_records Use MBEDTLS_SSL_RENEGOTIATION_NOT_ENFORCED if you don't want to * enforce renegotiation, or a non-negative value to enforce * it but allow for a grace period of max_records records. */ void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records ) { conf->renego_max_records = max_records; } /** * \brief Set record counter threshold for periodic renegotiation. * (Default: 2^48 - 1) * * Renegotiation is automatically triggered when a record * counter (outgoing or incoming) crosses the defined * threshold. The default value is meant to prevent the * connection from being closed when the counter is about to * reached its maximal value (it is not allowed to wrap). * * Lower values can be used to enforce policies such as "keys * must be refreshed every N packets with cipher X". * * The renegotiation period can be disabled by setting * conf->disable_renegotiation to * MBEDTLS_SSL_RENEGOTIATION_DISABLED. * * \note When the configured transport is * MBEDTLS_SSL_TRANSPORT_DATAGRAM the maximum renegotiation * period is 2^48 - 1, and for MBEDTLS_SSL_TRANSPORT_STREAM, * the maximum renegotiation period is 2^64 - 1. * * \param conf SSL configuration * \param period The threshold value: a big-endian 64-bit number. */ void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf, const unsigned char period[8] ) { memcpy( conf->renego_period, period, 8 ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) #if defined(MBEDTLS_SSL_CLI_C) /** * \brief Enable / Disable session tickets (client only). * (Default: MBEDTLS_SSL_SESSION_TICKETS_ENABLED.) * * \note On server, use \c mbedtls_ssl_conf_session_tickets_cb(). * * \param conf SSL configuration * \param use_tickets Enable or disable (MBEDTLS_SSL_SESSION_TICKETS_ENABLED or * MBEDTLS_SSL_SESSION_TICKETS_DISABLED) */ void mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets ) { conf->session_tickets = use_tickets; } #endif #if defined(MBEDTLS_SSL_SRV_C) /** * \brief Configure SSL session ticket callbacks (server only). * (Default: none.) * * \note On server, session tickets are enabled by providing * non-NULL callbacks. * * \note On client, use \c mbedtls_ssl_conf_session_tickets(). * * \param conf SSL configuration context * \param f_ticket_write Callback for writing a ticket * \param f_ticket_parse Callback for parsing a ticket * \param p_ticket Context shared by the two callbacks */ void mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf, mbedtls_ssl_ticket_write_t *f_ticket_write, mbedtls_ssl_ticket_parse_t *f_ticket_parse, void *p_ticket ) { conf->f_ticket_write = f_ticket_write; conf->f_ticket_parse = f_ticket_parse; conf->p_ticket = p_ticket; } #endif #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_SSL_EXPORT_KEYS) /** * \brief Configure key export callback. * (Default: none.) * * \note See \c mbedtls_ssl_export_keys_t. * * \param conf SSL configuration context * \param f_export_keys Callback for exporting keys * \param p_export_keys Context for the callback */ void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf, mbedtls_ssl_export_keys_t *f_export_keys, void *p_export_keys ) { conf->f_export_keys = f_export_keys; conf->p_export_keys = p_export_keys; } /** * \brief Configure extended key export callback. * (Default: none.) * * \note See \c mbedtls_ssl_export_keys_ext_t. * \warning Exported key material must not be used for any purpose * before the (D)TLS handshake is completed * * \param conf SSL configuration context * \param f_export_keys_ext Callback for exporting keys * \param p_export_keys Context for the callback */ void mbedtls_ssl_conf_export_keys_ext_cb( mbedtls_ssl_config *conf, mbedtls_ssl_export_keys_ext_t *f_export_keys_ext, void *p_export_keys ) { conf->f_export_keys_ext = f_export_keys_ext; conf->p_export_keys = p_export_keys; } #endif #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) /** * \brief Configure asynchronous private key operation callbacks. * * \param conf SSL configuration context * \param f_async_sign Callback to start a signature operation. See * the description of ::mbedtls_ssl_async_sign_t * for more information. This may be \c NULL if the * external processor does not support any signature * operation; in this case the private key object * associated with the certificate will be used. * \param f_async_decrypt Callback to start a decryption operation. See * the description of ::mbedtls_ssl_async_decrypt_t * for more information. This may be \c NULL if the * external processor does not support any decryption * operation; in this case the private key object * associated with the certificate will be used. * \param f_async_resume Callback to resume an asynchronous operation. See * the description of ::mbedtls_ssl_async_resume_t * for more information. This may not be \c NULL unless * \p f_async_sign and \p f_async_decrypt are both * \c NULL. * \param f_async_cancel Callback to cancel an asynchronous operation. See * the description of ::mbedtls_ssl_async_cancel_t * for more information. This may be \c NULL if * no cleanup is needed. * \param config_data A pointer to configuration data which can be * retrieved with * mbedtls_ssl_conf_get_async_config_data(). The * library stores this value without dereferencing it. */ void mbedtls_ssl_conf_async_private_cb( mbedtls_ssl_config *conf, mbedtls_ssl_async_sign_t *f_async_sign, mbedtls_ssl_async_decrypt_t *f_async_decrypt, mbedtls_ssl_async_resume_t *f_async_resume, mbedtls_ssl_async_cancel_t *f_async_cancel, void *async_config_data ) { conf->f_async_sign_start = f_async_sign; conf->f_async_decrypt_start = f_async_decrypt; conf->f_async_resume = f_async_resume; conf->f_async_cancel = f_async_cancel; conf->p_async_config_data = async_config_data; } /** * \brief Retrieve the configuration data set by * mbedtls_ssl_conf_async_private_cb(). * * \param conf SSL configuration context * \return The configuration data set by * mbedtls_ssl_conf_async_private_cb(). */ void *mbedtls_ssl_conf_get_async_config_data( const mbedtls_ssl_config *conf ) { return( conf->p_async_config_data ); } /** * \brief Retrieve the asynchronous operation user context. * * \note This function may only be called while a handshake * is in progress. * * \param ssl The SSL context to access. * * \return The asynchronous operation user context that was last * set during the current handshake. If * mbedtls_ssl_set_async_operation_data() has not yet been * called during the current handshake, this function returns * \c NULL. */ void *mbedtls_ssl_get_async_operation_data( const mbedtls_ssl_context *ssl ) { if( ssl->handshake == NULL ) return( NULL ); else return( ssl->handshake->user_async_ctx ); } /** * \brief Retrieve the asynchronous operation user context. * * \note This function may only be called while a handshake * is in progress. * * \param ssl The SSL context to access. * \param ctx The new value of the asynchronous operation user context. * Call mbedtls_ssl_get_async_operation_data() later during the * same handshake to retrieve this value. */ void mbedtls_ssl_set_async_operation_data( mbedtls_ssl_context *ssl, void *ctx ) { if( ssl->handshake != NULL ) ssl->handshake->user_async_ctx = ctx; } #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ /** * \brief Return the result of the certificate verification * * \param ssl The SSL context to use. * * \return \c 0 if the certificate verification was successful. * \return \c -1u if the result is not available. This may happen * e.g. if the handshake aborts early, or a verification * callback returned a fatal error. * \return A bitwise combination of \c MBEDTLS_X509_BADCERT_XXX * and \c MBEDTLS_X509_BADCRL_XXX failure flags; see x509.h. */ uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl ) { if( ssl->session != NULL ) return( ssl->session->verify_result ); if( ssl->session_negotiate != NULL ) return( ssl->session_negotiate->verify_result ); return( 0xFFFFFFFF ); } /** * \brief Return the name of the current ciphersuite * * \param ssl SSL context * * \return a string containing the ciphersuite name */ const char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl ) { if( ssl == NULL || ssl->session == NULL ) return( NULL ); return mbedtls_ssl_get_ciphersuite_name( ssl->session->ciphersuite ); } /** * \brief Return the current SSL version (SSLv3/TLSv1/etc) * * \param ssl SSL context * * \return a string containing the SSL version */ const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { switch( ssl->minor_ver ) { case MBEDTLS_SSL_MINOR_VERSION_2: return( "DTLSv1.0" ); case MBEDTLS_SSL_MINOR_VERSION_3: return( "DTLSv1.2" ); default: return( "unknown (DTLS)" ); } } #endif switch( ssl->minor_ver ) { case MBEDTLS_SSL_MINOR_VERSION_0: return( "SSLv3.0" ); case MBEDTLS_SSL_MINOR_VERSION_1: return( "TLSv1.0" ); case MBEDTLS_SSL_MINOR_VERSION_2: return( "TLSv1.1" ); case MBEDTLS_SSL_MINOR_VERSION_3: return( "TLSv1.2" ); default: return( "unknown" ); } } #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) /** * \brief Return the maximum fragment length (payload, in bytes) for * the input buffer. This is the negotiated maximum fragment * length, or, if there is none, MBEDTLS_SSL_MAX_CONTENT_LEN. * If it is not defined either, the value is 2^14. This function * works as its predecessor, \c mbedtls_ssl_get_max_frag_len(). * * \sa mbedtls_ssl_conf_max_frag_len() * \sa mbedtls_ssl_get_max_record_payload() * * \param ssl SSL context * * \return Current maximum fragment length for the output buffer. */ size_t mbedtls_ssl_get_input_max_frag_len( const mbedtls_ssl_context *ssl ) { size_t max_len = MBEDTLS_SSL_MAX_CONTENT_LEN; size_t read_mfl; /* Use the configured MFL for the client if we're past SERVER_HELLO_DONE */ if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT && ssl->state >= MBEDTLS_SSL_SERVER_HELLO_DONE ) { return ssl_mfl_code_to_length( ssl->conf->mfl_code ); } /* Check if a smaller max length was negotiated */ if( ssl->session_out != NULL ) { read_mfl = ssl_mfl_code_to_length( ssl->session_out->mfl_code ); if( read_mfl < max_len ) { max_len = read_mfl; } } // During a handshake, use the value being negotiated if( ssl->session_negotiate != NULL ) { read_mfl = ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code ); if( read_mfl < max_len ) { max_len = read_mfl; } } return( max_len ); } /** * \brief Return the maximum fragment length (payload, in bytes) for * the output buffer. For the client, this is the configured * value. For the server, it is the minimum of two - the * configured value and the negotiated one. * * \sa mbedtls_ssl_conf_max_frag_len() * \sa mbedtls_ssl_get_max_record_payload() * * \param ssl SSL context * * \return Current maximum fragment length for the output buffer. */ size_t mbedtls_ssl_get_output_max_frag_len( const mbedtls_ssl_context *ssl ) { size_t max_len; /* * Assume mfl_code is correct since it was checked when set */ max_len = ssl_mfl_code_to_length( ssl->conf->mfl_code ); /* Check if a smaller max length was negotiated */ if( ssl->session_out != NULL && ssl_mfl_code_to_length( ssl->session_out->mfl_code ) < max_len ) { max_len = ssl_mfl_code_to_length( ssl->session_out->mfl_code ); } /* During a handshake, use the value being negotiated */ if( ssl->session_negotiate != NULL && ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code ) < max_len ) { max_len = ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code ); } return( max_len ); } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_PROTO_DTLS) size_t mbedtls_ssl_get_current_mtu( const mbedtls_ssl_context *ssl ) { /* Return unlimited mtu for client hello messages to avoid fragmentation. */ if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT && ( ssl->state == MBEDTLS_SSL_CLIENT_HELLO || ssl->state == MBEDTLS_SSL_SERVER_HELLO ) ) return ( 0 ); if( ssl->handshake == NULL || ssl->handshake->mtu == 0 ) return( ssl->mtu ); if( ssl->mtu == 0 ) return( ssl->handshake->mtu ); return( ssl->mtu < ssl->handshake->mtu ? ssl->mtu : ssl->handshake->mtu ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ /** * \brief Return the current maximum outgoing record payload in bytes. * This takes into account the config.h setting \c * MBEDTLS_SSL_OUT_CONTENT_LEN, the configured and negotiated * max fragment length extension if used, and for DTLS the * path MTU as configured and current record expansion. * * \note With DTLS, \c mbedtls_ssl_write() will return an error if * called with a larger length value. * With TLS, \c mbedtls_ssl_write() will fragment the input if * necessary and return the number of bytes written; it is up * to the caller to call \c mbedtls_ssl_write() again in * order to send the remaining bytes if any. * * \note This function is not available (always returns an error) * when record compression is enabled. * * \sa mbedtls_ssl_set_mtu() * \sa mbedtls_ssl_get_output_max_frag_len() * \sa mbedtls_ssl_get_input_max_frag_len() * \sa mbedtls_ssl_get_record_expansion() * * \param ssl SSL context * * \return Current maximum payload for an outgoing record, * or a negative error code. */ int mbedtls_ssl_get_max_out_record_payload( const mbedtls_ssl_context *ssl ) { size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN; #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) && \ !defined(MBEDTLS_SSL_PROTO_DTLS) (void) ssl; #endif #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) const size_t mfl = mbedtls_ssl_get_output_max_frag_len( ssl ); if( max_len > mfl ) max_len = mfl; #endif #if defined(MBEDTLS_SSL_PROTO_DTLS) if( mbedtls_ssl_get_current_mtu( ssl ) != 0 ) { const size_t mtu = mbedtls_ssl_get_current_mtu( ssl ); const int ret = mbedtls_ssl_get_record_expansion( ssl ); const size_t overhead = (size_t) ret; if( ret < 0 ) return( ret ); if( mtu <= overhead ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "MTU too low for record expansion" ) ); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } if( max_len > mtu - overhead ) max_len = mtu - overhead; } #endif /* MBEDTLS_SSL_PROTO_DTLS */ #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) && \ !defined(MBEDTLS_SSL_PROTO_DTLS) ((void) ssl); #endif return( (int) max_len ); } #if defined(MBEDTLS_X509_CRT_PARSE_C) /** * \brief Return the peer certificate from the current connection. * * \param ssl The SSL context to use. This must be initialized and setup. * * \return The current peer certificate, if available. * The returned certificate is owned by the SSL context and * is valid only until the next call to the SSL API. * \return \c NULL if no peer certificate is available. This might * be because the chosen ciphersuite doesn't use CRTs * (PSK-based ciphersuites, for example), or because * #MBEDTLS_SSL_KEEP_PEER_CERTIFICATE has been disabled, * allowing the stack to free the peer's CRT to save memory. * * \note For one-time inspection of the peer's certificate during * the handshake, consider registering an X.509 CRT verification * callback through mbedtls_ssl_conf_verify() instead of calling * this function. Using mbedtls_ssl_conf_verify() also comes at * the benefit of allowing you to influence the verification * process, for example by masking expected and tolerated * verification failures. * * \warning You must not use the pointer returned by this function * after any further call to the SSL API, including * mbedtls_ssl_read() and mbedtls_ssl_write(); this is * because the pointer might change during renegotiation, * which happens transparently to the user. * If you want to use the certificate across API calls, * you must make a copy. */ const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl ) { if( ssl == NULL || ssl->session == NULL ) return( NULL ); #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) return( ssl->session->peer_cert ); #else return( NULL ); #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ } #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_SSL_CLI_C) /** * \brief Save session in order to resume it later (client-side only) * Session data is copied to presented session structure. * * * \param ssl SSL context * \param session session context * * \return 0 if successful, * MBEDTLS_ERR_SSL_ALLOC_FAILED if memory allocation failed, * MBEDTLS_ERR_SSL_BAD_INPUT_DATA if used server-side or * arguments are otherwise invalid. * * \note Only the server certificate is copied, and not the full chain, * so you should not attempt to validate the certificate again * by calling \c mbedtls_x509_crt_verify() on it. * Instead, you should use the results from the verification * in the original handshake by calling \c mbedtls_ssl_get_verify_result() * after loading the session again into a new SSL context * using \c mbedtls_ssl_set_session(). * * \note Once the session object is not needed anymore, you should * free it by calling \c mbedtls_ssl_session_free(). * * \sa mbedtls_ssl_set_session() */ int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session *dst ) { if( ssl == NULL || dst == NULL || ssl->session == NULL || ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } return( mbedtls_ssl_session_copy( dst, ssl->session ) ); } #endif /* MBEDTLS_SSL_CLI_C */ /** * \brief Get a pointer to the current session structure, for example * to serialize it. * * \warning Ownership of the session remains with the SSL context, and * the returned pointer is only guaranteed to be valid until * the next API call operating on the same \p ssl context. * * \see mbedtls_ssl_session_save() * * \param ssl The SSL context. * * \return A pointer to the current session if successful. * \return \c NULL if no session is active. */ const mbedtls_ssl_session *mbedtls_ssl_get_session_pointer( const mbedtls_ssl_context *ssl ) { if( ssl == NULL ) return( NULL ); return( ssl->session ); } /* * Define ticket header determining Mbed TLS version * and structure of the ticket. */ /* * Define bitflag determining compile-time settings influencing * structure of serialized SSL sessions. */ #if defined(MBEDTLS_HAVE_TIME) #define SSL_SERIALIZED_SESSION_CONFIG_TIME 1 #else #define SSL_SERIALIZED_SESSION_CONFIG_TIME 0 #endif /* MBEDTLS_HAVE_TIME */ #if defined(MBEDTLS_X509_CRT_PARSE_C) #define SSL_SERIALIZED_SESSION_CONFIG_CRT 1 #else #define SSL_SERIALIZED_SESSION_CONFIG_CRT 0 #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_SSL_CLI_C) && defined(MBEDTLS_SSL_SESSION_TICKETS) #define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET 1 #else #define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET 0 #endif /* MBEDTLS_SSL_CLI_C && MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) #define SSL_SERIALIZED_SESSION_CONFIG_MFL 1 #else #define SSL_SERIALIZED_SESSION_CONFIG_MFL 0 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #define SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC 0 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) #define SSL_SERIALIZED_SESSION_CONFIG_ETM 1 #else #define SSL_SERIALIZED_SESSION_CONFIG_ETM 0 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) #define SSL_SERIALIZED_SESSION_CONFIG_TICKET 1 #else #define SSL_SERIALIZED_SESSION_CONFIG_TICKET 0 #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #define SSL_SERIALIZED_SESSION_CONFIG_TIME_BIT 0 #define SSL_SERIALIZED_SESSION_CONFIG_CRT_BIT 1 #define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET_BIT 2 #define SSL_SERIALIZED_SESSION_CONFIG_MFL_BIT 3 #define SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC_BIT 4 #define SSL_SERIALIZED_SESSION_CONFIG_ETM_BIT 5 #define SSL_SERIALIZED_SESSION_CONFIG_TICKET_BIT 6 #define SSL_SERIALIZED_SESSION_CONFIG_BITFLAG \ ( (uint16_t) ( \ ( SSL_SERIALIZED_SESSION_CONFIG_TIME << SSL_SERIALIZED_SESSION_CONFIG_TIME_BIT ) | \ ( SSL_SERIALIZED_SESSION_CONFIG_CRT << SSL_SERIALIZED_SESSION_CONFIG_CRT_BIT ) | \ ( SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET << SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET_BIT ) | \ ( SSL_SERIALIZED_SESSION_CONFIG_MFL << SSL_SERIALIZED_SESSION_CONFIG_MFL_BIT ) | \ ( SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC << SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC_BIT ) | \ ( SSL_SERIALIZED_SESSION_CONFIG_ETM << SSL_SERIALIZED_SESSION_CONFIG_ETM_BIT ) | \ ( SSL_SERIALIZED_SESSION_CONFIG_TICKET << SSL_SERIALIZED_SESSION_CONFIG_TICKET_BIT ) ) ) static unsigned char ssl_serialized_session_header[] = { MBEDTLS_VERSION_MAJOR, MBEDTLS_VERSION_MINOR, MBEDTLS_VERSION_PATCH, ( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG >> 8 ) & 0xFF, ( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG >> 0 ) & 0xFF, }; /* * Serialize a session in the following format: * (in the presentation language of TLS, RFC 8446 section 3) * * opaque mbedtls_version[3]; // major, minor, patch * opaque session_format[2]; // version-specific 16-bit field determining * // the format of the remaining * // serialized data. * * Note: When updating the format, remember to keep * these version+format bytes. * * // In this version, `session_format` determines * // the setting of those compile-time * // configuration options which influence * // the structure of mbedtls_ssl_session. * uint64 start_time; * uint8 ciphersuite[2]; // defined by the standard * uint8 compression; // 0 or 1 * uint8 session_id_len; // at most 32 * opaque session_id[32]; * opaque master[48]; // fixed length in the standard * uint32 verify_result; * opaque peer_cert<0..2^24-1>; // length 0 means no peer cert * opaque ticket<0..2^24-1>; // length 0 means no ticket * uint32 ticket_lifetime; * uint8 mfl_code; // up to 255 according to standard * uint8 trunc_hmac; // 0 or 1 * uint8 encrypt_then_mac; // 0 or 1 * * The order is the same as in the definition of the structure, except * verify_result is put before peer_cert so that all mandatory fields come * together in one block. */ static int ssl_session_save( const mbedtls_ssl_session *session, unsigned char omit_header, unsigned char *buf, size_t buf_len, size_t *olen ) { unsigned char *p = buf; size_t used = 0; #if defined(MBEDTLS_X509_CRT_PARSE_C) #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) size_t cert_len; #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ if( !omit_header ) { /* * Add version identifier */ used += sizeof( ssl_serialized_session_header ); if( used <= buf_len ) { memcpy( p, ssl_serialized_session_header, sizeof( ssl_serialized_session_header ) ); p += sizeof( ssl_serialized_session_header ); } } /* * Time */ #if defined(MBEDTLS_HAVE_TIME) used += 8; if( used <= buf_len ) p = Write64be(p, session->start); #endif /* MBEDTLS_HAVE_TIME */ /* * Basic mandatory fields */ used += 2 /* ciphersuite */ + 1 /* compression */ + 1 /* id_len */ + sizeof( session->id ) + sizeof( session->master ) + 4; /* verify_result */ if( used <= buf_len ) { *p++ = (unsigned char)( ( session->ciphersuite >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( session->ciphersuite ) & 0xFF ); *p++ = (unsigned char)( session->compression & 0xFF ); *p++ = (unsigned char)( session->id_len & 0xFF ); memcpy( p, session->id, 32 ); p += 32; memcpy( p, session->master, 48 ); p += 48; *p++ = (unsigned char)( ( session->verify_result >> 24 ) & 0xFF ); *p++ = (unsigned char)( ( session->verify_result >> 16 ) & 0xFF ); *p++ = (unsigned char)( ( session->verify_result >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( session->verify_result ) & 0xFF ); } /* * Peer's end-entity certificate */ #if defined(MBEDTLS_X509_CRT_PARSE_C) #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) if( session->peer_cert == NULL ) cert_len = 0; else cert_len = session->peer_cert->raw.len; used += 3 + cert_len; if( used <= buf_len ) { *p++ = (unsigned char)( ( cert_len >> 16 ) & 0xFF ); *p++ = (unsigned char)( ( cert_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( cert_len ) & 0xFF ); if( session->peer_cert != NULL ) { memcpy( p, session->peer_cert->raw.p, cert_len ); p += cert_len; } } #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( session->peer_cert_digest != NULL ) { used += 1 /* type */ + 1 /* length */ + session->peer_cert_digest_len; if( used <= buf_len ) { *p++ = (unsigned char) session->peer_cert_digest_type; *p++ = (unsigned char) session->peer_cert_digest_len; memcpy( p, session->peer_cert_digest, session->peer_cert_digest_len ); p += session->peer_cert_digest_len; } } else { used += 2; if( used <= buf_len ) { *p++ = (unsigned char) MBEDTLS_MD_NONE; *p++ = 0; } } #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ /* * Session ticket if any, plus associated data */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C) used += 3 + session->ticket_len + 4; /* len + ticket + lifetime */ if( used <= buf_len ) { *p++ = (unsigned char)( ( session->ticket_len >> 16 ) & 0xFF ); *p++ = (unsigned char)( ( session->ticket_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( session->ticket_len ) & 0xFF ); if( session->ticket != NULL ) { memcpy( p, session->ticket, session->ticket_len ); p += session->ticket_len; } *p++ = (unsigned char)( ( session->ticket_lifetime >> 24 ) & 0xFF ); *p++ = (unsigned char)( ( session->ticket_lifetime >> 16 ) & 0xFF ); *p++ = (unsigned char)( ( session->ticket_lifetime >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( session->ticket_lifetime ) & 0xFF ); } #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */ /* * Misc extension-related info */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) used += 1; if( used <= buf_len ) *p++ = session->mfl_code; #endif #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) used += 1; if( used <= buf_len ) *p++ = (unsigned char)( ( session->encrypt_then_mac ) & 0xFF ); #endif /* Done */ *olen = used; if( used > buf_len ) return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); return( 0 ); } /** * \brief Save session structure as serialized data in a buffer. * On client, this can be used for saving session data, * potentially in non-volatile storage, for resuming later. * On server, this can be used for alternative implementations * of session cache or session tickets. * * \see mbedtls_ssl_session_load() * \see mbedtls_ssl_get_session_pointer() * * \param session The session structure to be saved. * \param buf The buffer to write the serialized data to. It must be a * writeable buffer of at least \p len bytes, or may be \c * NULL if \p len is \c 0. * \param buf_len The number of bytes available for writing in \p buf. * \param olen The size in bytes of the data that has been or would have * been written. It must point to a valid \c size_t. * * \note \p olen is updated to the correct value regardless of * whether \p buf_len was large enough. This makes it possible * to determine the necessary size by calling this function * with \p buf set to \c NULL and \p buf_len to \c 0. * * \return \c 0 if successful. * \return #MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL if \p buf is too small. */ int mbedtls_ssl_session_save( const mbedtls_ssl_session *session, unsigned char *buf, size_t buf_len, size_t *olen ) { return( ssl_session_save( session, 0, buf, buf_len, olen ) ); } /* * Deserialize session, see mbedtls_ssl_session_save() for format. * * This internal version is wrapped by a public function that cleans up in * case of error, and has an extra option omit_header. */ static int ssl_session_load( mbedtls_ssl_session *session, unsigned char omit_header, const unsigned char *buf, size_t len ) { const unsigned char *p = buf; const unsigned char * const end = buf + len; #if defined(MBEDTLS_HAVE_TIME) uint64_t start; #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) size_t cert_len; #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ if( !omit_header ) { /* * Check version identifier */ if( (size_t)( end - p ) < sizeof( ssl_serialized_session_header ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( timingsafe_bcmp( p, ssl_serialized_session_header, sizeof( ssl_serialized_session_header ) ) != 0 ) { return( MBEDTLS_ERR_SSL_VERSION_MISMATCH ); } p += sizeof( ssl_serialized_session_header ); } /* * Time */ #if defined(MBEDTLS_HAVE_TIME) if( 8 > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); start = Read64be(p); p += 8; session->start = (int64_t) start; #endif /* MBEDTLS_HAVE_TIME */ /* * Basic mandatory fields */ if( 2 + 1 + 1 + 32 + 48 + 4 > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->ciphersuite = ( p[0] << 8 ) | p[1]; p += 2; session->compression = *p++; session->id_len = *p++; memcpy( session->id, p, 32 ); p += 32; memcpy( session->master, p, 48 ); p += 48; session->verify_result = Read32be(p); p += 4; /* Immediately clear invalid pointer values that have been read, in case * we exit early before we replaced them with valid ones. */ #if defined(MBEDTLS_X509_CRT_PARSE_C) #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) session->peer_cert = NULL; #else session->peer_cert_digest = NULL; #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C) session->ticket = NULL; #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */ /* * Peer certificate */ #if defined(MBEDTLS_X509_CRT_PARSE_C) #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) /* Deserialize CRT from the end of the ticket. */ if( 3 > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); cert_len = ( p[0] << 16 ) | ( p[1] << 8 ) | p[2]; p += 3; if( cert_len != 0 ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( cert_len > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->peer_cert = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) ); if( session->peer_cert == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); mbedtls_x509_crt_init( session->peer_cert ); if( ( ret = mbedtls_x509_crt_parse_der( session->peer_cert, p, cert_len ) ) != 0 ) { mbedtls_x509_crt_free( session->peer_cert ); mbedtls_free( session->peer_cert ); session->peer_cert = NULL; return( ret ); } p += cert_len; } #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ /* Deserialize CRT digest from the end of the ticket. */ if( 2 > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->peer_cert_digest_type = (mbedtls_md_type_t) *p++; session->peer_cert_digest_len = (size_t) *p++; if( session->peer_cert_digest_len != 0 ) { const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( session->peer_cert_digest_type ); if( md_info == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( session->peer_cert_digest_len != mbedtls_md_get_size( md_info ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( session->peer_cert_digest_len > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->peer_cert_digest = mbedtls_calloc( 1, session->peer_cert_digest_len ); if( session->peer_cert_digest == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); memcpy( session->peer_cert_digest, p, session->peer_cert_digest_len ); p += session->peer_cert_digest_len; } #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ /* * Session ticket and associated data */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C) if( 3 > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->ticket_len = ( p[0] << 16 ) | ( p[1] << 8 ) | p[2]; p += 3; if( session->ticket_len != 0 ) { if( session->ticket_len > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->ticket = mbedtls_calloc( 1, session->ticket_len ); if( session->ticket == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); memcpy( session->ticket, p, session->ticket_len ); p += session->ticket_len; } if( 4 > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->ticket_lifetime = Read32be(p); p += 4; #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */ /* * Misc extension-related info */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) if( 1 > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->mfl_code = *p++; #endif #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) if( 1 > (size_t)( end - p ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->encrypt_then_mac = *p++; #endif /* Done, should have consumed entire buffer */ if( p != end ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); return( 0 ); } /** * \brief Load serialized session data into a session structure. * On client, this can be used for loading saved sessions * before resuming them with mbedstls_ssl_set_session(). * On server, this can be used for alternative implementations * of session cache or session tickets. * * \warning If a peer certificate chain is associated with the session, * the serialized state will only contain the peer's * end-entity certificate and the result of the chain * verification (unless verification was disabled), but not * the rest of the chain. * * \see mbedtls_ssl_session_save() * \see mbedtls_ssl_set_session() * * \param session The session structure to be populated. It must have been * initialised with mbedtls_ssl_session_init() but not * populated yet. * \param buf The buffer holding the serialized session data. It must be a * readable buffer of at least \p len bytes. * \param len The size of the serialized data in bytes. * * \return \c 0 if successful. * \return #MBEDTLS_ERR_SSL_ALLOC_FAILED if memory allocation failed. * \return #MBEDTLS_ERR_SSL_BAD_INPUT_DATA if input data is invalid. * \return #MBEDTLS_ERR_SSL_VERSION_MISMATCH if the serialized data * was generated in a different version or configuration of * Mbed TLS. * \return Another negative value for other kinds of errors (for * example, unsupported features in the embedded certificate). */ int mbedtls_ssl_session_load( mbedtls_ssl_session *session, const unsigned char *buf, size_t len ) { int ret = ssl_session_load( session, 0, buf, len ); if( ret != 0 ) mbedtls_ssl_session_free( session ); return( ret ); } /** * \brief Perform a single step of the SSL handshake * * \note The state of the context (ssl->state) will be at * the next state after this function returns \c 0. Do not * call this function if state is MBEDTLS_SSL_HANDSHAKE_OVER. * * \param ssl SSL context * * \return See mbedtls_ssl_handshake(). * * \warning If this function returns something other than \c 0, * #MBEDTLS_ERR_SSL_WANT_READ, #MBEDTLS_ERR_SSL_WANT_WRITE, * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS, you must stop using * the SSL context for reading or writing, and either free it * or call \c mbedtls_ssl_session_reset() on it before * re-using it for a new connection; the current connection * must be closed. */ int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl ) { if( ssl == NULL || ssl->conf == NULL || ssl->conf->f_step == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); return ssl->conf->f_step(ssl); } /** * \brief Perform the SSL handshake * * \param ssl SSL context * * \return \c 0 if successful. * \return #MBEDTLS_ERR_SSL_WANT_READ or #MBEDTLS_ERR_SSL_WANT_WRITE * if the handshake is incomplete and waiting for data to * be available for reading from or writing to the underlying * transport - in this case you must call this function again * when the underlying transport is ready for the operation. * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if an asynchronous * operation is in progress (see * mbedtls_ssl_conf_async_private_cb()) - in this case you * must call this function again when the operation is ready. * \return #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS if a cryptographic * operation is in progress (see mbedtls_ecp_set_max_ops()) - * in this case you must call this function again to complete * the handshake when you're done attending other tasks. * \return #MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED if DTLS is in use * and the client did not demonstrate reachability yet - in * this case you must stop using the context (see below). * \return Another SSL error code - in this case you must stop using * the context (see below). * * \warning If this function returns something other than * \c 0, * #MBEDTLS_ERR_SSL_WANT_READ, * #MBEDTLS_ERR_SSL_WANT_WRITE, * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS, * you must stop using the SSL context for reading or writing, * and either free it or call \c mbedtls_ssl_session_reset() * on it before re-using it for a new connection; the current * connection must be closed. * * \note If DTLS is in use, then you may choose to handle * #MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED specially for logging * purposes, as it is an expected return value rather than an * actual error, but you still need to reset/free the context. * * \note Remarks regarding event-driven DTLS: * If the function returns #MBEDTLS_ERR_SSL_WANT_READ, no datagram * from the underlying transport layer is currently being processed, * and it is safe to idle until the timer or the underlying transport * signal a new event. This is not true for a successful handshake, * in which case the datagram of the underlying transport that is * currently being processed might or might not contain further * DTLS records. */ int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl ) { int ret = 0; /* Sanity checks */ if( ssl == NULL || ssl->conf == NULL || ssl->conf->f_step == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ( ssl->f_set_timer == NULL || ssl->f_get_timer == NULL ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "You must use " "mbedtls_ssl_set_timer_cb() for DTLS" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> handshake" ) ); /* Main handshake loop */ while( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) { ret = ssl->conf->f_step( ssl ); if( ret != 0 ) break; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= handshake" ) ); return( ret ); } #if defined(MBEDTLS_SSL_RENEGOTIATION) #if defined(MBEDTLS_SSL_SRV_C) /* * Write HelloRequest to request renegotiation on server */ static int ssl_write_hello_request( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello request" ) ); ssl->out_msglen = 4; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_HELLO_REQUEST; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello request" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_SRV_C */ /* * Actually renegotiate current connection, triggered by either: * - any side: calling mbedtls_ssl_renegotiate(), * - client: receiving a HelloRequest during mbedtls_ssl_read(), * - server: receiving any handshake message on server during mbedtls_ssl_read() after * the initial handshake is completed. * If the handshake doesn't complete due to waiting for I/O, it will continue * during the next calls to mbedtls_ssl_renegotiate() or mbedtls_ssl_read() respectively. */ int mbedtls_ssl_start_renegotiation( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> renegotiate" ) ); if( ( ret = ssl_handshake_init( ssl ) ) != 0 ) return( ret ); /* RFC 6347 4.2.2: "[...] the HelloRequest will have message_seq = 0 and * the ServerHello will have message_seq = 1" */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) { if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) ssl->handshake->out_msg_seq = 1; else ssl->handshake->in_msg_seq = 1; } #endif ssl->state = MBEDTLS_SSL_HELLO_REQUEST; ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS; if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= renegotiate" ) ); return( 0 ); } /** * \brief Initiate an SSL renegotiation on the running connection. * Client: perform the renegotiation right now. * Server: request renegotiation, which will be performed * during the next call to mbedtls_ssl_read() if honored by * client. * * \param ssl SSL context * * \return 0 if successful, or any mbedtls_ssl_handshake() return * value except #MBEDTLS_ERR_SSL_CLIENT_RECONNECT that can't * happen during a renegotiation. * * \warning If this function returns something other than \c 0, * #MBEDTLS_ERR_SSL_WANT_READ, #MBEDTLS_ERR_SSL_WANT_WRITE, * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS, you must stop using * the SSL context for reading or writing, and either free it * or call \c mbedtls_ssl_session_reset() on it before * re-using it for a new connection; the current connection * must be closed. * */ int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); #if defined(MBEDTLS_SSL_SRV_C) /* On server, just send the request */ if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) { if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING; /* Did we already try/start sending HelloRequest? */ if( ssl->out_left != 0 ) return( mbedtls_ssl_flush_output( ssl ) ); return( ssl_write_hello_request( ssl ) ); } #endif /* MBEDTLS_SSL_SRV_C */ #if defined(MBEDTLS_SSL_CLI_C) /* * On client, either start the renegotiation process or, * if already in progress, continue the handshake */ if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( ( ret = mbedtls_ssl_start_renegotiation( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_start_renegotiation", ret ); return( ret ); } } else { if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret ); return( ret ); } } #endif /* MBEDTLS_SSL_CLI_C */ return( ret ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ #if defined(MBEDTLS_X509_CRT_PARSE_C) void mbedtls_ssl_key_cert_free( mbedtls_ssl_key_cert *key_cert ) { mbedtls_ssl_key_cert *cur = key_cert, *next; while( cur != NULL ) { next = cur->next; mbedtls_free( cur ); cur = next; } } #endif /* MBEDTLS_X509_CRT_PARSE_C */ /** * \brief Free referenced items in an SSL handshake context and clear * memory * * \param ssl SSL context */ void mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl ) { mbedtls_ssl_handshake_params *handshake = ssl->handshake; if( handshake == NULL ) return; #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) if( ssl->conf->f_async_cancel != NULL && handshake->async_in_progress != 0 ) { ssl->conf->f_async_cancel( ssl ); handshake->async_in_progress = 0; } #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) mbedtls_md5_free( &handshake->fin_md5 ); mbedtls_sha1_free( &handshake->fin_sha1 ); #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) mbedtls_sha256_free( &handshake->fin_sha256 ); #endif #if defined(MBEDTLS_SHA512_C) mbedtls_sha512_free( &handshake->fin_sha512 ); #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_DHM_C) mbedtls_dhm_free( &handshake->dhm_ctx ); #endif #if defined(MBEDTLS_ECDH_C) mbedtls_ecdh_free( &handshake->ecdh_ctx ); #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) mbedtls_ecjpake_free( &handshake->ecjpake_ctx ); #if defined(MBEDTLS_SSL_CLI_C) mbedtls_free( handshake->ecjpake_cache ); handshake->ecjpake_cache = NULL; handshake->ecjpake_cache_len = 0; #endif #endif #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) /* explicit void pointer cast for buggy MS compiler */ mbedtls_free( (void *) handshake->curves ); #endif #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) if( handshake->psk != NULL ) { mbedtls_platform_zeroize( handshake->psk, handshake->psk_len ); mbedtls_free( handshake->psk ); } #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) && \ defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) /* * Free only the linked list wrapper, not the keys themselves * since the belong to the SNI callback */ if( handshake->sni_key_cert != NULL ) { mbedtls_ssl_key_cert *cur = handshake->sni_key_cert, *next; while( cur != NULL ) { next = cur->next; mbedtls_free( cur ); cur = next; } } #endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) mbedtls_x509_crt_restart_free( &handshake->ecrs_ctx ); if( handshake->ecrs_peer_cert != NULL ) { mbedtls_x509_crt_free( handshake->ecrs_peer_cert ); mbedtls_free( handshake->ecrs_peer_cert ); } #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) && \ !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) mbedtls_pk_free( &handshake->peer_pubkey ); #endif /* MBEDTLS_X509_CRT_PARSE_C && !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ #if defined(MBEDTLS_SSL_PROTO_DTLS) mbedtls_free( handshake->verify_cookie ); mbedtls_ssl_flight_free( handshake->flight ); mbedtls_ssl_buffering_free( ssl ); #endif mbedtls_platform_zeroize( handshake, sizeof( mbedtls_ssl_handshake_params ) ); #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) /* If the buffers are too big - reallocate. Because of the way Mbed TLS * processes datagrams and the fact that a datagram is allowed to have * several records in it, it is possible that the I/O buffers are not * empty at this stage */ handle_buffer_resizing( ssl, 1, mbedtls_ssl_get_input_buflen( ssl ), mbedtls_ssl_get_output_buflen( ssl ) ); #endif } /** * \brief Free referenced items in an SSL session including the * peer certificate and clear memory * * \note A session object can be freed even if the SSL context * that was used to retrieve the session is still in use. * * \param session SSL session */ void mbedtls_ssl_session_free( mbedtls_ssl_session *session ) { if( session == NULL ) return; #if defined(MBEDTLS_X509_CRT_PARSE_C) ssl_clear_peer_cert( session ); #endif #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C) mbedtls_free( session->ticket ); #endif mbedtls_platform_zeroize( session, sizeof( mbedtls_ssl_session ) ); } #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION) #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID 1u #else #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID 0u #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT 1u #else #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT 0u #endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */ #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY 1u #else #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY 0u #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */ #if defined(MBEDTLS_SSL_ALPN) #define SSL_SERIALIZED_CONTEXT_CONFIG_ALPN 1u #else #define SSL_SERIALIZED_CONTEXT_CONFIG_ALPN 0u #endif /* MBEDTLS_SSL_ALPN */ #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID_BIT 0 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT_BIT 1 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY_BIT 2 #define SSL_SERIALIZED_CONTEXT_CONFIG_ALPN_BIT 3 #define SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG \ ( (uint32_t) ( \ ( SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID << SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID_BIT ) | \ ( SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT << SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT_BIT ) | \ ( SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY << SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY_BIT ) | \ ( SSL_SERIALIZED_CONTEXT_CONFIG_ALPN << SSL_SERIALIZED_CONTEXT_CONFIG_ALPN_BIT ) | \ 0u ) ) static unsigned char ssl_serialized_context_header[] = { MBEDTLS_VERSION_MAJOR, MBEDTLS_VERSION_MINOR, MBEDTLS_VERSION_PATCH, ( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG >> 8 ) & 0xFF, ( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG >> 0 ) & 0xFF, ( SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG >> 16 ) & 0xFF, ( SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG >> 8 ) & 0xFF, ( SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG >> 0 ) & 0xFF, }; /** * Serialize a full SSL context * * The format of the serialized data is: * (in the presentation language of TLS, RFC 8446 section 3) * * // header * opaque mbedtls_version[3]; // major, minor, patch * opaque context_format[5]; // version-specific field determining * // the format of the remaining * // serialized data. * Note: When updating the format, remember to keep these * version+format bytes. (We may make their size part of the API.) * * // session sub-structure * opaque session<1..2^32-1>; // see mbedtls_ssl_session_save() * // transform sub-structure * uint8 random[64]; // ServerHello.random+ClientHello.random * uint8 in_cid<0..2^8-1> // Connection ID: expected incoming value * uint8 out_cid<0..2^8-1> // Connection ID: outgoing value to use * // fields from ssl_context * uint32 badmac_seen; // DTLS: number of records with failing MAC * uint64 in_window_top; // DTLS: last validated record seq_num * uint64 in_window; // DTLS: bitmask for replay protection * uint8 disable_datagram_packing; // DTLS: only one record per datagram * uint64 cur_out_ctr; // Record layer: outgoing sequence number * uint16 mtu; // DTLS: path mtu (max outgoing fragment size) * uint8 alpn_chosen<0..2^8-1> // ALPN: negotiated application protocol * * Note that many fields of the ssl_context or sub-structures are not * serialized, as they fall in one of the following categories: * * 1. forced value (eg in_left must be 0) * 2. pointer to dynamically-allocated memory (eg session, transform) * 3. value can be re-derived from other data (eg session keys from MS) * 4. value was temporary (eg content of input buffer) * 5. value will be provided by the user again (eg I/O callbacks and context) * * \brief Save an active connection as serialized data in a buffer. * This allows the freeing or re-using of the SSL context * while still picking up the connection later in a way that * it entirely transparent to the peer. * * \see mbedtls_ssl_context_load() * * \note This feature is currently only available under certain * conditions, see the documentation of the return value * #MBEDTLS_ERR_SSL_BAD_INPUT_DATA for details. * * \note When this function succeeds, it calls * mbedtls_ssl_session_reset() on \p ssl which as a result is * no longer associated with the connection that has been * serialized. This avoids creating copies of the connection * state. You're then free to either re-use the context * structure for a different connection, or call * mbedtls_ssl_free() on it. See the documentation of * mbedtls_ssl_session_reset() for more details. * * \param ssl The SSL context to save. On success, it is no longer * associated with the connection that has been serialized. * \param buf The buffer to write the serialized data to. It must be a * writeable buffer of at least \p buf_len bytes, or may be \c * NULL if \p buf_len is \c 0. * \param buf_len The number of bytes available for writing in \p buf. * \param olen The size in bytes of the data that has been or would have * been written. It must point to a valid \c size_t. * * \note \p olen is updated to the correct value regardless of * whether \p buf_len was large enough. This makes it possible * to determine the necessary size by calling this function * with \p buf set to \c NULL and \p buf_len to \c 0. However, * the value of \p olen is only guaranteed to be correct when * the function returns #MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL or * \c 0. If the return value is different, then the value of * \p olen is undefined. * * \return \c 0 if successful. * \return #MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL if \p buf is too small. * \return #MBEDTLS_ERR_SSL_ALLOC_FAILED if memory allocation failed * while reseting the context. * \return #MBEDTLS_ERR_SSL_BAD_INPUT_DATA if a handshake is in * progress, or there is pending data for reading or sending, * or the connection does not use DTLS 1.2 with an AEAD * ciphersuite, or renegotiation is enabled. */ int mbedtls_ssl_context_save( mbedtls_ssl_context *ssl, unsigned char *buf, size_t buf_len, size_t *olen ) { unsigned char *p = buf; size_t used = 0; size_t session_len; int ret = 0; /* * Enforce usage restrictions, see "return BAD_INPUT_DATA" in * this function's documentation. * * These are due to assumptions/limitations in the implementation. Some of * them are likely to stay (no handshake in progress) some might go away * (only DTLS) but are currently used to simplify the implementation. */ /* The initial handshake must be over */ if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Initial handshake isn't over" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } if( ssl->handshake != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Handshake isn't completed" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* Double-check that sub-structures are indeed ready */ if( ssl->transform == NULL || ssl->session == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Serialised structures aren't ready" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* There must be no pending incoming or outgoing data */ if( mbedtls_ssl_check_pending( ssl ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "There is pending incoming data" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } if( ssl->out_left != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "There is pending outgoing data" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* Protocol must be DLTS, not TLS */ if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only DTLS is supported" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* Version must be 1.2 */ if( ssl->major_ver != MBEDTLS_SSL_MAJOR_VERSION_3 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only version 1.2 supported" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only version 1.2 supported" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* We must be using an AEAD ciphersuite */ if( mbedtls_ssl_transform_uses_aead( ssl->transform ) != 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only AEAD ciphersuites supported" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* Renegotiation must not be enabled */ #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->conf->disable_renegotiation != MBEDTLS_SSL_RENEGOTIATION_DISABLED ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Renegotiation must not be enabled" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } #endif /* * Version and format identifier */ used += sizeof( ssl_serialized_context_header ); if( used <= buf_len ) { p = mempcpy( p, ssl_serialized_context_header, sizeof( ssl_serialized_context_header ) ); } /* * Session (length + data) */ ret = ssl_session_save( ssl->session, 1, NULL, 0, &session_len ); if( ret != MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ) return( ret ); used += 4 + session_len; if( used <= buf_len ) { p = Write32be(p, session_len); ret = ssl_session_save( ssl->session, 1, p, session_len, &session_len ); if( ret != 0 ) return( ret ); p += session_len; } /* * Transform */ used += sizeof( ssl->transform->randbytes ); if( used <= buf_len ) { memcpy( p, ssl->transform->randbytes, sizeof( ssl->transform->randbytes ) ); p += sizeof( ssl->transform->randbytes ); } #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) used += 2 + ssl->transform->in_cid_len + ssl->transform->out_cid_len; if( used <= buf_len ) { *p++ = ssl->transform->in_cid_len; memcpy( p, ssl->transform->in_cid, ssl->transform->in_cid_len ); p += ssl->transform->in_cid_len; *p++ = ssl->transform->out_cid_len; memcpy( p, ssl->transform->out_cid, ssl->transform->out_cid_len ); p += ssl->transform->out_cid_len; } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ /* * Saved fields from top-level ssl_context structure */ #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) used += 4; if( used <= buf_len ) { p = Write32be(p, ssl->badmac_seen); } #endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */ #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) used += 16; if( used <= buf_len ) { p = Write64be(p, ssl->in_window_top); p = Write64be(p, ssl->in_window); } #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */ #if defined(MBEDTLS_SSL_PROTO_DTLS) used += 1; if( used <= buf_len ) { *p++ = ssl->disable_datagram_packing; } #endif /* MBEDTLS_SSL_PROTO_DTLS */ used += 8; if( used <= buf_len ) { memcpy( p, ssl->cur_out_ctr, 8 ); p += 8; } #if defined(MBEDTLS_SSL_PROTO_DTLS) used += 2; if( used <= buf_len ) { *p++ = (unsigned char)( ( ssl->mtu >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ssl->mtu ) & 0xFF ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ #if defined(MBEDTLS_SSL_ALPN) { const uint8_t alpn_len = ssl->alpn_chosen ? (uint8_t) strlen( ssl->alpn_chosen ) : 0; used += 1 + alpn_len; if( used <= buf_len ) { *p++ = alpn_len; if( ssl->alpn_chosen != NULL ) { memcpy( p, ssl->alpn_chosen, alpn_len ); p += alpn_len; } } } #endif /* MBEDTLS_SSL_ALPN */ /* * Done */ *olen = used; if( used > buf_len ) return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); MBEDTLS_SSL_DEBUG_BUF( 4, "saved context", buf, used ); return( mbedtls_ssl_session_reset_int( ssl, 0 ) ); } /* * Helper to get TLS 1.2 PRF from ciphersuite * (Duplicates bits of logic from ssl_set_handshake_prfs().) */ typedef int (*tls_prf_fn)( const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ); static tls_prf_fn ssl_tls12prf_from_cs( int ciphersuite_id ) { #if defined(MBEDTLS_SHA512_C) const mbedtls_ssl_ciphersuite_t * const ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuite_id ); if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 ) return( tls_prf_sha384 ); #else (void) ciphersuite_id; #endif return( tls_prf_sha256 ); } /* * Deserialize context, see mbedtls_ssl_context_save() for format. * * This internal version is wrapped by a public function that cleans up in * case of error. */ static int ssl_context_load( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { const unsigned char *p = buf; const unsigned char * const end = buf + len; size_t session_len; int ret = MBEDTLS_ERR_THIS_CORRUPTION; /* * The context should have been freshly setup or reset. * Give the user an error in case of obvious misuse. * (Checking session is useful because it won't be NULL if we're * renegotiating, or if the user mistakenly loaded a session first.) */ if( ssl->state != MBEDTLS_SSL_HELLO_REQUEST || ssl->session != NULL ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* * We can't check that the config matches the initial one, but we can at * least check it matches the requirements for serializing. */ if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM || ssl->conf->max_major_ver < MBEDTLS_SSL_MAJOR_VERSION_3 || ssl->conf->min_major_ver > MBEDTLS_SSL_MAJOR_VERSION_3 || ssl->conf->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 || ssl->conf->min_minor_ver > MBEDTLS_SSL_MINOR_VERSION_3 || #if defined(MBEDTLS_SSL_RENEGOTIATION) ssl->conf->disable_renegotiation != MBEDTLS_SSL_RENEGOTIATION_DISABLED || #endif 0 ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } MBEDTLS_SSL_DEBUG_BUF( 4, "context to load", buf, len ); /* * Check version identifier */ if( (size_t)( end - p ) < sizeof( ssl_serialized_context_header ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( timingsafe_bcmp( p, ssl_serialized_context_header, sizeof( ssl_serialized_context_header ) ) != 0 ) { return( MBEDTLS_ERR_SSL_VERSION_MISMATCH ); } p += sizeof( ssl_serialized_context_header ); /* * Session */ if( (size_t)( end - p ) < 4 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session_len = ( (size_t) p[0] << 24 ) | ( (size_t) p[1] << 16 ) | ( (size_t) p[2] << 8 ) | ( (size_t) p[3] ); p += 4; /* This has been allocated by ssl_handshake_init(), called by * by either mbedtls_ssl_session_reset_int() or mbedtls_ssl_setup(). */ ssl->session = ssl->session_negotiate; ssl->session_in = ssl->session; ssl->session_out = ssl->session; ssl->session_negotiate = NULL; if( (size_t)( end - p ) < session_len ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ret = ssl_session_load( ssl->session, 1, p, session_len ); if( ret != 0 ) { mbedtls_ssl_session_free( ssl->session ); return( ret ); } p += session_len; /* * Transform */ /* This has been allocated by ssl_handshake_init(), called by * by either mbedtls_ssl_session_reset_int() or mbedtls_ssl_setup(). */ ssl->transform = ssl->transform_negotiate; ssl->transform_in = ssl->transform; ssl->transform_out = ssl->transform; ssl->transform_negotiate = NULL; /* Read random bytes and populate structure */ if( (size_t)( end - p ) < sizeof( ssl->transform->randbytes ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ret = ssl_populate_transform( ssl->transform, ssl->session->ciphersuite, ssl->session->master, #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) ssl->session->encrypt_then_mac, #endif #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) ssl->session->trunc_hmac, #endif #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */ #if defined(MBEDTLS_ZLIB_SUPPORT) ssl->session->compression, #endif ssl_tls12prf_from_cs( ssl->session->ciphersuite ), p, /* currently pointing to randbytes */ MBEDTLS_SSL_MINOR_VERSION_3, /* (D)TLS 1.2 is forced */ ssl->conf->endpoint, ssl ); if( ret != 0 ) return( ret ); p += sizeof( ssl->transform->randbytes ); #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) /* Read connection IDs and store them */ if( (size_t)( end - p ) < 1 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl->transform->in_cid_len = *p++; if( (size_t)( end - p ) < ssl->transform->in_cid_len + 1u ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); memcpy( ssl->transform->in_cid, p, ssl->transform->in_cid_len ); p += ssl->transform->in_cid_len; ssl->transform->out_cid_len = *p++; if( (size_t)( end - p ) < ssl->transform->out_cid_len ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); memcpy( ssl->transform->out_cid, p, ssl->transform->out_cid_len ); p += ssl->transform->out_cid_len; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ /* * Saved fields from top-level ssl_context structure */ #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) if( (size_t)( end - p ) < 4 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl->badmac_seen = ( (uint32_t) p[0] << 24 ) | ( (uint32_t) p[1] << 16 ) | ( (uint32_t) p[2] << 8 ) | ( (uint32_t) p[3] ); p += 4; #endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */ #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) if( (size_t)( end - p ) < 16 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl->in_window_top = ( (uint64_t) p[0] << 56 ) | ( (uint64_t) p[1] << 48 ) | ( (uint64_t) p[2] << 40 ) | ( (uint64_t) p[3] << 32 ) | ( (uint64_t) p[4] << 24 ) | ( (uint64_t) p[5] << 16 ) | ( (uint64_t) p[6] << 8 ) | ( (uint64_t) p[7] ); p += 8; ssl->in_window = ( (uint64_t) p[0] << 56 ) | ( (uint64_t) p[1] << 48 ) | ( (uint64_t) p[2] << 40 ) | ( (uint64_t) p[3] << 32 ) | ( (uint64_t) p[4] << 24 ) | ( (uint64_t) p[5] << 16 ) | ( (uint64_t) p[6] << 8 ) | ( (uint64_t) p[7] ); p += 8; #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( (size_t)( end - p ) < 1 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl->disable_datagram_packing = *p++; #endif /* MBEDTLS_SSL_PROTO_DTLS */ if( (size_t)( end - p ) < 8 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); memcpy( ssl->cur_out_ctr, p, 8 ); p += 8; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( (size_t)( end - p ) < 2 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl->mtu = ( p[0] << 8 ) | p[1]; p += 2; #endif /* MBEDTLS_SSL_PROTO_DTLS */ #if defined(MBEDTLS_SSL_ALPN) { uint8_t alpn_len; const char **cur; if( (size_t)( end - p ) < 1 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); alpn_len = *p++; if( alpn_len != 0 && ssl->conf->alpn_list != NULL ) { /* alpn_chosen should point to an item in the configured list */ for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ ) { if( strlen( *cur ) == alpn_len && timingsafe_bcmp( p, cur, alpn_len ) == 0 ) { ssl->alpn_chosen = *cur; break; } } } /* can only happen on conf mismatch */ if( alpn_len != 0 && ssl->alpn_chosen == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); p += alpn_len; } #endif /* MBEDTLS_SSL_ALPN */ /* * Forced fields from top-level ssl_context structure * * Most of them already set to the correct value by mbedtls_ssl_init() and * mbedtls_ssl_reset(), so we only need to set the remaining ones. */ ssl->state = MBEDTLS_SSL_HANDSHAKE_OVER; ssl->major_ver = MBEDTLS_SSL_MAJOR_VERSION_3; ssl->minor_ver = MBEDTLS_SSL_MINOR_VERSION_3; /* Adjust pointers for header fields of outgoing records to * the given transform, accounting for explicit IV and CID. */ mbedtls_ssl_update_out_pointers( ssl, ssl->transform ); #if defined(MBEDTLS_SSL_PROTO_DTLS) ssl->in_epoch = 1; #endif /* mbedtls_ssl_reset() leaves the handshake sub-structure allocated, * which we don't want - otherwise we'd end up freeing the wrong transform * by calling mbedtls_ssl_handshake_wrapup_free_hs_transform() * inappropriately. */ if( ssl->handshake != NULL ) { mbedtls_ssl_handshake_free( ssl ); mbedtls_free( ssl->handshake ); ssl->handshake = NULL; } /* * Done - should have consumed entire buffer */ if( p != end ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); return( 0 ); } /** * \brief Load serialized connection data to an SSL context. * * \see mbedtls_ssl_context_save() * * \warning The same serialized data must never be loaded into more * that one context. In order to ensure that, after * successfully loading serialized data to an SSL context, you * should immediately destroy or invalidate all copies of the * serialized data that was loaded. Loading the same data in * more than one context would cause severe security failures * including but not limited to loss of confidentiality. * * \note Before calling this function, the SSL context must be * prepared in one of the two following ways. The first way is * to take a context freshly initialised with * mbedtls_ssl_init() and call mbedtls_ssl_setup() on it with * the same ::mbedtls_ssl_config structure that was used in * the original connection. The second way is to * call mbedtls_ssl_session_reset() on a context that was * previously prepared as above but used in the meantime. * Either way, you must not use the context to perform a * handshake between calling mbedtls_ssl_setup() or * mbedtls_ssl_session_reset() and calling this function. You * may however call other setter functions in that time frame * as indicated in the note below. * * \note Before or after calling this function successfully, you * also need to configure some connection-specific callbacks * and settings before you can use the connection again * (unless they were already set before calling * mbedtls_ssl_session_reset() and the values are suitable for * the present connection). Specifically, you want to call * at least mbedtls_ssl_set_bio() and * mbedtls_ssl_set_timer_cb(). All other SSL setter functions * are not necessary to call, either because they're only used * in handshakes, or because the setting is already saved. You * might choose to call them anyway, for example in order to * share code between the cases of establishing a new * connection and the case of loading an already-established * connection. * * \note If you have new information about the path MTU, you want to * call mbedtls_ssl_set_mtu() after calling this function, as * otherwise this function would overwrite your * newly-configured value with the value that was active when * the context was saved. * * \note When this function returns an error code, it calls * mbedtls_ssl_free() on \p ssl. In this case, you need to * prepare the context with the usual sequence starting with a * call to mbedtls_ssl_init() if you want to use it again. * * \param ssl The SSL context structure to be populated. It must have * been prepared as described in the note above. * \param buf The buffer holding the serialized connection data. It must * be a readable buffer of at least \p len bytes. * \param len The size of the serialized data in bytes. * * \return \c 0 if successful. * \return #MBEDTLS_ERR_SSL_ALLOC_FAILED if memory allocation failed. * \return #MBEDTLS_ERR_SSL_VERSION_MISMATCH if the serialized data * comes from a different Mbed TLS version or build. * \return #MBEDTLS_ERR_SSL_BAD_INPUT_DATA if input data is invalid. */ int mbedtls_ssl_context_load( mbedtls_ssl_context *context, const unsigned char *buf, size_t len ) { int ret = ssl_context_load( context, buf, len ); if( ret != 0 ) mbedtls_ssl_free( context ); return( ret ); } #endif /* MBEDTLS_SSL_CONTEXT_SERIALIZATION */ /** * \brief Free referenced items in an SSL context and clear memory * * \param ssl SSL context */ void mbedtls_ssl_free( mbedtls_ssl_context *ssl ) { if( ssl == NULL ) return; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> free" ) ); if( ssl->out_buf != NULL ) { #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) size_t out_buf_len = ssl->out_buf_len; #else size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN; #endif mbedtls_platform_zeroize( ssl->out_buf, out_buf_len ); mbedtls_free( ssl->out_buf ); ssl->out_buf = NULL; } if( ssl->in_buf != NULL ) { #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) size_t in_buf_len = ssl->in_buf_len; #else size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN; #endif mbedtls_platform_zeroize( ssl->in_buf, in_buf_len ); mbedtls_free( ssl->in_buf ); ssl->in_buf = NULL; } #if defined(MBEDTLS_ZLIB_SUPPORT) if( ssl->compress_buf != NULL ) { mbedtls_platform_zeroize( ssl->compress_buf, MBEDTLS_SSL_COMPRESS_BUFFER_LEN ); mbedtls_free( ssl->compress_buf ); } #endif if( ssl->transform ) { mbedtls_ssl_transform_free( ssl->transform ); mbedtls_free( ssl->transform ); } if( ssl->handshake ) { mbedtls_ssl_handshake_free( ssl ); mbedtls_ssl_transform_free( ssl->transform_negotiate ); mbedtls_ssl_session_free( ssl->session_negotiate ); mbedtls_free( ssl->handshake ); mbedtls_free( ssl->transform_negotiate ); mbedtls_free( ssl->session_negotiate ); } if( ssl->session ) { mbedtls_ssl_session_free( ssl->session ); mbedtls_free( ssl->session ); } #if defined(MBEDTLS_X509_CRT_PARSE_C) if( ssl->hostname != NULL ) { mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) ); mbedtls_free( ssl->hostname ); } #endif #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_finish != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_finish()" ) ); mbedtls_ssl_hw_record_finish( ssl ); } #endif #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) mbedtls_free( ssl->cli_id ); #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= free" ) ); /* Actually clear after last debug message */ mbedtls_platform_zeroize( ssl, sizeof( mbedtls_ssl_context ) ); } /** * \brief Initialize an SSL configuration context * Just makes the context ready for * mbedtls_ssl_config_defaults() or mbedtls_ssl_config_free(). * * \note You need to call mbedtls_ssl_config_defaults() unless you * manually set all of the relevant fields yourself. * * \param conf SSL configuration context */ void mbedtls_ssl_config_init( mbedtls_ssl_config *conf ) { mbedtls_platform_zeroize( conf, sizeof( mbedtls_ssl_config ) ); } #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) static uint8_t ssl_preset_default_hashes[] = { #if defined(MBEDTLS_SHA512_C) MBEDTLS_MD_SHA512, MBEDTLS_MD_SHA384, #endif #if defined(MBEDTLS_SHA256_C) MBEDTLS_MD_SHA256, MBEDTLS_MD_SHA224, #endif #if defined(MBEDTLS_SHA1_C) && defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE) MBEDTLS_MD_SHA1, #endif MBEDTLS_MD_NONE }; #endif static uint16_t ssl_preset_suiteb_ciphersuites[] = { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384, 0 }; #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) static uint8_t ssl_preset_suiteb_hashes[] = { MBEDTLS_MD_SHA384, MBEDTLS_MD_NONE }; #endif #if defined(MBEDTLS_ECP_C) static mbedtls_ecp_group_id ssl_preset_suiteb_curves[] = { #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) MBEDTLS_ECP_DP_SECP384R1, #endif #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) MBEDTLS_ECP_DP_SECP256R1, #endif MBEDTLS_ECP_DP_NONE }; #endif /* * Load default in mbedtls_ssl_config */ int mbedtls_ssl_config_defaults_impl( mbedtls_ssl_config *conf, int endpoint, int transport, int preset, int ssl_handshake_step(mbedtls_ssl_context *) ) { #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C) int ret = MBEDTLS_ERR_THIS_CORRUPTION; #endif conf->f_step = ssl_handshake_step; /* Use the functions here so that they are covered in tests, * but otherwise access member directly for efficiency */ mbedtls_ssl_conf_endpoint( conf, endpoint ); mbedtls_ssl_conf_transport( conf, transport ); /* * Things that are common to all presets */ #if defined(MBEDTLS_SSL_CLI_C) if( endpoint == MBEDTLS_SSL_IS_CLIENT ) { conf->authmode = MBEDTLS_SSL_VERIFY_REQUIRED; #if defined(MBEDTLS_SSL_SESSION_TICKETS) conf->session_tickets = MBEDTLS_SSL_SESSION_TICKETS_ENABLED; #endif } #endif #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) conf->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED; #endif #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) conf->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED; #endif #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) conf->cbc_record_splitting = MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED; #endif #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) conf->f_cookie_write = ssl_cookie_write_dummy; conf->f_cookie_check = ssl_cookie_check_dummy; #endif #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) conf->anti_replay = MBEDTLS_SSL_ANTI_REPLAY_ENABLED; #endif #if defined(MBEDTLS_SSL_SRV_C) conf->cert_req_ca_list = MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED; #endif #if defined(MBEDTLS_SSL_PROTO_DTLS) conf->hs_timeout_min = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN; conf->hs_timeout_max = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX; #endif #if defined(MBEDTLS_SSL_RENEGOTIATION) conf->renego_max_records = MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT; memset( conf->renego_period, 0x00, 2 ); memset( conf->renego_period + 2, 0xFF, 6 ); #endif #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C) if( endpoint == MBEDTLS_SSL_IS_SERVER ) { const unsigned char dhm_p[] = MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN; const unsigned char dhm_g[] = MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN; if ( ( ret = mbedtls_ssl_conf_dh_param_bin( conf, dhm_p, sizeof( dhm_p ), dhm_g, sizeof( dhm_g ) ) ) != 0 ) { return( ret ); } } #endif /* * Preset-specific defaults */ switch( preset ) { /* * NSA Suite B */ case MBEDTLS_SSL_PRESET_SUITEB: conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3; conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */ conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION; conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION; conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = ssl_preset_suiteb_ciphersuites; #if defined(MBEDTLS_X509_CRT_PARSE_C) conf->cert_profile = &mbedtls_x509_crt_profile_suiteb; #endif #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) conf->sig_hashes = ssl_preset_suiteb_hashes; #endif #if defined(MBEDTLS_ECP_C) conf->curve_list = ssl_preset_suiteb_curves; #endif break; /* * Default */ default: conf->min_major_ver = ( MBEDTLS_SSL_MIN_MAJOR_VERSION > MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION ) ? MBEDTLS_SSL_MIN_MAJOR_VERSION : MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION; conf->min_minor_ver = ( MBEDTLS_SSL_MIN_MINOR_VERSION > MBEDTLS_SSL_MIN_VALID_MINOR_VERSION ) ? MBEDTLS_SSL_MIN_MINOR_VERSION : MBEDTLS_SSL_MIN_VALID_MINOR_VERSION; conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION; conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_2; #endif conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = mbedtls_ssl_list_ciphersuites(); #if defined(MBEDTLS_X509_CRT_PARSE_C) conf->cert_profile = &mbedtls_x509_crt_profile_default; #endif #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) conf->sig_hashes = ssl_preset_default_hashes; #endif #if defined(MBEDTLS_ECP_C) conf->curve_list = mbedtls_ecp_grp_id_list(); #endif #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C) conf->dhm_min_bitlen = 1024; #endif } return( 0 ); } /** * \brief Free an SSL configuration context * * \param conf SSL configuration context */ void mbedtls_ssl_config_free( mbedtls_ssl_config *conf ) { #if defined(MBEDTLS_DHM_C) mbedtls_mpi_free( &conf->dhm_P ); mbedtls_mpi_free( &conf->dhm_G ); #endif #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) if( conf->psk != NULL ) { mbedtls_platform_zeroize( conf->psk, conf->psk_len ); mbedtls_free( conf->psk ); conf->psk = NULL; conf->psk_len = 0; } if( conf->psk_identity != NULL ) { mbedtls_platform_zeroize( conf->psk_identity, conf->psk_identity_len ); mbedtls_free( conf->psk_identity ); conf->psk_identity = NULL; conf->psk_identity_len = 0; } #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) mbedtls_ssl_key_cert_free( conf->key_cert ); #endif mbedtls_platform_zeroize( conf, sizeof( mbedtls_ssl_config ) ); } int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl, unsigned char *hash, size_t *hashlen, unsigned char *data, size_t data_len, mbedtls_md_type_t md_alg ) { int ret = 0; mbedtls_md_context_t ctx; const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg ); *hashlen = mbedtls_md_get_size( md_info ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "Perform mbedtls-based computation of digest of ServerKeyExchange" ) ); mbedtls_md_init( &ctx ); /* * digitally-signed struct { * opaque client_random[32]; * opaque server_random[32]; * ServerDHParams params; * }; */ if( ( ret = mbedtls_md_setup( &ctx, md_info, 0 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret ); goto exit; } if( ( ret = mbedtls_md_starts( &ctx ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_starts", ret ); goto exit; } if( ( ret = mbedtls_md_update( &ctx, ssl->handshake->randbytes, 64 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret ); goto exit; } if( ( ret = mbedtls_md_update( &ctx, data, data_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret ); goto exit; } if( ( ret = mbedtls_md_finish( &ctx, hash ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_finish", ret ); goto exit; } exit: mbedtls_md_free( &ctx ); if( ret != 0 ) mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( ret ); } #if defined(MBEDTLS_PK_C) && \ ( defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) ) /* * Convert between MBEDTLS_PK_XXX and SSL_SIG_XXX */ unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk ) { #if defined(MBEDTLS_RSA_C) if( mbedtls_pk_can_do( pk, MBEDTLS_PK_RSA ) ) return( MBEDTLS_SSL_SIG_RSA ); #endif #if defined(MBEDTLS_ECDSA_C) if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECDSA ) ) return( MBEDTLS_SSL_SIG_ECDSA ); #endif return( MBEDTLS_SSL_SIG_ANON ); } unsigned char mbedtls_ssl_sig_from_pk_alg( mbedtls_pk_type_t type ) { switch( type ) { case MBEDTLS_PK_RSA: return( MBEDTLS_SSL_SIG_RSA ); case MBEDTLS_PK_ECDSA: case MBEDTLS_PK_ECKEY: return( MBEDTLS_SSL_SIG_ECDSA ); default: return( MBEDTLS_SSL_SIG_ANON ); } } #endif /* MBEDTLS_PK_C && ( MBEDTLS_RSA_C || MBEDTLS_ECDSA_C ) */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /* Find an entry in a signature-hash set matching a given hash algorithm. */ mbedtls_md_type_t mbedtls_ssl_sig_hash_set_find( mbedtls_ssl_sig_hash_set_t *set, mbedtls_pk_type_t sig_alg ) { switch( sig_alg ) { case MBEDTLS_PK_RSA: return( set->rsa ); case MBEDTLS_PK_ECDSA: return( set->ecdsa ); default: return( MBEDTLS_MD_NONE ); } } /* Allow exactly one hash algorithm for each signature. */ void mbedtls_ssl_sig_hash_set_const_hash( mbedtls_ssl_sig_hash_set_t *set, mbedtls_md_type_t md_alg ) { set->rsa = md_alg; set->ecdsa = md_alg; } #endif /* MBEDTLS_SSL_PROTO_TLS1_2) && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ /* * Convert from MBEDTLS_MD_XXX to MBEDTLS_SSL_HASH_XXX */ unsigned char mbedtls_ssl_hash_from_md_alg( int md ) { switch( md ) { #if defined(MBEDTLS_MD5_C) case MBEDTLS_MD_MD5: return( MBEDTLS_SSL_HASH_MD5 ); #endif #if defined(MBEDTLS_SHA1_C) case MBEDTLS_MD_SHA1: return( MBEDTLS_SSL_HASH_SHA1 ); #endif #if defined(MBEDTLS_SHA256_C) case MBEDTLS_MD_SHA224: return( MBEDTLS_SSL_HASH_SHA224 ); case MBEDTLS_MD_SHA256: return( MBEDTLS_SSL_HASH_SHA256 ); #endif #if defined(MBEDTLS_SHA512_C) case MBEDTLS_MD_SHA384: return( MBEDTLS_SSL_HASH_SHA384 ); case MBEDTLS_MD_SHA512: return( MBEDTLS_SSL_HASH_SHA512 ); #endif default: return( MBEDTLS_SSL_HASH_NONE ); } } #if defined(MBEDTLS_ECP_C) /* * Check if a curve proposed by the peer is in our list. * Return 0 if we're willing to use it, -1 otherwise. */ int mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id ) { const mbedtls_ecp_group_id *gid; if( ssl->conf->curve_list == NULL ) return( -1 ); for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ ) if( *gid == grp_id ) return( 0 ); return( -1 ); } #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /* * Check if a hash proposed by the peer is in our list. * Return 0 if we're willing to use it, -1 otherwise. */ int mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl, mbedtls_md_type_t md ) { const uint8_t *cur; if( ssl->conf->sig_hashes == NULL ) return( -1 ); for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ ) if( *cur == (int) md ) return( 0 ); return( -1 ); } #endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ #if defined(MBEDTLS_X509_CRT_PARSE_C) int mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert, const mbedtls_ssl_ciphersuite_t *ciphersuite, int cert_endpoint, uint32_t *flags ) { int ret = 0; #if defined(MBEDTLS_X509_CHECK_KEY_USAGE) int usage = 0; #endif #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) const char *ext_oid; size_t ext_len; #endif #if !defined(MBEDTLS_X509_CHECK_KEY_USAGE) && \ !defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) ((void) cert); ((void) cert_endpoint); ((void) flags); #endif #if defined(MBEDTLS_X509_CHECK_KEY_USAGE) if( cert_endpoint == MBEDTLS_SSL_IS_SERVER ) { /* Server part of the key exchange */ switch( ciphersuite->key_exchange ) { case MBEDTLS_KEY_EXCHANGE_RSA: case MBEDTLS_KEY_EXCHANGE_RSA_PSK: usage = MBEDTLS_X509_KU_KEY_ENCIPHERMENT; break; case MBEDTLS_KEY_EXCHANGE_DHE_RSA: case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA: case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA: usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE; break; case MBEDTLS_KEY_EXCHANGE_ECDH_RSA: case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA: usage = MBEDTLS_X509_KU_KEY_AGREEMENT; break; /* Don't use default: we want warnings when adding new values */ case MBEDTLS_KEY_EXCHANGE_NONE: case MBEDTLS_KEY_EXCHANGE_PSK: case MBEDTLS_KEY_EXCHANGE_DHE_PSK: case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK: case MBEDTLS_KEY_EXCHANGE_ECJPAKE: usage = 0; } } else { /* Client auth: we only implement rsa_sign and mbedtls_ecdsa_sign for now */ usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE; } if( mbedtls_x509_crt_check_key_usage( cert, usage ) != 0 ) { *flags |= MBEDTLS_X509_BADCERT_KEY_USAGE; ret = -1; } #else ((void) ciphersuite); #endif /* MBEDTLS_X509_CHECK_KEY_USAGE */ #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) if( cert_endpoint == MBEDTLS_SSL_IS_SERVER ) { ext_oid = MBEDTLS_OID_SERVER_AUTH; ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_SERVER_AUTH ); } else { ext_oid = MBEDTLS_OID_CLIENT_AUTH; ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_CLIENT_AUTH ); } if( mbedtls_x509_crt_check_extended_key_usage( cert, ext_oid, ext_len ) != 0 ) { *flags |= MBEDTLS_X509_BADCERT_EXT_KEY_USAGE; ret = -1; } #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */ return( ret ); } #endif /* MBEDTLS_X509_CRT_PARSE_C */ int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md ) { #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 ) return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH; switch( md ) { #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) #if defined(MBEDTLS_MD5_C) case MBEDTLS_SSL_HASH_MD5: return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH; #endif #if defined(MBEDTLS_SHA1_C) case MBEDTLS_SSL_HASH_SHA1: ssl->handshake->calc_verify = ssl_calc_verify_tls; break; #endif #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SHA512_C) case MBEDTLS_SSL_HASH_SHA384: ssl->handshake->calc_verify = ssl_calc_verify_tls_sha384; break; #endif #if defined(MBEDTLS_SHA256_C) case MBEDTLS_SSL_HASH_SHA256: ssl->handshake->calc_verify = ssl_calc_verify_tls_sha256; break; #endif default: return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH; } return 0; #else /* !MBEDTLS_SSL_PROTO_TLS1_2 */ (void) ssl; (void) md; return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH; #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ } #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) int mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl, unsigned char *output, unsigned char *data, size_t data_len ) { int ret = 0; mbedtls_md5_context mbedtls_md5; mbedtls_sha1_context mbedtls_sha1; mbedtls_md5_init( &mbedtls_md5 ); mbedtls_sha1_init( &mbedtls_sha1 ); /* * digitally-signed struct { * opaque md5_hash[16]; * opaque sha_hash[20]; * }; * * md5_hash * MD5(ClientHello.random + ServerHello.random * + ServerParams); * sha_hash * SHA(ClientHello.random + ServerHello.random * + ServerParams); */ if( ( ret = mbedtls_md5_starts_ret( &mbedtls_md5 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_starts_ret", ret ); goto exit; } if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5, ssl->handshake->randbytes, 64 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_update_ret", ret ); goto exit; } if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5, data, data_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_update_ret", ret ); goto exit; } if( ( ret = mbedtls_md5_finish_ret( &mbedtls_md5, output ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_finish_ret", ret ); goto exit; } if( ( ret = mbedtls_sha1_starts_ret( &mbedtls_sha1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_starts_ret", ret ); goto exit; } if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1, ssl->handshake->randbytes, 64 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_update_ret", ret ); goto exit; } if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1, data, data_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_update_ret", ret ); goto exit; } if( ( ret = mbedtls_sha1_finish_ret( &mbedtls_sha1, output + 16 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_finish_ret", ret ); goto exit; } exit: mbedtls_md5_free( &mbedtls_md5 ); mbedtls_sha1_free( &mbedtls_sha1 ); if( ret != 0 ) mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( ret ); } #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \ MBEDTLS_SSL_PROTO_TLS1_1 */ #endif /* MBEDTLS_SSL_TLS_C */
307,671
8,183
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/md.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/stdio/stdio.h" #include "libc/str/blake2.h" #include "libc/str/str.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/md.h" #include "third_party/mbedtls/md5.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/sha1.h" #include "third_party/mbedtls/sha256.h" #include "third_party/mbedtls/sha512.h" /* clang-format off */ asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /** * \file md.c * * \brief Generic message digest wrapper for mbed TLS * * \author Adriaan de Jong <[email protected]> * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(MBEDTLS_MD_C) #define CHECK(f) \ do \ { \ if( ( ret = (f) ) ) \ goto cleanup; \ } while( 0 ) /* * Reminder: update profiles in x509_crt.c when adding a new hash! */ static const uint8_t supported_digests[] = { MBEDTLS_MD_BLAKE2B256, #if defined(MBEDTLS_SHA512_C) MBEDTLS_MD_SHA512, #if !defined(MBEDTLS_SHA512_NO_SHA384) MBEDTLS_MD_SHA384, #endif #endif #if defined(MBEDTLS_SHA256_C) MBEDTLS_MD_SHA256, MBEDTLS_MD_SHA224, #endif #if defined(MBEDTLS_SHA1_C) MBEDTLS_MD_SHA1, #endif #if defined(MBEDTLS_MD5_C) MBEDTLS_MD_MD5, #endif #if defined(MBEDTLS_MD4_C) MBEDTLS_MD_MD4, #endif #if defined(MBEDTLS_MD2_C) MBEDTLS_MD_MD2, #endif MBEDTLS_MD_NONE }; /** * \brief This function returns the list of digests supported by the * generic digest module. * * \note The list starts with the strongest available hashes. * * \return A statically allocated array of digests. Each element * in the returned list is an integer belonging to the * message-digest enumeration #mbedtls_md_type_t. * The last entry is 0. */ const uint8_t *mbedtls_md_list( void ) { return( supported_digests ); } /** * \brief This function returns the message-digest information * associated with the given digest name. * * \param md_name The name of the digest to search for. * * \return The message-digest information associated with \p md_name. * \return NULL if the associated message-digest information is not found. */ const mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name ) { if( NULL == md_name ) return( NULL ); /* Get the appropriate digest information */ #if defined(MBEDTLS_MD2_C) if( !strcasecmp( "MD2", md_name ) ) return mbedtls_md_info_from_type( MBEDTLS_MD_MD2 ); #endif #if defined(MBEDTLS_MD4_C) if( !strcasecmp( "MD4", md_name ) ) return mbedtls_md_info_from_type( MBEDTLS_MD_MD4 ); #endif #if defined(MBEDTLS_MD5_C) if( !strcasecmp( "MD5", md_name ) ) return mbedtls_md_info_from_type( MBEDTLS_MD_MD5 ); #endif #if defined(MBEDTLS_SHA1_C) if( !strcasecmp( "SHA1", md_name ) || !strcasecmp( "SHA", md_name ) ) return mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ); #endif #if defined(MBEDTLS_SHA256_C) if( !strcasecmp( "SHA224", md_name ) ) return mbedtls_md_info_from_type( MBEDTLS_MD_SHA224 ); if( !strcasecmp( "SHA256", md_name ) ) return mbedtls_md_info_from_type( MBEDTLS_MD_SHA256 ); #endif #if defined(MBEDTLS_SHA512_C) #if !defined(MBEDTLS_SHA512_NO_SHA384) if( !strcasecmp( "SHA384", md_name ) ) return mbedtls_md_info_from_type( MBEDTLS_MD_SHA384 ); #endif if( !strcasecmp( "SHA512", md_name ) ) return mbedtls_md_info_from_type( MBEDTLS_MD_SHA512 ); #endif if( !strcasecmp( "BLAKE2B256", md_name ) ) return mbedtls_md_info_from_type( MBEDTLS_MD_BLAKE2B256 ); return( NULL ); } /** * \brief This function returns the message-digest information * associated with the given digest type. * * \param md_type The type of digest to search for. * * \return The message-digest information associated with \p md_type. * \return NULL if the associated message-digest information is not found. */ const mbedtls_md_info_t *mbedtls_md_info_from_type( mbedtls_md_type_t md_type ) { switch( md_type ) { #if defined(MBEDTLS_MD2_C) case MBEDTLS_MD_MD2: return( &mbedtls_md2_info ); #endif #if defined(MBEDTLS_MD4_C) case MBEDTLS_MD_MD4: return( &mbedtls_md4_info ); #endif #if defined(MBEDTLS_MD5_C) case MBEDTLS_MD_MD5: return( &mbedtls_md5_info ); #endif #if defined(MBEDTLS_SHA1_C) case MBEDTLS_MD_SHA1: return( &mbedtls_sha1_info ); #endif #if defined(MBEDTLS_SHA256_C) case MBEDTLS_MD_SHA224: return( &mbedtls_sha224_info ); case MBEDTLS_MD_SHA256: return( &mbedtls_sha256_info ); #endif #if defined(MBEDTLS_SHA512_C) #if !defined(MBEDTLS_SHA512_NO_SHA384) case MBEDTLS_MD_SHA384: return( &mbedtls_sha384_info ); #endif case MBEDTLS_MD_SHA512: return( &mbedtls_sha512_info ); #endif case MBEDTLS_MD_BLAKE2B256: return( &mbedtls_blake2b256_info ); default: return( NULL ); } } static int16_t GetMdContextSize(mbedtls_md_type_t t) { switch( t ) { #if defined(MBEDTLS_MD2_C) case MBEDTLS_MD_MD2: return sizeof(mbedtls_md2_context); #endif #if defined(MBEDTLS_MD4_C) case MBEDTLS_MD_MD4: return sizeof(mbedtls_md4_context); #endif #if defined(MBEDTLS_MD5_C) case MBEDTLS_MD_MD5: return sizeof(mbedtls_md5_context); #endif #if defined(MBEDTLS_SHA1_C) case MBEDTLS_MD_SHA1: return sizeof(mbedtls_sha1_context); #endif #if defined(MBEDTLS_SHA256_C) case MBEDTLS_MD_SHA224: case MBEDTLS_MD_SHA256: return sizeof(mbedtls_sha256_context); #endif #if defined(MBEDTLS_SHA512_C) #if !defined(MBEDTLS_SHA512_NO_SHA384) case MBEDTLS_MD_SHA384: #endif case MBEDTLS_MD_SHA512: return sizeof(mbedtls_sha512_context); #endif case MBEDTLS_MD_BLAKE2B256: return sizeof(struct Blake2b); default: return( MBEDTLS_ERR_MD_BAD_INPUT_DATA ); } } /** * \brief This function initializes a message-digest context without * binding it to a particular message-digest algorithm. * * This function should always be called first. It prepares the * context for mbedtls_md_setup() for binding it to a * message-digest algorithm. */ void mbedtls_md_init( mbedtls_md_context_t *ctx ) { mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md_context_t ) ); } /** * \brief This function clears the internal structure of \p ctx and * frees any embedded internal structure, but does not free * \p ctx itself. * * If you have called mbedtls_md_setup() on \p ctx, you must * call mbedtls_md_free() when you are no longer using the * context. * Calling this function if you have previously * called mbedtls_md_init() and nothing else is optional. * You must not call this function if you have not called * mbedtls_md_init(). */ void mbedtls_md_free( mbedtls_md_context_t *ctx ) { int16_t csize; if( !ctx || !ctx->md_info ) return; if( ctx->md_ctx ) { if ( ( csize = GetMdContextSize( ctx->md_info->type ) ) > 0 ) mbedtls_platform_zeroize( ctx->md_ctx, csize ); mbedtls_free( ctx->md_ctx ); } if( ctx->hmac_ctx ) { mbedtls_platform_zeroize( ctx->hmac_ctx, 2 * ctx->md_info->block_size ); mbedtls_free( ctx->hmac_ctx ); } mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md_context_t ) ); } /** * \brief This function clones the state of an message-digest * context. * * \note You must call mbedtls_md_setup() on \c dst before calling * this function. * * \note The two contexts must have the same type, * for example, both are SHA-256. * * \warning This function clones the message-digest state, not the * HMAC state. * * \param dst The destination context. * \param src The context to be cloned. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification failure. */ int mbedtls_md_clone( mbedtls_md_context_t *dst, const mbedtls_md_context_t *src ) { int16_t csize; if( !dst || !dst->md_info || !src || !src->md_info || dst->md_info != src->md_info || ( csize = GetMdContextSize( src->md_info->type ) ) < 0) { return( MBEDTLS_ERR_MD_BAD_INPUT_DATA ); } memcpy( dst->md_ctx, src->md_ctx, csize ); return( 0 ); } #define ALLOC( type ) \ do { \ ctx->md_ctx = mbedtls_calloc( 1, sizeof( mbedtls_##type##_context ) ); \ if( !ctx->md_ctx ) \ return( MBEDTLS_ERR_MD_ALLOC_FAILED ); \ } \ while( 0 ) /** * \brief This function selects the message digest algorithm to use, * and allocates internal structures. * * It should be called after mbedtls_md_init() or * mbedtls_md_free(). Makes it necessary to call * mbedtls_md_free() later. * * \param ctx The context to set up. * \param md_info The information structure of the message-digest algorithm * to use. * \param hmac Defines if HMAC is used. 0: HMAC is not used (saves some memory), * or non-zero: HMAC is used with this context. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. * \return #MBEDTLS_ERR_MD_ALLOC_FAILED on memory-allocation failure. */ int mbedtls_md_setup( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info, int hmac ) { int16_t csize; if( !md_info || !ctx ) return( MBEDTLS_ERR_MD_BAD_INPUT_DATA ); ctx->md_info = md_info; ctx->md_ctx = NULL; ctx->hmac_ctx = NULL; if ((csize = GetMdContextSize(md_info->type)) < 0) return( csize ); if( !( ctx->md_ctx = mbedtls_calloc( 1, csize ) ) ) return( MBEDTLS_ERR_MD_ALLOC_FAILED ); if( hmac ) { ctx->hmac_ctx = mbedtls_calloc( 2, md_info->block_size ); if( !ctx->hmac_ctx ) { mbedtls_md_free( ctx ); return( MBEDTLS_ERR_MD_ALLOC_FAILED ); } } return( 0 ); } /** * \brief This function calculates the message-digest checksum * result of the contents of the provided file. * * The result is calculated as * Output = message_digest(file contents). * * \param md_info The information structure of the message-digest algorithm * to use. * \param path The input file name. * \param output The generic message-digest checksum result. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_FILE_IO_ERROR on an I/O error accessing * the file pointed by \p path. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info was NULL. */ int mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path, unsigned char *output ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; FILE *f; size_t n; mbedtls_md_context_t ctx; unsigned char buf[1024]; if( !md_info ) return( MBEDTLS_ERR_MD_BAD_INPUT_DATA ); if( !( f = fopen( path, "rb" ) ) ) return( MBEDTLS_ERR_MD_FILE_IO_ERROR ); mbedtls_md_init( &ctx ); CHECK( mbedtls_md_setup( &ctx, md_info, 0 ) ); CHECK( mbedtls_md_starts( &ctx ) ); while( ( n = fread( buf, 1, sizeof( buf ), f ) ) > 0 ) CHECK( mbedtls_md_update( &ctx, buf, n ) ); if( ferror( f ) ) ret = MBEDTLS_ERR_MD_FILE_IO_ERROR; else ret = mbedtls_md_finish( &ctx, output ); cleanup: mbedtls_platform_zeroize( buf, sizeof( buf ) ); mbedtls_md_free( &ctx ); fclose( f ); return( ret ); } /** * \brief This function sets the HMAC key and prepares to * authenticate a new message. * * Call this function after mbedtls_md_setup(), to use * the MD context for an HMAC calculation, then call * mbedtls_md_hmac_update() to provide the input data, and * mbedtls_md_hmac_finish() to get the HMAC value. * * \param ctx The message digest context containing an embedded HMAC * context. * \param key The HMAC secret key. * \param keylen The length of the HMAC key in Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. */ int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key, size_t keylen ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char sum[MBEDTLS_MD_MAX_SIZE]; unsigned char *ipad, *opad; size_t i; if( !ctx || !ctx->md_info || !ctx->hmac_ctx ) return( MBEDTLS_ERR_MD_BAD_INPUT_DATA ); if( keylen > (size_t) ctx->md_info->block_size ) { CHECK( mbedtls_md_starts( ctx ) ); CHECK( mbedtls_md_update( ctx, key, keylen ) ); CHECK( mbedtls_md_finish( ctx, sum ) ); keylen = ctx->md_info->size; key = sum; } ipad = (unsigned char *) ctx->hmac_ctx; opad = (unsigned char *) ctx->hmac_ctx + ctx->md_info->block_size; memset( ipad, 0x36, ctx->md_info->block_size ); memset( opad, 0x5C, ctx->md_info->block_size ); for( i = 0; i < keylen; i++ ) { ipad[i] = (unsigned char)( ipad[i] ^ key[i] ); opad[i] = (unsigned char)( opad[i] ^ key[i] ); } CHECK( mbedtls_md_starts( ctx ) ); CHECK( mbedtls_md_update( ctx, ipad, ctx->md_info->block_size ) ); cleanup: mbedtls_platform_zeroize( sum, sizeof( sum ) ); return( ret ); } /** * \brief This function finishes the HMAC operation, and writes * the result to the output buffer. * * Call this function after mbedtls_md_hmac_starts() and * mbedtls_md_hmac_update() to get the HMAC value. Afterwards * you may either call mbedtls_md_free() to clear the context, * or call mbedtls_md_hmac_reset() to reuse the context with * the same HMAC key. * * \param ctx The message digest context containing an embedded HMAC * context. * \param output The generic HMAC checksum result. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. */ int mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char tmp[MBEDTLS_MD_MAX_SIZE]; unsigned char *opad; if( !ctx || !ctx->md_info || !ctx->hmac_ctx ) return( MBEDTLS_ERR_MD_BAD_INPUT_DATA ); opad = (unsigned char *) ctx->hmac_ctx + ctx->md_info->block_size; CHECK( mbedtls_md_finish( ctx, tmp ) ); CHECK( mbedtls_md_starts( ctx ) ); CHECK( mbedtls_md_update( ctx, opad, ctx->md_info->block_size ) ); CHECK( mbedtls_md_update( ctx, tmp, ctx->md_info->size ) ); return( mbedtls_md_finish( ctx, output ) ); cleanup: return( ret ); } /** * \brief This function prepares to authenticate a new message with * the same key as the previous HMAC operation. * * You may call this function after mbedtls_md_hmac_finish(). * Afterwards call mbedtls_md_hmac_update() to pass the new * input. * * \param ctx The message digest context containing an embedded HMAC * context. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. */ int mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char *ipad; if( !ctx || !ctx->md_info || !ctx->hmac_ctx ) return( MBEDTLS_ERR_MD_BAD_INPUT_DATA ); ipad = (unsigned char *) ctx->hmac_ctx; if( ( ret = mbedtls_md_starts( ctx ) ) ) return( ret ); return( mbedtls_md_update( ctx, ipad, ctx->md_info->block_size ) ); } /** * \brief This function calculates the full generic HMAC * on the input buffer with the provided key. * * The function allocates the context, performs the * calculation, and frees the context. * * The HMAC result is calculated as * output = generic HMAC(hmac key, input buffer). * * \param md_info The information structure of the message-digest algorithm * to use. * \param key The HMAC secret key. * \param keylen The length of the HMAC secret key in Bytes. * \param input The buffer holding the input data. * \param ilen The length of the input data. * \param output The generic HMAC result. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. */ int mbedtls_md_hmac( const mbedtls_md_info_t *md_info, const unsigned char *key, size_t keylen, const unsigned char *input, size_t ilen, unsigned char *output ) { mbedtls_md_context_t ctx; int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( !md_info ) return( MBEDTLS_ERR_MD_BAD_INPUT_DATA ); mbedtls_md_init( &ctx ); CHECK( mbedtls_md_setup( &ctx, md_info, 1 ) ); CHECK( mbedtls_md_hmac_starts( &ctx, key, keylen ) ); CHECK( mbedtls_md_hmac_update( &ctx, input, ilen ) ); CHECK( mbedtls_md_hmac_finish( &ctx, output ) ); cleanup: mbedtls_md_free( &ctx ); return( ret ); } #if defined(MBEDTLS_MD2_C) const mbedtls_md_info_t mbedtls_md2_info = { "MD2", MBEDTLS_MD_MD2, 16, 16, }; #endif #if defined(MBEDTLS_MD4_C) const mbedtls_md_info_t mbedtls_md4_info = { "MD4", MBEDTLS_MD_MD4, 16, 64, }; #endif #endif /* MBEDTLS_MD_C */
21,429
601
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/mbedtls.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ PKGS += THIRD_PARTY_MBEDTLS THIRD_PARTY_MBEDTLS_ARTIFACTS += THIRD_PARTY_MBEDTLS_A THIRD_PARTY_MBEDTLS = $(THIRD_PARTY_MBEDTLS_A_DEPS) $(THIRD_PARTY_MBEDTLS_A) THIRD_PARTY_MBEDTLS_A = o/$(MODE)/third_party/mbedtls/mbedtls.a THIRD_PARTY_MBEDTLS_A_FILES := $(wildcard third_party/mbedtls/*) THIRD_PARTY_MBEDTLS_A_INCS = $(filter %.inc,$(THIRD_PARTY_MBEDTLS_A_FILES)) THIRD_PARTY_MBEDTLS_A_HDRS = $(filter %.h,$(THIRD_PARTY_MBEDTLS_A_FILES)) THIRD_PARTY_MBEDTLS_A_SRCS = $(filter %.c,$(THIRD_PARTY_MBEDTLS_A_FILES)) THIRD_PARTY_MBEDTLS_A_OBJS = $(THIRD_PARTY_MBEDTLS_A_SRCS:%.c=o/$(MODE)/%.o) THIRD_PARTY_MBEDTLS_A_CHECKS = \ $(THIRD_PARTY_MBEDTLS_A).pkg \ $(THIRD_PARTY_MBEDTLS_A_HDRS:%=o/$(MODE)/%.ok) THIRD_PARTY_MBEDTLS_A_DIRECTDEPS = \ LIBC_CALLS \ LIBC_DNS \ LIBC_FMT \ LIBC_INTRIN \ LIBC_MEM \ LIBC_NEXGEN32E \ LIBC_RUNTIME \ LIBC_SOCK \ LIBC_LOG \ LIBC_STDIO \ LIBC_STR \ LIBC_SYSV \ LIBC_TIME \ NET_HTTP \ THIRD_PARTY_COMPILER_RT \ THIRD_PARTY_GDTOA \ THIRD_PARTY_ZLIB THIRD_PARTY_MBEDTLS_A_DEPS := \ $(call uniq,$(foreach x,$(THIRD_PARTY_MBEDTLS_A_DIRECTDEPS),$($(x)))) $(THIRD_PARTY_MBEDTLS_A): \ third_party/mbedtls/ \ $(THIRD_PARTY_MBEDTLS_A).pkg \ $(THIRD_PARTY_MBEDTLS_A_OBJS) $(THIRD_PARTY_MBEDTLS_A).pkg: \ $(THIRD_PARTY_MBEDTLS_A_OBJS) \ $(foreach x,$(THIRD_PARTY_MBEDTLS_A_DIRECTDEPS),$($(x)_A).pkg) $(THIRD_PARTY_MBEDTLS_A_OBJS): private \ OVERRIDE_CFLAGS += \ -fdata-sections \ -ffunction-sections o/$(MODE)/third_party/mbedtls/everest.o: private \ OVERRIDE_CFLAGS += \ -O3 o/$(MODE)/third_party/mbedtls/bigmul4.o \ o/$(MODE)/third_party/mbedtls/bigmul6.o: private \ OVERRIDE_CFLAGS += \ -O2 ifeq ($(ARCH), x86_64) o/$(MODE)/third_party/mbedtls/shiftright-avx.o: private \ OVERRIDE_CFLAGS += \ -O3 -mavx endif o/$(MODE)/third_party/mbedtls/zeroize.o: private \ OVERRIDE_CFLAGS += \ -O3 \ -x-no-pg \ -fomit-frame-pointer \ -foptimize-sibling-calls THIRD_PARTY_MBEDTLS_LIBS = $(foreach x,$(THIRD_PARTY_MBEDTLS_ARTIFACTS),$($(x))) THIRD_PARTY_MBEDTLS_SRCS = $(foreach x,$(THIRD_PARTY_MBEDTLS_ARTIFACTS),$($(x)_SRCS)) THIRD_PARTY_MBEDTLS_HDRS = $(foreach x,$(THIRD_PARTY_MBEDTLS_ARTIFACTS),$($(x)_HDRS)) THIRD_PARTY_MBEDTLS_INCS = $(foreach x,$(THIRD_PARTY_MBEDTLS_ARTIFACTS),$($(x)_INCS)) THIRD_PARTY_MBEDTLS_CHECKS = $(foreach x,$(THIRD_PARTY_MBEDTLS_ARTIFACTS),$($(x)_CHECKS)) THIRD_PARTY_MBEDTLS_OBJS = $(foreach x,$(THIRD_PARTY_MBEDTLS_ARTIFACTS),$($(x)_OBJS)) $(THIRD_PARTY_MBEDTLS_A_OBJS): third_party/mbedtls/mbedtls.mk .PHONY: o/$(MODE)/third_party/mbedtls o/$(MODE)/third_party/mbedtls: \ o/$(MODE)/third_party/mbedtls/test \ $(THIRD_PARTY_MBEDTLS_CHECKS)
3,061
89
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
11,358
203
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/certs.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/mbedtls/certs.h" #include "third_party/mbedtls/common.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ #if defined(MBEDTLS_CERTS_C) /* * Test CA Certificates * * We define test CA certificates for each choice of the following parameters: * - PEM or DER encoding * - SHA-1 or SHA-256 hash * - RSA or EC key * * Things to add: * - multiple EC curve types * */ /* This is taken from tests/data_files/test-ca2.crt */ /* BEGIN FILE string macro TEST_CA_CRT_EC_PEM tests/data_files/test-ca2.crt */ #define TEST_CA_CRT_EC_PEM \ "-----BEGIN CERTIFICATE-----\r\n" \ "MIICBDCCAYigAwIBAgIJAMFD4n5iQ8zoMAwGCCqGSM49BAMCBQAwPjELMAkGA1UE\r\n" \ "BhMCTkwxETAPBgNVBAoMCFBvbGFyU1NMMRwwGgYDVQQDDBNQb2xhcnNzbCBUZXN0\r\n" \ "IEVDIENBMB4XDTE5MDIxMDE0NDQwMFoXDTI5MDIxMDE0NDQwMFowPjELMAkGA1UE\r\n" \ "BhMCTkwxETAPBgNVBAoMCFBvbGFyU1NMMRwwGgYDVQQDDBNQb2xhcnNzbCBUZXN0\r\n" \ "IEVDIENBMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEw9orNEE3WC+HVv78ibopQ0tO\r\n" \ "4G7DDldTMzlY1FK0kZU5CyPfXxckYkj8GpUpziwth8KIUoCv1mqrId240xxuWLjK\r\n" \ "6LJpjvNBrSnDtF91p0dv1RkpVWmaUzsgtGYWYDMeo1AwTjAMBgNVHRMEBTADAQH/\r\n" \ "MB0GA1UdDgQWBBSdbSAkSQE/K8t4tRm8fiTJ2/s2fDAfBgNVHSMEGDAWgBSdbSAk\r\n" \ "SQE/K8t4tRm8fiTJ2/s2fDAMBggqhkjOPQQDAgUAA2gAMGUCMFHKrjAPpHB0BN1a\r\n" \ "LH8TwcJ3vh0AxeKZj30mRdOKBmg/jLS3rU3g8VQBHpn8sOTTBwIxANxPO5AerimZ\r\n" \ "hCjMe0d4CTHf1gFZMF70+IqEP+o5VHsIp2Cqvflb0VGWFC5l9a4cQg==\r\n" \ "-----END CERTIFICATE-----\r\n" /* END FILE */ /* This is generated from tests/data_files/test-ca2.crt.der using `xxd -i`. */ /* BEGIN FILE binary macro TEST_CA_CRT_EC_DER tests/data_files/test-ca2.crt.der */ #define TEST_CA_CRT_EC_DER { \ 0x30, 0x82, 0x02, 0x04, 0x30, 0x82, 0x01, 0x88, 0xa0, 0x03, 0x02, 0x01, \ 0x02, 0x02, 0x09, 0x00, 0xc1, 0x43, 0xe2, 0x7e, 0x62, 0x43, 0xcc, 0xe8, \ 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, \ 0x05, 0x00, 0x30, 0x3e, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, \ 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, 0x03, 0x55, \ 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, \ 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x13, 0x50, \ 0x6f, 0x6c, 0x61, 0x72, 0x73, 0x73, 0x6c, 0x20, 0x54, 0x65, 0x73, 0x74, \ 0x20, 0x45, 0x43, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, 0x31, 0x39, \ 0x30, 0x32, 0x31, 0x30, 0x31, 0x34, 0x34, 0x34, 0x30, 0x30, 0x5a, 0x17, \ 0x0d, 0x32, 0x39, 0x30, 0x32, 0x31, 0x30, 0x31, 0x34, 0x34, 0x34, 0x30, \ 0x30, 0x5a, 0x30, 0x3e, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, \ 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, 0x03, 0x55, \ 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, \ 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x13, 0x50, \ 0x6f, 0x6c, 0x61, 0x72, 0x73, 0x73, 0x6c, 0x20, 0x54, 0x65, 0x73, 0x74, \ 0x20, 0x45, 0x43, 0x20, 0x43, 0x41, 0x30, 0x76, 0x30, 0x10, 0x06, 0x07, \ 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, \ 0x00, 0x22, 0x03, 0x62, 0x00, 0x04, 0xc3, 0xda, 0x2b, 0x34, 0x41, 0x37, \ 0x58, 0x2f, 0x87, 0x56, 0xfe, 0xfc, 0x89, 0xba, 0x29, 0x43, 0x4b, 0x4e, \ 0xe0, 0x6e, 0xc3, 0x0e, 0x57, 0x53, 0x33, 0x39, 0x58, 0xd4, 0x52, 0xb4, \ 0x91, 0x95, 0x39, 0x0b, 0x23, 0xdf, 0x5f, 0x17, 0x24, 0x62, 0x48, 0xfc, \ 0x1a, 0x95, 0x29, 0xce, 0x2c, 0x2d, 0x87, 0xc2, 0x88, 0x52, 0x80, 0xaf, \ 0xd6, 0x6a, 0xab, 0x21, 0xdd, 0xb8, 0xd3, 0x1c, 0x6e, 0x58, 0xb8, 0xca, \ 0xe8, 0xb2, 0x69, 0x8e, 0xf3, 0x41, 0xad, 0x29, 0xc3, 0xb4, 0x5f, 0x75, \ 0xa7, 0x47, 0x6f, 0xd5, 0x19, 0x29, 0x55, 0x69, 0x9a, 0x53, 0x3b, 0x20, \ 0xb4, 0x66, 0x16, 0x60, 0x33, 0x1e, 0xa3, 0x50, 0x30, 0x4e, 0x30, 0x0c, \ 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xff, \ 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x9d, \ 0x6d, 0x20, 0x24, 0x49, 0x01, 0x3f, 0x2b, 0xcb, 0x78, 0xb5, 0x19, 0xbc, \ 0x7e, 0x24, 0xc9, 0xdb, 0xfb, 0x36, 0x7c, 0x30, 0x1f, 0x06, 0x03, 0x55, \ 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x9d, 0x6d, 0x20, 0x24, \ 0x49, 0x01, 0x3f, 0x2b, 0xcb, 0x78, 0xb5, 0x19, 0xbc, 0x7e, 0x24, 0xc9, \ 0xdb, 0xfb, 0x36, 0x7c, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, \ 0x3d, 0x04, 0x03, 0x02, 0x05, 0x00, 0x03, 0x68, 0x00, 0x30, 0x65, 0x02, \ 0x30, 0x51, 0xca, 0xae, 0x30, 0x0f, 0xa4, 0x70, 0x74, 0x04, 0xdd, 0x5a, \ 0x2c, 0x7f, 0x13, 0xc1, 0xc2, 0x77, 0xbe, 0x1d, 0x00, 0xc5, 0xe2, 0x99, \ 0x8f, 0x7d, 0x26, 0x45, 0xd3, 0x8a, 0x06, 0x68, 0x3f, 0x8c, 0xb4, 0xb7, \ 0xad, 0x4d, 0xe0, 0xf1, 0x54, 0x01, 0x1e, 0x99, 0xfc, 0xb0, 0xe4, 0xd3, \ 0x07, 0x02, 0x31, 0x00, 0xdc, 0x4f, 0x3b, 0x90, 0x1e, 0xae, 0x29, 0x99, \ 0x84, 0x28, 0xcc, 0x7b, 0x47, 0x78, 0x09, 0x31, 0xdf, 0xd6, 0x01, 0x59, \ 0x30, 0x5e, 0xf4, 0xf8, 0x8a, 0x84, 0x3f, 0xea, 0x39, 0x54, 0x7b, 0x08, \ 0xa7, 0x60, 0xaa, 0xbd, 0xf9, 0x5b, 0xd1, 0x51, 0x96, 0x14, 0x2e, 0x65, \ 0xf5, 0xae, 0x1c, 0x42 \ } /* END FILE */ /* This is taken from tests/data_files/test-ca2.key.enc */ /* BEGIN FILE string macro TEST_CA_KEY_EC_PEM tests/data_files/test-ca2.key.enc */ #define TEST_CA_KEY_EC_PEM \ "-----BEGIN EC PRIVATE KEY-----\r\n" \ "Proc-Type: 4,ENCRYPTED\r\n" \ "DEK-Info: DES-EDE3-CBC,307EAB469933D64E\r\n" \ "\r\n" \ "IxbrRmKcAzctJqPdTQLA4SWyBYYGYJVkYEna+F7Pa5t5Yg/gKADrFKcm6B72e7DG\r\n" \ "ihExtZI648s0zdYw6qSJ74vrPSuWDe5qm93BqsfVH9svtCzWHW0pm1p0KTBCFfUq\r\n" \ "UsuWTITwJImcnlAs1gaRZ3sAWm7cOUidL0fo2G0fYUFNcYoCSLffCFTEHBuPnagb\r\n" \ "a77x/sY1Bvii8S9/XhDTb6pTMx06wzrm\r\n" \ "-----END EC PRIVATE KEY-----\r\n" /* END FILE */ #define TEST_CA_PWD_EC_PEM "PolarSSLTest" /* This is generated from tests/data_files/test-ca2.key.der using `xxd -i`. */ /* BEGIN FILE binary macro TEST_CA_KEY_EC_DER tests/data_files/test-ca2.key.der */ #define TEST_CA_KEY_EC_DER { \ 0x30, 0x81, 0xa4, 0x02, 0x01, 0x01, 0x04, 0x30, 0x83, 0xd9, 0x15, 0x0e, \ 0xa0, 0x71, 0xf0, 0x57, 0x10, 0x33, 0xa3, 0x38, 0xb8, 0x86, 0xc1, 0xa6, \ 0x11, 0x5d, 0x6d, 0xb4, 0x03, 0xe1, 0x29, 0x76, 0x45, 0xd7, 0x87, 0x6f, \ 0x23, 0xab, 0x44, 0x20, 0xea, 0x64, 0x7b, 0x85, 0xb1, 0x76, 0xe7, 0x85, \ 0x95, 0xaa, 0x74, 0xd6, 0xd1, 0xa4, 0x5e, 0xea, 0xa0, 0x07, 0x06, 0x05, \ 0x2b, 0x81, 0x04, 0x00, 0x22, 0xa1, 0x64, 0x03, 0x62, 0x00, 0x04, 0xc3, \ 0xda, 0x2b, 0x34, 0x41, 0x37, 0x58, 0x2f, 0x87, 0x56, 0xfe, 0xfc, 0x89, \ 0xba, 0x29, 0x43, 0x4b, 0x4e, 0xe0, 0x6e, 0xc3, 0x0e, 0x57, 0x53, 0x33, \ 0x39, 0x58, 0xd4, 0x52, 0xb4, 0x91, 0x95, 0x39, 0x0b, 0x23, 0xdf, 0x5f, \ 0x17, 0x24, 0x62, 0x48, 0xfc, 0x1a, 0x95, 0x29, 0xce, 0x2c, 0x2d, 0x87, \ 0xc2, 0x88, 0x52, 0x80, 0xaf, 0xd6, 0x6a, 0xab, 0x21, 0xdd, 0xb8, 0xd3, \ 0x1c, 0x6e, 0x58, 0xb8, 0xca, 0xe8, 0xb2, 0x69, 0x8e, 0xf3, 0x41, 0xad, \ 0x29, 0xc3, 0xb4, 0x5f, 0x75, 0xa7, 0x47, 0x6f, 0xd5, 0x19, 0x29, 0x55, \ 0x69, 0x9a, 0x53, 0x3b, 0x20, 0xb4, 0x66, 0x16, 0x60, 0x33, 0x1e \ } /* END FILE */ /* This is taken from tests/data_files/test-ca-sha256.crt. */ /* BEGIN FILE string macro TEST_CA_CRT_RSA_SHA256_PEM tests/data_files/test-ca-sha256.crt */ #define TEST_CA_CRT_RSA_SHA256_PEM \ "-----BEGIN CERTIFICATE-----\r\n" \ "MIIDQTCCAimgAwIBAgIBAzANBgkqhkiG9w0BAQsFADA7MQswCQYDVQQGEwJOTDER\r\n" \ "MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n" \ "MTkwMjEwMTQ0NDAwWhcNMjkwMjEwMTQ0NDAwWjA7MQswCQYDVQQGEwJOTDERMA8G\r\n" \ "A1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwggEiMA0G\r\n" \ "CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDA3zf8F7vglp0/ht6WMn1EpRagzSHx\r\n" \ "mdTs6st8GFgIlKXsm8WL3xoemTiZhx57wI053zhdcHgH057Zk+i5clHFzqMwUqny\r\n" \ "50BwFMtEonILwuVA+T7lpg6z+exKY8C4KQB0nFc7qKUEkHHxvYPZP9al4jwqj+8n\r\n" \ "YMPGn8u67GB9t+aEMr5P+1gmIgNb1LTV+/Xjli5wwOQuvfwu7uJBVcA0Ln0kcmnL\r\n" \ "R7EUQIN9Z/SG9jGr8XmksrUuEvmEF/Bibyc+E1ixVA0hmnM3oTDPb5Lc9un8rNsu\r\n" \ "KNF+AksjoBXyOGVkCeoMbo4bF6BxyLObyavpw/LPh5aPgAIynplYb6LVAgMBAAGj\r\n" \ "UDBOMAwGA1UdEwQFMAMBAf8wHQYDVR0OBBYEFLRa5KWz3tJS9rnVppUP6z68x/3/\r\n" \ "MB8GA1UdIwQYMBaAFLRa5KWz3tJS9rnVppUP6z68x/3/MA0GCSqGSIb3DQEBCwUA\r\n" \ "A4IBAQA4qFSCth2q22uJIdE4KGHJsJjVEfw2/xn+MkTvCMfxVrvmRvqCtjE4tKDl\r\n" \ "oK4MxFOek07oDZwvtAT9ijn1hHftTNS7RH9zd/fxNpfcHnMZXVC4w4DNA1fSANtW\r\n" \ "5sY1JB5Je9jScrsLSS+mAjyv0Ow3Hb2Bix8wu7xNNrV5fIf7Ubm+wt6SqEBxu3Kb\r\n" \ "+EfObAT4huf3czznhH3C17ed6NSbXwoXfby7stWUDeRJv08RaFOykf/Aae7bY5PL\r\n" \ "yTVrkAnikMntJ9YI+hNNYt3inqq11A5cN0+rVTst8UKCxzQ4GpvroSwPKTFkbMw4\r\n" \ "/anT1dVxr/BtwJfiESoK3/4CeXR1\r\n" \ "-----END CERTIFICATE-----\r\n" /* END FILE */ /* This is generated from tests/data_files/test-ca-sha256.crt.der * using `xxd -i`. */ /* BEGIN FILE binary macro TEST_CA_CRT_RSA_SHA256_DER tests/data_files/test-ca-sha256.crt.der */ #define TEST_CA_CRT_RSA_SHA256_DER { \ 0x30, 0x82, 0x03, 0x41, 0x30, 0x82, 0x02, 0x29, 0xa0, 0x03, 0x02, 0x01, \ 0x02, 0x02, 0x01, 0x03, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, \ 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x3b, 0x31, 0x0b, 0x30, \ 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, \ 0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, \ 0x61, 0x72, 0x53, 0x53, 0x4c, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, \ 0x04, 0x03, 0x0c, 0x10, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, \ 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, \ 0x31, 0x39, 0x30, 0x32, 0x31, 0x30, 0x31, 0x34, 0x34, 0x34, 0x30, 0x30, \ 0x5a, 0x17, 0x0d, 0x32, 0x39, 0x30, 0x32, 0x31, 0x30, 0x31, 0x34, 0x34, \ 0x34, 0x30, 0x30, 0x5a, 0x30, 0x3b, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, \ 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, \ 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, \ 0x53, 0x4c, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, \ 0x10, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, 0x20, 0x54, 0x65, \ 0x73, 0x74, 0x20, 0x43, 0x41, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, \ 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, \ 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, \ 0x01, 0x00, 0xc0, 0xdf, 0x37, 0xfc, 0x17, 0xbb, 0xe0, 0x96, 0x9d, 0x3f, \ 0x86, 0xde, 0x96, 0x32, 0x7d, 0x44, 0xa5, 0x16, 0xa0, 0xcd, 0x21, 0xf1, \ 0x99, 0xd4, 0xec, 0xea, 0xcb, 0x7c, 0x18, 0x58, 0x08, 0x94, 0xa5, 0xec, \ 0x9b, 0xc5, 0x8b, 0xdf, 0x1a, 0x1e, 0x99, 0x38, 0x99, 0x87, 0x1e, 0x7b, \ 0xc0, 0x8d, 0x39, 0xdf, 0x38, 0x5d, 0x70, 0x78, 0x07, 0xd3, 0x9e, 0xd9, \ 0x93, 0xe8, 0xb9, 0x72, 0x51, 0xc5, 0xce, 0xa3, 0x30, 0x52, 0xa9, 0xf2, \ 0xe7, 0x40, 0x70, 0x14, 0xcb, 0x44, 0xa2, 0x72, 0x0b, 0xc2, 0xe5, 0x40, \ 0xf9, 0x3e, 0xe5, 0xa6, 0x0e, 0xb3, 0xf9, 0xec, 0x4a, 0x63, 0xc0, 0xb8, \ 0x29, 0x00, 0x74, 0x9c, 0x57, 0x3b, 0xa8, 0xa5, 0x04, 0x90, 0x71, 0xf1, \ 0xbd, 0x83, 0xd9, 0x3f, 0xd6, 0xa5, 0xe2, 0x3c, 0x2a, 0x8f, 0xef, 0x27, \ 0x60, 0xc3, 0xc6, 0x9f, 0xcb, 0xba, 0xec, 0x60, 0x7d, 0xb7, 0xe6, 0x84, \ 0x32, 0xbe, 0x4f, 0xfb, 0x58, 0x26, 0x22, 0x03, 0x5b, 0xd4, 0xb4, 0xd5, \ 0xfb, 0xf5, 0xe3, 0x96, 0x2e, 0x70, 0xc0, 0xe4, 0x2e, 0xbd, 0xfc, 0x2e, \ 0xee, 0xe2, 0x41, 0x55, 0xc0, 0x34, 0x2e, 0x7d, 0x24, 0x72, 0x69, 0xcb, \ 0x47, 0xb1, 0x14, 0x40, 0x83, 0x7d, 0x67, 0xf4, 0x86, 0xf6, 0x31, 0xab, \ 0xf1, 0x79, 0xa4, 0xb2, 0xb5, 0x2e, 0x12, 0xf9, 0x84, 0x17, 0xf0, 0x62, \ 0x6f, 0x27, 0x3e, 0x13, 0x58, 0xb1, 0x54, 0x0d, 0x21, 0x9a, 0x73, 0x37, \ 0xa1, 0x30, 0xcf, 0x6f, 0x92, 0xdc, 0xf6, 0xe9, 0xfc, 0xac, 0xdb, 0x2e, \ 0x28, 0xd1, 0x7e, 0x02, 0x4b, 0x23, 0xa0, 0x15, 0xf2, 0x38, 0x65, 0x64, \ 0x09, 0xea, 0x0c, 0x6e, 0x8e, 0x1b, 0x17, 0xa0, 0x71, 0xc8, 0xb3, 0x9b, \ 0xc9, 0xab, 0xe9, 0xc3, 0xf2, 0xcf, 0x87, 0x96, 0x8f, 0x80, 0x02, 0x32, \ 0x9e, 0x99, 0x58, 0x6f, 0xa2, 0xd5, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, \ 0x50, 0x30, 0x4e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x05, \ 0x30, 0x03, 0x01, 0x01, 0xff, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, \ 0x04, 0x16, 0x04, 0x14, 0xb4, 0x5a, 0xe4, 0xa5, 0xb3, 0xde, 0xd2, 0x52, \ 0xf6, 0xb9, 0xd5, 0xa6, 0x95, 0x0f, 0xeb, 0x3e, 0xbc, 0xc7, 0xfd, 0xff, \ 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, \ 0x14, 0xb4, 0x5a, 0xe4, 0xa5, 0xb3, 0xde, 0xd2, 0x52, 0xf6, 0xb9, 0xd5, \ 0xa6, 0x95, 0x0f, 0xeb, 0x3e, 0xbc, 0xc7, 0xfd, 0xff, 0x30, 0x0d, 0x06, \ 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, \ 0x03, 0x82, 0x01, 0x01, 0x00, 0x38, 0xa8, 0x54, 0x82, 0xb6, 0x1d, 0xaa, \ 0xdb, 0x6b, 0x89, 0x21, 0xd1, 0x38, 0x28, 0x61, 0xc9, 0xb0, 0x98, 0xd5, \ 0x11, 0xfc, 0x36, 0xff, 0x19, 0xfe, 0x32, 0x44, 0xef, 0x08, 0xc7, 0xf1, \ 0x56, 0xbb, 0xe6, 0x46, 0xfa, 0x82, 0xb6, 0x31, 0x38, 0xb4, 0xa0, 0xe5, \ 0xa0, 0xae, 0x0c, 0xc4, 0x53, 0x9e, 0x93, 0x4e, 0xe8, 0x0d, 0x9c, 0x2f, \ 0xb4, 0x04, 0xfd, 0x8a, 0x39, 0xf5, 0x84, 0x77, 0xed, 0x4c, 0xd4, 0xbb, \ 0x44, 0x7f, 0x73, 0x77, 0xf7, 0xf1, 0x36, 0x97, 0xdc, 0x1e, 0x73, 0x19, \ 0x5d, 0x50, 0xb8, 0xc3, 0x80, 0xcd, 0x03, 0x57, 0xd2, 0x00, 0xdb, 0x56, \ 0xe6, 0xc6, 0x35, 0x24, 0x1e, 0x49, 0x7b, 0xd8, 0xd2, 0x72, 0xbb, 0x0b, \ 0x49, 0x2f, 0xa6, 0x02, 0x3c, 0xaf, 0xd0, 0xec, 0x37, 0x1d, 0xbd, 0x81, \ 0x8b, 0x1f, 0x30, 0xbb, 0xbc, 0x4d, 0x36, 0xb5, 0x79, 0x7c, 0x87, 0xfb, \ 0x51, 0xb9, 0xbe, 0xc2, 0xde, 0x92, 0xa8, 0x40, 0x71, 0xbb, 0x72, 0x9b, \ 0xf8, 0x47, 0xce, 0x6c, 0x04, 0xf8, 0x86, 0xe7, 0xf7, 0x73, 0x3c, 0xe7, \ 0x84, 0x7d, 0xc2, 0xd7, 0xb7, 0x9d, 0xe8, 0xd4, 0x9b, 0x5f, 0x0a, 0x17, \ 0x7d, 0xbc, 0xbb, 0xb2, 0xd5, 0x94, 0x0d, 0xe4, 0x49, 0xbf, 0x4f, 0x11, \ 0x68, 0x53, 0xb2, 0x91, 0xff, 0xc0, 0x69, 0xee, 0xdb, 0x63, 0x93, 0xcb, \ 0xc9, 0x35, 0x6b, 0x90, 0x09, 0xe2, 0x90, 0xc9, 0xed, 0x27, 0xd6, 0x08, \ 0xfa, 0x13, 0x4d, 0x62, 0xdd, 0xe2, 0x9e, 0xaa, 0xb5, 0xd4, 0x0e, 0x5c, \ 0x37, 0x4f, 0xab, 0x55, 0x3b, 0x2d, 0xf1, 0x42, 0x82, 0xc7, 0x34, 0x38, \ 0x1a, 0x9b, 0xeb, 0xa1, 0x2c, 0x0f, 0x29, 0x31, 0x64, 0x6c, 0xcc, 0x38, \ 0xfd, 0xa9, 0xd3, 0xd5, 0xd5, 0x71, 0xaf, 0xf0, 0x6d, 0xc0, 0x97, 0xe2, \ 0x11, 0x2a, 0x0a, 0xdf, 0xfe, 0x02, 0x79, 0x74, 0x75 \ } /* END FILE */ /* This is taken from tests/data_files/test-ca-sha1.crt. */ /* BEGIN FILE string macro TEST_CA_CRT_RSA_SHA1_PEM tests/data_files/test-ca-sha1.crt */ #define TEST_CA_CRT_RSA_SHA1_PEM \ "-----BEGIN CERTIFICATE-----\r\n" \ "MIIDQTCCAimgAwIBAgIBAzANBgkqhkiG9w0BAQUFADA7MQswCQYDVQQGEwJOTDER\r\n" \ "MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n" \ "MTEwMjEyMTQ0NDAwWhcNMjEwMjEyMTQ0NDAwWjA7MQswCQYDVQQGEwJOTDERMA8G\r\n" \ "A1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwggEiMA0G\r\n" \ "CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDA3zf8F7vglp0/ht6WMn1EpRagzSHx\r\n" \ "mdTs6st8GFgIlKXsm8WL3xoemTiZhx57wI053zhdcHgH057Zk+i5clHFzqMwUqny\r\n" \ "50BwFMtEonILwuVA+T7lpg6z+exKY8C4KQB0nFc7qKUEkHHxvYPZP9al4jwqj+8n\r\n" \ "YMPGn8u67GB9t+aEMr5P+1gmIgNb1LTV+/Xjli5wwOQuvfwu7uJBVcA0Ln0kcmnL\r\n" \ "R7EUQIN9Z/SG9jGr8XmksrUuEvmEF/Bibyc+E1ixVA0hmnM3oTDPb5Lc9un8rNsu\r\n" \ "KNF+AksjoBXyOGVkCeoMbo4bF6BxyLObyavpw/LPh5aPgAIynplYb6LVAgMBAAGj\r\n" \ "UDBOMAwGA1UdEwQFMAMBAf8wHQYDVR0OBBYEFLRa5KWz3tJS9rnVppUP6z68x/3/\r\n" \ "MB8GA1UdIwQYMBaAFLRa5KWz3tJS9rnVppUP6z68x/3/MA0GCSqGSIb3DQEBBQUA\r\n" \ "A4IBAQABE3OEPfEd/bcJW5ZdU3/VgPNS4tMzh8gnJP/V2FcvFtGylMpQq6YnEBYI\r\n" \ "yBHAL4DRvlMY5rnXGBp3ODR8MpqHC6AquRTCLzjS57iYff//4QFQqW9n92zctspv\r\n" \ "czkaPKgjqo1No3Uq0Xaz10rcxyTUPrf5wNVRZ2V0KvllvAAVSzbI4mpdUXztjhST\r\n" \ "S5A2BeWQAAOr0zq1F7TSRVJpJs7jmB2ai/igkh1IAjcuwV6VwlP+sbw0gjQ0NpGM\r\n" \ "iHpnlzRAi/tIbtOvMIGOBU2TIfax/5jq1agUx5aPmT5TWAiJPOOP6l5xXnDwxeYS\r\n" \ "NWqiX9GyusBZjezaCaHabjDLU0qQ\r\n" \ "-----END CERTIFICATE-----\r\n" /* END FILE */ /* This is taken from tests/data_files/test-ca-sha1.crt.der. */ /* BEGIN FILE binary macro TEST_CA_CRT_RSA_SHA1_DER tests/data_files/test-ca-sha1.crt.der */ #define TEST_CA_CRT_RSA_SHA1_DER { \ 0x30, 0x82, 0x03, 0x41, 0x30, 0x82, 0x02, 0x29, 0xa0, 0x03, 0x02, 0x01, \ 0x02, 0x02, 0x01, 0x03, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, \ 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30, 0x3b, 0x31, 0x0b, 0x30, \ 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, \ 0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, \ 0x61, 0x72, 0x53, 0x53, 0x4c, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, \ 0x04, 0x03, 0x0c, 0x10, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, \ 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, \ 0x31, 0x31, 0x30, 0x32, 0x31, 0x32, 0x31, 0x34, 0x34, 0x34, 0x30, 0x30, \ 0x5a, 0x17, 0x0d, 0x32, 0x31, 0x30, 0x32, 0x31, 0x32, 0x31, 0x34, 0x34, \ 0x34, 0x30, 0x30, 0x5a, 0x30, 0x3b, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, \ 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, \ 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, \ 0x53, 0x4c, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, \ 0x10, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, 0x20, 0x54, 0x65, \ 0x73, 0x74, 0x20, 0x43, 0x41, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, \ 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, \ 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, \ 0x01, 0x00, 0xc0, 0xdf, 0x37, 0xfc, 0x17, 0xbb, 0xe0, 0x96, 0x9d, 0x3f, \ 0x86, 0xde, 0x96, 0x32, 0x7d, 0x44, 0xa5, 0x16, 0xa0, 0xcd, 0x21, 0xf1, \ 0x99, 0xd4, 0xec, 0xea, 0xcb, 0x7c, 0x18, 0x58, 0x08, 0x94, 0xa5, 0xec, \ 0x9b, 0xc5, 0x8b, 0xdf, 0x1a, 0x1e, 0x99, 0x38, 0x99, 0x87, 0x1e, 0x7b, \ 0xc0, 0x8d, 0x39, 0xdf, 0x38, 0x5d, 0x70, 0x78, 0x07, 0xd3, 0x9e, 0xd9, \ 0x93, 0xe8, 0xb9, 0x72, 0x51, 0xc5, 0xce, 0xa3, 0x30, 0x52, 0xa9, 0xf2, \ 0xe7, 0x40, 0x70, 0x14, 0xcb, 0x44, 0xa2, 0x72, 0x0b, 0xc2, 0xe5, 0x40, \ 0xf9, 0x3e, 0xe5, 0xa6, 0x0e, 0xb3, 0xf9, 0xec, 0x4a, 0x63, 0xc0, 0xb8, \ 0x29, 0x00, 0x74, 0x9c, 0x57, 0x3b, 0xa8, 0xa5, 0x04, 0x90, 0x71, 0xf1, \ 0xbd, 0x83, 0xd9, 0x3f, 0xd6, 0xa5, 0xe2, 0x3c, 0x2a, 0x8f, 0xef, 0x27, \ 0x60, 0xc3, 0xc6, 0x9f, 0xcb, 0xba, 0xec, 0x60, 0x7d, 0xb7, 0xe6, 0x84, \ 0x32, 0xbe, 0x4f, 0xfb, 0x58, 0x26, 0x22, 0x03, 0x5b, 0xd4, 0xb4, 0xd5, \ 0xfb, 0xf5, 0xe3, 0x96, 0x2e, 0x70, 0xc0, 0xe4, 0x2e, 0xbd, 0xfc, 0x2e, \ 0xee, 0xe2, 0x41, 0x55, 0xc0, 0x34, 0x2e, 0x7d, 0x24, 0x72, 0x69, 0xcb, \ 0x47, 0xb1, 0x14, 0x40, 0x83, 0x7d, 0x67, 0xf4, 0x86, 0xf6, 0x31, 0xab, \ 0xf1, 0x79, 0xa4, 0xb2, 0xb5, 0x2e, 0x12, 0xf9, 0x84, 0x17, 0xf0, 0x62, \ 0x6f, 0x27, 0x3e, 0x13, 0x58, 0xb1, 0x54, 0x0d, 0x21, 0x9a, 0x73, 0x37, \ 0xa1, 0x30, 0xcf, 0x6f, 0x92, 0xdc, 0xf6, 0xe9, 0xfc, 0xac, 0xdb, 0x2e, \ 0x28, 0xd1, 0x7e, 0x02, 0x4b, 0x23, 0xa0, 0x15, 0xf2, 0x38, 0x65, 0x64, \ 0x09, 0xea, 0x0c, 0x6e, 0x8e, 0x1b, 0x17, 0xa0, 0x71, 0xc8, 0xb3, 0x9b, \ 0xc9, 0xab, 0xe9, 0xc3, 0xf2, 0xcf, 0x87, 0x96, 0x8f, 0x80, 0x02, 0x32, \ 0x9e, 0x99, 0x58, 0x6f, 0xa2, 0xd5, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, \ 0x50, 0x30, 0x4e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x05, \ 0x30, 0x03, 0x01, 0x01, 0xff, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, \ 0x04, 0x16, 0x04, 0x14, 0xb4, 0x5a, 0xe4, 0xa5, 0xb3, 0xde, 0xd2, 0x52, \ 0xf6, 0xb9, 0xd5, 0xa6, 0x95, 0x0f, 0xeb, 0x3e, 0xbc, 0xc7, 0xfd, 0xff, \ 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, \ 0x14, 0xb4, 0x5a, 0xe4, 0xa5, 0xb3, 0xde, 0xd2, 0x52, 0xf6, 0xb9, 0xd5, \ 0xa6, 0x95, 0x0f, 0xeb, 0x3e, 0xbc, 0xc7, 0xfd, 0xff, 0x30, 0x0d, 0x06, \ 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, \ 0x03, 0x82, 0x01, 0x01, 0x00, 0x01, 0x13, 0x73, 0x84, 0x3d, 0xf1, 0x1d, \ 0xfd, 0xb7, 0x09, 0x5b, 0x96, 0x5d, 0x53, 0x7f, 0xd5, 0x80, 0xf3, 0x52, \ 0xe2, 0xd3, 0x33, 0x87, 0xc8, 0x27, 0x24, 0xff, 0xd5, 0xd8, 0x57, 0x2f, \ 0x16, 0xd1, 0xb2, 0x94, 0xca, 0x50, 0xab, 0xa6, 0x27, 0x10, 0x16, 0x08, \ 0xc8, 0x11, 0xc0, 0x2f, 0x80, 0xd1, 0xbe, 0x53, 0x18, 0xe6, 0xb9, 0xd7, \ 0x18, 0x1a, 0x77, 0x38, 0x34, 0x7c, 0x32, 0x9a, 0x87, 0x0b, 0xa0, 0x2a, \ 0xb9, 0x14, 0xc2, 0x2f, 0x38, 0xd2, 0xe7, 0xb8, 0x98, 0x7d, 0xff, 0xff, \ 0xe1, 0x01, 0x50, 0xa9, 0x6f, 0x67, 0xf7, 0x6c, 0xdc, 0xb6, 0xca, 0x6f, \ 0x73, 0x39, 0x1a, 0x3c, 0xa8, 0x23, 0xaa, 0x8d, 0x4d, 0xa3, 0x75, 0x2a, \ 0xd1, 0x76, 0xb3, 0xd7, 0x4a, 0xdc, 0xc7, 0x24, 0xd4, 0x3e, 0xb7, 0xf9, \ 0xc0, 0xd5, 0x51, 0x67, 0x65, 0x74, 0x2a, 0xf9, 0x65, 0xbc, 0x00, 0x15, \ 0x4b, 0x36, 0xc8, 0xe2, 0x6a, 0x5d, 0x51, 0x7c, 0xed, 0x8e, 0x14, 0x93, \ 0x4b, 0x90, 0x36, 0x05, 0xe5, 0x90, 0x00, 0x03, 0xab, 0xd3, 0x3a, 0xb5, \ 0x17, 0xb4, 0xd2, 0x45, 0x52, 0x69, 0x26, 0xce, 0xe3, 0x98, 0x1d, 0x9a, \ 0x8b, 0xf8, 0xa0, 0x92, 0x1d, 0x48, 0x02, 0x37, 0x2e, 0xc1, 0x5e, 0x95, \ 0xc2, 0x53, 0xfe, 0xb1, 0xbc, 0x34, 0x82, 0x34, 0x34, 0x36, 0x91, 0x8c, \ 0x88, 0x7a, 0x67, 0x97, 0x34, 0x40, 0x8b, 0xfb, 0x48, 0x6e, 0xd3, 0xaf, \ 0x30, 0x81, 0x8e, 0x05, 0x4d, 0x93, 0x21, 0xf6, 0xb1, 0xff, 0x98, 0xea, \ 0xd5, 0xa8, 0x14, 0xc7, 0x96, 0x8f, 0x99, 0x3e, 0x53, 0x58, 0x08, 0x89, \ 0x3c, 0xe3, 0x8f, 0xea, 0x5e, 0x71, 0x5e, 0x70, 0xf0, 0xc5, 0xe6, 0x12, \ 0x35, 0x6a, 0xa2, 0x5f, 0xd1, 0xb2, 0xba, 0xc0, 0x59, 0x8d, 0xec, 0xda, \ 0x09, 0xa1, 0xda, 0x6e, 0x30, 0xcb, 0x53, 0x4a, 0x90 \ } /* END FILE */ /* This is taken from tests/data_files/test-ca.key */ /* BEGIN FILE string macro TEST_CA_KEY_RSA_PEM tests/data_files/test-ca.key */ #define TEST_CA_KEY_RSA_PEM \ "-----BEGIN RSA PRIVATE KEY-----\r\n" \ "Proc-Type: 4,ENCRYPTED\r\n" \ "DEK-Info: DES-EDE3-CBC,A8A95B05D5B7206B\r\n" \ "\r\n" \ "9Qd9GeArejl1GDVh2lLV1bHt0cPtfbh5h/5zVpAVaFpqtSPMrElp50Rntn9et+JA\r\n" \ "7VOyboR+Iy2t/HU4WvA687k3Bppe9GwKHjHhtl//8xFKwZr3Xb5yO5JUP8AUctQq\r\n" \ "Nb8CLlZyuUC+52REAAthdWgsX+7dJO4yabzUcQ22Tp9JSD0hiL43BlkWYUNK3dAo\r\n" \ "PZlmiptjnzVTjg1MxsBSydZinWOLBV8/JQgxSPo2yD4uEfig28qbvQ2wNIn0pnAb\r\n" \ "GxnSAOazkongEGfvcjIIs+LZN9gXFhxcOh6kc4Q/c99B7QWETwLLkYgZ+z1a9VY9\r\n" \ "gEU7CwCxYCD+h9hY6FPmsK0/lC4O7aeRKpYq00rPPxs6i7phiexg6ax6yTMmArQq\r\n" \ "QmK3TAsJm8V/J5AWpLEV6jAFgRGymGGHnof0DXzVWZidrcZJWTNuGEX90nB3ee2w\r\n" \ "PXJEFWKoD3K3aFcSLdHYr3mLGxP7H9ThQai9VsycxZKS5kwvBKQ//YMrmFfwPk8x\r\n" \ "vTeY4KZMaUrveEel5tWZC94RSMKgxR6cyE1nBXyTQnDOGbfpNNgBKxyKbINWoOJU\r\n" \ "WJZAwlsQn+QzCDwpri7+sV1mS3gBE6UY7aQmnmiiaC2V3Hbphxct/en5QsfDOt1X\r\n" \ "JczSfpRWLlbPznZg8OQh/VgCMA58N5DjOzTIK7sJJ5r+94ZBTCpgAMbF588f0NTR\r\n" \ "KCe4yrxGJR7X02M4nvD4IwOlpsQ8xQxZtOSgXv4LkxvdU9XJJKWZ/XNKJeWztxSe\r\n" \ "Z1vdTc2YfsDBA2SEv33vxHx2g1vqtw8SjDRT2RaQSS0QuSaMJimdOX6mTOCBKk1J\r\n" \ "9Q5mXTrER+/LnK0jEmXsBXWA5bqqVZIyahXSx4VYZ7l7w/PHiUDtDgyRhMMKi4n2\r\n" \ "iQvQcWSQTjrpnlJbca1/DkpRt3YwrvJwdqb8asZU2VrNETh5x0QVefDRLFiVpif/\r\n" \ "tUaeAe/P1F8OkS7OIZDs1SUbv/sD2vMbhNkUoCms3/PvNtdnvgL4F0zhaDpKCmlT\r\n" \ "P8vx49E7v5CyRNmED9zZg4o3wmMqrQO93PtTug3Eu9oVx1zPQM1NVMyBa2+f29DL\r\n" \ "1nuTCeXdo9+ni45xx+jAI4DCwrRdhJ9uzZyC6962H37H6D+5naNvClFR1s6li1Gb\r\n" \ "nqPoiy/OBsEx9CaDGcqQBp5Wme/3XW+6z1ISOx+igwNTVCT14mHdBMbya0eIKft5\r\n" \ "X+GnwtgEMyCYyyWuUct8g4RzErcY9+yW9Om5Hzpx4zOuW4NPZgPDTgK+t2RSL/Yq\r\n" \ "rE1njrgeGYcVeG3f+OftH4s6fPbq7t1A5ZgUscbLMBqr9tK+OqygR4EgKBPsH6Cz\r\n" \ "L6zlv/2RV0qAHvVuDJcIDIgwY5rJtINEm32rhOeFNJwZS5MNIC1czXZx5//ugX7l\r\n" \ "I4sy5nbVhwSjtAk8Xg5dZbdTZ6mIrb7xqH+fdakZor1khG7bC2uIwibD3cSl2XkR\r\n" \ "wN48lslbHnqqagr6Xm1nNOSVl8C/6kbJEsMpLhAezfRtGwvOucoaE+WbeUNolGde\r\n" \ "P/eQiddSf0brnpiLJRh7qZrl9XuqYdpUqnoEdMAfotDOID8OtV7gt8a48ad8VPW2\r\n" \ "-----END RSA PRIVATE KEY-----\r\n" /* END FILE */ #define TEST_CA_PWD_RSA_PEM "PolarSSLTest" /* This was generated from test-ca.key.der using `xxd -i`. */ /* BEGIN FILE binary macro TEST_CA_KEY_RSA_DER tests/data_files/test-ca.key.der */ #define TEST_CA_KEY_RSA_DER { \ 0x30, 0x82, 0x04, 0xa4, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, \ 0xc0, 0xdf, 0x37, 0xfc, 0x17, 0xbb, 0xe0, 0x96, 0x9d, 0x3f, 0x86, 0xde, \ 0x96, 0x32, 0x7d, 0x44, 0xa5, 0x16, 0xa0, 0xcd, 0x21, 0xf1, 0x99, 0xd4, \ 0xec, 0xea, 0xcb, 0x7c, 0x18, 0x58, 0x08, 0x94, 0xa5, 0xec, 0x9b, 0xc5, \ 0x8b, 0xdf, 0x1a, 0x1e, 0x99, 0x38, 0x99, 0x87, 0x1e, 0x7b, 0xc0, 0x8d, \ 0x39, 0xdf, 0x38, 0x5d, 0x70, 0x78, 0x07, 0xd3, 0x9e, 0xd9, 0x93, 0xe8, \ 0xb9, 0x72, 0x51, 0xc5, 0xce, 0xa3, 0x30, 0x52, 0xa9, 0xf2, 0xe7, 0x40, \ 0x70, 0x14, 0xcb, 0x44, 0xa2, 0x72, 0x0b, 0xc2, 0xe5, 0x40, 0xf9, 0x3e, \ 0xe5, 0xa6, 0x0e, 0xb3, 0xf9, 0xec, 0x4a, 0x63, 0xc0, 0xb8, 0x29, 0x00, \ 0x74, 0x9c, 0x57, 0x3b, 0xa8, 0xa5, 0x04, 0x90, 0x71, 0xf1, 0xbd, 0x83, \ 0xd9, 0x3f, 0xd6, 0xa5, 0xe2, 0x3c, 0x2a, 0x8f, 0xef, 0x27, 0x60, 0xc3, \ 0xc6, 0x9f, 0xcb, 0xba, 0xec, 0x60, 0x7d, 0xb7, 0xe6, 0x84, 0x32, 0xbe, \ 0x4f, 0xfb, 0x58, 0x26, 0x22, 0x03, 0x5b, 0xd4, 0xb4, 0xd5, 0xfb, 0xf5, \ 0xe3, 0x96, 0x2e, 0x70, 0xc0, 0xe4, 0x2e, 0xbd, 0xfc, 0x2e, 0xee, 0xe2, \ 0x41, 0x55, 0xc0, 0x34, 0x2e, 0x7d, 0x24, 0x72, 0x69, 0xcb, 0x47, 0xb1, \ 0x14, 0x40, 0x83, 0x7d, 0x67, 0xf4, 0x86, 0xf6, 0x31, 0xab, 0xf1, 0x79, \ 0xa4, 0xb2, 0xb5, 0x2e, 0x12, 0xf9, 0x84, 0x17, 0xf0, 0x62, 0x6f, 0x27, \ 0x3e, 0x13, 0x58, 0xb1, 0x54, 0x0d, 0x21, 0x9a, 0x73, 0x37, 0xa1, 0x30, \ 0xcf, 0x6f, 0x92, 0xdc, 0xf6, 0xe9, 0xfc, 0xac, 0xdb, 0x2e, 0x28, 0xd1, \ 0x7e, 0x02, 0x4b, 0x23, 0xa0, 0x15, 0xf2, 0x38, 0x65, 0x64, 0x09, 0xea, \ 0x0c, 0x6e, 0x8e, 0x1b, 0x17, 0xa0, 0x71, 0xc8, 0xb3, 0x9b, 0xc9, 0xab, \ 0xe9, 0xc3, 0xf2, 0xcf, 0x87, 0x96, 0x8f, 0x80, 0x02, 0x32, 0x9e, 0x99, \ 0x58, 0x6f, 0xa2, 0xd5, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x82, 0x01, \ 0x00, 0x3f, 0xf7, 0x07, 0xd3, 0x34, 0x6f, 0xdb, 0xc9, 0x37, 0xb7, 0x84, \ 0xdc, 0x37, 0x45, 0xe1, 0x63, 0xad, 0xb8, 0xb6, 0x75, 0xb1, 0xc7, 0x35, \ 0xb4, 0x77, 0x2a, 0x5b, 0x77, 0xf9, 0x7e, 0xe0, 0xc1, 0xa3, 0xd1, 0xb7, \ 0xcb, 0xa9, 0x5a, 0xc1, 0x87, 0xda, 0x5a, 0xfa, 0x17, 0xe4, 0xd5, 0x38, \ 0x03, 0xde, 0x68, 0x98, 0x81, 0xec, 0xb5, 0xf2, 0x2a, 0x8d, 0xe9, 0x2c, \ 0xf3, 0xa6, 0xe5, 0x32, 0x17, 0x7f, 0x33, 0x81, 0xe8, 0x38, 0x72, 0xd5, \ 0x9c, 0xfa, 0x4e, 0xfb, 0x26, 0xf5, 0x15, 0x0b, 0xaf, 0x84, 0x66, 0xab, \ 0x02, 0xe0, 0x18, 0xd5, 0x91, 0x7c, 0xd6, 0x8f, 0xc9, 0x4b, 0x76, 0x08, \ 0x2b, 0x1d, 0x81, 0x68, 0x30, 0xe1, 0xfa, 0x70, 0x6c, 0x13, 0x4e, 0x10, \ 0x03, 0x35, 0x3e, 0xc5, 0xca, 0x58, 0x20, 0x8a, 0x21, 0x18, 0x38, 0xa0, \ 0x0f, 0xed, 0xc4, 0xbb, 0x45, 0x6f, 0xf5, 0x84, 0x5b, 0xb0, 0xcf, 0x4e, \ 0x9d, 0x58, 0x13, 0x6b, 0x35, 0x35, 0x69, 0xa1, 0xd2, 0xc4, 0xf2, 0xc1, \ 0x48, 0x04, 0x20, 0x51, 0xb9, 0x6b, 0xa4, 0x5d, 0xa5, 0x4b, 0x84, 0x88, \ 0x43, 0x48, 0x99, 0x2c, 0xbb, 0xa4, 0x97, 0xd6, 0xd6, 0x18, 0xf6, 0xec, \ 0x5c, 0xd1, 0x31, 0x49, 0xc9, 0xf2, 0x8f, 0x0b, 0x4d, 0xef, 0x09, 0x02, \ 0xfe, 0x7d, 0xfd, 0xbb, 0xaf, 0x2b, 0x83, 0x94, 0x22, 0xc4, 0xa7, 0x3e, \ 0x66, 0xf5, 0xe0, 0x57, 0xdc, 0xf2, 0xed, 0x2c, 0x3e, 0x81, 0x74, 0x76, \ 0x1e, 0x96, 0x6f, 0x74, 0x1e, 0x32, 0x0e, 0x14, 0x31, 0xd0, 0x74, 0xf0, \ 0xf4, 0x07, 0xbd, 0xc3, 0xd1, 0x22, 0xc2, 0xa8, 0x95, 0x92, 0x06, 0x7f, \ 0x43, 0x02, 0x91, 0xbc, 0xdd, 0x23, 0x01, 0x89, 0x94, 0x20, 0x44, 0x64, \ 0xf5, 0x1d, 0x67, 0xd2, 0x8f, 0xe8, 0x69, 0xa5, 0x29, 0x25, 0xe6, 0x50, \ 0x9c, 0xe3, 0xe9, 0xcb, 0x75, 0x02, 0x81, 0x81, 0x00, 0xe2, 0x29, 0x3e, \ 0xaa, 0x6b, 0xd5, 0x59, 0x1e, 0x9c, 0xe6, 0x47, 0xd5, 0xb6, 0xd7, 0xe3, \ 0xf1, 0x8e, 0x9e, 0xe9, 0x83, 0x5f, 0x10, 0x9f, 0x63, 0xec, 0x04, 0x44, \ 0xcc, 0x3f, 0xf8, 0xd9, 0x3a, 0x17, 0xe0, 0x4f, 0xfe, 0xd8, 0x4d, 0xcd, \ 0x46, 0x54, 0x74, 0xbf, 0x0a, 0xc4, 0x67, 0x9c, 0xa7, 0xd8, 0x89, 0x65, \ 0x4c, 0xfd, 0x58, 0x2a, 0x47, 0x0f, 0xf4, 0x37, 0xb6, 0x55, 0xb0, 0x1d, \ 0xed, 0xa7, 0x39, 0xfc, 0x4f, 0xa3, 0xc4, 0x75, 0x3a, 0xa3, 0x98, 0xa7, \ 0x45, 0xf5, 0x66, 0xcb, 0x7c, 0x65, 0xfb, 0x80, 0x23, 0xe6, 0xff, 0xfd, \ 0x99, 0x1f, 0x8e, 0x6b, 0xff, 0x5e, 0x93, 0x66, 0xdf, 0x6c, 0x6f, 0xc3, \ 0xf6, 0x38, 0x2e, 0xff, 0x69, 0xb5, 0xac, 0xae, 0xbb, 0xc6, 0x71, 0x16, \ 0x6b, 0xd0, 0xf8, 0x22, 0xd9, 0xf8, 0xa2, 0x72, 0x20, 0xd2, 0xe2, 0x3a, \ 0x70, 0x4b, 0xde, 0xab, 0x2f, 0x02, 0x81, 0x81, 0x00, 0xda, 0x51, 0x9b, \ 0xb8, 0xb2, 0x2a, 0x14, 0x75, 0x58, 0x40, 0x8d, 0x27, 0x70, 0xfa, 0x31, \ 0x48, 0xb0, 0x20, 0x21, 0x34, 0xfa, 0x4c, 0x57, 0xa8, 0x11, 0x88, 0xf3, \ 0xa7, 0xae, 0x21, 0xe9, 0xb6, 0x2b, 0xd1, 0xcd, 0xa7, 0xf8, 0xd8, 0x0c, \ 0x8a, 0x76, 0x22, 0x35, 0x44, 0xce, 0x3f, 0x25, 0x29, 0x83, 0x7d, 0x79, \ 0xa7, 0x31, 0xd6, 0xec, 0xb2, 0xbf, 0xda, 0x34, 0xb6, 0xf6, 0xb2, 0x3b, \ 0xf3, 0x78, 0x5a, 0x04, 0x83, 0x33, 0x3e, 0xa2, 0xe2, 0x81, 0x82, 0x13, \ 0xd4, 0x35, 0x17, 0x63, 0x9b, 0x9e, 0xc4, 0x8d, 0x91, 0x4c, 0x03, 0x77, \ 0xc7, 0x71, 0x5b, 0xee, 0x83, 0x6d, 0xd5, 0x78, 0x88, 0xf6, 0x2c, 0x79, \ 0xc2, 0x4a, 0xb4, 0x79, 0x90, 0x70, 0xbf, 0xdf, 0x34, 0x56, 0x96, 0x71, \ 0xe3, 0x0e, 0x68, 0x91, 0xbc, 0xea, 0xcb, 0x33, 0xc0, 0xbe, 0x45, 0xd7, \ 0xfc, 0x30, 0xfd, 0x01, 0x3b, 0x02, 0x81, 0x81, 0x00, 0xd2, 0x9f, 0x2a, \ 0xb7, 0x38, 0x19, 0xc7, 0x17, 0x95, 0x73, 0x78, 0xae, 0xf5, 0xcb, 0x75, \ 0x83, 0x7f, 0x19, 0x4b, 0xcb, 0x86, 0xfb, 0x4a, 0x15, 0x9a, 0xb6, 0x17, \ 0x04, 0x49, 0x07, 0x8d, 0xf6, 0x66, 0x4a, 0x06, 0xf6, 0x05, 0xa7, 0xdf, \ 0x66, 0x82, 0x3c, 0xff, 0xb6, 0x1d, 0x57, 0x89, 0x33, 0x5f, 0x9c, 0x05, \ 0x75, 0x7f, 0xf3, 0x5d, 0xdc, 0x34, 0x65, 0x72, 0x85, 0x22, 0xa4, 0x14, \ 0x1b, 0x41, 0xc3, 0xe4, 0xd0, 0x9e, 0x69, 0xd5, 0xeb, 0x38, 0x74, 0x70, \ 0x43, 0xdc, 0xd9, 0x50, 0xe4, 0x97, 0x6d, 0x73, 0xd6, 0xfb, 0xc8, 0xa7, \ 0xfa, 0xb4, 0xc2, 0xc4, 0x9d, 0x5d, 0x0c, 0xd5, 0x9f, 0x79, 0xb3, 0x54, \ 0xc2, 0xb7, 0x6c, 0x3d, 0x7d, 0xcb, 0x2d, 0xf8, 0xc4, 0xf3, 0x78, 0x5a, \ 0x33, 0x2a, 0xb8, 0x0c, 0x6d, 0x06, 0xfa, 0xf2, 0x62, 0xd3, 0x42, 0xd0, \ 0xbd, 0xc8, 0x4a, 0xa5, 0x0d, 0x02, 0x81, 0x81, 0x00, 0xd4, 0xa9, 0x90, \ 0x15, 0xde, 0xbf, 0x2c, 0xc4, 0x8d, 0x9d, 0xfb, 0xa1, 0xc2, 0xe4, 0x83, \ 0xe3, 0x79, 0x65, 0x22, 0xd3, 0xb7, 0x49, 0x6c, 0x4d, 0x94, 0x1f, 0x22, \ 0xb1, 0x60, 0xe7, 0x3a, 0x00, 0xb1, 0x38, 0xa2, 0xab, 0x0f, 0xb4, 0x6c, \ 0xaa, 0xe7, 0x9e, 0x34, 0xe3, 0x7c, 0x40, 0x78, 0x53, 0xb2, 0xf9, 0x23, \ 0xea, 0xa0, 0x9a, 0xea, 0x60, 0xc8, 0x8f, 0xa6, 0xaf, 0xdf, 0x29, 0x09, \ 0x4b, 0x06, 0x1e, 0x31, 0xad, 0x17, 0xda, 0xd8, 0xd1, 0xe9, 0x33, 0xab, \ 0x5b, 0x18, 0x08, 0x5b, 0x87, 0xf8, 0xa5, 0x1f, 0xfd, 0xbb, 0xdc, 0xd8, \ 0xed, 0x97, 0x57, 0xe4, 0xc3, 0x73, 0xd6, 0xf0, 0x9e, 0x01, 0xa6, 0x9b, \ 0x48, 0x8e, 0x7a, 0xb4, 0xbb, 0xe5, 0x88, 0x91, 0xc5, 0x2a, 0xdf, 0x4b, \ 0xba, 0xd0, 0x8b, 0x3e, 0x03, 0x97, 0x77, 0x2f, 0x47, 0x7e, 0x51, 0x0c, \ 0xae, 0x65, 0x8d, 0xde, 0x87, 0x02, 0x81, 0x80, 0x20, 0x24, 0x0f, 0xd2, \ 0xaf, 0xc2, 0x28, 0x3b, 0x97, 0x20, 0xb2, 0x92, 0x49, 0xeb, 0x09, 0x68, \ 0x40, 0xb2, 0xbe, 0xd1, 0xc3, 0x83, 0x94, 0x34, 0x38, 0xd6, 0xc9, 0xec, \ 0x34, 0x09, 0xf9, 0x41, 0x6d, 0x5c, 0x42, 0x94, 0xf7, 0x04, 0xfc, 0x32, \ 0x39, 0x69, 0xbc, 0x1c, 0xfb, 0x3e, 0x61, 0x98, 0xc0, 0x80, 0xd8, 0x36, \ 0x47, 0xc3, 0x6d, 0xc2, 0x2e, 0xe7, 0x81, 0x2a, 0x17, 0x34, 0x64, 0x30, \ 0x4e, 0x96, 0xbb, 0x26, 0x16, 0xb9, 0x41, 0x36, 0xfe, 0x8a, 0xd6, 0x53, \ 0x7c, 0xaa, 0xec, 0x39, 0x42, 0x50, 0xef, 0xe3, 0xb3, 0x01, 0x28, 0x32, \ 0xca, 0x6d, 0xf5, 0x9a, 0x1e, 0x9f, 0x37, 0xbe, 0xfe, 0x38, 0x20, 0x22, \ 0x91, 0x8c, 0xcd, 0x95, 0x02, 0xf2, 0x4d, 0x6f, 0x1a, 0xb4, 0x43, 0xf0, \ 0x19, 0xdf, 0x65, 0xc0, 0x92, 0xe7, 0x9d, 0x2f, 0x09, 0xe7, 0xec, 0x69, \ 0xa8, 0xc2, 0x8f, 0x0d \ } /* END FILE */ /* * Test server Certificates * * Test server certificates are defined for each choice * of the following parameters: * - PEM or DER encoding * - SHA-1 or SHA-256 hash * - RSA or EC key * * Things to add: * - multiple EC curve types */ /* This is taken from tests/data_files/server5.crt. */ /* BEGIN FILE string macro TEST_SRV_CRT_EC_PEM tests/data_files/server5.crt */ #define TEST_SRV_CRT_EC_PEM \ "-----BEGIN CERTIFICATE-----\r\n" \ "MIICHzCCAaWgAwIBAgIBCTAKBggqhkjOPQQDAjA+MQswCQYDVQQGEwJOTDERMA8G\r\n" \ "A1UEChMIUG9sYXJTU0wxHDAaBgNVBAMTE1BvbGFyc3NsIFRlc3QgRUMgQ0EwHhcN\r\n" \ "MTMwOTI0MTU1MjA0WhcNMjMwOTIyMTU1MjA0WjA0MQswCQYDVQQGEwJOTDERMA8G\r\n" \ "A1UEChMIUG9sYXJTU0wxEjAQBgNVBAMTCWxvY2FsaG9zdDBZMBMGByqGSM49AgEG\r\n" \ "CCqGSM49AwEHA0IABDfMVtl2CR5acj7HWS3/IG7ufPkGkXTQrRS192giWWKSTuUA\r\n" \ "2CMR/+ov0jRdXRa9iojCa3cNVc2KKg76Aci07f+jgZ0wgZowCQYDVR0TBAIwADAd\r\n" \ "BgNVHQ4EFgQUUGGlj9QH2deCAQzlZX+MY0anE74wbgYDVR0jBGcwZYAUnW0gJEkB\r\n" \ "PyvLeLUZvH4kydv7NnyhQqRAMD4xCzAJBgNVBAYTAk5MMREwDwYDVQQKEwhQb2xh\r\n" \ "clNTTDEcMBoGA1UEAxMTUG9sYXJzc2wgVGVzdCBFQyBDQYIJAMFD4n5iQ8zoMAoG\r\n" \ "CCqGSM49BAMCA2gAMGUCMQCaLFzXptui5WQN8LlO3ddh1hMxx6tzgLvT03MTVK2S\r\n" \ "C12r0Lz3ri/moSEpNZWqPjkCMCE2f53GXcYLqyfyJR078c/xNSUU5+Xxl7VZ414V\r\n" \ "fGa5kHvHARBPc8YAIVIqDvHH1Q==\r\n" \ "-----END CERTIFICATE-----\r\n" /* END FILE */ /* This is generated from tests/data_files/server5.crt.der using `xxd -i`. */ /* BEGIN FILE binary macro TEST_SRV_CRT_EC_DER tests/data_files/server5.crt.der */ #define TEST_SRV_CRT_EC_DER { \ 0x30, 0x82, 0x02, 0x1f, 0x30, 0x82, 0x01, 0xa5, 0xa0, 0x03, 0x02, 0x01, \ 0x02, 0x02, 0x01, 0x09, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, \ 0x3d, 0x04, 0x03, 0x02, 0x30, 0x3e, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, \ 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, \ 0x03, 0x55, 0x04, 0x0a, 0x13, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, \ 0x53, 0x4c, 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, \ 0x13, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x73, 0x73, 0x6c, 0x20, 0x54, 0x65, \ 0x73, 0x74, 0x20, 0x45, 0x43, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, \ 0x31, 0x33, 0x30, 0x39, 0x32, 0x34, 0x31, 0x35, 0x35, 0x32, 0x30, 0x34, \ 0x5a, 0x17, 0x0d, 0x32, 0x33, 0x30, 0x39, 0x32, 0x32, 0x31, 0x35, 0x35, \ 0x32, 0x30, 0x34, 0x5a, 0x30, 0x34, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, \ 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, \ 0x03, 0x55, 0x04, 0x0a, 0x13, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, \ 0x53, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, \ 0x09, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73, 0x74, 0x30, 0x59, \ 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, \ 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, \ 0x04, 0x37, 0xcc, 0x56, 0xd9, 0x76, 0x09, 0x1e, 0x5a, 0x72, 0x3e, 0xc7, \ 0x59, 0x2d, 0xff, 0x20, 0x6e, 0xee, 0x7c, 0xf9, 0x06, 0x91, 0x74, 0xd0, \ 0xad, 0x14, 0xb5, 0xf7, 0x68, 0x22, 0x59, 0x62, 0x92, 0x4e, 0xe5, 0x00, \ 0xd8, 0x23, 0x11, 0xff, 0xea, 0x2f, 0xd2, 0x34, 0x5d, 0x5d, 0x16, 0xbd, \ 0x8a, 0x88, 0xc2, 0x6b, 0x77, 0x0d, 0x55, 0xcd, 0x8a, 0x2a, 0x0e, 0xfa, \ 0x01, 0xc8, 0xb4, 0xed, 0xff, 0xa3, 0x81, 0x9d, 0x30, 0x81, 0x9a, 0x30, \ 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x02, 0x30, 0x00, 0x30, 0x1d, \ 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x50, 0x61, 0xa5, \ 0x8f, 0xd4, 0x07, 0xd9, 0xd7, 0x82, 0x01, 0x0c, 0xe5, 0x65, 0x7f, 0x8c, \ 0x63, 0x46, 0xa7, 0x13, 0xbe, 0x30, 0x6e, 0x06, 0x03, 0x55, 0x1d, 0x23, \ 0x04, 0x67, 0x30, 0x65, 0x80, 0x14, 0x9d, 0x6d, 0x20, 0x24, 0x49, 0x01, \ 0x3f, 0x2b, 0xcb, 0x78, 0xb5, 0x19, 0xbc, 0x7e, 0x24, 0xc9, 0xdb, 0xfb, \ 0x36, 0x7c, 0xa1, 0x42, 0xa4, 0x40, 0x30, 0x3e, 0x31, 0x0b, 0x30, 0x09, \ 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, \ 0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x08, 0x50, 0x6f, 0x6c, 0x61, \ 0x72, 0x53, 0x53, 0x4c, 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x03, 0x55, 0x04, \ 0x03, 0x13, 0x13, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x73, 0x73, 0x6c, 0x20, \ 0x54, 0x65, 0x73, 0x74, 0x20, 0x45, 0x43, 0x20, 0x43, 0x41, 0x82, 0x09, \ 0x00, 0xc1, 0x43, 0xe2, 0x7e, 0x62, 0x43, 0xcc, 0xe8, 0x30, 0x0a, 0x06, \ 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x68, 0x00, \ 0x30, 0x65, 0x02, 0x31, 0x00, 0x9a, 0x2c, 0x5c, 0xd7, 0xa6, 0xdb, 0xa2, \ 0xe5, 0x64, 0x0d, 0xf0, 0xb9, 0x4e, 0xdd, 0xd7, 0x61, 0xd6, 0x13, 0x31, \ 0xc7, 0xab, 0x73, 0x80, 0xbb, 0xd3, 0xd3, 0x73, 0x13, 0x54, 0xad, 0x92, \ 0x0b, 0x5d, 0xab, 0xd0, 0xbc, 0xf7, 0xae, 0x2f, 0xe6, 0xa1, 0x21, 0x29, \ 0x35, 0x95, 0xaa, 0x3e, 0x39, 0x02, 0x30, 0x21, 0x36, 0x7f, 0x9d, 0xc6, \ 0x5d, 0xc6, 0x0b, 0xab, 0x27, 0xf2, 0x25, 0x1d, 0x3b, 0xf1, 0xcf, 0xf1, \ 0x35, 0x25, 0x14, 0xe7, 0xe5, 0xf1, 0x97, 0xb5, 0x59, 0xe3, 0x5e, 0x15, \ 0x7c, 0x66, 0xb9, 0x90, 0x7b, 0xc7, 0x01, 0x10, 0x4f, 0x73, 0xc6, 0x00, \ 0x21, 0x52, 0x2a, 0x0e, 0xf1, 0xc7, 0xd5 \ } /* END FILE */ /* This is taken from tests/data_files/server5.key. */ /* BEGIN FILE string macro TEST_SRV_KEY_EC_PEM tests/data_files/server5.key */ #define TEST_SRV_KEY_EC_PEM \ "-----BEGIN EC PRIVATE KEY-----\r\n" \ "MHcCAQEEIPEqEyB2AnCoPL/9U/YDHvdqXYbIogTywwyp6/UfDw6noAoGCCqGSM49\r\n" \ "AwEHoUQDQgAEN8xW2XYJHlpyPsdZLf8gbu58+QaRdNCtFLX3aCJZYpJO5QDYIxH/\r\n" \ "6i/SNF1dFr2KiMJrdw1VzYoqDvoByLTt/w==\r\n" \ "-----END EC PRIVATE KEY-----\r\n" /* END FILE */ /* This is generated from tests/data_files/server5.key.der using `xxd -i`. */ /* BEGIN FILE binary macro TEST_SRV_KEY_EC_DER tests/data_files/server5.key.der */ #define TEST_SRV_KEY_EC_DER { \ 0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20, 0xf1, 0x2a, 0x13, 0x20, 0x76, \ 0x02, 0x70, 0xa8, 0x3c, 0xbf, 0xfd, 0x53, 0xf6, 0x03, 0x1e, 0xf7, 0x6a, \ 0x5d, 0x86, 0xc8, 0xa2, 0x04, 0xf2, 0xc3, 0x0c, 0xa9, 0xeb, 0xf5, 0x1f, \ 0x0f, 0x0e, 0xa7, 0xa0, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, \ 0x03, 0x01, 0x07, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0x37, 0xcc, 0x56, \ 0xd9, 0x76, 0x09, 0x1e, 0x5a, 0x72, 0x3e, 0xc7, 0x59, 0x2d, 0xff, 0x20, \ 0x6e, 0xee, 0x7c, 0xf9, 0x06, 0x91, 0x74, 0xd0, 0xad, 0x14, 0xb5, 0xf7, \ 0x68, 0x22, 0x59, 0x62, 0x92, 0x4e, 0xe5, 0x00, 0xd8, 0x23, 0x11, 0xff, \ 0xea, 0x2f, 0xd2, 0x34, 0x5d, 0x5d, 0x16, 0xbd, 0x8a, 0x88, 0xc2, 0x6b, \ 0x77, 0x0d, 0x55, 0xcd, 0x8a, 0x2a, 0x0e, 0xfa, 0x01, 0xc8, 0xb4, 0xed, \ 0xff \ } /* END FILE */ /* This is taken from tests/data_files/server2-sha256.crt. */ /* BEGIN FILE string macro TEST_SRV_CRT_RSA_SHA256_PEM tests/data_files/server2-sha256.crt */ #define TEST_SRV_CRT_RSA_SHA256_PEM \ "-----BEGIN CERTIFICATE-----\r\n" \ "MIIDNzCCAh+gAwIBAgIBAjANBgkqhkiG9w0BAQsFADA7MQswCQYDVQQGEwJOTDER\r\n" \ "MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n" \ "MTkwMjEwMTQ0NDA2WhcNMjkwMjEwMTQ0NDA2WjA0MQswCQYDVQQGEwJOTDERMA8G\r\n" \ "A1UECgwIUG9sYXJTU0wxEjAQBgNVBAMMCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcN\r\n" \ "AQEBBQADggEPADCCAQoCggEBAMFNo93nzR3RBNdJcriZrA545Do8Ss86ExbQWuTN\r\n" \ "owCIp+4ea5anUrSQ7y1yej4kmvy2NKwk9XfgJmSMnLAofaHa6ozmyRyWvP7BBFKz\r\n" \ "NtSj+uGxdtiQwWG0ZlI2oiZTqqt0Xgd9GYLbKtgfoNkNHC1JZvdbJXNG6AuKT2kM\r\n" \ "tQCQ4dqCEGZ9rlQri2V5kaHiYcPNQEkI7mgM8YuG0ka/0LiqEQMef1aoGh5EGA8P\r\n" \ "hYvai0Re4hjGYi/HZo36Xdh98yeJKQHFkA4/J/EwyEoO79bex8cna8cFPXrEAjya\r\n" \ "HT4P6DSYW8tzS1KW2BGiLICIaTla0w+w3lkvEcf36hIBMJcCAwEAAaNNMEswCQYD\r\n" \ "VR0TBAIwADAdBgNVHQ4EFgQUpQXoZLjc32APUBJNYKhkr02LQ5MwHwYDVR0jBBgw\r\n" \ "FoAUtFrkpbPe0lL2udWmlQ/rPrzH/f8wDQYJKoZIhvcNAQELBQADggEBAC465FJh\r\n" \ "Pqel7zJngHIHJrqj/wVAxGAFOTF396XKATGAp+HRCqJ81Ry60CNK1jDzk8dv6M6U\r\n" \ "HoS7RIFiM/9rXQCbJfiPD5xMTejZp5n5UYHAmxsxDaazfA5FuBhkfokKK6jD4Eq9\r\n" \ "1C94xGKb6X4/VkaPF7cqoBBw/bHxawXc0UEPjqayiBpCYU/rJoVZgLqFVP7Px3sv\r\n" \ "a1nOrNx8rPPI1hJ+ZOg8maiPTxHZnBVLakSSLQy/sWeWyazO1RnrbxjrbgQtYKz0\r\n" \ "e3nwGpu1w13vfckFmUSBhHXH7AAS/HpKC4IH7G2GAk3+n8iSSN71sZzpxonQwVbo\r\n" \ "pMZqLmbBm/7WPLc=\r\n" \ "-----END CERTIFICATE-----\r\n" /* END FILE */ /* This is taken from tests/data_files/server2-sha256.crt.der. */ /* BEGIN FILE binary macro TEST_SRV_CRT_RSA_SHA256_DER tests/data_files/server2-sha256.crt.der */ #define TEST_SRV_CRT_RSA_SHA256_DER { \ 0x30, 0x82, 0x03, 0x37, 0x30, 0x82, 0x02, 0x1f, 0xa0, 0x03, 0x02, 0x01, \ 0x02, 0x02, 0x01, 0x02, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, \ 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x3b, 0x31, 0x0b, 0x30, \ 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, \ 0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, \ 0x61, 0x72, 0x53, 0x53, 0x4c, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, \ 0x04, 0x03, 0x0c, 0x10, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, \ 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, \ 0x31, 0x39, 0x30, 0x32, 0x31, 0x30, 0x31, 0x34, 0x34, 0x34, 0x30, 0x36, \ 0x5a, 0x17, 0x0d, 0x32, 0x39, 0x30, 0x32, 0x31, 0x30, 0x31, 0x34, 0x34, \ 0x34, 0x30, 0x36, 0x5a, 0x30, 0x34, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, \ 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, \ 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, \ 0x53, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, \ 0x09, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73, 0x74, 0x30, 0x82, \ 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, \ 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, \ 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xc1, 0x4d, 0xa3, 0xdd, 0xe7, \ 0xcd, 0x1d, 0xd1, 0x04, 0xd7, 0x49, 0x72, 0xb8, 0x99, 0xac, 0x0e, 0x78, \ 0xe4, 0x3a, 0x3c, 0x4a, 0xcf, 0x3a, 0x13, 0x16, 0xd0, 0x5a, 0xe4, 0xcd, \ 0xa3, 0x00, 0x88, 0xa7, 0xee, 0x1e, 0x6b, 0x96, 0xa7, 0x52, 0xb4, 0x90, \ 0xef, 0x2d, 0x72, 0x7a, 0x3e, 0x24, 0x9a, 0xfc, 0xb6, 0x34, 0xac, 0x24, \ 0xf5, 0x77, 0xe0, 0x26, 0x64, 0x8c, 0x9c, 0xb0, 0x28, 0x7d, 0xa1, 0xda, \ 0xea, 0x8c, 0xe6, 0xc9, 0x1c, 0x96, 0xbc, 0xfe, 0xc1, 0x04, 0x52, 0xb3, \ 0x36, 0xd4, 0xa3, 0xfa, 0xe1, 0xb1, 0x76, 0xd8, 0x90, 0xc1, 0x61, 0xb4, \ 0x66, 0x52, 0x36, 0xa2, 0x26, 0x53, 0xaa, 0xab, 0x74, 0x5e, 0x07, 0x7d, \ 0x19, 0x82, 0xdb, 0x2a, 0xd8, 0x1f, 0xa0, 0xd9, 0x0d, 0x1c, 0x2d, 0x49, \ 0x66, 0xf7, 0x5b, 0x25, 0x73, 0x46, 0xe8, 0x0b, 0x8a, 0x4f, 0x69, 0x0c, \ 0xb5, 0x00, 0x90, 0xe1, 0xda, 0x82, 0x10, 0x66, 0x7d, 0xae, 0x54, 0x2b, \ 0x8b, 0x65, 0x79, 0x91, 0xa1, 0xe2, 0x61, 0xc3, 0xcd, 0x40, 0x49, 0x08, \ 0xee, 0x68, 0x0c, 0xf1, 0x8b, 0x86, 0xd2, 0x46, 0xbf, 0xd0, 0xb8, 0xaa, \ 0x11, 0x03, 0x1e, 0x7f, 0x56, 0xa8, 0x1a, 0x1e, 0x44, 0x18, 0x0f, 0x0f, \ 0x85, 0x8b, 0xda, 0x8b, 0x44, 0x5e, 0xe2, 0x18, 0xc6, 0x62, 0x2f, 0xc7, \ 0x66, 0x8d, 0xfa, 0x5d, 0xd8, 0x7d, 0xf3, 0x27, 0x89, 0x29, 0x01, 0xc5, \ 0x90, 0x0e, 0x3f, 0x27, 0xf1, 0x30, 0xc8, 0x4a, 0x0e, 0xef, 0xd6, 0xde, \ 0xc7, 0xc7, 0x27, 0x6b, 0xc7, 0x05, 0x3d, 0x7a, 0xc4, 0x02, 0x3c, 0x9a, \ 0x1d, 0x3e, 0x0f, 0xe8, 0x34, 0x98, 0x5b, 0xcb, 0x73, 0x4b, 0x52, 0x96, \ 0xd8, 0x11, 0xa2, 0x2c, 0x80, 0x88, 0x69, 0x39, 0x5a, 0xd3, 0x0f, 0xb0, \ 0xde, 0x59, 0x2f, 0x11, 0xc7, 0xf7, 0xea, 0x12, 0x01, 0x30, 0x97, 0x02, \ 0x03, 0x01, 0x00, 0x01, 0xa3, 0x4d, 0x30, 0x4b, 0x30, 0x09, 0x06, 0x03, \ 0x55, 0x1d, 0x13, 0x04, 0x02, 0x30, 0x00, 0x30, 0x1d, 0x06, 0x03, 0x55, \ 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0xa5, 0x05, 0xe8, 0x64, 0xb8, 0xdc, \ 0xdf, 0x60, 0x0f, 0x50, 0x12, 0x4d, 0x60, 0xa8, 0x64, 0xaf, 0x4d, 0x8b, \ 0x43, 0x93, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, \ 0x16, 0x80, 0x14, 0xb4, 0x5a, 0xe4, 0xa5, 0xb3, 0xde, 0xd2, 0x52, 0xf6, \ 0xb9, 0xd5, 0xa6, 0x95, 0x0f, 0xeb, 0x3e, 0xbc, 0xc7, 0xfd, 0xff, 0x30, \ 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, \ 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x2e, 0x3a, 0xe4, 0x52, 0x61, \ 0x3e, 0xa7, 0xa5, 0xef, 0x32, 0x67, 0x80, 0x72, 0x07, 0x26, 0xba, 0xa3, \ 0xff, 0x05, 0x40, 0xc4, 0x60, 0x05, 0x39, 0x31, 0x77, 0xf7, 0xa5, 0xca, \ 0x01, 0x31, 0x80, 0xa7, 0xe1, 0xd1, 0x0a, 0xa2, 0x7c, 0xd5, 0x1c, 0xba, \ 0xd0, 0x23, 0x4a, 0xd6, 0x30, 0xf3, 0x93, 0xc7, 0x6f, 0xe8, 0xce, 0x94, \ 0x1e, 0x84, 0xbb, 0x44, 0x81, 0x62, 0x33, 0xff, 0x6b, 0x5d, 0x00, 0x9b, \ 0x25, 0xf8, 0x8f, 0x0f, 0x9c, 0x4c, 0x4d, 0xe8, 0xd9, 0xa7, 0x99, 0xf9, \ 0x51, 0x81, 0xc0, 0x9b, 0x1b, 0x31, 0x0d, 0xa6, 0xb3, 0x7c, 0x0e, 0x45, \ 0xb8, 0x18, 0x64, 0x7e, 0x89, 0x0a, 0x2b, 0xa8, 0xc3, 0xe0, 0x4a, 0xbd, \ 0xd4, 0x2f, 0x78, 0xc4, 0x62, 0x9b, 0xe9, 0x7e, 0x3f, 0x56, 0x46, 0x8f, \ 0x17, 0xb7, 0x2a, 0xa0, 0x10, 0x70, 0xfd, 0xb1, 0xf1, 0x6b, 0x05, 0xdc, \ 0xd1, 0x41, 0x0f, 0x8e, 0xa6, 0xb2, 0x88, 0x1a, 0x42, 0x61, 0x4f, 0xeb, \ 0x26, 0x85, 0x59, 0x80, 0xba, 0x85, 0x54, 0xfe, 0xcf, 0xc7, 0x7b, 0x2f, \ 0x6b, 0x59, 0xce, 0xac, 0xdc, 0x7c, 0xac, 0xf3, 0xc8, 0xd6, 0x12, 0x7e, \ 0x64, 0xe8, 0x3c, 0x99, 0xa8, 0x8f, 0x4f, 0x11, 0xd9, 0x9c, 0x15, 0x4b, \ 0x6a, 0x44, 0x92, 0x2d, 0x0c, 0xbf, 0xb1, 0x67, 0x96, 0xc9, 0xac, 0xce, \ 0xd5, 0x19, 0xeb, 0x6f, 0x18, 0xeb, 0x6e, 0x04, 0x2d, 0x60, 0xac, 0xf4, \ 0x7b, 0x79, 0xf0, 0x1a, 0x9b, 0xb5, 0xc3, 0x5d, 0xef, 0x7d, 0xc9, 0x05, \ 0x99, 0x44, 0x81, 0x84, 0x75, 0xc7, 0xec, 0x00, 0x12, 0xfc, 0x7a, 0x4a, \ 0x0b, 0x82, 0x07, 0xec, 0x6d, 0x86, 0x02, 0x4d, 0xfe, 0x9f, 0xc8, 0x92, \ 0x48, 0xde, 0xf5, 0xb1, 0x9c, 0xe9, 0xc6, 0x89, 0xd0, 0xc1, 0x56, 0xe8, \ 0xa4, 0xc6, 0x6a, 0x2e, 0x66, 0xc1, 0x9b, 0xfe, 0xd6, 0x3c, 0xb7 \ } /* END FILE */ /* This is taken from tests/data_files/server2.crt. */ /* BEGIN FILE string macro TEST_SRV_CRT_RSA_SHA1_PEM tests/data_files/server2.crt */ #define TEST_SRV_CRT_RSA_SHA1_PEM \ "-----BEGIN CERTIFICATE-----\r\n" \ "MIIDNzCCAh+gAwIBAgIBAjANBgkqhkiG9w0BAQUFADA7MQswCQYDVQQGEwJOTDER\r\n" \ "MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n" \ "MTkwMjEwMTQ0NDA2WhcNMjkwMjEwMTQ0NDA2WjA0MQswCQYDVQQGEwJOTDERMA8G\r\n" \ "A1UECgwIUG9sYXJTU0wxEjAQBgNVBAMMCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcN\r\n" \ "AQEBBQADggEPADCCAQoCggEBAMFNo93nzR3RBNdJcriZrA545Do8Ss86ExbQWuTN\r\n" \ "owCIp+4ea5anUrSQ7y1yej4kmvy2NKwk9XfgJmSMnLAofaHa6ozmyRyWvP7BBFKz\r\n" \ "NtSj+uGxdtiQwWG0ZlI2oiZTqqt0Xgd9GYLbKtgfoNkNHC1JZvdbJXNG6AuKT2kM\r\n" \ "tQCQ4dqCEGZ9rlQri2V5kaHiYcPNQEkI7mgM8YuG0ka/0LiqEQMef1aoGh5EGA8P\r\n" \ "hYvai0Re4hjGYi/HZo36Xdh98yeJKQHFkA4/J/EwyEoO79bex8cna8cFPXrEAjya\r\n" \ "HT4P6DSYW8tzS1KW2BGiLICIaTla0w+w3lkvEcf36hIBMJcCAwEAAaNNMEswCQYD\r\n" \ "VR0TBAIwADAdBgNVHQ4EFgQUpQXoZLjc32APUBJNYKhkr02LQ5MwHwYDVR0jBBgw\r\n" \ "FoAUtFrkpbPe0lL2udWmlQ/rPrzH/f8wDQYJKoZIhvcNAQEFBQADggEBAJklg3Q4\r\n" \ "cB7v7BzsxM/vLyKccO6op0/gZzM4ghuLq2Y32kl0sM6kSNUUmduuq3u/+GmUZN2A\r\n" \ "O/7c+Hw7hDFEIvZk98aBGjCLqn3DmgHIv8ToQ67nellQxx2Uj309PdgjNi/r9HOc\r\n" \ "KNAYPbBcg6MJGWWj2TI6vNaceios/DhOYx5V0j5nfqSJ/pnU0g9Ign2LAhgYpGJE\r\n" \ "iEM9wW7hEMkwmk0h/sqZsrJsGH5YsF/VThSq/JVO1e2mZH2vruyZKJVBq+8tDNYp\r\n" \ "HkK6tSyVYQhzIt3StMJWKMl/o5k2AYz6tSC164+1oG+ML3LWg8XrGKa91H4UOKap\r\n" \ "Awgk0+4m0T25cNs=\r\n" \ "-----END CERTIFICATE-----\r\n" /* END FILE */ /* This is taken from tests/data_files/server2.crt.der. */ /* BEGIN FILE binary macro TEST_SRV_CRT_RSA_SHA1_DER tests/data_files/server2.crt.der */ #define TEST_SRV_CRT_RSA_SHA1_DER { \ 0x30, 0x82, 0x03, 0x37, 0x30, 0x82, 0x02, 0x1f, 0xa0, 0x03, 0x02, 0x01, \ 0x02, 0x02, 0x01, 0x02, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, \ 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30, 0x3b, 0x31, 0x0b, 0x30, \ 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, \ 0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, \ 0x61, 0x72, 0x53, 0x53, 0x4c, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, \ 0x04, 0x03, 0x0c, 0x10, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, \ 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, \ 0x31, 0x31, 0x30, 0x32, 0x31, 0x32, 0x31, 0x34, 0x34, 0x34, 0x30, 0x36, \ 0x5a, 0x17, 0x0d, 0x32, 0x31, 0x30, 0x32, 0x31, 0x32, 0x31, 0x34, 0x34, \ 0x34, 0x30, 0x36, 0x5a, 0x30, 0x34, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, \ 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, \ 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, \ 0x53, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, \ 0x09, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73, 0x74, 0x30, 0x82, \ 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, \ 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, \ 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xc1, 0x4d, 0xa3, 0xdd, 0xe7, \ 0xcd, 0x1d, 0xd1, 0x04, 0xd7, 0x49, 0x72, 0xb8, 0x99, 0xac, 0x0e, 0x78, \ 0xe4, 0x3a, 0x3c, 0x4a, 0xcf, 0x3a, 0x13, 0x16, 0xd0, 0x5a, 0xe4, 0xcd, \ 0xa3, 0x00, 0x88, 0xa7, 0xee, 0x1e, 0x6b, 0x96, 0xa7, 0x52, 0xb4, 0x90, \ 0xef, 0x2d, 0x72, 0x7a, 0x3e, 0x24, 0x9a, 0xfc, 0xb6, 0x34, 0xac, 0x24, \ 0xf5, 0x77, 0xe0, 0x26, 0x64, 0x8c, 0x9c, 0xb0, 0x28, 0x7d, 0xa1, 0xda, \ 0xea, 0x8c, 0xe6, 0xc9, 0x1c, 0x96, 0xbc, 0xfe, 0xc1, 0x04, 0x52, 0xb3, \ 0x36, 0xd4, 0xa3, 0xfa, 0xe1, 0xb1, 0x76, 0xd8, 0x90, 0xc1, 0x61, 0xb4, \ 0x66, 0x52, 0x36, 0xa2, 0x26, 0x53, 0xaa, 0xab, 0x74, 0x5e, 0x07, 0x7d, \ 0x19, 0x82, 0xdb, 0x2a, 0xd8, 0x1f, 0xa0, 0xd9, 0x0d, 0x1c, 0x2d, 0x49, \ 0x66, 0xf7, 0x5b, 0x25, 0x73, 0x46, 0xe8, 0x0b, 0x8a, 0x4f, 0x69, 0x0c, \ 0xb5, 0x00, 0x90, 0xe1, 0xda, 0x82, 0x10, 0x66, 0x7d, 0xae, 0x54, 0x2b, \ 0x8b, 0x65, 0x79, 0x91, 0xa1, 0xe2, 0x61, 0xc3, 0xcd, 0x40, 0x49, 0x08, \ 0xee, 0x68, 0x0c, 0xf1, 0x8b, 0x86, 0xd2, 0x46, 0xbf, 0xd0, 0xb8, 0xaa, \ 0x11, 0x03, 0x1e, 0x7f, 0x56, 0xa8, 0x1a, 0x1e, 0x44, 0x18, 0x0f, 0x0f, \ 0x85, 0x8b, 0xda, 0x8b, 0x44, 0x5e, 0xe2, 0x18, 0xc6, 0x62, 0x2f, 0xc7, \ 0x66, 0x8d, 0xfa, 0x5d, 0xd8, 0x7d, 0xf3, 0x27, 0x89, 0x29, 0x01, 0xc5, \ 0x90, 0x0e, 0x3f, 0x27, 0xf1, 0x30, 0xc8, 0x4a, 0x0e, 0xef, 0xd6, 0xde, \ 0xc7, 0xc7, 0x27, 0x6b, 0xc7, 0x05, 0x3d, 0x7a, 0xc4, 0x02, 0x3c, 0x9a, \ 0x1d, 0x3e, 0x0f, 0xe8, 0x34, 0x98, 0x5b, 0xcb, 0x73, 0x4b, 0x52, 0x96, \ 0xd8, 0x11, 0xa2, 0x2c, 0x80, 0x88, 0x69, 0x39, 0x5a, 0xd3, 0x0f, 0xb0, \ 0xde, 0x59, 0x2f, 0x11, 0xc7, 0xf7, 0xea, 0x12, 0x01, 0x30, 0x97, 0x02, \ 0x03, 0x01, 0x00, 0x01, 0xa3, 0x4d, 0x30, 0x4b, 0x30, 0x09, 0x06, 0x03, \ 0x55, 0x1d, 0x13, 0x04, 0x02, 0x30, 0x00, 0x30, 0x1d, 0x06, 0x03, 0x55, \ 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0xa5, 0x05, 0xe8, 0x64, 0xb8, 0xdc, \ 0xdf, 0x60, 0x0f, 0x50, 0x12, 0x4d, 0x60, 0xa8, 0x64, 0xaf, 0x4d, 0x8b, \ 0x43, 0x93, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, \ 0x16, 0x80, 0x14, 0xb4, 0x5a, 0xe4, 0xa5, 0xb3, 0xde, 0xd2, 0x52, 0xf6, \ 0xb9, 0xd5, 0xa6, 0x95, 0x0f, 0xeb, 0x3e, 0xbc, 0xc7, 0xfd, 0xff, 0x30, \ 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, \ 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x01, 0x73, 0x0b, 0x4a, 0xc5, \ 0xcb, 0xa0, 0xde, 0xf1, 0x63, 0x1c, 0x76, 0x04, 0x2b, 0x13, 0x0d, 0xc0, \ 0x84, 0x11, 0xc5, 0x8f, 0x3a, 0xa7, 0xc5, 0x9c, 0x35, 0x7a, 0x77, 0xb8, \ 0x20, 0x14, 0x82, 0xee, 0x54, 0xf0, 0xf2, 0xb0, 0x52, 0xcb, 0x78, 0xce, \ 0x59, 0x07, 0x4f, 0x51, 0x69, 0xfe, 0xd3, 0x2f, 0xe9, 0x09, 0xe7, 0x85, \ 0x92, 0xd8, 0xba, 0xb1, 0xeb, 0xc5, 0x76, 0x5d, 0x61, 0x2d, 0xe9, 0x86, \ 0xb5, 0xde, 0x2a, 0xf9, 0x3f, 0x53, 0x28, 0x42, 0x86, 0x83, 0x73, 0x43, \ 0xe0, 0x04, 0x5f, 0x07, 0x90, 0x14, 0x65, 0x9f, 0x6e, 0x10, 0x7a, 0xbc, \ 0x58, 0x19, 0x22, 0xc2, 0xeb, 0x39, 0x72, 0x51, 0x92, 0xd7, 0xb4, 0x1d, \ 0x75, 0x2f, 0xd3, 0x3a, 0x2b, 0x01, 0xe7, 0xdb, 0x50, 0xae, 0xe2, 0xf1, \ 0xd4, 0x4d, 0x5b, 0x3c, 0xbb, 0x41, 0x2b, 0x2a, 0xa4, 0xe2, 0x4a, 0x02, \ 0xe5, 0x60, 0x14, 0x2c, 0x9c, 0x1f, 0xa6, 0xcc, 0x06, 0x4b, 0x25, 0x89, \ 0x4e, 0x96, 0x30, 0x22, 0x9c, 0x5c, 0x58, 0x4d, 0xc3, 0xda, 0xd0, 0x6e, \ 0x50, 0x1e, 0x8c, 0x65, 0xf5, 0xd9, 0x17, 0x35, 0xa6, 0x58, 0x43, 0xb2, \ 0x29, 0xb7, 0xa8, 0x5e, 0x35, 0xde, 0xf0, 0x60, 0x42, 0x1a, 0x01, 0xcb, \ 0xcb, 0x0b, 0xd8, 0x0e, 0xc1, 0x90, 0xdf, 0xa1, 0xd2, 0x1a, 0xd1, 0x2c, \ 0x02, 0xf4, 0x76, 0x41, 0xa4, 0xcb, 0x4b, 0x15, 0x98, 0x71, 0xf9, 0x35, \ 0x7d, 0xb0, 0xe7, 0xe2, 0x34, 0x96, 0x91, 0xbe, 0x32, 0x67, 0x2d, 0x6b, \ 0xd3, 0x55, 0x04, 0x8a, 0x01, 0x50, 0xb4, 0xe3, 0x62, 0x78, 0x6c, 0x11, \ 0x15, 0xa5, 0x2a, 0x11, 0xc1, 0x49, 0x1c, 0x9b, 0xc4, 0x10, 0x65, 0x60, \ 0x87, 0xd9, 0x1e, 0x69, 0x59, 0x4e, 0x8f, 0x6b, 0xeb, 0xc1, 0xfe, 0x6b, \ 0xe2, 0x63, 0x78, 0x95, 0x6e, 0xe0, 0x2d, 0xd7, 0xa7, 0x37, 0xa8 \ } /* END FILE */ /* This is taken from tests/data_files/server2.key. */ /* BEGIN FILE string macro TEST_SRV_KEY_RSA_PEM tests/data_files/server2.key */ #define TEST_SRV_KEY_RSA_PEM \ "-----BEGIN RSA PRIVATE KEY-----\r\n" \ "MIIEpAIBAAKCAQEAwU2j3efNHdEE10lyuJmsDnjkOjxKzzoTFtBa5M2jAIin7h5r\r\n" \ "lqdStJDvLXJ6PiSa/LY0rCT1d+AmZIycsCh9odrqjObJHJa8/sEEUrM21KP64bF2\r\n" \ "2JDBYbRmUjaiJlOqq3ReB30Zgtsq2B+g2Q0cLUlm91slc0boC4pPaQy1AJDh2oIQ\r\n" \ "Zn2uVCuLZXmRoeJhw81ASQjuaAzxi4bSRr/QuKoRAx5/VqgaHkQYDw+Fi9qLRF7i\r\n" \ "GMZiL8dmjfpd2H3zJ4kpAcWQDj8n8TDISg7v1t7HxydrxwU9esQCPJodPg/oNJhb\r\n" \ "y3NLUpbYEaIsgIhpOVrTD7DeWS8Rx/fqEgEwlwIDAQABAoIBAQCXR0S8EIHFGORZ\r\n" \ "++AtOg6eENxD+xVs0f1IeGz57Tjo3QnXX7VBZNdj+p1ECvhCE/G7XnkgU5hLZX+G\r\n" \ "Z0jkz/tqJOI0vRSdLBbipHnWouyBQ4e/A1yIJdlBtqXxJ1KE/ituHRbNc4j4kL8Z\r\n" \ "/r6pvwnTI0PSx2Eqs048YdS92LT6qAv4flbNDxMn2uY7s4ycS4Q8w1JXnCeaAnYm\r\n" \ "WYI5wxO+bvRELR2Mcz5DmVnL8jRyml6l6582bSv5oufReFIbyPZbQWlXgYnpu6He\r\n" \ "GTc7E1zKYQGG/9+DQUl/1vQuCPqQwny0tQoX2w5tdYpdMdVm+zkLtbajzdTviJJa\r\n" \ "TWzL6lt5AoGBAN86+SVeJDcmQJcv4Eq6UhtRr4QGMiQMz0Sod6ettYxYzMgxtw28\r\n" \ "CIrgpozCc+UaZJLo7UxvC6an85r1b2nKPCLQFaggJ0H4Q0J/sZOhBIXaoBzWxveK\r\n" \ "nupceKdVxGsFi8CDy86DBfiyFivfBj+47BbaQzPBj7C4rK7UlLjab2rDAoGBAN2u\r\n" \ "AM2gchoFiu4v1HFL8D7lweEpi6ZnMJjnEu/dEgGQJFjwdpLnPbsj4c75odQ4Gz8g\r\n" \ "sw9lao9VVzbusoRE/JGI4aTdO0pATXyG7eG1Qu+5Yc1YGXcCrliA2xM9xx+d7f+s\r\n" \ "mPzN+WIEg5GJDYZDjAzHG5BNvi/FfM1C9dOtjv2dAoGAF0t5KmwbjWHBhcVqO4Ic\r\n" \ "BVvN3BIlc1ue2YRXEDlxY5b0r8N4XceMgKmW18OHApZxfl8uPDauWZLXOgl4uepv\r\n" \ "whZC3EuWrSyyICNhLY21Ah7hbIEBPF3L3ZsOwC+UErL+dXWLdB56Jgy3gZaBeW7b\r\n" \ "vDrEnocJbqCm7IukhXHOBK8CgYEAwqdHB0hqyNSzIOGY7v9abzB6pUdA3BZiQvEs\r\n" \ "3LjHVd4HPJ2x0N8CgrBIWOE0q8+0hSMmeE96WW/7jD3fPWwCR5zlXknxBQsfv0gP\r\n" \ "3BC5PR0Qdypz+d+9zfMf625kyit4T/hzwhDveZUzHnk1Cf+IG7Q+TOEnLnWAWBED\r\n" \ "ISOWmrUCgYAFEmRxgwAc/u+D6t0syCwAYh6POtscq9Y0i9GyWk89NzgC4NdwwbBH\r\n" \ "4AgahOxIxXx2gxJnq3yfkJfIjwf0s2DyP0kY2y6Ua1OeomPeY9mrIS4tCuDQ6LrE\r\n" \ "TB6l9VGoxJL4fyHnZb8L5gGvnB1bbD8cL6YPaDiOhcRseC9vBiEuVg==\r\n" \ "-----END RSA PRIVATE KEY-----\r\n" /* END FILE */ /* This was generated from tests/data_files/server2.key.der using `xxd -i`. */ /* BEGIN FILE binary macro TEST_SRV_KEY_RSA_DER tests/data_files/server2.key.der */ #define TEST_SRV_KEY_RSA_DER { \ 0x30, 0x82, 0x04, 0xa4, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, \ 0xc1, 0x4d, 0xa3, 0xdd, 0xe7, 0xcd, 0x1d, 0xd1, 0x04, 0xd7, 0x49, 0x72, \ 0xb8, 0x99, 0xac, 0x0e, 0x78, 0xe4, 0x3a, 0x3c, 0x4a, 0xcf, 0x3a, 0x13, \ 0x16, 0xd0, 0x5a, 0xe4, 0xcd, 0xa3, 0x00, 0x88, 0xa7, 0xee, 0x1e, 0x6b, \ 0x96, 0xa7, 0x52, 0xb4, 0x90, 0xef, 0x2d, 0x72, 0x7a, 0x3e, 0x24, 0x9a, \ 0xfc, 0xb6, 0x34, 0xac, 0x24, 0xf5, 0x77, 0xe0, 0x26, 0x64, 0x8c, 0x9c, \ 0xb0, 0x28, 0x7d, 0xa1, 0xda, 0xea, 0x8c, 0xe6, 0xc9, 0x1c, 0x96, 0xbc, \ 0xfe, 0xc1, 0x04, 0x52, 0xb3, 0x36, 0xd4, 0xa3, 0xfa, 0xe1, 0xb1, 0x76, \ 0xd8, 0x90, 0xc1, 0x61, 0xb4, 0x66, 0x52, 0x36, 0xa2, 0x26, 0x53, 0xaa, \ 0xab, 0x74, 0x5e, 0x07, 0x7d, 0x19, 0x82, 0xdb, 0x2a, 0xd8, 0x1f, 0xa0, \ 0xd9, 0x0d, 0x1c, 0x2d, 0x49, 0x66, 0xf7, 0x5b, 0x25, 0x73, 0x46, 0xe8, \ 0x0b, 0x8a, 0x4f, 0x69, 0x0c, 0xb5, 0x00, 0x90, 0xe1, 0xda, 0x82, 0x10, \ 0x66, 0x7d, 0xae, 0x54, 0x2b, 0x8b, 0x65, 0x79, 0x91, 0xa1, 0xe2, 0x61, \ 0xc3, 0xcd, 0x40, 0x49, 0x08, 0xee, 0x68, 0x0c, 0xf1, 0x8b, 0x86, 0xd2, \ 0x46, 0xbf, 0xd0, 0xb8, 0xaa, 0x11, 0x03, 0x1e, 0x7f, 0x56, 0xa8, 0x1a, \ 0x1e, 0x44, 0x18, 0x0f, 0x0f, 0x85, 0x8b, 0xda, 0x8b, 0x44, 0x5e, 0xe2, \ 0x18, 0xc6, 0x62, 0x2f, 0xc7, 0x66, 0x8d, 0xfa, 0x5d, 0xd8, 0x7d, 0xf3, \ 0x27, 0x89, 0x29, 0x01, 0xc5, 0x90, 0x0e, 0x3f, 0x27, 0xf1, 0x30, 0xc8, \ 0x4a, 0x0e, 0xef, 0xd6, 0xde, 0xc7, 0xc7, 0x27, 0x6b, 0xc7, 0x05, 0x3d, \ 0x7a, 0xc4, 0x02, 0x3c, 0x9a, 0x1d, 0x3e, 0x0f, 0xe8, 0x34, 0x98, 0x5b, \ 0xcb, 0x73, 0x4b, 0x52, 0x96, 0xd8, 0x11, 0xa2, 0x2c, 0x80, 0x88, 0x69, \ 0x39, 0x5a, 0xd3, 0x0f, 0xb0, 0xde, 0x59, 0x2f, 0x11, 0xc7, 0xf7, 0xea, \ 0x12, 0x01, 0x30, 0x97, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x82, 0x01, \ 0x01, 0x00, 0x97, 0x47, 0x44, 0xbc, 0x10, 0x81, 0xc5, 0x18, 0xe4, 0x59, \ 0xfb, 0xe0, 0x2d, 0x3a, 0x0e, 0x9e, 0x10, 0xdc, 0x43, 0xfb, 0x15, 0x6c, \ 0xd1, 0xfd, 0x48, 0x78, 0x6c, 0xf9, 0xed, 0x38, 0xe8, 0xdd, 0x09, 0xd7, \ 0x5f, 0xb5, 0x41, 0x64, 0xd7, 0x63, 0xfa, 0x9d, 0x44, 0x0a, 0xf8, 0x42, \ 0x13, 0xf1, 0xbb, 0x5e, 0x79, 0x20, 0x53, 0x98, 0x4b, 0x65, 0x7f, 0x86, \ 0x67, 0x48, 0xe4, 0xcf, 0xfb, 0x6a, 0x24, 0xe2, 0x34, 0xbd, 0x14, 0x9d, \ 0x2c, 0x16, 0xe2, 0xa4, 0x79, 0xd6, 0xa2, 0xec, 0x81, 0x43, 0x87, 0xbf, \ 0x03, 0x5c, 0x88, 0x25, 0xd9, 0x41, 0xb6, 0xa5, 0xf1, 0x27, 0x52, 0x84, \ 0xfe, 0x2b, 0x6e, 0x1d, 0x16, 0xcd, 0x73, 0x88, 0xf8, 0x90, 0xbf, 0x19, \ 0xfe, 0xbe, 0xa9, 0xbf, 0x09, 0xd3, 0x23, 0x43, 0xd2, 0xc7, 0x61, 0x2a, \ 0xb3, 0x4e, 0x3c, 0x61, 0xd4, 0xbd, 0xd8, 0xb4, 0xfa, 0xa8, 0x0b, 0xf8, \ 0x7e, 0x56, 0xcd, 0x0f, 0x13, 0x27, 0xda, 0xe6, 0x3b, 0xb3, 0x8c, 0x9c, \ 0x4b, 0x84, 0x3c, 0xc3, 0x52, 0x57, 0x9c, 0x27, 0x9a, 0x02, 0x76, 0x26, \ 0x59, 0x82, 0x39, 0xc3, 0x13, 0xbe, 0x6e, 0xf4, 0x44, 0x2d, 0x1d, 0x8c, \ 0x73, 0x3e, 0x43, 0x99, 0x59, 0xcb, 0xf2, 0x34, 0x72, 0x9a, 0x5e, 0xa5, \ 0xeb, 0x9f, 0x36, 0x6d, 0x2b, 0xf9, 0xa2, 0xe7, 0xd1, 0x78, 0x52, 0x1b, \ 0xc8, 0xf6, 0x5b, 0x41, 0x69, 0x57, 0x81, 0x89, 0xe9, 0xbb, 0xa1, 0xde, \ 0x19, 0x37, 0x3b, 0x13, 0x5c, 0xca, 0x61, 0x01, 0x86, 0xff, 0xdf, 0x83, \ 0x41, 0x49, 0x7f, 0xd6, 0xf4, 0x2e, 0x08, 0xfa, 0x90, 0xc2, 0x7c, 0xb4, \ 0xb5, 0x0a, 0x17, 0xdb, 0x0e, 0x6d, 0x75, 0x8a, 0x5d, 0x31, 0xd5, 0x66, \ 0xfb, 0x39, 0x0b, 0xb5, 0xb6, 0xa3, 0xcd, 0xd4, 0xef, 0x88, 0x92, 0x5a, \ 0x4d, 0x6c, 0xcb, 0xea, 0x5b, 0x79, 0x02, 0x81, 0x81, 0x00, 0xdf, 0x3a, \ 0xf9, 0x25, 0x5e, 0x24, 0x37, 0x26, 0x40, 0x97, 0x2f, 0xe0, 0x4a, 0xba, \ 0x52, 0x1b, 0x51, 0xaf, 0x84, 0x06, 0x32, 0x24, 0x0c, 0xcf, 0x44, 0xa8, \ 0x77, 0xa7, 0xad, 0xb5, 0x8c, 0x58, 0xcc, 0xc8, 0x31, 0xb7, 0x0d, 0xbc, \ 0x08, 0x8a, 0xe0, 0xa6, 0x8c, 0xc2, 0x73, 0xe5, 0x1a, 0x64, 0x92, 0xe8, \ 0xed, 0x4c, 0x6f, 0x0b, 0xa6, 0xa7, 0xf3, 0x9a, 0xf5, 0x6f, 0x69, 0xca, \ 0x3c, 0x22, 0xd0, 0x15, 0xa8, 0x20, 0x27, 0x41, 0xf8, 0x43, 0x42, 0x7f, \ 0xb1, 0x93, 0xa1, 0x04, 0x85, 0xda, 0xa0, 0x1c, 0xd6, 0xc6, 0xf7, 0x8a, \ 0x9e, 0xea, 0x5c, 0x78, 0xa7, 0x55, 0xc4, 0x6b, 0x05, 0x8b, 0xc0, 0x83, \ 0xcb, 0xce, 0x83, 0x05, 0xf8, 0xb2, 0x16, 0x2b, 0xdf, 0x06, 0x3f, 0xb8, \ 0xec, 0x16, 0xda, 0x43, 0x33, 0xc1, 0x8f, 0xb0, 0xb8, 0xac, 0xae, 0xd4, \ 0x94, 0xb8, 0xda, 0x6f, 0x6a, 0xc3, 0x02, 0x81, 0x81, 0x00, 0xdd, 0xae, \ 0x00, 0xcd, 0xa0, 0x72, 0x1a, 0x05, 0x8a, 0xee, 0x2f, 0xd4, 0x71, 0x4b, \ 0xf0, 0x3e, 0xe5, 0xc1, 0xe1, 0x29, 0x8b, 0xa6, 0x67, 0x30, 0x98, 0xe7, \ 0x12, 0xef, 0xdd, 0x12, 0x01, 0x90, 0x24, 0x58, 0xf0, 0x76, 0x92, 0xe7, \ 0x3d, 0xbb, 0x23, 0xe1, 0xce, 0xf9, 0xa1, 0xd4, 0x38, 0x1b, 0x3f, 0x20, \ 0xb3, 0x0f, 0x65, 0x6a, 0x8f, 0x55, 0x57, 0x36, 0xee, 0xb2, 0x84, 0x44, \ 0xfc, 0x91, 0x88, 0xe1, 0xa4, 0xdd, 0x3b, 0x4a, 0x40, 0x4d, 0x7c, 0x86, \ 0xed, 0xe1, 0xb5, 0x42, 0xef, 0xb9, 0x61, 0xcd, 0x58, 0x19, 0x77, 0x02, \ 0xae, 0x58, 0x80, 0xdb, 0x13, 0x3d, 0xc7, 0x1f, 0x9d, 0xed, 0xff, 0xac, \ 0x98, 0xfc, 0xcd, 0xf9, 0x62, 0x04, 0x83, 0x91, 0x89, 0x0d, 0x86, 0x43, \ 0x8c, 0x0c, 0xc7, 0x1b, 0x90, 0x4d, 0xbe, 0x2f, 0xc5, 0x7c, 0xcd, 0x42, \ 0xf5, 0xd3, 0xad, 0x8e, 0xfd, 0x9d, 0x02, 0x81, 0x80, 0x17, 0x4b, 0x79, \ 0x2a, 0x6c, 0x1b, 0x8d, 0x61, 0xc1, 0x85, 0xc5, 0x6a, 0x3b, 0x82, 0x1c, \ 0x05, 0x5b, 0xcd, 0xdc, 0x12, 0x25, 0x73, 0x5b, 0x9e, 0xd9, 0x84, 0x57, \ 0x10, 0x39, 0x71, 0x63, 0x96, 0xf4, 0xaf, 0xc3, 0x78, 0x5d, 0xc7, 0x8c, \ 0x80, 0xa9, 0x96, 0xd7, 0xc3, 0x87, 0x02, 0x96, 0x71, 0x7e, 0x5f, 0x2e, \ 0x3c, 0x36, 0xae, 0x59, 0x92, 0xd7, 0x3a, 0x09, 0x78, 0xb9, 0xea, 0x6f, \ 0xc2, 0x16, 0x42, 0xdc, 0x4b, 0x96, 0xad, 0x2c, 0xb2, 0x20, 0x23, 0x61, \ 0x2d, 0x8d, 0xb5, 0x02, 0x1e, 0xe1, 0x6c, 0x81, 0x01, 0x3c, 0x5d, 0xcb, \ 0xdd, 0x9b, 0x0e, 0xc0, 0x2f, 0x94, 0x12, 0xb2, 0xfe, 0x75, 0x75, 0x8b, \ 0x74, 0x1e, 0x7a, 0x26, 0x0c, 0xb7, 0x81, 0x96, 0x81, 0x79, 0x6e, 0xdb, \ 0xbc, 0x3a, 0xc4, 0x9e, 0x87, 0x09, 0x6e, 0xa0, 0xa6, 0xec, 0x8b, 0xa4, \ 0x85, 0x71, 0xce, 0x04, 0xaf, 0x02, 0x81, 0x81, 0x00, 0xc2, 0xa7, 0x47, \ 0x07, 0x48, 0x6a, 0xc8, 0xd4, 0xb3, 0x20, 0xe1, 0x98, 0xee, 0xff, 0x5a, \ 0x6f, 0x30, 0x7a, 0xa5, 0x47, 0x40, 0xdc, 0x16, 0x62, 0x42, 0xf1, 0x2c, \ 0xdc, 0xb8, 0xc7, 0x55, 0xde, 0x07, 0x3c, 0x9d, 0xb1, 0xd0, 0xdf, 0x02, \ 0x82, 0xb0, 0x48, 0x58, 0xe1, 0x34, 0xab, 0xcf, 0xb4, 0x85, 0x23, 0x26, \ 0x78, 0x4f, 0x7a, 0x59, 0x6f, 0xfb, 0x8c, 0x3d, 0xdf, 0x3d, 0x6c, 0x02, \ 0x47, 0x9c, 0xe5, 0x5e, 0x49, 0xf1, 0x05, 0x0b, 0x1f, 0xbf, 0x48, 0x0f, \ 0xdc, 0x10, 0xb9, 0x3d, 0x1d, 0x10, 0x77, 0x2a, 0x73, 0xf9, 0xdf, 0xbd, \ 0xcd, 0xf3, 0x1f, 0xeb, 0x6e, 0x64, 0xca, 0x2b, 0x78, 0x4f, 0xf8, 0x73, \ 0xc2, 0x10, 0xef, 0x79, 0x95, 0x33, 0x1e, 0x79, 0x35, 0x09, 0xff, 0x88, \ 0x1b, 0xb4, 0x3e, 0x4c, 0xe1, 0x27, 0x2e, 0x75, 0x80, 0x58, 0x11, 0x03, \ 0x21, 0x23, 0x96, 0x9a, 0xb5, 0x02, 0x81, 0x80, 0x05, 0x12, 0x64, 0x71, \ 0x83, 0x00, 0x1c, 0xfe, 0xef, 0x83, 0xea, 0xdd, 0x2c, 0xc8, 0x2c, 0x00, \ 0x62, 0x1e, 0x8f, 0x3a, 0xdb, 0x1c, 0xab, 0xd6, 0x34, 0x8b, 0xd1, 0xb2, \ 0x5a, 0x4f, 0x3d, 0x37, 0x38, 0x02, 0xe0, 0xd7, 0x70, 0xc1, 0xb0, 0x47, \ 0xe0, 0x08, 0x1a, 0x84, 0xec, 0x48, 0xc5, 0x7c, 0x76, 0x83, 0x12, 0x67, \ 0xab, 0x7c, 0x9f, 0x90, 0x97, 0xc8, 0x8f, 0x07, 0xf4, 0xb3, 0x60, 0xf2, \ 0x3f, 0x49, 0x18, 0xdb, 0x2e, 0x94, 0x6b, 0x53, 0x9e, 0xa2, 0x63, 0xde, \ 0x63, 0xd9, 0xab, 0x21, 0x2e, 0x2d, 0x0a, 0xe0, 0xd0, 0xe8, 0xba, 0xc4, \ 0x4c, 0x1e, 0xa5, 0xf5, 0x51, 0xa8, 0xc4, 0x92, 0xf8, 0x7f, 0x21, 0xe7, \ 0x65, 0xbf, 0x0b, 0xe6, 0x01, 0xaf, 0x9c, 0x1d, 0x5b, 0x6c, 0x3f, 0x1c, \ 0x2f, 0xa6, 0x0f, 0x68, 0x38, 0x8e, 0x85, 0xc4, 0x6c, 0x78, 0x2f, 0x6f, \ 0x06, 0x21, 0x2e, 0x56 \ } /* END FILE */ /* * Test client Certificates * * Test client certificates are defined for each choice * of the following parameters: * - PEM or DER encoding * - RSA or EC key * * Things to add: * - hash type * - multiple EC curve types */ /* This is taken from tests/data_files/cli2.crt. */ /* BEGIN FILE string macro TEST_CLI_CRT_EC_PEM tests/data_files/cli2.crt */ #define TEST_CLI_CRT_EC_PEM \ "-----BEGIN CERTIFICATE-----\r\n" \ "MIIB3zCCAWOgAwIBAgIBDTAMBggqhkjOPQQDAgUAMD4xCzAJBgNVBAYTAk5MMREw\r\n" \ "DwYDVQQKDAhQb2xhclNTTDEcMBoGA1UEAwwTUG9sYXJTU0wgVGVzdCBFQyBDQTAe\r\n" \ "Fw0xOTAyMTAxNDQ0MDBaFw0yOTAyMTAxNDQ0MDBaMEExCzAJBgNVBAYTAk5MMREw\r\n" \ "DwYDVQQKDAhQb2xhclNTTDEfMB0GA1UEAwwWUG9sYXJTU0wgVGVzdCBDbGllbnQg\r\n" \ "MjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABFflrrFz39Osu5O4gf8Sru7mU6zO\r\n" \ "VVP2NA7MLuNjJQvfmOLzXGA2lsDVGBRw5X+f1UtFGOWwbNVc+JaPh3Cj5MejTTBL\r\n" \ "MAkGA1UdEwQCMAAwHQYDVR0OBBYEFHoAX4Zk/OBd5REQO7LmO8QmP8/iMB8GA1Ud\r\n" \ "IwQYMBaAFJ1tICRJAT8ry3i1Gbx+JMnb+zZ8MAwGCCqGSM49BAMCBQADaAAwZQIx\r\n" \ "AMqme4DKMldUlplDET9Q6Eptre7uUWKhsLOF+zPkKDlfzpIkJYEFgcloDHGYw80u\r\n" \ "IgIwNftyPXsabTqMM7iEHgVpX/GRozKklY9yQI/5eoA6gGW7Y+imuGR/oao5ySOb\r\n" \ "a9Vk\r\n" \ "-----END CERTIFICATE-----\r\n" /* END FILE */ /* This is generated from tests/data_files/cli2.crt.der using `xxd -i`. */ /* BEGIN FILE binary macro TEST_CLI_CRT_EC_DER tests/data_files/cli2.crt.der */ #define TEST_CLI_CRT_EC_DER { \ 0x30, 0x82, 0x01, 0xdf, 0x30, 0x82, 0x01, 0x63, 0xa0, 0x03, 0x02, 0x01, \ 0x02, 0x02, 0x01, 0x0d, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, \ 0x3d, 0x04, 0x03, 0x02, 0x05, 0x00, 0x30, 0x3e, 0x31, 0x0b, 0x30, 0x09, \ 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, \ 0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, 0x61, \ 0x72, 0x53, 0x53, 0x4c, 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x03, 0x55, 0x04, \ 0x03, 0x0c, 0x13, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, 0x20, \ 0x54, 0x65, 0x73, 0x74, 0x20, 0x45, 0x43, 0x20, 0x43, 0x41, 0x30, 0x1e, \ 0x17, 0x0d, 0x31, 0x39, 0x30, 0x32, 0x31, 0x30, 0x31, 0x34, 0x34, 0x34, \ 0x30, 0x30, 0x5a, 0x17, 0x0d, 0x32, 0x39, 0x30, 0x32, 0x31, 0x30, 0x31, \ 0x34, 0x34, 0x34, 0x30, 0x30, 0x5a, 0x30, 0x41, 0x31, 0x0b, 0x30, 0x09, \ 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, \ 0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, 0x61, \ 0x72, 0x53, 0x53, 0x4c, 0x31, 0x1f, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x04, \ 0x03, 0x0c, 0x16, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, 0x20, \ 0x54, 0x65, 0x73, 0x74, 0x20, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x20, \ 0x32, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, \ 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, \ 0x03, 0x42, 0x00, 0x04, 0x57, 0xe5, 0xae, 0xb1, 0x73, 0xdf, 0xd3, 0xac, \ 0xbb, 0x93, 0xb8, 0x81, 0xff, 0x12, 0xae, 0xee, 0xe6, 0x53, 0xac, 0xce, \ 0x55, 0x53, 0xf6, 0x34, 0x0e, 0xcc, 0x2e, 0xe3, 0x63, 0x25, 0x0b, 0xdf, \ 0x98, 0xe2, 0xf3, 0x5c, 0x60, 0x36, 0x96, 0xc0, 0xd5, 0x18, 0x14, 0x70, \ 0xe5, 0x7f, 0x9f, 0xd5, 0x4b, 0x45, 0x18, 0xe5, 0xb0, 0x6c, 0xd5, 0x5c, \ 0xf8, 0x96, 0x8f, 0x87, 0x70, 0xa3, 0xe4, 0xc7, 0xa3, 0x4d, 0x30, 0x4b, \ 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x02, 0x30, 0x00, 0x30, \ 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x7a, 0x00, \ 0x5f, 0x86, 0x64, 0xfc, 0xe0, 0x5d, 0xe5, 0x11, 0x10, 0x3b, 0xb2, 0xe6, \ 0x3b, 0xc4, 0x26, 0x3f, 0xcf, 0xe2, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, \ 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x9d, 0x6d, 0x20, 0x24, 0x49, \ 0x01, 0x3f, 0x2b, 0xcb, 0x78, 0xb5, 0x19, 0xbc, 0x7e, 0x24, 0xc9, 0xdb, \ 0xfb, 0x36, 0x7c, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, \ 0x04, 0x03, 0x02, 0x05, 0x00, 0x03, 0x68, 0x00, 0x30, 0x65, 0x02, 0x31, \ 0x00, 0xca, 0xa6, 0x7b, 0x80, 0xca, 0x32, 0x57, 0x54, 0x96, 0x99, 0x43, \ 0x11, 0x3f, 0x50, 0xe8, 0x4a, 0x6d, 0xad, 0xee, 0xee, 0x51, 0x62, 0xa1, \ 0xb0, 0xb3, 0x85, 0xfb, 0x33, 0xe4, 0x28, 0x39, 0x5f, 0xce, 0x92, 0x24, \ 0x25, 0x81, 0x05, 0x81, 0xc9, 0x68, 0x0c, 0x71, 0x98, 0xc3, 0xcd, 0x2e, \ 0x22, 0x02, 0x30, 0x35, 0xfb, 0x72, 0x3d, 0x7b, 0x1a, 0x6d, 0x3a, 0x8c, \ 0x33, 0xb8, 0x84, 0x1e, 0x05, 0x69, 0x5f, 0xf1, 0x91, 0xa3, 0x32, 0xa4, \ 0x95, 0x8f, 0x72, 0x40, 0x8f, 0xf9, 0x7a, 0x80, 0x3a, 0x80, 0x65, 0xbb, \ 0x63, 0xe8, 0xa6, 0xb8, 0x64, 0x7f, 0xa1, 0xaa, 0x39, 0xc9, 0x23, 0x9b, \ 0x6b, 0xd5, 0x64 \ } /* END FILE */ /* This is taken from tests/data_files/cli2.key. */ /* BEGIN FILE string macro TEST_CLI_KEY_EC_PEM tests/data_files/cli2.key */ #define TEST_CLI_KEY_EC_PEM \ "-----BEGIN EC PRIVATE KEY-----\r\n" \ "MHcCAQEEIPb3hmTxZ3/mZI3vyk7p3U3wBf+WIop6hDhkFzJhmLcqoAoGCCqGSM49\r\n" \ "AwEHoUQDQgAEV+WusXPf06y7k7iB/xKu7uZTrM5VU/Y0Dswu42MlC9+Y4vNcYDaW\r\n" \ "wNUYFHDlf5/VS0UY5bBs1Vz4lo+HcKPkxw==\r\n" \ "-----END EC PRIVATE KEY-----\r\n" /* END FILE */ /* This is generated from tests/data_files/cli2.key.der using `xxd -i`. */ /* BEGIN FILE binary macro TEST_CLI_KEY_EC_DER tests/data_files/cli2.key.der */ #define TEST_CLI_KEY_EC_DER { \ 0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20, 0xf6, 0xf7, 0x86, 0x64, 0xf1, \ 0x67, 0x7f, 0xe6, 0x64, 0x8d, 0xef, 0xca, 0x4e, 0xe9, 0xdd, 0x4d, 0xf0, \ 0x05, 0xff, 0x96, 0x22, 0x8a, 0x7a, 0x84, 0x38, 0x64, 0x17, 0x32, 0x61, \ 0x98, 0xb7, 0x2a, 0xa0, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, \ 0x03, 0x01, 0x07, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0x57, 0xe5, 0xae, \ 0xb1, 0x73, 0xdf, 0xd3, 0xac, 0xbb, 0x93, 0xb8, 0x81, 0xff, 0x12, 0xae, \ 0xee, 0xe6, 0x53, 0xac, 0xce, 0x55, 0x53, 0xf6, 0x34, 0x0e, 0xcc, 0x2e, \ 0xe3, 0x63, 0x25, 0x0b, 0xdf, 0x98, 0xe2, 0xf3, 0x5c, 0x60, 0x36, 0x96, \ 0xc0, 0xd5, 0x18, 0x14, 0x70, 0xe5, 0x7f, 0x9f, 0xd5, 0x4b, 0x45, 0x18, \ 0xe5, 0xb0, 0x6c, 0xd5, 0x5c, 0xf8, 0x96, 0x8f, 0x87, 0x70, 0xa3, 0xe4, \ 0xc7 \ } /* END FILE */ /* This is taken from tests/data_files/cli-rsa-sha256.crt. */ /* BEGIN FILE string macro TEST_CLI_CRT_RSA_PEM tests/data_files/cli-rsa-sha256.crt */ #define TEST_CLI_CRT_RSA_PEM \ "-----BEGIN CERTIFICATE-----\r\n" \ "MIIDPzCCAiegAwIBAgIBBDANBgkqhkiG9w0BAQsFADA7MQswCQYDVQQGEwJOTDER\r\n" \ "MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n" \ "MTkwMjEwMTQ0NDA2WhcNMjkwMjEwMTQ0NDA2WjA8MQswCQYDVQQGEwJOTDERMA8G\r\n" \ "A1UECgwIUG9sYXJTU0wxGjAYBgNVBAMMEVBvbGFyU1NMIENsaWVudCAyMIIBIjAN\r\n" \ "BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyHTEzLn5tXnpRdkUYLB9u5Pyax6f\r\n" \ "M60Nj4o8VmXl3ETZzGaFB9X4J7BKNdBjngpuG7fa8H6r7gwQk4ZJGDTzqCrSV/Uu\r\n" \ "1C93KYRhTYJQj6eVSHD1bk2y1RPD0hrt5kPqQhTrdOrA7R/UV06p86jt0uDBMHEw\r\n" \ "MjDV0/YI0FZPRo7yX/k9Z5GIMC5Cst99++UMd//sMcB4j7/Cf8qtbCHWjdmLao5v\r\n" \ "4Jv4EFbMs44TFeY0BGbH7vk2DmqV9gmaBmf0ZXH4yqSxJeD+PIs1BGe64E92hfx/\r\n" \ "/DZrtenNLQNiTrM9AM+vdqBpVoNq0qjU51Bx5rU2BXcFbXvI5MT9TNUhXwIDAQAB\r\n" \ "o00wSzAJBgNVHRMEAjAAMB0GA1UdDgQWBBRxoQBzckAvVHZeM/xSj7zx3WtGITAf\r\n" \ "BgNVHSMEGDAWgBS0WuSls97SUva51aaVD+s+vMf9/zANBgkqhkiG9w0BAQsFAAOC\r\n" \ "AQEAXidv1d4pLlBiKWED95rMycBdgDcgyNqJxakFkRfRyA2y1mlyTn7uBXRkNLY5\r\n" \ "ZFzK82GCjk2Q2OD4RZSCPAJJqLpHHU34t71ciffvy2KK81YvrxczRhMAE64i+qna\r\n" \ "yP3Td2XuWJR05PVPoSemsNELs9gWttdnYy3ce+EY2Y0n7Rsi7982EeLIAA7H6ca4\r\n" \ "2Es/NUH//JZJT32OP0doMxeDRA+vplkKqTLLWf7dX26LIriBkBaRCgR5Yv9LBPFc\r\n" \ "NOtpzu/LbrY7QFXKJMI+JXDudCsOn8KCmiA4d6Emisqfh3V3485l7HEQNcvLTxlD\r\n" \ "6zDQyi0/ykYUYZkwQTK1N2Nvlw==\r\n" \ "-----END CERTIFICATE-----\r\n" /* END FILE */ /* This was generated from tests/data_files/cli-rsa-sha256.crt.der using `xxd -i.` */ /* BEGIN FILE binary macro TEST_CLI_CRT_RSA_DER tests/data_files/cli-rsa-sha256.crt.der */ #define TEST_CLI_CRT_RSA_DER { \ 0x30, 0x82, 0x03, 0x3f, 0x30, 0x82, 0x02, 0x27, 0xa0, 0x03, 0x02, 0x01, \ 0x02, 0x02, 0x01, 0x04, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, \ 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x3b, 0x31, 0x0b, 0x30, \ 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, \ 0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, \ 0x61, 0x72, 0x53, 0x53, 0x4c, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, \ 0x04, 0x03, 0x0c, 0x10, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, \ 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, \ 0x31, 0x39, 0x30, 0x32, 0x31, 0x30, 0x31, 0x34, 0x34, 0x34, 0x30, 0x36, \ 0x5a, 0x17, 0x0d, 0x32, 0x39, 0x30, 0x32, 0x31, 0x30, 0x31, 0x34, 0x34, \ 0x34, 0x30, 0x36, 0x5a, 0x30, 0x3c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, \ 0x55, 0x04, 0x06, 0x13, 0x02, 0x4e, 0x4c, 0x31, 0x11, 0x30, 0x0f, 0x06, \ 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x08, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, \ 0x53, 0x4c, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, \ 0x11, 0x50, 0x6f, 0x6c, 0x61, 0x72, 0x53, 0x53, 0x4c, 0x20, 0x43, 0x6c, \ 0x69, 0x65, 0x6e, 0x74, 0x20, 0x32, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, \ 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, \ 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, \ 0x01, 0x01, 0x00, 0xc8, 0x74, 0xc4, 0xcc, 0xb9, 0xf9, 0xb5, 0x79, 0xe9, \ 0x45, 0xd9, 0x14, 0x60, 0xb0, 0x7d, 0xbb, 0x93, 0xf2, 0x6b, 0x1e, 0x9f, \ 0x33, 0xad, 0x0d, 0x8f, 0x8a, 0x3c, 0x56, 0x65, 0xe5, 0xdc, 0x44, 0xd9, \ 0xcc, 0x66, 0x85, 0x07, 0xd5, 0xf8, 0x27, 0xb0, 0x4a, 0x35, 0xd0, 0x63, \ 0x9e, 0x0a, 0x6e, 0x1b, 0xb7, 0xda, 0xf0, 0x7e, 0xab, 0xee, 0x0c, 0x10, \ 0x93, 0x86, 0x49, 0x18, 0x34, 0xf3, 0xa8, 0x2a, 0xd2, 0x57, 0xf5, 0x2e, \ 0xd4, 0x2f, 0x77, 0x29, 0x84, 0x61, 0x4d, 0x82, 0x50, 0x8f, 0xa7, 0x95, \ 0x48, 0x70, 0xf5, 0x6e, 0x4d, 0xb2, 0xd5, 0x13, 0xc3, 0xd2, 0x1a, 0xed, \ 0xe6, 0x43, 0xea, 0x42, 0x14, 0xeb, 0x74, 0xea, 0xc0, 0xed, 0x1f, 0xd4, \ 0x57, 0x4e, 0xa9, 0xf3, 0xa8, 0xed, 0xd2, 0xe0, 0xc1, 0x30, 0x71, 0x30, \ 0x32, 0x30, 0xd5, 0xd3, 0xf6, 0x08, 0xd0, 0x56, 0x4f, 0x46, 0x8e, 0xf2, \ 0x5f, 0xf9, 0x3d, 0x67, 0x91, 0x88, 0x30, 0x2e, 0x42, 0xb2, 0xdf, 0x7d, \ 0xfb, 0xe5, 0x0c, 0x77, 0xff, 0xec, 0x31, 0xc0, 0x78, 0x8f, 0xbf, 0xc2, \ 0x7f, 0xca, 0xad, 0x6c, 0x21, 0xd6, 0x8d, 0xd9, 0x8b, 0x6a, 0x8e, 0x6f, \ 0xe0, 0x9b, 0xf8, 0x10, 0x56, 0xcc, 0xb3, 0x8e, 0x13, 0x15, 0xe6, 0x34, \ 0x04, 0x66, 0xc7, 0xee, 0xf9, 0x36, 0x0e, 0x6a, 0x95, 0xf6, 0x09, 0x9a, \ 0x06, 0x67, 0xf4, 0x65, 0x71, 0xf8, 0xca, 0xa4, 0xb1, 0x25, 0xe0, 0xfe, \ 0x3c, 0x8b, 0x35, 0x04, 0x67, 0xba, 0xe0, 0x4f, 0x76, 0x85, 0xfc, 0x7f, \ 0xfc, 0x36, 0x6b, 0xb5, 0xe9, 0xcd, 0x2d, 0x03, 0x62, 0x4e, 0xb3, 0x3d, \ 0x00, 0xcf, 0xaf, 0x76, 0xa0, 0x69, 0x56, 0x83, 0x6a, 0xd2, 0xa8, 0xd4, \ 0xe7, 0x50, 0x71, 0xe6, 0xb5, 0x36, 0x05, 0x77, 0x05, 0x6d, 0x7b, 0xc8, \ 0xe4, 0xc4, 0xfd, 0x4c, 0xd5, 0x21, 0x5f, 0x02, 0x03, 0x01, 0x00, 0x01, \ 0xa3, 0x4d, 0x30, 0x4b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, \ 0x02, 0x30, 0x00, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, \ 0x04, 0x14, 0x71, 0xa1, 0x00, 0x73, 0x72, 0x40, 0x2f, 0x54, 0x76, 0x5e, \ 0x33, 0xfc, 0x52, 0x8f, 0xbc, 0xf1, 0xdd, 0x6b, 0x46, 0x21, 0x30, 0x1f, \ 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0xb4, \ 0x5a, 0xe4, 0xa5, 0xb3, 0xde, 0xd2, 0x52, 0xf6, 0xb9, 0xd5, 0xa6, 0x95, \ 0x0f, 0xeb, 0x3e, 0xbc, 0xc7, 0xfd, 0xff, 0x30, 0x0d, 0x06, 0x09, 0x2a, \ 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03, 0x82, \ 0x01, 0x01, 0x00, 0x5e, 0x27, 0x6f, 0xd5, 0xde, 0x29, 0x2e, 0x50, 0x62, \ 0x29, 0x61, 0x03, 0xf7, 0x9a, 0xcc, 0xc9, 0xc0, 0x5d, 0x80, 0x37, 0x20, \ 0xc8, 0xda, 0x89, 0xc5, 0xa9, 0x05, 0x91, 0x17, 0xd1, 0xc8, 0x0d, 0xb2, \ 0xd6, 0x69, 0x72, 0x4e, 0x7e, 0xee, 0x05, 0x74, 0x64, 0x34, 0xb6, 0x39, \ 0x64, 0x5c, 0xca, 0xf3, 0x61, 0x82, 0x8e, 0x4d, 0x90, 0xd8, 0xe0, 0xf8, \ 0x45, 0x94, 0x82, 0x3c, 0x02, 0x49, 0xa8, 0xba, 0x47, 0x1d, 0x4d, 0xf8, \ 0xb7, 0xbd, 0x5c, 0x89, 0xf7, 0xef, 0xcb, 0x62, 0x8a, 0xf3, 0x56, 0x2f, \ 0xaf, 0x17, 0x33, 0x46, 0x13, 0x00, 0x13, 0xae, 0x22, 0xfa, 0xa9, 0xda, \ 0xc8, 0xfd, 0xd3, 0x77, 0x65, 0xee, 0x58, 0x94, 0x74, 0xe4, 0xf5, 0x4f, \ 0xa1, 0x27, 0xa6, 0xb0, 0xd1, 0x0b, 0xb3, 0xd8, 0x16, 0xb6, 0xd7, 0x67, \ 0x63, 0x2d, 0xdc, 0x7b, 0xe1, 0x18, 0xd9, 0x8d, 0x27, 0xed, 0x1b, 0x22, \ 0xef, 0xdf, 0x36, 0x11, 0xe2, 0xc8, 0x00, 0x0e, 0xc7, 0xe9, 0xc6, 0xb8, \ 0xd8, 0x4b, 0x3f, 0x35, 0x41, 0xff, 0xfc, 0x96, 0x49, 0x4f, 0x7d, 0x8e, \ 0x3f, 0x47, 0x68, 0x33, 0x17, 0x83, 0x44, 0x0f, 0xaf, 0xa6, 0x59, 0x0a, \ 0xa9, 0x32, 0xcb, 0x59, 0xfe, 0xdd, 0x5f, 0x6e, 0x8b, 0x22, 0xb8, 0x81, \ 0x90, 0x16, 0x91, 0x0a, 0x04, 0x79, 0x62, 0xff, 0x4b, 0x04, 0xf1, 0x5c, \ 0x34, 0xeb, 0x69, 0xce, 0xef, 0xcb, 0x6e, 0xb6, 0x3b, 0x40, 0x55, 0xca, \ 0x24, 0xc2, 0x3e, 0x25, 0x70, 0xee, 0x74, 0x2b, 0x0e, 0x9f, 0xc2, 0x82, \ 0x9a, 0x20, 0x38, 0x77, 0xa1, 0x26, 0x8a, 0xca, 0x9f, 0x87, 0x75, 0x77, \ 0xe3, 0xce, 0x65, 0xec, 0x71, 0x10, 0x35, 0xcb, 0xcb, 0x4f, 0x19, 0x43, \ 0xeb, 0x30, 0xd0, 0xca, 0x2d, 0x3f, 0xca, 0x46, 0x14, 0x61, 0x99, 0x30, \ 0x41, 0x32, 0xb5, 0x37, 0x63, 0x6f, 0x97 \ } /* END FILE */ /* This is taken from tests/data_files/cli-rsa.key. */ /* BEGIN FILE string macro TEST_CLI_KEY_RSA_PEM tests/data_files/cli-rsa.key */ #define TEST_CLI_KEY_RSA_PEM \ "-----BEGIN RSA PRIVATE KEY-----\r\n" \ "MIIEpAIBAAKCAQEAyHTEzLn5tXnpRdkUYLB9u5Pyax6fM60Nj4o8VmXl3ETZzGaF\r\n" \ "B9X4J7BKNdBjngpuG7fa8H6r7gwQk4ZJGDTzqCrSV/Uu1C93KYRhTYJQj6eVSHD1\r\n" \ "bk2y1RPD0hrt5kPqQhTrdOrA7R/UV06p86jt0uDBMHEwMjDV0/YI0FZPRo7yX/k9\r\n" \ "Z5GIMC5Cst99++UMd//sMcB4j7/Cf8qtbCHWjdmLao5v4Jv4EFbMs44TFeY0BGbH\r\n" \ "7vk2DmqV9gmaBmf0ZXH4yqSxJeD+PIs1BGe64E92hfx//DZrtenNLQNiTrM9AM+v\r\n" \ "dqBpVoNq0qjU51Bx5rU2BXcFbXvI5MT9TNUhXwIDAQABAoIBAGdNtfYDiap6bzst\r\n" \ "yhCiI8m9TtrhZw4MisaEaN/ll3XSjaOG2dvV6xMZCMV+5TeXDHOAZnY18Yi18vzz\r\n" \ "4Ut2TnNFzizCECYNaA2fST3WgInnxUkV3YXAyP6CNxJaCmv2aA0yFr2kFVSeaKGt\r\n" \ "ymvljNp2NVkvm7Th8fBQBO7I7AXhz43k0mR7XmPgewe8ApZOG3hstkOaMvbWAvWA\r\n" \ "zCZupdDjZYjOJqlA4eEA4H8/w7F83r5CugeBE8LgEREjLPiyejrU5H1fubEY+h0d\r\n" \ "l5HZBJ68ybTXfQ5U9o/QKA3dd0toBEhhdRUDGzWtjvwkEQfqF1reGWj/tod/gCpf\r\n" \ "DFi6X0ECgYEA4wOv/pjSC3ty6TuOvKX2rOUiBrLXXv2JSxZnMoMiWI5ipLQt+RYT\r\n" \ "VPafL/m7Dn6MbwjayOkcZhBwk5CNz5A6Q4lJ64Mq/lqHznRCQQ2Mc1G8eyDF/fYL\r\n" \ "Ze2pLvwP9VD5jTc2miDfw+MnvJhywRRLcemDFP8k4hQVtm8PMp3ZmNECgYEA4gz7\r\n" \ "wzObR4gn8ibe617uQPZjWzUj9dUHYd+in1gwBCIrtNnaRn9I9U/Q6tegRYpii4ys\r\n" \ "c176NmU+umy6XmuSKV5qD9bSpZWG2nLFnslrN15Lm3fhZxoeMNhBaEDTnLT26yoi\r\n" \ "33gp0mSSWy94ZEqipms+ULF6sY1ZtFW6tpGFoy8CgYAQHhnnvJflIs2ky4q10B60\r\n" \ "ZcxFp3rtDpkp0JxhFLhiizFrujMtZSjYNm5U7KkgPVHhLELEUvCmOnKTt4ap/vZ0\r\n" \ "BxJNe1GZH3pW6SAvGDQpl9sG7uu/vTFP+lCxukmzxB0DrrDcvorEkKMom7ZCCRvW\r\n" \ "KZsZ6YeH2Z81BauRj218kQKBgQCUV/DgKP2985xDTT79N08jUo3hTP5MVYCCuj/+\r\n" \ "UeEw1TvZcx3LJby7P6Xad6a1/BqveaGyFKIfEFIaBUBItk801sDDpDaYc4gL00Xc\r\n" \ "7lFuBHOZkxJYlss5QrGpuOEl9ZwUt5IrFLBdYaKqNHzNVC1pCPfb/JyH6Dr2HUxq\r\n" \ "gxUwAQKBgQCcU6G2L8AG9d9c0UpOyL1tMvFe5Ttw0KjlQVdsh1MP6yigYo9DYuwu\r\n" \ "bHFVW2r0dBTqegP2/KTOxKzaHfC1qf0RGDsUoJCNJrd1cwoCLG8P2EF4w3OBrKqv\r\n" \ "8u4ytY0F+Vlanj5lm3TaoHSVF1+NWPyOTiwevIECGKwSxvlki4fDAA==\r\n" \ "-----END RSA PRIVATE KEY-----\r\n"/* END FILE */ /* This was generated from tests/data_files/cli-rsa.key.der using `xxd -i`. */ /* BEGIN FILE binary macro TEST_CLI_KEY_RSA_DER tests/data_files/cli-rsa.key.der */ #define TEST_CLI_KEY_RSA_DER { \ 0x30, 0x82, 0x04, 0xa4, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, \ 0xc8, 0x74, 0xc4, 0xcc, 0xb9, 0xf9, 0xb5, 0x79, 0xe9, 0x45, 0xd9, 0x14, \ 0x60, 0xb0, 0x7d, 0xbb, 0x93, 0xf2, 0x6b, 0x1e, 0x9f, 0x33, 0xad, 0x0d, \ 0x8f, 0x8a, 0x3c, 0x56, 0x65, 0xe5, 0xdc, 0x44, 0xd9, 0xcc, 0x66, 0x85, \ 0x07, 0xd5, 0xf8, 0x27, 0xb0, 0x4a, 0x35, 0xd0, 0x63, 0x9e, 0x0a, 0x6e, \ 0x1b, 0xb7, 0xda, 0xf0, 0x7e, 0xab, 0xee, 0x0c, 0x10, 0x93, 0x86, 0x49, \ 0x18, 0x34, 0xf3, 0xa8, 0x2a, 0xd2, 0x57, 0xf5, 0x2e, 0xd4, 0x2f, 0x77, \ 0x29, 0x84, 0x61, 0x4d, 0x82, 0x50, 0x8f, 0xa7, 0x95, 0x48, 0x70, 0xf5, \ 0x6e, 0x4d, 0xb2, 0xd5, 0x13, 0xc3, 0xd2, 0x1a, 0xed, 0xe6, 0x43, 0xea, \ 0x42, 0x14, 0xeb, 0x74, 0xea, 0xc0, 0xed, 0x1f, 0xd4, 0x57, 0x4e, 0xa9, \ 0xf3, 0xa8, 0xed, 0xd2, 0xe0, 0xc1, 0x30, 0x71, 0x30, 0x32, 0x30, 0xd5, \ 0xd3, 0xf6, 0x08, 0xd0, 0x56, 0x4f, 0x46, 0x8e, 0xf2, 0x5f, 0xf9, 0x3d, \ 0x67, 0x91, 0x88, 0x30, 0x2e, 0x42, 0xb2, 0xdf, 0x7d, 0xfb, 0xe5, 0x0c, \ 0x77, 0xff, 0xec, 0x31, 0xc0, 0x78, 0x8f, 0xbf, 0xc2, 0x7f, 0xca, 0xad, \ 0x6c, 0x21, 0xd6, 0x8d, 0xd9, 0x8b, 0x6a, 0x8e, 0x6f, 0xe0, 0x9b, 0xf8, \ 0x10, 0x56, 0xcc, 0xb3, 0x8e, 0x13, 0x15, 0xe6, 0x34, 0x04, 0x66, 0xc7, \ 0xee, 0xf9, 0x36, 0x0e, 0x6a, 0x95, 0xf6, 0x09, 0x9a, 0x06, 0x67, 0xf4, \ 0x65, 0x71, 0xf8, 0xca, 0xa4, 0xb1, 0x25, 0xe0, 0xfe, 0x3c, 0x8b, 0x35, \ 0x04, 0x67, 0xba, 0xe0, 0x4f, 0x76, 0x85, 0xfc, 0x7f, 0xfc, 0x36, 0x6b, \ 0xb5, 0xe9, 0xcd, 0x2d, 0x03, 0x62, 0x4e, 0xb3, 0x3d, 0x00, 0xcf, 0xaf, \ 0x76, 0xa0, 0x69, 0x56, 0x83, 0x6a, 0xd2, 0xa8, 0xd4, 0xe7, 0x50, 0x71, \ 0xe6, 0xb5, 0x36, 0x05, 0x77, 0x05, 0x6d, 0x7b, 0xc8, 0xe4, 0xc4, 0xfd, \ 0x4c, 0xd5, 0x21, 0x5f, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x82, 0x01, \ 0x00, 0x67, 0x4d, 0xb5, 0xf6, 0x03, 0x89, 0xaa, 0x7a, 0x6f, 0x3b, 0x2d, \ 0xca, 0x10, 0xa2, 0x23, 0xc9, 0xbd, 0x4e, 0xda, 0xe1, 0x67, 0x0e, 0x0c, \ 0x8a, 0xc6, 0x84, 0x68, 0xdf, 0xe5, 0x97, 0x75, 0xd2, 0x8d, 0xa3, 0x86, \ 0xd9, 0xdb, 0xd5, 0xeb, 0x13, 0x19, 0x08, 0xc5, 0x7e, 0xe5, 0x37, 0x97, \ 0x0c, 0x73, 0x80, 0x66, 0x76, 0x35, 0xf1, 0x88, 0xb5, 0xf2, 0xfc, 0xf3, \ 0xe1, 0x4b, 0x76, 0x4e, 0x73, 0x45, 0xce, 0x2c, 0xc2, 0x10, 0x26, 0x0d, \ 0x68, 0x0d, 0x9f, 0x49, 0x3d, 0xd6, 0x80, 0x89, 0xe7, 0xc5, 0x49, 0x15, \ 0xdd, 0x85, 0xc0, 0xc8, 0xfe, 0x82, 0x37, 0x12, 0x5a, 0x0a, 0x6b, 0xf6, \ 0x68, 0x0d, 0x32, 0x16, 0xbd, 0xa4, 0x15, 0x54, 0x9e, 0x68, 0xa1, 0xad, \ 0xca, 0x6b, 0xe5, 0x8c, 0xda, 0x76, 0x35, 0x59, 0x2f, 0x9b, 0xb4, 0xe1, \ 0xf1, 0xf0, 0x50, 0x04, 0xee, 0xc8, 0xec, 0x05, 0xe1, 0xcf, 0x8d, 0xe4, \ 0xd2, 0x64, 0x7b, 0x5e, 0x63, 0xe0, 0x7b, 0x07, 0xbc, 0x02, 0x96, 0x4e, \ 0x1b, 0x78, 0x6c, 0xb6, 0x43, 0x9a, 0x32, 0xf6, 0xd6, 0x02, 0xf5, 0x80, \ 0xcc, 0x26, 0x6e, 0xa5, 0xd0, 0xe3, 0x65, 0x88, 0xce, 0x26, 0xa9, 0x40, \ 0xe1, 0xe1, 0x00, 0xe0, 0x7f, 0x3f, 0xc3, 0xb1, 0x7c, 0xde, 0xbe, 0x42, \ 0xba, 0x07, 0x81, 0x13, 0xc2, 0xe0, 0x11, 0x11, 0x23, 0x2c, 0xf8, 0xb2, \ 0x7a, 0x3a, 0xd4, 0xe4, 0x7d, 0x5f, 0xb9, 0xb1, 0x18, 0xfa, 0x1d, 0x1d, \ 0x97, 0x91, 0xd9, 0x04, 0x9e, 0xbc, 0xc9, 0xb4, 0xd7, 0x7d, 0x0e, 0x54, \ 0xf6, 0x8f, 0xd0, 0x28, 0x0d, 0xdd, 0x77, 0x4b, 0x68, 0x04, 0x48, 0x61, \ 0x75, 0x15, 0x03, 0x1b, 0x35, 0xad, 0x8e, 0xfc, 0x24, 0x11, 0x07, 0xea, \ 0x17, 0x5a, 0xde, 0x19, 0x68, 0xff, 0xb6, 0x87, 0x7f, 0x80, 0x2a, 0x5f, \ 0x0c, 0x58, 0xba, 0x5f, 0x41, 0x02, 0x81, 0x81, 0x00, 0xe3, 0x03, 0xaf, \ 0xfe, 0x98, 0xd2, 0x0b, 0x7b, 0x72, 0xe9, 0x3b, 0x8e, 0xbc, 0xa5, 0xf6, \ 0xac, 0xe5, 0x22, 0x06, 0xb2, 0xd7, 0x5e, 0xfd, 0x89, 0x4b, 0x16, 0x67, \ 0x32, 0x83, 0x22, 0x58, 0x8e, 0x62, 0xa4, 0xb4, 0x2d, 0xf9, 0x16, 0x13, \ 0x54, 0xf6, 0x9f, 0x2f, 0xf9, 0xbb, 0x0e, 0x7e, 0x8c, 0x6f, 0x08, 0xda, \ 0xc8, 0xe9, 0x1c, 0x66, 0x10, 0x70, 0x93, 0x90, 0x8d, 0xcf, 0x90, 0x3a, \ 0x43, 0x89, 0x49, 0xeb, 0x83, 0x2a, 0xfe, 0x5a, 0x87, 0xce, 0x74, 0x42, \ 0x41, 0x0d, 0x8c, 0x73, 0x51, 0xbc, 0x7b, 0x20, 0xc5, 0xfd, 0xf6, 0x0b, \ 0x65, 0xed, 0xa9, 0x2e, 0xfc, 0x0f, 0xf5, 0x50, 0xf9, 0x8d, 0x37, 0x36, \ 0x9a, 0x20, 0xdf, 0xc3, 0xe3, 0x27, 0xbc, 0x98, 0x72, 0xc1, 0x14, 0x4b, \ 0x71, 0xe9, 0x83, 0x14, 0xff, 0x24, 0xe2, 0x14, 0x15, 0xb6, 0x6f, 0x0f, \ 0x32, 0x9d, 0xd9, 0x98, 0xd1, 0x02, 0x81, 0x81, 0x00, 0xe2, 0x0c, 0xfb, \ 0xc3, 0x33, 0x9b, 0x47, 0x88, 0x27, 0xf2, 0x26, 0xde, 0xeb, 0x5e, 0xee, \ 0x40, 0xf6, 0x63, 0x5b, 0x35, 0x23, 0xf5, 0xd5, 0x07, 0x61, 0xdf, 0xa2, \ 0x9f, 0x58, 0x30, 0x04, 0x22, 0x2b, 0xb4, 0xd9, 0xda, 0x46, 0x7f, 0x48, \ 0xf5, 0x4f, 0xd0, 0xea, 0xd7, 0xa0, 0x45, 0x8a, 0x62, 0x8b, 0x8c, 0xac, \ 0x73, 0x5e, 0xfa, 0x36, 0x65, 0x3e, 0xba, 0x6c, 0xba, 0x5e, 0x6b, 0x92, \ 0x29, 0x5e, 0x6a, 0x0f, 0xd6, 0xd2, 0xa5, 0x95, 0x86, 0xda, 0x72, 0xc5, \ 0x9e, 0xc9, 0x6b, 0x37, 0x5e, 0x4b, 0x9b, 0x77, 0xe1, 0x67, 0x1a, 0x1e, \ 0x30, 0xd8, 0x41, 0x68, 0x40, 0xd3, 0x9c, 0xb4, 0xf6, 0xeb, 0x2a, 0x22, \ 0xdf, 0x78, 0x29, 0xd2, 0x64, 0x92, 0x5b, 0x2f, 0x78, 0x64, 0x4a, 0xa2, \ 0xa6, 0x6b, 0x3e, 0x50, 0xb1, 0x7a, 0xb1, 0x8d, 0x59, 0xb4, 0x55, 0xba, \ 0xb6, 0x91, 0x85, 0xa3, 0x2f, 0x02, 0x81, 0x80, 0x10, 0x1e, 0x19, 0xe7, \ 0xbc, 0x97, 0xe5, 0x22, 0xcd, 0xa4, 0xcb, 0x8a, 0xb5, 0xd0, 0x1e, 0xb4, \ 0x65, 0xcc, 0x45, 0xa7, 0x7a, 0xed, 0x0e, 0x99, 0x29, 0xd0, 0x9c, 0x61, \ 0x14, 0xb8, 0x62, 0x8b, 0x31, 0x6b, 0xba, 0x33, 0x2d, 0x65, 0x28, 0xd8, \ 0x36, 0x6e, 0x54, 0xec, 0xa9, 0x20, 0x3d, 0x51, 0xe1, 0x2c, 0x42, 0xc4, \ 0x52, 0xf0, 0xa6, 0x3a, 0x72, 0x93, 0xb7, 0x86, 0xa9, 0xfe, 0xf6, 0x74, \ 0x07, 0x12, 0x4d, 0x7b, 0x51, 0x99, 0x1f, 0x7a, 0x56, 0xe9, 0x20, 0x2f, \ 0x18, 0x34, 0x29, 0x97, 0xdb, 0x06, 0xee, 0xeb, 0xbf, 0xbd, 0x31, 0x4f, \ 0xfa, 0x50, 0xb1, 0xba, 0x49, 0xb3, 0xc4, 0x1d, 0x03, 0xae, 0xb0, 0xdc, \ 0xbe, 0x8a, 0xc4, 0x90, 0xa3, 0x28, 0x9b, 0xb6, 0x42, 0x09, 0x1b, 0xd6, \ 0x29, 0x9b, 0x19, 0xe9, 0x87, 0x87, 0xd9, 0x9f, 0x35, 0x05, 0xab, 0x91, \ 0x8f, 0x6d, 0x7c, 0x91, 0x02, 0x81, 0x81, 0x00, 0x94, 0x57, 0xf0, 0xe0, \ 0x28, 0xfd, 0xbd, 0xf3, 0x9c, 0x43, 0x4d, 0x3e, 0xfd, 0x37, 0x4f, 0x23, \ 0x52, 0x8d, 0xe1, 0x4c, 0xfe, 0x4c, 0x55, 0x80, 0x82, 0xba, 0x3f, 0xfe, \ 0x51, 0xe1, 0x30, 0xd5, 0x3b, 0xd9, 0x73, 0x1d, 0xcb, 0x25, 0xbc, 0xbb, \ 0x3f, 0xa5, 0xda, 0x77, 0xa6, 0xb5, 0xfc, 0x1a, 0xaf, 0x79, 0xa1, 0xb2, \ 0x14, 0xa2, 0x1f, 0x10, 0x52, 0x1a, 0x05, 0x40, 0x48, 0xb6, 0x4f, 0x34, \ 0xd6, 0xc0, 0xc3, 0xa4, 0x36, 0x98, 0x73, 0x88, 0x0b, 0xd3, 0x45, 0xdc, \ 0xee, 0x51, 0x6e, 0x04, 0x73, 0x99, 0x93, 0x12, 0x58, 0x96, 0xcb, 0x39, \ 0x42, 0xb1, 0xa9, 0xb8, 0xe1, 0x25, 0xf5, 0x9c, 0x14, 0xb7, 0x92, 0x2b, \ 0x14, 0xb0, 0x5d, 0x61, 0xa2, 0xaa, 0x34, 0x7c, 0xcd, 0x54, 0x2d, 0x69, \ 0x08, 0xf7, 0xdb, 0xfc, 0x9c, 0x87, 0xe8, 0x3a, 0xf6, 0x1d, 0x4c, 0x6a, \ 0x83, 0x15, 0x30, 0x01, 0x02, 0x81, 0x81, 0x00, 0x9c, 0x53, 0xa1, 0xb6, \ 0x2f, 0xc0, 0x06, 0xf5, 0xdf, 0x5c, 0xd1, 0x4a, 0x4e, 0xc8, 0xbd, 0x6d, \ 0x32, 0xf1, 0x5e, 0xe5, 0x3b, 0x70, 0xd0, 0xa8, 0xe5, 0x41, 0x57, 0x6c, \ 0x87, 0x53, 0x0f, 0xeb, 0x28, 0xa0, 0x62, 0x8f, 0x43, 0x62, 0xec, 0x2e, \ 0x6c, 0x71, 0x55, 0x5b, 0x6a, 0xf4, 0x74, 0x14, 0xea, 0x7a, 0x03, 0xf6, \ 0xfc, 0xa4, 0xce, 0xc4, 0xac, 0xda, 0x1d, 0xf0, 0xb5, 0xa9, 0xfd, 0x11, \ 0x18, 0x3b, 0x14, 0xa0, 0x90, 0x8d, 0x26, 0xb7, 0x75, 0x73, 0x0a, 0x02, \ 0x2c, 0x6f, 0x0f, 0xd8, 0x41, 0x78, 0xc3, 0x73, 0x81, 0xac, 0xaa, 0xaf, \ 0xf2, 0xee, 0x32, 0xb5, 0x8d, 0x05, 0xf9, 0x59, 0x5a, 0x9e, 0x3e, 0x65, \ 0x9b, 0x74, 0xda, 0xa0, 0x74, 0x95, 0x17, 0x5f, 0x8d, 0x58, 0xfc, 0x8e, \ 0x4e, 0x2c, 0x1e, 0xbc, 0x81, 0x02, 0x18, 0xac, 0x12, 0xc6, 0xf9, 0x64, \ 0x8b, 0x87, 0xc3, 0x00 \ } /* END FILE */ /* * * Test certificates and keys as C variables * */ /* * CA */ const char mbedtls_test_ca_crt_ec_pem[] = TEST_CA_CRT_EC_PEM; const char mbedtls_test_ca_key_ec_pem[] = TEST_CA_KEY_EC_PEM; const char mbedtls_test_ca_pwd_ec_pem[] = TEST_CA_PWD_EC_PEM; const char mbedtls_test_ca_key_rsa_pem[] = TEST_CA_KEY_RSA_PEM; const char mbedtls_test_ca_pwd_rsa_pem[] = TEST_CA_PWD_RSA_PEM; const char mbedtls_test_ca_crt_rsa_sha1_pem[] = TEST_CA_CRT_RSA_SHA1_PEM; const char mbedtls_test_ca_crt_rsa_sha256_pem[] = TEST_CA_CRT_RSA_SHA256_PEM; const unsigned char mbedtls_test_ca_crt_ec_der[] = TEST_CA_CRT_EC_DER; const unsigned char mbedtls_test_ca_key_ec_der[] = TEST_CA_KEY_EC_DER; const unsigned char mbedtls_test_ca_key_rsa_der[] = TEST_CA_KEY_RSA_DER; const unsigned char mbedtls_test_ca_crt_rsa_sha1_der[] = TEST_CA_CRT_RSA_SHA1_DER; const unsigned char mbedtls_test_ca_crt_rsa_sha256_der[] = TEST_CA_CRT_RSA_SHA256_DER; const size_t mbedtls_test_ca_crt_ec_pem_len = sizeof( mbedtls_test_ca_crt_ec_pem ); const size_t mbedtls_test_ca_key_ec_pem_len = sizeof( mbedtls_test_ca_key_ec_pem ); const size_t mbedtls_test_ca_pwd_ec_pem_len = sizeof( mbedtls_test_ca_pwd_ec_pem ) - 1; const size_t mbedtls_test_ca_key_rsa_pem_len = sizeof( mbedtls_test_ca_key_rsa_pem ); const size_t mbedtls_test_ca_pwd_rsa_pem_len = sizeof( mbedtls_test_ca_pwd_rsa_pem ) - 1; const size_t mbedtls_test_ca_crt_rsa_sha1_pem_len = sizeof( mbedtls_test_ca_crt_rsa_sha1_pem ); const size_t mbedtls_test_ca_crt_rsa_sha256_pem_len = sizeof( mbedtls_test_ca_crt_rsa_sha256_pem ); const size_t mbedtls_test_ca_crt_ec_der_len = sizeof( mbedtls_test_ca_crt_ec_der ); const size_t mbedtls_test_ca_key_ec_der_len = sizeof( mbedtls_test_ca_key_ec_der ); const size_t mbedtls_test_ca_pwd_ec_der_len = 0; const size_t mbedtls_test_ca_key_rsa_der_len = sizeof( mbedtls_test_ca_key_rsa_der ); const size_t mbedtls_test_ca_pwd_rsa_der_len = 0; const size_t mbedtls_test_ca_crt_rsa_sha1_der_len = sizeof( mbedtls_test_ca_crt_rsa_sha1_der ); const size_t mbedtls_test_ca_crt_rsa_sha256_der_len = sizeof( mbedtls_test_ca_crt_rsa_sha256_der ); /* * Server */ const char mbedtls_test_srv_crt_ec_pem[] = TEST_SRV_CRT_EC_PEM; const char mbedtls_test_srv_key_ec_pem[] = TEST_SRV_KEY_EC_PEM; const char mbedtls_test_srv_pwd_ec_pem[] = ""; const char mbedtls_test_srv_key_rsa_pem[] = TEST_SRV_KEY_RSA_PEM; const char mbedtls_test_srv_pwd_rsa_pem[] = ""; const char mbedtls_test_srv_crt_rsa_sha1_pem[] = TEST_SRV_CRT_RSA_SHA1_PEM; const char mbedtls_test_srv_crt_rsa_sha256_pem[] = TEST_SRV_CRT_RSA_SHA256_PEM; const unsigned char mbedtls_test_srv_crt_ec_der[] = TEST_SRV_CRT_EC_DER; const unsigned char mbedtls_test_srv_key_ec_der[] = TEST_SRV_KEY_EC_DER; const unsigned char mbedtls_test_srv_key_rsa_der[] = TEST_SRV_KEY_RSA_DER; const unsigned char mbedtls_test_srv_crt_rsa_sha1_der[] = TEST_SRV_CRT_RSA_SHA1_DER; const unsigned char mbedtls_test_srv_crt_rsa_sha256_der[] = TEST_SRV_CRT_RSA_SHA256_DER; const size_t mbedtls_test_srv_crt_ec_pem_len = sizeof( mbedtls_test_srv_crt_ec_pem ); const size_t mbedtls_test_srv_key_ec_pem_len = sizeof( mbedtls_test_srv_key_ec_pem ); const size_t mbedtls_test_srv_pwd_ec_pem_len = sizeof( mbedtls_test_srv_pwd_ec_pem ) - 1; const size_t mbedtls_test_srv_key_rsa_pem_len = sizeof( mbedtls_test_srv_key_rsa_pem ); const size_t mbedtls_test_srv_pwd_rsa_pem_len = sizeof( mbedtls_test_srv_pwd_rsa_pem ) - 1; const size_t mbedtls_test_srv_crt_rsa_sha1_pem_len = sizeof( mbedtls_test_srv_crt_rsa_sha1_pem ); const size_t mbedtls_test_srv_crt_rsa_sha256_pem_len = sizeof( mbedtls_test_srv_crt_rsa_sha256_pem ); const size_t mbedtls_test_srv_crt_ec_der_len = sizeof( mbedtls_test_srv_crt_ec_der ); const size_t mbedtls_test_srv_key_ec_der_len = sizeof( mbedtls_test_srv_key_ec_der ); const size_t mbedtls_test_srv_pwd_ec_der_len = 0; const size_t mbedtls_test_srv_key_rsa_der_len = sizeof( mbedtls_test_srv_key_rsa_der ); const size_t mbedtls_test_srv_pwd_rsa_der_len = 0; const size_t mbedtls_test_srv_crt_rsa_sha1_der_len = sizeof( mbedtls_test_srv_crt_rsa_sha1_der ); const size_t mbedtls_test_srv_crt_rsa_sha256_der_len = sizeof( mbedtls_test_srv_crt_rsa_sha256_der ); /* * Client */ const char mbedtls_test_cli_crt_ec_pem[] = TEST_CLI_CRT_EC_PEM; const char mbedtls_test_cli_key_ec_pem[] = TEST_CLI_KEY_EC_PEM; const char mbedtls_test_cli_pwd_ec_pem[] = ""; const char mbedtls_test_cli_key_rsa_pem[] = TEST_CLI_KEY_RSA_PEM; const char mbedtls_test_cli_pwd_rsa_pem[] = ""; const char mbedtls_test_cli_crt_rsa_pem[] = TEST_CLI_CRT_RSA_PEM; const unsigned char mbedtls_test_cli_crt_ec_der[] = TEST_CLI_CRT_EC_DER; const unsigned char mbedtls_test_cli_key_ec_der[] = TEST_CLI_KEY_EC_DER; const unsigned char mbedtls_test_cli_key_rsa_der[] = TEST_CLI_KEY_RSA_DER; const unsigned char mbedtls_test_cli_crt_rsa_der[] = TEST_CLI_CRT_RSA_DER; const size_t mbedtls_test_cli_crt_ec_pem_len = sizeof( mbedtls_test_cli_crt_ec_pem ); const size_t mbedtls_test_cli_key_ec_pem_len = sizeof( mbedtls_test_cli_key_ec_pem ); const size_t mbedtls_test_cli_pwd_ec_pem_len = sizeof( mbedtls_test_cli_pwd_ec_pem ) - 1; const size_t mbedtls_test_cli_key_rsa_pem_len = sizeof( mbedtls_test_cli_key_rsa_pem ); const size_t mbedtls_test_cli_pwd_rsa_pem_len = sizeof( mbedtls_test_cli_pwd_rsa_pem ) - 1; const size_t mbedtls_test_cli_crt_rsa_pem_len = sizeof( mbedtls_test_cli_crt_rsa_pem ); const size_t mbedtls_test_cli_crt_ec_der_len = sizeof( mbedtls_test_cli_crt_ec_der ); const size_t mbedtls_test_cli_key_ec_der_len = sizeof( mbedtls_test_cli_key_ec_der ); const size_t mbedtls_test_cli_key_rsa_der_len = sizeof( mbedtls_test_cli_key_rsa_der ); const size_t mbedtls_test_cli_crt_rsa_der_len = sizeof( mbedtls_test_cli_crt_rsa_der ); /* * * Definitions of test CRTs without specification of all parameters, choosing * them automatically according to the config. For example, mbedtls_test_ca_crt * is one of mbedtls_test_ca_crt_{rsa|ec}_{sha1|sha256}_{pem|der}. * */ /* * Dispatch between PEM and DER according to config */ #if defined(MBEDTLS_PEM_PARSE_C) /* PEM encoded test CA certificates and keys */ #define TEST_CA_KEY_RSA TEST_CA_KEY_RSA_PEM #define TEST_CA_PWD_RSA TEST_CA_PWD_RSA_PEM #define TEST_CA_CRT_RSA_SHA256 TEST_CA_CRT_RSA_SHA256_PEM #define TEST_CA_CRT_RSA_SHA1 TEST_CA_CRT_RSA_SHA1_PEM #define TEST_CA_KEY_EC TEST_CA_KEY_EC_PEM #define TEST_CA_PWD_EC TEST_CA_PWD_EC_PEM #define TEST_CA_CRT_EC TEST_CA_CRT_EC_PEM /* PEM encoded test server certificates and keys */ #define TEST_SRV_KEY_RSA TEST_SRV_KEY_RSA_PEM #define TEST_SRV_PWD_RSA "" #define TEST_SRV_CRT_RSA_SHA256 TEST_SRV_CRT_RSA_SHA256_PEM #define TEST_SRV_CRT_RSA_SHA1 TEST_SRV_CRT_RSA_SHA1_PEM #define TEST_SRV_KEY_EC TEST_SRV_KEY_EC_PEM #define TEST_SRV_PWD_EC "" #define TEST_SRV_CRT_EC TEST_SRV_CRT_EC_PEM /* PEM encoded test client certificates and keys */ #define TEST_CLI_KEY_RSA TEST_CLI_KEY_RSA_PEM #define TEST_CLI_PWD_RSA "" #define TEST_CLI_CRT_RSA TEST_CLI_CRT_RSA_PEM #define TEST_CLI_KEY_EC TEST_CLI_KEY_EC_PEM #define TEST_CLI_PWD_EC "" #define TEST_CLI_CRT_EC TEST_CLI_CRT_EC_PEM #else /* MBEDTLS_PEM_PARSE_C */ /* DER encoded test CA certificates and keys */ #define TEST_CA_KEY_RSA TEST_CA_KEY_RSA_DER #define TEST_CA_PWD_RSA "" #define TEST_CA_CRT_RSA_SHA256 TEST_CA_CRT_RSA_SHA256_DER #define TEST_CA_CRT_RSA_SHA1 TEST_CA_CRT_RSA_SHA1_DER #define TEST_CA_KEY_EC TEST_CA_KEY_EC_DER #define TEST_CA_PWD_EC "" #define TEST_CA_CRT_EC TEST_CA_CRT_EC_DER /* DER encoded test server certificates and keys */ #define TEST_SRV_KEY_RSA TEST_SRV_KEY_RSA_DER #define TEST_SRV_PWD_RSA "" #define TEST_SRV_CRT_RSA_SHA256 TEST_SRV_CRT_RSA_SHA256_DER #define TEST_SRV_CRT_RSA_SHA1 TEST_SRV_CRT_RSA_SHA1_DER #define TEST_SRV_KEY_EC TEST_SRV_KEY_EC_DER #define TEST_SRV_PWD_EC "" #define TEST_SRV_CRT_EC TEST_SRV_CRT_EC_DER /* DER encoded test client certificates and keys */ #define TEST_CLI_KEY_RSA TEST_CLI_KEY_RSA_DER #define TEST_CLI_PWD_RSA "" #define TEST_CLI_CRT_RSA TEST_CLI_CRT_RSA_DER #define TEST_CLI_KEY_EC TEST_CLI_KEY_EC_DER #define TEST_CLI_PWD_EC "" #define TEST_CLI_CRT_EC TEST_CLI_CRT_EC_DER #endif /* MBEDTLS_PEM_PARSE_C */ const char mbedtls_test_ca_key_rsa[] = TEST_CA_KEY_RSA; const char mbedtls_test_ca_pwd_rsa[] = TEST_CA_PWD_RSA; const char mbedtls_test_ca_crt_rsa_sha256[] = TEST_CA_CRT_RSA_SHA256; const char mbedtls_test_ca_crt_rsa_sha1[] = TEST_CA_CRT_RSA_SHA1; const char mbedtls_test_ca_key_ec[] = TEST_CA_KEY_EC; const char mbedtls_test_ca_pwd_ec[] = TEST_CA_PWD_EC; const char mbedtls_test_ca_crt_ec[] = TEST_CA_CRT_EC; const char mbedtls_test_srv_key_rsa[] = TEST_SRV_KEY_RSA; const char mbedtls_test_srv_pwd_rsa[] = TEST_SRV_PWD_RSA; const char mbedtls_test_srv_crt_rsa_sha256[] = TEST_SRV_CRT_RSA_SHA256; const char mbedtls_test_srv_crt_rsa_sha1[] = TEST_SRV_CRT_RSA_SHA1; const char mbedtls_test_srv_key_ec[] = TEST_SRV_KEY_EC; const char mbedtls_test_srv_pwd_ec[] = TEST_SRV_PWD_EC; const char mbedtls_test_srv_crt_ec[] = TEST_SRV_CRT_EC; const char mbedtls_test_cli_key_rsa[] = TEST_CLI_KEY_RSA; const char mbedtls_test_cli_pwd_rsa[] = TEST_CLI_PWD_RSA; const char mbedtls_test_cli_crt_rsa[] = TEST_CLI_CRT_RSA; const char mbedtls_test_cli_key_ec[] = TEST_CLI_KEY_EC; const char mbedtls_test_cli_pwd_ec[] = TEST_CLI_PWD_EC; const char mbedtls_test_cli_crt_ec[] = TEST_CLI_CRT_EC; const size_t mbedtls_test_ca_key_rsa_len = sizeof( mbedtls_test_ca_key_rsa ); const size_t mbedtls_test_ca_pwd_rsa_len = sizeof( mbedtls_test_ca_pwd_rsa ) - 1; const size_t mbedtls_test_ca_crt_rsa_sha256_len = sizeof( mbedtls_test_ca_crt_rsa_sha256 ); const size_t mbedtls_test_ca_crt_rsa_sha1_len = sizeof( mbedtls_test_ca_crt_rsa_sha1 ); const size_t mbedtls_test_ca_key_ec_len = sizeof( mbedtls_test_ca_key_ec ); const size_t mbedtls_test_ca_pwd_ec_len = sizeof( mbedtls_test_ca_pwd_ec ) - 1; const size_t mbedtls_test_ca_crt_ec_len = sizeof( mbedtls_test_ca_crt_ec ); const size_t mbedtls_test_srv_key_rsa_len = sizeof( mbedtls_test_srv_key_rsa ); const size_t mbedtls_test_srv_pwd_rsa_len = sizeof( mbedtls_test_srv_pwd_rsa ) -1; const size_t mbedtls_test_srv_crt_rsa_sha256_len = sizeof( mbedtls_test_srv_crt_rsa_sha256 ); const size_t mbedtls_test_srv_crt_rsa_sha1_len = sizeof( mbedtls_test_srv_crt_rsa_sha1 ); const size_t mbedtls_test_srv_key_ec_len = sizeof( mbedtls_test_srv_key_ec ); const size_t mbedtls_test_srv_pwd_ec_len = sizeof( mbedtls_test_srv_pwd_ec ) - 1; const size_t mbedtls_test_srv_crt_ec_len = sizeof( mbedtls_test_srv_crt_ec ); const size_t mbedtls_test_cli_key_rsa_len = sizeof( mbedtls_test_cli_key_rsa ); const size_t mbedtls_test_cli_pwd_rsa_len = sizeof( mbedtls_test_cli_pwd_rsa ) - 1; const size_t mbedtls_test_cli_crt_rsa_len = sizeof( mbedtls_test_cli_crt_rsa ); const size_t mbedtls_test_cli_key_ec_len = sizeof( mbedtls_test_cli_key_ec ); const size_t mbedtls_test_cli_pwd_ec_len = sizeof( mbedtls_test_cli_pwd_ec ) - 1; const size_t mbedtls_test_cli_crt_ec_len = sizeof( mbedtls_test_cli_crt_ec ); /* * Dispatch between SHA-1 and SHA-256 */ #if defined(MBEDTLS_SHA256_C) #define TEST_CA_CRT_RSA TEST_CA_CRT_RSA_SHA256 #define TEST_SRV_CRT_RSA TEST_SRV_CRT_RSA_SHA256 #else #define TEST_CA_CRT_RSA TEST_CA_CRT_RSA_SHA1 #define TEST_SRV_CRT_RSA TEST_SRV_CRT_RSA_SHA1 #endif /* MBEDTLS_SHA256_C */ const char mbedtls_test_ca_crt_rsa[] = TEST_CA_CRT_RSA; const char mbedtls_test_srv_crt_rsa[] = TEST_SRV_CRT_RSA; const size_t mbedtls_test_ca_crt_rsa_len = sizeof( mbedtls_test_ca_crt_rsa ); const size_t mbedtls_test_srv_crt_rsa_len = sizeof( mbedtls_test_srv_crt_rsa ); /* * Dispatch between RSA and EC */ #if defined(MBEDTLS_RSA_C) #define TEST_CA_KEY TEST_CA_KEY_RSA #define TEST_CA_PWD TEST_CA_PWD_RSA #define TEST_CA_CRT TEST_CA_CRT_RSA #define TEST_SRV_KEY TEST_SRV_KEY_RSA #define TEST_SRV_PWD TEST_SRV_PWD_RSA #define TEST_SRV_CRT TEST_SRV_CRT_RSA #define TEST_CLI_KEY TEST_CLI_KEY_RSA #define TEST_CLI_PWD TEST_CLI_PWD_RSA #define TEST_CLI_CRT TEST_CLI_CRT_RSA #else /* no RSA, so assume ECDSA */ #define TEST_CA_KEY TEST_CA_KEY_EC #define TEST_CA_PWD TEST_CA_PWD_EC #define TEST_CA_CRT TEST_CA_CRT_EC #define TEST_SRV_KEY TEST_SRV_KEY_EC #define TEST_SRV_PWD TEST_SRV_PWD_EC #define TEST_SRV_CRT TEST_SRV_CRT_EC #define TEST_CLI_KEY TEST_CLI_KEY_EC #define TEST_CLI_PWD TEST_CLI_PWD_EC #define TEST_CLI_CRT TEST_CLI_CRT_EC #endif /* MBEDTLS_RSA_C */ /* API stability forces us to declare * mbedtls_test_{ca|srv|cli}_{key|pwd|crt} * as pointers. */ static const char test_ca_key[] = TEST_CA_KEY; static const char test_ca_pwd[] = TEST_CA_PWD; static const char test_ca_crt[] = TEST_CA_CRT; static const char test_srv_key[] = TEST_SRV_KEY; static const char test_srv_pwd[] = TEST_SRV_PWD; static const char test_srv_crt[] = TEST_SRV_CRT; static const char test_cli_key[] = TEST_CLI_KEY; static const char test_cli_pwd[] = TEST_CLI_PWD; static const char test_cli_crt[] = TEST_CLI_CRT; const char *mbedtls_test_ca_key = test_ca_key; const char *mbedtls_test_ca_pwd = test_ca_pwd; const char *mbedtls_test_ca_crt = test_ca_crt; const char *mbedtls_test_srv_key = test_srv_key; const char *mbedtls_test_srv_pwd = test_srv_pwd; const char *mbedtls_test_srv_crt = test_srv_crt; const char *mbedtls_test_cli_key = test_cli_key; const char *mbedtls_test_cli_pwd = test_cli_pwd; const char *mbedtls_test_cli_crt = test_cli_crt; const size_t mbedtls_test_ca_key_len = sizeof( test_ca_key ); const size_t mbedtls_test_ca_pwd_len = sizeof( test_ca_pwd ) - 1; const size_t mbedtls_test_ca_crt_len = sizeof( test_ca_crt ); const size_t mbedtls_test_srv_key_len = sizeof( test_srv_key ); const size_t mbedtls_test_srv_pwd_len = sizeof( test_srv_pwd ) - 1; const size_t mbedtls_test_srv_crt_len = sizeof( test_srv_crt ); const size_t mbedtls_test_cli_key_len = sizeof( test_cli_key ); const size_t mbedtls_test_cli_pwd_len = sizeof( test_cli_pwd ) - 1; const size_t mbedtls_test_cli_crt_len = sizeof( test_cli_crt ); /* * * Lists of certificates * */ /* List of CAs in PEM or DER, depending on config */ const char * mbedtls_test_cas[] = { #if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_SHA1_C) mbedtls_test_ca_crt_rsa_sha1, #endif #if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_SHA256_C) mbedtls_test_ca_crt_rsa_sha256, #endif #if defined(MBEDTLS_ECDSA_C) mbedtls_test_ca_crt_ec, #endif NULL }; const size_t mbedtls_test_cas_len[] = { #if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_SHA1_C) sizeof( mbedtls_test_ca_crt_rsa_sha1 ), #endif #if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_SHA256_C) sizeof( mbedtls_test_ca_crt_rsa_sha256 ), #endif #if defined(MBEDTLS_ECDSA_C) sizeof( mbedtls_test_ca_crt_ec ), #endif 0 }; /* List of all available CA certificates in DER format */ const unsigned char * mbedtls_test_cas_der[] = { #if defined(MBEDTLS_RSA_C) #if defined(MBEDTLS_SHA256_C) mbedtls_test_ca_crt_rsa_sha256_der, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA1_C) mbedtls_test_ca_crt_rsa_sha1_der, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_ECDSA_C) mbedtls_test_ca_crt_ec_der, #endif /* MBEDTLS_ECDSA_C */ NULL }; const size_t mbedtls_test_cas_der_len[] = { #if defined(MBEDTLS_RSA_C) #if defined(MBEDTLS_SHA256_C) sizeof( mbedtls_test_ca_crt_rsa_sha256_der ), #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA1_C) sizeof( mbedtls_test_ca_crt_rsa_sha1_der ), #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_ECDSA_C) sizeof( mbedtls_test_ca_crt_ec_der ), #endif /* MBEDTLS_ECDSA_C */ 0 }; /* Concatenation of all available CA certificates in PEM format */ #if defined(MBEDTLS_PEM_PARSE_C) const char mbedtls_test_cas_pem[] = #if defined(MBEDTLS_RSA_C) #if defined(MBEDTLS_SHA256_C) TEST_CA_CRT_RSA_SHA256_PEM #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA1_C) TEST_CA_CRT_RSA_SHA1_PEM #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_ECDSA_C) TEST_CA_CRT_EC_PEM #endif /* MBEDTLS_ECDSA_C */ ""; const size_t mbedtls_test_cas_pem_len = sizeof( mbedtls_test_cas_pem ); #endif /* MBEDTLS_PEM_PARSE_C */ #endif /* MBEDTLS_CERTS_C */
108,871
1,751
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/x509_csr.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/oid.h" #include "third_party/mbedtls/pem.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/x509_csr.h" /* clang-format off */ asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /** * @fileoverview X.509 Certificate Signing Request (CSR) parsing * * The ITU-T X.509 standard defines a certificate format for PKI. * * http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs) * http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs) * http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10) * * http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf * http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf */ #if defined(MBEDTLS_X509_CSR_PARSE_C) /* * Version ::= INTEGER { v1(0) } */ static int x509_csr_get_version( unsigned char **p, const unsigned char *end, int *ver ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( ( ret = mbedtls_asn1_get_int( p, end, ver ) ) != 0 ) { if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) { *ver = 0; return( 0 ); } return( MBEDTLS_ERR_X509_INVALID_VERSION + ret ); } return( 0 ); } /** * \brief Load a Certificate Signing Request (CSR) in DER format * * \note CSR attributes (if any) are currently silently ignored. * * \param csr CSR context to fill * \param buf buffer holding the CRL data * \param buflen size of the buffer * * \return 0 if successful, or a specific X509 error code */ int mbedtls_x509_csr_parse_der( mbedtls_x509_csr *csr, const unsigned char *buf, size_t buflen ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len; unsigned char *p, *end; mbedtls_x509_buf sig_params; mbedtls_platform_zeroize( &sig_params, sizeof( mbedtls_x509_buf ) ); /* * Check for valid input */ if( csr == NULL || buf == NULL || buflen == 0 ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); mbedtls_x509_csr_init( csr ); /* * first copy the raw DER data */ p = mbedtls_calloc( 1, len = buflen ); if( p == NULL ) return( MBEDTLS_ERR_X509_ALLOC_FAILED ); memcpy( p, buf, buflen ); csr->raw.p = p; csr->raw.len = len; end = p + len; /* * CertificationRequest ::= SEQUENCE { * certificationRequestInfo CertificationRequestInfo, * signatureAlgorithm AlgorithmIdentifier, * signature BIT STRING * } */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( MBEDTLS_ERR_X509_INVALID_FORMAT ); } if( len != (size_t) ( end - p ) ) { mbedtls_x509_csr_free( csr ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } /* * CertificationRequestInfo ::= SEQUENCE { */ csr->cri.p = p; if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret ); } end = p + len; csr->cri.len = end - csr->cri.p; /* * Version ::= INTEGER { v1(0) } */ if( ( ret = x509_csr_get_version( &p, end, &csr->version ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( ret ); } if( csr->version != 0 ) { mbedtls_x509_csr_free( csr ); return( MBEDTLS_ERR_X509_UNKNOWN_VERSION ); } csr->version++; /* * subject Name */ csr->subject_raw.p = p; if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret ); } if( ( ret = mbedtls_x509_get_name( &p, p + len, &csr->subject ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( ret ); } csr->subject_raw.len = p - csr->subject_raw.p; /* * subjectPKInfo SubjectPublicKeyInfo */ if( ( ret = mbedtls_pk_parse_subpubkey( &p, end, &csr->pk ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( ret ); } /* * attributes [0] Attributes * * The list of possible attributes is open-ended, though RFC 2985 * (PKCS#9) defines a few in section 5.4. We currently don't support any, * so we just ignore them. This is a safe thing to do as the worst thing * that could happen is that we issue a certificate that does not match * the requester's expectations - this cannot cause a violation of our * signature policies. */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret ); } p += len; end = csr->raw.p + csr->raw.len; /* * signatureAlgorithm AlgorithmIdentifier, * signature BIT STRING */ if( ( ret = mbedtls_x509_get_alg( &p, end, &csr->sig_oid, &sig_params ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( ret ); } if( ( ret = mbedtls_x509_get_sig_alg( &csr->sig_oid, &sig_params, &csr->sig_md, &csr->sig_pk, &csr->sig_opts ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG ); } if( ( ret = mbedtls_x509_get_sig( &p, end, &csr->sig ) ) != 0 ) { mbedtls_x509_csr_free( csr ); return( ret ); } if( p != end ) { mbedtls_x509_csr_free( csr ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } return( 0 ); } /** * \brief Load a Certificate Signing Request (CSR), DER or PEM format * * \note See notes for \c mbedtls_x509_csr_parse_der() * * \param csr CSR context to fill * \param buf buffer holding the CRL data * \param buflen size of the buffer * (including the terminating null byte for PEM data) * * \return 0 if successful, or a specific X509 or PEM error code */ int mbedtls_x509_csr_parse( mbedtls_x509_csr *csr, const unsigned char *buf, size_t buflen ) { #if defined(MBEDTLS_PEM_PARSE_C) int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t use_len; mbedtls_pem_context pem; #endif /* * Check for valid input */ if( csr == NULL || buf == NULL || buflen == 0 ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); #if defined(MBEDTLS_PEM_PARSE_C) /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */ if( buf[buflen - 1] == '\0' ) { mbedtls_pem_init( &pem ); ret = mbedtls_pem_read_buffer( &pem, "-----BEGIN CERTIFICATE REQUEST-----", "-----END CERTIFICATE REQUEST-----", buf, NULL, 0, &use_len ); if( ret == MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT ) { ret = mbedtls_pem_read_buffer( &pem, "-----BEGIN NEW CERTIFICATE REQUEST-----", "-----END NEW CERTIFICATE REQUEST-----", buf, NULL, 0, &use_len ); } if( ret == 0 ) { /* * Was PEM encoded, parse the result */ ret = mbedtls_x509_csr_parse_der( csr, pem.buf, pem.buflen ); } mbedtls_pem_free( &pem ); if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT ) return( ret ); } #endif /* MBEDTLS_PEM_PARSE_C */ return( mbedtls_x509_csr_parse_der( csr, buf, buflen ) ); } /** * \brief Load a Certificate Signing Request (CSR) * * \note See notes for \c mbedtls_x509_csr_parse() * * \param csr CSR context to fill * \param path filename to read the CSR from * * \return 0 if successful, or a specific X509 or PEM error code */ int mbedtls_x509_csr_parse_file( mbedtls_x509_csr *csr, const char *path ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t n; unsigned char *buf; if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 ) return( ret ); ret = mbedtls_x509_csr_parse( csr, buf, n ); mbedtls_platform_zeroize( buf, n ); mbedtls_free( buf ); return( ret ); } #define BEFORE_COLON 14 #define BC "14" /** * \brief Returns an informational string about the * CSR. * * \param buf Buffer to write to * \param size Maximum size of buffer * \param prefix A line prefix * \param csr The X509 CSR to represent * * \return The length of the string written (not including the * terminated nul byte), or a negative error code. */ int mbedtls_x509_csr_info( char *buf, size_t size, const char *prefix, const mbedtls_x509_csr *csr ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t n; char *p; char key_size_str[BEFORE_COLON]; p = buf; n = size; ret = mbedtls_snprintf( p, n, "%sCSR version : %d", prefix, csr->version ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%ssubject name : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_x509_dn_gets( p, n, &csr->subject ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%ssigned using : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_x509_sig_alg_gets( p, n, &csr->sig_oid, csr->sig_pk, csr->sig_md, csr->sig_opts ); MBEDTLS_X509_SAFE_SNPRINTF; if( ( ret = mbedtls_x509_key_size_helper( key_size_str, BEFORE_COLON, mbedtls_pk_get_name( &csr->pk ) ) ) != 0 ) { return( ret ); } ret = mbedtls_snprintf( p, n, "\n%s%-" BC "s: %d bits\n", prefix, key_size_str, (int) mbedtls_pk_get_bitlen( &csr->pk ) ); MBEDTLS_X509_SAFE_SNPRINTF; return( (int) ( size - n ) ); } /** * \brief Initialize a CSR * * \param csr CSR to initialize */ void mbedtls_x509_csr_init( mbedtls_x509_csr *csr ) { mbedtls_platform_zeroize( csr, sizeof(mbedtls_x509_csr) ); } /** * \brief Unallocate all CSR data * * \param csr CSR to free */ void mbedtls_x509_csr_free( mbedtls_x509_csr *csr ) { mbedtls_x509_name *name_cur; mbedtls_x509_name *name_prv; if( csr == NULL ) return; mbedtls_pk_free( &csr->pk ); name_cur = csr->subject.next; while( name_cur != NULL ) { name_prv = name_cur; name_cur = name_cur->next; mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) ); mbedtls_free( name_prv ); } if( csr->raw.p != NULL ) { mbedtls_platform_zeroize( csr->raw.p, csr->raw.len ); mbedtls_free( csr->raw.p ); } mbedtls_platform_zeroize( csr, sizeof( mbedtls_x509_csr ) ); } #endif /* MBEDTLS_X509_CSR_PARSE_C */
13,510
431
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/memory_buffer_alloc.h
#ifndef MBEDTLS_MEMORY_BUFFER_ALLOC_H #define MBEDTLS_MEMORY_BUFFER_ALLOC_H #include "third_party/mbedtls/config.h" /* clang-format off */ /** * \name SECTION: Module settings * * The configuration options you can set for this module are in this section. * Either change them in config.h or define them on the compiler command line. * \{ */ #if !defined(MBEDTLS_MEMORY_ALIGN_MULTIPLE) #define MBEDTLS_MEMORY_ALIGN_MULTIPLE 4 /*< Align on multiples of this value */ #endif /* \} name SECTION: Module settings */ #define MBEDTLS_MEMORY_VERIFY_NONE 0 #define MBEDTLS_MEMORY_VERIFY_ALLOC (1 << 0) #define MBEDTLS_MEMORY_VERIFY_FREE (1 << 1) #define MBEDTLS_MEMORY_VERIFY_ALWAYS (MBEDTLS_MEMORY_VERIFY_ALLOC | MBEDTLS_MEMORY_VERIFY_FREE) #ifdef __cplusplus extern "C" { #endif /** * \brief Initialize use of stack-based memory allocator. * The stack-based allocator does memory management inside the * presented buffer and does not call calloc() and free(). * It sets the global mbedtls_calloc() and mbedtls_free() pointers * to its own functions. * * \note This code is not optimized and provides a straight-forward * implementation of a stack-based memory allocator. * * \param buf buffer to use as heap * \param len size of the buffer */ void mbedtls_memory_buffer_alloc_init( unsigned char *buf, size_t len ); /** * \brief Free the mutex for thread-safety and clear remaining memory */ void mbedtls_memory_buffer_alloc_free( void ); /** * \brief Determine when the allocator should automatically verify the state * of the entire chain of headers / meta-data. * (Default: MBEDTLS_MEMORY_VERIFY_NONE) * * \param verify One of MBEDTLS_MEMORY_VERIFY_NONE, MBEDTLS_MEMORY_VERIFY_ALLOC, * MBEDTLS_MEMORY_VERIFY_FREE or MBEDTLS_MEMORY_VERIFY_ALWAYS */ void mbedtls_memory_buffer_set_verify( int verify ); #if defined(MBEDTLS_MEMORY_DEBUG) /** * \brief Print out the status of the allocated memory (primarily for use * after a program should have de-allocated all memory) * Prints out a list of 'still allocated' blocks and their stack * trace if MBEDTLS_MEMORY_BACKTRACE is defined. */ void mbedtls_memory_buffer_alloc_status( void ); /** * \brief Get the peak heap usage so far * * \param max_used Peak number of bytes in use or committed. This * includes bytes in allocated blocks too small to split * into smaller blocks but larger than the requested size. * \param max_blocks Peak number of blocks in use, including free and used */ void mbedtls_memory_buffer_alloc_max_get( size_t *max_used, size_t *max_blocks ); /** * \brief Reset peak statistics */ void mbedtls_memory_buffer_alloc_max_reset( void ); /** * \brief Get the current heap usage * * \param cur_used Current number of bytes in use or committed. This * includes bytes in allocated blocks too small to split * into smaller blocks but larger than the requested size. * \param cur_blocks Current number of blocks in use, including free and used */ void mbedtls_memory_buffer_alloc_cur_get( size_t *cur_used, size_t *cur_blocks ); #endif /* MBEDTLS_MEMORY_DEBUG */ /** * \brief Verifies that all headers in the memory buffer are correct * and contain sane values. Helps debug buffer-overflow errors. * * Prints out first failure if MBEDTLS_MEMORY_DEBUG is defined. * Prints out full header information if MBEDTLS_MEMORY_DEBUG * is defined. (Includes stack trace information for each block if * MBEDTLS_MEMORY_BACKTRACE is defined as well). * * \return 0 if verified, 1 otherwise */ int mbedtls_memory_buffer_alloc_verify( void ); #if defined(MBEDTLS_SELF_TEST) /** * \brief Checkup routine * * \return 0 if successful, or 1 if a test failed */ int mbedtls_memory_buffer_alloc_self_test( int verbose ); #endif #ifdef __cplusplus } #endif #endif /* memory_buffer_alloc.h */
4,148
121
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/sha256.h
#ifndef MBEDTLS_SHA256_H_ #define MBEDTLS_SHA256_H_ #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/platform.h" COSMOPOLITAN_C_START_ /* clang-format off */ #define MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED -0x0037 /*< SHA-256 hardware accelerator failed */ #define MBEDTLS_ERR_SHA256_BAD_INPUT_DATA -0x0074 /*< SHA-256 input data was malformed. */ /** * \brief The SHA-256 context structure. * * The structure is used both for SHA-256 and for SHA-224 * checksum calculations. The choice between these two is * made in the call to mbedtls_sha256_starts_ret(). */ typedef struct mbedtls_sha256_context { uint32_t state[8]; /*!< The intermediate digest state. */ uint32_t total[2]; /*!< The number of Bytes processed. */ unsigned char buffer[64]; /*!< The data block being processed. */ int is224; /*!< Determines which function to use: 0: Use SHA-256, or 1: Use SHA-224. */ } mbedtls_sha256_context; void mbedtls_sha256_clone( mbedtls_sha256_context *, const mbedtls_sha256_context * ); int mbedtls_sha256_starts_ret( mbedtls_sha256_context *, int ); int mbedtls_sha256_update_ret( mbedtls_sha256_context *, const unsigned char *, size_t ); int mbedtls_sha256_finish_ret( mbedtls_sha256_context *, unsigned char[32] ); int mbedtls_internal_sha256_process( mbedtls_sha256_context *, const unsigned char[64] ); int mbedtls_sha256_ret( const void *, size_t, unsigned char[32], int ); int mbedtls_sha256_ret_224( const void *, size_t , unsigned char * ); int mbedtls_sha256_ret_256( const void *, size_t , unsigned char * ); int mbedtls_sha256_self_test( int ); /** * \brief This function initializes a SHA-256 context. * * \param ctx The SHA-256 context to initialize. This must not be \c NULL. */ static inline void mbedtls_sha256_init( mbedtls_sha256_context *ctx ) { mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha256_context ) ); } /** * \brief This function clears a SHA-256 context. * * \param ctx The SHA-256 context to clear. This may be \c NULL, in which * case this function returns immediately. If it is not \c NULL, * it must point to an initialized SHA-256 context. */ static inline void mbedtls_sha256_free( mbedtls_sha256_context *ctx ) { if( !ctx ) return; mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha256_context ) ); } COSMOPOLITAN_C_END_ #endif /* MBEDTLS_SHA256_H_ */
2,583
63
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/version.h
#ifndef MBEDTLS_VERSION_H #define MBEDTLS_VERSION_H #include "third_party/mbedtls/config.h" /* clang-format off */ /** * The version number x.y.z is split into three parts. * Major, Minor, Patchlevel */ #define MBEDTLS_VERSION_MAJOR 2 #define MBEDTLS_VERSION_MINOR 26 #define MBEDTLS_VERSION_PATCH 0 /** * The single version number has the following structure: * MMNNPP00 * Major version | Minor version | Patch version */ #define MBEDTLS_VERSION_NUMBER 0x021A0000 #define MBEDTLS_VERSION_STRING "2.26.0" #define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.26.0" #if defined(MBEDTLS_VERSION_C) #ifdef __cplusplus extern "C" { #endif /** * Get the version number. * * \return The constructed version number in the format * MMNNPP00 (Major, Minor, Patch). */ unsigned int mbedtls_version_get_number( void ); /** * Get the version string ("x.y.z"). * * \param string The string that will receive the value. * (Should be at least 9 bytes in size) */ void mbedtls_version_get_string( char *string ); /** * Get the full version string ("mbed TLS x.y.z"). * * \param string The string that will receive the value. The mbed TLS version * string will use 18 bytes AT MOST including a terminating * null byte. * (So the buffer should be at least 18 bytes to receive this * version string). */ void mbedtls_version_get_string_full( char *string ); /** * \brief Check if support for a feature was compiled into this * mbed TLS binary. This allows you to see at runtime if the * library was for instance compiled with or without * Multi-threading support. * * \note only checks against defines in the sections "System * support", "mbed TLS modules" and "mbed TLS feature * support" in config.h * * \param feature The string for the define to check (e.g. "MBEDTLS_AES_C") * * \return 0 if the feature is present, * -1 if the feature is not present and * -2 if support for feature checking as a whole was not * compiled in. */ int mbedtls_version_check_feature( const char *feature ); #ifdef __cplusplus } #endif #endif /* MBEDTLS_VERSION_C */ #endif /* version.h */
2,413
82
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/iana.h
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_IANA_H_ #define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_IANA_H_ #include "third_party/mbedtls/ssl.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ bool IsCipherSuiteGood(uint16_t); const char *GetCipherSuiteName(uint16_t); const char *GetAlertDescription(unsigned char); dontdiscard char *FormatSslClientCiphers(const mbedtls_ssl_context *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_IANA_H_ */
513
15
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/x509_csr.h
#ifndef MBEDTLS_X509_CSR_H_ #define MBEDTLS_X509_CSR_H_ #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/x509.h" COSMOPOLITAN_C_START_ /* clang-format off */ /** * Certificate Signing Request (CSR) structure. */ typedef struct mbedtls_x509_csr { mbedtls_x509_buf raw; /*< The raw CSR data (DER). */ mbedtls_x509_buf cri; /*< The raw CertificateRequestInfo body (DER). */ int version; /*< CSR version (1=v1). */ mbedtls_x509_buf subject_raw; /*< The raw subject data (DER). */ mbedtls_x509_name subject; /*< The parsed subject data (named information object). */ mbedtls_pk_context pk; /*< Container for the public key context. */ mbedtls_x509_buf sig_oid; mbedtls_x509_buf sig; mbedtls_md_type_t sig_md; /*< Internal representation of the MD algorithm of the signature algorithm, e.g. MBEDTLS_MD_SHA256 */ mbedtls_pk_type_t sig_pk; /*< Internal representation of the Public Key algorithm of the signature algorithm, e.g. MBEDTLS_PK_RSA */ void *sig_opts; /*< Signature options to be passed to mbedtls_pk_verify_ext(), e.g. for RSASSA-PSS */ } mbedtls_x509_csr; /** * Container for writing a CSR */ typedef struct mbedtls_x509write_csr { mbedtls_pk_context *key; mbedtls_asn1_named_data *subject; mbedtls_md_type_t md_alg; mbedtls_asn1_named_data *extensions; } mbedtls_x509write_csr; int mbedtls_x509_csr_info( char *, size_t, const char *, const mbedtls_x509_csr * ); int mbedtls_x509_csr_parse( mbedtls_x509_csr *, const unsigned char *, size_t ); int mbedtls_x509_csr_parse_der( mbedtls_x509_csr *, const unsigned char *, size_t ); int mbedtls_x509_csr_parse_file( mbedtls_x509_csr *, const char * ); int mbedtls_x509write_csr_der( mbedtls_x509write_csr *, unsigned char *, size_t, int (*)(void *, unsigned char *, size_t), void * ); int mbedtls_x509write_csr_pem( mbedtls_x509write_csr *, unsigned char *, size_t, int (*)(void *, unsigned char *, size_t), void * ); int mbedtls_x509write_csr_set_extension( mbedtls_x509write_csr *, const char *, size_t, const unsigned char *, size_t ); int mbedtls_x509write_csr_set_key_usage( mbedtls_x509write_csr *, unsigned char ); int mbedtls_x509write_csr_set_ns_cert_type( mbedtls_x509write_csr *, unsigned char ); int mbedtls_x509write_csr_set_subject_name( mbedtls_x509write_csr *, const char * ); void mbedtls_x509_csr_free( mbedtls_x509_csr * ); void mbedtls_x509_csr_init( mbedtls_x509_csr * ); void mbedtls_x509write_csr_free( mbedtls_x509write_csr * ); void mbedtls_x509write_csr_init( mbedtls_x509write_csr * ); void mbedtls_x509write_csr_set_key( mbedtls_x509write_csr *, mbedtls_pk_context * ); void mbedtls_x509write_csr_set_md_alg( mbedtls_x509write_csr *, mbedtls_md_type_t ); COSMOPOLITAN_C_END_ #endif /* MBEDTLS_X509_CSR_H_ */
2,860
54
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/md5.h
#ifndef MBEDTLS_MD5_H_ #define MBEDTLS_MD5_H_ #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/platform.h" COSMOPOLITAN_C_START_ /* clang-format off */ #define MBEDTLS_ERR_MD5_HW_ACCEL_FAILED -0x002F /*< MD5 hardware accelerator failed */ /** * \brief MD5 context structure * * \warning MD5 is considered a weak message digest and its use * constitutes a security risk. We recommend considering * stronger message digests instead. * */ typedef struct mbedtls_md5_context { uint32_t total[2]; /*!< number of bytes processed */ uint32_t state[4]; /*!< intermediate digest state */ unsigned char buffer[64]; /*!< data block being processed */ } mbedtls_md5_context; void mbedtls_md5_clone( mbedtls_md5_context *, const mbedtls_md5_context * ); int mbedtls_md5_starts_ret( mbedtls_md5_context * ); int mbedtls_md5_update_ret( mbedtls_md5_context *, const unsigned char *, size_t ); int mbedtls_md5_finish_ret( mbedtls_md5_context *, unsigned char[16] ); int mbedtls_internal_md5_process( mbedtls_md5_context *, const unsigned char[64] ); int mbedtls_md5_ret( const void *, size_t, unsigned char[16] ); int mbedtls_md5_self_test( int ); /** * \brief Initialize MD5 context * * \param ctx MD5 context to be initialized * * \warning MD5 is considered a weak message digest and its use * constitutes a security risk. We recommend considering * stronger message digests instead. */ static inline void mbedtls_md5_init( mbedtls_md5_context *ctx ) { mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md5_context ) ); } /** * \brief Clear MD5 context * * \param ctx MD5 context to be cleared * * \warning MD5 is considered a weak message digest and its use * constitutes a security risk. We recommend considering * stronger message digests instead. */ static inline void mbedtls_md5_free( mbedtls_md5_context *ctx ) { if( !ctx ) return; mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md5_context ) ); } COSMOPOLITAN_C_END_ #endif /* MBEDTLS_MD5_H_ */
2,187
65
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/gcm.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/bits.h" #include "libc/intrin/likely.h" #include "libc/log/log.h" #include "libc/nexgen32e/x86feature.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "third_party/mbedtls/aes.h" #include "third_party/mbedtls/aesni.h" #include "third_party/mbedtls/cipher.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/endian.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/gcm.h" #include "third_party/mbedtls/platform.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /* * NIST SP800-38D compliant GCM implementation * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf * * See also: * [MGV] http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf * * We use the algorithm described as Shoup's method with 4-bit tables in * [MGV] 4.1, pp. 12-13, to enhance speed without using too much memory. */ #if !defined(MBEDTLS_GCM_ALT) /* Parameter validation macros */ #define GCM_VALIDATE_RET( cond ) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_GCM_BAD_INPUT ) #define GCM_VALIDATE( cond ) \ MBEDTLS_INTERNAL_VALIDATE( cond ) /** * \brief This function initializes the specified GCM context, * to make references valid, and prepares the context * for mbedtls_gcm_setkey() or mbedtls_gcm_free(). * * The function does not bind the GCM context to a particular * cipher, nor set the key. For this purpose, use * mbedtls_gcm_setkey(). * * \param ctx The GCM context to initialize. This must not be \c NULL. */ void mbedtls_gcm_init( mbedtls_gcm_context *ctx ) { GCM_VALIDATE( ctx != NULL ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_gcm_context ) ); } /* * Precompute small multiples of H, that is set * HH[i] || HL[i] = H times i, * where i is seen as a field element as in [MGV], ie high-order bits * correspond to low powers of P. The result is stored in the same way, that * is the high-order bit of HH corresponds to P^0 and the low-order bit of HL * corresponds to P^127. */ static int gcm_gen_table( mbedtls_gcm_context *ctx ) { int ret, i, j; uint64_t hi, lo; uint64_t vl, vh; unsigned char h[16]; size_t olen = 0; mbedtls_platform_zeroize( h, 16 ); if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, h, 16, h, &olen ) ) != 0 ) return( ret ); vh = READ64BE( h + 0 ); vl = READ64BE( h + 8 ); #if defined(MBEDTLS_AESNI_C) && defined(MBEDTLS_HAVE_X86_64) /* With CLMUL support, we need only h, not the rest of the table */ if (X86_HAVE(AES) && X86_HAVE(PCLMUL)) { ctx->H8[0] = vl; ctx->H8[1] = vh; return 0; } #endif /* 0 corresponds to 0 in GF(2^128) */ ctx->HH[0] = 0; ctx->HL[0] = 0; /* 8 = 1000 corresponds to 1 in GF(2^128) */ ctx->HL[8] = vl; ctx->HH[8] = vh; for( i = 4; i > 0; i >>= 1 ) { uint32_t T = ( vl & 1 ) * 0xe1000000U; vl = ( vh << 63 ) | ( vl >> 1 ); vh = ( vh >> 1 ) ^ ( (uint64_t) T << 32); ctx->HL[i] = vl; ctx->HH[i] = vh; } for( i = 2; i <= 8; i *= 2 ) { uint64_t *HiL = ctx->HL + i, *HiH = ctx->HH + i; vh = *HiH; vl = *HiL; for( j = 1; j < i; j++ ) { HiH[j] = vh ^ ctx->HH[j]; HiL[j] = vl ^ ctx->HL[j]; } } return( 0 ); } /** * \brief This function associates a GCM context with a * cipher algorithm and a key. * * \param ctx The GCM context. This must be initialized. * \param cipher The 128-bit block cipher to use. * \param key The encryption key. This must be a readable buffer of at * least \p keybits bits. * \param keybits The key size in bits. Valid options are: * <ul><li>128 bits</li> * <li>192 bits</li> * <li>256 bits</li></ul> * * \return \c 0 on success. * \return A cipher-specific error code on failure. */ int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx, mbedtls_cipher_id_t cipher, const unsigned char *key, unsigned int keybits ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; const mbedtls_cipher_info_t *cipher_info; GCM_VALIDATE_RET( ctx != NULL ); GCM_VALIDATE_RET( key != NULL ); GCM_VALIDATE_RET( keybits == 128 || keybits == 192 || keybits == 256 ); cipher_info = mbedtls_cipher_info_from_values( cipher, keybits, MBEDTLS_MODE_ECB ); if( cipher_info == NULL ) return( MBEDTLS_ERR_GCM_BAD_INPUT ); if( cipher_info->block_size != 16 ) return( MBEDTLS_ERR_GCM_BAD_INPUT ); mbedtls_cipher_free( &ctx->cipher_ctx ); ctx->cipher = cipher; if( ( ret = mbedtls_cipher_setup( &ctx->cipher_ctx, cipher_info ) ) != 0 ) return( ret ); if( ( ret = mbedtls_cipher_setkey( &ctx->cipher_ctx, key, keybits, MBEDTLS_ENCRYPT ) ) != 0 ) { return( ret ); } if( ( ret = gcm_gen_table( ctx ) ) != 0 ) return( ret ); return( 0 ); } /* * Shoup's method for multiplication use this table with * last4[x] = x times P^128 * where x and last4[x] are seen as elements of GF(2^128) as in [MGV] */ static const uint64_t last4[16] = { 0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0, 0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0 }; /* * Sets output to x times H using the precomputed tables. * x and output are seen as elements of GF(2^128) as in [MGV]. */ static void gcm_mult( mbedtls_gcm_context *ctx, unsigned char x[16] ) { int i; uint64_t zh, zl; unsigned char lo, hi, rem; #if defined(MBEDTLS_AESNI_C) && defined(MBEDTLS_HAVE_X86_64) if (LIKELY(X86_HAVE(AES) && X86_HAVE(PCLMUL))) { mbedtls_aesni_gcm_mult( x, ctx->H8 ); return; } #endif /* MBEDTLS_AESNI_C && MBEDTLS_HAVE_X86_64 */ lo = x[15] & 0xf; zh = ctx->HH[lo]; zl = ctx->HL[lo]; for( i = 15; i >= 0; i-- ) { lo = x[i] & 0xf; hi = ( x[i] >> 4 ) & 0xf; if( i != 15 ) { rem = (unsigned char) zl & 0xf; zl = ( zh << 60 ) | ( zl >> 4 ); zh = ( zh >> 4 ); zh ^= (uint64_t) last4[rem] << 48; zh ^= ctx->HH[lo]; zl ^= ctx->HL[lo]; } rem = (unsigned char) zl & 0xf; zl = ( zh << 60 ) | ( zl >> 4 ); zh = ( zh >> 4 ); zh ^= (uint64_t) last4[rem] << 48; zh ^= ctx->HH[hi]; zl ^= ctx->HL[hi]; } PUT_UINT64_BE( zh, x, 0 ); PUT_UINT64_BE( zl, x, 8 ); } /** * \brief This function starts a GCM encryption or decryption * operation. * * \param ctx The GCM context. This must be initialized. * \param mode The operation to perform: #MBEDTLS_GCM_ENCRYPT or * #MBEDTLS_GCM_DECRYPT. * \param iv The initialization vector. This must be a readable buffer of * at least \p iv_len Bytes. * \param iv_len The length of the IV. * \param add The buffer holding the additional data, or \c NULL * if \p add_len is \c 0. * \param add_len The length of the additional data. If \c 0, * \p add may be \c NULL. * * \return \c 0 on success. */ int mbedtls_gcm_starts( mbedtls_gcm_context *ctx, int mode, const unsigned char *iv, size_t iv_len, const unsigned char *add, size_t add_len ) { size_t i; const unsigned char *p; size_t use_len, olen = 0; unsigned char work_buf[16]; int ret = MBEDTLS_ERR_THIS_CORRUPTION; GCM_VALIDATE_RET( ctx != NULL ); GCM_VALIDATE_RET( iv != NULL ); GCM_VALIDATE_RET( add_len == 0 || add != NULL ); /* IV and AD are limited to 2^64 bits, so 2^61 bytes */ /* IV is not allowed to be zero length */ if( iv_len == 0 || ( (uint64_t) iv_len ) >> 61 != 0 || ( (uint64_t) add_len ) >> 61 != 0 ) { return( MBEDTLS_ERR_GCM_BAD_INPUT ); } mbedtls_platform_zeroize( ctx->y, sizeof(ctx->y) ); mbedtls_platform_zeroize( ctx->buf, sizeof(ctx->buf) ); ctx->mode = mode; ctx->len = 0; ctx->add_len = 0; if( iv_len == 12 ) { memcpy( ctx->y, iv, iv_len ); ctx->y[15] = 1; } else { mbedtls_platform_zeroize( work_buf, 16 ); PUT_UINT32_BE( iv_len * 8, work_buf, 12 ); p = iv; while( iv_len > 0 ) { use_len = ( iv_len < 16 ) ? iv_len : 16; for( i = 0; i < use_len; i++ ) ctx->y[i] ^= p[i]; gcm_mult( ctx, ctx->y ); iv_len -= use_len; p += use_len; } for( i = 0; i < 16; i++ ) ctx->y[i] ^= work_buf[i]; gcm_mult( ctx, ctx->y ); } if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, ctx->y, 16, ctx->base_ectr, &olen ) ) != 0 ) { return( ret ); } ctx->add_len = add_len; p = add; while( add_len > 0 ) { use_len = ( add_len < 16 ) ? add_len : 16; for( i = 0; i < use_len; i++ ) ctx->buf[i] ^= p[i]; gcm_mult( ctx, ctx->buf ); add_len -= use_len; p += use_len; } return( 0 ); } /** * \brief This function feeds an input buffer into an ongoing GCM * encryption or decryption operation. * * The function expects input to be a multiple of 16 * Bytes. Only the last call before calling * mbedtls_gcm_finish() can be less than 16 Bytes. * * \note For decryption, the output buffer cannot be the same as * input buffer. If the buffers overlap, the output buffer * must trail at least 8 Bytes behind the input buffer. * * \param ctx The GCM context. This must be initialized. * \param length The length of the input data. This must be a multiple of * 16 except in the last call before mbedtls_gcm_finish(). * \param input The buffer holding the input data. If \p length is greater * than zero, this must be a readable buffer of at least that * size in Bytes. * \param output The buffer for holding the output data. If \p length is * greater than zero, this must be a writable buffer of at * least that size in Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_GCM_BAD_INPUT on failure. */ int mbedtls_gcm_update( mbedtls_gcm_context *ctx, size_t length, const unsigned char *input, unsigned char *output ) { size_t i, j; uint64_t a, b; int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char ectr[16]; const unsigned char *p; unsigned char *q, *out_p = output; size_t olen = 0; GCM_VALIDATE_RET( ctx ); GCM_VALIDATE_RET( !length || input ); GCM_VALIDATE_RET( !length || output ); if( output > input && (size_t) ( output - input ) < length ) return( MBEDTLS_ERR_GCM_BAD_INPUT ); /* Total length is restricted to 2^39 - 256 bits, ie 2^36 - 2^5 bytes * Also check for possible overflow */ if( ctx->len + length < ctx->len || (uint64_t) ctx->len + length > 0xFFFFFFFE0ull ) { return( MBEDTLS_ERR_GCM_BAD_INPUT ); } ctx->len += length; p = input; q = ctx->buf; for( j = 0; j + 16 <= length; j += 16 ){ for( i = 16; i > 12; i-- ) if( ++ctx->y[i - 1] != 0 ) break; if( !( ret = mbedtls_cipher_update( &ctx->cipher_ctx, ctx->y, 16, ectr, &olen ) ) ) { if( ctx->mode == MBEDTLS_GCM_DECRYPT ) { __builtin_memcpy(&a, p+j, 8); __builtin_memcpy(&b, q, 8); b ^= a; __builtin_memcpy(q, &b, 8); __builtin_memcpy(&b, ectr, 8); b ^= a; __builtin_memcpy(out_p+j, &b, 8); __builtin_memcpy(&a, p+j+8, 8); __builtin_memcpy(&b, q+8, 8); b ^= a; __builtin_memcpy(q+8, &b, 8); __builtin_memcpy(&b, ectr+8, 8); b ^= a; __builtin_memcpy(out_p+j+8, &b, 8); /* for( i = 0; i < 16; i++ ) ctx->buf[i] ^= p[i]; */ /* for( i = 0; i < 16; i++ ) out_p[i] = ectr[i] ^ p[i]; */ } else { __builtin_memcpy(&a, ectr, 8); __builtin_memcpy(&b, p+j, 8); b ^= a; __builtin_memcpy(out_p+j, &b, 8); __builtin_memcpy(&a, q, 8); b ^= a; __builtin_memcpy(q, &b, 8); __builtin_memcpy(&a, ectr+8, 8); __builtin_memcpy(&b, p+j+8, 8); b ^= a; __builtin_memcpy(out_p+j+8, &b, 8); __builtin_memcpy(&a, q+8, 8); b ^= a; __builtin_memcpy(q+8, &b, 8); /* for( i = 0; i < 16; i++ ) out_p[i] = ectr[i] ^ p[i]; */ /* for( i = 0; i < 16; i++ ) ctx->buf[i] ^= out_p[i]; */ } gcm_mult( ctx, q ); } else { return( ret ); } } length -= j; out_p += j; p += j; if( length ) { for( i = 16; i > 12; i-- ) if( ++ctx->y[i - 1] != 0 ) break; if( !( ret = mbedtls_cipher_update( &ctx->cipher_ctx, ctx->y, 16, ectr, &olen ) ) ) { if( ctx->mode == MBEDTLS_GCM_DECRYPT ) { for( i = 0; i < length; i++ ){ q[i] ^= p[i]; out_p[i] = ectr[i] ^ p[i]; } } else { for( i = 0; i < length; i++ ){ out_p[i] = ectr[i] ^ p[i]; q[i] ^= out_p[i]; } } gcm_mult( ctx, q ); } else { return( ret ); } } return( 0 ); } /** * \brief This function finishes the GCM operation and generates * the authentication tag. * * It wraps up the GCM stream, and generates the * tag. The tag can have a maximum length of 16 Bytes. * * \param ctx The GCM context. This must be initialized. * \param tag The buffer for holding the tag. This must be a writable * buffer of at least \p tag_len Bytes. * \param tag_len The length of the tag to generate. This must be at least * four. * * \return \c 0 on success. * \return #MBEDTLS_ERR_GCM_BAD_INPUT on failure. */ int mbedtls_gcm_finish( mbedtls_gcm_context *ctx, unsigned char *tag, size_t tag_len ) { size_t i; uint64_t orig_len; uint64_t orig_add_len; GCM_VALIDATE_RET( ctx != NULL ); GCM_VALIDATE_RET( tag != NULL ); orig_len = ctx->len * 8; orig_add_len = ctx->add_len * 8; if( tag_len > 16 || tag_len < 4 ) return( MBEDTLS_ERR_GCM_BAD_INPUT ); memcpy( tag, ctx->base_ectr, tag_len ); if( orig_len || orig_add_len ) { Write64be( ctx->buf + 0, READ64BE( ctx->buf + 0 ) ^ orig_add_len ); Write64be( ctx->buf + 8, READ64BE( ctx->buf + 8 ) ^ orig_len ); gcm_mult( ctx, ctx->buf ); for( i = 0; i < tag_len; i++ ) tag[i] ^= ctx->buf[i]; } return( 0 ); } /** * \brief This function performs GCM encryption or decryption of a buffer. * * \note For encryption, the output buffer can be the same as the * input buffer. For decryption, the output buffer cannot be * the same as input buffer. If the buffers overlap, the output * buffer must trail at least 8 Bytes behind the input buffer. * * \warning When this function performs a decryption, it outputs the * authentication tag and does not verify that the data is * authentic. You should use this function to perform encryption * only. For decryption, use mbedtls_gcm_auth_decrypt() instead. * * \param ctx The GCM context to use for encryption or decryption. This * must be initialized. * \param mode The operation to perform: * - #MBEDTLS_GCM_ENCRYPT to perform authenticated encryption. * The ciphertext is written to \p output and the * authentication tag is written to \p tag. * - #MBEDTLS_GCM_DECRYPT to perform decryption. * The plaintext is written to \p output and the * authentication tag is written to \p tag. * Note that this mode is not recommended, because it does * not verify the authenticity of the data. For this reason, * you should use mbedtls_gcm_auth_decrypt() instead of * calling this function in decryption mode. * \param length The length of the input data, which is equal to the length * of the output data. * \param iv The initialization vector. This must be a readable buffer of * at least \p iv_len Bytes. * \param iv_len The length of the IV. * \param add The buffer holding the additional data. This must be of at * least that size in Bytes. * \param add_len The length of the additional data. * \param input The buffer holding the input data. If \p length is greater * than zero, this must be a readable buffer of at least that * size in Bytes. * \param output The buffer for holding the output data. If \p length is greater * than zero, this must be a writable buffer of at least that * size in Bytes. * \param tag_len The length of the tag to generate. * \param tag The buffer for holding the tag. This must be a writable * buffer of at least \p tag_len Bytes. * * \return \c 0 if the encryption or decryption was performed * successfully. Note that in #MBEDTLS_GCM_DECRYPT mode, * this does not indicate that the data is authentic. * \return #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths or pointers are * not valid or a cipher-specific error code if the encryption * or decryption failed. */ int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx, int mode, size_t length, const unsigned char *iv, size_t iv_len, const unsigned char *add, size_t add_len, const unsigned char *input, unsigned char *output, size_t tag_len, unsigned char *tag ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; GCM_VALIDATE_RET( ctx != NULL ); GCM_VALIDATE_RET( iv != NULL ); GCM_VALIDATE_RET( add_len == 0 || add != NULL ); GCM_VALIDATE_RET( length == 0 || input != NULL ); GCM_VALIDATE_RET( length == 0 || output != NULL ); GCM_VALIDATE_RET( tag != NULL ); if( ( ret = mbedtls_gcm_starts( ctx, mode, iv, iv_len, add, add_len ) ) != 0 ) return( ret ); if( ( ret = mbedtls_gcm_update( ctx, length, input, output ) ) != 0 ) return( ret ); if( ( ret = mbedtls_gcm_finish( ctx, tag, tag_len ) ) != 0 ) return( ret ); return( 0 ); } /** * \brief This function performs a GCM authenticated decryption of a * buffer. * * \note For decryption, the output buffer cannot be the same as * input buffer. If the buffers overlap, the output buffer * must trail at least 8 Bytes behind the input buffer. * * \param ctx The GCM context. This must be initialized. * \param length The length of the ciphertext to decrypt, which is also * the length of the decrypted plaintext. * \param iv The initialization vector. This must be a readable buffer * of at least \p iv_len Bytes. * \param iv_len The length of the IV. * \param add The buffer holding the additional data. This must be of at * least that size in Bytes. * \param add_len The length of the additional data. * \param tag The buffer holding the tag to verify. This must be a * readable buffer of at least \p tag_len Bytes. * \param tag_len The length of the tag to verify. * \param input The buffer holding the ciphertext. If \p length is greater * than zero, this must be a readable buffer of at least that * size. * \param output The buffer for holding the decrypted plaintext. If \p length * is greater than zero, this must be a writable buffer of at * least that size. * * \return \c 0 if successful and authenticated. * \return #MBEDTLS_ERR_GCM_AUTH_FAILED if the tag does not match. * \return #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths or pointers are * not valid or a cipher-specific error code if the decryption * failed. */ int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx, size_t length, const unsigned char *iv, size_t iv_len, const unsigned char *add, size_t add_len, const unsigned char *tag, size_t tag_len, const unsigned char *input, unsigned char *output ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char check_tag[16]; size_t i; int diff; GCM_VALIDATE_RET( ctx != NULL ); GCM_VALIDATE_RET( iv != NULL ); GCM_VALIDATE_RET( add_len == 0 || add != NULL ); GCM_VALIDATE_RET( tag != NULL ); GCM_VALIDATE_RET( length == 0 || input != NULL ); GCM_VALIDATE_RET( length == 0 || output != NULL ); if( ( ret = mbedtls_gcm_crypt_and_tag( ctx, MBEDTLS_GCM_DECRYPT, length, iv, iv_len, add, add_len, input, output, tag_len, check_tag ) ) != 0 ) { return( ret ); } /* Check tag in "constant-time" */ for( diff = 0, i = 0; i < tag_len; i++ ) diff |= tag[i] ^ check_tag[i]; if( diff != 0 ) { mbedtls_platform_zeroize( output, length ); return( MBEDTLS_ERR_GCM_AUTH_FAILED ); } return( 0 ); } /** * \brief This function clears a GCM context and the underlying * cipher sub-context. * * \param ctx The GCM context to clear. If this is \c NULL, the call has * no effect. Otherwise, this must be initialized. */ void mbedtls_gcm_free( mbedtls_gcm_context *ctx ) { if( ctx == NULL ) return; mbedtls_cipher_free( &ctx->cipher_ctx ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_gcm_context ) ); } #endif /* !MBEDTLS_GCM_ALT */ #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C) /* * AES-GCM test vectors from: * * http://csrc.nist.gov/groups/STM/cavp/documents/mac/gcmtestvectors.zip */ #define MAX_TESTS 6 static const int key_index_test_data[MAX_TESTS] = { 0, 0, 1, 1, 1, 1 }; static const unsigned char key_test_data[MAX_TESTS][32] = { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08, 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08 }, }; static const size_t iv_len_test_data[MAX_TESTS] = { 12, 12, 12, 12, 8, 60 }; static const int iv_index_test_data[MAX_TESTS] = { 0, 0, 1, 1, 1, 2 }; static const unsigned char iv_test_data[MAX_TESTS][64] = { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, 0xde, 0xca, 0xf8, 0x88 }, { 0x93, 0x13, 0x22, 0x5d, 0xf8, 0x84, 0x06, 0xe5, 0x55, 0x90, 0x9c, 0x5a, 0xff, 0x52, 0x69, 0xaa, 0x6a, 0x7a, 0x95, 0x38, 0x53, 0x4f, 0x7d, 0xa1, 0xe4, 0xc3, 0x03, 0xd2, 0xa3, 0x18, 0xa7, 0x28, 0xc3, 0xc0, 0xc9, 0x51, 0x56, 0x80, 0x95, 0x39, 0xfc, 0xf0, 0xe2, 0x42, 0x9a, 0x6b, 0x52, 0x54, 0x16, 0xae, 0xdb, 0xf5, 0xa0, 0xde, 0x6a, 0x57, 0xa6, 0x37, 0xb3, 0x9b }, }; static const size_t add_len_test_data[MAX_TESTS] = { 0, 0, 0, 20, 20, 20 }; static const int add_index_test_data[MAX_TESTS] = { 0, 0, 0, 1, 1, 1 }; static const unsigned char additional_test_data[MAX_TESTS][64] = { { 0x00 }, { 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, 0xab, 0xad, 0xda, 0xd2 }, }; static const size_t pt_len_test_data[MAX_TESTS] = { 0, 16, 64, 60, 60, 60 }; static const int pt_index_test_data[MAX_TESTS] = { 0, 0, 1, 1, 1, 1 }; static const unsigned char pt_test_data[MAX_TESTS][64] = { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, 0xba, 0x63, 0x7b, 0x39, 0x1a, 0xaf, 0xd2, 0x55 }, }; static const unsigned char ct_test_data[MAX_TESTS * 3][64] = { { 0x00 }, { 0x03, 0x88, 0xda, 0xce, 0x60, 0xb6, 0xa3, 0x92, 0xf3, 0x28, 0xc2, 0xb9, 0x71, 0xb2, 0xfe, 0x78 }, { 0x42, 0x83, 0x1e, 0xc2, 0x21, 0x77, 0x74, 0x24, 0x4b, 0x72, 0x21, 0xb7, 0x84, 0xd0, 0xd4, 0x9c, 0xe3, 0xaa, 0x21, 0x2f, 0x2c, 0x02, 0xa4, 0xe0, 0x35, 0xc1, 0x7e, 0x23, 0x29, 0xac, 0xa1, 0x2e, 0x21, 0xd5, 0x14, 0xb2, 0x54, 0x66, 0x93, 0x1c, 0x7d, 0x8f, 0x6a, 0x5a, 0xac, 0x84, 0xaa, 0x05, 0x1b, 0xa3, 0x0b, 0x39, 0x6a, 0x0a, 0xac, 0x97, 0x3d, 0x58, 0xe0, 0x91, 0x47, 0x3f, 0x59, 0x85 }, { 0x42, 0x83, 0x1e, 0xc2, 0x21, 0x77, 0x74, 0x24, 0x4b, 0x72, 0x21, 0xb7, 0x84, 0xd0, 0xd4, 0x9c, 0xe3, 0xaa, 0x21, 0x2f, 0x2c, 0x02, 0xa4, 0xe0, 0x35, 0xc1, 0x7e, 0x23, 0x29, 0xac, 0xa1, 0x2e, 0x21, 0xd5, 0x14, 0xb2, 0x54, 0x66, 0x93, 0x1c, 0x7d, 0x8f, 0x6a, 0x5a, 0xac, 0x84, 0xaa, 0x05, 0x1b, 0xa3, 0x0b, 0x39, 0x6a, 0x0a, 0xac, 0x97, 0x3d, 0x58, 0xe0, 0x91 }, { 0x61, 0x35, 0x3b, 0x4c, 0x28, 0x06, 0x93, 0x4a, 0x77, 0x7f, 0xf5, 0x1f, 0xa2, 0x2a, 0x47, 0x55, 0x69, 0x9b, 0x2a, 0x71, 0x4f, 0xcd, 0xc6, 0xf8, 0x37, 0x66, 0xe5, 0xf9, 0x7b, 0x6c, 0x74, 0x23, 0x73, 0x80, 0x69, 0x00, 0xe4, 0x9f, 0x24, 0xb2, 0x2b, 0x09, 0x75, 0x44, 0xd4, 0x89, 0x6b, 0x42, 0x49, 0x89, 0xb5, 0xe1, 0xeb, 0xac, 0x0f, 0x07, 0xc2, 0x3f, 0x45, 0x98 }, { 0x8c, 0xe2, 0x49, 0x98, 0x62, 0x56, 0x15, 0xb6, 0x03, 0xa0, 0x33, 0xac, 0xa1, 0x3f, 0xb8, 0x94, 0xbe, 0x91, 0x12, 0xa5, 0xc3, 0xa2, 0x11, 0xa8, 0xba, 0x26, 0x2a, 0x3c, 0xca, 0x7e, 0x2c, 0xa7, 0x01, 0xe4, 0xa9, 0xa4, 0xfb, 0xa4, 0x3c, 0x90, 0xcc, 0xdc, 0xb2, 0x81, 0xd4, 0x8c, 0x7c, 0x6f, 0xd6, 0x28, 0x75, 0xd2, 0xac, 0xa4, 0x17, 0x03, 0x4c, 0x34, 0xae, 0xe5 }, { 0x00 }, { 0x98, 0xe7, 0x24, 0x7c, 0x07, 0xf0, 0xfe, 0x41, 0x1c, 0x26, 0x7e, 0x43, 0x84, 0xb0, 0xf6, 0x00 }, { 0x39, 0x80, 0xca, 0x0b, 0x3c, 0x00, 0xe8, 0x41, 0xeb, 0x06, 0xfa, 0xc4, 0x87, 0x2a, 0x27, 0x57, 0x85, 0x9e, 0x1c, 0xea, 0xa6, 0xef, 0xd9, 0x84, 0x62, 0x85, 0x93, 0xb4, 0x0c, 0xa1, 0xe1, 0x9c, 0x7d, 0x77, 0x3d, 0x00, 0xc1, 0x44, 0xc5, 0x25, 0xac, 0x61, 0x9d, 0x18, 0xc8, 0x4a, 0x3f, 0x47, 0x18, 0xe2, 0x44, 0x8b, 0x2f, 0xe3, 0x24, 0xd9, 0xcc, 0xda, 0x27, 0x10, 0xac, 0xad, 0xe2, 0x56 }, { 0x39, 0x80, 0xca, 0x0b, 0x3c, 0x00, 0xe8, 0x41, 0xeb, 0x06, 0xfa, 0xc4, 0x87, 0x2a, 0x27, 0x57, 0x85, 0x9e, 0x1c, 0xea, 0xa6, 0xef, 0xd9, 0x84, 0x62, 0x85, 0x93, 0xb4, 0x0c, 0xa1, 0xe1, 0x9c, 0x7d, 0x77, 0x3d, 0x00, 0xc1, 0x44, 0xc5, 0x25, 0xac, 0x61, 0x9d, 0x18, 0xc8, 0x4a, 0x3f, 0x47, 0x18, 0xe2, 0x44, 0x8b, 0x2f, 0xe3, 0x24, 0xd9, 0xcc, 0xda, 0x27, 0x10 }, { 0x0f, 0x10, 0xf5, 0x99, 0xae, 0x14, 0xa1, 0x54, 0xed, 0x24, 0xb3, 0x6e, 0x25, 0x32, 0x4d, 0xb8, 0xc5, 0x66, 0x63, 0x2e, 0xf2, 0xbb, 0xb3, 0x4f, 0x83, 0x47, 0x28, 0x0f, 0xc4, 0x50, 0x70, 0x57, 0xfd, 0xdc, 0x29, 0xdf, 0x9a, 0x47, 0x1f, 0x75, 0xc6, 0x65, 0x41, 0xd4, 0xd4, 0xda, 0xd1, 0xc9, 0xe9, 0x3a, 0x19, 0xa5, 0x8e, 0x8b, 0x47, 0x3f, 0xa0, 0xf0, 0x62, 0xf7 }, { 0xd2, 0x7e, 0x88, 0x68, 0x1c, 0xe3, 0x24, 0x3c, 0x48, 0x30, 0x16, 0x5a, 0x8f, 0xdc, 0xf9, 0xff, 0x1d, 0xe9, 0xa1, 0xd8, 0xe6, 0xb4, 0x47, 0xef, 0x6e, 0xf7, 0xb7, 0x98, 0x28, 0x66, 0x6e, 0x45, 0x81, 0xe7, 0x90, 0x12, 0xaf, 0x34, 0xdd, 0xd9, 0xe2, 0xf0, 0x37, 0x58, 0x9b, 0x29, 0x2d, 0xb3, 0xe6, 0x7c, 0x03, 0x67, 0x45, 0xfa, 0x22, 0xe7, 0xe9, 0xb7, 0x37, 0x3b }, { 0x00 }, { 0xce, 0xa7, 0x40, 0x3d, 0x4d, 0x60, 0x6b, 0x6e, 0x07, 0x4e, 0xc5, 0xd3, 0xba, 0xf3, 0x9d, 0x18 }, { 0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07, 0xf4, 0x7f, 0x37, 0xa3, 0x2a, 0x84, 0x42, 0x7d, 0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9, 0x75, 0x98, 0xa2, 0xbd, 0x25, 0x55, 0xd1, 0xaa, 0x8c, 0xb0, 0x8e, 0x48, 0x59, 0x0d, 0xbb, 0x3d, 0xa7, 0xb0, 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38, 0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a, 0xbc, 0xc9, 0xf6, 0x62, 0x89, 0x80, 0x15, 0xad }, { 0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07, 0xf4, 0x7f, 0x37, 0xa3, 0x2a, 0x84, 0x42, 0x7d, 0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9, 0x75, 0x98, 0xa2, 0xbd, 0x25, 0x55, 0xd1, 0xaa, 0x8c, 0xb0, 0x8e, 0x48, 0x59, 0x0d, 0xbb, 0x3d, 0xa7, 0xb0, 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38, 0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a, 0xbc, 0xc9, 0xf6, 0x62 }, { 0xc3, 0x76, 0x2d, 0xf1, 0xca, 0x78, 0x7d, 0x32, 0xae, 0x47, 0xc1, 0x3b, 0xf1, 0x98, 0x44, 0xcb, 0xaf, 0x1a, 0xe1, 0x4d, 0x0b, 0x97, 0x6a, 0xfa, 0xc5, 0x2f, 0xf7, 0xd7, 0x9b, 0xba, 0x9d, 0xe0, 0xfe, 0xb5, 0x82, 0xd3, 0x39, 0x34, 0xa4, 0xf0, 0x95, 0x4c, 0xc2, 0x36, 0x3b, 0xc7, 0x3f, 0x78, 0x62, 0xac, 0x43, 0x0e, 0x64, 0xab, 0xe4, 0x99, 0xf4, 0x7c, 0x9b, 0x1f }, { 0x5a, 0x8d, 0xef, 0x2f, 0x0c, 0x9e, 0x53, 0xf1, 0xf7, 0x5d, 0x78, 0x53, 0x65, 0x9e, 0x2a, 0x20, 0xee, 0xb2, 0xb2, 0x2a, 0xaf, 0xde, 0x64, 0x19, 0xa0, 0x58, 0xab, 0x4f, 0x6f, 0x74, 0x6b, 0xf4, 0x0f, 0xc0, 0xc3, 0xb7, 0x80, 0xf2, 0x44, 0x45, 0x2d, 0xa3, 0xeb, 0xf1, 0xc5, 0xd8, 0x2c, 0xde, 0xa2, 0x41, 0x89, 0x97, 0x20, 0x0e, 0xf8, 0x2e, 0x44, 0xae, 0x7e, 0x3f }, }; static const unsigned char tag_test_data[MAX_TESTS * 3][16] = { { 0x58, 0xe2, 0xfc, 0xce, 0xfa, 0x7e, 0x30, 0x61, 0x36, 0x7f, 0x1d, 0x57, 0xa4, 0xe7, 0x45, 0x5a }, { 0xab, 0x6e, 0x47, 0xd4, 0x2c, 0xec, 0x13, 0xbd, 0xf5, 0x3a, 0x67, 0xb2, 0x12, 0x57, 0xbd, 0xdf }, { 0x4d, 0x5c, 0x2a, 0xf3, 0x27, 0xcd, 0x64, 0xa6, 0x2c, 0xf3, 0x5a, 0xbd, 0x2b, 0xa6, 0xfa, 0xb4 }, { 0x5b, 0xc9, 0x4f, 0xbc, 0x32, 0x21, 0xa5, 0xdb, 0x94, 0xfa, 0xe9, 0x5a, 0xe7, 0x12, 0x1a, 0x47 }, { 0x36, 0x12, 0xd2, 0xe7, 0x9e, 0x3b, 0x07, 0x85, 0x56, 0x1b, 0xe1, 0x4a, 0xac, 0xa2, 0xfc, 0xcb }, { 0x61, 0x9c, 0xc5, 0xae, 0xff, 0xfe, 0x0b, 0xfa, 0x46, 0x2a, 0xf4, 0x3c, 0x16, 0x99, 0xd0, 0x50 }, { 0xcd, 0x33, 0xb2, 0x8a, 0xc7, 0x73, 0xf7, 0x4b, 0xa0, 0x0e, 0xd1, 0xf3, 0x12, 0x57, 0x24, 0x35 }, { 0x2f, 0xf5, 0x8d, 0x80, 0x03, 0x39, 0x27, 0xab, 0x8e, 0xf4, 0xd4, 0x58, 0x75, 0x14, 0xf0, 0xfb }, { 0x99, 0x24, 0xa7, 0xc8, 0x58, 0x73, 0x36, 0xbf, 0xb1, 0x18, 0x02, 0x4d, 0xb8, 0x67, 0x4a, 0x14 }, { 0x25, 0x19, 0x49, 0x8e, 0x80, 0xf1, 0x47, 0x8f, 0x37, 0xba, 0x55, 0xbd, 0x6d, 0x27, 0x61, 0x8c }, { 0x65, 0xdc, 0xc5, 0x7f, 0xcf, 0x62, 0x3a, 0x24, 0x09, 0x4f, 0xcc, 0xa4, 0x0d, 0x35, 0x33, 0xf8 }, { 0xdc, 0xf5, 0x66, 0xff, 0x29, 0x1c, 0x25, 0xbb, 0xb8, 0x56, 0x8f, 0xc3, 0xd3, 0x76, 0xa6, 0xd9 }, { 0x53, 0x0f, 0x8a, 0xfb, 0xc7, 0x45, 0x36, 0xb9, 0xa9, 0x63, 0xb4, 0xf1, 0xc4, 0xcb, 0x73, 0x8b }, { 0xd0, 0xd1, 0xc8, 0xa7, 0x99, 0x99, 0x6b, 0xf0, 0x26, 0x5b, 0x98, 0xb5, 0xd4, 0x8a, 0xb9, 0x19 }, { 0xb0, 0x94, 0xda, 0xc5, 0xd9, 0x34, 0x71, 0xbd, 0xec, 0x1a, 0x50, 0x22, 0x70, 0xe3, 0xcc, 0x6c }, { 0x76, 0xfc, 0x6e, 0xce, 0x0f, 0x4e, 0x17, 0x68, 0xcd, 0xdf, 0x88, 0x53, 0xbb, 0x2d, 0x55, 0x1b }, { 0x3a, 0x33, 0x7d, 0xbf, 0x46, 0xa7, 0x92, 0xc4, 0x5e, 0x45, 0x49, 0x13, 0xfe, 0x2e, 0xa8, 0xf2 }, { 0xa4, 0x4a, 0x82, 0x66, 0xee, 0x1c, 0x8e, 0xb0, 0xc8, 0xb5, 0xd4, 0xcf, 0x5a, 0xe9, 0xf1, 0x9a }, }; /** * \brief The GCM checkup routine. * * \return \c 0 on success. * \return \c 1 on failure. */ int mbedtls_gcm_self_test( int verbose ) { mbedtls_gcm_context ctx; unsigned char buf[64]; unsigned char tag_buf[16]; int i, j, ret; mbedtls_cipher_id_t cipher = MBEDTLS_CIPHER_ID_AES; for( j = 0; j < 3; j++ ) { int key_len = 128 + 64 * j; for( i = 0; i < MAX_TESTS; i++ ) { mbedtls_gcm_init( &ctx ); if( verbose != 0 ) mbedtls_printf( " AES-GCM-%3d #%d (%s): ", key_len, i, "enc" ); ret = mbedtls_gcm_setkey( &ctx, cipher, key_test_data[key_index_test_data[i]], key_len ); if( ret != 0 ) { goto exit; } ret = mbedtls_gcm_crypt_and_tag( &ctx, MBEDTLS_GCM_ENCRYPT, pt_len_test_data[i], iv_test_data[iv_index_test_data[i]], iv_len_test_data[i], additional_test_data[add_index_test_data[i]], add_len_test_data[i], pt_test_data[pt_index_test_data[i]], buf, 16, tag_buf ); if( ret != 0 ) goto exit; if ( timingsafe_bcmp( buf, ct_test_data[j * 6 + i], pt_len_test_data[i] ) != 0 || timingsafe_bcmp( tag_buf, tag_test_data[j * 6 + i], 16 ) != 0 ) { ret = 1; goto exit; } mbedtls_gcm_free( &ctx ); if( verbose != 0 ) mbedtls_printf( "passed\n" ); mbedtls_gcm_init( &ctx ); if( verbose != 0 ) mbedtls_printf( " AES-GCM-%3d #%d (%s): ", key_len, i, "dec" ); ret = mbedtls_gcm_setkey( &ctx, cipher, key_test_data[key_index_test_data[i]], key_len ); if( ret != 0 ) goto exit; ret = mbedtls_gcm_crypt_and_tag( &ctx, MBEDTLS_GCM_DECRYPT, pt_len_test_data[i], iv_test_data[iv_index_test_data[i]], iv_len_test_data[i], additional_test_data[add_index_test_data[i]], add_len_test_data[i], ct_test_data[j * 6 + i], buf, 16, tag_buf ); if( ret != 0 ) goto exit; if( timingsafe_bcmp( buf, pt_test_data[pt_index_test_data[i]], pt_len_test_data[i] ) != 0 || timingsafe_bcmp( tag_buf, tag_test_data[j * 6 + i], 16 ) != 0 ) { ret = 1; goto exit; } mbedtls_gcm_free( &ctx ); if( verbose != 0 ) mbedtls_printf( "passed\n" ); mbedtls_gcm_init( &ctx ); if( verbose != 0 ) mbedtls_printf( " AES-GCM-%3d #%d split (%s): ", key_len, i, "enc" ); ret = mbedtls_gcm_setkey( &ctx, cipher, key_test_data[key_index_test_data[i]], key_len ); if( ret != 0 ) goto exit; ret = mbedtls_gcm_starts( &ctx, MBEDTLS_GCM_ENCRYPT, iv_test_data[iv_index_test_data[i]], iv_len_test_data[i], additional_test_data[add_index_test_data[i]], add_len_test_data[i] ); if( ret != 0 ) goto exit; if( pt_len_test_data[i] > 32 ) { size_t rest_len = pt_len_test_data[i] - 32; ret = mbedtls_gcm_update( &ctx, 32, pt_test_data[pt_index_test_data[i]], buf ); if( ret != 0 ) goto exit; ret = mbedtls_gcm_update( &ctx, rest_len, pt_test_data[pt_index_test_data[i]] + 32, buf + 32 ); if( ret != 0 ) goto exit; } else { ret = mbedtls_gcm_update( &ctx, pt_len_test_data[i], pt_test_data[pt_index_test_data[i]], buf ); if( ret != 0 ) goto exit; } ret = mbedtls_gcm_finish( &ctx, tag_buf, 16 ); if( ret != 0 ) goto exit; if( timingsafe_bcmp( buf, ct_test_data[j * 6 + i], pt_len_test_data[i] ) != 0 || timingsafe_bcmp( tag_buf, tag_test_data[j * 6 + i], 16 ) != 0 ) { ret = 1; goto exit; } mbedtls_gcm_free( &ctx ); if( verbose != 0 ) mbedtls_printf( "passed\n" ); mbedtls_gcm_init( &ctx ); if( verbose != 0 ) mbedtls_printf( " AES-GCM-%3d #%d split (%s): ", key_len, i, "dec" ); ret = mbedtls_gcm_setkey( &ctx, cipher, key_test_data[key_index_test_data[i]], key_len ); if( ret != 0 ) goto exit; ret = mbedtls_gcm_starts( &ctx, MBEDTLS_GCM_DECRYPT, iv_test_data[iv_index_test_data[i]], iv_len_test_data[i], additional_test_data[add_index_test_data[i]], add_len_test_data[i] ); if( ret != 0 ) goto exit; if( pt_len_test_data[i] > 32 ) { size_t rest_len = pt_len_test_data[i] - 32; ret = mbedtls_gcm_update( &ctx, 32, ct_test_data[j * 6 + i], buf ); if( ret != 0 ) goto exit; ret = mbedtls_gcm_update( &ctx, rest_len, ct_test_data[j * 6 + i] + 32, buf + 32 ); if( ret != 0 ) goto exit; } else { ret = mbedtls_gcm_update( &ctx, pt_len_test_data[i], ct_test_data[j * 6 + i], buf ); if( ret != 0 ) goto exit; } ret = mbedtls_gcm_finish( &ctx, tag_buf, 16 ); if( ret != 0 ) goto exit; if( timingsafe_bcmp( buf, pt_test_data[pt_index_test_data[i]], pt_len_test_data[i] ) != 0 || timingsafe_bcmp( tag_buf, tag_test_data[j * 6 + i], 16 ) != 0 ) { ret = 1; goto exit; } mbedtls_gcm_free( &ctx ); if( verbose != 0 ) mbedtls_printf( "passed\n" ); } } if( verbose != 0 ) mbedtls_printf( "\n" ); ret = 0; exit: if( ret != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); mbedtls_gcm_free( &ctx ); } return( ret ); } #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
44,587
1,116
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/sha256t.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/sha256.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off /* * FIPS-180-2 test vectors */ static const unsigned char sha256_test_buf[3][57] = { { "abc" }, { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" }, { "" } }; static const size_t sha256_test_buflen[3] = { 3, 56, 1000 }; static const unsigned char sha256_test_sum[6][32] = { /* * SHA-224 test vectors */ { 0x23, 0x09, 0x7D, 0x22, 0x34, 0x05, 0xD8, 0x22, 0x86, 0x42, 0xA4, 0x77, 0xBD, 0xA2, 0x55, 0xB3, 0x2A, 0xAD, 0xBC, 0xE4, 0xBD, 0xA0, 0xB3, 0xF7, 0xE3, 0x6C, 0x9D, 0xA7 }, { 0x75, 0x38, 0x8B, 0x16, 0x51, 0x27, 0x76, 0xCC, 0x5D, 0xBA, 0x5D, 0xA1, 0xFD, 0x89, 0x01, 0x50, 0xB0, 0xC6, 0x45, 0x5C, 0xB4, 0xF5, 0x8B, 0x19, 0x52, 0x52, 0x25, 0x25 }, { 0x20, 0x79, 0x46, 0x55, 0x98, 0x0C, 0x91, 0xD8, 0xBB, 0xB4, 0xC1, 0xEA, 0x97, 0x61, 0x8A, 0x4B, 0xF0, 0x3F, 0x42, 0x58, 0x19, 0x48, 0xB2, 0xEE, 0x4E, 0xE7, 0xAD, 0x67 }, /* * SHA-256 test vectors */ { 0xBA, 0x78, 0x16, 0xBF, 0x8F, 0x01, 0xCF, 0xEA, 0x41, 0x41, 0x40, 0xDE, 0x5D, 0xAE, 0x22, 0x23, 0xB0, 0x03, 0x61, 0xA3, 0x96, 0x17, 0x7A, 0x9C, 0xB4, 0x10, 0xFF, 0x61, 0xF2, 0x00, 0x15, 0xAD }, { 0x24, 0x8D, 0x6A, 0x61, 0xD2, 0x06, 0x38, 0xB8, 0xE5, 0xC0, 0x26, 0x93, 0x0C, 0x3E, 0x60, 0x39, 0xA3, 0x3C, 0xE4, 0x59, 0x64, 0xFF, 0x21, 0x67, 0xF6, 0xEC, 0xED, 0xD4, 0x19, 0xDB, 0x06, 0xC1 }, { 0xCD, 0xC7, 0x6E, 0x5C, 0x99, 0x14, 0xFB, 0x92, 0x81, 0xA1, 0xC7, 0xE2, 0x84, 0xD7, 0x3E, 0x67, 0xF1, 0x80, 0x9A, 0x48, 0xA4, 0x97, 0x20, 0x0E, 0x04, 0x6D, 0x39, 0xCC, 0xC7, 0x11, 0x2C, 0xD0 } }; /** * \brief The SHA-224 and SHA-256 checkup routine. * * \return \c 0 on success. * \return \c 1 on failure. */ int mbedtls_sha256_self_test( int verbose ) { int i, j, k, buflen, ret = 0; unsigned char *buf; unsigned char sha256sum[32]; mbedtls_sha256_context ctx; buf = mbedtls_calloc( 1024, sizeof(unsigned char) ); if( NULL == buf ) { if( verbose != 0 ) mbedtls_printf( "Buffer allocation failed\n" ); return( 1 ); } mbedtls_sha256_init( &ctx ); for( i = 0; i < 6; i++ ) { j = i % 3; k = i < 3; if( verbose != 0 ) mbedtls_printf( " SHA-%d test #%d: ", 256 - k * 32, j + 1 ); if( ( ret = mbedtls_sha256_starts_ret( &ctx, k ) ) != 0 ) goto fail; if( j == 2 ) { memset( buf, 'a', buflen = 1000 ); for( j = 0; j < 1000; j++ ) { ret = mbedtls_sha256_update_ret( &ctx, buf, buflen ); if( ret != 0 ) goto fail; } } else { ret = mbedtls_sha256_update_ret( &ctx, sha256_test_buf[j], sha256_test_buflen[j] ); if( ret != 0 ) goto fail; } if( ( ret = mbedtls_sha256_finish_ret( &ctx, sha256sum ) ) != 0 ) goto fail; if( timingsafe_bcmp( sha256sum, sha256_test_sum[i], 32 - k * 4 ) != 0 ) { ret = 1; goto fail; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); } if( verbose != 0 ) mbedtls_printf( "\n" ); goto exit; fail: if( verbose != 0 ) mbedtls_printf( "failed\n" ); exit: mbedtls_sha256_free( &ctx ); mbedtls_free( buf ); return( ret ); }
5,528
145
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/pem.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/str/str.h" #include "third_party/mbedtls/aes.h" #include "third_party/mbedtls/base64.h" #include "third_party/mbedtls/chk.h" #include "third_party/mbedtls/cipher.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/des.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/md5.h" #include "third_party/mbedtls/pem.h" #include "third_party/mbedtls/platform.h" /* clang-format off */ asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /** * @fileoverview Privacy Enhanced Mail (PEM) decoding */ #if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C) #if defined(MBEDTLS_PEM_PARSE_C) void mbedtls_pem_init( mbedtls_pem_context *ctx ) { mbedtls_platform_zeroize( ctx, sizeof( mbedtls_pem_context ) ); } #if defined(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) && \ ( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) ) /* * Read a 16-byte hex string and convert it to binary */ static int pem_get_iv( const unsigned char *s, unsigned char *iv, size_t iv_len ) { size_t i, j, k; mbedtls_platform_zeroize( iv, iv_len ); for( i = 0; i < iv_len * 2; i++, s++ ) { if( *s >= '0' && *s <= '9' ) j = *s - '0'; else if( *s >= 'A' && *s <= 'F' ) j = *s - '7'; else if( *s >= 'a' && *s <= 'f' ) j = *s - 'W'; else return( MBEDTLS_ERR_PEM_INVALID_ENC_IV ); k = ( ( i & 1 ) != 0 ) ? j : j << 4; iv[i >> 1] = (unsigned char)( iv[i >> 1] | k ); } return( 0 ); } static int pem_pbkdf1( unsigned char *key, size_t keylen, unsigned char *iv, const unsigned char *pwd, size_t pwdlen ) { mbedtls_md5_context md5_ctx; unsigned char md5sum[16]; size_t use_len; int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_md5_init( &md5_ctx ); /* * key[ 0..15] = MD5(pwd || IV) */ MBEDTLS_CHK( mbedtls_md5_starts_ret( &md5_ctx ) ); MBEDTLS_CHK( mbedtls_md5_update_ret( &md5_ctx, pwd, pwdlen ) ); MBEDTLS_CHK( mbedtls_md5_update_ret( &md5_ctx, iv, 8 ) ); MBEDTLS_CHK( mbedtls_md5_finish_ret( &md5_ctx, md5sum ) ); if( keylen <= 16 ) { memcpy( key, md5sum, keylen ); goto cleanup; } memcpy( key, md5sum, 16 ); /* * key[16..23] = MD5(key[ 0..15] || pwd || IV]) */ MBEDTLS_CHK( mbedtls_md5_starts_ret( &md5_ctx ) ); MBEDTLS_CHK( mbedtls_md5_update_ret( &md5_ctx, md5sum, 16 ) ); MBEDTLS_CHK( mbedtls_md5_update_ret( &md5_ctx, pwd, pwdlen ) ); MBEDTLS_CHK( mbedtls_md5_update_ret( &md5_ctx, iv, 8 ) ); MBEDTLS_CHK( mbedtls_md5_finish_ret( &md5_ctx, md5sum ) ); use_len = 16; if( keylen < 32 ) use_len = keylen - 16; memcpy( key + 16, md5sum, use_len ); cleanup: mbedtls_md5_free( &md5_ctx ); mbedtls_platform_zeroize( md5sum, 16 ); return( ret ); } #if defined(MBEDTLS_DES_C) /* * Decrypt with DES-CBC, using PBKDF1 for key derivation */ static int pem_des_decrypt( unsigned char des_iv[8], unsigned char *buf, size_t buflen, const unsigned char *pwd, size_t pwdlen ) { mbedtls_des_context des_ctx; unsigned char des_key[8]; int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_des_init( &des_ctx ); if( ( ret = pem_pbkdf1( des_key, 8, des_iv, pwd, pwdlen ) ) != 0 ) goto exit; if( ( ret = mbedtls_des_setkey_dec( &des_ctx, des_key ) ) != 0 ) goto exit; ret = mbedtls_des_crypt_cbc( &des_ctx, MBEDTLS_DES_DECRYPT, buflen, des_iv, buf, buf ); exit: mbedtls_des_free( &des_ctx ); mbedtls_platform_zeroize( des_key, 8 ); return( ret ); } /* * Decrypt with 3DES-CBC, using PBKDF1 for key derivation */ static int pem_des3_decrypt( unsigned char des3_iv[8], unsigned char *buf, size_t buflen, const unsigned char *pwd, size_t pwdlen ) { mbedtls_des3_context des3_ctx; unsigned char des3_key[24]; int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_des3_init( &des3_ctx ); if( ( ret = pem_pbkdf1( des3_key, 24, des3_iv, pwd, pwdlen ) ) != 0 ) goto exit; if( ( ret = mbedtls_des3_set3key_dec( &des3_ctx, des3_key ) ) != 0 ) goto exit; ret = mbedtls_des3_crypt_cbc( &des3_ctx, MBEDTLS_DES_DECRYPT, buflen, des3_iv, buf, buf ); exit: mbedtls_des3_free( &des3_ctx ); mbedtls_platform_zeroize( des3_key, 24 ); return( ret ); } #endif /* MBEDTLS_DES_C */ #if defined(MBEDTLS_AES_C) /* * Decrypt with AES-XXX-CBC, using PBKDF1 for key derivation */ static int pem_aes_decrypt( unsigned char aes_iv[16], unsigned int keylen, unsigned char *buf, size_t buflen, const unsigned char *pwd, size_t pwdlen ) { mbedtls_aes_context aes_ctx; unsigned char aes_key[32]; int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_aes_init( &aes_ctx ); if( ( ret = pem_pbkdf1( aes_key, keylen, aes_iv, pwd, pwdlen ) ) != 0 ) goto exit; if( ( ret = mbedtls_aes_setkey_dec( &aes_ctx, aes_key, keylen * 8 ) ) != 0 ) goto exit; ret = mbedtls_aes_crypt_cbc( &aes_ctx, MBEDTLS_AES_DECRYPT, buflen, aes_iv, buf, buf ); exit: mbedtls_aes_free( &aes_ctx ); mbedtls_platform_zeroize( aes_key, keylen ); return( ret ); } #endif /* MBEDTLS_AES_C */ #endif /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC && ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */ int mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const char *footer, const unsigned char *data, const unsigned char *pwd, size_t pwdlen, size_t *use_len ) { int ret, enc; size_t len; unsigned char *buf; const unsigned char *s1, *s2, *end; #if defined(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) && \ ( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) ) unsigned char pem_iv[16]; mbedtls_cipher_type_t enc_alg = MBEDTLS_CIPHER_NONE; #else ((void) pwd); ((void) pwdlen); #endif /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC && ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */ if( !ctx ) return( MBEDTLS_ERR_PEM_BAD_INPUT_DATA ); s1 = (unsigned char *) strstr( (const char *) data, header ); if( !s1 ) return( MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT ); s2 = (unsigned char *) strstr( (const char *) data, footer ); if( !s2 || s2 <= s1 ) return( MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT ); s1 += strlen( header ); if( *s1 == ' ' ) s1++; if( *s1 == '\r' ) s1++; if( *s1 == '\n' ) s1++; else return( MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT ); end = s2; end += strlen( footer ); if( *end == ' ' ) end++; if( *end == '\r' ) end++; if( *end == '\n' ) end++; *use_len = end - data; enc = 0; if( s2 - s1 >= 22 && timingsafe_bcmp( s1, "Proc-Type: 4,ENCRYPTED", 22 ) == 0 ) { #if defined(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) && \ ( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) ) enc++; s1 += 22; if( *s1 == '\r' ) s1++; if( *s1 == '\n' ) s1++; else return( MBEDTLS_ERR_PEM_INVALID_DATA ); #if defined(MBEDTLS_DES_C) if( s2 - s1 >= 23 && timingsafe_bcmp( s1, "DEK-Info: DES-EDE3-CBC,", 23 ) == 0 ) { enc_alg = MBEDTLS_CIPHER_DES_EDE3_CBC; s1 += 23; if( s2 - s1 < 16 || pem_get_iv( s1, pem_iv, 8 ) != 0 ) return( MBEDTLS_ERR_PEM_INVALID_ENC_IV ); s1 += 16; } else if( s2 - s1 >= 18 && timingsafe_bcmp( s1, "DEK-Info: DES-CBC,", 18 ) == 0 ) { enc_alg = MBEDTLS_CIPHER_DES_CBC; s1 += 18; if( s2 - s1 < 16 || pem_get_iv( s1, pem_iv, 8) != 0 ) return( MBEDTLS_ERR_PEM_INVALID_ENC_IV ); s1 += 16; } #endif /* MBEDTLS_DES_C */ #if defined(MBEDTLS_AES_C) if( s2 - s1 >= 14 && timingsafe_bcmp( s1, "DEK-Info: AES-", 14 ) == 0 ) { if( s2 - s1 < 22 ) return( MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG ); else if( timingsafe_bcmp( s1, "DEK-Info: AES-128-CBC,", 22 ) == 0 ) enc_alg = MBEDTLS_CIPHER_AES_128_CBC; else if( timingsafe_bcmp( s1, "DEK-Info: AES-192-CBC,", 22 ) == 0 ) enc_alg = MBEDTLS_CIPHER_AES_192_CBC; else if( timingsafe_bcmp( s1, "DEK-Info: AES-256-CBC,", 22 ) == 0 ) enc_alg = MBEDTLS_CIPHER_AES_256_CBC; else return( MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG ); s1 += 22; if( s2 - s1 < 32 || pem_get_iv( s1, pem_iv, 16 ) != 0 ) return( MBEDTLS_ERR_PEM_INVALID_ENC_IV ); s1 += 32; } #endif /* MBEDTLS_AES_C */ if( enc_alg == MBEDTLS_CIPHER_NONE ) return( MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG ); if( *s1 == '\r' ) s1++; if( *s1 == '\n' ) s1++; else return( MBEDTLS_ERR_PEM_INVALID_DATA ); #else return( MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE ); #endif /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC && ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */ } if( s1 >= s2 ) return( MBEDTLS_ERR_PEM_INVALID_DATA ); ret = mbedtls_base64_decode( NULL, 0, &len, s1, s2 - s1 ); if( ret == MBEDTLS_ERR_BASE64_INVALID_CHARACTER ) return( MBEDTLS_ERR_PEM_INVALID_DATA + ret ); if( ( buf = mbedtls_calloc( 1, len ) ) == NULL ) return( MBEDTLS_ERR_PEM_ALLOC_FAILED ); if( ( ret = mbedtls_base64_decode( buf, len, &len, s1, s2 - s1 ) ) != 0 ) { mbedtls_platform_zeroize( buf, len ); mbedtls_free( buf ); return( MBEDTLS_ERR_PEM_INVALID_DATA + ret ); } if( enc != 0 ) { #if defined(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) && \ ( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) ) if( pwd == NULL ) { mbedtls_platform_zeroize( buf, len ); mbedtls_free( buf ); return( MBEDTLS_ERR_PEM_PASSWORD_REQUIRED ); } ret = 0; #if defined(MBEDTLS_DES_C) if( enc_alg == MBEDTLS_CIPHER_DES_EDE3_CBC ) ret = pem_des3_decrypt( pem_iv, buf, len, pwd, pwdlen ); else if( enc_alg == MBEDTLS_CIPHER_DES_CBC ) ret = pem_des_decrypt( pem_iv, buf, len, pwd, pwdlen ); #endif /* MBEDTLS_DES_C */ #if defined(MBEDTLS_AES_C) if( enc_alg == MBEDTLS_CIPHER_AES_128_CBC ) ret = pem_aes_decrypt( pem_iv, 16, buf, len, pwd, pwdlen ); else if( enc_alg == MBEDTLS_CIPHER_AES_192_CBC ) ret = pem_aes_decrypt( pem_iv, 24, buf, len, pwd, pwdlen ); else if( enc_alg == MBEDTLS_CIPHER_AES_256_CBC ) ret = pem_aes_decrypt( pem_iv, 32, buf, len, pwd, pwdlen ); #endif /* MBEDTLS_AES_C */ if( ret != 0 ) { mbedtls_free( buf ); return( ret ); } /* * The result will be ASN.1 starting with a SEQUENCE tag, with 1 to 3 * length bytes (allow 4 to be sure) in all known use cases. * * Use that as a heuristic to try to detect password mismatches. */ if( len <= 2 || buf[0] != 0x30 || buf[1] > 0x83 ) { mbedtls_platform_zeroize( buf, len ); mbedtls_free( buf ); return( MBEDTLS_ERR_PEM_PASSWORD_MISMATCH ); } #else mbedtls_platform_zeroize( buf, len ); mbedtls_free( buf ); return( MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE ); #endif /* MBEDTLS_MD5_C && MBEDTLS_CIPHER_MODE_CBC && ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */ } ctx->buf = buf; ctx->buflen = len; return( 0 ); } void mbedtls_pem_free( mbedtls_pem_context *ctx ) { if ( ctx->buf ) { mbedtls_platform_zeroize( ctx->buf, ctx->buflen ); mbedtls_free( ctx->buf ); } mbedtls_free( ctx->info ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_pem_context ) ); } #endif /* MBEDTLS_PEM_PARSE_C */ #if defined(MBEDTLS_PEM_WRITE_C) int mbedtls_pem_write_buffer( const char *header, const char *footer, const unsigned char *der_data, size_t der_len, unsigned char *buf, size_t buf_len, size_t *olen ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char *encode_buf = NULL, *c, *p = buf; size_t len = 0, use_len, add_len = 0; mbedtls_base64_encode( NULL, 0, &use_len, der_data, der_len ); add_len = strlen( header ) + strlen( footer ) + ( use_len / 64 ) + 1; if( use_len + add_len > buf_len ) { *olen = use_len + add_len; return( MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL ); } if( use_len != 0 && ( ( encode_buf = mbedtls_calloc( 1, use_len ) ) == NULL ) ) return( MBEDTLS_ERR_PEM_ALLOC_FAILED ); if( ( ret = mbedtls_base64_encode( encode_buf, use_len, &use_len, der_data, der_len ) ) != 0 ) { mbedtls_free( encode_buf ); return( ret ); } memcpy( p, header, strlen( header ) ); p += strlen( header ); c = encode_buf; while( use_len ) { len = ( use_len > 64 ) ? 64 : use_len; memcpy( p, c, len ); use_len -= len; p += len; c += len; *p++ = '\n'; } memcpy( p, footer, strlen( footer ) ); p += strlen( footer ); *p++ = '\0'; *olen = p - buf; /* Clean any remaining data previously written to the buffer */ mbedtls_platform_zeroize( buf + *olen, buf_len - *olen ); mbedtls_free( encode_buf ); return( 0 ); } #endif /* MBEDTLS_PEM_WRITE_C */ #endif /* MBEDTLS_PEM_PARSE_C || MBEDTLS_PEM_WRITE_C */
15,700
410
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/entropy_poll.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/nexgen32e/rdtsc.h" #include "libc/str/str.h" #include "third_party/mbedtls/entropy_poll.h" int mbedtls_hardclock_poll(void *data, unsigned char *output, size_t len, size_t *olen) { unsigned long timer; timer = rdtsc(); *olen = 0; if (len < sizeof(unsigned long)) return 0; memcpy(output, &timer, sizeof(unsigned long)); *olen = sizeof(unsigned long); return 0; }
2,171
32
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/pk_wrap.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "third_party/mbedtls/asn1.h" #include "third_party/mbedtls/asn1write.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/ecdsa.h" #include "third_party/mbedtls/ecp.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/pk_internal.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/rsa.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /** * @fileoverview Public Key abstraction layer: wrapper functions */ #if defined(MBEDTLS_PK_C) #if defined(MBEDTLS_RSA_C) static int rsa_can_do( mbedtls_pk_type_t type ) { return( type == MBEDTLS_PK_RSA || type == MBEDTLS_PK_RSASSA_PSS ); } static size_t rsa_get_bitlen( const void *ctx ) { const mbedtls_rsa_context * rsa = (const mbedtls_rsa_context *) ctx; return( 8 * mbedtls_rsa_get_len( rsa ) ); } static int rsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, const unsigned char *sig, size_t sig_len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx; size_t rsa_len = mbedtls_rsa_get_len( rsa ); #if SIZE_MAX > UINT_MAX if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); #endif /* SIZE_MAX > UINT_MAX */ if( sig_len < rsa_len ) return( MBEDTLS_ERR_RSA_VERIFY_FAILED ); if( ( ret = mbedtls_rsa_pkcs1_verify( rsa, NULL, NULL, MBEDTLS_RSA_PUBLIC, md_alg, (unsigned int) hash_len, hash, sig ) ) != 0 ) return( ret ); /* The buffer contains a valid signature followed by extra data. * We have a special error code for that so that so that callers can * use mbedtls_pk_verify() to check "Does the buffer start with a * valid signature?" and not just "Does the buffer contain a valid * signature?". */ if( sig_len > rsa_len ) return( MBEDTLS_ERR_PK_SIG_LEN_MISMATCH ); return( 0 ); } static int rsa_sign_wrap( void *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, unsigned char *sig, size_t *sig_len, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx; #if SIZE_MAX > UINT_MAX if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); #endif /* SIZE_MAX > UINT_MAX */ *sig_len = mbedtls_rsa_get_len( rsa ); return( mbedtls_rsa_pkcs1_sign( rsa, f_rng, p_rng, MBEDTLS_RSA_PRIVATE, md_alg, (unsigned int) hash_len, hash, sig ) ); } static int rsa_decrypt_wrap( void *ctx, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen, size_t osize, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx; if( ilen != mbedtls_rsa_get_len( rsa ) ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); return( mbedtls_rsa_pkcs1_decrypt( rsa, f_rng, p_rng, MBEDTLS_RSA_PRIVATE, olen, input, output, osize ) ); } static int rsa_encrypt_wrap( void *ctx, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen, size_t osize, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx; *olen = mbedtls_rsa_get_len( rsa ); if( *olen > osize ) return( MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE ); return( mbedtls_rsa_pkcs1_encrypt( rsa, f_rng, p_rng, MBEDTLS_RSA_PUBLIC, ilen, input, output ) ); } static int rsa_check_pair_wrap( const void *pub, const void *prv ) { return( mbedtls_rsa_check_pub_priv( (const mbedtls_rsa_context *) pub, (const mbedtls_rsa_context *) prv ) ); } static void *rsa_alloc_wrap( void ) { void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_rsa_context ) ); if( ctx != NULL ) mbedtls_rsa_init( (mbedtls_rsa_context *) ctx, 0, 0 ); return( ctx ); } static void rsa_free_wrap( void *ctx ) { mbedtls_rsa_free( (mbedtls_rsa_context *) ctx ); mbedtls_free( ctx ); } static void rsa_debug( const void *ctx, mbedtls_pk_debug_item *items ) { items->type = MBEDTLS_PK_DEBUG_MPI; items->name = "rsa.N"; items->value = &( ((mbedtls_rsa_context *) ctx)->N ); items++; items->type = MBEDTLS_PK_DEBUG_MPI; items->name = "rsa.E"; items->value = &( ((mbedtls_rsa_context *) ctx)->E ); } const mbedtls_pk_info_t mbedtls_rsa_info = { MBEDTLS_PK_RSA, "RSA", rsa_get_bitlen, rsa_can_do, rsa_verify_wrap, rsa_sign_wrap, #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) NULL, NULL, #endif rsa_decrypt_wrap, rsa_encrypt_wrap, rsa_check_pair_wrap, rsa_alloc_wrap, rsa_free_wrap, #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) NULL, NULL, #endif rsa_debug, }; #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_ECP_C) /* * Generic EC key */ static int eckey_can_do( mbedtls_pk_type_t type ) { return( type == MBEDTLS_PK_ECKEY || type == MBEDTLS_PK_ECKEY_DH || type == MBEDTLS_PK_ECDSA ); } static size_t eckey_get_bitlen( const void *ctx ) { return( ((mbedtls_ecp_keypair *) ctx)->grp.pbits ); } #if defined(MBEDTLS_ECDSA_C) /* Forward declarations */ static int ecdsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, const unsigned char *sig, size_t sig_len ); static int ecdsa_sign_wrap( void *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, unsigned char *sig, size_t *sig_len, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); static int eckey_verify_wrap( void *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, const unsigned char *sig, size_t sig_len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_ecdsa_context ecdsa; mbedtls_ecdsa_init( &ecdsa ); if( ( ret = mbedtls_ecdsa_from_keypair( &ecdsa, ctx ) ) == 0 ) ret = ecdsa_verify_wrap( &ecdsa, md_alg, hash, hash_len, sig, sig_len ); mbedtls_ecdsa_free( &ecdsa ); return( ret ); } static int eckey_sign_wrap( void *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, unsigned char *sig, size_t *sig_len, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_ecdsa_context ecdsa; mbedtls_ecdsa_init( &ecdsa ); if( ( ret = mbedtls_ecdsa_from_keypair( &ecdsa, ctx ) ) == 0 ) ret = ecdsa_sign_wrap( &ecdsa, md_alg, hash, hash_len, sig, sig_len, f_rng, p_rng ); mbedtls_ecdsa_free( &ecdsa ); return( ret ); } #if defined(MBEDTLS_ECP_RESTARTABLE) /* Forward declarations */ static int ecdsa_verify_rs_wrap( void *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, const unsigned char *sig, size_t sig_len, void *rs_ctx ); static int ecdsa_sign_rs_wrap( void *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, unsigned char *sig, size_t *sig_len, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, void *rs_ctx ); /* * Restart context for ECDSA operations with ECKEY context * * We need to store an actual ECDSA context, as we need to pass the same to * the underlying ecdsa function, so we can't create it on the fly every time. */ typedef struct { mbedtls_ecdsa_restart_ctx ecdsa_rs; mbedtls_ecdsa_context ecdsa_ctx; } eckey_restart_ctx; static void *eckey_rs_alloc( void ) { eckey_restart_ctx *rs_ctx; void *ctx = mbedtls_calloc( 1, sizeof( eckey_restart_ctx ) ); if( ctx != NULL ) { rs_ctx = ctx; mbedtls_ecdsa_restart_init( &rs_ctx->ecdsa_rs ); mbedtls_ecdsa_init( &rs_ctx->ecdsa_ctx ); } return( ctx ); } static void eckey_rs_free( void *ctx ) { eckey_restart_ctx *rs_ctx; if( ctx == NULL) return; rs_ctx = ctx; mbedtls_ecdsa_restart_free( &rs_ctx->ecdsa_rs ); mbedtls_ecdsa_free( &rs_ctx->ecdsa_ctx ); mbedtls_free( ctx ); } static int eckey_verify_rs_wrap( void *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, const unsigned char *sig, size_t sig_len, void *rs_ctx ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; eckey_restart_ctx *rs = rs_ctx; /* Should never happen */ if( rs == NULL ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); /* set up our own sub-context if needed (that is, on first run) */ if( rs->ecdsa_ctx.grp.pbits == 0 ) MBEDTLS_MPI_CHK( mbedtls_ecdsa_from_keypair( &rs->ecdsa_ctx, ctx ) ); MBEDTLS_MPI_CHK( ecdsa_verify_rs_wrap( &rs->ecdsa_ctx, md_alg, hash, hash_len, sig, sig_len, &rs->ecdsa_rs ) ); cleanup: return( ret ); } static int eckey_sign_rs_wrap( void *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, unsigned char *sig, size_t *sig_len, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, void *rs_ctx ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; eckey_restart_ctx *rs = rs_ctx; /* Should never happen */ if( !rs ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); /* set up our own sub-context if needed (that is, on first run) */ if( rs->ecdsa_ctx.grp.pbits == 0 ) MBEDTLS_MPI_CHK( mbedtls_ecdsa_from_keypair( &rs->ecdsa_ctx, ctx ) ); MBEDTLS_MPI_CHK( ecdsa_sign_rs_wrap( &rs->ecdsa_ctx, md_alg, hash, hash_len, sig, sig_len, f_rng, p_rng, &rs->ecdsa_rs ) ); cleanup: return( ret ); } #endif /* MBEDTLS_ECP_RESTARTABLE */ #endif /* MBEDTLS_ECDSA_C */ static int eckey_check_pair( const void *pub, const void *prv ) { return( mbedtls_ecp_check_pub_priv( (const mbedtls_ecp_keypair *) pub, (const mbedtls_ecp_keypair *) prv ) ); } static void *eckey_alloc_wrap( void ) { void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_ecp_keypair ) ); if( ctx != NULL ) mbedtls_ecp_keypair_init( ctx ); return( ctx ); } static void eckey_free_wrap( void *ctx ) { mbedtls_ecp_keypair_free( (mbedtls_ecp_keypair *) ctx ); mbedtls_free( ctx ); } static void eckey_debug( const void *ctx, mbedtls_pk_debug_item *items ) { items->type = MBEDTLS_PK_DEBUG_ECP; items->name = "eckey.Q"; items->value = &( ((mbedtls_ecp_keypair *) ctx)->Q ); } const mbedtls_pk_info_t mbedtls_eckey_info = { MBEDTLS_PK_ECKEY, "EC", eckey_get_bitlen, eckey_can_do, #if defined(MBEDTLS_ECDSA_C) eckey_verify_wrap, eckey_sign_wrap, #if defined(MBEDTLS_ECP_RESTARTABLE) eckey_verify_rs_wrap, eckey_sign_rs_wrap, #endif #else /* MBEDTLS_ECDSA_C */ NULL, NULL, #endif /* MBEDTLS_ECDSA_C */ NULL, NULL, eckey_check_pair, eckey_alloc_wrap, eckey_free_wrap, #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) eckey_rs_alloc, eckey_rs_free, #endif eckey_debug, }; /* * EC key restricted to ECDH */ static int eckeydh_can_do( mbedtls_pk_type_t type ) { return( type == MBEDTLS_PK_ECKEY || type == MBEDTLS_PK_ECKEY_DH ); } const mbedtls_pk_info_t mbedtls_eckeydh_info = { MBEDTLS_PK_ECKEY_DH, "EC_DH", eckey_get_bitlen, /* Same underlying key structure */ eckeydh_can_do, NULL, NULL, #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) NULL, NULL, #endif NULL, NULL, eckey_check_pair, eckey_alloc_wrap, /* Same underlying key structure */ eckey_free_wrap, /* Same underlying key structure */ #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) NULL, NULL, #endif eckey_debug, /* Same underlying key structure */ }; #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_ECDSA_C) static int ecdsa_can_do( mbedtls_pk_type_t type ) { return( type == MBEDTLS_PK_ECDSA ); } static int ecdsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, const unsigned char *sig, size_t sig_len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; ((void) md_alg); ret = mbedtls_ecdsa_read_signature( (mbedtls_ecdsa_context *) ctx, hash, hash_len, sig, sig_len ); if( ret == MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH ) return( MBEDTLS_ERR_PK_SIG_LEN_MISMATCH ); return( ret ); } static int ecdsa_sign_wrap( void *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, unsigned char *sig, size_t *sig_len, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { return( mbedtls_ecdsa_write_signature( (mbedtls_ecdsa_context *) ctx, md_alg, hash, hash_len, sig, sig_len, f_rng, p_rng ) ); } #if defined(MBEDTLS_ECP_RESTARTABLE) static int ecdsa_verify_rs_wrap( void *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, const unsigned char *sig, size_t sig_len, void *rs_ctx ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; ((void) md_alg); ret = mbedtls_ecdsa_read_signature_restartable( (mbedtls_ecdsa_context *) ctx, hash, hash_len, sig, sig_len, (mbedtls_ecdsa_restart_ctx *) rs_ctx ); if( ret == MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH ) return( MBEDTLS_ERR_PK_SIG_LEN_MISMATCH ); return( ret ); } static int ecdsa_sign_rs_wrap( void *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, unsigned char *sig, size_t *sig_len, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, void *rs_ctx ) { return( mbedtls_ecdsa_write_signature_restartable( (mbedtls_ecdsa_context *) ctx, md_alg, hash, hash_len, sig, sig_len, f_rng, p_rng, (mbedtls_ecdsa_restart_ctx *) rs_ctx ) ); } #endif /* MBEDTLS_ECP_RESTARTABLE */ static void *ecdsa_alloc_wrap( void ) { void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_ecdsa_context ) ); if( ctx != NULL ) mbedtls_ecdsa_init( (mbedtls_ecdsa_context *) ctx ); return( ctx ); } static void ecdsa_free_wrap( void *ctx ) { mbedtls_ecdsa_free( (mbedtls_ecdsa_context *) ctx ); mbedtls_free( ctx ); } #if defined(MBEDTLS_ECP_RESTARTABLE) static void *ecdsa_rs_alloc( void ) { void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_ecdsa_restart_ctx ) ); if( ctx != NULL ) mbedtls_ecdsa_restart_init( ctx ); return( ctx ); } static void ecdsa_rs_free( void *ctx ) { mbedtls_ecdsa_restart_free( ctx ); mbedtls_free( ctx ); } #endif /* MBEDTLS_ECP_RESTARTABLE */ const mbedtls_pk_info_t mbedtls_ecdsa_info = { MBEDTLS_PK_ECDSA, "ECDSA", eckey_get_bitlen, /* Compatible key structures */ ecdsa_can_do, ecdsa_verify_wrap, ecdsa_sign_wrap, #if defined(MBEDTLS_ECP_RESTARTABLE) ecdsa_verify_rs_wrap, ecdsa_sign_rs_wrap, #endif NULL, NULL, eckey_check_pair, /* Compatible key structures */ ecdsa_alloc_wrap, ecdsa_free_wrap, #if defined(MBEDTLS_ECP_RESTARTABLE) ecdsa_rs_alloc, ecdsa_rs_free, #endif eckey_debug, /* Compatible key structures */ }; #endif /* MBEDTLS_ECDSA_C */ /* * Support for alternative RSA-private implementations */ static int rsa_alt_can_do( mbedtls_pk_type_t type ) { return( type == MBEDTLS_PK_RSA ); } static size_t rsa_alt_get_bitlen( const void *ctx ) { const mbedtls_rsa_alt_context *rsa_alt = (const mbedtls_rsa_alt_context *) ctx; return( 8 * rsa_alt->key_len_func( rsa_alt->key ) ); } static int rsa_alt_sign_wrap( void *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, unsigned char *sig, size_t *sig_len, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { mbedtls_rsa_alt_context *rsa_alt = (mbedtls_rsa_alt_context *) ctx; #if SIZE_MAX > UINT_MAX if( UINT_MAX < hash_len ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); #endif /* SIZE_MAX > UINT_MAX */ *sig_len = rsa_alt->key_len_func( rsa_alt->key ); if( *sig_len > MBEDTLS_PK_SIGNATURE_MAX_SIZE ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); return( rsa_alt->sign_func( rsa_alt->key, f_rng, p_rng, MBEDTLS_RSA_PRIVATE, md_alg, (unsigned int) hash_len, hash, sig ) ); } static int rsa_alt_decrypt_wrap( void *ctx, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen, size_t osize, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { mbedtls_rsa_alt_context *rsa_alt = (mbedtls_rsa_alt_context *) ctx; ((void) f_rng); ((void) p_rng); if( ilen != rsa_alt->key_len_func( rsa_alt->key ) ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); return( rsa_alt->decrypt_func( rsa_alt->key, MBEDTLS_RSA_PRIVATE, olen, input, output, osize ) ); } #if defined(MBEDTLS_RSA_C) static int rsa_alt_check_pair( const void *pub, const void *prv ) { unsigned char sig[MBEDTLS_MPI_MAX_SIZE]; unsigned char hash[32]; size_t sig_len = 0; int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( rsa_alt_get_bitlen( prv ) != rsa_get_bitlen( pub ) ) return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ); memset( hash, 0x2a, sizeof( hash ) ); if( ( ret = rsa_alt_sign_wrap( (void *) prv, MBEDTLS_MD_NONE, hash, sizeof( hash ), sig, &sig_len, NULL, NULL ) ) != 0 ) { return( ret ); } if( rsa_verify_wrap( (void *) pub, MBEDTLS_MD_NONE, hash, sizeof( hash ), sig, sig_len ) != 0 ) { return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ); } return( 0 ); } #endif /* MBEDTLS_RSA_C */ static void *rsa_alt_alloc_wrap( void ) { void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_rsa_alt_context ) ); if( ctx != NULL ) mbedtls_platform_zeroize( ctx, sizeof( mbedtls_rsa_alt_context ) ); return( ctx ); } static void rsa_alt_free_wrap( void *ctx ) { mbedtls_platform_zeroize( ctx, sizeof( mbedtls_rsa_alt_context ) ); mbedtls_free( ctx ); } const mbedtls_pk_info_t mbedtls_rsa_alt_info = { MBEDTLS_PK_RSA_ALT, "RSA-alt", rsa_alt_get_bitlen, rsa_alt_can_do, NULL, rsa_alt_sign_wrap, #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) NULL, NULL, #endif rsa_alt_decrypt_wrap, NULL, #if defined(MBEDTLS_RSA_C) rsa_alt_check_pair, #else NULL, #endif rsa_alt_alloc_wrap, rsa_alt_free_wrap, #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) NULL, NULL, #endif NULL, }; #endif /* MBEDTLS_PK_C */
21,933
651
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/rsa.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/strace.internal.h" #include "libc/runtime/runtime.h" #include "libc/stdio/rand.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/md.h" #include "third_party/mbedtls/oid.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/profile.h" #include "third_party/mbedtls/rsa.h" #include "third_party/mbedtls/rsa_internal.h" #include "third_party/mbedtls/sha1.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /** * @fileoverview The RSA public-key cryptosystem * * LENGTH SECURITY * -------------- -------- * RSA 512 57 * RSA 1024 80 * RSA 2048 110 * RSA 4096 150 * RSA 8192 202 * RSA 16384 270 * RSA 32768 359 * RSA 65536 475 * RSA 131072 626 * * (1.923*cbrt(L*log(2))*cbrt(log(L*log(2))*log(L*log(2)))-4.69)/log(2) * * The following sources were referenced in the design of this implementation * of the RSA algorithm: * * [1] A method for obtaining digital signatures and public-key cryptosystems * R Rivest, A Shamir, and L Adleman * http://people.csail.mit.edu/rivest/pubs.html#RSA78 * * [2] Handbook of Applied Cryptography - 1997, Chapter 8 * Menezes, van Oorschot and Vanstone * * [3] Malware Guard Extension: Using SGX to Conceal Cache Attacks * Michael Schwarz, Samuel Weiser, Daniel Gruss, Clémentine Maurice and * Stefan Mangard * https://arxiv.org/abs/1702.08719v2 */ #if defined(MBEDTLS_RSA_C) /* Parameter validation macros */ #define RSA_VALIDATE_RET( cond ) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_RSA_BAD_INPUT_DATA ) #define RSA_VALIDATE( cond ) \ MBEDTLS_INTERNAL_VALIDATE( cond ) int mbedtls_rsa_import( mbedtls_rsa_context *ctx, const mbedtls_mpi *N, const mbedtls_mpi *P, const mbedtls_mpi *Q, const mbedtls_mpi *D, const mbedtls_mpi *E ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; RSA_VALIDATE_RET( ctx != NULL ); if( ( N && ( ret = mbedtls_mpi_copy( &ctx->N, N ) ) != 0 ) || ( P && ( ret = mbedtls_mpi_copy( &ctx->P, P ) ) != 0 ) || ( Q && ( ret = mbedtls_mpi_copy( &ctx->Q, Q ) ) != 0 ) || ( D && ( ret = mbedtls_mpi_copy( &ctx->D, D ) ) != 0 ) || ( E && ( ret = mbedtls_mpi_copy( &ctx->E, E ) ) != 0 ) ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret ); } if( N ) ctx->len = mbedtls_mpi_size( &ctx->N ); return( 0 ); } int mbedtls_rsa_import_raw( mbedtls_rsa_context *ctx, unsigned char const *N, size_t N_len, unsigned char const *P, size_t P_len, unsigned char const *Q, size_t Q_len, unsigned char const *D, size_t D_len, unsigned char const *E, size_t E_len ) { int ret = 0; RSA_VALIDATE_RET( ctx != NULL ); if( N ) { MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->N, N, N_len ) ); ctx->len = mbedtls_mpi_size( &ctx->N ); } if( P ) MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->P, P, P_len ) ); if( Q ) MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->Q, Q, Q_len ) ); if( D ) MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->D, D, D_len ) ); if( E ) MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->E, E, E_len ) ); cleanup: if( ret ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret ); return( 0 ); } /* * Checks whether the context fields are set in such a way * that the RSA primitives will be able to execute without error. * It does *not* make guarantees for consistency of the parameters. */ static int rsa_check_context( mbedtls_rsa_context const *ctx, int is_priv, int blinding_needed ) { #if !defined(MBEDTLS_RSA_NO_CRT) /* blinding_needed is only used for NO_CRT to decide whether * P,Q need to be present or not. */ ((void) blinding_needed); #endif if( ctx->len != mbedtls_mpi_size( &ctx->N ) || ctx->len > MBEDTLS_MPI_MAX_SIZE ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } /* * 1. Modular exponentiation needs positive, odd moduli. */ /* Modular exponentiation wrt. N is always used for * RSA public key operations. */ if( mbedtls_mpi_cmp_int( &ctx->N, 0 ) <= 0 || mbedtls_mpi_get_bit( &ctx->N, 0 ) == 0 ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } #if !defined(MBEDTLS_RSA_NO_CRT) /* Modular exponentiation for P and Q is only * used for private key operations and if CRT * is used. */ if( is_priv && ( mbedtls_mpi_cmp_int( &ctx->P, 0 ) <= 0 || mbedtls_mpi_get_bit( &ctx->P, 0 ) == 0 || mbedtls_mpi_cmp_int( &ctx->Q, 0 ) <= 0 || mbedtls_mpi_get_bit( &ctx->Q, 0 ) == 0 ) ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } #endif /* !MBEDTLS_RSA_NO_CRT */ /* * 2. Exponents must be positive */ /* Always need E for public key operations */ if( mbedtls_mpi_cmp_int( &ctx->E, 0 ) <= 0 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); #if defined(MBEDTLS_RSA_NO_CRT) /* For private key operations, use D or DP & DQ * as (unblinded) exponents. */ if( is_priv && mbedtls_mpi_cmp_int( &ctx->D, 0 ) <= 0 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); #else if( is_priv && ( mbedtls_mpi_cmp_int( &ctx->DP, 0 ) <= 0 || mbedtls_mpi_cmp_int( &ctx->DQ, 0 ) <= 0 ) ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } #endif /* MBEDTLS_RSA_NO_CRT */ /* Blinding shouldn't make exponents negative either, * so check that P, Q >= 1 if that hasn't yet been * done as part of 1. */ #if defined(MBEDTLS_RSA_NO_CRT) if( is_priv && blinding_needed && ( mbedtls_mpi_cmp_int( &ctx->P, 0 ) <= 0 || mbedtls_mpi_cmp_int( &ctx->Q, 0 ) <= 0 ) ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } #endif /* It wouldn't lead to an error if it wasn't satisfied, * but check for QP >= 1 nonetheless. */ #if !defined(MBEDTLS_RSA_NO_CRT) if( is_priv && mbedtls_mpi_cmp_int( &ctx->QP, 0 ) <= 0 ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } #endif return( 0 ); } int mbedtls_rsa_complete( mbedtls_rsa_context *ctx ) { int ret = 0; int have_N, have_P, have_Q, have_D, have_E; #if !defined(MBEDTLS_RSA_NO_CRT) int have_DP, have_DQ, have_QP; #endif int n_missing, pq_missing, d_missing, is_pub, is_priv; RSA_VALIDATE_RET( ctx != NULL ); have_N = ( mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 ); have_P = ( mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 ); have_Q = ( mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 ); have_D = ( mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 ); have_E = ( mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0 ); #if !defined(MBEDTLS_RSA_NO_CRT) have_DP = ( mbedtls_mpi_cmp_int( &ctx->DP, 0 ) != 0 ); have_DQ = ( mbedtls_mpi_cmp_int( &ctx->DQ, 0 ) != 0 ); have_QP = ( mbedtls_mpi_cmp_int( &ctx->QP, 0 ) != 0 ); #endif /* * Check whether provided parameters are enough * to deduce all others. The following incomplete * parameter sets for private keys are supported: * * (1) P, Q missing. * (2) D and potentially N missing. * */ n_missing = have_P && have_Q && have_D && have_E; pq_missing = have_N && !have_P && !have_Q && have_D && have_E; d_missing = have_P && have_Q && !have_D && have_E; is_pub = have_N && !have_P && !have_Q && !have_D && have_E; /* These three alternatives are mutually exclusive */ is_priv = n_missing || pq_missing || d_missing; if( !is_priv && !is_pub ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); /* * Step 1: Deduce N if P, Q are provided. */ if( !have_N && have_P && have_Q ) { if( ( ret = mbedtls_mpi_mul_mpi( &ctx->N, &ctx->P, &ctx->Q ) ) != 0 ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret ); } ctx->len = mbedtls_mpi_size( &ctx->N ); } /* * Step 2: Deduce and verify all remaining core parameters. */ if( pq_missing ) { ret = mbedtls_rsa_deduce_primes( &ctx->N, &ctx->E, &ctx->D, &ctx->P, &ctx->Q ); if( ret != 0 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret ); } else if( d_missing ) { if( ( ret = mbedtls_rsa_deduce_private_exponent( &ctx->P, &ctx->Q, &ctx->E, &ctx->D ) ) != 0 ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret ); } } /* * Step 3: Deduce all additional parameters specific * to our current RSA implementation. */ #if !defined(MBEDTLS_RSA_NO_CRT) if( is_priv && ! ( have_DP && have_DQ && have_QP ) ) { ret = mbedtls_rsa_deduce_crt( &ctx->P, &ctx->Q, &ctx->D, &ctx->DP, &ctx->DQ, &ctx->QP ); if( ret != 0 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret ); } #endif /* MBEDTLS_RSA_NO_CRT */ /* * Step 3: Basic sanity checks */ return( rsa_check_context( ctx, is_priv, 1 ) ); } int mbedtls_rsa_export_raw( const mbedtls_rsa_context *ctx, unsigned char *N, size_t N_len, unsigned char *P, size_t P_len, unsigned char *Q, size_t Q_len, unsigned char *D, size_t D_len, unsigned char *E, size_t E_len ) { int ret = 0; int is_priv; RSA_VALIDATE_RET( ctx != NULL ); /* Check if key is private or public */ is_priv = mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0; if( !is_priv ) { /* If we're trying to export private parameters for a public key, * something must be wrong. */ if( P != NULL || Q != NULL || D != NULL ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } if( N ) MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->N, N, N_len ) ); if( P ) MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->P, P, P_len ) ); if( Q ) MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->Q, Q, Q_len ) ); if( D ) MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->D, D, D_len ) ); if( E ) MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->E, E, E_len ) ); cleanup: return( ret ); } int mbedtls_rsa_export( const mbedtls_rsa_context *ctx, mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q, mbedtls_mpi *D, mbedtls_mpi *E ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; int is_priv; RSA_VALIDATE_RET( ctx != NULL ); /* Check if key is private or public */ is_priv = mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0; if( !is_priv ) { /* If we're trying to export private parameters for a public key, * something must be wrong. */ if( P != NULL || Q != NULL || D != NULL ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } /* Export all requested core parameters. */ if( ( N != NULL && ( ret = mbedtls_mpi_copy( N, &ctx->N ) ) != 0 ) || ( P != NULL && ( ret = mbedtls_mpi_copy( P, &ctx->P ) ) != 0 ) || ( Q != NULL && ( ret = mbedtls_mpi_copy( Q, &ctx->Q ) ) != 0 ) || ( D != NULL && ( ret = mbedtls_mpi_copy( D, &ctx->D ) ) != 0 ) || ( E != NULL && ( ret = mbedtls_mpi_copy( E, &ctx->E ) ) != 0 ) ) { return( ret ); } return( 0 ); } /* * Export CRT parameters * This must also be implemented if CRT is not used, for being able to * write DER encoded RSA keys. The helper function mbedtls_rsa_deduce_crt * can be used in this case. */ int mbedtls_rsa_export_crt( const mbedtls_rsa_context *ctx, mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; int is_priv; RSA_VALIDATE_RET( ctx != NULL ); /* Check if key is private or public */ is_priv = mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 && mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0; if( !is_priv ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); #if !defined(MBEDTLS_RSA_NO_CRT) /* Export all requested blinding parameters. */ if( ( DP != NULL && ( ret = mbedtls_mpi_copy( DP, &ctx->DP ) ) != 0 ) || ( DQ != NULL && ( ret = mbedtls_mpi_copy( DQ, &ctx->DQ ) ) != 0 ) || ( QP != NULL && ( ret = mbedtls_mpi_copy( QP, &ctx->QP ) ) != 0 ) ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret ); } #else if( ( ret = mbedtls_rsa_deduce_crt( &ctx->P, &ctx->Q, &ctx->D, DP, DQ, QP ) ) != 0 ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret ); } #endif return( 0 ); } /* * Initialize an RSA context */ void mbedtls_rsa_init( mbedtls_rsa_context *ctx, int padding, int hash_id ) { RSA_VALIDATE( ctx != NULL ); RSA_VALIDATE( padding == MBEDTLS_RSA_PKCS_V15 || padding == MBEDTLS_RSA_PKCS_V21 ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_rsa_context ) ); mbedtls_rsa_set_padding( ctx, padding, hash_id ); } /* * Set padding for an existing RSA context */ void mbedtls_rsa_set_padding( mbedtls_rsa_context *ctx, int padding, int hash_id ) { RSA_VALIDATE( ctx != NULL ); RSA_VALIDATE( padding == MBEDTLS_RSA_PKCS_V15 || padding == MBEDTLS_RSA_PKCS_V21 ); ctx->padding = padding; ctx->hash_id = hash_id; } /* * Get length in bytes of RSA modulus */ size_t mbedtls_rsa_get_len( const mbedtls_rsa_context *ctx ) { return( ctx->len ); } #if defined(MBEDTLS_GENPRIME) /* * Generate an RSA keypair * * This generation method follows the RSA key pair generation procedure of * FIPS 186-4 if 2^16 < exponent < 2^256 and nbits = 2048 or nbits = 3072. */ int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, unsigned int nbits, int exponent ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_mpi H, G, L; int prime_quality = 0; RSA_VALIDATE_RET( ctx ); RSA_VALIDATE_RET( f_rng ); /* * If the modulus is 1024 bit long or shorter, then the security strength of * the RSA algorithm is less than or equal to 80 bits and therefore an error * rate of 2^-80 is sufficient. */ if( nbits > 1024 ) prime_quality = MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR; mbedtls_mpi_init( &H ); mbedtls_mpi_init( &G ); mbedtls_mpi_init( &L ); if( nbits < 128 || exponent < 3 || nbits % 2 != 0 ) { ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA; goto cleanup; } /* * find primes P and Q with Q < P so that: * 1. |P-Q| > 2^( nbits / 2 - 100 ) * 2. GCD( E, (P-1)*(Q-1) ) == 1 * 3. E^-1 mod LCM(P-1, Q-1) > 2^( nbits / 2 ) */ MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &ctx->E, exponent ) ); do { MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->P, nbits >> 1, prime_quality, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q, nbits >> 1, prime_quality, f_rng, p_rng ) ); /* make sure the difference between p and q is not too small (FIPS 186-4 §B.3.3 step 5.4) */ MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &H, &ctx->P, &ctx->Q ) ); if( mbedtls_mpi_bitlen( &H ) <= ( ( nbits >= 200 ) ? ( ( nbits >> 1 ) - 99 ) : 0 ) ) continue; /* not required by any standards, but some users rely on the fact that P > Q */ if( H.s < 0 ) mbedtls_mpi_swap( &ctx->P, &ctx->Q ); /* Temporarily replace P,Q by P-1, Q-1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &ctx->P, &ctx->P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &ctx->Q, &ctx->Q, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &H, &ctx->P, &ctx->Q ) ); /* check GCD( E, (P-1)*(Q-1) ) == 1 (FIPS 186-4 §B.3.1 criterion 2(a)) */ MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, &ctx->E, &H ) ); if( !mbedtls_mpi_is_one( &G ) ) continue; /* compute smallest possible D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b)) */ MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, &ctx->P, &ctx->Q ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &L, NULL, &H, &G ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->D, &ctx->E, &L ) ); if( mbedtls_mpi_bitlen( &ctx->D ) <= ( ( nbits + 1 ) / 2 ) ) // (FIPS 186-4 §B.3.1 criterion 3(a)) continue; break; } while( 1 ); /* Restore P,Q */ MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &ctx->P, &ctx->P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &ctx->Q, &ctx->Q, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->N, &ctx->P, &ctx->Q ) ); ctx->len = mbedtls_mpi_size( &ctx->N ); #if !defined(MBEDTLS_RSA_NO_CRT) /* * DP = D mod (P - 1) * DQ = D mod (Q - 1) * QP = Q^-1 mod P */ MBEDTLS_MPI_CHK( mbedtls_rsa_deduce_crt( &ctx->P, &ctx->Q, &ctx->D, &ctx->DP, &ctx->DQ, &ctx->QP ) ); #endif /* MBEDTLS_RSA_NO_CRT */ /* Double-check */ MBEDTLS_MPI_CHK( mbedtls_rsa_check_privkey( ctx ) ); cleanup: mbedtls_mpi_free( &H ); mbedtls_mpi_free( &G ); mbedtls_mpi_free( &L ); if( ret != 0 ) { mbedtls_rsa_free( ctx ); if( ( -ret & ~0x7f ) == 0 ) ret = MBEDTLS_ERR_RSA_KEY_GEN_FAILED + ret; } STRACE("%s() → %d", "mbedtls_rsa_gen_key", ret); return( ret ); } #endif /* MBEDTLS_GENPRIME */ /* * Check a public RSA key */ int mbedtls_rsa_check_pubkey( const mbedtls_rsa_context *ctx ) { RSA_VALIDATE_RET( ctx ); if( rsa_check_context( ctx, 0 /* public */, 0 /* no blinding */ ) != 0 ) return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ); if( mbedtls_mpi_bitlen( &ctx->N ) < 128 ) { return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ); } if( mbedtls_mpi_get_bit( &ctx->E, 0 ) == 0 || mbedtls_mpi_bitlen( &ctx->E ) < 2 || mbedtls_mpi_cmp_mpi( &ctx->E, &ctx->N ) >= 0 ) { return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ); } return( 0 ); } /* * Check for the consistency of all fields in an RSA private key context */ int mbedtls_rsa_check_privkey( const mbedtls_rsa_context *ctx ) { RSA_VALIDATE_RET( ctx ); if( mbedtls_rsa_check_pubkey( ctx ) != 0 || rsa_check_context( ctx, 1 /* private */, 1 /* blinding */ ) != 0 ) { return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ); } if( mbedtls_rsa_validate_params( &ctx->N, &ctx->P, &ctx->Q, &ctx->D, &ctx->E, NULL, NULL ) != 0 ) { return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ); } #if !defined(MBEDTLS_RSA_NO_CRT) else if( mbedtls_rsa_validate_crt( &ctx->P, &ctx->Q, &ctx->D, &ctx->DP, &ctx->DQ, &ctx->QP ) != 0 ) { return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ); } #endif return( 0 ); } /* * Check if contexts holding a public and private key match */ int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub, const mbedtls_rsa_context *prv ) { RSA_VALIDATE_RET( pub ); RSA_VALIDATE_RET( prv ); if( mbedtls_rsa_check_pubkey( pub ) != 0 || mbedtls_rsa_check_privkey( prv ) != 0 ) { return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ); } if( mbedtls_mpi_cmp_mpi( &pub->N, &prv->N ) != 0 || mbedtls_mpi_cmp_mpi( &pub->E, &prv->E ) != 0 ) { return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ); } return( 0 ); } /* * Do an RSA public key operation */ int mbedtls_rsa_public( mbedtls_rsa_context *ctx, const unsigned char *input, unsigned char *output ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t olen; mbedtls_mpi T; RSA_VALIDATE_RET( ctx ); RSA_VALIDATE_RET( input ); RSA_VALIDATE_RET( output ); if( rsa_check_context( ctx, 0 /* public */, 0 /* no blinding */ ) ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); mbedtls_mpi_init( &T ); MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &T, input, ctx->len ) ); if( mbedtls_mpi_cmp_mpi( &T, &ctx->N ) >= 0 ) { ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA; goto cleanup; } olen = ctx->len; MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T, &T, &ctx->E, &ctx->N, &ctx->RN ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &T, output, olen ) ); cleanup: mbedtls_mpi_free( &T ); if( ret != 0 ) return( MBEDTLS_ERR_RSA_PUBLIC_FAILED + ret ); return( 0 ); } /* * TODO(jart): Why is MbedTLS release source so different from Git source? * This function takes 806us to execute. */ /* * Generate or update blinding values, see section 10 of: * KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA, * DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer * Berlin Heidelberg, 1996. p. 104-113. */ static int rsa_prepare_blinding( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret, count = 0; mbedtls_mpi R; mbedtls_mpi_init( &R ); if( ctx->Vf.p ) { /* We already have blinding values, just update them by squaring */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vi, &ctx->Vi ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vf, &ctx->Vf, &ctx->Vf ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vf, &ctx->Vf, &ctx->N ) ); goto cleanup; } /* Unblinding value: Vf = random number, invertible mod N */ do { if( count++ > 10 ) { ret = MBEDTLS_ERR_RSA_RNG_FAILED; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->Vf, ctx->len - 1, f_rng, p_rng ) ); /* Compute Vf^-1 as R * (R Vf)^-1 to avoid leaks from inv_mod. */ MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, ctx->len - 1, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vf, &R ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->N ) ); /* At this point, Vi is invertible mod N if and only if both Vf and R * are invertible mod N. If one of them isn't, we don't need to know * which one, we just loop and choose new values for both of them. * (Each iteration succeeds with overwhelming probability.) */ ret = mbedtls_mpi_inv_mod( &ctx->Vi, &ctx->Vi, &ctx->N ); if( ret != 0 && ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE ) goto cleanup; } while( ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE ); /* Finish the computation of Vf^-1 = R * (R Vf)^-1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vi, &R ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->N ) ); /* Blinding value: Vi = Vf^(-e) mod N * (Vi already contains Vf^-1 at this point) */ MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN ) ); cleanup: mbedtls_mpi_free( &R ); return( ret ); } /* * Exponent blinding supposed to prevent side-channel attacks using multiple * traces of measurements to recover the RSA key. The more collisions are there, * the more bits of the key can be recovered. See [3]. * * Collecting n collisions with m bit long blinding value requires 2^(m-m/n) * observations on avarage. * * For example with 28 byte blinding to achieve 2 collisions the adversary has * to make 2^112 observations on avarage. * * (With the currently (as of 2017 April) known best algorithms breaking 2048 * bit RSA requires approximately as much time as trying out 2^112 random keys. * Thus in this sense with 28 byte blinding the security is not reduced by * side-channel attacks like the one in [3]) * * This countermeasure does not help if the key recovery is possible with a * single trace. */ #define RSA_EXPONENT_BLINDING 28 /* * Do an RSA private key operation */ int mbedtls_rsa_private( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, const unsigned char *input, unsigned char *output ) { RSA_VALIDATE_RET( ctx ); RSA_VALIDATE_RET( input ); RSA_VALIDATE_RET( output ); int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t olen; /* Temporary holding the result */ mbedtls_mpi T; /* Temporaries holding P-1, Q-1 and the * exponent blinding factor, respectively. */ mbedtls_mpi P1, Q1, R; #if !defined(MBEDTLS_RSA_NO_CRT) /* Temporaries holding the results mod p resp. mod q. */ mbedtls_mpi TP, TQ; /* Temporaries holding the blinded exponents for * the mod p resp. mod q computation (if used). */ mbedtls_mpi DP_blind, DQ_blind; /* Pointers to actual exponents to be used - either the unblinded * or the blinded ones, depending on the presence of a PRNG. */ mbedtls_mpi *DP = &ctx->DP; mbedtls_mpi *DQ = &ctx->DQ; #else /* Temporary holding the blinded exponent (if used). */ mbedtls_mpi D_blind; /* Pointer to actual exponent to be used - either the unblinded * or the blinded one, depending on the presence of a PRNG. */ mbedtls_mpi *D = &ctx->D; #endif /* MBEDTLS_RSA_NO_CRT */ /* Temporaries holding the initial input and the double * checked result; should be the same in the end. */ mbedtls_mpi I, C; if( rsa_check_context( ctx, 1 /* private key checks */, f_rng != NULL /* blinding y/n */ ) != 0 ) { return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } /* MPI Initialization */ mbedtls_mpi_init( &T ); mbedtls_mpi_init( &P1 ); mbedtls_mpi_init( &Q1 ); mbedtls_mpi_init( &R ); if( f_rng ) { #if defined(MBEDTLS_RSA_NO_CRT) mbedtls_mpi_init( &D_blind ); #else mbedtls_mpi_init( &DP_blind ); mbedtls_mpi_init( &DQ_blind ); #endif } #if !defined(MBEDTLS_RSA_NO_CRT) mbedtls_mpi_init( &TP ); mbedtls_mpi_init( &TQ ); #endif mbedtls_mpi_init( &I ); mbedtls_mpi_init( &C ); /* End of MPI initialization */ MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &T, input, ctx->len ) ); if( mbedtls_mpi_cmp_mpi( &T, &ctx->N ) >= 0 ) { ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &I, &T ) ); if( f_rng ) { /* * Blinding * T = T * Vi mod N */ MBEDTLS_MPI_CHK( rsa_prepare_blinding( ctx, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &T, &ctx->Vi ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &T, &ctx->N ) ); /* * Exponent blinding */ MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &P1, &ctx->P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &Q1, &ctx->Q, 1 ) ); #if defined(MBEDTLS_RSA_NO_CRT) /* * D_blind = ( P - 1 ) * ( Q - 1 ) * R + D */ MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &D_blind, &P1, &Q1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &D_blind, &D_blind, &R ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &D_blind, &D_blind, &ctx->D ) ); D = &D_blind; #else /* * DP_blind = ( P - 1 ) * R + DP */ MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DP_blind, &P1, &R ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &DP_blind, &DP_blind, &ctx->DP ) ); DP = &DP_blind; /* * DQ_blind = ( Q - 1 ) * R + DQ */ MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DQ_blind, &Q1, &R ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &DQ_blind, &DQ_blind, &ctx->DQ ) ); DQ = &DQ_blind; #endif /* MBEDTLS_RSA_NO_CRT */ } #if defined(MBEDTLS_RSA_NO_CRT) MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T, &T, D, &ctx->N, &ctx->RN ) ); #else /* * Faster decryption using the CRT * * TP = input ^ dP mod P * TQ = input ^ dQ mod Q */ MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &TP, &T, DP, &ctx->P, &ctx->RP ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &TQ, &T, DQ, &ctx->Q, &ctx->RQ ) ); /* * T = (TP - TQ) * (Q^-1 mod P) mod P */ MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T, &TP, &TQ ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &TP, &T, &ctx->QP ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &TP, &ctx->P ) ); /* * T = TQ + T * Q */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &TP, &T, &ctx->Q ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &T, &TQ, &TP ) ); #endif /* MBEDTLS_RSA_NO_CRT */ if( f_rng ) { /* * Unblind * T = T * Vf mod N */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &T, &ctx->Vf ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &T, &ctx->N ) ); } /* Verify the result to prevent glitching attacks. */ MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &C, &T, &ctx->E, &ctx->N, &ctx->RN ) ); if( mbedtls_mpi_cmp_mpi( &C, &I ) != 0 ) { ret = MBEDTLS_ERR_RSA_VERIFY_FAILED; goto cleanup; } olen = ctx->len; MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &T, output, olen ) ); cleanup: mbedtls_mpi_free( &P1 ); mbedtls_mpi_free( &Q1 ); mbedtls_mpi_free( &R ); if( f_rng ) { #if defined(MBEDTLS_RSA_NO_CRT) mbedtls_mpi_free( &D_blind ); #else mbedtls_mpi_free( &DP_blind ); mbedtls_mpi_free( &DQ_blind ); #endif } mbedtls_mpi_free( &T ); #if !defined(MBEDTLS_RSA_NO_CRT) mbedtls_mpi_free( &TP ); mbedtls_mpi_free( &TQ ); #endif mbedtls_mpi_free( &C ); mbedtls_mpi_free( &I ); if( ret != 0 && ret >= -0x007f ) return( MBEDTLS_ERR_RSA_PRIVATE_FAILED + ret ); return( ret ); } /** * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer. * * \param dst buffer to mask * \param dlen length of destination buffer * \param src source of the mask generation * \param slen length of the source buffer * \param md_ctx message digest context to use */ static int mgf_mask( unsigned char *dst, size_t dlen, unsigned char *src, size_t slen, mbedtls_md_context_t *md_ctx ) { unsigned char mask[MBEDTLS_MD_MAX_SIZE]; unsigned char counter[4]; unsigned char *p; unsigned int hlen; size_t i, use_len; int ret = 0; mbedtls_platform_zeroize( mask, MBEDTLS_MD_MAX_SIZE ); memset( counter, 0, 4 ); hlen = mbedtls_md_get_size( md_ctx->md_info ); /* Generate and apply dbMask */ p = dst; while( dlen > 0 ) { use_len = hlen; if( dlen < hlen ) use_len = dlen; if( ( ret = mbedtls_md_starts( md_ctx ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_update( md_ctx, src, slen ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_update( md_ctx, counter, 4 ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_finish( md_ctx, mask ) ) != 0 ) goto exit; for( i = 0; i < use_len; ++i ) *p++ ^= mask[i]; counter[3]++; dlen -= use_len; } exit: mbedtls_platform_zeroize( mask, sizeof( mask ) ); return( ret ); } /* * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function */ int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, const unsigned char *label, size_t label_len, size_t ilen, const unsigned char *input, unsigned char *output ) { size_t olen; int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char *p = output; unsigned int hlen; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( output != NULL ); RSA_VALIDATE_RET( ilen == 0 || input != NULL ); RSA_VALIDATE_RET( label_len == 0 || label != NULL ); if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); if( !f_rng ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id ); if( !md_info ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); olen = ctx->len; hlen = mbedtls_md_get_size( md_info ); /* first comparison checks for overflow */ if( ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); mbedtls_platform_zeroize( output, olen ); *p++ = 0; /* Generate a random octet string seed */ if( ( ret = f_rng( p_rng, p, hlen ) ) != 0 ) return( MBEDTLS_ERR_RSA_RNG_FAILED + ret ); p += hlen; /* Construct DB */ if( ( ret = mbedtls_md( md_info, label, label_len, p ) ) != 0 ) return( ret ); p += hlen; p += olen - 2 * hlen - 2 - ilen; *p++ = 1; if( ilen != 0 ) memcpy( p, input, ilen ); mbedtls_md_init( &md_ctx ); if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 ) goto exit; /* maskedDB: Apply dbMask to DB */ if( ( ret = mgf_mask( output + hlen + 1, olen - hlen - 1, output + 1, hlen, &md_ctx ) ) != 0 ) goto exit; /* maskedSeed: Apply seedMask to seed */ if( ( ret = mgf_mask( output + 1, hlen, output + hlen + 1, olen - hlen - 1, &md_ctx ) ) != 0 ) goto exit; exit: mbedtls_md_free( &md_ctx ); if( ret != 0 ) return( ret ); return( ( mode == MBEDTLS_RSA_PUBLIC ) ? mbedtls_rsa_public( ctx, output, output ) : mbedtls_rsa_private( ctx, f_rng, p_rng, output, output ) ); } #if defined(MBEDTLS_PKCS1_V15) /* * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function */ int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, size_t ilen, const unsigned char *input, unsigned char *output ) { size_t nb_pad, olen; int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char *p = output; RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( output != NULL ); RSA_VALIDATE_RET( ilen == 0 || input != NULL ); if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); olen = ctx->len; /* first comparison checks for overflow */ if( ilen + 11 < ilen || olen < ilen + 11 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); nb_pad = olen - 3 - ilen; *p++ = 0; if( mode == MBEDTLS_RSA_PUBLIC ) { if( !f_rng ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); *p++ = MBEDTLS_RSA_CRYPT; while( nb_pad-- > 0 ) { int rng_dl = 100; do { ret = f_rng( p_rng, p, 1 ); } while( *p == 0 && --rng_dl && ret == 0 ); /* Check if RNG failed to generate data */ if( rng_dl == 0 || ret != 0 ) return( MBEDTLS_ERR_RSA_RNG_FAILED + ret ); p++; } } else { *p++ = MBEDTLS_RSA_SIGN; while( nb_pad-- > 0 ) *p++ = 0xFF; } *p++ = 0; if( ilen != 0 ) memcpy( p, input, ilen ); return( ( mode == MBEDTLS_RSA_PUBLIC ) ? mbedtls_rsa_public( ctx, output, output ) : mbedtls_rsa_private( ctx, f_rng, p_rng, output, output ) ); } #endif /* MBEDTLS_PKCS1_V15 */ /* * Add the message padding, then do an RSA operation */ int mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, size_t ilen, const unsigned char *input, unsigned char *output ) { RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( output != NULL ); RSA_VALIDATE_RET( ilen == 0 || input != NULL ); switch( ctx->padding ) { #if defined(MBEDTLS_PKCS1_V15) case MBEDTLS_RSA_PKCS_V15: return mbedtls_rsa_rsaes_pkcs1_v15_encrypt( ctx, f_rng, p_rng, mode, ilen, input, output ); #endif #if defined(MBEDTLS_PKCS1_V21) case MBEDTLS_RSA_PKCS_V21: return mbedtls_rsa_rsaes_oaep_encrypt( ctx, f_rng, p_rng, mode, NULL, 0, ilen, input, output ); #endif default: return( MBEDTLS_ERR_RSA_INVALID_PADDING ); } } /* * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function */ int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, const unsigned char *label, size_t label_len, size_t *olen, const unsigned char *input, unsigned char *output, size_t output_max_len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t ilen, i, pad_len; unsigned char *p, bad, pad_done; unsigned char buf[MBEDTLS_MPI_MAX_SIZE]; unsigned char lhash[MBEDTLS_MD_MAX_SIZE]; unsigned int hlen; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( output_max_len == 0 || output != NULL ); RSA_VALIDATE_RET( label_len == 0 || label != NULL ); RSA_VALIDATE_RET( input != NULL ); RSA_VALIDATE_RET( olen != NULL ); /* * Parameters sanity checks */ if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); ilen = ctx->len; if( ilen < 16 || ilen > sizeof( buf ) ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id ); if( !md_info ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); hlen = mbedtls_md_get_size( md_info ); // checking for integer underflow if( 2 * hlen + 2 > ilen ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); /* * RSA operation */ ret = ( mode == MBEDTLS_RSA_PUBLIC ) ? mbedtls_rsa_public( ctx, input, buf ) : mbedtls_rsa_private( ctx, f_rng, p_rng, input, buf ); if( ret ) goto cleanup; /* * Unmask data and generate lHash */ mbedtls_md_init( &md_ctx ); if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 ) { mbedtls_md_free( &md_ctx ); goto cleanup; } /* seed: Apply seedMask to maskedSeed */ if( ( ret = mgf_mask( buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1, &md_ctx ) ) != 0 || /* DB: Apply dbMask to maskedDB */ ( ret = mgf_mask( buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen, &md_ctx ) ) != 0 ) { mbedtls_md_free( &md_ctx ); goto cleanup; } mbedtls_md_free( &md_ctx ); /* Generate lHash */ if( ( ret = mbedtls_md( md_info, label, label_len, lhash ) ) != 0 ) goto cleanup; /* * Check contents, in "constant-time" */ p = buf; bad = 0; bad |= *p++; /* First byte must be 0 */ p += hlen; /* Skip seed */ /* Check lHash */ for( i = 0; i < hlen; i++ ) bad |= lhash[i] ^ *p++; /* Get zero-padding len, but always read till end of buffer * (minus one, for the 01 byte) */ pad_len = 0; pad_done = 0; for( i = 0; i < ilen - 2 * hlen - 2; i++ ) { pad_done |= p[i]; pad_len += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1; } p += pad_len; bad |= *p++ ^ 0x01; /* * The only information "leaked" is whether the padding was correct or not * (eg, no data is copied if it was not correct). This meets the * recommendations in PKCS#1 v2.2: an opponent cannot distinguish between * the different error conditions. */ if( bad ) { ret = MBEDTLS_ERR_RSA_INVALID_PADDING; goto cleanup; } if( ilen - ( p - buf ) > output_max_len ) { ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE; goto cleanup; } *olen = ilen - (p - buf); memcpy( output, p, *olen ); ret = 0; cleanup: mbedtls_platform_zeroize( buf, sizeof( buf ) ); mbedtls_platform_zeroize( lhash, sizeof( lhash ) ); return( ret ); } #if defined(MBEDTLS_PKCS1_V15) /** * Does -!!value without branches. * * \param value The value to analyze. * \return Zero if \p value is zero, otherwise all-bits-one. */ forceinline unsigned all_or_nothing_int( unsigned value ) { /* MSVC has a warning about unary minus on unsigned, but this is * well-defined and precisely what we want to do here */ #if defined(_MSC_VER) #pragma warning( push ) #pragma warning( disable : 4146 ) #endif return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) ); #if defined(_MSC_VER) #pragma warning( pop ) #endif } /** * Check whether a size is out of bounds, without branches. * * This is equivalent to `size > max`, but is likely to be compiled to * to code using bitwise operation rather than a branch. * * \param size Size to check. * \param max Maximum desired value for \p size. * \return \c 0 if `size <= max`. * \return \c 1 if `size > max`. */ forceinline unsigned size_greater_than( size_t size, size_t max ) { /* Return the sign bit (1 for negative) of (max - size). */ return( ( max - size ) >> ( sizeof( size_t ) * 8 - 1 ) ); } /** * Choose between two integer values, without branches. * * This is equivalent to `cond ? if1 : if0`, but is likely to be compiled * to code using bitwise operation rather than a branch. * * \param cond Condition to test. * \param if1 Value to use if \p cond is nonzero. * \param if0 Value to use if \p cond is zero. * \return \c if1 if \p cond is nonzero, otherwise \c if0. */ forceinline unsigned if_int( unsigned cond, unsigned if1, unsigned if0 ) { unsigned mask = all_or_nothing_int( cond ); return( ( CONCEAL( "r", mask ) & if1 ) | ( CONCEAL( "r", ~mask ) & if0 ) ); } /** * Shift some data towards the left inside a buffer without leaking * the length of the data through side channels. * * mem_move_to_left(start, total, offset); * * is functionally equivalent to * * memmove(start, start + offset, total - offset); * memset(start + offset, 0, total - offset); * * but it strives to use a memory access pattern (and thus total timing) * that does not depend on \p offset. This timing independence comes at * the expense of performance. * * \param start Pointer to the start of the buffer. * \param total Total size of the buffer. * \param offset Offset from which to copy \p total - \p offset bytes. */ static void mem_move_to_left( void *start, size_t total, size_t offset ) { volatile unsigned char *buf = start; size_t i, n; if( total == 0 ) return; for( i = 0; i < total; i++ ) { unsigned no_op = size_greater_than( total - offset, i ); /* The first `total - offset` passes are a no-op. The last * `offset` passes shift the data one byte to the left and * zero out the last byte. */ for( n = 0; n < total - 1; n++ ) { unsigned char current = buf[n]; unsigned char next = buf[n+1]; buf[n] = if_int( no_op, current, next ); } buf[total-1] = if_int( no_op, buf[total-1], 0 ); } } /* * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function */ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, size_t *olen, const unsigned char *input, unsigned char *output, size_t output_max_len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t ilen, i, plaintext_max_size; unsigned char buf[MBEDTLS_MPI_MAX_SIZE]; /* The following variables take sensitive values: their value must * not leak into the observable behavior of the function other than * the designated outputs (output, olen, return value). Otherwise * this would open the execution of the function to * side-channel-based variants of the Bleichenbacher padding oracle * attack. Potential side channels include overall timing, memory * access patterns (especially visible to an adversary who has access * to a shared memory cache), and branches (especially visible to * an adversary who has access to a shared code cache or to a shared * branch predictor). */ size_t pad_count = 0; unsigned bad = 0; unsigned char pad_done = 0; size_t plaintext_size = 0; unsigned output_too_large; RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( output_max_len == 0 || output != NULL ); RSA_VALIDATE_RET( input != NULL ); RSA_VALIDATE_RET( olen != NULL ); ilen = ctx->len; plaintext_max_size = ( output_max_len > ilen - 11 ? ilen - 11 : output_max_len ); if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); if( ilen < 16 || ilen > sizeof( buf ) ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); ret = ( mode == MBEDTLS_RSA_PUBLIC ) ? mbedtls_rsa_public( ctx, input, buf ) : mbedtls_rsa_private( ctx, f_rng, p_rng, input, buf ); if( ret != 0 ) goto cleanup; /* Check and get padding length in constant time and constant * memory trace. The first byte must be 0. */ bad |= buf[0]; if( mode == MBEDTLS_RSA_PRIVATE ) { /* Decode EME-PKCS1-v1_5 padding: 0x00 || 0x02 || PS || 0x00 * where PS must be at least 8 nonzero bytes. */ bad |= buf[1] ^ MBEDTLS_RSA_CRYPT; /* Read the whole buffer. Set pad_done to nonzero if we find * the 0x00 byte and remember the padding length in pad_count. */ for( i = 2; i < ilen; i++ ) { pad_done |= ((buf[i] | (unsigned char)-buf[i]) >> 7) ^ 1; pad_count += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1; } } else { /* Decode EMSA-PKCS1-v1_5 padding: 0x00 || 0x01 || PS || 0x00 * where PS must be at least 8 bytes with the value 0xFF. */ bad |= buf[1] ^ MBEDTLS_RSA_SIGN; /* Read the whole buffer. Set pad_done to nonzero if we find * the 0x00 byte and remember the padding length in pad_count. * If there's a non-0xff byte in the padding, the padding is bad. */ for( i = 2; i < ilen; i++ ) { pad_done |= if_int( buf[i], 0, 1 ); pad_count += if_int( pad_done, 0, 1 ); bad |= if_int( pad_done, 0, buf[i] ^ 0xFF ); } } /* If pad_done is still zero, there's no data, only unfinished padding. */ bad |= if_int( pad_done, 0, 1 ); /* There must be at least 8 bytes of padding. */ bad |= size_greater_than( 8, pad_count ); /* If the padding is valid, set plaintext_size to the number of * remaining bytes after stripping the padding. If the padding * is invalid, avoid leaking this fact through the size of the * output: use the maximum message size that fits in the output * buffer. Do it without branches to avoid leaking the padding * validity through timing. RSA keys are small enough that all the * size_t values involved fit in unsigned int. */ plaintext_size = if_int( bad, (unsigned) plaintext_max_size, (unsigned) ( ilen - pad_count - 3 ) ); /* Set output_too_large to 0 if the plaintext fits in the output * buffer and to 1 otherwise. */ output_too_large = size_greater_than( plaintext_size, plaintext_max_size ); /* Set ret without branches to avoid timing attacks. Return: * - INVALID_PADDING if the padding is bad (bad != 0). * - OUTPUT_TOO_LARGE if the padding is good but the decrypted * plaintext does not fit in the output buffer. * - 0 if the padding is correct. */ ret = - (int) if_int( bad, - MBEDTLS_ERR_RSA_INVALID_PADDING, if_int( output_too_large, - MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE, 0 ) ); /* If the padding is bad or the plaintext is too large, zero the * data that we're about to copy to the output buffer. * We need to copy the same amount of data * from the same buffer whether the padding is good or not to * avoid leaking the padding validity through overall timing or * through memory or cache access patterns. */ bad = all_or_nothing_int( bad | output_too_large ); for( i = 11; i < ilen; i++ ) buf[i] &= ~bad; /* If the plaintext is too large, truncate it to the buffer size. * Copy anyway to avoid revealing the length through timing, because * revealing the length is as bad as revealing the padding validity * for a Bleichenbacher attack. */ plaintext_size = if_int( output_too_large, (unsigned) plaintext_max_size, (unsigned) plaintext_size ); /* Move the plaintext to the leftmost position where it can start in * the working buffer, i.e. make it start plaintext_max_size from * the end of the buffer. Do this with a memory access trace that * does not depend on the plaintext size. After this move, the * starting location of the plaintext is no longer sensitive * information. */ mem_move_to_left( buf + ilen - plaintext_max_size, plaintext_max_size, plaintext_max_size - plaintext_size ); /* Finally copy the decrypted plaintext plus trailing zeros into the output * buffer. If output_max_len is 0, then output may be an invalid pointer * and the result of memcpy() would be undefined; prevent undefined * behavior making sure to depend only on output_max_len (the size of the * user-provided output buffer), which is independent from plaintext * length, validity of padding, success of the decryption, and other * secrets. */ if( output_max_len != 0 ) memcpy( output, buf + ilen - plaintext_max_size, plaintext_max_size ); /* Report the amount of data we copied to the output buffer. In case * of errors (bad padding or output too large), the value of *olen * when this function returns is not specified. Making it equivalent * to the good case limits the risks of leaking the padding validity. */ *olen = plaintext_size; cleanup: mbedtls_platform_zeroize( buf, sizeof( buf ) ); return( ret ); } #endif /* MBEDTLS_PKCS1_V15 */ /* * Do an RSA operation, then remove the message padding */ int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, size_t *olen, const unsigned char *input, unsigned char *output, size_t output_max_len) { RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( output_max_len == 0 || output != NULL ); RSA_VALIDATE_RET( input != NULL ); RSA_VALIDATE_RET( olen != NULL ); switch( ctx->padding ) { #if defined(MBEDTLS_PKCS1_V15) case MBEDTLS_RSA_PKCS_V15: return mbedtls_rsa_rsaes_pkcs1_v15_decrypt( ctx, f_rng, p_rng, mode, olen, input, output, output_max_len ); #endif #if defined(MBEDTLS_PKCS1_V21) case MBEDTLS_RSA_PKCS_V21: return mbedtls_rsa_rsaes_oaep_decrypt( ctx, f_rng, p_rng, mode, NULL, 0, olen, input, output, output_max_len ); #endif default: return( MBEDTLS_ERR_RSA_INVALID_PADDING ); } } /* * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function */ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, unsigned char *sig ) { size_t olen; unsigned char *p = sig; unsigned char salt[MBEDTLS_MD_MAX_SIZE]; size_t slen, min_slen, hlen, offset = 0; int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t msb; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hashlen == 0 ) || hash != NULL ); RSA_VALIDATE_RET( sig != NULL ); if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); if( !f_rng ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); olen = ctx->len; if( md_alg != MBEDTLS_MD_NONE ) { /* Gather length of hash to sign */ md_info = mbedtls_md_info_from_type( md_alg ); if( !md_info ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); hashlen = mbedtls_md_get_size( md_info ); } md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id ); if( !md_info ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); hlen = mbedtls_md_get_size( md_info ); /* Calculate the largest possible salt length. Normally this is the hash * length, which is the maximum length the salt can have. If there is not * enough room, use the maximum salt length that fits. The constraint is * that the hash length plus the salt length plus 2 bytes must be at most * the key length. This complies with FIPS 186-4 §5.5 (e) and RFC 8017 * (PKCS#1 v2.2) §9.1.1 step 3. */ min_slen = hlen - 2; if( olen < hlen + min_slen + 2 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); else if( olen >= hlen + hlen + 2 ) slen = hlen; else slen = olen - hlen - 2; mbedtls_platform_zeroize( sig, olen ); /* Generate salt of length slen */ if( ( ret = f_rng( p_rng, salt, slen ) ) != 0 ) return( MBEDTLS_ERR_RSA_RNG_FAILED + ret ); /* Note: EMSA-PSS encoding is over the length of N - 1 bits */ msb = mbedtls_mpi_bitlen( &ctx->N ) - 1; p += olen - hlen - slen - 2; *p++ = 0x01; memcpy( p, salt, slen ); p += slen; mbedtls_md_init( &md_ctx ); if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 ) goto exit; /* Generate H = Hash( M' ) */ if( ( ret = mbedtls_md_starts( &md_ctx ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_update( &md_ctx, p, 8 ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_update( &md_ctx, hash, hashlen ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_update( &md_ctx, salt, slen ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_finish( &md_ctx, p ) ) != 0 ) goto exit; /* Compensate for boundary condition when applying mask */ if( msb % 8 == 0 ) offset = 1; /* maskedDB: Apply dbMask to DB */ if( ( ret = mgf_mask( sig + offset, olen - hlen - 1 - offset, p, hlen, &md_ctx ) ) != 0 ) goto exit; msb = mbedtls_mpi_bitlen( &ctx->N ) - 1; sig[0] &= 0xFF >> ( olen * 8 - msb ); p += hlen; *p++ = 0xBC; mbedtls_platform_zeroize( salt, sizeof( salt ) ); exit: mbedtls_md_free( &md_ctx ); if( ret != 0 ) return( ret ); return( ( mode == MBEDTLS_RSA_PUBLIC ) ? mbedtls_rsa_public( ctx, sig, sig ) : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, sig ) ); } #if defined(MBEDTLS_PKCS1_V15) /* * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function */ /* Construct a PKCS v1.5 encoding of a hashed message * * This is used both for signature generation and verification. * * Parameters: * - md_alg: Identifies the hash algorithm used to generate the given hash; * MBEDTLS_MD_NONE if raw data is signed. * - hashlen: Length of hash in case hashlen is MBEDTLS_MD_NONE. * - hash: Buffer containing the hashed message or the raw data. * - dst_len: Length of the encoded message. * - dst: Buffer to hold the encoded message. * * Assumptions: * - hash has size hashlen if md_alg == MBEDTLS_MD_NONE. * - hash has size corresponding to md_alg if md_alg != MBEDTLS_MD_NONE. * - dst points to a buffer of size at least dst_len. * */ static int rsa_rsassa_pkcs1_v15_encode( mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, size_t dst_len, unsigned char *dst ) { size_t oid_size = 0; size_t nb_pad = dst_len; unsigned char *p = dst; const char *oid = NULL; /* Are we signing hashed or raw data? */ if( md_alg != MBEDTLS_MD_NONE ) { const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg ); if( !md_info ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); if( mbedtls_oid_get_oid_by_md( md_alg, &oid, &oid_size ) != 0 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); hashlen = mbedtls_md_get_size( md_info ); /* Double-check that 8 + hashlen + oid_size can be used as a * 1-byte ASN.1 length encoding and that there's no overflow. */ if( 8 + hashlen + oid_size >= 0x80 || 10 + hashlen < hashlen || 10 + hashlen + oid_size < 10 + hashlen ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); /* * Static bounds check: * - Need 10 bytes for five tag-length pairs. * (Insist on 1-byte length encodings to protect against variants of * Bleichenbacher's forgery attack against lax PKCS#1v1.5 verification) * - Need hashlen bytes for hash * - Need oid_size bytes for hash alg OID. */ if( nb_pad < 10 + hashlen + oid_size ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); nb_pad -= 10 + hashlen + oid_size; } else { if( nb_pad < hashlen ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); nb_pad -= hashlen; } /* Need space for signature header and padding delimiter (3 bytes), * and 8 bytes for the minimal padding */ if( nb_pad < 3 + 8 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); nb_pad -= 3; /* Now nb_pad is the amount of memory to be filled * with padding, and at least 8 bytes long. */ /* Write signature header and padding */ *p++ = 0; *p++ = MBEDTLS_RSA_SIGN; memset( p, 0xFF, nb_pad ); p += nb_pad; *p++ = 0; /* Are we signing raw data? */ if( md_alg == MBEDTLS_MD_NONE ) { memcpy( p, hash, hashlen ); return( 0 ); } /* Signing hashed data, add corresponding ASN.1 structure * * DigestInfo ::= SEQUENCE { * digestAlgorithm DigestAlgorithmIdentifier, * digest Digest } * DigestAlgorithmIdentifier ::= AlgorithmIdentifier * Digest ::= OCTET STRING * * Schematic: * TAG-SEQ + LEN [ TAG-SEQ + LEN [ TAG-OID + LEN [ OID ] * TAG-NULL + LEN [ NULL ] ] * TAG-OCTET + LEN [ HASH ] ] */ *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED; *p++ = (unsigned char)( 0x08 + oid_size + hashlen ); *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED; *p++ = (unsigned char)( 0x04 + oid_size ); *p++ = MBEDTLS_ASN1_OID; *p++ = (unsigned char) oid_size; memcpy( p, oid, oid_size ); p += oid_size; *p++ = MBEDTLS_ASN1_NULL; *p++ = 0x00; *p++ = MBEDTLS_ASN1_OCTET_STRING; *p++ = (unsigned char) hashlen; memcpy( p, hash, hashlen ); p += hashlen; /* Just a sanity-check, should be automatic * after the initial bounds check. */ if( p != dst + dst_len ) { mbedtls_platform_zeroize( dst, dst_len ); return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); } return( 0 ); } /* * Do an RSA operation to sign the message digest */ int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, unsigned char *sig ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char *sig_try = NULL, *verif = NULL; RSA_VALIDATE_RET( ctx ); RSA_VALIDATE_RET( sig ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( hash || ( !hashlen && md_alg == MBEDTLS_MD_NONE ) ); if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); /* * Prepare PKCS1-v1.5 encoding (padding and hash identifier) */ if( ( ret = rsa_rsassa_pkcs1_v15_encode( md_alg, hashlen, hash, ctx->len, sig ) ) != 0 ) return( ret ); /* * Call respective RSA primitive */ if( mode == MBEDTLS_RSA_PUBLIC ) { /* Skip verification on a public key operation */ return( mbedtls_rsa_public( ctx, sig, sig ) ); } /* Private key operation * * In order to prevent Lenstra's attack, make the signature in a * temporary buffer and check it before returning it. */ sig_try = mbedtls_calloc( 1, ctx->len ); if( !sig_try ) return( MBEDTLS_ERR_MPI_ALLOC_FAILED ); verif = mbedtls_calloc( 1, ctx->len ); if( !verif ) { mbedtls_free( sig_try ); return( MBEDTLS_ERR_MPI_ALLOC_FAILED ); } MBEDTLS_MPI_CHK( mbedtls_rsa_private( ctx, f_rng, p_rng, sig, sig_try ) ); MBEDTLS_MPI_CHK( mbedtls_rsa_public( ctx, sig_try, verif ) ); if( timingsafe_bcmp( verif, sig, ctx->len ) ) { ret = MBEDTLS_ERR_RSA_PRIVATE_FAILED; goto cleanup; } memcpy( sig, sig_try, ctx->len ); cleanup: mbedtls_free( sig_try ); mbedtls_free( verif ); return( ret ); } #endif /* MBEDTLS_PKCS1_V15 */ /* * Do an RSA operation to sign the message digest */ int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, unsigned char *sig ) { RSA_VALIDATE_RET( ctx ); RSA_VALIDATE_RET( sig ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( hash || ( !hashlen && md_alg == MBEDTLS_MD_NONE ) ); switch( ctx->padding ) { #if defined(MBEDTLS_PKCS1_V15) case MBEDTLS_RSA_PKCS_V15: return mbedtls_rsa_rsassa_pkcs1_v15_sign( ctx, f_rng, p_rng, mode, md_alg, hashlen, hash, sig ); #endif #if defined(MBEDTLS_PKCS1_V21) case MBEDTLS_RSA_PKCS_V21: return mbedtls_rsa_rsassa_pss_sign( ctx, f_rng, p_rng, mode, md_alg, hashlen, hash, sig ); #endif default: return( MBEDTLS_ERR_RSA_INVALID_PADDING ); } } #if defined(MBEDTLS_PKCS1_V15) /** * \brief This function performs a PKCS#1 v2.1 PSS verification * operation (RSASSA-PSS-VERIFY). * * The hash function for the MGF mask generating function * is that specified in \p mgf1_hash_id. * * \note The \p sig buffer must be as large as the size * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. * * \note The \p hash_id in the RSA context is ignored. * * \param ctx The initialized RSA public key context to use. * \param f_rng The RNG function to use. If \p mode is #MBEDTLS_RSA_PRIVATE, * this is used for blinding and should be provided; see * mbedtls_rsa_private() for more. Otherwise, it is ignored. * \param p_rng The RNG context to be passed to \p f_rng. This may be * \c NULL if \p f_rng is \c NULL or doesn't need a context. * \param mode The mode of operation. This must be either * #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. * \param md_alg The message-digest algorithm used to hash the original data. * Use #MBEDTLS_MD_NONE for signing raw data. * \param hashlen The length of the message digest. * This is only used if \p md_alg is #MBEDTLS_MD_NONE. * \param hash The buffer holding the message digest or raw data. * If \p md_alg is #MBEDTLS_MD_NONE, this must be a readable * buffer of length \p hashlen Bytes. If \p md_alg is not * #MBEDTLS_MD_NONE, it must be a readable buffer of length * the size of the hash corresponding to \p md_alg. * \param mgf1_hash_id The message digest used for mask generation. * \param expected_salt_len The length of the salt used in padding. Use * #MBEDTLS_RSA_SALT_LEN_ANY to accept any salt length. * \param sig The buffer holding the signature. This must be a readable * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes * for an 2048-bit RSA modulus. * * \return \c 0 if the verify operation was successful. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, mbedtls_md_type_t mgf1_hash_id, int expected_salt_len, const unsigned char *sig ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t siglen; unsigned char *p; unsigned char *hash_start; unsigned char result[MBEDTLS_MD_MAX_SIZE]; unsigned char zeros[8]; unsigned int hlen; size_t observed_salt_len, msb; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; unsigned char buf[MBEDTLS_MPI_MAX_SIZE]; RSA_VALIDATE_RET( ctx ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( sig ); RSA_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hashlen == 0 ) || hash ); if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); siglen = ctx->len; if( siglen < 16 || siglen > sizeof( buf ) ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); ret = ( mode == MBEDTLS_RSA_PUBLIC ) ? mbedtls_rsa_public( ctx, sig, buf ) : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, buf ); if( ret != 0 ) return( ret ); p = buf; if( buf[siglen - 1] != 0xBC ) return( MBEDTLS_ERR_RSA_INVALID_PADDING ); if( md_alg != MBEDTLS_MD_NONE ) { /* Gather length of hash to sign */ md_info = mbedtls_md_info_from_type( md_alg ); if( !md_info ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); hashlen = mbedtls_md_get_size( md_info ); } md_info = mbedtls_md_info_from_type( mgf1_hash_id ); if( !md_info ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); hlen = mbedtls_md_get_size( md_info ); memset( zeros, 0, 8 ); /* * Note: EMSA-PSS verification is over the length of N - 1 bits */ msb = mbedtls_mpi_bitlen( &ctx->N ) - 1; if( buf[0] >> ( 8 - siglen * 8 + msb ) ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); /* Compensate for boundary condition when applying mask */ if( msb % 8 == 0 ) { p++; siglen -= 1; } if( siglen < hlen + 2 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); hash_start = p + siglen - hlen - 1; mbedtls_md_init( &md_ctx ); if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 ) goto exit; ret = mgf_mask( p, siglen - hlen - 1, hash_start, hlen, &md_ctx ); if( ret != 0 ) goto exit; buf[0] &= 0xFF >> ( siglen * 8 - msb ); while( p < hash_start - 1 && *p == 0 ) p++; if( *p++ != 0x01 ) { ret = MBEDTLS_ERR_RSA_INVALID_PADDING; goto exit; } observed_salt_len = hash_start - p; if( expected_salt_len != MBEDTLS_RSA_SALT_LEN_ANY && observed_salt_len != (size_t) expected_salt_len ) { ret = MBEDTLS_ERR_RSA_INVALID_PADDING; goto exit; } /* * Generate H = Hash( M' ) */ if(( ret = mbedtls_md_starts( &md_ctx ) )) goto exit; if(( ret = mbedtls_md_update( &md_ctx, zeros, 8 ) )) goto exit; if(( ret = mbedtls_md_update( &md_ctx, hash, hashlen ) )) goto exit; if(( ret = mbedtls_md_update( &md_ctx, p, observed_salt_len ) )) goto exit; if(( ret = mbedtls_md_finish( &md_ctx, result ) )) goto exit; if ( timingsafe_bcmp( hash_start, result, hlen ) ) { ret = MBEDTLS_ERR_RSA_VERIFY_FAILED; goto exit; } exit: mbedtls_md_free( &md_ctx ); return( ret ); } /** * \brief This function performs a PKCS#1 v2.1 PSS verification * operation (RSASSA-PSS-VERIFY). * * The hash function for the MGF mask generating function * is that specified in the RSA context. * * \note The \p hash_id in the RSA context is the one used for the * verification. \p md_alg in the function call is the type of * hash that is verified. According to <em>RFC-3447: Public-Key * Cryptography Standards (PKCS) #1 v2.1: RSA Cryptography * Specifications</em> it is advised to keep both hashes the * same. If \p hash_id in the RSA context is unset, * the \p md_alg from the function call is used. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library * are likely to remove the \p mode argument and have it * implicitly set to #MBEDTLS_RSA_PUBLIC. * * \param ctx The initialized RSA public key context to use. * \param f_rng The RNG function to use. If \p mode is #MBEDTLS_RSA_PRIVATE, * this is used for blinding and should be provided; see * mbedtls_rsa_private() for more. Otherwise, it is ignored. * \param p_rng The RNG context to be passed to \p f_rng. This may be * \c NULL if \p f_rng is \c NULL or doesn't need a context. * \param mode The mode of operation. This must be either * #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE (deprecated). * \param md_alg The message-digest algorithm used to hash the original data. * Use #MBEDTLS_MD_NONE for signing raw data. * \param hashlen The length of the message digest. * This is only used if \p md_alg is #MBEDTLS_MD_NONE. * \param hash The buffer holding the message digest or raw data. * If \p md_alg is #MBEDTLS_MD_NONE, this must be a readable * buffer of length \p hashlen Bytes. If \p md_alg is not * #MBEDTLS_MD_NONE, it must be a readable buffer of length * the size of the hash corresponding to \p md_alg. * \param sig The buffer holding the signature. This must be a readable * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes * for an 2048-bit RSA modulus. * * \return \c 0 if the verify operation was successful. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, const unsigned char *sig ) { mbedtls_md_type_t mgf1_hash_id; RSA_VALIDATE_RET( ctx ); RSA_VALIDATE_RET( sig ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( hash || ( !hashlen && md_alg == MBEDTLS_MD_NONE ) ); mgf1_hash_id = ( ctx->hash_id != MBEDTLS_MD_NONE ) ? (mbedtls_md_type_t) ctx->hash_id : md_alg; return( mbedtls_rsa_rsassa_pss_verify_ext( ctx, f_rng, p_rng, mode, md_alg, hashlen, hash, mgf1_hash_id, MBEDTLS_RSA_SALT_LEN_ANY, sig ) ); } /** * \brief This function performs a PKCS#1 v1.5 verification * operation (RSASSA-PKCS1-v1_5-VERIFY). * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library * are likely to remove the \p mode argument and have it * set to #MBEDTLS_RSA_PUBLIC. * * \param ctx The initialized RSA public key context to use. * \param f_rng The RNG function to use. If \p mode is #MBEDTLS_RSA_PRIVATE, * this is used for blinding and should be provided; see * mbedtls_rsa_private() for more. Otherwise, it is ignored. * \param p_rng The RNG context to be passed to \p f_rng. This may be * \c NULL if \p f_rng is \c NULL or doesn't need a context. * \param mode The mode of operation. This must be either * #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE (deprecated). * \param md_alg The message-digest algorithm used to hash the original data. * Use #MBEDTLS_MD_NONE for signing raw data. * \param hashlen The length of the message digest. * This is only used if \p md_alg is #MBEDTLS_MD_NONE. * \param hash The buffer holding the message digest or raw data. * If \p md_alg is #MBEDTLS_MD_NONE, this must be a readable * buffer of length \p hashlen Bytes. If \p md_alg is not * #MBEDTLS_MD_NONE, it must be a readable buffer of length * the size of the hash corresponding to \p md_alg. * \param sig The buffer holding the signature. This must be a readable * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes * for an 2048-bit RSA modulus. * * \return \c 0 if the verify operation was successful. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, const unsigned char *sig ) { int ret = 0; size_t sig_len; unsigned char *encoded = NULL, *encoded_expected = NULL; RSA_VALIDATE_RET( ctx != NULL ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( sig != NULL ); RSA_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hashlen == 0 ) || hash != NULL ); sig_len = ctx->len; if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); /* * Prepare expected PKCS1 v1.5 encoding of hash. */ if( ( encoded = mbedtls_calloc( 1, sig_len ) ) == NULL || ( encoded_expected = mbedtls_calloc( 1, sig_len ) ) == NULL ) { ret = MBEDTLS_ERR_MPI_ALLOC_FAILED; goto cleanup; } if( ( ret = rsa_rsassa_pkcs1_v15_encode( md_alg, hashlen, hash, sig_len, encoded_expected ) ) != 0 ) goto cleanup; /* * Apply RSA primitive to get what should be PKCS1 encoded hash. */ ret = ( mode == MBEDTLS_RSA_PUBLIC ) ? mbedtls_rsa_public( ctx, sig, encoded ) : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, encoded ); if( ret != 0 ) goto cleanup; /* * Compare */ if( ( ret = timingsafe_bcmp( encoded, encoded_expected, sig_len ) ) ) { ret = MBEDTLS_ERR_RSA_VERIFY_FAILED; goto cleanup; } cleanup: if( encoded ) { mbedtls_platform_zeroize( encoded, sig_len ); mbedtls_free( encoded ); } if( encoded_expected ) { mbedtls_platform_zeroize( encoded_expected, sig_len ); mbedtls_free( encoded_expected ); } return( ret ); } #endif /* MBEDTLS_PKCS1_V15 */ /* * Do an RSA operation and check the message digest */ int mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, const unsigned char *sig ) { RSA_VALIDATE_RET( ctx ); RSA_VALIDATE_RET( sig ); RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE || mode == MBEDTLS_RSA_PUBLIC ); RSA_VALIDATE_RET( hash || ( !hashlen && md_alg == MBEDTLS_MD_NONE ) ); switch( ctx->padding ) { #if defined(MBEDTLS_PKCS1_V15) case MBEDTLS_RSA_PKCS_V15: return mbedtls_rsa_rsassa_pkcs1_v15_verify( ctx, f_rng, p_rng, mode, md_alg, hashlen, hash, sig ); #endif #if defined(MBEDTLS_PKCS1_V21) case MBEDTLS_RSA_PKCS_V21: return mbedtls_rsa_rsassa_pss_verify( ctx, f_rng, p_rng, mode, md_alg, hashlen, hash, sig ); #endif default: return( MBEDTLS_ERR_RSA_INVALID_PADDING ); } } /** * \brief This function copies the components of an RSA context. * * \param dst The destination context. This must be initialized. * \param src The source context. This must be initialized. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory allocation failure. */ int mbedtls_rsa_copy( mbedtls_rsa_context *dst, const mbedtls_rsa_context *src ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; RSA_VALIDATE_RET( dst ); RSA_VALIDATE_RET( src ); dst->len = src->len; MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->N, &src->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->E, &src->E ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->D, &src->D ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->P, &src->P ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Q, &src->Q ) ); #if !defined(MBEDTLS_RSA_NO_CRT) MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->DP, &src->DP ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->DQ, &src->DQ ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->QP, &src->QP ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RP, &src->RP ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RQ, &src->RQ ) ); #endif MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RN, &src->RN ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Vi, &src->Vi ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Vf, &src->Vf ) ); dst->padding = src->padding; dst->hash_id = src->hash_id; cleanup: if( ret != 0 ) mbedtls_rsa_free( dst ); return( ret ); } /** * \brief This function frees the components of an RSA key. * * \param ctx The RSA context to free. May be \c NULL, in which case * this function is a no-op. If it is not \c NULL, it must * point to an initialized RSA context. */ void mbedtls_rsa_free( mbedtls_rsa_context *ctx ) { if( !ctx ) return; mbedtls_mpi_free( &ctx->Vi ); mbedtls_mpi_free( &ctx->Vf ); mbedtls_mpi_free( &ctx->RN ); mbedtls_mpi_free( &ctx->D ); mbedtls_mpi_free( &ctx->Q ); mbedtls_mpi_free( &ctx->P ); mbedtls_mpi_free( &ctx->E ); mbedtls_mpi_free( &ctx->N ); #if !defined(MBEDTLS_RSA_NO_CRT) mbedtls_mpi_free( &ctx->RQ ); mbedtls_mpi_free( &ctx->RP ); mbedtls_mpi_free( &ctx->QP ); mbedtls_mpi_free( &ctx->DQ ); mbedtls_mpi_free( &ctx->DP ); #endif /* MBEDTLS_RSA_NO_CRT */ } #if defined(MBEDTLS_SELF_TEST) /* * Example RSA-1024 keypair, for test purposes */ #define PT_LEN 24 #define KEY_LEN 128 #define RSA_E "10001" #define RSA_N "9292758453063D803DD603D5E777D788" \ "8ED1D5BF35786190FA2F23EBC0848AEA" \ "DDA92CA6C3D80B32C4D109BE0F36D6AE" \ "7130B9CED7ACDF54CFC7555AC14EEBAB" \ "93A89813FBF3C4F8066D2D800F7C38A8" \ "1AE31942917403FF4946B0A83D3D3E05" \ "EE57C6F5F5606FB5D4BC6CD34EE0801A" \ "5E94BB77B07507233A0BC7BAC8F90F79" #define RSA_D "24BF6185468786FDD303083D25E64EFC" \ "66CA472BC44D253102F8B4A9D3BFA750" \ "91386C0077937FE33FA3252D28855837" \ "AE1B484A8A9A45F7EE8C0C634F99E8CD" \ "DF79C5CE07EE72C7F123142198164234" \ "CABB724CF78B8173B9F880FC86322407" \ "AF1FEDFDDE2BEB674CA15F3E81A1521E" \ "071513A1E85B5DFA031F21ECAE91A34D" #define RSA_P "C36D0EB7FCD285223CFB5AABA5BDA3D8" \ "2C01CAD19EA484A87EA4377637E75500" \ "FCB2005C5C7DD6EC4AC023CDA285D796" \ "C3D9E75E1EFC42488BB4F1D13AC30A57" #define RSA_Q "C000DF51A7C77AE8D7C7370C1FF55B69" \ "E211C2B9E5DB1ED0BF61D0D9899620F4" \ "910E4168387E3C30AA1E00C339A79508" \ "8452DD96A9A5EA5D9DCA68DA636032AF" #define RSA_PT "\xAA\xBB\xCC\x03\x02\x01\x00\xFF\xFF\xFF\xFF\xFF" \ "\x11\x22\x33\x0A\x0B\x0C\xCC\xDD\xDD\xDD\xDD\xDD" #if defined(MBEDTLS_PKCS1_V15) static int myrand( void *rng_state, unsigned char *output, size_t len ) { #if !defined(__OpenBSD__) && !defined(__NetBSD__) size_t i; for( i = 0; i < len; ++i ) output[i] = rand(); #else arc4random_buf( output, len ); #endif /* !OpenBSD && !NetBSD */ return( 0 ); } #endif /* MBEDTLS_PKCS1_V15 */ /** * \brief The RSA checkup routine. * * \return \c 0 on success. * \return \c 1 on failure. */ int mbedtls_rsa_self_test( int verbose ) { int ret = 0; #if defined(MBEDTLS_PKCS1_V15) size_t len; mbedtls_rsa_context rsa; unsigned char rsa_plaintext[PT_LEN]; unsigned char rsa_decrypted[PT_LEN]; unsigned char rsa_ciphertext[KEY_LEN]; #if defined(MBEDTLS_SHA1_C) unsigned char sha1sum[20]; #endif mbedtls_mpi K; mbedtls_mpi_init( &K ); mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 ); MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_N ) ); MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, &K, NULL, NULL, NULL, NULL ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_P ) ); MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, &K, NULL, NULL, NULL ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_Q ) ); MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, NULL, &K, NULL, NULL ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_D ) ); MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, NULL, NULL, &K, NULL ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_E ) ); MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, NULL, NULL, NULL, &K ) ); MBEDTLS_MPI_CHK( mbedtls_rsa_complete( &rsa ) ); if( verbose != 0 ) mbedtls_printf( " RSA key validation: " ); if( mbedtls_rsa_check_pubkey( &rsa ) != 0 || mbedtls_rsa_check_privkey( &rsa ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); ret = 1; goto cleanup; } if( verbose != 0 ) mbedtls_printf( "passed\n PKCS#1 encryption : " ); memcpy( rsa_plaintext, RSA_PT, PT_LEN ); if( mbedtls_rsa_pkcs1_encrypt( &rsa, myrand, NULL, MBEDTLS_RSA_PUBLIC, PT_LEN, rsa_plaintext, rsa_ciphertext ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); ret = 1; goto cleanup; } if( verbose != 0 ) mbedtls_printf( "passed\n PKCS#1 decryption : " ); if( mbedtls_rsa_pkcs1_decrypt( &rsa, myrand, NULL, MBEDTLS_RSA_PRIVATE, &len, rsa_ciphertext, rsa_decrypted, sizeof(rsa_decrypted) ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); ret = 1; goto cleanup; } if( timingsafe_bcmp( rsa_decrypted, rsa_plaintext, len ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); ret = 1; goto cleanup; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); #if defined(MBEDTLS_SHA1_C) if( verbose != 0 ) mbedtls_printf( " PKCS#1 data sign : " ); if( mbedtls_sha1_ret( rsa_plaintext, PT_LEN, sha1sum ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); return( 1 ); } if( mbedtls_rsa_pkcs1_sign( &rsa, myrand, NULL, MBEDTLS_RSA_PRIVATE, MBEDTLS_MD_SHA1, 0, sha1sum, rsa_ciphertext ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); ret = 1; goto cleanup; } if( verbose != 0 ) mbedtls_printf( "passed\n PKCS#1 sig. verify: " ); if( mbedtls_rsa_pkcs1_verify( &rsa, NULL, NULL, MBEDTLS_RSA_PUBLIC, MBEDTLS_MD_SHA1, 0, sha1sum, rsa_ciphertext ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); ret = 1; goto cleanup; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); #endif /* MBEDTLS_SHA1_C */ if( verbose != 0 ) mbedtls_printf( "\n" ); cleanup: mbedtls_mpi_free( &K ); mbedtls_rsa_free( &rsa ); #else /* MBEDTLS_PKCS1_V15 */ ((void) verbose); #endif /* MBEDTLS_PKCS1_V15 */ return( ret ); } #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_RSA_C */
93,683
2,537
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/ecdsa.h
#ifndef MBEDTLS_ECDSA_H_ #define MBEDTLS_ECDSA_H_ #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/ecp.h" #include "third_party/mbedtls/md.h" COSMOPOLITAN_C_START_ /* clang-format off */ /** * \brief Maximum ECDSA signature size for a given curve bit size * * \param bits Curve size in bits * \return Maximum signature size in bytes * * \note This macro returns a compile-time constant if its argument * is one. It may evaluate its argument multiple times. */ /* * Ecdsa-Sig-Value ::= SEQUENCE { * r INTEGER, * s INTEGER * } * * For each of r and s, the value (V) may include an extra initial "0" bit. */ #define MBEDTLS_ECDSA_MAX_SIG_LEN( bits ) \ ( /*T,L of SEQUENCE*/ ( ( bits ) >= 61 * 8 ? 3 : 2 ) + \ /*T,L of r,s*/ 2 * ( ( ( bits ) >= 127 * 8 ? 3 : 2 ) + \ /*V of r,s*/ ( ( bits ) + 8 ) / 8 ) ) /** The maximal size of an ECDSA signature in Bytes. */ #define MBEDTLS_ECDSA_MAX_LEN MBEDTLS_ECDSA_MAX_SIG_LEN( MBEDTLS_ECP_MAX_BITS ) /** * \brief The ECDSA context structure. * * \warning Performing multiple operations concurrently on the same * ECDSA context is not supported; objects of this type * should not be shared between multiple threads. */ typedef mbedtls_ecp_keypair mbedtls_ecdsa_context; #if defined(MBEDTLS_ECP_RESTARTABLE) /** * \brief Internal restart context for ecdsa_verify() * * \note Opaque struct, defined in ecdsa.c */ typedef struct mbedtls_ecdsa_restart_ver mbedtls_ecdsa_restart_ver_ctx; /** * \brief Internal restart context for ecdsa_sign() * * \note Opaque struct, defined in ecdsa.c */ typedef struct mbedtls_ecdsa_restart_sig mbedtls_ecdsa_restart_sig_ctx; /** * \brief Internal restart context for ecdsa_sign_det() * * \note Opaque struct, defined in ecdsa.c */ typedef struct mbedtls_ecdsa_restart_det mbedtls_ecdsa_restart_det_ctx; /** * \brief General context for resuming ECDSA operations */ typedef struct { mbedtls_ecp_restart_ctx ecp; /*!< base context for ECP restart and shared administrative info */ mbedtls_ecdsa_restart_ver_ctx *ver; /*!< ecdsa_verify() sub-context */ mbedtls_ecdsa_restart_sig_ctx *sig; /*!< ecdsa_sign() sub-context */ #if defined(MBEDTLS_ECDSA_DETERMINISTIC) mbedtls_ecdsa_restart_det_ctx *det; /*!< ecdsa_sign_det() sub-context */ #endif } mbedtls_ecdsa_restart_ctx; #else /* MBEDTLS_ECP_RESTARTABLE */ /* Now we can declare functions that take a pointer to that */ typedef void mbedtls_ecdsa_restart_ctx; #endif /* MBEDTLS_ECP_RESTARTABLE */ /** * \brief This function checks whether a given group can be used * for ECDSA. * * \param gid The ECP group ID to check. * * \return \c 1 if the group can be used, \c 0 otherwise */ int mbedtls_ecdsa_can_do( mbedtls_ecp_group_id gid ); /** * \brief This function computes the ECDSA signature of a * previously-hashed message. * * \note The deterministic version implemented in * mbedtls_ecdsa_sign_det() is usually preferred. * * \note If the bitlength of the message hash is larger than the * bitlength of the group order, then the hash is truncated * as defined in <em>Standards for Efficient Cryptography Group * (SECG): SEC1 Elliptic Curve Cryptography</em>, section * 4.1.3, step 5. * * \see ecp.h * * \param grp The context for the elliptic curve to use. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param r The MPI context in which to store the first part * the signature. This must be initialized. * \param s The MPI context in which to store the second part * the signature. This must be initialized. * \param d The private signing key. This must be initialized. * \param buf The content to be signed. This is usually the hash of * the original data to be signed. This must be a readable * buffer of length \p blen Bytes. It may be \c NULL if * \p blen is zero. * \param blen The length of \p buf in Bytes. * \param f_rng The RNG function. This must not be \c NULL. * \param p_rng The RNG context to be passed to \p f_rng. This may be * \c NULL if \p f_rng doesn't need a context parameter. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX * or \c MBEDTLS_MPI_XXX error code on failure. */ int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief This function computes the ECDSA signature of a * previously-hashed message, deterministic version. * * For more information, see <em>RFC-6979: Deterministic * Usage of the Digital Signature Algorithm (DSA) and Elliptic * Curve Digital Signature Algorithm (ECDSA)</em>. * * \note If the bitlength of the message hash is larger than the * bitlength of the group order, then the hash is truncated as * defined in <em>Standards for Efficient Cryptography Group * (SECG): SEC1 Elliptic Curve Cryptography</em>, section * 4.1.3, step 5. * * \see ecp.h * * \param grp The context for the elliptic curve to use. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param r The MPI context in which to store the first part * the signature. This must be initialized. * \param s The MPI context in which to store the second part * the signature. This must be initialized. * \param d The private signing key. This must be initialized * and setup, for example through mbedtls_ecp_gen_privkey(). * \param buf The hashed content to be signed. This must be a readable * buffer of length \p blen Bytes. It may be \c NULL if * \p blen is zero. * \param blen The length of \p buf in Bytes. * \param md_alg The hash algorithm used to hash the original data. * \param f_rng_blind The RNG function used for blinding. This must not be * \c NULL. * \param p_rng_blind The RNG context to be passed to \p f_rng. This may be * \c NULL if \p f_rng doesn't need a context parameter. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX * error code on failure. */ int mbedtls_ecdsa_sign_det_ext( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg, int (*f_rng_blind)(void *, unsigned char *, size_t), void *p_rng_blind ); /** * \brief This function verifies the ECDSA signature of a * previously-hashed message. * * \note If the bitlength of the message hash is larger than the * bitlength of the group order, then the hash is truncated as * defined in <em>Standards for Efficient Cryptography Group * (SECG): SEC1 Elliptic Curve Cryptography</em>, section * 4.1.4, step 3. * * \see ecp.h * * \param grp The ECP group to use. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param buf The hashed content that was signed. This must be a readable * buffer of length \p blen Bytes. It may be \c NULL if * \p blen is zero. * \param blen The length of \p buf in Bytes. * \param Q The public key to use for verification. This must be * initialized and setup. * \param r The first integer of the signature. * This must be initialized. * \param s The second integer of the signature. * This must be initialized. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the signature * is invalid. * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX * error code on failure for any other reason. */ int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp, const unsigned char *buf, size_t blen, const mbedtls_ecp_point *Q, const mbedtls_mpi *r, const mbedtls_mpi *s); /** * \brief This function computes the ECDSA signature and writes it * to a buffer, serialized as defined in <em>RFC-4492: * Elliptic Curve Cryptography (ECC) Cipher Suites for * Transport Layer Security (TLS)</em>. * * \warning It is not thread-safe to use the same context in * multiple threads. * * \note The deterministic version is used if * #MBEDTLS_ECDSA_DETERMINISTIC is defined. For more * information, see <em>RFC-6979: Deterministic Usage * of the Digital Signature Algorithm (DSA) and Elliptic * Curve Digital Signature Algorithm (ECDSA)</em>. * * \note If the bitlength of the message hash is larger than the * bitlength of the group order, then the hash is truncated as * defined in <em>Standards for Efficient Cryptography Group * (SECG): SEC1 Elliptic Curve Cryptography</em>, section * 4.1.3, step 5. * * \see ecp.h * * \param ctx The ECDSA context to use. This must be initialized * and have a group and private key bound to it, for example * via mbedtls_ecdsa_genkey() or mbedtls_ecdsa_from_keypair(). * \param md_alg The message digest that was used to hash the message. * \param hash The message hash to be signed. This must be a readable * buffer of length \p blen Bytes. * \param hlen The length of the hash \p hash in Bytes. * \param sig The buffer to which to write the signature. This must be a * writable buffer of length at least twice as large as the * size of the curve used, plus 9. For example, 73 Bytes if * a 256-bit curve is used. A buffer length of * #MBEDTLS_ECDSA_MAX_LEN is always safe. * \param slen The address at which to store the actual length of * the signature written. Must not be \c NULL. * \param f_rng The RNG function. This must not be \c NULL if * #MBEDTLS_ECDSA_DETERMINISTIC is unset. Otherwise, * it is used only for blinding and may be set to \c NULL, but * doing so is DEPRECATED. * \param p_rng The RNG context to be passed to \p f_rng. This may be * \c NULL if \p f_rng is \c NULL or doesn't use a context. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or * \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hlen, unsigned char *sig, size_t *slen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief This function computes the ECDSA signature and writes it * to a buffer, in a restartable way. * * \see \c mbedtls_ecdsa_write_signature() * * \note This function is like \c mbedtls_ecdsa_write_signature() * but it can return early and restart according to the limit * set with \c mbedtls_ecp_set_max_ops() to reduce blocking. * * \param ctx The ECDSA context to use. This must be initialized * and have a group and private key bound to it, for example * via mbedtls_ecdsa_genkey() or mbedtls_ecdsa_from_keypair(). * \param md_alg The message digest that was used to hash the message. * \param hash The message hash to be signed. This must be a readable * buffer of length \p blen Bytes. * \param hlen The length of the hash \p hash in Bytes. * \param sig The buffer to which to write the signature. This must be a * writable buffer of length at least twice as large as the * size of the curve used, plus 9. For example, 73 Bytes if * a 256-bit curve is used. A buffer length of * #MBEDTLS_ECDSA_MAX_LEN is always safe. * \param slen The address at which to store the actual length of * the signature written. Must not be \c NULL. * \param f_rng The RNG function. This must not be \c NULL if * #MBEDTLS_ECDSA_DETERMINISTIC is unset. Otherwise, * it is unused and may be set to \c NULL. * \param p_rng The RNG context to be passed to \p f_rng. This may be * \c NULL if \p f_rng is \c NULL or doesn't use a context. * \param rs_ctx The restart context to use. This may be \c NULL to disable * restarting. If it is not \c NULL, it must point to an * initialized restart context. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of * operations was reached: see \c mbedtls_ecp_set_max_ops(). * \return Another \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or * \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_ecdsa_write_signature_restartable( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hlen, unsigned char *sig, size_t *slen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, mbedtls_ecdsa_restart_ctx *rs_ctx ); /** * \brief This function reads and verifies an ECDSA signature. * * \note If the bitlength of the message hash is larger than the * bitlength of the group order, then the hash is truncated as * defined in <em>Standards for Efficient Cryptography Group * (SECG): SEC1 Elliptic Curve Cryptography</em>, section * 4.1.4, step 3. * * \see ecp.h * * \param ctx The ECDSA context to use. This must be initialized * and have a group and public key bound to it. * \param hash The message hash that was signed. This must be a readable * buffer of length \p size Bytes. * \param hlen The size of the hash \p hash. * \param sig The signature to read and verify. This must be a readable * buffer of length \p slen Bytes. * \param slen The size of \p sig in Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid. * \return #MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if there is a valid * signature in \p sig, but its length is less than \p siglen. * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_ERR_MPI_XXX * error code on failure for any other reason. */ int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx, const unsigned char *hash, size_t hlen, const unsigned char *sig, size_t slen ); /** * \brief This function reads and verifies an ECDSA signature, * in a restartable way. * * \see \c mbedtls_ecdsa_read_signature() * * \note This function is like \c mbedtls_ecdsa_read_signature() * but it can return early and restart according to the limit * set with \c mbedtls_ecp_set_max_ops() to reduce blocking. * * \param ctx The ECDSA context to use. This must be initialized * and have a group and public key bound to it. * \param hash The message hash that was signed. This must be a readable * buffer of length \p size Bytes. * \param hlen The size of the hash \p hash. * \param sig The signature to read and verify. This must be a readable * buffer of length \p slen Bytes. * \param slen The size of \p sig in Bytes. * \param rs_ctx The restart context to use. This may be \c NULL to disable * restarting. If it is not \c NULL, it must point to an * initialized restart context. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid. * \return #MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if there is a valid * signature in \p sig, but its length is less than \p siglen. * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of * operations was reached: see \c mbedtls_ecp_set_max_ops(). * \return Another \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_ERR_MPI_XXX * error code on failure for any other reason. */ int mbedtls_ecdsa_read_signature_restartable( mbedtls_ecdsa_context *ctx, const unsigned char *hash, size_t hlen, const unsigned char *sig, size_t slen, mbedtls_ecdsa_restart_ctx *rs_ctx ); /** * \brief This function generates an ECDSA keypair on the given curve. * * \see ecp.h * * \param ctx The ECDSA context to store the keypair in. * This must be initialized. * \param gid The elliptic curve to use. One of the various * \c MBEDTLS_ECP_DP_XXX macros depending on configuration. * \param f_rng The RNG function to use. This must not be \c NULL. * \param p_rng The RNG context to be passed to \p f_rng. This may be * \c NULL if \p f_rng doesn't need a context argument. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX code on failure. */ int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief This function sets up an ECDSA context from an EC key pair. * * \see ecp.h * * \param ctx The ECDSA context to setup. This must be initialized. * \param key The EC key to use. This must be initialized and hold * a private-public key pair or a public key. In the former * case, the ECDSA context may be used for signature creation * and verification after this call. In the latter case, it * may be used for signature verification. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX code on failure. */ int mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, const mbedtls_ecp_keypair *key ); /** * \brief This function initializes an ECDSA context. * * \param ctx The ECDSA context to initialize. * This must not be \c NULL. */ void mbedtls_ecdsa_init( mbedtls_ecdsa_context *ctx ); /** * \brief This function frees an ECDSA context. * * \param ctx The ECDSA context to free. This may be \c NULL, * in which case this function does nothing. If it * is not \c NULL, it must be initialized. */ void mbedtls_ecdsa_free( mbedtls_ecdsa_context *ctx ); #if defined(MBEDTLS_ECP_RESTARTABLE) /** * \brief Initialize a restart context. * * \param ctx The restart context to initialize. * This must not be \c NULL. */ void mbedtls_ecdsa_restart_init( mbedtls_ecdsa_restart_ctx *ctx ); /** * \brief Free the components of a restart context. * * \param ctx The restart context to free. This may be \c NULL, * in which case this function does nothing. If it * is not \c NULL, it must be initialized. */ void mbedtls_ecdsa_restart_free( mbedtls_ecdsa_restart_ctx *ctx ); #endif /* MBEDTLS_ECP_RESTARTABLE */ COSMOPOLITAN_C_END_ #endif /* ECDSA_H_ */
21,697
464
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/endian.h
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_ENDIAN_H_ #define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_ENDIAN_H_ #define Read32be(S) \ ({ \ const uint8_t *Ptr = (S); \ ((uint32_t)Ptr[0] << 030 | (uint32_t)Ptr[1] << 020 | \ (uint32_t)Ptr[2] << 010 | (uint32_t)Ptr[3] << 000); \ }) #define Write32be(P, V) \ ({ \ uint8_t *OuT = (P); \ uint64_t VaL = (V); \ OuT[0] = (0x00000000FF000000 & VaL) >> 030; \ OuT[1] = (0x0000000000FF0000 & VaL) >> 020; \ OuT[2] = (0x000000000000FF00 & VaL) >> 010; \ OuT[3] = (0x00000000000000FF & VaL) >> 000; \ OuT + 4; \ }) #define Read64be(S) \ ({ \ const uint8_t *Ptr = (S); \ ((uint64_t)Ptr[0] << 070 | (uint64_t)Ptr[1] << 060 | \ (uint64_t)Ptr[2] << 050 | (uint64_t)Ptr[3] << 040 | \ (uint64_t)Ptr[4] << 030 | (uint64_t)Ptr[5] << 020 | \ (uint64_t)Ptr[6] << 010 | (uint64_t)Ptr[7] << 000); \ }) #define Write64be(P, V) \ ({ \ uint64_t VaL = (V); \ uint8_t *OuT = (P); \ OuT[0] = (0xFF00000000000000 & VaL) >> 070; \ OuT[1] = (0x00FF000000000000 & VaL) >> 060; \ OuT[2] = (0x0000FF0000000000 & VaL) >> 050; \ OuT[3] = (0x000000FF00000000 & VaL) >> 040; \ OuT[4] = (0x00000000FF000000 & VaL) >> 030; \ OuT[5] = (0x0000000000FF0000 & VaL) >> 020; \ OuT[6] = (0x000000000000FF00 & VaL) >> 010; \ OuT[7] = (0x00000000000000FF & VaL) >> 000; \ OuT + 8; \ }) #define Write64le(P, V) \ ({ \ uint64_t VaL = (V); \ uint8_t *OuT = (P); \ OuT[0] = (0x00000000000000FF & VaL) >> 000; \ OuT[1] = (0x000000000000FF00 & VaL) >> 010; \ OuT[2] = (0x0000000000FF0000 & VaL) >> 020; \ OuT[3] = (0x00000000FF000000 & VaL) >> 030; \ OuT[4] = (0x000000FF00000000 & VaL) >> 040; \ OuT[5] = (0x0000FF0000000000 & VaL) >> 050; \ OuT[6] = (0x00FF000000000000 & VaL) >> 060; \ OuT[7] = (0xFF00000000000000 & VaL) >> 070; \ OuT + 8; \ }) #define GET_UINT32_BE(n, b, i) (n) = Read32be((b) + (i)) #define PUT_UINT32_BE(n, b, i) Write32be((b) + (i), n) #define GET_UINT64_BE(n, b, i) (n) = Read64be((b) + (i)) #define PUT_UINT64_BE(n, b, i) Write64be((b) + (i), n) #endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_ENDIAN_H_ */
2,872
67
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/dhm.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/str/str.h" #include "third_party/mbedtls/asn1.h" #include "third_party/mbedtls/bignum.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/dhm.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/pem.h" #include "third_party/mbedtls/platform.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /** * @fileoverview Diffie-Hellman-Merkle key exchange * * The following sources were referenced in the design of this * implementation of the Diffie-Hellman-Merkle algorithm: * * [1] Handbook of Applied Cryptography - 1997, Chapter 12 * Menezes, van Oorschot and Vanstone */ #if defined(MBEDTLS_DHM_C) #if !defined(MBEDTLS_DHM_ALT) #define DHM_VALIDATE_RET( cond ) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_DHM_BAD_INPUT_DATA ) #define DHM_VALIDATE( cond ) \ MBEDTLS_INTERNAL_VALIDATE( cond ) /* * helper to validate the mbedtls_mpi size and import it */ static int dhm_read_bignum( mbedtls_mpi *X, unsigned char **p, const unsigned char *end ) { int ret, n; if( end - *p < 2 ) return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA ); n = ( (*p)[0] << 8 ) | (*p)[1]; (*p) += 2; if( (int)( end - *p ) < n ) return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA ); if( ( ret = mbedtls_mpi_read_binary( X, *p, n ) ) != 0 ) return( MBEDTLS_ERR_DHM_READ_PARAMS_FAILED + ret ); (*p) += n; return( 0 ); } /* * Verify sanity of parameter with regards to P * * Parameter should be: 2 <= public_param <= P - 2 * * This means that we need to return an error if * public_param < 2 or public_param > P-2 * * For more information on the attack, see: * http://www.cl.cam.ac.uk/~rja14/Papers/psandqs.pdf * http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-2643 */ static int dhm_check_range( const mbedtls_mpi *param, const mbedtls_mpi *P ) { mbedtls_mpi L, U; int ret = 0; mbedtls_mpi_init( &L ); mbedtls_mpi_init( &U ); MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &L, 2 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &U, P, 2 ) ); if( mbedtls_mpi_cmp_mpi( param, &L ) < 0 || mbedtls_mpi_cmp_mpi( param, &U ) > 0 ) { ret = MBEDTLS_ERR_DHM_BAD_INPUT_DATA; } cleanup: mbedtls_mpi_free( &L ); mbedtls_mpi_free( &U ); return( ret ); } void mbedtls_dhm_init( mbedtls_dhm_context *ctx ) { DHM_VALIDATE( ctx != NULL ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_dhm_context ) ); } /* * Parse the ServerKeyExchange parameters */ int mbedtls_dhm_read_params( mbedtls_dhm_context *ctx, unsigned char **p, const unsigned char *end ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; DHM_VALIDATE_RET( ctx != NULL ); DHM_VALIDATE_RET( p != NULL && *p != NULL ); DHM_VALIDATE_RET( end != NULL ); if( ( ret = dhm_read_bignum( &ctx->P, p, end ) ) != 0 || ( ret = dhm_read_bignum( &ctx->G, p, end ) ) != 0 || ( ret = dhm_read_bignum( &ctx->GY, p, end ) ) != 0 ) return( ret ); if( ( ret = dhm_check_range( &ctx->GY, &ctx->P ) ) != 0 ) return( ret ); ctx->len = mbedtls_mpi_size( &ctx->P ); return( 0 ); } /* * Setup and write the ServerKeyExchange parameters */ int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size, unsigned char *output, size_t *olen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret, count = 0; size_t n1, n2, n3; unsigned char *p; DHM_VALIDATE_RET( ctx != NULL ); DHM_VALIDATE_RET( output != NULL ); DHM_VALIDATE_RET( olen != NULL ); DHM_VALIDATE_RET( f_rng != NULL ); if( mbedtls_mpi_cmp_int( &ctx->P, 0 ) == 0 ) return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA ); /* * Generate X as large as possible ( < P ) */ do { MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->X, x_size, f_rng, p_rng ) ); while( mbedtls_mpi_cmp_mpi( &ctx->X, &ctx->P ) >= 0 ) mbedtls_mpi_shift_r( &ctx->X, 1 ); if( count++ > 10 ) return( MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED ); } while( dhm_check_range( &ctx->X, &ctx->P ) != 0 ); /* * Calculate GX = G^X mod P */ MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->GX, &ctx->G, &ctx->X, &ctx->P , &ctx->RP ) ); if( ( ret = dhm_check_range( &ctx->GX, &ctx->P ) ) != 0 ) return( ret ); /* * export P, G, GX */ #define DHM_MPI_EXPORT( X, n ) \ do { \ MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( ( X ), \ p + 2, \ ( n ) ) ); \ *p++ = (unsigned char)( ( n ) >> 8 ); \ *p++ = (unsigned char)( ( n ) ); \ p += ( n ); \ } while( 0 ) n1 = mbedtls_mpi_size( &ctx->P ); n2 = mbedtls_mpi_size( &ctx->G ); n3 = mbedtls_mpi_size( &ctx->GX ); p = output; DHM_MPI_EXPORT( &ctx->P , n1 ); DHM_MPI_EXPORT( &ctx->G , n2 ); DHM_MPI_EXPORT( &ctx->GX, n3 ); *olen = p - output; ctx->len = n1; cleanup: if( ret != 0 ) return( MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED + ret ); return( 0 ); } /* * Set prime modulus and generator */ int mbedtls_dhm_set_group( mbedtls_dhm_context *ctx, const mbedtls_mpi *P, const mbedtls_mpi *G ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; DHM_VALIDATE_RET( ctx != NULL ); DHM_VALIDATE_RET( P != NULL ); DHM_VALIDATE_RET( G != NULL ); if( ( ret = mbedtls_mpi_copy( &ctx->P, P ) ) != 0 || ( ret = mbedtls_mpi_copy( &ctx->G, G ) ) != 0 ) { return( MBEDTLS_ERR_DHM_SET_GROUP_FAILED + ret ); } ctx->len = mbedtls_mpi_size( &ctx->P ); return( 0 ); } /* * Import the peer's public value G^Y */ int mbedtls_dhm_read_public( mbedtls_dhm_context *ctx, const unsigned char *input, size_t ilen ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; DHM_VALIDATE_RET( ctx != NULL ); DHM_VALIDATE_RET( input != NULL ); if( ilen < 1 || ilen > ctx->len ) return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA ); if( ( ret = mbedtls_mpi_read_binary( &ctx->GY, input, ilen ) ) != 0 ) return( MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED + ret ); return( 0 ); } /* * Create own private value X and export G^X */ int mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size, unsigned char *output, size_t olen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret, count = 0; DHM_VALIDATE_RET( ctx != NULL ); DHM_VALIDATE_RET( output != NULL ); DHM_VALIDATE_RET( f_rng != NULL ); if( olen < 1 || olen > ctx->len ) return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA ); if( mbedtls_mpi_cmp_int( &ctx->P, 0 ) == 0 ) return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA ); /* * generate X and calculate GX = G^X mod P */ do { MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->X, x_size, f_rng, p_rng ) ); while( mbedtls_mpi_cmp_mpi( &ctx->X, &ctx->P ) >= 0 ) mbedtls_mpi_shift_r( &ctx->X, 1 ); if( count++ > 10 ) return( MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED ); } while( dhm_check_range( &ctx->X, &ctx->P ) != 0 ); MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->GX, &ctx->G, &ctx->X, &ctx->P , &ctx->RP ) ); if( ( ret = dhm_check_range( &ctx->GX, &ctx->P ) ) != 0 ) return( ret ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->GX, output, olen ) ); cleanup: if( ret != 0 ) return( MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED + ret ); return( 0 ); } /* * Pick a random R in the range [2, M) for blinding purposes */ static int dhm_random_below( mbedtls_mpi *R, const mbedtls_mpi *M, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret, count; count = 0; do { MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( R, mbedtls_mpi_size( M ), f_rng, p_rng ) ); while( mbedtls_mpi_cmp_mpi( R, M ) >= 0 ) mbedtls_mpi_shift_r( R, 1 ); if( count++ > 10 ) return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE ); } while( mbedtls_mpi_cmp_int( R, 1 ) <= 0 ); cleanup: return( ret ); } /* * Use the blinding method and optimisation suggested in section 10 of: * KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA, * DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer * Berlin Heidelberg, 1996. p. 104-113. */ static int dhm_update_blinding( mbedtls_dhm_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret; mbedtls_mpi R; mbedtls_mpi_init( &R ); /* * Don't use any blinding the first time a particular X is used, * but remember it to use blinding next time. */ if( mbedtls_mpi_cmp_mpi( &ctx->X, &ctx->pX ) != 0 ) { MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &ctx->pX, &ctx->X ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &ctx->Vi, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &ctx->Vf, 1 ) ); return( 0 ); } /* * Ok, we need blinding. Can we re-use existing values? * If yes, just update them by squaring them. */ if( !mbedtls_mpi_is_one( &ctx->Vi ) ) { MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vi, &ctx->Vi ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->P ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vf, &ctx->Vf, &ctx->Vf ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vf, &ctx->Vf, &ctx->P ) ); return( 0 ); } /* * We need to generate blinding values from scratch */ /* Vi = random( 2, P-1 ) */ MBEDTLS_MPI_CHK( dhm_random_below( &ctx->Vi, &ctx->P, f_rng, p_rng ) ); /* Vf = Vi^-X mod P * First compute Vi^-1 = R * (R Vi)^-1, (avoiding leaks from inv_mod), * then elevate to the Xth power. */ MBEDTLS_MPI_CHK( dhm_random_below( &R, &ctx->P, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vf, &ctx->Vi, &R ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vf, &ctx->Vf, &ctx->P ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->Vf, &ctx->Vf, &ctx->P ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vf, &ctx->Vf, &R ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vf, &ctx->Vf, &ctx->P ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->Vf, &ctx->Vf, &ctx->X, &ctx->P, &ctx->RP ) ); cleanup: mbedtls_mpi_free( &R ); return( ret ); } /* * Derive and export the shared secret (G^Y)^X mod P */ int mbedtls_dhm_calc_secret( mbedtls_dhm_context *ctx, unsigned char *output, size_t output_size, size_t *olen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_mpi GYb; DHM_VALIDATE_RET( ctx != NULL ); DHM_VALIDATE_RET( output != NULL ); DHM_VALIDATE_RET( olen != NULL ); if( output_size < ctx->len ) return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA ); if( ( ret = dhm_check_range( &ctx->GY, &ctx->P ) ) != 0 ) return( ret ); mbedtls_mpi_init( &GYb ); /* Blind peer's value */ if( f_rng != NULL ) { MBEDTLS_MPI_CHK( dhm_update_blinding( ctx, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &GYb, &ctx->GY, &ctx->Vi ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &GYb, &GYb, &ctx->P ) ); } else MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &GYb, &ctx->GY ) ); /* Do modular exponentiation */ MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->K, &GYb, &ctx->X, &ctx->P, &ctx->RP ) ); /* Unblind secret value */ if( f_rng != NULL ) { MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->K, &ctx->K, &ctx->Vf ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->K, &ctx->K, &ctx->P ) ); } *olen = mbedtls_mpi_size( &ctx->K ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->K, output, *olen ) ); cleanup: mbedtls_mpi_free( &GYb ); if( ret != 0 ) return( MBEDTLS_ERR_DHM_CALC_SECRET_FAILED + ret ); return( 0 ); } /* * Free the components of a DHM key */ void mbedtls_dhm_free( mbedtls_dhm_context *ctx ) { if( ctx == NULL ) return; mbedtls_mpi_free( &ctx->pX ); mbedtls_mpi_free( &ctx->Vf ); mbedtls_mpi_free( &ctx->Vi ); mbedtls_mpi_free( &ctx->RP ); mbedtls_mpi_free( &ctx->K ); mbedtls_mpi_free( &ctx->GY ); mbedtls_mpi_free( &ctx->GX ); mbedtls_mpi_free( &ctx->X ); mbedtls_mpi_free( &ctx->G ); mbedtls_mpi_free( &ctx->P ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_dhm_context ) ); } #if defined(MBEDTLS_ASN1_PARSE_C) /* * Parse DHM parameters */ int mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin, size_t dhminlen ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len; unsigned char *p, *end; #if defined(MBEDTLS_PEM_PARSE_C) mbedtls_pem_context pem; #endif /* MBEDTLS_PEM_PARSE_C */ DHM_VALIDATE_RET( dhm != NULL ); DHM_VALIDATE_RET( dhmin != NULL ); #if defined(MBEDTLS_PEM_PARSE_C) mbedtls_pem_init( &pem ); /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */ if( dhminlen == 0 || dhmin[dhminlen - 1] != '\0' ) ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT; else ret = mbedtls_pem_read_buffer( &pem, "-----BEGIN DH PARAMETERS-----", "-----END DH PARAMETERS-----", dhmin, NULL, 0, &dhminlen ); if( ret == 0 ) { /* * Was PEM encoded */ dhminlen = pem.buflen; } else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT ) goto exit; p = ( ret == 0 ) ? pem.buf : (unsigned char *) dhmin; #else p = (unsigned char *) dhmin; #endif /* MBEDTLS_PEM_PARSE_C */ end = p + dhminlen; /* * DHParams ::= SEQUENCE { * prime INTEGER, -- P * generator INTEGER, -- g * privateValueLength INTEGER OPTIONAL * } */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { ret = MBEDTLS_ERR_DHM_INVALID_FORMAT + ret; goto exit; } end = p + len; if( ( ret = mbedtls_asn1_get_mpi( &p, end, &dhm->P ) ) != 0 || ( ret = mbedtls_asn1_get_mpi( &p, end, &dhm->G ) ) != 0 ) { ret = MBEDTLS_ERR_DHM_INVALID_FORMAT + ret; goto exit; } if( p != end ) { /* This might be the optional privateValueLength. * If so, we can cleanly discard it */ mbedtls_mpi rec; mbedtls_mpi_init( &rec ); ret = mbedtls_asn1_get_mpi( &p, end, &rec ); mbedtls_mpi_free( &rec ); if ( ret != 0 ) { ret = MBEDTLS_ERR_DHM_INVALID_FORMAT + ret; goto exit; } if ( p != end ) { ret = MBEDTLS_ERR_DHM_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH; goto exit; } } ret = 0; dhm->len = mbedtls_mpi_size( &dhm->P ); exit: #if defined(MBEDTLS_PEM_PARSE_C) mbedtls_pem_free( &pem ); #endif if( ret != 0 ) mbedtls_dhm_free( dhm ); return( ret ); } #if defined(MBEDTLS_FS_IO) /* * Load all data from a file into a given buffer. * * The file is expected to contain either PEM or DER encoded data. * A terminating null byte is always appended. It is included in the announced * length only if the data looks like it is PEM encoded. */ static int load_file( const char *path, unsigned char **buf, size_t *n ) { FILE *f; long size; if( ( f = fopen( path, "rb" ) ) == NULL ) return( MBEDTLS_ERR_DHM_FILE_IO_ERROR ); fseek( f, 0, SEEK_END ); if( ( size = ftell( f ) ) == -1 ) { fclose( f ); return( MBEDTLS_ERR_DHM_FILE_IO_ERROR ); } fseek( f, 0, SEEK_SET ); *n = (size_t) size; if( *n + 1 == 0 || ( *buf = mbedtls_calloc( 1, *n + 1 ) ) == NULL ) { fclose( f ); return( MBEDTLS_ERR_DHM_ALLOC_FAILED ); } if( fread( *buf, 1, *n, f ) != *n ) { fclose( f ); mbedtls_platform_zeroize( *buf, *n + 1 ); mbedtls_free( *buf ); return( MBEDTLS_ERR_DHM_FILE_IO_ERROR ); } fclose( f ); (*buf)[*n] = '\0'; if( strstr( (const char *) *buf, "-----BEGIN " ) != NULL ) ++*n; return( 0 ); } /* * Load and parse DHM parameters */ int mbedtls_dhm_parse_dhmfile( mbedtls_dhm_context *dhm, const char *path ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t n; unsigned char *buf; DHM_VALIDATE_RET( dhm != NULL ); DHM_VALIDATE_RET( path != NULL ); if( ( ret = load_file( path, &buf, &n ) ) != 0 ) return( ret ); ret = mbedtls_dhm_parse_dhm( dhm, buf, n ); mbedtls_platform_zeroize( buf, n ); mbedtls_free( buf ); return( ret ); } #endif /* MBEDTLS_FS_IO */ #endif /* MBEDTLS_ASN1_PARSE_C */ #endif /* MBEDTLS_DHM_ALT */ #if defined(MBEDTLS_SELF_TEST) #if defined(MBEDTLS_PEM_PARSE_C) static const char mbedtls_test_dhm_params[] = "-----BEGIN DH PARAMETERS-----\r\n" "MIGHAoGBAJ419DBEOgmQTzo5qXl5fQcN9TN455wkOL7052HzxxRVMyhYmwQcgJvh\r\n" "1sa18fyfR9OiVEMYglOpkqVoGLN7qd5aQNNi5W7/C+VBdHTBJcGZJyyP5B3qcz32\r\n" "9mLJKudlVudV0Qxk5qUJaPZ/xupz0NyoVpviuiBOI1gNi8ovSXWzAgEC\r\n" "-----END DH PARAMETERS-----\r\n"; #else /* MBEDTLS_PEM_PARSE_C */ static const char mbedtls_test_dhm_params[] = { 0x30, 0x81, 0x87, 0x02, 0x81, 0x81, 0x00, 0x9e, 0x35, 0xf4, 0x30, 0x44, 0x3a, 0x09, 0x90, 0x4f, 0x3a, 0x39, 0xa9, 0x79, 0x79, 0x7d, 0x07, 0x0d, 0xf5, 0x33, 0x78, 0xe7, 0x9c, 0x24, 0x38, 0xbe, 0xf4, 0xe7, 0x61, 0xf3, 0xc7, 0x14, 0x55, 0x33, 0x28, 0x58, 0x9b, 0x04, 0x1c, 0x80, 0x9b, 0xe1, 0xd6, 0xc6, 0xb5, 0xf1, 0xfc, 0x9f, 0x47, 0xd3, 0xa2, 0x54, 0x43, 0x18, 0x82, 0x53, 0xa9, 0x92, 0xa5, 0x68, 0x18, 0xb3, 0x7b, 0xa9, 0xde, 0x5a, 0x40, 0xd3, 0x62, 0xe5, 0x6e, 0xff, 0x0b, 0xe5, 0x41, 0x74, 0x74, 0xc1, 0x25, 0xc1, 0x99, 0x27, 0x2c, 0x8f, 0xe4, 0x1d, 0xea, 0x73, 0x3d, 0xf6, 0xf6, 0x62, 0xc9, 0x2a, 0xe7, 0x65, 0x56, 0xe7, 0x55, 0xd1, 0x0c, 0x64, 0xe6, 0xa5, 0x09, 0x68, 0xf6, 0x7f, 0xc6, 0xea, 0x73, 0xd0, 0xdc, 0xa8, 0x56, 0x9b, 0xe2, 0xba, 0x20, 0x4e, 0x23, 0x58, 0x0d, 0x8b, 0xca, 0x2f, 0x49, 0x75, 0xb3, 0x02, 0x01, 0x02 }; #endif /* MBEDTLS_PEM_PARSE_C */ static const size_t mbedtls_test_dhm_params_len = sizeof( mbedtls_test_dhm_params ); /* * Checkup routine */ int mbedtls_dhm_self_test( int verbose ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_dhm_context dhm; mbedtls_dhm_init( &dhm ); if( verbose != 0 ) mbedtls_printf( " DHM parameter load: " ); if( ( ret = mbedtls_dhm_parse_dhm( &dhm, (const unsigned char *) mbedtls_test_dhm_params, mbedtls_test_dhm_params_len ) ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); ret = 1; goto exit; } if( verbose != 0 ) mbedtls_printf( "passed\n\n" ); exit: mbedtls_dhm_free( &dhm ); return( ret ); } #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_DHM_C */
22,049
729
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/aesni.h
#ifndef MBEDTLS_AESNI_H_ #define MBEDTLS_AESNI_H_ #include "third_party/mbedtls/aes.h" #include "third_party/mbedtls/config.h" COSMOPOLITAN_C_START_ /* clang-format off */ #define MBEDTLS_AESNI_AES 0x02000000u #define MBEDTLS_AESNI_CLMUL 0x00000002u int mbedtls_aesni_crypt_ecb( mbedtls_aes_context *, int, const unsigned char[16], unsigned char[16] ); void mbedtls_aesni_gcm_mult( unsigned char[16], const uint64_t[2] ); void mbedtls_aesni_inverse_key( unsigned char *, const unsigned char *, int ); int mbedtls_aesni_setkey_enc( unsigned char *, const unsigned char *, size_t ); COSMOPOLITAN_C_END_ #endif /* MBEDTLS_AESNI_H_ */
642
18
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/rsa_internal.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/mbedtls/bignum.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/profile.h" #include "third_party/mbedtls/rsa.h" #include "third_party/mbedtls/rsa_internal.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /* * Helper functions for the RSA module * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #if defined(MBEDTLS_RSA_C) /* * Compute RSA prime factors from public and private exponents * * Summary of algorithm: * Setting F := lcm(P-1,Q-1), the idea is as follows: * * (a) For any 1 <= X < N with gcd(X,N)=1, we have X^F = 1 modulo N, so X^(F/2) * is a square root of 1 in Z/NZ. Since Z/NZ ~= Z/PZ x Z/QZ by CRT and the * square roots of 1 in Z/PZ and Z/QZ are +1 and -1, this leaves the four * possibilities X^(F/2) = (+-1, +-1). If it happens that X^(F/2) = (-1,+1) * or (+1,-1), then gcd(X^(F/2) + 1, N) will be equal to one of the prime * factors of N. * * (b) If we don't know F/2 but (F/2) * K for some odd (!) K, then the same * construction still applies since (-)^K is the identity on the set of * roots of 1 in Z/NZ. * * The public and private key primitives (-)^E and (-)^D are mutually inverse * bijections on Z/NZ if and only if (-)^(DE) is the identity on Z/NZ, i.e. * if and only if DE - 1 is a multiple of F, say DE - 1 = F * L. * Splitting L = 2^t * K with K odd, we have * * DE - 1 = FL = (F/2) * (2^(t+1)) * K, * * so (F / 2) * K is among the numbers * * (DE - 1) >> 1, (DE - 1) >> 2, ..., (DE - 1) >> ord * * where ord is the order of 2 in (DE - 1). * We can therefore iterate through these numbers apply the construction * of (a) and (b) above to attempt to factor N. * */ int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N, mbedtls_mpi const *E, mbedtls_mpi const *D, mbedtls_mpi *P, mbedtls_mpi *Q ) { int ret = 0; uint16_t attempt; /* Number of current attempt */ uint16_t iter; /* Number of squares computed in the current attempt */ uint16_t order; /* Order of 2 in DE - 1 */ mbedtls_mpi T; /* Holds largest odd divisor of DE - 1 */ mbedtls_mpi K; /* Temporary holding the current candidate */ const unsigned char primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251 }; const size_t num_primes = sizeof( primes ) / sizeof( *primes ); if( P == NULL || Q == NULL || P->p != NULL || Q->p != NULL ) return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); if( mbedtls_mpi_cmp_int( N, 0 ) <= 0 || mbedtls_mpi_cmp_int( D, 1 ) <= 0 || mbedtls_mpi_cmp_mpi( D, N ) >= 0 || mbedtls_mpi_cmp_int( E, 1 ) <= 0 || mbedtls_mpi_cmp_mpi( E, N ) >= 0 ) { return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); } /* * Initializations and temporary changes */ mbedtls_mpi_init( &K ); mbedtls_mpi_init( &T ); /* T := DE - 1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, D, E ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &T, &T, 1 ) ); if( ( order = (uint16_t) mbedtls_mpi_lsb( &T ) ) == 0 ) { ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA; goto cleanup; } /* After this operation, T holds the largest odd divisor of DE - 1. */ MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &T, order ) ); /* * Actual work */ /* Skip trying 2 if N == 1 mod 8 */ attempt = 0; if( N->p[0] % 8 == 1 ) attempt = 1; for( ; attempt < num_primes; ++attempt ) { mbedtls_mpi_lset( &K, primes[attempt] ); /* Check if gcd(K,N) = 1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( P, &K, N ) ); if( !mbedtls_mpi_is_one( P ) ) continue; /* Go through K^T + 1, K^(2T) + 1, K^(4T) + 1, ... * and check whether they have nontrivial GCD with N. */ MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &K, &K, &T, N, Q /* temporarily use Q for storing Montgomery * multiplication helper values */ ) ); for( iter = 1; iter <= order; ++iter ) { /* If we reach 1 prematurely, there's no point * in continuing to square K */ if( mbedtls_mpi_is_one( &K ) ) break; MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &K, &K, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( P, &K, N ) ); if( mbedtls_mpi_cmp_int( P, 1 ) == 1 && mbedtls_mpi_cmp_mpi( P, N ) == -1 ) { /* * Have found a nontrivial divisor P of N. * Set Q := N / P. */ MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( Q, NULL, N, P ) ); goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, &K, &K ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, N ) ); } /* * If we get here, then either we prematurely aborted the loop because * we reached 1, or K holds primes[attempt]^(DE - 1) mod N, which must * be 1 if D,E,N were consistent. * Check if that's the case and abort if not, to avoid very long, * yet eventually failing, computations if N,D,E were not sane. */ if( !mbedtls_mpi_is_one( &K ) ) { break; } } ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA; cleanup: mbedtls_mpi_free( &K ); mbedtls_mpi_free( &T ); return( ret ); } /* * Given P, Q and the public exponent E, deduce D. * This is essentially a modular inversion. */ int mbedtls_rsa_deduce_private_exponent( mbedtls_mpi const *P, mbedtls_mpi const *Q, mbedtls_mpi const *E, mbedtls_mpi *D ) { int ret = 0; mbedtls_mpi K, L; if( D == NULL || mbedtls_mpi_cmp_int( D, 0 ) != 0 ) return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); if( mbedtls_mpi_cmp_int( P, 1 ) <= 0 || mbedtls_mpi_cmp_int( Q, 1 ) <= 0 || mbedtls_mpi_cmp_int( E, 0 ) == 0 ) { return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); } mbedtls_mpi_init( &K ); mbedtls_mpi_init( &L ); /* Temporarily put K := P-1 and L := Q-1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, Q, 1 ) ); /* Temporarily put D := gcd(P-1, Q-1) */ MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( D, &K, &L ) ); /* K := LCM(P-1, Q-1) */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, &K, &L ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &K, NULL, &K, D ) ); /* Compute modular inverse of E in LCM(P-1, Q-1) */ MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( D, E, &K ) ); cleanup: mbedtls_mpi_free( &K ); mbedtls_mpi_free( &L ); return( ret ); } /* * Check that RSA CRT parameters are in accordance with core parameters. */ int mbedtls_rsa_validate_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q, const mbedtls_mpi *D, const mbedtls_mpi *DP, const mbedtls_mpi *DQ, const mbedtls_mpi *QP ) { int ret = 0; mbedtls_mpi K, L; mbedtls_mpi_init( &K ); mbedtls_mpi_init( &L ); /* Check that DP - D == 0 mod P - 1 */ if( DP != NULL ) { if( P == NULL ) { ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &L, DP, D ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &L, &L, &K ) ); if( mbedtls_mpi_cmp_int( &L, 0 ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } } /* Check that DQ - D == 0 mod Q - 1 */ if( DQ != NULL ) { if( Q == NULL ) { ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, Q, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &L, DQ, D ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &L, &L, &K ) ); if( mbedtls_mpi_cmp_int( &L, 0 ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } } /* Check that QP * Q - 1 == 0 mod P */ if( QP != NULL ) { if( P == NULL || Q == NULL ) { ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, QP, Q ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, P ) ); if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } } cleanup: /* Wrap MPI error codes by RSA check failure error code */ if( ret != 0 && ret != MBEDTLS_ERR_RSA_KEY_CHECK_FAILED && ret != MBEDTLS_ERR_RSA_BAD_INPUT_DATA ) { ret += MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; } mbedtls_mpi_free( &K ); mbedtls_mpi_free( &L ); return( ret ); } /* * Check that core RSA parameters are sane. */ int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P, const mbedtls_mpi *Q, const mbedtls_mpi *D, const mbedtls_mpi *E, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = 0; mbedtls_mpi K, L; mbedtls_mpi_init( &K ); mbedtls_mpi_init( &L ); /* * Step 1: If PRNG provided, check that P and Q are prime */ #if defined(MBEDTLS_GENPRIME) /* * When generating keys, the strongest security we support aims for an error * rate of at most 2^-100 and we are aiming for the same certainty here as * well. */ if( f_rng != NULL && P != NULL && ( ret = mbedtls_mpi_is_prime_ext( P, 50, f_rng, p_rng ) ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } if( f_rng != NULL && Q != NULL && ( ret = mbedtls_mpi_is_prime_ext( Q, 50, f_rng, p_rng ) ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } #else ((void) f_rng); ((void) p_rng); #endif /* MBEDTLS_GENPRIME */ /* * Step 2: Check that 1 < N = P * Q */ if( P != NULL && Q != NULL && N != NULL ) { MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, P, Q ) ); if( mbedtls_mpi_cmp_int( N, 1 ) <= 0 || mbedtls_mpi_cmp_mpi( &K, N ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } } /* * Step 3: Check and 1 < D, E < N if present. */ if( N != NULL && D != NULL && E != NULL ) { if ( mbedtls_mpi_cmp_int( D, 1 ) <= 0 || mbedtls_mpi_cmp_int( E, 1 ) <= 0 || mbedtls_mpi_cmp_mpi( D, N ) >= 0 || mbedtls_mpi_cmp_mpi( E, N ) >= 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } } /* * Step 4: Check that D, E are inverse modulo P-1 and Q-1 */ if( P != NULL && Q != NULL && D != NULL && E != NULL ) { if( mbedtls_mpi_cmp_int( P, 1 ) <= 0 || mbedtls_mpi_cmp_int( Q, 1 ) <= 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } /* Compute DE-1 mod P-1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, D, E ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, &L ) ); if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } /* Compute DE-1 mod Q-1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, D, E ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, Q, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, &L ) ); if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } } cleanup: mbedtls_mpi_free( &K ); mbedtls_mpi_free( &L ); /* Wrap MPI error codes by RSA check failure error code */ if( ret != 0 && ret != MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ) { ret += MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; } return( ret ); } int mbedtls_rsa_deduce_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q, const mbedtls_mpi *D, mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP ) { int ret = 0; mbedtls_mpi K; mbedtls_mpi_init( &K ); /* DP = D mod P-1 */ if( DP != NULL ) { MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( DP, D, &K ) ); } /* DQ = D mod Q-1 */ if( DQ != NULL ) { MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, Q, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( DQ, D, &K ) ); } /* QP = Q^{-1} mod P */ if( QP != NULL ) { MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( QP, Q, P ) ); } cleanup: mbedtls_mpi_free( &K ); return( ret ); } #endif /* MBEDTLS_RSA_C */
16,410
511
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/asn1write.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "third_party/mbedtls/asn1write.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/platform.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /** * @fileoverview ASN.1 buffer writing functionality */ #if defined(MBEDTLS_ASN1_WRITE_C) /** * \brief Write a length field in ASN.1 format. * * \note This function works backwards in data buffer. * * \param p The reference to the current position pointer. * \param start The start of the buffer, for bounds-checking. * \param len The length value to write. * * \return The number of bytes written to \p p on success. * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_asn1_write_len( unsigned char **p, unsigned char *start, size_t len ) { if( len < 0x80 ) { if( *p - start < 1 ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); *--(*p) = (unsigned char) len; return( 1 ); } if( len <= 0xFF ) { if( *p - start < 2 ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); *--(*p) = (unsigned char) len; *--(*p) = 0x81; return( 2 ); } if( len <= 0xFFFF ) { if( *p - start < 3 ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); *--(*p) = ( len ) & 0xFF; *--(*p) = ( len >> 8 ) & 0xFF; *--(*p) = 0x82; return( 3 ); } if( len <= 0xFFFFFF ) { if( *p - start < 4 ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); *--(*p) = ( len ) & 0xFF; *--(*p) = ( len >> 8 ) & 0xFF; *--(*p) = ( len >> 16 ) & 0xFF; *--(*p) = 0x83; return( 4 ); } #if SIZE_MAX > 0xFFFFFFFF if( len <= 0xFFFFFFFF ) #endif { if( *p - start < 5 ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); *--(*p) = ( len ) & 0xFF; *--(*p) = ( len >> 8 ) & 0xFF; *--(*p) = ( len >> 16 ) & 0xFF; *--(*p) = ( len >> 24 ) & 0xFF; *--(*p) = 0x84; return( 5 ); } #if SIZE_MAX > 0xFFFFFFFF return( MBEDTLS_ERR_ASN1_INVALID_LENGTH ); #endif } /** * \brief Write an ASN.1 tag in ASN.1 format. * * \note This function works backwards in data buffer. * * \param p The reference to the current position pointer. * \param start The start of the buffer, for bounds-checking. * \param tag The tag to write. * * \return The number of bytes written to \p p on success. * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_asn1_write_tag( unsigned char **p, unsigned char *start, unsigned char tag ) { if( *p - start < 1 ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); *--(*p) = tag; return( 1 ); } /** * \brief Write raw buffer data. * * \note This function works backwards in data buffer. * * \param p The reference to the current position pointer. * \param start The start of the buffer, for bounds-checking. * \param buf The data buffer to write. * \param size The length of the data buffer. * * \return The number of bytes written to \p p on success. * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_asn1_write_raw_buffer( unsigned char **p, unsigned char *start, const unsigned char *buf, size_t size ) { size_t len = 0; if( *p < start || (size_t)( *p - start ) < size ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); len = size; (*p) -= len; memcpy( *p, buf, len ); return( (int) len ); } #if defined(MBEDTLS_BIGNUM_C) /** * \brief Write a arbitrary-precision number (#MBEDTLS_ASN1_INTEGER) * in ASN.1 format. * * \note This function works backwards in data buffer. * * \param p The reference to the current position pointer. * \param start The start of the buffer, for bounds-checking. * \param X The MPI to write. * It must be non-negative. * * \return The number of bytes written to \p p on success. * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_asn1_write_mpi( unsigned char **p, unsigned char *start, const mbedtls_mpi *X ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len = 0; // Write the MPI // len = mbedtls_mpi_size( X ); if( *p < start || (size_t)( *p - start ) < len ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); (*p) -= len; MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( X, *p, len ) ); // DER format assumes 2s complement for numbers, so the leftmost bit // should be 0 for positive numbers and 1 for negative numbers. // if( X->s ==1 && **p & 0x80 ) { if( *p - start < 1 ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); *--(*p) = 0x00; len += 1; } MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_INTEGER ) ); ret = (int) len; cleanup: return( ret ); } #endif /* MBEDTLS_BIGNUM_C */ /** * \brief Write a NULL tag (#MBEDTLS_ASN1_NULL) with zero data * in ASN.1 format. * * \note This function works backwards in data buffer. * * \param p The reference to the current position pointer. * \param start The start of the buffer, for bounds-checking. * * \return The number of bytes written to \p p on success. * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_asn1_write_null( unsigned char **p, unsigned char *start ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len = 0; // Write NULL // MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, 0) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_NULL ) ); return( (int) len ); } /** * \brief Write an OID tag (#MBEDTLS_ASN1_OID) and data * in ASN.1 format. * * \note This function works backwards in data buffer. * * \param p The reference to the current position pointer. * \param start The start of the buffer, for bounds-checking. * \param oid The OID to write. * \param oid_len The length of the OID. * * \return The number of bytes written to \p p on success. * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_asn1_write_oid( unsigned char **p, unsigned char *start, const char *oid, size_t oid_len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len = 0; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start, (const unsigned char *) oid, oid_len ) ); MBEDTLS_ASN1_CHK_ADD( len , mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len , mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_OID ) ); return( (int) len ); } /** * \brief Write an AlgorithmIdentifier sequence in ASN.1 format. * * \note This function works backwards in data buffer. * * \param p The reference to the current position pointer. * \param start The start of the buffer, for bounds-checking. * \param oid The OID of the algorithm to write. * \param oid_len The length of the algorithm's OID. * \param par_len The length of the parameters, which must be already written. * If 0, NULL parameters are added * * \return The number of bytes written to \p p on success. * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_asn1_write_algorithm_identifier( unsigned char **p, unsigned char *start, const char *oid, size_t oid_len, size_t par_len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len = 0; if( par_len == 0 ) MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_null( p, start ) ); else len += par_len; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_oid( p, start, oid, oid_len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); return( (int) len ); } /** * \brief Write a boolean tag (#MBEDTLS_ASN1_BOOLEAN) and value * in ASN.1 format. * * \note This function works backwards in data buffer. * * \param p The reference to the current position pointer. * \param start The start of the buffer, for bounds-checking. * \param boolean The boolean value to write, either \c 0 or \c 1. * * \return The number of bytes written to \p p on success. * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_asn1_write_bool( unsigned char **p, unsigned char *start, int boolean ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len = 0; if( *p - start < 1 ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); *--(*p) = (boolean) ? 255 : 0; len++; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_BOOLEAN ) ); return( (int) len ); } static int asn1_write_tagged_int( unsigned char **p, unsigned char *start, int val, int tag ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len = 0; do { if( *p - start < 1 ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); len += 1; *--(*p) = val & 0xff; val >>= 8; } while( val > 0 ); if( **p & 0x80 ) { if( *p - start < 1 ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); *--(*p) = 0x00; len += 1; } MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, tag ) ); return( (int) len ); } /** * \brief Write an int tag (#MBEDTLS_ASN1_INTEGER) and value * in ASN.1 format. * * \note This function works backwards in data buffer. * * \param p The reference to the current position pointer. * \param start The start of the buffer, for bounds-checking. * \param val The integer value to write. * It must be non-negative. * * \return The number of bytes written to \p p on success. * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_asn1_write_int( unsigned char **p, unsigned char *start, int val ) { return( asn1_write_tagged_int( p, start, val, MBEDTLS_ASN1_INTEGER ) ); } /** * \brief Write an enum tag (#MBEDTLS_ASN1_ENUMERATED) and value * in ASN.1 format. * * \note This function works backwards in data buffer. * * \param p The reference to the current position pointer. * \param start The start of the buffer, for bounds-checking. * \param val The integer value to write. * * \return The number of bytes written to \p p on success. * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_asn1_write_enum( unsigned char **p, unsigned char *start, int val ) { return( asn1_write_tagged_int( p, start, val, MBEDTLS_ASN1_ENUMERATED ) ); } /** * \brief Write a string in ASN.1 format using a specific * string encoding tag. * * \note This function works backwards in data buffer. * * \param p The reference to the current position pointer. * \param start The start of the buffer, for bounds-checking. * \param tag The string encoding tag to write, e.g. * #MBEDTLS_ASN1_UTF8_STRING. * \param text The string to write. * \param text_len The length of \p text in bytes (which might * be strictly larger than the number of characters). * * \return The number of bytes written to \p p on success. * \return A negative error code on failure. */ int mbedtls_asn1_write_tagged_string( unsigned char **p, unsigned char *start, int tag, const char *text, size_t text_len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len = 0; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start, (const unsigned char *) text, text_len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, tag ) ); return( (int) len ); } /** * \brief Write a UTF8 string in ASN.1 format using the UTF8String * string encoding tag (#MBEDTLS_ASN1_UTF8_STRING). * * \note This function works backwards in data buffer. * * \param p The reference to the current position pointer. * \param start The start of the buffer, for bounds-checking. * \param text The string to write. * \param text_len The length of \p text in bytes (which might * be strictly larger than the number of characters). * * \return The number of bytes written to \p p on success. * \return A negative error code on failure. */ int mbedtls_asn1_write_utf8_string( unsigned char **p, unsigned char *start, const char *text, size_t text_len ) { return( mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_UTF8_STRING, text, text_len) ); } /** * \brief Write a string in ASN.1 format using the PrintableString * string encoding tag (#MBEDTLS_ASN1_PRINTABLE_STRING). * * \note This function works backwards in data buffer. * * \param p The reference to the current position pointer. * \param start The start of the buffer, for bounds-checking. * \param text The string to write. * \param text_len The length of \p text in bytes (which might * be strictly larger than the number of characters). * * \return The number of bytes written to \p p on success. * \return A negative error code on failure. */ int mbedtls_asn1_write_printable_string( unsigned char **p, unsigned char *start, const char *text, size_t text_len ) { return( mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_PRINTABLE_STRING, text, text_len) ); } /** * \brief Write a string in ASN.1 format using the IA5String * string encoding tag (#MBEDTLS_ASN1_IA5_STRING). * * \note This function works backwards in data buffer. * * \param p The reference to the current position pointer. * \param start The start of the buffer, for bounds-checking. * \param text The string to write. * \param text_len The length of \p text in bytes (which might * be strictly larger than the number of characters). * * \return The number of bytes written to \p p on success. * \return A negative error code on failure. */ int mbedtls_asn1_write_ia5_string( unsigned char **p, unsigned char *start, const char *text, size_t text_len ) { return( mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_IA5_STRING, text, text_len) ); } /** * \brief This function writes a named bitstring tag * (#MBEDTLS_ASN1_BIT_STRING) and value in ASN.1 format. * * As stated in RFC 5280 Appendix B, trailing zeroes are * omitted when encoding named bitstrings in DER. * * \note This function works backwards within the data buffer. * * \param p The reference to the current position pointer. * \param start The start of the buffer which is used for bounds-checking. * \param buf The bitstring to write. * \param bits The total number of bits in the bitstring. * * \return The number of bytes written to \p p on success. * \return A negative error code on failure. */ int mbedtls_asn1_write_named_bitstring( unsigned char **p, unsigned char *start, const unsigned char *buf, size_t bits ) { size_t unused_bits, byte_len; const unsigned char *cur_byte; unsigned char cur_byte_shifted; unsigned char bit; byte_len = ( bits + 7 ) / 8; unused_bits = ( byte_len * 8 ) - bits; /* * Named bitstrings require that trailing 0s are excluded in the encoding * of the bitstring. Trailing 0s are considered part of the 'unused' bits * when encoding this value in the first content octet */ if( bits ) { cur_byte = buf + byte_len - 1; cur_byte_shifted = *cur_byte >> unused_bits; for( ; ; ) { bit = cur_byte_shifted & 0x1; cur_byte_shifted >>= 1; if( bit ) break; bits--; if( bits == 0 ) break; if( bits % 8 == 0 ) cur_byte_shifted = *--cur_byte; } } return( mbedtls_asn1_write_bitstring( p, start, buf, bits ) ); } /** * \brief Write a bitstring tag (#MBEDTLS_ASN1_BIT_STRING) and * value in ASN.1 format. * * \note This function works backwards in data buffer. * * \param p The reference to the current position pointer. * \param start The start of the buffer, for bounds-checking. * \param buf The bitstring to write. * \param bits The total number of bits in the bitstring. * * \return The number of bytes written to \p p on success. * \return A negative error code on failure. */ int mbedtls_asn1_write_bitstring( unsigned char **p, unsigned char *start, const unsigned char *buf, size_t bits ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len = 0; size_t unused_bits, byte_len; byte_len = ( bits + 7 ) / 8; unused_bits = ( byte_len * 8 ) - bits; if( *p < start || (size_t)( *p - start ) < byte_len + 1 ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); len = byte_len + 1; /* Write the bitstring. Ensure the unused bits are zeroed */ if( byte_len > 0 ) { byte_len--; *--( *p ) = buf[byte_len] & ~( ( 0x1 << unused_bits ) - 1 ); ( *p ) -= byte_len; memcpy( *p, buf, byte_len ); } /* Write unused bits */ *--( *p ) = (unsigned char)unused_bits; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_BIT_STRING ) ); return( (int) len ); } /** * \brief Write an octet string tag (#MBEDTLS_ASN1_OCTET_STRING) * and value in ASN.1 format. * * \note This function works backwards in data buffer. * * \param p The reference to the current position pointer. * \param start The start of the buffer, for bounds-checking. * \param buf The buffer holding the data to write. * \param size The length of the data buffer \p buf. * * \return The number of bytes written to \p p on success. * \return A negative error code on failure. */ int mbedtls_asn1_write_octet_string( unsigned char **p, unsigned char *start, const unsigned char *buf, size_t size ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len = 0; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start, buf, size ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_OCTET_STRING ) ); return( (int) len ); } /* This is a copy of the ASN.1 parsing function mbedtls_asn1_find_named_data(), * which is replicated to avoid a dependency ASN1_WRITE_C on ASN1_PARSE_C. */ static mbedtls_asn1_named_data *asn1_find_named_data( mbedtls_asn1_named_data *list, const char *oid, size_t len ) { while( list ) { if( list->oid.len == len && timingsafe_bcmp( list->oid.p, oid, len ) == 0 ) { break; } list = list->next; } return( list ); } /** * \brief Create or find a specific named_data entry for writing in a * sequence or list based on the OID. If not already in there, * a new entry is added to the head of the list. * Warning: Destructive behaviour for the val data! * * \param list The pointer to the location of the head of the list to seek * through (will be updated in case of a new entry). * \param oid The OID to look for. * \param oid_len The size of the OID. * \param val The associated data to store. If this is \c NULL, * no data is copied to the new or existing buffer. * \param val_len The minimum length of the data buffer needed. * If this is 0, do not allocate a buffer for the associated * data. * If the OID was already present, enlarge, shrink or free * the existing buffer to fit \p val_len. * * \return A pointer to the new / existing entry on success. * \return \c NULL if if there was a memory allocation error. */ mbedtls_asn1_named_data *mbedtls_asn1_store_named_data(mbedtls_asn1_named_data **head, const char *oid, size_t oid_len, const unsigned char *val, size_t val_len ) { mbedtls_asn1_named_data *cur; if( ( cur = asn1_find_named_data( *head, oid, oid_len ) ) == NULL ) { // Add new entry if not present yet based on OID // cur = (mbedtls_asn1_named_data*)mbedtls_calloc( 1, sizeof(mbedtls_asn1_named_data) ); if( !cur ) return( NULL ); cur->oid.len = oid_len; cur->oid.p = mbedtls_calloc( 1, oid_len ); if( !cur->oid.p ) { mbedtls_free( cur ); return( NULL ); } memcpy( cur->oid.p, oid, oid_len ); cur->val.len = val_len; if( val_len ) { cur->val.p = mbedtls_calloc( 1, val_len ); if( !cur->val.p ) { mbedtls_free( cur->oid.p ); mbedtls_free( cur ); return( NULL ); } } cur->next = *head; *head = cur; } else if( val_len == 0 ) { mbedtls_free( cur->val.p ); cur->val.p = NULL; } else if( cur->val.len != val_len ) { /* * Enlarge existing value buffer if needed * Preserve old data until the allocation succeeded, to leave list in * a consistent state in case allocation fails. */ void *p = mbedtls_calloc( 1, val_len ); if( !p ) return( NULL ); mbedtls_free( cur->val.p ); cur->val.p = p; cur->val.len = val_len; } if( val ) memcpy( cur->val.p, val, val_len ); return( cur ); } #endif /* MBEDTLS_ASN1_WRITE_C */
25,810
671
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/des.h
#ifndef MBEDTLS_DES_H #define MBEDTLS_DES_H #include "third_party/mbedtls/config.h" /* clang-format off */ #define MBEDTLS_DES_ENCRYPT 1 #define MBEDTLS_DES_DECRYPT 0 #define MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH -0x0032 /*< The data input has an invalid length. */ /* MBEDTLS_ERR_DES_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_DES_HW_ACCEL_FAILED -0x0033 /*< DES hardware accelerator failed. */ #define MBEDTLS_DES_KEY_SIZE 8 #ifdef __cplusplus extern "C" { #endif #if !defined(MBEDTLS_DES_ALT) // Regular implementation // /** * \brief DES context structure * * \warning DES is considered a weak cipher and its use constitutes a * security risk. We recommend considering stronger ciphers * instead. */ typedef struct mbedtls_des_context { uint32_t sk[32]; /*!< DES subkeys */ } mbedtls_des_context; /** * \brief Triple-DES context structure */ typedef struct mbedtls_des3_context { uint32_t sk[96]; /*!< 3DES subkeys */ } mbedtls_des3_context; #endif /* MBEDTLS_DES_ALT */ /** * \brief Initialize DES context * * \param ctx DES context to be initialized * * \warning DES is considered a weak cipher and its use constitutes a * security risk. We recommend considering stronger ciphers * instead. */ void mbedtls_des_init( mbedtls_des_context *ctx ); /** * \brief Clear DES context * * \param ctx DES context to be cleared * * \warning DES is considered a weak cipher and its use constitutes a * security risk. We recommend considering stronger ciphers * instead. */ void mbedtls_des_free( mbedtls_des_context *ctx ); /** * \brief Initialize Triple-DES context * * \param ctx DES3 context to be initialized */ void mbedtls_des3_init( mbedtls_des3_context *ctx ); /** * \brief Clear Triple-DES context * * \param ctx DES3 context to be cleared */ void mbedtls_des3_free( mbedtls_des3_context *ctx ); /** * \brief Set key parity on the given key to odd. * * DES keys are 56 bits long, but each byte is padded with * a parity bit to allow verification. * * \param key 8-byte secret key * * \warning DES is considered a weak cipher and its use constitutes a * security risk. We recommend considering stronger ciphers * instead. */ void mbedtls_des_key_set_parity( unsigned char key[MBEDTLS_DES_KEY_SIZE] ); /** * \brief Check that key parity on the given key is odd. * * DES keys are 56 bits long, but each byte is padded with * a parity bit to allow verification. * * \param key 8-byte secret key * * \return 0 is parity was ok, 1 if parity was not correct. * * \warning DES is considered a weak cipher and its use constitutes a * security risk. We recommend considering stronger ciphers * instead. */ int mbedtls_des_key_check_key_parity( const unsigned char key[MBEDTLS_DES_KEY_SIZE] ); /** * \brief Check that key is not a weak or semi-weak DES key * * \param key 8-byte secret key * * \return 0 if no weak key was found, 1 if a weak key was identified. * * \warning DES is considered a weak cipher and its use constitutes a * security risk. We recommend considering stronger ciphers * instead. */ int mbedtls_des_key_check_weak( const unsigned char key[MBEDTLS_DES_KEY_SIZE] ); /** * \brief DES key schedule (56-bit, encryption) * * \param ctx DES context to be initialized * \param key 8-byte secret key * * \return 0 * * \warning DES is considered a weak cipher and its use constitutes a * security risk. We recommend considering stronger ciphers * instead. */ int mbedtls_des_setkey_enc( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] ); /** * \brief DES key schedule (56-bit, decryption) * * \param ctx DES context to be initialized * \param key 8-byte secret key * * \return 0 * * \warning DES is considered a weak cipher and its use constitutes a * security risk. We recommend considering stronger ciphers * instead. */ int mbedtls_des_setkey_dec( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] ); /** * \brief Triple-DES key schedule (112-bit, encryption) * * \param ctx 3DES context to be initialized * \param key 16-byte secret key * * \return 0 */ int mbedtls_des3_set2key_enc( mbedtls_des3_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE * 2] ); /** * \brief Triple-DES key schedule (112-bit, decryption) * * \param ctx 3DES context to be initialized * \param key 16-byte secret key * * \return 0 */ int mbedtls_des3_set2key_dec( mbedtls_des3_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE * 2] ); /** * \brief Triple-DES key schedule (168-bit, encryption) * * \param ctx 3DES context to be initialized * \param key 24-byte secret key * * \return 0 */ int mbedtls_des3_set3key_enc( mbedtls_des3_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE * 3] ); /** * \brief Triple-DES key schedule (168-bit, decryption) * * \param ctx 3DES context to be initialized * \param key 24-byte secret key * * \return 0 */ int mbedtls_des3_set3key_dec( mbedtls_des3_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE * 3] ); /** * \brief DES-ECB block encryption/decryption * * \param ctx DES context * \param input 64-bit input block * \param output 64-bit output block * * \return 0 if successful * * \warning DES is considered a weak cipher and its use constitutes a * security risk. We recommend considering stronger ciphers * instead. */ int mbedtls_des_crypt_ecb( mbedtls_des_context *ctx, const unsigned char input[8], unsigned char output[8] ); #if defined(MBEDTLS_CIPHER_MODE_CBC) /** * \brief DES-CBC buffer encryption/decryption * * \note Upon exit, the content of the IV is updated so that you can * call the function same function again on the following * block(s) of data and get the same result as if it was * encrypted in one call. This allows a "streaming" usage. * If on the other hand you need to retain the contents of the * IV, you should either save it manually or use the cipher * module instead. * * \param ctx DES context * \param mode MBEDTLS_DES_ENCRYPT or MBEDTLS_DES_DECRYPT * \param length length of the input data * \param iv initialization vector (updated after use) * \param input buffer holding the input data * \param output buffer holding the output data * * \warning DES is considered a weak cipher and its use constitutes a * security risk. We recommend considering stronger ciphers * instead. */ int mbedtls_des_crypt_cbc( mbedtls_des_context *ctx, int mode, size_t length, unsigned char iv[8], const unsigned char *input, unsigned char *output ); #endif /* MBEDTLS_CIPHER_MODE_CBC */ /** * \brief 3DES-ECB block encryption/decryption * * \param ctx 3DES context * \param input 64-bit input block * \param output 64-bit output block * * \return 0 if successful */ int mbedtls_des3_crypt_ecb( mbedtls_des3_context *ctx, const unsigned char input[8], unsigned char output[8] ); #if defined(MBEDTLS_CIPHER_MODE_CBC) /** * \brief 3DES-CBC buffer encryption/decryption * * \note Upon exit, the content of the IV is updated so that you can * call the function same function again on the following * block(s) of data and get the same result as if it was * encrypted in one call. This allows a "streaming" usage. * If on the other hand you need to retain the contents of the * IV, you should either save it manually or use the cipher * module instead. * * \param ctx 3DES context * \param mode MBEDTLS_DES_ENCRYPT or MBEDTLS_DES_DECRYPT * \param length length of the input data * \param iv initialization vector (updated after use) * \param input buffer holding the input data * \param output buffer holding the output data * * \return 0 if successful, or MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH */ int mbedtls_des3_crypt_cbc( mbedtls_des3_context *ctx, int mode, size_t length, unsigned char iv[8], const unsigned char *input, unsigned char *output ); #endif /* MBEDTLS_CIPHER_MODE_CBC */ /** * \brief Internal function for key expansion. * (Only exposed to allow overriding it, * see MBEDTLS_DES_SETKEY_ALT) * * \param SK Round keys * \param key Base key * * \warning DES is considered a weak cipher and its use constitutes a * security risk. We recommend considering stronger ciphers * instead. */ void mbedtls_des_setkey( uint32_t SK[32], const unsigned char key[MBEDTLS_DES_KEY_SIZE] ); #if defined(MBEDTLS_SELF_TEST) /** * \brief Checkup routine * * \return 0 if successful, or 1 if the test failed */ int mbedtls_des_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST */ #ifdef __cplusplus } #endif #endif /* des.h */
10,291
320
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/ecdh_everest.h
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_X25519_H_ #define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_X25519_H_ #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/ecp.h" COSMOPOLITAN_C_START_ #define MBEDTLS_ECP_TLS_CURVE25519 0x1d #define MBEDTLS_X25519_KEY_SIZE_BYTES 32 typedef enum { MBEDTLS_EVEREST_ECDH_OURS, MBEDTLS_EVEREST_ECDH_THEIRS, } mbedtls_everest_ecdh_side; typedef struct { unsigned char our_secret[MBEDTLS_X25519_KEY_SIZE_BYTES]; unsigned char peer_point[MBEDTLS_X25519_KEY_SIZE_BYTES]; } mbedtls_ecdh_context_everest; int mbedtls_everest_setup(mbedtls_ecdh_context_everest *, int); void mbedtls_everest_free(mbedtls_ecdh_context_everest *); int mbedtls_everest_make_params(mbedtls_ecdh_context_everest *, size_t *, unsigned char *, size_t, int (*)(void *, unsigned char *, size_t), void *); int mbedtls_everest_read_params(mbedtls_ecdh_context_everest *, const unsigned char **, const unsigned char *); int mbedtls_everest_get_params(mbedtls_ecdh_context_everest *, const mbedtls_ecp_keypair *, mbedtls_everest_ecdh_side); int mbedtls_everest_make_public(mbedtls_ecdh_context_everest *, size_t *, unsigned char *, size_t, int (*)(void *, unsigned char *, size_t), void *); int mbedtls_everest_read_public(mbedtls_ecdh_context_everest *, const unsigned char *, size_t); int mbedtls_everest_calc_secret(mbedtls_ecdh_context_everest *, size_t *, unsigned char *, size_t, int (*)(void *, unsigned char *, size_t), void *); COSMOPOLITAN_C_END_ #endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_X25519_H_ */
1,952
44
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/getalertdescription.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/fmt/itoa.h" #include "third_party/mbedtls/iana.h" #include "third_party/mbedtls/ssl.h" /** * Returns SSL fatal alert description. * @see RFC5246 §7.2 */ const char *GetAlertDescription(unsigned char x) { static char buf[21]; switch (x) { case MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY: /* 0 */ return "close_notify"; case MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE: /* 10 */ return "unexpected_message"; case MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC: /* 20 */ return "bad_record_mac"; case MBEDTLS_SSL_ALERT_MSG_DECRYPTION_FAILED: /* 21 */ return "decryption_failed"; case MBEDTLS_SSL_ALERT_MSG_RECORD_OVERFLOW: /* 22 */ return "record_overflow"; case MBEDTLS_SSL_ALERT_MSG_DECOMPRESSION_FAILURE: /* 30 */ return "decompression_failure"; case MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE: /* 40 */ return "handshake_failure"; case MBEDTLS_SSL_ALERT_MSG_NO_CERT: /* 41 */ return "no_cert"; case MBEDTLS_SSL_ALERT_MSG_BAD_CERT: /* 42 */ return "bad_cert"; case MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT: /* 43 */ return "unsupported_cert"; case MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED: /* 44 */ return "cert_revoked"; case MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED: /* 45 */ return "cert_expired"; case MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN: /* 46 */ return "cert_unknown"; case MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER: /* 47 */ return "illegal_parameter"; case MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA: /* 48 */ return "unknown_ca"; case MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED: /* 49 */ return "access_denied"; case MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR: /* 50 */ return "decode_error"; case MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR: /* 51 */ return "decrypt_error"; case MBEDTLS_SSL_ALERT_MSG_EXPORT_RESTRICTION: /* 60 */ return "export_restriction"; case MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION: /* 70 */ return "protocol_version"; case MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY: /* 71 */ return "insufficient_security"; case MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR: /* 80 */ return "internal_error"; case MBEDTLS_SSL_ALERT_MSG_USER_CANCELED: /* 90 */ return "user_canceled"; case MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION: /* 100 */ return "no_renegotiation"; case MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT: /* 110 */ return "unsupported_extension"; default: FormatUint32(buf, x); return buf; } }
4,278
84
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/x509_crl.h
#ifndef MBEDTLS_X509_CRL_H #define MBEDTLS_X509_CRL_H #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/x509.h" /* clang-format off */ #ifdef __cplusplus extern "C" { #endif /** * \addtogroup x509_module * \{ */ /** * \name Structures and functions for parsing CRLs * \{ */ /** * Certificate revocation list entry. * Contains the CA-specific serial numbers and revocation dates. */ typedef struct mbedtls_x509_crl_entry { mbedtls_x509_buf raw; mbedtls_x509_buf serial; mbedtls_x509_time revocation_date; mbedtls_x509_buf entry_ext; struct mbedtls_x509_crl_entry *next; } mbedtls_x509_crl_entry; /** * Certificate revocation list structure. * Every CRL may have multiple entries. */ typedef struct mbedtls_x509_crl { mbedtls_x509_buf raw; /*< The raw certificate data (DER). */ mbedtls_x509_buf tbs; /*< The raw certificate body (DER). The part that is To Be Signed. */ int version; /*< CRL version (1=v1, 2=v2) */ mbedtls_x509_buf sig_oid; /*< CRL signature type identifier */ mbedtls_x509_buf issuer_raw; /*< The raw issuer data (DER). */ mbedtls_x509_name issuer; /*< The parsed issuer data (named information object). */ mbedtls_x509_time this_update; mbedtls_x509_time next_update; mbedtls_x509_crl_entry entry; /*< The CRL entries containing the certificate revocation times for this CA. */ mbedtls_x509_buf crl_ext; mbedtls_x509_buf sig_oid2; mbedtls_x509_buf sig; mbedtls_md_type_t sig_md; /*< Internal representation of the MD algorithm of the signature algorithm, e.g. MBEDTLS_MD_SHA256 */ mbedtls_pk_type_t sig_pk; /*< Internal representation of the Public Key algorithm of the signature algorithm, e.g. MBEDTLS_PK_RSA */ void *sig_opts; /*< Signature options to be passed to mbedtls_pk_verify_ext(), e.g. for RSASSA-PSS */ struct mbedtls_x509_crl *next; } mbedtls_x509_crl; /** * \brief Parse a DER-encoded CRL and append it to the chained list * * \param chain points to the start of the chain * \param buf buffer holding the CRL data in DER format * \param buflen size of the buffer * (including the terminating null byte for PEM data) * * \return 0 if successful, or a specific X509 or PEM error code */ int mbedtls_x509_crl_parse_der( mbedtls_x509_crl *chain, const unsigned char *buf, size_t buflen ); /** * \brief Parse one or more CRLs and append them to the chained list * * \note Multiple CRLs are accepted only if using PEM format * * \param chain points to the start of the chain * \param buf buffer holding the CRL data in PEM or DER format * \param buflen size of the buffer * (including the terminating null byte for PEM data) * * \return 0 if successful, or a specific X509 or PEM error code */ int mbedtls_x509_crl_parse( mbedtls_x509_crl *chain, const unsigned char *buf, size_t buflen ); /** * \brief Load one or more CRLs and append them to the chained list * * \note Multiple CRLs are accepted only if using PEM format * * \param chain points to the start of the chain * \param path filename to read the CRLs from (in PEM or DER encoding) * * \return 0 if successful, or a specific X509 or PEM error code */ int mbedtls_x509_crl_parse_file( mbedtls_x509_crl *chain, const char *path ); /** * \brief Returns an informational string about the CRL. * * \param buf Buffer to write to * \param size Maximum size of buffer * \param prefix A line prefix * \param crl The X509 CRL to represent * * \return The length of the string written (not including the * terminated nul byte), or a negative error code. */ int mbedtls_x509_crl_info( char *buf, size_t size, const char *prefix, const mbedtls_x509_crl *crl ); /** * \brief Initialize a CRL (chain) * * \param crl CRL chain to initialize */ void mbedtls_x509_crl_init( mbedtls_x509_crl *crl ); /** * \brief Unallocate all CRL data * * \param crl CRL chain to free */ void mbedtls_x509_crl_free( mbedtls_x509_crl *crl ); /* \} name */ /* \} addtogroup x509_module */ #ifdef __cplusplus } #endif #endif /* mbedtls_x509_crl.h */
4,418
145
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/hmac_drbg.h
#ifndef MBEDTLS_HMAC_DRBG_H_ #define MBEDTLS_HMAC_DRBG_H_ #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/md.h" COSMOPOLITAN_C_START_ /* clang-format off */ #define MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG -0x0003 /*< Too many random requested in single call. */ #define MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG -0x0005 /*< Input too large (Entropy + additional). */ #define MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR -0x0007 /*< Read/write error in file. */ #define MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED -0x0009 /*< The entropy source failed. */ #if !defined(MBEDTLS_HMAC_DRBG_RESEED_INTERVAL) #define MBEDTLS_HMAC_DRBG_RESEED_INTERVAL 10000 /*< Interval before reseed is performed by default */ #endif #if !defined(MBEDTLS_HMAC_DRBG_MAX_INPUT) #define MBEDTLS_HMAC_DRBG_MAX_INPUT 256 /*< Maximum number of additional input bytes */ #endif #if !defined(MBEDTLS_HMAC_DRBG_MAX_REQUEST) #define MBEDTLS_HMAC_DRBG_MAX_REQUEST 1024 /*< Maximum number of requested bytes per call */ #endif #if !defined(MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT) #define MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT 384 /*< Maximum size of (re)seed buffer */ #endif #define MBEDTLS_HMAC_DRBG_PR_OFF 0 /*< No prediction resistance */ #define MBEDTLS_HMAC_DRBG_PR_ON 1 /*< Prediction resistance enabled */ typedef struct mbedtls_hmac_drbg_context { mbedtls_md_context_t md_ctx; unsigned char V[MBEDTLS_MD_MAX_SIZE]; int reseed_counter; size_t entropy_len; int prediction_resistance; int reseed_interval; int (*f_entropy)(void *, unsigned char *, size_t); void *p_entropy; } mbedtls_hmac_drbg_context; void mbedtls_hmac_drbg_init( mbedtls_hmac_drbg_context * ); int mbedtls_hmac_drbg_seed( mbedtls_hmac_drbg_context *, const mbedtls_md_info_t * , int (*)(void *, unsigned char *, size_t), void *, const unsigned char *, size_t ); int mbedtls_hmac_drbg_seed_buf( mbedtls_hmac_drbg_context *, const mbedtls_md_info_t *, const unsigned char *, size_t ); void mbedtls_hmac_drbg_set_prediction_resistance( mbedtls_hmac_drbg_context *, int ); void mbedtls_hmac_drbg_set_entropy_len( mbedtls_hmac_drbg_context *, size_t ); void mbedtls_hmac_drbg_set_reseed_interval( mbedtls_hmac_drbg_context *, int ); int mbedtls_hmac_drbg_update_ret( mbedtls_hmac_drbg_context *, const unsigned char *, size_t ); int mbedtls_hmac_drbg_reseed( mbedtls_hmac_drbg_context *, const unsigned char *, size_t ); int mbedtls_hmac_drbg_random_with_add( void *, unsigned char *, size_t , const unsigned char *, size_t ); int mbedtls_hmac_drbg_random( void *, unsigned char *, size_t ); void mbedtls_hmac_drbg_free( mbedtls_hmac_drbg_context * ); int mbedtls_hmac_drbg_write_seed_file( mbedtls_hmac_drbg_context *, const char * ); int mbedtls_hmac_drbg_update_seed_file( mbedtls_hmac_drbg_context *, const char * ); int mbedtls_hmac_drbg_self_test( int ); COSMOPOLITAN_C_END_ #endif /* MBEDTLS_HMAC_DRBG_H_ */
2,988
61
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/nist_kw.h
#ifndef MBEDTLS_NIST_KW_H #define MBEDTLS_NIST_KW_H #include "third_party/mbedtls/cipher.h" #include "third_party/mbedtls/config.h" /* clang-format off */ #ifdef __cplusplus extern "C" { #endif typedef enum { MBEDTLS_KW_MODE_KW = 0, MBEDTLS_KW_MODE_KWP = 1 } mbedtls_nist_kw_mode_t; #if !defined(MBEDTLS_NIST_KW_ALT) // Regular implementation // /** * \brief The key wrapping context-type definition. The key wrapping context is passed * to the APIs called. * * \note The definition of this type may change in future library versions. * Don't make any assumptions on this context! */ typedef struct { mbedtls_cipher_context_t cipher_ctx; /*!< The cipher context used. */ } mbedtls_nist_kw_context; #endif /* MBEDTLS_NIST_KW_ALT */ /** * \brief This function initializes the specified key wrapping context * to make references valid and prepare the context * for mbedtls_nist_kw_setkey() or mbedtls_nist_kw_free(). * * \param ctx The key wrapping context to initialize. * */ void mbedtls_nist_kw_init( mbedtls_nist_kw_context *ctx ); /** * \brief This function initializes the key wrapping context set in the * \p ctx parameter and sets the encryption key. * * \param ctx The key wrapping context. * \param cipher The 128-bit block cipher to use. Only AES is supported. * \param key The Key Encryption Key (KEK). * \param keybits The KEK size in bits. This must be acceptable by the cipher. * \param is_wrap Specify whether the operation within the context is wrapping or unwrapping * * \return \c 0 on success. * \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for any invalid input. * \return \c MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE for 128-bit block ciphers * which are not supported. * \return cipher-specific error code on failure of the underlying cipher. */ int mbedtls_nist_kw_setkey( mbedtls_nist_kw_context *ctx, mbedtls_cipher_id_t cipher, const unsigned char *key, unsigned int keybits, const int is_wrap ); /** * \brief This function releases and clears the specified key wrapping context * and underlying cipher sub-context. * * \param ctx The key wrapping context to clear. */ void mbedtls_nist_kw_free( mbedtls_nist_kw_context *ctx ); /** * \brief This function encrypts a buffer using key wrapping. * * \param ctx The key wrapping context to use for encryption. * \param mode The key wrapping mode to use (MBEDTLS_KW_MODE_KW or MBEDTLS_KW_MODE_KWP) * \param input The buffer holding the input data. * \param in_len The length of the input data in Bytes. * The input uses units of 8 Bytes called semiblocks. * <ul><li>For KW mode: a multiple of 8 bytes between 16 and 2^57-8 inclusive. </li> * <li>For KWP mode: any length between 1 and 2^32-1 inclusive.</li></ul> * \param[out] output The buffer holding the output data. * <ul><li>For KW mode: Must be at least 8 bytes larger than \p in_len.</li> * <li>For KWP mode: Must be at least 8 bytes larger rounded up to a multiple of * 8 bytes for KWP (15 bytes at most).</li></ul> * \param[out] out_len The number of bytes written to the output buffer. \c 0 on failure. * \param[in] out_size The capacity of the output buffer. * * \return \c 0 on success. * \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for invalid input length. * \return cipher-specific error code on failure of the underlying cipher. */ int mbedtls_nist_kw_wrap( mbedtls_nist_kw_context *ctx, mbedtls_nist_kw_mode_t mode, const unsigned char *input, size_t in_len, unsigned char *output, size_t* out_len, size_t out_size ); /** * \brief This function decrypts a buffer using key wrapping. * * \param ctx The key wrapping context to use for decryption. * \param mode The key wrapping mode to use (MBEDTLS_KW_MODE_KW or MBEDTLS_KW_MODE_KWP) * \param input The buffer holding the input data. * \param in_len The length of the input data in Bytes. * The input uses units of 8 Bytes called semiblocks. * The input must be a multiple of semiblocks. * <ul><li>For KW mode: a multiple of 8 bytes between 24 and 2^57 inclusive. </li> * <li>For KWP mode: a multiple of 8 bytes between 16 and 2^32 inclusive.</li></ul> * \param[out] output The buffer holding the output data. * The output buffer's minimal length is 8 bytes shorter than \p in_len. * \param[out] out_len The number of bytes written to the output buffer. \c 0 on failure. * For KWP mode, the length could be up to 15 bytes shorter than \p in_len, * depending on how much padding was added to the data. * \param[in] out_size The capacity of the output buffer. * * \return \c 0 on success. * \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for invalid input length. * \return \c MBEDTLS_ERR_CIPHER_AUTH_FAILED for verification failure of the ciphertext. * \return cipher-specific error code on failure of the underlying cipher. */ int mbedtls_nist_kw_unwrap( mbedtls_nist_kw_context *ctx, mbedtls_nist_kw_mode_t mode, const unsigned char *input, size_t in_len, unsigned char *output, size_t* out_len, size_t out_size); #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C) /** * \brief The key wrapping checkup routine. * * \return \c 0 on success. * \return \c 1 on failure. */ int mbedtls_nist_kw_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */ #ifdef __cplusplus } #endif #endif /* MBEDTLS_NIST_KW_H */
6,105
142
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/san.h
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_SAN_H_ #define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_SAN_H_ #include "third_party/mbedtls/x509_crt.h" COSMOPOLITAN_C_START_ struct mbedtls_san { int tag; union { const char *val; uint32_t ip4; }; }; int mbedtls_x509write_crt_set_subject_alternative_name( mbedtls_x509write_cert *, const struct mbedtls_san *, size_t); COSMOPOLITAN_C_END_ #endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_SAN_H_ */
448
19
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/md5t.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "third_party/mbedtls/md5.h" #include "third_party/mbedtls/platform.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off /* * RFC 1321 test vectors */ static const unsigned char md5_test_buf[7][81] = { { "" }, { "a" }, { "abc" }, { "message digest" }, { "abcdefghijklmnopqrstuvwxyz" }, { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" }, { "12345678901234567890123456789012345678901234567890123456789012345678901234567890" } }; static const size_t md5_test_buflen[7] = { 0, 1, 3, 14, 26, 62, 80 }; static const unsigned char md5_test_sum[7][16] = { { 0xD4, 0x1D, 0x8C, 0xD9, 0x8F, 0x00, 0xB2, 0x04, 0xE9, 0x80, 0x09, 0x98, 0xEC, 0xF8, 0x42, 0x7E }, { 0x0C, 0xC1, 0x75, 0xB9, 0xC0, 0xF1, 0xB6, 0xA8, 0x31, 0xC3, 0x99, 0xE2, 0x69, 0x77, 0x26, 0x61 }, { 0x90, 0x01, 0x50, 0x98, 0x3C, 0xD2, 0x4F, 0xB0, 0xD6, 0x96, 0x3F, 0x7D, 0x28, 0xE1, 0x7F, 0x72 }, { 0xF9, 0x6B, 0x69, 0x7D, 0x7C, 0xB7, 0x93, 0x8D, 0x52, 0x5A, 0x2F, 0x31, 0xAA, 0xF1, 0x61, 0xD0 }, { 0xC3, 0xFC, 0xD3, 0xD7, 0x61, 0x92, 0xE4, 0x00, 0x7D, 0xFB, 0x49, 0x6C, 0xCA, 0x67, 0xE1, 0x3B }, { 0xD1, 0x74, 0xAB, 0x98, 0xD2, 0x77, 0xD9, 0xF5, 0xA5, 0x61, 0x1C, 0x2C, 0x9F, 0x41, 0x9D, 0x9F }, { 0x57, 0xED, 0xF4, 0xA2, 0x2B, 0xE3, 0xC9, 0x55, 0xAC, 0x49, 0xDA, 0x2E, 0x21, 0x07, 0xB6, 0x7A } }; /** * \brief Checkup routine * * \return 0 if successful, or 1 if the test failed * * \warning MD5 is considered a weak message digest and its use * constitutes a security risk. We recommend considering * stronger message digests instead. * */ int mbedtls_md5_self_test( int verbose ) { int i, ret = 0; unsigned char md5sum[16]; for( i = 0; i < 7; i++ ) { if( verbose != 0 ) mbedtls_printf( " MD5 test #%d: ", i + 1 ); ret = mbedtls_md5_ret( md5_test_buf[i], md5_test_buflen[i], md5sum ); if( ret != 0 ) goto fail; if( timingsafe_bcmp( md5sum, md5_test_sum[i], 16 ) != 0 ) { ret = 1; goto fail; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); } if( verbose != 0 ) mbedtls_printf( "\n" ); return( 0 ); fail: if( verbose != 0 ) mbedtls_printf( "failed\n" ); return( ret ); }
4,304
111
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/ssl_cache.h
#ifndef MBEDTLS_SSL_CACHE_H #define MBEDTLS_SSL_CACHE_H #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/ssl.h" /* clang-format off */ /** * \name SECTION: Module settings * * The configuration options you can set for this module are in this section. * Either change them in config.h or define them on the compiler command line. * \{ */ #if !defined(MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT) #define MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT 86400 /*!< 1 day */ #endif #if !defined(MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES) #define MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES 50 /*!< Maximum entries in cache */ #endif /* \} name SECTION: Module settings */ #ifdef __cplusplus extern "C" { #endif typedef struct mbedtls_ssl_cache_context mbedtls_ssl_cache_context; typedef struct mbedtls_ssl_cache_entry mbedtls_ssl_cache_entry; /** * \brief This structure is used for storing cache entries */ struct mbedtls_ssl_cache_entry { #if defined(MBEDTLS_HAVE_TIME) mbedtls_time_t timestamp; /*!< entry timestamp */ #endif mbedtls_ssl_session session; /*!< entry session */ #if defined(MBEDTLS_X509_CRT_PARSE_C) && \ defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) mbedtls_x509_buf peer_cert; /*!< entry peer_cert */ #endif mbedtls_ssl_cache_entry *next; /*!< chain pointer */ }; /** * \brief Cache context */ struct mbedtls_ssl_cache_context { mbedtls_ssl_cache_entry *chain; /*!< start of the chain */ int timeout; /*!< cache entry timeout */ int max_entries; /*!< maximum entries */ }; /** * \brief Initialize an SSL cache context * * \param cache SSL cache context */ void mbedtls_ssl_cache_init( mbedtls_ssl_cache_context *cache ); /** * \brief Cache get callback implementation * * \param data SSL cache context * \param session session to retrieve entry for */ int mbedtls_ssl_cache_get( void *data, mbedtls_ssl_session *session ); /** * \brief Cache set callback implementation * * \param data SSL cache context * \param session session to store entry for */ int mbedtls_ssl_cache_set( void *data, const mbedtls_ssl_session *session ); #if defined(MBEDTLS_HAVE_TIME) /** * \brief Set the cache timeout * (Default: MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT (1 day)) * * A timeout of 0 indicates no timeout. * * \param cache SSL cache context * \param timeout cache entry timeout in seconds */ void mbedtls_ssl_cache_set_timeout( mbedtls_ssl_cache_context *cache, int timeout ); #endif /* MBEDTLS_HAVE_TIME */ /** * \brief Set the maximum number of cache entries * (Default: MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES (50)) * * \param cache SSL cache context * \param max cache entry maximum */ void mbedtls_ssl_cache_set_max_entries( mbedtls_ssl_cache_context *cache, int max ); /** * \brief Free referenced items in a cache context and clear memory * * \param cache SSL cache context */ void mbedtls_ssl_cache_free( mbedtls_ssl_cache_context *cache ); #ifdef __cplusplus } #endif #endif /* ssl_cache.h */
3,213
115
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/isciphersuitegood.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/mbedtls/iana.h" bool IsCipherSuiteGood(uint16_t x) { switch (x) { case 0x009E: /* TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 (RFC5288) */ case 0x009F: /* TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 (RFC5288) */ case 0x00AA: /* TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 (RFC5487) */ case 0x00AB: /* TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 (RFC5487) */ case 0x1301: /* TLS_AES_128_GCM_SHA256 (RFC8446) */ case 0x1302: /* TLS_AES_256_GCM_SHA384 (RFC8446) */ case 0x1303: /* TLS_CHACHA20_POLY1305_SHA256 (RFC8446) */ case 0x1304: /* TLS_AES_128_CCM_SHA256 (RFC8446) */ case 0xC02B: /* TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 (RFC5289) */ case 0xC02C: /* TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 (RFC5289) */ case 0xC02F: /* TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (RFC5289) */ case 0xC030: /* TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (RFC5289) */ case 0xC09E: /* TLS_DHE_RSA_WITH_AES_128_CCM (RFC6655) */ case 0xC09F: /* TLS_DHE_RSA_WITH_AES_256_CCM (RFC6655) */ case 0xC0A6: /* TLS_DHE_PSK_WITH_AES_128_CCM (RFC6655) */ case 0xC0A7: /* TLS_DHE_PSK_WITH_AES_256_CCM (RFC6655) */ case 0xCCA8: /* TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (RFC7905) */ case 0xCCA9: /* TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 (RFC7905) */ case 0xCCAA: /* TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (RFC7905) */ case 0xCCAC: /* TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 (RFC7905) */ case 0xCCAD: /* TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 (RFC7905) */ case 0xD001: /* TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256 (RFC8442) */ case 0xD002: /* TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384 (RFC8442) */ case 0xD005: /* TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256 (RFC8442) */ return true; default: return false; } }
3,538
51
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/chacha20.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/bits.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "third_party/mbedtls/chacha20.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/platform.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /* Parameter validation macros */ #define CHACHA20_VALIDATE_RET( cond ) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA ) #define CHACHA20_VALIDATE( cond ) \ MBEDTLS_INTERNAL_VALIDATE( cond ) #define BYTES_TO_U32_LE( data, offset ) READ32LE((data) + (offset)) #define ROTL32( value, amount ) \ ( (uint32_t) ( (value) << (amount) ) | ( (value) >> ( 32 - (amount) ) ) ) #define CHACHA20_CTR_INDEX ( 12U ) #define CHACHA20_BLOCK_SIZE_BYTES ( 4U * 16U ) /** * \brief Generates a keystream block. * * \param s The initial ChaCha20 state (key, nonce, counter). * \param k Generated keystream bytes are written to this buffer. */ static void chacha20_block( const uint32_t s[16], unsigned char k[64] ) { int i; uint8_t *p; uint32_t A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P; A = s[ 0]; B = s[ 1]; C = s[ 2]; D = s[ 3]; E = s[ 4]; F = s[ 5]; G = s[ 6]; H = s[ 7]; I = s[ 8]; J = s[ 9]; K = s[10]; L = s[11]; M = s[12]; N = s[13]; O = s[14]; P = s[15]; for (i = 0; i < 10; ++i) { A += E; M = ROTL32(M ^ A, 16); B += F; N = ROTL32(N ^ B, 16); C += G; O = ROTL32(O ^ C, 16); D += H; P = ROTL32(P ^ D, 16); I += M; E = ROTL32(E ^ I, 12); J += N; F = ROTL32(F ^ J, 12); K += O; G = ROTL32(G ^ K, 12); L += P; H = ROTL32(H ^ L, 12); A += E; M = ROTL32(M ^ A, 8); B += F; N = ROTL32(N ^ B, 8); C += G; O = ROTL32(O ^ C, 8); D += H; P = ROTL32(P ^ D, 8); I += M; E = ROTL32(E ^ I, 7); J += N; F = ROTL32(F ^ J, 7); K += O; G = ROTL32(G ^ K, 7); L += P; H = ROTL32(H ^ L, 7); A += F; P = ROTL32(P ^ A, 16); B += G; M = ROTL32(M ^ B, 16); C += H; N = ROTL32(N ^ C, 16); D += E; O = ROTL32(O ^ D, 16); K += P; F = ROTL32(F ^ K, 12); L += M; G = ROTL32(G ^ L, 12); I += N; H = ROTL32(H ^ I, 12); J += O; E = ROTL32(E ^ J, 12); A += F; P = ROTL32(P ^ A, 8); B += G; M = ROTL32(M ^ B, 8); C += H; N = ROTL32(N ^ C, 8); D += E; O = ROTL32(O ^ D, 8); K += P; F = ROTL32(F ^ K, 7); L += M; G = ROTL32(G ^ L, 7); I += N; H = ROTL32(H ^ I, 7); J += O; E = ROTL32(E ^ J, 7); } p = k; A += s[ 0]; p = WRITE32LE(p, A); B += s[ 1]; p = WRITE32LE(p, B); C += s[ 2]; p = WRITE32LE(p, C); D += s[ 3]; p = WRITE32LE(p, D); E += s[ 4]; p = WRITE32LE(p, E); F += s[ 5]; p = WRITE32LE(p, F); G += s[ 6]; p = WRITE32LE(p, G); H += s[ 7]; p = WRITE32LE(p, H); I += s[ 8]; p = WRITE32LE(p, I); J += s[ 9]; p = WRITE32LE(p, J); K += s[10]; p = WRITE32LE(p, K); L += s[11]; p = WRITE32LE(p, L); M += s[12]; p = WRITE32LE(p, M); N += s[13]; p = WRITE32LE(p, N); O += s[14]; p = WRITE32LE(p, O); P += s[15]; p = WRITE32LE(p, P); } /** * \brief This function initializes the specified ChaCha20 context. * * It must be the first API called before using * the context. * * It is usually followed by calls to * \c mbedtls_chacha20_setkey() and * \c mbedtls_chacha20_starts(), then one or more calls to * to \c mbedtls_chacha20_update(), and finally to * \c mbedtls_chacha20_free(). * * \param ctx The ChaCha20 context to initialize. * This must not be \c NULL. */ void mbedtls_chacha20_init( mbedtls_chacha20_context *ctx ) { CHACHA20_VALIDATE( ctx != NULL ); mbedtls_platform_zeroize( ctx->state, sizeof( ctx->state ) ); mbedtls_platform_zeroize( ctx->keystream8, sizeof( ctx->keystream8 ) ); /* Initially, there's no keystream bytes available */ ctx->keystream_bytes_used = CHACHA20_BLOCK_SIZE_BYTES; } /** * \brief This function releases and clears the specified * ChaCha20 context. * * \param ctx The ChaCha20 context to clear. This may be \c NULL, * in which case this function is a no-op. If it is not * \c NULL, it must point to an initialized context. * */ void mbedtls_chacha20_free( mbedtls_chacha20_context *ctx ) { if( ctx != NULL ) { mbedtls_platform_zeroize( ctx, sizeof( mbedtls_chacha20_context ) ); } } /** * \brief This function sets the encryption/decryption key. * * \note After using this function, you must also call * \c mbedtls_chacha20_starts() to set a nonce before you * start encrypting/decrypting data with * \c mbedtls_chacha_update(). * * \param ctx The ChaCha20 context to which the key should be bound. * It must be initialized. * \param key The encryption/decryption key. This must be \c 32 Bytes * in length. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if ctx or key is NULL. */ int mbedtls_chacha20_setkey( mbedtls_chacha20_context *ctx, const unsigned char key[32] ) { CHACHA20_VALIDATE_RET( ctx != NULL ); CHACHA20_VALIDATE_RET( key != NULL ); /* ChaCha20 constants - the string "expand 32-byte k" */ ctx->state[0] = 0x61707865; ctx->state[1] = 0x3320646e; ctx->state[2] = 0x79622d32; ctx->state[3] = 0x6b206574; /* Set key */ ctx->state[4] = BYTES_TO_U32_LE( key, 0 ); ctx->state[5] = BYTES_TO_U32_LE( key, 4 ); ctx->state[6] = BYTES_TO_U32_LE( key, 8 ); ctx->state[7] = BYTES_TO_U32_LE( key, 12 ); ctx->state[8] = BYTES_TO_U32_LE( key, 16 ); ctx->state[9] = BYTES_TO_U32_LE( key, 20 ); ctx->state[10] = BYTES_TO_U32_LE( key, 24 ); ctx->state[11] = BYTES_TO_U32_LE( key, 28 ); return( 0 ); } /** * \brief This function sets the nonce and initial counter value. * * \note A ChaCha20 context can be re-used with the same key by * calling this function to change the nonce. * * \warning You must never use the same nonce twice with the same key. * This would void any confidentiality guarantees for the * messages encrypted with the same nonce and key. * * \param ctx The ChaCha20 context to which the nonce should be bound. * It must be initialized and bound to a key. * \param nonce The nonce. This must be \c 12 Bytes in size. * \param counter The initial counter value. This is usually \c 0. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if ctx or nonce is * NULL. */ int mbedtls_chacha20_starts( mbedtls_chacha20_context* ctx, const unsigned char nonce[12], uint32_t counter ) { CHACHA20_VALIDATE_RET( ctx != NULL ); CHACHA20_VALIDATE_RET( nonce != NULL ); /* Counter */ ctx->state[12] = counter; /* Nonce */ ctx->state[13] = BYTES_TO_U32_LE( nonce, 0 ); ctx->state[14] = BYTES_TO_U32_LE( nonce, 4 ); ctx->state[15] = BYTES_TO_U32_LE( nonce, 8 ); mbedtls_platform_zeroize( ctx->keystream8, sizeof( ctx->keystream8 ) ); /* Initially, there's no keystream bytes available */ ctx->keystream_bytes_used = CHACHA20_BLOCK_SIZE_BYTES; return( 0 ); } /** * \brief This function encrypts or decrypts data. * * Since ChaCha20 is a stream cipher, the same operation is * used for encrypting and decrypting data. * * \note The \p input and \p output pointers must either be equal or * point to non-overlapping buffers. * * \note \c mbedtls_chacha20_setkey() and * \c mbedtls_chacha20_starts() must be called at least once * to setup the context before this function can be called. * * \note This function can be called multiple times in a row in * order to encrypt of decrypt data piecewise with the same * key and nonce. * * \param ctx The ChaCha20 context to use for encryption or decryption. * It must be initialized and bound to a key and nonce. * \param size The length of the input data in Bytes. * \param input The buffer holding the input data. * This pointer can be \c NULL if `size == 0`. * \param output The buffer holding the output data. * This must be able to hold \p size Bytes. * This pointer can be \c NULL if `size == 0`. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_chacha20_update( mbedtls_chacha20_context *ctx, size_t size, const unsigned char *input, unsigned char *output ) { size_t offset = 0U; size_t i; CHACHA20_VALIDATE_RET( ctx != NULL ); CHACHA20_VALIDATE_RET( size == 0 || input != NULL ); CHACHA20_VALIDATE_RET( size == 0 || output != NULL ); /* Use leftover keystream bytes, if available */ while( size > 0U && ctx->keystream_bytes_used < CHACHA20_BLOCK_SIZE_BYTES ) { output[offset] = input[offset] ^ ctx->keystream8[ctx->keystream_bytes_used]; ctx->keystream_bytes_used++; offset++; size--; } /* Process full blocks */ while( size >= CHACHA20_BLOCK_SIZE_BYTES ) { /* Generate new keystream block and increment counter */ chacha20_block( ctx->state, ctx->keystream8 ); ctx->state[CHACHA20_CTR_INDEX]++; for( i = 0U; i < 64U; i += 8U ) { output[offset + i ] = input[offset + i ] ^ ctx->keystream8[i ]; output[offset + i+1] = input[offset + i+1] ^ ctx->keystream8[i+1]; output[offset + i+2] = input[offset + i+2] ^ ctx->keystream8[i+2]; output[offset + i+3] = input[offset + i+3] ^ ctx->keystream8[i+3]; output[offset + i+4] = input[offset + i+4] ^ ctx->keystream8[i+4]; output[offset + i+5] = input[offset + i+5] ^ ctx->keystream8[i+5]; output[offset + i+6] = input[offset + i+6] ^ ctx->keystream8[i+6]; output[offset + i+7] = input[offset + i+7] ^ ctx->keystream8[i+7]; } offset += CHACHA20_BLOCK_SIZE_BYTES; size -= CHACHA20_BLOCK_SIZE_BYTES; } /* Last (partial) block */ if( size > 0U ) { /* Generate new keystream block and increment counter */ chacha20_block( ctx->state, ctx->keystream8 ); ctx->state[CHACHA20_CTR_INDEX]++; for( i = 0U; i < size; i++) { output[offset + i] = input[offset + i] ^ ctx->keystream8[i]; } ctx->keystream_bytes_used = size; } return( 0 ); } /** * \brief This function encrypts or decrypts data with ChaCha20 and * the given key and nonce. * * Since ChaCha20 is a stream cipher, the same operation is * used for encrypting and decrypting data. * * \warning You must never use the same (key, nonce) pair more than * once. This would void any confidentiality guarantees for * the messages encrypted with the same nonce and key. * * \note The \p input and \p output pointers must either be equal or * point to non-overlapping buffers. * * \param key The encryption/decryption key. * This must be \c 32 Bytes in length. * \param nonce The nonce. This must be \c 12 Bytes in size. * \param counter The initial counter value. This is usually \c 0. * \param size The length of the input data in Bytes. * \param input The buffer holding the input data. * This pointer can be \c NULL if `size == 0`. * \param output The buffer holding the output data. * This must be able to hold \p size Bytes. * This pointer can be \c NULL if `size == 0`. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_chacha20_crypt( const unsigned char key[32], const unsigned char nonce[12], uint32_t counter, size_t data_len, const unsigned char* input, unsigned char* output ) { mbedtls_chacha20_context ctx; int ret = MBEDTLS_ERR_THIS_CORRUPTION; CHACHA20_VALIDATE_RET( key != NULL ); CHACHA20_VALIDATE_RET( nonce != NULL ); CHACHA20_VALIDATE_RET( data_len == 0 || input != NULL ); CHACHA20_VALIDATE_RET( data_len == 0 || output != NULL ); mbedtls_chacha20_init( &ctx ); ret = mbedtls_chacha20_setkey( &ctx, key ); if( ret != 0 ) goto cleanup; ret = mbedtls_chacha20_starts( &ctx, nonce, counter ); if( ret != 0 ) goto cleanup; ret = mbedtls_chacha20_update( &ctx, data_len, input, output ); cleanup: mbedtls_chacha20_free( &ctx ); return( ret ); } #if defined(MBEDTLS_SELF_TEST) static const unsigned char test_keys[2][32] = { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 } }; static const unsigned char test_nonces[2][12] = { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02 } }; static const uint32_t test_counters[2] = { 0U, 1U }; static const unsigned char test_input[2][375] = { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x41, 0x6e, 0x79, 0x20, 0x73, 0x75, 0x62, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x49, 0x45, 0x54, 0x46, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x6f, 0x72, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61, 0x73, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x6f, 0x72, 0x20, 0x70, 0x61, 0x72, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x61, 0x6e, 0x20, 0x49, 0x45, 0x54, 0x46, 0x20, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2d, 0x44, 0x72, 0x61, 0x66, 0x74, 0x20, 0x6f, 0x72, 0x20, 0x52, 0x46, 0x43, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x73, 0x74, 0x61, 0x74, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6d, 0x61, 0x64, 0x65, 0x20, 0x77, 0x69, 0x74, 0x68, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x61, 0x6e, 0x20, 0x49, 0x45, 0x54, 0x46, 0x20, 0x61, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x20, 0x69, 0x73, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x69, 0x64, 0x65, 0x72, 0x65, 0x64, 0x20, 0x61, 0x6e, 0x20, 0x22, 0x49, 0x45, 0x54, 0x46, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x2e, 0x20, 0x53, 0x75, 0x63, 0x68, 0x20, 0x73, 0x74, 0x61, 0x74, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x20, 0x6f, 0x72, 0x61, 0x6c, 0x20, 0x73, 0x74, 0x61, 0x74, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x20, 0x69, 0x6e, 0x20, 0x49, 0x45, 0x54, 0x46, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x2c, 0x20, 0x61, 0x73, 0x20, 0x77, 0x65, 0x6c, 0x6c, 0x20, 0x61, 0x73, 0x20, 0x77, 0x72, 0x69, 0x74, 0x74, 0x65, 0x6e, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x72, 0x6f, 0x6e, 0x69, 0x63, 0x20, 0x63, 0x6f, 0x6d, 0x6d, 0x75, 0x6e, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x6d, 0x61, 0x64, 0x65, 0x20, 0x61, 0x74, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x74, 0x69, 0x6d, 0x65, 0x20, 0x6f, 0x72, 0x20, 0x70, 0x6c, 0x61, 0x63, 0x65, 0x2c, 0x20, 0x77, 0x68, 0x69, 0x63, 0x68, 0x20, 0x61, 0x72, 0x65, 0x20, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x64, 0x20, 0x74, 0x6f } }; static const unsigned char test_output[2][375] = { { 0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90, 0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86, 0xbd, 0x28, 0xbd, 0xd2, 0x19, 0xb8, 0xa0, 0x8d, 0xed, 0x1a, 0xa8, 0x36, 0xef, 0xcc, 0x8b, 0x77, 0x0d, 0xc7, 0xda, 0x41, 0x59, 0x7c, 0x51, 0x57, 0x48, 0x8d, 0x77, 0x24, 0xe0, 0x3f, 0xb8, 0xd8, 0x4a, 0x37, 0x6a, 0x43, 0xb8, 0xf4, 0x15, 0x18, 0xa1, 0x1c, 0xc3, 0x87, 0xb6, 0x69, 0xb2, 0xee, 0x65, 0x86 }, { 0xa3, 0xfb, 0xf0, 0x7d, 0xf3, 0xfa, 0x2f, 0xde, 0x4f, 0x37, 0x6c, 0xa2, 0x3e, 0x82, 0x73, 0x70, 0x41, 0x60, 0x5d, 0x9f, 0x4f, 0x4f, 0x57, 0xbd, 0x8c, 0xff, 0x2c, 0x1d, 0x4b, 0x79, 0x55, 0xec, 0x2a, 0x97, 0x94, 0x8b, 0xd3, 0x72, 0x29, 0x15, 0xc8, 0xf3, 0xd3, 0x37, 0xf7, 0xd3, 0x70, 0x05, 0x0e, 0x9e, 0x96, 0xd6, 0x47, 0xb7, 0xc3, 0x9f, 0x56, 0xe0, 0x31, 0xca, 0x5e, 0xb6, 0x25, 0x0d, 0x40, 0x42, 0xe0, 0x27, 0x85, 0xec, 0xec, 0xfa, 0x4b, 0x4b, 0xb5, 0xe8, 0xea, 0xd0, 0x44, 0x0e, 0x20, 0xb6, 0xe8, 0xdb, 0x09, 0xd8, 0x81, 0xa7, 0xc6, 0x13, 0x2f, 0x42, 0x0e, 0x52, 0x79, 0x50, 0x42, 0xbd, 0xfa, 0x77, 0x73, 0xd8, 0xa9, 0x05, 0x14, 0x47, 0xb3, 0x29, 0x1c, 0xe1, 0x41, 0x1c, 0x68, 0x04, 0x65, 0x55, 0x2a, 0xa6, 0xc4, 0x05, 0xb7, 0x76, 0x4d, 0x5e, 0x87, 0xbe, 0xa8, 0x5a, 0xd0, 0x0f, 0x84, 0x49, 0xed, 0x8f, 0x72, 0xd0, 0xd6, 0x62, 0xab, 0x05, 0x26, 0x91, 0xca, 0x66, 0x42, 0x4b, 0xc8, 0x6d, 0x2d, 0xf8, 0x0e, 0xa4, 0x1f, 0x43, 0xab, 0xf9, 0x37, 0xd3, 0x25, 0x9d, 0xc4, 0xb2, 0xd0, 0xdf, 0xb4, 0x8a, 0x6c, 0x91, 0x39, 0xdd, 0xd7, 0xf7, 0x69, 0x66, 0xe9, 0x28, 0xe6, 0x35, 0x55, 0x3b, 0xa7, 0x6c, 0x5c, 0x87, 0x9d, 0x7b, 0x35, 0xd4, 0x9e, 0xb2, 0xe6, 0x2b, 0x08, 0x71, 0xcd, 0xac, 0x63, 0x89, 0x39, 0xe2, 0x5e, 0x8a, 0x1e, 0x0e, 0xf9, 0xd5, 0x28, 0x0f, 0xa8, 0xca, 0x32, 0x8b, 0x35, 0x1c, 0x3c, 0x76, 0x59, 0x89, 0xcb, 0xcf, 0x3d, 0xaa, 0x8b, 0x6c, 0xcc, 0x3a, 0xaf, 0x9f, 0x39, 0x79, 0xc9, 0x2b, 0x37, 0x20, 0xfc, 0x88, 0xdc, 0x95, 0xed, 0x84, 0xa1, 0xbe, 0x05, 0x9c, 0x64, 0x99, 0xb9, 0xfd, 0xa2, 0x36, 0xe7, 0xe8, 0x18, 0xb0, 0x4b, 0x0b, 0xc3, 0x9c, 0x1e, 0x87, 0x6b, 0x19, 0x3b, 0xfe, 0x55, 0x69, 0x75, 0x3f, 0x88, 0x12, 0x8c, 0xc0, 0x8a, 0xaa, 0x9b, 0x63, 0xd1, 0xa1, 0x6f, 0x80, 0xef, 0x25, 0x54, 0xd7, 0x18, 0x9c, 0x41, 0x1f, 0x58, 0x69, 0xca, 0x52, 0xc5, 0xb8, 0x3f, 0xa3, 0x6f, 0xf2, 0x16, 0xb9, 0xc1, 0xd3, 0x00, 0x62, 0xbe, 0xbc, 0xfd, 0x2d, 0xc5, 0xbc, 0xe0, 0x91, 0x19, 0x34, 0xfd, 0xa7, 0x9a, 0x86, 0xf6, 0xe6, 0x98, 0xce, 0xd7, 0x59, 0xc3, 0xff, 0x9b, 0x64, 0x77, 0x33, 0x8f, 0x3d, 0xa4, 0xf9, 0xcd, 0x85, 0x14, 0xea, 0x99, 0x82, 0xcc, 0xaf, 0xb3, 0x41, 0xb2, 0x38, 0x4d, 0xd9, 0x02, 0xf3, 0xd1, 0xab, 0x7a, 0xc6, 0x1d, 0xd2, 0x9c, 0x6f, 0x21, 0xba, 0x5b, 0x86, 0x2f, 0x37, 0x30, 0xe3, 0x7c, 0xfd, 0xc4, 0xfd, 0x80, 0x6c, 0x22, 0xf2, 0x21 } }; static const size_t test_lengths[2] = { 64U, 375U }; /* Make sure no other definition is already present. */ #undef ASSERT #define ASSERT( cond, args ) \ do \ { \ if( ! ( cond ) ) \ { \ if( verbose != 0 ) \ mbedtls_printf args; \ \ return( -1 ); \ } \ } \ while( 0 ) /** * \brief The ChaCha20 checkup routine. * * \return \c 0 on success. * \return \c 1 on failure. */ int mbedtls_chacha20_self_test( int verbose ) { unsigned char output[381]; unsigned i; int ret = MBEDTLS_ERR_THIS_CORRUPTION; for( i = 0U; i < 2U; i++ ) { if( verbose != 0 ) mbedtls_printf( " ChaCha20 test %u ", i ); ret = mbedtls_chacha20_crypt( test_keys[i], test_nonces[i], test_counters[i], test_lengths[i], test_input[i], output ); ASSERT( 0 == ret, ( "error code: %i\n", ret ) ); ASSERT( 0 == timingsafe_bcmp( output, test_output[i], test_lengths[i] ), ( "failed (output)\n" ) ); if( verbose != 0 ) mbedtls_printf( "passed\n" ); } if( verbose != 0 ) mbedtls_printf( "\n" ); return( 0 ); } #endif /* MBEDTLS_SELF_TEST */
24,502
630
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/ecdh_everest.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "third_party/mbedtls/ecdh_everest.h" #include "third_party/mbedtls/everest.h" #if defined(MBEDTLS_ECDH_C) && defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED) #define KEYSIZE 32 asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /** * \brief This function sets up the ECDH context with the information * given. * * This function should be called after mbedtls_ecdh_init() but * before mbedtls_ecdh_make_params(). There is no need to call * this function before mbedtls_ecdh_read_params(). * * This is the first function used by a TLS server for * ECDHE ciphersuites. * * \param ctx The ECDH context to set up. * \param grp_id The group id of the group to set up the context for. * * \return \c 0 on success. */ int mbedtls_everest_setup(mbedtls_ecdh_context_everest *ctx, int grp_id) { if (grp_id != MBEDTLS_ECP_DP_CURVE25519) return MBEDTLS_ERR_ECP_BAD_INPUT_DATA; mbedtls_platform_zeroize(ctx, sizeof(*ctx)); return 0; } /** * \brief This function frees a context. * * \param ctx The context to free. */ void mbedtls_everest_free(mbedtls_ecdh_context_everest *ctx) { if (!ctx) return; mbedtls_platform_zeroize(ctx, sizeof(*ctx)); } /** * \brief This function generates a public key and a TLS * ServerKeyExchange payload. * * This is the second function used by a TLS server for ECDHE * ciphersuites. (It is called after mbedtls_ecdh_setup().) * * \note This function assumes that the ECP group (grp) of the * \p ctx context has already been properly set, * for example, using mbedtls_ecp_group_load(). * * \see ecp.h * * \param ctx The ECDH context. * \param olen The number of characters written. * \param buf The destination buffer. * \param blen The length of the destination buffer. * \param f_rng The RNG function. * \param p_rng The RNG context. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_everest_make_params(mbedtls_ecdh_context_everest *ctx, size_t *olen, unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng) { int ret = 0; uint8_t base[KEYSIZE] = {9}; if ((ret = f_rng(p_rng, ctx->our_secret, KEYSIZE)) != 0) return ret; *olen = KEYSIZE + 4; if (blen < *olen) return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL; *buf++ = MBEDTLS_ECP_TLS_NAMED_CURVE; *buf++ = MBEDTLS_ECP_TLS_CURVE25519 >> 8; *buf++ = MBEDTLS_ECP_TLS_CURVE25519 & 0xFF; *buf++ = KEYSIZE; curve25519(buf, ctx->our_secret, base); base[0] = 0; if (!timingsafe_bcmp(buf, base, KEYSIZE)) return MBEDTLS_ERR_ECP_RANDOM_FAILED; return 0; } /** * \brief This function parses and processes a TLS ServerKeyExhange * payload. * * This is the first function used by a TLS client for ECDHE * ciphersuites. * * \see ecp.h * * \param ctx The ECDH context. * \param buf The pointer to the start of the input buffer. * \param end The address for one Byte past the end of the buffer. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_everest_read_params(mbedtls_ecdh_context_everest *ctx, const unsigned char **buf, const unsigned char *end) { if (end - *buf < KEYSIZE + 1) return MBEDTLS_ERR_ECP_BAD_INPUT_DATA; if ((*(*buf)++ != KEYSIZE)) return MBEDTLS_ERR_ECP_BAD_INPUT_DATA; memcpy(ctx->peer_point, *buf, KEYSIZE); *buf += KEYSIZE; return 0; } /** * \brief This function sets up an ECDH context from an EC key. * * It is used by clients and servers in place of the * ServerKeyEchange for static ECDH, and imports ECDH * parameters from the EC key information of a certificate. * * \see ecp.h * * \param ctx The ECDH context to set up. * \param key The EC key to use. * \param side Defines the source of the key: 1: Our key, or * 0: The key of the peer. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_everest_get_params(mbedtls_ecdh_context_everest *ctx, const mbedtls_ecp_keypair *key, mbedtls_everest_ecdh_side side) { size_t olen = 0; mbedtls_everest_ecdh_side s; switch (side) { case MBEDTLS_EVEREST_ECDH_THEIRS: return mbedtls_ecp_point_write_binary(&key->grp, &key->Q, MBEDTLS_ECP_PF_COMPRESSED, &olen, ctx->peer_point, KEYSIZE); case MBEDTLS_EVEREST_ECDH_OURS: return mbedtls_mpi_write_binary_le(&key->d, ctx->our_secret, KEYSIZE); default: return MBEDTLS_ERR_ECP_BAD_INPUT_DATA; } } /** * \brief This function generates a public key and a TLS * ClientKeyExchange payload. * * This is the second function used by a TLS client for ECDH(E) * ciphersuites. * * \see ecp.h * * \param ctx The ECDH context. * \param olen The number of Bytes written. * \param buf The destination buffer. * \param blen The size of the destination buffer. * \param f_rng The RNG function. * \param p_rng The RNG context. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_everest_make_public(mbedtls_ecdh_context_everest *ctx, size_t *olen, unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng) { int ret = 0; unsigned char base[KEYSIZE] = {9}; if (!ctx) return MBEDTLS_ERR_ECP_BAD_INPUT_DATA; if ((ret = f_rng(p_rng, ctx->our_secret, KEYSIZE))) return ret; *olen = KEYSIZE + 1; if (blen < *olen) return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL; *buf++ = KEYSIZE; curve25519(buf, ctx->our_secret, base); base[0] = 0; if (!timingsafe_bcmp(buf, base, KEYSIZE)) return MBEDTLS_ERR_ECP_RANDOM_FAILED; return ret; } /** * \brief This function parses and processes a TLS ClientKeyExchange * payload. * * This is the third function used by a TLS server for ECDH(E) * ciphersuites. (It is called after mbedtls_ecdh_setup() and * mbedtls_ecdh_make_params().) * * \see ecp.h * * \param ctx The ECDH context. * \param buf The start of the input buffer. * \param blen The length of the input buffer. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_everest_read_public(mbedtls_ecdh_context_everest *ctx, const unsigned char *buf, size_t blen) { if (blen < KEYSIZE + 1) return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL; if ((*buf++ != KEYSIZE)) return MBEDTLS_ERR_ECP_BAD_INPUT_DATA; memcpy(ctx->peer_point, buf, KEYSIZE); return 0; } /** * \brief This function derives and exports the shared secret. * * This is the last function used by both TLS client * and servers. * * \note If \p f_rng is not NULL, it is used to implement * countermeasures against side-channel attacks. * For more information, see mbedtls_ecp_mul(). * * \see ecp.h * * \param ctx The ECDH context. * \param olen The number of Bytes written. * \param buf The destination buffer. * \param blen The length of the destination buffer. * \param f_rng The RNG function. * \param p_rng The RNG context. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_everest_calc_secret(mbedtls_ecdh_context_everest *ctx, size_t *olen, unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng) { /* f_rng and p_rng are not used here because this implementation does not need blinding since it has constant trace. (todo(jart): wut?) */ *olen = KEYSIZE; if (blen < *olen) return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL; curve25519(buf, ctx->our_secret, ctx->peer_point); if (!timingsafe_bcmp(buf, ctx->our_secret, KEYSIZE)) goto wut; /* Wipe the DH secret and don't let the peer chose a small subgroup point */ mbedtls_platform_zeroize(ctx->our_secret, KEYSIZE); if (!timingsafe_bcmp(buf, ctx->our_secret, KEYSIZE)) goto wut; return 0; wut: mbedtls_platform_zeroize(buf, KEYSIZE); mbedtls_platform_zeroize(ctx->our_secret, KEYSIZE); return MBEDTLS_ERR_ECP_RANDOM_FAILED; } #endif
11,202
281
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/entropy.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/entropy.h" #include "third_party/mbedtls/entropy_poll.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/platform.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /* * Entropy accumulator implementation * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(MBEDTLS_ENTROPY_C) #if defined(MBEDTLS_TEST_NULL_ENTROPY) #warning "**** WARNING! MBEDTLS_TEST_NULL_ENTROPY defined! " #warning "**** THIS BUILD HAS NO DEFINED ENTROPY SOURCES " #warning "**** THIS BUILD IS *NOT* SUITABLE FOR PRODUCTION USE " #endif #define ENTROPY_MAX_LOOP 256 /*< Maximum amount to loop before error */ /** * \brief Initialize the context * * \param ctx Entropy context to initialize */ void mbedtls_entropy_init( mbedtls_entropy_context *ctx ) { ctx->source_count = 0; mbedtls_platform_zeroize( ctx->source, sizeof( ctx->source ) ); ctx->accumulator_started = 0; #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR) mbedtls_sha512_init( &ctx->accumulator ); #else mbedtls_sha256_init( &ctx->accumulator ); #endif /* Reminder: Update ENTROPY_HAVE_STRONG in the test files * when adding more strong entropy sources here. */ mbedtls_entropy_add_source( ctx, mbedtls_hardware_poll, NULL, MBEDTLS_ENTROPY_MIN_HARDWARE, MBEDTLS_ENTROPY_SOURCE_STRONG ); } /** * \brief Free the data in the context * * \param ctx Entropy context to free */ void mbedtls_entropy_free( mbedtls_entropy_context *ctx ) { /* If the context was already free, don't call free() again. * This is important for mutexes which don't allow double-free. */ if( ctx->accumulator_started == -1 ) return; #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR) mbedtls_sha512_free( &ctx->accumulator ); #else mbedtls_sha256_free( &ctx->accumulator ); #endif #if defined(MBEDTLS_ENTROPY_NV_SEED) ctx->initial_entropy_run = 0; #endif ctx->source_count = 0; mbedtls_platform_zeroize( ctx->source, sizeof( ctx->source ) ); ctx->accumulator_started = -1; } /** * \brief Adds an entropy source to poll * * \param ctx Entropy context * \param f_source Entropy function * \param p_source Function data * \param threshold Minimum required from source before entropy is released * ( with mbedtls_entropy_func() ) (in bytes) * \param strong MBEDTLS_ENTROPY_SOURCE_STRONG or * MBEDTLS_ENTROPY_SOURCE_WEAK. * At least one strong source needs to be added. * Weaker sources (such as the cycle counter) can be used as * a complement. * * \return 0 if successful or MBEDTLS_ERR_ENTROPY_MAX_SOURCES */ int mbedtls_entropy_add_source( mbedtls_entropy_context *ctx, mbedtls_entropy_f_source_ptr f_source, void *p_source, size_t threshold, int strong ) { int idx; idx = ctx->source_count; if( idx >= MBEDTLS_ENTROPY_MAX_SOURCES ) return MBEDTLS_ERR_ENTROPY_MAX_SOURCES; ctx->source[idx].f_source = f_source; ctx->source[idx].p_source = p_source; ctx->source[idx].threshold = threshold; ctx->source[idx].strong = strong; ctx->source_count++; return 0; } /* * Entropy accumulator update */ static int entropy_update( mbedtls_entropy_context *ctx, unsigned char source_id, const unsigned char *data, size_t len ) { unsigned char header[2]; unsigned char tmp[MBEDTLS_ENTROPY_BLOCK_SIZE]; size_t use_len = len; const unsigned char *p = data; int ret = 0; if( use_len > MBEDTLS_ENTROPY_BLOCK_SIZE ) { #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR) if( ( ret = mbedtls_sha512_ret( data, len, tmp, 0 ) ) != 0 ) goto cleanup; #else if( ( ret = mbedtls_sha256_ret( data, len, tmp, 0 ) ) != 0 ) goto cleanup; #endif p = tmp; use_len = MBEDTLS_ENTROPY_BLOCK_SIZE; } header[0] = source_id; header[1] = use_len & 0xFF; /* * Start the accumulator if this has not already happened. Note that * it is sufficient to start the accumulator here only because all calls to * gather entropy eventually execute this code. */ #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR) if( ctx->accumulator_started == 0 && ( ret = mbedtls_sha512_starts_ret( &ctx->accumulator, 0 ) ) != 0 ) goto cleanup; else ctx->accumulator_started = 1; if( ( ret = mbedtls_sha512_update_ret( &ctx->accumulator, header, 2 ) ) != 0 ) goto cleanup; ret = mbedtls_sha512_update_ret( &ctx->accumulator, p, use_len ); #else if( ctx->accumulator_started == 0 && ( ret = mbedtls_sha256_starts_ret( &ctx->accumulator, 0 ) ) != 0 ) goto cleanup; else ctx->accumulator_started = 1; if( ( ret = mbedtls_sha256_update_ret( &ctx->accumulator, header, 2 ) ) != 0 ) goto cleanup; ret = mbedtls_sha256_update_ret( &ctx->accumulator, p, use_len ); #endif cleanup: mbedtls_platform_zeroize( tmp, sizeof( tmp ) ); return( ret ); } /** * \brief Add data to the accumulator manually * * \param ctx Entropy context * \param data Data to add * \param len Length of data * * \return 0 if successful */ int mbedtls_entropy_update_manual( mbedtls_entropy_context *ctx, const unsigned char *data, size_t len ) { return entropy_update( ctx, MBEDTLS_ENTROPY_SOURCE_MANUAL, data, len ); } /* * Run through the different sources to add entropy to our accumulator */ static int entropy_gather_internal( mbedtls_entropy_context *ctx ) { int ret = MBEDTLS_ERR_ENTROPY_SOURCE_FAILED; int i; int have_one_strong = 0; unsigned char buf[MBEDTLS_ENTROPY_MAX_GATHER]; size_t olen; if( ctx->source_count == 0 ) return( MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED ); /* * Run through our entropy sources */ for( i = 0; i < ctx->source_count; i++ ) { if( ctx->source[i].strong == MBEDTLS_ENTROPY_SOURCE_STRONG ) have_one_strong = 1; olen = 0; if( ( ret = ctx->source[i].f_source( ctx->source[i].p_source, buf, MBEDTLS_ENTROPY_MAX_GATHER, &olen ) ) != 0 ) { goto cleanup; } /* * Add if we actually gathered something */ if( olen > 0 ) { if( ( ret = entropy_update( ctx, (unsigned char) i, buf, olen ) ) != 0 ) return( ret ); ctx->source[i].size += olen; } } if( have_one_strong == 0 ) ret = MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE; cleanup: mbedtls_platform_zeroize( buf, sizeof( buf ) ); return( ret ); } /** * \brief Trigger an extra gather poll for the accumulator * * \param ctx Entropy context * * \return 0 if successful, or MBEDTLS_ERR_ENTROPY_SOURCE_FAILED */ int mbedtls_entropy_gather( mbedtls_entropy_context *ctx ) { return entropy_gather_internal( ctx ); } /** * \brief Retrieve entropy from the accumulator * (Maximum length: MBEDTLS_ENTROPY_BLOCK_SIZE) * * \param data Entropy context * \param output Buffer to fill * \param len Number of bytes desired, must be at most MBEDTLS_ENTROPY_BLOCK_SIZE * * \return 0 if successful, or MBEDTLS_ERR_ENTROPY_SOURCE_FAILED */ int mbedtls_entropy_func( void *data, unsigned char *output, size_t len ) { int ret, count = 0, i, thresholds_reached; size_t strong_size; mbedtls_entropy_context *ctx = (mbedtls_entropy_context *) data; unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE]; if( len > MBEDTLS_ENTROPY_BLOCK_SIZE ) return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED ); #if defined(MBEDTLS_ENTROPY_NV_SEED) /* Update the NV entropy seed before generating any entropy for outside * use. */ if( ctx->initial_entropy_run == 0 ) { ctx->initial_entropy_run = 1; if( ( ret = mbedtls_entropy_update_nv_seed( ctx ) ) != 0 ) return( ret ); } #endif /* * Always gather extra entropy before a call */ do { if( count++ > ENTROPY_MAX_LOOP ) { ret = MBEDTLS_ERR_ENTROPY_SOURCE_FAILED; goto exit; } if( ( ret = entropy_gather_internal( ctx ) ) != 0 ) goto exit; thresholds_reached = 1; strong_size = 0; for( i = 0; i < ctx->source_count; i++ ) { if( ctx->source[i].size < ctx->source[i].threshold ) thresholds_reached = 0; if( ctx->source[i].strong == MBEDTLS_ENTROPY_SOURCE_STRONG ) strong_size += ctx->source[i].size; } } while( ! thresholds_reached || strong_size < MBEDTLS_ENTROPY_BLOCK_SIZE ); mbedtls_platform_zeroize( buf, MBEDTLS_ENTROPY_BLOCK_SIZE ); #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR) /* * Note that at this stage it is assumed that the accumulator was started * in a previous call to entropy_update(). If this is not guaranteed, the * code below will fail. */ if( ( ret = mbedtls_sha512_finish_ret( &ctx->accumulator, buf ) ) != 0 ) goto exit; /* * Reset accumulator and counters and recycle existing entropy */ mbedtls_sha512_free( &ctx->accumulator ); mbedtls_sha512_init( &ctx->accumulator ); if( ( ret = mbedtls_sha512_starts_ret( &ctx->accumulator, 0 ) ) != 0 ) goto exit; if( ( ret = mbedtls_sha512_update_ret( &ctx->accumulator, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 ) goto exit; /* * Perform second SHA-512 on entropy */ if( ( ret = mbedtls_sha512_ret( buf, MBEDTLS_ENTROPY_BLOCK_SIZE, buf, 0 ) ) != 0 ) goto exit; #else /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */ if( ( ret = mbedtls_sha256_finish_ret( &ctx->accumulator, buf ) ) != 0 ) goto exit; /* * Reset accumulator and counters and recycle existing entropy */ mbedtls_sha256_free( &ctx->accumulator ); mbedtls_sha256_init( &ctx->accumulator ); if( ( ret = mbedtls_sha256_starts_ret( &ctx->accumulator, 0 ) ) != 0 ) goto exit; if( ( ret = mbedtls_sha256_update_ret( &ctx->accumulator, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 ) goto exit; /* * Perform second SHA-256 on entropy */ if( ( ret = mbedtls_sha256_ret( buf, MBEDTLS_ENTROPY_BLOCK_SIZE, buf, 0 ) ) != 0 ) goto exit; #endif /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */ for( i = 0; i < ctx->source_count; i++ ) ctx->source[i].size = 0; memcpy( output, buf, len ); ret = 0; exit: mbedtls_platform_zeroize( buf, sizeof( buf ) ); return( ret ); } #if defined(MBEDTLS_ENTROPY_NV_SEED) /** * \brief Trigger an update of the seed file in NV by using the * current entropy pool. * * \param ctx Entropy context * * \return 0 if successful */ int mbedtls_entropy_update_nv_seed( mbedtls_entropy_context *ctx ) { int ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR; unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE]; /* Read new seed and write it to NV */ if( ( ret = mbedtls_entropy_func( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 ) return( ret ); if( mbedtls_nv_seed_write( buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) < 0 ) return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR ); /* Manually update the remaining stream with a separator value to diverge */ mbedtls_platform_zeroize( buf, MBEDTLS_ENTROPY_BLOCK_SIZE ); ret = mbedtls_entropy_update_manual( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ); return( ret ); } #endif /* MBEDTLS_ENTROPY_NV_SEED */ #if defined(MBEDTLS_FS_IO) /** * \brief Write a seed file * * \param ctx Entropy context * \param path Name of the file * * \return 0 if successful, * MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR on file error, or * MBEDTLS_ERR_ENTROPY_SOURCE_FAILED */ int mbedtls_entropy_write_seed_file( mbedtls_entropy_context *ctx, const char *path ) { int ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR; FILE *f; unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE]; if( ( f = fopen( path, "wb" ) ) == NULL ) return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR ); if( ( ret = mbedtls_entropy_func( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 ) goto exit; if( fwrite( buf, 1, MBEDTLS_ENTROPY_BLOCK_SIZE, f ) != MBEDTLS_ENTROPY_BLOCK_SIZE ) { ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR; goto exit; } ret = 0; exit: mbedtls_platform_zeroize( buf, sizeof( buf ) ); fclose( f ); return( ret ); } /** * \brief Read and update a seed file. Seed is added to this * instance. No more than MBEDTLS_ENTROPY_MAX_SEED_SIZE bytes are * read from the seed file. The rest is ignored. * * \param ctx Entropy context * \param path Name of the file * * \return 0 if successful, * MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR on file error, * MBEDTLS_ERR_ENTROPY_SOURCE_FAILED */ int mbedtls_entropy_update_seed_file( mbedtls_entropy_context *ctx, const char *path ) { int ret = 0; FILE *f; size_t n; unsigned char buf[ MBEDTLS_ENTROPY_MAX_SEED_SIZE ]; if( ( f = fopen( path, "rb" ) ) == NULL ) return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR ); fseek( f, 0, SEEK_END ); n = (size_t) ftell( f ); fseek( f, 0, SEEK_SET ); if( n > MBEDTLS_ENTROPY_MAX_SEED_SIZE ) n = MBEDTLS_ENTROPY_MAX_SEED_SIZE; if( fread( buf, 1, n, f ) != n ) ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR; else ret = mbedtls_entropy_update_manual( ctx, buf, n ); fclose( f ); mbedtls_platform_zeroize( buf, sizeof( buf ) ); if( ret != 0 ) return( ret ); return( mbedtls_entropy_write_seed_file( ctx, path ) ); } #endif /* MBEDTLS_FS_IO */ #if defined(MBEDTLS_SELF_TEST) #if !defined(MBEDTLS_TEST_NULL_ENTROPY) /* * Dummy source function */ static int entropy_dummy_source( void *data, unsigned char *output, size_t len, size_t *olen ) { ((void) data); memset( output, 0x2a, len ); *olen = len; return( 0 ); } #endif /* !MBEDTLS_TEST_NULL_ENTROPY */ #if defined(MBEDTLS_ENTROPY_HARDWARE_ALT) static int mbedtls_entropy_source_self_test_gather( unsigned char *buf, size_t buf_len ) { int ret = 0; size_t entropy_len = 0; size_t olen = 0; size_t attempts = buf_len; while( attempts > 0 && entropy_len < buf_len ) { if( ( ret = mbedtls_hardware_poll( NULL, buf + entropy_len, buf_len - entropy_len, &olen ) ) != 0 ) return( ret ); entropy_len += olen; attempts--; } if( entropy_len < buf_len ) { ret = 1; } return( ret ); } static int mbedtls_entropy_source_self_test_check_bits( const unsigned char *buf, size_t buf_len ) { unsigned char set= 0xFF; unsigned char unset = 0x00; size_t i; for( i = 0; i < buf_len; i++ ) { set &= buf[i]; unset |= buf[i]; } return( set == 0xFF || unset == 0x00 ); } /** * \brief Checkup routine * * Verifies the integrity of the hardware entropy source * provided by the function 'mbedtls_hardware_poll()'. * * Note this is the only hardware entropy source that is known * at link time, and other entropy sources configured * dynamically at runtime by the function * mbedtls_entropy_add_source() will not be tested. * * \return 0 if successful, or 1 if a test failed */ int mbedtls_entropy_source_self_test( int verbose ) { /* * A test to ensure hat the entropy sources are functioning correctly * and there is no obvious failure. The test performs the following checks: * - The entropy source is not providing only 0s (all bits unset) or 1s (all * bits set). * - The entropy source is not providing values in a pattern. Because the * hardware could be providing data in an arbitrary length, this check polls * the hardware entropy source twice and compares the result to ensure they * are not equal. * - The error code returned by the entropy source is not an error. */ int ret = 0; unsigned char buf0[2 * sizeof( unsigned long long int )]; unsigned char buf1[2 * sizeof( unsigned long long int )]; if( verbose != 0 ) mbedtls_printf( " ENTROPY_BIAS test: " ); mbedtls_platform_zeroize( buf0, sizeof( buf0 ) ); mbedtls_platform_zeroize( buf1, sizeof( buf1 ) ); if( ( ret = mbedtls_entropy_source_self_test_gather( buf0, sizeof( buf0 ) ) ) != 0 ) goto cleanup; if( ( ret = mbedtls_entropy_source_self_test_gather( buf1, sizeof( buf1 ) ) ) != 0 ) goto cleanup; /* Make sure that the returned values are not all 0 or 1 */ if( ( ret = mbedtls_entropy_source_self_test_check_bits( buf0, sizeof( buf0 ) ) ) != 0 ) goto cleanup; if( ( ret = mbedtls_entropy_source_self_test_check_bits( buf1, sizeof( buf1 ) ) ) != 0 ) goto cleanup; /* Make sure that the entropy source is not returning values in a * pattern */ ret = timingsafe_bcmp( buf0, buf1, sizeof( buf0 ) ) == 0; cleanup: if( verbose != 0 ) { if( ret != 0 ) mbedtls_printf( "failed\n" ); else mbedtls_printf( "passed\n" ); mbedtls_printf( "\n" ); } return( ret != 0 ); } #endif /* MBEDTLS_ENTROPY_HARDWARE_ALT */ /** * \brief Checkup routine * * The actual entropy quality is hard to test, but we * can at least test that the functions don't cause * errors and write the correct amount of data to * buffers. * * This module self-test also calls the entropy self-test, * mbedtls_entropy_source_self_test(); * * \return 0 if successful, or 1 if a test failed */ int mbedtls_entropy_self_test( int verbose ) { int ret = 1; #if !defined(MBEDTLS_TEST_NULL_ENTROPY) mbedtls_entropy_context ctx; unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE] = { 0 }; unsigned char acc[MBEDTLS_ENTROPY_BLOCK_SIZE] = { 0 }; size_t i, j; #endif /* !MBEDTLS_TEST_NULL_ENTROPY */ if( verbose != 0 ) mbedtls_printf( " ENTROPY test: " ); #if !defined(MBEDTLS_TEST_NULL_ENTROPY) mbedtls_entropy_init( &ctx ); /* First do a gather to make sure we have default sources */ if( ( ret = mbedtls_entropy_gather( &ctx ) ) != 0 ) goto cleanup; ret = mbedtls_entropy_add_source( &ctx, entropy_dummy_source, NULL, 16, MBEDTLS_ENTROPY_SOURCE_WEAK ); if( ret != 0 ) goto cleanup; if( ( ret = mbedtls_entropy_update_manual( &ctx, buf, sizeof buf ) ) != 0 ) goto cleanup; /* * To test that mbedtls_entropy_func writes correct number of bytes: * - use the whole buffer and rely on ASan to detect overruns * - collect entropy 8 times and OR the result in an accumulator: * any byte should then be 0 with probably 2^(-64), so requiring * each of the 32 or 64 bytes to be non-zero has a false failure rate * of at most 2^(-58) which is acceptable. */ for( i = 0; i < 8; i++ ) { if( ( ret = mbedtls_entropy_func( &ctx, buf, sizeof( buf ) ) ) != 0 ) goto cleanup; for( j = 0; j < sizeof( buf ); j++ ) acc[j] |= buf[j]; } for( j = 0; j < sizeof( buf ); j++ ) { if( acc[j] == 0 ) { ret = 1; goto cleanup; } } #if defined(MBEDTLS_ENTROPY_HARDWARE_ALT) if( ( ret = mbedtls_entropy_source_self_test( 0 ) ) != 0 ) goto cleanup; #endif cleanup: mbedtls_entropy_free( &ctx ); #endif /* !MBEDTLS_TEST_NULL_ENTROPY */ if( verbose != 0 ) { if( ret != 0 ) mbedtls_printf( "failed\n" ); else mbedtls_printf( "passed\n" ); mbedtls_printf( "\n" ); } return( ret != 0 ); } #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_ENTROPY_C */
23,495
727
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/ecp256.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/nexgen32e/x86feature.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "third_party/mbedtls/bignum_internal.h" #include "third_party/mbedtls/ecp.h" #include "third_party/mbedtls/ecp_internal.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/math.h" #include "third_party/mbedtls/profile.h" #include "third_party/mbedtls/select.h" /* clang-format off */ static bool mbedtls_p256_isz( uint64_t p[4] ) { return( !p[0] & !p[1] & !p[2] & !p[3] ); } static bool mbedtls_p256_gte( uint64_t p[5] ) { return( (((int64_t)p[4] > 0) | (!p[4] & ((p[3] > 0xffffffff00000001) | ((p[3] == 0xffffffff00000001) & ((p[2] > 0x0000000000000000) | ((p[2] == 0x0000000000000000) & ((p[1] > 0x00000000ffffffff) | ((p[1] == 0x00000000ffffffff) & ((p[0] > 0xffffffffffffffff) | (p[0] == 0xffffffffffffffff)))))))))) ); } static int mbedtls_p256_cmp( const uint64_t a[5], const uint64_t b[5] ) { int i, x, y, done = 0; // return -1 if a[4] < b[4] x = -((int64_t)a[4] < (int64_t)b[4]); done = x; // return +1 if a[4] > b[4] y = (int64_t)a[4] > (int64_t)b[4]; x = Select(x, y, done); done |= -y; for (i = 4; i--;) { y = -(a[i] < b[i]); x = Select(x, y, done); done |= y; y = a[i] > b[i]; x = Select(x, y, done); done |= -y; } return x; } static void mbedtls_p256_red( uint64_t p[5] ) { #if defined(__x86_64__) && !defined(__STRICT_ANSI__) asm("subq\t%1,%0\n\t" "sbbq\t%2,8+%0\n\t" "sbbq\t%3,16+%0\n\t" "sbbq\t%4,24+%0\n\t" "sbbq\t$0,32+%0" : "+o"(*p) : "i"(0xffffffffffffffffl), "r"(0x00000000ffffffffl), "i"(0x0000000000000000l), "r"(0xffffffff00000001l) : "memory", "cc"); #else uint64_t c; SBB( p[0], p[0], 0xffffffffffffffff, 0, c ); SBB( p[1], p[1], 0x00000000ffffffff, c, c ); SBB( p[2], p[2], 0x0000000000000000, c, c ); SBB( p[3], p[3], 0xffffffff00000001, c, c ); SBB( p[4], p[4], 0, c, c ); #endif } static void mbedtls_p256_gro( uint64_t p[5] ) { #if defined(__x86_64__) && !defined(__STRICT_ANSI__) asm("addq\t%1,%0\n\t" "adcq\t%2,8+%0\n\t" "adcq\t%3,16+%0\n\t" "adcq\t%4,24+%0\n\t" "adcq\t$0,32+%0" : "+o"(*p) : "i"(0xffffffffffffffffl), "r"(0x00000000ffffffffl), "i"(0x0000000000000000l), "r"(0xffffffff00000001l) : "memory", "cc"); #else uint64_t c; ADC( p[0], p[0], 0xffffffffffffffff, 0, c ); ADC( p[1], p[1], 0x00000000ffffffff, c, c ); ADC( p[2], p[2], 0x0000000000000000, c, c ); ADC( p[3], p[3], 0xffffffff00000001, c, c ); ADC( p[4], p[4], 0, c, c ); #endif } static void mbedtls_p256_rum( uint64_t p[5] ) { while( mbedtls_p256_gte( p ) ) mbedtls_p256_red( p ); } static void mbedtls_p256_mod(uint64_t X[8]) { secp256r1(X); if ((int64_t)X[4] < 0) { do { mbedtls_p256_gro(X); } while ((int64_t)X[4] < 0); } else { while (mbedtls_p256_gte(X)) { mbedtls_p256_red(X); } } } static void mbedtls_p256_sar( uint64_t p[5] ) { p[0] = p[0] >> 1 | p[1] << 63; p[1] = p[1] >> 1 | p[2] << 63; p[2] = p[2] >> 1 | p[3] << 63; p[3] = p[3] >> 1 | p[4] << 63; p[4] = (int64_t)p[4] >> 1; } static void mbedtls_p256_shl( uint64_t p[5] ) { p[4] = p[3] >> 63; p[3] = p[3] << 1 | p[2] >> 63; p[2] = p[2] << 1 | p[1] >> 63; p[1] = p[1] << 1 | p[0] >> 63; p[0] = p[0] << 1; mbedtls_p256_rum( p ); } static inline void mbedtls_p256_mul( uint64_t X[8], const uint64_t A[4], size_t n, const uint64_t B[4], size_t m ) { Mul4x4( X, A, B ); mbedtls_p256_mod( X ); } static void mbedtls_p256_plu( uint64_t A[5], const uint64_t B[5] ) { #if defined(__x86_64__) && !defined(__STRICT_ANSI__) asm("mov\t%1,%%rax\n\t" "add\t%%rax,%0\n\t" "mov\t8+%1,%%rax\n\t" "adc\t%%rax,8+%0\n\t" "mov\t16+%1,%%rax\n\t" "adc\t%%rax,16+%0\n\t" "mov\t24+%1,%%rax\n\t" "adc\t%%rax,24+%0\n\t" "mov\t32+%1,%%rax\n\t" "adc\t%%rax,32+%0" : /* no outputs */ : "o"(*A), "o"(*B) : "rax", "memory", "cc"); #else uint64_t c; ADC( A[0], A[0], B[0], 0, c ); ADC( A[1], A[1], B[1], c, c ); ADC( A[2], A[2], B[2], c, c ); ADC( A[3], A[3], B[3], c, c ); ADC( A[4], A[4], B[4], c, c ); #endif } static void mbedtls_p256_slu( uint64_t A[5], const uint64_t B[5] ) { #if defined(__x86_64__) && !defined(__STRICT_ANSI__) asm("mov\t%1,%%rax\n\t" "sub\t%%rax,%0\n\t" "mov\t8+%1,%%rax\n\t" "sbb\t%%rax,8+%0\n\t" "mov\t16+%1,%%rax\n\t" "sbb\t%%rax,16+%0\n\t" "mov\t24+%1,%%rax\n\t" "sbb\t%%rax,24+%0\n\t" "mov\t32+%1,%%rax\n\t" "sbb\t%%rax,32+%0" : /* no outputs */ : "o"(*A), "o"(*B) : "rax", "memory", "cc"); #else uint64_t c; SBB( A[0], A[0], B[0], 0, c ); SBB( A[1], A[1], B[1], c, c ); SBB( A[2], A[2], B[2], c, c ); SBB( A[3], A[3], B[3], c, c ); SBB( A[4], A[4], B[4], c, c ); #endif } static void mbedtls_p256_add( uint64_t X[5], const uint64_t A[4], const uint64_t B[4] ) { #if defined(__x86_64__) && !defined(__STRICT_ANSI__) asm("xor\t%%rcx,%%rcx\n\t" "mov\t%1,%%rax\n\t" "add\t%2,%%rax\n\t" "mov\t%%rax,%0\n\t" "mov\t8+%1,%%rax\n\t" "adc\t8+%2,%%rax\n\t" "mov\t%%rax,8+%0\n\t" "mov\t16+%1,%%rax\n\t" "adc\t16+%2,%%rax\n\t" "mov\t%%rax,16+%0\n\t" "mov\t24+%1,%%rax\n\t" "adc\t24+%2,%%rax\n\t" "mov\t%%rax,24+%0\n\t" "adc\t$0,%%rcx\n\t" "mov\t%%rcx,32+%0" : "+o"(*X) : "o"(*A), "o"(*B) : "rax", "rcx", "memory", "cc"); #else uint64_t c; ADC( X[0], A[0], B[0], 0, c ); ADC( X[1], A[1], B[1], c, c ); ADC( X[2], A[2], B[2], c, c ); ADC( X[3], A[3], B[3], c, X[4] ); #endif mbedtls_p256_rum( X ); MBEDTLS_ASSERT( 0 == X[4] ); } static void mbedtls_p256_sub( uint64_t X[5], const uint64_t A[4], const uint64_t B[4] ) { #if defined(__x86_64__) && !defined(__STRICT_ANSI__) asm("xor\t%%rcx,%%rcx\n\t" "mov\t%1,%%rax\n\t" "sub\t%2,%%rax\n\t" "mov\t%%rax,%0\n\t" "mov\t8+%1,%%rax\n\t" "sbb\t8+%2,%%rax\n\t" "mov\t%%rax,8+%0\n\t" "mov\t16+%1,%%rax\n\t" "sbb\t16+%2,%%rax\n\t" "mov\t%%rax,16+%0\n\t" "mov\t24+%1,%%rax\n\t" "sbb\t24+%2,%%rax\n\t" "mov\t%%rax,24+%0\n\t" "sbb\t$0,%%rcx\n\t" "mov\t%%rcx,32+%0" : "+o"(*X) : "o"(*A), "o"(*B) : "rax", "rcx", "memory", "cc"); #else uint64_t c; SBB( X[0], A[0], B[0], 0, c ); SBB( X[1], A[1], B[1], c, c ); SBB( X[2], A[2], B[2], c, c ); SBB( X[3], A[3], B[3], c, c ); X[4] = -c; #endif while( (int64_t)X[4] < 0 ) mbedtls_p256_gro( X ); MBEDTLS_ASSERT( 0 == X[4] ); } static void mbedtls_p256_hub( uint64_t A[5], const uint64_t B[4] ) { #if defined(__x86_64__) && !defined(__STRICT_ANSI__) asm("xor\t%%rcx,%%rcx\n\t" "mov\t%1,%%rax\n\t" "sub\t%%rax,%0\n\t" "mov\t8+%1,%%rax\n\t" "sbb\t%%rax,8+%0\n\t" "mov\t16+%1,%%rax\n\t" "sbb\t%%rax,16+%0\n\t" "mov\t24+%1,%%rax\n\t" "sbb\t%%rax,24+%0\n\t" "sbb\t$0,%%rcx\n\t" "mov\t%%rcx,32+%0" : "+o"(*A) : "o"(*B) : "rax", "rcx", "memory", "cc"); while( (int64_t)A[4] < 0 ) mbedtls_p256_gro( A ); MBEDTLS_ASSERT( 0 == A[4] ); #else mbedtls_p256_sub( A, A, B ); #endif } static inline void mbedtls_p256_cop( uint64_t X[4], const uint64_t Y[4] ) { memcpy( X, Y, 4 * 8 ); } static int mbedtls_p256_dim( mbedtls_ecp_point *R ) { int ret; if( R->X.n < 4 && ( ret = mbedtls_mpi_grow( &R->X, 4 ) ) ) return ret; if( R->Y.n < 4 && ( ret = mbedtls_mpi_grow( &R->Y, 4 ) ) ) return ret; if( R->Z.n < 4 && ( ret = mbedtls_mpi_grow( &R->Z, 4 ) ) ) return ret; return 0; } int mbedtls_p256_double_jac( const mbedtls_ecp_group *G, const mbedtls_ecp_point *P, mbedtls_ecp_point *R ) { int ret; struct { uint64_t X[4], Y[4], Z[4]; uint64_t M[8], S[8], T[8], U[8]; size_t Xn, Yn, Zn; } s; MBEDTLS_ASSERT( G->A.p == 0 ); MBEDTLS_ASSERT( P->X.s == 1 ); MBEDTLS_ASSERT( P->Y.s == 1 ); MBEDTLS_ASSERT( P->Z.s == 1 ); MBEDTLS_ASSERT( G->P.p[0] == 0xffffffffffffffff ); MBEDTLS_ASSERT( G->P.p[1] == 0x00000000ffffffff ); MBEDTLS_ASSERT( G->P.p[2] == 0x0000000000000000 ); MBEDTLS_ASSERT( G->P.p[3] == 0xffffffff00000001 ); if ( ( ret = mbedtls_p256_dim( R ) ) ) return ret; mbedtls_platform_zeroize(&s, sizeof(s)); s.Xn = mbedtls_mpi_limbs( &P->X ); s.Yn = mbedtls_mpi_limbs( &P->Y ); s.Zn = mbedtls_mpi_limbs( &P->Z ); MBEDTLS_ASSERT( s.Xn <= 4 ); MBEDTLS_ASSERT( s.Yn <= 4 ); MBEDTLS_ASSERT( s.Zn <= 4 ); memcpy( s.X, P->X.p, s.Xn * 8 ); memcpy( s.Y, P->Y.p, s.Yn * 8 ); memcpy( s.Z, P->Z.p, s.Zn * 8 ); mbedtls_p256_mul( s.S, s.Z, s.Zn, s.Z, s.Zn ); mbedtls_p256_add( s.T, s.X, s.S ); mbedtls_p256_sub( s.U, s.X, s.S ); mbedtls_p256_mul( s.S, s.T, 4, s.U, 4 ); mbedtls_mpi_mul_hlp1( 4, s.S, s.M, 3 ); mbedtls_p256_rum( s.M ); mbedtls_p256_mul( s.T, s.Y, s.Yn, s.Y, s.Yn ); mbedtls_p256_shl( s.T ); mbedtls_p256_mul( s.S, s.X, s.Xn, s.T, 4 ); mbedtls_p256_shl( s.S ); mbedtls_p256_mul( s.U, s.T, 4, s.T, 4 ); mbedtls_p256_shl( s.U ); mbedtls_p256_mul( s.T, s.M, 4, s.M, 4 ); mbedtls_p256_hub( s.T, s.S ); mbedtls_p256_hub( s.T, s.S ); mbedtls_p256_hub( s.S, s.T ); mbedtls_p256_mul( s.S, s.S, 4, s.M, 4 ); mbedtls_p256_hub( s.S, s.U ); mbedtls_p256_mul( s.U, s.Y, s.Yn, s.Z, s.Zn ); mbedtls_p256_shl( s.U ); mbedtls_p256_cop( R->X.p, s.T ); mbedtls_p256_cop( R->Y.p, s.S ); mbedtls_p256_cop( R->Z.p, s.U ); mbedtls_platform_zeroize( &s, sizeof(s) ); return 0; } int mbedtls_p256_add_mixed( const mbedtls_ecp_group *G, const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q, mbedtls_ecp_point *R ) { int ret; struct { uint64_t X[8], Y[8], Z[8]; uint64_t T1[8], T2[8], T3[8], T4[8]; size_t Xn, Yn, Zn, QXn, QYn; } s; MBEDTLS_ASSERT( P->X.s == 1 ); MBEDTLS_ASSERT( P->Y.s == 1 ); MBEDTLS_ASSERT( P->Z.s == 1 ); MBEDTLS_ASSERT( Q->X.s == 1 ); MBEDTLS_ASSERT( Q->Y.s == 1 ); if ( ( ret = mbedtls_p256_dim( R ) ) ) return ret; mbedtls_platform_zeroize(&s, sizeof(s)); s.Xn = mbedtls_mpi_limbs( &P->X ); s.Yn = mbedtls_mpi_limbs( &P->Y ); s.Zn = mbedtls_mpi_limbs( &P->Z ); s.QXn = mbedtls_mpi_limbs( &Q->X ); s.QYn = mbedtls_mpi_limbs( &Q->Y ); MBEDTLS_ASSERT( s.Xn <= 4 ); MBEDTLS_ASSERT( s.Yn <= 4 ); MBEDTLS_ASSERT( s.Zn <= 4 ); MBEDTLS_ASSERT( s.QXn <= 4 ); MBEDTLS_ASSERT( s.QYn <= 4 ); memcpy( s.X, P->X.p, s.Xn * 8 ); memcpy( s.Y, P->Y.p, s.Yn * 8 ); memcpy( s.Z, P->Z.p, s.Zn * 8 ); mbedtls_p256_mul( s.T1, s.Z, s.Zn, s.Z, s.Zn ); mbedtls_p256_mul( s.T2, s.T1, 4, s.Z, s.Zn ); mbedtls_p256_mul( s.T1, s.T1, 4, Q->X.p, s.QXn ); mbedtls_p256_mul( s.T2, s.T2, 4, Q->Y.p, s.QYn ); mbedtls_p256_hub( s.T1, s.X ); mbedtls_p256_hub( s.T2, s.Y ); if( mbedtls_p256_isz( s.T1 ) ) { if( mbedtls_p256_isz( s.T2 ) ) return mbedtls_p256_double_jac( G, P, R ); else return mbedtls_ecp_set_zero( R ); } mbedtls_p256_mul( s.Z, s.Z, s.Zn, s.T1, 4 ); mbedtls_p256_mul( s.T3, s.T1, 4, s.T1, 4 ); mbedtls_p256_mul( s.T4, s.T3, 4, s.T1, 4 ); mbedtls_p256_mul( s.T3, s.T3, 4, s.X, s.Xn ); mbedtls_p256_cop( s.T1, s.T3 ); mbedtls_p256_shl( s.T1 ); mbedtls_p256_mul( s.X, s.T2, 4, s.T2, 4 ); mbedtls_p256_hub( s.X, s.T1 ); mbedtls_p256_hub( s.X, s.T4 ); mbedtls_p256_hub( s.T3, s.X ); mbedtls_p256_mul( s.T3, s.T3, 4, s.T2, 4 ); mbedtls_p256_mul( s.T4, s.T4, 4, s.Y, s.Yn ); mbedtls_p256_sub( s.Y, s.T3, s.T4 ); mbedtls_p256_cop( R->X.p, s.X ); mbedtls_p256_cop( R->Y.p, s.Y ); mbedtls_p256_cop( R->Z.p, s.Z ); mbedtls_platform_zeroize(&s, sizeof(s)); return 0; } static void mbedtls_p256_inv( uint64_t X[4], const uint64_t A[4], const uint64_t N[4] ) { uint64_t TA[5], TU[5], TV[5], UV[4][5]; mbedtls_platform_zeroize( UV, sizeof( UV ) ); *(uint64_t *)mempcpy( TA, A, 4*8 ) = 0; *(uint64_t *)mempcpy( TU, A, 4*8 ) = 0; *(uint64_t *)mempcpy( TV, N, 4*8 ) = 0; UV[0][0] = 1; UV[3][0] = 1; do { while( ~TU[0] & 1 ){ mbedtls_p256_sar( TU ); if( ( UV[0][0] | UV[1][0] ) & 1 ){ mbedtls_p256_gro( UV[0] ); mbedtls_p256_slu( UV[1], TA ); } mbedtls_p256_sar( UV[0] ); mbedtls_p256_sar( UV[1] ); } while( ~TV[0] & 1 ){ mbedtls_p256_sar( TV ); if( ( UV[2][0] | UV[3][0] ) & 1 ){ mbedtls_p256_gro( UV[2] ); mbedtls_p256_slu( UV[3], TA ); } mbedtls_p256_sar( UV[2] ); mbedtls_p256_sar( UV[3] ); } if( mbedtls_p256_cmp( TU, TV ) >= 0 ){ mbedtls_p256_slu( TU, TV ); mbedtls_p256_slu( UV[0], UV[2] ); mbedtls_p256_slu( UV[1], UV[3] ); } else { mbedtls_p256_slu( TV, TU ); mbedtls_p256_slu( UV[2], UV[0] ); mbedtls_p256_slu( UV[3], UV[1] ); } } while( TU[0] | TU[1] | TU[2] | TU[3] | TU[4] ); while( (int64_t)UV[2][4] < 0 ) mbedtls_p256_gro( UV[2] ); while( mbedtls_p256_gte( UV[2] ) ) mbedtls_p256_red( UV[2] ); mbedtls_p256_cop( X, UV[2] ); } int mbedtls_p256_normalize_jac_many( const mbedtls_ecp_group *grp, mbedtls_ecp_point *T[], size_t n ) { size_t i; uint64_t *c, u[8], ta[8], Zi[8], ZZi[8]; if( !( c = mbedtls_calloc( n, 8*8 ) ) ) return( MBEDTLS_ERR_ECP_ALLOC_FAILED ); memcpy( c, T[0]->Z.p, T[0]->Z.n*8 ); for( i = 1; i < n; i++ ) mbedtls_p256_mul( c+i*8, c+(i-1)*8, 4, T[i]->Z.p, 4 ); mbedtls_p256_inv( u, c+(n-1)*8, grp->P.p ); for( i = n - 1; ; i-- ){ if( !i ){ mbedtls_p256_cop( Zi, u ); } else { mbedtls_p256_mul( Zi, u, 4, c+(i-1)*8, 4 ); mbedtls_p256_mul( u, u, 4, T[i]->Z.p, 4 ); } mbedtls_p256_mul( ZZi, Zi, 4, Zi, 4 ); mbedtls_p256_mul( ta, T[i]->X.p, 4, ZZi, 4 ); mbedtls_p256_cop( T[i]->X.p, ta ); mbedtls_p256_mul( ta, T[i]->Y.p, 4, ZZi, 4 ); mbedtls_p256_mul( ta, ta, 4, Zi, 4 ); mbedtls_p256_cop( T[i]->Y.p, ta ); mbedtls_mpi_free( &T[i]->Z ); if( !i ) break; } mbedtls_platform_zeroize( ta, sizeof( ta ) ); mbedtls_platform_zeroize( c, n*8*8 ); mbedtls_free( c ); return( 0 ); } int mbedtls_p256_normalize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt ) { int ret; uint64_t t[8], Zi[8], ZZi[8]; if ((ret = mbedtls_p256_dim(pt))) return ret; mbedtls_p256_inv( Zi, pt->Z.p, grp->P.p ); mbedtls_p256_mul( ZZi, Zi, 4, Zi, 4 ); mbedtls_p256_mul( t, pt->X.p, 4, ZZi, 4 ); mbedtls_p256_cop( pt->X.p, t ); mbedtls_p256_mul( t, pt->Y.p, 4, ZZi, 4 ); mbedtls_p256_mul( t, t, 4, Zi, 4 ); mbedtls_p256_cop( pt->Y.p, t ); mbedtls_mpi_lset( &pt->Z, 1 ); return( 0 ); }
18,383
562
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/README.cosmo
DESCRIPTION Mbed TLS is a crypto library built by ARM that's been released under a more permissive license than alternatives like OpenSSL and is useful for interoperating with systems that require TLS SOURCE https://github.com/ARMmbed/mbedtls/archive/refs/tags/v2.26.0.tar.gz LICENSE Apache 2.o LOCAL CHANGES - Strengthened server against DOS by removing expensive protections for old Internet Explorer against Lucky Thirteen timing attacks. - Reduce build+test latency from 15 seconds to 5 seconds. - Features have been added that enable this library to produce SSL certificates that can be used by Google Chrome. This required we add featurces for editing Subject Alternative Names and Extended Key Usage X.509 extension fields since upstream mbedtls can only do that currently for Netscape Navigator. - Local changes needed to be made to test_suite_ssl.datax due to it not taking into consideration disabled features like DTLS. - Local changes needed to be made to test_suite_x509parse.datax due to the features we added for subject alternative name parsing. - We've slimmed things down to meet our own specific local needs. For example, we don't need the PSA code since we don't target ARM hardware. We also don't need algorithms like camellia, blowfish, ripemd, arc4, ecjpake, etc. We want security code that's simple, readable, and easy to maintain. For example, the formally verified eliptic curve diffie-helman code was 38 files and most of it was dead code which could be consolidated into one < 1 kLOC file. - The only breaking API change that's been made is to redefine int arrays of things like long lists of ciphersuites to be uint8_t or uint16_t instead when appropriate. - Exported test code so it (a) doesn't have python as a build time dependency, (b) doesn't print to stdout on success, (c) bundles its dependencies inside a zip container so the tests are able to run hermetically if the binary is scp'd to some machine, and (d) doesn't have large amounts of duplicated generated code. - Fix mbedtls_mpi_sub_abs() to not call malloc/free/memcpy since it's called 11,124 times during as SSL handshake. - Make P-256 and P-384 modulus goes 5x faster. - Make chacha20 26% faster. - Make base64 100x faster. - Make gcm faster.
2,375
62
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/x509.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/fmt/fmt.h" #include "libc/mem/mem.h" #include "libc/stdio/stdio.h" #include "libc/time/struct/tm.h" #include "libc/time/time.h" #include "third_party/mbedtls/asn1.h" #include "third_party/mbedtls/certs.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/oid.h" #include "third_party/mbedtls/pem.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/x509.h" #include "third_party/mbedtls/x509_crt.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /* * X.509 common functions for parsing and verification * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * The ITU-T X.509 standard defines a certificate format for PKI. * * http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs) * http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs) * http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10) * * http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf * http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf */ #if defined(MBEDTLS_X509_USE_C) #define CHECK(code) if( ( ret = ( code ) ) != 0 ){ return( ret ); } #define CHECK_RANGE(min, max, val) \ do \ { \ if( ( val ) < ( min ) || ( val ) > ( max ) ) \ { \ return( ret ); \ } \ } while( 0 ) /* * CertificateSerialNumber ::= INTEGER */ int mbedtls_x509_get_serial( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *serial ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( ( end - *p ) < 1 ) return( MBEDTLS_ERR_X509_INVALID_SERIAL + MBEDTLS_ERR_ASN1_OUT_OF_DATA ); if( **p != ( MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_PRIMITIVE | 2 ) && **p != MBEDTLS_ASN1_INTEGER ) return( MBEDTLS_ERR_X509_INVALID_SERIAL + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ); serial->tag = *(*p)++; if( ( ret = mbedtls_asn1_get_len( p, end, &serial->len ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_SERIAL + ret ); serial->p = *p; *p += serial->len; return( 0 ); } /* Get an algorithm identifier without parameters (eg for signatures) * * AlgorithmIdentifier ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, * parameters ANY DEFINED BY algorithm OPTIONAL } */ int mbedtls_x509_get_alg_null( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *alg ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( ( ret = mbedtls_asn1_get_alg_null( p, end, alg ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_ALG + ret ); return( 0 ); } /* * Parse an algorithm identifier with (optional) parameters */ int mbedtls_x509_get_alg( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *alg, mbedtls_x509_buf *params ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( ( ret = mbedtls_asn1_get_alg( p, end, alg, params ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_ALG + ret ); return( 0 ); } /* * AttributeTypeAndValue ::= SEQUENCE { * type AttributeType, * value AttributeValue } * * AttributeType ::= OBJECT IDENTIFIER * * AttributeValue ::= ANY DEFINED BY AttributeType */ static int x509_get_attr_type_value( unsigned char **p, const unsigned char *end, mbedtls_x509_name *cur ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len; mbedtls_x509_buf *oid; mbedtls_x509_buf *val; if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_NAME + ret ); end = *p + len; if( ( end - *p ) < 1 ) return( MBEDTLS_ERR_X509_INVALID_NAME + MBEDTLS_ERR_ASN1_OUT_OF_DATA ); oid = &cur->oid; oid->tag = **p; if( ( ret = mbedtls_asn1_get_tag( p, end, &oid->len, MBEDTLS_ASN1_OID ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_NAME + ret ); oid->p = *p; *p += oid->len; if( ( end - *p ) < 1 ) return( MBEDTLS_ERR_X509_INVALID_NAME + MBEDTLS_ERR_ASN1_OUT_OF_DATA ); if( **p != MBEDTLS_ASN1_BMP_STRING && **p != MBEDTLS_ASN1_UTF8_STRING && **p != MBEDTLS_ASN1_T61_STRING && **p != MBEDTLS_ASN1_PRINTABLE_STRING && **p != MBEDTLS_ASN1_IA5_STRING && **p != MBEDTLS_ASN1_UNIVERSAL_STRING && **p != MBEDTLS_ASN1_BIT_STRING ) return( MBEDTLS_ERR_X509_INVALID_NAME + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ); val = &cur->val; val->tag = *(*p)++; if( ( ret = mbedtls_asn1_get_len( p, end, &val->len ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_NAME + ret ); val->p = *p; *p += val->len; if( *p != end ) { return( MBEDTLS_ERR_X509_INVALID_NAME + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } cur->next = NULL; return( 0 ); } /* * Name ::= CHOICE { -- only one possibility for now -- * rdnSequence RDNSequence } * * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName * * RelativeDistinguishedName ::= * SET OF AttributeTypeAndValue * * AttributeTypeAndValue ::= SEQUENCE { * type AttributeType, * value AttributeValue } * * AttributeType ::= OBJECT IDENTIFIER * * AttributeValue ::= ANY DEFINED BY AttributeType * * The data structure is optimized for the common case where each RDN has only * one element, which is represented as a list of AttributeTypeAndValue. * For the general case we still use a flat list, but we mark elements of the * same set so that they are "merged" together in the functions that consume * this list, eg mbedtls_x509_dn_gets(). */ int mbedtls_x509_get_name( unsigned char **p, const unsigned char *end, mbedtls_x509_name *cur ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t set_len; const unsigned char *end_set; /* don't use recursion, we'd risk stack overflow if not optimized */ while( 1 ) { /* * parse SET */ if( ( ret = mbedtls_asn1_get_tag( p, end, &set_len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_NAME + ret ); end_set = *p + set_len; while( 1 ) { if( ( ret = x509_get_attr_type_value( p, end_set, cur ) ) != 0 ) return( ret ); if( *p == end_set ) break; /* Mark this item as being no the only one in a set */ cur->next_merged = 1; cur->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_name ) ); if( cur->next == NULL ) return( MBEDTLS_ERR_X509_ALLOC_FAILED ); cur = cur->next; } /* * continue until end of SEQUENCE is reached */ if( *p == end ) return( 0 ); cur->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_name ) ); if( cur->next == NULL ) return( MBEDTLS_ERR_X509_ALLOC_FAILED ); cur = cur->next; } } forceinline int x509_parse_int( unsigned char **p, size_t n, int *res ) { *res = 0; for( ; n > 0; --n ) { if( ( **p < '0') || ( **p > '9' ) ) return ( MBEDTLS_ERR_X509_INVALID_DATE ); *res *= 10; *res += ( *(*p)++ - '0' ); } return( 0 ); } static int x509_date_is_valid(const mbedtls_x509_time *t ) { int ret = MBEDTLS_ERR_X509_INVALID_DATE; int month_len; CHECK_RANGE( 0, 9999, t->year ); CHECK_RANGE( 0, 23, t->hour ); CHECK_RANGE( 0, 59, t->min ); CHECK_RANGE( 0, 59, t->sec ); switch( t->mon ) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: month_len = 31; break; case 4: case 6: case 9: case 11: month_len = 30; break; case 2: if( ( !( t->year % 4 ) && t->year % 100 ) || !( t->year % 400 ) ) month_len = 29; else month_len = 28; break; default: return( ret ); } CHECK_RANGE( 1, month_len, t->day ); return( 0 ); } /* * Parse an ASN1_UTC_TIME (yearlen=2) or ASN1_GENERALIZED_TIME (yearlen=4) * field. */ static int x509_parse_time( unsigned char **p, size_t len, size_t yearlen, mbedtls_x509_time *tm ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; /* * Minimum length is 10 or 12 depending on yearlen */ if ( len < yearlen + 8 ) return ( MBEDTLS_ERR_X509_INVALID_DATE ); len -= yearlen + 8; /* * Parse year, month, day, hour, minute */ CHECK( x509_parse_int( p, yearlen, &tm->year ) ); if ( 2 == yearlen ) { if ( tm->year < 50 ) tm->year += 100; tm->year += 1900; } CHECK( x509_parse_int( p, 2, &tm->mon ) ); CHECK( x509_parse_int( p, 2, &tm->day ) ); CHECK( x509_parse_int( p, 2, &tm->hour ) ); CHECK( x509_parse_int( p, 2, &tm->min ) ); /* * Parse seconds if present */ if ( len >= 2 ) { CHECK( x509_parse_int( p, 2, &tm->sec ) ); len -= 2; } else return ( MBEDTLS_ERR_X509_INVALID_DATE ); /* * Parse trailing 'Z' if present */ if ( 1 == len && 'Z' == **p ) { (*p)++; len--; } /* * We should have parsed all characters at this point */ if ( 0 != len ) return ( MBEDTLS_ERR_X509_INVALID_DATE ); CHECK( x509_date_is_valid( tm ) ); return ( 0 ); } /* * Time ::= CHOICE { * utcTime UTCTime, * generalTime GeneralizedTime } */ int mbedtls_x509_get_time( unsigned char **p, const unsigned char *end, mbedtls_x509_time *tm ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len, year_len; unsigned char tag; if( ( end - *p ) < 1 ) return( MBEDTLS_ERR_X509_INVALID_DATE + MBEDTLS_ERR_ASN1_OUT_OF_DATA ); tag = **p; if( tag == MBEDTLS_ASN1_UTC_TIME ) year_len = 2; else if( tag == MBEDTLS_ASN1_GENERALIZED_TIME ) year_len = 4; else return( MBEDTLS_ERR_X509_INVALID_DATE + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ); (*p)++; ret = mbedtls_asn1_get_len( p, end, &len ); if( ret != 0 ) return( MBEDTLS_ERR_X509_INVALID_DATE + ret ); return x509_parse_time( p, len, year_len, tm ); } int mbedtls_x509_get_sig( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *sig ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len; int tag_type; if( ( end - *p ) < 1 ) return( MBEDTLS_ERR_X509_INVALID_SIGNATURE + MBEDTLS_ERR_ASN1_OUT_OF_DATA ); tag_type = **p; if( ( ret = mbedtls_asn1_get_bitstring_null( p, end, &len ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_SIGNATURE + ret ); sig->tag = tag_type; sig->len = len; sig->p = *p; *p += len; return( 0 ); } /* * Get signature algorithm from alg OID and optional parameters */ int mbedtls_x509_get_sig_alg( const mbedtls_x509_buf *sig_oid, const mbedtls_x509_buf *sig_params, mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg, void **sig_opts ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( *sig_opts != NULL ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); if( ( ret = mbedtls_oid_get_sig_alg( sig_oid, md_alg, pk_alg ) ) != 0 ) return( MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + ret ); /* Make sure parameters are absent or NULL */ if( ( sig_params->tag != MBEDTLS_ASN1_NULL && sig_params->tag != 0 ) || sig_params->len != 0 ) return( MBEDTLS_ERR_X509_INVALID_ALG ); return( 0 ); } /* * X.509 Extensions (No parsing of extensions, pointer should * be either manually updated or extensions should be parsed!) */ int mbedtls_x509_get_ext( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *ext, int tag ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len; /* Extension structure use EXPLICIT tagging. That is, the actual * `Extensions` structure is wrapped by a tag-length pair using * the respective context-specific tag. */ ret = mbedtls_asn1_get_tag( p, end, &ext->len, MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | tag ); if( ret != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); ext->tag = MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | tag; ext->p = *p; end = *p + ext->len; /* * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension */ if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( end != *p + len ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( 0 ); } /** * \brief Store the certificate DN in printable form into buf; * no more than size characters will be written. * * \param buf Buffer to write to * \param size Maximum size of buffer * \param dn The X509 name to represent * * \return The length of the string written (not including the * terminated nul byte), or a negative error code. */ int mbedtls_x509_dn_gets( char *buf, size_t size, const mbedtls_x509_name *dn ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t i, n; unsigned char c, merge = 0; const mbedtls_x509_name *name; const char *short_name = NULL; char s[MBEDTLS_X509_MAX_DN_NAME_SIZE], *p; mbedtls_platform_zeroize( s, sizeof( s ) ); name = dn; p = buf; n = size; while( name != NULL ) { if( !name->oid.p ) { name = name->next; continue; } if( name != dn ) { ret = mbedtls_snprintf( p, n, merge ? " + " : ", " ); MBEDTLS_X509_SAFE_SNPRINTF; } ret = mbedtls_oid_get_attr_short_name( &name->oid, &short_name ); if( ret == 0 ) ret = mbedtls_snprintf( p, n, "%s=", short_name ); else ret = mbedtls_snprintf( p, n, "\?\?=" ); MBEDTLS_X509_SAFE_SNPRINTF; for( i = 0; i < name->val.len; i++ ) { if( i >= sizeof( s ) - 1 ) break; c = name->val.p[i]; if( c < 32 || c >= 127 ) s[i] = '?'; else s[i] = c; } s[i] = '\0'; ret = mbedtls_snprintf( p, n, "%s", s ); MBEDTLS_X509_SAFE_SNPRINTF; merge = name->next_merged; name = name->next; } return( (int) ( size - n ) ); } /** * \brief Store the certificate serial in printable form into buf; * no more than size characters will be written. * * \param buf Buffer to write to * \param size Maximum size of buffer * \param serial The X509 serial to represent * * \return The length of the string written (not including the * terminated nul byte), or a negative error code. */ int mbedtls_x509_serial_gets( char *buf, size_t size, const mbedtls_x509_buf *serial ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t i, n, nr; char *p; p = buf; n = size; nr = ( serial->len <= 32 ) ? serial->len : 28; for( i = 0; i < nr; i++ ) { if( i == 0 && nr > 1 && serial->p[i] == 0x0 ) continue; ret = mbedtls_snprintf( p, n, "%02X%s", serial->p[i], ( i < nr - 1 ) ? ":" : "" ); MBEDTLS_X509_SAFE_SNPRINTF; } if( nr != serial->len ) { ret = mbedtls_snprintf( p, n, "...." ); MBEDTLS_X509_SAFE_SNPRINTF; } return( (int) ( size - n ) ); } /* * Helper for writing signature algorithms */ int mbedtls_x509_sig_alg_gets( char *buf, size_t size, const mbedtls_x509_buf *sig_oid, mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg, const void *sig_opts ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; char *p = buf; size_t n = size; const char *desc = NULL; ret = mbedtls_oid_get_sig_alg_desc( sig_oid, &desc ); if( ret != 0 ) ret = mbedtls_snprintf( p, n, "???" ); else ret = mbedtls_snprintf( p, n, "%s", desc ); MBEDTLS_X509_SAFE_SNPRINTF; return( (int)( size - n ) ); } /* * Helper for writing "RSA key size", "EC key size", etc */ int mbedtls_x509_key_size_helper( char *buf, size_t buf_size, const char *name ) { char *p = buf; size_t n = buf_size; int ret = MBEDTLS_ERR_THIS_CORRUPTION; ret = mbedtls_snprintf( p, n, "%s key size", name ); MBEDTLS_X509_SAFE_SNPRINTF; return( 0 ); } #if defined(MBEDTLS_HAVE_TIME_DATE) /* * Set the time structure to the current time. * Return 0 on success, non-zero on failure. */ static int x509_get_current_time( mbedtls_x509_time *now ) { struct tm *lt, tm_buf; mbedtls_time_t tt; int ret = 0; tt = mbedtls_time( NULL ); lt = mbedtls_platform_gmtime_r( &tt, &tm_buf ); if( lt == NULL ) ret = -1; else { now->year = lt->tm_year + 1900; now->mon = lt->tm_mon + 1; now->day = lt->tm_mday; now->hour = lt->tm_hour; now->min = lt->tm_min; now->sec = lt->tm_sec; } return( ret ); } /* * Return 0 if before <= after, 1 otherwise */ static int x509_check_time( const mbedtls_x509_time *before, const mbedtls_x509_time *after ) { if( before->year > after->year ) return( 1 ); if( before->year == after->year && before->mon > after->mon ) return( 1 ); if( before->year == after->year && before->mon == after->mon && before->day > after->day ) return( 1 ); if( before->year == after->year && before->mon == after->mon && before->day == after->day && before->hour > after->hour ) return( 1 ); if( before->year == after->year && before->mon == after->mon && before->day == after->day && before->hour == after->hour && before->min > after->min ) return( 1 ); if( before->year == after->year && before->mon == after->mon && before->day == after->day && before->hour == after->hour && before->min == after->min && before->sec > after->sec ) return( 1 ); return( 0 ); } #endif /* MBEDTLS_HAVE_TIME_DATE */ /** * \brief Check a given mbedtls_x509_time against the system time * and tell if it's in the past. * * \note Intended usage is "if( is_past( valid_to ) ) ERROR". * Hence the return value of 1 if on internal errors. * * \param to mbedtls_x509_time to check * * \return 1 if the given time is in the past or an error occurred, * 0 otherwise. */ int mbedtls_x509_time_is_past( const mbedtls_x509_time *to ) { #if defined(MBEDTLS_HAVE_TIME_DATE) mbedtls_x509_time now; if (x509_get_current_time(&now)) return 1; return x509_check_time(&now, to); #else /* MBEDTLS_HAVE_TIME_DATE */ return 0; #endif /* MBEDTLS_HAVE_TIME_DATE */ } /** * \brief Check a given mbedtls_x509_time against the system time * and tell if it's in the future. * * \note Intended usage is "if( is_future( valid_from ) ) ERROR". * Hence the return value of 1 if on internal errors. * * \param from mbedtls_x509_time to check * * \return 1 if the given time is in the future or an error occurred, * 0 otherwise. */ int mbedtls_x509_time_is_future( const mbedtls_x509_time *from ) { #if defined(MBEDTLS_HAVE_TIME_DATE) mbedtls_x509_time now; if (x509_get_current_time(&now)) return 1; return x509_check_time(from, &now); #else return 0; #endif } #if defined(MBEDTLS_SELF_TEST) /** * \brief Checkup routine * * \return 0 if successful, or 1 if the test failed */ int mbedtls_x509_self_test( int verbose ) { int ret = 0; #if defined(MBEDTLS_CERTS_C) && defined(MBEDTLS_SHA256_C) uint32_t flags; mbedtls_x509_crt cacert; mbedtls_x509_crt clicert; if( verbose != 0 ) mbedtls_printf( " X.509 certificate load: " ); mbedtls_x509_crt_init( &cacert ); mbedtls_x509_crt_init( &clicert ); ret = mbedtls_x509_crt_parse( &clicert, (const unsigned char *) mbedtls_test_cli_crt, mbedtls_test_cli_crt_len ); if( ret != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); goto cleanup; } ret = mbedtls_x509_crt_parse( &cacert, (const unsigned char *) mbedtls_test_ca_crt, mbedtls_test_ca_crt_len ); if( ret != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); goto cleanup; } if( verbose != 0 ) mbedtls_printf( "passed\n X.509 signature verify: "); ret = mbedtls_x509_crt_verify( &clicert, &cacert, NULL, NULL, &flags, NULL, NULL ); if( ret != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); goto cleanup; } if( verbose != 0 ) mbedtls_printf( "passed\n\n"); cleanup: mbedtls_x509_crt_free( &cacert ); mbedtls_x509_crt_free( &clicert ); #else ((void) verbose); #endif /* MBEDTLS_CERTS_C && MBEDTLS_SHA256_C */ return( ret ); } #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_X509_USE_C */
24,719
844
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/base64.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "third_party/mbedtls/base64.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/platform.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ #define ENC "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" static const unsigned char base64_dec_map[128] = { 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 62, 127, 127, 127, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 127, 127, 127, 64, 127, 127, 127, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 127, 127, 127, 127, 127, 127, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 127, 127, 127, 127, 127 }; #define BASE64_SIZE_T_MAX ( (size_t) -1 ) /* SIZE_T_MAX is not standard */ /* * Constant flow conditional assignment to unsigned char */ forceinline void mbedtls_base64_cond_assign_uchar( unsigned char * dest, const unsigned char * const src, unsigned char condition ) { /* Generate bitmask from condition, mask will either be 0xFF or 0 */ unsigned char mask = ( condition | -condition ); mask >>= 7; mask = -mask; *dest = ( ( *src ) & mask ) | ( ( *dest ) & ~mask ); } /* * Constant flow conditional assignment to uint_32 */ forceinline void mbedtls_base64_cond_assign_uint32( uint32_t * dest, const uint32_t src, uint32_t condition ) { /* Generate bitmask from condition, mask will either be 0xFFFFFFFF or 0 */ uint32_t mask = ( condition | -condition ); mask >>= 31; mask = -mask; *dest = ( src & mask ) | ( ( *dest ) & ~mask ); } /* * Constant flow check for equality */ forceinline unsigned char mbedtls_base64_eq( size_t in_a, size_t in_b ) { size_t difference = in_a ^ in_b; difference |= -difference; /* cope with the varying size of size_t per platform */ difference >>= ( sizeof( difference ) * 8 - 1 ); return (unsigned char) ( 1 ^ difference ); } /* * Constant flow lookup into table. */ static inline unsigned char mbedtls_base64_table_lookup( const unsigned char * const table, const size_t table_size, const size_t table_index ) { return 0 <= table_index && table_index < table_size ? table[table_index] : 127; /* come on really? */ size_t i; unsigned char result = 0; for( i = 0; i < table_size; ++i ) { mbedtls_base64_cond_assign_uchar( &result, &table[i], mbedtls_base64_eq( i, table_index ) ); } return result; } /** * \brief Encode a buffer into base64 format * * \param dst destination buffer * \param dlen size of the destination buffer * \param olen number of bytes written * \param src source buffer * \param slen amount of data to be encoded * * \return 0 if successful, or MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL. * *olen is always updated to reflect the amount * of data that has (or would have) been written. * If that length cannot be represented, then no data is * written to the buffer and *olen is set to the maximum * length representable as a size_t. * * \note Call this function with dlen = 0 to obtain the * required buffer size in *olen */ int mbedtls_base64_encode( unsigned char *dst, size_t dlen, size_t *olen, const unsigned char *src, size_t slen ) { unsigned w; size_t i, n; unsigned char *q; const unsigned char *p, *pe; if( !slen ) { if (dlen) *dst = 0; *olen = 0; return 0; } n = slen / 3 + ( slen % 3 != 0 ); if( n > ( BASE64_SIZE_T_MAX - 1 ) / 4 ) { *olen = BASE64_SIZE_T_MAX; return MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL; } n *= 4; if( ( dlen < n + 1 ) || !dst ) { *olen = n + 1; return MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL; } for (q = dst, p = src, pe = p + slen; p < pe; p += 3) { w = p[0] << 020; if (p + 1 < pe) w |= p[1] << 010; if (p + 2 < pe) w |= p[2] << 000; *q++ = ENC[(w >> 18) & 077]; *q++ = ENC[(w >> 12) & 077]; *q++ = p + 1 < pe ? ENC[(w >> 6) & 077] : '='; *q++ = p + 2 < pe ? ENC[w & 077] : '='; } *olen = n; *q = 0; return 0; } /** * \brief Decode a base64-formatted buffer * * \param dst destination buffer (can be NULL for checking size) * \param dlen size of the destination buffer * \param olen number of bytes written * \param src source buffer * \param slen amount of data to be decoded * * \return 0 if successful, MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL, or * MBEDTLS_ERR_BASE64_INVALID_CHARACTER if the input data is * not correct. *olen is always updated to reflect the amount * of data that has (or would have) been written. * * \note Call this function with *dst = NULL or dlen = 0 to obtain * the required buffer size in *olen */ int mbedtls_base64_decode( unsigned char *dst, size_t dlen, size_t *olen, const unsigned char *src, size_t slen ) { size_t i, n; uint32_t j, x; unsigned char *p; unsigned char dec_map_lookup; /* First pass: check for validity and get output length */ for( i = n = j = 0; i < slen; i++ ) { /* Skip spaces before checking for EOL */ x = 0; while( i < slen && src[i] == ' ' ) { ++i; ++x; } /* Spaces at end of buffer are OK */ if( i == slen ) break; if( ( slen - i ) >= 2 && src[i] == '\r' && src[i + 1] == '\n' ) continue; if( src[i] == '\n' ) continue; /* Space inside a line is an error */ if( x != 0 ) return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER ); if( src[i] == '=' && ++j > 2 ) return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER ); dec_map_lookup = mbedtls_base64_table_lookup( base64_dec_map, sizeof( base64_dec_map ), src[i] ); if( src[i] > 127 || dec_map_lookup == 127 ) return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER ); if( dec_map_lookup < 64 && j != 0 ) return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER ); n++; } if( n == 0 ) { *olen = 0; return( 0 ); } /* The following expression is to calculate the following formula without * risk of integer overflow in n: * n = ( ( n * 6 ) + 7 ) >> 3; */ n = ( 6 * ( n >> 3 ) ) + ( ( 6 * ( n & 0x7 ) + 7 ) >> 3 ); n -= j; if( dst == NULL || dlen < n ) { *olen = n; return( MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL ); } for( j = 3, n = x = 0, p = dst; i > 0; i--, src++ ) { if( *src == '\r' || *src == '\n' || *src == ' ' ) continue; dec_map_lookup = mbedtls_base64_table_lookup( base64_dec_map, sizeof( base64_dec_map ), *src ); mbedtls_base64_cond_assign_uint32( &j, j - 1, mbedtls_base64_eq( dec_map_lookup, 64 ) ); x = ( x << 6 ) | ( dec_map_lookup & 0x3F ); if( ++n == 4 ) { n = 0; if( j > 0 ) *p++ = (unsigned char)( x >> 16 ); if( j > 1 ) *p++ = (unsigned char)( x >> 8 ); if( j > 2 ) *p++ = (unsigned char)( x ); } } *olen = p - dst; return( 0 ); } #if defined(MBEDTLS_SELF_TEST) static const unsigned char base64_test_dec[64] = { 0x24, 0x48, 0x6E, 0x56, 0x87, 0x62, 0x5A, 0xBD, 0xBF, 0x17, 0xD9, 0xA2, 0xC4, 0x17, 0x1A, 0x01, 0x94, 0xED, 0x8F, 0x1E, 0x11, 0xB3, 0xD7, 0x09, 0x0C, 0xB6, 0xE9, 0x10, 0x6F, 0x22, 0xEE, 0x13, 0xCA, 0xB3, 0x07, 0x05, 0x76, 0xC9, 0xFA, 0x31, 0x6C, 0x08, 0x34, 0xFF, 0x8D, 0xC2, 0x6C, 0x38, 0x00, 0x43, 0xE9, 0x54, 0x97, 0xAF, 0x50, 0x4B, 0xD1, 0x41, 0xBA, 0x95, 0x31, 0x5A, 0x0B, 0x97 }; static const unsigned char base64_test_enc[] = "JEhuVodiWr2/F9mixBcaAZTtjx4Rs9cJDLbpEG8i7hPK" "swcFdsn6MWwINP+Nwmw4AEPpVJevUEvRQbqVMVoLlw=="; /** * \brief Checkup routine * * \return 0 if successful, or 1 if the test failed */ int mbedtls_base64_self_test( int verbose ) { size_t len; const unsigned char *src; unsigned char buffer[128]; if( verbose != 0 ) mbedtls_printf( " Base64 encoding test: " ); src = base64_test_dec; if( mbedtls_base64_encode( buffer, sizeof( buffer ), &len, src, 64 ) != 0 || timingsafe_bcmp( base64_test_enc, buffer, 88 ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); return( 1 ); } if( verbose != 0 ) mbedtls_printf( "passed\n Base64 decoding test: " ); src = base64_test_enc; if( mbedtls_base64_decode( buffer, sizeof( buffer ), &len, src, 88 ) != 0 || timingsafe_bcmp( base64_test_dec, buffer, 64 ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); return( 1 ); } if( verbose != 0 ) mbedtls_printf( "passed\n\n" ); return( 0 ); } #endif /* MBEDTLS_SELF_TEST */
11,614
306
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/bigmul4.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/nexgen32e/x86feature.h" #include "third_party/mbedtls/bignum_internal.h" #include "third_party/mbedtls/math.h" /* clang-format off */ /** * Computes 512-bit product of 256-bit and 256-bit numbers. * * @param C receives 8 quadword result * @param A is left hand side which must have 4 quadwords * @param B is right hand side which must have 4 quadwords * @note words are host endian while array is little endian * @mayalias */ void (*Mul4x4)(uint64_t C[16], const uint64_t A[8], const uint64_t B[8]); static textstartup void Mul4x4Init() { Mul4x4 = X86_HAVE(ADX) && X86_HAVE(BMI2) ? Mul4x4Adx : Mul4x4Pure; } const void *const Mul4x4Ctor[] initarray = {Mul4x4Init}; void Mul4x4Pure(uint64_t C[16], const uint64_t A[8], const uint64_t B[8]) { uint128_t t; uint64_t h, c1, c2, c3; uint64_t r0, r1, r2, r3; c1 = c2 = c3 = 0; MADD(A[0], B[0], c1, c2, c3); r0 = c1, c1 = 0; MADD(A[0], B[1], c2, c3, c1); MADD(A[1], B[0], c2, c3, c1); r1 = c2, c2 = 0; MADD(A[2], B[0], c3, c1, c2); MADD(A[1], B[1], c3, c1, c2); MADD(A[0], B[2], c3, c1, c2); r2 = c3, c3 = 0; MADD(A[0], B[3], c1, c2, c3); MADD(A[1], B[2], c1, c2, c3); MADD(A[2], B[1], c1, c2, c3); MADD(A[3], B[0], c1, c2, c3); C[0] = r0; r3 = c1, c1 = 0; MADD(A[3], B[1], c2, c3, c1); MADD(A[2], B[2], c2, c3, c1); MADD(A[1], B[3], c2, c3, c1); C[1] = r1; C[4] = c2, c2 = 0; MADD(A[2], B[3], c3, c1, c2); MADD(A[3], B[2], c3, c1, c2); C[2] = r2; C[5] = c3, c3 = 0; MADD(A[3], B[3], c1, c2, c3); C[3] = r3; C[6] = c1; C[7] = c2; }
3,385
76
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/check.inc
/* clang-format off */ #if defined(TARGET_LIKE_MBED) && \ ( defined(MBEDTLS_NET_C) || defined(MBEDTLS_TIMING_C) ) #error "The NET and TIMING modules are not available for mbed OS - please use the network and timing functions provided by mbed OS" #endif #if defined(MBEDTLS_DEPRECATED_WARNING) && \ !defined(__GNUC__) && !defined(__clang__) #error "MBEDTLS_DEPRECATED_WARNING only works with GCC and Clang" #endif #if defined(MBEDTLS_HAVE_TIME_DATE) && !defined(MBEDTLS_HAVE_TIME) #error "MBEDTLS_HAVE_TIME_DATE without MBEDTLS_HAVE_TIME does not make sense" #endif #if defined(MBEDTLS_CTR_DRBG_C) && !defined(MBEDTLS_AES_C) #error "MBEDTLS_CTR_DRBG_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_DHM_C) && !defined(MBEDTLS_BIGNUM_C) #error "MBEDTLS_DHM_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT) && !defined(MBEDTLS_SSL_TRUNCATED_HMAC) #error "MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT defined, but not all prerequisites" #endif #if defined(MBEDTLS_CMAC_C) && \ !defined(MBEDTLS_AES_C) && !defined(MBEDTLS_DES_C) #error "MBEDTLS_CMAC_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_NIST_KW_C) && \ ( !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CIPHER_C) ) #error "MBEDTLS_NIST_KW_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECDH_C) && !defined(MBEDTLS_ECP_C) #error "MBEDTLS_ECDH_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECDSA_C) && \ ( !defined(MBEDTLS_ECP_C) || \ !( defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) || \ defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) ) || \ !defined(MBEDTLS_ASN1_PARSE_C) || \ !defined(MBEDTLS_ASN1_WRITE_C) ) #error "MBEDTLS_ECDSA_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECJPAKE_C) && \ ( !defined(MBEDTLS_ECP_C) || !defined(MBEDTLS_MD_C) ) #error "MBEDTLS_ECJPAKE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_RESTARTABLE) && \ ( defined(MBEDTLS_ECDH_COMPUTE_SHARED_ALT) || \ defined(MBEDTLS_ECDH_GEN_PUBLIC_ALT) || \ defined(MBEDTLS_ECDSA_SIGN_ALT) || \ defined(MBEDTLS_ECDSA_VERIFY_ALT) || \ defined(MBEDTLS_ECDSA_GENKEY_ALT) || \ defined(MBEDTLS_ECP_INTERNAL_ALT) || \ defined(MBEDTLS_ECP_ALT) ) #error "MBEDTLS_ECP_RESTARTABLE defined, but it cannot coexist with an alternative or PSA-based ECP implementation" #endif #if defined(MBEDTLS_ECP_RESTARTABLE) && \ ! defined(MBEDTLS_ECDH_LEGACY_CONTEXT) #error "MBEDTLS_ECP_RESTARTABLE defined, but not MBEDTLS_ECDH_LEGACY_CONTEXT" #endif #if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED) && \ defined(MBEDTLS_ECDH_LEGACY_CONTEXT) #error "MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED defined, but MBEDTLS_ECDH_LEGACY_CONTEXT not disabled" #endif #if defined(MBEDTLS_ECDSA_DETERMINISTIC) && !defined(MBEDTLS_HMAC_DRBG_C) #error "MBEDTLS_ECDSA_DETERMINISTIC defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_C) && ( !defined(MBEDTLS_BIGNUM_C) || ( \ !defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) && \ !defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) ) ) #error "MBEDTLS_ECP_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_C) && !( \ defined(MBEDTLS_ECP_ALT) || \ defined(MBEDTLS_CTR_DRBG_C) || \ defined(MBEDTLS_HMAC_DRBG_C) || \ defined(MBEDTLS_ECP_NO_INTERNAL_RNG)) #error "MBEDTLS_ECP_C requires a DRBG module unless MBEDTLS_ECP_NO_INTERNAL_RNG is defined or an alternative implementation is used" #endif #if defined(MBEDTLS_PK_PARSE_C) && !defined(MBEDTLS_ASN1_PARSE_C) #error "MBEDTLS_PK_PARSE_C defined, but not all prerequesites" #endif #if defined(MBEDTLS_ENTROPY_C) && (!defined(MBEDTLS_SHA512_C) && \ !defined(MBEDTLS_SHA256_C)) #error "MBEDTLS_ENTROPY_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_ENTROPY_C) && defined(MBEDTLS_SHA512_C) && \ defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN) && (MBEDTLS_CTR_DRBG_ENTROPY_LEN > 64) #error "MBEDTLS_CTR_DRBG_ENTROPY_LEN value too high" #endif #if defined(MBEDTLS_ENTROPY_C) && \ ( !defined(MBEDTLS_SHA512_C) || defined(MBEDTLS_ENTROPY_FORCE_SHA256) ) \ && defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN) && (MBEDTLS_CTR_DRBG_ENTROPY_LEN > 32) #error "MBEDTLS_CTR_DRBG_ENTROPY_LEN value too high" #endif #if defined(MBEDTLS_ENTROPY_C) && \ defined(MBEDTLS_ENTROPY_FORCE_SHA256) && !defined(MBEDTLS_SHA256_C) #error "MBEDTLS_ENTROPY_FORCE_SHA256 defined, but not all prerequisites" #endif #if defined(__has_feature) #if __has_feature(memory_sanitizer) #define MBEDTLS_HAS_MEMSAN #endif #endif #if defined(MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN) && !defined(MBEDTLS_HAS_MEMSAN) #error "MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN requires building with MemorySanitizer" #endif #undef MBEDTLS_HAS_MEMSAN #if defined(MBEDTLS_TEST_NULL_ENTROPY) && \ ( !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES) ) #error "MBEDTLS_TEST_NULL_ENTROPY defined, but not all prerequisites" #endif #if defined(MBEDTLS_TEST_NULL_ENTROPY) && \ ( defined(MBEDTLS_ENTROPY_NV_SEED) || defined(MBEDTLS_ENTROPY_HARDWARE_ALT) || \ defined(MBEDTLS_HAVEGE_C) ) #error "MBEDTLS_TEST_NULL_ENTROPY defined, but entropy sources too" #endif #if defined(MBEDTLS_GCM_C) && ( \ !defined(MBEDTLS_AES_C) && !defined(MBEDTLS_CAMELLIA_C) && !defined(MBEDTLS_ARIA_C) ) #error "MBEDTLS_GCM_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) #error "MBEDTLS_ECP_RANDOMIZE_JAC_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_ADD_MIXED_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) #error "MBEDTLS_ECP_ADD_MIXED_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) #error "MBEDTLS_ECP_DOUBLE_JAC_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) #error "MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) #error "MBEDTLS_ECP_NORMALIZE_JAC_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) #error "MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) #error "MBEDTLS_ECP_RANDOMIZE_MXZ_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) #error "MBEDTLS_ECP_NORMALIZE_MXZ_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_NO_FALLBACK) && !defined(MBEDTLS_ECP_INTERNAL_ALT) #error "MBEDTLS_ECP_NO_FALLBACK defined, but no alternative implementation enabled" #endif #if defined(MBEDTLS_HKDF_C) && !defined(MBEDTLS_MD_C) #error "MBEDTLS_HKDF_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_HMAC_DRBG_C) && !defined(MBEDTLS_MD_C) #error "MBEDTLS_HMAC_DRBG_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) && \ ( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_ECDSA_C) || \ !defined(MBEDTLS_X509_CRT_PARSE_C) ) #error "MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) && \ ( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_RSA_C) || \ !defined(MBEDTLS_X509_CRT_PARSE_C) ) #error "MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) && !defined(MBEDTLS_DHM_C) #error "MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) && \ !defined(MBEDTLS_ECDH_C) #error "MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) && \ ( !defined(MBEDTLS_DHM_C) || !defined(MBEDTLS_RSA_C) || \ !defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_PKCS1_V15) ) #error "MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \ ( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_RSA_C) || \ !defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_PKCS1_V15) ) #error "MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) && \ ( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_ECDSA_C) || \ !defined(MBEDTLS_X509_CRT_PARSE_C) ) #error "MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) && \ ( !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) || \ !defined(MBEDTLS_PKCS1_V15) ) #error "MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) && \ ( !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) || \ !defined(MBEDTLS_PKCS1_V15) ) #error "MBEDTLS_KEY_EXCHANGE_RSA_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) && \ ( !defined(MBEDTLS_ECJPAKE_C) || !defined(MBEDTLS_SHA256_C) || \ !defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) ) #error "MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) && \ !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) && \ ( !defined(MBEDTLS_SHA256_C) && \ !defined(MBEDTLS_SHA512_C) && \ !defined(MBEDTLS_SHA1_C) ) #error "!MBEDTLS_SSL_KEEP_PEER_CERTIFICATE requires MBEDTLS_SHA512_C, MBEDTLS_SHA256_C or MBEDTLS_SHA1_C" #endif #if defined(MBEDTLS_MEMORY_BACKTRACE) && !defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) #error "MBEDTLS_MEMORY_BACKTRACE defined, but not all prerequesites" #endif #if defined(MBEDTLS_MEMORY_DEBUG) && !defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) #error "MBEDTLS_MEMORY_DEBUG defined, but not all prerequesites" #endif #if defined(MBEDTLS_PEM_PARSE_C) && !defined(MBEDTLS_BASE64_C) #error "MBEDTLS_PEM_PARSE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_PEM_WRITE_C) && !defined(MBEDTLS_BASE64_C) #error "MBEDTLS_PEM_WRITE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_PK_C) && \ ( !defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_ECP_C) ) #error "MBEDTLS_PK_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_PK_PARSE_C) && !defined(MBEDTLS_PK_C) #error "MBEDTLS_PK_PARSE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_PK_WRITE_C) && !defined(MBEDTLS_PK_C) #error "MBEDTLS_PK_WRITE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_PKCS11_C) && !defined(MBEDTLS_PK_C) #error "MBEDTLS_PKCS11_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_PKCS11_C) #if defined(MBEDTLS_DEPRECATED_REMOVED) #error "MBEDTLS_PKCS11_C is deprecated and will be removed in a future version of Mbed TLS" #elif defined(MBEDTLS_DEPRECATED_WARNING) #warning "MBEDTLS_PKCS11_C is deprecated and will be removed in a future version of Mbed TLS" #endif #endif /* MBEDTLS_PKCS11_C */ #if defined(MBEDTLS_RSA_C) && ( !defined(MBEDTLS_BIGNUM_C) || \ !defined(MBEDTLS_OID_C) ) #error "MBEDTLS_RSA_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_RSA_C) && ( !defined(MBEDTLS_PKCS1_V21) && \ !defined(MBEDTLS_PKCS1_V15) ) #error "MBEDTLS_RSA_C defined, but none of the PKCS1 versions enabled" #endif #if defined(MBEDTLS_SHA512_NO_SHA384) && !defined(MBEDTLS_SHA512_C) #error "MBEDTLS_SHA512_NO_SHA384 defined without MBEDTLS_SHA512_C" #endif #if defined(MBEDTLS_SSL_PROTO_SSL3) && ( !defined(MBEDTLS_MD5_C) || \ !defined(MBEDTLS_SHA1_C) ) #error "MBEDTLS_SSL_PROTO_SSL3 defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_PROTO_TLS1) && ( !defined(MBEDTLS_MD5_C) || \ !defined(MBEDTLS_SHA1_C) ) #error "MBEDTLS_SSL_PROTO_TLS1 defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_1) && ( !defined(MBEDTLS_MD5_C) || \ !defined(MBEDTLS_SHA1_C) ) #error "MBEDTLS_SSL_PROTO_TLS1_1 defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && ( !defined(MBEDTLS_SHA1_C) && \ !defined(MBEDTLS_SHA256_C) && !defined(MBEDTLS_SHA512_C) ) #error "MBEDTLS_SSL_PROTO_TLS1_2 defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) && ( !defined(MBEDTLS_HKDF_C) && \ !defined(MBEDTLS_SHA256_C) && !defined(MBEDTLS_SHA512_C) ) #error "MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL defined, but not all prerequisites" #endif #if (defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)) && \ !(defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) ) #error "One or more versions of the TLS protocol are enabled " \ "but no key exchange methods defined with MBEDTLS_KEY_EXCHANGE_xxxx" #endif #if defined(MBEDTLS_SSL_PROTO_DTLS) && \ !defined(MBEDTLS_SSL_PROTO_TLS1_1) && \ !defined(MBEDTLS_SSL_PROTO_TLS1_2) #error "MBEDTLS_SSL_PROTO_DTLS defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_CLI_C) && !defined(MBEDTLS_SSL_TLS_C) #error "MBEDTLS_SSL_CLI_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_TLS_C) && ( !defined(MBEDTLS_CIPHER_C) || \ !defined(MBEDTLS_MD_C) ) #error "MBEDTLS_SSL_TLS_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_SRV_C) && !defined(MBEDTLS_SSL_TLS_C) #error "MBEDTLS_SSL_SRV_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_TLS_C) && (!defined(MBEDTLS_SSL_PROTO_SSL3) && \ !defined(MBEDTLS_SSL_PROTO_TLS1) && !defined(MBEDTLS_SSL_PROTO_TLS1_1) && \ !defined(MBEDTLS_SSL_PROTO_TLS1_2)) #error "MBEDTLS_SSL_TLS_C defined, but no protocols are active" #endif #if defined(MBEDTLS_SSL_TLS_C) && (defined(MBEDTLS_SSL_PROTO_SSL3) && \ defined(MBEDTLS_SSL_PROTO_TLS1_1) && !defined(MBEDTLS_SSL_PROTO_TLS1)) #error "Illegal protocol selection" #endif #if defined(MBEDTLS_SSL_TLS_C) && (defined(MBEDTLS_SSL_PROTO_TLS1) && \ defined(MBEDTLS_SSL_PROTO_TLS1_2) && !defined(MBEDTLS_SSL_PROTO_TLS1_1)) #error "Illegal protocol selection" #endif #if defined(MBEDTLS_SSL_TLS_C) && (defined(MBEDTLS_SSL_PROTO_SSL3) && \ defined(MBEDTLS_SSL_PROTO_TLS1_2) && (!defined(MBEDTLS_SSL_PROTO_TLS1) || \ !defined(MBEDTLS_SSL_PROTO_TLS1_1))) #error "Illegal protocol selection" #endif #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && !defined(MBEDTLS_SSL_PROTO_DTLS) #error "MBEDTLS_SSL_DTLS_HELLO_VERIFY defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && \ !defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) #error "MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) && \ ( !defined(MBEDTLS_SSL_TLS_C) || !defined(MBEDTLS_SSL_PROTO_DTLS) ) #error "MBEDTLS_SSL_DTLS_ANTI_REPLAY defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \ ( !defined(MBEDTLS_SSL_TLS_C) || !defined(MBEDTLS_SSL_PROTO_DTLS) ) #error "MBEDTLS_SSL_DTLS_CONNECTION_ID defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \ defined(MBEDTLS_SSL_CID_IN_LEN_MAX) && \ MBEDTLS_SSL_CID_IN_LEN_MAX > 255 #error "MBEDTLS_SSL_CID_IN_LEN_MAX too large (max 255)" #endif #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \ defined(MBEDTLS_SSL_CID_OUT_LEN_MAX) && \ MBEDTLS_SSL_CID_OUT_LEN_MAX > 255 #error "MBEDTLS_SSL_CID_OUT_LEN_MAX too large (max 255)" #endif #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) && \ ( !defined(MBEDTLS_SSL_TLS_C) || !defined(MBEDTLS_SSL_PROTO_DTLS) ) #error "MBEDTLS_SSL_DTLS_BADMAC_LIMIT defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) && \ !defined(MBEDTLS_SSL_PROTO_TLS1) && \ !defined(MBEDTLS_SSL_PROTO_TLS1_1) && \ !defined(MBEDTLS_SSL_PROTO_TLS1_2) #error "MBEDTLS_SSL_ENCRYPT_THEN_MAC defined, but not all prerequsites" #endif #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) && \ !defined(MBEDTLS_SSL_PROTO_TLS1) && \ !defined(MBEDTLS_SSL_PROTO_TLS1_1) && \ !defined(MBEDTLS_SSL_PROTO_TLS1_2) #error "MBEDTLS_SSL_EXTENDED_MASTER_SECRET defined, but not all prerequsites" #endif #if defined(MBEDTLS_SSL_TICKET_C) && !defined(MBEDTLS_CIPHER_C) #error "MBEDTLS_SSL_TICKET_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) && \ !defined(MBEDTLS_SSL_PROTO_SSL3) && !defined(MBEDTLS_SSL_PROTO_TLS1) #undef MBEDTLS_SSL_CBC_RECORD_SPLITTING #endif #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) && \ !defined(MBEDTLS_X509_CRT_PARSE_C) #error "MBEDTLS_SSL_SERVER_NAME_INDICATION defined, but not all prerequisites" #endif #if defined(MBEDTLS_VERSION_FEATURES) && !defined(MBEDTLS_VERSION_C) #error "MBEDTLS_VERSION_FEATURES defined, but not all prerequisites" #endif #if defined(MBEDTLS_X509_USE_C) && ( !defined(MBEDTLS_BIGNUM_C) || \ !defined(MBEDTLS_OID_C) || !defined(MBEDTLS_ASN1_PARSE_C) || \ !defined(MBEDTLS_PK_PARSE_C) ) #error "MBEDTLS_X509_USE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_X509_CREATE_C) && ( !defined(MBEDTLS_BIGNUM_C) || \ !defined(MBEDTLS_OID_C) || !defined(MBEDTLS_ASN1_WRITE_C) || \ !defined(MBEDTLS_PK_WRITE_C) ) #error "MBEDTLS_X509_CREATE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_CERTS_C) && !defined(MBEDTLS_X509_USE_C) #error "MBEDTLS_CERTS_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) && ( !defined(MBEDTLS_X509_USE_C) ) #error "MBEDTLS_X509_CRT_PARSE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_X509_CRL_PARSE_C) && ( !defined(MBEDTLS_X509_USE_C) ) #error "MBEDTLS_X509_CRL_PARSE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_X509_CSR_PARSE_C) && ( !defined(MBEDTLS_X509_USE_C) ) #error "MBEDTLS_X509_CSR_PARSE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_X509_CRT_WRITE_C) && ( !defined(MBEDTLS_X509_CREATE_C) ) #error "MBEDTLS_X509_CRT_WRITE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_X509_CSR_WRITE_C) && ( !defined(MBEDTLS_X509_CREATE_C) ) #error "MBEDTLS_X509_CSR_WRITE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_HAVE_INT32) && defined(MBEDTLS_HAVE_INT64) #error "MBEDTLS_HAVE_INT32 and MBEDTLS_HAVE_INT64 cannot be defined simultaneously" #endif /* MBEDTLS_HAVE_INT32 && MBEDTLS_HAVE_INT64 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) #if defined(MBEDTLS_DEPRECATED_REMOVED) #error "MBEDTLS_SSL_PROTO_SSL3 is deprecated and will be removed in a future version of Mbed TLS" #elif defined(MBEDTLS_DEPRECATED_WARNING) #warning "MBEDTLS_SSL_PROTO_SSL3 is deprecated and will be removed in a future version of Mbed TLS" #endif #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_DTLS_SRTP) && ( !defined(MBEDTLS_SSL_PROTO_DTLS) ) #error "MBEDTLS_SSL_DTLS_SRTP defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) && ( !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) ) #error "MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH defined, but not all prerequisites" #endif #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C) || defined(MBEDTLS_CHACHAPOLY_C) #define MBEDTLS_CIPHER_MODE_AEAD #endif #if defined(MBEDTLS_CIPHER_MODE_CBC) #define MBEDTLS_CIPHER_MODE_WITH_PADDING #endif #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) || \ defined(MBEDTLS_CHACHA20_C) #define MBEDTLS_CIPHER_MODE_STREAM #endif /* Key exchanges using a certificate */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) #define MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED #endif /* Key exchanges allowing client certificate requests */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) #define MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED #endif /* Key exchanges involving server signature in ServerKeyExchange */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) #define MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED #endif /* Key exchanges using ECDH */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) #define MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED #endif /* Key exchanges that don't involve ephemeral keys */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED) #define MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED #endif /* Key exchanges that involve ephemeral keys */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) #define MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED #endif /* Key exchanges using a PSK */ #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) #define MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED #endif /* Key exchanges using DHE */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) #define MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED #endif /* Key exchanges using ECDHE */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) #define MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED #endif /* Shorthand for restartable ECC */ #if defined(MBEDTLS_ECP_RESTARTABLE) && \ defined(MBEDTLS_SSL_CLI_C) && \ defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) #define MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED #endif /* Flags indicating whether to include code that is specific to certain * types of curves. These flags are for internal library use only. */ #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) #define MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED #endif #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) || \ defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) #define MBEDTLS_ECP_MONTGOMERY_ENABLED #endif /* This macro determines whether CBC is supported. */ #if defined(MBEDTLS_CIPHER_MODE_CBC) && \ ( defined(MBEDTLS_AES_C) || \ defined(MBEDTLS_CAMELLIA_C) || \ defined(MBEDTLS_ARIA_C) || \ defined(MBEDTLS_DES_C) ) #define MBEDTLS_SSL_SOME_SUITES_USE_CBC #endif /* This macro determines whether the CBC construct used in TLS 1.0-1.2 (as * opposed to the very different CBC construct used in SSLv3) is supported. */ #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) && \ ( defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) ) #define MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC #endif #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) || \ defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) #define MBEDTLS_SSL_SOME_MODES_USE_MAC #endif #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) && \ !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) #define MBEDTLS_SSL_PEER_CERT_DIGEST_MAX_LEN 48 #if defined(MBEDTLS_SHA256_C) #define MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE MBEDTLS_MD_SHA256 #define MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN 32 #elif defined(MBEDTLS_SHA512_C) #define MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE MBEDTLS_MD_SHA384 #define MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN 48 #elif defined(MBEDTLS_SHA1_C) #define MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE MBEDTLS_MD_SHA1 #define MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN 20 #else /* This is already checked in check.h, but be sure. */ #error "Bad configuration - need SHA-1, SHA-256 or SHA-512 enabled to compute digest of peer CRT." #endif #endif /* * Avoid warning from -pedantic. This is a convenient place for this * workaround since this is included by every single file before the * #if defined(MBEDTLS_xxx_C) that results in empty translation units. */ typedef int mbedtls_iso_c_forbids_empty_translation_units;
29,003
695
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/karatsuba.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/nexgen32e/x86feature.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "third_party/mbedtls/bignum_internal.h" #include "third_party/mbedtls/math.h" #include "third_party/mbedtls/platform.h" forceinline int Cmp(uint64_t *a, uint64_t *b, size_t n) { size_t i; uint64_t x, y; while (n--) { x = a[n]; y = b[n]; if (x != y) { return x > y ? 1 : -1; } } return 0; } forceinline bool Sub(uint64_t *C, uint64_t *A, uint64_t *B, size_t n) { bool cf; uint64_t c, i; #ifdef __x86_64__ asm volatile("xor\t%1,%1\n\t" ".align\t16\n1:\t" "mov\t(%5,%3,8),%1\n\t" "sbb\t(%6,%3,8),%1\n\t" "mov\t%1,(%4,%3,8)\n\t" "lea\t1(%3),%3\n\t" "dec\t%2\n\t" "jnz\t1b" : "=@ccb"(cf), "=&r"(c), "+c"(n), "=r"(i) : "r"(C), "r"(A), "r"(B), "3"(0) : "cc", "memory"); #else for (cf = false, c = i = 0; i < n; ++i) { SBB(C[i], A[i], B[i], cf, cf); } #endif return cf; } forceinline bool Add(uint64_t *C, uint64_t *A, uint64_t *B, size_t n) { bool cf; uint64_t c, i; #ifdef __x86_64__ asm volatile("xor\t%1,%1\n\t" ".align\t16\n1:\t" "mov\t(%5,%3,8),%1\n\t" "adc\t(%6,%3,8),%1\n\t" "mov\t%1,(%4,%3,8)\n\t" "lea\t1(%3),%3\n\t" "dec\t%2\n\t" "jnz\t1b" : "=@ccc"(cf), "=&r"(c), "+c"(n), "=r"(i) : "r"(C), "r"(A), "r"(B), "3"(0) : "cc", "memory"); #else for (cf = false, c = i = 0; i < n; ++i) { ADC(C[i], A[i], B[i], cf, cf); } #endif return cf; } /** * Multiplies huge numbers faster. * * For 4096 bit numbers it's twice as fast. * For 16384 bit numbers it's thrice as fast. */ void Karatsuba(uint64_t *C, uint64_t *A, uint64_t *B, size_t n, uint64_t *K) { int q, r; size_t i; uint64_t c, t; uint64_t *x, *y; if (n == 8) { #ifdef __x86_64__ if (X86_HAVE(BMI2) && X86_HAVE(ADX)) { Mul8x8Adx(C, A, B); return; } #endif Mul(C, A, 8, B, 8); return; } switch (Cmp(A, A + n / 2, n / 2) * 3 + Cmp(B + n / 2, B, n / 2)) { case -1 * 3 + +0: case +0 * 3 + -1: case +0 * 3 + +0: case +0 * 3 + +1: case +1 * 3 + +0: Karatsuba(C, A, B, n / 2, K + n * 2); Karatsuba(C + n, A + n / 2, B + n / 2, n / 2, K + n * 2); c = Add(K, C, C + n, n); c += Add(C + n / 2, C + n / 2, K, n); break; case -1 * 3 + -1: Sub(K, A + n / 2, A, n / 2); Sub(K + n / 2, B, B + n / 2, n / 2); Karatsuba(K + n, K, K + n / 2, n / 2, K + n * 2); Karatsuba(C, A, B, n / 2, K + n * 2); Karatsuba(C + n, A + n / 2, B + n / 2, n / 2, K + n * 2); c = Add(K, C, C + n, n); c += Add(K + n, K, K + n, n); c += Add(C + n / 2, C + n / 2, K + n, n); break; case -1 * 3 + +1: Sub(K, A + n / 2, A, n / 2); Sub(K + n / 2, B + n / 2, B, n / 2); Karatsuba(K + n, K, K + n / 2, n / 2, K + n * 2); Karatsuba(C, A, B, n / 2, K + n * 2); Karatsuba(C + n, A + n / 2, B + n / 2, n / 2, K + n * 2); c = Add(K, C, C + n, n); c -= Sub(K + n, K, K + n, n); c += Add(C + n / 2, C + n / 2, K + n, n); break; case +1 * 3 + -1: Sub(K, A, A + n / 2, n / 2); Sub(K + n / 2, B, B + n / 2, n / 2); Karatsuba(K + n, K, K + n / 2, n / 2, K + n * 2); Karatsuba(C, A, B, n / 2, K + n * 2); Karatsuba(C + n, A + n / 2, B + n / 2, n / 2, K + n * 2); c = Add(K, C, C + n, n); c -= Sub(K + n, K, K + n, n); c += Add(C + n / 2, C + n / 2, K + n, n); break; case +1 * 3 + +1: Sub(K, A, A + n / 2, n / 2); Sub(K + n / 2, B + n / 2, B, n / 2); Karatsuba(K + n, K, K + n / 2, n / 2, K + n * 2); Karatsuba(C, A, B, n / 2, K + n * 2); Karatsuba(C + n, A + n / 2, B + n / 2, n / 2, K + n * 2); c = Add(K, C, C + n, n); c += Add(K + n, K, K + n, n); c += Add(C + n / 2, C + n / 2, K + n, n); break; default: unreachable; } for (i = n / 2 + n; c && i < n + n; i++) { t = C[i]; c = (C[i] = t + c) < t; } }
6,067
165
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/everest.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016-2018 INRIA and Microsoft Corporation │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/bits.h" #include "third_party/mbedtls/endian.h" asm(".ident\t\"\\n\\n\ Everest (Apache 2.0)\\n\ Copyright 2016-2018 INRIA and Microsoft Corporation\""); asm(".include \"libc/disclaimer.inc\""); #define DW(x) (uint128_t)(x) #define EQ(x, y) ((((x ^ y) | (~(x ^ y) + 1)) >> 63) - 1) #define GTE(x, y) (((x ^ ((x ^ y) | ((x - y) ^ y))) >> 63) - 1) forceinline void HaclBignumCopy(uint64_t o[5], uint64_t p[5]) { for (unsigned i = 0; i < 5; ++i) { o[i] = p[i]; } } forceinline void HaclBignumFsum(uint64_t o[5], uint64_t p[5]) { for (unsigned i = 0; i < 5; ++i) { o[i] += p[i]; } } forceinline void HaclBignumTrunc(uint64_t o[5], uint128_t p[5]) { for (unsigned i = 0; i < 5; ++i) { o[i] = p[i]; } } forceinline void HaclBignumCarry(uint64_t p[5]) { for (unsigned i = 0; i < 4; ++i) { p[i + 1] += p[i] >> 51; p[i] &= 0x7ffffffffffff; } } forceinline void HaclBignumCarryWide(uint128_t p[5]) { for (unsigned i = 0; i < 4; ++i) { p[i + 1] += p[i] >> 51; p[i] &= 0x7ffffffffffff; } } static void HaclBignumFmulReduce(uint128_t o[5], uint64_t p[5], uint64_t q[5]) { uint64_t t; unsigned i, j; for (i = 0;; ++i) { for (j = 0; j < 5; ++j) { o[j] += DW(p[j]) * q[i]; } if (i == 4) break; t = p[4] * 19; p[4] = p[3]; p[3] = p[2]; p[2] = p[1]; p[1] = p[0]; p[0] = t; } } static void HaclBignumFmul(uint64_t o[5], uint64_t p[5], uint64_t q[5]) { uint128_t t[5] = {0}; uint64_t u[5] = {p[0], p[1], p[2], p[3], p[4]}; HaclBignumFmulReduce(t, u, q); HaclBignumCarryWide(t); t[0] += DW(19) * (uint64_t)(t[4] >> 51); HaclBignumTrunc(o, t); o[1] += o[0] >> 51; o[4] &= 0x7ffffffffffff; o[0] &= 0x7ffffffffffff; } static void HaclBignumFsquare(uint128_t t[5], uint64_t p[5]) { t[0] = DW(p[0] * 1) * p[0] + DW(p[4] * 38) * p[1] + DW(p[2] * 38) * p[3]; t[1] = DW(p[0] * 2) * p[1] + DW(p[4] * 38) * p[2] + DW(p[3] * 19) * p[3]; t[2] = DW(p[0] * 2) * p[2] + DW(p[1] * 01) * p[1] + DW(p[4] * 38) * p[3]; t[3] = DW(p[0] * 2) * p[3] + DW(p[1] * 02) * p[2] + DW(p[4]) * (p[4] * 19); t[4] = DW(p[0] * 2) * p[4] + DW(p[1] * 02) * p[3] + DW(p[2]) * p[2]; } static void HaclBignumFsqa(uint64_t o[5], uint32_t n) { uint128_t t[5]; for (unsigned i = 0; i < n; ++i) { HaclBignumFsquare(t, o); HaclBignumCarryWide(t); t[0] += DW(19) * (uint64_t)(t[4] >> 51); HaclBignumTrunc(o, t); o[1] += o[0] >> 51; o[4] &= 0x7ffffffffffff; o[0] &= 0x7ffffffffffff; } } static void HaclBignumFsqr(uint64_t o[5], uint64_t p[5], uint32_t n) { HaclBignumCopy(o, p); HaclBignumFsqa(o, n); } static void HaclBignumCrecip(uint64_t o[5], uint64_t z[5]) { uint64_t b[4][5]; HaclBignumFsqr(b[0], z, 1); HaclBignumFsqr(b[1], b[0], 2); HaclBignumFmul(b[2], b[1], z); HaclBignumFmul(b[0], b[2], b[0]); HaclBignumFsqr(b[1], b[0], 1); HaclBignumFmul(b[2], b[1], b[2]); HaclBignumFsqr(b[1], b[2], 5); HaclBignumFmul(b[2], b[1], b[2]); HaclBignumFsqr(b[1], b[2], 10); HaclBignumFmul(b[3], b[1], b[2]); HaclBignumFsqr(b[1], b[3], 20); HaclBignumFmul(b[1], b[1], b[3]); HaclBignumFsqa(b[1], 10); HaclBignumFmul(b[2], b[1], b[2]); HaclBignumFsqr(b[1], b[2], 50); HaclBignumFmul(b[3], b[1], b[2]); HaclBignumFsqr(b[1], b[3], 100); HaclBignumFmul(b[1], b[1], b[3]); HaclBignumFsqa(b[1], 50); HaclBignumFmul(b[1], b[1], b[2]); HaclBignumFsqa(b[1], 5); HaclBignumFmul(o, b[1], b[0]); } static void HaclBignumFdif(uint64_t a[5], uint64_t b[5]) { a[0] = b[0] + 0x3fffffffffff68 - a[0]; a[1] = b[1] + 0x3ffffffffffff8 - a[1]; a[2] = b[2] + 0x3ffffffffffff8 - a[2]; a[3] = b[3] + 0x3ffffffffffff8 - a[3]; a[4] = b[4] + 0x3ffffffffffff8 - a[4]; } static void HaclBignumFscalar(uint64_t o[5], uint64_t p[5], uint64_t s) { unsigned i; uint128_t t[5]; for (i = 0; i < 5; ++i) t[i] = DW(p[i]) * s; HaclBignumCarryWide(t); t[0] += DW(19) * (uint64_t)(t[4] >> 51); t[4] &= 0x7ffffffffffff; HaclBignumTrunc(o, t); } static void HaclEcPointSwap(uint64_t a[2][5], uint64_t b[2][5], uint64_t m) { unsigned i, j; uint64_t x, y; for (i = 0; i < 2; ++i) { for (j = 0; j < 5; ++j) { x = a[i][j] ^ (-m & (a[i][j] ^ b[i][j])); y = b[i][j] ^ (-m & (a[i][j] ^ b[i][j])); a[i][j] = x; b[i][j] = y; } } } static void HaclEcFormatFexpand(uint64_t o[5], uint8_t p[32]) { o[0] = READ64LE(p + 000) >> 00 & 0x7ffffffffffff; o[1] = READ64LE(p + 006) >> 03 & 0x7ffffffffffff; o[2] = READ64LE(p + 014) >> 06 & 0x7ffffffffffff; o[3] = READ64LE(p + 023) >> 01 & 0x7ffffffffffff; o[4] = READ64LE(p + 030) >> 12 & 0x7ffffffffffff; } static void HaclEcFormatFcontract(uint8_t o[32], uint64_t p[5]) { uint64_t m; HaclBignumCarry(p); p[0] += 19 * (p[4] >> 51); p[4] &= 0x7ffffffffffff; HaclBignumCarry(p); p[0] += 19 * (p[4] >> 51); p[1] += p[0] >> 51; p[0] &= 0x7ffffffffffff; p[1] &= 0x7ffffffffffff; p[4] &= 0x7ffffffffffff; m = GTE(p[0], 0x7ffffffffffed); m &= EQ(p[1], 0x7ffffffffffff); m &= EQ(p[2], 0x7ffffffffffff); m &= EQ(p[3], 0x7ffffffffffff); m &= EQ(p[4], 0x7ffffffffffff); p[0] -= 0x7ffffffffffed & m; p[1] -= 0x7ffffffffffff & m; p[2] -= 0x7ffffffffffff & m; p[3] -= 0x7ffffffffffff & m; p[4] -= 0x7ffffffffffff & m; Write64le(o + 000, p[1] << 51 | p[0] >> 00); Write64le(o + 010, p[2] << 38 | p[1] >> 13); Write64le(o + 020, p[3] << 25 | p[2] >> 26); Write64le(o + 030, p[4] << 12 | p[3] >> 39); } static void HaclEcFormatScalarOfPoint(uint8_t o[32], uint64_t p[2][5]) { uint64_t t[2][5]; HaclBignumCrecip(t[0], p[1]); HaclBignumFmul(t[1], p[0], t[0]); HaclEcFormatFcontract(o, t[1]); } static void HaclEcAddAndDoubleFmonty(uint64_t xz2[2][5], uint64_t xz3[2][5], uint64_t xz[2][5], uint64_t xzprime[2][5], uint64_t qx[5]) { uint64_t b[7][5]; HaclBignumCopy(b[0], xz[0]); HaclBignumFsum(xz[0], xz[1]); HaclBignumFdif(xz[1], b[0]); HaclBignumCopy(b[0], xzprime[0]); HaclBignumFsum(xzprime[0], xzprime[1]); HaclBignumFdif(xzprime[1], b[0]); HaclBignumFmul(b[4], xzprime[0], xz[1]); HaclBignumFmul(b[5], xz[0], xzprime[1]); HaclBignumCopy(b[0], b[4]); HaclBignumFsum(b[4], b[5]); HaclBignumFdif(b[5], b[0]); HaclBignumFsqr(xz3[0], b[4], 1); HaclBignumFsqr(b[6], b[5], 1); HaclBignumFmul(xz3[1], b[6], qx); HaclBignumFsqr(b[2], xz[0], 1); HaclBignumFsqr(b[3], xz[1], 1); HaclBignumFmul(xz2[0], b[2], b[3]); HaclBignumFdif(b[3], b[2]); HaclBignumFscalar(b[1], b[3], 121665); HaclBignumFsum(b[1], b[2]); HaclBignumFmul(xz2[1], b[1], b[3]); } /** * Computes elliptic curve 25519. */ void curve25519(uint8_t mypublic[32], const uint8_t secret[32], const uint8_t basepoint[32]) { uint32_t i, j; uint8_t e[32], s; uint64_t q[5], t[4][2][5] = {{{1}}, {{0}, {1}}}; HaclEcFormatFexpand(q, basepoint); for (j = 0; j < 32; ++j) e[j] = secret[j]; e[0] &= 248; e[31] = (e[31] & 127) | 64; HaclBignumCopy(t[1][0], q); for (i = 32; i--;) { for (s = e[i], j = 4; j--;) { HaclEcPointSwap(t[0], t[1], s >> 7); HaclEcAddAndDoubleFmonty(t[2], t[3], t[0], t[1], q); HaclEcPointSwap(t[2], t[3], s >> 7); s <<= 1; HaclEcPointSwap(t[2], t[3], s >> 7); HaclEcAddAndDoubleFmonty(t[0], t[1], t[2], t[3], q); HaclEcPointSwap(t[0], t[1], s >> 7); s <<= 1; } } HaclEcFormatScalarOfPoint(mypublic, t[0]); }
9,228
270
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/pkparse.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "third_party/mbedtls/asn1.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/ecdsa.h" #include "third_party/mbedtls/ecp.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/oid.h" #include "third_party/mbedtls/pem.h" #include "third_party/mbedtls/pk.h" #include "third_party/mbedtls/pkcs5.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/rsa.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /* * Public Key layer for parsing key files and structures * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(MBEDTLS_PK_PARSE_C) /* Parameter validation macros based on platform_util.h */ #define PK_VALIDATE_RET( cond ) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_PK_BAD_INPUT_DATA ) #define PK_VALIDATE( cond ) \ MBEDTLS_INTERNAL_VALIDATE( cond ) #if defined(MBEDTLS_FS_IO) /* * Load all data from a file into a given buffer. * * The file is expected to contain either PEM or DER encoded data. * A terminating null byte is always appended. It is included in the announced * length only if the data looks like it is PEM encoded. */ int mbedtls_pk_load_file( const char *path, unsigned char **buf, size_t *n ) { FILE *f; long size; PK_VALIDATE_RET( path != NULL ); PK_VALIDATE_RET( buf != NULL ); PK_VALIDATE_RET( n != NULL ); if( ( f = fopen( path, "rb" ) ) == NULL ) return( MBEDTLS_ERR_PK_FILE_IO_ERROR ); fseek( f, 0, SEEK_END ); if( ( size = ftell( f ) ) == -1 ) { fclose( f ); return( MBEDTLS_ERR_PK_FILE_IO_ERROR ); } fseek( f, 0, SEEK_SET ); *n = (size_t) size; if( *n + 1 == 0 || ( *buf = mbedtls_calloc( 1, *n + 1 ) ) == NULL ) { fclose( f ); return( MBEDTLS_ERR_PK_ALLOC_FAILED ); } if( fread( *buf, 1, *n, f ) != *n ) { fclose( f ); mbedtls_platform_zeroize( *buf, *n ); mbedtls_free( *buf ); return( MBEDTLS_ERR_PK_FILE_IO_ERROR ); } fclose( f ); (*buf)[*n] = '\0'; if( strstr( (const char *) *buf, "-----BEGIN " ) != NULL ) ++*n; return( 0 ); } /** * \brief Load and parse a private key * * \param ctx The PK context to fill. It must have been initialized * but not set up. * \param path filename to read the private key from * \param password Optional password to decrypt the file. * Pass \c NULL if expecting a non-encrypted key. * Pass a null-terminated string if expecting an encrypted * key; a non-encrypted key will also be accepted. * The empty password is not supported. * * \note On entry, ctx must be empty, either freshly initialised * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a * specific key type, check the result with mbedtls_pk_can_do(). * * \note The key is also checked for correctness. * * \return 0 if successful, or a specific PK or PEM error code */ int mbedtls_pk_parse_keyfile( mbedtls_pk_context *ctx, const char *path, const char *pwd ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t n; unsigned char *buf; PK_VALIDATE_RET( ctx != NULL ); PK_VALIDATE_RET( path != NULL ); if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 ) return( ret ); if( pwd == NULL ) ret = mbedtls_pk_parse_key( ctx, buf, n, NULL, 0 ); else ret = mbedtls_pk_parse_key( ctx, buf, n, (const unsigned char *) pwd, strlen( pwd ) ); mbedtls_platform_zeroize( buf, n ); mbedtls_free( buf ); return( ret ); } /** * \brief Load and parse a public key * * \param ctx The PK context to fill. It must have been initialized * but not set up. * \param path filename to read the public key from * * \note On entry, ctx must be empty, either freshly initialised * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If * you need a specific key type, check the result with * mbedtls_pk_can_do(). * * \note The key is also checked for correctness. * * \return 0 if successful, or a specific PK or PEM error code */ int mbedtls_pk_parse_public_keyfile( mbedtls_pk_context *ctx, const char *path ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t n; unsigned char *buf; PK_VALIDATE_RET( ctx != NULL ); PK_VALIDATE_RET( path != NULL ); if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 ) return( ret ); ret = mbedtls_pk_parse_public_key( ctx, buf, n ); mbedtls_platform_zeroize( buf, n ); mbedtls_free( buf ); return( ret ); } #endif /* MBEDTLS_FS_IO */ #if defined(MBEDTLS_ECP_C) /* Minimally parse an ECParameters buffer to and mbedtls_asn1_buf * * ECParameters ::= CHOICE { * namedCurve OBJECT IDENTIFIER * specifiedCurve SpecifiedECDomain -- = SEQUENCE { ... } * -- implicitCurve NULL * } */ static int pk_get_ecparams( unsigned char **p, const unsigned char *end, mbedtls_asn1_buf *params ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if ( end - *p < 1 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + MBEDTLS_ERR_ASN1_OUT_OF_DATA ); /* Tag may be either OID or SEQUENCE */ params->tag = **p; if( params->tag != MBEDTLS_ASN1_OID #if defined(MBEDTLS_PK_PARSE_EC_EXTENDED) && params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) #endif ) { return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ); } if( ( ret = mbedtls_asn1_get_tag( p, end, &params->len, params->tag ) ) != 0 ) { return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); } params->p = *p; *p += params->len; if( *p != end ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( 0 ); } #if defined(MBEDTLS_PK_PARSE_EC_EXTENDED) /* * Parse a SpecifiedECDomain (SEC 1 C.2) and (mostly) fill the group with it. * WARNING: the resulting group should only be used with * pk_group_id_from_specified(), since its base point may not be set correctly * if it was encoded compressed. * * SpecifiedECDomain ::= SEQUENCE { * version SpecifiedECDomainVersion(ecdpVer1 | ecdpVer2 | ecdpVer3, ...), * fieldID FieldID {{FieldTypes}}, * curve Curve, * base ECPoint, * order INTEGER, * cofactor INTEGER OPTIONAL, * hash HashAlgorithm OPTIONAL, * ... * } * * We only support prime-field as field type, and ignore hash and cofactor. */ static int pk_group_from_specified( const mbedtls_asn1_buf *params, mbedtls_ecp_group *grp ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char *p = params->p; const unsigned char * const end = params->p + params->len; const unsigned char *end_field, *end_curve; size_t len; int ver; /* SpecifiedECDomainVersion ::= INTEGER { 1, 2, 3 } */ if( ( ret = mbedtls_asn1_get_int( &p, end, &ver ) ) != 0 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); if( ver < 1 || ver > 3 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT ); /* * FieldID { FIELD-ID:IOSet } ::= SEQUENCE { -- Finite field * fieldType FIELD-ID.&id({IOSet}), * parameters FIELD-ID.&Type({IOSet}{@fieldType}) * } */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( ret ); end_field = p + len; /* * FIELD-ID ::= TYPE-IDENTIFIER * FieldTypes FIELD-ID ::= { * { Prime-p IDENTIFIED BY prime-field } | * { Characteristic-two IDENTIFIED BY characteristic-two-field } * } * prime-field OBJECT IDENTIFIER ::= { id-fieldType 1 } */ if( ( ret = mbedtls_asn1_get_tag( &p, end_field, &len, MBEDTLS_ASN1_OID ) ) != 0 ) return( ret ); if( len != MBEDTLS_OID_SIZE( MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD ) || timingsafe_bcmp( p, MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD, len ) != 0 ) { return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE ); } p += len; /* Prime-p ::= INTEGER -- Field of size p. */ if( ( ret = mbedtls_asn1_get_mpi( &p, end_field, &grp->P ) ) != 0 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); grp->pbits = mbedtls_mpi_bitlen( &grp->P ); if( p != end_field ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); /* * Curve ::= SEQUENCE { * a FieldElement, * b FieldElement, * seed BIT STRING OPTIONAL * -- Shall be present if used in SpecifiedECDomain * -- with version equal to ecdpVer2 or ecdpVer3 * } */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( ret ); end_curve = p + len; /* * FieldElement ::= OCTET STRING * containing an integer in the case of a prime field */ if( ( ret = mbedtls_asn1_get_tag( &p, end_curve, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 || ( ret = mbedtls_mpi_read_binary( &grp->A, p, len ) ) != 0 ) { return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); } p += len; if( ( ret = mbedtls_asn1_get_tag( &p, end_curve, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 || ( ret = mbedtls_mpi_read_binary( &grp->B, p, len ) ) != 0 ) { return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); } p += len; /* Ignore seed BIT STRING OPTIONAL */ if( ( ret = mbedtls_asn1_get_tag( &p, end_curve, &len, MBEDTLS_ASN1_BIT_STRING ) ) == 0 ) p += len; if( p != end_curve ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); /* * ECPoint ::= OCTET STRING */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); if( ( ret = mbedtls_ecp_point_read_binary( grp, &grp->G, ( const unsigned char *) p, len ) ) != 0 ) { /* * If we can't read the point because it's compressed, cheat by * reading only the X coordinate and the parity bit of Y. */ if( ret != MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE || ( p[0] != 0x02 && p[0] != 0x03 ) || len != mbedtls_mpi_size( &grp->P ) + 1 || mbedtls_mpi_read_binary( &grp->G.X, p + 1, len - 1 ) != 0 || mbedtls_mpi_lset( &grp->G.Y, p[0] - 2 ) != 0 || mbedtls_mpi_lset( &grp->G.Z, 1 ) != 0 ) { return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT ); } } p += len; /* * order INTEGER */ if( ( ret = mbedtls_asn1_get_mpi( &p, end, &grp->N ) ) != 0 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); grp->nbits = mbedtls_mpi_bitlen( &grp->N ); /* * Allow optional elements by purposefully not enforcing p == end here. */ return( 0 ); } /* * Find the group id associated with an (almost filled) group as generated by * pk_group_from_specified(), or return an error if unknown. */ static int pk_group_id_from_group( const mbedtls_ecp_group *grp, mbedtls_ecp_group_id *grp_id ) { int ret = 0; mbedtls_ecp_group ref; const mbedtls_ecp_group_id *id; mbedtls_ecp_group_init( &ref ); for( id = mbedtls_ecp_grp_id_list(); *id != MBEDTLS_ECP_DP_NONE; id++ ) { /* Load the group associated to that id */ mbedtls_ecp_group_free( &ref ); MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &ref, *id ) ); /* Compare to the group we were given, starting with easy tests */ if( grp->pbits == ref.pbits && grp->nbits == ref.nbits && mbedtls_mpi_cmp_mpi( &grp->P, &ref.P ) == 0 && mbedtls_mpi_cmp_mpi( &grp->A, &ref.A ) == 0 && mbedtls_mpi_cmp_mpi( &grp->B, &ref.B ) == 0 && mbedtls_mpi_cmp_mpi( &grp->N, &ref.N ) == 0 && mbedtls_mpi_cmp_mpi( &grp->G.X, &ref.G.X ) == 0 && mbedtls_mpi_cmp_mpi( &grp->G.Z, &ref.G.Z ) == 0 && /* For Y we may only know the parity bit, so compare only that */ mbedtls_mpi_get_bit( &grp->G.Y, 0 ) == mbedtls_mpi_get_bit( &ref.G.Y, 0 ) ) { break; } } cleanup: mbedtls_ecp_group_free( &ref ); *grp_id = *id; if( ret == 0 && *id == MBEDTLS_ECP_DP_NONE ) ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE; return( ret ); } /* * Parse a SpecifiedECDomain (SEC 1 C.2) and find the associated group ID */ static int pk_group_id_from_specified( const mbedtls_asn1_buf *params, mbedtls_ecp_group_id *grp_id ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_ecp_group grp; mbedtls_ecp_group_init( &grp ); if( ( ret = pk_group_from_specified( params, &grp ) ) != 0 ) goto cleanup; ret = pk_group_id_from_group( &grp, grp_id ); cleanup: mbedtls_ecp_group_free( &grp ); return( ret ); } #endif /* MBEDTLS_PK_PARSE_EC_EXTENDED */ /* * Use EC parameters to initialise an EC group * * ECParameters ::= CHOICE { * namedCurve OBJECT IDENTIFIER * specifiedCurve SpecifiedECDomain -- = SEQUENCE { ... } * -- implicitCurve NULL */ static int pk_use_ecparams( const mbedtls_asn1_buf *params, mbedtls_ecp_group *grp ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_ecp_group_id grp_id; if( params->tag == MBEDTLS_ASN1_OID ) { if( mbedtls_oid_get_ec_grp( params, &grp_id ) != 0 ) return( MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE ); } else { #if defined(MBEDTLS_PK_PARSE_EC_EXTENDED) if( ( ret = pk_group_id_from_specified( params, &grp_id ) ) != 0 ) return( ret ); #else return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT ); #endif } /* * grp may already be initilialized; if so, make sure IDs match */ if( grp->id != MBEDTLS_ECP_DP_NONE && grp->id != grp_id ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT ); if( ( ret = mbedtls_ecp_group_load( grp, grp_id ) ) != 0 ) return( ret ); return( 0 ); } /* * EC public key is an EC point * * The caller is responsible for clearing the structure upon failure if * desired. Take care to pass along the possible ECP_FEATURE_UNAVAILABLE * return code of mbedtls_ecp_point_read_binary() and leave p in a usable state. */ static int pk_get_ecpubkey( unsigned char **p, const unsigned char *end, mbedtls_ecp_keypair *key ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( ( ret = mbedtls_ecp_point_read_binary( &key->grp, &key->Q, (const unsigned char *) *p, end - *p ) ) == 0 ) { ret = mbedtls_ecp_check_pubkey( &key->grp, &key->Q ); } /* * We know mbedtls_ecp_point_read_binary consumed all bytes or failed */ *p = (unsigned char *) end; return( ret ); } #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_RSA_C) /* * RSAPublicKey ::= SEQUENCE { * modulus INTEGER, -- n * publicExponent INTEGER -- e * } */ static int pk_get_rsapubkey( unsigned char **p, const unsigned char *end, mbedtls_rsa_context *rsa ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len; if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_PK_INVALID_PUBKEY + ret ); if( *p + len != end ) return( MBEDTLS_ERR_PK_INVALID_PUBKEY + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); /* Import N */ if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_INTEGER ) ) != 0 ) return( MBEDTLS_ERR_PK_INVALID_PUBKEY + ret ); if( ( ret = mbedtls_rsa_import_raw( rsa, *p, len, NULL, 0, NULL, 0, NULL, 0, NULL, 0 ) ) != 0 ) return( MBEDTLS_ERR_PK_INVALID_PUBKEY ); *p += len; /* Import E */ if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_INTEGER ) ) != 0 ) return( MBEDTLS_ERR_PK_INVALID_PUBKEY + ret ); if( ( ret = mbedtls_rsa_import_raw( rsa, NULL, 0, NULL, 0, NULL, 0, NULL, 0, *p, len ) ) != 0 ) return( MBEDTLS_ERR_PK_INVALID_PUBKEY ); *p += len; if( mbedtls_rsa_complete( rsa ) != 0 || mbedtls_rsa_check_pubkey( rsa ) != 0 ) { return( MBEDTLS_ERR_PK_INVALID_PUBKEY ); } if( *p != end ) return( MBEDTLS_ERR_PK_INVALID_PUBKEY + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( 0 ); } #endif /* MBEDTLS_RSA_C */ /* Get a PK algorithm identifier * * AlgorithmIdentifier ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, * parameters ANY DEFINED BY algorithm OPTIONAL } */ static int pk_get_pk_alg( unsigned char **p, const unsigned char *end, mbedtls_pk_type_t *pk_alg, mbedtls_asn1_buf *params ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_asn1_buf alg_oid; mbedtls_platform_zeroize( params, sizeof(mbedtls_asn1_buf) ); if( ( ret = mbedtls_asn1_get_alg( p, end, &alg_oid, params ) ) != 0 ) return( MBEDTLS_ERR_PK_INVALID_ALG + ret ); if( mbedtls_oid_get_pk_alg( &alg_oid, pk_alg ) != 0 ) return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG ); /* * No parameters with RSA (only for EC) */ if( *pk_alg == MBEDTLS_PK_RSA && ( ( params->tag != MBEDTLS_ASN1_NULL && params->tag != 0 ) || params->len != 0 ) ) { return( MBEDTLS_ERR_PK_INVALID_ALG ); } return( 0 ); } /** * \brief Parse a SubjectPublicKeyInfo DER structure * * SubjectPublicKeyInfo ::= SEQUENCE { * algorithm AlgorithmIdentifier, * subjectPublicKey BIT STRING } * * \param p the position in the ASN.1 data * \param end end of the buffer * \param pk The PK context to fill. It must have been initialized * but not set up. * * \return 0 if successful, or a specific PK error code */ int mbedtls_pk_parse_subpubkey( unsigned char **p, const unsigned char *end, mbedtls_pk_context *pk ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len; mbedtls_asn1_buf alg_params; mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE; const mbedtls_pk_info_t *pk_info; PK_VALIDATE_RET( p != NULL ); PK_VALIDATE_RET( *p != NULL ); PK_VALIDATE_RET( end != NULL ); PK_VALIDATE_RET( pk != NULL ); if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); } end = *p + len; if( ( ret = pk_get_pk_alg( p, end, &pk_alg, &alg_params ) ) != 0 ) return( ret ); if( ( ret = mbedtls_asn1_get_bitstring_null( p, end, &len ) ) != 0 ) return( MBEDTLS_ERR_PK_INVALID_PUBKEY + ret ); if( *p + len != end ) return( MBEDTLS_ERR_PK_INVALID_PUBKEY + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); if( ( pk_info = mbedtls_pk_info_from_type( pk_alg ) ) == NULL ) return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG ); if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 ) return( ret ); #if defined(MBEDTLS_RSA_C) if( pk_alg == MBEDTLS_PK_RSA ) { ret = pk_get_rsapubkey( p, end, mbedtls_pk_rsa( *pk ) ); } else #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_ECP_C) if( pk_alg == MBEDTLS_PK_ECKEY_DH || pk_alg == MBEDTLS_PK_ECKEY ) { ret = pk_use_ecparams( &alg_params, &mbedtls_pk_ec( *pk )->grp ); if( ret == 0 ) ret = pk_get_ecpubkey( p, end, mbedtls_pk_ec( *pk ) ); } else #endif /* MBEDTLS_ECP_C */ ret = MBEDTLS_ERR_PK_UNKNOWN_PK_ALG; if( ret == 0 && *p != end ) ret = MBEDTLS_ERR_PK_INVALID_PUBKEY + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH; if( ret != 0 ) mbedtls_pk_free( pk ); return( ret ); } #if defined(MBEDTLS_RSA_C) /* * Wrapper around mbedtls_asn1_get_mpi() that rejects zero. * * The value zero is: * - never a valid value for an RSA parameter * - interpreted as "omitted, please reconstruct" by mbedtls_rsa_complete(). * * Since values can't be omitted in PKCS#1, passing a zero value to * rsa_complete() would be incorrect, so reject zero values early. */ static int asn1_get_nonzero_mpi( unsigned char **p, const unsigned char *end, mbedtls_mpi *X ) { int ret; ret = mbedtls_asn1_get_mpi( p, end, X ); if( ret != 0 ) return( ret ); if( mbedtls_mpi_cmp_int( X, 0 ) == 0 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT ); return( 0 ); } /* * Parse a PKCS#1 encoded private RSA key */ static int pk_parse_key_pkcs1_der( mbedtls_rsa_context *rsa, const unsigned char *key, size_t keylen ) { int ret, version; size_t len; unsigned char *p, *end; mbedtls_mpi T; mbedtls_mpi_init( &T ); p = (unsigned char *) key; end = p + keylen; /* * This function parses the RSAPrivateKey (PKCS#1) * * RSAPrivateKey ::= SEQUENCE { * version Version, * modulus INTEGER, -- n * publicExponent INTEGER, -- e * privateExponent INTEGER, -- d * prime1 INTEGER, -- p * prime2 INTEGER, -- q * exponent1 INTEGER, -- d mod (p-1) * exponent2 INTEGER, -- d mod (q-1) * coefficient INTEGER, -- (inverse of q) mod p * otherPrimeInfos OtherPrimeInfos OPTIONAL * } */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); } end = p + len; if( ( ret = mbedtls_asn1_get_int( &p, end, &version ) ) != 0 ) { return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); } if( version != 0 ) { return( MBEDTLS_ERR_PK_KEY_INVALID_VERSION ); } /* Import N */ if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 || ( ret = mbedtls_rsa_import( rsa, &T, NULL, NULL, NULL, NULL ) ) != 0 ) goto cleanup; /* Import E */ if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 || ( ret = mbedtls_rsa_import( rsa, NULL, NULL, NULL, NULL, &T ) ) != 0 ) goto cleanup; /* Import D */ if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 || ( ret = mbedtls_rsa_import( rsa, NULL, NULL, NULL, &T, NULL ) ) != 0 ) goto cleanup; /* Import P */ if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 || ( ret = mbedtls_rsa_import( rsa, NULL, &T, NULL, NULL, NULL ) ) != 0 ) goto cleanup; /* Import Q */ if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 || ( ret = mbedtls_rsa_import( rsa, NULL, NULL, &T, NULL, NULL ) ) != 0 ) goto cleanup; #if !defined(MBEDTLS_RSA_NO_CRT) && !defined(MBEDTLS_RSA_ALT) /* * The RSA CRT parameters DP, DQ and QP are nominally redundant, in * that they can be easily recomputed from D, P and Q. However by * parsing them from the PKCS1 structure it is possible to avoid * recalculating them which both reduces the overhead of loading * RSA private keys into memory and also avoids side channels which * can arise when computing those values, since all of D, P, and Q * are secret. See https://eprint.iacr.org/2020/055 for a * description of one such attack. */ /* Import DP */ if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 || ( ret = mbedtls_mpi_copy( &rsa->DP, &T ) ) != 0 ) goto cleanup; /* Import DQ */ if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 || ( ret = mbedtls_mpi_copy( &rsa->DQ, &T ) ) != 0 ) goto cleanup; /* Import QP */ if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 || ( ret = mbedtls_mpi_copy( &rsa->QP, &T ) ) != 0 ) goto cleanup; #else /* Verify existance of the CRT params */ if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 || ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 || ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ) goto cleanup; #endif /* rsa_complete() doesn't complete anything with the default * implementation but is still called: * - for the benefit of alternative implementation that may want to * pre-compute stuff beyond what's provided (eg Montgomery factors) * - as is also sanity-checks the key * * Furthermore, we also check the public part for consistency with * mbedtls_pk_parse_pubkey(), as it includes size minima for example. */ if( ( ret = mbedtls_rsa_complete( rsa ) ) != 0 || ( ret = mbedtls_rsa_check_pubkey( rsa ) ) != 0 ) { goto cleanup; } if( p != end ) { ret = MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ; } cleanup: mbedtls_mpi_free( &T ); if( ret != 0 ) { /* Wrap error code if it's coming from a lower level */ if( ( ret & 0xff80 ) == 0 ) ret = MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret; else ret = MBEDTLS_ERR_PK_KEY_INVALID_FORMAT; mbedtls_rsa_free( rsa ); } return( ret ); } #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_ECP_C) /* * Parse a SEC1 encoded private EC key */ static int pk_parse_key_sec1_der( mbedtls_ecp_keypair *eck, const unsigned char *key, size_t keylen ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; int version, pubkey_done; size_t len; mbedtls_asn1_buf params; unsigned char *p = (unsigned char *) key; unsigned char *end = p + keylen; unsigned char *end2; /* * RFC 5915, or SEC1 Appendix C.4 * * ECPrivateKey ::= SEQUENCE { * version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1), * privateKey OCTET STRING, * parameters [0] ECParameters {{ NamedCurve }} OPTIONAL, * publicKey [1] BIT STRING OPTIONAL * } */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); } end = p + len; if( ( ret = mbedtls_asn1_get_int( &p, end, &version ) ) != 0 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); if( version != 1 ) return( MBEDTLS_ERR_PK_KEY_INVALID_VERSION ); if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); if( ( ret = mbedtls_mpi_read_binary( &eck->d, p, len ) ) != 0 ) { mbedtls_ecp_keypair_free( eck ); return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); } p += len; pubkey_done = 0; if( p != end ) { /* * Is 'parameters' present? */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) == 0 ) { if( ( ret = pk_get_ecparams( &p, p + len, &params) ) != 0 || ( ret = pk_use_ecparams( &params, &eck->grp ) ) != 0 ) { mbedtls_ecp_keypair_free( eck ); return( ret ); } } else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) { mbedtls_ecp_keypair_free( eck ); return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); } } if( p != end ) { /* * Is 'publickey' present? If not, or if we can't read it (eg because it * is compressed), create it from the private key. */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 1 ) ) == 0 ) { end2 = p + len; if( ( ret = mbedtls_asn1_get_bitstring_null( &p, end2, &len ) ) != 0 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); if( p + len != end2 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); if( ( ret = pk_get_ecpubkey( &p, end2, eck ) ) == 0 ) pubkey_done = 1; else { /* * The only acceptable failure mode of pk_get_ecpubkey() above * is if the point format is not recognized. */ if( ret != MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT ); } } else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) { mbedtls_ecp_keypair_free( eck ); return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); } } if( ! pubkey_done && ( ret = mbedtls_ecp_mul( &eck->grp, &eck->Q, &eck->d, &eck->grp.G, NULL, NULL ) ) != 0 ) { mbedtls_ecp_keypair_free( eck ); return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); } if( ( ret = mbedtls_ecp_check_privkey( &eck->grp, &eck->d ) ) != 0 ) { mbedtls_ecp_keypair_free( eck ); return( ret ); } return( 0 ); } #endif /* MBEDTLS_ECP_C */ /* * Parse an unencrypted PKCS#8 encoded private key * * Notes: * * - This function does not own the key buffer. It is the * responsibility of the caller to take care of zeroizing * and freeing it after use. * * - The function is responsible for freeing the provided * PK context on failure. * */ static int pk_parse_key_pkcs8_unencrypted_der( mbedtls_pk_context *pk, const unsigned char* key, size_t keylen ) { int ret, version; size_t len; mbedtls_asn1_buf params; unsigned char *p = (unsigned char *) key; unsigned char *end = p + keylen; mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE; const mbedtls_pk_info_t *pk_info; /* * This function parses the PrivateKeyInfo object (PKCS#8 v1.2 = RFC 5208) * * PrivateKeyInfo ::= SEQUENCE { * version Version, * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, * privateKey PrivateKey, * attributes [0] IMPLICIT Attributes OPTIONAL } * * Version ::= INTEGER * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier * PrivateKey ::= OCTET STRING * * The PrivateKey OCTET STRING is a SEC1 ECPrivateKey */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); } end = p + len; if( ( ret = mbedtls_asn1_get_int( &p, end, &version ) ) != 0 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); if( version != 0 ) return( MBEDTLS_ERR_PK_KEY_INVALID_VERSION + ret ); if( ( ret = pk_get_pk_alg( &p, end, &pk_alg, &params ) ) != 0 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); if( len < 1 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + MBEDTLS_ERR_ASN1_OUT_OF_DATA ); if( ( pk_info = mbedtls_pk_info_from_type( pk_alg ) ) == NULL ) return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG ); if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 ) return( ret ); #if defined(MBEDTLS_RSA_C) if( pk_alg == MBEDTLS_PK_RSA ) { if( ( ret = pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ), p, len ) ) != 0 ) { mbedtls_pk_free( pk ); return( ret ); } } else #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_ECP_C) if( pk_alg == MBEDTLS_PK_ECKEY || pk_alg == MBEDTLS_PK_ECKEY_DH ) { if( ( ret = pk_use_ecparams( &params, &mbedtls_pk_ec( *pk )->grp ) ) != 0 || ( ret = pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ), p, len ) ) != 0 ) { mbedtls_pk_free( pk ); return( ret ); } } else #endif /* MBEDTLS_ECP_C */ return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG ); return( 0 ); } /* * Parse an encrypted PKCS#8 encoded private key * * To save space, the decryption happens in-place on the given key buffer. * Also, while this function may modify the keybuffer, it doesn't own it, * and instead it is the responsibility of the caller to zeroize and properly * free it after use. * */ #if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C) static int pk_parse_key_pkcs8_encrypted_der( mbedtls_pk_context *pk, unsigned char *key, size_t keylen, const unsigned char *pwd, size_t pwdlen ) { int ret, decrypted = 0; size_t len; unsigned char *buf; unsigned char *p, *end; mbedtls_asn1_buf pbe_alg_oid, pbe_params; #if defined(MBEDTLS_PKCS12_C) mbedtls_cipher_type_t cipher_alg; mbedtls_md_type_t md_alg; #endif p = key; end = p + keylen; if( pwdlen == 0 ) return( MBEDTLS_ERR_PK_PASSWORD_REQUIRED ); /* * This function parses the EncryptedPrivateKeyInfo object (PKCS#8) * * EncryptedPrivateKeyInfo ::= SEQUENCE { * encryptionAlgorithm EncryptionAlgorithmIdentifier, * encryptedData EncryptedData * } * * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier * * EncryptedData ::= OCTET STRING * * The EncryptedData OCTET STRING is a PKCS#8 PrivateKeyInfo * */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); } end = p + len; if( ( ret = mbedtls_asn1_get_alg( &p, end, &pbe_alg_oid, &pbe_params ) ) != 0 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); buf = p; /* * Decrypt EncryptedData with appropriate PBE */ #if defined(MBEDTLS_PKCS12_C) if( mbedtls_oid_get_pkcs12_pbe_alg( &pbe_alg_oid, &md_alg, &cipher_alg ) == 0 ) { if( ( ret = mbedtls_pkcs12_pbe( &pbe_params, MBEDTLS_PKCS12_PBE_DECRYPT, cipher_alg, md_alg, pwd, pwdlen, p, len, buf ) ) != 0 ) { if( ret == MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH ) return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH ); return( ret ); } decrypted = 1; } else if( MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_128, &pbe_alg_oid ) == 0 ) { if( ( ret = mbedtls_pkcs12_pbe_sha1_rc4_128( &pbe_params, MBEDTLS_PKCS12_PBE_DECRYPT, pwd, pwdlen, p, len, buf ) ) != 0 ) { return( ret ); } // Best guess for password mismatch when using RC4. If first tag is // not MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE // if( *buf != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH ); decrypted = 1; } else #endif /* MBEDTLS_PKCS12_C */ #if defined(MBEDTLS_PKCS5_C) if( MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS5_PBES2, &pbe_alg_oid ) == 0 ) { if( ( ret = mbedtls_pkcs5_pbes2( &pbe_params, MBEDTLS_PKCS5_DECRYPT, pwd, pwdlen, p, len, buf ) ) != 0 ) { if( ret == MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH ) return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH ); return( ret ); } decrypted = 1; } else #endif /* MBEDTLS_PKCS5_C */ { ((void) pwd); } if( decrypted == 0 ) return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE ); return( pk_parse_key_pkcs8_unencrypted_der( pk, buf, len ) ); } #endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */ /** * \brief Parse a private key in PEM or DER format * * \param ctx The PK context to fill. It must have been initialized * but not set up. * \param key Input buffer to parse. * The buffer must contain the input exactly, with no * extra trailing material. For PEM, the buffer must * contain a null-terminated string. * \param keylen Size of \b key in bytes. * For PEM data, this includes the terminating null byte, * so \p keylen must be equal to `strlen(key) + 1`. * \param pwd Optional password for decryption. * Pass \c NULL if expecting a non-encrypted key. * Pass a string of \p pwdlen bytes if expecting an encrypted * key; a non-encrypted key will also be accepted. * The empty password is not supported. * \param pwdlen Size of the password in bytes. * Ignored if \p pwd is \c NULL. * * \note On entry, ctx must be empty, either freshly initialised * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a * specific key type, check the result with mbedtls_pk_can_do(). * * \note The key is also checked for correctness. * * \return 0 if successful, or a specific PK or PEM error code */ int mbedtls_pk_parse_key( mbedtls_pk_context *pk, const unsigned char *key, size_t keylen, const unsigned char *pwd, size_t pwdlen ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; const mbedtls_pk_info_t *pk_info; #if defined(MBEDTLS_PEM_PARSE_C) size_t len; mbedtls_pem_context pem; #endif PK_VALIDATE_RET( pk != NULL ); if( keylen == 0 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT ); PK_VALIDATE_RET( key != NULL ); #if defined(MBEDTLS_PEM_PARSE_C) mbedtls_pem_init( &pem ); #if defined(MBEDTLS_RSA_C) /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */ if( key[keylen - 1] != '\0' ) ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT; else ret = mbedtls_pem_read_buffer( &pem, "-----BEGIN RSA PRIVATE KEY-----", "-----END RSA PRIVATE KEY-----", key, pwd, pwdlen, &len ); if( ret == 0 ) { pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA ); if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 || ( ret = pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ), pem.buf, pem.buflen ) ) != 0 ) { mbedtls_pk_free( pk ); } mbedtls_pem_free( &pem ); return( ret ); } else if( ret == MBEDTLS_ERR_PEM_PASSWORD_MISMATCH ) return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH ); else if( ret == MBEDTLS_ERR_PEM_PASSWORD_REQUIRED ) return( MBEDTLS_ERR_PK_PASSWORD_REQUIRED ); else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT ) return( ret ); #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_ECP_C) /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */ if( key[keylen - 1] != '\0' ) ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT; else ret = mbedtls_pem_read_buffer( &pem, "-----BEGIN EC PRIVATE KEY-----", "-----END EC PRIVATE KEY-----", key, pwd, pwdlen, &len ); if( ret == 0 ) { pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY ); if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 || ( ret = pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ), pem.buf, pem.buflen ) ) != 0 ) { mbedtls_pk_free( pk ); } mbedtls_pem_free( &pem ); return( ret ); } else if( ret == MBEDTLS_ERR_PEM_PASSWORD_MISMATCH ) return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH ); else if( ret == MBEDTLS_ERR_PEM_PASSWORD_REQUIRED ) return( MBEDTLS_ERR_PK_PASSWORD_REQUIRED ); else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT ) return( ret ); #endif /* MBEDTLS_ECP_C */ /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */ if( key[keylen - 1] != '\0' ) ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT; else ret = mbedtls_pem_read_buffer( &pem, "-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----", key, NULL, 0, &len ); if( ret == 0 ) { if( ( ret = pk_parse_key_pkcs8_unencrypted_der( pk, pem.buf, pem.buflen ) ) != 0 ) { mbedtls_pk_free( pk ); } mbedtls_pem_free( &pem ); return( ret ); } else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT ) return( ret ); #if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C) /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */ if( key[keylen - 1] != '\0' ) ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT; else ret = mbedtls_pem_read_buffer( &pem, "-----BEGIN ENCRYPTED PRIVATE KEY-----", "-----END ENCRYPTED PRIVATE KEY-----", key, NULL, 0, &len ); if( ret == 0 ) { if( ( ret = pk_parse_key_pkcs8_encrypted_der( pk, pem.buf, pem.buflen, pwd, pwdlen ) ) != 0 ) { mbedtls_pk_free( pk ); } mbedtls_pem_free( &pem ); return( ret ); } else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT ) return( ret ); #endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */ #else ((void) pwd); ((void) pwdlen); #endif /* MBEDTLS_PEM_PARSE_C */ /* * At this point we only know it's not a PEM formatted key. Could be any * of the known DER encoded private key formats * * We try the different DER format parsers to see if one passes without * error */ #if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C) { unsigned char *key_copy; if( ( key_copy = mbedtls_calloc( 1, keylen ) ) == NULL ) return( MBEDTLS_ERR_PK_ALLOC_FAILED ); memcpy( key_copy, key, keylen ); ret = pk_parse_key_pkcs8_encrypted_der( pk, key_copy, keylen, pwd, pwdlen ); mbedtls_platform_zeroize( key_copy, keylen ); mbedtls_free( key_copy ); } if( ret == 0 ) return( 0 ); mbedtls_pk_free( pk ); mbedtls_pk_init( pk ); if( ret == MBEDTLS_ERR_PK_PASSWORD_MISMATCH ) { return( ret ); } #endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */ if( ( ret = pk_parse_key_pkcs8_unencrypted_der( pk, key, keylen ) ) == 0 ) return( 0 ); mbedtls_pk_free( pk ); mbedtls_pk_init( pk ); #if defined(MBEDTLS_RSA_C) pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA ); if( mbedtls_pk_setup( pk, pk_info ) == 0 && pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ), key, keylen ) == 0 ) { return( 0 ); } mbedtls_pk_free( pk ); mbedtls_pk_init( pk ); #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_ECP_C) pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY ); if( mbedtls_pk_setup( pk, pk_info ) == 0 && pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ), key, keylen ) == 0 ) { return( 0 ); } mbedtls_pk_free( pk ); #endif /* MBEDTLS_ECP_C */ /* If MBEDTLS_RSA_C is defined but MBEDTLS_ECP_C isn't, * it is ok to leave the PK context initialized but not * freed: It is the caller's responsibility to call pk_init() * before calling this function, and to call pk_free() * when it fails. If MBEDTLS_ECP_C is defined but MBEDTLS_RSA_C * isn't, this leads to mbedtls_pk_free() being called * twice, once here and once by the caller, but this is * also ok and in line with the mbedtls_pk_free() calls * on failed PEM parsing attempts. */ return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT ); } /** * \brief Parse a public key in PEM or DER format * * \param ctx The PK context to fill. It must have been initialized * but not set up. * \param key Input buffer to parse. * The buffer must contain the input exactly, with no * extra trailing material. For PEM, the buffer must * contain a null-terminated string. * \param keylen Size of \b key in bytes. * For PEM data, this includes the terminating null byte, * so \p keylen must be equal to `strlen(key) + 1`. * * \note On entry, ctx must be empty, either freshly initialised * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a * specific key type, check the result with mbedtls_pk_can_do(). * * \note The key is also checked for correctness. * * \return 0 if successful, or a specific PK or PEM error code */ int mbedtls_pk_parse_public_key( mbedtls_pk_context *ctx, const unsigned char *key, size_t keylen ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char *p; #if defined(MBEDTLS_RSA_C) const mbedtls_pk_info_t *pk_info; #endif #if defined(MBEDTLS_PEM_PARSE_C) size_t len; mbedtls_pem_context pem; #endif PK_VALIDATE_RET( ctx != NULL ); if( keylen == 0 ) return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT ); PK_VALIDATE_RET( key != NULL || keylen == 0 ); #if defined(MBEDTLS_PEM_PARSE_C) mbedtls_pem_init( &pem ); #if defined(MBEDTLS_RSA_C) /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */ if( key[keylen - 1] != '\0' ) ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT; else ret = mbedtls_pem_read_buffer( &pem, "-----BEGIN RSA PUBLIC KEY-----", "-----END RSA PUBLIC KEY-----", key, NULL, 0, &len ); if( ret == 0 ) { p = pem.buf; if( ( pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA ) ) == NULL ) return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG ); if( ( ret = mbedtls_pk_setup( ctx, pk_info ) ) != 0 ) return( ret ); if ( ( ret = pk_get_rsapubkey( &p, p + pem.buflen, mbedtls_pk_rsa( *ctx ) ) ) != 0 ) mbedtls_pk_free( ctx ); mbedtls_pem_free( &pem ); return( ret ); } else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT ) { mbedtls_pem_free( &pem ); return( ret ); } #endif /* MBEDTLS_RSA_C */ /* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */ if( key[keylen - 1] != '\0' ) ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT; else ret = mbedtls_pem_read_buffer( &pem, "-----BEGIN PUBLIC KEY-----", "-----END PUBLIC KEY-----", key, NULL, 0, &len ); if( ret == 0 ) { /* * Was PEM encoded */ p = pem.buf; ret = mbedtls_pk_parse_subpubkey( &p, p + pem.buflen, ctx ); mbedtls_pem_free( &pem ); return( ret ); } else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT ) { mbedtls_pem_free( &pem ); return( ret ); } mbedtls_pem_free( &pem ); #endif /* MBEDTLS_PEM_PARSE_C */ #if defined(MBEDTLS_RSA_C) if( ( pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA ) ) == NULL ) return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG ); if( ( ret = mbedtls_pk_setup( ctx, pk_info ) ) != 0 ) return( ret ); p = (unsigned char *)key; ret = pk_get_rsapubkey( &p, p + keylen, mbedtls_pk_rsa( *ctx ) ); if( ret == 0 ) { return( ret ); } mbedtls_pk_free( ctx ); if( ret != ( MBEDTLS_ERR_PK_INVALID_PUBKEY + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) ) { return( ret ); } #endif /* MBEDTLS_RSA_C */ p = (unsigned char *) key; ret = mbedtls_pk_parse_subpubkey( &p, p + keylen, ctx ); return( ret ); } #endif /* MBEDTLS_PK_PARSE_C */
52,697
1,553
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/rsa.h
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_RSA_H_ #define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_RSA_H_ #include "third_party/mbedtls/bignum.h" #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/md.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ /* clang-format off */ /* * RSA Error codes */ #define MBEDTLS_ERR_RSA_BAD_INPUT_DATA -0x4080 /*< Bad input parameters to function. */ #define MBEDTLS_ERR_RSA_INVALID_PADDING -0x4100 /*< Input data contains invalid padding and is rejected. */ #define MBEDTLS_ERR_RSA_KEY_GEN_FAILED -0x4180 /*< Something failed during generation of a key. */ #define MBEDTLS_ERR_RSA_KEY_CHECK_FAILED -0x4200 /*< Key failed to pass the validity check of the library. */ #define MBEDTLS_ERR_RSA_PUBLIC_FAILED -0x4280 /*< The public key operation failed. */ #define MBEDTLS_ERR_RSA_PRIVATE_FAILED -0x4300 /*< The private key operation failed. */ #define MBEDTLS_ERR_RSA_VERIFY_FAILED -0x4380 /*< The PKCS#1 verification failed. */ #define MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE -0x4400 /*< The output buffer for decryption is not large enough. */ #define MBEDTLS_ERR_RSA_RNG_FAILED -0x4480 /*< The random generator failed to generate non-zeros. */ /* MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION is deprecated and should not be used. */ #define MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION -0x4500 /*< The implementation does not offer the requested operation, for example, because of security violations or lack of functionality. */ /* MBEDTLS_ERR_RSA_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_RSA_HW_ACCEL_FAILED -0x4580 /*< RSA hardware accelerator failed. */ /* * RSA constants */ #define MBEDTLS_RSA_PUBLIC 0 /*< Request private key operation. */ #define MBEDTLS_RSA_PRIVATE 1 /*< Request public key operation. */ #define MBEDTLS_RSA_PKCS_V15 0 /*< Use PKCS#1 v1.5 encoding. */ #define MBEDTLS_RSA_PKCS_V21 1 /*< Use PKCS#1 v2.1 encoding. */ #define MBEDTLS_RSA_SIGN 1 /*< Identifier for RSA signature operations. */ #define MBEDTLS_RSA_CRYPT 2 /*< Identifier for RSA encryption and decryption operations. */ #define MBEDTLS_RSA_SALT_LEN_ANY -1 /* * The above constants may be used even if the RSA module is compile out, * eg for alternative (PKCS#11) RSA implemenations in the PK layers. */ /** * \brief The RSA context structure. * * \note Direct manipulation of the members of this structure * is deprecated. All manipulation should instead be done through * the public interface functions. */ typedef struct mbedtls_rsa_context { int ver; /*!< Reserved for internal purposes. * Do not set this field in application * code. Its meaning might change without * notice. */ size_t len; /*!< The size of \p N in Bytes. */ mbedtls_mpi N; /*!< The public modulus. */ mbedtls_mpi E; /*!< The public exponent. */ mbedtls_mpi D; /*!< The private exponent. */ mbedtls_mpi P; /*!< The first prime factor. */ mbedtls_mpi Q; /*!< The second prime factor. */ mbedtls_mpi DP; /*!< <code>D % (P - 1)</code>. */ mbedtls_mpi DQ; /*!< <code>D % (Q - 1)</code>. */ mbedtls_mpi QP; /*!< <code>1 / (Q % P)</code>. */ mbedtls_mpi RN; /*!< cached <code>R^2 mod N</code>. */ mbedtls_mpi RP; /*!< cached <code>R^2 mod P</code>. */ mbedtls_mpi RQ; /*!< cached <code>R^2 mod Q</code>. */ mbedtls_mpi Vi; /*!< The cached blinding value. */ mbedtls_mpi Vf; /*!< The cached un-blinding value. */ int padding; /*!< Selects padding mode: #MBEDTLS_RSA_PKCS_V15 for 1.5 padding and #MBEDTLS_RSA_PKCS_V21 for OAEP or PSS. */ int hash_id; /*!< Hash identifier of mbedtls_md_type_t type, as specified in md.h for use in the MGF mask generating function used in the EME-OAEP and EMSA-PSS encodings. */ } mbedtls_rsa_context; /** * \brief This function initializes an RSA context. * * \note Set padding to #MBEDTLS_RSA_PKCS_V21 for the RSAES-OAEP * encryption scheme and the RSASSA-PSS signature scheme. * * \note The \p hash_id parameter is ignored when using * #MBEDTLS_RSA_PKCS_V15 padding. * * \note The choice of padding mode is strictly enforced for private key * operations, since there might be security concerns in * mixing padding modes. For public key operations it is * a default value, which can be overridden by calling specific * \c rsa_rsaes_xxx or \c rsa_rsassa_xxx functions. * * \note The hash selected in \p hash_id is always used for OEAP * encryption. For PSS signatures, it is always used for * making signatures, but can be overridden for verifying them. * If set to #MBEDTLS_MD_NONE, it is always overridden. * * \param ctx The RSA context to initialize. This must not be \c NULL. * \param padding The padding mode to use. This must be either * #MBEDTLS_RSA_PKCS_V15 or #MBEDTLS_RSA_PKCS_V21. * \param hash_id The hash identifier of ::mbedtls_md_type_t type, if * \p padding is #MBEDTLS_RSA_PKCS_V21. It is unused * otherwise. */ void mbedtls_rsa_init( mbedtls_rsa_context *ctx, int padding, int hash_id ); /** * \brief This function imports a set of core parameters into an * RSA context. * * \note This function can be called multiple times for successive * imports, if the parameters are not simultaneously present. * * Any sequence of calls to this function should be followed * by a call to mbedtls_rsa_complete(), which checks and * completes the provided information to a ready-for-use * public or private RSA key. * * \note See mbedtls_rsa_complete() for more information on which * parameters are necessary to set up a private or public * RSA key. * * \note The imported parameters are copied and need not be preserved * for the lifetime of the RSA context being set up. * * \param ctx The initialized RSA context to store the parameters in. * \param N The RSA modulus. This may be \c NULL. * \param P The first prime factor of \p N. This may be \c NULL. * \param Q The second prime factor of \p N. This may be \c NULL. * \param D The private exponent. This may be \c NULL. * \param E The public exponent. This may be \c NULL. * * \return \c 0 on success. * \return A non-zero error code on failure. */ int mbedtls_rsa_import( mbedtls_rsa_context *ctx, const mbedtls_mpi *N, const mbedtls_mpi *P, const mbedtls_mpi *Q, const mbedtls_mpi *D, const mbedtls_mpi *E ); /** * \brief This function imports core RSA parameters, in raw big-endian * binary format, into an RSA context. * * \note This function can be called multiple times for successive * imports, if the parameters are not simultaneously present. * * Any sequence of calls to this function should be followed * by a call to mbedtls_rsa_complete(), which checks and * completes the provided information to a ready-for-use * public or private RSA key. * * \note See mbedtls_rsa_complete() for more information on which * parameters are necessary to set up a private or public * RSA key. * * \note The imported parameters are copied and need not be preserved * for the lifetime of the RSA context being set up. * * \param ctx The initialized RSA context to store the parameters in. * \param N The RSA modulus. This may be \c NULL. * \param N_len The Byte length of \p N; it is ignored if \p N == NULL. * \param P The first prime factor of \p N. This may be \c NULL. * \param P_len The Byte length of \p P; it ns ignored if \p P == NULL. * \param Q The second prime factor of \p N. This may be \c NULL. * \param Q_len The Byte length of \p Q; it is ignored if \p Q == NULL. * \param D The private exponent. This may be \c NULL. * \param D_len The Byte length of \p D; it is ignored if \p D == NULL. * \param E The public exponent. This may be \c NULL. * \param E_len The Byte length of \p E; it is ignored if \p E == NULL. * * \return \c 0 on success. * \return A non-zero error code on failure. */ int mbedtls_rsa_import_raw( mbedtls_rsa_context *ctx, unsigned char const *N, size_t N_len, unsigned char const *P, size_t P_len, unsigned char const *Q, size_t Q_len, unsigned char const *D, size_t D_len, unsigned char const *E, size_t E_len ); /** * \brief This function completes an RSA context from * a set of imported core parameters. * * To setup an RSA public key, precisely \p N and \p E * must have been imported. * * To setup an RSA private key, sufficient information must * be present for the other parameters to be derivable. * * The default implementation supports the following: * <ul><li>Derive \p P, \p Q from \p N, \p D, \p E.</li> * <li>Derive \p N, \p D from \p P, \p Q, \p E.</li></ul> * Alternative implementations need not support these. * * If this function runs successfully, it guarantees that * the RSA context can be used for RSA operations without * the risk of failure or crash. * * \warning This function need not perform consistency checks * for the imported parameters. In particular, parameters that * are not needed by the implementation might be silently * discarded and left unchecked. To check the consistency * of the key material, see mbedtls_rsa_check_privkey(). * * \param ctx The initialized RSA context holding imported parameters. * * \return \c 0 on success. * \return #MBEDTLS_ERR_RSA_BAD_INPUT_DATA if the attempted derivations * failed. * */ int mbedtls_rsa_complete( mbedtls_rsa_context *ctx ); /** * \brief This function exports the core parameters of an RSA key. * * If this function runs successfully, the non-NULL buffers * pointed to by \p N, \p P, \p Q, \p D, and \p E are fully * written, with additional unused space filled leading by * zero Bytes. * * If the function fails due to an unsupported operation, * the RSA context stays intact and remains usable. * * \param ctx The initialized RSA context. * \param N The MPI to hold the RSA modulus. * This may be \c NULL if this field need not be exported. * \param P The MPI to hold the first prime factor of \p N. * This may be \c NULL if this field need not be exported. * \param Q The MPI to hold the second prime factor of \p N. * This may be \c NULL if this field need not be exported. * \param D The MPI to hold the private exponent. * This may be \c NULL if this field need not be exported. * \param E The MPI to hold the public exponent. * This may be \c NULL if this field need not be exported. * * \return \c 0 on success. * \return A non-zero return code on any other failure. * */ int mbedtls_rsa_export( const mbedtls_rsa_context *ctx, mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q, mbedtls_mpi *D, mbedtls_mpi *E ); /** * \brief This function exports core parameters of an RSA key * in raw big-endian binary format. * * If this function runs successfully, the non-NULL buffers * pointed to by \p N, \p P, \p Q, \p D, and \p E are fully * written, with additional unused space filled leading by * zero Bytes. * * If the function fails due to an unsupported operation, * the RSA context stays intact and remains usable. * * \note The length parameters are ignored if the corresponding * buffer pointers are NULL. * * \param ctx The initialized RSA context. * \param N The Byte array to store the RSA modulus, * or \c NULL if this field need not be exported. * \param N_len The size of the buffer for the modulus. * \param P The Byte array to hold the first prime factor of \p N, * or \c NULL if this field need not be exported. * \param P_len The size of the buffer for the first prime factor. * \param Q The Byte array to hold the second prime factor of \p N, * or \c NULL if this field need not be exported. * \param Q_len The size of the buffer for the second prime factor. * \param D The Byte array to hold the private exponent, * or \c NULL if this field need not be exported. * \param D_len The size of the buffer for the private exponent. * \param E The Byte array to hold the public exponent, * or \c NULL if this field need not be exported. * \param E_len The size of the buffer for the public exponent. * * \return \c 0 on success. * \return A non-zero return code on any other failure. */ int mbedtls_rsa_export_raw( const mbedtls_rsa_context *ctx, unsigned char *N, size_t N_len, unsigned char *P, size_t P_len, unsigned char *Q, size_t Q_len, unsigned char *D, size_t D_len, unsigned char *E, size_t E_len ); /** * \brief This function exports CRT parameters of a private RSA key. * * \note Alternative RSA implementations not using CRT-parameters * internally can implement this function based on * mbedtls_rsa_deduce_opt(). * * \param ctx The initialized RSA context. * \param DP The MPI to hold \c D modulo `P-1`, * or \c NULL if it need not be exported. * \param DQ The MPI to hold \c D modulo `Q-1`, * or \c NULL if it need not be exported. * \param QP The MPI to hold modular inverse of \c Q modulo \c P, * or \c NULL if it need not be exported. * * \return \c 0 on success. * \return A non-zero error code on failure. * */ int mbedtls_rsa_export_crt( const mbedtls_rsa_context *ctx, mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP ); /** * \brief This function sets padding for an already initialized RSA * context. See mbedtls_rsa_init() for details. * * \param ctx The initialized RSA context to be configured. * \param padding The padding mode to use. This must be either * #MBEDTLS_RSA_PKCS_V15 or #MBEDTLS_RSA_PKCS_V21. * \param hash_id The #MBEDTLS_RSA_PKCS_V21 hash identifier. */ void mbedtls_rsa_set_padding( mbedtls_rsa_context *ctx, int padding, int hash_id ); /** * \brief This function retrieves the length of RSA modulus in Bytes. * * \param ctx The initialized RSA context. * * \return The length of the RSA modulus in Bytes. * */ size_t mbedtls_rsa_get_len( const mbedtls_rsa_context *ctx ); /** * \brief This function generates an RSA keypair. * * \note mbedtls_rsa_init() must be called before this function, * to set up the RSA context. * * \param ctx The initialized RSA context used to hold the key. * \param f_rng The RNG function to be used for key generation. * This must not be \c NULL. * \param p_rng The RNG context to be passed to \p f_rng. * This may be \c NULL if \p f_rng doesn't need a context. * \param nbits The size of the public key in bits. * \param exponent The public exponent to use. For example, \c 65537. * This must be odd and greater than \c 1. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, unsigned int nbits, int exponent ); /** * \brief This function checks if a context contains at least an RSA * public key. * * If the function runs successfully, it is guaranteed that * enough information is present to perform an RSA public key * operation using mbedtls_rsa_public(). * * \param ctx The initialized RSA context to check. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. * */ int mbedtls_rsa_check_pubkey( const mbedtls_rsa_context *ctx ); /** * \brief This function checks if a context contains an RSA private key * and perform basic consistency checks. * * \note The consistency checks performed by this function not only * ensure that mbedtls_rsa_private() can be called successfully * on the given context, but that the various parameters are * mutually consistent with high probability, in the sense that * mbedtls_rsa_public() and mbedtls_rsa_private() are inverses. * * \warning This function should catch accidental misconfigurations * like swapping of parameters, but it cannot establish full * trust in neither the quality nor the consistency of the key * material that was used to setup the given RSA context: * <ul><li>Consistency: Imported parameters that are irrelevant * for the implementation might be silently dropped. If dropped, * the current function does not have access to them, * and therefore cannot check them. See mbedtls_rsa_complete(). * If you want to check the consistency of the entire * content of an PKCS1-encoded RSA private key, for example, you * should use mbedtls_rsa_validate_params() before setting * up the RSA context. * Additionally, if the implementation performs empirical checks, * these checks substantiate but do not guarantee consistency.</li> * <li>Quality: This function is not expected to perform * extended quality assessments like checking that the prime * factors are safe. Additionally, it is the responsibility of the * user to ensure the trustworthiness of the source of his RSA * parameters, which goes beyond what is effectively checkable * by the library.</li></ul> * * \param ctx The initialized RSA context to check. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_check_privkey( const mbedtls_rsa_context *ctx ); /** * \brief This function checks a public-private RSA key pair. * * It checks each of the contexts, and makes sure they match. * * \param pub The initialized RSA context holding the public key. * \param prv The initialized RSA context holding the private key. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub, const mbedtls_rsa_context *prv ); /** * \brief This function performs an RSA public key operation. * * \param ctx The initialized RSA context to use. * \param input The input buffer. This must be a readable buffer * of length \c ctx->len Bytes. For example, \c 256 Bytes * for an 2048-bit RSA modulus. * \param output The output buffer. This must be a writable buffer * of length \c ctx->len Bytes. For example, \c 256 Bytes * for an 2048-bit RSA modulus. * * \note This function does not handle message padding. * * \note Make sure to set \p input[0] = 0 or ensure that * input is smaller than \p N. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_public( mbedtls_rsa_context *ctx, const unsigned char *input, unsigned char *output ); /** * \brief This function performs an RSA private key operation. * * \note Blinding is used if and only if a PRNG is provided. * * \note If blinding is used, both the base of exponentation * and the exponent are blinded, providing protection * against some side-channel attacks. * * \warning It is deprecated and a security risk to not provide * a PRNG here and thereby prevent the use of blinding. * Future versions of the library may enforce the presence * of a PRNG. * * \param ctx The initialized RSA context to use. * \param f_rng The RNG function, used for blinding. It is discouraged * and deprecated to pass \c NULL here, in which case * blinding will be omitted. * \param p_rng The RNG context to pass to \p f_rng. This may be \c NULL * if \p f_rng is \c NULL or if \p f_rng doesn't need a context. * \param input The input buffer. This must be a readable buffer * of length \c ctx->len Bytes. For example, \c 256 Bytes * for an 2048-bit RSA modulus. * \param output The output buffer. This must be a writable buffer * of length \c ctx->len Bytes. For example, \c 256 Bytes * for an 2048-bit RSA modulus. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. * */ int mbedtls_rsa_private( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, const unsigned char *input, unsigned char *output ); /** * \brief This function adds the message padding, then performs an RSA * operation. * * It is the generic wrapper for performing a PKCS#1 encryption * operation using the \p mode from the context. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library * are likely to remove the \p mode argument and have it * implicitly set to #MBEDTLS_RSA_PUBLIC. * * \param ctx The initialized RSA context to use. * \param f_rng The RNG to use. It is mandatory for PKCS#1 v2.1 padding * encoding, and for PKCS#1 v1.5 padding encoding when used * with \p mode set to #MBEDTLS_RSA_PUBLIC. For PKCS#1 v1.5 * padding encoding and \p mode set to #MBEDTLS_RSA_PRIVATE, * it is used for blinding and should be provided in this * case; see mbedtls_rsa_private() for more. * \param p_rng The RNG context to be passed to \p f_rng. May be * \c NULL if \p f_rng is \c NULL or if \p f_rng doesn't * need a context argument. * \param mode The mode of operation. This must be either * #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE (deprecated). * \param ilen The length of the plaintext in Bytes. * \param input The input data to encrypt. This must be a readable * buffer of size \p ilen Bytes. It may be \c NULL if * `ilen == 0`. * \param output The output buffer. This must be a writable buffer * of length \c ctx->len Bytes. For example, \c 256 Bytes * for an 2048-bit RSA modulus. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, size_t ilen, const unsigned char *input, unsigned char *output ); /** * \brief This function performs a PKCS#1 v1.5 encryption operation * (RSAES-PKCS1-v1_5-ENCRYPT). * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library * are likely to remove the \p mode argument and have it * implicitly set to #MBEDTLS_RSA_PUBLIC. * * \param ctx The initialized RSA context to use. * \param f_rng The RNG function to use. It is needed for padding generation * if \p mode is #MBEDTLS_RSA_PUBLIC. If \p mode is * #MBEDTLS_RSA_PRIVATE (discouraged), it is used for * blinding and should be provided; see mbedtls_rsa_private(). * \param p_rng The RNG context to be passed to \p f_rng. This may * be \c NULL if \p f_rng is \c NULL or if \p f_rng * doesn't need a context argument. * \param mode The mode of operation. This must be either * #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE (deprecated). * \param ilen The length of the plaintext in Bytes. * \param input The input data to encrypt. This must be a readable * buffer of size \p ilen Bytes. It may be \c NULL if * `ilen == 0`. * \param output The output buffer. This must be a writable buffer * of length \c ctx->len Bytes. For example, \c 256 Bytes * for an 2048-bit RSA modulus. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, size_t ilen, const unsigned char *input, unsigned char *output ); /** * \brief This function performs a PKCS#1 v2.1 OAEP encryption * operation (RSAES-OAEP-ENCRYPT). * * \note The output buffer must be as large as the size * of ctx->N. For example, 128 Bytes if RSA-1024 is used. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library * are likely to remove the \p mode argument and have it * implicitly set to #MBEDTLS_RSA_PUBLIC. * * \param ctx The initnialized RSA context to use. * \param f_rng The RNG function to use. This is needed for padding * generation and must be provided. * \param p_rng The RNG context to be passed to \p f_rng. This may * be \c NULL if \p f_rng doesn't need a context argument. * \param mode The mode of operation. This must be either * #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE (deprecated). * \param label The buffer holding the custom label to use. * This must be a readable buffer of length \p label_len * Bytes. It may be \c NULL if \p label_len is \c 0. * \param label_len The length of the label in Bytes. * \param ilen The length of the plaintext buffer \p input in Bytes. * \param input The input data to encrypt. This must be a readable * buffer of size \p ilen Bytes. It may be \c NULL if * `ilen == 0`. * \param output The output buffer. This must be a writable buffer * of length \c ctx->len Bytes. For example, \c 256 Bytes * for an 2048-bit RSA modulus. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, const unsigned char *label, size_t label_len, size_t ilen, const unsigned char *input, unsigned char *output ); /** * \brief This function performs an RSA operation, then removes the * message padding. * * It is the generic wrapper for performing a PKCS#1 decryption * operation using the \p mode from the context. * * \note The output buffer length \c output_max_len should be * as large as the size \p ctx->len of \p ctx->N (for example, * 128 Bytes if RSA-1024 is used) to be able to hold an * arbitrary decrypted message. If it is not large enough to * hold the decryption of the particular ciphertext provided, * the function returns \c MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library * are likely to remove the \p mode argument and have it * implicitly set to #MBEDTLS_RSA_PRIVATE. * * \param ctx The initialized RSA context to use. * \param f_rng The RNG function. If \p mode is #MBEDTLS_RSA_PRIVATE, * this is used for blinding and should be provided; see * mbedtls_rsa_private() for more. If \p mode is * #MBEDTLS_RSA_PUBLIC, it is ignored. * \param p_rng The RNG context to be passed to \p f_rng. This may be * \c NULL if \p f_rng is \c NULL or doesn't need a context. * \param mode The mode of operation. This must be either * #MBEDTLS_RSA_PRIVATE or #MBEDTLS_RSA_PUBLIC (deprecated). * \param olen The address at which to store the length of * the plaintext. This must not be \c NULL. * \param input The ciphertext buffer. This must be a readable buffer * of length \c ctx->len Bytes. For example, \c 256 Bytes * for an 2048-bit RSA modulus. * \param output The buffer used to hold the plaintext. This must * be a writable buffer of length \p output_max_len Bytes. * \param output_max_len The length in Bytes of the output buffer \p output. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, size_t *olen, const unsigned char *input, unsigned char *output, size_t output_max_len ); /** * \brief This function performs a PKCS#1 v1.5 decryption * operation (RSAES-PKCS1-v1_5-DECRYPT). * * \note The output buffer length \c output_max_len should be * as large as the size \p ctx->len of \p ctx->N, for example, * 128 Bytes if RSA-1024 is used, to be able to hold an * arbitrary decrypted message. If it is not large enough to * hold the decryption of the particular ciphertext provided, * the function returns #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library * are likely to remove the \p mode argument and have it * implicitly set to #MBEDTLS_RSA_PRIVATE. * * \param ctx The initialized RSA context to use. * \param f_rng The RNG function. If \p mode is #MBEDTLS_RSA_PRIVATE, * this is used for blinding and should be provided; see * mbedtls_rsa_private() for more. If \p mode is * #MBEDTLS_RSA_PUBLIC, it is ignored. * \param p_rng The RNG context to be passed to \p f_rng. This may be * \c NULL if \p f_rng is \c NULL or doesn't need a context. * \param mode The mode of operation. This must be either * #MBEDTLS_RSA_PRIVATE or #MBEDTLS_RSA_PUBLIC (deprecated). * \param olen The address at which to store the length of * the plaintext. This must not be \c NULL. * \param input The ciphertext buffer. This must be a readable buffer * of length \c ctx->len Bytes. For example, \c 256 Bytes * for an 2048-bit RSA modulus. * \param output The buffer used to hold the plaintext. This must * be a writable buffer of length \p output_max_len Bytes. * \param output_max_len The length in Bytes of the output buffer \p output. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. * */ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, size_t *olen, const unsigned char *input, unsigned char *output, size_t output_max_len ); /** * \brief This function performs a PKCS#1 v2.1 OAEP decryption * operation (RSAES-OAEP-DECRYPT). * * \note The output buffer length \c output_max_len should be * as large as the size \p ctx->len of \p ctx->N, for * example, 128 Bytes if RSA-1024 is used, to be able to * hold an arbitrary decrypted message. If it is not * large enough to hold the decryption of the particular * ciphertext provided, the function returns * #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library * are likely to remove the \p mode argument and have it * implicitly set to #MBEDTLS_RSA_PRIVATE. * * \param ctx The initialized RSA context to use. * \param f_rng The RNG function. If \p mode is #MBEDTLS_RSA_PRIVATE, * this is used for blinding and should be provided; see * mbedtls_rsa_private() for more. If \p mode is * #MBEDTLS_RSA_PUBLIC, it is ignored. * \param p_rng The RNG context to be passed to \p f_rng. This may be * \c NULL if \p f_rng is \c NULL or doesn't need a context. * \param mode The mode of operation. This must be either * #MBEDTLS_RSA_PRIVATE or #MBEDTLS_RSA_PUBLIC (deprecated). * \param label The buffer holding the custom label to use. * This must be a readable buffer of length \p label_len * Bytes. It may be \c NULL if \p label_len is \c 0. * \param label_len The length of the label in Bytes. * \param olen The address at which to store the length of * the plaintext. This must not be \c NULL. * \param input The ciphertext buffer. This must be a readable buffer * of length \c ctx->len Bytes. For example, \c 256 Bytes * for an 2048-bit RSA modulus. * \param output The buffer used to hold the plaintext. This must * be a writable buffer of length \p output_max_len Bytes. * \param output_max_len The length in Bytes of the output buffer \p output. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, const unsigned char *label, size_t label_len, size_t *olen, const unsigned char *input, unsigned char *output, size_t output_max_len ); /** * \brief This function performs a private RSA operation to sign * a message digest using PKCS#1. * * It is the generic wrapper for performing a PKCS#1 * signature using the \p mode from the context. * * \note The \p sig buffer must be as large as the size * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. * * \note For PKCS#1 v2.1 encoding, see comments on * mbedtls_rsa_rsassa_pss_sign() for details on * \p md_alg and \p hash_id. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library * are likely to remove the \p mode argument and have it * implicitly set to #MBEDTLS_RSA_PRIVATE. * * \param ctx The initialized RSA context to use. * \param f_rng The RNG function to use. If the padding mode is PKCS#1 v2.1, * this must be provided. If the padding mode is PKCS#1 v1.5 and * \p mode is #MBEDTLS_RSA_PRIVATE, it is used for blinding * and should be provided; see mbedtls_rsa_private() for more * more. It is ignored otherwise. * \param p_rng The RNG context to be passed to \p f_rng. This may be \c NULL * if \p f_rng is \c NULL or doesn't need a context argument. * \param mode The mode of operation. This must be either * #MBEDTLS_RSA_PRIVATE or #MBEDTLS_RSA_PUBLIC (deprecated). * \param md_alg The message-digest algorithm used to hash the original data. * Use #MBEDTLS_MD_NONE for signing raw data. * \param hashlen The length of the message digest. * Ths is only used if \p md_alg is #MBEDTLS_MD_NONE. * \param hash The buffer holding the message digest or raw data. * If \p md_alg is #MBEDTLS_MD_NONE, this must be a readable * buffer of length \p hashlen Bytes. If \p md_alg is not * #MBEDTLS_MD_NONE, it must be a readable buffer of length * the size of the hash corresponding to \p md_alg. * \param sig The buffer to hold the signature. This must be a writable * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes * for an 2048-bit RSA modulus. A buffer length of * #MBEDTLS_MPI_MAX_SIZE is always safe. * * \return \c 0 if the signing operation was successful. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, unsigned char *sig ); /** * \brief This function performs a PKCS#1 v1.5 signature * operation (RSASSA-PKCS1-v1_5-SIGN). * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library * are likely to remove the \p mode argument and have it * implicitly set to #MBEDTLS_RSA_PRIVATE. * * \param ctx The initialized RSA context to use. * \param f_rng The RNG function. If \p mode is #MBEDTLS_RSA_PRIVATE, * this is used for blinding and should be provided; see * mbedtls_rsa_private() for more. If \p mode is * #MBEDTLS_RSA_PUBLIC, it is ignored. * \param p_rng The RNG context to be passed to \p f_rng. This may be \c NULL * if \p f_rng is \c NULL or doesn't need a context argument. * \param mode The mode of operation. This must be either * #MBEDTLS_RSA_PRIVATE or #MBEDTLS_RSA_PUBLIC (deprecated). * \param md_alg The message-digest algorithm used to hash the original data. * Use #MBEDTLS_MD_NONE for signing raw data. * \param hashlen The length of the message digest. * Ths is only used if \p md_alg is #MBEDTLS_MD_NONE. * \param hash The buffer holding the message digest or raw data. * If \p md_alg is #MBEDTLS_MD_NONE, this must be a readable * buffer of length \p hashlen Bytes. If \p md_alg is not * #MBEDTLS_MD_NONE, it must be a readable buffer of length * the size of the hash corresponding to \p md_alg. * \param sig The buffer to hold the signature. This must be a writable * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes * for an 2048-bit RSA modulus. A buffer length of * #MBEDTLS_MPI_MAX_SIZE is always safe. * * \return \c 0 if the signing operation was successful. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, unsigned char *sig ); /** * \brief This function performs a PKCS#1 v2.1 PSS signature * operation (RSASSA-PSS-SIGN). * * \note The \p hash_id in the RSA context is the one used for the * encoding. \p md_alg in the function call is the type of hash * that is encoded. According to <em>RFC-3447: Public-Key * Cryptography Standards (PKCS) #1 v2.1: RSA Cryptography * Specifications</em> it is advised to keep both hashes the * same. * * \note This function always uses the maximum possible salt size, * up to the length of the payload hash. This choice of salt * size complies with FIPS 186-4 §5.5 (e) and RFC 8017 (PKCS#1 * v2.2) §9.1.1 step 3. Furthermore this function enforces a * minimum salt size which is the hash size minus 2 bytes. If * this minimum size is too large given the key size (the salt * size, plus the hash size, plus 2 bytes must be no more than * the key size in bytes), this function returns * #MBEDTLS_ERR_RSA_BAD_INPUT_DATA. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library * are likely to remove the \p mode argument and have it * implicitly set to #MBEDTLS_RSA_PRIVATE. * * \param ctx The initialized RSA context to use. * \param f_rng The RNG function. It must not be \c NULL. * \param p_rng The RNG context to be passed to \p f_rng. This may be \c NULL * if \p f_rng doesn't need a context argument. * \param mode The mode of operation. This must be either * #MBEDTLS_RSA_PRIVATE or #MBEDTLS_RSA_PUBLIC (deprecated). * \param md_alg The message-digest algorithm used to hash the original data. * Use #MBEDTLS_MD_NONE for signing raw data. * \param hashlen The length of the message digest. * Ths is only used if \p md_alg is #MBEDTLS_MD_NONE. * \param hash The buffer holding the message digest or raw data. * If \p md_alg is #MBEDTLS_MD_NONE, this must be a readable * buffer of length \p hashlen Bytes. If \p md_alg is not * #MBEDTLS_MD_NONE, it must be a readable buffer of length * the size of the hash corresponding to \p md_alg. * \param sig The buffer to hold the signature. This must be a writable * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes * for an 2048-bit RSA modulus. A buffer length of * #MBEDTLS_MPI_MAX_SIZE is always safe. * * \return \c 0 if the signing operation was successful. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, unsigned char *sig ); /** * \brief This function performs a public RSA operation and checks * the message digest. * * This is the generic wrapper for performing a PKCS#1 * verification using the mode from the context. * * \note For PKCS#1 v2.1 encoding, see comments on * mbedtls_rsa_rsassa_pss_verify() about \p md_alg and * \p hash_id. * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library * are likely to remove the \p mode argument and have it * set to #MBEDTLS_RSA_PUBLIC. * * \param ctx The initialized RSA public key context to use. * \param f_rng The RNG function to use. If \p mode is #MBEDTLS_RSA_PRIVATE, * this is used for blinding and should be provided; see * mbedtls_rsa_private() for more. Otherwise, it is ignored. * \param p_rng The RNG context to be passed to \p f_rng. This may be * \c NULL if \p f_rng is \c NULL or doesn't need a context. * \param mode The mode of operation. This must be either * #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE (deprecated). * \param md_alg The message-digest algorithm used to hash the original data. * Use #MBEDTLS_MD_NONE for signing raw data. * \param hashlen The length of the message digest. * This is only used if \p md_alg is #MBEDTLS_MD_NONE. * \param hash The buffer holding the message digest or raw data. * If \p md_alg is #MBEDTLS_MD_NONE, this must be a readable * buffer of length \p hashlen Bytes. If \p md_alg is not * #MBEDTLS_MD_NONE, it must be a readable buffer of length * the size of the hash corresponding to \p md_alg. * \param sig The buffer holding the signature. This must be a readable * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes * for an 2048-bit RSA modulus. * * \return \c 0 if the verify operation was successful. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. */ int mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, const unsigned char *sig ); int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, const unsigned char *sig ); int mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, const unsigned char *sig ); int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, mbedtls_md_type_t mgf1_hash_id, int expected_salt_len, const unsigned char *sig ); int mbedtls_rsa_copy( mbedtls_rsa_context *dst, const mbedtls_rsa_context *src ); void mbedtls_rsa_free( mbedtls_rsa_context *ctx ); int mbedtls_rsa_self_test( int ); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_RSA_H_ */
51,919
1,009
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/debug.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/debug.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/platform.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ char mbedtls_debug_threshold; void mbedtls_debug_set_threshold( int threshold ) { mbedtls_debug_threshold = threshold; } #if defined(MBEDTLS_DEBUG_C) #define DEBUG_BUF_SIZE 512 /* * All calls to f_dbg must be made via this function */ static inline void debug_send_line( const mbedtls_ssl_context *ssl, int level, const char *file, int line, const char *str ) { ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, str ); } MBEDTLS_PRINTF_ATTRIBUTE(5, 6) void mbedtls_debug_print_msg( const mbedtls_ssl_context *ssl, int level, const char *file, int line, const char *format, ... ) { va_list argp; char str[DEBUG_BUF_SIZE]; int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( NULL == ssl || NULL == ssl->conf || NULL == ssl->conf->f_dbg || level > mbedtls_debug_threshold ) { return; } va_start( argp, format ); ret = mbedtls_vsnprintf( str, DEBUG_BUF_SIZE, format, argp ); va_end( argp ); if( ret >= 0 && ret < DEBUG_BUF_SIZE - 1 ) { str[ret] = '\0'; } debug_send_line( ssl, level, file, line, str ); } void mbedtls_debug_print_ret( const mbedtls_ssl_context *ssl, int level, const char *file, int line, const char *text, int ret ) { char str[DEBUG_BUF_SIZE]; if( NULL == ssl || NULL == ssl->conf || NULL == ssl->conf->f_dbg || level > mbedtls_debug_threshold ) { return; } /* * With non-blocking I/O and examples that just retry immediately, * the logs would be quickly flooded with WANT_READ, so ignore that. * Don't ignore WANT_WRITE however, since is is usually rare. */ if( ret == MBEDTLS_ERR_SSL_WANT_READ ) return; mbedtls_snprintf( str, sizeof( str ), "%s() returned %d (-0x%04x)", text, ret, (unsigned int) -ret ); debug_send_line( ssl, level, file, line, str ); } void mbedtls_debug_print_buf( const mbedtls_ssl_context *ssl, int level, const char *file, int line, const char *text, const unsigned char *buf, size_t len ) { char str[DEBUG_BUF_SIZE]; char txt[17]; size_t i, idx = 0; if( NULL == ssl || NULL == ssl->conf || NULL == ssl->conf->f_dbg || level > mbedtls_debug_threshold ) { return; } mbedtls_snprintf( str + idx, sizeof( str ) - idx, "dumping '%s' (%u bytes)", text, (unsigned int) len ); debug_send_line( ssl, level, file, line, str ); idx = 0; mbedtls_platform_zeroize( txt, sizeof( txt ) ); for( i = 0; i < len; i++ ) { if( i >= 4096 ) break; if( i % 16 == 0 ) { if( i > 0 ) { mbedtls_snprintf( str + idx, sizeof( str ) - idx, " %s", txt ); debug_send_line( ssl, level, file, line, str ); idx = 0; mbedtls_platform_zeroize( txt, sizeof( txt ) ); } idx += mbedtls_snprintf( str + idx, sizeof( str ) - idx, "%04x: ", (unsigned int) i ); } idx += mbedtls_snprintf( str + idx, sizeof( str ) - idx, " %02x", (unsigned int) buf[i] ); txt[i % 16] = ( buf[i] > 31 && buf[i] < 127 ) ? buf[i] : '.' ; } if( len > 0 ) { for( /* i = i */; i % 16 != 0; i++ ) idx += mbedtls_snprintf( str + idx, sizeof( str ) - idx, " " ); mbedtls_snprintf( str + idx, sizeof( str ) - idx, " %s", txt ); debug_send_line( ssl, level, file, line, str ); } } #if defined(MBEDTLS_ECP_C) void mbedtls_debug_print_ecp( const mbedtls_ssl_context *ssl, int level, const char *file, int line, const char *text, const mbedtls_ecp_point *X ) { char str[DEBUG_BUF_SIZE]; if( NULL == ssl || NULL == ssl->conf || NULL == ssl->conf->f_dbg || level > mbedtls_debug_threshold ) { return; } mbedtls_snprintf( str, sizeof( str ), "%s(X)", text ); mbedtls_debug_print_mpi( ssl, level, file, line, str, &X->X ); mbedtls_snprintf( str, sizeof( str ), "%s(Y)", text ); mbedtls_debug_print_mpi( ssl, level, file, line, str, &X->Y ); } #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_BIGNUM_C) void mbedtls_debug_print_mpi( const mbedtls_ssl_context *ssl, int level, const char *file, int line, const char *text, const mbedtls_mpi *X ) { char str[DEBUG_BUF_SIZE]; int j, k, zeros = 1; size_t i, n, idx = 0; if( NULL == ssl || NULL == ssl->conf || NULL == ssl->conf->f_dbg || NULL == X || level > mbedtls_debug_threshold ) { return; } /* TODO(jart): wut */ if (!X->n) { mbedtls_snprintf(str, sizeof(str), "value of '%s' has empty X->n", text); debug_send_line(ssl, level, file, line, str); return; } for( n = X->n - 1; n > 0; n-- ) if( X->p[n] != 0 ) break; for( j = ( sizeof(mbedtls_mpi_uint) << 3 ) - 1; j >= 0; j-- ) if( ( ( X->p[n] >> j ) & 1 ) != 0 ) break; mbedtls_snprintf( str + idx, sizeof( str ) - idx, "value of '%s' (%d bits) is:", text, (int) ( ( n * ( sizeof(mbedtls_mpi_uint) << 3 ) ) + j + 1 ) ); debug_send_line( ssl, level, file, line, str ); idx = 0; for( i = n + 1, j = 0; i > 0; i-- ) { if( zeros && X->p[i - 1] == 0 ) continue; for( k = sizeof( mbedtls_mpi_uint ) - 1; k >= 0; k-- ) { if( zeros && ( ( X->p[i - 1] >> ( k << 3 ) ) & 0xFF ) == 0 ) continue; else zeros = 0; if( j % 16 == 0 ) { if( j > 0 ) { debug_send_line( ssl, level, file, line, str ); idx = 0; } } idx += mbedtls_snprintf( str + idx, sizeof( str ) - idx, " %02x", (unsigned int) ( X->p[i - 1] >> ( k << 3 ) ) & 0xFF ); j++; } } if( zeros == 1 ) idx += mbedtls_snprintf( str + idx, sizeof( str ) - idx, " 00" ); debug_send_line( ssl, level, file, line, str ); } #endif /* MBEDTLS_BIGNUM_C */ #if defined(MBEDTLS_X509_CRT_PARSE_C) static void debug_print_pk( const mbedtls_ssl_context *ssl, int level, const char *file, int line, const char *text, const mbedtls_pk_context *pk ) { size_t i; mbedtls_pk_debug_item items[MBEDTLS_PK_DEBUG_MAX_ITEMS]; char name[16]; mbedtls_platform_zeroize( items, sizeof( items ) ); if( mbedtls_pk_debug( pk, items ) != 0 ) { debug_send_line( ssl, level, file, line, "invalid PK context" ); return; } for( i = 0; i < MBEDTLS_PK_DEBUG_MAX_ITEMS; i++ ) { if( items[i].type == MBEDTLS_PK_DEBUG_NONE ) return; mbedtls_snprintf( name, sizeof( name ), "%s%s", text, items[i].name ); name[sizeof( name ) - 1] = '\0'; if( items[i].type == MBEDTLS_PK_DEBUG_MPI ) mbedtls_debug_print_mpi( ssl, level, file, line, name, items[i].value ); else #if defined(MBEDTLS_ECP_C) if( items[i].type == MBEDTLS_PK_DEBUG_ECP ) mbedtls_debug_print_ecp( ssl, level, file, line, name, items[i].value ); else #endif debug_send_line( ssl, level, file, line, "should not happen" ); } } static void debug_print_line_by_line( const mbedtls_ssl_context *ssl, int level, const char *file, int line, const char *text ) { char str[DEBUG_BUF_SIZE]; const char *start, *cur; start = text; for( cur = text; *cur != '\0'; cur++ ) { if( *cur == '\n' ) { size_t len = cur - start; if( len > DEBUG_BUF_SIZE - 1 ) len = DEBUG_BUF_SIZE - 1; memcpy( str, start, len ); str[len] = '\0'; debug_send_line( ssl, level, file, line, str ); start = cur + 1; } } } void mbedtls_debug_print_crt( const mbedtls_ssl_context *ssl, int level, const char *file, int line, const char *text, const mbedtls_x509_crt *crt ) { char str[DEBUG_BUF_SIZE]; int i = 0; if( NULL == ssl || NULL == ssl->conf || NULL == ssl->conf->f_dbg || NULL == crt || level > mbedtls_debug_threshold ) { return; } while( crt != NULL ) { char buf[1024]; mbedtls_snprintf( str, sizeof( str ), "%s #%d:", text, ++i ); debug_send_line( ssl, level, file, line, str ); mbedtls_x509_crt_info( buf, sizeof( buf ) - 1, "", crt ); debug_print_line_by_line( ssl, level, file, line, buf ); debug_print_pk( ssl, level, file, line, "crt->", &crt->pk ); crt = crt->next; } } #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_ECDH_C) static void mbedtls_debug_printf_ecdh_internal( const mbedtls_ssl_context *ssl, int level, const char *file, int line, const mbedtls_ecdh_context *ecdh, mbedtls_debug_ecdh_attr attr ) { #if defined(MBEDTLS_ECDH_LEGACY_CONTEXT) const mbedtls_ecdh_context* ctx = ecdh; #else const mbedtls_ecdh_context_mbed* ctx = &ecdh->ctx.mbed_ecdh; #endif switch( attr ) { case MBEDTLS_DEBUG_ECDH_Q: mbedtls_debug_print_ecp( ssl, level, file, line, "ECDH: Q", &ctx->Q ); break; case MBEDTLS_DEBUG_ECDH_QP: mbedtls_debug_print_ecp( ssl, level, file, line, "ECDH: Qp", &ctx->Qp ); break; case MBEDTLS_DEBUG_ECDH_Z: mbedtls_debug_print_mpi( ssl, level, file, line, "ECDH: z", &ctx->z ); break; default: break; } } void mbedtls_debug_printf_ecdh( const mbedtls_ssl_context *ssl, int level, const char *file, int line, const mbedtls_ecdh_context *ecdh, mbedtls_debug_ecdh_attr attr ) { #if defined(MBEDTLS_ECDH_LEGACY_CONTEXT) mbedtls_debug_printf_ecdh_internal( ssl, level, file, line, ecdh, attr ); #else switch( ecdh->var ) { default: mbedtls_debug_printf_ecdh_internal( ssl, level, file, line, ecdh, attr ); } #endif } #endif /* MBEDTLS_ECDH_C */ #endif /* MBEDTLS_DEBUG_C */
13,405
414
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/debug.h
#ifndef MBEDTLS_DEBUG_H #define MBEDTLS_DEBUG_H #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/ecp.h" #include "third_party/mbedtls/ssl.h" COSMOPOLITAN_C_START_ #ifdef MBEDTLS_DEBUG_C #define MBEDTLS_DEBUG_STRIP_PARENS(...) __VA_ARGS__ #define MBEDTLS_SSL_DEBUG_MSG(level, args) \ do { \ if (level <= mbedtls_debug_threshold) { \ mbedtls_debug_print_msg(ssl, level, __FILE__, __LINE__, \ MBEDTLS_DEBUG_STRIP_PARENS args); \ } \ } while (0) #define MBEDTLS_SSL_DEBUG_RET(level, text, ret) \ do { \ if (level <= mbedtls_debug_threshold) { \ mbedtls_debug_print_ret(ssl, level, __FILE__, __LINE__, text, ret); \ } \ } while (0) #define MBEDTLS_SSL_DEBUG_BUF(level, text, buf, len) \ do { \ if (level <= mbedtls_debug_threshold) { \ mbedtls_debug_print_buf(ssl, level, __FILE__, __LINE__, text, buf, len); \ } \ } while (0) #if defined(MBEDTLS_BIGNUM_C) #define MBEDTLS_SSL_DEBUG_MPI(level, text, X) \ do { \ if (level <= mbedtls_debug_threshold) { \ mbedtls_debug_print_mpi(ssl, level, __FILE__, __LINE__, text, X); \ } \ } while (0) #endif #if defined(MBEDTLS_ECP_C) #define MBEDTLS_SSL_DEBUG_ECP(level, text, X) \ do { \ if (level <= mbedtls_debug_threshold) { \ mbedtls_debug_print_ecp(ssl, level, __FILE__, __LINE__, text, X); \ } \ } while (0) #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) #define MBEDTLS_SSL_DEBUG_CRT(level, text, crt) \ do { \ if (level <= mbedtls_debug_threshold) { \ mbedtls_debug_print_crt(ssl, level, __FILE__, __LINE__, text, crt); \ } \ } while (0) #endif #if defined(MBEDTLS_ECDH_C) #define MBEDTLS_SSL_DEBUG_ECDH(level, ecdh, attr) \ do { \ if (level <= mbedtls_debug_threshold) { \ mbedtls_debug_printf_ecdh(ssl, level, __FILE__, __LINE__, ecdh, attr); \ } \ } while (0) #endif #else /* MBEDTLS_DEBUG_C */ #define MBEDTLS_SSL_DEBUG_MSG(level, args) ((void)0) #define MBEDTLS_SSL_DEBUG_RET(level, text, ret) ((void)0) #define MBEDTLS_SSL_DEBUG_BUF(level, text, buf, len) ((void)0) #define MBEDTLS_SSL_DEBUG_MPI(level, text, X) ((void)0) #define MBEDTLS_SSL_DEBUG_ECP(level, text, X) ((void)0) #define MBEDTLS_SSL_DEBUG_CRT(level, text, crt) ((void)0) #define MBEDTLS_SSL_DEBUG_ECDH(level, ecdh, attr) ((void)0) #endif /* MBEDTLS_DEBUG_C */ /** * \def MBEDTLS_PRINTF_ATTRIBUTE * * Mark a function as having printf attributes, and thus enable checking * via -wFormat and other flags. This does nothing on builds with compilers * that do not support the format attribute * * Module: library/debug.c * Caller: * * This module provides debugging functions. */ #if defined(__has_attribute) #if __has_attribute(format) #define MBEDTLS_PRINTF_ATTRIBUTE(string_index, first_to_check) \ __attribute__((format(printf, string_index, first_to_check))) #else /* __has_attribute(format) */ #define MBEDTLS_PRINTF_ATTRIBUTE(string_index, first_to_check) #endif /* __has_attribute(format) */ #else /* defined(__has_attribute) */ #define MBEDTLS_PRINTF_ATTRIBUTE(string_index, first_to_check) #endif /** * \def MBEDTLS_PRINTF_SIZET * * MBEDTLS_PRINTF_xxx: Due to issues with older window compilers * and MinGW we need to define the printf specifier for size_t * and long long per platform. * * Module: library/debug.c * Caller: * * This module provides debugging functions. */ #if defined(__MINGW32__) || (defined(_MSC_VER) && _MSC_VER < 1800) #define MBEDTLS_PRINTF_SIZET PRIuPTR #define MBEDTLS_PRINTF_LONGLONG "I64d" #else /* defined(__MINGW32__) || (defined(_MSC_VER) && _MSC_VER < 1800) */ #define MBEDTLS_PRINTF_SIZET "zu" #define MBEDTLS_PRINTF_LONGLONG "lld" #endif /* defined(__MINGW32__) || (defined(_MSC_VER) && _MSC_VER < 1800) */ extern char mbedtls_debug_threshold; /** * \brief Set the threshold error level to handle globally all debug output. * Debug messages that have a level over the threshold value are * discarded. * (Default value: 0 = No debug ) * * \param threshold theshold level of messages to filter on. Messages at a * higher level will be discarded. * - Debug levels * - 0 No debug * - 1 Error * - 2 State change * - 3 Informational * - 4 Verbose */ void mbedtls_debug_set_threshold(int threshold); /** * \brief Print a message to the debug output. This function is always used * through the MBEDTLS_SSL_DEBUG_MSG() macro, which supplies the ssl * context, file and line number parameters. * * \param ssl SSL context * \param level error level of the debug message * \param file file the message has occurred in * \param line line number the message has occurred at * \param format format specifier, in printf format * \param ... variables used by the format specifier * * \attention This function is intended for INTERNAL usage within the * library only. */ void mbedtls_debug_print_msg(const mbedtls_ssl_context *ssl, int level, const char *file, int line, const char *format, ...) MBEDTLS_PRINTF_ATTRIBUTE(5, 6); /** * \brief Print the return value of a function to the debug output. This * function is always used through the MBEDTLS_SSL_DEBUG_RET() macro, * which supplies the ssl context, file and line number parameters. * * \param ssl SSL context * \param level error level of the debug message * \param file file the error has occurred in * \param line line number the error has occurred in * \param text the name of the function that returned the error * \param ret the return code value * * \attention This function is intended for INTERNAL usage within the * library only. */ void mbedtls_debug_print_ret(const mbedtls_ssl_context *ssl, int level, const char *file, int line, const char *text, int ret); /** * \brief Output a buffer of size len bytes to the debug output. This function * is always used through the MBEDTLS_SSL_DEBUG_BUF() macro, * which supplies the ssl context, file and line number parameters. * * \param ssl SSL context * \param level error level of the debug message * \param file file the error has occurred in * \param line line number the error has occurred in * \param text a name or label for the buffer being dumped. Normally the * variable or buffer name * \param buf the buffer to be outputted * \param len length of the buffer * * \attention This function is intended for INTERNAL usage within the * library only. */ void mbedtls_debug_print_buf(const mbedtls_ssl_context *ssl, int level, const char *file, int line, const char *text, const unsigned char *buf, size_t len); #if defined(MBEDTLS_BIGNUM_C) /** * \brief Print a MPI variable to the debug output. This function is always * used through the MBEDTLS_SSL_DEBUG_MPI() macro, which supplies the * ssl context, file and line number parameters. * * \param ssl SSL context * \param level error level of the debug message * \param file file the error has occurred in * \param line line number the error has occurred in * \param text a name or label for the MPI being output. Normally the * variable name * \param X the MPI variable * * \attention This function is intended for INTERNAL usage within the * library only. */ void mbedtls_debug_print_mpi(const mbedtls_ssl_context *ssl, int level, const char *file, int line, const char *text, const mbedtls_mpi *X); #endif #if defined(MBEDTLS_ECP_C) /** * \brief Print an ECP point to the debug output. This function is always * used through the MBEDTLS_SSL_DEBUG_ECP() macro, which supplies the * ssl context, file and line number parameters. * * \param ssl SSL context * \param level error level of the debug message * \param file file the error has occurred in * \param line line number the error has occurred in * \param text a name or label for the ECP point being output. Normally the * variable name * \param X the ECP point * * \attention This function is intended for INTERNAL usage within the * library only. */ void mbedtls_debug_print_ecp(const mbedtls_ssl_context *ssl, int level, const char *file, int line, const char *text, const mbedtls_ecp_point *X); #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) /** * \brief Print a X.509 certificate structure to the debug output. This * function is always used through the MBEDTLS_SSL_DEBUG_CRT() macro, * which supplies the ssl context, file and line number parameters. * * \param ssl SSL context * \param level error level of the debug message * \param file file the error has occurred in * \param line line number the error has occurred in * \param text a name or label for the certificate being output * \param crt X.509 certificate structure * * \attention This function is intended for INTERNAL usage within the * library only. */ void mbedtls_debug_print_crt(const mbedtls_ssl_context *ssl, int level, const char *file, int line, const char *text, const mbedtls_x509_crt *crt); #endif #if defined(MBEDTLS_ECDH_C) typedef enum { MBEDTLS_DEBUG_ECDH_Q, MBEDTLS_DEBUG_ECDH_QP, MBEDTLS_DEBUG_ECDH_Z, } mbedtls_debug_ecdh_attr; /** * \brief Print a field of the ECDH structure in the SSL context to the debug * output. This function is always used through the * MBEDTLS_SSL_DEBUG_ECDH() macro, which supplies the ssl context, file * and line number parameters. * * \param ssl SSL context * \param level error level of the debug message * \param file file the error has occurred in * \param line line number the error has occurred in * \param ecdh the ECDH context * \param attr the identifier of the attribute being output * * \attention This function is intended for INTERNAL usage within the * library only. */ void mbedtls_debug_printf_ecdh(const mbedtls_ssl_context *ssl, int level, const char *file, int line, const mbedtls_ecdh_context *ecdh, mbedtls_debug_ecdh_attr attr); #endif COSMOPOLITAN_C_END_ #endif /* MBEDTLS_DEBUG_H */
12,438
299
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/bignum.h
#ifndef MBEDTLS_BIGNUM_H_ #define MBEDTLS_BIGNUM_H_ #include "libc/stdio/stdio.h" #include "third_party/mbedtls/bignum_internal.h" #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/platform.h" COSMOPOLITAN_C_START_ /* clang-format off */ #define MBEDTLS_ERR_MPI_FILE_IO_ERROR -0x0002 /*< An error occurred while reading from or writing to a file. */ #define MBEDTLS_ERR_MPI_BAD_INPUT_DATA -0x0004 /*< Bad input parameters to function. */ #define MBEDTLS_ERR_MPI_INVALID_CHARACTER -0x0006 /*< There is an invalid character in the digit string. */ #define MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL -0x0008 /*< The buffer is too small to write to. */ #define MBEDTLS_ERR_MPI_NEGATIVE_VALUE -0x000A /*< The input arguments are negative or result in illegal output. */ #define MBEDTLS_ERR_MPI_DIVISION_BY_ZERO -0x000C /*< The input argument for division is zero, which is not allowed. */ #define MBEDTLS_ERR_MPI_NOT_ACCEPTABLE -0x000E /*< The input arguments are not acceptable. */ #define MBEDTLS_ERR_MPI_ALLOC_FAILED -0x0010 /*< Memory allocation failed. */ #define MBEDTLS_MPI_CHK(f) \ do \ { \ if( ( ret = (f) ) ) \ goto cleanup; \ } while( 0 ) /* * Maximum size MPIs are allowed to grow to in number of limbs. */ #define MBEDTLS_MPI_MAX_LIMBS 10000 #if !defined(MBEDTLS_MPI_WINDOW_SIZE) /* * Maximum window size used for modular exponentiation. Default: 6 * Minimum value: 1. Maximum value: 6. * * Result is an array of ( 2 ** MBEDTLS_MPI_WINDOW_SIZE ) MPIs used * for the sliding window calculation. (So 64 by default) * * Reduction in size, reduces speed. */ #define MBEDTLS_MPI_WINDOW_SIZE 6 /*< Maximum window size used. */ #endif /* !MBEDTLS_MPI_WINDOW_SIZE */ #if !defined(MBEDTLS_MPI_MAX_SIZE) /* * Maximum size of MPIs allowed in bits and bytes for user-MPIs. * ( Default: 512 bytes => 4096 bits, Maximum tested: 2048 bytes => 16384 bits ) * * Note: Calculations can temporarily result in larger MPIs. So the number * of limbs required (MBEDTLS_MPI_MAX_LIMBS) is higher. */ #define MBEDTLS_MPI_MAX_SIZE 1024 /*< Maximum number of bytes for usable MPIs. */ #endif /* !MBEDTLS_MPI_MAX_SIZE */ #define MBEDTLS_MPI_MAX_BITS ( 8 * MBEDTLS_MPI_MAX_SIZE ) /*< Maximum number of bits for usable MPIs. */ /* * When reading from files with mbedtls_mpi_read_file() and writing to files with * mbedtls_mpi_write_file() the buffer should have space * for a (short) label, the MPI (in the provided radix), the newline * characters and the '\0'. * * By default we assume at least a 10 char label, a minimum radix of 10 * (decimal) and a maximum of 4096 bit numbers (1234 decimal chars). * Autosized at compile time for at least a 10 char label, a minimum radix * of 10 (decimal) for a number of MBEDTLS_MPI_MAX_BITS size. * * This used to be statically sized to 1250 for a maximum of 4096 bit * numbers (1234 decimal chars). * * Calculate using the formula: * MBEDTLS_MPI_RW_BUFFER_SIZE = ceil(MBEDTLS_MPI_MAX_BITS / ln(10) * ln(2)) + * LabelSize + 6 */ #define MBEDTLS_MPI_MAX_BITS_SCALE100 ( 100 * MBEDTLS_MPI_MAX_BITS ) #define MBEDTLS_LN_2_DIV_LN_10_SCALE100 332 #define MBEDTLS_MPI_RW_BUFFER_SIZE ( ((MBEDTLS_MPI_MAX_BITS_SCALE100 + MBEDTLS_LN_2_DIV_LN_10_SCALE100 - 1) / MBEDTLS_LN_2_DIV_LN_10_SCALE100) + 10 + 6 ) typedef int64_t mbedtls_mpi_sint; typedef uint64_t mbedtls_mpi_uint; /** * \brief MPI structure */ typedef struct mbedtls_mpi { int s; /*!< Sign: -1 if the mpi is negative, 1 otherwise */ unsigned n; /*!< total # of limbs */ mbedtls_mpi_uint *p; /*!< pointer to limbs */ } mbedtls_mpi forcealign(16); /** * \brief Flags for mbedtls_mpi_gen_prime() * * Each of these flags is a constraint on the result X returned by * mbedtls_mpi_gen_prime(). */ typedef enum { MBEDTLS_MPI_GEN_PRIME_FLAG_DH = 0x0001, /*< (X-1)/2 is prime too */ MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR = 0x0002, /*< lower error rate from 2<sup>-80</sup> to 2<sup>-128</sup> */ } mbedtls_mpi_gen_prime_flag_t; int mbedtls_mpi_add_abs( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * ); int mbedtls_mpi_add_int( mbedtls_mpi *, const mbedtls_mpi *, mbedtls_mpi_sint ); int mbedtls_mpi_add_mpi( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * ); int mbedtls_mpi_cmp_abs( const mbedtls_mpi *, const mbedtls_mpi * ); int mbedtls_mpi_cmp_int( const mbedtls_mpi *, mbedtls_mpi_sint ); int mbedtls_mpi_cmp_mpi( const mbedtls_mpi *, const mbedtls_mpi * ); int mbedtls_mpi_copy( mbedtls_mpi *, const mbedtls_mpi * ); int mbedtls_mpi_div_int( mbedtls_mpi *, mbedtls_mpi *, const mbedtls_mpi *, mbedtls_mpi_sint ); int mbedtls_mpi_div_mpi( mbedtls_mpi *, mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * ); int mbedtls_mpi_exp_mod( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi *, mbedtls_mpi * ); int mbedtls_mpi_fill_random( mbedtls_mpi *, size_t, int (*)(void *, unsigned char *, size_t), void * ); int mbedtls_mpi_gcd( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * ); int mbedtls_mpi_gen_prime( mbedtls_mpi *, size_t, int, int (*)(void *, unsigned char *, size_t), void * ); int mbedtls_mpi_get_bit( const mbedtls_mpi *, size_t ); int mbedtls_mpi_grow( mbedtls_mpi *, size_t ); int mbedtls_mpi_inv_mod( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * ); int mbedtls_mpi_is_prime_ext( const mbedtls_mpi *, int, int (*)(void *, unsigned char *, size_t), void * ); int mbedtls_mpi_lset( mbedtls_mpi *, mbedtls_mpi_sint ); int mbedtls_mpi_lt_mpi_ct( const mbedtls_mpi *, const mbedtls_mpi *, unsigned * ); int mbedtls_mpi_mod_int( mbedtls_mpi_uint *, const mbedtls_mpi *, mbedtls_mpi_sint ); int mbedtls_mpi_mod_mpi( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * ); int mbedtls_mpi_mul_int( mbedtls_mpi *, const mbedtls_mpi *, mbedtls_mpi_uint ); int mbedtls_mpi_mul_mpi( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * ); int mbedtls_mpi_read_binary( mbedtls_mpi *, const unsigned char *, size_t ); int mbedtls_mpi_read_binary_le( mbedtls_mpi *, const unsigned char *, size_t ); int mbedtls_mpi_read_file( mbedtls_mpi *, int, FILE * ); int mbedtls_mpi_read_string( mbedtls_mpi *, int, const char * ); int mbedtls_mpi_resize( mbedtls_mpi *, size_t ); int mbedtls_mpi_safe_cond_assign( mbedtls_mpi *, const mbedtls_mpi *, unsigned char ); int mbedtls_mpi_safe_cond_swap( mbedtls_mpi *, mbedtls_mpi *, unsigned char ); int mbedtls_mpi_self_test( int ); int mbedtls_mpi_set_bit( mbedtls_mpi *, size_t, unsigned char ); int mbedtls_mpi_shift_l( mbedtls_mpi *, size_t ); int mbedtls_mpi_shift_r( mbedtls_mpi *, size_t ); int mbedtls_mpi_shrink( mbedtls_mpi *, size_t ); int mbedtls_mpi_sub_abs( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * ); int mbedtls_mpi_sub_int( mbedtls_mpi *, const mbedtls_mpi *, mbedtls_mpi_sint ); int mbedtls_mpi_sub_mpi( mbedtls_mpi *, const mbedtls_mpi *, const mbedtls_mpi * ); int mbedtls_mpi_write_binary( const mbedtls_mpi *, unsigned char *, size_t ); int mbedtls_mpi_write_binary_le( const mbedtls_mpi *, unsigned char *, size_t ); int mbedtls_mpi_write_file( const char *, const mbedtls_mpi *, int, FILE * ); int mbedtls_mpi_write_string( const mbedtls_mpi *, int, char *, size_t, size_t * ); size_t mbedtls_mpi_bitlen( const mbedtls_mpi * ); size_t mbedtls_mpi_lsb( const mbedtls_mpi * ); size_t mbedtls_mpi_size( const mbedtls_mpi * ); void mbedtls_mpi_free( mbedtls_mpi * ); void mbedtls_mpi_swap( mbedtls_mpi *, mbedtls_mpi * ); /** * \brief Initialize an MPI context. * * This makes the MPI ready to be set or freed, * but does not define a value for the MPI. * * \param X The MPI context to initialize. This must not be \c NULL. */ forceinline void mbedtls_mpi_init(mbedtls_mpi *X) { MBEDTLS_INTERNAL_VALIDATE(X); typedef int mbedtls_mpi_lol __attribute__((__vector_size__(16), __aligned__(16))); *(mbedtls_mpi_lol *)X = (mbedtls_mpi_lol){1}; } forceinline size_t mbedtls_mpi_limbs(const mbedtls_mpi *X) { size_t i; for (i = X->n; i; i--) { if (X->p[i - 1]) { break; } } return i; } static inline bool mbedtls_mpi_is_zero(const mbedtls_mpi *X) { if (X->n && *X->p) return false; if (!mbedtls_mpi_limbs(X)) return true; return false; } static inline bool mbedtls_mpi_is_one(const mbedtls_mpi *X) { if (!X->n || *X->p != 1 || X->s != 1) return false; return mbedtls_mpi_limbs(X) == 1; } COSMOPOLITAN_C_END_ #endif /* MBEDTLS_BIGNUM_H_ */
8,969
192
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/common.h
#ifndef MBEDTLS_LIBRARY_COMMON_H #define MBEDTLS_LIBRARY_COMMON_H #include "third_party/mbedtls/config.h" #ifdef MBEDTLS_TEST_HOOKS #define MBEDTLS_STATIC_TESTABLE #else #define MBEDTLS_STATIC_TESTABLE static #endif #endif /* MBEDTLS_LIBRARY_COMMON_H */
256
12
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/ccm.h
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_CCM_H_ #define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_CCM_H_ #include "third_party/mbedtls/cipher.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define MBEDTLS_ERR_CCM_BAD_INPUT \ -0x000D /*< Bad input parameters to the function. */ #define MBEDTLS_ERR_CCM_AUTH_FAILED \ -0x000F /*< Authenticated decryption failed. */ /* MBEDTLS_ERR_CCM_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_CCM_HW_ACCEL_FAILED \ -0x0011 /*< CCM hardware accelerator failed. */ /** * \brief The CCM context-type definition. The CCM context is passed * to the APIs called. */ typedef struct mbedtls_ccm_context { mbedtls_cipher_context_t cipher_ctx; /*!< The cipher context used. */ } mbedtls_ccm_context; void mbedtls_ccm_init(mbedtls_ccm_context *); int mbedtls_ccm_setkey(mbedtls_ccm_context *, mbedtls_cipher_id_t, const unsigned char *, unsigned int); void mbedtls_ccm_free(mbedtls_ccm_context *); int mbedtls_ccm_encrypt_and_tag(mbedtls_ccm_context *, size_t, const unsigned char *, size_t, const unsigned char *, size_t, const unsigned char *, unsigned char *, unsigned char *, size_t); int mbedtls_ccm_star_encrypt_and_tag(mbedtls_ccm_context *, size_t, const unsigned char *, size_t, const unsigned char *, size_t, const unsigned char *, unsigned char *, unsigned char *, size_t); int mbedtls_ccm_auth_decrypt(mbedtls_ccm_context *, size_t, const unsigned char *, size_t, const unsigned char *, size_t, const unsigned char *, unsigned char *, const unsigned char *, size_t); int mbedtls_ccm_star_auth_decrypt(mbedtls_ccm_context *, size_t, const unsigned char *, size_t, const unsigned char *, size_t, const unsigned char *, unsigned char *, const unsigned char *, size_t); int mbedtls_ccm_self_test(int); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_CCM_H_ */
2,474
54
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/select.h
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_SELECT_H_ #define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_SELECT_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ static inline uint64_t Select(uint64_t a, uint64_t b, uint64_t mask) { return (CONCEAL("r", mask) & a) | (CONCEAL("r", ~mask) & b); } COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_SELECT_H_ */
423
13
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/ecp_curves.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/ecp.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/platform.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /* * Elliptic curves over GF(p): curve-specific data and functions * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(MBEDTLS_ECP_C) #if !defined(MBEDTLS_ECP_ALT) #define ECP_VALIDATE_RET( cond ) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_ECP_BAD_INPUT_DATA ) #define ECP_VALIDATE( cond ) \ MBEDTLS_INTERNAL_VALIDATE( cond ) /* * Conversion macros for embedded constants: * build lists of mbedtls_mpi_uint's from lists of unsigned char's grouped by 8, 4 or 2 */ #if defined(MBEDTLS_HAVE_INT32) #define BYTES_TO_T_UINT_4( a, b, c, d ) \ ( (mbedtls_mpi_uint) (a) << 0 ) | \ ( (mbedtls_mpi_uint) (b) << 8 ) | \ ( (mbedtls_mpi_uint) (c) << 16 ) | \ ( (mbedtls_mpi_uint) (d) << 24 ) #define BYTES_TO_T_UINT_2( a, b ) \ BYTES_TO_T_UINT_4( a, b, 0, 0 ) #define BYTES_TO_T_UINT_8( a, b, c, d, e, f, g, h ) \ BYTES_TO_T_UINT_4( a, b, c, d ), \ BYTES_TO_T_UINT_4( e, f, g, h ) #else /* 64-bits */ #define BYTES_TO_T_UINT_8( a, b, c, d, e, f, g, h ) \ ( (mbedtls_mpi_uint) (a) << 0 ) | \ ( (mbedtls_mpi_uint) (b) << 8 ) | \ ( (mbedtls_mpi_uint) (c) << 16 ) | \ ( (mbedtls_mpi_uint) (d) << 24 ) | \ ( (mbedtls_mpi_uint) (e) << 32 ) | \ ( (mbedtls_mpi_uint) (f) << 40 ) | \ ( (mbedtls_mpi_uint) (g) << 48 ) | \ ( (mbedtls_mpi_uint) (h) << 56 ) #define BYTES_TO_T_UINT_4( a, b, c, d ) \ BYTES_TO_T_UINT_8( a, b, c, d, 0, 0, 0, 0 ) #define BYTES_TO_T_UINT_2( a, b ) \ BYTES_TO_T_UINT_8( a, b, 0, 0, 0, 0, 0, 0 ) #endif /* bits in mbedtls_mpi_uint */ /* * Note: the constants are in little-endian order * to be directly usable in MPIs */ /* * Domain parameters for secp192r1 */ #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) static const mbedtls_mpi_uint secp192r1_p[] = { BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), }; static const mbedtls_mpi_uint secp192r1_b[] = { BYTES_TO_T_UINT_8( 0xB1, 0xB9, 0x46, 0xC1, 0xEC, 0xDE, 0xB8, 0xFE ), BYTES_TO_T_UINT_8( 0x49, 0x30, 0x24, 0x72, 0xAB, 0xE9, 0xA7, 0x0F ), BYTES_TO_T_UINT_8( 0xE7, 0x80, 0x9C, 0xE5, 0x19, 0x05, 0x21, 0x64 ), }; static const mbedtls_mpi_uint secp192r1_gx[] = { BYTES_TO_T_UINT_8( 0x12, 0x10, 0xFF, 0x82, 0xFD, 0x0A, 0xFF, 0xF4 ), BYTES_TO_T_UINT_8( 0x00, 0x88, 0xA1, 0x43, 0xEB, 0x20, 0xBF, 0x7C ), BYTES_TO_T_UINT_8( 0xF6, 0x90, 0x30, 0xB0, 0x0E, 0xA8, 0x8D, 0x18 ), }; static const mbedtls_mpi_uint secp192r1_gy[] = { BYTES_TO_T_UINT_8( 0x11, 0x48, 0x79, 0x1E, 0xA1, 0x77, 0xF9, 0x73 ), BYTES_TO_T_UINT_8( 0xD5, 0xCD, 0x24, 0x6B, 0xED, 0x11, 0x10, 0x63 ), BYTES_TO_T_UINT_8( 0x78, 0xDA, 0xC8, 0xFF, 0x95, 0x2B, 0x19, 0x07 ), }; static const mbedtls_mpi_uint secp192r1_n[] = { BYTES_TO_T_UINT_8( 0x31, 0x28, 0xD2, 0xB4, 0xB1, 0xC9, 0x6B, 0x14 ), BYTES_TO_T_UINT_8( 0x36, 0xF8, 0xDE, 0x99, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), }; #endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */ /* * Domain parameters for secp224r1 */ #if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) static const mbedtls_mpi_uint secp224r1_p[] = { BYTES_TO_T_UINT_8( 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ), BYTES_TO_T_UINT_8( 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00 ), }; static const mbedtls_mpi_uint secp224r1_b[] = { BYTES_TO_T_UINT_8( 0xB4, 0xFF, 0x55, 0x23, 0x43, 0x39, 0x0B, 0x27 ), BYTES_TO_T_UINT_8( 0xBA, 0xD8, 0xBF, 0xD7, 0xB7, 0xB0, 0x44, 0x50 ), BYTES_TO_T_UINT_8( 0x56, 0x32, 0x41, 0xF5, 0xAB, 0xB3, 0x04, 0x0C ), BYTES_TO_T_UINT_4( 0x85, 0x0A, 0x05, 0xB4 ), }; static const mbedtls_mpi_uint secp224r1_gx[] = { BYTES_TO_T_UINT_8( 0x21, 0x1D, 0x5C, 0x11, 0xD6, 0x80, 0x32, 0x34 ), BYTES_TO_T_UINT_8( 0x22, 0x11, 0xC2, 0x56, 0xD3, 0xC1, 0x03, 0x4A ), BYTES_TO_T_UINT_8( 0xB9, 0x90, 0x13, 0x32, 0x7F, 0xBF, 0xB4, 0x6B ), BYTES_TO_T_UINT_4( 0xBD, 0x0C, 0x0E, 0xB7 ), }; static const mbedtls_mpi_uint secp224r1_gy[] = { BYTES_TO_T_UINT_8( 0x34, 0x7E, 0x00, 0x85, 0x99, 0x81, 0xD5, 0x44 ), BYTES_TO_T_UINT_8( 0x64, 0x47, 0x07, 0x5A, 0xA0, 0x75, 0x43, 0xCD ), BYTES_TO_T_UINT_8( 0xE6, 0xDF, 0x22, 0x4C, 0xFB, 0x23, 0xF7, 0xB5 ), BYTES_TO_T_UINT_4( 0x88, 0x63, 0x37, 0xBD ), }; static const mbedtls_mpi_uint secp224r1_n[] = { BYTES_TO_T_UINT_8( 0x3D, 0x2A, 0x5C, 0x5C, 0x45, 0x29, 0xDD, 0x13 ), BYTES_TO_T_UINT_8( 0x3E, 0xF0, 0xB8, 0xE0, 0xA2, 0x16, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_4( 0xFF, 0xFF, 0xFF, 0xFF ), }; #endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */ /* * Domain parameters for secp256r1 */ #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) static const mbedtls_mpi_uint secp256r1_p[] = { BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00 ), BYTES_TO_T_UINT_8( 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ), BYTES_TO_T_UINT_8( 0x01, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF ), }; static const mbedtls_mpi_uint secp256r1_b[] = { BYTES_TO_T_UINT_8( 0x4B, 0x60, 0xD2, 0x27, 0x3E, 0x3C, 0xCE, 0x3B ), BYTES_TO_T_UINT_8( 0xF6, 0xB0, 0x53, 0xCC, 0xB0, 0x06, 0x1D, 0x65 ), BYTES_TO_T_UINT_8( 0xBC, 0x86, 0x98, 0x76, 0x55, 0xBD, 0xEB, 0xB3 ), BYTES_TO_T_UINT_8( 0xE7, 0x93, 0x3A, 0xAA, 0xD8, 0x35, 0xC6, 0x5A ), }; static const mbedtls_mpi_uint secp256r1_gx[] = { BYTES_TO_T_UINT_8( 0x96, 0xC2, 0x98, 0xD8, 0x45, 0x39, 0xA1, 0xF4 ), BYTES_TO_T_UINT_8( 0xA0, 0x33, 0xEB, 0x2D, 0x81, 0x7D, 0x03, 0x77 ), BYTES_TO_T_UINT_8( 0xF2, 0x40, 0xA4, 0x63, 0xE5, 0xE6, 0xBC, 0xF8 ), BYTES_TO_T_UINT_8( 0x47, 0x42, 0x2C, 0xE1, 0xF2, 0xD1, 0x17, 0x6B ), }; static const mbedtls_mpi_uint secp256r1_gy[] = { BYTES_TO_T_UINT_8( 0xF5, 0x51, 0xBF, 0x37, 0x68, 0x40, 0xB6, 0xCB ), BYTES_TO_T_UINT_8( 0xCE, 0x5E, 0x31, 0x6B, 0x57, 0x33, 0xCE, 0x2B ), BYTES_TO_T_UINT_8( 0x16, 0x9E, 0x0F, 0x7C, 0x4A, 0xEB, 0xE7, 0x8E ), BYTES_TO_T_UINT_8( 0x9B, 0x7F, 0x1A, 0xFE, 0xE2, 0x42, 0xE3, 0x4F ), }; static const mbedtls_mpi_uint secp256r1_n[] = { BYTES_TO_T_UINT_8( 0x51, 0x25, 0x63, 0xFC, 0xC2, 0xCA, 0xB9, 0xF3 ), BYTES_TO_T_UINT_8( 0x84, 0x9E, 0x17, 0xA7, 0xAD, 0xFA, 0xE6, 0xBC ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF ), }; #endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */ /* * Domain parameters for secp384r1 */ #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) static const mbedtls_mpi_uint secp384r1_p[] = { BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00 ), BYTES_TO_T_UINT_8( 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), }; static const mbedtls_mpi_uint secp384r1_b[] = { BYTES_TO_T_UINT_8( 0xEF, 0x2A, 0xEC, 0xD3, 0xED, 0xC8, 0x85, 0x2A ), BYTES_TO_T_UINT_8( 0x9D, 0xD1, 0x2E, 0x8A, 0x8D, 0x39, 0x56, 0xC6 ), BYTES_TO_T_UINT_8( 0x5A, 0x87, 0x13, 0x50, 0x8F, 0x08, 0x14, 0x03 ), BYTES_TO_T_UINT_8( 0x12, 0x41, 0x81, 0xFE, 0x6E, 0x9C, 0x1D, 0x18 ), BYTES_TO_T_UINT_8( 0x19, 0x2D, 0xF8, 0xE3, 0x6B, 0x05, 0x8E, 0x98 ), BYTES_TO_T_UINT_8( 0xE4, 0xE7, 0x3E, 0xE2, 0xA7, 0x2F, 0x31, 0xB3 ), }; static const mbedtls_mpi_uint secp384r1_gx[] = { BYTES_TO_T_UINT_8( 0xB7, 0x0A, 0x76, 0x72, 0x38, 0x5E, 0x54, 0x3A ), BYTES_TO_T_UINT_8( 0x6C, 0x29, 0x55, 0xBF, 0x5D, 0xF2, 0x02, 0x55 ), BYTES_TO_T_UINT_8( 0x38, 0x2A, 0x54, 0x82, 0xE0, 0x41, 0xF7, 0x59 ), BYTES_TO_T_UINT_8( 0x98, 0x9B, 0xA7, 0x8B, 0x62, 0x3B, 0x1D, 0x6E ), BYTES_TO_T_UINT_8( 0x74, 0xAD, 0x20, 0xF3, 0x1E, 0xC7, 0xB1, 0x8E ), BYTES_TO_T_UINT_8( 0x37, 0x05, 0x8B, 0xBE, 0x22, 0xCA, 0x87, 0xAA ), }; static const mbedtls_mpi_uint secp384r1_gy[] = { BYTES_TO_T_UINT_8( 0x5F, 0x0E, 0xEA, 0x90, 0x7C, 0x1D, 0x43, 0x7A ), BYTES_TO_T_UINT_8( 0x9D, 0x81, 0x7E, 0x1D, 0xCE, 0xB1, 0x60, 0x0A ), BYTES_TO_T_UINT_8( 0xC0, 0xB8, 0xF0, 0xB5, 0x13, 0x31, 0xDA, 0xE9 ), BYTES_TO_T_UINT_8( 0x7C, 0x14, 0x9A, 0x28, 0xBD, 0x1D, 0xF4, 0xF8 ), BYTES_TO_T_UINT_8( 0x29, 0xDC, 0x92, 0x92, 0xBF, 0x98, 0x9E, 0x5D ), BYTES_TO_T_UINT_8( 0x6F, 0x2C, 0x26, 0x96, 0x4A, 0xDE, 0x17, 0x36 ), }; static const mbedtls_mpi_uint secp384r1_n[] = { BYTES_TO_T_UINT_8( 0x73, 0x29, 0xC5, 0xCC, 0x6A, 0x19, 0xEC, 0xEC ), BYTES_TO_T_UINT_8( 0x7A, 0xA7, 0xB0, 0x48, 0xB2, 0x0D, 0x1A, 0x58 ), BYTES_TO_T_UINT_8( 0xDF, 0x2D, 0x37, 0xF4, 0x81, 0x4D, 0x63, 0xC7 ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), }; #endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */ /* * Domain parameters for secp521r1 */ #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) static const mbedtls_mpi_uint secp521r1_p[] = { BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_2( 0xFF, 0x01 ), }; static const mbedtls_mpi_uint secp521r1_b[] = { BYTES_TO_T_UINT_8( 0x00, 0x3F, 0x50, 0x6B, 0xD4, 0x1F, 0x45, 0xEF ), BYTES_TO_T_UINT_8( 0xF1, 0x34, 0x2C, 0x3D, 0x88, 0xDF, 0x73, 0x35 ), BYTES_TO_T_UINT_8( 0x07, 0xBF, 0xB1, 0x3B, 0xBD, 0xC0, 0x52, 0x16 ), BYTES_TO_T_UINT_8( 0x7B, 0x93, 0x7E, 0xEC, 0x51, 0x39, 0x19, 0x56 ), BYTES_TO_T_UINT_8( 0xE1, 0x09, 0xF1, 0x8E, 0x91, 0x89, 0xB4, 0xB8 ), BYTES_TO_T_UINT_8( 0xF3, 0x15, 0xB3, 0x99, 0x5B, 0x72, 0xDA, 0xA2 ), BYTES_TO_T_UINT_8( 0xEE, 0x40, 0x85, 0xB6, 0xA0, 0x21, 0x9A, 0x92 ), BYTES_TO_T_UINT_8( 0x1F, 0x9A, 0x1C, 0x8E, 0x61, 0xB9, 0x3E, 0x95 ), BYTES_TO_T_UINT_2( 0x51, 0x00 ), }; static const mbedtls_mpi_uint secp521r1_gx[] = { BYTES_TO_T_UINT_8( 0x66, 0xBD, 0xE5, 0xC2, 0x31, 0x7E, 0x7E, 0xF9 ), BYTES_TO_T_UINT_8( 0x9B, 0x42, 0x6A, 0x85, 0xC1, 0xB3, 0x48, 0x33 ), BYTES_TO_T_UINT_8( 0xDE, 0xA8, 0xFF, 0xA2, 0x27, 0xC1, 0x1D, 0xFE ), BYTES_TO_T_UINT_8( 0x28, 0x59, 0xE7, 0xEF, 0x77, 0x5E, 0x4B, 0xA1 ), BYTES_TO_T_UINT_8( 0xBA, 0x3D, 0x4D, 0x6B, 0x60, 0xAF, 0x28, 0xF8 ), BYTES_TO_T_UINT_8( 0x21, 0xB5, 0x3F, 0x05, 0x39, 0x81, 0x64, 0x9C ), BYTES_TO_T_UINT_8( 0x42, 0xB4, 0x95, 0x23, 0x66, 0xCB, 0x3E, 0x9E ), BYTES_TO_T_UINT_8( 0xCD, 0xE9, 0x04, 0x04, 0xB7, 0x06, 0x8E, 0x85 ), BYTES_TO_T_UINT_2( 0xC6, 0x00 ), }; static const mbedtls_mpi_uint secp521r1_gy[] = { BYTES_TO_T_UINT_8( 0x50, 0x66, 0xD1, 0x9F, 0x76, 0x94, 0xBE, 0x88 ), BYTES_TO_T_UINT_8( 0x40, 0xC2, 0x72, 0xA2, 0x86, 0x70, 0x3C, 0x35 ), BYTES_TO_T_UINT_8( 0x61, 0x07, 0xAD, 0x3F, 0x01, 0xB9, 0x50, 0xC5 ), BYTES_TO_T_UINT_8( 0x40, 0x26, 0xF4, 0x5E, 0x99, 0x72, 0xEE, 0x97 ), BYTES_TO_T_UINT_8( 0x2C, 0x66, 0x3E, 0x27, 0x17, 0xBD, 0xAF, 0x17 ), BYTES_TO_T_UINT_8( 0x68, 0x44, 0x9B, 0x57, 0x49, 0x44, 0xF5, 0x98 ), BYTES_TO_T_UINT_8( 0xD9, 0x1B, 0x7D, 0x2C, 0xB4, 0x5F, 0x8A, 0x5C ), BYTES_TO_T_UINT_8( 0x04, 0xC0, 0x3B, 0x9A, 0x78, 0x6A, 0x29, 0x39 ), BYTES_TO_T_UINT_2( 0x18, 0x01 ), }; static const mbedtls_mpi_uint secp521r1_n[] = { BYTES_TO_T_UINT_8( 0x09, 0x64, 0x38, 0x91, 0x1E, 0xB7, 0x6F, 0xBB ), BYTES_TO_T_UINT_8( 0xAE, 0x47, 0x9C, 0x89, 0xB8, 0xC9, 0xB5, 0x3B ), BYTES_TO_T_UINT_8( 0xD0, 0xA5, 0x09, 0xF7, 0x48, 0x01, 0xCC, 0x7F ), BYTES_TO_T_UINT_8( 0x6B, 0x96, 0x2F, 0xBF, 0x83, 0x87, 0x86, 0x51 ), BYTES_TO_T_UINT_8( 0xFA, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_2( 0xFF, 0x01 ), }; #endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) static const mbedtls_mpi_uint secp192k1_p[] = { BYTES_TO_T_UINT_8( 0x37, 0xEE, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), }; static const mbedtls_mpi_uint secp192k1_a[] = { BYTES_TO_T_UINT_2( 0x00, 0x00 ), }; static const mbedtls_mpi_uint secp192k1_b[] = { BYTES_TO_T_UINT_2( 0x03, 0x00 ), }; static const mbedtls_mpi_uint secp192k1_gx[] = { BYTES_TO_T_UINT_8( 0x7D, 0x6C, 0xE0, 0xEA, 0xB1, 0xD1, 0xA5, 0x1D ), BYTES_TO_T_UINT_8( 0x34, 0xF4, 0xB7, 0x80, 0x02, 0x7D, 0xB0, 0x26 ), BYTES_TO_T_UINT_8( 0xAE, 0xE9, 0x57, 0xC0, 0x0E, 0xF1, 0x4F, 0xDB ), }; static const mbedtls_mpi_uint secp192k1_gy[] = { BYTES_TO_T_UINT_8( 0x9D, 0x2F, 0x5E, 0xD9, 0x88, 0xAA, 0x82, 0x40 ), BYTES_TO_T_UINT_8( 0x34, 0x86, 0xBE, 0x15, 0xD0, 0x63, 0x41, 0x84 ), BYTES_TO_T_UINT_8( 0xA7, 0x28, 0x56, 0x9C, 0x6D, 0x2F, 0x2F, 0x9B ), }; static const mbedtls_mpi_uint secp192k1_n[] = { BYTES_TO_T_UINT_8( 0x8D, 0xFD, 0xDE, 0x74, 0x6A, 0x46, 0x69, 0x0F ), BYTES_TO_T_UINT_8( 0x17, 0xFC, 0xF2, 0x26, 0xFE, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), }; #endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) static const mbedtls_mpi_uint secp224k1_p[] = { BYTES_TO_T_UINT_8( 0x6D, 0xE5, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_4( 0xFF, 0xFF, 0xFF, 0xFF ), }; static const mbedtls_mpi_uint secp224k1_a[] = { BYTES_TO_T_UINT_2( 0x00, 0x00 ), }; static const mbedtls_mpi_uint secp224k1_b[] = { BYTES_TO_T_UINT_2( 0x05, 0x00 ), }; static const mbedtls_mpi_uint secp224k1_gx[] = { BYTES_TO_T_UINT_8( 0x5C, 0xA4, 0xB7, 0xB6, 0x0E, 0x65, 0x7E, 0x0F ), BYTES_TO_T_UINT_8( 0xA9, 0x75, 0x70, 0xE4, 0xE9, 0x67, 0xA4, 0x69 ), BYTES_TO_T_UINT_8( 0xA1, 0x28, 0xFC, 0x30, 0xDF, 0x99, 0xF0, 0x4D ), BYTES_TO_T_UINT_4( 0x33, 0x5B, 0x45, 0xA1 ), }; static const mbedtls_mpi_uint secp224k1_gy[] = { BYTES_TO_T_UINT_8( 0xA5, 0x61, 0x6D, 0x55, 0xDB, 0x4B, 0xCA, 0xE2 ), BYTES_TO_T_UINT_8( 0x59, 0xBD, 0xB0, 0xC0, 0xF7, 0x19, 0xE3, 0xF7 ), BYTES_TO_T_UINT_8( 0xD6, 0xFB, 0xCA, 0x82, 0x42, 0x34, 0xBA, 0x7F ), BYTES_TO_T_UINT_4( 0xED, 0x9F, 0x08, 0x7E ), }; static const mbedtls_mpi_uint secp224k1_n[] = { BYTES_TO_T_UINT_8( 0xF7, 0xB1, 0x9F, 0x76, 0x71, 0xA9, 0xF0, 0xCA ), BYTES_TO_T_UINT_8( 0x84, 0x61, 0xEC, 0xD2, 0xE8, 0xDC, 0x01, 0x00 ), BYTES_TO_T_UINT_8( 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ), BYTES_TO_T_UINT_8( 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 ), }; #endif /* MBEDTLS_ECP_DP_SECP224K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) static const mbedtls_mpi_uint secp256k1_p[] = { BYTES_TO_T_UINT_8( 0x2F, 0xFC, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), }; static const mbedtls_mpi_uint secp256k1_a[] = { BYTES_TO_T_UINT_2( 0x00, 0x00 ), }; static const mbedtls_mpi_uint secp256k1_b[] = { BYTES_TO_T_UINT_2( 0x07, 0x00 ), }; static const mbedtls_mpi_uint secp256k1_gx[] = { BYTES_TO_T_UINT_8( 0x98, 0x17, 0xF8, 0x16, 0x5B, 0x81, 0xF2, 0x59 ), BYTES_TO_T_UINT_8( 0xD9, 0x28, 0xCE, 0x2D, 0xDB, 0xFC, 0x9B, 0x02 ), BYTES_TO_T_UINT_8( 0x07, 0x0B, 0x87, 0xCE, 0x95, 0x62, 0xA0, 0x55 ), BYTES_TO_T_UINT_8( 0xAC, 0xBB, 0xDC, 0xF9, 0x7E, 0x66, 0xBE, 0x79 ), }; static const mbedtls_mpi_uint secp256k1_gy[] = { BYTES_TO_T_UINT_8( 0xB8, 0xD4, 0x10, 0xFB, 0x8F, 0xD0, 0x47, 0x9C ), BYTES_TO_T_UINT_8( 0x19, 0x54, 0x85, 0xA6, 0x48, 0xB4, 0x17, 0xFD ), BYTES_TO_T_UINT_8( 0xA8, 0x08, 0x11, 0x0E, 0xFC, 0xFB, 0xA4, 0x5D ), BYTES_TO_T_UINT_8( 0x65, 0xC4, 0xA3, 0x26, 0x77, 0xDA, 0x3A, 0x48 ), }; static const mbedtls_mpi_uint secp256k1_n[] = { BYTES_TO_T_UINT_8( 0x41, 0x41, 0x36, 0xD0, 0x8C, 0x5E, 0xD2, 0xBF ), BYTES_TO_T_UINT_8( 0x3B, 0xA0, 0x48, 0xAF, 0xE6, 0xDC, 0xAE, 0xBA ), BYTES_TO_T_UINT_8( 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), BYTES_TO_T_UINT_8( 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ), }; #endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */ /* * Domain parameters for brainpoolP256r1 (RFC 5639 3.4) */ #if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) static const mbedtls_mpi_uint brainpoolP256r1_p[] = { BYTES_TO_T_UINT_8( 0x77, 0x53, 0x6E, 0x1F, 0x1D, 0x48, 0x13, 0x20 ), BYTES_TO_T_UINT_8( 0x28, 0x20, 0x26, 0xD5, 0x23, 0xF6, 0x3B, 0x6E ), BYTES_TO_T_UINT_8( 0x72, 0x8D, 0x83, 0x9D, 0x90, 0x0A, 0x66, 0x3E ), BYTES_TO_T_UINT_8( 0xBC, 0xA9, 0xEE, 0xA1, 0xDB, 0x57, 0xFB, 0xA9 ), }; static const mbedtls_mpi_uint brainpoolP256r1_a[] = { BYTES_TO_T_UINT_8( 0xD9, 0xB5, 0x30, 0xF3, 0x44, 0x4B, 0x4A, 0xE9 ), BYTES_TO_T_UINT_8( 0x6C, 0x5C, 0xDC, 0x26, 0xC1, 0x55, 0x80, 0xFB ), BYTES_TO_T_UINT_8( 0xE7, 0xFF, 0x7A, 0x41, 0x30, 0x75, 0xF6, 0xEE ), BYTES_TO_T_UINT_8( 0x57, 0x30, 0x2C, 0xFC, 0x75, 0x09, 0x5A, 0x7D ), }; static const mbedtls_mpi_uint brainpoolP256r1_b[] = { BYTES_TO_T_UINT_8( 0xB6, 0x07, 0x8C, 0xFF, 0x18, 0xDC, 0xCC, 0x6B ), BYTES_TO_T_UINT_8( 0xCE, 0xE1, 0xF7, 0x5C, 0x29, 0x16, 0x84, 0x95 ), BYTES_TO_T_UINT_8( 0xBF, 0x7C, 0xD7, 0xBB, 0xD9, 0xB5, 0x30, 0xF3 ), BYTES_TO_T_UINT_8( 0x44, 0x4B, 0x4A, 0xE9, 0x6C, 0x5C, 0xDC, 0x26 ), }; static const mbedtls_mpi_uint brainpoolP256r1_gx[] = { BYTES_TO_T_UINT_8( 0x62, 0x32, 0xCE, 0x9A, 0xBD, 0x53, 0x44, 0x3A ), BYTES_TO_T_UINT_8( 0xC2, 0x23, 0xBD, 0xE3, 0xE1, 0x27, 0xDE, 0xB9 ), BYTES_TO_T_UINT_8( 0xAF, 0xB7, 0x81, 0xFC, 0x2F, 0x48, 0x4B, 0x2C ), BYTES_TO_T_UINT_8( 0xCB, 0x57, 0x7E, 0xCB, 0xB9, 0xAE, 0xD2, 0x8B ), }; static const mbedtls_mpi_uint brainpoolP256r1_gy[] = { BYTES_TO_T_UINT_8( 0x97, 0x69, 0x04, 0x2F, 0xC7, 0x54, 0x1D, 0x5C ), BYTES_TO_T_UINT_8( 0x54, 0x8E, 0xED, 0x2D, 0x13, 0x45, 0x77, 0xC2 ), BYTES_TO_T_UINT_8( 0xC9, 0x1D, 0x61, 0x14, 0x1A, 0x46, 0xF8, 0x97 ), BYTES_TO_T_UINT_8( 0xFD, 0xC4, 0xDA, 0xC3, 0x35, 0xF8, 0x7E, 0x54 ), }; static const mbedtls_mpi_uint brainpoolP256r1_n[] = { BYTES_TO_T_UINT_8( 0xA7, 0x56, 0x48, 0x97, 0x82, 0x0E, 0x1E, 0x90 ), BYTES_TO_T_UINT_8( 0xF7, 0xA6, 0x61, 0xB5, 0xA3, 0x7A, 0x39, 0x8C ), BYTES_TO_T_UINT_8( 0x71, 0x8D, 0x83, 0x9D, 0x90, 0x0A, 0x66, 0x3E ), BYTES_TO_T_UINT_8( 0xBC, 0xA9, 0xEE, 0xA1, 0xDB, 0x57, 0xFB, 0xA9 ), }; #endif /* MBEDTLS_ECP_DP_BP256R1_ENABLED */ /* * Domain parameters for brainpoolP384r1 (RFC 5639 3.6) */ #if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) static const mbedtls_mpi_uint brainpoolP384r1_p[] = { BYTES_TO_T_UINT_8( 0x53, 0xEC, 0x07, 0x31, 0x13, 0x00, 0x47, 0x87 ), BYTES_TO_T_UINT_8( 0x71, 0x1A, 0x1D, 0x90, 0x29, 0xA7, 0xD3, 0xAC ), BYTES_TO_T_UINT_8( 0x23, 0x11, 0xB7, 0x7F, 0x19, 0xDA, 0xB1, 0x12 ), BYTES_TO_T_UINT_8( 0xB4, 0x56, 0x54, 0xED, 0x09, 0x71, 0x2F, 0x15 ), BYTES_TO_T_UINT_8( 0xDF, 0x41, 0xE6, 0x50, 0x7E, 0x6F, 0x5D, 0x0F ), BYTES_TO_T_UINT_8( 0x28, 0x6D, 0x38, 0xA3, 0x82, 0x1E, 0xB9, 0x8C ), }; static const mbedtls_mpi_uint brainpoolP384r1_a[] = { BYTES_TO_T_UINT_8( 0x26, 0x28, 0xCE, 0x22, 0xDD, 0xC7, 0xA8, 0x04 ), BYTES_TO_T_UINT_8( 0xEB, 0xD4, 0x3A, 0x50, 0x4A, 0x81, 0xA5, 0x8A ), BYTES_TO_T_UINT_8( 0x0F, 0xF9, 0x91, 0xBA, 0xEF, 0x65, 0x91, 0x13 ), BYTES_TO_T_UINT_8( 0x87, 0x27, 0xB2, 0x4F, 0x8E, 0xA2, 0xBE, 0xC2 ), BYTES_TO_T_UINT_8( 0xA0, 0xAF, 0x05, 0xCE, 0x0A, 0x08, 0x72, 0x3C ), BYTES_TO_T_UINT_8( 0x0C, 0x15, 0x8C, 0x3D, 0xC6, 0x82, 0xC3, 0x7B ), }; static const mbedtls_mpi_uint brainpoolP384r1_b[] = { BYTES_TO_T_UINT_8( 0x11, 0x4C, 0x50, 0xFA, 0x96, 0x86, 0xB7, 0x3A ), BYTES_TO_T_UINT_8( 0x94, 0xC9, 0xDB, 0x95, 0x02, 0x39, 0xB4, 0x7C ), BYTES_TO_T_UINT_8( 0xD5, 0x62, 0xEB, 0x3E, 0xA5, 0x0E, 0x88, 0x2E ), BYTES_TO_T_UINT_8( 0xA6, 0xD2, 0xDC, 0x07, 0xE1, 0x7D, 0xB7, 0x2F ), BYTES_TO_T_UINT_8( 0x7C, 0x44, 0xF0, 0x16, 0x54, 0xB5, 0x39, 0x8B ), BYTES_TO_T_UINT_8( 0x26, 0x28, 0xCE, 0x22, 0xDD, 0xC7, 0xA8, 0x04 ), }; static const mbedtls_mpi_uint brainpoolP384r1_gx[] = { BYTES_TO_T_UINT_8( 0x1E, 0xAF, 0xD4, 0x47, 0xE2, 0xB2, 0x87, 0xEF ), BYTES_TO_T_UINT_8( 0xAA, 0x46, 0xD6, 0x36, 0x34, 0xE0, 0x26, 0xE8 ), BYTES_TO_T_UINT_8( 0xE8, 0x10, 0xBD, 0x0C, 0xFE, 0xCA, 0x7F, 0xDB ), BYTES_TO_T_UINT_8( 0xE3, 0x4F, 0xF1, 0x7E, 0xE7, 0xA3, 0x47, 0x88 ), BYTES_TO_T_UINT_8( 0x6B, 0x3F, 0xC1, 0xB7, 0x81, 0x3A, 0xA6, 0xA2 ), BYTES_TO_T_UINT_8( 0xFF, 0x45, 0xCF, 0x68, 0xF0, 0x64, 0x1C, 0x1D ), }; static const mbedtls_mpi_uint brainpoolP384r1_gy[] = { BYTES_TO_T_UINT_8( 0x15, 0x53, 0x3C, 0x26, 0x41, 0x03, 0x82, 0x42 ), BYTES_TO_T_UINT_8( 0x11, 0x81, 0x91, 0x77, 0x21, 0x46, 0x46, 0x0E ), BYTES_TO_T_UINT_8( 0x28, 0x29, 0x91, 0xF9, 0x4F, 0x05, 0x9C, 0xE1 ), BYTES_TO_T_UINT_8( 0x64, 0x58, 0xEC, 0xFE, 0x29, 0x0B, 0xB7, 0x62 ), BYTES_TO_T_UINT_8( 0x52, 0xD5, 0xCF, 0x95, 0x8E, 0xEB, 0xB1, 0x5C ), BYTES_TO_T_UINT_8( 0xA4, 0xC2, 0xF9, 0x20, 0x75, 0x1D, 0xBE, 0x8A ), }; static const mbedtls_mpi_uint brainpoolP384r1_n[] = { BYTES_TO_T_UINT_8( 0x65, 0x65, 0x04, 0xE9, 0x02, 0x32, 0x88, 0x3B ), BYTES_TO_T_UINT_8( 0x10, 0xC3, 0x7F, 0x6B, 0xAF, 0xB6, 0x3A, 0xCF ), BYTES_TO_T_UINT_8( 0xA7, 0x25, 0x04, 0xAC, 0x6C, 0x6E, 0x16, 0x1F ), BYTES_TO_T_UINT_8( 0xB3, 0x56, 0x54, 0xED, 0x09, 0x71, 0x2F, 0x15 ), BYTES_TO_T_UINT_8( 0xDF, 0x41, 0xE6, 0x50, 0x7E, 0x6F, 0x5D, 0x0F ), BYTES_TO_T_UINT_8( 0x28, 0x6D, 0x38, 0xA3, 0x82, 0x1E, 0xB9, 0x8C ), }; #endif /* MBEDTLS_ECP_DP_BP384R1_ENABLED */ /* * Domain parameters for brainpoolP512r1 (RFC 5639 3.7) */ #if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) static const mbedtls_mpi_uint brainpoolP512r1_p[] = { BYTES_TO_T_UINT_8( 0xF3, 0x48, 0x3A, 0x58, 0x56, 0x60, 0xAA, 0x28 ), BYTES_TO_T_UINT_8( 0x85, 0xC6, 0x82, 0x2D, 0x2F, 0xFF, 0x81, 0x28 ), BYTES_TO_T_UINT_8( 0xE6, 0x80, 0xA3, 0xE6, 0x2A, 0xA1, 0xCD, 0xAE ), BYTES_TO_T_UINT_8( 0x42, 0x68, 0xC6, 0x9B, 0x00, 0x9B, 0x4D, 0x7D ), BYTES_TO_T_UINT_8( 0x71, 0x08, 0x33, 0x70, 0xCA, 0x9C, 0x63, 0xD6 ), BYTES_TO_T_UINT_8( 0x0E, 0xD2, 0xC9, 0xB3, 0xB3, 0x8D, 0x30, 0xCB ), BYTES_TO_T_UINT_8( 0x07, 0xFC, 0xC9, 0x33, 0xAE, 0xE6, 0xD4, 0x3F ), BYTES_TO_T_UINT_8( 0x8B, 0xC4, 0xE9, 0xDB, 0xB8, 0x9D, 0xDD, 0xAA ), }; static const mbedtls_mpi_uint brainpoolP512r1_a[] = { BYTES_TO_T_UINT_8( 0xCA, 0x94, 0xFC, 0x77, 0x4D, 0xAC, 0xC1, 0xE7 ), BYTES_TO_T_UINT_8( 0xB9, 0xC7, 0xF2, 0x2B, 0xA7, 0x17, 0x11, 0x7F ), BYTES_TO_T_UINT_8( 0xB5, 0xC8, 0x9A, 0x8B, 0xC9, 0xF1, 0x2E, 0x0A ), BYTES_TO_T_UINT_8( 0xA1, 0x3A, 0x25, 0xA8, 0x5A, 0x5D, 0xED, 0x2D ), BYTES_TO_T_UINT_8( 0xBC, 0x63, 0x98, 0xEA, 0xCA, 0x41, 0x34, 0xA8 ), BYTES_TO_T_UINT_8( 0x10, 0x16, 0xF9, 0x3D, 0x8D, 0xDD, 0xCB, 0x94 ), BYTES_TO_T_UINT_8( 0xC5, 0x4C, 0x23, 0xAC, 0x45, 0x71, 0x32, 0xE2 ), BYTES_TO_T_UINT_8( 0x89, 0x3B, 0x60, 0x8B, 0x31, 0xA3, 0x30, 0x78 ), }; static const mbedtls_mpi_uint brainpoolP512r1_b[] = { BYTES_TO_T_UINT_8( 0x23, 0xF7, 0x16, 0x80, 0x63, 0xBD, 0x09, 0x28 ), BYTES_TO_T_UINT_8( 0xDD, 0xE5, 0xBA, 0x5E, 0xB7, 0x50, 0x40, 0x98 ), BYTES_TO_T_UINT_8( 0x67, 0x3E, 0x08, 0xDC, 0xCA, 0x94, 0xFC, 0x77 ), BYTES_TO_T_UINT_8( 0x4D, 0xAC, 0xC1, 0xE7, 0xB9, 0xC7, 0xF2, 0x2B ), BYTES_TO_T_UINT_8( 0xA7, 0x17, 0x11, 0x7F, 0xB5, 0xC8, 0x9A, 0x8B ), BYTES_TO_T_UINT_8( 0xC9, 0xF1, 0x2E, 0x0A, 0xA1, 0x3A, 0x25, 0xA8 ), BYTES_TO_T_UINT_8( 0x5A, 0x5D, 0xED, 0x2D, 0xBC, 0x63, 0x98, 0xEA ), BYTES_TO_T_UINT_8( 0xCA, 0x41, 0x34, 0xA8, 0x10, 0x16, 0xF9, 0x3D ), }; static const mbedtls_mpi_uint brainpoolP512r1_gx[] = { BYTES_TO_T_UINT_8( 0x22, 0xF8, 0xB9, 0xBC, 0x09, 0x22, 0x35, 0x8B ), BYTES_TO_T_UINT_8( 0x68, 0x5E, 0x6A, 0x40, 0x47, 0x50, 0x6D, 0x7C ), BYTES_TO_T_UINT_8( 0x5F, 0x7D, 0xB9, 0x93, 0x7B, 0x68, 0xD1, 0x50 ), BYTES_TO_T_UINT_8( 0x8D, 0xD4, 0xD0, 0xE2, 0x78, 0x1F, 0x3B, 0xFF ), BYTES_TO_T_UINT_8( 0x8E, 0x09, 0xD0, 0xF4, 0xEE, 0x62, 0x3B, 0xB4 ), BYTES_TO_T_UINT_8( 0xC1, 0x16, 0xD9, 0xB5, 0x70, 0x9F, 0xED, 0x85 ), BYTES_TO_T_UINT_8( 0x93, 0x6A, 0x4C, 0x9C, 0x2E, 0x32, 0x21, 0x5A ), BYTES_TO_T_UINT_8( 0x64, 0xD9, 0x2E, 0xD8, 0xBD, 0xE4, 0xAE, 0x81 ), }; static const mbedtls_mpi_uint brainpoolP512r1_gy[] = { BYTES_TO_T_UINT_8( 0x92, 0x08, 0xD8, 0x3A, 0x0F, 0x1E, 0xCD, 0x78 ), BYTES_TO_T_UINT_8( 0x06, 0x54, 0xF0, 0xA8, 0x2F, 0x2B, 0xCA, 0xD1 ), BYTES_TO_T_UINT_8( 0xAE, 0x63, 0x27, 0x8A, 0xD8, 0x4B, 0xCA, 0x5B ), BYTES_TO_T_UINT_8( 0x5E, 0x48, 0x5F, 0x4A, 0x49, 0xDE, 0xDC, 0xB2 ), BYTES_TO_T_UINT_8( 0x11, 0x81, 0x1F, 0x88, 0x5B, 0xC5, 0x00, 0xA0 ), BYTES_TO_T_UINT_8( 0x1A, 0x7B, 0xA5, 0x24, 0x00, 0xF7, 0x09, 0xF2 ), BYTES_TO_T_UINT_8( 0xFD, 0x22, 0x78, 0xCF, 0xA9, 0xBF, 0xEA, 0xC0 ), BYTES_TO_T_UINT_8( 0xEC, 0x32, 0x63, 0x56, 0x5D, 0x38, 0xDE, 0x7D ), }; static const mbedtls_mpi_uint brainpoolP512r1_n[] = { BYTES_TO_T_UINT_8( 0x69, 0x00, 0xA9, 0x9C, 0x82, 0x96, 0x87, 0xB5 ), BYTES_TO_T_UINT_8( 0xDD, 0xDA, 0x5D, 0x08, 0x81, 0xD3, 0xB1, 0x1D ), BYTES_TO_T_UINT_8( 0x47, 0x10, 0xAC, 0x7F, 0x19, 0x61, 0x86, 0x41 ), BYTES_TO_T_UINT_8( 0x19, 0x26, 0xA9, 0x4C, 0x41, 0x5C, 0x3E, 0x55 ), BYTES_TO_T_UINT_8( 0x70, 0x08, 0x33, 0x70, 0xCA, 0x9C, 0x63, 0xD6 ), BYTES_TO_T_UINT_8( 0x0E, 0xD2, 0xC9, 0xB3, 0xB3, 0x8D, 0x30, 0xCB ), BYTES_TO_T_UINT_8( 0x07, 0xFC, 0xC9, 0x33, 0xAE, 0xE6, 0xD4, 0x3F ), BYTES_TO_T_UINT_8( 0x8B, 0xC4, 0xE9, 0xDB, 0xB8, 0x9D, 0xDD, 0xAA ), }; #endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) /* For these curves, we build the group parameters dynamically. */ #define ECP_LOAD_GROUP #endif #if defined(ECP_LOAD_GROUP) /* * Create an MPI from embedded constants * (assumes len is an exact multiple of sizeof mbedtls_mpi_uint) */ static inline void ecp_mpi_load( mbedtls_mpi *X, const mbedtls_mpi_uint *p, size_t len ) { X->s = 1; X->n = len / sizeof( mbedtls_mpi_uint ); X->p = (mbedtls_mpi_uint *) p; } /* * Set an MPI to static value 1 */ static inline void ecp_mpi_set1( mbedtls_mpi *X ) { static mbedtls_mpi_uint one[] = { 1 }; X->s = 1; X->n = 1; X->p = one; } /* * Make group available from embedded constants */ static int ecp_group_load( mbedtls_ecp_group *grp, const mbedtls_mpi_uint *p, size_t plen, const mbedtls_mpi_uint *a, size_t alen, const mbedtls_mpi_uint *b, size_t blen, const mbedtls_mpi_uint *gx, size_t gxlen, const mbedtls_mpi_uint *gy, size_t gylen, const mbedtls_mpi_uint *n, size_t nlen) { ecp_mpi_load( &grp->P, p, plen ); if( a != NULL ) ecp_mpi_load( &grp->A, a, alen ); ecp_mpi_load( &grp->B, b, blen ); ecp_mpi_load( &grp->N, n, nlen ); ecp_mpi_load( &grp->G.X, gx, gxlen ); ecp_mpi_load( &grp->G.Y, gy, gylen ); ecp_mpi_set1( &grp->G.Z ); grp->pbits = mbedtls_mpi_bitlen( &grp->P ); grp->nbits = mbedtls_mpi_bitlen( &grp->N ); grp->h = 1; return( 0 ); } #endif /* ECP_LOAD_GROUP */ #if defined(MBEDTLS_ECP_NIST_OPTIM) /* Forward declarations */ #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) static int ecp_mod_p192( mbedtls_mpi * ); #endif #if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) static int ecp_mod_p224( mbedtls_mpi * ); #endif #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) static int ecp_mod_p521( mbedtls_mpi * ); #endif #define NIST_MODP( P ) grp->modp = ecp_mod_ ## P; #else #define NIST_MODP( P ) #endif /* MBEDTLS_ECP_NIST_OPTIM */ /* Additional forward declarations */ #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) static int ecp_mod_p255( mbedtls_mpi * ); #endif #if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) static int ecp_mod_p448( mbedtls_mpi * ); #endif #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) static int ecp_mod_p192k1( mbedtls_mpi * ); #endif #if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) static int ecp_mod_p224k1( mbedtls_mpi * ); #endif #if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) static int ecp_mod_p256k1( mbedtls_mpi * ); #endif #if defined(ECP_LOAD_GROUP) #define LOAD_GROUP_A( G ) ecp_group_load( grp, \ G ## _p, sizeof( G ## _p ), \ G ## _a, sizeof( G ## _a ), \ G ## _b, sizeof( G ## _b ), \ G ## _gx, sizeof( G ## _gx ), \ G ## _gy, sizeof( G ## _gy ), \ G ## _n, sizeof( G ## _n ) ) #define LOAD_GROUP( G ) ecp_group_load( grp, \ G ## _p, sizeof( G ## _p ), \ NULL, 0, \ G ## _b, sizeof( G ## _b ), \ G ## _gx, sizeof( G ## _gx ), \ G ## _gy, sizeof( G ## _gy ), \ G ## _n, sizeof( G ## _n ) ) #endif /* ECP_LOAD_GROUP */ #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) /* * Specialized function for creating the Curve25519 group */ static int ecp_use_curve25519( mbedtls_ecp_group *grp ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; /* Actually ( A + 2 ) / 4 */ MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &grp->A, 16, "01DB42" ) ); /* P = 2^255 - 19 */ MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &grp->P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &grp->P, 255 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &grp->P, &grp->P, 19 ) ); grp->pbits = mbedtls_mpi_bitlen( &grp->P ); /* N = 2^252 + 27742317777372353535851937790883648493 */ MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &grp->N, 16, "14DEF9DEA2F79CD65812631A5CF5D3ED" ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &grp->N, 252, 1 ) ); /* Y intentionally not set, since we use x/z coordinates. * This is used as a marker to identify Montgomery curves! */ MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &grp->G.X, 9 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &grp->G.Z, 1 ) ); mbedtls_mpi_free( &grp->G.Y ); /* Actually, the required msb for private keys */ grp->nbits = 254; cleanup: if( ret != 0 ) mbedtls_ecp_group_free( grp ); return( ret ); } #endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */ #if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) /* * Specialized function for creating the Curve448 group */ static int ecp_use_curve448( mbedtls_ecp_group *grp ) { mbedtls_mpi Ns; int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_mpi_init( &Ns ); /* Actually ( A + 2 ) / 4 */ MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &grp->A, 16, "98AA" ) ); /* P = 2^448 - 2^224 - 1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &grp->P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &grp->P, 224 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &grp->P, &grp->P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &grp->P, 224 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &grp->P, &grp->P, 1 ) ); grp->pbits = mbedtls_mpi_bitlen( &grp->P ); /* Y intentionally not set, since we use x/z coordinates. * This is used as a marker to identify Montgomery curves! */ MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &grp->G.X, 5 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &grp->G.Z, 1 ) ); mbedtls_mpi_free( &grp->G.Y ); /* N = 2^446 - 13818066809895115352007386748515426880336692474882178609894547503885 */ MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &grp->N, 446, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &Ns, 16, "8335DC163BB124B65129C96FDE933D8D723A70AADC873D6D54A7BB0D" ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &grp->N, &grp->N, &Ns ) ); /* Actually, the required msb for private keys */ grp->nbits = 447; cleanup: mbedtls_mpi_free( &Ns ); if( ret != 0 ) mbedtls_ecp_group_free( grp ); return( ret ); } #endif /* MBEDTLS_ECP_DP_CURVE448_ENABLED */ /** * \brief This function sets up an ECP group context * from a standardized set of domain parameters. * * \note The index should be a value of the NamedCurve enum, * as defined in <em>RFC-4492: Elliptic Curve Cryptography * (ECC) Cipher Suites for Transport Layer Security (TLS)</em>, * usually in the form of an \c MBEDTLS_ECP_DP_XXX macro. * * \param grp The group context to setup. This must be initialized. * \param id The identifier of the domain parameter set to load. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if \p id doesn't * correspond to a known group. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_group_load( mbedtls_ecp_group *grp, mbedtls_ecp_group_id id ) { ECP_VALIDATE_RET( grp != NULL ); mbedtls_ecp_group_free( grp ); grp->id = id; switch( id ) { #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) case MBEDTLS_ECP_DP_SECP192R1: NIST_MODP( p192 ); return( LOAD_GROUP( secp192r1 ) ); #endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) case MBEDTLS_ECP_DP_SECP224R1: NIST_MODP( p224 ); return( LOAD_GROUP( secp224r1 ) ); #endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) case MBEDTLS_ECP_DP_SECP256R1: NIST_MODP( p256 ); return( LOAD_GROUP( secp256r1 ) ); #endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) case MBEDTLS_ECP_DP_SECP384R1: NIST_MODP( p384 ); return( LOAD_GROUP( secp384r1 ) ); #endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) case MBEDTLS_ECP_DP_SECP521R1: NIST_MODP( p521 ); return( LOAD_GROUP( secp521r1 ) ); #endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) case MBEDTLS_ECP_DP_SECP192K1: grp->modp = ecp_mod_p192k1; return( LOAD_GROUP_A( secp192k1 ) ); #endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) case MBEDTLS_ECP_DP_SECP224K1: grp->modp = ecp_mod_p224k1; return( LOAD_GROUP_A( secp224k1 ) ); #endif /* MBEDTLS_ECP_DP_SECP224K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) case MBEDTLS_ECP_DP_SECP256K1: grp->modp = ecp_mod_p256k1; return( LOAD_GROUP_A( secp256k1 ) ); #endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) case MBEDTLS_ECP_DP_BP256R1: return( LOAD_GROUP_A( brainpoolP256r1 ) ); #endif /* MBEDTLS_ECP_DP_BP256R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) case MBEDTLS_ECP_DP_BP384R1: return( LOAD_GROUP_A( brainpoolP384r1 ) ); #endif /* MBEDTLS_ECP_DP_BP384R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) case MBEDTLS_ECP_DP_BP512R1: return( LOAD_GROUP_A( brainpoolP512r1 ) ); #endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) case MBEDTLS_ECP_DP_CURVE25519: grp->modp = ecp_mod_p255; return( ecp_use_curve25519( grp ) ); #endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */ #if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) case MBEDTLS_ECP_DP_CURVE448: grp->modp = ecp_mod_p448; return( ecp_use_curve448( grp ) ); #endif /* MBEDTLS_ECP_DP_CURVE448_ENABLED */ default: grp->id = MBEDTLS_ECP_DP_NONE; return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ); } } #if defined(MBEDTLS_ECP_NIST_OPTIM) /* * Fast reduction modulo the primes used by the NIST curves. * * These functions are critical for speed, but not needed for correct * operations. So, we make the choice to heavily rely on the internals of our * bignum library, which creates a tight coupling between these functions and * our MPI implementation. However, the coupling between the ECP module and * MPI remains loose, since these functions can be deactivated at will. */ #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) /* * Compared to the way things are presented in FIPS 186-3 D.2, * we proceed in columns, from right (least significant chunk) to left, * adding chunks to N in place, and keeping a carry for the next chunk. * This avoids moving things around in memory, and uselessly adding zeros, * compared to the more straightforward, line-oriented approach. * * For this prime we need to handle data in chunks of 64 bits. * Since this is always a multiple of our basic mbedtls_mpi_uint, we can * use a mbedtls_mpi_uint * to designate such a chunk, and small loops to handle it. */ /* Add 64-bit chunks (dst += src) and update carry */ static inline void add64( mbedtls_mpi_uint *dst, mbedtls_mpi_uint *src, mbedtls_mpi_uint *carry ) { unsigned char i; mbedtls_mpi_uint c = 0; for( i = 0; i < 8 / sizeof( mbedtls_mpi_uint ); i++, dst++, src++ ) { *dst += c; c = ( *dst < c ); *dst += *src; c += ( *dst < *src ); } *carry += c; } /* Add carry to a 64-bit chunk and update carry */ static inline void carry64( mbedtls_mpi_uint *dst, mbedtls_mpi_uint *carry ) { unsigned char i; for( i = 0; i < 8 / sizeof( mbedtls_mpi_uint ); i++, dst++ ) { *dst += *carry; *carry = ( *dst < *carry ); } } #define WIDTH 8 / sizeof( mbedtls_mpi_uint ) #define A( i ) N->p + (i) * WIDTH #define ADD( i ) add64( p, A( i ), &c ) #define NEXT p += WIDTH; carry64( p, &c ) #define LAST p += WIDTH; *p = c; while( ++p < end ) *p = 0 /* * Fast quasi-reduction modulo p192 (FIPS 186-3 D.2.1) */ static int ecp_mod_p192( mbedtls_mpi *N ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_mpi_uint c = 0; mbedtls_mpi_uint *p, *end; /* Make sure we have enough blocks so that A(5) is legal */ MBEDTLS_MPI_CHK( mbedtls_mpi_grow( N, 6 * WIDTH ) ); p = N->p; end = p + N->n; ADD( 3 ); ADD( 5 ); NEXT; // A0 += A3 + A5 ADD( 3 ); ADD( 4 ); ADD( 5 ); NEXT; // A1 += A3 + A4 + A5 ADD( 4 ); ADD( 5 ); LAST; // A2 += A4 + A5 cleanup: return( ret ); } #undef WIDTH #undef A #undef ADD #undef NEXT #undef LAST #endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) /* * The reader is advised to first understand ecp_mod_p192() since the same * general structure is used here, but with additional complications: * (1) chunks of 32 bits, and (2) subtractions. */ /* * For these primes, we need to handle data in chunks of 32 bits. * This makes it more complicated if we use 64 bits limbs in MPI, * which prevents us from using a uniform access method as for p192. * * So, we define a mini abstraction layer to access 32 bit chunks, * load them in 'cur' for work, and store them back from 'cur' when done. * * While at it, also define the size of N in terms of 32-bit chunks. */ #define LOAD32 cur = A( i ); #if defined(MBEDTLS_HAVE_INT32) /* 32 bit */ #define MAX32 N->n #define A( j ) N->p[j] #define STORE32 N->p[i] = cur; #else /* 64-bit */ #define MAX32 N->n * 2 #define A( j ) (j) % 2 ? (uint32_t)( N->p[(j)/2] >> 32 ) : \ (uint32_t)( N->p[(j)/2] ) #define STORE32 \ if( i % 2 ) { \ N->p[i/2] &= 0x00000000FFFFFFFF; \ N->p[i/2] |= ((mbedtls_mpi_uint) cur) << 32; \ } else { \ N->p[i/2] &= 0xFFFFFFFF00000000; \ N->p[i/2] |= (mbedtls_mpi_uint) cur; \ } #endif /* sizeof( mbedtls_mpi_uint ) */ /* * Helpers for addition and subtraction of chunks, with signed carry. */ static inline void add32( uint32_t *dst, uint32_t src, signed char *carry ) { *dst += src; *carry += ( *dst < src ); } static inline void sub32( uint32_t *dst, uint32_t src, signed char *carry ) { *carry -= ( *dst < src ); *dst -= src; } #define ADD( j ) add32( &cur, A( j ), &c ); #define SUB( j ) sub32( &cur, A( j ), &c ); /* * Helpers for the main 'loop' * (see fix_negative for the motivation of C) */ #define INIT( b ) \ int ret = MBEDTLS_ERR_THIS_CORRUPTION; \ signed char c = 0, cc; \ uint32_t cur; \ size_t i = 0, bits = (b); \ mbedtls_mpi C; \ mbedtls_mpi_uint Cp[ (b) / 8 / sizeof( mbedtls_mpi_uint) + 1 ]; \ \ C.s = 1; \ C.n = (b) / 8 / sizeof( mbedtls_mpi_uint) + 1; \ C.p = Cp; \ memset( Cp, 0, C.n * sizeof( mbedtls_mpi_uint ) ); \ \ MBEDTLS_MPI_CHK( mbedtls_mpi_grow( N, (b) * 2 / 8 / \ sizeof( mbedtls_mpi_uint ) ) ); \ LOAD32; #define NEXT \ STORE32; i++; LOAD32; \ cc = c; c = 0; \ if( cc < 0 ) \ sub32( &cur, -cc, &c ); \ else \ add32( &cur, cc, &c ); \ #define LAST \ STORE32; i++; \ cur = c > 0 ? c : 0; STORE32; \ cur = 0; while( ++i < MAX32 ) { STORE32; } \ if( c < 0 ) MBEDTLS_MPI_CHK( fix_negative( N, c, &C, bits ) ); /* * If the result is negative, we get it in the form * c * 2^(bits + 32) + N, with c negative and N positive shorter than 'bits' */ static inline int fix_negative( mbedtls_mpi *N, signed char c, mbedtls_mpi *C, size_t bits ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; /* C = - c * 2^(bits + 32) */ #if !defined(MBEDTLS_HAVE_INT64) ((void) bits); #else if( bits == 224 ) C->p[ C->n - 1 ] = ((mbedtls_mpi_uint) -c) << 32; else #endif C->p[ C->n - 1 ] = (mbedtls_mpi_uint) -c; /* N = - ( C - N ) */ MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( N, C, N ) ); N->s = -1; cleanup: return( ret ); } #if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) /* * Fast quasi-reduction modulo p224 (FIPS 186-3 D.2.2) */ static int ecp_mod_p224( mbedtls_mpi *N ) { INIT( 224 ); SUB( 7 ); SUB( 11 ); NEXT; // A0 += -A7 - A11 SUB( 8 ); SUB( 12 ); NEXT; // A1 += -A8 - A12 SUB( 9 ); SUB( 13 ); NEXT; // A2 += -A9 - A13 SUB( 10 ); ADD( 7 ); ADD( 11 ); NEXT; // A3 += -A10 + A7 + A11 SUB( 11 ); ADD( 8 ); ADD( 12 ); NEXT; // A4 += -A11 + A8 + A12 SUB( 12 ); ADD( 9 ); ADD( 13 ); NEXT; // A5 += -A12 + A9 + A13 SUB( 13 ); ADD( 10 ); LAST; // A6 += -A13 + A10 cleanup: return( ret ); } #endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) /* * Fast quasi-reduction modulo p256 (FIPS 186-3 D.2.3) */ int ecp_mod_p256_old( mbedtls_mpi *N ) { INIT( 256 ); ADD( 8 ); ADD( 9 ); SUB( 11 ); SUB( 12 ); SUB( 13 ); SUB( 14 ); NEXT; // A0 ADD( 9 ); ADD( 10 ); SUB( 12 ); SUB( 13 ); SUB( 14 ); SUB( 15 ); NEXT; // A1 ADD( 10 ); ADD( 11 ); SUB( 13 ); SUB( 14 ); SUB( 15 ); NEXT; // A2 ADD( 11 ); ADD( 11 ); ADD( 12 ); ADD( 12 ); ADD( 13 ); SUB( 15 ); SUB( 8 ); SUB( 9 ); NEXT; // A3 ADD( 12 ); ADD( 12 ); ADD( 13 ); ADD( 13 ); ADD( 14 ); SUB( 9 ); SUB( 10 ); NEXT; // A4 ADD( 13 ); ADD( 13 ); ADD( 14 ); ADD( 14 ); ADD( 15 ); SUB( 10 ); SUB( 11 ); NEXT; // A5 ADD( 14 ); ADD( 14 ); ADD( 15 ); ADD( 15 ); ADD( 14 ); ADD( 13 ); SUB( 8 ); SUB( 9 ); NEXT; // A6 ADD( 15 ); ADD( 15 ); ADD( 15 ); ADD( 8 ); SUB( 10 ); SUB( 11 ); SUB( 12 ); SUB( 13 ); LAST; // A7 cleanup: return( ret ); } #endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) /* * Fast quasi-reduction modulo p384 (FIPS 186-3 D.2.4) */ int ecp_mod_p384_old( mbedtls_mpi *N ) { INIT( 384 ); ADD( 12 ); ADD( 21 ); ADD( 20 ); SUB( 23 ); NEXT; // A0 ADD( 13 ); ADD( 22 ); ADD( 23 ); SUB( 12 ); SUB( 20 ); NEXT; // A2 ADD( 14 ); ADD( 23 ); SUB( 13 ); SUB( 21 ); NEXT; // A2 ADD( 15 ); ADD( 12 ); ADD( 20 ); ADD( 21 ); SUB( 14 ); SUB( 22 ); SUB( 23 ); NEXT; // A3 ADD( 21 ); ADD( 21 ); ADD( 16 ); ADD( 13 ); ADD( 12 ); ADD( 20 ); ADD( 22 ); SUB( 15 ); SUB( 23 ); SUB( 23 ); NEXT; // A4 ADD( 22 ); ADD( 22 ); ADD( 17 ); ADD( 14 ); ADD( 13 ); ADD( 21 ); ADD( 23 ); SUB( 16 ); NEXT; // A5 ADD( 23 ); ADD( 23 ); ADD( 18 ); ADD( 15 ); ADD( 14 ); ADD( 22 ); SUB( 17 ); NEXT; // A6 ADD( 19 ); ADD( 16 ); ADD( 15 ); ADD( 23 ); SUB( 18 ); NEXT; // A7 ADD( 20 ); ADD( 17 ); ADD( 16 ); SUB( 19 ); NEXT; // A8 ADD( 21 ); ADD( 18 ); ADD( 17 ); SUB( 20 ); NEXT; // A9 ADD( 22 ); ADD( 19 ); ADD( 18 ); SUB( 21 ); NEXT; // A10 ADD( 23 ); ADD( 20 ); ADD( 19 ); SUB( 22 ); LAST; // A11 cleanup: return( ret ); } #endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */ #undef A #undef LOAD32 #undef STORE32 #undef MAX32 #undef INIT #undef NEXT #undef LAST #endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED || MBEDTLS_ECP_DP_SECP256R1_ENABLED || MBEDTLS_ECP_DP_SECP384R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) /* * Here we have an actual Mersenne prime, so things are more straightforward. * However, chunks are aligned on a 'weird' boundary (521 bits). */ /* Size of p521 in terms of mbedtls_mpi_uint */ #define P521_WIDTH ( 521 / 8 / sizeof( mbedtls_mpi_uint ) + 1 ) /* Bits to keep in the most significant mbedtls_mpi_uint */ #define P521_MASK 0x01FF /* * Fast quasi-reduction modulo p521 (FIPS 186-3 D.2.5) * Write N as A1 + 2^521 A0, return A0 + A1 */ static int ecp_mod_p521( mbedtls_mpi *N ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t i; mbedtls_mpi M; mbedtls_mpi_uint Mp[P521_WIDTH + 1]; /* Worst case for the size of M is when mbedtls_mpi_uint is 16 bits: * we need to hold bits 513 to 1056, which is 34 limbs, that is * P521_WIDTH + 1. Otherwise P521_WIDTH is enough. */ if( N->n < P521_WIDTH ) return( 0 ); /* M = A1 */ M.s = 1; M.n = N->n - ( P521_WIDTH - 1 ); if( M.n > P521_WIDTH + 1 ) M.n = P521_WIDTH + 1; M.p = Mp; memcpy( Mp, N->p + P521_WIDTH - 1, M.n * sizeof( mbedtls_mpi_uint ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &M, 521 % ( 8 * sizeof( mbedtls_mpi_uint ) ) ) ); /* N = A0 */ N->p[P521_WIDTH - 1] &= P521_MASK; for( i = P521_WIDTH; i < N->n; i++ ) N->p[i] = 0; /* N = A0 + A1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_add_abs( N, N, &M ) ); cleanup: return( ret ); } #undef P521_WIDTH #undef P521_MASK #endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */ #endif /* MBEDTLS_ECP_NIST_OPTIM */ #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) /* Size of p255 in terms of mbedtls_mpi_uint */ #define P255_WIDTH ( 255 / 8 / sizeof( mbedtls_mpi_uint ) + 1 ) /* * Fast quasi-reduction modulo p255 = 2^255 - 19 * Write N as A0 + 2^255 A1, return A0 + 19 * A1 */ static int ecp_mod_p255( mbedtls_mpi *N ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t i; mbedtls_mpi M; mbedtls_mpi_uint Mp[P255_WIDTH + 2]; if( N->n < P255_WIDTH ) return( 0 ); /* M = A1 */ M.s = 1; M.n = N->n - ( P255_WIDTH - 1 ); if( M.n > P255_WIDTH + 1 ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); M.p = Mp; memset( Mp, 0, sizeof Mp ); memcpy( Mp, N->p + P255_WIDTH - 1, M.n * sizeof( mbedtls_mpi_uint ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &M, 255 % ( 8 * sizeof( mbedtls_mpi_uint ) ) ) ); M.n++; /* Make room for multiplication by 19 */ /* N = A0 */ MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( N, 255, 0 ) ); for( i = P255_WIDTH; i < N->n; i++ ) N->p[i] = 0; /* N = A0 + 19 * A1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &M, &M, 19 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_abs( N, N, &M ) ); cleanup: return( ret ); } #endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */ #if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) /* Size of p448 in terms of mbedtls_mpi_uint */ #define P448_WIDTH ( 448 / 8 / sizeof( mbedtls_mpi_uint ) ) /* Number of limbs fully occupied by 2^224 (max), and limbs used by it (min) */ #define DIV_ROUND_UP( X, Y ) ( ( ( X ) + ( Y ) - 1 ) / ( Y ) ) #define P224_WIDTH_MIN ( 28 / sizeof( mbedtls_mpi_uint ) ) #define P224_WIDTH_MAX DIV_ROUND_UP( 28, sizeof( mbedtls_mpi_uint ) ) #define P224_UNUSED_BITS ( ( P224_WIDTH_MAX * sizeof( mbedtls_mpi_uint ) * 8 ) - 224 ) /* * Fast quasi-reduction modulo p448 = 2^448 - 2^224 - 1 * Write N as A0 + 2^448 A1 and A1 as B0 + 2^224 B1, and return * A0 + A1 + B1 + (B0 + B1) * 2^224. This is different to the reference * implementation of Curve448, which uses its own special 56-bit limbs rather * than a generic bignum library. We could squeeze some extra speed out on * 32-bit machines by splitting N up into 32-bit limbs and doing the * arithmetic using the limbs directly as we do for the NIST primes above, * but for 64-bit targets it should use half the number of operations if we do * the reduction with 224-bit limbs, since mpi_add_mpi will then use 64-bit adds. */ static int ecp_mod_p448( mbedtls_mpi *N ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t i; mbedtls_mpi M, Q; mbedtls_mpi_uint Mp[P448_WIDTH + 1], Qp[P448_WIDTH]; if( N->n <= P448_WIDTH ) return( 0 ); /* M = A1 */ M.s = 1; M.n = N->n - ( P448_WIDTH ); if( M.n > P448_WIDTH ) /* Shouldn't be called with N larger than 2^896! */ return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); M.p = Mp; memset( Mp, 0, sizeof( Mp ) ); memcpy( Mp, N->p + P448_WIDTH, M.n * sizeof( mbedtls_mpi_uint ) ); /* N = A0 */ for( i = P448_WIDTH; i < N->n; i++ ) N->p[i] = 0; /* N += A1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( N, N, &M ) ); /* Q = B1, N += B1 */ Q = M; Q.p = Qp; memcpy( Qp, Mp, sizeof( Qp ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &Q, 224 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( N, N, &Q ) ); /* M = (B0 + B1) * 2^224, N += M */ if( sizeof( mbedtls_mpi_uint ) > 4 ) Mp[P224_WIDTH_MIN] &= ( (mbedtls_mpi_uint)-1 ) >> ( P224_UNUSED_BITS ); for( i = P224_WIDTH_MAX; i < M.n; ++i ) Mp[i] = 0; MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &M, &M, &Q ) ); M.n = P448_WIDTH + 1; /* Make room for shifted carry bit from the addition */ MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &M, 224 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( N, N, &M ) ); cleanup: return( ret ); } #endif /* MBEDTLS_ECP_DP_CURVE448_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) /* * Fast quasi-reduction modulo P = 2^s - R, * with R about 33 bits, used by the Koblitz curves. * * Write N as A0 + 2^224 A1, return A0 + R * A1. * Actually do two passes, since R is big. */ #define P_KOBLITZ_MAX ( 256 / 8 / sizeof( mbedtls_mpi_uint ) ) // Max limbs in P #define P_KOBLITZ_R ( 8 / sizeof( mbedtls_mpi_uint ) ) // Limbs in R static inline int ecp_mod_koblitz( mbedtls_mpi *N, mbedtls_mpi_uint *Rp, size_t p_limbs, size_t adjust, size_t shift, mbedtls_mpi_uint mask ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t i; mbedtls_mpi M, R; mbedtls_mpi_uint Mp[P_KOBLITZ_MAX + P_KOBLITZ_R + 1]; if( N->n < p_limbs ) return( 0 ); /* Init R */ R.s = 1; R.p = Rp; R.n = P_KOBLITZ_R; /* Common setup for M */ M.s = 1; M.p = Mp; /* M = A1 */ M.n = N->n - ( p_limbs - adjust ); if( M.n > p_limbs + adjust ) M.n = p_limbs + adjust; memset( Mp, 0, sizeof Mp ); memcpy( Mp, N->p + p_limbs - adjust, M.n * sizeof( mbedtls_mpi_uint ) ); if( shift != 0 ) MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &M, shift ) ); M.n += R.n; /* Make room for multiplication by R */ /* N = A0 */ if( mask != 0 ) N->p[p_limbs - 1] &= mask; for( i = p_limbs; i < N->n; i++ ) N->p[i] = 0; /* N = A0 + R * A1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &M, &M, &R ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_abs( N, N, &M ) ); /* Second pass */ /* M = A1 */ M.n = N->n - ( p_limbs - adjust ); if( M.n > p_limbs + adjust ) M.n = p_limbs + adjust; memset( Mp, 0, sizeof Mp ); memcpy( Mp, N->p + p_limbs - adjust, M.n * sizeof( mbedtls_mpi_uint ) ); if( shift != 0 ) MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &M, shift ) ); M.n += R.n; /* Make room for multiplication by R */ /* N = A0 */ if( mask != 0 ) N->p[p_limbs - 1] &= mask; for( i = p_limbs; i < N->n; i++ ) N->p[i] = 0; /* N = A0 + R * A1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &M, &M, &R ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_abs( N, N, &M ) ); cleanup: return( ret ); } #endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED) || MBEDTLS_ECP_DP_SECP224K1_ENABLED) || MBEDTLS_ECP_DP_SECP256K1_ENABLED) */ #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) /* * Fast quasi-reduction modulo p192k1 = 2^192 - R, * with R = 2^32 + 2^12 + 2^8 + 2^7 + 2^6 + 2^3 + 1 = 0x0100001119 */ static int ecp_mod_p192k1( mbedtls_mpi *N ) { static mbedtls_mpi_uint Rp[] = { BYTES_TO_T_UINT_8( 0xC9, 0x11, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 ) }; return( ecp_mod_koblitz( N, Rp, 192 / 8 / sizeof( mbedtls_mpi_uint ), 0, 0, 0 ) ); } #endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) /* * Fast quasi-reduction modulo p224k1 = 2^224 - R, * with R = 2^32 + 2^12 + 2^11 + 2^9 + 2^7 + 2^4 + 2 + 1 = 0x0100001A93 */ static int ecp_mod_p224k1( mbedtls_mpi *N ) { static mbedtls_mpi_uint Rp[] = { BYTES_TO_T_UINT_8( 0x93, 0x1A, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 ) }; #if defined(MBEDTLS_HAVE_INT64) return( ecp_mod_koblitz( N, Rp, 4, 1, 32, 0xFFFFFFFF ) ); #else return( ecp_mod_koblitz( N, Rp, 224 / 8 / sizeof( mbedtls_mpi_uint ), 0, 0, 0 ) ); #endif } #endif /* MBEDTLS_ECP_DP_SECP224K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) /* * Fast quasi-reduction modulo p256k1 = 2^256 - R, * with R = 2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1 = 0x01000003D1 */ static int ecp_mod_p256k1( mbedtls_mpi *N ) { static mbedtls_mpi_uint Rp[] = { BYTES_TO_T_UINT_8( 0xD1, 0x03, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 ) }; return( ecp_mod_koblitz( N, Rp, 256 / 8 / sizeof( mbedtls_mpi_uint ), 0, 0, 0 ) ); } #endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */ #endif /* !MBEDTLS_ECP_ALT */ #endif /* MBEDTLS_ECP_C */
61,168
1,509
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/rsa_internal.h
#ifndef MBEDTLS_RSA_INTERNAL_H #define MBEDTLS_RSA_INTERNAL_H #include "third_party/mbedtls/bignum.h" #include "third_party/mbedtls/config.h" /* clang-format off */ #ifdef __cplusplus extern "C" { #endif /** * \brief Compute RSA prime moduli P, Q from public modulus N=PQ * and a pair of private and public key. * * \note This is a 'static' helper function not operating on * an RSA context. Alternative implementations need not * overwrite it. * * \param N RSA modulus N = PQ, with P, Q to be found * \param E RSA public exponent * \param D RSA private exponent * \param P Pointer to MPI holding first prime factor of N on success * \param Q Pointer to MPI holding second prime factor of N on success * * \return * - 0 if successful. In this case, P and Q constitute a * factorization of N. * - A non-zero error code otherwise. * * \note It is neither checked that P, Q are prime nor that * D, E are modular inverses wrt. P-1 and Q-1. For that, * use the helper function \c mbedtls_rsa_validate_params. * */ int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N, mbedtls_mpi const *E, mbedtls_mpi const *D, mbedtls_mpi *P, mbedtls_mpi *Q ); /** * \brief Compute RSA private exponent from * prime moduli and public key. * * \note This is a 'static' helper function not operating on * an RSA context. Alternative implementations need not * overwrite it. * * \param P First prime factor of RSA modulus * \param Q Second prime factor of RSA modulus * \param E RSA public exponent * \param D Pointer to MPI holding the private exponent on success. * * \return * - 0 if successful. In this case, D is set to a simultaneous * modular inverse of E modulo both P-1 and Q-1. * - A non-zero error code otherwise. * * \note This function does not check whether P and Q are primes. * */ int mbedtls_rsa_deduce_private_exponent( mbedtls_mpi const *P, mbedtls_mpi const *Q, mbedtls_mpi const *E, mbedtls_mpi *D ); /** * \brief Generate RSA-CRT parameters * * \note This is a 'static' helper function not operating on * an RSA context. Alternative implementations need not * overwrite it. * * \param P First prime factor of N * \param Q Second prime factor of N * \param D RSA private exponent * \param DP Output variable for D modulo P-1 * \param DQ Output variable for D modulo Q-1 * \param QP Output variable for the modular inverse of Q modulo P. * * \return 0 on success, non-zero error code otherwise. * * \note This function does not check whether P, Q are * prime and whether D is a valid private exponent. * */ int mbedtls_rsa_deduce_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q, const mbedtls_mpi *D, mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP ); /** * \brief Check validity of core RSA parameters * * \note This is a 'static' helper function not operating on * an RSA context. Alternative implementations need not * overwrite it. * * \param N RSA modulus N = PQ * \param P First prime factor of N * \param Q Second prime factor of N * \param D RSA private exponent * \param E RSA public exponent * \param f_rng PRNG to be used for primality check, or NULL * \param p_rng PRNG context for f_rng, or NULL * * \return * - 0 if the following conditions are satisfied * if all relevant parameters are provided: * - P prime if f_rng != NULL (%) * - Q prime if f_rng != NULL (%) * - 1 < N = P * Q * - 1 < D, E < N * - D and E are modular inverses modulo P-1 and Q-1 * (%) This is only done if MBEDTLS_GENPRIME is defined. * - A non-zero error code otherwise. * * \note The function can be used with a restricted set of arguments * to perform specific checks only. E.g., calling it with * (-,P,-,-,-) and a PRNG amounts to a primality check for P. */ int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P, const mbedtls_mpi *Q, const mbedtls_mpi *D, const mbedtls_mpi *E, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief Check validity of RSA CRT parameters * * \note This is a 'static' helper function not operating on * an RSA context. Alternative implementations need not * overwrite it. * * \param P First prime factor of RSA modulus * \param Q Second prime factor of RSA modulus * \param D RSA private exponent * \param DP MPI to check for D modulo P-1 * \param DQ MPI to check for D modulo P-1 * \param QP MPI to check for the modular inverse of Q modulo P. * * \return * - 0 if the following conditions are satisfied: * - D = DP mod P-1 if P, D, DP != NULL * - Q = DQ mod P-1 if P, D, DQ != NULL * - QP = Q^-1 mod P if P, Q, QP != NULL * - \c MBEDTLS_ERR_RSA_KEY_CHECK_FAILED if check failed, * potentially including \c MBEDTLS_ERR_MPI_XXX if some * MPI calculations failed. * - \c MBEDTLS_ERR_RSA_BAD_INPUT_DATA if insufficient * data was provided to check DP, DQ or QP. * * \note The function can be used with a restricted set of arguments * to perform specific checks only. E.g., calling it with the * parameters (P, -, D, DP, -, -) will check DP = D mod P-1. */ int mbedtls_rsa_validate_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q, const mbedtls_mpi *D, const mbedtls_mpi *DP, const mbedtls_mpi *DQ, const mbedtls_mpi *QP ); #ifdef __cplusplus } #endif #endif /* rsa_internal.h */
6,766
166
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/secp256r1.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/check.h" #include "third_party/mbedtls/bignum.h" #include "third_party/mbedtls/math.h" #include "third_party/mbedtls/platform.h" #define Q(i) p[i >> 1] #define L(w) (w & 0x00000000ffffffff) #define H(w) (w & 0xffffffff00000000) /** * Fastest quasi-reduction modulo ℘256. * * p = 2²⁵⁶ - 2²²⁴ + 2¹⁹² + 2⁹⁶ - 1 * B = T + 2×S₁ + 2×S₂ + S₃ + S₄ – D₁ – D₂ – D₃ – D₄ mod p * T = ( A₇ ‖ A₆ ‖ A₅ ‖ A₄ ‖ A₃ ‖ A₂ ‖ A₁ ‖ A₀ ) * S₁ = ( A₁₅ ‖ A₁₄ ‖ A₁₃ ‖ A₁₂ ‖ A₁₁ ‖ 0 ‖ 0 ‖ 0 ) * S₂ = ( 0 ‖ A₁₅ ‖ A₁₄‖ A₁₃ ‖ A₁₂ ‖ 0 ‖ 0 ‖ 0 ) * S₃ = ( A₁₅ ‖ A₁₄ ‖ 0 ‖ 0 ‖ 0 ‖ A₁₀ ‖ A₉ ‖ A₈ ) * S₄ = ( A₈ ‖ A₁₃ ‖ A₁₅ ‖ A₁₄ ‖ A₁₃ ‖ A₁₁ ‖ A₁₀ ‖ A₉ ) * D₁ = ( A₁₀ ‖ A₈ ‖ 0 ‖ 0 ‖ 0 ‖ A₁₃ ‖ A₁₂ ‖ A₁₁ ) * D₂ = ( A₁₁ ‖ A₉ ‖ 0 ‖ 0 ‖ A₁₅ ‖ A₁₄ ‖ A₁₃ ‖ A₁₂ ) * D₃ = ( A₁₂ ‖ 0 ‖ A₁₀ ‖ A₉ ‖ A₈ ‖ A₁₅ ‖ A₁₄ ‖ A₁₃ ) * D₄ = ( A₁₃ ‖ 0 ‖ A₁₁ ‖ A₁₀ ‖ A₉ ‖ 0 ‖ A₁₅ ‖ A₁₄ ) * * @see FIPS 186-3 §D.2.3 */ void secp256r1(uint64_t p[8]) { int r; char o; signed char E; uint64_t A, B, C, D, a, b, c, d, e; A = Q(0); B = Q(2); C = Q(4); D = Q(6); E = 0; #if !defined(__x86_64__) || defined(__STRICT_ANSI__) ADC(B, B, H(Q(10)) << 1, 0, o); ADC(C, C, Q(12) << 1 | Q(10) >> 63, o, o); ADC(D, D, Q(14) << 1 | Q(12) >> 63, o, o); E += o + (Q(14) >> 63); ADC(B, B, Q(12) << 33, 0, o); ADC(C, C, Q(14) << 33 | Q(12) >> 31, o, o); ADC(D, D, Q(14) >> 31, o, o); E += o; ADC(A, A, Q(8), 0, o); ADC(B, B, L(Q(10)), o, o); ADC(C, C, 0, o, o); ADC(D, D, Q(14), o, o); E += o; ADC(A, A, Q(10) << 32 | Q(8) >> 32, 0, o); ADC(B, B, H(Q(12)) | Q(10) >> 32, o, o); ADC(C, C, Q(14), o, o); ADC(D, D, Q(8) << 32 | Q(12) >> 32, o, o); E += o; SBB(A, A, Q(12) << 32 | Q(10) >> 32, 0, o); SBB(B, B, Q(12) >> 32, o, o); SBB(C, C, 0, o, o); SBB(D, D, Q(10) << 32 | L(Q(8)), o, o); E -= o; SBB(A, A, Q(12), 0, o); SBB(B, B, Q(14), o, o); SBB(C, C, 0, o, o); SBB(D, D, H(Q(10)) | Q(8) >> 32, o, o); E -= o; SBB(A, A, Q(14) << 32 | Q(12) >> 32, 0, o); SBB(B, B, Q(8) << 32 | Q(14) >> 32, o, o); SBB(C, C, Q(10) << 32 | Q(8) >> 32, o, o); SBB(D, D, Q(12) << 32, o, o); E -= o; SBB(A, A, Q(14), 0, o); SBB(B, B, H(Q(8)), o, o); SBB(C, C, Q(10), o, o); SBB(D, D, H(Q(12)), o, o); E -= o; #else asm volatile(/* x += 2 × ( A₁₅ ‖ A₁₄ ‖ A₁₃ ‖ A₁₂ ‖ A₁₁ ‖ 0 ‖ 0 ‖ 0 ) */ "mov\t11*4(%8),%k5\n\t" "mov\t12*4(%8),%6\n\t" "mov\t14*4(%8),%7\n\t" "shl\t$33,%5\n\t" "rcl\t%6\n\t" "rcl\t%7\n\t" "adc\t$0,%b4\n\t" "add\t%5,%1\n\t" "adc\t%6,%2\n\t" "adc\t%7,%3\n\t" "adc\t$0,%b4\n\t" /* x += 2 × ( 0 ‖ A₁₅ ‖ A₁₄‖ A₁₃ ‖ A₁₂ ‖ 0 ‖ 0 ‖ 0 ) */ "mov\t12*4(%8),%k5\n\t" "mov\t13*4(%8),%6\n\t" "mov\t15*4(%8),%k7\n\t" "shl\t$33,%5\n\t" "rcl\t%6\n\t" "rcl\t%7\n\t" "add\t%5,%1\n\t" "adc\t%6,%2\n\t" "adc\t%7,%3\n\t" /* x += ( A₁₅ ‖ A₁₄ ‖ 0 ‖ 0 ‖ 0 ‖ A₁₀ ‖ A₉ ‖ A₈ ) */ "mov\t10*4(%8),%k5\n\t" "add\t8*4(%8),%0\n\t" "adc\t%5,%1\n\t" "adc\t$0,%2\n\t" "adc\t14*4(%8),%3\n\t" "adc\t$0,%b4\n\t" /* x += ( A₈ ‖ A₁₃ ‖ A₁₅ ‖ A₁₄ ‖ A₁₃ ‖ A₁₁ ‖ A₁₀ ‖ A₉ ) */ "mov\t8*4(%8),%k7\n\t" /* A₈ ‖ A₁₃ */ "mov\t13*4(%8),%k5\n\t" /* ... */ "shl\t$32,%7\n\t" /* ... */ "or\t%5,%7\n\t" /* ... */ "shl\t$32,%5\n\t" /* A₁₃ ‖ A₁₁ */ "mov\t11*4(%8),%k6\n\t" /* ... */ "or\t%6,%5\n\t" /* ... */ "add\t9*4(%8),%0\n\t" /* A₁₀ ‖ A₉ */ "adc\t%5,%1\n\t" /* ... */ "adc\t14*4(%8),%2\n\t" /* A₁₅ ‖ A₁₄ */ "adc\t%7,%3\n\t" "adc\t$0,%b4\n\t" /* x -= ( A₁₀ ‖ A₈ ‖ 0 ‖ 0 ‖ 0 ‖ A₁₃ ‖ A₁₂ ‖ A₁₁ ) */ "mov\t10*4(%8),%k6\n\t" "mov\t8*4(%8),%k7\n\t" "shl\t$32,%6\n\t" "or\t%6,%7\n\t" "mov\t13*4(%8),%k5\n\t" "sub\t11*4(%8),%0\n\t" "sbb\t%5,%1\n\t" "sbb\t$0,%2\n\t" "sbb\t%7,%3\n\t" "sbb\t$0,%b4\n\t" /* x -= ( A₁₁ ‖ A₉ ‖ 0 ‖ 0 ‖ A₁₅ ‖ A₁₄ ‖ A₁₃ ‖ A₁₂ ) */ "mov\t11*4(%8),%k6\n\t" "mov\t9*4(%8),%k7\n\t" "shl\t$32,%6\n\t" "or\t%6,%7\n\t" "sub\t12*4(%8),%0\n\t" "sbb\t14*4(%8),%1\n\t" "sbb\t$0,%2\n\t" "sbb\t%7,%3\n\t" "sbb\t$0,%b4\n\t" /* x -= ( A₁₂ ‖ 0 ‖ A₁₀ ‖ A₉ ‖ A₈ ‖ A₁₅ ‖ A₁₄ ‖ A₁₃ ) */ "mov\t12*4(%8),%k7\n\t" "shl\t$32,%7\n\t" "mov\t15*4(%8),%k6\n\t" "mov\t8*4(%8),%k5\n\t" "shl\t$32,%5\n\t" "or\t%5,%6\n\t" "sub\t13*4(%8),%0\n\t" "sbb\t%6,%1\n\t" "sbb\t9*4(%8),%2\n\t" "sbb\t%7,%3\n\t" "sbb\t$0,%b4\n\t" /* x -= ( A₁₃ ‖ 0 ‖ A₁₁ ‖ A₁₀ ‖ A₉ ‖ 0 ‖ A₁₅ ‖ A₁₄ ) */ "mov\t9*4(%8),%k6\n\t" "shl\t$32,%6\n\t" "mov\t13*4(%8),%k5\n\t" "shl\t$32,%5\n\t" "sub\t14*4(%8),%0\n\t" "sbb\t%6,%1\n\t" "sbb\t10*4(%8),%2\n\t" "sbb\t%5,%3\n\t" "sbb\t$0,%b4\n\t" : "+r"(A), "+r"(B), "+r"(C), "+r"(D), "+&q"(E), "=&r"(b), "=&r"(c), "=&r"(d) : "r"(p) : "memory"); #endif p[0] = A; p[1] = B; p[2] = C; p[3] = D; p[4] = E; p[5] = 0; p[6] = 0; p[7] = 0; } int ecp_mod_p256(mbedtls_mpi *N) { int r; char o; if (N->n < 8 && (r = mbedtls_mpi_grow(N, 8))) return r; secp256r1(N->p); if ((int64_t)N->p[4] < 0) { N->s = -1; SBB(N->p[0], 0, N->p[0], 0, o); SBB(N->p[1], 0, N->p[1], o, o); SBB(N->p[2], 0, N->p[2], o, o); SBB(N->p[3], 0, N->p[3], o, o); N->p[4] = 0 - (N->p[4] + o); } else { N->s = 1; } return 0; }
8,959
212
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/san.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/bits.h" #include "libc/sock/sock.h" #include "libc/sysv/consts/af.h" #include "third_party/mbedtls/asn1.h" #include "third_party/mbedtls/asn1write.h" #include "third_party/mbedtls/oid.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/san.h" #include "third_party/mbedtls/x509_crt.h" /** * Writes Subject Alternative Name section to certificate. * * @see RFC5280 §4.2.1.6 */ int mbedtls_x509write_crt_set_subject_alternative_name( mbedtls_x509write_cert *ctx, const struct mbedtls_san *san, size_t sanlen) { int ret, a, b, c; size_t i, len, cap, itemlen; unsigned char *pc, *buf, *item, ip4[4]; if (!sanlen) return 0; cap = sanlen * (253 + 5 + 1) + 5 + 1; if (!(buf = mbedtls_calloc(1, cap))) return MBEDTLS_ERR_ASN1_ALLOC_FAILED; pc = buf + cap; len = 0; for (i = sanlen; i--;) { switch (san[i].tag) { case MBEDTLS_X509_SAN_RFC822_NAME: case MBEDTLS_X509_SAN_DNS_NAME: case MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER: item = (const unsigned char *)san[i].val; itemlen = strlen(san[i].val); break; case MBEDTLS_X509_SAN_IP_ADDRESS: WRITE32BE(ip4, san[i].ip4); item = ip4; itemlen = 4; break; default: ret = MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE; goto finish; } if (itemlen > 253) { ret = MBEDTLS_ERR_ASN1_INVALID_LENGTH; goto finish; } ret = mbedtls_asn1_write_raw_buffer(&pc, buf, item, itemlen); if (ret < 0) goto finish; len += ret; ret = mbedtls_asn1_write_len(&pc, buf, itemlen); if (ret < 0) goto finish; len += ret; ret = mbedtls_asn1_write_tag(&pc, buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | san[i].tag); if (ret < 0) goto finish; len += ret; } ret = mbedtls_asn1_write_len(&pc, buf, len); if (ret < 0) goto finish; len += ret; ret = mbedtls_asn1_write_tag( &pc, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); if (ret < 0) goto finish; len += ret; ret = mbedtls_x509write_crt_set_extension( ctx, MBEDTLS_OID_SUBJECT_ALT_NAME, MBEDTLS_OID_SIZE(MBEDTLS_OID_SUBJECT_ALT_NAME), 0, buf + cap - len, len); finish: mbedtls_free(buf); return ret; }
4,100
90
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/error.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/fmt/fmt.h" #include "libc/str/str.h" #include "third_party/mbedtls/aes.h" #include "third_party/mbedtls/asn1.h" #include "third_party/mbedtls/base64.h" #include "third_party/mbedtls/bignum.h" #include "third_party/mbedtls/ccm.h" #include "third_party/mbedtls/chacha20.h" #include "third_party/mbedtls/chachapoly.h" #include "third_party/mbedtls/cipher.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/ctr_drbg.h" #include "third_party/mbedtls/des.h" #include "third_party/mbedtls/dhm.h" #include "third_party/mbedtls/ecp.h" #include "third_party/mbedtls/entropy.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/gcm.h" #include "third_party/mbedtls/hkdf.h" #include "third_party/mbedtls/hmac_drbg.h" #include "third_party/mbedtls/md.h" #include "third_party/mbedtls/md5.h" #include "third_party/mbedtls/oid.h" #include "third_party/mbedtls/pem.h" #include "third_party/mbedtls/pk.h" #include "third_party/mbedtls/pkcs5.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/poly1305.h" #include "third_party/mbedtls/rsa.h" #include "third_party/mbedtls/sha1.h" #include "third_party/mbedtls/sha256.h" #include "third_party/mbedtls/sha512.h" #include "third_party/mbedtls/ssl.h" #include "third_party/mbedtls/x509.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /* * Error message information * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(MBEDTLS_ERROR_C) || defined(MBEDTLS_ERROR_STRERROR_DUMMY) #if defined(MBEDTLS_ERROR_C) const char * mbedtls_high_level_strerr( int error_code ) { int high_level_error_code; if( error_code < 0 ) error_code = -error_code; /* Extract the high-level part from the error code. */ high_level_error_code = error_code & 0xFF80; switch( high_level_error_code ) { /* Begin Auto-Generated Code. */ #if defined(MBEDTLS_CIPHER_C) case -(MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE): return( "CIPHER - The selected feature is not available" ); case -(MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA): return( "CIPHER - Bad input parameters" ); case -(MBEDTLS_ERR_CIPHER_ALLOC_FAILED): return( "CIPHER - Failed to allocate memory" ); case -(MBEDTLS_ERR_CIPHER_INVALID_PADDING): return( "CIPHER - Input data contains invalid padding and is rejected" ); case -(MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED): return( "CIPHER - Decryption of block requires a full block" ); case -(MBEDTLS_ERR_CIPHER_AUTH_FAILED): return( "CIPHER - Authentication failed (for AEAD modes)" ); case -(MBEDTLS_ERR_CIPHER_INVALID_CONTEXT): return( "CIPHER - The context is invalid. For example, because it was freed" ); case -(MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED): return( "CIPHER - Cipher hardware accelerator failed" ); #endif /* MBEDTLS_CIPHER_C */ #if defined(MBEDTLS_DHM_C) case -(MBEDTLS_ERR_DHM_BAD_INPUT_DATA): return( "DHM - Bad input parameters" ); case -(MBEDTLS_ERR_DHM_READ_PARAMS_FAILED): return( "DHM - Reading of the DHM parameters failed" ); case -(MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED): return( "DHM - Making of the DHM parameters failed" ); case -(MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED): return( "DHM - Reading of the public values failed" ); case -(MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED): return( "DHM - Making of the public value failed" ); case -(MBEDTLS_ERR_DHM_CALC_SECRET_FAILED): return( "DHM - Calculation of the DHM secret failed" ); case -(MBEDTLS_ERR_DHM_INVALID_FORMAT): return( "DHM - The ASN.1 data is not formatted correctly" ); case -(MBEDTLS_ERR_DHM_ALLOC_FAILED): return( "DHM - Allocation of memory failed" ); case -(MBEDTLS_ERR_DHM_FILE_IO_ERROR): return( "DHM - Read or write of file failed" ); case -(MBEDTLS_ERR_DHM_HW_ACCEL_FAILED): return( "DHM - DHM hardware accelerator failed" ); case -(MBEDTLS_ERR_DHM_SET_GROUP_FAILED): return( "DHM - Setting the modulus and generator failed" ); #endif /* MBEDTLS_DHM_C */ #if defined(MBEDTLS_ECP_C) case -(MBEDTLS_ERR_ECP_BAD_INPUT_DATA): return( "ECP - Bad input parameters to function" ); case -(MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL): return( "ECP - The buffer is too small to write to" ); case -(MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE): return( "ECP - The requested feature is not available, for example, the requested curve is not supported" ); case -(MBEDTLS_ERR_ECP_VERIFY_FAILED): return( "ECP - The signature is not valid" ); case -(MBEDTLS_ERR_ECP_ALLOC_FAILED): return( "ECP - Memory allocation failed" ); case -(MBEDTLS_ERR_ECP_RANDOM_FAILED): return( "ECP - Generation of random value, such as ephemeral key, failed" ); case -(MBEDTLS_ERR_ECP_INVALID_KEY): return( "ECP - Invalid private or public key" ); case -(MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH): return( "ECP - The buffer contains a valid signature followed by more data" ); case -(MBEDTLS_ERR_ECP_HW_ACCEL_FAILED): return( "ECP - The ECP hardware accelerator failed" ); case -(MBEDTLS_ERR_ECP_IN_PROGRESS): return( "ECP - Operation in progress, call again with the same parameters to continue" ); #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_MD_C) case -(MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE): return( "MD - The selected feature is not available" ); case -(MBEDTLS_ERR_MD_BAD_INPUT_DATA): return( "MD - Bad input parameters to function" ); case -(MBEDTLS_ERR_MD_ALLOC_FAILED): return( "MD - Failed to allocate memory" ); case -(MBEDTLS_ERR_MD_FILE_IO_ERROR): return( "MD - Opening or reading of file failed" ); case -(MBEDTLS_ERR_MD_HW_ACCEL_FAILED): return( "MD - MD hardware accelerator failed" ); #endif /* MBEDTLS_MD_C */ #if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C) case -(MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT): return( "PEM - No PEM header or footer found" ); case -(MBEDTLS_ERR_PEM_INVALID_DATA): return( "PEM - PEM string is not as expected" ); case -(MBEDTLS_ERR_PEM_ALLOC_FAILED): return( "PEM - Failed to allocate memory" ); case -(MBEDTLS_ERR_PEM_INVALID_ENC_IV): return( "PEM - RSA IV is not in hex-format" ); case -(MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG): return( "PEM - Unsupported key encryption algorithm" ); case -(MBEDTLS_ERR_PEM_PASSWORD_REQUIRED): return( "PEM - Private key password can't be empty" ); case -(MBEDTLS_ERR_PEM_PASSWORD_MISMATCH): return( "PEM - Given private key password does not allow for correct decryption" ); case -(MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE): return( "PEM - Unavailable feature, e.g. hashing/encryption combination" ); case -(MBEDTLS_ERR_PEM_BAD_INPUT_DATA): return( "PEM - Bad input parameters to function" ); #endif /* MBEDTLS_PEM_PARSE_C || MBEDTLS_PEM_WRITE_C */ #if defined(MBEDTLS_PK_C) case -(MBEDTLS_ERR_PK_ALLOC_FAILED): return( "PK - Memory allocation failed" ); case -(MBEDTLS_ERR_PK_TYPE_MISMATCH): return( "PK - Type mismatch, eg attempt to encrypt with an ECDSA key" ); case -(MBEDTLS_ERR_PK_BAD_INPUT_DATA): return( "PK - Bad input parameters to function" ); case -(MBEDTLS_ERR_PK_FILE_IO_ERROR): return( "PK - Read/write of file failed" ); case -(MBEDTLS_ERR_PK_KEY_INVALID_VERSION): return( "PK - Unsupported key version" ); case -(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT): return( "PK - Invalid key tag or value" ); case -(MBEDTLS_ERR_PK_UNKNOWN_PK_ALG): return( "PK - Key algorithm is unsupported (only RSA and EC are supported)" ); case -(MBEDTLS_ERR_PK_PASSWORD_REQUIRED): return( "PK - Private key password can't be empty" ); case -(MBEDTLS_ERR_PK_PASSWORD_MISMATCH): return( "PK - Given private key password does not allow for correct decryption" ); case -(MBEDTLS_ERR_PK_INVALID_PUBKEY): return( "PK - The pubkey tag or value is invalid (only RSA and EC are supported)" ); case -(MBEDTLS_ERR_PK_INVALID_ALG): return( "PK - The algorithm tag or value is invalid" ); case -(MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE): return( "PK - Elliptic curve is unsupported (only NIST curves are supported)" ); case -(MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE): return( "PK - Unavailable feature, e.g. RSA disabled for RSA key" ); case -(MBEDTLS_ERR_PK_SIG_LEN_MISMATCH): return( "PK - The buffer contains a valid signature followed by more data" ); case -(MBEDTLS_ERR_PK_HW_ACCEL_FAILED): return( "PK - PK hardware accelerator failed" ); #endif /* MBEDTLS_PK_C */ #if defined(MBEDTLS_PKCS5_C) case -(MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA): return( "PKCS5 - Bad input parameters to function" ); case -(MBEDTLS_ERR_PKCS5_INVALID_FORMAT): return( "PKCS5 - Unexpected ASN.1 data" ); case -(MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE): return( "PKCS5 - Requested encryption or digest alg not available" ); case -(MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH): return( "PKCS5 - Given private key password does not allow for correct decryption" ); #endif /* MBEDTLS_PKCS5_C */ #if defined(MBEDTLS_RSA_C) case -(MBEDTLS_ERR_RSA_BAD_INPUT_DATA): return( "RSA - Bad input parameters to function" ); case -(MBEDTLS_ERR_RSA_INVALID_PADDING): return( "RSA - Input data contains invalid padding and is rejected" ); case -(MBEDTLS_ERR_RSA_KEY_GEN_FAILED): return( "RSA - Something failed during generation of a key" ); case -(MBEDTLS_ERR_RSA_KEY_CHECK_FAILED): return( "RSA - Key failed to pass the validity check of the library" ); case -(MBEDTLS_ERR_RSA_PUBLIC_FAILED): return( "RSA - The public key operation failed" ); case -(MBEDTLS_ERR_RSA_PRIVATE_FAILED): return( "RSA - The private key operation failed" ); case -(MBEDTLS_ERR_RSA_VERIFY_FAILED): return( "RSA - The PKCS#1 verification failed" ); case -(MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE): return( "RSA - The output buffer for decryption is not large enough" ); case -(MBEDTLS_ERR_RSA_RNG_FAILED): return( "RSA - The random generator failed to generate non-zeros" ); case -(MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION): return( "RSA - The implementation does not offer the requested operation, for example, because of security violations or lack of functionality" ); case -(MBEDTLS_ERR_RSA_HW_ACCEL_FAILED): return( "RSA - RSA hardware accelerator failed" ); #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_SSL_TLS_C) case -(MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE): return( "SSL - The requested feature is not available" ); case -(MBEDTLS_ERR_SSL_BAD_INPUT_DATA): return( "SSL - Bad input parameters to function" ); case -(MBEDTLS_ERR_SSL_INVALID_MAC): return( "SSL - Verification of the message MAC failed" ); case -(MBEDTLS_ERR_SSL_INVALID_RECORD): return( "SSL - An invalid SSL record was received" ); case -(MBEDTLS_ERR_SSL_CONN_EOF): return( "SSL - The connection indicated an EOF" ); case -(MBEDTLS_ERR_SSL_UNKNOWN_CIPHER): return( "SSL - An unknown cipher was received" ); case -(MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN): return( "SSL - The server has no ciphersuites in common with the client" ); case -(MBEDTLS_ERR_SSL_NO_RNG): return( "SSL - No RNG was provided to the SSL module" ); case -(MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE): return( "SSL - No client certification received from the client, but required by the authentication mode" ); case -(MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE): return( "SSL - Our own certificate(s) is/are too large to send in an SSL message" ); case -(MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED): return( "SSL - The own certificate is not set, but needed by the server" ); case -(MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED): return( "SSL - The own private key or pre-shared key is not set, but needed" ); case -(MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED): return( "SSL - No CA Chain is set, but required to operate" ); case -(MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE): return( "SSL - An unexpected message was received from our peer" ); case -(MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE): return( "SSL - A fatal alert message was received from our peer" ); case -(MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED): return( "SSL - Verification of our peer failed" ); case -(MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY): return( "SSL - The peer notified us that the connection is going to be closed" ); case -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO): return( "SSL - Processing of the ClientHello handshake message failed" ); case -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO): return( "SSL - Processing of the ServerHello handshake message failed" ); case -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE): return( "SSL - Processing of the Certificate handshake message failed" ); case -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST): return( "SSL - Processing of the CertificateRequest handshake message failed" ); case -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE): return( "SSL - Processing of the ServerKeyExchange handshake message failed" ); case -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE): return( "SSL - Processing of the ServerHelloDone handshake message failed" ); case -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE): return( "SSL - Processing of the ClientKeyExchange handshake message failed" ); case -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP): return( "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Read Public" ); case -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS): return( "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Calculate Secret" ); case -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY): return( "SSL - Processing of the CertificateVerify handshake message failed" ); case -(MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC): return( "SSL - Processing of the ChangeCipherSpec handshake message failed" ); case -(MBEDTLS_ERR_SSL_BAD_HS_FINISHED): return( "SSL - Processing of the Finished handshake message failed" ); case -(MBEDTLS_ERR_SSL_ALLOC_FAILED): return( "SSL - Memory allocation failed" ); case -(MBEDTLS_ERR_SSL_HW_ACCEL_FAILED): return( "SSL - Hardware acceleration function returned with error" ); case -(MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH): return( "SSL - Hardware acceleration function skipped / left alone data" ); case -(MBEDTLS_ERR_SSL_COMPRESSION_FAILED): return( "SSL - Processing of the compression / decompression failed" ); case -(MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION): return( "SSL - Handshake protocol not within min/max boundaries" ); case -(MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET): return( "SSL - Processing of the NewSessionTicket handshake message failed" ); case -(MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED): return( "SSL - Session ticket has expired" ); case -(MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH): return( "SSL - Public key type mismatch (eg, asked for RSA key exchange and presented EC key)" ); case -(MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY): return( "SSL - Unknown identity received (eg, PSK identity)" ); case -(MBEDTLS_ERR_SSL_INTERNAL_ERROR): return( "SSL - Internal error (eg, unexpected failure in lower-level module)" ); case -(MBEDTLS_ERR_SSL_COUNTER_WRAPPING): return( "SSL - A counter would wrap (eg, too many messages exchanged)" ); case -(MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO): return( "SSL - Unexpected message at ServerHello in renegotiation" ); case -(MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED): return( "SSL - DTLS client must retry for hello verification" ); case -(MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL): return( "SSL - A buffer is too small to receive or write a message" ); case -(MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE): return( "SSL - None of the common ciphersuites is usable (eg, no suitable certificate, see debug messages)" ); case -(MBEDTLS_ERR_SSL_WANT_READ): return( "SSL - No data of requested type currently available on underlying transport" ); case -(MBEDTLS_ERR_SSL_WANT_WRITE): return( "SSL - Connection requires a write call" ); case -(MBEDTLS_ERR_SSL_TIMEOUT): return( "SSL - The operation timed out" ); case -(MBEDTLS_ERR_SSL_CLIENT_RECONNECT): return( "SSL - The client initiated a reconnect from the same port" ); case -(MBEDTLS_ERR_SSL_UNEXPECTED_RECORD): return( "SSL - Record header looks valid but is not expected" ); case -(MBEDTLS_ERR_SSL_NON_FATAL): return( "SSL - The alert message received indicates a non-fatal error" ); case -(MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH): return( "SSL - Couldn't set the hash for verifying CertificateVerify" ); case -(MBEDTLS_ERR_SSL_CONTINUE_PROCESSING): return( "SSL - Internal-only message signaling that further message-processing should be done" ); case -(MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS): return( "SSL - The asynchronous operation is not completed yet" ); case -(MBEDTLS_ERR_SSL_EARLY_MESSAGE): return( "SSL - Internal-only message signaling that a message arrived early" ); case -(MBEDTLS_ERR_SSL_UNEXPECTED_CID): return( "SSL - An encrypted DTLS-frame with an unexpected CID was received" ); case -(MBEDTLS_ERR_SSL_VERSION_MISMATCH): return( "SSL - An operation failed due to an unexpected version or configuration" ); case -(MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS): return( "SSL - A cryptographic operation is in progress. Try again later" ); case -(MBEDTLS_ERR_SSL_BAD_CONFIG): return( "SSL - Invalid value in SSL config" ); #endif /* MBEDTLS_SSL_TLS_C */ #if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C) case -(MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE): return( "X509 - Unavailable feature, e.g. RSA hashing/encryption combination" ); case -(MBEDTLS_ERR_X509_UNKNOWN_OID): return( "X509 - Requested OID is unknown" ); case -(MBEDTLS_ERR_X509_INVALID_FORMAT): return( "X509 - The CRT/CRL/CSR format is invalid, e.g. different type expected" ); case -(MBEDTLS_ERR_X509_INVALID_VERSION): return( "X509 - The CRT/CRL/CSR version element is invalid" ); case -(MBEDTLS_ERR_X509_INVALID_SERIAL): return( "X509 - The serial tag or value is invalid" ); case -(MBEDTLS_ERR_X509_INVALID_ALG): return( "X509 - The algorithm tag or value is invalid" ); case -(MBEDTLS_ERR_X509_INVALID_NAME): return( "X509 - The name tag or value is invalid" ); case -(MBEDTLS_ERR_X509_INVALID_DATE): return( "X509 - The date tag or value is invalid" ); case -(MBEDTLS_ERR_X509_INVALID_SIGNATURE): return( "X509 - The signature tag or value invalid" ); case -(MBEDTLS_ERR_X509_INVALID_EXTENSIONS): return( "X509 - The extension tag or value is invalid" ); case -(MBEDTLS_ERR_X509_UNKNOWN_VERSION): return( "X509 - CRT/CRL/CSR has an unsupported version number" ); case -(MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG): return( "X509 - Signature algorithm (oid) is unsupported" ); case -(MBEDTLS_ERR_X509_SIG_MISMATCH): return( "X509 - Signature algorithms do not match. (see \\c ::mbedtls_x509_crt sig_oid)" ); case -(MBEDTLS_ERR_X509_CERT_VERIFY_FAILED): return( "X509 - Certificate verification failed, e.g. CRL, CA or signature check failed" ); case -(MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT): return( "X509 - Format not recognized as DER or PEM" ); case -(MBEDTLS_ERR_X509_BAD_INPUT_DATA): return( "X509 - Input invalid" ); case -(MBEDTLS_ERR_X509_ALLOC_FAILED): return( "X509 - Allocation of memory failed" ); case -(MBEDTLS_ERR_X509_FILE_IO_ERROR): return( "X509 - Read/write of file failed" ); case -(MBEDTLS_ERR_X509_BUFFER_TOO_SMALL): return( "X509 - Destination buffer is too small" ); case -(MBEDTLS_ERR_X509_FATAL_ERROR): return( "X509 - A fatal error occurred, eg the chain is too long or the vrfy callback failed" ); #endif /* MBEDTLS_X509_USE_C || MBEDTLS_X509_CREATE_C */ /* End Auto-Generated Code. */ default: break; } return( NULL ); } const char * mbedtls_low_level_strerr( int error_code ) { int low_level_error_code; if( error_code < 0 ) error_code = -error_code; /* Extract the low-level part from the error code. */ low_level_error_code = error_code & ~0xFF80; switch( low_level_error_code ) { /* Begin Auto-Generated Code. */ #if defined(MBEDTLS_AES_C) case -(MBEDTLS_ERR_AES_INVALID_KEY_LENGTH): return( "AES - Invalid key length" ); case -(MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH): return( "AES - Invalid data input length" ); case -(MBEDTLS_ERR_AES_BAD_INPUT_DATA): return( "AES - Invalid input data" ); case -(MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE): return( "AES - Feature not available. For example, an unsupported AES key size" ); case -(MBEDTLS_ERR_AES_HW_ACCEL_FAILED): return( "AES - AES hardware accelerator failed" ); #endif /* MBEDTLS_AES_C */ #if defined(MBEDTLS_ASN1_PARSE_C) case -(MBEDTLS_ERR_ASN1_OUT_OF_DATA): return( "ASN1 - Out of data when parsing an ASN1 data structure" ); case -(MBEDTLS_ERR_ASN1_UNEXPECTED_TAG): return( "ASN1 - ASN1 tag was of an unexpected value" ); case -(MBEDTLS_ERR_ASN1_INVALID_LENGTH): return( "ASN1 - Error when trying to determine the length or invalid length" ); case -(MBEDTLS_ERR_ASN1_LENGTH_MISMATCH): return( "ASN1 - Actual length differs from expected length" ); case -(MBEDTLS_ERR_ASN1_INVALID_DATA): return( "ASN1 - Data is invalid" ); case -(MBEDTLS_ERR_ASN1_ALLOC_FAILED): return( "ASN1 - Memory allocation failed" ); case -(MBEDTLS_ERR_ASN1_BUF_TOO_SMALL): return( "ASN1 - Buffer too small when writing ASN.1 data structure" ); #endif /* MBEDTLS_ASN1_PARSE_C */ #if defined(MBEDTLS_BASE64_C) case -(MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL): return( "BASE64 - Output buffer too small" ); case -(MBEDTLS_ERR_BASE64_INVALID_CHARACTER): return( "BASE64 - Invalid character in input" ); #endif /* MBEDTLS_BASE64_C */ #if defined(MBEDTLS_BIGNUM_C) case -(MBEDTLS_ERR_MPI_FILE_IO_ERROR): return( "BIGNUM - An error occurred while reading from or writing to a file" ); case -(MBEDTLS_ERR_MPI_BAD_INPUT_DATA): return( "BIGNUM - Bad input parameters to function" ); case -(MBEDTLS_ERR_MPI_INVALID_CHARACTER): return( "BIGNUM - There is an invalid character in the digit string" ); case -(MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL): return( "BIGNUM - The buffer is too small to write to" ); case -(MBEDTLS_ERR_MPI_NEGATIVE_VALUE): return( "BIGNUM - The input arguments are negative or result in illegal output" ); case -(MBEDTLS_ERR_MPI_DIVISION_BY_ZERO): return( "BIGNUM - The input argument for division is zero, which is not allowed" ); case -(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE): return( "BIGNUM - The input arguments are not acceptable" ); case -(MBEDTLS_ERR_MPI_ALLOC_FAILED): return( "BIGNUM - Memory allocation failed" ); #endif /* MBEDTLS_BIGNUM_C */ #if defined(MBEDTLS_CCM_C) case -(MBEDTLS_ERR_CCM_BAD_INPUT): return( "CCM - Bad input parameters to the function" ); case -(MBEDTLS_ERR_CCM_AUTH_FAILED): return( "CCM - Authenticated decryption failed" ); case -(MBEDTLS_ERR_CCM_HW_ACCEL_FAILED): return( "CCM - CCM hardware accelerator failed" ); #endif /* MBEDTLS_CCM_C */ #if defined(MBEDTLS_CHACHA20_C) case -(MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA): return( "CHACHA20 - Invalid input parameter(s)" ); #endif /* MBEDTLS_CHACHA20_C */ #if defined(MBEDTLS_CHACHAPOLY_C) case -(MBEDTLS_ERR_CHACHAPOLY_BAD_STATE): return( "CHACHAPOLY - The requested operation is not permitted in the current state" ); case -(MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED): return( "CHACHAPOLY - Authenticated decryption failed: data was not authentic" ); #endif /* MBEDTLS_CHACHAPOLY_C */ #if defined(MBEDTLS_CMAC_C) case -(MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED): return( "CMAC - CMAC hardware accelerator failed" ); #endif /* MBEDTLS_CMAC_C */ #if defined(MBEDTLS_CTR_DRBG_C) case -(MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED): return( "CTR_DRBG - The entropy source failed" ); case -(MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG): return( "CTR_DRBG - The requested random buffer length is too big" ); case -(MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG): return( "CTR_DRBG - The input (entropy + additional data) is too large" ); case -(MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR): return( "CTR_DRBG - Read or write error in file" ); #endif /* MBEDTLS_CTR_DRBG_C */ #if defined(MBEDTLS_DES_C) case -(MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH): return( "DES - The data input has an invalid length" ); case -(MBEDTLS_ERR_DES_HW_ACCEL_FAILED): return( "DES - DES hardware accelerator failed" ); #endif /* MBEDTLS_DES_C */ #if defined(MBEDTLS_ENTROPY_C) case -(MBEDTLS_ERR_ENTROPY_SOURCE_FAILED): return( "ENTROPY - Critical entropy source failure" ); case -(MBEDTLS_ERR_ENTROPY_MAX_SOURCES): return( "ENTROPY - No more sources can be added" ); case -(MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED): return( "ENTROPY - No sources have been added to poll" ); case -(MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE): return( "ENTROPY - No strong sources have been added to poll" ); case -(MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR): return( "ENTROPY - Read/write error in file" ); #endif /* MBEDTLS_ENTROPY_C */ #if defined(MBEDTLS_ERROR_C) case -(MBEDTLS_ERR_ERROR_GENERIC_ERROR): return( "ERROR - Generic error" ); case -(MBEDTLS_ERR_THIS_CORRUPTION): return( "ERROR - This is a bug in the library" ); #endif /* MBEDTLS_ERROR_C */ #if defined(MBEDTLS_GCM_C) case -(MBEDTLS_ERR_GCM_AUTH_FAILED): return( "GCM - Authenticated decryption failed" ); case -(MBEDTLS_ERR_GCM_BAD_INPUT): return( "GCM - Bad input parameters to function" ); #endif /* MBEDTLS_GCM_C */ #if defined(MBEDTLS_HKDF_C) case -(MBEDTLS_ERR_HKDF_BAD_INPUT_DATA): return( "HKDF - Bad input parameters to function" ); #endif /* MBEDTLS_HKDF_C */ #if defined(MBEDTLS_HMAC_DRBG_C) case -(MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG): return( "HMAC_DRBG - Too many random requested in single call" ); case -(MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG): return( "HMAC_DRBG - Input too large (Entropy + additional)" ); case -(MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR): return( "HMAC_DRBG - Read/write error in file" ); case -(MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED): return( "HMAC_DRBG - The entropy source failed" ); #endif /* MBEDTLS_HMAC_DRBG_C */ #if defined(MBEDTLS_MD5_C) case -(MBEDTLS_ERR_MD5_HW_ACCEL_FAILED): return( "MD5 - MD5 hardware accelerator failed" ); #endif /* MBEDTLS_MD5_C */ #if defined(MBEDTLS_OID_C) case -(MBEDTLS_ERR_OID_NOT_FOUND): return( "OID - OID is not found" ); case -(MBEDTLS_ERR_OID_BUF_TOO_SMALL): return( "OID - output buffer is too small" ); #endif /* MBEDTLS_OID_C */ #if defined(MBEDTLS_PADLOCK_C) case -(MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED): return( "PADLOCK - Input data should be aligned" ); #endif /* MBEDTLS_PADLOCK_C */ #if defined(MBEDTLS_POLY1305_C) case -(MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA): return( "POLY1305 - Invalid input parameter(s)" ); case -(MBEDTLS_ERR_POLY1305_FEATURE_UNAVAILABLE): return( "POLY1305 - Feature not available. For example, s part of the API is not implemented" ); case -(MBEDTLS_ERR_POLY1305_HW_ACCEL_FAILED): return( "POLY1305 - Poly1305 hardware accelerator failed" ); #endif /* MBEDTLS_POLY1305_C */ #if defined(MBEDTLS_SHA1_C) case -(MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED): return( "SHA1 - SHA-1 hardware accelerator failed" ); case -(MBEDTLS_ERR_SHA1_BAD_INPUT_DATA): return( "SHA1 - SHA-1 input data was malformed" ); #endif /* MBEDTLS_SHA1_C */ #if defined(MBEDTLS_SHA256_C) case -(MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED): return( "SHA256 - SHA-256 hardware accelerator failed" ); case -(MBEDTLS_ERR_SHA256_BAD_INPUT_DATA): return( "SHA256 - SHA-256 input data was malformed" ); #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) case -(MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED): return( "SHA512 - SHA-512 hardware accelerator failed" ); case -(MBEDTLS_ERR_SHA512_BAD_INPUT_DATA): return( "SHA512 - SHA-512 input data was malformed" ); #endif /* MBEDTLS_SHA512_C */ /* End Auto-Generated Code. */ default: break; } return( NULL ); } void mbedtls_strerror( int ret, char *buf, size_t buflen ) { size_t len; int use_ret; const char * high_level_error_description = NULL; const char * low_level_error_description = NULL; if( buflen == 0 ) return; mbedtls_platform_zeroize( buf, buflen ); if( ret < 0 ) ret = -ret; if( ret & 0xFF80 ) { use_ret = ret & 0xFF80; // Translate high level error code. high_level_error_description = mbedtls_high_level_strerr( ret ); if( high_level_error_description == NULL ) mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", (unsigned int) use_ret ); else mbedtls_snprintf( buf, buflen, "%s", high_level_error_description ); #if defined(MBEDTLS_SSL_TLS_C) // Early return in case of a fatal error - do not try to translate low // level code. if(use_ret == -(MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE)) return; #endif /* MBEDTLS_SSL_TLS_C */ } use_ret = ret & ~0xFF80; if( use_ret == 0 ) return; // If high level code is present, make a concatenation between both // error strings. // len = strlen( buf ); if( len > 0 ) { if( buflen - len < 5 ) return; mbedtls_snprintf( buf + len, buflen - len, " : " ); buf += len + 3; buflen -= len + 3; } // Translate low level error code. low_level_error_description = mbedtls_low_level_strerr( ret ); if( low_level_error_description == NULL ) mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", (unsigned int) use_ret ); else mbedtls_snprintf( buf, buflen, "%s", low_level_error_description ); } #else /* MBEDTLS_ERROR_C */ /* * Provide an non-function in case MBEDTLS_ERROR_C is not defined */ void mbedtls_strerror( int ret, char *buf, size_t buflen ) { ((void) ret); if( buflen > 0 ) buf[0] = '\0'; } #endif /* MBEDTLS_ERROR_C */ #endif /* MBEDTLS_ERROR_C || MBEDTLS_ERROR_STRERROR_DUMMY */
35,714
729
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/sha512.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/asan.internal.h" #include "libc/literal.h" #include "libc/macros.internal.h" #include "libc/nexgen32e/nexgen32e.h" #include "libc/nexgen32e/x86feature.h" #include "libc/str/str.h" #include "third_party/mbedtls/chk.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/endian.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/md.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/sha512.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /** * @fileoverview FIPS-180-2 compliant SHA-384/512 implementation * * The SHA-512 Secure Hash Standard was published by NIST in 2002. * * @see http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf */ void sha512_transform_rorx(mbedtls_sha512_context *, const uint8_t *, int); #if defined(MBEDTLS_SHA512_C) #define SHA512_VALIDATE_RET(cond) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_SHA512_BAD_INPUT_DATA ) #define SHA512_VALIDATE(cond) MBEDTLS_INTERNAL_VALIDATE( cond ) #if !defined(MBEDTLS_SHA512_ALT) #define sha512_put_uint64_be PUT_UINT64_BE /** * \brief This function clones the state of a SHA-512 context. * * \param dst The destination context. This must be initialized. * \param src The context to clone. This must be initialized. */ void mbedtls_sha512_clone( mbedtls_sha512_context *dst, const mbedtls_sha512_context *src ) { SHA512_VALIDATE( dst ); SHA512_VALIDATE( src ); *dst = *src; } int mbedtls_sha512_starts_384( mbedtls_sha512_context *ctx ) { SHA512_VALIDATE_RET( ctx ); ctx->total[0] = 0; ctx->total[1] = 0; ctx->state[0] = 0xCBBB9D5DC1059ED8; ctx->state[1] = 0x629A292A367CD507; ctx->state[2] = 0x9159015A3070DD17; ctx->state[3] = 0x152FECD8F70E5939; ctx->state[4] = 0x67332667FFC00B31; ctx->state[5] = 0x8EB44A8768581511; ctx->state[6] = 0xDB0C2E0D64F98FA7; ctx->state[7] = 0x47B5481DBEFA4FA4; ctx->is384 = true; return( 0 ); } int mbedtls_sha512_starts_512( mbedtls_sha512_context *ctx ) { SHA512_VALIDATE_RET( ctx ); ctx->total[0] = 0; ctx->total[1] = 0; ctx->state[0] = 0x6A09E667F3BCC908; ctx->state[1] = 0xBB67AE8584CAA73B; ctx->state[2] = 0x3C6EF372FE94F82B; ctx->state[3] = 0xA54FF53A5F1D36F1; ctx->state[4] = 0x510E527FADE682D1; ctx->state[5] = 0x9B05688C2B3E6C1F; ctx->state[6] = 0x1F83D9ABFB41BD6B; ctx->state[7] = 0x5BE0CD19137E2179; ctx->is384 = false; return( 0 ); } /** * \brief This function starts a SHA-384 or SHA-512 checksum * calculation. * * \param ctx The SHA-512 context to use. This must be initialized. * \param is384 Determines which function to use. This must be * either \c 0 for SHA-512, or \c 1 for SHA-384. * * \note When \c MBEDTLS_SHA512_NO_SHA384 is defined, \p is384 must * be \c 0, or the function will return * #MBEDTLS_ERR_SHA512_BAD_INPUT_DATA. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_sha512_starts_ret( mbedtls_sha512_context *ctx, int is384 ) { SHA512_VALIDATE_RET( ctx ); SHA512_VALIDATE_RET( is384 == 0 || is384 == 1 ); if( !is384 ) return mbedtls_sha512_starts_512( ctx ); else return mbedtls_sha512_starts_384( ctx ); } #if !defined(MBEDTLS_SHA512_PROCESS_ALT) #define SHR(x,n) ((x) >> (n)) #define ROR(x,n) (SHR((x),(n)) | ((x) << (64 - (n)))) #define S0(x) (ROR(x, 1) ^ ROR(x, 8) ^ SHR(x, 7)) #define S1(x) (ROR(x,19) ^ ROR(x,61) ^ SHR(x, 6)) #define S2(x) (ROR(x,28) ^ ROR(x,34) ^ ROR(x,39)) #define S3(x) (ROR(x,14) ^ ROR(x,18) ^ ROR(x,41)) #define F0(x,y,z) (((x) & (y)) | ((z) & ((x) | (y)))) #define F1(x,y,z) ((z) ^ ((x) & ((y) ^ (z)))) #define P(a,b,c,d,e,f,g,h,x,k) \ do \ { \ local.temp1 = (h) + S3(e) + F1((e),(f),(g)) + (k) + (x); \ local.temp2 = S2(a) + F0((a),(b),(c)); \ (d) += local.temp1; (h) = local.temp1 + local.temp2; \ } while( 0 ) /** * \brief This function processes a single data block within * the ongoing SHA-512 computation. * This function is for internal use only. * * \param ctx The SHA-512 context. This must be initialized. * \param data The buffer holding one block of data. This * must be a readable buffer of length \c 128 Bytes. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_internal_sha512_process( mbedtls_sha512_context *ctx, const unsigned char data[128] ) { int i; struct { uint64_t temp1, temp2, W[80]; uint64_t A[8]; } local; SHA512_VALIDATE_RET( ctx != NULL ); SHA512_VALIDATE_RET( (const unsigned char *)data != NULL ); if( !IsTiny() && X86_HAVE(AVX2) ) { if (IsAsan()) __asan_verify(data, 128); sha512_transform_rorx(ctx, data, 1); return 0; } for( i = 0; i < 8; i++ ) local.A[i] = ctx->state[i]; #if defined(MBEDTLS_SHA512_SMALLER) for( i = 0; i < 80; i++ ) { if( i < 16 ) { GET_UINT64_BE( local.W[i], data, i << 3 ); } else { local.W[i] = S1(local.W[i - 2]) + local.W[i - 7] + S0(local.W[i - 15]) + local.W[i - 16]; } P( local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.W[i], kSha512[i] ); local.temp1 = local.A[7]; local.A[7] = local.A[6]; local.A[6] = local.A[5]; local.A[5] = local.A[4]; local.A[4] = local.A[3]; local.A[3] = local.A[2]; local.A[2] = local.A[1]; local.A[1] = local.A[0]; local.A[0] = local.temp1; } #else /* MBEDTLS_SHA512_SMALLER */ for( i = 0; i < 16; i++ ) { GET_UINT64_BE( local.W[i], data, i << 3 ); } for( ; i < 80; i++ ) { local.W[i] = S1(local.W[i - 2]) + local.W[i - 7] + S0(local.W[i - 15]) + local.W[i - 16]; } i = 0; do { P( local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.W[i], kSha512[i] ); i++; P( local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.W[i], kSha512[i] ); i++; P( local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.W[i], kSha512[i] ); i++; P( local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.W[i], kSha512[i] ); i++; P( local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.W[i], kSha512[i] ); i++; P( local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.W[i], kSha512[i] ); i++; P( local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.W[i], kSha512[i] ); i++; P( local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.W[i], kSha512[i] ); i++; } while( i < 80 ); #endif /* MBEDTLS_SHA512_SMALLER */ for( i = 0; i < 8; i++ ) ctx->state[i] += local.A[i]; /* Zeroise buffers and variables to clear sensitive data from memory. */ mbedtls_platform_zeroize( &local, sizeof( local ) ); return( 0 ); } #endif /* !MBEDTLS_SHA512_PROCESS_ALT */ /** * \brief This function feeds an input buffer into an ongoing * SHA-512 checksum calculation. * * \param ctx The SHA-512 context. This must be initialized * and have a hash operation started. * \param input The buffer holding the input data. This must * be a readable buffer of length \p ilen Bytes. * \param ilen The length of the input data in Bytes. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_sha512_update_ret( mbedtls_sha512_context *ctx, const unsigned char *input, size_t ilen ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t fill; unsigned int left; SHA512_VALIDATE_RET( ctx != NULL ); SHA512_VALIDATE_RET( ilen == 0 || input != NULL ); if( ilen == 0 ) return( 0 ); left = (unsigned int) (ctx->total[0] & 0x7F); fill = 128 - left; ctx->total[0] += (uint64_t) ilen; if( ctx->total[0] < (uint64_t) ilen ) ctx->total[1]++; if( left && ilen >= fill ) { memcpy( (void *) (ctx->buffer + left), input, fill ); if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 ) return( ret ); input += fill; ilen -= fill; left = 0; } if (!IsTiny() && ilen >= 128 && X86_HAVE(AVX2)) { if (IsAsan()) __asan_verify(input, ilen / 128 * 128); sha512_transform_rorx(ctx, input, ilen / 128); input += ROUNDDOWN(ilen, 128); ilen -= ROUNDDOWN(ilen, 128); } while( ilen >= 128 ) { if( ( ret = mbedtls_internal_sha512_process( ctx, input ) ) != 0 ) return( ret ); input += 128; ilen -= 128; } if( ilen > 0 ) memcpy( (void *) (ctx->buffer + left), input, ilen ); return( 0 ); } /** * \brief This function finishes the SHA-512 operation, and writes * the result to the output buffer. * * \param ctx The SHA-512 context. This must be initialized * and have a hash operation started. * \param output The SHA-384 or SHA-512 checksum result. * This must be a writable buffer of length \c 64 Bytes. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_sha512_finish_ret( mbedtls_sha512_context *ctx, unsigned char output[64] ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned used; uint64_t high, low; SHA512_VALIDATE_RET( ctx != NULL ); SHA512_VALIDATE_RET( (unsigned char *)output != NULL ); /* * Add padding: 0x80 then 0x00 until 16 bytes remain for the length */ used = ctx->total[0] & 0x7F; ctx->buffer[used++] = 0x80; if( used <= 112 ) { /* Enough room for padding + length in current block */ mbedtls_platform_zeroize( ctx->buffer + used, 112 - used ); } else { /* We'll need an extra block */ mbedtls_platform_zeroize( ctx->buffer + used, 128 - used ); if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 ) return( ret ); mbedtls_platform_zeroize( ctx->buffer, 112 ); } /* * Add message length */ high = ( ctx->total[0] >> 61 ) | ( ctx->total[1] << 3 ); low = ( ctx->total[0] << 3 ); sha512_put_uint64_be( high, ctx->buffer, 112 ); sha512_put_uint64_be( low, ctx->buffer, 120 ); if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 ) return( ret ); /* * Output final state */ sha512_put_uint64_be( ctx->state[0], output, 0 ); sha512_put_uint64_be( ctx->state[1], output, 8 ); sha512_put_uint64_be( ctx->state[2], output, 16 ); sha512_put_uint64_be( ctx->state[3], output, 24 ); sha512_put_uint64_be( ctx->state[4], output, 32 ); sha512_put_uint64_be( ctx->state[5], output, 40 ); #if !defined(MBEDTLS_SHA512_NO_SHA384) if( ctx->is384 == 0 ) #endif { sha512_put_uint64_be( ctx->state[6], output, 48 ); sha512_put_uint64_be( ctx->state[7], output, 56 ); } return( 0 ); } #endif /* !MBEDTLS_SHA512_ALT */ /** * \brief This function calculates the SHA-512 or SHA-384 * checksum of a buffer. * * The function allocates the context, performs the * calculation, and frees the context. * * The SHA-512 result is calculated as * output = SHA-512(input buffer). * * \param input The buffer holding the input data. This must be * a readable buffer of length \p ilen Bytes. * \param ilen The length of the input data in Bytes. * \param output The SHA-384 or SHA-512 checksum result. * This must be a writable buffer of length \c 64 Bytes. * \param is384 Determines which function to use. This must be either * \c 0 for SHA-512, or \c 1 for SHA-384. * * \note When \c MBEDTLS_SHA512_NO_SHA384 is defined, \p is384 must * be \c 0, or the function will return * #MBEDTLS_ERR_SHA512_BAD_INPUT_DATA. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_sha512_ret( const void *input, size_t ilen, unsigned char output[64], int is384 ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_sha512_context ctx; #if !defined(MBEDTLS_SHA512_NO_SHA384) SHA512_VALIDATE_RET( is384 == 0 || is384 == 1 ); #else SHA512_VALIDATE_RET( is384 == 0 ); #endif SHA512_VALIDATE_RET( ilen == 0 || input ); SHA512_VALIDATE_RET( (unsigned char *)output ); mbedtls_sha512_init( &ctx ); MBEDTLS_CHK( mbedtls_sha512_starts_ret( &ctx, is384 ) ); MBEDTLS_CHK( mbedtls_sha512_update_ret( &ctx, input, ilen ) ); MBEDTLS_CHK( mbedtls_sha512_finish_ret( &ctx, output ) ); cleanup: mbedtls_sha512_free( &ctx ); return( ret ); } noinstrument int mbedtls_sha512_ret_384( const void *input, size_t ilen, unsigned char *output ) { return mbedtls_sha512_ret( input, ilen, output, true ); } noinstrument int mbedtls_sha512_ret_512( const void *input, size_t ilen, unsigned char *output ) { return mbedtls_sha512_ret( input, ilen, output, false ); } #if !defined(MBEDTLS_SHA512_NO_SHA384) const mbedtls_md_info_t mbedtls_sha384_info = { "SHA384", MBEDTLS_MD_SHA384, 48, 128, (void *)mbedtls_sha512_starts_384, (void *)mbedtls_sha512_update_ret, (void *)mbedtls_internal_sha512_process, (void *)mbedtls_sha512_finish_ret, mbedtls_sha512_ret_384, }; #endif const mbedtls_md_info_t mbedtls_sha512_info = { "SHA512", MBEDTLS_MD_SHA512, 64, 128, (void *)mbedtls_sha512_starts_512, (void *)mbedtls_sha512_update_ret, (void *)mbedtls_internal_sha512_process, (void *)mbedtls_sha512_finish_ret, mbedtls_sha512_ret_512, }; #endif /* MBEDTLS_SHA512_C */
17,008
459
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/speed.sh
#!/bin/sh make -j8 o//third_party/mbedtls || exit run() { echo $1 $1 } ( run o//third_party/mbedtls/test/test_suite_aes.cbc.com run o//third_party/mbedtls/test/test_suite_aes.cfb.com run o//third_party/mbedtls/test/test_suite_aes.ecb.com run o//third_party/mbedtls/test/test_suite_aes.ofb.com run o//third_party/mbedtls/test/test_suite_aes.rest.com run o//third_party/mbedtls/test/test_suite_aes.xts.com run o//third_party/mbedtls/test/test_suite_asn1parse.com run o//third_party/mbedtls/test/test_suite_asn1write.com run o//third_party/mbedtls/test/test_suite_base64.com run o//third_party/mbedtls/test/test_suite_blowfish.com run o//third_party/mbedtls/test/test_suite_chacha20.com run o//third_party/mbedtls/test/test_suite_chachapoly.com run o//third_party/mbedtls/test/test_suite_cipher.aes.com run o//third_party/mbedtls/test/test_suite_cipher.blowfish.com run o//third_party/mbedtls/test/test_suite_cipher.ccm.com run o//third_party/mbedtls/test/test_suite_cipher.chacha20.com run o//third_party/mbedtls/test/test_suite_cipher.chachapoly.com run o//third_party/mbedtls/test/test_suite_cipher.des.com run o//third_party/mbedtls/test/test_suite_cipher.gcm.com run o//third_party/mbedtls/test/test_suite_cipher.misc.com run o//third_party/mbedtls/test/test_suite_cipher.nist_kw.com run o//third_party/mbedtls/test/test_suite_cipher.null.com run o//third_party/mbedtls/test/test_suite_cipher.padding.com run o//third_party/mbedtls/test/test_suite_ctr_drbg.com run o//third_party/mbedtls/test/test_suite_des.com run o//third_party/mbedtls/test/test_suite_dhm.com run o//third_party/mbedtls/test/test_suite_ecdh.com run o//third_party/mbedtls/test/test_suite_ecdsa.com run o//third_party/mbedtls/test/test_suite_ecjpake.com run o//third_party/mbedtls/test/test_suite_ecp.com run o//third_party/mbedtls/test/test_suite_entropy.com run o//third_party/mbedtls/test/test_suite_error.com run o//third_party/mbedtls/test/test_suite_gcm.aes128_de.com run o//third_party/mbedtls/test/test_suite_gcm.aes128_en.com run o//third_party/mbedtls/test/test_suite_gcm.aes192_de.com run o//third_party/mbedtls/test/test_suite_gcm.aes192_en.com run o//third_party/mbedtls/test/test_suite_gcm.aes256_de.com run o//third_party/mbedtls/test/test_suite_gcm.aes256_en.com run o//third_party/mbedtls/test/test_suite_gcm.misc.com run o//third_party/mbedtls/test/test_suite_hkdf.com run o//third_party/mbedtls/test/test_suite_hmac_drbg.misc.com run o//third_party/mbedtls/test/test_suite_hmac_drbg.no_reseed.com run o//third_party/mbedtls/test/test_suite_hmac_drbg.nopr.com run o//third_party/mbedtls/test/test_suite_hmac_drbg.pr.com run o//third_party/mbedtls/test/test_suite_md.com run o//third_party/mbedtls/test/test_suite_mdx.com run o//third_party/mbedtls/test/test_suite_memory_buffer_alloc.com run o//third_party/mbedtls/test/test_suite_mpi.com run o//third_party/mbedtls/test/test_suite_net.com run o//third_party/mbedtls/test/test_suite_nist_kw.com run o//third_party/mbedtls/test/test_suite_oid.com run o//third_party/mbedtls/test/test_suite_pem.com run o//third_party/mbedtls/test/test_suite_pk.com run o//third_party/mbedtls/test/test_suite_pkcs1_v15.com run o//third_party/mbedtls/test/test_suite_pkcs1_v21.com run o//third_party/mbedtls/test/test_suite_pkcs5.com run o//third_party/mbedtls/test/test_suite_pkparse.com run o//third_party/mbedtls/test/test_suite_pkwrite.com run o//third_party/mbedtls/test/test_suite_poly1305.com run o//third_party/mbedtls/test/test_suite_random.com run o//third_party/mbedtls/test/test_suite_rsa.com run o//third_party/mbedtls/test/test_suite_shax.com run o//third_party/mbedtls/test/test_suite_ssl.com run o//third_party/mbedtls/test/test_suite_timing.com run o//third_party/mbedtls/test/test_suite_version.com run o//third_party/mbedtls/test/test_suite_x509parse.com run o//third_party/mbedtls/test/test_suite_x509write.com ) | o//tool/build/deltaify2.com | sort -n | tee speed.txt mkdir -p ~/speed/mbedtls cp speed.txt ~/speed/mbedtls/$(date +%Y-%m-%d-%H-%H).txt
4,131
81
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/x509_create.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/mbedtls/asn1write.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/oid.h" #include "third_party/mbedtls/x509.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /* * X.509 base functions for creating certificates / CSRs * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(MBEDTLS_X509_CREATE_C) /* Structure linking OIDs for X.509 DN AttributeTypes to their * string representations and default string encodings used by Mbed TLS. */ typedef struct { const char *name; /* String representation of AttributeType, e.g. * "CN" or "emailAddress". */ size_t name_len; /* Length of 'name', without trailing 0 byte. */ const char *oid; /* String representation of OID of AttributeType, * as per RFC 5280, Appendix A.1. */ int default_tag; /* The default character encoding used for the * given attribute type, e.g. * MBEDTLS_ASN1_UTF8_STRING for UTF-8. */ } x509_attr_descriptor_t; #define ADD_STRLEN( s ) s, sizeof( s ) - 1 /* X.509 DN attributes from RFC 5280, Appendix A.1. */ static const x509_attr_descriptor_t x509_attrs[] = { { ADD_STRLEN( "CN" ), MBEDTLS_OID_AT_CN, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "commonName" ), MBEDTLS_OID_AT_CN, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "C" ), MBEDTLS_OID_AT_COUNTRY, MBEDTLS_ASN1_PRINTABLE_STRING }, { ADD_STRLEN( "countryName" ), MBEDTLS_OID_AT_COUNTRY, MBEDTLS_ASN1_PRINTABLE_STRING }, { ADD_STRLEN( "O" ), MBEDTLS_OID_AT_ORGANIZATION, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "organizationName" ), MBEDTLS_OID_AT_ORGANIZATION, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "L" ), MBEDTLS_OID_AT_LOCALITY, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "locality" ), MBEDTLS_OID_AT_LOCALITY, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "R" ), MBEDTLS_OID_PKCS9_EMAIL, MBEDTLS_ASN1_IA5_STRING }, { ADD_STRLEN( "OU" ), MBEDTLS_OID_AT_ORG_UNIT, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "organizationalUnitName" ), MBEDTLS_OID_AT_ORG_UNIT, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "ST" ), MBEDTLS_OID_AT_STATE, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "stateOrProvinceName" ), MBEDTLS_OID_AT_STATE, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "emailAddress" ), MBEDTLS_OID_PKCS9_EMAIL, MBEDTLS_ASN1_IA5_STRING }, { ADD_STRLEN( "serialNumber" ), MBEDTLS_OID_AT_SERIAL_NUMBER, MBEDTLS_ASN1_PRINTABLE_STRING }, { ADD_STRLEN( "postalAddress" ), MBEDTLS_OID_AT_POSTAL_ADDRESS, MBEDTLS_ASN1_PRINTABLE_STRING }, { ADD_STRLEN( "postalCode" ), MBEDTLS_OID_AT_POSTAL_CODE, MBEDTLS_ASN1_PRINTABLE_STRING }, { ADD_STRLEN( "dnQualifier" ), MBEDTLS_OID_AT_DN_QUALIFIER, MBEDTLS_ASN1_PRINTABLE_STRING }, { ADD_STRLEN( "title" ), MBEDTLS_OID_AT_TITLE, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "surName" ), MBEDTLS_OID_AT_SUR_NAME, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "SN" ), MBEDTLS_OID_AT_SUR_NAME, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "givenName" ), MBEDTLS_OID_AT_GIVEN_NAME, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "GN" ), MBEDTLS_OID_AT_GIVEN_NAME, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "initials" ), MBEDTLS_OID_AT_INITIALS, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "pseudonym" ), MBEDTLS_OID_AT_PSEUDONYM, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "generationQualifier" ), MBEDTLS_OID_AT_GENERATION_QUALIFIER, MBEDTLS_ASN1_UTF8_STRING }, { ADD_STRLEN( "domainComponent" ), MBEDTLS_OID_DOMAIN_COMPONENT, MBEDTLS_ASN1_IA5_STRING }, { ADD_STRLEN( "DC" ), MBEDTLS_OID_DOMAIN_COMPONENT, MBEDTLS_ASN1_IA5_STRING }, { NULL, 0, NULL, MBEDTLS_ASN1_NULL } }; static const x509_attr_descriptor_t *x509_attr_descr_from_name( const char *name, size_t name_len ) { const x509_attr_descriptor_t *cur; for( cur = x509_attrs; cur->name != NULL; cur++ ) if( cur->name_len == name_len && strncmp( cur->name, name, name_len ) == 0 ) break; if ( cur->name == NULL ) return( NULL ); return( cur ); } int mbedtls_x509_string_to_names( mbedtls_asn1_named_data **head, const char *name ) { int ret = 0; const char *s = name, *c = s; const char *end = s + strlen( s ); const char *oid = NULL; const x509_attr_descriptor_t* attr_descr = NULL; int in_tag = 1; char data[MBEDTLS_X509_MAX_DN_NAME_SIZE]; char *d = data; /* Clear existing chain if present */ mbedtls_asn1_free_named_data_list( head ); while( c <= end ) { if( in_tag && *c == '=' ) { if( ( attr_descr = x509_attr_descr_from_name( s, c - s ) ) == NULL ) { ret = MBEDTLS_ERR_X509_UNKNOWN_OID; goto exit; } oid = attr_descr->oid; s = c + 1; in_tag = 0; d = data; } if( !in_tag && *c == '\\' && c != end ) { c++; /* Check for valid escaped characters */ if( c == end || *c != ',' ) { ret = MBEDTLS_ERR_X509_INVALID_NAME; goto exit; } } else if( !in_tag && ( *c == ',' || c == end ) ) { mbedtls_asn1_named_data* cur = mbedtls_asn1_store_named_data( head, oid, strlen( oid ), (unsigned char *) data, d - data ); if(cur == NULL ) { return( MBEDTLS_ERR_X509_ALLOC_FAILED ); } // set tagType cur->val.tag = attr_descr->default_tag; while( c < end && *(c + 1) == ' ' ) c++; s = c + 1; in_tag = 1; } if( !in_tag && s != c + 1 ) { *(d++) = *c; if( d - data == MBEDTLS_X509_MAX_DN_NAME_SIZE ) { ret = MBEDTLS_ERR_X509_INVALID_NAME; goto exit; } } c++; } exit: return( ret ); } /* The first byte of the value in the mbedtls_asn1_named_data structure is reserved * to store the critical boolean for us */ int mbedtls_x509_set_extension( mbedtls_asn1_named_data **head, const char *oid, size_t oid_len, int critical, const unsigned char *val, size_t val_len ) { mbedtls_asn1_named_data *cur; if( ( cur = mbedtls_asn1_store_named_data( head, oid, oid_len, NULL, val_len + 1 ) ) == NULL ) { return( MBEDTLS_ERR_X509_ALLOC_FAILED ); } cur->val.p[0] = critical; memcpy( cur->val.p + 1, val, val_len ); return( 0 ); } /* * RelativeDistinguishedName ::= * SET OF AttributeTypeAndValue * * AttributeTypeAndValue ::= SEQUENCE { * type AttributeType, * value AttributeValue } * * AttributeType ::= OBJECT IDENTIFIER * * AttributeValue ::= ANY DEFINED BY AttributeType */ static int x509_write_name( unsigned char **p, unsigned char *start, mbedtls_asn1_named_data* cur_name) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len = 0; const char *oid = (const char*)cur_name->oid.p; size_t oid_len = cur_name->oid.len; const unsigned char *name = cur_name->val.p; size_t name_len = cur_name->val.len; // Write correct string tag and value MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tagged_string( p, start, cur_name->val.tag, (const char *) name, name_len ) ); // Write OID // MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_oid( p, start, oid, oid_len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET ) ); return( (int) len ); } int mbedtls_x509_write_names( unsigned char **p, unsigned char *start, mbedtls_asn1_named_data *first ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len = 0; mbedtls_asn1_named_data *cur = first; while( cur != NULL ) { MBEDTLS_ASN1_CHK_ADD( len, x509_write_name( p, start, cur ) ); cur = cur->next; } MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); return( (int) len ); } int mbedtls_x509_write_sig( unsigned char **p, unsigned char *start, const char *oid, size_t oid_len, unsigned char *sig, size_t size ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len = 0; if( *p < start || (size_t)( *p - start ) < size ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); len = size; (*p) -= len; memcpy( *p, sig, len ); if( *p - start < 1 ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); *--(*p) = 0; len += 1; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_BIT_STRING ) ); // Write OID // MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_algorithm_identifier( p, start, oid, oid_len, 0 ) ); return( (int) len ); } static int x509_write_extension( unsigned char **p, unsigned char *start, mbedtls_asn1_named_data *ext ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len = 0; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start, ext->val.p + 1, ext->val.len - 1 ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, ext->val.len - 1 ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_OCTET_STRING ) ); if( ext->val.p[0] != 0 ) { MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_bool( p, start, 1 ) ); } MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start, ext->oid.p, ext->oid.len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, ext->oid.len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_OID ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); return( (int) len ); } /* * Extension ::= SEQUENCE { * extnID OBJECT IDENTIFIER, * critical BOOLEAN DEFAULT FALSE, * extnValue OCTET STRING * -- contains the DER encoding of an ASN.1 value * -- corresponding to the extension type identified * -- by extnID * } */ int mbedtls_x509_write_extensions( unsigned char **p, unsigned char *start, mbedtls_asn1_named_data *first ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len = 0; mbedtls_asn1_named_data *cur_ext = first; while( cur_ext != NULL ) { MBEDTLS_ASN1_CHK_ADD( len, x509_write_extension( p, start, cur_ext ) ); cur_ext = cur_ext->next; } return( (int) len ); } #endif /* MBEDTLS_X509_CREATE_C */
14,823
396
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/srtp.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/mbedtls/ssl.h" const char *mbedtls_ssl_get_srtp_profile_as_string( mbedtls_ssl_srtp_profile profile) { switch (profile) { case MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_80: return "MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_80"; case MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_32: return "MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_32"; case MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_80: return "MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_80"; case MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_32: return "MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_32"; default: return ""; } }
2,427
36
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/math.h
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_MATH_H_ #define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_MATH_H_ #define ADC(R, A, B, CI, CO) \ do { \ uint64_t Ta = A; \ uint64_t Tb = B; \ CO = (Ta += CI) < CI; \ CO += (Ta += Tb) < Tb; \ R = Ta; \ } while (0) #define SBB(R, A, B, CI, CO) \ do { \ uint64_t Ta = A; \ uint64_t Tb = B; \ uint64_t Tc = Ta < CI; \ Ta -= CI; \ CO = (Ta < Tb) + Tc; \ Ta -= Tb; \ R = Ta; \ } while (0) #define MADD(a, b, c0, c1, c2) \ t = (uint128_t)a * b; \ t += c0; \ c0 = t; \ h = t >> 64; \ c1 += h; \ if (c1 < h) c2++ #endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_MATH_H_ */
897
33
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/chacha20.h
#ifndef MBEDTLS_CHACHA20_H_ #define MBEDTLS_CHACHA20_H_ #include "third_party/mbedtls/config.h" COSMOPOLITAN_C_START_ /* clang-format off */ #define MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA -0x0051 /*< Invalid input parameter(s). */ typedef struct mbedtls_chacha20_context { uint32_t state[16]; /*! The state (before round operations). */ uint8_t keystream8[64]; /*! Leftover keystream bytes. */ size_t keystream_bytes_used; /*! Number of keystream bytes already used. */ } mbedtls_chacha20_context; void mbedtls_chacha20_init( mbedtls_chacha20_context * ); void mbedtls_chacha20_free( mbedtls_chacha20_context * ); int mbedtls_chacha20_setkey( mbedtls_chacha20_context *, const unsigned char[32] ); int mbedtls_chacha20_starts( mbedtls_chacha20_context *, const unsigned char[12], uint32_t ); int mbedtls_chacha20_update( mbedtls_chacha20_context *, size_t, const unsigned char *, unsigned char * ); int mbedtls_chacha20_crypt( const unsigned char[32], const unsigned char[12], uint32_t, size_t, const unsigned char *, unsigned char * ); int mbedtls_chacha20_self_test( int ); COSMOPOLITAN_C_END_ #endif /* MBEDTLS_CHACHA20_H_ */
1,164
27
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/ecdh.h
#ifndef MBEDTLS_ECDH_H #define MBEDTLS_ECDH_H #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/ecdh_everest.h" #include "third_party/mbedtls/ecp.h" /* clang-format off */ #ifdef __cplusplus extern "C" { #endif /** * Defines the source of the imported EC key. */ typedef enum { MBEDTLS_ECDH_OURS, /*< Our key. */ MBEDTLS_ECDH_THEIRS, /*< The key of the peer. */ } mbedtls_ecdh_side; #if !defined(MBEDTLS_ECDH_LEGACY_CONTEXT) /** * Defines the ECDH implementation used. * * Later versions of the library may add new variants, therefore users should * not make any assumptions about them. */ typedef enum { MBEDTLS_ECDH_VARIANT_NONE = 0, /*!< Implementation not defined. */ MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0,/*!< The default Mbed TLS implementation */ #if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED) MBEDTLS_ECDH_VARIANT_EVEREST /*!< Everest implementation */ #endif } mbedtls_ecdh_variant; /** * The context used by the default ECDH implementation. * * Later versions might change the structure of this context, therefore users * should not make any assumptions about the structure of * mbedtls_ecdh_context_mbed. */ typedef struct mbedtls_ecdh_context_mbed { mbedtls_ecp_group grp; /*!< The elliptic curve used. */ mbedtls_mpi d; /*!< The private key. */ mbedtls_ecp_point Q; /*!< The public key. */ mbedtls_ecp_point Qp; /*!< The value of the public key of the peer. */ mbedtls_mpi z; /*!< The shared secret. */ #if defined(MBEDTLS_ECP_RESTARTABLE) mbedtls_ecp_restart_ctx rs; /*!< The restart context for EC computations. */ #endif } mbedtls_ecdh_context_mbed; #endif /** * * \warning Performing multiple operations concurrently on the same * ECDSA context is not supported; objects of this type * should not be shared between multiple threads. * \brief The ECDH context structure. */ typedef struct mbedtls_ecdh_context { #if defined(MBEDTLS_ECDH_LEGACY_CONTEXT) mbedtls_ecp_group grp; /*!< The elliptic curve used. */ mbedtls_mpi d; /*!< The private key. */ mbedtls_ecp_point Q; /*!< The public key. */ mbedtls_ecp_point Qp; /*!< The value of the public key of the peer. */ mbedtls_mpi z; /*!< The shared secret. */ int point_format; /*!< The format of point export in TLS messages. */ mbedtls_ecp_point Vi; /*!< The blinding value. */ mbedtls_ecp_point Vf; /*!< The unblinding value. */ mbedtls_mpi _d; /*!< The previous \p d. */ #if defined(MBEDTLS_ECP_RESTARTABLE) int restart_enabled; /*!< The flag for restartable mode. */ mbedtls_ecp_restart_ctx rs; /*!< The restart context for EC computations. */ #endif /* MBEDTLS_ECP_RESTARTABLE */ #else uint8_t point_format; /*!< The format of point export in TLS messages as defined in RFC 4492. */ mbedtls_ecp_group_id grp_id;/*!< The elliptic curve used. */ mbedtls_ecdh_variant var; /*!< The ECDH implementation/structure used. */ union { mbedtls_ecdh_context_mbed mbed_ecdh; #if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED) mbedtls_ecdh_context_everest everest_ecdh; #endif } ctx; /*!< Implementation-specific context. The context in use is specified by the \c var field. */ #if defined(MBEDTLS_ECP_RESTARTABLE) uint8_t restart_enabled; /*!< The flag for restartable mode. */ #endif /* MBEDTLS_ECP_RESTARTABLE */ #endif /* MBEDTLS_ECDH_LEGACY_CONTEXT */ } mbedtls_ecdh_context; /** * \brief Check whether a given group can be used for ECDH. * * \param gid The ECP group ID to check. * * \return \c 1 if the group can be used, \c 0 otherwise */ int mbedtls_ecdh_can_do( mbedtls_ecp_group_id gid ); /** * \brief This function generates an ECDH keypair on an elliptic * curve. * * This function performs the first of two core computations * implemented during the ECDH key exchange. The second core * computation is performed by mbedtls_ecdh_compute_shared(). * * \see ecp.h * * \param grp The ECP group to use. This must be initialized and have * domain parameters loaded, for example through * mbedtls_ecp_load() or mbedtls_ecp_tls_read_group(). * \param d The destination MPI (private key). * This must be initialized. * \param Q The destination point (public key). * This must be initialized. * \param f_rng The RNG function to use. This must not be \c NULL. * \param p_rng The RNG context to be passed to \p f_rng. This may be * \c NULL in case \p f_rng doesn't need a context argument. * * \return \c 0 on success. * \return Another \c MBEDTLS_ERR_ECP_XXX or * \c MBEDTLS_MPI_XXX error code on failure. */ int mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief This function computes the shared secret. * * This function performs the second of two core computations * implemented during the ECDH key exchange. The first core * computation is performed by mbedtls_ecdh_gen_public(). * * \see ecp.h * * \note If \p f_rng is not NULL, it is used to implement * countermeasures against side-channel attacks. * For more information, see mbedtls_ecp_mul(). * * \param grp The ECP group to use. This must be initialized and have * domain parameters loaded, for example through * mbedtls_ecp_load() or mbedtls_ecp_tls_read_group(). * \param z The destination MPI (shared secret). * This must be initialized. * \param Q The public key from another party. * This must be initialized. * \param d Our secret exponent (private key). * This must be initialized. * \param f_rng The RNG function. This may be \c NULL if randomization * of intermediate results during the ECP computations is * not needed (discouraged). See the documentation of * mbedtls_ecp_mul() for more. * \param p_rng The RNG context to be passed to \p f_rng. This may be * \c NULL if \p f_rng is \c NULL or doesn't need a * context argument. * * \return \c 0 on success. * \return Another \c MBEDTLS_ERR_ECP_XXX or * \c MBEDTLS_MPI_XXX error code on failure. */ int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z, const mbedtls_ecp_point *Q, const mbedtls_mpi *d, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief This function initializes an ECDH context. * * \param ctx The ECDH context to initialize. This must not be \c NULL. */ void mbedtls_ecdh_init( mbedtls_ecdh_context *ctx ); /** * \brief This function sets up the ECDH context with the information * given. * * This function should be called after mbedtls_ecdh_init() but * before mbedtls_ecdh_make_params(). There is no need to call * this function before mbedtls_ecdh_read_params(). * * This is the first function used by a TLS server for ECDHE * ciphersuites. * * \param ctx The ECDH context to set up. This must be initialized. * \param grp_id The group id of the group to set up the context for. * * \return \c 0 on success. */ int mbedtls_ecdh_setup( mbedtls_ecdh_context *ctx, mbedtls_ecp_group_id grp_id ); /** * \brief This function frees a context. * * \param ctx The context to free. This may be \c NULL, in which * case this function does nothing. If it is not \c NULL, * it must point to an initialized ECDH context. */ void mbedtls_ecdh_free( mbedtls_ecdh_context *ctx ); /** * \brief This function generates an EC key pair and exports its * in the format used in a TLS ServerKeyExchange handshake * message. * * This is the second function used by a TLS server for ECDHE * ciphersuites. (It is called after mbedtls_ecdh_setup().) * * \see ecp.h * * \param ctx The ECDH context to use. This must be initialized * and bound to a group, for example via mbedtls_ecdh_setup(). * \param olen The address at which to store the number of Bytes written. * \param buf The destination buffer. This must be a writable buffer of * length \p blen Bytes. * \param blen The length of the destination buffer \p buf in Bytes. * \param f_rng The RNG function to use. This must not be \c NULL. * \param p_rng The RNG context to be passed to \p f_rng. This may be * \c NULL in case \p f_rng doesn't need a context argument. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of * operations was reached: see \c mbedtls_ecp_set_max_ops(). * \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen, unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief This function parses the ECDHE parameters in a * TLS ServerKeyExchange handshake message. * * \note In a TLS handshake, this is the how the client * sets up its ECDHE context from the server's public * ECDHE key material. * * \see ecp.h * * \param ctx The ECDHE context to use. This must be initialized. * \param buf On input, \c *buf must be the start of the input buffer. * On output, \c *buf is updated to point to the end of the * data that has been read. On success, this is the first byte * past the end of the ServerKeyExchange parameters. * On error, this is the point at which an error has been * detected, which is usually not useful except to debug * failures. * \param end The end of the input buffer. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. * */ int mbedtls_ecdh_read_params( mbedtls_ecdh_context *ctx, const unsigned char **buf, const unsigned char *end ); /** * \brief This function sets up an ECDH context from an EC key. * * It is used by clients and servers in place of the * ServerKeyEchange for static ECDH, and imports ECDH * parameters from the EC key information of a certificate. * * \see ecp.h * * \param ctx The ECDH context to set up. This must be initialized. * \param key The EC key to use. This must be initialized. * \param side Defines the source of the key. Possible values are: * - #MBEDTLS_ECDH_OURS: The key is ours. * - #MBEDTLS_ECDH_THEIRS: The key is that of the peer. * * \return \c 0 on success. * \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure. * */ int mbedtls_ecdh_get_params( mbedtls_ecdh_context *ctx, const mbedtls_ecp_keypair *key, mbedtls_ecdh_side side ); /** * \brief This function generates a public key and exports it * as a TLS ClientKeyExchange payload. * * This is the second function used by a TLS client for ECDH(E) * ciphersuites. * * \see ecp.h * * \param ctx The ECDH context to use. This must be initialized * and bound to a group, the latter usually by * mbedtls_ecdh_read_params(). * \param olen The address at which to store the number of Bytes written. * This must not be \c NULL. * \param buf The destination buffer. This must be a writable buffer * of length \p blen Bytes. * \param blen The size of the destination buffer \p buf in Bytes. * \param f_rng The RNG function to use. This must not be \c NULL. * \param p_rng The RNG context to be passed to \p f_rng. This may be * \c NULL in case \p f_rng doesn't need a context argument. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of * operations was reached: see \c mbedtls_ecp_set_max_ops(). * \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen, unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief This function parses and processes the ECDHE payload of a * TLS ClientKeyExchange message. * * This is the third function used by a TLS server for ECDH(E) * ciphersuites. (It is called after mbedtls_ecdh_setup() and * mbedtls_ecdh_make_params().) * * \see ecp.h * * \param ctx The ECDH context to use. This must be initialized * and bound to a group, for example via mbedtls_ecdh_setup(). * \param buf The pointer to the ClientKeyExchange payload. This must * be a readable buffer of length \p blen Bytes. * \param blen The length of the input buffer \p buf in Bytes. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_ecdh_read_public( mbedtls_ecdh_context *ctx, const unsigned char *buf, size_t blen ); /** * \brief This function derives and exports the shared secret. * * This is the last function used by both TLS client * and servers. * * \note If \p f_rng is not NULL, it is used to implement * countermeasures against side-channel attacks. * For more information, see mbedtls_ecp_mul(). * * \see ecp.h * \param ctx The ECDH context to use. This must be initialized * and have its own private key generated and the peer's * public key imported. * \param olen The address at which to store the total number of * Bytes written on success. This must not be \c NULL. * \param buf The buffer to write the generated shared key to. This * must be a writable buffer of size \p blen Bytes. * \param blen The length of the destination buffer \p buf in Bytes. * \param f_rng The RNG function, for blinding purposes. This may * b \c NULL if blinding isn't needed. * \param p_rng The RNG context. This may be \c NULL if \p f_rng * doesn't need a context argument. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of * operations was reached: see \c mbedtls_ecp_set_max_ops(). * \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_ecdh_calc_secret( mbedtls_ecdh_context *ctx, size_t *olen, unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief This function enables restartable EC computations for this * context. (Default: disabled.) * * \see \c mbedtls_ecp_set_max_ops() * * \note It is not possible to safely disable restartable * computations once enabled, except by free-ing the context, * which cancels possible in-progress operations. * * \param ctx The ECDH context to use. This must be initialized. */ void mbedtls_ecdh_enable_restart( mbedtls_ecdh_context *ctx ); #ifdef __cplusplus } #endif #endif /* ecdh.h */
16,990
401
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/ssl_msg.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/limits.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/debug.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/iana.h" #include "third_party/mbedtls/oid.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/ssl.h" #include "third_party/mbedtls/ssl_internal.h" #include "third_party/mbedtls/ssl_invasive.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /* * Generic SSL/TLS messaging layer functions * (record layer + retransmission state machine) * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * The SSL 3.0 specification was drafted by Netscape in 1996, * and became an IETF standard in 1999. * * http://wp.netscape.com/eng/ssl3/ * http://www.ietf.org/rfc/rfc2246.txt * http://www.ietf.org/rfc/rfc4346.txt */ #if defined(MBEDTLS_SSL_TLS_C) static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl ); /* * Start a timer. * Passing millisecs = 0 cancels a running timer. */ void mbedtls_ssl_set_timer( mbedtls_ssl_context *ssl, uint32_t millisecs ) { if( ssl->f_set_timer == NULL ) return; MBEDTLS_SSL_DEBUG_MSG( 3, ( "set_timer to %d ms", (int) millisecs ) ); ssl->f_set_timer( ssl->p_timer, millisecs / 4, millisecs ); } /* * Return -1 is timer is expired, 0 if it isn't. */ int mbedtls_ssl_check_timer( mbedtls_ssl_context *ssl ) { if( ssl->f_get_timer == NULL ) return( 0 ); if( ssl->f_get_timer( ssl->p_timer ) == 2 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "timer expired" ) ); return( -1 ); } return( 0 ); } static int ssl_parse_record_header( mbedtls_ssl_context const *ssl, unsigned char *buf, size_t len, mbedtls_record *rec ); /** * \brief Check whether a buffer contains a valid and authentic record * that has not been seen before. (DTLS only). * * This function does not change the user-visible state * of the SSL context. Its sole purpose is to provide * an indication of the legitimacy of an incoming record. * * This can be useful e.g. in distributed server environments * using the DTLS Connection ID feature, in which connections * might need to be passed between service instances on a change * of peer address, but where such disruptive operations should * only happen after the validity of incoming records has been * confirmed. * * \param ssl The SSL context to use. * \param buf The address of the buffer holding the record to be checked. * This must be a read/write buffer of length \p buflen Bytes. * \param buflen The length of \p buf in Bytes. * * \note This routine only checks whether the provided buffer begins * with a valid and authentic record that has not been seen * before, but does not check potential data following the * initial record. In particular, it is possible to pass DTLS * datagrams containing multiple records, in which case only * the first record is checked. * * \note This function modifies the input buffer \p buf. If you need * to preserve the original record, you have to maintain a copy. * * \return \c 0 if the record is valid and authentic and has not been * seen before. * \return MBEDTLS_ERR_SSL_INVALID_MAC if the check completed * successfully but the record was found to be not authentic. * \return MBEDTLS_ERR_SSL_INVALID_RECORD if the check completed * successfully but the record was found to be invalid for * a reason different from authenticity checking. * \return MBEDTLS_ERR_SSL_UNEXPECTED_RECORD if the check completed * successfully but the record was found to be unexpected * in the state of the SSL context, including replayed records. * \return Another negative error code on different kinds of failure. * In this case, the SSL context becomes unusable and needs * to be freed or reset before reuse. */ int mbedtls_ssl_check_record( mbedtls_ssl_context const *ssl, unsigned char *buf, size_t buflen ) { int ret = 0; MBEDTLS_SSL_DEBUG_MSG( 1, ( "=> mbedtls_ssl_check_record" ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "record buffer", buf, buflen ); /* We don't support record checking in TLS because * (a) there doesn't seem to be a usecase for it, and * (b) In SSLv3 and TLS 1.0, CBC record decryption has state * and we'd need to backup the transform here. */ if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM ) { ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; goto exit; } #if defined(MBEDTLS_SSL_PROTO_DTLS) else { mbedtls_record rec; ret = ssl_parse_record_header( ssl, buf, buflen, &rec ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 3, "ssl_parse_record_header", ret ); goto exit; } if( ssl->transform_in != NULL ) { ret = mbedtls_ssl_decrypt_buf( ssl, ssl->transform_in, &rec ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 3, "mbedtls_ssl_decrypt_buf", ret ); goto exit; } } } #endif /* MBEDTLS_SSL_PROTO_DTLS */ exit: /* On success, we have decrypted the buffer in-place, so make * sure we don't leak any plaintext data. */ mbedtls_platform_zeroize( buf, buflen ); /* For the purpose of this API, treat messages with unexpected CID * as well as such from future epochs as unexpected. */ if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_CID || ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE ) { ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD; } MBEDTLS_SSL_DEBUG_MSG( 1, ( "<= mbedtls_ssl_check_record" ) ); return( ret ); } #define SSL_DONT_FORCE_FLUSH 0 #define SSL_FORCE_FLUSH 1 #if defined(MBEDTLS_SSL_PROTO_DTLS) /* Forward declarations for functions related to message buffering. */ static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl, uint8_t slot ); static void ssl_free_buffered_record( mbedtls_ssl_context *ssl ); static int ssl_load_buffered_message( mbedtls_ssl_context *ssl ); static int ssl_load_buffered_record( mbedtls_ssl_context *ssl ); static int ssl_buffer_message( mbedtls_ssl_context *ssl ); static int ssl_buffer_future_record( mbedtls_ssl_context *ssl, mbedtls_record const *rec ); static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl ); static size_t ssl_get_maximum_datagram_size( mbedtls_ssl_context const *ssl ) { size_t mtu = mbedtls_ssl_get_current_mtu( ssl ); #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) size_t out_buf_len = ssl->out_buf_len; #else size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN; #endif if( mtu != 0 && mtu < out_buf_len ) return( mtu ); return( out_buf_len ); } static int ssl_get_remaining_space_in_datagram( mbedtls_ssl_context const *ssl ) { size_t const bytes_written = ssl->out_left; size_t const mtu = ssl_get_maximum_datagram_size( ssl ); /* Double-check that the write-index hasn't gone * past what we can transmit in a single datagram. */ if( bytes_written > mtu ) { /* Should never happen... */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } return( (int) ( mtu - bytes_written ) ); } static int ssl_get_remaining_payload_in_datagram( mbedtls_ssl_context const *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t remaining, expansion; size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN; #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) const size_t mfl = mbedtls_ssl_get_output_max_frag_len( ssl ); if( max_len > mfl ) max_len = mfl; /* By the standard (RFC 6066 Sect. 4), the MFL extension * only limits the maximum record payload size, so in theory * we would be allowed to pack multiple records of payload size * MFL into a single datagram. However, this would mean that there's * no way to explicitly communicate MTU restrictions to the peer. * * The following reduction of max_len makes sure that we never * write datagrams larger than MFL + Record Expansion Overhead. */ if( max_len <= ssl->out_left ) return( 0 ); max_len -= ssl->out_left; #endif ret = ssl_get_remaining_space_in_datagram( ssl ); if( ret < 0 ) return( ret ); remaining = (size_t) ret; ret = mbedtls_ssl_get_record_expansion( ssl ); if( ret < 0 ) return( ret ); expansion = (size_t) ret; if( remaining <= expansion ) return( 0 ); remaining -= expansion; if( remaining >= max_len ) remaining = max_len; return( (int) remaining ); } /* * Double the retransmit timeout value, within the allowed range, * returning -1 if the maximum value has already been reached. */ static int ssl_double_retransmit_timeout( mbedtls_ssl_context *ssl ) { uint32_t new_timeout; if( ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max ) return( -1 ); /* Implement the final paragraph of RFC 6347 section 4.1.1.1 * in the following way: after the initial transmission and a first * retransmission, back off to a temporary estimated MTU of 508 bytes. * This value is guaranteed to be deliverable (if not guaranteed to be * delivered) of any compliant IPv4 (and IPv6) network, and should work * on most non-IP stacks too. */ if( ssl->handshake->retransmit_timeout != ssl->conf->hs_timeout_min ) { ssl->handshake->mtu = 508; MBEDTLS_SSL_DEBUG_MSG( 2, ( "mtu autoreduction to %d bytes", ssl->handshake->mtu ) ); } new_timeout = 2 * ssl->handshake->retransmit_timeout; /* Avoid arithmetic overflow and range overflow */ if( new_timeout < ssl->handshake->retransmit_timeout || new_timeout > ssl->conf->hs_timeout_max ) { new_timeout = ssl->conf->hs_timeout_max; } ssl->handshake->retransmit_timeout = new_timeout; MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %lu millisecs", (unsigned long) ssl->handshake->retransmit_timeout ) ); return( 0 ); } static void ssl_reset_retransmit_timeout( mbedtls_ssl_context *ssl ) { ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min; MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %lu millisecs", (unsigned long) ssl->handshake->retransmit_timeout ) ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) int (*mbedtls_ssl_hw_record_init)( mbedtls_ssl_context *ssl, const unsigned char *key_enc, const unsigned char *key_dec, size_t keylen, const unsigned char *iv_enc, const unsigned char *iv_dec, size_t ivlen, const unsigned char *mac_enc, const unsigned char *mac_dec, size_t maclen ) = NULL; int (*mbedtls_ssl_hw_record_activate)( mbedtls_ssl_context *ssl, int direction) = NULL; int (*mbedtls_ssl_hw_record_reset)( mbedtls_ssl_context *ssl ) = NULL; int (*mbedtls_ssl_hw_record_write)( mbedtls_ssl_context *ssl ) = NULL; int (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL; int (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL; #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ /* * Encryption/decryption functions */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) || \ defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) static size_t ssl_compute_padding_length( size_t len, size_t granularity ) { return( ( granularity - ( len + 1 ) % granularity ) % granularity ); } /* This functions transforms a (D)TLS plaintext fragment and a record content * type into an instance of the (D)TLSInnerPlaintext structure. This is used * in DTLS 1.2 + CID and within TLS 1.3 to allow flexible padding and to protect * a record's content type. * * struct { * opaque content[DTLSPlaintext.length]; * ContentType real_type; * uint8 zeros[length_of_padding]; * } (D)TLSInnerPlaintext; * * Input: * - `content`: The beginning of the buffer holding the * plaintext to be wrapped. * - `*content_size`: The length of the plaintext in Bytes. * - `max_len`: The number of Bytes available starting from * `content`. This must be `>= *content_size`. * - `rec_type`: The desired record content type. * * Output: * - `content`: The beginning of the resulting (D)TLSInnerPlaintext structure. * - `*content_size`: The length of the resulting (D)TLSInnerPlaintext structure. * * Returns: * - `0` on success. * - A negative error code if `max_len` didn't offer enough space * for the expansion. */ static int ssl_build_inner_plaintext( unsigned char *content, size_t *content_size, size_t remaining, uint8_t rec_type, size_t pad ) { size_t len = *content_size; /* Write real content type */ if( remaining == 0 ) return( -1 ); content[ len ] = rec_type; len++; remaining--; if( remaining < pad ) return( -1 ); mbedtls_platform_zeroize( content + len, pad ); len += pad; remaining -= pad; *content_size = len; return( 0 ); } /* This function parses a (D)TLSInnerPlaintext structure. * See ssl_build_inner_plaintext() for details. */ static int ssl_parse_inner_plaintext( unsigned char const *content, size_t *content_size, uint8_t *rec_type ) { size_t remaining = *content_size; /* Determine length of padding by skipping zeroes from the back. */ do { if( remaining == 0 ) return( -1 ); remaining--; } while( content[ remaining ] == 0 ); *content_size = remaining; *rec_type = content[ remaining ]; return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID || MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ /* `add_data` must have size 13 Bytes if the CID extension is disabled, * and 13 + 1 + CID-length Bytes if the CID extension is enabled. */ static void ssl_extract_add_data_from_record( unsigned char* add_data, size_t *add_data_len, mbedtls_record *rec, unsigned minor_ver ) { /* Quoting RFC 5246 (TLS 1.2): * * additional_data = seq_num + TLSCompressed.type + * TLSCompressed.version + TLSCompressed.length; * * For the CID extension, this is extended as follows * (quoting draft-ietf-tls-dtls-connection-id-05, * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05): * * additional_data = seq_num + DTLSPlaintext.type + * DTLSPlaintext.version + * cid + * cid_length + * length_of_DTLSInnerPlaintext; * * For TLS 1.3, the record sequence number is dropped from the AAD * and encoded within the nonce of the AEAD operation instead. */ unsigned char *cur = add_data; #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) if( minor_ver != MBEDTLS_SSL_MINOR_VERSION_4 ) #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ { ((void) minor_ver); memcpy( cur, rec->ctr, sizeof( rec->ctr ) ); cur += sizeof( rec->ctr ); } *cur = rec->type; cur++; memcpy( cur, rec->ver, sizeof( rec->ver ) ); cur += sizeof( rec->ver ); #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) if( rec->cid_len != 0 ) { memcpy( cur, rec->cid, rec->cid_len ); cur += rec->cid_len; *cur = rec->cid_len; cur++; cur[0] = ( rec->data_len >> 8 ) & 0xFF; cur[1] = ( rec->data_len >> 0 ) & 0xFF; cur += 2; } else #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ { cur[0] = ( rec->data_len >> 8 ) & 0xFF; cur[1] = ( rec->data_len >> 0 ) & 0xFF; cur += 2; } *add_data_len = cur - add_data; } #if defined(MBEDTLS_SSL_PROTO_SSL3) #define SSL3_MAC_MAX_BYTES 20 /* MD-5 or SHA-1 */ /* * SSLv3.0 MAC functions */ static void ssl_mac( mbedtls_md_context_t *md_ctx, const unsigned char *secret, const unsigned char *buf, size_t len, const unsigned char *ctr, int type, unsigned char out[SSL3_MAC_MAX_BYTES] ) { unsigned char header[11]; unsigned char padding[48]; int padlen; int md_size = mbedtls_md_get_size( md_ctx->md_info ); int md_type = mbedtls_md_get_type( md_ctx->md_info ); /* Only MD5 and SHA-1 supported */ if( md_type == MBEDTLS_MD_MD5 ) padlen = 48; else padlen = 40; memcpy( header, ctr, 8 ); header[ 8] = (unsigned char) type; header[ 9] = (unsigned char)( len >> 8 ); header[10] = (unsigned char)( len ); memset( padding, 0x36, padlen ); mbedtls_md_starts( md_ctx ); mbedtls_md_update( md_ctx, secret, md_size ); mbedtls_md_update( md_ctx, padding, padlen ); mbedtls_md_update( md_ctx, header, 11 ); mbedtls_md_update( md_ctx, buf, len ); mbedtls_md_finish( md_ctx, out ); memset( padding, 0x5C, padlen ); mbedtls_md_starts( md_ctx ); mbedtls_md_update( md_ctx, secret, md_size ); mbedtls_md_update( md_ctx, padding, padlen ); mbedtls_md_update( md_ctx, out, md_size ); mbedtls_md_finish( md_ctx, out ); } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_GCM_C) || \ defined(MBEDTLS_CCM_C) || \ defined(MBEDTLS_CHACHAPOLY_C) static int ssl_transform_aead_dynamic_iv_is_explicit( mbedtls_ssl_transform const *transform ) { return( transform->ivlen != transform->fixed_ivlen ); } /* Compute IV := ( fixed_iv || 0 ) XOR ( 0 || dynamic_IV ) * * Concretely, this occurs in two variants: * * a) Fixed and dynamic IV lengths add up to total IV length, giving * IV = fixed_iv || dynamic_iv * * This variant is used in TLS 1.2 when used with GCM or CCM. * * b) Fixed IV lengths matches total IV length, giving * IV = fixed_iv XOR ( 0 || dynamic_iv ) * * This variant occurs in TLS 1.3 and for TLS 1.2 when using ChaChaPoly. * * See also the documentation of mbedtls_ssl_transform. * * This function has the precondition that * * dst_iv_len >= max( fixed_iv_len, dynamic_iv_len ) * * which has to be ensured by the caller. If this precondition * violated, the behavior of this function is undefined. */ static void ssl_build_record_nonce( unsigned char *dst_iv, size_t dst_iv_len, unsigned char const *fixed_iv, size_t fixed_iv_len, unsigned char const *dynamic_iv, size_t dynamic_iv_len ) { size_t i; /* Start with Fixed IV || 0 */ mbedtls_platform_zeroize( dst_iv, dst_iv_len ); memcpy( dst_iv, fixed_iv, fixed_iv_len ); dst_iv += dst_iv_len - dynamic_iv_len; for( i = 0; i < dynamic_iv_len; i++ ) dst_iv[i] ^= dynamic_iv[i]; } #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */ int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl, mbedtls_ssl_transform *transform, mbedtls_record *rec, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { mbedtls_cipher_mode_t mode; int auth_done = 0; unsigned char * data; unsigned char add_data[13 + 1 + MBEDTLS_SSL_CID_OUT_LEN_MAX ]; size_t add_data_len; size_t post_avail; /* The SSL context is only used for debugging purposes! */ #if !defined(MBEDTLS_DEBUG_C) ssl = NULL; /* make sure we don't use it except for debug */ ((void) ssl); #endif /* The PRNG is used for dynamic IV generation that's used * for CBC transformations in TLS 1.1 and TLS 1.2. */ #if !( defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) && \ ( defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) ) ) ((void) f_rng); ((void) p_rng); #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) ); if( transform == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "no transform provided to encrypt_buf" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } if( rec == NULL || rec->buf == NULL || rec->buf_len < rec->data_offset || rec->buf_len - rec->data_offset < rec->data_len #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) || rec->cid_len != 0 #endif ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad record structure provided to encrypt_buf" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } data = rec->buf + rec->data_offset; post_avail = rec->buf_len - ( rec->data_len + rec->data_offset ); MBEDTLS_SSL_DEBUG_BUF( 4, "before encrypt: output payload", data, rec->data_len ); mode = mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ); if( rec->data_len > MBEDTLS_SSL_OUT_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Record content %" MBEDTLS_PRINTF_SIZET " too large, maximum %" MBEDTLS_PRINTF_SIZET, rec->data_len, (size_t) MBEDTLS_SSL_OUT_CONTENT_LEN ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* The following two code paths implement the (D)TLSInnerPlaintext * structure present in TLS 1.3 and DTLS 1.2 + CID. * * See ssl_build_inner_plaintext() for more information. * * Note that this changes `rec->data_len`, and hence * `post_avail` needs to be recalculated afterwards. * * Note also that the two code paths cannot occur simultaneously * since they apply to different versions of the protocol. There * is hence no risk of double-addition of the inner plaintext. */ #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_4 ) { size_t padding = ssl_compute_padding_length( rec->data_len, MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY ); if( ssl_build_inner_plaintext( data, &rec->data_len, post_avail, rec->type, padding ) != 0 ) { return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } rec->type = MBEDTLS_SSL_MSG_APPLICATION_DATA; } #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) /* * Add CID information */ rec->cid_len = transform->out_cid_len; memcpy( rec->cid, transform->out_cid, transform->out_cid_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "CID", rec->cid, rec->cid_len ); if( rec->cid_len != 0 ) { size_t padding = ssl_compute_padding_length( rec->data_len, MBEDTLS_SSL_CID_PADDING_GRANULARITY ); /* * Wrap plaintext into DTLSInnerPlaintext structure. * See ssl_build_inner_plaintext() for more information. * * Note that this changes `rec->data_len`, and hence * `post_avail` needs to be recalculated afterwards. */ if( ssl_build_inner_plaintext( data, &rec->data_len, post_avail, rec->type, padding ) != 0 ) { return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } rec->type = MBEDTLS_SSL_MSG_CID; } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ post_avail = rec->buf_len - ( rec->data_len + rec->data_offset ); /* * Add MAC before if needed */ #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) if( mode == MBEDTLS_MODE_STREAM || ( mode == MBEDTLS_MODE_CBC #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) && transform->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED #endif ) ) { if( post_avail < transform->maclen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { unsigned char mac[SSL3_MAC_MAX_BYTES]; ssl_mac( &transform->md_ctx_enc, transform->mac_enc, data, rec->data_len, rec->ctr, rec->type, mac ); memcpy( data + rec->data_len, mac, transform->maclen ); } else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 ) { unsigned char mac[MBEDTLS_SSL_MAC_ADD]; ssl_extract_add_data_from_record( add_data, &add_data_len, rec, transform->minor_ver ); mbedtls_md_hmac_update( &transform->md_ctx_enc, add_data, add_data_len ); mbedtls_md_hmac_update( &transform->md_ctx_enc, data, rec->data_len ); mbedtls_md_hmac_finish( &transform->md_ctx_enc, mac ); mbedtls_md_hmac_reset( &transform->md_ctx_enc ); memcpy( data + rec->data_len, mac, transform->maclen ); } else #endif { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac", data + rec->data_len, transform->maclen ); rec->data_len += transform->maclen; post_avail -= transform->maclen; auth_done++; } #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */ /* * Encrypt */ #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) if( mode == MBEDTLS_MODE_STREAM ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t olen; MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %" MBEDTLS_PRINTF_SIZET ", " "including %d bytes of padding", rec->data_len, 0 ) ); if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_enc, transform->iv_enc, transform->ivlen, data, rec->data_len, data, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); return( ret ); } if( rec->data_len != olen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } else #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */ #if defined(MBEDTLS_GCM_C) || \ defined(MBEDTLS_CCM_C) || \ defined(MBEDTLS_CHACHAPOLY_C) if( mode == MBEDTLS_MODE_GCM || mode == MBEDTLS_MODE_CCM || mode == MBEDTLS_MODE_CHACHAPOLY ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char iv[12]; unsigned char *dynamic_iv; size_t dynamic_iv_len; int dynamic_iv_is_explicit = ssl_transform_aead_dynamic_iv_is_explicit( transform ); /* Check that there's space for the authentication tag. */ if( post_avail < transform->taglen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } /* * Build nonce for AEAD encryption. * * Note: In the case of CCM and GCM in TLS 1.2, the dynamic * part of the IV is prepended to the ciphertext and * can be chosen freely - in particular, it need not * agree with the record sequence number. * However, since ChaChaPoly as well as all AEAD modes * in TLS 1.3 use the record sequence number as the * dynamic part of the nonce, we uniformly use the * record sequence number here in all cases. */ dynamic_iv = rec->ctr; dynamic_iv_len = sizeof( rec->ctr ); ssl_build_record_nonce( iv, sizeof( iv ), transform->iv_enc, transform->fixed_ivlen, dynamic_iv, dynamic_iv_len ); /* * Build additional data for AEAD encryption. * This depends on the TLS version. */ ssl_extract_add_data_from_record( add_data, &add_data_len, rec, transform->minor_ver ); MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (internal)", iv, transform->ivlen ); MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (transmitted)", dynamic_iv, dynamic_iv_is_explicit ? dynamic_iv_len : 0 ); MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD", add_data, add_data_len ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %" MBEDTLS_PRINTF_SIZET ", " "including 0 bytes of padding", rec->data_len ) ); /* * Encrypt and authenticate */ if( ( ret = mbedtls_cipher_auth_encrypt_ext( &transform->cipher_ctx_enc, iv, transform->ivlen, add_data, add_data_len, data, rec->data_len, /* src */ data, rec->buf_len - (data - rec->buf), /* dst */ &rec->data_len, transform->taglen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_encrypt", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_BUF( 4, "after encrypt: tag", data + rec->data_len - transform->taglen, transform->taglen ); /* Account for authentication tag. */ post_avail -= transform->taglen; /* * Prefix record content with dynamic IV in case it is explicit. */ if( dynamic_iv_is_explicit != 0 ) { if( rec->data_offset < dynamic_iv_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } memcpy( data - dynamic_iv_len, dynamic_iv, dynamic_iv_len ); rec->data_offset -= dynamic_iv_len; rec->data_len += dynamic_iv_len; } auth_done++; } else #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */ #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) if( mode == MBEDTLS_MODE_CBC ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t padlen, i; size_t olen; /* Currently we're always using minimal padding * (up to 255 bytes would be allowed). */ padlen = transform->ivlen - ( rec->data_len + 1 ) % transform->ivlen; if( padlen == transform->ivlen ) padlen = 0; /* Check there's enough space in the buffer for the padding. */ if( post_avail < padlen + 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } for( i = 0; i <= padlen; i++ ) data[rec->data_len + i] = (unsigned char) padlen; rec->data_len += padlen + 1; post_avail -= padlen + 1; #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) /* * Prepend per-record IV for block cipher in TLS v1.1 and up as per * Method 1 (6.2.3.2. in RFC4346 and RFC5246) */ if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) { if( f_rng == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "No PRNG provided to encrypt_record routine" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } if( rec->data_offset < transform->ivlen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } /* * Generate IV */ ret = f_rng( p_rng, transform->iv_enc, transform->ivlen ); if( ret != 0 ) return( ret ); memcpy( data - transform->ivlen, transform->iv_enc, transform->ivlen ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %" MBEDTLS_PRINTF_SIZET ", " "including %" MBEDTLS_PRINTF_SIZET " bytes of IV and %" MBEDTLS_PRINTF_SIZET " bytes of padding", rec->data_len, transform->ivlen, padlen + 1 ) ); if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_enc, transform->iv_enc, transform->ivlen, data, rec->data_len, data, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); return( ret ); } if( rec->data_len != olen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) if( transform->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ) { /* * Save IV in SSL3 and TLS1 */ memcpy( transform->iv_enc, transform->cipher_ctx_enc.iv, transform->ivlen ); } else #endif { data -= transform->ivlen; rec->data_offset -= transform->ivlen; rec->data_len += transform->ivlen; } #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) if( auth_done == 0 ) { unsigned char mac[MBEDTLS_SSL_MAC_ADD]; /* * MAC(MAC_write_key, seq_num + * TLSCipherText.type + * TLSCipherText.version + * length_of( (IV +) ENC(...) ) + * IV + // except for TLS 1.0 * ENC(content + padding + padding_length)); */ if( post_avail < transform->maclen) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } ssl_extract_add_data_from_record( add_data, &add_data_len, rec, transform->minor_ver ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", add_data, add_data_len ); mbedtls_md_hmac_update( &transform->md_ctx_enc, add_data, add_data_len ); mbedtls_md_hmac_update( &transform->md_ctx_enc, data, rec->data_len ); mbedtls_md_hmac_finish( &transform->md_ctx_enc, mac ); mbedtls_md_hmac_reset( &transform->md_ctx_enc ); memcpy( data + rec->data_len, mac, transform->maclen ); rec->data_len += transform->maclen; post_avail -= transform->maclen; auth_done++; } #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ } else #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC) */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* Make extra sure authentication was performed, exactly once */ if( auth_done != 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC) /* * Turn a bit into a mask: * - if bit == 1, return the all-bits 1 mask, aka (size_t) -1 * - if bit == 0, return the all-bits 0 mask, aka 0 * * This function can be used to write constant-time code by replacing branches * with bit operations using masks. * * This function is implemented without using comparison operators, as those * might be translated to branches by some compilers on some platforms. */ static inline size_t mbedtls_ssl_cf_mask_from_bit( size_t bit ) { /* MSVC has a warning about unary minus on unsigned integer types, * but this is well-defined and precisely what we want to do here. */ #if defined(_MSC_VER) #pragma warning( push ) #pragma warning( disable : 4146 ) #endif return -bit; #if defined(_MSC_VER) #pragma warning( pop ) #endif } /* * Constant-flow mask generation for "less than" comparison: * - if x < y, return all bits 1, that is (size_t) -1 * - otherwise, return all bits 0, that is 0 * * This function can be used to write constant-time code by replacing branches * with bit operations using masks. * * This function is implemented without using comparison operators, as those * might be translated to branches by some compilers on some platforms. */ static inline size_t mbedtls_ssl_cf_mask_lt( size_t x, size_t y ) { /* This has the most significant bit set if and only if x < y */ const size_t sub = x - y; /* sub1 = (x < y) ? 1 : 0 */ const size_t sub1 = sub >> ( sizeof( sub ) * 8 - 1 ); /* mask = (x < y) ? 0xff... : 0x00... */ const size_t mask = mbedtls_ssl_cf_mask_from_bit( sub1 ); return( mask ); } /* * Constant-flow mask generation for "greater or equal" comparison: * - if x >= y, return all bits 1, that is (size_t) -1 * - otherwise, return all bits 0, that is 0 * * This function can be used to write constant-time code by replacing branches * with bit operations using masks. * * This function is implemented without using comparison operators, as those * might be translated to branches by some compilers on some platforms. */ static inline size_t mbedtls_ssl_cf_mask_ge( size_t x, size_t y ) { return( ~mbedtls_ssl_cf_mask_lt( x, y ) ); } /* * Constant-flow boolean "equal" comparison: * return x == y * * This function can be used to write constant-time code by replacing branches * with bit operations - it can be used in conjunction with * mbedtls_ssl_cf_mask_from_bit(). * * This function is implemented without using comparison operators, as those * might be translated to branches by some compilers on some platforms. */ static inline size_t mbedtls_ssl_cf_bool_eq( size_t x, size_t y ) { /* diff = 0 if x == y, non-zero otherwise */ const size_t diff = x ^ y; /* MSVC has a warning about unary minus on unsigned integer types, * but this is well-defined and precisely what we want to do here. */ #if defined(_MSC_VER) #pragma warning( push ) #pragma warning( disable : 4146 ) #endif /* diff_msb's most significant bit is equal to x != y */ const size_t diff_msb = ( diff | -diff ); #if defined(_MSC_VER) #pragma warning( pop ) #endif /* diff1 = (x != y) ? 1 : 0 */ const size_t diff1 = diff_msb >> ( sizeof( diff_msb ) * 8 - 1 ); return( 1 ^ diff1 ); } /* * Constant-flow conditional memcpy: * - if c1 == c2, equivalent to memcpy(dst, src, len), * - otherwise, a no-op, * but with execution flow independent of the values of c1 and c2. * * This function is implemented without using comparison operators, as those * might be translated to branches by some compilers on some platforms. */ static void mbedtls_ssl_cf_memcpy_if_eq( unsigned char *dst, const unsigned char *src, size_t len, size_t c1, size_t c2 ) { size_t i; uint64_t x, y; const size_t equal = mbedtls_ssl_cf_bool_eq( c1, c2 ); const unsigned char mask = (unsigned char) mbedtls_ssl_cf_mask_from_bit( equal ); for (i = 0; i + 8 <= len; i += 8) { __builtin_memcpy( &x, dst + i, 8 ); __builtin_memcpy( &y, src + i, 8 ); x = ( x & ~-equal ) | ( y & -equal ); __builtin_memcpy( dst + i, &x, 8 ); } for( ; i < len; i++ ) dst[i] = ( src[i] & mask ) | ( dst[i] & ~mask ); } /* * Compute HMAC of variable-length data with constant flow. * * Only works with MD-5, SHA-1, SHA-256 and SHA-384. * (Otherwise, computation of block_size needs to be adapted.) */ MBEDTLS_STATIC_TESTABLE int mbedtls_ssl_cf_hmac( mbedtls_md_context_t *ctx, const unsigned char *add_data, size_t add_data_len, const unsigned char *data, size_t data_len_secret, size_t min_data_len, size_t max_data_len, unsigned char *output ) { /* * This function breaks the HMAC abstraction and uses the md_clone() * extension to the MD API in order to get constant-flow behaviour. * * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means * concatenation, and okey/ikey are the XOR of the key with some fixed bit * patterns (see RFC 2104, sec. 2), which are stored in ctx->hmac_ctx. * * We'll first compute inner_hash = HASH(ikey + msg) by hashing up to * minlen, then cloning the context, and for each byte up to maxlen * finishing up the hash computation, keeping only the correct result. * * Then we only need to compute HASH(okey + inner_hash) and we're done. */ const mbedtls_md_type_t md_alg = mbedtls_md_get_type( ctx->md_info ); /* TLS 1.0-1.2 only support SHA-384, SHA-256, SHA-1, MD-5, * all of which have the same block size except SHA-384. */ const size_t block_size = md_alg == MBEDTLS_MD_SHA384 ? 128 : 64; const unsigned char * const ikey = ctx->hmac_ctx; const unsigned char * const okey = ikey + block_size; const size_t hash_size = mbedtls_md_get_size( ctx->md_info ); unsigned char aux_out[MBEDTLS_MD_MAX_SIZE]; size_t offset; int ret = MBEDTLS_ERR_THIS_CORRUPTION; #define MD_CHK( func_call ) \ do { \ ret = (func_call); \ if( ret != 0 ) \ goto cleanup; \ } while( 0 ) /* After hmac_start() of hmac_reset(), ikey has already been hashed, * so we can start directly with the message */ MD_CHK( mbedtls_md_update( ctx, add_data, add_data_len ) ); MD_CHK( mbedtls_md_update( ctx, data, min_data_len ) ); #if 1 /* * This code path strengthens the server against DOS attacks by * weakening Internet Explorer sessions against Lucky Thirteen. */ MD_CHK( mbedtls_md_update( ctx, data + min_data_len, data_len_secret - min_data_len ) ); MD_CHK( mbedtls_md_finish( ctx, output ) ); #else mbedtls_md_context_t aux; mbedtls_md_init( &aux ); MD_CHK( mbedtls_md_setup( &aux, ctx->md_info, 0 ) ); /* For each possible length, compute the hash up to that point */ for( offset = min_data_len; offset <= max_data_len; offset++ ) { MD_CHK( mbedtls_md_clone( &aux, ctx ) ); MD_CHK( mbedtls_md_finish( &aux, aux_out ) ); /* Keep only the correct inner_hash in the output buffer */ mbedtls_ssl_cf_memcpy_if_eq( output, aux_out, hash_size, offset, data_len_secret ); if( offset < max_data_len ) MD_CHK( mbedtls_md_update( ctx, data + offset, 1 ) ); } mbedtls_md_free( &aux ); #endif /* Now compute HASH(okey + inner_hash) */ MD_CHK( mbedtls_md_starts( ctx ) ); MD_CHK( mbedtls_md_update( ctx, okey, block_size ) ); MD_CHK( mbedtls_md_update( ctx, output, hash_size ) ); MD_CHK( mbedtls_md_finish( ctx, output ) ); /* Done, get ready for next time */ MD_CHK( mbedtls_md_hmac_reset( ctx ) ); #undef MD_CHK cleanup: return( ret ); } /* * Constant-flow memcpy from variable position in buffer. * - functionally equivalent to memcpy(dst, src + offset_secret, len) * - but with execution flow independent from the value of offset_secret. */ MBEDTLS_STATIC_TESTABLE void mbedtls_ssl_cf_memcpy_offset( unsigned char *dst, const unsigned char *src_base, size_t offset_secret, size_t offset_min, size_t offset_max, size_t len ) { size_t offset; for( offset = offset_min; offset <= offset_max; offset++ ) { mbedtls_ssl_cf_memcpy_if_eq( dst, src_base + offset, len, offset, offset_secret ); } } #endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */ int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context const *ssl, mbedtls_ssl_transform *transform, mbedtls_record *rec ) { size_t olen; mbedtls_cipher_mode_t mode; int ret, auth_done = 0; #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) size_t padlen = 0, correct = 1; #endif unsigned char* data; unsigned char add_data[13 + 1 + MBEDTLS_SSL_CID_IN_LEN_MAX ]; size_t add_data_len; #if !defined(MBEDTLS_DEBUG_C) ssl = NULL; /* make sure we don't use it except for debug */ ((void) ssl); #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) ); if( rec == NULL || rec->buf == NULL || rec->buf_len < rec->data_offset || rec->buf_len - rec->data_offset < rec->data_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad record structure provided to decrypt_buf" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } data = rec->buf + rec->data_offset; mode = mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_dec ); #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) /* * Match record's CID with incoming CID. */ if( rec->cid_len != transform->in_cid_len || timingsafe_bcmp( rec->cid, transform->in_cid, rec->cid_len ) != 0 ) { return( MBEDTLS_ERR_SSL_UNEXPECTED_CID ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) if( mode == MBEDTLS_MODE_STREAM ) { padlen = 0; if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_dec, transform->iv_dec, transform->ivlen, data, rec->data_len, data, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); return( ret ); } if( rec->data_len != olen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } else #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */ #if defined(MBEDTLS_GCM_C) || \ defined(MBEDTLS_CCM_C) || \ defined(MBEDTLS_CHACHAPOLY_C) if( mode == MBEDTLS_MODE_GCM || mode == MBEDTLS_MODE_CCM || mode == MBEDTLS_MODE_CHACHAPOLY ) { unsigned char iv[12]; unsigned char *dynamic_iv; size_t dynamic_iv_len; /* * Extract dynamic part of nonce for AEAD decryption. * * Note: In the case of CCM and GCM in TLS 1.2, the dynamic * part of the IV is prepended to the ciphertext and * can be chosen freely - in particular, it need not * agree with the record sequence number. */ dynamic_iv_len = sizeof( rec->ctr ); if( ssl_transform_aead_dynamic_iv_is_explicit( transform ) == 1 ) { if( rec->data_len < dynamic_iv_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%" MBEDTLS_PRINTF_SIZET " ) < explicit_iv_len (%" MBEDTLS_PRINTF_SIZET ") ", rec->data_len, dynamic_iv_len ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } dynamic_iv = data; data += dynamic_iv_len; rec->data_offset += dynamic_iv_len; rec->data_len -= dynamic_iv_len; } else { dynamic_iv = rec->ctr; } /* Check that there's space for the authentication tag. */ if( rec->data_len < transform->taglen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%" MBEDTLS_PRINTF_SIZET ") < taglen (%" MBEDTLS_PRINTF_SIZET ") ", rec->data_len, transform->taglen ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } rec->data_len -= transform->taglen; /* * Prepare nonce from dynamic and static parts. */ ssl_build_record_nonce( iv, sizeof( iv ), transform->iv_dec, transform->fixed_ivlen, dynamic_iv, dynamic_iv_len ); /* * Build additional data for AEAD encryption. * This depends on the TLS version. */ ssl_extract_add_data_from_record( add_data, &add_data_len, rec, transform->minor_ver ); MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD", add_data, add_data_len ); /* Because of the check above, we know that there are * explicit_iv_len Bytes preceeding data, and taglen * bytes following data + data_len. This justifies * the debug message and the invocation of * mbedtls_cipher_auth_decrypt() below. */ MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", iv, transform->ivlen ); MBEDTLS_SSL_DEBUG_BUF( 4, "TAG used", data + rec->data_len, transform->taglen ); /* * Decrypt and authenticate */ if( ( ret = mbedtls_cipher_auth_decrypt_ext( &transform->cipher_ctx_dec, iv, transform->ivlen, add_data, add_data_len, data, rec->data_len + transform->taglen, /* src */ data, rec->buf_len - (data - rec->buf), &olen, /* dst */ transform->taglen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_decrypt", ret ); if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED ) return( MBEDTLS_ERR_SSL_INVALID_MAC ); return( ret ); } auth_done++; /* Double-check that AEAD decryption doesn't change content length. */ if( olen != rec->data_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } else #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */ #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) if( mode == MBEDTLS_MODE_CBC ) { size_t minlen = 0; /* * Check immediate ciphertext sanity */ #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) { /* The ciphertext is prefixed with the CBC IV. */ minlen += transform->ivlen; } #endif /* Size considerations: * * - The CBC cipher text must not be empty and hence * at least of size transform->ivlen. * * Together with the potential IV-prefix, this explains * the first of the two checks below. * * - The record must contain a MAC, either in plain or * encrypted, depending on whether Encrypt-then-MAC * is used or not. * - If it is, the message contains the IV-prefix, * the CBC ciphertext, and the MAC. * - If it is not, the padded plaintext, and hence * the CBC ciphertext, has at least length maclen + 1 * because there is at least the padding length byte. * * As the CBC ciphertext is not empty, both cases give the * lower bound minlen + maclen + 1 on the record size, which * we test for in the second check below. */ if( rec->data_len < minlen + transform->ivlen || rec->data_len < minlen + transform->maclen + 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%" MBEDTLS_PRINTF_SIZET ") < max( ivlen(%" MBEDTLS_PRINTF_SIZET "), maclen (%" MBEDTLS_PRINTF_SIZET ") " "+ 1 ) ( + expl IV )", rec->data_len, transform->ivlen, transform->maclen ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } /* * Authenticate before decrypt if enabled */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) if( transform->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED ) { unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD]; MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) ); /* Update data_len in tandem with add_data. * * The subtraction is safe because of the previous check * data_len >= minlen + maclen + 1. * * Afterwards, we know that data + data_len is followed by at * least maclen Bytes, which justifies the call to * timingsafe_bcmp() below. * * Further, we still know that data_len > minlen */ rec->data_len -= transform->maclen; ssl_extract_add_data_from_record( add_data, &add_data_len, rec, transform->minor_ver ); /* Calculate expected MAC. */ MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", add_data, add_data_len ); mbedtls_md_hmac_update( &transform->md_ctx_dec, add_data, add_data_len ); mbedtls_md_hmac_update( &transform->md_ctx_dec, data, rec->data_len ); mbedtls_md_hmac_finish( &transform->md_ctx_dec, mac_expect ); mbedtls_md_hmac_reset( &transform->md_ctx_dec ); MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", data + rec->data_len, transform->maclen ); MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect, transform->maclen ); /* Compare expected MAC with MAC at the end of the record. */ if( timingsafe_bcmp( data + rec->data_len, mac_expect, transform->maclen ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } auth_done++; } #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ /* * Check length sanity */ /* We know from above that data_len > minlen >= 0, * so the following check in particular implies that * data_len >= minlen + ivlen ( = minlen or 2 * minlen ). */ if( rec->data_len % transform->ivlen != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%" MBEDTLS_PRINTF_SIZET ") %% ivlen (%" MBEDTLS_PRINTF_SIZET ") != 0", rec->data_len, transform->ivlen ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) /* * Initialize for prepended IV for block cipher in TLS v1.1 and up */ if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) { /* Safe because data_len >= minlen + ivlen = 2 * ivlen. */ memcpy( transform->iv_dec, data, transform->ivlen ); data += transform->ivlen; rec->data_offset += transform->ivlen; rec->data_len -= transform->ivlen; } #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */ /* We still have data_len % ivlen == 0 and data_len >= ivlen here. */ if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_dec, transform->iv_dec, transform->ivlen, data, rec->data_len, data, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); return( ret ); } /* Double-check that length hasn't changed during decryption. */ if( rec->data_len != olen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) if( transform->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ) { /* * Save IV in SSL3 and TLS1, where CBC decryption of consecutive * records is equivalent to CBC decryption of the concatenation * of the records; in other words, IVs are maintained across * record decryptions. */ memcpy( transform->iv_dec, transform->cipher_ctx_dec.iv, transform->ivlen ); } #endif /* Safe since data_len >= minlen + maclen + 1, so after having * subtracted at most minlen and maclen up to this point, * data_len > 0 (because of data_len % ivlen == 0, it's actually * >= ivlen ). */ padlen = data[rec->data_len - 1]; if( auth_done == 1 ) { const size_t mask = mbedtls_ssl_cf_mask_ge( rec->data_len, padlen + 1 ); correct &= mask; padlen &= mask; } else { #if defined(MBEDTLS_SSL_DEBUG_ALL) if( rec->data_len < transform->maclen + padlen + 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%" MBEDTLS_PRINTF_SIZET ") < maclen (%" MBEDTLS_PRINTF_SIZET ") + padlen (%" MBEDTLS_PRINTF_SIZET ")", rec->data_len, transform->maclen, padlen + 1 ) ); } #endif const size_t mask = mbedtls_ssl_cf_mask_ge( rec->data_len, transform->maclen + padlen + 1 ); correct &= mask; padlen &= mask; } padlen++; /* Regardless of the validity of the padding, * we have data_len >= padlen here. */ #if defined(MBEDTLS_SSL_PROTO_SSL3) if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { /* This is the SSL 3.0 path, we don't have to worry about Lucky * 13, because there's a strictly worse padding attack built in * the protocol (known as part of POODLE), so we don't care if the * code is not constant-time, in particular branches are OK. */ if( padlen > transform->ivlen ) { #if defined(MBEDTLS_SSL_DEBUG_ALL) MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding length: is %" MBEDTLS_PRINTF_SIZET ", " "should be no more than %" MBEDTLS_PRINTF_SIZET, padlen, transform->ivlen ) ); #endif correct = 0; } } else #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( transform->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 ) { /* The padding check involves a series of up to 256 * consecutive memory reads at the end of the record * plaintext buffer. In order to hide the length and * validity of the padding, always perform exactly * `min(256,plaintext_len)` reads (but take into account * only the last `padlen` bytes for the padding check). */ size_t pad_count = 0; volatile unsigned char* const check = data; /* Index of first padding byte; it has been ensured above * that the subtraction is safe. */ size_t const padding_idx = rec->data_len - padlen; size_t const num_checks = rec->data_len <= 256 ? rec->data_len : 256; size_t const start_idx = rec->data_len - num_checks; size_t idx; for( idx = start_idx; idx < rec->data_len; idx++ ) { /* pad_count += (idx >= padding_idx) && * (check[idx] == padlen - 1); */ const size_t mask = mbedtls_ssl_cf_mask_ge( idx, padding_idx ); const size_t equal = mbedtls_ssl_cf_bool_eq( check[idx], padlen - 1 ); pad_count += mask & equal; } correct &= mbedtls_ssl_cf_bool_eq( pad_count, padlen ); #if defined(MBEDTLS_SSL_DEBUG_ALL) if( padlen > 0 && correct == 0 ) MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) ); #endif padlen &= mbedtls_ssl_cf_mask_from_bit( correct ); } else #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* If the padding was found to be invalid, padlen == 0 * and the subtraction is safe. If the padding was found valid, * padlen hasn't been changed and the previous assertion * data_len >= padlen still holds. */ rec->data_len -= padlen; } else #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_DEBUG_ALL) MBEDTLS_SSL_DEBUG_BUF( 4, "raw buffer after decryption", data, rec->data_len ); #endif /* * Authenticate if not done yet. * Compute the MAC regardless of the padding result (RFC4346, CBCTIME). */ #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) if( auth_done == 0 ) { unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD]; unsigned char mac_peer[MBEDTLS_SSL_MAC_ADD]; /* If the initial value of padlen was such that * data_len < maclen + padlen + 1, then padlen * got reset to 1, and the initial check * data_len >= minlen + maclen + 1 * guarantees that at this point we still * have at least data_len >= maclen. * * If the initial value of padlen was such that * data_len >= maclen + padlen + 1, then we have * subtracted either padlen + 1 (if the padding was correct) * or 0 (if the padding was incorrect) since then, * hence data_len >= maclen in any case. */ rec->data_len -= transform->maclen; ssl_extract_add_data_from_record( add_data, &add_data_len, rec, transform->minor_ver ); #if defined(MBEDTLS_SSL_PROTO_SSL3) if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { ssl_mac( &transform->md_ctx_dec, transform->mac_dec, data, rec->data_len, rec->ctr, rec->type, mac_expect ); memcpy( mac_peer, data + rec->data_len, transform->maclen ); } else #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( transform->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 ) { /* * The next two sizes are the minimum and maximum values of * data_len over all padlen values. * * They're independent of padlen, since we previously did * data_len -= padlen. * * Note that max_len + maclen is never more than the buffer * length, as we previously did in_msglen -= maclen too. */ const size_t max_len = rec->data_len + padlen; const size_t min_len = ( max_len > 256 ) ? max_len - 256 : 0; ret = mbedtls_ssl_cf_hmac( &transform->md_ctx_dec, add_data, add_data_len, data, rec->data_len, min_len, max_len, mac_expect ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_cf_hmac", ret ); return( ret ); } mbedtls_ssl_cf_memcpy_offset( mac_peer, data, rec->data_len, min_len, max_len, transform->maclen ); } else #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_DEBUG_ALL) MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect, transform->maclen ); MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", mac_peer, transform->maclen ); #endif if( timingsafe_bcmp( mac_peer, mac_expect, transform->maclen ) != 0 ) { #if defined(MBEDTLS_SSL_DEBUG_ALL) MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) ); #endif correct = 0; } auth_done++; } /* * Finally check the correct flag */ if( correct == 0 ) return( MBEDTLS_ERR_SSL_INVALID_MAC ); #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */ /* Make extra sure authentication was performed, exactly once */ if( auth_done != 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_4 ) { /* Remove inner padding and infer true content type. */ ret = ssl_parse_inner_plaintext( data, &rec->data_len, &rec->type ); if( ret != 0 ) return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) if( rec->cid_len != 0 ) { ret = ssl_parse_inner_plaintext( data, &rec->data_len, &rec->type ); if( ret != 0 ) return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) ); return( 0 ); } #undef MAC_NONE #undef MAC_PLAINTEXT #undef MAC_CIPHERTEXT #if defined(MBEDTLS_ZLIB_SUPPORT) /* * Compression/decompression functions */ static int ssl_compress_buf( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char *msg_post = ssl->out_msg; ptrdiff_t bytes_written = ssl->out_msg - ssl->out_buf; size_t len_pre = ssl->out_msglen; unsigned char *msg_pre = ssl->compress_buf; #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) size_t out_buf_len = ssl->out_buf_len; #else size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN; #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> compress buf" ) ); if( len_pre == 0 ) return( 0 ); memcpy( msg_pre, ssl->out_msg, len_pre ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "before compression: msglen = %" MBEDTLS_PRINTF_SIZET ", ", ssl->out_msglen ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "before compression: output payload", ssl->out_msg, ssl->out_msglen ); ssl->transform_out->ctx_deflate.next_in = msg_pre; ssl->transform_out->ctx_deflate.avail_in = len_pre; ssl->transform_out->ctx_deflate.next_out = msg_post; ssl->transform_out->ctx_deflate.avail_out = out_buf_len - bytes_written; ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH ); if( ret != Z_OK ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) ); return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED ); } ssl->out_msglen = out_buf_len - ssl->transform_out->ctx_deflate.avail_out - bytes_written; MBEDTLS_SSL_DEBUG_MSG( 3, ( "after compression: msglen = %" MBEDTLS_PRINTF_SIZET ", ", ssl->out_msglen ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "after compression: output payload", ssl->out_msg, ssl->out_msglen ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= compress buf" ) ); return( 0 ); } static int ssl_decompress_buf( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char *msg_post = ssl->in_msg; ptrdiff_t header_bytes = ssl->in_msg - ssl->in_buf; size_t len_pre = ssl->in_msglen; unsigned char *msg_pre = ssl->compress_buf; #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) size_t in_buf_len = ssl->in_buf_len; #else size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN; #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) ); if( len_pre == 0 ) return( 0 ); memcpy( msg_pre, ssl->in_msg, len_pre ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %" MBEDTLS_PRINTF_SIZET ", ", ssl->in_msglen ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "before decompression: input payload", ssl->in_msg, ssl->in_msglen ); ssl->transform_in->ctx_inflate.next_in = msg_pre; ssl->transform_in->ctx_inflate.avail_in = len_pre; ssl->transform_in->ctx_inflate.next_out = msg_post; ssl->transform_in->ctx_inflate.avail_out = in_buf_len - header_bytes; ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH ); if( ret != Z_OK ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) ); return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED ); } ssl->in_msglen = in_buf_len - ssl->transform_in->ctx_inflate.avail_out - header_bytes; MBEDTLS_SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %" MBEDTLS_PRINTF_SIZET ", ", ssl->in_msglen ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "after decompression: input payload", ssl->in_msg, ssl->in_msglen ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) ); return( 0 ); } #endif /* MBEDTLS_ZLIB_SUPPORT */ /* * Fill the input message buffer by appending data to it. * The amount of data already fetched is in ssl->in_left. * * If we return 0, is it guaranteed that (at least) nb_want bytes are * available (from this read and/or a previous one). Otherwise, an error code * is returned (possibly EOF or WANT_READ). * * With stream transport (TLS) on success ssl->in_left == nb_want, but * with datagram transport (DTLS) on success ssl->in_left >= nb_want, * since we always read a whole datagram at once. * * For DTLS, it is up to the caller to set ssl->next_record_offset when * they're done reading a record. */ int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len; #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) size_t in_buf_len = ssl->in_buf_len; #else size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN; #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> fetch input" ) ); if( ssl->f_recv == NULL && ssl->f_recv_timeout == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() " "or mbedtls_ssl_set_bio()" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } if( nb_want > in_buf_len - (size_t)( ssl->in_hdr - ssl->in_buf ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "requesting more data than fits" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { uint32_t timeout; /* * The point is, we need to always read a full datagram at once, so we * sometimes read more then requested, and handle the additional data. * It could be the rest of the current record (while fetching the * header) and/or some other records in the same datagram. */ /* * Move to the next record in the already read datagram if applicable */ if( ssl->next_record_offset != 0 ) { if( ssl->in_left < ssl->next_record_offset ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } ssl->in_left -= ssl->next_record_offset; if( ssl->in_left != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "next record in same datagram, offset: %" MBEDTLS_PRINTF_SIZET, ssl->next_record_offset ) ); memmove( ssl->in_hdr, ssl->in_hdr + ssl->next_record_offset, ssl->in_left ); } ssl->next_record_offset = 0; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %" MBEDTLS_PRINTF_SIZET ", nb_want: %" MBEDTLS_PRINTF_SIZET, ssl->in_left, nb_want ) ); /* * Done if we already have enough data. */ if( nb_want <= ssl->in_left) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) ); return( 0 ); } /* * A record can't be split across datagrams. If we need to read but * are not at the beginning of a new record, the caller did something * wrong. */ if( ssl->in_left != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* * Don't even try to read if time's out already. * This avoids by-passing the timer when repeatedly receiving messages * that will end up being dropped. */ if( mbedtls_ssl_check_timer( ssl ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "timer has expired" ) ); ret = MBEDTLS_ERR_SSL_TIMEOUT; } else { len = in_buf_len - ( ssl->in_hdr - ssl->in_buf ); if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) timeout = ssl->handshake->retransmit_timeout; else timeout = ssl->conf->read_timeout; MBEDTLS_SSL_DEBUG_MSG( 3, ( "f_recv_timeout: %lu ms", (unsigned long) timeout ) ); if( ssl->f_recv_timeout != NULL ) ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr, len, timeout ); else ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr, len ); MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret ); if( ret == 0 ) return( MBEDTLS_ERR_SSL_CONN_EOF ); } if( ret == MBEDTLS_ERR_SSL_TIMEOUT ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "timeout" ) ); mbedtls_ssl_set_timer( ssl, 0 ); if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) { if( ssl_double_retransmit_timeout( ssl ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake timeout" ) ); return( MBEDTLS_ERR_SSL_TIMEOUT ); } if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret ); return( ret ); } return( MBEDTLS_ERR_SSL_WANT_READ ); } #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION) else if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) { if( ( ret = mbedtls_ssl_resend_hello_request( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend_hello_request", ret ); return( ret ); } return( MBEDTLS_ERR_SSL_WANT_READ ); } #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */ } if( ret < 0 ) return( ret ); ssl->in_left = ret; } else #endif { MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %" MBEDTLS_PRINTF_SIZET ", nb_want: %" MBEDTLS_PRINTF_SIZET, ssl->in_left, nb_want ) ); while( ssl->in_left < nb_want ) { len = nb_want - ssl->in_left; if( mbedtls_ssl_check_timer( ssl ) != 0 ) ret = MBEDTLS_ERR_SSL_TIMEOUT; else { if( ssl->f_recv_timeout != NULL ) { ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr + ssl->in_left, len, ssl->conf->read_timeout ); } else { ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr + ssl->in_left, len ); } } MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %" MBEDTLS_PRINTF_SIZET ", nb_want: %" MBEDTLS_PRINTF_SIZET, ssl->in_left, nb_want ) ); MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret ); if( ret == 0 ) return( MBEDTLS_ERR_SSL_CONN_EOF ); if( ret < 0 ) return( ret ); if ( (size_t)ret > len || ( INT_MAX > SIZE_MAX && ret > (int)SIZE_MAX ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "f_recv returned %d bytes but only %" MBEDTLS_PRINTF_SIZET " were requested", ret, len ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } ssl->in_left += ret; } } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) ); return( 0 ); } /* * Flush any data not yet written */ int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char *buf; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> flush output" ) ); if( ssl->f_send == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() " "or mbedtls_ssl_set_bio()" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* Avoid incrementing counter if data is flushed */ if( ssl->out_left == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) ); return( 0 ); } while( ssl->out_left > 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "message length: %" MBEDTLS_PRINTF_SIZET ", out_left: %" MBEDTLS_PRINTF_SIZET, mbedtls_ssl_out_hdr_len( ssl ) + ssl->out_msglen, ssl->out_left ) ); buf = ssl->out_hdr - ssl->out_left; ret = ssl->f_send( ssl->p_bio, buf, ssl->out_left ); MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", ret ); if( ret <= 0 ) return( ret ); if( (size_t)ret > ssl->out_left || ( INT_MAX > SIZE_MAX && ret > (int)SIZE_MAX ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "f_send returned %d bytes but only %" MBEDTLS_PRINTF_SIZET " bytes were sent", ret, ssl->out_left ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } ssl->out_left -= ret; } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { ssl->out_hdr = ssl->out_buf; } else #endif { ssl->out_hdr = ssl->out_buf + 8; } mbedtls_ssl_update_out_pointers( ssl, ssl->transform_out ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) ); return( 0 ); } /* * Functions to handle the DTLS retransmission state machine */ #if defined(MBEDTLS_SSL_PROTO_DTLS) /* * Append current handshake message to current outgoing flight */ static int ssl_flight_append( mbedtls_ssl_context *ssl ) { mbedtls_ssl_flight_item *msg; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_flight_append" ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "message appended to flight", ssl->out_msg, ssl->out_msglen ); /* Allocate space for current message */ if( ( msg = mbedtls_calloc( 1, sizeof( mbedtls_ssl_flight_item ) ) ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %" MBEDTLS_PRINTF_SIZET " bytes failed", sizeof( mbedtls_ssl_flight_item ) ) ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } if( ( msg->p = mbedtls_calloc( 1, ssl->out_msglen ) ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %" MBEDTLS_PRINTF_SIZET " bytes failed", ssl->out_msglen ) ); mbedtls_free( msg ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } /* Copy current handshake message with headers */ memcpy( msg->p, ssl->out_msg, ssl->out_msglen ); msg->len = ssl->out_msglen; msg->type = ssl->out_msgtype; msg->next = NULL; /* Append to the current flight */ if( ssl->handshake->flight == NULL ) ssl->handshake->flight = msg; else { mbedtls_ssl_flight_item *cur = ssl->handshake->flight; while( cur->next != NULL ) cur = cur->next; cur->next = msg; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_flight_append" ) ); return( 0 ); } /* * Free the current flight of handshake messages */ void mbedtls_ssl_flight_free( mbedtls_ssl_flight_item *flight ) { mbedtls_ssl_flight_item *cur = flight; mbedtls_ssl_flight_item *next; while( cur != NULL ) { next = cur->next; mbedtls_free( cur->p ); mbedtls_free( cur ); cur = next; } } /* * Swap transform_out and out_ctr with the alternative ones */ static int ssl_swap_epochs( mbedtls_ssl_context *ssl ) { mbedtls_ssl_transform *tmp_transform; unsigned char tmp_out_ctr[8]; if( ssl->transform_out == ssl->handshake->alt_transform_out ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip swap epochs" ) ); return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "swap epochs" ) ); /* Swap transforms */ tmp_transform = ssl->transform_out; ssl->transform_out = ssl->handshake->alt_transform_out; ssl->handshake->alt_transform_out = tmp_transform; /* Swap epoch + sequence_number */ memcpy( tmp_out_ctr, ssl->cur_out_ctr, 8 ); memcpy( ssl->cur_out_ctr, ssl->handshake->alt_out_ctr, 8 ); memcpy( ssl->handshake->alt_out_ctr, tmp_out_ctr, 8 ); /* Adjust to the newly activated transform */ mbedtls_ssl_update_out_pointers( ssl, ssl->transform_out ); #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_activate != NULL ) { int ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } } #endif return( 0 ); } /* * Retransmit the current flight of messages. */ int mbedtls_ssl_resend( mbedtls_ssl_context *ssl ) { int ret = 0; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_resend" ) ); ret = mbedtls_ssl_flight_transmit( ssl ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_resend" ) ); return( ret ); } /* * Transmit or retransmit the current flight of messages. * * Need to remember the current message in case flush_output returns * WANT_WRITE, causing us to exit this function and come back later. * This function must be called until state is no longer SENDING. */ int mbedtls_ssl_flight_transmit( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_flight_transmit" ) ); if( ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialise flight transmission" ) ); ssl->handshake->cur_msg = ssl->handshake->flight; ssl->handshake->cur_msg_p = ssl->handshake->flight->p + 12; ret = ssl_swap_epochs( ssl ); if( ret != 0 ) return( ret ); ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING; } while( ssl->handshake->cur_msg != NULL ) { size_t max_frag_len; const mbedtls_ssl_flight_item * const cur = ssl->handshake->cur_msg; int const is_finished = ( cur->type == MBEDTLS_SSL_MSG_HANDSHAKE && cur->p[0] == MBEDTLS_SSL_HS_FINISHED ); uint8_t const force_flush = ssl->disable_datagram_packing == 1 ? SSL_FORCE_FLUSH : SSL_DONT_FORCE_FLUSH; /* Swap epochs before sending Finished: we can't do it after * sending ChangeCipherSpec, in case write returns WANT_READ. * Must be done before copying, may change out_msg pointer */ if( is_finished && ssl->handshake->cur_msg_p == ( cur->p + 12 ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "swap epochs to send finished message" ) ); ret = ssl_swap_epochs( ssl ); if( ret != 0 ) return( ret ); } ret = ssl_get_remaining_payload_in_datagram( ssl ); if( ret < 0 ) return( ret ); max_frag_len = (size_t) ret; /* CCS is copied as is, while HS messages may need fragmentation */ if( cur->type == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ) { if( max_frag_len == 0 ) { if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) return( ret ); continue; } memcpy( ssl->out_msg, cur->p, cur->len ); ssl->out_msglen = cur->len; ssl->out_msgtype = cur->type; /* Update position inside current message */ ssl->handshake->cur_msg_p += cur->len; } else { const unsigned char * const p = ssl->handshake->cur_msg_p; const size_t hs_len = cur->len - 12; const size_t frag_off = p - ( cur->p + 12 ); const size_t rem_len = hs_len - frag_off; size_t cur_hs_frag_len, max_hs_frag_len; if( ( max_frag_len < 12 ) || ( max_frag_len == 12 && hs_len != 0 ) ) { if( is_finished ) { ret = ssl_swap_epochs( ssl ); if( ret != 0 ) return( ret ); } if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) return( ret ); continue; } max_hs_frag_len = max_frag_len - 12; cur_hs_frag_len = rem_len > max_hs_frag_len ? max_hs_frag_len : rem_len; if( frag_off == 0 && cur_hs_frag_len != hs_len ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "fragmenting handshake message (%u > %u)", (unsigned) cur_hs_frag_len, (unsigned) max_hs_frag_len ) ); } /* Messages are stored with handshake headers as if not fragmented, * copy beginning of headers then fill fragmentation fields. * Handshake headers: type(1) len(3) seq(2) f_off(3) f_len(3) */ memcpy( ssl->out_msg, cur->p, 6 ); ssl->out_msg[6] = ( ( frag_off >> 16 ) & 0xff ); ssl->out_msg[7] = ( ( frag_off >> 8 ) & 0xff ); ssl->out_msg[8] = ( ( frag_off ) & 0xff ); ssl->out_msg[ 9] = ( ( cur_hs_frag_len >> 16 ) & 0xff ); ssl->out_msg[10] = ( ( cur_hs_frag_len >> 8 ) & 0xff ); ssl->out_msg[11] = ( ( cur_hs_frag_len ) & 0xff ); MBEDTLS_SSL_DEBUG_BUF( 3, "handshake header", ssl->out_msg, 12 ); /* Copy the handshake message content and set records fields */ memcpy( ssl->out_msg + 12, p, cur_hs_frag_len ); ssl->out_msglen = cur_hs_frag_len + 12; ssl->out_msgtype = cur->type; /* Update position inside current message */ ssl->handshake->cur_msg_p += cur_hs_frag_len; } /* If done with the current message move to the next one if any */ if( ssl->handshake->cur_msg_p >= cur->p + cur->len ) { if( cur->next != NULL ) { ssl->handshake->cur_msg = cur->next; ssl->handshake->cur_msg_p = cur->next->p + 12; } else { ssl->handshake->cur_msg = NULL; ssl->handshake->cur_msg_p = NULL; } } /* Actually send the message out */ if( ( ret = mbedtls_ssl_write_record( ssl, force_flush ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); return( ret ); } } if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) return( ret ); /* Update state and set timer */ if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED; else { ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING; mbedtls_ssl_set_timer( ssl, ssl->handshake->retransmit_timeout ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_flight_transmit" ) ); return( 0 ); } /* * To be called when the last message of an incoming flight is received. */ void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl ) { /* We won't need to resend that one any more */ mbedtls_ssl_flight_free( ssl->handshake->flight ); ssl->handshake->flight = NULL; ssl->handshake->cur_msg = NULL; /* The next incoming flight will start with this msg_seq */ ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq; /* We don't want to remember CCS's across flight boundaries. */ ssl->handshake->buffering.seen_ccs = 0; /* Clear future message buffering structure. */ mbedtls_ssl_buffering_free( ssl ); /* Cancel timer */ mbedtls_ssl_set_timer( ssl, 0 ); if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED ) { ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED; } else ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING; } /* * To be called when the last message of an outgoing flight is send. */ void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl ) { ssl_reset_retransmit_timeout( ssl ); mbedtls_ssl_set_timer( ssl, ssl->handshake->retransmit_timeout ); if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED ) { ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED; } else ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING; } #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* * Handshake layer functions */ /* * Write (DTLS: or queue) current handshake (including CCS) message. * * - fill in handshake headers * - update handshake checksum * - DTLS: save message for resending * - then pass to the record layer * * DTLS: except for HelloRequest, messages are only queued, and will only be * actually sent when calling flight_transmit() or resend(). * * Inputs: * - ssl->out_msglen: 4 + actual handshake message len * (4 is the size of handshake headers for TLS) * - ssl->out_msg[0]: the handshake type (ClientHello, ServerHello, etc) * - ssl->out_msg + 4: the handshake message body * * Outputs, ie state before passing to flight_append() or write_record(): * - ssl->out_msglen: the length of the record contents * (including handshake headers but excluding record headers) * - ssl->out_msg: the record contents (handshake headers + content) */ int mbedtls_ssl_write_handshake_msg( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; const size_t hs_len = ssl->out_msglen - 4; const unsigned char hs_type = ssl->out_msg[0]; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write handshake message" ) ); /* * Sanity checks */ if( ssl->out_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE && ssl->out_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ) { /* In SSLv3, the client might send a NoCertificate alert. */ #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C) if( ! ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 && ssl->out_msgtype == MBEDTLS_SSL_MSG_ALERT && ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) ) #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } /* Whenever we send anything different from a * HelloRequest we should be in a handshake - double check. */ if( ! ( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST ) && ssl->handshake == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake != NULL && ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #endif /* Double-check that we did not exceed the bounds * of the outgoing record buffer. * This should never fail as the various message * writing functions must obey the bounds of the * outgoing record buffer, but better be safe. * * Note: We deliberately do not check for the MTU or MFL here. */ if( ssl->out_msglen > MBEDTLS_SSL_OUT_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Record too large: " "size %" MBEDTLS_PRINTF_SIZET ", maximum %" MBEDTLS_PRINTF_SIZET, ssl->out_msglen, (size_t) MBEDTLS_SSL_OUT_CONTENT_LEN ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* * Fill handshake headers */ if( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) { ssl->out_msg[1] = (unsigned char)( hs_len >> 16 ); ssl->out_msg[2] = (unsigned char)( hs_len >> 8 ); ssl->out_msg[3] = (unsigned char)( hs_len ); /* * DTLS has additional fields in the Handshake layer, * between the length field and the actual payload: * uint16 message_seq; * uint24 fragment_offset; * uint24 fragment_length; */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* Make room for the additional DTLS fields */ if( MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen < 8 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS handshake message too large: " "size %" MBEDTLS_PRINTF_SIZET ", maximum %" MBEDTLS_PRINTF_SIZET, hs_len, (size_t) ( MBEDTLS_SSL_OUT_CONTENT_LEN - 12 ) ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } memmove( ssl->out_msg + 12, ssl->out_msg + 4, hs_len ); ssl->out_msglen += 8; /* Write message_seq and update it, except for HelloRequest */ if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST ) { ssl->out_msg[4] = ( ssl->handshake->out_msg_seq >> 8 ) & 0xFF; ssl->out_msg[5] = ( ssl->handshake->out_msg_seq ) & 0xFF; ++( ssl->handshake->out_msg_seq ); } else { ssl->out_msg[4] = 0; ssl->out_msg[5] = 0; } /* Handshake hashes are computed without fragmentation, * so set frag_offset = 0 and frag_len = hs_len for now */ mbedtls_platform_zeroize( ssl->out_msg + 6, 3 ); memcpy( ssl->out_msg + 9, ssl->out_msg + 1, 3 ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* Update running hashes of handshake messages seen */ if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST ) ssl->handshake->update_checksum( ssl, ssl->out_msg, ssl->out_msglen ); } /* Either send now, or just save to be sent (and resent) later */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ! ( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST ) ) { if( ( ret = ssl_flight_append( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_flight_append", ret ); return( ret ); } } else #endif { if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_record", ret ); return( ret ); } } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write handshake message" ) ); return( 0 ); } /* * Record layer functions */ /* * Write current record. * * Uses: * - ssl->out_msgtype: type of the message (AppData, Handshake, Alert, CCS) * - ssl->out_msglen: length of the record content (excl headers) * - ssl->out_msg: record content */ int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl, uint8_t force_flush ) { int ret, done = 0; size_t len = ssl->out_msglen; uint8_t flush = force_flush; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write record" ) ); #if defined(MBEDTLS_ZLIB_SUPPORT) if( ssl->transform_out != NULL && ssl->session_out->compression == MBEDTLS_SSL_COMPRESS_DEFLATE ) { if( ( ret = ssl_compress_buf( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compress_buf", ret ); return( ret ); } len = ssl->out_msglen; } #endif /*MBEDTLS_ZLIB_SUPPORT */ #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_write != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_write()" ) ); ret = mbedtls_ssl_hw_record_write( ssl ); if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_write", ret ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } if( ret == 0 ) done = 1; } #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ if( !done ) { unsigned i; size_t protected_record_size; #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) size_t out_buf_len = ssl->out_buf_len; #else size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN; #endif /* Skip writing the record content type to after the encryption, * as it may change when using the CID extension. */ mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver, ssl->conf->transport, ssl->out_hdr + 1 ); memcpy( ssl->out_ctr, ssl->cur_out_ctr, 8 ); ssl->out_len[0] = (unsigned char)( len >> 8 ); ssl->out_len[1] = (unsigned char)( len ); if( ssl->transform_out != NULL ) { mbedtls_record rec; rec.buf = ssl->out_iv; rec.buf_len = out_buf_len - ( ssl->out_iv - ssl->out_buf ); rec.data_len = ssl->out_msglen; rec.data_offset = ssl->out_msg - rec.buf; memcpy( &rec.ctr[0], ssl->out_ctr, 8 ); mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver, ssl->conf->transport, rec.ver ); rec.type = ssl->out_msgtype; #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) /* The CID is set by mbedtls_ssl_encrypt_buf(). */ rec.cid_len = 0; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ if( ( ret = mbedtls_ssl_encrypt_buf( ssl, ssl->transform_out, &rec, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret ); return( ret ); } if( rec.data_offset != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* Update the record content type and CID. */ ssl->out_msgtype = rec.type; #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID ) memcpy( ssl->out_cid, rec.cid, rec.cid_len ); #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ ssl->out_msglen = len = rec.data_len; ssl->out_len[0] = (unsigned char)( rec.data_len >> 8 ); ssl->out_len[1] = (unsigned char)( rec.data_len ); } protected_record_size = len + mbedtls_ssl_out_hdr_len( ssl ); #if defined(MBEDTLS_SSL_PROTO_DTLS) /* In case of DTLS, double-check that we don't exceed * the remaining space in the datagram. */ if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { ret = ssl_get_remaining_space_in_datagram( ssl ); if( ret < 0 ) return( ret ); if( protected_record_size > (size_t) ret ) { /* Should never happen */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* Now write the potentially updated record content type. */ ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype; MBEDTLS_SSL_DEBUG_MSG( 3, ( "output record: msgtype = %u, " "version = [%u:%u], msglen = %" MBEDTLS_PRINTF_SIZET, ssl->out_hdr[0], ssl->out_hdr[1], ssl->out_hdr[2], len ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network", ssl->out_hdr, protected_record_size ); ssl->out_left += protected_record_size; ssl->out_hdr += protected_record_size; mbedtls_ssl_update_out_pointers( ssl, ssl->transform_out ); for( i = 8; i > mbedtls_ssl_ep_len( ssl ); i-- ) if( ++ssl->cur_out_ctr[i - 1] != 0 ) break; /* The loop goes to its end iff the counter is wrapping */ if( i == mbedtls_ssl_ep_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "outgoing message counter would wrap" ) ); return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); } } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && flush == SSL_DONT_FORCE_FLUSH ) { size_t remaining; ret = ssl_get_remaining_payload_in_datagram( ssl ); if( ret < 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_remaining_payload_in_datagram", ret ); return( ret ); } remaining = (size_t) ret; if( remaining == 0 ) { flush = SSL_FORCE_FLUSH; } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Still %u bytes available in current datagram", (unsigned) remaining ) ); } } #endif /* MBEDTLS_SSL_PROTO_DTLS */ if( ( flush == SSL_FORCE_FLUSH ) && ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write record" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) static int ssl_hs_is_proper_fragment( mbedtls_ssl_context *ssl ) { if( ssl->in_msglen < ssl->in_hslen || timingsafe_bcmp( ssl->in_msg + 6, "\0\0\0", 3 ) != 0 || timingsafe_bcmp( ssl->in_msg + 9, ssl->in_msg + 1, 3 ) != 0 ) { return( 1 ); } return( 0 ); } static uint32_t ssl_get_hs_frag_len( mbedtls_ssl_context const *ssl ) { return( ( ssl->in_msg[9] << 16 ) | ( ssl->in_msg[10] << 8 ) | ssl->in_msg[11] ); } static uint32_t ssl_get_hs_frag_off( mbedtls_ssl_context const *ssl ) { return( ( ssl->in_msg[6] << 16 ) | ( ssl->in_msg[7] << 8 ) | ssl->in_msg[8] ); } static int ssl_check_hs_header( mbedtls_ssl_context const *ssl ) { uint32_t msg_len, frag_off, frag_len; msg_len = ssl_get_hs_total_len( ssl ); frag_off = ssl_get_hs_frag_off( ssl ); frag_len = ssl_get_hs_frag_len( ssl ); if( frag_off > msg_len ) return( -1 ); if( frag_len > msg_len - frag_off ) return( -1 ); if( frag_len + 12 > ssl->in_msglen ) return( -1 ); return( 0 ); } /* * Mark bits in bitmask (used for DTLS HS reassembly) */ static void ssl_bitmask_set( unsigned char *mask, size_t offset, size_t len ) { unsigned int start_bits, end_bits; start_bits = 8 - ( offset % 8 ); if( start_bits != 8 ) { size_t first_byte_idx = offset / 8; /* Special case */ if( len <= start_bits ) { for( ; len != 0; len-- ) mask[first_byte_idx] |= 1 << ( start_bits - len ); /* Avoid potential issues with offset or len becoming invalid */ return; } offset += start_bits; /* Now offset % 8 == 0 */ len -= start_bits; for( ; start_bits != 0; start_bits-- ) mask[first_byte_idx] |= 1 << ( start_bits - 1 ); } end_bits = len % 8; if( end_bits != 0 ) { size_t last_byte_idx = ( offset + len ) / 8; len -= end_bits; /* Now len % 8 == 0 */ for( ; end_bits != 0; end_bits-- ) mask[last_byte_idx] |= 1 << ( 8 - end_bits ); } memset( mask + offset / 8, 0xFF, len / 8 ); } /* * Check that bitmask is full */ static int ssl_bitmask_check( unsigned char *mask, size_t len ) { size_t i; for( i = 0; i < len / 8; i++ ) if( mask[i] != 0xFF ) return( -1 ); for( i = 0; i < len % 8; i++ ) if( ( mask[len / 8] & ( 1 << ( 7 - i ) ) ) == 0 ) return( -1 ); return( 0 ); } /* msg_len does not include the handshake header */ static size_t ssl_get_reassembly_buffer_size( size_t msg_len, unsigned add_bitmap ) { size_t alloc_len; alloc_len = 12; /* Handshake header */ alloc_len += msg_len; /* Content buffer */ if( add_bitmap ) alloc_len += msg_len / 8 + ( msg_len % 8 != 0 ); /* Bitmap */ return( alloc_len ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl ) { return( ( ssl->in_msg[1] << 16 ) | ( ssl->in_msg[2] << 8 ) | ssl->in_msg[3] ); } int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl ) { if( ssl->in_msglen < mbedtls_ssl_hs_hdr_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too short: %" MBEDTLS_PRINTF_SIZET, ssl->in_msglen ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } ssl->in_hslen = mbedtls_ssl_hs_hdr_len( ssl ) + ssl_get_hs_total_len( ssl ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "handshake message: msglen =" " %" MBEDTLS_PRINTF_SIZET ", type = %u, hslen = %" MBEDTLS_PRINTF_SIZET, ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned int recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5]; if( ssl_check_hs_header( ssl ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid handshake header" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } if( ssl->handshake != NULL && ( ( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER && recv_msg_seq != ssl->handshake->in_msg_seq ) || ( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER && ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) ) ) { if( recv_msg_seq > ssl->handshake->in_msg_seq ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "received future handshake message of sequence number %u (next %u)", recv_msg_seq, ssl->handshake->in_msg_seq ) ); return( MBEDTLS_ERR_SSL_EARLY_MESSAGE ); } /* Retransmit only on last message from previous flight, to avoid * too many retransmissions. * Besides, No sane server ever retransmits HelloVerifyRequest */ if( recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 && ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "received message from last flight, " "message_seq = %u, start_of_flight = %u", recv_msg_seq, ssl->handshake->in_flight_start_seq ) ); if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret ); return( ret ); } } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "dropping out-of-sequence message: " "message_seq = %u, expected = %u", recv_msg_seq, ssl->handshake->in_msg_seq ) ); } return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING ); } /* Wait until message completion to increment in_msg_seq */ /* Message reassembly is handled alongside buffering of future * messages; the commonality is that both handshake fragments and * future messages cannot be forwarded immediately to the * handshake logic layer. */ if( ssl_hs_is_proper_fragment( ssl ) == 1 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "found fragmented DTLS handshake message" ) ); return( MBEDTLS_ERR_SSL_EARLY_MESSAGE ); } } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* With TLS we don't handle fragmentation (for now) */ if( ssl->in_msglen < ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLS handshake fragmentation not supported" ) ); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } return( 0 ); } void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl ) { mbedtls_ssl_handshake_params * const hs = ssl->handshake; if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER && hs != NULL ) { ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen ); } /* Handshake message is complete, increment counter */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake != NULL ) { unsigned offset; mbedtls_ssl_hs_buffer *hs_buf; /* Increment handshake sequence number */ hs->in_msg_seq++; /* * Clear up handshake buffering and reassembly structure. */ /* Free first entry */ ssl_buffering_free_slot( ssl, 0 ); /* Shift all other entries */ for( offset = 0, hs_buf = &hs->buffering.hs[0]; offset + 1 < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++, hs_buf++ ) { *hs_buf = *(hs_buf + 1); } /* Create a fresh last entry */ mbedtls_platform_zeroize( hs_buf, sizeof( mbedtls_ssl_hs_buffer ) ); } #endif } /* * DTLS anti-replay: RFC 6347 4.1.2.6 * * in_window is a field of bits numbered from 0 (lsb) to 63 (msb). * Bit n is set iff record number in_window_top - n has been seen. * * Usually, in_window_top is the last record number seen and the lsb of * in_window is set. The only exception is the initial state (record number 0 * not seen yet). */ #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) void mbedtls_ssl_dtls_replay_reset( mbedtls_ssl_context *ssl ) { ssl->in_window_top = 0; ssl->in_window = 0; } static inline uint64_t ssl_load_six_bytes( unsigned char *buf ) { return( ( (uint64_t) buf[0] << 40 ) | ( (uint64_t) buf[1] << 32 ) | ( (uint64_t) buf[2] << 24 ) | ( (uint64_t) buf[3] << 16 ) | ( (uint64_t) buf[4] << 8 ) | ( (uint64_t) buf[5] ) ); } static int mbedtls_ssl_dtls_record_replay_check( mbedtls_ssl_context *ssl, uint8_t *record_in_ctr ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char *original_in_ctr; // save original in_ctr original_in_ctr = ssl->in_ctr; // use counter from record ssl->in_ctr = record_in_ctr; ret = mbedtls_ssl_dtls_replay_check( (mbedtls_ssl_context const *) ssl ); // restore the counter ssl->in_ctr = original_in_ctr; return ret; } /* * Return 0 if sequence number is acceptable, -1 otherwise */ int mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context const *ssl ) { uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 ); uint64_t bit; if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED ) return( 0 ); if( rec_seqnum > ssl->in_window_top ) return( 0 ); bit = ssl->in_window_top - rec_seqnum; if( bit >= 64 ) return( -1 ); if( ( ssl->in_window & ( (uint64_t) 1 << bit ) ) != 0 ) return( -1 ); return( 0 ); } /* * Update replay window on new validated record */ void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl ) { uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 ); if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED ) return; if( rec_seqnum > ssl->in_window_top ) { /* Update window_top and the contents of the window */ uint64_t shift = rec_seqnum - ssl->in_window_top; if( shift >= 64 ) ssl->in_window = 1; else { ssl->in_window <<= shift; ssl->in_window |= 1; } ssl->in_window_top = rec_seqnum; } else { /* Mark that number as seen in the current window */ uint64_t bit = ssl->in_window_top - rec_seqnum; if( bit < 64 ) /* Always true, but be extra sure */ ssl->in_window |= (uint64_t) 1 << bit; } } #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */ #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C) /* * Without any SSL context, check if a datagram looks like a ClientHello with * a valid cookie, and if it doesn't, generate a HelloVerifyRequest message. * Both input and output include full DTLS headers. * * - if cookie is valid, return 0 * - if ClientHello looks superficially valid but cookie is not, * fill obuf and set olen, then * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED * - otherwise return a specific error code */ static int ssl_check_dtls_clihlo_cookie( mbedtls_ssl_cookie_write_t *f_cookie_write, mbedtls_ssl_cookie_check_t *f_cookie_check, void *p_cookie, const unsigned char *cli_id, size_t cli_id_len, const unsigned char *in, size_t in_len, unsigned char *obuf, size_t buf_len, size_t *olen ) { size_t sid_len, cookie_len; unsigned char *p; /* * Structure of ClientHello with record and handshake headers, * and expected values. We don't need to check a lot, more checks will be * done when actually parsing the ClientHello - skipping those checks * avoids code duplication and does not make cookie forging any easier. * * 0-0 ContentType type; copied, must be handshake * 1-2 ProtocolVersion version; copied * 3-4 uint16 epoch; copied, must be 0 * 5-10 uint48 sequence_number; copied * 11-12 uint16 length; (ignored) * * 13-13 HandshakeType msg_type; (ignored) * 14-16 uint24 length; (ignored) * 17-18 uint16 message_seq; copied * 19-21 uint24 fragment_offset; copied, must be 0 * 22-24 uint24 fragment_length; (ignored) * * 25-26 ProtocolVersion client_version; (ignored) * 27-58 Random random; (ignored) * 59-xx SessionID session_id; 1 byte len + sid_len content * 60+ opaque cookie<0..2^8-1>; 1 byte len + content * ... * * Minimum length is 61 bytes. */ if( in_len < 61 || in[0] != MBEDTLS_SSL_MSG_HANDSHAKE || in[3] != 0 || in[4] != 0 || in[19] != 0 || in[20] != 0 || in[21] != 0 ) { return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } sid_len = in[59]; if( sid_len > in_len - 61 ) return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); cookie_len = in[60 + sid_len]; if( cookie_len > in_len - 60 ) return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); if( f_cookie_check( p_cookie, in + sid_len + 61, cookie_len, cli_id, cli_id_len ) == 0 ) { /* Valid cookie */ return( 0 ); } /* * If we get here, we've got an invalid cookie, let's prepare HVR. * * 0-0 ContentType type; copied * 1-2 ProtocolVersion version; copied * 3-4 uint16 epoch; copied * 5-10 uint48 sequence_number; copied * 11-12 uint16 length; olen - 13 * * 13-13 HandshakeType msg_type; hello_verify_request * 14-16 uint24 length; olen - 25 * 17-18 uint16 message_seq; copied * 19-21 uint24 fragment_offset; copied * 22-24 uint24 fragment_length; olen - 25 * * 25-26 ProtocolVersion server_version; 0xfe 0xff * 27-27 opaque cookie<0..2^8-1>; cookie_len = olen - 27, cookie * * Minimum length is 28. */ if( buf_len < 28 ) return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); /* Copy most fields and adapt others */ memcpy( obuf, in, 25 ); obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST; obuf[25] = 0xfe; obuf[26] = 0xff; /* Generate and write actual cookie */ p = obuf + 28; if( f_cookie_write( p_cookie, &p, obuf + buf_len, cli_id, cli_id_len ) != 0 ) { return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } *olen = p - obuf; /* Go back and fill length fields */ obuf[27] = (unsigned char)( *olen - 28 ); obuf[14] = obuf[22] = (unsigned char)( ( *olen - 25 ) >> 16 ); obuf[15] = obuf[23] = (unsigned char)( ( *olen - 25 ) >> 8 ); obuf[16] = obuf[24] = (unsigned char)( ( *olen - 25 ) ); obuf[11] = (unsigned char)( ( *olen - 13 ) >> 8 ); obuf[12] = (unsigned char)( ( *olen - 13 ) ); return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED ); } /* * Handle possible client reconnect with the same UDP quadruplet * (RFC 6347 Section 4.2.8). * * Called by ssl_parse_record_header() in case we receive an epoch 0 record * that looks like a ClientHello. * * - if the input looks like a ClientHello without cookies, * send back HelloVerifyRequest, then return 0 * - if the input looks like a ClientHello with a valid cookie, * reset the session of the current context, and * return MBEDTLS_ERR_SSL_CLIENT_RECONNECT * - if anything goes wrong, return a specific error code * * This function is called (through ssl_check_client_reconnect()) when an * unexpected record is found in ssl_get_next_record(), which will discard the * record if we return 0, and bubble up the return value otherwise (this * includes the case of MBEDTLS_ERR_SSL_CLIENT_RECONNECT and of unexpected * errors, and is the right thing to do in both cases). */ static int ssl_handle_possible_reconnect( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len; if( ssl->conf->f_cookie_write == NULL || ssl->conf->f_cookie_check == NULL ) { /* If we can't use cookies to verify reachability of the peer, * drop the record. */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "no cookie callbacks, " "can't check reconnect validity" ) ); return( 0 ); } ret = ssl_check_dtls_clihlo_cookie( ssl->conf->f_cookie_write, ssl->conf->f_cookie_check, ssl->conf->p_cookie, ssl->cli_id, ssl->cli_id_len, ssl->in_buf, ssl->in_left, ssl->out_buf, MBEDTLS_SSL_OUT_CONTENT_LEN, &len ); MBEDTLS_SSL_DEBUG_RET( 2, "ssl_check_dtls_clihlo_cookie", ret ); if( ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED ) { int send_ret; MBEDTLS_SSL_DEBUG_MSG( 1, ( "sending HelloVerifyRequest" ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network", ssl->out_buf, len ); /* Don't check write errors as we can't do anything here. * If the error is permanent we'll catch it later, * if it's not, then hopefully it'll work next time. */ send_ret = ssl->f_send( ssl->p_bio, ssl->out_buf, len ); MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", send_ret ); (void) send_ret; return( 0 ); } if( ret == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "cookie is valid, resetting context" ) ); if( ( ret = mbedtls_ssl_session_reset_int( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "reset", ret ); return( ret ); } return( MBEDTLS_ERR_SSL_CLIENT_RECONNECT ); } return( ret ); } #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */ static int ssl_check_record_type( uint8_t record_type ) { if( record_type != MBEDTLS_SSL_MSG_HANDSHAKE && record_type != MBEDTLS_SSL_MSG_ALERT && record_type != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC && record_type != MBEDTLS_SSL_MSG_APPLICATION_DATA ) { return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } return( 0 ); } /* * ContentType type; * ProtocolVersion version; * uint16 epoch; // DTLS only * uint48 sequence_number; // DTLS only * uint16 length; * * Return 0 if header looks sane (and, for DTLS, the record is expected) * MBEDTLS_ERR_SSL_INVALID_RECORD if the header looks bad, * MBEDTLS_ERR_SSL_UNEXPECTED_RECORD (DTLS only) if sane but unexpected. * * With DTLS, mbedtls_ssl_read_record() will: * 1. proceed with the record if this function returns 0 * 2. drop only the current record if this function returns UNEXPECTED_RECORD * 3. return CLIENT_RECONNECT if this function return that value * 4. drop the whole datagram if this function returns anything else. * Point 2 is needed when the peer is resending, and we have already received * the first record from a datagram but are still waiting for the others. */ static int ssl_parse_record_header( mbedtls_ssl_context const *ssl, unsigned char *buf, size_t len, mbedtls_record *rec ) { int major_ver, minor_ver; size_t const rec_hdr_type_offset = 0; size_t const rec_hdr_type_len = 1; size_t const rec_hdr_version_offset = rec_hdr_type_offset + rec_hdr_type_len; size_t const rec_hdr_version_len = 2; size_t const rec_hdr_ctr_len = 8; #if defined(MBEDTLS_SSL_PROTO_DTLS) uint32_t rec_epoch; size_t const rec_hdr_ctr_offset = rec_hdr_version_offset + rec_hdr_version_len; #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) size_t const rec_hdr_cid_offset = rec_hdr_ctr_offset + rec_hdr_ctr_len; size_t rec_hdr_cid_len = 0; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #endif /* MBEDTLS_SSL_PROTO_DTLS */ size_t rec_hdr_len_offset; /* To be determined */ size_t const rec_hdr_len_len = 2; /* * Check minimum lengths for record header. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { rec_hdr_len_offset = rec_hdr_ctr_offset + rec_hdr_ctr_len; } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ { rec_hdr_len_offset = rec_hdr_version_offset + rec_hdr_version_len; } if( len < rec_hdr_len_offset + rec_hdr_len_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "datagram of length %u too small to hold DTLS record header of length %u", (unsigned) len, (unsigned)( rec_hdr_len_len + rec_hdr_len_len ) ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } /* * Parse and validate record content type */ rec->type = buf[ rec_hdr_type_offset ]; /* Check record content type */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) rec->cid_len = 0; if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->conf->cid_len != 0 && rec->type == MBEDTLS_SSL_MSG_CID ) { /* Shift pointers to account for record header including CID * struct { * ContentType special_type = tls12_cid; * ProtocolVersion version; * uint16 epoch; * uint48 sequence_number; * opaque cid[cid_length]; // Additional field compared to * // default DTLS record format * uint16 length; * opaque enc_content[DTLSCiphertext.length]; * } DTLSCiphertext; */ /* So far, we only support static CID lengths * fixed in the configuration. */ rec_hdr_cid_len = ssl->conf->cid_len; rec_hdr_len_offset += rec_hdr_cid_len; if( len < rec_hdr_len_offset + rec_hdr_len_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "datagram of length %u too small to hold DTLS record header including CID, length %u", (unsigned) len, (unsigned)( rec_hdr_len_offset + rec_hdr_len_len ) ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } /* configured CID len is guaranteed at most 255, see * MBEDTLS_SSL_CID_OUT_LEN_MAX in check_config.h */ rec->cid_len = (uint8_t) rec_hdr_cid_len; memcpy( rec->cid, buf + rec_hdr_cid_offset, rec_hdr_cid_len ); } else #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ { if( ssl_check_record_type( rec->type ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type %u", (unsigned) rec->type ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } } /* * Parse and validate record version */ rec->ver[0] = buf[ rec_hdr_version_offset + 0 ]; rec->ver[1] = buf[ rec_hdr_version_offset + 1 ]; mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, &rec->ver[0] ); if( major_ver != ssl->major_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "major version mismatch" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } if( minor_ver > ssl->conf->max_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "minor version mismatch" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } /* * Parse/Copy record sequence number. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* Copy explicit record sequence number from input buffer. */ memcpy( &rec->ctr[0], buf + rec_hdr_ctr_offset, rec_hdr_ctr_len ); } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ { /* Copy implicit record sequence number from SSL context structure. */ memcpy( &rec->ctr[0], ssl->in_ctr, rec_hdr_ctr_len ); } /* * Parse record length. */ rec->data_offset = rec_hdr_len_offset + rec_hdr_len_len; rec->data_len = ( (size_t) buf[ rec_hdr_len_offset + 0 ] << 8 ) | ( (size_t) buf[ rec_hdr_len_offset + 1 ] << 0 ); MBEDTLS_SSL_DEBUG_BUF( 4, "input record header", buf, rec->data_offset ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "input record: msgtype = %u, " "version = [%d:%d], msglen = %" MBEDTLS_PRINTF_SIZET, rec->type, major_ver, minor_ver, rec->data_len ) ); rec->buf = buf; rec->buf_len = rec->data_offset + rec->data_len; if( rec->data_len == 0 ) return( MBEDTLS_ERR_SSL_INVALID_RECORD ); /* * DTLS-related tests. * Check epoch before checking length constraint because * the latter varies with the epoch. E.g., if a ChangeCipherSpec * message gets duplicated before the corresponding Finished message, * the second ChangeCipherSpec should be discarded because it belongs * to an old epoch, but not because its length is shorter than * the minimum record length for packets using the new record transform. * Note that these two kinds of failures are handled differently, * as an unexpected record is silently skipped but an invalid * record leads to the entire datagram being dropped. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { rec_epoch = ( rec->ctr[0] << 8 ) | rec->ctr[1]; /* Check that the datagram is large enough to contain a record * of the advertised length. */ if( len < rec->data_offset + rec->data_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Datagram of length %u too small to contain record of advertised length %u.", (unsigned) len, (unsigned)( rec->data_offset + rec->data_len ) ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } /* Records from other, non-matching epochs are silently discarded. * (The case of same-port Client reconnects must be considered in * the caller). */ if( rec_epoch != ssl->in_epoch ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "record from another epoch: " "expected %u, received %lu", ssl->in_epoch, (unsigned long) rec_epoch ) ); /* Records from the next epoch are considered for buffering * (concretely: early Finished messages). */ if( rec_epoch == (unsigned) ssl->in_epoch + 1 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Consider record for buffering" ) ); return( MBEDTLS_ERR_SSL_EARLY_MESSAGE ); } return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); } #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) /* For records from the correct epoch, check whether their * sequence number has been seen before. */ else if( mbedtls_ssl_dtls_record_replay_check( (mbedtls_ssl_context *) ssl, &rec->ctr[0] ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); } #endif } #endif /* MBEDTLS_SSL_PROTO_DTLS */ return( 0 ); } #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C) static int ssl_check_client_reconnect( mbedtls_ssl_context *ssl ) { unsigned int rec_epoch = ( ssl->in_ctr[0] << 8 ) | ssl->in_ctr[1]; /* * Check for an epoch 0 ClientHello. We can't use in_msg here to * access the first byte of record content (handshake type), as we * have an active transform (possibly iv_len != 0), so use the * fact that the record header len is 13 instead. */ if( rec_epoch == 0 && ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER && ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && ssl->in_left > 13 && ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "possible client reconnect " "from the same port" ) ); return( ssl_handle_possible_reconnect( ssl ) ); } return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */ /* * If applicable, decrypt record content */ static int ssl_prepare_record_content( mbedtls_ssl_context *ssl, mbedtls_record *rec ) { int ret, done = 0; MBEDTLS_SSL_DEBUG_BUF( 4, "input record from network", rec->buf, rec->buf_len ); #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_read != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_read()" ) ); ret = mbedtls_ssl_hw_record_read( ssl ); if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_read", ret ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } if( ret == 0 ) done = 1; } #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ if( !done && ssl->transform_in != NULL ) { unsigned char const old_msg_type = rec->type; if( ( ret = mbedtls_ssl_decrypt_buf( ssl, ssl->transform_in, rec ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decrypt_buf", ret ); #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_CID && ssl->conf->ignore_unexpected_cid == MBEDTLS_SSL_UNEXPECTED_CID_IGNORE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ignoring unexpected CID" ) ); ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING; } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ return( ret ); } if( old_msg_type != rec->type ) { MBEDTLS_SSL_DEBUG_MSG( 4, ( "record type after decrypt (before %d): %d", old_msg_type, rec->type ) ); } MBEDTLS_SSL_DEBUG_BUF( 4, "input payload after decrypt", rec->buf + rec->data_offset, rec->data_len ); #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) /* We have already checked the record content type * in ssl_parse_record_header(), failing or silently * dropping the record in the case of an unknown type. * * Since with the use of CIDs, the record content type * might change during decryption, re-check the record * content type, but treat a failure as fatal this time. */ if( ssl_check_record_type( rec->type ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ if( rec->data_len == 0 ) { #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 && rec->type != MBEDTLS_SSL_MSG_APPLICATION_DATA ) { /* TLS v1.2 explicitly disallows zero-length messages which are not application data */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid zero-length message type: %d", ssl->in_msgtype ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ ssl->nb_zero++; /* * Three or more empty messages may be a DoS attack * (excessive CPU consumption). */ if( ssl->nb_zero > 3 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "received four consecutive empty " "messages, possible DoS attack" ) ); /* Treat the records as if they were not properly authenticated, * thereby failing the connection if we see more than allowed * by the configured bad MAC threshold. */ return( MBEDTLS_ERR_SSL_INVALID_MAC ); } } else ssl->nb_zero = 0; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { ; /* in_ctr read from peer, not maintained internally */ } else #endif { unsigned i; for( i = 8; i > mbedtls_ssl_ep_len( ssl ); i-- ) if( ++ssl->in_ctr[i - 1] != 0 ) break; /* The loop goes to its end iff the counter is wrapping */ if( i == mbedtls_ssl_ep_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "incoming message counter would wrap" ) ); return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); } } } #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { mbedtls_ssl_dtls_replay_update( ssl ); } #endif /* Check actual (decrypted) record content length against * configured maximum. */ if( ssl->in_msglen > MBEDTLS_SSL_IN_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } return( 0 ); } /* * Read a record. * * Silently ignore non-fatal alert (and for DTLS, invalid records as well, * RFC 6347 4.1.2.7) and continue reading until a valid record is found. * */ /* Helper functions for mbedtls_ssl_read_record(). */ static int ssl_consume_current_message( mbedtls_ssl_context *ssl ); static int ssl_get_next_record( mbedtls_ssl_context *ssl ); static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl ); /** * \brief Update record layer * * This function roughly separates the implementation * of the logic of (D)TLS from the implementation * of the secure transport. * * \param ssl The SSL context to use. * \param update_hs_digest This indicates if the handshake digest * should be automatically updated in case * a handshake message is found. * * \return 0 or non-zero error code. * * \note A clarification on what is called 'record layer' here * is in order, as many sensible definitions are possible: * * The record layer takes as input an untrusted underlying * transport (stream or datagram) and transforms it into * a serially multiplexed, secure transport, which * conceptually provides the following: * * (1) Three datagram based, content-agnostic transports * for handshake, alert and CCS messages. * (2) One stream- or datagram-based transport * for application data. * (3) Functionality for changing the underlying transform * securing the contents. * * The interface to this functionality is given as follows: * * a Updating * [Currently implemented by mbedtls_ssl_read_record] * * Check if and on which of the four 'ports' data is pending: * Nothing, a controlling datagram of type (1), or application * data (2). In any case data is present, internal buffers * provide access to the data for the user to process it. * Consumption of type (1) datagrams is done automatically * on the next update, invalidating that the internal buffers * for previous datagrams, while consumption of application * data (2) is user-controlled. * * b Reading of application data * [Currently manual adaption of ssl->in_offt pointer] * * As mentioned in the last paragraph, consumption of data * is different from the automatic consumption of control * datagrams (1) because application data is treated as a stream. * * c Tracking availability of application data * [Currently manually through decreasing ssl->in_msglen] * * For efficiency and to retain datagram semantics for * application data in case of DTLS, the record layer * provides functionality for checking how much application * data is still available in the internal buffer. * * d Changing the transformation securing the communication. * * Given an opaque implementation of the record layer in the * above sense, it should be possible to implement the logic * of (D)TLS on top of it without the need to know anything * about the record layer's internals. This is done e.g. * in all the handshake handling functions, and in the * application data reading function mbedtls_ssl_read. * * \note The above tries to give a conceptual picture of the * record layer, but the current implementation deviates * from it in some places. For example, our implementation of * the update functionality through mbedtls_ssl_read_record * discards datagrams depending on the current state, which * wouldn't fall under the record layer's responsibility * following the above definition. */ int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl, unsigned update_hs_digest ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read record" ) ); if( ssl->keep_current_message == 0 ) { do { ret = ssl_consume_current_message( ssl ); if( ret != 0 ) return( ret ); if( ssl_record_is_in_progress( ssl ) == 0 ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) int have_buffered = 0; /* We only check for buffered messages if the * current datagram is fully consumed. */ if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl_next_record_is_in_datagram( ssl ) == 0 ) { if( ssl_load_buffered_message( ssl ) == 0 ) have_buffered = 1; } if( have_buffered == 0 ) #endif /* MBEDTLS_SSL_PROTO_DTLS */ { ret = ssl_get_next_record( ssl ); if( ret == MBEDTLS_ERR_SSL_CONTINUE_PROCESSING ) continue; if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_get_next_record" ), ret ); return( ret ); } } } ret = mbedtls_ssl_handle_message_type( ssl ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE ) { /* Buffer future message */ ret = ssl_buffer_message( ssl ); if( ret != 0 ) return( ret ); ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING; } #endif /* MBEDTLS_SSL_PROTO_DTLS */ } while( MBEDTLS_ERR_SSL_NON_FATAL == ret || MBEDTLS_ERR_SSL_CONTINUE_PROCESSING == ret ); if( 0 != ret ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_handle_message_type" ), ret ); return( ret ); } if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && update_hs_digest == 1 ) { mbedtls_ssl_update_handshake_status( ssl ); } } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "reuse previously read message" ) ); ssl->keep_current_message = 0; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read record" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl ) { if( ssl->in_left > ssl->next_record_offset ) return( 1 ); return( 0 ); } static int ssl_load_buffered_message( mbedtls_ssl_context *ssl ) { mbedtls_ssl_handshake_params * const hs = ssl->handshake; mbedtls_ssl_hs_buffer * hs_buf; int ret = 0; if( hs == NULL ) return( -1 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_messsage" ) ); if( ssl->state == MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC || ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC ) { /* Check if we have seen a ChangeCipherSpec before. * If yes, synthesize a CCS record. */ if( !hs->buffering.seen_ccs ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "CCS not seen in the current flight" ) ); ret = -1; goto exit; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "Injecting buffered CCS message" ) ); ssl->in_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC; ssl->in_msglen = 1; ssl->in_msg[0] = 1; /* As long as they are equal, the exact value doesn't matter. */ ssl->in_left = 0; ssl->next_record_offset = 0; hs->buffering.seen_ccs = 0; goto exit; } #if defined(MBEDTLS_DEBUG_C) /* Debug only */ { unsigned offset; for( offset = 1; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++ ) { hs_buf = &hs->buffering.hs[offset]; if( hs_buf->is_valid == 1 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Future message with sequence number %u %s buffered.", hs->in_msg_seq + offset, hs_buf->is_complete ? "fully" : "partially" ) ); } } } #endif /* MBEDTLS_DEBUG_C */ /* Check if we have buffered and/or fully reassembled the * next handshake message. */ hs_buf = &hs->buffering.hs[0]; if( ( hs_buf->is_valid == 1 ) && ( hs_buf->is_complete == 1 ) ) { /* Synthesize a record containing the buffered HS message. */ size_t msg_len = ( hs_buf->data[1] << 16 ) | ( hs_buf->data[2] << 8 ) | hs_buf->data[3]; /* Double-check that we haven't accidentally buffered * a message that doesn't fit into the input buffer. */ if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message has been buffered - load" ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered handshake message (incl. header)", hs_buf->data, msg_len + 12 ); ssl->in_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->in_hslen = msg_len + 12; ssl->in_msglen = msg_len + 12; memcpy( ssl->in_msg, hs_buf->data, ssl->in_hslen ); ret = 0; goto exit; } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message %u not or only partially bufffered", hs->in_msg_seq ) ); } ret = -1; exit: MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_message" ) ); return( ret ); } static int ssl_buffer_make_space( mbedtls_ssl_context *ssl, size_t desired ) { int offset; mbedtls_ssl_handshake_params * const hs = ssl->handshake; MBEDTLS_SSL_DEBUG_MSG( 2, ( "Attempt to free buffered messages to have %u bytes available", (unsigned) desired ) ); /* Get rid of future records epoch first, if such exist. */ ssl_free_buffered_record( ssl ); /* Check if we have enough space available now. */ if( desired <= ( MBEDTLS_SSL_DTLS_MAX_BUFFERING - hs->buffering.total_bytes_buffered ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing future epoch record" ) ); return( 0 ); } /* We don't have enough space to buffer the next expected handshake * message. Remove buffers used for future messages to gain space, * starting with the most distant one. */ for( offset = MBEDTLS_SSL_MAX_BUFFERED_HS - 1; offset >= 0; offset-- ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Free buffering slot %d to make space for reassembly of next handshake message", offset ) ); ssl_buffering_free_slot( ssl, (uint8_t) offset ); /* Check if we have enough space available now. */ if( desired <= ( MBEDTLS_SSL_DTLS_MAX_BUFFERING - hs->buffering.total_bytes_buffered ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing buffered HS messages" ) ); return( 0 ); } } return( -1 ); } static int ssl_buffer_message( mbedtls_ssl_context *ssl ) { int ret = 0; mbedtls_ssl_handshake_params * const hs = ssl->handshake; if( hs == NULL ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_buffer_message" ) ); switch( ssl->in_msgtype ) { case MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC: MBEDTLS_SSL_DEBUG_MSG( 2, ( "Remember CCS message" ) ); hs->buffering.seen_ccs = 1; break; case MBEDTLS_SSL_MSG_HANDSHAKE: { unsigned recv_msg_seq_offset; unsigned recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5]; mbedtls_ssl_hs_buffer *hs_buf; size_t msg_len = ssl->in_hslen - 12; /* We should never receive an old handshake * message - double-check nonetheless. */ if( recv_msg_seq < ssl->handshake->in_msg_seq ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } recv_msg_seq_offset = recv_msg_seq - ssl->handshake->in_msg_seq; if( recv_msg_seq_offset >= MBEDTLS_SSL_MAX_BUFFERED_HS ) { /* Silently ignore -- message too far in the future */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "Ignore future HS message with sequence number %u, " "buffering window %u - %u", recv_msg_seq, ssl->handshake->in_msg_seq, ssl->handshake->in_msg_seq + MBEDTLS_SSL_MAX_BUFFERED_HS - 1 ) ); goto exit; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering HS message with sequence number %u, offset %u ", recv_msg_seq, recv_msg_seq_offset ) ); hs_buf = &hs->buffering.hs[ recv_msg_seq_offset ]; /* Check if the buffering for this seq nr has already commenced. */ if( !hs_buf->is_valid ) { size_t reassembly_buf_sz; hs_buf->is_fragmented = ( ssl_hs_is_proper_fragment( ssl ) == 1 ); /* We copy the message back into the input buffer * after reassembly, so check that it's not too large. * This is an implementation-specific limitation * and not one from the standard, hence it is not * checked in ssl_check_hs_header(). */ if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN ) { /* Ignore message */ goto exit; } /* Check if we have enough space to buffer the message. */ if( hs->buffering.total_bytes_buffered > MBEDTLS_SSL_DTLS_MAX_BUFFERING ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } reassembly_buf_sz = ssl_get_reassembly_buffer_size( msg_len, hs_buf->is_fragmented ); if( reassembly_buf_sz > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING - hs->buffering.total_bytes_buffered ) ) { if( recv_msg_seq_offset > 0 ) { /* If we can't buffer a future message because * of space limitations -- ignore. */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future message of size %" MBEDTLS_PRINTF_SIZET " would exceed the compile-time limit %" MBEDTLS_PRINTF_SIZET " (already %" MBEDTLS_PRINTF_SIZET " bytes buffered) -- ignore\n", msg_len, (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING, hs->buffering.total_bytes_buffered ) ); goto exit; } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future message of size %" MBEDTLS_PRINTF_SIZET " would exceed the compile-time limit %" MBEDTLS_PRINTF_SIZET " (already %" MBEDTLS_PRINTF_SIZET " bytes buffered) -- attempt to make space by freeing buffered future messages\n", msg_len, (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING, hs->buffering.total_bytes_buffered ) ); } if( ssl_buffer_make_space( ssl, reassembly_buf_sz ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Reassembly of next message of size %" MBEDTLS_PRINTF_SIZET " (%" MBEDTLS_PRINTF_SIZET " with bitmap) would exceed" " the compile-time limit %" MBEDTLS_PRINTF_SIZET " (already %" MBEDTLS_PRINTF_SIZET " bytes buffered) -- fail\n", msg_len, reassembly_buf_sz, (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING, hs->buffering.total_bytes_buffered ) ); ret = MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL; goto exit; } } MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialize reassembly, total length = %" MBEDTLS_PRINTF_SIZET, msg_len ) ); hs_buf->data = mbedtls_calloc( 1, reassembly_buf_sz ); if( hs_buf->data == NULL ) { ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; goto exit; } hs_buf->data_len = reassembly_buf_sz; /* Prepare final header: copy msg_type, length and message_seq, * then add standardised fragment_offset and fragment_length */ memcpy( hs_buf->data, ssl->in_msg, 6 ); mbedtls_platform_zeroize( hs_buf->data + 6, 3 ); memcpy( hs_buf->data + 9, hs_buf->data + 1, 3 ); hs_buf->is_valid = 1; hs->buffering.total_bytes_buffered += reassembly_buf_sz; } else { /* Make sure msg_type and length are consistent */ if( timingsafe_bcmp( hs_buf->data, ssl->in_msg, 4 ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Fragment header mismatch - ignore" ) ); /* Ignore */ goto exit; } } if( !hs_buf->is_complete ) { size_t frag_len, frag_off; unsigned char * const msg = hs_buf->data + 12; /* * Check and copy current fragment */ /* Validation of header fields already done in * mbedtls_ssl_prepare_handshake_record(). */ frag_off = ssl_get_hs_frag_off( ssl ); frag_len = ssl_get_hs_frag_len( ssl ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "adding fragment, offset = %" MBEDTLS_PRINTF_SIZET ", length = %" MBEDTLS_PRINTF_SIZET, frag_off, frag_len ) ); memcpy( msg + frag_off, ssl->in_msg + 12, frag_len ); if( hs_buf->is_fragmented ) { unsigned char * const bitmask = msg + msg_len; ssl_bitmask_set( bitmask, frag_off, frag_len ); hs_buf->is_complete = ( ssl_bitmask_check( bitmask, msg_len ) == 0 ); } else { hs_buf->is_complete = 1; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "message %scomplete", hs_buf->is_complete ? "" : "not yet " ) ); } break; } default: /* We don't buffer other types of messages. */ break; } exit: MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_buffer_message" ) ); return( ret ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ static int ssl_consume_current_message( mbedtls_ssl_context *ssl ) { /* * Consume last content-layer message and potentially * update in_msglen which keeps track of the contents' * consumption state. * * (1) Handshake messages: * Remove last handshake message, move content * and adapt in_msglen. * * (2) Alert messages: * Consume whole record content, in_msglen = 0. * * (3) Change cipher spec: * Consume whole record content, in_msglen = 0. * * (4) Application data: * Don't do anything - the record layer provides * the application data as a stream transport * and consumes through mbedtls_ssl_read only. * */ /* Case (1): Handshake messages */ if( ssl->in_hslen != 0 ) { /* Hard assertion to be sure that no application data * is in flight, as corrupting ssl->in_msglen during * ssl->in_offt != NULL is fatal. */ if( ssl->in_offt != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* * Get next Handshake message in the current record */ /* Notes: * (1) in_hslen is not necessarily the size of the * current handshake content: If DTLS handshake * fragmentation is used, that's the fragment * size instead. Using the total handshake message * size here is faulty and should be changed at * some point. * (2) While it doesn't seem to cause problems, one * has to be very careful not to assume that in_hslen * is always <= in_msglen in a sensible communication. * Again, it's wrong for DTLS handshake fragmentation. * The following check is therefore mandatory, and * should not be treated as a silently corrected assertion. * Additionally, ssl->in_hslen might be arbitrarily out of * bounds after handling a DTLS message with an unexpected * sequence number, see mbedtls_ssl_prepare_handshake_record. */ if( ssl->in_hslen < ssl->in_msglen ) { ssl->in_msglen -= ssl->in_hslen; memmove( ssl->in_msg, ssl->in_msg + ssl->in_hslen, ssl->in_msglen ); MBEDTLS_SSL_DEBUG_BUF( 4, "remaining content in record", ssl->in_msg, ssl->in_msglen ); } else { ssl->in_msglen = 0; } ssl->in_hslen = 0; } /* Case (4): Application data */ else if( ssl->in_offt != NULL ) { return( 0 ); } /* Everything else (CCS & Alerts) */ else { ssl->in_msglen = 0; } return( 0 ); } static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl ) { if( ssl->in_msglen > 0 ) return( 1 ); return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) static void ssl_free_buffered_record( mbedtls_ssl_context *ssl ) { mbedtls_ssl_handshake_params * const hs = ssl->handshake; if( hs == NULL ) return; if( hs->buffering.future_record.data != NULL ) { hs->buffering.total_bytes_buffered -= hs->buffering.future_record.len; mbedtls_free( hs->buffering.future_record.data ); hs->buffering.future_record.data = NULL; } } static int ssl_load_buffered_record( mbedtls_ssl_context *ssl ) { mbedtls_ssl_handshake_params * const hs = ssl->handshake; unsigned char * rec; size_t rec_len; unsigned rec_epoch; #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) size_t in_buf_len = ssl->in_buf_len; #else size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN; #endif if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) return( 0 ); if( hs == NULL ) return( 0 ); rec = hs->buffering.future_record.data; rec_len = hs->buffering.future_record.len; rec_epoch = hs->buffering.future_record.epoch; if( rec == NULL ) return( 0 ); /* Only consider loading future records if the * input buffer is empty. */ if( ssl_next_record_is_in_datagram( ssl ) == 1 ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_record" ) ); if( rec_epoch != ssl->in_epoch ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffered record not from current epoch." ) ); goto exit; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "Found buffered record from current epoch - load" ) ); /* Double-check that the record is not too large */ if( rec_len > in_buf_len - (size_t)( ssl->in_hdr - ssl->in_buf ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } memcpy( ssl->in_hdr, rec, rec_len ); ssl->in_left = rec_len; ssl->next_record_offset = 0; ssl_free_buffered_record( ssl ); exit: MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_record" ) ); return( 0 ); } static int ssl_buffer_future_record( mbedtls_ssl_context *ssl, mbedtls_record const *rec ) { mbedtls_ssl_handshake_params * const hs = ssl->handshake; /* Don't buffer future records outside handshakes. */ if( hs == NULL ) return( 0 ); /* Only buffer handshake records (we are only interested * in Finished messages). */ if( rec->type != MBEDTLS_SSL_MSG_HANDSHAKE ) return( 0 ); /* Don't buffer more than one future epoch record. */ if( hs->buffering.future_record.data != NULL ) return( 0 ); /* Don't buffer record if there's not enough buffering space remaining. */ if( rec->buf_len > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING - hs->buffering.total_bytes_buffered ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future epoch record of size %" MBEDTLS_PRINTF_SIZET " would exceed the compile-time limit %" MBEDTLS_PRINTF_SIZET " (already %" MBEDTLS_PRINTF_SIZET " bytes buffered) -- ignore\n", rec->buf_len, (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING, hs->buffering.total_bytes_buffered ) ); return( 0 ); } /* Buffer record */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffer record from epoch %u", ssl->in_epoch + 1U ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered record", rec->buf, rec->buf_len ); /* ssl_parse_record_header() only considers records * of the next epoch as candidates for buffering. */ hs->buffering.future_record.epoch = ssl->in_epoch + 1; hs->buffering.future_record.len = rec->buf_len; hs->buffering.future_record.data = mbedtls_calloc( 1, hs->buffering.future_record.len ); if( hs->buffering.future_record.data == NULL ) { /* If we run out of RAM trying to buffer a * record from the next epoch, just ignore. */ return( 0 ); } memcpy( hs->buffering.future_record.data, rec->buf, rec->buf_len ); hs->buffering.total_bytes_buffered += rec->buf_len; return( 0 ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ static int ssl_get_next_record( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_record rec; #if defined(MBEDTLS_SSL_PROTO_DTLS) /* We might have buffered a future record; if so, * and if the epoch matches now, load it. * On success, this call will set ssl->in_left to * the length of the buffered record, so that * the calls to ssl_fetch_input() below will * essentially be no-ops. */ ret = ssl_load_buffered_record( ssl ); if( ret != 0 ) return( ret ); #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* Ensure that we have enough space available for the default form * of TLS / DTLS record headers (5 Bytes for TLS, 13 Bytes for DTLS, * with no space for CIDs counted in). */ ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_in_hdr_len( ssl ) ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); return( ret ); } ret = ssl_parse_record_header( ssl, ssl->in_hdr, ssl->in_left, &rec ); if( ret != 0 ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { if( ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE ) { ret = ssl_buffer_future_record( ssl, &rec ); if( ret != 0 ) return( ret ); /* Fall through to handling of unexpected records */ ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD; } if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ) { #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C) /* Reset in pointers to default state for TLS/DTLS records, * assuming no CID and no offset between record content and * record plaintext. */ mbedtls_ssl_update_in_pointers( ssl ); /* Setup internal message pointers from record structure. */ ssl->in_msgtype = rec.type; #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) ssl->in_len = ssl->in_cid + rec.cid_len; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ ssl->in_iv = ssl->in_msg = ssl->in_len + 2; ssl->in_msglen = rec.data_len; ret = ssl_check_client_reconnect( ssl ); MBEDTLS_SSL_DEBUG_RET( 2, "ssl_check_client_reconnect", ret ); if( ret != 0 ) return( ret ); #endif /* Skip unexpected record (but not whole datagram) */ ssl->next_record_offset = rec.buf_len; MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding unexpected record " "(header)" ) ); } else { /* Skip invalid record and the rest of the datagram */ ssl->next_record_offset = 0; ssl->in_left = 0; MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record " "(header)" ) ); } /* Get next record */ return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING ); } else #endif { return( ret ); } } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* Remember offset of next record within datagram. */ ssl->next_record_offset = rec.buf_len; if( ssl->next_record_offset < ssl->in_left ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "more than one record within datagram" ) ); } } else #endif { /* * Fetch record contents from underlying transport. */ ret = mbedtls_ssl_fetch_input( ssl, rec.buf_len ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); return( ret ); } ssl->in_left = 0; } /* * Decrypt record contents. */ if( ( ret = ssl_prepare_record_content( ssl, &rec ) ) != 0 ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* Silently discard invalid records */ if( ret == MBEDTLS_ERR_SSL_INVALID_MAC ) { /* Except when waiting for Finished as a bad mac here * probably means something went wrong in the handshake * (eg wrong psk used, mitm downgrade attempt, etc.) */ if( ssl->state == MBEDTLS_SSL_CLIENT_FINISHED || ssl->state == MBEDTLS_SSL_SERVER_FINISHED ) { #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES) if( ret == MBEDTLS_ERR_SSL_INVALID_MAC ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC ); } #endif return( ret ); } #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) if( ssl->conf->badmac_limit != 0 && ++ssl->badmac_seen >= ssl->conf->badmac_limit ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "too many records with bad MAC" ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } #endif /* As above, invalid records cause * dismissal of the whole datagram. */ ssl->next_record_offset = 0; ssl->in_left = 0; MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record (mac)" ) ); return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING ); } return( ret ); } else #endif { /* Error out (and send alert) on invalid records */ #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES) if( ret == MBEDTLS_ERR_SSL_INVALID_MAC ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC ); } #endif return( ret ); } } /* Reset in pointers to default state for TLS/DTLS records, * assuming no CID and no offset between record content and * record plaintext. */ mbedtls_ssl_update_in_pointers( ssl ); #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) ssl->in_len = ssl->in_cid + rec.cid_len; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ ssl->in_iv = ssl->in_len + 2; /* The record content type may change during decryption, * so re-read it. */ ssl->in_msgtype = rec.type; /* Also update the input buffer, because unfortunately * the server-side ssl_parse_client_hello() reparses the * record header when receiving a ClientHello initiating * a renegotiation. */ ssl->in_hdr[0] = rec.type; ssl->in_msg = rec.buf + rec.data_offset; ssl->in_msglen = rec.data_len; ssl->in_len[0] = (unsigned char)( rec.data_len >> 8 ); ssl->in_len[1] = (unsigned char)( rec.data_len ); #if defined(MBEDTLS_ZLIB_SUPPORT) if( ssl->transform_in != NULL && ssl->session_in->compression == MBEDTLS_SSL_COMPRESS_DEFLATE ) { if( ( ret = ssl_decompress_buf( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decompress_buf", ret ); return( ret ); } /* Check actual (decompress) record content length against * configured maximum. */ if( ssl->in_msglen > MBEDTLS_SSL_IN_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } } #endif /* MBEDTLS_ZLIB_SUPPORT */ return( 0 ); } int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; /* * Handle particular types of records */ if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) { if( ( ret = mbedtls_ssl_prepare_handshake_record( ssl ) ) != 0 ) { return( ret ); } } if( ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ) { if( ssl->in_msglen != 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid CCS message, len: %" MBEDTLS_PRINTF_SIZET, ssl->in_msglen ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } if( ssl->in_msg[0] != 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid CCS message, content: %02x", ssl->in_msg[0] ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC && ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC ) { if( ssl->handshake == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping ChangeCipherSpec outside handshake" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "received out-of-order ChangeCipherSpec - remember" ) ); return( MBEDTLS_ERR_SSL_EARLY_MESSAGE ); } #endif } if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT ) { if( ssl->in_msglen != 2 ) { /* Note: Standard allows for more than one 2 byte alert to be packed in a single message, but Mbed TLS doesn't currently support this. */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid alert message, len: %" MBEDTLS_PRINTF_SIZET, ssl->in_msglen ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "got an alert message, type: [%u:%s]", ssl->in_msg[0], GetAlertDescription(ssl->in_msg[1]) ) ); /* * Ignore non-fatal alerts, except close_notify and no_renegotiation */ if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "is a fatal alert message (%s)", GetAlertDescription(ssl->in_msg[1]) ) ); ssl->fatal_alert = ssl->in_msg[1]; return( MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE ); } if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a close notify message" ) ); return( MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ); } #if defined(MBEDTLS_SSL_RENEGOTIATION_ENABLED) if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no renegotiation alert" ) ); /* Will be handled when trying to parse ServerHello */ return( 0 ); } #endif #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_SRV_C) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 && ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) ); /* Will be handled in mbedtls_ssl_parse_certificate() */ return( 0 ); } #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */ /* Silently ignore: fetch new message */ return MBEDTLS_ERR_SSL_NON_FATAL; } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* Drop unexpected ApplicationData records, * except at the beginning of renegotiations */ if( ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA && ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER #if defined(MBEDTLS_SSL_RENEGOTIATION) && ! ( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->state == MBEDTLS_SSL_SERVER_HELLO ) #endif ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ApplicationData" ) ); return( MBEDTLS_ERR_SSL_NON_FATAL ); } if( ssl->handshake != NULL && ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) { mbedtls_ssl_handshake_wrapup_free_hs_transform( ssl ); } } #endif /* MBEDTLS_SSL_PROTO_DTLS */ return( 0 ); } int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl ) { return( mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ) ); } /** * \brief Send an alert message * * \param ssl SSL context * \param level The alert level of the message * (MBEDTLS_SSL_ALERT_LEVEL_WARNING or MBEDTLS_SSL_ALERT_LEVEL_FATAL) * \param message The alert message (SSL_ALERT_MSG_*) * * \return 0 if successful, or a specific SSL error code. * * \note If this function returns something other than 0 or * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using * the SSL context for reading or writing, and either free it or * call \c mbedtls_ssl_session_reset() on it before re-using it * for a new connection; the current connection must be closed. */ int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl, unsigned char level, unsigned char message ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> send alert message" ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "send alert level=%u message=%u", level, message )); ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT; ssl->out_msglen = 2; ssl->out_msg[0] = level; ssl->out_msg[1] = message; if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= send alert message" ) ); return( 0 ); } int mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write change cipher spec" ) ); ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC; ssl->out_msglen = 1; ssl->out_msg[0] = 1; ssl->state++; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write change cipher spec" ) ); return( 0 ); } int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse change cipher spec" ) ); if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } /* CCS records are only accepted if they have length 1 and content '1', * so we don't need to check this here. */ /* * Switch to our negotiated transform and session parameters for inbound * data. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for inbound data" ) ); ssl->transform_in = ssl->transform_negotiate; ssl->session_in = ssl->session_negotiate; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) mbedtls_ssl_dtls_replay_reset( ssl ); #endif /* Increment epoch */ if( ++ssl->in_epoch == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) ); /* This is highly unlikely to happen for legitimate reasons, so treat it as an attack and don't send an alert. */ return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); } } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ mbedtls_platform_zeroize( ssl->in_ctr, 8 ); mbedtls_ssl_update_in_pointers( ssl ); #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_activate != NULL ) { if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_INBOUND ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } } #endif ssl->state++; MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse change cipher spec" ) ); return( 0 ); } /* Once ssl->out_hdr as the address of the beginning of the * next outgoing record is set, deduce the other pointers. * * Note: For TLS, we save the implicit record sequence number * (entering MAC computation) in the 8 bytes before ssl->out_hdr, * and the caller has to make sure there's space for this. */ static size_t ssl_transform_get_explicit_iv_len( mbedtls_ssl_transform const *transform ) { if( transform->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ) return( 0 ); return( transform->ivlen - transform->fixed_ivlen ); } void mbedtls_ssl_update_out_pointers( mbedtls_ssl_context *ssl, mbedtls_ssl_transform *transform ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { ssl->out_ctr = ssl->out_hdr + 3; #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) ssl->out_cid = ssl->out_ctr + 8; ssl->out_len = ssl->out_cid; if( transform != NULL ) ssl->out_len += transform->out_cid_len; #else /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ ssl->out_len = ssl->out_ctr + 8; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ ssl->out_iv = ssl->out_len + 2; } else #endif { ssl->out_ctr = ssl->out_hdr - 8; ssl->out_len = ssl->out_hdr + 3; #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) ssl->out_cid = ssl->out_len; #endif ssl->out_iv = ssl->out_hdr + 5; } ssl->out_msg = ssl->out_iv; /* Adjust out_msg to make space for explicit IV, if used. */ if( transform != NULL ) ssl->out_msg += ssl_transform_get_explicit_iv_len( transform ); } /* Once ssl->in_hdr as the address of the beginning of the * next incoming record is set, deduce the other pointers. * * Note: For TLS, we save the implicit record sequence number * (entering MAC computation) in the 8 bytes before ssl->in_hdr, * and the caller has to make sure there's space for this. */ void mbedtls_ssl_update_in_pointers( mbedtls_ssl_context *ssl ) { /* This function sets the pointers to match the case * of unprotected TLS/DTLS records, with both ssl->in_iv * and ssl->in_msg pointing to the beginning of the record * content. * * When decrypting a protected record, ssl->in_msg * will be shifted to point to the beginning of the * record plaintext. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* This sets the header pointers to match records * without CID. When we receive a record containing * a CID, the fields are shifted accordingly in * ssl_parse_record_header(). */ ssl->in_ctr = ssl->in_hdr + 3; #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) ssl->in_cid = ssl->in_ctr + 8; ssl->in_len = ssl->in_cid; /* Default: no CID */ #else /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ ssl->in_len = ssl->in_ctr + 8; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ ssl->in_iv = ssl->in_len + 2; } else #endif { ssl->in_ctr = ssl->in_hdr - 8; ssl->in_len = ssl->in_hdr + 3; #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) ssl->in_cid = ssl->in_len; #endif ssl->in_iv = ssl->in_hdr + 5; } /* This will be adjusted at record decryption time. */ ssl->in_msg = ssl->in_iv; } /* * Setup an SSL context */ void mbedtls_ssl_reset_in_out_pointers( mbedtls_ssl_context *ssl ) { /* Set the incoming and outgoing record pointers. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { ssl->out_hdr = ssl->out_buf; ssl->in_hdr = ssl->in_buf; } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ { ssl->out_hdr = ssl->out_buf + 8; ssl->in_hdr = ssl->in_buf + 8; } /* Derive other internal pointers. */ mbedtls_ssl_update_out_pointers( ssl, NULL /* no transform enabled */ ); mbedtls_ssl_update_in_pointers ( ssl ); } /** * \brief Return the number of application data bytes * remaining to be read from the current record. * * \param ssl SSL context * * \return How many bytes are available in the application * data record read buffer. * * \note When working over a datagram transport, this is * useful to detect the current datagram's boundary * in case \c mbedtls_ssl_read has written the maximal * amount of data fitting into the input buffer. * */ size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl ) { return( ssl->in_offt == NULL ? 0 : ssl->in_msglen ); } /** * \brief Check if there is data already read from the * underlying transport but not yet processed. * * \param ssl SSL context * * \return 0 if nothing's pending, 1 otherwise. * * \note This is different in purpose and behaviour from * \c mbedtls_ssl_get_bytes_avail in that it considers * any kind of unprocessed data, not only unread * application data. If \c mbedtls_ssl_get_bytes * returns a non-zero value, this function will * also signal pending data, but the converse does * not hold. For example, in DTLS there might be * further records waiting to be processed from * the current underlying transport's datagram. * * \note If this function returns 1 (data pending), this * does not imply that a subsequent call to * \c mbedtls_ssl_read will provide any data; * e.g., the unprocessed data might turn out * to be an alert or a handshake message. * * \note This function is useful in the following situation: * If the SSL/TLS module successfully returns from an * operation - e.g. a handshake or an application record * read - and you're awaiting incoming data next, you * must not immediately idle on the underlying transport * to have data ready, but you need to check the value * of this function first. The reason is that the desired * data might already be read but not yet processed. * If, in contrast, a previous call to the SSL/TLS module * returned MBEDTLS_ERR_SSL_WANT_READ, it is not necessary * to call this function, as the latter error code entails * that all internal data has been processed. * */ int mbedtls_ssl_check_pending( const mbedtls_ssl_context *ssl ) { /* * Case A: We're currently holding back * a message for further processing. */ if( ssl->keep_current_message == 1 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: record held back for processing" ) ); return( 1 ); } /* * Case B: Further records are pending in the current datagram. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->in_left > ssl->next_record_offset ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more records within current datagram" ) ); return( 1 ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* * Case C: A handshake message is being processed. */ if( ssl->in_hslen > 0 && ssl->in_hslen < ssl->in_msglen ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more handshake messages within current record" ) ); return( 1 ); } /* * Case D: An application data message is being processed */ if( ssl->in_offt != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: application data record is being processed" ) ); return( 1 ); } /* * In all other cases, the rest of the message can be dropped. * As in ssl_get_next_record, this needs to be adapted if * we implement support for multiple alerts in single records. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: nothing pending" ) ); return( 0 ); } /** * \brief Return the (maximum) number of bytes added by the record * layer: header + encryption/MAC overhead (inc. padding) * * \note This function is not available (always returns an error) * when record compression is enabled. * * \param ssl SSL context * * \return Current maximum record expansion in bytes, or * MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE if compression is * enabled, which makes expansion much less predictable */ int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl ) { size_t transform_expansion = 0; const mbedtls_ssl_transform *transform = ssl->transform_out; unsigned block_size; size_t out_hdr_len = mbedtls_ssl_out_hdr_len( ssl ); if( transform == NULL ) return( (int) out_hdr_len ); #if defined(MBEDTLS_ZLIB_SUPPORT) if( ssl->session_out->compression != MBEDTLS_SSL_COMPRESS_NULL ) return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); #endif switch( mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ) ) { case MBEDTLS_MODE_GCM: case MBEDTLS_MODE_CCM: case MBEDTLS_MODE_CHACHAPOLY: case MBEDTLS_MODE_STREAM: transform_expansion = transform->minlen; break; case MBEDTLS_MODE_CBC: block_size = mbedtls_cipher_get_block_size( &transform->cipher_ctx_enc ); /* Expansion due to the addition of the MAC. */ transform_expansion += transform->maclen; /* Expansion due to the addition of CBC padding; * Theoretically up to 256 bytes, but we never use * more than the block size of the underlying cipher. */ transform_expansion += block_size; /* For TLS 1.1 or higher, an explicit IV is added * after the record header. */ #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) transform_expansion += block_size; #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */ break; default: MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) if( transform->out_cid_len != 0 ) transform_expansion += MBEDTLS_SSL_MAX_CID_EXPANSION; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ return( (int)( out_hdr_len + transform_expansion ) ); } #if defined(MBEDTLS_SSL_RENEGOTIATION) /* * Check record counters and renegotiate if they're above the limit. */ static int ssl_check_ctr_renegotiate( mbedtls_ssl_context *ssl ) { size_t ep_len = mbedtls_ssl_ep_len( ssl ); int in_ctr_cmp; int out_ctr_cmp; if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER || ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING || ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ) { return( 0 ); } in_ctr_cmp = timingsafe_memcmp( ssl->in_ctr + ep_len, ssl->conf->renego_period + ep_len, 8 - ep_len ); out_ctr_cmp = timingsafe_memcmp( ssl->cur_out_ctr + ep_len, ssl->conf->renego_period + ep_len, 8 - ep_len ); if( in_ctr_cmp <= 0 && out_ctr_cmp <= 0 ) { return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "record counter limit reached: renegotiate" ) ); return( mbedtls_ssl_renegotiate( ssl ) ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ /** * \brief Read at most 'len' application data bytes * * \param ssl SSL context * \param buf buffer that will hold the data * \param len maximum number of bytes to read * * \return The (positive) number of bytes read if successful. * \return \c 0 if the read end of the underlying transport was closed * without sending a CloseNotify beforehand, which might happen * because of various reasons (internal error of an underlying * stack, non-conformant peer not sending a CloseNotify and * such) - in this case you must stop using the context * (see below). * \return #MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY if the underlying * transport is still functional, but the peer has * acknowledged to not send anything anymore. * \return #MBEDTLS_ERR_SSL_WANT_READ or #MBEDTLS_ERR_SSL_WANT_WRITE * if the handshake is incomplete and waiting for data to * be available for reading from or writing to the underlying * transport - in this case you must call this function again * when the underlying transport is ready for the operation. * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if an asynchronous * operation is in progress (see * mbedtls_ssl_conf_async_private_cb()) - in this case you * must call this function again when the operation is ready. * \return #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS if a cryptographic * operation is in progress (see mbedtls_ecp_set_max_ops()) - * in this case you must call this function again to complete * the handshake when you're done attending other tasks. * \return #MBEDTLS_ERR_SSL_CLIENT_RECONNECT if we're at the server * side of a DTLS connection and the client is initiating a * new connection using the same source port. See below. * \return Another SSL error code - in this case you must stop using * the context (see below). * * \warning If this function returns something other than * a positive value, * #MBEDTLS_ERR_SSL_WANT_READ, * #MBEDTLS_ERR_SSL_WANT_WRITE, * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS, * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS or * #MBEDTLS_ERR_SSL_CLIENT_RECONNECT, * you must stop using the SSL context for reading or writing, * and either free it or call \c mbedtls_ssl_session_reset() * on it before re-using it for a new connection; the current * connection must be closed. * * \note When this function returns #MBEDTLS_ERR_SSL_CLIENT_RECONNECT * (which can only happen server-side), it means that a client * is initiating a new connection using the same source port. * You can either treat that as a connection close and wait * for the client to resend a ClientHello, or directly * continue with \c mbedtls_ssl_handshake() with the same * context (as it has been reset internally). Either way, you * must make sure this is seen by the application as a new * connection: application state, if any, should be reset, and * most importantly the identity of the client must be checked * again. WARNING: not validating the identity of the client * again, or not transmitting the new identity to the * application layer, would allow authentication bypass! * * \note Remarks regarding event-driven DTLS: * - If the function returns #MBEDTLS_ERR_SSL_WANT_READ, no datagram * from the underlying transport layer is currently being processed, * and it is safe to idle until the timer or the underlying transport * signal a new event. * - This function may return MBEDTLS_ERR_SSL_WANT_READ even if data was * initially available on the underlying transport, as this data may have * been only e.g. duplicated messages or a renegotiation request. * Therefore, you must be prepared to receive MBEDTLS_ERR_SSL_WANT_READ even * when reacting to an incoming-data event from the underlying transport. * - On success, the datagram of the underlying transport that is currently * being processed may contain further DTLS records. You should call * \c mbedtls_ssl_check_pending to check for remaining records. * */ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, void *buf, size_t len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t n; if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read" ) ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) return( ret ); if( ssl->handshake != NULL && ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING ) { if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 ) return( ret ); } } #endif /* * Check if renegotiation is necessary and/or handshake is * in process. If yes, perform/continue, and fall through * if an unexpected packet is received while the client * is waiting for the ServerHello. * * (There is no equivalent to the last condition on * the server-side as it is not treated as within * a handshake while waiting for the ClientHello * after a renegotiation request.) */ #if defined(MBEDTLS_SSL_RENEGOTIATION) ret = ssl_check_ctr_renegotiate( ssl ); if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO && ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret ); return( ret ); } #endif if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) { ret = mbedtls_ssl_handshake( ssl ); if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO && ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret ); return( ret ); } } /* Loop as long as no application data record is available */ while( ssl->in_offt == NULL ) { /* Start timer if not already running */ if( ssl->f_get_timer != NULL && ssl->f_get_timer( ssl->p_timer ) == -1 ) { mbedtls_ssl_set_timer( ssl, ssl->conf->read_timeout ); } if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { if( ret == MBEDTLS_ERR_SSL_CONN_EOF ) return( 0 ); MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } if( ssl->in_msglen == 0 && ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA ) { /* * OpenSSL sends empty messages to randomize the IV */ if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { if( ret == MBEDTLS_ERR_SSL_CONN_EOF ) return( 0 ); MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } } if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "received handshake message" ) ); /* * - For client-side, expect SERVER_HELLO_REQUEST. * - For server-side, expect CLIENT_HELLO. * - Fail (TLS) or silently drop record (DTLS) in other cases. */ #if defined(MBEDTLS_SSL_CLI_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT && ( ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST || ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not HelloRequest)" ) ); /* With DTLS, drop the packet (probably from last handshake) */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { continue; } #endif return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } #endif /* MBEDTLS_SSL_CLI_C */ #if defined(MBEDTLS_SSL_SRV_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not ClientHello)" ) ); /* With DTLS, drop the packet (probably from last handshake) */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { continue; } #endif return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } #endif /* MBEDTLS_SSL_SRV_C */ #if defined(MBEDTLS_SSL_RENEGOTIATION) /* Determine whether renegotiation attempt should be accepted */ if( ! ( ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED || ( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) ) ) { /* * Accept renegotiation request */ /* DTLS clients need to know renego is server-initiated */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) { ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING; } #endif ret = mbedtls_ssl_start_renegotiation( ssl ); if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO && ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_start_renegotiation", ret ); return( ret ); } } else #endif /* MBEDTLS_SSL_RENEGOTIATION */ { /* * Refuse renegotiation */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "refusing renegotiation, sending alert" ) ); #if defined(MBEDTLS_SSL_PROTO_SSL3) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { /* SSLv3 does not have a "no_renegotiation" warning, so we send a fatal alert and abort the connection. */ mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } else #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 ) { if( ( ret = mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_WARNING, MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 ) { return( ret ); } } else #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } /* At this point, we don't know whether the renegotiation has been * completed or not. The cases to consider are the following: * 1) The renegotiation is complete. In this case, no new record * has been read yet. * 2) The renegotiation is incomplete because the client received * an application data record while awaiting the ServerHello. * 3) The renegotiation is incomplete because the client received * a non-handshake, non-application data message while awaiting * the ServerHello. * In each of these case, looping will be the proper action: * - For 1), the next iteration will read a new record and check * if it's application data. * - For 2), the loop condition isn't satisfied as application data * is present, hence continue is the same as break * - For 3), the loop condition is satisfied and read_record * will re-deliver the message that was held back by the client * when expecting the ServerHello. */ continue; } #if defined(MBEDTLS_SSL_RENEGOTIATION) else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) { if( ssl->conf->renego_max_records >= 0 ) { if( ++ssl->renego_records_seen > ssl->conf->renego_max_records ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, " "but not honored by client" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } } } #endif /* MBEDTLS_SSL_RENEGOTIATION */ /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */ if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "ignoring non-fatal non-closure alert" ) ); return( MBEDTLS_ERR_SSL_WANT_READ ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad application data message" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } ssl->in_offt = ssl->in_msg; /* We're going to return something now, cancel timer, * except if handshake (renegotiation) is in progress */ if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) mbedtls_ssl_set_timer( ssl, 0 ); #if defined(MBEDTLS_SSL_PROTO_DTLS) /* If we requested renego but received AppData, resend HelloRequest. * Do it now, after setting in_offt, to avoid taking this branch * again if ssl_write_hello_request() returns WANT_WRITE */ #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) { if( ( ret = mbedtls_ssl_resend_hello_request( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend_hello_request", ret ); return( ret ); } } #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */ #endif /* MBEDTLS_SSL_PROTO_DTLS */ } n = ( len < ssl->in_msglen ) ? len : ssl->in_msglen; memcpy( buf, ssl->in_offt, n ); ssl->in_msglen -= n; /* Zeroising the plaintext buffer to erase unused application data from the memory. */ mbedtls_platform_zeroize( ssl->in_offt, n ); if( ssl->in_msglen == 0 ) { /* all bytes consumed */ ssl->in_offt = NULL; ssl->keep_current_message = 0; } else { /* more data available */ ssl->in_offt += n; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read" ) ); return( (int) n ); } /* * Send application data to be encrypted by the SSL layer, taking care of max * fragment length and buffer size. * * According to RFC 5246 Section 6.2.1: * * Zero-length fragments of Application data MAY be sent as they are * potentially useful as a traffic analysis countermeasure. * * Therefore, it is possible that the input message length is 0 and the * corresponding return code is 0 on success. */ static int ssl_write_real( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret = mbedtls_ssl_get_max_out_record_payload( ssl ); const size_t max_len = (size_t) ret; if( ret < 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_get_max_out_record_payload", ret ); return( ret ); } if( len > max_len ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment larger than the (negotiated) " "maximum fragment length: %" MBEDTLS_PRINTF_SIZET " > %" MBEDTLS_PRINTF_SIZET, len, max_len ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } else #endif len = max_len; } if( ssl->out_left != 0 ) { /* * The user has previously tried to send the data and * MBEDTLS_ERR_SSL_WANT_WRITE or the message was only partially * written. In this case, we expect the high-level write function * (e.g. mbedtls_ssl_write()) to be called with the same parameters */ if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret ); return( ret ); } } else { /* * The user is trying to send a message the first time, so we need to * copy the data into the internal buffers and setup the data structure * to keep track of partial writes */ ssl->out_msglen = len; ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA; memcpy( ssl->out_msg, buf, len ); if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); return( ret ); } } return( (int) len ); } /* * Write application data, doing 1/n-1 splitting if necessary. * * With non-blocking I/O, ssl_write_real() may return WANT_WRITE, * then the caller will call us again with the same arguments, so * remember whether we already did the split or not. */ #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) static int ssl_write_split( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( ssl->conf->cbc_record_splitting == MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED || len <= 1 || ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_1 || mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc ) != MBEDTLS_MODE_CBC ) { return( ssl_write_real( ssl, buf, len ) ); } if( ssl->split_done == 0 ) { if( ( ret = ssl_write_real( ssl, buf, 1 ) ) <= 0 ) return( ret ); ssl->split_done = 1; } if( ( ret = ssl_write_real( ssl, buf + 1, len - 1 ) ) <= 0 ) return( ret ); ssl->split_done = 0; return( ret + 1 ); } #endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */ /** * \brief Try to write exactly 'len' application data bytes * * \warning This function will do partial writes in some cases. If the * return value is non-negative but less than length, the * function must be called again with updated arguments: * buf + ret, len - ret (if ret is the return value) until * it returns a value equal to the last 'len' argument. * * \param ssl SSL context * \param buf buffer holding the data * \param len how many bytes must be written * * \return The (non-negative) number of bytes actually written if * successful (may be less than \p len). * \return #MBEDTLS_ERR_SSL_WANT_READ or #MBEDTLS_ERR_SSL_WANT_WRITE * if the handshake is incomplete and waiting for data to * be available for reading from or writing to the underlying * transport - in this case you must call this function again * when the underlying transport is ready for the operation. * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if an asynchronous * operation is in progress (see * mbedtls_ssl_conf_async_private_cb()) - in this case you * must call this function again when the operation is ready. * \return #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS if a cryptographic * operation is in progress (see mbedtls_ecp_set_max_ops()) - * in this case you must call this function again to complete * the handshake when you're done attending other tasks. * \return Another SSL error code - in this case you must stop using * the context (see below). * * \warning If this function returns something other than * a non-negative value, * #MBEDTLS_ERR_SSL_WANT_READ, * #MBEDTLS_ERR_SSL_WANT_WRITE, * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS, * you must stop using the SSL context for reading or writing, * and either free it or call \c mbedtls_ssl_session_reset() * on it before re-using it for a new connection; the current * connection must be closed. * * \note When this function returns #MBEDTLS_ERR_SSL_WANT_WRITE/READ, * it must be called later with the *same* arguments, * until it returns a value greater that or equal to 0. When * the function returns #MBEDTLS_ERR_SSL_WANT_WRITE there may be * some partial data in the output buffer, however this is not * yet sent. * * \note If the requested length is greater than the maximum * fragment length (either the built-in limit or the one set * or negotiated with the peer), then: * - with TLS, less bytes than requested are written. * - with DTLS, MBEDTLS_ERR_SSL_BAD_INPUT_DATA is returned. * \c mbedtls_ssl_get_output_max_frag_len() may be used to * query the active maximum fragment length. * * \note Attempting to write 0 bytes will result in an empty TLS * application record being sent. */ int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const void *buf, size_t len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write" ) ); if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret ); return( ret ); } #endif if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) { if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret ); return( ret ); } } #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) ret = ssl_write_split( ssl, buf, len ); #else ret = ssl_write_real( ssl, buf, len ); #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write" ) ); return( ret ); } /** * \brief Notify the peer that the connection is being closed * * \param ssl SSL context * * \return 0 if successful, or a specific SSL error code. * * \note If this function returns something other than 0 or * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using * the SSL context for reading or writing, and either free it or * call \c mbedtls_ssl_session_reset() on it before re-using it * for a new connection; the current connection must be closed. */ int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write close notify" ) ); if( ssl->out_left != 0 ) return( mbedtls_ssl_flush_output( ssl ) ); if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) { if( ( ret = mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_WARNING, MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_send_alert_message", ret ); return( ret ); } } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write close notify" ) ); return( 0 ); } /** * \brief Free referenced items in an SSL transform context and clear * memory * * \param transform SSL transform context */ void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform ) { if( transform == NULL ) return; #if defined(MBEDTLS_ZLIB_SUPPORT) deflateEnd( &transform->ctx_deflate ); inflateEnd( &transform->ctx_inflate ); #endif mbedtls_cipher_free( &transform->cipher_ctx_enc ); mbedtls_cipher_free( &transform->cipher_ctx_dec ); #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) mbedtls_md_free( &transform->md_ctx_enc ); mbedtls_md_free( &transform->md_ctx_dec ); #endif mbedtls_platform_zeroize( transform, sizeof( mbedtls_ssl_transform ) ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) void mbedtls_ssl_buffering_free( mbedtls_ssl_context *ssl ) { unsigned offset; mbedtls_ssl_handshake_params * const hs = ssl->handshake; if( hs == NULL ) return; ssl_free_buffered_record( ssl ); for( offset = 0; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++ ) ssl_buffering_free_slot( ssl, offset ); } static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl, uint8_t slot ) { mbedtls_ssl_handshake_params * const hs = ssl->handshake; mbedtls_ssl_hs_buffer * const hs_buf = &hs->buffering.hs[slot]; if( slot >= MBEDTLS_SSL_MAX_BUFFERED_HS ) return; if( hs_buf->is_valid == 1 ) { hs->buffering.total_bytes_buffered -= hs_buf->data_len; mbedtls_platform_zeroize( hs_buf->data, hs_buf->data_len ); mbedtls_free( hs_buf->data ); mbedtls_platform_zeroize( hs_buf, sizeof( mbedtls_ssl_hs_buffer ) ); } } #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* * Convert version numbers to/from wire format * and, for DTLS, to/from TLS equivalent. * * For TLS this is the identity. * For DTLS, use 1's complement (v -> 255 - v, and then map as follows: * 1.0 <-> 3.2 (DTLS 1.0 is based on TLS 1.1) * 1.x <-> 3.x+1 for x != 0 (DTLS 1.2 based on TLS 1.2) */ void mbedtls_ssl_write_version( int major, int minor, int transport, unsigned char ver[2] ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { if( minor == MBEDTLS_SSL_MINOR_VERSION_2 ) --minor; /* DTLS 1.0 stored as TLS 1.1 internally */ ver[0] = (unsigned char)( 255 - ( major - 2 ) ); ver[1] = (unsigned char)( 255 - ( minor - 1 ) ); } else #else ((void) transport); #endif { ver[0] = (unsigned char) major; ver[1] = (unsigned char) minor; } } void mbedtls_ssl_read_version( int *major, int *minor, int transport, const unsigned char ver[2] ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { *major = 255 - ver[0] + 2; *minor = 255 - ver[1] + 1; if( *minor == MBEDTLS_SSL_MINOR_VERSION_1 ) ++*minor; /* DTLS 1.0 stored as TLS 1.1 internally */ } else #else ((void) transport); #endif { *major = ver[0]; *minor = ver[1]; } } #endif /* MBEDTLS_SSL_TLS_C */
231,490
6,330
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/x509write_csr.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/mbedtls/asn1write.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/oid.h" #include "third_party/mbedtls/pem.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/x509_csr.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /* * X.509 Certificate Signing Request writing * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * References: * - CSRs: PKCS#10 v1.7 aka RFC 2986 * - attributes: PKCS#9 v2.0 aka RFC 2985 */ #if defined(MBEDTLS_X509_CSR_WRITE_C) /** * \brief Initialize a CSR context * * \param ctx CSR context to initialize */ void mbedtls_x509write_csr_init( mbedtls_x509write_csr *ctx ) { mbedtls_platform_zeroize( ctx, sizeof( mbedtls_x509write_csr ) ); } /** * \brief Free the contents of a CSR context * * \param ctx CSR context to free */ void mbedtls_x509write_csr_free( mbedtls_x509write_csr *ctx ) { mbedtls_asn1_free_named_data_list( &ctx->subject ); mbedtls_asn1_free_named_data_list( &ctx->extensions ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_x509write_csr ) ); } /** * \brief Set the MD algorithm to use for the signature * (e.g. MBEDTLS_MD_SHA1) * * \param ctx CSR context to use * \param md_alg MD algorithm to use */ void mbedtls_x509write_csr_set_md_alg( mbedtls_x509write_csr *ctx, mbedtls_md_type_t md_alg ) { ctx->md_alg = md_alg; } /** * \brief Set the key for a CSR (public key will be included, * private key used to sign the CSR when writing it) * * \param ctx CSR context to use * \param key Asymetric key to include */ void mbedtls_x509write_csr_set_key( mbedtls_x509write_csr *ctx, mbedtls_pk_context *key ) { ctx->key = key; } /** * \brief Set the subject name for a CSR * Subject names should contain a comma-separated list * of OID types and values: * e.g. "C=UK,O=ARM,CN=mbed TLS Server 1" * * \param ctx CSR context to use * \param subject_name subject name to set * * \return 0 if subject name was parsed successfully, or * a specific error code */ int mbedtls_x509write_csr_set_subject_name( mbedtls_x509write_csr *ctx, const char *subject_name ) { return mbedtls_x509_string_to_names( &ctx->subject, subject_name ); } /** * \brief Generic function to add to or replace an extension in the * CSR * * \param ctx CSR context to use * \param oid OID of the extension * \param oid_len length of the OID * \param val value of the extension OCTET STRING * \param val_len length of the value data * * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED */ int mbedtls_x509write_csr_set_extension( mbedtls_x509write_csr *ctx, const char *oid, size_t oid_len, const unsigned char *val, size_t val_len ) { return mbedtls_x509_set_extension( &ctx->extensions, oid, oid_len, 0, val, val_len ); } /** * \brief Set the Key Usage Extension flags * (e.g. MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_KEY_CERT_SIGN) * * \param ctx CSR context to use * \param key_usage key usage flags to set * * \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED * * \note The <code>decipherOnly</code> flag from the Key Usage * extension is represented by bit 8 (i.e. * <code>0x8000</code>), which cannot typically be represented * in an unsigned char. Therefore, the flag * <code>decipherOnly</code> (i.e. * #MBEDTLS_X509_KU_DECIPHER_ONLY) cannot be set using this * function. */ int mbedtls_x509write_csr_set_key_usage( mbedtls_x509write_csr *ctx, unsigned char key_usage ) { unsigned char buf[4]; unsigned char *c; int ret = MBEDTLS_ERR_THIS_CORRUPTION; c = buf + 4; ret = mbedtls_asn1_write_named_bitstring( &c, buf, &key_usage, 8 ); if( ret < 3 || ret > 4 ) return ret; ret = mbedtls_x509write_csr_set_extension( ctx, MBEDTLS_OID_KEY_USAGE, MBEDTLS_OID_SIZE( MBEDTLS_OID_KEY_USAGE ), c, (size_t)ret ); if( ret != 0 ) return ret; return 0; } /** * \brief Set the Netscape Cert Type flags * (e.g. MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT | MBEDTLS_X509_NS_CERT_TYPE_EMAIL) * * \param ctx CSR context to use * \param ns_cert_type Netscape Cert Type flags to set * * \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED */ int mbedtls_x509write_csr_set_ns_cert_type( mbedtls_x509write_csr *ctx, unsigned char ns_cert_type ) { unsigned char buf[4]; unsigned char *c; int ret = MBEDTLS_ERR_THIS_CORRUPTION; c = buf + 4; ret = mbedtls_asn1_write_named_bitstring( &c, buf, &ns_cert_type, 8 ); if( ret < 3 || ret > 4 ) return ret; ret = mbedtls_x509write_csr_set_extension( ctx, MBEDTLS_OID_NS_CERT_TYPE, MBEDTLS_OID_SIZE( MBEDTLS_OID_NS_CERT_TYPE ), c, (size_t)ret ); if( ret != 0 ) return ret; return 0; } static int x509write_csr_der_internal( mbedtls_x509write_csr *ctx, unsigned char *buf, size_t size, unsigned char *sig, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; const char *sig_oid; size_t sig_oid_len = 0; unsigned char *c, *c2; unsigned char hash[64]; size_t pub_len = 0, sig_and_oid_len = 0, sig_len; size_t len = 0; mbedtls_pk_type_t pk_alg; /* Write the CSR backwards starting from the end of buf */ c = buf + size; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_extensions( &c, buf, ctx->extensions ) ); if( len ) { MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_oid( &c, buf, MBEDTLS_OID_PKCS9_CSR_EXT_REQ, MBEDTLS_OID_SIZE( MBEDTLS_OID_PKCS9_CSR_EXT_REQ ) ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); } MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC ) ); MBEDTLS_ASN1_CHK_ADD( pub_len, mbedtls_pk_write_pubkey_der( ctx->key, buf, c - buf ) ); c -= pub_len; len += pub_len; /* * Subject ::= Name */ MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_names( &c, buf, ctx->subject ) ); /* * Version ::= INTEGER { v1(0), v2(1), v3(2) } */ MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_int( &c, buf, 0 ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); /* * Sign the written CSR data into the sig buffer * Note: hash errors can happen only after an internal error */ ret = mbedtls_md( mbedtls_md_info_from_type( ctx->md_alg ), c, len, hash ); if( ret != 0 ) return ret; if( ( ret = mbedtls_pk_sign( ctx->key, ctx->md_alg, hash, 0, sig, &sig_len, f_rng, p_rng ) ) != 0 ) { return ret; } if( mbedtls_pk_can_do( ctx->key, MBEDTLS_PK_RSA ) ) pk_alg = MBEDTLS_PK_RSA; else if( mbedtls_pk_can_do( ctx->key, MBEDTLS_PK_ECDSA ) ) pk_alg = MBEDTLS_PK_ECDSA; else return( MBEDTLS_ERR_X509_INVALID_ALG ); if( ( ret = mbedtls_oid_get_oid_by_sig_alg( pk_alg, ctx->md_alg, &sig_oid, &sig_oid_len ) ) != 0 ) { return ret; } /* * Move the written CSR data to the start of buf to create space for * writing the signature into buf. */ memmove( buf, c, len ); /* * Write sig and its OID into buf backwards from the end of buf. * Note: mbedtls_x509_write_sig will check for c2 - ( buf + len ) < sig_len * and return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL if needed. */ c2 = buf + size; MBEDTLS_ASN1_CHK_ADD( sig_and_oid_len, mbedtls_x509_write_sig( &c2, buf + len, sig_oid, sig_oid_len, sig, sig_len ) ); /* * Compact the space between the CSR data and signature by moving the * CSR data to the start of the signature. */ c2 -= len; memmove( c2, buf, len ); /* ASN encode the total size and tag the CSR data with it. */ len += sig_and_oid_len; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c2, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c2, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); /* Zero the unused bytes at the start of buf */ mbedtls_platform_zeroize( buf, c2 - buf); return( (int) len ); } /** * \brief Write a CSR (Certificate Signing Request) to a * DER structure * Note: data is written at the end of the buffer! Use the * return value to determine where you should start * using the buffer * * \param ctx CSR to write away * \param buf buffer to write to * \param size size of the buffer * \param f_rng RNG function (for signature, see note) * \param p_rng RNG parameter * * \return length of data written if successful, or a specific * error code * * \note f_rng may be NULL if RSA is used for signature and the * signature is made offline (otherwise f_rng is desirable * for countermeasures against timing attacks). * ECDSA signatures always require a non-NULL f_rng. */ int mbedtls_x509write_csr_der( mbedtls_x509write_csr *ctx, unsigned char *buf, size_t size, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret; unsigned char *sig; if( ( sig = mbedtls_calloc( 1, MBEDTLS_PK_SIGNATURE_MAX_SIZE ) ) == NULL ) { return( MBEDTLS_ERR_X509_ALLOC_FAILED ); } ret = x509write_csr_der_internal( ctx, buf, size, sig, f_rng, p_rng ); mbedtls_free( sig ); return ret; } #define PEM_BEGIN_CSR "-----BEGIN CERTIFICATE REQUEST-----\n" #define PEM_END_CSR "-----END CERTIFICATE REQUEST-----\n" /** * \brief Write a CSR (Certificate Signing Request) to a * PEM string * * \param ctx CSR to write away * \param buf buffer to write to * \param size size of the buffer * \param f_rng RNG function (for signature, see note) * \param p_rng RNG parameter * * \return 0 if successful, or a specific error code * * \note f_rng may be NULL if RSA is used for signature and the * signature is made offline (otherwise f_rng is desirable * for countermeasures against timing attacks). * ECDSA signatures always require a non-NULL f_rng. */ int mbedtls_x509write_csr_pem( mbedtls_x509write_csr *ctx, unsigned char *buf, size_t size, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t olen = 0; if( ( ret = mbedtls_x509write_csr_der( ctx, buf, size, f_rng, p_rng ) ) < 0 ) { return ret; } if( ( ret = mbedtls_pem_write_buffer( PEM_BEGIN_CSR, PEM_END_CSR, buf + size - ret, ret, buf, size, &olen ) ) != 0 ) { return ret; } return 0; } #endif /* MBEDTLS_X509_CSR_WRITE_C */
15,848
402
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/pkcs5.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/mbedtls/asn1.h" #include "third_party/mbedtls/cipher.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/oid.h" #include "third_party/mbedtls/pkcs5.h" #include "third_party/mbedtls/platform.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /** * @fileoverview PKCS#5 functions, e.g. PBKDF2 * @see http://tools.ietf.org/html/rfc2898 (Specification) * @see http://tools.ietf.org/html/rfc6070 (Test vectors) * @author Mathias Olsson <[email protected]> */ #if defined(MBEDTLS_PKCS5_C) #if defined(MBEDTLS_ASN1_PARSE_C) static int pkcs5_parse_pbkdf2_params( const mbedtls_asn1_buf *params, mbedtls_asn1_buf *salt, int *iterations, int *keylen, mbedtls_md_type_t *md_type ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_asn1_buf prf_alg_oid; unsigned char *p = params->p; const unsigned char *end = params->p + params->len; if( params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ); /* * PBKDF2-params ::= SEQUENCE { * salt OCTET STRING, * iterationCount INTEGER, * keyLength INTEGER OPTIONAL * prf AlgorithmIdentifier DEFAULT algid-hmacWithSHA1 * } * */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &salt->len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 ) return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret ); salt->p = p; p += salt->len; if( ( ret = mbedtls_asn1_get_int( &p, end, iterations ) ) != 0 ) return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret ); if( p == end ) return( 0 ); if( ( ret = mbedtls_asn1_get_int( &p, end, keylen ) ) != 0 ) { if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret ); } if( p == end ) return( 0 ); if( ( ret = mbedtls_asn1_get_alg_null( &p, end, &prf_alg_oid ) ) != 0 ) return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret ); if( mbedtls_oid_get_md_hmac( &prf_alg_oid, md_type ) != 0 ) return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE ); if( p != end ) return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( 0 ); } /** * \brief PKCS#5 PBES2 function * * \param pbe_params the ASN.1 algorithm parameters * \param mode either MBEDTLS_PKCS5_DECRYPT or MBEDTLS_PKCS5_ENCRYPT * \param pwd password to use when generating key * \param pwdlen length of password * \param data data to process * \param datalen length of data * \param output output buffer * * \returns 0 on success, or MBEDTLS_ERR_XXX if verification fails. */ int mbedtls_pkcs5_pbes2( const mbedtls_asn1_buf *pbe_params, int mode, const unsigned char *pwd, size_t pwdlen, const unsigned char *data, size_t datalen, unsigned char *output ) { int ret, iterations = 0, keylen = 0; unsigned char *p, *end; mbedtls_asn1_buf kdf_alg_oid, enc_scheme_oid, kdf_alg_params, enc_scheme_params; mbedtls_asn1_buf salt; mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1; unsigned char key[32], iv[32]; size_t olen = 0; const mbedtls_md_info_t *md_info; const mbedtls_cipher_info_t *cipher_info; mbedtls_md_context_t md_ctx; mbedtls_cipher_type_t cipher_alg; mbedtls_cipher_context_t cipher_ctx; p = pbe_params->p; end = p + pbe_params->len; /* * PBES2-params ::= SEQUENCE { * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}}, * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}} * } */ if( pbe_params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ); if( ( ret = mbedtls_asn1_get_alg( &p, end, &kdf_alg_oid, &kdf_alg_params ) ) != 0 ) return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret ); /* Only PBKDF2 supported at the moment */ if( MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS5_PBKDF2, &kdf_alg_oid ) != 0 ) return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE ); if( ( ret = pkcs5_parse_pbkdf2_params( &kdf_alg_params, &salt, &iterations, &keylen, &md_type ) ) != 0 ) { return( ret ); } md_info = mbedtls_md_info_from_type( md_type ); if( md_info == NULL ) return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE ); if( ( ret = mbedtls_asn1_get_alg( &p, end, &enc_scheme_oid, &enc_scheme_params ) ) != 0 ) { return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret ); } if( mbedtls_oid_get_cipher_alg( &enc_scheme_oid, &cipher_alg ) != 0 ) return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE ); cipher_info = mbedtls_cipher_info_from_type( cipher_alg ); if( cipher_info == NULL ) return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE ); /* * The value of keylen from pkcs5_parse_pbkdf2_params() is ignored * since it is optional and we don't know if it was set or not */ keylen = cipher_info->key_bitlen / 8; if( enc_scheme_params.tag != MBEDTLS_ASN1_OCTET_STRING || enc_scheme_params.len != cipher_info->iv_size ) { return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT ); } mbedtls_md_init( &md_ctx ); mbedtls_cipher_init( &cipher_ctx ); memcpy( iv, enc_scheme_params.p, enc_scheme_params.len ); if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 ) goto exit; if( ( ret = mbedtls_pkcs5_pbkdf2_hmac( &md_ctx, pwd, pwdlen, salt.p, salt.len, iterations, keylen, key ) ) != 0 ) { goto exit; } if( ( ret = mbedtls_cipher_setup( &cipher_ctx, cipher_info ) ) != 0 ) goto exit; if( ( ret = mbedtls_cipher_setkey( &cipher_ctx, key, 8 * keylen, (mbedtls_operation_t) mode ) ) != 0 ) goto exit; if( ( ret = mbedtls_cipher_crypt( &cipher_ctx, iv, enc_scheme_params.len, data, datalen, output, &olen ) ) != 0 ) ret = MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH; exit: mbedtls_md_free( &md_ctx ); mbedtls_cipher_free( &cipher_ctx ); return( ret ); } #endif /* MBEDTLS_ASN1_PARSE_C */ /** * \brief PKCS#5 PBKDF2 using HMAC * * \param ctx Generic HMAC context * \param password Password to use when generating key * \param plen Length of password * \param salt Salt to use when generating key * \param slen Length of salt * \param c Iteration count * \param dklen Length of generated key in bytes * \param output Generated key. Must be at least as big as dklen * * \returns 0 on success, or a MBEDTLS_ERR_XXX code if verification fails. */ int mbedtls_pkcs5_pbkdf2_hmac( mbedtls_md_context_t *ctx, const void *password, size_t plen, const void *salt, size_t slen, unsigned c, uint32_t dklen, unsigned char *output ) { int j; int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned int i; unsigned char md1[MBEDTLS_MD_MAX_SIZE]; unsigned char work[MBEDTLS_MD_MAX_SIZE]; unsigned char md_size = mbedtls_md_get_size( ctx->md_info ); size_t use_len; unsigned char *out_p = output; unsigned char counter[4]; memset( counter, 0, 4 ); counter[3] = 1; #if UINT_MAX > 0xFFFFFFFF if( c > 0xFFFFFFFF ) return( MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA ); #endif if( ( ret = mbedtls_md_hmac_starts( ctx, password, plen ) ) != 0 ) return( ret ); while( dklen ) { // U1 ends up in work // if( ( ret = mbedtls_md_hmac_update( ctx, salt, slen ) ) != 0 ) goto cleanup; if( ( ret = mbedtls_md_hmac_update( ctx, counter, 4 ) ) != 0 ) goto cleanup; if( ( ret = mbedtls_md_hmac_finish( ctx, work ) ) != 0 ) goto cleanup; if( ( ret = mbedtls_md_hmac_reset( ctx ) ) != 0 ) goto cleanup; memcpy( md1, work, md_size ); for( i = 1; i < c; i++ ) { // U2 ends up in md1 // if( ( ret = mbedtls_md_hmac_update( ctx, md1, md_size ) ) != 0 ) goto cleanup; if( ( ret = mbedtls_md_hmac_finish( ctx, md1 ) ) != 0 ) goto cleanup; if( ( ret = mbedtls_md_hmac_reset( ctx ) ) != 0 ) goto cleanup; // U1 xor U2 // for( j = 0; j < md_size; j++ ) work[j] ^= md1[j]; } use_len = ( dklen < md_size ) ? dklen : md_size; memcpy( out_p, work, use_len ); dklen -= (uint32_t) use_len; out_p += use_len; for( i = 4; i > 0; i-- ) if( ++counter[i - 1] != 0 ) break; } cleanup: /* Zeroise buffers to clear sensitive data from memory. */ mbedtls_platform_zeroize( work, MBEDTLS_MD_MAX_SIZE ); mbedtls_platform_zeroize( md1, MBEDTLS_MD_MAX_SIZE ); return( ret ); } #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_SHA1_C) #define MAX_TESTS 6 /** * \brief Checkup routine * * \return 0 if successful, or 1 if the test failed */ int mbedtls_pkcs5_self_test( int verbose ) { static const size_t plen_test_data[MAX_TESTS] = { 8, 8, 8, 24, 9 }; static const unsigned char password_test_data[MAX_TESTS][32] = { "password", "password", "password", "passwordPASSWORDpassword", "pass\0word", }; static const size_t slen_test_data[MAX_TESTS] = { 4, 4, 4, 36, 5 }; static const unsigned char salt_test_data[MAX_TESTS][40] = { "salt", "salt", "salt", "saltSALTsaltSALTsaltSALTsaltSALTsalt", "sa\0lt", }; static const uint32_t it_cnt_test_data[MAX_TESTS] = { 1, 2, 4096, 4096, 4096 }; static const uint32_t key_len_test_data[MAX_TESTS] = { 20, 20, 20, 25, 16 }; static const unsigned char result_key_test_data[MAX_TESTS][32] = { { 0x0c, 0x60, 0xc8, 0x0f, 0x96, 0x1f, 0x0e, 0x71, 0xf3, 0xa9, 0xb5, 0x24, 0xaf, 0x60, 0x12, 0x06, 0x2f, 0xe0, 0x37, 0xa6 }, { 0xea, 0x6c, 0x01, 0x4d, 0xc7, 0x2d, 0x6f, 0x8c, 0xcd, 0x1e, 0xd9, 0x2a, 0xce, 0x1d, 0x41, 0xf0, 0xd8, 0xde, 0x89, 0x57 }, { 0x4b, 0x00, 0x79, 0x01, 0xb7, 0x65, 0x48, 0x9a, 0xbe, 0xad, 0x49, 0xd9, 0x26, 0xf7, 0x21, 0xd0, 0x65, 0xa4, 0x29, 0xc1 }, { 0x3d, 0x2e, 0xec, 0x4f, 0xe4, 0x1c, 0x84, 0x9b, 0x80, 0xc8, 0xd8, 0x36, 0x62, 0xc0, 0xe4, 0x4a, 0x8b, 0x29, 0x1a, 0x96, 0x4c, 0xf2, 0xf0, 0x70, 0x38 }, { 0x56, 0xfa, 0x6a, 0xa7, 0x55, 0x48, 0x09, 0x9d, 0xcc, 0x37, 0xd7, 0xf0, 0x34, 0x25, 0xe0, 0xc3 }, }; mbedtls_md_context_t sha1_ctx; const mbedtls_md_info_t *info_sha1; int ret, i; unsigned char key[64]; mbedtls_md_init( &sha1_ctx ); info_sha1 = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ); if( info_sha1 == NULL ) { ret = 1; goto exit; } if( ( ret = mbedtls_md_setup( &sha1_ctx, info_sha1, 1 ) ) != 0 ) { ret = 1; goto exit; } for( i = 0; i < MAX_TESTS; i++ ) { if( verbose != 0 ) mbedtls_printf( " PBKDF2 (SHA1) #%d: ", i ); ret = mbedtls_pkcs5_pbkdf2_hmac( &sha1_ctx, password_test_data[i], plen_test_data[i], salt_test_data[i], slen_test_data[i], it_cnt_test_data[i], key_len_test_data[i], key ); if( ret != 0 || timingsafe_bcmp( result_key_test_data[i], key, key_len_test_data[i] ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); ret = 1; goto exit; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); } if( verbose != 0 ) mbedtls_printf( "\n" ); exit: mbedtls_md_free( &sha1_ctx ); return( ret ); } #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_PKCS5_C */
14,589
365
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/ecp.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/strace.internal.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "third_party/mbedtls/bignum.h" #include "third_party/mbedtls/bignum_internal.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/ctr_drbg.h" #include "third_party/mbedtls/ecp.h" #include "third_party/mbedtls/ecp_internal.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/hmac_drbg.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/profile.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /** * @fileoverview Elliptic curves over GF(p): generic functions * * References: * * SEC1 http://www.secg.org/index.php?action=secg,docs_secg * GECC = Guide to Elliptic Curve Cryptography - Hankerson, Menezes, Vanstone * FIPS 186-3 http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf * RFC 4492 for the related TLS structures and constants * RFC 7748 for the Curve448 and Curve25519 curve definitions * * [Curve25519] http://cr.yp.to/ecdh/curve25519-20060209.pdf * * [2] CORON, Jean-S'ebastien. Resistance against differential power analysis * for elliptic curve cryptosystems. In : Cryptographic Hardware and * Embedded Systems. Springer Berlin Heidelberg, 1999. p. 292-302. * <http://link.springer.com/chapter/10.1007/3-540-48059-5_25> * * [3] HEDABOU, Mustapha, PINEL, Pierre, et B'EN'ETEAU, Lucien. A comb method to * render ECC resistant against Side Channel Attacks. IACR Cryptology * ePrint Archive, 2004, vol. 2004, p. 342. * <http://eprint.iacr.org/2004/342.pdf> */ #define ECP_VALIDATE_RET( cond ) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_ECP_BAD_INPUT_DATA ) #define ECP_VALIDATE( cond ) \ MBEDTLS_INTERNAL_VALIDATE( cond ) #if defined(MBEDTLS_ECP_C) #if !defined(MBEDTLS_ECP_ALT) #if defined(MBEDTLS_SELF_TEST) /* * Counts of point addition and doubling, and field multiplications. * Used to test resistance of point multiplication to simple timing attacks. */ static unsigned long add_count, dbl_count, mul_count; #endif #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) /* * Currently ecp_mul() takes a RNG function as an argument, used for * side-channel protection, but it can be NULL. The initial reasoning was * that people will pass non-NULL RNG when they care about side-channels, but * unfortunately we have some APIs that call ecp_mul() with a NULL RNG, with * no opportunity for the user to do anything about it. * * The obvious strategies for addressing that include: * - change those APIs so that they take RNG arguments; * - require a global RNG to be available to all crypto modules. * * Unfortunately those would break compatibility. So what we do instead is * have our own internal DRBG instance, seeded from the secret scalar. * * The following is a light-weight abstraction layer for doing that with * HMAC_DRBG (first choice) or CTR_DRBG. */ #if defined(MBEDTLS_HMAC_DRBG_C) /* DRBG context type */ typedef mbedtls_hmac_drbg_context ecp_drbg_context; /* DRBG context init */ static inline void ecp_drbg_init( ecp_drbg_context *ctx ) { mbedtls_hmac_drbg_init( ctx ); } /* DRBG context free */ static inline void ecp_drbg_free( ecp_drbg_context *ctx ) { mbedtls_hmac_drbg_free( ctx ); } /* DRBG function */ static inline int ecp_drbg_random( void *p_rng, unsigned char *output, size_t output_len ) { return( mbedtls_hmac_drbg_random( p_rng, output, output_len ) ); } /* DRBG context seeding */ static int ecp_drbg_seed( ecp_drbg_context *ctx, const mbedtls_mpi *secret, size_t secret_len ) { int ret; unsigned char secret_bytes[MBEDTLS_ECP_MAX_BYTES]; /* The list starts with strong hashes */ const mbedtls_md_type_t md_type = mbedtls_md_list()[0]; const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_type ); if( secret_len > MBEDTLS_ECP_MAX_BYTES ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( secret, secret_bytes, secret_len ) ); ret = mbedtls_hmac_drbg_seed_buf( ctx, md_info, secret_bytes, secret_len ); cleanup: mbedtls_platform_zeroize( secret_bytes, secret_len ); return( ret ); } #elif defined(MBEDTLS_CTR_DRBG_C) /* DRBG context type */ typedef mbedtls_ctr_drbg_context ecp_drbg_context; /* DRBG context init */ static inline void ecp_drbg_init( ecp_drbg_context *ctx ) { mbedtls_ctr_drbg_init( ctx ); } /* DRBG context free */ static inline void ecp_drbg_free( ecp_drbg_context *ctx ) { mbedtls_ctr_drbg_free( ctx ); } /* DRBG function */ static inline int ecp_drbg_random( void *p_rng, unsigned char *output, size_t output_len ) { return( mbedtls_ctr_drbg_random( p_rng, output, output_len ) ); } /* * Since CTR_DRBG doesn't have a seed_buf() function the way HMAC_DRBG does, * we need to pass an entropy function when seeding. So we use a dummy * function for that, and pass the actual entropy as customisation string. * (During seeding of CTR_DRBG the entropy input and customisation string are * concatenated before being used to update the secret state.) */ static int ecp_ctr_drbg_null_entropy(void *ctx, unsigned char *out, size_t len) { (void) ctx; mbedtls_platform_zeroize( out, len ); return( 0 ); } /* DRBG context seeding */ static int ecp_drbg_seed( ecp_drbg_context *ctx, const mbedtls_mpi *secret, size_t secret_len ) { int ret; unsigned char secret_bytes[MBEDTLS_ECP_MAX_BYTES]; if( secret_len > MBEDTLS_ECP_MAX_BYTES ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( secret, secret_bytes, secret_len ) ); ret = mbedtls_ctr_drbg_seed( ctx, ecp_ctr_drbg_null_entropy, NULL, secret_bytes, secret_len ); cleanup: mbedtls_platform_zeroize( secret_bytes, secret_len ); return( ret ); } #else #error "Invalid configuration detected. Include check.h to ensure that the configuration is valid." #endif /* DRBG modules */ #endif /* MBEDTLS_ECP_NO_INTERNAL_RNG */ #if defined(MBEDTLS_ECP_RESTARTABLE) /* * Maximum number of "basic operations" to be done in a row. * * Default value 0 means that ECC operations will not yield. * Note that regardless of the value of ecp_max_ops, always at * least one step is performed before yielding. * * Setting ecp_max_ops=1 can be suitable for testing purposes * as it will interrupt computation at all possible points. */ static unsigned ecp_max_ops = 0; /** * \brief Set the maximum number of basic operations done in a row. * * If more operations are needed to complete a computation, * #MBEDTLS_ERR_ECP_IN_PROGRESS will be returned by the * function performing the computation. It is then the * caller's responsibility to either call again with the same * parameters until it returns 0 or an error code; or to free * the restart context if the operation is to be aborted. * * It is strictly required that all input parameters and the * restart context be the same on successive calls for the * same operation, but output parameters need not be the * same; they must not be used until the function finally * returns 0. * * This only applies to functions whose documentation * mentions they may return #MBEDTLS_ERR_ECP_IN_PROGRESS (or * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS for functions in the * SSL module). For functions that accept a "restart context" * argument, passing NULL disables restart and makes the * function equivalent to the function with the same name * with \c _restartable removed. For functions in the ECDH * module, restart is disabled unless the function accepts * an "ECDH context" argument and * mbedtls_ecdh_enable_restart() was previously called on * that context. For function in the SSL module, restart is * only enabled for specific sides and key exchanges * (currently only for clients and ECDHE-ECDSA). * * \param max_ops Maximum number of basic operations done in a row. * Default: 0 (unlimited). * Lower (non-zero) values mean ECC functions will block for * a lesser maximum amount of time. * * \note A "basic operation" is defined as a rough equivalent of a * multiplication in GF(p) for the NIST P-256 curve. * As an indication, with default settings, a scalar * multiplication (full run of \c mbedtls_ecp_mul()) is: * - about 3300 basic operations for P-256 * - about 9400 basic operations for P-384 * * \note Very low values are not always respected: sometimes * functions need to block for a minimum number of * operations, and will do so even if max_ops is set to a * lower value. That minimum depends on the curve size, and * can be made lower by decreasing the value of * \c MBEDTLS_ECP_WINDOW_SIZE. As an indication, here is the * lowest effective value for various curves and values of * that parameter (w for short): * w=6 w=5 w=4 w=3 w=2 * P-256 208 208 160 136 124 * P-384 682 416 320 272 248 * P-521 1364 832 640 544 496 * * \note This setting is currently ignored by Curve25519. */ void mbedtls_ecp_set_max_ops( unsigned max_ops ) { ecp_max_ops = max_ops; } /** * \brief Check if restart is enabled (max_ops != 0) * * \return \c 0 if \c max_ops == 0 (restart disabled) * \return \c 1 otherwise (restart enabled) */ int mbedtls_ecp_restart_is_enabled( void ) { return( ecp_max_ops != 0 ); } /* * Restart sub-context for ecp_mul_comb() */ struct mbedtls_ecp_restart_mul { mbedtls_ecp_point R; /* current intermediate result */ size_t i; /* current index in various loops, 0 outside */ mbedtls_ecp_point *T; /* table for precomputed points */ unsigned char T_size; /* number of points in table T */ enum { /* what were we doing last time we returned? */ ecp_rsm_init = 0, /* nothing so far, dummy initial state */ ecp_rsm_pre_dbl, /* precompute 2^n multiples */ ecp_rsm_pre_norm_dbl, /* normalize precomputed 2^n multiples */ ecp_rsm_pre_add, /* precompute remaining points by adding */ ecp_rsm_pre_norm_add, /* normalize all precomputed points */ ecp_rsm_comb_core, /* ecp_mul_comb_core() */ ecp_rsm_final_norm, /* do the final normalization */ } state; #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) ecp_drbg_context drbg_ctx; unsigned char drbg_seeded; #endif }; /* * Init restart_mul sub-context */ static void ecp_restart_rsm_init( mbedtls_ecp_restart_mul_ctx *ctx ) { mbedtls_ecp_point_init( &ctx->R ); ctx->i = 0; ctx->T = NULL; ctx->T_size = 0; ctx->state = ecp_rsm_init; #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) ecp_drbg_init( &ctx->drbg_ctx ); ctx->drbg_seeded = 0; #endif } /* * Free the components of a restart_mul sub-context */ static void ecp_restart_rsm_free( mbedtls_ecp_restart_mul_ctx *ctx ) { unsigned char i; if( !ctx ) return; mbedtls_ecp_point_free( &ctx->R ); if( ctx->T ) { for( i = 0; i < ctx->T_size; i++ ) mbedtls_ecp_point_free( ctx->T + i ); mbedtls_free( ctx->T ); } #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) ecp_drbg_free( &ctx->drbg_ctx ); #endif ecp_restart_rsm_init( ctx ); } /* * Restart context for ecp_muladd() */ struct mbedtls_ecp_restart_muladd { mbedtls_ecp_point mP; /* mP value */ mbedtls_ecp_point R; /* R intermediate result */ enum { /* what should we do next? */ ecp_rsma_mul1 = 0, /* first multiplication */ ecp_rsma_mul2, /* second multiplication */ ecp_rsma_add, /* addition */ ecp_rsma_norm, /* normalization */ } state; }; /* * Init restart_muladd sub-context */ static void ecp_restart_ma_init( mbedtls_ecp_restart_muladd_ctx *ctx ) { mbedtls_ecp_point_init( &ctx->mP ); mbedtls_ecp_point_init( &ctx->R ); ctx->state = ecp_rsma_mul1; } /* * Free the components of a restart_muladd sub-context */ static void ecp_restart_ma_free( mbedtls_ecp_restart_muladd_ctx *ctx ) { if( !ctx ) return; mbedtls_ecp_point_free( &ctx->mP ); mbedtls_ecp_point_free( &ctx->R ); ecp_restart_ma_init( ctx ); } /** * \brief Initialize a restart context. * * \param ctx The restart context to initialize. This must * not be \c NULL. */ void mbedtls_ecp_restart_init( mbedtls_ecp_restart_ctx *ctx ) { ECP_VALIDATE( ctx ); ctx->ops_done = 0; ctx->depth = 0; ctx->rsm = NULL; ctx->ma = NULL; } /** * \brief Free the components of a restart context. * * \param ctx The restart context to free. This may be \c NULL, in which * case this function returns immediately. If it is not * \c NULL, it must point to an initialized restart context. */ void mbedtls_ecp_restart_free( mbedtls_ecp_restart_ctx *ctx ) { if( ctx == NULL ) return; ecp_restart_rsm_free( ctx->rsm ); mbedtls_free( ctx->rsm ); ecp_restart_ma_free( ctx->ma ); mbedtls_free( ctx->ma ); mbedtls_ecp_restart_init( ctx ); } /* * Check if we can do the next step */ int mbedtls_ecp_check_budget( const mbedtls_ecp_group *grp, mbedtls_ecp_restart_ctx *rs_ctx, unsigned ops ) { ECP_VALIDATE_RET( grp ); if( rs_ctx && ecp_max_ops != 0 ) { /* scale depending on curve size: the chosen reference is 256-bit, * and multiplication is quadratic. Round to the closest integer. */ if( grp->pbits >= 512 ) ops *= 4; else if( grp->pbits >= 384 ) ops *= 2; /* Avoid infinite loops: always allow first step. * Because of that, however, it's not generally true * that ops_done <= ecp_max_ops, so the check * ops_done > ecp_max_ops below is mandatory. */ if( ( rs_ctx->ops_done != 0 ) && ( rs_ctx->ops_done > ecp_max_ops || ops > ecp_max_ops - rs_ctx->ops_done ) ) { return( MBEDTLS_ERR_ECP_IN_PROGRESS ); } /* update running count */ rs_ctx->ops_done += ops; } return( 0 ); } /* Call this when entering a function that needs its own sub-context */ #define ECP_RS_ENTER( SUB ) do { \ /* reset ops count for this call if top-level */ \ if( rs_ctx && rs_ctx->depth++ == 0 ) \ rs_ctx->ops_done = 0; \ \ /* set up our own sub-context if needed */ \ if( mbedtls_ecp_restart_is_enabled() && \ rs_ctx && rs_ctx->SUB == NULL ) \ { \ rs_ctx->SUB = mbedtls_calloc( 1, sizeof( *rs_ctx->SUB ) ); \ if( rs_ctx->SUB == NULL ) \ return( MBEDTLS_ERR_ECP_ALLOC_FAILED ); \ \ ecp_restart_## SUB ##_init( rs_ctx->SUB ); \ } \ } while( 0 ) /* Call this when leaving a function that needs its own sub-context */ #define ECP_RS_LEAVE( SUB ) do { \ /* clear our sub-context when not in progress (done or error) */ \ if( rs_ctx && rs_ctx->SUB && \ ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) \ { \ ecp_restart_## SUB ##_free( rs_ctx->SUB ); \ mbedtls_free( rs_ctx->SUB ); \ rs_ctx->SUB = NULL; \ } \ \ if( rs_ctx ) \ rs_ctx->depth--; \ } while( 0 ) #else /* MBEDTLS_ECP_RESTARTABLE */ #define ECP_RS_ENTER( sub ) (void) rs_ctx; #define ECP_RS_LEAVE( sub ) (void) rs_ctx; #endif /* MBEDTLS_ECP_RESTARTABLE */ /* * List of supported curves: * - internal ID * - TLS NamedCurve ID (RFC 4492 sec. 5.1.1, RFC 7071 sec. 2, RFC 8446 sec. 4.2.7) * - size in bits * - readable name * * ELLIPTIC CURVES 101 * * CURVE SECURITY RECOMMENDED BY * ---------- --------- -------------------------------- * SECP256R1 128 IANA, NIST, FRANCE, GERMANY * SECP384R1 192 IANA, NIST, FRANCE, GERMANY, NSA * X25519 112-128 IANA * X448 224 IANA * SECP256K1 128 BITCOIN * BP384R1 GERMANY * SECP521R1 FRANCE * GC512A RUSSIA * SM2 CHINA * * Reminder: update profiles in x509_crt.c when adding a new curves! */ static const mbedtls_ecp_curve_info ecp_supported_curves[] = { #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) { MBEDTLS_ECP_DP_SECP256R1, 23, 256, "secp256r1" }, #endif #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) { MBEDTLS_ECP_DP_SECP384R1, 24, 384, "secp384r1" }, #endif #if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) { MBEDTLS_ECP_DP_CURVE448, 30, 448, "x448" }, #endif #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) { MBEDTLS_ECP_DP_CURVE25519, 29, 256, "x25519" }, #endif #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) { MBEDTLS_ECP_DP_SECP521R1, 25, 521, "secp521r1" }, #endif #if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) { MBEDTLS_ECP_DP_SECP256K1, 22, 256, "secp256k1" }, #endif #if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) { MBEDTLS_ECP_DP_BP512R1, 28, 512, "brainpoolP512r1" }, #endif #if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) { MBEDTLS_ECP_DP_BP384R1, 27, 384, "brainpoolP384r1" }, #endif #if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) { MBEDTLS_ECP_DP_BP256R1, 26, 256, "brainpoolP256r1" }, #endif #if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) { MBEDTLS_ECP_DP_SECP224R1, 21, 224, "secp224r1" }, #endif #if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) { MBEDTLS_ECP_DP_SECP224K1, 20, 224, "secp224k1" }, #endif #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) { MBEDTLS_ECP_DP_SECP192R1, 19, 192, "secp192r1" }, #endif #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) { MBEDTLS_ECP_DP_SECP192K1, 18, 192, "secp192k1" }, #endif { MBEDTLS_ECP_DP_NONE, 0, 0, NULL }, }; #define ECP_NB_CURVES sizeof( ecp_supported_curves ) / \ sizeof( ecp_supported_curves[0] ) static mbedtls_ecp_group_id ecp_supported_grp_id[ECP_NB_CURVES]; /** * \brief This function retrieves the information defined in * mbedtls_ecp_curve_info() for all supported curves in order * of preference. * * \note This function returns information about all curves * supported by the library. Some curves may not be * supported for all algorithms. Call mbedtls_ecdh_can_do() * or mbedtls_ecdsa_can_do() to check if a curve is * supported for ECDH or ECDSA. * * \return A statically allocated array. The last entry is 0. */ const mbedtls_ecp_curve_info *mbedtls_ecp_curve_list( void ) { return( ecp_supported_curves ); } /** * \brief This function retrieves the list of internal group * identifiers of all supported curves in the order of * preference. * * \note This function returns information about all curves * supported by the library. Some curves may not be * supported for all algorithms. Call mbedtls_ecdh_can_do() * or mbedtls_ecdsa_can_do() to check if a curve is * supported for ECDH or ECDSA. * * \return A statically allocated array, * terminated with MBEDTLS_ECP_DP_NONE. */ const mbedtls_ecp_group_id *mbedtls_ecp_grp_id_list( void ) { static int init_done = 0; if( ! init_done ) { size_t i = 0; const mbedtls_ecp_curve_info *curve_info; for( curve_info = mbedtls_ecp_curve_list(); curve_info->grp_id != MBEDTLS_ECP_DP_NONE; curve_info++ ) { ecp_supported_grp_id[i++] = curve_info->grp_id; } ecp_supported_grp_id[i] = MBEDTLS_ECP_DP_NONE; init_done = 1; } return( ecp_supported_grp_id ); } /** * \brief This function retrieves curve information from an internal * group identifier. * * \param grp_id An \c MBEDTLS_ECP_DP_XXX value. * * \return The associated curve information on success. * \return NULL on failure. */ const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_grp_id( mbedtls_ecp_group_id grp_id ) { const mbedtls_ecp_curve_info *curve_info; for( curve_info = mbedtls_ecp_curve_list(); curve_info->grp_id != MBEDTLS_ECP_DP_NONE; curve_info++ ) { if( curve_info->grp_id == grp_id ) return( curve_info ); } return( NULL ); } /** * \brief This function retrieves curve information from a TLS * NamedCurve value. * * \param tls_id An \c MBEDTLS_ECP_DP_XXX value. * * \return The associated curve information on success. * \return NULL on failure. */ const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_tls_id( uint16_t tls_id ) { const mbedtls_ecp_curve_info *curve_info; for( curve_info = mbedtls_ecp_curve_list(); curve_info->grp_id != MBEDTLS_ECP_DP_NONE; curve_info++ ) { if( curve_info->tls_id == tls_id ) return( curve_info ); } return( NULL ); } /** * \brief This function retrieves curve information from a * human-readable name. * * \param name The human-readable name. * * \return The associated curve information on success. * \return NULL on failure. */ const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_name( const char *name ) { const mbedtls_ecp_curve_info *curve_info; if( name == NULL ) return( NULL ); for( curve_info = mbedtls_ecp_curve_list(); curve_info->grp_id != MBEDTLS_ECP_DP_NONE; curve_info++ ) { if( strcmp( curve_info->name, name ) == 0 ) return( curve_info ); } return( NULL ); } /* * Get the type of a curve */ mbedtls_ecp_curve_type mbedtls_ecp_get_type( const mbedtls_ecp_group *grp ) { if( grp->G.X.p == NULL ) return( MBEDTLS_ECP_TYPE_NONE ); if( grp->G.Y.p == NULL ) return( MBEDTLS_ECP_TYPE_MONTGOMERY ); else return( MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ); } /** * \brief This function initializes a point as zero. * * \param pt The point to initialize. */ void mbedtls_ecp_point_init( mbedtls_ecp_point *pt ) { ECP_VALIDATE( pt ); mbedtls_mpi_init( &pt->X ); mbedtls_mpi_init( &pt->Y ); mbedtls_mpi_init( &pt->Z ); } /** * \brief This function initializes an ECP group context * without loading any domain parameters. * * \note After this function is called, domain parameters * for various ECP groups can be loaded through the * mbedtls_ecp_group_load() or mbedtls_ecp_tls_read_group() * functions. */ void mbedtls_ecp_group_init( mbedtls_ecp_group *grp ) { ECP_VALIDATE( grp ); grp->id = MBEDTLS_ECP_DP_NONE; mbedtls_mpi_init( &grp->P ); mbedtls_mpi_init( &grp->A ); mbedtls_mpi_init( &grp->B ); mbedtls_ecp_point_init( &grp->G ); mbedtls_mpi_init( &grp->N ); grp->pbits = 0; grp->nbits = 0; grp->h = 0; grp->modp = NULL; grp->t_pre = NULL; grp->t_post = NULL; grp->t_data = NULL; grp->T = NULL; grp->T_size = 0; } /** * \brief This function initializes a key pair as an invalid one. * * \param key The key pair to initialize. */ void mbedtls_ecp_keypair_init( mbedtls_ecp_keypair *key ) { ECP_VALIDATE( key ); mbedtls_ecp_group_init( &key->grp ); mbedtls_mpi_init( &key->d ); mbedtls_ecp_point_init( &key->Q ); } /** * \brief This function frees the components of a point. * * \param pt The point to free. */ void mbedtls_ecp_point_free( mbedtls_ecp_point *pt ) { if( !pt ) return; mbedtls_mpi_free( &( pt->X ) ); mbedtls_mpi_free( &( pt->Y ) ); mbedtls_mpi_free( &( pt->Z ) ); } /** * \brief This function frees the components of an ECP group. * * \param grp The group to free. This may be \c NULL, in which * case this function returns immediately. If it is not * \c NULL, it must point to an initialized ECP group. */ void mbedtls_ecp_group_free( mbedtls_ecp_group *grp ) { size_t i; if( !grp ) return; if( grp->h != 1 ) { mbedtls_mpi_free( &grp->P ); mbedtls_mpi_free( &grp->A ); mbedtls_mpi_free( &grp->B ); mbedtls_ecp_point_free( &grp->G ); mbedtls_mpi_free( &grp->N ); } if( grp->T ) { for( i = 0; i < grp->T_size; i++ ) mbedtls_ecp_point_free( &grp->T[i] ); mbedtls_free( grp->T ); } mbedtls_platform_zeroize( grp, sizeof( mbedtls_ecp_group ) ); } /** * \brief This function frees the components of a key pair. * * \param key The key pair to free. This may be \c NULL, in which * case this function returns immediately. If it is not * \c NULL, it must point to an initialized ECP key pair. */ void mbedtls_ecp_keypair_free( mbedtls_ecp_keypair *key ) { if( !key ) return; mbedtls_ecp_group_free( &key->grp ); mbedtls_mpi_free( &key->d ); mbedtls_ecp_point_free( &key->Q ); } /** * \brief This function copies the contents of point \p Q into * point \p P. * * \param P The destination point. This must be initialized. * \param Q The source point. This must be initialized. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. * \return Another negative error code for other kinds of failure. */ int mbedtls_ecp_copy( mbedtls_ecp_point *P, const mbedtls_ecp_point *Q ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; ECP_VALIDATE_RET( P ); ECP_VALIDATE_RET( Q ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &P->X, &Q->X ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &P->Y, &Q->Y ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &P->Z, &Q->Z ) ); cleanup: return( ret ); } /** * \brief This function copies the contents of group \p src into * group \p dst. * * \param dst The destination group. This must be initialized. * \param src The source group. This must be initialized. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_group_copy( mbedtls_ecp_group *dst, const mbedtls_ecp_group *src ) { ECP_VALIDATE_RET( dst ); ECP_VALIDATE_RET( src ); return( mbedtls_ecp_group_load( dst, src->id ) ); } /** * \brief This function checks if a point is the point at infinity. * * \param pt The point to test. This must be initialized. * * \return \c 1 if the point is zero. * \return \c 0 if the point is non-zero. * \return A negative error code on failure. */ int mbedtls_ecp_is_zero( mbedtls_ecp_point *pt ) { ECP_VALIDATE_RET( pt ); return( mbedtls_mpi_is_zero( &pt->Z ) ); } /** * \brief This function compares two points. * * \note This assumes that the points are normalized. Otherwise, * they may compare as "not equal" even if they are. * * \param P The first point to compare. This must be initialized. * \param Q The second point to compare. This must be initialized. * * \return \c 0 if the points are equal. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the points are not equal. */ int mbedtls_ecp_point_cmp( const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q ) { ECP_VALIDATE_RET( P ); ECP_VALIDATE_RET( Q ); if( mbedtls_mpi_cmp_mpi( &P->X, &Q->X ) == 0 && mbedtls_mpi_cmp_mpi( &P->Y, &Q->Y ) == 0 && mbedtls_mpi_cmp_mpi( &P->Z, &Q->Z ) == 0 ) { return( 0 ); } return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); } /** * \brief This function imports a non-zero point from two ASCII * strings. * * \param P The destination point. This must be initialized. * \param radix The numeric base of the input. * \param x The first affine coordinate, as a null-terminated string. * \param y The second affine coordinate, as a null-terminated string. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_MPI_XXX error code on failure. */ int mbedtls_ecp_point_read_string( mbedtls_ecp_point *P, int radix, const char *x, const char *y ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; ECP_VALIDATE_RET( P ); ECP_VALIDATE_RET( x ); ECP_VALIDATE_RET( y ); MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &P->X, radix, x ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &P->Y, radix, y ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &P->Z, 1 ) ); cleanup: return( ret ); } /** * \brief This function exports a point into unsigned binary data. * * \param grp The group to which the point should belong. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param P The point to export. This must be initialized. * \param format The point format. This must be either * #MBEDTLS_ECP_PF_COMPRESSED or #MBEDTLS_ECP_PF_UNCOMPRESSED. * (For groups without these formats, this parameter is * ignored. But it still has to be either of the above * values.) * \param olen The address at which to store the length of * the output in Bytes. This must not be \c NULL. * \param buf The output buffer. This must be a writable buffer * of length \p buflen Bytes. * \param buflen The length of the output buffer \p buf in Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL if the output buffer * is too small to hold the point. * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the point format * or the export for the given group is not implemented. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_point_write_binary( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *P, int format, size_t *olen, unsigned char *buf, size_t buflen ) { /* * Export a point into unsigned binary data (SEC1 2.3.3 and RFC7748) */ int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE; size_t plen; ECP_VALIDATE_RET( grp ); ECP_VALIDATE_RET( P ); ECP_VALIDATE_RET( olen ); ECP_VALIDATE_RET( buf ); ECP_VALIDATE_RET( format == MBEDTLS_ECP_PF_UNCOMPRESSED || format == MBEDTLS_ECP_PF_COMPRESSED ); plen = mbedtls_mpi_size( &grp->P ); #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) (void) format; /* Montgomery curves always use the same point format */ if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY ) { *olen = plen; if( buflen < *olen ) return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary_le( &P->X, buf, plen ) ); } #endif #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) { /* * Common case: P == 0 */ if( mbedtls_mpi_is_zero( &P->Z ) ) { if( buflen < 1 ) return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL ); buf[0] = 0x00; *olen = 1; return( 0 ); } if( format == MBEDTLS_ECP_PF_UNCOMPRESSED ) { *olen = 2 * plen + 1; if( buflen < *olen ) return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL ); buf[0] = 0x04; MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &P->X, buf + 1, plen ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &P->Y, buf + 1 + plen, plen ) ); } else if( format == MBEDTLS_ECP_PF_COMPRESSED ) { *olen = plen + 1; if( buflen < *olen ) return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL ); buf[0] = 0x02 + mbedtls_mpi_get_bit( &P->Y, 0 ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &P->X, buf + 1, plen ) ); } } #endif cleanup: return( ret ); } /** * \brief This function imports a point from unsigned binary data. * * \note This function does not check that the point actually * belongs to the given group, see mbedtls_ecp_check_pubkey() * for that. * * \param grp The group to which the point should belong. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param P The destination context to import the point to. * This must be initialized. * \param buf The input buffer. This must be a readable buffer * of length \p ilen Bytes. * \param ilen The length of the input buffer \p buf in Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the input is invalid. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the import for the * given group is not implemented. */ int mbedtls_ecp_point_read_binary( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt, const unsigned char *buf, size_t ilen ) { /* * Import a point from unsigned binary data (SEC1 2.3.4 and RFC7748) */ int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE; size_t plen; ECP_VALIDATE_RET( grp ); ECP_VALIDATE_RET( pt ); ECP_VALIDATE_RET( buf ); if( ilen < 1 ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); plen = mbedtls_mpi_size( &grp->P ); #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY ) { if( plen != ilen ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary_le( &pt->X, buf, plen ) ); mbedtls_mpi_free( &pt->Y ); if( grp->id == MBEDTLS_ECP_DP_CURVE25519 ) /* Set most significant bit to 0 as prescribed in RFC7748 §5 */ MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &pt->X, plen * 8 - 1, 0 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Z, 1 ) ); } #endif #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) { if( !buf[0] ) { if( ilen == 1 ) return( mbedtls_ecp_set_zero( pt ) ); else return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); } if( buf[0] != 0x04 ) return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ); if( ilen != 2 * plen + 1 ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &pt->X, buf + 1, plen ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &pt->Y, buf + 1 + plen, plen ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Z, 1 ) ); } #endif cleanup: return( ret ); } /** * \brief This function imports a point from a TLS ECPoint record. * * \note On function return, \p *buf is updated to point immediately * after the ECPoint record. * * \param grp The ECP group to use. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param pt The destination point. * \param buf The address of the pointer to the start of the input buffer. * \param len The length of the buffer. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_MPI_XXX error code on initialization * failure. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid. */ int mbedtls_ecp_tls_read_point( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt, const unsigned char **buf, size_t buf_len ) { /* * Import a point from a TLS ECPoint record (RFC 4492) * struct { * opaque point <1..2^8-1>; * } ECPoint; */ unsigned char data_len; const unsigned char *buf_start; ECP_VALIDATE_RET( grp ); ECP_VALIDATE_RET( pt ); ECP_VALIDATE_RET( buf ); ECP_VALIDATE_RET( *buf ); /* * We must have at least two bytes (1 for length, at least one for data) */ if( buf_len < 2 ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); data_len = *(*buf)++; if( data_len < 1 || data_len > buf_len - 1 ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); /* * Save buffer start for read_binary and update buf */ buf_start = *buf; *buf += data_len; return( mbedtls_ecp_point_read_binary( grp, pt, buf_start, data_len ) ); } /** * \brief This function exports a point as a TLS ECPoint record * defined in RFC 4492, Section 5.4. * * \param grp The ECP group to use. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param pt The point to be exported. This must be initialized. * \param format The point format to use. This must be either * #MBEDTLS_ECP_PF_COMPRESSED or #MBEDTLS_ECP_PF_UNCOMPRESSED. * \param olen The address at which to store the length in Bytes * of the data written. * \param buf The target buffer. This must be a writable buffer of * length \p blen Bytes. * \param blen The length of the target buffer \p buf in Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the input is invalid. * \return #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL if the target buffer * is too small to hold the exported point. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_tls_write_point( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt, int format, size_t *olen, unsigned char *buf, size_t blen ) { /* * Export a point as a TLS ECPoint record (RFC 4492) * struct { * opaque point <1..2^8-1>; * } ECPoint; */ int ret = MBEDTLS_ERR_THIS_CORRUPTION; ECP_VALIDATE_RET( grp ); ECP_VALIDATE_RET( pt ); ECP_VALIDATE_RET( olen ); ECP_VALIDATE_RET( buf ); ECP_VALIDATE_RET( format == MBEDTLS_ECP_PF_UNCOMPRESSED || format == MBEDTLS_ECP_PF_COMPRESSED ); /* * buffer length must be at least one, for our length byte */ if( blen < 1 ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); if( ( ret = mbedtls_ecp_point_write_binary( grp, pt, format, olen, buf + 1, blen - 1) ) != 0 ) return( ret ); /* * write length to the first byte and update total length */ buf[0] = (unsigned char) *olen; ++*olen; return( 0 ); } /** * \brief This function sets up an ECP group context from a TLS * ECParameters record as defined in RFC 4492, Section 5.4. * * \note The read pointer \p buf is updated to point right after * the ECParameters record on exit. * * \param grp The group context to setup. This must be initialized. * \param buf The address of the pointer to the start of the input buffer. * \param len The length of the input buffer \c *buf in Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid. * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the group is not * recognized. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_tls_read_group( mbedtls_ecp_group *grp, const unsigned char **buf, size_t len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_ecp_group_id grp_id; ECP_VALIDATE_RET( grp ); ECP_VALIDATE_RET( buf ); ECP_VALIDATE_RET( *buf ); if( ( ret = mbedtls_ecp_tls_read_group_id( &grp_id, buf, len ) ) != 0 ) return( ret ); return( mbedtls_ecp_group_load( grp, grp_id ) ); } /** * \brief This function extracts an elliptic curve group ID from a * TLS ECParameters record as defined in RFC 4492, Section 5.4. * * \note The read pointer \p buf is updated to point right after * the ECParameters record on exit. * * \param grp The address at which to store the group id. * This must not be \c NULL. * \param buf The address of the pointer to the start of the input buffer. * \param len The length of the input buffer \c *buf in Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid. * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the group is not * recognized. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_tls_read_group_id( mbedtls_ecp_group_id *grp, const unsigned char **buf, size_t len ) { uint16_t tls_id; const mbedtls_ecp_curve_info *curve_info; ECP_VALIDATE_RET( grp ); ECP_VALIDATE_RET( buf ); ECP_VALIDATE_RET( *buf ); /* * We expect at least three bytes (see below) */ if( len < 3 ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); /* * First byte is curve_type; only named_curve is handled */ if( *(*buf)++ != MBEDTLS_ECP_TLS_NAMED_CURVE ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); /* * Next two bytes are the namedcurve value */ tls_id = *(*buf)++; tls_id <<= 8; tls_id |= *(*buf)++; if( ( curve_info = mbedtls_ecp_curve_info_from_tls_id( tls_id ) ) == NULL ) return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ); *grp = curve_info->grp_id; return( 0 ); } /** * \brief This function exports an elliptic curve as a TLS * ECParameters record as defined in RFC 4492, Section 5.4. * * \param grp The ECP group to be exported. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param olen The address at which to store the number of Bytes written. * This must not be \c NULL. * \param buf The buffer to write to. This must be a writable buffer * of length \p blen Bytes. * \param blen The length of the output buffer \p buf in Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL if the output * buffer is too small to hold the exported group. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_tls_write_group( const mbedtls_ecp_group *grp, size_t *olen, unsigned char *buf, size_t blen ) { const mbedtls_ecp_curve_info *curve_info; ECP_VALIDATE_RET( grp ); ECP_VALIDATE_RET( buf ); ECP_VALIDATE_RET( olen ); if( ( curve_info = mbedtls_ecp_curve_info_from_grp_id( grp->id ) ) == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); /* * We are going to write 3 bytes (see below) */ *olen = 3; if( blen < *olen ) return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL ); /* * First byte is curve_type, always named_curve */ *buf++ = MBEDTLS_ECP_TLS_NAMED_CURVE; /* * Next two bytes are the namedcurve value */ buf[0] = curve_info->tls_id >> 8; buf[1] = curve_info->tls_id & 0xFF; return( 0 ); } /* * Wrapper around fast quasi-modp functions, with fall-back to mbedtls_mpi_mod_mpi. * See the documentation of struct mbedtls_ecp_group. * * This function is in the critial loop for mbedtls_ecp_mul, so pay attention to perf. */ static int ecp_modp( mbedtls_mpi *N, const mbedtls_ecp_group *grp ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( !grp->modp ) return( mbedtls_mpi_mod_mpi( N, N, &grp->P ) ); /* N->s < 0 is a much faster test, which fails only if N is 0 */ if( ( N->s < 0 && !mbedtls_mpi_is_zero( N ) ) || mbedtls_mpi_bitlen( N ) > 2 * grp->pbits ) { return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); } MBEDTLS_MPI_CHK( grp->modp( N ) ); /* N->s < 0 is a much faster test, which fails only if N is 0 */ while( N->s < 0 && !mbedtls_mpi_is_zero( N ) ) MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( N, N, &grp->P ) ); while( mbedtls_mpi_cmp_mpi( N, &grp->P ) >= 0 ) /* we known P, N and the result are positive */ MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( N, N, &grp->P ) ); cleanup: return( ret ); } /* * Fast mod-p functions expect their argument to be in the 0..p^2 range. * * In order to guarantee that, we need to ensure that operands of * mbedtls_mpi_mul_mpi are in the 0..p range. So, after each operation we will * bring the result back to this range. * * The following macros are shortcuts for doing that. */ /* * Reduce a mbedtls_mpi mod p in-place, general case, to use after mbedtls_mpi_mul_mpi */ #if defined(MBEDTLS_SELF_TEST) #define INC_MUL_COUNT mul_count++; #else #define INC_MUL_COUNT #endif #define MOD_MUL( N ) \ do \ { \ MBEDTLS_MPI_CHK( ecp_modp( &(N), grp ) ); \ INC_MUL_COUNT \ } while( 0 ) int mbedtls_mpi_mul_mod( const mbedtls_ecp_group *grp, mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( X, A, B ) ); MOD_MUL( *X ); cleanup: return( ret ); } /* * Reduce a mbedtls_mpi mod p in-place, to use after mbedtls_mpi_sub_mpi * N->s < 0 is a very fast test, which fails only if N is 0 */ #define MOD_SUB( N ) \ while( (N).s < 0 && !mbedtls_mpi_is_zero( &(N) ) ) \ MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &(N), &(N), &grp->P ) ) #if ( defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) && \ !( defined(MBEDTLS_ECP_NO_FALLBACK) && \ defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) && \ defined(MBEDTLS_ECP_ADD_MIXED_ALT) ) ) || \ ( defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) && \ !( defined(MBEDTLS_ECP_NO_FALLBACK) && \ defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) ) ) int mbedtls_mpi_sub_mod( const mbedtls_ecp_group *grp, mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( X, A, B ) ); MOD_SUB( *X ); cleanup: return( ret ); } #endif /* All functions referencing mbedtls_mpi_sub_mod() are alt-implemented without fallback */ /* * Reduce a mbedtls_mpi mod p in-place, to use after mbedtls_mpi_add_mpi and mbedtls_mpi_mul_int. * We known P, N and the result are positive, so sub_abs is correct, and * a bit faster. */ #define MOD_ADD( N ) \ while( mbedtls_mpi_cmp_mpi( &(N), &grp->P ) >= 0 ) \ MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( &(N), &(N), &grp->P ) ) static inline int mbedtls_mpi_add_mod( const mbedtls_ecp_group *grp, mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( X, A, B ) ); MOD_ADD( *X ); cleanup: return( ret ); } #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) /* * For curves in short Weierstrass form, we do all the internal operations in * Jacobian coordinates. * * For multiplication, we'll use a comb method with coutermeasueres against * SPA, hence timing attacks. */ /* * Normalize jacobian coordinates so that Z == 0 || Z == 1 (GECC 3.2.1) * Cost: 1N := 1I + 3M + 1S */ static int ecp_normalize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt ) { if( mbedtls_ecp_is_zero( pt ) ) return( 0 ); #if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT) if( mbedtls_internal_ecp_grp_capable( grp ) ) return( mbedtls_internal_ecp_normalize_jac( grp, pt ) ); #endif /* MBEDTLS_ECP_NORMALIZE_JAC_ALT */ #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT) return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ); #else #ifdef MBEDTLS_ECP_DP_SECP384R1_ENABLED if ( grp->modp == ecp_mod_p384 ) return mbedtls_p384_normalize_jac(grp, pt); #endif #ifdef MBEDTLS_ECP_DP_SECP256R1_ENABLED if ( grp->modp == ecp_mod_p256 ) return mbedtls_p256_normalize_jac(grp, pt); #endif int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_mpi Zi, ZZi; mbedtls_mpi_init( &Zi ); mbedtls_mpi_init( &ZZi ); /* * X = X / Z^2 mod p */ MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &Zi, &pt->Z, &grp->P ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &ZZi, &Zi, &Zi ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &pt->X, &pt->X, &ZZi ) ); /* * Y = Y / Z^3 mod p */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &pt->Y, &pt->Y, &ZZi ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &pt->Y, &pt->Y, &Zi ) ); /* * Z = 1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Z, 1 ) ); cleanup: mbedtls_mpi_free( &Zi ); mbedtls_mpi_free( &ZZi ); return( ret ); #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT) */ } /* * Normalize jacobian coordinates of an array of (pointers to) points, * using Montgomery's trick to perform only one inversion mod P. * (See for example Cohen's "A Course in Computational Algebraic Number * Theory", Algorithm 10.3.4.) * * Warning: fails (returning an error) if one of the points is zero! * This should never happen, see choice of w in ecp_mul_comb(). * * Cost: 1N(t) := 1I + (6t - 3)M + 1S */ static int ecp_normalize_jac_many( const mbedtls_ecp_group *grp, mbedtls_ecp_point *T[], size_t T_size ) { if( T_size < 2 ) return( ecp_normalize_jac( grp, *T ) ); #if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT) if( mbedtls_internal_ecp_grp_capable( grp ) ) return( mbedtls_internal_ecp_normalize_jac_many( grp, T, T_size ) ); #endif #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT) return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ); #else #ifdef MBEDTLS_ECP_DP_SECP384R1_ENABLED if ( grp->modp == ecp_mod_p384 ) return mbedtls_p384_normalize_jac_many(grp, T, T_size); #endif #ifdef MBEDTLS_ECP_DP_SECP256R1_ENABLED if ( grp->modp == ecp_mod_p256 ) return mbedtls_p256_normalize_jac_many(grp, T, T_size); #endif int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t i; mbedtls_mpi *c, u, Zi, ZZi; if( ( c = mbedtls_calloc( T_size, sizeof( mbedtls_mpi ) ) ) == NULL ) return( MBEDTLS_ERR_ECP_ALLOC_FAILED ); for( i = 0; i < T_size; i++ ) mbedtls_mpi_init( &c[i] ); mbedtls_mpi_init( &u ); mbedtls_mpi_init( &Zi ); mbedtls_mpi_init( &ZZi ); /* * c[i] = Z_0 * ... * Z_i */ MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &c[0], &T[0]->Z ) ); for( i = 1; i < T_size; i++ ) { MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &c[i], &c[i-1], &T[i]->Z ) ); } /* * u = 1 / (Z_0 * ... * Z_n) mod P */ MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &u, &c[T_size-1], &grp->P ) ); for( i = T_size - 1; ; i-- ) { /* * Zi = 1 / Z_i mod p * u = 1 / (Z_0 * ... * Z_i) mod P */ if( i == 0 ) { MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Zi, &u ) ); } else { MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &Zi, &u, &c[i-1] ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &u, &u, &T[i]->Z ) ); } /* * proceed as in normalize() */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &ZZi, &Zi, &Zi ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T[i]->X, &T[i]->X, &ZZi ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T[i]->Y, &T[i]->Y, &ZZi ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T[i]->Y, &T[i]->Y, &Zi ) ); /* * Post-precessing: reclaim some memory by shrinking coordinates * - not storing Z (always 1) * - shrinking other coordinates, but still keeping the same number of * limbs as P, as otherwise it will too likely be regrown too fast. */ MBEDTLS_MPI_CHK( mbedtls_mpi_shrink( &T[i]->X, grp->P.n ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shrink( &T[i]->Y, grp->P.n ) ); mbedtls_mpi_free( &T[i]->Z ); if( i == 0 ) break; } cleanup: mbedtls_mpi_free( &u ); mbedtls_mpi_free( &Zi ); mbedtls_mpi_free( &ZZi ); for( i = 0; i < T_size; i++ ) mbedtls_mpi_free( &c[i] ); mbedtls_free( c ); return( ret ); #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT) */ } /* * Conditional point inversion: Q -> -Q = (Q.X, -Q.Y, Q.Z) without leak. * "inv" must be 0 (don't invert) or 1 (invert) or the result will be invalid */ static int ecp_safe_invert_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *Q, unsigned char inv ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char nonzero; mbedtls_mpi mQY; mbedtls_mpi_init( &mQY ); /* Use the fact that -Q.Y mod P = P - Q.Y unless Q.Y == 0 */ MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &mQY, &grp->P, &Q->Y ) ); nonzero = !mbedtls_mpi_is_zero( &Q->Y ); MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &Q->Y, &mQY, inv & nonzero ) ); cleanup: mbedtls_mpi_free( &mQY ); return( ret ); } /* * Point doubling R = 2 P, Jacobian coordinates * * Based on http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-dbl-1998-cmo-2 . * * We follow the variable naming fairly closely. The formula variations that trade a MUL for a SQR * (plus a few ADDs) aren't useful as our bignum implementation doesn't distinguish squaring. * * Standard optimizations are applied when curve parameter A is one of { 0, -3 }. * * Cost: 1D := 3M + 4S (A == 0) * 4M + 4S (A == -3) * 3M + 6S + 1a otherwise */ static int ecp_double_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_ecp_point *P ) { #if defined(MBEDTLS_SELF_TEST) dbl_count++; #endif #if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) if( mbedtls_internal_ecp_grp_capable( grp ) ) return( mbedtls_internal_ecp_double_jac( grp, R, P ) ); #endif /* MBEDTLS_ECP_DOUBLE_JAC_ALT */ #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ); #else #ifdef MBEDTLS_ECP_DP_SECP256R1_ENABLED if ( grp->modp == ecp_mod_p256 ) return mbedtls_p256_double_jac(grp, P, R); #endif #ifdef MBEDTLS_ECP_DP_SECP384R1_ENABLED if ( grp->modp == ecp_mod_p384 ) return mbedtls_p384_double_jac(grp, P, R); #endif int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_mpi M, S, T, U; mbedtls_mpi_init( &M ); mbedtls_mpi_init( &S ); mbedtls_mpi_init( &T ); mbedtls_mpi_init( &U ); /* Special case for A = -3 */ if( !grp->A.p ) { /* M = 3(X + Z^2)(X - Z^2) */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S, &P->Z, &P->Z ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &T, &P->X, &S ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &U, &P->X, &S ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S, &T, &U ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &M, &S, 3 ) ); MOD_ADD( M ); } else { /* M = 3.X^2 */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S, &P->X, &P->X ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &M, &S, 3 ) ); MOD_ADD( M ); /* Optimize away for "koblitz" curves with A = 0 */ if( !mbedtls_mpi_is_zero( &grp->A ) ) { /* M += A.Z^4 */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S, &P->Z, &P->Z ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T, &S, &S ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S, &T, &grp->A ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &M, &M, &S ) ); } } /* S = 4.X.Y^2 */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T, &P->Y, &P->Y ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l_mod( grp, &T ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S, &P->X, &T ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l_mod( grp, &S ) ); /* U = 8.Y^4 */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &U, &T, &T ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l_mod( grp, &U ) ); /* T = M^2 - 2.S */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T, &M, &M ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &T, &T, &S ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &T, &T, &S ) ); /* S = M(S - T) - U */ MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &S, &S, &T ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S, &S, &M ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &S, &S, &U ) ); /* U = 2.Y.Z */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &U, &P->Y, &P->Z ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l_mod( grp, &U ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->X, &T ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->Y, &S ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->Z, &U ) ); cleanup: mbedtls_mpi_free( &M ); mbedtls_mpi_free( &S ); mbedtls_mpi_free( &T ); mbedtls_mpi_free( &U ); return( ret ); #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) */ } /* * Addition: R = P + Q, mixed affine-Jacobian coordinates (GECC 3.22) * * The coordinates of Q must be normalized (= affine), * but those of P don't need to. R is not normalized. * * Special cases: (1) P or Q is zero, (2) R is zero, (3) P == Q. * None of these cases can happen as intermediate step in ecp_mul_comb(): * - at each step, P, Q and R are multiples of the base point, the factor * being less than its order, so none of them is zero; * - Q is an odd multiple of the base point, P an even multiple, * due to the choice of precomputed points in the modified comb method. * So branches for these cases do not leak secret information. * * We accept Q->Z being unset (saving memory in tables) as meaning 1. * * Cost: 1A := 8M + 3S */ static int ecp_add_mixed( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q ) { #if defined(MBEDTLS_SELF_TEST) add_count++; #endif #if defined(MBEDTLS_ECP_ADD_MIXED_ALT) if( mbedtls_internal_ecp_grp_capable( grp ) ) return( mbedtls_internal_ecp_add_mixed( grp, R, P, Q ) ); #endif /* MBEDTLS_ECP_ADD_MIXED_ALT */ #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_ADD_MIXED_ALT) return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ); #else int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_mpi T1, T2, T3, T4, X, Y, Z; /* * Trivial cases: P == 0 or Q == 0 (case 1) */ if( mbedtls_ecp_is_zero( P ) ) return( mbedtls_ecp_copy( R, Q ) ); if( Q->Z.p && mbedtls_ecp_is_zero( Q ) ) return( mbedtls_ecp_copy( R, P ) ); /* * Make sure Q coordinates are normalized */ if( Q->Z.p && !mbedtls_mpi_is_one( &Q->Z ) ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); #ifdef MBEDTLS_ECP_DP_SECP384R1_ENABLED if ( grp->modp == ecp_mod_p384 ) return mbedtls_p384_add_mixed(grp, P, Q, R); #endif #ifdef MBEDTLS_ECP_DP_SECP256R1_ENABLED if ( grp->modp == ecp_mod_p256 ) return mbedtls_p256_add_mixed(grp, P, Q, R); #endif mbedtls_mpi_init( &T1 ); mbedtls_mpi_init( &T2 ); mbedtls_mpi_init( &T3 ); mbedtls_mpi_init( &T4 ); mbedtls_mpi_init( &X ); mbedtls_mpi_init( &Y ); mbedtls_mpi_init( &Z ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T1, &P->Z, &P->Z ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T2, &T1, &P->Z ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T1, &T1, &Q->X ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T2, &T2, &Q->Y ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &T1, &T1, &P->X ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &T2, &T2, &P->Y ) ); /* Special cases (2) and (3) */ if( mbedtls_mpi_is_zero( &T1 ) ) { if( mbedtls_mpi_is_zero( &T2 ) ) { ret = ecp_double_jac( grp, R, P ); goto cleanup; } else { ret = mbedtls_ecp_set_zero( R ); goto cleanup; } } MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &Z, &P->Z, &T1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T3, &T1, &T1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T4, &T3, &T1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T3, &T3, &P->X ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &T1, &T3 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l_mod( grp, &T1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &X, &T2, &T2 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &X, &X, &T1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &X, &X, &T4 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &T3, &T3, &X ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T3, &T3, &T2 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T4, &T4, &P->Y ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &Y, &T3, &T4 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->X, &X ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->Y, &Y ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->Z, &Z ) ); cleanup: mbedtls_mpi_free( &T1 ); mbedtls_mpi_free( &T2 ); mbedtls_mpi_free( &T3 ); mbedtls_mpi_free( &T4 ); mbedtls_mpi_free( &X ); mbedtls_mpi_free( &Y ); mbedtls_mpi_free( &Z ); return( ret ); #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_ADD_MIXED_ALT) */ } /* * Randomize jacobian coordinates: * (X, Y, Z) -> (l^2 X, l^3 Y, l Z) for random l * This is sort of the reverse operation of ecp_normalize_jac(). * * This countermeasure was first suggested in [2]. */ static int ecp_randomize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { #if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) if( mbedtls_internal_ecp_grp_capable( grp ) ) return( mbedtls_internal_ecp_randomize_jac( grp, pt, f_rng, p_rng ) ); #endif /* MBEDTLS_ECP_RANDOMIZE_JAC_ALT */ #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ); #else int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_mpi l, ll; int count = 0; size_t p_size = ( grp->pbits + 7 ) / 8; mbedtls_mpi_init( &l ); mbedtls_mpi_init( &ll ); /* Generate l such that 1 < l < p */ do { MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &l, p_size, f_rng, p_rng ) ); while( mbedtls_mpi_cmp_mpi( &l, &grp->P ) >= 0 ) mbedtls_mpi_shift_r( &l, 1 ); if( count++ > 10 ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } } while( mbedtls_mpi_cmp_int( &l, 1 ) <= 0 ); /* Z = l * Z */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &pt->Z, &pt->Z, &l ) ); /* X = l^2 * X */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &ll, &l, &l ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &pt->X, &pt->X, &ll ) ); /* Y = l^3 * Y */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &ll, &ll, &l ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &pt->Y, &pt->Y, &ll ) ); cleanup: mbedtls_mpi_free( &l ); mbedtls_mpi_free( &ll ); return( ret ); #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) */ } /* * Check and define parameters used by the comb method (see below for details) */ #if MBEDTLS_ECP_WINDOW_SIZE < 2 || MBEDTLS_ECP_WINDOW_SIZE > 7 #error "MBEDTLS_ECP_WINDOW_SIZE out of bounds" #endif /* d = ceil( n / w ) */ #define COMB_MAX_D ( MBEDTLS_ECP_MAX_BITS + 1 ) / 2 /* number of precomputed points */ #define COMB_MAX_PRE ( 1 << ( MBEDTLS_ECP_WINDOW_SIZE - 1 ) ) /* * Compute the representation of m that will be used with our comb method. * * The basic comb method is described in GECC 3.44 for example. We use a * modified version that provides resistance to SPA by avoiding zero * digits in the representation as in [3]. We modify the method further by * requiring that all K_i be odd, which has the small cost that our * representation uses one more K_i, due to carries, but saves on the size of * the precomputed table. * * Summary of the comb method and its modifications: * * - The goal is to compute m*P for some w*d-bit integer m. * * - The basic comb method splits m into the w-bit integers * x[0] .. x[d-1] where x[i] consists of the bits in m whose * index has residue i modulo d, and computes m * P as * S[x[0]] + 2 * S[x[1]] + .. + 2^(d-1) S[x[d-1]], where * S[i_{w-1} .. i_0] := i_{w-1} 2^{(w-1)d} P + ... + i_1 2^d P + i_0 P. * * - If it happens that, say, x[i+1]=0 (=> S[x[i+1]]=0), one can replace the sum by * .. + 2^{i-1} S[x[i-1]] - 2^i S[x[i]] + 2^{i+1} S[x[i]] + 2^{i+2} S[x[i+2]] .., * thereby successively converting it into a form where all summands * are nonzero, at the cost of negative summands. This is the basic idea of [3]. * * - More generally, even if x[i+1] != 0, we can first transform the sum as * .. - 2^i S[x[i]] + 2^{i+1} ( S[x[i]] + S[x[i+1]] ) + 2^{i+2} S[x[i+2]] .., * and then replace S[x[i]] + S[x[i+1]] = S[x[i] ^ x[i+1]] + 2 S[x[i] & x[i+1]]. * Performing and iterating this procedure for those x[i] that are even * (keeping track of carry), we can transform the original sum into one of the form * S[x'[0]] +- 2 S[x'[1]] +- .. +- 2^{d-1} S[x'[d-1]] + 2^d S[x'[d]] * with all x'[i] odd. It is therefore only necessary to know S at odd indices, * which is why we are only computing half of it in the first place in * ecp_precompute_comb and accessing it with index abs(i) / 2 in ecp_select_comb. * * - For the sake of compactness, only the seven low-order bits of x[i] * are used to represent its absolute value (K_i in the paper), and the msb * of x[i] encodes the sign (s_i in the paper): it is set if and only if * if s_i == -1; * * Calling conventions: * - x is an array of size d + 1 * - w is the size, ie number of teeth, of the comb, and must be between * 2 and 7 (in practice, between 2 and MBEDTLS_ECP_WINDOW_SIZE) * - m is the MPI, expected to be odd and such that bitlength(m) <= w * d * (the result will be incorrect if these assumptions are not satisfied) */ static void ecp_comb_recode_core( unsigned char x[], size_t d, unsigned char w, const mbedtls_mpi *m ) { size_t i, j; unsigned char c, cc, adjust; mbedtls_platform_zeroize( x, d+1 ); /* First get the classical comb values (except for x_d = 0) */ for( i = 0; i < d; i++ ) for( j = 0; j < w; j++ ) x[i] |= mbedtls_mpi_get_bit( m, i + d * j ) << j; /* Now make sure x_1 .. x_d are odd */ c = 0; for( i = 1; i <= d; i++ ) { /* Add carry and update it */ cc = x[i] & c; x[i] = x[i] ^ c; c = cc; /* Adjust if needed, avoiding branches */ adjust = 1 - ( x[i] & 0x01 ); c |= x[i] & ( x[i-1] * adjust ); x[i] = x[i] ^ ( x[i-1] * adjust ); x[i-1] |= adjust << 7; } } /* * Precompute points for the adapted comb method * * Assumption: T must be able to hold 2^{w - 1} elements. * * Operation: If i = i_{w-1} ... i_1 is the binary representation of i, * sets T[i] = i_{w-1} 2^{(w-1)d} P + ... + i_1 2^d P + P. * * Cost: d(w-1) D + (2^{w-1} - 1) A + 1 N(w-1) + 1 N(2^{w-1} - 1) * * Note: Even comb values (those where P would be omitted from the * sum defining T[i] above) are not needed in our adaption * the comb method. See ecp_comb_recode_core(). * * This function currently works in four steps: * (1) [dbl] Computation of intermediate T[i] for 2-power values of i * (2) [norm_dbl] Normalization of coordinates of these T[i] * (3) [add] Computation of all T[i] * (4) [norm_add] Normalization of all T[i] * * Step 1 can be interrupted but not the others; together with the final * coordinate normalization they are the largest steps done at once, depending * on the window size. Here are operation counts for P-256: * * step (2) (3) (4) * w = 5 142 165 208 * w = 4 136 77 160 * w = 3 130 33 136 * w = 2 124 11 124 * * So if ECC operations are blocking for too long even with a low max_ops * value, it's useful to set MBEDTLS_ECP_WINDOW_SIZE to a lower value in order * to minimize maximum blocking time. */ static int ecp_precompute_comb( const mbedtls_ecp_group *grp, mbedtls_ecp_point T[], const mbedtls_ecp_point *P, unsigned char w, size_t d, mbedtls_ecp_restart_ctx *rs_ctx ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char i; size_t j = 0; const unsigned char T_size = 1U << ( w - 1 ); mbedtls_ecp_point *cur, *TT[COMB_MAX_PRE - 1]; #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->rsm ) { if( rs_ctx->rsm->state == ecp_rsm_pre_dbl ) goto dbl; if( rs_ctx->rsm->state == ecp_rsm_pre_norm_dbl ) goto norm_dbl; if( rs_ctx->rsm->state == ecp_rsm_pre_add ) goto add; if( rs_ctx->rsm->state == ecp_rsm_pre_norm_add ) goto norm_add; } #else (void) rs_ctx; #endif #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->rsm ) { rs_ctx->rsm->state = ecp_rsm_pre_dbl; /* initial state for the loop */ rs_ctx->rsm->i = 0; } dbl: #endif /* * Set T[0] = P and * T[2^{l-1}] = 2^{dl} P for l = 1 .. w-1 (this is not the final value) */ MBEDTLS_MPI_CHK( mbedtls_ecp_copy( &T[0], P ) ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->rsm && rs_ctx->rsm->i != 0 ) j = rs_ctx->rsm->i; else #endif j = 0; for( ; j < d * ( w - 1 ); j++ ) { MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_DBL ); i = 1U << ( j / d ); cur = T + i; if( !( j % d ) ) MBEDTLS_MPI_CHK( mbedtls_ecp_copy( cur, T + ( i >> 1 ) ) ); MBEDTLS_MPI_CHK( ecp_double_jac( grp, cur, cur ) ); } #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->rsm ) rs_ctx->rsm->state = ecp_rsm_pre_norm_dbl; norm_dbl: #endif /* * Normalize current elements in T. As T has holes, * use an auxiliary array of pointers to elements in T. */ j = 0; for( i = 1; i < T_size; i <<= 1 ) TT[j++] = T + i; MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_INV + 6 * j - 2 ); MBEDTLS_MPI_CHK( ecp_normalize_jac_many( grp, TT, j ) ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->rsm ) rs_ctx->rsm->state = ecp_rsm_pre_add; add: #endif /* * Compute the remaining ones using the minimal number of additions * Be careful to update T[2^l] only after using it! */ MBEDTLS_ECP_BUDGET( ( T_size - 1 ) * MBEDTLS_ECP_OPS_ADD ); for( i = 1; i < T_size; i <<= 1 ) { j = i; while( j-- ) { MBEDTLS_MPI_CHK( ecp_add_mixed( grp, &T[i + j], &T[j], &T[i] ) ); } } #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->rsm ) rs_ctx->rsm->state = ecp_rsm_pre_norm_add; norm_add: #endif /* * Normalize final elements in T. Even though there are no holes now, we * still need the auxiliary array for homogeneity with the previous * call. Also, skip T[0] which is already normalised, being a copy of P. */ for( j = 0; j + 1 < T_size; j++ ) TT[j] = T + j + 1; MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_INV + 6 * j - 2 ); MBEDTLS_MPI_CHK( ecp_normalize_jac_many( grp, TT, j ) ); cleanup: #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->rsm && ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) { if( rs_ctx->rsm->state == ecp_rsm_pre_dbl ) rs_ctx->rsm->i = j; } #endif return( ret ); } /* * Select precomputed point: R = sign(i) * T[ abs(i) / 2 ] * * See ecp_comb_recode_core() for background */ static int ecp_select_comb( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_ecp_point T[], unsigned char T_size, unsigned char i ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char ii, j; /* Ignore the "sign" bit and scale down */ ii = ( i & 0x7Fu ) >> 1; /* Read the whole table to thwart cache-based timing attacks */ for( j = 0; j < T_size; j++ ) { MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &R->X, &T[j].X, j == ii ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &R->Y, &T[j].Y, j == ii ) ); } /* Safely invert result if i is "negative" */ MBEDTLS_MPI_CHK( ecp_safe_invert_jac( grp, R, i >> 7 ) ); cleanup: return( ret ); } /* * Core multiplication algorithm for the (modified) comb method. * This part is actually common with the basic comb method (GECC 3.44) * * Cost: d A + d D + 1 R */ static int ecp_mul_comb_core( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_ecp_point T[], unsigned char T_size, const unsigned char x[], size_t d, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, mbedtls_ecp_restart_ctx *rs_ctx ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_ecp_point Txi; size_t i; mbedtls_ecp_point_init( &Txi ); #if !defined(MBEDTLS_ECP_RESTARTABLE) (void) rs_ctx; #endif #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->rsm && rs_ctx->rsm->state != ecp_rsm_comb_core ) { rs_ctx->rsm->i = 0; rs_ctx->rsm->state = ecp_rsm_comb_core; } /* new 'if' instead of nested for the sake of the 'else' branch */ if( rs_ctx && rs_ctx->rsm && rs_ctx->rsm->i != 0 ) { /* restore current index (R already pointing to rs_ctx->rsm->R) */ i = rs_ctx->rsm->i; } else #endif { /* Start with a non-zero point and randomize its coordinates */ i = d; MBEDTLS_MPI_CHK( ecp_select_comb( grp, R, T, T_size, x[i] ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &R->Z, 1 ) ); #if defined(MBEDTLS_ECP_NO_INTERNAL_RNG) if( f_rng != 0 ) #endif MBEDTLS_MPI_CHK( ecp_randomize_jac( grp, R, f_rng, p_rng ) ); } while( i != 0 ) { MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_DBL + MBEDTLS_ECP_OPS_ADD ); --i; MBEDTLS_MPI_CHK( ecp_double_jac( grp, R, R ) ); MBEDTLS_MPI_CHK( ecp_select_comb( grp, &Txi, T, T_size, x[i] ) ); MBEDTLS_MPI_CHK( ecp_add_mixed( grp, R, R, &Txi ) ); } cleanup: mbedtls_ecp_point_free( &Txi ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->rsm && ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) { rs_ctx->rsm->i = i; /* no need to save R, already pointing to rs_ctx->rsm->R */ } #endif return( ret ); } /* * Recode the scalar to get constant-time comb multiplication * * As the actual scalar recoding needs an odd scalar as a starting point, * this wrapper ensures that by replacing m by N - m if necessary, and * informs the caller that the result of multiplication will be negated. * * This works because we only support large prime order for Short Weierstrass * curves, so N is always odd hence either m or N - m is. * * See ecp_comb_recode_core() for background. */ static int ecp_comb_recode_scalar( const mbedtls_ecp_group *grp, const mbedtls_mpi *m, unsigned char k[COMB_MAX_D + 1], size_t d, unsigned char w, unsigned char *parity_trick ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_mpi M, mm; mbedtls_mpi_init( &M ); mbedtls_mpi_init( &mm ); /* N is always odd (see above), just make extra sure */ if( mbedtls_mpi_get_bit( &grp->N, 0 ) != 1 ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); /* do we need the parity trick? */ *parity_trick = ( mbedtls_mpi_get_bit( m, 0 ) == 0 ); /* execute parity fix in constant time */ MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &M, m ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &mm, &grp->N, m ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &M, &mm, *parity_trick ) ); /* actual scalar recoding */ ecp_comb_recode_core( k, d, w, &M ); cleanup: mbedtls_mpi_free( &mm ); mbedtls_mpi_free( &M ); return( ret ); } /* * Perform comb multiplication (for short Weierstrass curves) * once the auxiliary table has been pre-computed. * * Scalar recoding may use a parity trick that makes us compute -m * P, * if that is the case we'll need to recover m * P at the end. */ static int ecp_mul_comb_after_precomp( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *T, unsigned char T_size, unsigned char w, size_t d, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, mbedtls_ecp_restart_ctx *rs_ctx ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char parity_trick; unsigned char k[COMB_MAX_D + 1]; mbedtls_ecp_point *RR = R; #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->rsm ) { RR = &rs_ctx->rsm->R; if( rs_ctx->rsm->state == ecp_rsm_final_norm ) goto final_norm; } #endif MBEDTLS_MPI_CHK( ecp_comb_recode_scalar( grp, m, k, d, w, &parity_trick ) ); MBEDTLS_MPI_CHK( ecp_mul_comb_core( grp, RR, T, T_size, k, d, f_rng, p_rng, rs_ctx ) ); MBEDTLS_MPI_CHK( ecp_safe_invert_jac( grp, RR, parity_trick ) ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->rsm ) rs_ctx->rsm->state = ecp_rsm_final_norm; final_norm: MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_INV ); #endif /* * Knowledge of the jacobian coordinates may leak the last few bits of the * scalar [1], and since our MPI implementation isn't constant-flow, * inversion (used for coordinate normalization) may leak the full value * of its input via side-channels [2]. * * [1] https://eprint.iacr.org/2003/191 * [2] https://eprint.iacr.org/2020/055 * * Avoid the leak by randomizing coordinates before we normalize them. */ #if defined(MBEDTLS_ECP_NO_INTERNAL_RNG) if( f_rng != 0 ) #endif MBEDTLS_MPI_CHK( ecp_randomize_jac( grp, RR, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( ecp_normalize_jac( grp, RR ) ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->rsm ) MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, RR ) ); #endif cleanup: return( ret ); } /* * Pick window size based on curve size and whether we optimize for base point */ static unsigned char ecp_pick_window_size( const mbedtls_ecp_group *grp, unsigned char p_eq_g ) { unsigned char w; /* * Minimize the number of multiplications, that is minimize * 10 * d * w + 18 * 2^(w-1) + 11 * d + 7 * w, with d = ceil( nbits / w ) * (see costs of the various parts, with 1S = 1M) */ w = grp->nbits >= 384 ? 5 : 4; /* * If P == G, pre-compute a bit more, since this may be re-used later. * Just adding one avoids upping the cost of the first mul too much, * and the memory cost too. */ if( p_eq_g ) w++; /* * Make sure w is within bounds. * (The last test is useful only for very small curves in the test suite.) */ #if( MBEDTLS_ECP_WINDOW_SIZE < 6 ) if( w > MBEDTLS_ECP_WINDOW_SIZE ) w = MBEDTLS_ECP_WINDOW_SIZE; #endif if( w >= grp->nbits ) w = 2; return( w ); } /* * Multiplication using the comb method - for curves in short Weierstrass form * * This function is mainly responsible for administrative work: * - managing the restart context if enabled * - managing the table of precomputed points (passed between the below two * functions): allocation, computation, ownership tranfer, freeing. * * It delegates the actual arithmetic work to: * ecp_precompute_comb() and ecp_mul_comb_with_precomp() * * See comments on ecp_comb_recode_core() regarding the computation strategy. */ static int ecp_mul_comb( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, mbedtls_ecp_restart_ctx *rs_ctx ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char w, p_eq_g, i; size_t d; unsigned char T_size = 0, T_ok = 0; mbedtls_ecp_point *T = NULL; #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) ecp_drbg_context drbg_ctx; ecp_drbg_init( &drbg_ctx ); #endif ECP_RS_ENTER( rsm ); #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) if( f_rng == NULL ) { /* Adjust pointers */ f_rng = &ecp_drbg_random; #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->rsm ) p_rng = &rs_ctx->rsm->drbg_ctx; else #endif p_rng = &drbg_ctx; /* Initialize internal DRBG if necessary */ #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx == NULL || rs_ctx->rsm == NULL || rs_ctx->rsm->drbg_seeded == 0 ) #endif { const size_t m_len = ( grp->nbits + 7 ) / 8; MBEDTLS_MPI_CHK( ecp_drbg_seed( p_rng, m, m_len ) ); } #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->rsm ) rs_ctx->rsm->drbg_seeded = 1; #endif } #endif /* !MBEDTLS_ECP_NO_INTERNAL_RNG */ /* Is P the base point ? */ #if MBEDTLS_ECP_FIXED_POINT_OPTIM == 1 p_eq_g = ( mbedtls_mpi_cmp_mpi( &P->Y, &grp->G.Y ) == 0 && mbedtls_mpi_cmp_mpi( &P->X, &grp->G.X ) == 0 ); #else p_eq_g = 0; #endif /* Pick window size and deduce related sizes */ w = ecp_pick_window_size( grp, p_eq_g ); T_size = 1U << ( w - 1 ); d = ( grp->nbits + w - 1 ) / w; /* Pre-computed table: do we have it already for the base point? */ if( p_eq_g && grp->T ) { /* second pointer to the same table, will be deleted on exit */ T = grp->T; T_ok = 1; } else #if defined(MBEDTLS_ECP_RESTARTABLE) /* Pre-computed table: do we have one in progress? complete? */ if( rs_ctx && rs_ctx->rsm && rs_ctx->rsm->T ) { /* transfer ownership of T from rsm to local function */ T = rs_ctx->rsm->T; rs_ctx->rsm->T = NULL; rs_ctx->rsm->T_size = 0; /* This effectively jumps to the call to mul_comb_after_precomp() */ T_ok = rs_ctx->rsm->state >= ecp_rsm_comb_core; } else #endif /* Allocate table if we didn't have any */ { T = mbedtls_calloc( T_size, sizeof( mbedtls_ecp_point ) ); if( !T ) { ret = MBEDTLS_ERR_ECP_ALLOC_FAILED; goto cleanup; } for( i = 0; i < T_size; i++ ) mbedtls_ecp_point_init( &T[i] ); T_ok = 0; } /* Compute table (or finish computing it) if not done already */ if( !T_ok ) { MBEDTLS_MPI_CHK( ecp_precompute_comb( grp, T, P, w, d, rs_ctx ) ); if( p_eq_g ) { /* almost transfer ownership of T to the group, but keep a copy of * the pointer to use for calling the next function more easily */ grp->T = T; grp->T_size = T_size; } } /* Actual comb multiplication using precomputed points */ MBEDTLS_MPI_CHK( ecp_mul_comb_after_precomp( grp, R, m, T, T_size, w, d, f_rng, p_rng, rs_ctx ) ); cleanup: #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) ecp_drbg_free( &drbg_ctx ); #endif /* does T belong to the group? */ if( T == grp->T ) T = NULL; /* does T belong to the restart context? */ #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->rsm && ret == MBEDTLS_ERR_ECP_IN_PROGRESS && T ) { /* transfer ownership of T from local function to rsm */ rs_ctx->rsm->T_size = T_size; rs_ctx->rsm->T = T; T = NULL; } #endif /* did T belong to us? then let's destroy it! */ if( T ) { for( i = 0; i < T_size; i++ ) mbedtls_ecp_point_free( &T[i] ); mbedtls_free( T ); } /* don't free R while in progress in case R == P */ #if defined(MBEDTLS_ECP_RESTARTABLE) if( ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) #endif /* prevent caller from using invalid value */ if( ret != 0 ) mbedtls_ecp_point_free( R ); ECP_RS_LEAVE( rsm ); return( ret ); } #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) /* * For Montgomery curves, we do all the internal arithmetic in projective * coordinates. Import/export of points uses only the x coordinates, which is * internaly represented as X / Z. * * For scalar multiplication, we'll use a Montgomery ladder. */ /* * Normalize Montgomery x/z coordinates: X = X/Z, Z = 1 * Cost: 1M + 1I */ static int ecp_normalize_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P ) { #if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT) if( mbedtls_internal_ecp_grp_capable( grp ) ) return( mbedtls_internal_ecp_normalize_mxz( grp, P ) ); #endif /* MBEDTLS_ECP_NORMALIZE_MXZ_ALT */ #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT) return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ); #else int ret = MBEDTLS_ERR_THIS_CORRUPTION; MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &P->Z, &P->Z, &grp->P ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &P->X, &P->X, &P->Z ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &P->Z, 1 ) ); cleanup: return( ret ); #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT) */ } /* * Randomize projective x/z coordinates: * (X, Z) -> (l X, l Z) for random l * This is sort of the reverse operation of ecp_normalize_mxz(). * * This countermeasure was first suggested in [2]. * Cost: 2M */ static int ecp_randomize_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { #if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT) if( mbedtls_internal_ecp_grp_capable( grp ) ) return( mbedtls_internal_ecp_randomize_mxz( grp, P, f_rng, p_rng ); #endif /* MBEDTLS_ECP_RANDOMIZE_MXZ_ALT */ #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT) return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ); #else int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_mpi l; int count = 0; size_t p_size = ( grp->pbits + 7 ) / 8; mbedtls_mpi_init( &l ); /* Generate l such that 1 < l < p */ do { MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &l, p_size, f_rng, p_rng ) ); while( mbedtls_mpi_cmp_mpi( &l, &grp->P ) >= 0 ) mbedtls_mpi_shift_r( &l, 1 ); if( count++ > 10 ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } } while( mbedtls_mpi_cmp_int( &l, 1 ) <= 0 ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &P->X, &P->X, &l ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &P->Z, &P->Z, &l ) ); cleanup: mbedtls_mpi_free( &l ); return( ret ); #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT) */ } /* * Double-and-add: R = 2P, S = P + Q, with d = X(P - Q), * for Montgomery curves in x/z coordinates. * * http://www.hyperelliptic.org/EFD/g1p/auto-code/montgom/xz/ladder/mladd-1987-m.op3 * with * d = X1 * P = (X2, Z2) * Q = (X3, Z3) * R = (X4, Z4) * S = (X5, Z5) * and eliminating temporary variables tO, ..., t4. * * Cost: 5M + 4S */ static int ecp_double_add_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R, mbedtls_ecp_point *S, const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q, const mbedtls_mpi *d ) { #if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) if( mbedtls_internal_ecp_grp_capable( grp ) ) return( mbedtls_internal_ecp_double_add_mxz( grp, R, S, P, Q, d ) ); #endif /* MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT */ #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ); #else int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_mpi A, AA, B, BB, E, C, D, DA, CB; mbedtls_mpi_init( &A ); mbedtls_mpi_init( &AA ); mbedtls_mpi_init( &B ); mbedtls_mpi_init( &BB ); mbedtls_mpi_init( &E ); mbedtls_mpi_init( &C ); mbedtls_mpi_init( &D ); mbedtls_mpi_init( &DA ); mbedtls_mpi_init( &CB ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &A, &P->X, &P->Z ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &AA, &A, &A ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &B, &P->X, &P->Z ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &BB, &B, &B ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &E, &AA, &BB ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &C, &Q->X, &Q->Z ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &D, &Q->X, &Q->Z ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &DA, &D, &A ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &CB, &C, &B ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &S->X, &DA, &CB ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S->X, &S->X, &S->X ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &S->Z, &DA, &CB ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S->Z, &S->Z, &S->Z ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S->Z, d, &S->Z ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &R->X, &AA, &BB ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &R->Z, &grp->A, &E ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &R->Z, &BB, &R->Z ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &R->Z, &E, &R->Z ) ); cleanup: mbedtls_mpi_free( &A ); mbedtls_mpi_free( &AA ); mbedtls_mpi_free( &B ); mbedtls_mpi_free( &BB ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &C ); mbedtls_mpi_free( &D ); mbedtls_mpi_free( &DA ); mbedtls_mpi_free( &CB ); return( ret ); #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) */ } /* * Multiplication with Montgomery ladder in x/z coordinates, * for curves in Montgomery form */ static int ecp_mul_mxz( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t i; unsigned char b; mbedtls_ecp_point RP; mbedtls_mpi PX; #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) ecp_drbg_context drbg_ctx; ecp_drbg_init( &drbg_ctx ); #endif mbedtls_ecp_point_init( &RP ); mbedtls_mpi_init( &PX ); #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) if( f_rng == NULL ) { const size_t m_len = ( grp->nbits + 7 ) / 8; MBEDTLS_MPI_CHK( ecp_drbg_seed( &drbg_ctx, m, m_len ) ); f_rng = &ecp_drbg_random; p_rng = &drbg_ctx; } #endif /* !MBEDTLS_ECP_NO_INTERNAL_RNG */ /* Save PX and read from P before writing to R, in case P == R */ MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &PX, &P->X ) ); MBEDTLS_MPI_CHK( mbedtls_ecp_copy( &RP, P ) ); /* Set R to zero in modified x/z coordinates */ MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &R->X, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &R->Z, 0 ) ); mbedtls_mpi_free( &R->Y ); /* RP.X might be sligtly larger than P, so reduce it */ MOD_ADD( RP.X ); /* Randomize coordinates of the starting point */ #if defined(MBEDTLS_ECP_NO_INTERNAL_RNG) if( f_rng ) #endif MBEDTLS_MPI_CHK( ecp_randomize_mxz( grp, &RP, f_rng, p_rng ) ); /* Loop invariant: R = result so far, RP = R + P */ i = mbedtls_mpi_bitlen( m ); /* one past the (zero-based) most significant bit */ while( i-- > 0 ) { b = mbedtls_mpi_get_bit( m, i ); /* * if (b) R = 2R + P else R = 2R, * which is: * if (b) double_add( RP, R, RP, R ) * else double_add( R, RP, R, RP ) * but using safe conditional swaps to avoid leaks */ MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->X, &RP.X, b ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->Z, &RP.Z, b ) ); MBEDTLS_MPI_CHK( ecp_double_add_mxz( grp, R, &RP, R, &RP, &PX ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->X, &RP.X, b ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->Z, &RP.Z, b ) ); } /* * Knowledge of the projective coordinates may leak the last few bits of the * scalar [1], and since our MPI implementation isn't constant-flow, * inversion (used for coordinate normalization) may leak the full value * of its input via side-channels [2]. * * [1] https://eprint.iacr.org/2003/191 * [2] https://eprint.iacr.org/2020/055 * * Avoid the leak by randomizing coordinates before we normalize them. */ #if defined(MBEDTLS_ECP_NO_INTERNAL_RNG) if( f_rng ) #endif MBEDTLS_MPI_CHK( ecp_randomize_mxz( grp, R, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( ecp_normalize_mxz( grp, R ) ); cleanup: #if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) ecp_drbg_free( &drbg_ctx ); #endif mbedtls_ecp_point_free( &RP ); mbedtls_mpi_free( &PX ); return( ret ); } #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */ /** * \brief This function performs multiplication of a point by * an integer: \p R = \p m * \p P in a restartable way. * * \see mbedtls_ecp_mul() * * \note This function does the same as \c mbedtls_ecp_mul(), but * it can return early and restart according to the limit set * with \c mbedtls_ecp_set_max_ops() to reduce blocking. * * \param grp The ECP group to use. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param R The point in which to store the result of the calculation. * This must be initialized. * \param m The integer by which to multiply. This must be initialized. * \param P The point to multiply. This must be initialized. * \param f_rng The RNG function. This may be \c NULL if randomization * of intermediate results isn't desired (discouraged). * \param p_rng The RNG context to be passed to \p p_rng. * \param rs_ctx The restart context (NULL disables restart). * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m is not a valid private * key, or \p P is not a valid public key. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of * operations was reached: see \c mbedtls_ecp_set_max_ops(). * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_mul_restartable( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, mbedtls_ecp_restart_ctx *rs_ctx ) { int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA; #if defined(MBEDTLS_ECP_INTERNAL_ALT) char is_grp_capable = 0; #endif ECP_VALIDATE_RET( grp ); ECP_VALIDATE_RET( R ); ECP_VALIDATE_RET( m ); ECP_VALIDATE_RET( P ); #if defined(MBEDTLS_ECP_RESTARTABLE) /* reset ops count for this call if top-level */ if( rs_ctx && rs_ctx->depth++ == 0 ) rs_ctx->ops_done = 0; #else (void) rs_ctx; #endif #if defined(MBEDTLS_ECP_INTERNAL_ALT) if( ( is_grp_capable = mbedtls_internal_ecp_grp_capable( grp ) ) ) MBEDTLS_MPI_CHK( mbedtls_internal_ecp_init( grp ) ); #endif /* MBEDTLS_ECP_INTERNAL_ALT */ #if defined(MBEDTLS_ECP_RESTARTABLE) /* skip argument check when restarting */ if( !rs_ctx || !rs_ctx->rsm ) #endif { /* check_privkey is free */ MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_CHK ); /* Common sanity checks */ MBEDTLS_MPI_CHK( mbedtls_ecp_check_privkey( grp, m ) ); MBEDTLS_MPI_CHK( mbedtls_ecp_check_pubkey( grp, P ) ); } ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA; #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY ) MBEDTLS_MPI_CHK( ecp_mul_mxz( grp, R, m, P, f_rng, p_rng ) ); #endif #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) MBEDTLS_MPI_CHK( ecp_mul_comb( grp, R, m, P, f_rng, p_rng, rs_ctx ) ); #endif cleanup: #if defined(MBEDTLS_ECP_INTERNAL_ALT) if( is_grp_capable ) mbedtls_internal_ecp_free( grp ); #endif /* MBEDTLS_ECP_INTERNAL_ALT */ #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx ) rs_ctx->depth--; #endif return( ret ); } /** * \brief This function performs a scalar multiplication of a point * by an integer: \p R = \p m * \p P. * * It is not thread-safe to use same group in multiple threads. * * \note To prevent timing attacks, this function * executes the exact same sequence of base-field * operations for any valid \p m. It avoids any if-branch or * array index depending on the value of \p m. * * \note If \p f_rng is not NULL, it is used to randomize * intermediate results to prevent potential timing attacks * targeting these results. We recommend always providing * a non-NULL \p f_rng. The overhead is negligible. * Note: unless #MBEDTLS_ECP_NO_INTERNAL_RNG is defined, when * \p f_rng is NULL, an internal RNG (seeded from the value * of \p m) will be used instead. * * \param grp The ECP group to use. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param R The point in which to store the result of the calculation. * This must be initialized. * \param m The integer by which to multiply. This must be initialized. * \param P The point to multiply. This must be initialized. * \param f_rng The RNG function. This may be \c NULL if randomization * of intermediate results isn't desired (discouraged). * \param p_rng The RNG context to be passed to \p p_rng. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m is not a valid private * key, or \p P is not a valid public key. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_mul( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { ECP_VALIDATE_RET( grp ); ECP_VALIDATE_RET( R ); ECP_VALIDATE_RET( m ); ECP_VALIDATE_RET( P ); return( mbedtls_ecp_mul_restartable( grp, R, m, P, f_rng, p_rng, NULL ) ); } #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) /* * Check that an affine point is valid as a public key, * short weierstrass curves (SEC1 3.2.3.1) */ static int ecp_check_pubkey_sw( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_mpi YY, RHS; /* pt coordinates must be normalized for our checks */ if( mbedtls_mpi_cmp_int( &pt->X, 0 ) < 0 || mbedtls_mpi_cmp_int( &pt->Y, 0 ) < 0 || mbedtls_mpi_cmp_mpi( &pt->X, &grp->P ) >= 0 || mbedtls_mpi_cmp_mpi( &pt->Y, &grp->P ) >= 0 ) return( MBEDTLS_ERR_ECP_INVALID_KEY ); mbedtls_mpi_init( &YY ); mbedtls_mpi_init( &RHS ); /* * YY = Y^2 * RHS = X (X^2 + A) + B = X^3 + A X + B */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &YY, &pt->Y, &pt->Y ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &RHS, &pt->X, &pt->X ) ); /* Special case for A = -3 */ if( !grp->A.p ) { MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &RHS, &RHS, 3 ) ); MOD_SUB( RHS ); } else { MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &RHS, &RHS, &grp->A ) ); } MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &RHS, &RHS, &pt->X ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &RHS, &RHS, &grp->B ) ); if( mbedtls_mpi_cmp_mpi( &YY, &RHS ) != 0 ) ret = MBEDTLS_ERR_ECP_INVALID_KEY; cleanup: mbedtls_mpi_free( &YY ); mbedtls_mpi_free( &RHS ); return( ret ); } #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) /* * R = m * P with shortcuts for m == 1 and m == -1 * NOT constant-time - ONLY for short Weierstrass! */ static int mbedtls_ecp_mul_shortcuts( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, mbedtls_ecp_restart_ctx *rs_ctx ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( mbedtls_mpi_is_one( m ) ) { MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, P ) ); } else if( mbedtls_mpi_cmp_int( m, -1 ) == 0 ) { MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, P ) ); if( !mbedtls_mpi_is_zero( &R->Y ) ) MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &R->Y, &grp->P, &R->Y ) ); } else { MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, R, m, P, NULL, NULL, rs_ctx ) ); } cleanup: return( ret ); } /** * \brief This function performs multiplication and addition of two * points by integers: \p R = \p m * \p P + \p n * \p Q in a * restartable way. * * \see \c mbedtls_ecp_muladd() * * \note This function works the same as \c mbedtls_ecp_muladd(), * but it can return early and restart according to the limit * set with \c mbedtls_ecp_set_max_ops() to reduce blocking. * * \note This function is only defined for short Weierstrass curves. * It may not be included in builds without any short * Weierstrass curve. * * \param grp The ECP group to use. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param R The point in which to store the result of the calculation. * This must be initialized. * \param m The integer by which to multiply \p P. * This must be initialized. * \param P The point to multiply by \p m. This must be initialized. * \param n The integer by which to multiply \p Q. * This must be initialized. * \param Q The point to be multiplied by \p n. * This must be initialized. * \param rs_ctx The restart context (NULL disables restart). * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m or \p n are not * valid private keys, or \p P or \p Q are not valid public * keys. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if \p grp does not * designate a short Weierstrass curve. * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of * operations was reached: see \c mbedtls_ecp_set_max_ops(). * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_muladd_restartable( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, const mbedtls_mpi *n, const mbedtls_ecp_point *Q, mbedtls_ecp_restart_ctx *rs_ctx ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_ecp_point mP; mbedtls_ecp_point *pmP = &mP; mbedtls_ecp_point *pR = R; #if defined(MBEDTLS_ECP_INTERNAL_ALT) char is_grp_capable = 0; #endif ECP_VALIDATE_RET( grp ); ECP_VALIDATE_RET( R ); ECP_VALIDATE_RET( m ); ECP_VALIDATE_RET( P ); ECP_VALIDATE_RET( n ); ECP_VALIDATE_RET( Q ); if( mbedtls_ecp_get_type( grp ) != MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ); mbedtls_ecp_point_init( &mP ); ECP_RS_ENTER( ma ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->ma ) { /* redirect intermediate results to restart context */ pmP = &rs_ctx->ma->mP; pR = &rs_ctx->ma->R; /* jump to next operation */ if( rs_ctx->ma->state == ecp_rsma_mul2 ) goto mul2; if( rs_ctx->ma->state == ecp_rsma_add ) goto add; if( rs_ctx->ma->state == ecp_rsma_norm ) goto norm; } #endif /* MBEDTLS_ECP_RESTARTABLE */ MBEDTLS_MPI_CHK( mbedtls_ecp_mul_shortcuts( grp, pmP, m, P, rs_ctx ) ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->ma ) rs_ctx->ma->state = ecp_rsma_mul2; mul2: #endif MBEDTLS_MPI_CHK( mbedtls_ecp_mul_shortcuts( grp, pR, n, Q, rs_ctx ) ); #if defined(MBEDTLS_ECP_INTERNAL_ALT) if( ( is_grp_capable = mbedtls_internal_ecp_grp_capable( grp ) ) ) MBEDTLS_MPI_CHK( mbedtls_internal_ecp_init( grp ) ); #endif /* MBEDTLS_ECP_INTERNAL_ALT */ #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->ma ) rs_ctx->ma->state = ecp_rsma_add; add: #endif MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_ADD ); MBEDTLS_MPI_CHK( ecp_add_mixed( grp, pR, pmP, pR ) ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->ma ) rs_ctx->ma->state = ecp_rsma_norm; norm: #endif MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_INV ); MBEDTLS_MPI_CHK( ecp_normalize_jac( grp, pR ) ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx && rs_ctx->ma ) MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, pR ) ); #endif cleanup: #if defined(MBEDTLS_ECP_INTERNAL_ALT) if( is_grp_capable ) mbedtls_internal_ecp_free( grp ); #endif /* MBEDTLS_ECP_INTERNAL_ALT */ mbedtls_ecp_point_free( &mP ); ECP_RS_LEAVE( ma ); return( ret ); } /** * \brief This function performs multiplication and addition of two * points by integers: \p R = \p m * \p P + \p n * \p Q * * It is not thread-safe to use same group in multiple threads. * * \note In contrast to mbedtls_ecp_mul(), this function does not * guarantee a constant execution flow and timing. * * \note This function is only defined for short Weierstrass curves. * It may not be included in builds without any short * Weierstrass curve. * * \param grp The ECP group to use. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param R The point in which to store the result of the calculation. * This must be initialized. * \param m The integer by which to multiply \p P. * This must be initialized. * \param P The point to multiply by \p m. This must be initialized. * \param n The integer by which to multiply \p Q. * This must be initialized. * \param Q The point to be multiplied by \p n. * This must be initialized. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m or \p n are not * valid private keys, or \p P or \p Q are not valid public * keys. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if \p grp does not * designate a short Weierstrass curve. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, const mbedtls_mpi *n, const mbedtls_ecp_point *Q ) { ECP_VALIDATE_RET( grp ); ECP_VALIDATE_RET( R ); ECP_VALIDATE_RET( m ); ECP_VALIDATE_RET( P ); ECP_VALIDATE_RET( n ); ECP_VALIDATE_RET( Q ); return( mbedtls_ecp_muladd_restartable( grp, R, m, P, n, Q, NULL ) ); } #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) /* * Check validity of a public key for Montgomery curves with x-only schemes */ static int ecp_check_pubkey_mx( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt ) { /* [Curve25519 p. 5] Just check X is the correct number of bytes */ /* Allow any public value, if it's too big then we'll just reduce it mod p * (RFC 7748 sec. 5 para. 3). */ if( mbedtls_mpi_size( &pt->X ) > ( grp->nbits + 7 ) / 8 ) return( MBEDTLS_ERR_ECP_INVALID_KEY ); return( 0 ); } #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */ /** * \brief This function checks that a point is a valid public key * on this curve. * * It only checks that the point is non-zero, has * valid coordinates and lies on the curve. It does not verify * that it is indeed a multiple of \p G. This additional * check is computationally more expensive, is not required * by standards, and should not be necessary if the group * used has a small cofactor. In particular, it is useless for * the NIST groups which all have a cofactor of 1. * * \note This function uses bare components rather than an * ::mbedtls_ecp_keypair structure, to ease use with other * structures, such as ::mbedtls_ecdh_context or * ::mbedtls_ecdsa_context. * * \param grp The ECP group the point should belong to. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param pt The point to check. This must be initialized. * * \return \c 0 if the point is a valid public key. * \return #MBEDTLS_ERR_ECP_INVALID_KEY if the point is not * a valid public key for the given curve. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_check_pubkey( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt ) { ECP_VALIDATE_RET( grp ); ECP_VALIDATE_RET( pt ); /* Must use affine coordinates */ if( !mbedtls_mpi_is_one( &pt->Z ) ) return( MBEDTLS_ERR_ECP_INVALID_KEY ); #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY ) return( ecp_check_pubkey_mx( grp, pt ) ); #endif #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) return( ecp_check_pubkey_sw( grp, pt ) ); #endif return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); } /** * \brief This function checks that an \p mbedtls_mpi is a * valid private key for this curve. * * \note This function uses bare components rather than an * ::mbedtls_ecp_keypair structure to ease use with other * structures, such as ::mbedtls_ecdh_context or * ::mbedtls_ecdsa_context. * * \param grp The ECP group the private key should belong to. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param d The integer to check. This must be initialized. * * \return \c 0 if the point is a valid private key. * \return #MBEDTLS_ERR_ECP_INVALID_KEY if the point is not a valid * private key for the given curve. * \return Another negative error code on other kinds of failure. */ dontinline int mbedtls_ecp_check_privkey( const mbedtls_ecp_group *grp, const mbedtls_mpi *d ) { ECP_VALIDATE_RET( grp ); ECP_VALIDATE_RET( d ); #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY ) { /* see RFC 7748 sec. 5 para. 5 */ if( mbedtls_mpi_get_bit( d, 0 ) != 0 || mbedtls_mpi_get_bit( d, 1 ) != 0 || mbedtls_mpi_bitlen( d ) - 1 != grp->nbits ) /* mbedtls_mpi_bitlen is one-based! */ return( MBEDTLS_ERR_ECP_INVALID_KEY ); /* see [Curve25519] page 5 */ if( grp->nbits == 254 && mbedtls_mpi_get_bit( d, 2 ) != 0 ) return( MBEDTLS_ERR_ECP_INVALID_KEY ); return( 0 ); } #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */ #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) { /* see SEC1 3.2 */ if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 ) return( MBEDTLS_ERR_ECP_INVALID_KEY ); else return( 0 ); } #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); } /** * \brief This function generates a private key. * * \param grp The ECP group to generate a private key for. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param d The destination MPI (secret part). This must be initialized. * \param f_rng The RNG function. This must not be \c NULL. * \param p_rng The RNG parameter to be passed to \p f_rng. This may be * \c NULL if \p f_rng doesn't need a context argument. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code * on failure. */ int mbedtls_ecp_gen_privkey( const mbedtls_ecp_group *grp, mbedtls_mpi *d, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA; size_t n_size; ECP_VALIDATE_RET( grp ); ECP_VALIDATE_RET( d ); ECP_VALIDATE_RET( f_rng ); n_size = ( grp->nbits + 7 ) / 8; #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY ) { /* [M225] page 5 */ size_t b; do { MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) ); } while( mbedtls_mpi_bitlen( d ) == 0); /* Make sure the most significant bit is nbits */ b = mbedtls_mpi_bitlen( d ) - 1; /* mbedtls_mpi_bitlen is one-based */ if( b > grp->nbits ) MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, b - grp->nbits ) ); else MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, grp->nbits, 1 ) ); /* Make sure the last two bits are unset for Curve448, three bits for Curve25519 */ MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 0, 0 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 1, 0 ) ); if( grp->nbits == 254 ) { MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 2, 0 ) ); } } #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */ #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) { /* SEC1 3.2.1: Generate d such that 1 <= n < N */ int count = 0; unsigned cmp = 0; /* * Match the procedure given in RFC 6979 (deterministic ECDSA): * - use the same byte ordering; * - keep the leftmost nbits bits of the generated octet string; * - try until result is in the desired range. * This also avoids any biais, which is especially important for ECDSA. */ do { MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_size - grp->nbits ) ); /* * Each try has at worst a probability 1/2 of failing (the msb has * a probability 1/2 of being 0, and then the result will be < N), * so after 30 tries failure probability is a most 2**(-30). * * For most curves, 1 try is enough with overwhelming probability, * since N starts with a lot of 1s in binary, but some curves * such as secp224k1 are actually very close to the worst case. */ if( ++count > 30 ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } ret = mbedtls_mpi_lt_mpi_ct( d, &grp->N, &cmp ); if( ret != 0 ) { goto cleanup; } } while( mbedtls_mpi_cmp_int( d, 1 ) < 0 || cmp != 1 ); } #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ cleanup: return( ret ); } /** * \brief This function generates a keypair with a configurable base * point. * * \note This function uses bare components rather than an * ::mbedtls_ecp_keypair structure to ease use with other * structures, such as ::mbedtls_ecdh_context or * ::mbedtls_ecdsa_context. * * \param grp The ECP group to generate a key pair for. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param G The base point to use. This must be initialized * and belong to \p grp. It replaces the default base * point \c grp->G used by mbedtls_ecp_gen_keypair(). * \param d The destination MPI (secret part). * This must be initialized. * \param Q The destination point (public part). * This must be initialized. * \param f_rng The RNG function. This must not be \c NULL. * \param p_rng The RNG context to be passed to \p f_rng. This may * be \c NULL if \p f_rng doesn't need a context argument. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code * on failure. */ int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp, const mbedtls_ecp_point *G, mbedtls_mpi *d, mbedtls_ecp_point *Q, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; ECP_VALIDATE_RET( grp ); ECP_VALIDATE_RET( d ); ECP_VALIDATE_RET( G ); ECP_VALIDATE_RET( Q ); ECP_VALIDATE_RET( f_rng ); MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, d, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, Q, d, G, f_rng, p_rng ) ); cleanup: return( ret ); } /** * \brief This function generates an ECP keypair. * * \note This function uses bare components rather than an * ::mbedtls_ecp_keypair structure to ease use with other * structures, such as ::mbedtls_ecdh_context or * ::mbedtls_ecdsa_context. * * \param grp The ECP group to generate a key pair for. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param d The destination MPI (secret part). * This must be initialized. * \param Q The destination point (public part). * This must be initialized. * \param f_rng The RNG function. This must not be \c NULL. * \param p_rng The RNG context to be passed to \p f_rng. This may * be \c NULL if \p f_rng doesn't need a context argument. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code * on failure. */ int mbedtls_ecp_gen_keypair( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int rc; ECP_VALIDATE_RET( grp ); ECP_VALIDATE_RET( d ); ECP_VALIDATE_RET( Q ); ECP_VALIDATE_RET( f_rng ); rc = mbedtls_ecp_gen_keypair_base( grp, &grp->G, d, Q, f_rng, p_rng ); STRACE("%s() → %d", "mbedtls_ecp_gen_keypair", rc); return( rc ); } /** * \brief This function generates an ECP key. * * \param grp_id The ECP group identifier. * \param key The destination key. This must be initialized. * \param f_rng The RNG function to use. This must not be \c NULL. * \param p_rng The RNG context to be passed to \p f_rng. This may * be \c NULL if \p f_rng doesn't need a context argument. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code * on failure. */ int mbedtls_ecp_gen_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; ECP_VALIDATE_RET( key ); ECP_VALIDATE_RET( f_rng ); if( ( ret = mbedtls_ecp_group_load( &key->grp, grp_id ) ) != 0 ) return( ret ); return( mbedtls_ecp_gen_keypair( &key->grp, &key->d, &key->Q, f_rng, p_rng ) ); } #define ECP_CURVE25519_KEY_SIZE 32 /** * \brief This function reads an elliptic curve private key. * * \param grp_id The ECP group identifier. * \param key The destination key. * \param buf The the buffer containing the binary representation of the * key. (Big endian integer for Weierstrass curves, byte * string for Montgomery curves.) * \param buflen The length of the buffer in bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_INVALID_KEY error if the key is * invalid. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed. * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the operation for * the group is not implemented. * \return Another negative error code on different kinds of failure. */ int mbedtls_ecp_read_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key, const unsigned char *buf, size_t buflen ) { int ret = 0; ECP_VALIDATE_RET( key ); ECP_VALIDATE_RET( buf ); if( ( ret = mbedtls_ecp_group_load( &key->grp, grp_id ) ) != 0 ) return( ret ); ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE; #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) if( mbedtls_ecp_get_type( &key->grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY ) { /* * If it is Curve25519 curve then mask the key as mandated by RFC7748 */ if( grp_id == MBEDTLS_ECP_DP_CURVE25519 ) { if( buflen != ECP_CURVE25519_KEY_SIZE ) return MBEDTLS_ERR_ECP_INVALID_KEY; MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary_le( &key->d, buf, buflen ) ); /* Set the three least significant bits to 0 */ MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &key->d, 0, 0 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &key->d, 1, 0 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &key->d, 2, 0 ) ); /* Set the most significant bit to 0 */ MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &key->d, ECP_CURVE25519_KEY_SIZE * 8 - 1, 0 ) ); /* Set the second most significant bit to 1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &key->d, ECP_CURVE25519_KEY_SIZE * 8 - 2, 1 ) ); } else ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE; } #endif #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) if( mbedtls_ecp_get_type( &key->grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) { MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &key->d, buf, buflen ) ); MBEDTLS_MPI_CHK( mbedtls_ecp_check_privkey( &key->grp, &key->d ) ); } #endif cleanup: if( ret != 0 ) mbedtls_mpi_free( &key->d ); return( ret ); } /** * \brief This function exports an elliptic curve private key. * * \param key The private key. * \param buf The output buffer for containing the binary representation * of the key. (Big endian integer for Weierstrass curves, byte * string for Montgomery curves.) * \param buflen The total length of the buffer in bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL if the \p key representation is larger than the available space in \p buf. * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the operation for * the group is not implemented. * \return Another negative error code on different kinds of failure. */ int mbedtls_ecp_write_key( mbedtls_ecp_keypair *key, unsigned char *buf, size_t buflen ) { int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE; ECP_VALIDATE_RET( key ); ECP_VALIDATE_RET( buf ); #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) if( mbedtls_ecp_get_type( &key->grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY ) { if( key->grp.id == MBEDTLS_ECP_DP_CURVE25519 ) { if( buflen < ECP_CURVE25519_KEY_SIZE ) return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL; MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary_le( &key->d, buf, buflen ) ); } else ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE; } #endif #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) if( mbedtls_ecp_get_type( &key->grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) { MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &key->d, buf, buflen ) ); } #endif cleanup: return( ret ); } /** * \brief This function checks that the keypair objects * \p pub and \p prv have the same group and the * same public point, and that the private key in * \p prv is consistent with the public key. * * \param pub The keypair structure holding the public key. This * must be initialized. If it contains a private key, that * part is ignored. * \param prv The keypair structure holding the full keypair. * This must be initialized. * * \return \c 0 on success, meaning that the keys are valid and match. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the keys are invalid or do not match. * \return An \c MBEDTLS_ERR_ECP_XXX or an \c MBEDTLS_ERR_MPI_XXX * error code on calculation failure. */ int mbedtls_ecp_check_pub_priv( const mbedtls_ecp_keypair *pub, const mbedtls_ecp_keypair *prv ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_ecp_point Q; mbedtls_ecp_group grp; ECP_VALIDATE_RET( pub ); ECP_VALIDATE_RET( prv ); if( pub->grp.id == MBEDTLS_ECP_DP_NONE || pub->grp.id != prv->grp.id || mbedtls_mpi_cmp_mpi( &pub->Q.X, &prv->Q.X ) || mbedtls_mpi_cmp_mpi( &pub->Q.Y, &prv->Q.Y ) || mbedtls_mpi_cmp_mpi( &pub->Q.Z, &prv->Q.Z ) ) { return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); } mbedtls_ecp_point_init( &Q ); mbedtls_ecp_group_init( &grp ); /* mbedtls_ecp_mul() needs a non-const group... */ mbedtls_ecp_group_copy( &grp, &prv->grp ); /* Also checks d is valid */ MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &Q, &prv->d, &prv->grp.G, NULL, NULL ) ); if( mbedtls_mpi_cmp_mpi( &Q.X, &prv->Q.X ) || mbedtls_mpi_cmp_mpi( &Q.Y, &prv->Q.Y ) || mbedtls_mpi_cmp_mpi( &Q.Z, &prv->Q.Z ) ) { ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA; goto cleanup; } cleanup: mbedtls_ecp_point_free( &Q ); mbedtls_ecp_group_free( &grp ); return( ret ); } #if defined(MBEDTLS_SELF_TEST) /* Adjust the exponent to be a valid private point for the specified curve. * This is sometimes necessary because we use a single set of exponents * for all curves but the validity of values depends on the curve. */ static int self_test_adjust_exponent( const mbedtls_ecp_group *grp, mbedtls_mpi *m ) { int ret = 0; switch( grp->id ) { /* If Curve25519 is available, then that's what we use for the * Montgomery test, so we don't need the adjustment code. */ #if ! defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) #if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) case MBEDTLS_ECP_DP_CURVE448: /* Move highest bit from 254 to N-1. Setting bit N-1 is * necessary to enforce the highest-bit-set constraint. */ MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( m, 254, 0 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( m, grp->nbits, 1 ) ); /* Copy second-highest bit from 253 to N-2. This is not * necessary but improves the test variety a bit. */ MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( m, grp->nbits - 1, mbedtls_mpi_get_bit( m, 253 ) ) ); break; #endif #endif /* ! defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) */ default: /* Non-Montgomery curves and Curve25519 need no adjustment. */ (void) grp; (void) m; goto cleanup; } cleanup: return( ret ); } /* Calculate R = m.P for each m in exponents. Check that the number of * basic operations doesn't depend on the value of m. */ static int self_test_point( int verbose, mbedtls_ecp_group *grp, mbedtls_ecp_point *R, mbedtls_mpi *m, const mbedtls_ecp_point *P, const char *const *exponents, size_t n_exponents ) { int ret = 0; size_t i = 0; unsigned long add_c_prev, dbl_c_prev, mul_c_prev; add_count = 0; dbl_count = 0; mul_count = 0; MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( m, 16, exponents[0] ) ); MBEDTLS_MPI_CHK( self_test_adjust_exponent( grp, m ) ); MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, R, m, P, NULL, NULL ) ); for( i = 1; i < n_exponents; i++ ) { add_c_prev = add_count; dbl_c_prev = dbl_count; mul_c_prev = mul_count; add_count = 0; dbl_count = 0; mul_count = 0; MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( m, 16, exponents[i] ) ); MBEDTLS_MPI_CHK( self_test_adjust_exponent( grp, m ) ); MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, R, m, P, NULL, NULL ) ); if( add_count != add_c_prev || dbl_count != dbl_c_prev || mul_count != mul_c_prev ) { ret = 1; break; } } cleanup: if( verbose != 0 ) { if( ret != 0 ) mbedtls_printf( "failed (%u)\n", (unsigned int) i ); else mbedtls_printf( "passed\n" ); } return( ret ); } /** * \brief The ECP checkup routine. * * \return \c 0 on success. * \return \c 1 on failure. */ int mbedtls_ecp_self_test( int verbose ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_ecp_group grp; mbedtls_ecp_point R, P; mbedtls_mpi m; #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) /* Exponents especially adapted for secp192k1, which has the lowest * order n of all supported curves (secp192r1 is in a slightly larger * field but the order of its base point is slightly smaller). */ const char *sw_exponents[] = { "000000000000000000000000000000000000000000000001", /* one */ "FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8C", /* n - 1 */ "5EA6F389A38B8BC81E767753B15AA5569E1782E30ABE7D25", /* random */ "400000000000000000000000000000000000000000000000", /* one and zeros */ "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", /* all ones */ "555555555555555555555555555555555555555555555555", /* 101010... */ }; #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) const char *m_exponents[] = { /* Valid private values for Curve25519. In a build with Curve448 * but not Curve25519, they will be adjusted in * self_test_adjust_exponent(). */ "4000000000000000000000000000000000000000000000000000000000000000", "5C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C30", "5715ECCE24583F7A7023C24164390586842E816D7280A49EF6DF4EAE6B280BF8", "41A2B017516F6D254E1F002BCCBADD54BE30F8CEC737A0E912B4963B6BA74460", "5555555555555555555555555555555555555555555555555555555555555550", "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8", }; #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */ mbedtls_ecp_group_init( &grp ); mbedtls_ecp_point_init( &R ); mbedtls_ecp_point_init( &P ); mbedtls_mpi_init( &m ); #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) /* Use secp192r1 if available, or any available curve */ #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &grp, MBEDTLS_ECP_DP_SECP192R1 ) ); #else MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &grp, mbedtls_ecp_curve_list()->grp_id ) ); #endif if( verbose != 0 ) mbedtls_printf( " ECP SW test #1 (constant op_count, base point G): " ); /* Do a dummy multiplication first to trigger precomputation */ MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &m, 2 ) ); MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &P, &m, &grp.G, NULL, NULL ) ); ret = self_test_point( verbose, &grp, &R, &m, &grp.G, sw_exponents, sizeof( sw_exponents ) / sizeof( sw_exponents[0] )); if( ret != 0 ) goto cleanup; if( verbose != 0 ) mbedtls_printf( " ECP SW test #2 (constant op_count, other point): " ); /* We computed P = 2G last time, use it */ ret = self_test_point( verbose, &grp, &R, &m, &P, sw_exponents, sizeof( sw_exponents ) / sizeof( sw_exponents[0] )); if( ret != 0 ) goto cleanup; mbedtls_ecp_group_free( &grp ); mbedtls_ecp_point_free( &R ); #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) if( verbose != 0 ) mbedtls_printf( " ECP Montgomery test (constant op_count): " ); #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &grp, MBEDTLS_ECP_DP_CURVE25519 ) ); #elif defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &grp, MBEDTLS_ECP_DP_CURVE448 ) ); #else #error "MBEDTLS_ECP_MONTGOMERY_ENABLED is defined, but no curve is supported for self-test" #endif ret = self_test_point( verbose, &grp, &R, &m, &grp.G, m_exponents, sizeof( m_exponents ) / sizeof( m_exponents[0] )); if( ret != 0 ) goto cleanup; #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */ cleanup: if( ret < 0 && verbose != 0 ) mbedtls_printf( "Unexpected error, return code = %08X\n", (unsigned int) ret ); mbedtls_ecp_group_free( &grp ); mbedtls_ecp_point_free( &R ); mbedtls_ecp_point_free( &P ); mbedtls_mpi_free( &m ); if( verbose != 0 ) mbedtls_printf( "\n" ); return( ret ); } #endif /* MBEDTLS_SELF_TEST */ #endif /* !MBEDTLS_ECP_ALT */ #endif /* MBEDTLS_ECP_C */ /** * \brief This function sets a point to the point at infinity. * * \param pt The point to set. This must be initialized. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_set_zero( mbedtls_ecp_point *pt ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; ECP_VALIDATE_RET( pt ); MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->X , 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Y , 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Z , 0 ) ); cleanup: return( ret ); }
146,506
3,806
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/ssl_cli.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/time/time.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/debug.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/ssl.h" #include "third_party/mbedtls/ssl_internal.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /* * SSLv3/TLSv1 client-side functions * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(MBEDTLS_SSL_CLI_C) #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) static int ssl_conf_has_static_psk( mbedtls_ssl_config const *conf ) { if( conf->psk_identity == NULL || conf->psk_identity_len == 0 ) { return( 0 ); } if( conf->psk != NULL && conf->psk_len != 0 ) return( 1 ); return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) static int ssl_write_hostname_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; size_t hostname_len; *olen = 0; if( ssl->hostname == NULL ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding server name extension: %s", ssl->hostname ) ); hostname_len = strlen( ssl->hostname ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, hostname_len + 9 ); /* * Sect. 3, RFC 6066 (TLS Extensions Definitions) * * In order to provide any of the server names, clients MAY include an * extension of type "server_name" in the (extended) client hello. The * "extension_data" field of this extension SHALL contain * "ServerNameList" where: * * struct { * NameType name_type; * select (name_type) { * case host_name: HostName; * } name; * } ServerName; * * enum { * host_name(0), (255) * } NameType; * * opaque HostName<1..2^16-1>; * * struct { * ServerName server_name_list<1..2^16-1> * } ServerNameList; * */ *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME ) & 0xFF ); *p++ = (unsigned char)( ( (hostname_len + 5) >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( (hostname_len + 5) ) & 0xFF ); *p++ = (unsigned char)( ( (hostname_len + 3) >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( (hostname_len + 3) ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME ) & 0xFF ); *p++ = (unsigned char)( ( hostname_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( hostname_len ) & 0xFF ); memcpy( p, ssl->hostname, hostname_len ); *olen = hostname_len + 9; return( 0 ); } #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_SSL_RENEGOTIATION) static int ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; *olen = 0; /* We're always including an TLS_EMPTY_RENEGOTIATION_INFO_SCSV in the * initial ClientHello, in which case also adding the renegotiation * info extension is NOT RECOMMENDED as per RFC 5746 Section 3.4. */ if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding renegotiation extension" ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 5 + ssl->verify_data_len ); /* * Secure renegotiation */ *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO ) & 0xFF ); *p++ = 0x00; *p++ = ( ssl->verify_data_len + 1 ) & 0xFF; *p++ = ssl->verify_data_len & 0xFF; memcpy( p, ssl->own_verify_data, ssl->verify_data_len ); *olen = 5 + ssl->verify_data_len; return( 0 ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ /* * Only if we handle at least one key exchange that needs signatures. */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) static int ssl_write_signature_algorithms_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; size_t sig_alg_len = 0; const uint8_t *md; #if defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) unsigned char *sig_alg_list = buf + 6; #endif *olen = 0; if( ssl->conf->max_minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding signature_algorithms extension" ) ); if( ssl->conf->sig_hashes == NULL ) return( MBEDTLS_ERR_SSL_BAD_CONFIG ); for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ ) { #if defined(MBEDTLS_ECDSA_C) sig_alg_len += 2; #endif #if defined(MBEDTLS_RSA_C) sig_alg_len += 2; #endif if( sig_alg_len > MBEDTLS_SSL_MAX_SIG_HASH_ALG_LIST_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "length in bytes of sig-hash-alg extension too big" ) ); return( MBEDTLS_ERR_SSL_BAD_CONFIG ); } } /* Empty signature algorithms list, this is a configuration error. */ if( sig_alg_len == 0 ) return( MBEDTLS_ERR_SSL_BAD_CONFIG ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, sig_alg_len + 6 ); /* * Prepare signature_algorithms extension (TLS 1.2) */ sig_alg_len = 0; for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ ) { #if defined(MBEDTLS_ECDSA_C) sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md ); sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_ECDSA; #endif #if defined(MBEDTLS_RSA_C) sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md ); sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_RSA; #endif } /* * enum { * none(0), md5(1), sha1(2), sha224(3), sha256(4), sha384(5), * sha512(6), (255) * } HashAlgorithm; * * enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) } * SignatureAlgorithm; * * struct { * HashAlgorithm hash; * SignatureAlgorithm signature; * } SignatureAndHashAlgorithm; * * SignatureAndHashAlgorithm * supported_signature_algorithms<2..2^16-2>; */ *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG ) & 0xFF ); *p++ = (unsigned char)( ( ( sig_alg_len + 2 ) >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ( sig_alg_len + 2 ) ) & 0xFF ); *p++ = (unsigned char)( ( sig_alg_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( sig_alg_len ) & 0xFF ); *olen = 6 + sig_alg_len; return( 0 ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static int ssl_write_supported_elliptic_curves_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; unsigned char *elliptic_curve_list = p + 6; size_t elliptic_curve_len = 0; const mbedtls_ecp_curve_info *info; const mbedtls_ecp_group_id *grp_id; *olen = 0; MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_elliptic_curves extension" ) ); if( ssl->conf->curve_list == NULL ) return( MBEDTLS_ERR_SSL_BAD_CONFIG ); for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ ) { info = mbedtls_ecp_curve_info_from_grp_id( *grp_id ); if( info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid curve in ssl configuration" ) ); return( MBEDTLS_ERR_SSL_BAD_CONFIG ); } elliptic_curve_len += 2; if( elliptic_curve_len > MBEDTLS_SSL_MAX_CURVE_LIST_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "malformed supported_elliptic_curves extension in config" ) ); return( MBEDTLS_ERR_SSL_BAD_CONFIG ); } } /* Empty elliptic curve list, this is a configuration error. */ if( elliptic_curve_len == 0 ) return( MBEDTLS_ERR_SSL_BAD_CONFIG ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 6 + elliptic_curve_len ); elliptic_curve_len = 0; for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ ) { info = mbedtls_ecp_curve_info_from_grp_id( *grp_id ); elliptic_curve_list[elliptic_curve_len++] = info->tls_id >> 8; elliptic_curve_list[elliptic_curve_len++] = info->tls_id & 0xFF; } *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES ) & 0xFF ); *p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) ) & 0xFF ); *p++ = (unsigned char)( ( ( elliptic_curve_len ) >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ( elliptic_curve_len ) ) & 0xFF ); *olen = 6 + elliptic_curve_len; return( 0 ); } static int ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; (void) ssl; /* ssl used for debugging only */ *olen = 0; MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_point_formats extension" ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 6 ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS ) & 0xFF ); *p++ = 0x00; *p++ = 2; *p++ = 1; *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED; *olen = 6; return( 0 ); } #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static int ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char *p = buf; size_t kkpp_len; *olen = 0; /* Skip costly extension if we can't use EC J-PAKE anyway */ if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding ecjpake_kkpp extension" ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP ) & 0xFF ); /* * We may need to send ClientHello multiple times for Hello verification. * We don't want to compute fresh values every time (both for performance * and consistency reasons), so cache the extension content. */ if( ssl->handshake->ecjpake_cache == NULL || ssl->handshake->ecjpake_cache_len == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "generating new ecjpake parameters" ) ); ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx, p + 2, end - p - 2, &kkpp_len, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1 , "mbedtls_ecjpake_write_round_one", ret ); return( ret ); } ssl->handshake->ecjpake_cache = mbedtls_calloc( 1, kkpp_len ); if( ssl->handshake->ecjpake_cache == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "allocation failed" ) ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } memcpy( ssl->handshake->ecjpake_cache, p + 2, kkpp_len ); ssl->handshake->ecjpake_cache_len = kkpp_len; } else { MBEDTLS_SSL_DEBUG_MSG( 3, ( "re-using cached ecjpake parameters" ) ); kkpp_len = ssl->handshake->ecjpake_cache_len; MBEDTLS_SSL_CHK_BUF_PTR( p + 2, end, kkpp_len ); memcpy( p + 2, ssl->handshake->ecjpake_cache, kkpp_len ); } *p++ = (unsigned char)( ( kkpp_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( kkpp_len ) & 0xFF ); *olen = kkpp_len + 4; return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) static int ssl_write_cid_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; size_t ext_len; /* * Quoting draft-ietf-tls-dtls-connection-id-05 * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05 * * struct { * opaque cid<0..2^8-1>; * } ConnectionId; */ *olen = 0; if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM || ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED ) { return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding CID extension" ) ); /* ssl->own_cid_len is at most MBEDTLS_SSL_CID_IN_LEN_MAX * which is at most 255, so the increment cannot overflow. */ MBEDTLS_SSL_CHK_BUF_PTR( p, end, (unsigned)( ssl->own_cid_len + 5 ) ); /* Add extension ID + size */ *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_CID >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_CID ) & 0xFF ); ext_len = (size_t) ssl->own_cid_len + 1; *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ext_len ) & 0xFF ); *p++ = (uint8_t) ssl->own_cid_len; memcpy( p, ssl->own_cid, ssl->own_cid_len ); *olen = ssl->own_cid_len + 5; return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) static int ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; *olen = 0; if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding max_fragment_length extension" ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 5 ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH ) & 0xFF ); *p++ = 0x00; *p++ = 1; *p++ = ssl->conf->mfl_code; *olen = 5; return( 0 ); } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) static int ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; *olen = 0; if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED || ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding encrypt_then_mac extension" ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC ) & 0xFF ); *p++ = 0x00; *p++ = 0x00; *olen = 4; return( 0 ); } #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) static int ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; *olen = 0; if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED || ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding extended_master_secret extension" ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET ) & 0xFF ); *p++ = 0x00; *p++ = 0x00; *olen = 4; return( 0 ); } #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) static int ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; size_t tlen = ssl->session_negotiate->ticket_len; *olen = 0; if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding session ticket extension" ) ); /* The addition is safe here since the ticket length is 16 bit. */ MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 + tlen ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET ) & 0xFF ); *p++ = (unsigned char)( ( tlen >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( tlen ) & 0xFF ); *olen = 4; if( ssl->session_negotiate->ticket == NULL || tlen == 0 ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "sending session ticket of length %" MBEDTLS_PRINTF_SIZET, tlen ) ); memcpy( p, ssl->session_negotiate->ticket, tlen ); *olen += tlen; return( 0 ); } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_SSL_ALPN) static int ssl_write_alpn_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; size_t alpnlen = 0; const char **cur; *olen = 0; if( ssl->conf->alpn_list == NULL ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding alpn extension" ) ); for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ ) alpnlen += strlen( *cur ) + 1; MBEDTLS_SSL_CHK_BUF_PTR( p, end, 6 + alpnlen ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN ) & 0xFF ); /* * opaque ProtocolName<1..2^8-1>; * * struct { * ProtocolName protocol_name_list<2..2^16-1> * } ProtocolNameList; */ /* Skip writing extension and list length for now */ p += 4; for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ ) { /* * mbedtls_ssl_conf_set_alpn_protocols() checked that the length of * protocol names is less than 255. */ *p = (unsigned char)strlen( *cur ); memcpy( p + 1, *cur, *p ); p += 1 + *p; } *olen = p - buf; /* List length = olen - 2 (ext_type) - 2 (ext_len) - 2 (list_len) */ buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF ); buf[5] = (unsigned char)( ( ( *olen - 6 ) ) & 0xFF ); /* Extension length = olen - 2 (ext_type) - 2 (ext_len) */ buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF ); buf[3] = (unsigned char)( ( ( *olen - 4 ) ) & 0xFF ); return( 0 ); } #endif /* MBEDTLS_SSL_ALPN */ #if defined(MBEDTLS_SSL_DTLS_SRTP) static int ssl_write_use_srtp_ext( mbedtls_ssl_context *ssl, unsigned char *buf, const unsigned char *end, size_t *olen ) { unsigned char *p = buf; size_t protection_profiles_index = 0, ext_len = 0; uint16_t mki_len = 0, profile_value = 0; *olen = 0; if( ( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) || ( ssl->conf->dtls_srtp_profile_list == NULL ) || ( ssl->conf->dtls_srtp_profile_list_len == 0 ) ) { return( 0 ); } /* RFC 5764 section 4.1.1 * uint8 SRTPProtectionProfile[2]; * * struct { * SRTPProtectionProfiles SRTPProtectionProfiles; * opaque srtp_mki<0..255>; * } UseSRTPData; * SRTPProtectionProfile SRTPProtectionProfiles<2..2^16-1>; */ if( ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED ) { mki_len = ssl->dtls_srtp_info.mki_len; } /* Extension length = 2 bytes for profiles length, * ssl->conf->dtls_srtp_profile_list_len * 2 (each profile is 2 bytes length ), * 1 byte for srtp_mki vector length and the mki_len value */ ext_len = 2 + 2 * ( ssl->conf->dtls_srtp_profile_list_len ) + 1 + mki_len; MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding use_srtp extension" ) ); /* Check there is room in the buffer for the extension + 4 bytes * - the extension tag (2 bytes) * - the extension length (2 bytes) */ MBEDTLS_SSL_CHK_BUF_PTR( p, end, ext_len + 4 ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_USE_SRTP >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_USE_SRTP ) & 0xFF ); *p++ = (unsigned char)( ( ( ext_len & 0xFF00 ) >> 8 ) & 0xFF ); *p++ = (unsigned char)( ext_len & 0xFF ); /* protection profile length: 2*(ssl->conf->dtls_srtp_profile_list_len) */ /* micro-optimization: * the list size is limited to MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH * which is lower than 127, so the upper byte of the length is always 0 * For the documentation, the more generic code is left in comments * *p++ = (unsigned char)( ( ( 2 * ssl->conf->dtls_srtp_profile_list_len ) * >> 8 ) & 0xFF ); */ *p++ = 0; *p++ = (unsigned char)( ( 2 * ssl->conf->dtls_srtp_profile_list_len ) & 0xFF ); for( protection_profiles_index=0; protection_profiles_index < ssl->conf->dtls_srtp_profile_list_len; protection_profiles_index++ ) { profile_value = mbedtls_ssl_check_srtp_profile_value ( ssl->conf->dtls_srtp_profile_list[protection_profiles_index] ); if( profile_value != MBEDTLS_TLS_SRTP_UNSET ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_write_use_srtp_ext, add profile: %04x", profile_value ) ); *p++ = ( ( profile_value >> 8 ) & 0xFF ); *p++ = ( profile_value & 0xFF ); } else { /* * Note: we shall never arrive here as protection profiles * is checked by mbedtls_ssl_conf_dtls_srtp_protection_profiles function */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, " "illegal DTLS-SRTP protection profile %d", ssl->conf->dtls_srtp_profile_list[protection_profiles_index] ) ); return( MBEDTLS_ERR_THIS_CORRUPTION ); } } *p++ = mki_len & 0xFF; if( mki_len != 0 ) { memcpy( p, ssl->dtls_srtp_info.mki_value, mki_len ); /* * Increment p to point to the current position. */ p += mki_len; MBEDTLS_SSL_DEBUG_BUF( 3, "sending mki", ssl->dtls_srtp_info.mki_value, ssl->dtls_srtp_info.mki_len ); } /* * total extension length: extension type (2 bytes) * + extension length (2 bytes) * + protection profile length (2 bytes) * + 2 * number of protection profiles * + srtp_mki vector length(1 byte) * + mki value */ *olen = p - buf; return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_SRTP */ /* * Generate random bytes for ClientHello */ static int ssl_generate_random( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char *p = ssl->handshake->randbytes; #if defined(MBEDTLS_HAVE_TIME) mbedtls_time_t t; #endif /* * When responding to a verify request, MUST reuse random (RFC 6347 4.2.1) */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake->verify_cookie != NULL ) { return( 0 ); } #endif #if defined(MBEDTLS_HAVE_TIME) t = mbedtls_time( NULL ); *p++ = (unsigned char)( t >> 24 ); *p++ = (unsigned char)( t >> 16 ); *p++ = (unsigned char)( t >> 8 ); *p++ = (unsigned char)( t ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, current time: %" MBEDTLS_PRINTF_LONGLONG, (long long) t ) ); #else if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 ) return( ret ); p += 4; #endif /* MBEDTLS_HAVE_TIME */ if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 ) return( ret ); return( 0 ); } /** * \brief Validate cipher suite against config in SSL context. * * \param suite_info cipher suite to validate * \param ssl SSL context * \param min_minor_ver Minimal minor version to accept a cipher suite * \param max_minor_ver Maximal minor version to accept a cipher suite * * \return 0 if valid, else 1 */ static int ssl_validate_ciphersuite( const mbedtls_ssl_ciphersuite_t * suite_info, const mbedtls_ssl_context * ssl, int min_minor_ver, int max_minor_ver ) { (void) ssl; if( suite_info == NULL ) return( 1 ); if( suite_info->min_minor_ver > max_minor_ver || suite_info->max_minor_ver < min_minor_ver ) return( 1 ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ( suite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) ) return( 1 ); #endif #if defined(MBEDTLS_ARC4_C) if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED && suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 ) return( 1 ); #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE && mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 ) return( 1 ); #endif /* Don't suggest PSK-based ciphersuite if no PSK is available. */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) if( mbedtls_ssl_ciphersuite_uses_psk( suite_info ) && ssl_conf_has_static_psk( ssl->conf ) == 0 ) { return( 1 ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ return( 0 ); } static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t i, n, olen, ext_len = 0; unsigned char *buf; unsigned char *p, *q; const unsigned char *end; unsigned char offer_compress; const uint16_t *ciphersuites; const mbedtls_ssl_ciphersuite_t *ciphersuite_info; #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) int uses_ec = 0; #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client hello" ) ); if( ssl->conf->f_rng == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "no RNG provided") ); return( MBEDTLS_ERR_SSL_NO_RNG ); } #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE ) #endif { ssl->major_ver = ssl->conf->min_major_ver; ssl->minor_ver = ssl->conf->min_minor_ver; } if( ssl->conf->max_major_ver == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "configured max major version is invalid, consider using mbedtls_ssl_config_defaults()" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } buf = ssl->out_msg; end = buf + MBEDTLS_SSL_OUT_CONTENT_LEN; /* * Check if there's enough space for the first part of the ClientHello * consisting of the 38 bytes described below, the session identifier (at * most 32 bytes) and its length (1 byte). * * Use static upper bounds instead of the actual values * to allow the compiler to optimize this away. */ MBEDTLS_SSL_CHK_BUF_PTR( buf, end, 38 + 1 + 32 ); /* * The 38 first bytes of the ClientHello: * 0 . 0 handshake type (written later) * 1 . 3 handshake length (written later) * 4 . 5 highest version supported * 6 . 9 current UNIX time * 10 . 37 random bytes * * The current UNIX time (4 bytes) and following 28 random bytes are written * by ssl_generate_random() into ssl->handshake->randbytes buffer and then * copied from there into the output buffer. */ p = buf + 4; mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver, ssl->conf->transport, p ); p += 2; MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, max version: [%d:%d]", buf[4], buf[5] ) ); if( ( ret = ssl_generate_random( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_generate_random", ret ); return( ret ); } memcpy( p, ssl->handshake->randbytes, 32 ); MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", p, 32 ); p += 32; /* * 38 . 38 session id length * 39 . 39+n session id * 39+n . 39+n DTLS only: cookie length (1 byte) * 40+n . .. DTLS only: cookie * .. . .. ciphersuitelist length (2 bytes) * .. . .. ciphersuitelist * .. . .. compression methods length (1 byte) * .. . .. compression methods * .. . .. extensions length (2 bytes) * .. . .. extensions */ n = ssl->session_negotiate->id_len; if( n < 16 || n > 32 || #if defined(MBEDTLS_SSL_RENEGOTIATION) ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE || #endif ssl->handshake->resume == 0 ) { n = 0; } #if defined(MBEDTLS_SSL_SESSION_TICKETS) /* * RFC 5077 section 3.4: "When presenting a ticket, the client MAY * generate and include a Session ID in the TLS ClientHello." */ #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE ) #endif { if( ssl->session_negotiate->ticket != NULL && ssl->session_negotiate->ticket_len != 0 ) { ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id, 32 ); if( ret != 0 ) return( ret ); ssl->session_negotiate->id_len = n = 32; } } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ /* * The first check of the output buffer size above ( * MBEDTLS_SSL_CHK_BUF_PTR( buf, end, 38 + 1 + 32 );) * has checked that there is enough space in the output buffer for the * session identifier length byte and the session identifier (n <= 32). */ *p++ = (unsigned char) n; for( i = 0; i < n; i++ ) *p++ = ssl->session_negotiate->id[i]; MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, session id len.: %" MBEDTLS_PRINTF_SIZET, n ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf + 39, n ); /* * With 'n' being the length of the session identifier * * 39+n . 39+n DTLS only: cookie length (1 byte) * 40+n . .. DTLS only: cookie * .. . .. ciphersuitelist length (2 bytes) * .. . .. ciphersuitelist * .. . .. compression methods length (1 byte) * .. . .. compression methods * .. . .. extensions length (2 bytes) * .. . .. extensions */ /* * DTLS cookie */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { MBEDTLS_SSL_CHK_BUF_PTR( p, end, 1 ); if( ssl->handshake->verify_cookie == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "no verify cookie to send" ) ); *p++ = 0; } else { MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, cookie", ssl->handshake->verify_cookie, ssl->handshake->verify_cookie_len ); *p++ = ssl->handshake->verify_cookie_len; MBEDTLS_SSL_CHK_BUF_PTR( p, end, ssl->handshake->verify_cookie_len ); memcpy( p, ssl->handshake->verify_cookie, ssl->handshake->verify_cookie_len ); p += ssl->handshake->verify_cookie_len; } } #endif /* * Ciphersuite list */ ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver]; /* Skip writing ciphersuite length for now */ n = 0; q = p; MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 ); p += 2; for( i = 0; ciphersuites[i] != 0; i++ ) { ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuites[i] ); if( ssl_validate_ciphersuite( ciphersuite_info, ssl, ssl->conf->min_minor_ver, ssl->conf->max_minor_ver ) != 0 ) continue; MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, add ciphersuite: %#04x (%s)", (unsigned int)ciphersuites[i], ciphersuite_info->name ) ); #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) uses_ec |= mbedtls_ssl_ciphersuite_uses_ec( ciphersuite_info ); #endif MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 ); n++; *p++ = (unsigned char)( ciphersuites[i] >> 8 ); *p++ = (unsigned char)( ciphersuites[i] ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, got %" MBEDTLS_PRINTF_SIZET " ciphersuites (excluding SCSVs)", n ) ); /* * Add TLS_EMPTY_RENEGOTIATION_INFO_SCSV */ #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE ) #endif { MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding EMPTY_RENEGOTIATION_INFO_SCSV" ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 ); *p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO >> 8 ); *p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO ); n++; } /* Some versions of OpenSSL don't handle it correctly if not at end */ #if defined(MBEDTLS_SSL_FALLBACK_SCSV) if( ssl->conf->fallback == MBEDTLS_SSL_IS_FALLBACK ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding FALLBACK_SCSV" ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 ); *p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ); *p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE ); n++; } #endif *q++ = (unsigned char)( n >> 7 ); *q++ = (unsigned char)( n << 1 ); #if defined(MBEDTLS_ZLIB_SUPPORT) offer_compress = !ssl->conf->disable_compression; #else offer_compress = 0; #endif /* * We don't support compression with DTLS right now: if many records come * in the same datagram, uncompressing one could overwrite the next one. * We don't want to add complexity for handling that case unless there is * an actual need for it. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) offer_compress = 0; #endif if( offer_compress ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 2 ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d %d", MBEDTLS_SSL_COMPRESS_DEFLATE, MBEDTLS_SSL_COMPRESS_NULL ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 3 ); *p++ = 2; *p++ = MBEDTLS_SSL_COMPRESS_DEFLATE; *p++ = MBEDTLS_SSL_COMPRESS_NULL; } else { MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 1 ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d", MBEDTLS_SSL_COMPRESS_NULL ) ); MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 ); *p++ = 1; *p++ = MBEDTLS_SSL_COMPRESS_NULL; } /* First write extensions, then the total length */ MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 ); #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) if( ( ret = ssl_write_hostname_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_hostname_ext", ret ); return( ret ); } ext_len += olen; #endif /* Note that TLS_EMPTY_RENEGOTIATION_INFO_SCSV is always added * even if MBEDTLS_SSL_RENEGOTIATION is not defined. */ #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ( ret = ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_renegotiation_ext", ret ); return( ret ); } ext_len += olen; #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) if( ( ret = ssl_write_signature_algorithms_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_signature_algorithms_ext", ret ); return( ret ); } ext_len += olen; #endif #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( uses_ec ) { if( ( ret = ssl_write_supported_elliptic_curves_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_supported_elliptic_curves_ext", ret ); return( ret ); } ext_len += olen; if( ( ret = ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_supported_point_formats_ext", ret ); return( ret ); } ext_len += olen; } #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( ( ret = ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_ecjpake_kkpp_ext", ret ); return( ret ); } ext_len += olen; #endif #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) if( ( ret = ssl_write_cid_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_cid_ext", ret ); return( ret ); } ext_len += olen; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) if( ( ret = ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_max_fragment_length_ext", ret ); return( ret ); } ext_len += olen; #endif #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) if( ( ret = ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_encrypt_then_mac_ext", ret ); return( ret ); } ext_len += olen; #endif #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) if( ( ret = ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_extended_ms_ext", ret ); return( ret ); } ext_len += olen; #endif #if defined(MBEDTLS_SSL_ALPN) if( ( ret = ssl_write_alpn_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_alpn_ext", ret ); return( ret ); } ext_len += olen; #endif #if defined(MBEDTLS_SSL_DTLS_SRTP) if( ( ret = ssl_write_use_srtp_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_use_srtp_ext", ret ); return( ret ); } ext_len += olen; #endif #if defined(MBEDTLS_SSL_SESSION_TICKETS) if( ( ret = ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_session_ticket_ext", ret ); return( ret ); } ext_len += olen; #endif /* olen unused if all extensions are disabled */ ((void) olen); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, total extension length: %" MBEDTLS_PRINTF_SIZET, ext_len ) ); if( ext_len > 0 ) { /* No need to check for space here, because the extension * writing functions already took care of that. */ *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ext_len ) & 0xFF ); p += ext_len; } ssl->out_msglen = p - buf; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_CLIENT_HELLO; ssl->state++; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_send_flight_completed( ssl ); #endif if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret ); return( ret ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client hello" ) ); return( 0 ); } static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) { /* Check verify-data in constant-time. The length OTOH is no secret */ if( len != 1 + ssl->verify_data_len * 2 || buf[0] != ssl->verify_data_len * 2 || timingsafe_bcmp( buf + 1, ssl->own_verify_data, ssl->verify_data_len ) != 0 || timingsafe_bcmp( buf + 1 + ssl->verify_data_len, ssl->peer_verify_data, ssl->verify_data_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } } else #endif /* MBEDTLS_SSL_RENEGOTIATION */ { if( len != 1 || buf[0] != 0x00 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-zero length renegotiation info" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION; } return( 0 ); } #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { /* * server should use the extension only if we did, * and if so the server's value should match ours (and len is always 1) */ if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE || len != 1 || buf[0] != ssl->conf->mfl_code ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching max fragment length extension" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } return( 0 ); } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) static int ssl_parse_cid_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t peer_cid_len; if( /* CID extension only makes sense in DTLS */ ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM || /* The server must only send the CID extension if we have offered it. */ ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "CID extension unexpected" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } if( len == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "CID extension invalid" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } peer_cid_len = *buf++; len--; if( peer_cid_len > MBEDTLS_SSL_CID_OUT_LEN_MAX ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "CID extension invalid" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } if( len != peer_cid_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "CID extension invalid" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } ssl->handshake->cid_in_use = MBEDTLS_SSL_CID_ENABLED; ssl->handshake->peer_cid_len = (uint8_t) peer_cid_len; memcpy( ssl->handshake->peer_cid, buf, peer_cid_len ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use of CID extension negotiated" ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "Server CID", buf, peer_cid_len ); return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED || ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 || len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching encrypt-then-MAC extension" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } ((void) buf); ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED; return( 0 ); } #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED || ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 || len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching extended master secret extension" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } ((void) buf); ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED; return( 0 ); } #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED || len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching session ticket extension" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } ((void) buf); ssl->handshake->new_session_ticket = 1; return( 0 ); } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static int ssl_parse_supported_point_formats_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t list_size; const unsigned char *p; if( len == 0 || (size_t)( buf[0] + 1 ) != len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } list_size = buf[0]; p = buf + 1; while( list_size > 0 ) { if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED || p[0] == MBEDTLS_ECP_PF_COMPRESSED ) { #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) ssl->handshake->ecdh_ctx.point_format = p[0]; #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) ssl->handshake->ecjpake_ctx.point_format = p[0]; #endif MBEDTLS_SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) ); return( 0 ); } list_size--; p++; } MBEDTLS_SSL_DEBUG_MSG( 1, ( "no point format in common" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( ssl->handshake->ciphersuite_info->key_exchange != MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip ecjpake kkpp extension" ) ); return( 0 ); } /* If we goth here, we no longer need our cached extension */ mbedtls_free( ssl->handshake->ecjpake_cache ); ssl->handshake->ecjpake_cache = NULL; ssl->handshake->ecjpake_cache_len = 0; if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx, buf, len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( ret ); } return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_SSL_ALPN) static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t list_len, name_len; const char **p; /* If we didn't send it, the server shouldn't send it */ if( ssl->conf->alpn_list == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching ALPN extension" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } /* * opaque ProtocolName<1..2^8-1>; * * struct { * ProtocolName protocol_name_list<2..2^16-1> * } ProtocolNameList; * * the "ProtocolNameList" MUST contain exactly one "ProtocolName" */ /* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */ if( len < 4 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } list_len = ( buf[0] << 8 ) | buf[1]; if( list_len != len - 2 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } name_len = buf[2]; if( name_len != list_len - 1 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } /* Check that the server chosen protocol was in our list and save it */ for( p = ssl->conf->alpn_list; *p != NULL; p++ ) { if( name_len == strlen( *p ) && timingsafe_bcmp( buf + 3, *p, name_len ) == 0 ) { ssl->alpn_chosen = *p; return( 0 ); } } MBEDTLS_SSL_DEBUG_MSG( 1, ( "ALPN extension: no matching protocol" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } #endif /* MBEDTLS_SSL_ALPN */ #if defined(MBEDTLS_SSL_DTLS_SRTP) static int ssl_parse_use_srtp_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { mbedtls_ssl_srtp_profile server_protection = MBEDTLS_TLS_SRTP_UNSET; size_t i, mki_len = 0; uint16_t server_protection_profile_value = 0; /* If use_srtp is not configured, just ignore the extension */ if( ( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) || ( ssl->conf->dtls_srtp_profile_list == NULL ) || ( ssl->conf->dtls_srtp_profile_list_len == 0 ) ) return( 0 ); /* RFC 5764 section 4.1.1 * uint8 SRTPProtectionProfile[2]; * * struct { * SRTPProtectionProfiles SRTPProtectionProfiles; * opaque srtp_mki<0..255>; * } UseSRTPData; * SRTPProtectionProfile SRTPProtectionProfiles<2..2^16-1>; * */ if( ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED ) { mki_len = ssl->dtls_srtp_info.mki_len; } /* * Length is 5 + optional mki_value : one protection profile length (2 bytes) * + protection profile (2 bytes) * + mki_len(1 byte) * and optional srtp_mki */ if( ( len < 5 ) || ( len != ( buf[4] + 5u ) ) ) return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); /* * get the server protection profile */ /* * protection profile length must be 0x0002 as we must have only * one protection profile in server Hello */ if( ( buf[0] != 0 ) || ( buf[1] != 2 ) ) return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); server_protection_profile_value = ( buf[2] << 8 ) | buf[3]; server_protection = mbedtls_ssl_check_srtp_profile_value( server_protection_profile_value ); if( server_protection != MBEDTLS_TLS_SRTP_UNSET ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "found srtp profile: %s", mbedtls_ssl_get_srtp_profile_as_string( server_protection ) ) ); } ssl->dtls_srtp_info.chosen_dtls_srtp_profile = MBEDTLS_TLS_SRTP_UNSET; /* * Check we have the server profile in our list */ for( i=0; i < ssl->conf->dtls_srtp_profile_list_len; i++) { if( server_protection == ssl->conf->dtls_srtp_profile_list[i] ) { ssl->dtls_srtp_info.chosen_dtls_srtp_profile = ssl->conf->dtls_srtp_profile_list[i]; MBEDTLS_SSL_DEBUG_MSG( 3, ( "selected srtp profile: %s", mbedtls_ssl_get_srtp_profile_as_string( server_protection ) ) ); break; } } /* If no match was found : server problem, it shall never answer with incompatible profile */ if( ssl->dtls_srtp_info.chosen_dtls_srtp_profile == MBEDTLS_TLS_SRTP_UNSET ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } /* If server does not use mki in its reply, make sure the client won't keep * one as negotiated */ if( len == 5 ) { ssl->dtls_srtp_info.mki_len = 0; } /* * RFC5764: * If the client detects a nonzero-length MKI in the server's response * that is different than the one the client offered, then the client * MUST abort the handshake and SHOULD send an invalid_parameter alert. */ if( len > 5 && ( buf[4] != mki_len || ( timingsafe_bcmp( ssl->dtls_srtp_info.mki_value, &buf[5], mki_len ) ) ) ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } #if defined (MBEDTLS_DEBUG_C) if( len > 5 ) { MBEDTLS_SSL_DEBUG_BUF( 3, "received mki", ssl->dtls_srtp_info.mki_value, ssl->dtls_srtp_info.mki_len ); } #endif return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_SRTP */ /* * Parse HelloVerifyRequest. Only called after verifying the HS type. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) static int ssl_parse_hello_verify_request( mbedtls_ssl_context *ssl ) { const unsigned char *p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); int major_ver, minor_ver; unsigned char cookie_len; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse hello verify request" ) ); /* Check that there is enough room for: * - 2 bytes of version * - 1 byte of cookie_len */ if( mbedtls_ssl_hs_hdr_len( ssl ) + 3 > ssl->in_msglen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "incoming HelloVerifyRequest message is too short" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } /* * struct { * ProtocolVersion server_version; * opaque cookie<0..2^8-1>; * } HelloVerifyRequest; */ MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p, 2 ); mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, p ); p += 2; /* * Since the RFC is not clear on this point, accept DTLS 1.0 (TLS 1.1) * even is lower than our min version. */ if( major_ver < MBEDTLS_SSL_MAJOR_VERSION_3 || minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 || major_ver > ssl->conf->max_major_ver || minor_ver > ssl->conf->max_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server version" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION ); } cookie_len = *p++; if( ( ssl->in_msg + ssl->in_msglen ) - p < cookie_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "cookie length does not match incoming message size" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "cookie", p, cookie_len ); mbedtls_free( ssl->handshake->verify_cookie ); ssl->handshake->verify_cookie = mbedtls_calloc( 1, cookie_len ); if( ssl->handshake->verify_cookie == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc failed (%d bytes)", cookie_len ) ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } memcpy( ssl->handshake->verify_cookie, p, cookie_len ); ssl->handshake->verify_cookie_len = cookie_len; /* Start over at ClientHello */ ssl->state = MBEDTLS_SSL_CLIENT_HELLO; mbedtls_ssl_reset_checksum( ssl ); mbedtls_ssl_recv_flight_completed( ssl ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse hello verify request" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) { int ret, i; size_t n; size_t ext_len; unsigned char *buf, *ext; unsigned char comp; #if defined(MBEDTLS_ZLIB_SUPPORT) int accept_comp; #endif #if defined(MBEDTLS_SSL_RENEGOTIATION) int renegotiation_info_seen = 0; #endif int handshake_failure = 0; const mbedtls_ssl_ciphersuite_t *suite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello" ) ); if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { /* No alert on a read error. */ MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } buf = ssl->in_msg; if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { ssl->renego_records_seen++; if( ssl->conf->renego_max_records >= 0 && ssl->renego_records_seen > ssl->conf->renego_max_records ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, but not honored by server" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-handshake message during renegotiation" ) ); ssl->keep_current_message = 1; return( MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { if( buf[0] == MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "received hello verify request" ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) ); return( ssl_parse_hello_verify_request( ssl ) ); } else { /* We made it through the verification process */ mbedtls_free( ssl->handshake->verify_cookie ); ssl->handshake->verify_cookie = NULL; ssl->handshake->verify_cookie_len = 0; } } #endif /* MBEDTLS_SSL_PROTO_DTLS */ if( ssl->in_hslen < 38 + mbedtls_ssl_hs_hdr_len( ssl ) || buf[0] != MBEDTLS_SSL_HS_SERVER_HELLO ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } /* * 0 . 1 server_version * 2 . 33 random (maybe including 4 bytes of Unix time) * 34 . 34 session_id length = n * 35 . 34+n session_id * 35+n . 36+n cipher_suite * 37+n . 37+n compression_method * * 38+n . 39+n extensions length (optional) * 40+n . .. extensions */ buf += mbedtls_ssl_hs_hdr_len( ssl ); MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, version", buf + 0, 2 ); mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver, ssl->conf->transport, buf + 0 ); if( ssl->major_ver < ssl->conf->min_major_ver || ssl->minor_ver < ssl->conf->min_minor_ver || ssl->major_ver > ssl->conf->max_major_ver || ssl->minor_ver > ssl->conf->max_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "server version out of bounds - min: [%d:%d], server: [%d:%d], max: [%d:%d]", ssl->conf->min_major_ver, ssl->conf->min_minor_ver, ssl->major_ver, ssl->minor_ver, ssl->conf->max_major_ver, ssl->conf->max_minor_ver ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %lu", ( (unsigned long) buf[2] << 24 ) | ( (unsigned long) buf[3] << 16 ) | ( (unsigned long) buf[4] << 8 ) | ( (unsigned long) buf[5] ) ) ); memcpy( ssl->handshake->randbytes + 32, buf + 2, 32 ); n = buf[34]; MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, random bytes", buf + 2, 32 ); if( n > 32 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } if( ssl->in_hslen > mbedtls_ssl_hs_hdr_len( ssl ) + 39 + n ) { ext_len = ( ( buf[38 + n] << 8 ) | ( buf[39 + n] ) ); if( ( ext_len > 0 && ext_len < 4 ) || ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 40 + n + ext_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } } else if( ssl->in_hslen == mbedtls_ssl_hs_hdr_len( ssl ) + 38 + n ) { ext_len = 0; } else { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } /* ciphersuite (used later) */ i = ( buf[35 + n] << 8 ) | buf[36 + n]; /* * Read and check compression */ comp = buf[37 + n]; #if defined(MBEDTLS_ZLIB_SUPPORT) /* See comments in ssl_write_client_hello() */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) accept_comp = 0; else #endif accept_comp = !ssl->conf->disable_compression; if( comp != MBEDTLS_SSL_COMPRESS_NULL && ( comp != MBEDTLS_SSL_COMPRESS_DEFLATE || accept_comp == 0 ) ) #else /* MBEDTLS_ZLIB_SUPPORT */ if( comp != MBEDTLS_SSL_COMPRESS_NULL ) #endif/* MBEDTLS_ZLIB_SUPPORT */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "server hello, bad compression: %d", comp ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } /* * Initialize update checksum functions */ ssl->handshake->ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( i ); if( ssl->handshake->ciphersuite_info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "ciphersuite info for %04x not found", (unsigned int)i ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } mbedtls_ssl_optimize_checksum( ssl, ssl->handshake->ciphersuite_info ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, session id len.: %" MBEDTLS_PRINTF_SIZET, n ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, session id", buf + 35, n ); /* * Check if the session can be resumed */ if( ssl->handshake->resume == 0 || n == 0 || #if defined(MBEDTLS_SSL_RENEGOTIATION) ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE || #endif ssl->session_negotiate->ciphersuite != i || ssl->session_negotiate->compression != comp || ssl->session_negotiate->id_len != n || timingsafe_bcmp( ssl->session_negotiate->id, buf + 35, n ) != 0 ) { ssl->state++; ssl->handshake->resume = 0; #if defined(MBEDTLS_HAVE_TIME) ssl->session_negotiate->start = mbedtls_time( NULL ); #endif ssl->session_negotiate->ciphersuite = i; ssl->session_negotiate->compression = comp; ssl->session_negotiate->id_len = n; memcpy( ssl->session_negotiate->id, buf + 35, n ); } else { ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC; if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( ret ); } } MBEDTLS_SSL_DEBUG_MSG( 3, ( "%s session has been resumed", ssl->handshake->resume ? "a" : "no" ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %04x", (unsigned) i ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: %d", buf[37 + n] ) ); /* * Perform cipher suite validation in same way as in ssl_write_client_hello. */ i = 0; while( 1 ) { if( ssl->conf->ciphersuite_list[ssl->minor_ver][i] == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } if( ssl->conf->ciphersuite_list[ssl->minor_ver][i++] == ssl->session_negotiate->ciphersuite ) { break; } } suite_info = mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite ); if( ssl_validate_ciphersuite( suite_info, ssl, ssl->minor_ver, ssl->minor_ver ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s", suite_info->name ) ); #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA && ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { ssl->handshake->ecrs_enabled = 1; } #endif if( comp != MBEDTLS_SSL_COMPRESS_NULL #if defined(MBEDTLS_ZLIB_SUPPORT) && comp != MBEDTLS_SSL_COMPRESS_DEFLATE #endif ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } ssl->session_negotiate->compression = comp; ext = buf + 40 + n; MBEDTLS_SSL_DEBUG_MSG( 2, ( "server hello, total extension length: %" MBEDTLS_PRINTF_SIZET, ext_len ) ); while( ext_len ) { unsigned int ext_id = ( ( ext[0] << 8 ) | ( ext[1] ) ); unsigned int ext_size = ( ( ext[2] << 8 ) | ( ext[3] ) ); if( ext_size + 4 > ext_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } switch( ext_id ) { case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found renegotiation extension" ) ); #if defined(MBEDTLS_SSL_RENEGOTIATION) renegotiation_info_seen = 1; #endif if( ( ret = ssl_parse_renegotiation_info( ssl, ext + 4, ext_size ) ) != 0 ) return( ret ); break; #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found max_fragment_length extension" ) ); if( ( ret = ssl_parse_max_fragment_length_ext( ssl, ext + 4, ext_size ) ) != 0 ) { return( ret ); } break; #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) case MBEDTLS_TLS_EXT_CID: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found CID extension" ) ); if( ( ret = ssl_parse_cid_ext( ssl, ext + 4, ext_size ) ) != 0 ) { return( ret ); } break; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found encrypt_then_mac extension" ) ); if( ( ret = ssl_parse_encrypt_then_mac_ext( ssl, ext + 4, ext_size ) ) != 0 ) { return( ret ); } break; #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found extended_master_secret extension" ) ); if( ( ret = ssl_parse_extended_ms_ext( ssl, ext + 4, ext_size ) ) != 0 ) { return( ret ); } break; #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) case MBEDTLS_TLS_EXT_SESSION_TICKET: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found session_ticket extension" ) ); if( ( ret = ssl_parse_session_ticket_ext( ssl, ext + 4, ext_size ) ) != 0 ) { return( ret ); } break; #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported_point_formats extension" ) ); if( ( ret = ssl_parse_supported_point_formats_ext( ssl, ext + 4, ext_size ) ) != 0 ) { return( ret ); } break; #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) case MBEDTLS_TLS_EXT_ECJPAKE_KKPP: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ecjpake_kkpp extension" ) ); if( ( ret = ssl_parse_ecjpake_kkpp( ssl, ext + 4, ext_size ) ) != 0 ) { return( ret ); } break; #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_SSL_ALPN) case MBEDTLS_TLS_EXT_ALPN: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) ); if( ( ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size ) ) != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_ALPN */ #if defined(MBEDTLS_SSL_DTLS_SRTP) case MBEDTLS_TLS_EXT_USE_SRTP: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found use_srtp extension" ) ); if( ( ret = ssl_parse_use_srtp_ext( ssl, ext + 4, ext_size ) ) != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_DTLS_SRTP */ default: MBEDTLS_SSL_DEBUG_MSG( 3, ( "unknown extension found: %u (ignoring)", ext_id ) ); } ext_len -= 4 + ext_size; ext += 4 + ext_size; if( ext_len > 0 && ext_len < 4 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } } /* * Renegotiation security checks */ if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) ); handshake_failure = 1; } #if defined(MBEDTLS_SSL_RENEGOTIATION) else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION && renegotiation_info_seen == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension missing (secure)" ) ); handshake_failure = 1; } else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) ); handshake_failure = 1; } else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && renegotiation_info_seen == 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension present (legacy)" ) ); handshake_failure = 1; } #endif /* MBEDTLS_SSL_RENEGOTIATION */ if( handshake_failure == 1 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) ); return( 0 ); } #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) static int ssl_parse_server_dh_params( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; /* * Ephemeral DH parameters: * * struct { * opaque dh_p<1..2^16-1>; * opaque dh_g<1..2^16-1>; * opaque dh_Ys<1..2^16-1>; * } ServerDHParams; */ if( ( ret = mbedtls_dhm_read_params( &ssl->handshake->dhm_ctx, p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 2, ( "mbedtls_dhm_read_params" ), ret ); return( ret ); } if( ssl->handshake->dhm_ctx.len * 8 < ssl->conf->dhm_min_bitlen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "DHM prime too short: %" MBEDTLS_PRINTF_SIZET " < %u", ssl->handshake->dhm_ctx.len * 8, ssl->conf->dhm_min_bitlen ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P ); MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G ); MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY ); return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) static int ssl_check_server_ecdh_params( const mbedtls_ssl_context *ssl ) { const mbedtls_ecp_curve_info *curve_info; mbedtls_ecp_group_id grp_id; #if defined(MBEDTLS_ECDH_LEGACY_CONTEXT) grp_id = ssl->handshake->ecdh_ctx.grp.id; #else grp_id = ssl->handshake->ecdh_ctx.grp_id; #endif curve_info = mbedtls_ecp_curve_info_from_grp_id( grp_id ); if( curve_info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDH curve: %s", curve_info->name ) ); #if defined(MBEDTLS_ECP_C) if( mbedtls_ssl_check_curve( ssl, grp_id ) != 0 ) #else if( ssl->handshake->ecdh_ctx.grp.nbits < 163 || ssl->handshake->ecdh_ctx.grp.nbits > 521 ) #endif return( -1 ); MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_QP ); return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) static int ssl_parse_server_ecdh_params( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; /* * Ephemeral ECDH parameters: * * struct { * ECParameters curve_params; * ECPoint public; * } ServerECDHParams; */ if( ( ret = mbedtls_ecdh_read_params( &ssl->handshake->ecdh_ctx, (const unsigned char **) p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_read_params" ), ret ); #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS; #endif return( ret ); } if( ssl_check_server_ecdh_params( ssl ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message (ECDHE curve)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; uint16_t len; ((void) ssl); /* * PSK parameters: * * opaque psk_identity_hint<0..2^16-1>; */ if( end - (*p) < 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message (psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } len = (*p)[0] << 8 | (*p)[1]; *p += 2; if( end - (*p) < len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message (psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } /* * Note: we currently ignore the PKS identity hint, as we only allow one * PSK to be provisionned on the client. This could be changed later if * someone needs that feature. */ *p += len; ret = 0; return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) /* * Generate a pre-master secret and encrypt it with the server's RSA key */ static int ssl_write_encrypted_pms( mbedtls_ssl_context *ssl, size_t offset, size_t *olen, size_t pms_offset ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t len_bytes = ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ? 0 : 2; unsigned char *p = ssl->handshake->premaster + pms_offset; mbedtls_pk_context * peer_pk; if( offset + len_bytes > MBEDTLS_SSL_OUT_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small for encrypted pms" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } /* * Generate (part of) the pre-master as * struct { * ProtocolVersion client_version; * opaque random[46]; * } PreMasterSecret; */ mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver, ssl->conf->transport, p ); if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p + 2, 46 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "f_rng", ret ); return( ret ); } ssl->handshake->pmslen = 48; #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) peer_pk = &ssl->handshake->peer_pubkey; #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( ssl->session_negotiate->peer_cert == NULL ) { /* Should never happen */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } peer_pk = &ssl->session_negotiate->peer_cert->pk; #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ /* * Now write it out, encrypted */ if( ! mbedtls_pk_can_do( peer_pk, MBEDTLS_PK_RSA ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate key type mismatch" ) ); return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH ); } if( ( ret = mbedtls_pk_encrypt( peer_pk, p, ssl->handshake->pmslen, ssl->out_msg + offset + len_bytes, olen, MBEDTLS_SSL_OUT_CONTENT_LEN - offset - len_bytes, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_rsa_pkcs1_encrypt", ret ); return( ret ); } #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( len_bytes == 2 ) { ssl->out_msg[offset+0] = (unsigned char)( *olen >> 8 ); ssl->out_msg[offset+1] = (unsigned char)( *olen ); *olen += 2; } #endif #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) /* We don't need the peer's public key anymore. Free it. */ mbedtls_pk_free( peer_pk ); #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) static int ssl_parse_signature_algorithm( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end, mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg ) { ((void) ssl); *md_alg = MBEDTLS_MD_NONE; *pk_alg = MBEDTLS_PK_NONE; /* Only in TLS 1.2 */ if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 ) { return( 0 ); } if( (*p) + 2 > end ) return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); /* * Get hash algorithm */ if( ( *md_alg = mbedtls_ssl_md_alg_from_hash( (*p)[0] ) ) == MBEDTLS_MD_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Server used unsupported HashAlgorithm %d", *(p)[0] ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } /* * Get signature algorithm */ if( ( *pk_alg = mbedtls_ssl_pk_alg_from_sig( (*p)[1] ) ) == MBEDTLS_PK_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used unsupported SignatureAlgorithm %d", (*p)[1] ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } /* * Check if the hash is acceptable */ if( mbedtls_ssl_check_sig_hash( ssl, *md_alg ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used HashAlgorithm %d that was not offered", *(p)[0] ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used SignatureAlgorithm %d", (*p)[1] ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used HashAlgorithm %d", (*p)[0] ) ); *p += 2; return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */ #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; const mbedtls_ecp_keypair *peer_key; mbedtls_pk_context * peer_pk; #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) peer_pk = &ssl->handshake->peer_pubkey; #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( ssl->session_negotiate->peer_cert == NULL ) { /* Should never happen */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } peer_pk = &ssl->session_negotiate->peer_cert->pk; #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( ! mbedtls_pk_can_do( peer_pk, MBEDTLS_PK_ECKEY ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) ); return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH ); } peer_key = mbedtls_pk_ec( *peer_pk ); if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx, peer_key, MBEDTLS_ECDH_THEIRS ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret ); return( ret ); } if( ssl_check_server_ecdh_params( ssl ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server certificate (ECDH curve)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) /* We don't need the peer's public key anymore. Free it, * so that more RAM is available for upcoming expensive * operations like ECDHE. */ mbedtls_pk_free( peer_pk ); #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; unsigned char *p = NULL, *end = NULL; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) ); #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) ); ssl->state++; return( 0 ); } ((void) p); ((void) end); #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA ) { if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) ); ssl->state++; return( 0 ); } ((void) p); ((void) end); #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled && ssl->handshake->ecrs_state == ssl_ecrs_ske_start_processing ) { goto start_processing; } #endif if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } /* * ServerKeyExchange may be skipped with PSK and RSA-PSK when the server * doesn't use a psk_identity_hint */ if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE ) { if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) { /* Current message is probably either * CertificateRequest or ServerHelloDone */ ssl->keep_current_message = 1; goto exit; } MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key exchange message must not be skipped" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled ) ssl->handshake->ecrs_state = ssl_ecrs_ske_start_processing; start_processing: #endif p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); end = ssl->in_msg + ssl->in_hslen; MBEDTLS_SSL_DEBUG_BUF( 3, "server key exchange", p, end - p ); #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) { if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } /* FALLTROUGH */ #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) ; /* nothing more to do */ else #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED || MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ) { if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ) { if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx, p, end - p ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) ) { size_t sig_len, hashlen; unsigned char hash[64]; mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE; mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE; unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); size_t params_len = p - params; void *rs_ctx = NULL; mbedtls_pk_context * peer_pk; /* * Handle the digitally-signed structure */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { if( ssl_parse_signature_algorithm( ssl, &p, end, &md_alg, &pk_alg ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 ) { pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ); /* Default hash for ECDSA is SHA-1 */ if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE ) md_alg = MBEDTLS_MD_SHA1; } else #endif { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* * Read signature */ if( p > end - 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } sig_len = ( p[0] << 8 ) | p[1]; p += 2; if( p != end - sig_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } MBEDTLS_SSL_DEBUG_BUF( 3, "signature", p, sig_len ); /* * Compute the hash that has been signed */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( md_alg == MBEDTLS_MD_NONE ) { hashlen = 36; ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params, params_len ); if( ret != 0 ) return( ret ); } else #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \ MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( md_alg != MBEDTLS_MD_NONE ) { ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, &hashlen, params, params_len, md_alg ); if( ret != 0 ) return( ret ); } else #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen ); #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) peer_pk = &ssl->handshake->peer_pubkey; #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( ssl->session_negotiate->peer_cert == NULL ) { /* Should never happen */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } peer_pk = &ssl->session_negotiate->peer_cert->pk; #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ /* * Verify signature */ if( !mbedtls_pk_can_do( peer_pk, pk_alg ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH ); } #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled ) rs_ctx = &ssl->handshake->ecrs_ctx.pk; #endif if( ( ret = mbedtls_pk_verify_restartable( peer_pk, md_alg, hash, hashlen, p, sig_len, rs_ctx ) ) != 0 ) { #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) #endif mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR ); MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret ); #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS; #endif return( ret ); } #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) /* We don't need the peer's public key anymore. Free it, * so that more RAM is available for upcoming expensive * operations like ECDHE. */ mbedtls_pk_free( peer_pk ); #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ } #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */ exit: ssl->state++; MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) ); return( 0 ); } #if ! defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED) static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) ); if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) ); ssl->state++; return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #else /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char *buf; size_t n = 0; size_t cert_type_len = 0, dn_len = 0; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) ); if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) ); ssl->state++; return( 0 ); } if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } ssl->state++; ssl->client_auth = ( ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE_REQUEST ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "got %s certificate request", ssl->client_auth ? "a" : "no" ) ); if( ssl->client_auth == 0 ) { /* Current message is probably the ServerHelloDone */ ssl->keep_current_message = 1; goto exit; } /* * struct { * ClientCertificateType certificate_types<1..2^8-1>; * SignatureAndHashAlgorithm * supported_signature_algorithms<2^16-1>; -- TLS 1.2 only * DistinguishedName certificate_authorities<0..2^16-1>; * } CertificateRequest; * * Since we only support a single certificate on clients, let's just * ignore all the information that's supposed to help us pick a * certificate. * * We could check that our certificate matches the request, and bail out * if it doesn't, but it's simpler to just send the certificate anyway, * and give the server the opportunity to decide if it should terminate * the connection when it doesn't like our certificate. * * Same goes for the hash in TLS 1.2's signature_algorithms: at this * point we only have one hash available (see comments in * write_certificate_verify), so let's just use what we have. * * However, we still minimally parse the message to check it is at least * superficially sane. */ buf = ssl->in_msg; /* certificate_types */ if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST ); } cert_type_len = buf[mbedtls_ssl_hs_hdr_len( ssl )]; n = cert_type_len; /* * In the subsequent code there are two paths that read from buf: * * the length of the signature algorithms field (if minor version of * SSL is 3), * * distinguished name length otherwise. * Both reach at most the index: * ...hdr_len + 2 + n, * therefore the buffer length at this point must be greater than that * regardless of the actual code path. */ if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST ); } /* supported_signature_algorithms */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { size_t sig_alg_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] << 8 ) | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n] ) ); #if defined(MBEDTLS_DEBUG_C) unsigned char* sig_alg; size_t i; #endif /* * The furthest access in buf is in the loop few lines below: * sig_alg[i + 1], * where: * sig_alg = buf + ...hdr_len + 3 + n, * max(i) = sig_alg_len - 1. * Therefore the furthest access is: * buf[...hdr_len + 3 + n + sig_alg_len - 1 + 1], * which reduces to: * buf[...hdr_len + 3 + n + sig_alg_len], * which is one less than we need the buf to be. */ if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n + sig_alg_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST ); } #if defined(MBEDTLS_DEBUG_C) sig_alg = buf + mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n; for( i = 0; i < sig_alg_len; i += 2 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Supported Signature Algorithm found: %d,%d", sig_alg[i], sig_alg[i + 1] ) ); } #endif n += 2 + sig_alg_len; } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ /* certificate_authorities */ dn_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] << 8 ) | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n] ) ); n += dn_len; if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST ); } exit: MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate request" ) ); return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ static int ssl_parse_server_hello_done( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello done" ) ); if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) || ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_HELLO_DONE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE ); } ssl->state++; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_recv_flight_completed( ssl ); #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello done" ) ); return( 0 ); } static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t header_len; size_t content_len; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client key exchange" ) ); #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ) { /* * DHM key exchange -- send G^X mod P */ content_len = ssl->handshake->dhm_ctx.len; ssl->out_msg[4] = (unsigned char)( content_len >> 8 ); ssl->out_msg[5] = (unsigned char)( content_len ); header_len = 6; ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx, (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ), &ssl->out_msg[header_len], content_len, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X ); MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX ); if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx, ssl->handshake->premaster, MBEDTLS_PREMASTER_SIZE, &ssl->handshake->pmslen, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K ); } else #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA ) { /* * ECDH key exchange -- send client public value */ header_len = 4; #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled ) { if( ssl->handshake->ecrs_state == ssl_ecrs_cke_ecdh_calc_secret ) goto ecdh_calc_secret; mbedtls_ecdh_enable_restart( &ssl->handshake->ecdh_ctx ); } #endif ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx, &content_len, &ssl->out_msg[header_len], 1000, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret ); #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS; #endif return( ret ); } MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_Q ); #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled ) { ssl->handshake->ecrs_n = content_len; ssl->handshake->ecrs_state = ssl_ecrs_cke_ecdh_calc_secret; } ecdh_calc_secret: if( ssl->handshake->ecrs_enabled ) content_len = ssl->handshake->ecrs_n; #endif if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &ssl->handshake->pmslen, ssl->handshake->premaster, MBEDTLS_MPI_MAX_SIZE, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret ); #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS; #endif return( ret ); } MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_Z ); } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) if( mbedtls_ssl_ciphersuite_uses_psk( ciphersuite_info ) ) { /* * opaque psk_identity<0..2^16-1>; */ if( ssl_conf_has_static_psk( ssl->conf ) == 0 ) { /* We don't offer PSK suites if we don't have a PSK, * and we check that the server's choice is among the * ciphersuites we offered, so this should never happen. */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } header_len = 4; content_len = ssl->conf->psk_identity_len; if( header_len + 2 + content_len > MBEDTLS_SSL_OUT_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity too long or SSL buffer too short" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } ssl->out_msg[header_len++] = (unsigned char)( content_len >> 8 ); ssl->out_msg[header_len++] = (unsigned char)( content_len ); memcpy( ssl->out_msg + header_len, ssl->conf->psk_identity, ssl->conf->psk_identity_len ); header_len += ssl->conf->psk_identity_len; #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ) { content_len = 0; } else #endif #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) { if( ( ret = ssl_write_encrypted_pms( ssl, header_len, &content_len, 2 ) ) != 0 ) return( ret ); } else #endif #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ) { /* * ClientDiffieHellmanPublic public (DHM send G^X mod P) */ content_len = ssl->handshake->dhm_ctx.len; if( header_len + 2 + content_len > MBEDTLS_SSL_OUT_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity or DHM size too long or SSL buffer too short" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } ssl->out_msg[header_len++] = (unsigned char)( content_len >> 8 ); ssl->out_msg[header_len++] = (unsigned char)( content_len ); ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx, (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ), &ssl->out_msg[header_len], content_len, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) { /* * ClientECDiffieHellmanPublic public; */ ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx, &content_len, &ssl->out_msg[header_len], MBEDTLS_SSL_OUT_CONTENT_LEN - header_len, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_Q ); } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl, ciphersuite_info->key_exchange ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA ) { header_len = 4; if( ( ret = ssl_write_encrypted_pms( ssl, header_len, &content_len, 0 ) ) != 0 ) return( ret ); } else #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { header_len = 4; ret = mbedtls_ecjpake_write_round_two( &ssl->handshake->ecjpake_ctx, ssl->out_msg + header_len, MBEDTLS_SSL_OUT_CONTENT_LEN - header_len, &content_len, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret ); return( ret ); } ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx, ssl->handshake->premaster, 32, &ssl->handshake->pmslen, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */ { ((void) ciphersuite_info); MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } ssl->out_msglen = header_len + content_len; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE; ssl->state++; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client key exchange" ) ); return( 0 ); } #if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED) static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; int ret = MBEDTLS_ERR_THIS_CORRUPTION; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) ); if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret ); return( ret ); } if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) ); ssl->state++; return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; size_t n = 0, offset = 0; unsigned char hash[48]; unsigned char *hash_start = hash; mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE; size_t hashlen; void *rs_ctx = NULL; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) ); #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled && ssl->handshake->ecrs_state == ssl_ecrs_crt_vrfy_sign ) { goto sign; } #endif if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret ); return( ret ); } if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) ); ssl->state++; return( 0 ); } if( ssl->client_auth == 0 || mbedtls_ssl_own_cert( ssl ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) ); ssl->state++; return( 0 ); } if( mbedtls_ssl_own_key( ssl ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for certificate" ) ); return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); } /* * Make a signature of the handshake digests */ #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled ) ssl->handshake->ecrs_state = ssl_ecrs_crt_vrfy_sign; sign: #endif ssl->handshake->calc_verify( ssl, hash, &hashlen ); #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 ) { /* * digitally-signed struct { * opaque md5_hash[16]; * opaque sha_hash[20]; * }; * * md5_hash * MD5(handshake_messages); * * sha_hash * SHA(handshake_messages); */ md_alg = MBEDTLS_MD_NONE; /* * For ECDSA, default hash is SHA-1 only */ if( mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECDSA ) ) { hash_start += 16; hashlen -= 16; md_alg = MBEDTLS_MD_SHA1; } } else #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \ MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { /* * digitally-signed struct { * opaque handshake_messages[handshake_messages_length]; * }; * * Taking shortcut here. We assume that the server always allows the * PRF Hash function and has sent it in the allowed signature * algorithms list received in the Certificate Request message. * * Until we encounter a server that does not, we will take this * shortcut. * * Reason: Otherwise we should have running hashes for SHA512 and * SHA224 in order to satisfy 'weird' needs from the server * side. */ if( ssl->handshake->ciphersuite_info->mac == MBEDTLS_MD_SHA384 ) { md_alg = MBEDTLS_MD_SHA384; ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA384; } else { md_alg = MBEDTLS_MD_SHA256; ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA256; } ssl->out_msg[5] = mbedtls_ssl_sig_from_pk( mbedtls_ssl_own_key( ssl ) ); /* Info from md_alg will be used instead */ hashlen = 0; offset = 2; } else #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ssl->handshake->ecrs_enabled ) rs_ctx = &ssl->handshake->ecrs_ctx.pk; #endif if( ( ret = mbedtls_pk_sign_restartable( mbedtls_ssl_own_key( ssl ), md_alg, hash_start, hashlen, ssl->out_msg + 6 + offset, &n, ssl->conf->f_rng, ssl->conf->p_rng, rs_ctx ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret ); #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS; #endif return( ret ); } ssl->out_msg[4 + offset] = (unsigned char)( n >> 8 ); ssl->out_msg[5 + offset] = (unsigned char)( n ); ssl->out_msglen = 6 + n + offset; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE_VERIFY; ssl->state++; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate verify" ) ); return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) static int ssl_parse_new_session_ticket( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; uint32_t lifetime; size_t ticket_len; unsigned char *ticket; const unsigned char *msg; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse new session ticket" ) ); if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } /* * struct { * uint32 ticket_lifetime_hint; * opaque ticket<0..2^16-1>; * } NewSessionTicket; * * 0 . 3 ticket_lifetime_hint * 4 . 5 ticket_len (n) * 6 . 5+n ticket content */ if( ssl->in_msg[0] != MBEDTLS_SSL_HS_NEW_SESSION_TICKET || ssl->in_hslen < 6 + mbedtls_ssl_hs_hdr_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET ); } msg = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); lifetime = ( ((uint32_t) msg[0]) << 24 ) | ( msg[1] << 16 ) | ( msg[2] << 8 ) | ( msg[3] ); ticket_len = ( msg[4] << 8 ) | ( msg[5] ); if( ticket_len + 6 + mbedtls_ssl_hs_hdr_len( ssl ) != ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %" MBEDTLS_PRINTF_SIZET, ticket_len ) ); /* We're not waiting for a NewSessionTicket message any more */ ssl->handshake->new_session_ticket = 0; ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC; /* * Zero-length ticket means the server changed his mind and doesn't want * to send a ticket after all, so just forget it */ if( ticket_len == 0 ) return( 0 ); if( ssl->session != NULL && ssl->session->ticket != NULL ) { mbedtls_platform_zeroize( ssl->session->ticket, ssl->session->ticket_len ); mbedtls_free( ssl->session->ticket ); ssl->session->ticket = NULL; ssl->session->ticket_len = 0; } mbedtls_platform_zeroize( ssl->session_negotiate->ticket, ssl->session_negotiate->ticket_len ); mbedtls_free( ssl->session_negotiate->ticket ); ssl->session_negotiate->ticket = NULL; ssl->session_negotiate->ticket_len = 0; if( ( ticket = mbedtls_calloc( 1, ticket_len ) ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "ticket alloc failed" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } memcpy( ticket, msg + 6, ticket_len ); ssl->session_negotiate->ticket = ticket; ssl->session_negotiate->ticket_len = ticket_len; ssl->session_negotiate->ticket_lifetime = lifetime; /* * RFC 5077 section 3.4: * "If the client receives a session ticket from the server, then it * discards any Session ID that was sent in the ServerHello." */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket in use, discarding session id" ) ); ssl->session_negotiate->id_len = 0; MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse new session ticket" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ /** * \brief Perform a single step of the SSL client handshake * * \note The state of the context (ssl->state) will be at * the next state after this function returns \c 0. Do not * call this function if state is MBEDTLS_SSL_HANDSHAKE_OVER. * * \param ssl SSL context * * \return See mbedtls_ssl_handshake(). * * \warning If this function returns something other than \c 0, * #MBEDTLS_ERR_SSL_WANT_READ, #MBEDTLS_ERR_SSL_WANT_WRITE, * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS, you must stop using * the SSL context for reading or writing, and either free it * or call \c mbedtls_ssl_session_reset() on it before * re-using it for a new connection; the current connection * must be closed. */ int mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl ) { int ret = 0; if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "client state: %d", ssl->state ) ); if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) return( ret ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING ) { if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 ) return( ret ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* Change state now, so that it is right in mbedtls_ssl_read_record(), used * by DTLS for dropping out-of-sequence ChangeCipherSpec records */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) if( ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC && ssl->handshake->new_session_ticket != 0 ) { ssl->state = MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET; } #endif switch( ssl->state ) { case MBEDTLS_SSL_HELLO_REQUEST: ssl->state = MBEDTLS_SSL_CLIENT_HELLO; break; /* * ==> ClientHello */ case MBEDTLS_SSL_CLIENT_HELLO: ret = ssl_write_client_hello( ssl ); break; /* * <== ServerHello * Certificate * ( ServerKeyExchange ) * ( CertificateRequest ) * ServerHelloDone */ case MBEDTLS_SSL_SERVER_HELLO: ret = ssl_parse_server_hello( ssl ); break; case MBEDTLS_SSL_SERVER_CERTIFICATE: ret = mbedtls_ssl_parse_certificate( ssl ); break; case MBEDTLS_SSL_SERVER_KEY_EXCHANGE: ret = ssl_parse_server_key_exchange( ssl ); break; case MBEDTLS_SSL_CERTIFICATE_REQUEST: ret = ssl_parse_certificate_request( ssl ); break; case MBEDTLS_SSL_SERVER_HELLO_DONE: ret = ssl_parse_server_hello_done( ssl ); break; /* * ==> ( Certificate/Alert ) * ClientKeyExchange * ( CertificateVerify ) * ChangeCipherSpec * Finished */ case MBEDTLS_SSL_CLIENT_CERTIFICATE: ret = mbedtls_ssl_write_certificate( ssl ); break; case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE: ret = ssl_write_client_key_exchange( ssl ); break; case MBEDTLS_SSL_CERTIFICATE_VERIFY: ret = ssl_write_certificate_verify( ssl ); break; case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC: ret = mbedtls_ssl_write_change_cipher_spec( ssl ); break; case MBEDTLS_SSL_CLIENT_FINISHED: ret = mbedtls_ssl_write_finished( ssl ); break; /* * <== ( NewSessionTicket ) * ChangeCipherSpec * Finished */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) case MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET: ret = ssl_parse_new_session_ticket( ssl ); break; #endif case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC: ret = mbedtls_ssl_parse_change_cipher_spec( ssl ); break; case MBEDTLS_SSL_SERVER_FINISHED: ret = mbedtls_ssl_parse_finished( ssl ); break; case MBEDTLS_SSL_FLUSH_BUFFERS: MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) ); ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP; break; case MBEDTLS_SSL_HANDSHAKE_WRAPUP: mbedtls_ssl_handshake_wrapup( ssl ); break; default: MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } return( ret ); } #endif /* MBEDTLS_SSL_CLI_C */
145,850
4,076
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/platform.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/mbedtls/platform.h" int mbedtls_platform_setup(mbedtls_platform_context *ctx) { return 0; } void mbedtls_platform_teardown(mbedtls_platform_context *ctx) { }
1,935
26
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/bigshift.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/macros.internal.h" #include "libc/str/str.h" #include "third_party/mbedtls/bignum.h" #include "third_party/mbedtls/bignum_internal.h" #include "third_party/mbedtls/platform.h" /* clang-format off */ typedef long long xmm_t __attribute__((__vector_size__(16), __aligned__(1))); static inline void shrd(mbedtls_mpi_uint *p, size_t n, size_t j, size_t m, char k) { mbedtls_mpi_uint x, y, *e, *f; f = p + m; if (n) { y = 0; x = p[j]; e = p + n; for (; ++p < e; x = y) { y = p[j]; p[-1] = x >> k | y << (biL - k); } p[-1] = x >> k; } while (p < f) *p++ = 0; } static inline void shld(mbedtls_mpi_uint *p, size_t n, size_t m, char k) { size_t i; mbedtls_mpi_uint x, y; MBEDTLS_ASSERT(n > m); i = n - 1; y = p[i - m]; for (; i - m > 0; --i, y = x) { x = p[i - m - 1]; p[i] = y << k | x >> (64 - k); } p[i] = y << k; while (i) { p[--i] = 0; } } /** * Performs left shift on big number: X <<= k */ int mbedtls_mpi_shift_l(mbedtls_mpi *X, size_t k) { int r; size_t b, n, m, l, z; MPI_VALIDATE_RET(X); l = mbedtls_mpi_bitlen(X); b = l + k; n = BITS_TO_LIMBS(b); m = k / biL; k = k % biL; z = X->n; if (n > X->n && (r = mbedtls_mpi_grow(X, n))) return r; if (k) { shld(X->p, X->n, m, k); } else if (m) { memmove(X->p + m, X->p, (X->n - m) * ciL); explicit_bzero(X->p, m * ciL); } return 0; } void ShiftRightPure(mbedtls_mpi_uint *p, size_t n, unsigned char k) { shrd(p, n, 0, n, k); } /** * Performs right arithmetic shift on big number: X >>= k */ int mbedtls_mpi_shift_r(mbedtls_mpi *X, size_t k) { size_t n; mbedtls_mpi_uint x, y; MPI_VALIDATE_RET(X); k = MIN(k, X->n * biL); n = k / biL; k = k % biL; if (k) { if (!n) ShiftRight(X->p, X->n, k); else shrd(X->p, X->n - n, n, X->n, k); } else if (n) { memmove(X->p, X->p + n, (X->n - n) * ciL); explicit_bzero(X->p + X->n - n, n * ciL); } return 0; }
3,988
124
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/entropy_poll.h
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_ENTROPY_POLL_H_ #define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_ENTROPY_POLL_H_ COSMOPOLITAN_C_START_ int mbedtls_null_entropy_poll(void *, unsigned char *, size_t, size_t *); int mbedtls_platform_entropy_poll(void *, unsigned char *, size_t, size_t *); int mbedtls_hardclock_poll(void *, unsigned char *, size_t, size_t *); int mbedtls_hardware_poll(void *, unsigned char *, size_t, size_t *); COSMOPOLITAN_C_END_ /* clang-format off */ #define MBEDTLS_ENTROPY_MIN_PLATFORM 32 /*< Minimum for platform source */ #define MBEDTLS_ENTROPY_MIN_HARDCLOCK 4 /*< Minimum for mbedtls_timing_hardclock() */ #define MBEDTLS_ENTROPY_MIN_HARDWARE 32 /*< Minimum for the hardware source */ #endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_ENTROPY_POLL_H_ */
810
16
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/oid.h
#ifndef MBEDTLS_OID_H #define MBEDTLS_OID_H #include "third_party/mbedtls/asn1.h" #include "third_party/mbedtls/cipher.h" #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/md.h" #include "third_party/mbedtls/pk.h" /* clang-format off */ #define MBEDTLS_ERR_OID_NOT_FOUND -0x002E /*< OID is not found. */ #define MBEDTLS_ERR_OID_BUF_TOO_SMALL -0x000B /*< output buffer is too small */ /* This is for the benefit of X.509, but defined here in order to avoid * having a "backwards" include of x.509.h here */ /* * X.509 extension types (internal, arbitrary values for bitsets) */ #define MBEDTLS_OID_X509_EXT_AUTHORITY_KEY_IDENTIFIER (1 << 0) #define MBEDTLS_OID_X509_EXT_SUBJECT_KEY_IDENTIFIER (1 << 1) #define MBEDTLS_OID_X509_EXT_KEY_USAGE (1 << 2) #define MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES (1 << 3) #define MBEDTLS_OID_X509_EXT_POLICY_MAPPINGS (1 << 4) #define MBEDTLS_OID_X509_EXT_SUBJECT_ALT_NAME (1 << 5) #define MBEDTLS_OID_X509_EXT_ISSUER_ALT_NAME (1 << 6) #define MBEDTLS_OID_X509_EXT_SUBJECT_DIRECTORY_ATTRS (1 << 7) #define MBEDTLS_OID_X509_EXT_BASIC_CONSTRAINTS (1 << 8) #define MBEDTLS_OID_X509_EXT_NAME_CONSTRAINTS (1 << 9) #define MBEDTLS_OID_X509_EXT_POLICY_CONSTRAINTS (1 << 10) #define MBEDTLS_OID_X509_EXT_EXTENDED_KEY_USAGE (1 << 11) #define MBEDTLS_OID_X509_EXT_CRL_DISTRIBUTION_POINTS (1 << 12) #define MBEDTLS_OID_X509_EXT_INIHIBIT_ANYPOLICY (1 << 13) #define MBEDTLS_OID_X509_EXT_FRESHEST_CRL (1 << 14) #define MBEDTLS_OID_X509_EXT_NS_CERT_TYPE (1 << 16) /* * Top level OID tuples */ #define MBEDTLS_OID_ISO_MEMBER_BODIES "\x2a" /* {iso(1) member-body(2)} */ #define MBEDTLS_OID_ISO_IDENTIFIED_ORG "\x2b" /* {iso(1) identified-organization(3)} */ #define MBEDTLS_OID_ISO_CCITT_DS "\x55" /* {joint-iso-ccitt(2) ds(5)} */ #define MBEDTLS_OID_ISO_ITU_COUNTRY "\x60" /* {joint-iso-itu-t(2) country(16)} */ /* * ISO Member bodies OID parts */ #define MBEDTLS_OID_COUNTRY_US "\x86\x48" /* {us(840)} */ #define MBEDTLS_OID_ORG_RSA_DATA_SECURITY "\x86\xf7\x0d" /* {rsadsi(113549)} */ #define MBEDTLS_OID_RSA_COMPANY MBEDTLS_OID_ISO_MEMBER_BODIES MBEDTLS_OID_COUNTRY_US \ MBEDTLS_OID_ORG_RSA_DATA_SECURITY /* {iso(1) member-body(2) us(840) rsadsi(113549)} */ #define MBEDTLS_OID_ORG_ANSI_X9_62 "\xce\x3d" /* ansi-X9-62(10045) */ #define MBEDTLS_OID_ANSI_X9_62 MBEDTLS_OID_ISO_MEMBER_BODIES MBEDTLS_OID_COUNTRY_US \ MBEDTLS_OID_ORG_ANSI_X9_62 /* * ISO Identified organization OID parts */ #define MBEDTLS_OID_ORG_DOD "\x06" /* {dod(6)} */ #define MBEDTLS_OID_ORG_OIW "\x0e" #define MBEDTLS_OID_OIW_SECSIG MBEDTLS_OID_ORG_OIW "\x03" #define MBEDTLS_OID_OIW_SECSIG_ALG MBEDTLS_OID_OIW_SECSIG "\x02" #define MBEDTLS_OID_OIW_SECSIG_SHA1 MBEDTLS_OID_OIW_SECSIG_ALG "\x1a" #define MBEDTLS_OID_ORG_CERTICOM "\x81\x04" /* certicom(132) */ #define MBEDTLS_OID_CERTICOM MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_ORG_CERTICOM #define MBEDTLS_OID_ORG_TELETRUST "\x24" /* teletrust(36) */ #define MBEDTLS_OID_TELETRUST MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_ORG_TELETRUST /* * ISO ITU OID parts */ #define MBEDTLS_OID_ORGANIZATION "\x01" /* {organization(1)} */ #define MBEDTLS_OID_ISO_ITU_US_ORG MBEDTLS_OID_ISO_ITU_COUNTRY MBEDTLS_OID_COUNTRY_US MBEDTLS_OID_ORGANIZATION /* {joint-iso-itu-t(2) country(16) us(840) organization(1)} */ #define MBEDTLS_OID_ORG_GOV "\x65" /* {gov(101)} */ #define MBEDTLS_OID_GOV MBEDTLS_OID_ISO_ITU_US_ORG MBEDTLS_OID_ORG_GOV /* {joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101)} */ #define MBEDTLS_OID_ORG_NETSCAPE "\x86\xF8\x42" /* {netscape(113730)} */ #define MBEDTLS_OID_NETSCAPE MBEDTLS_OID_ISO_ITU_US_ORG MBEDTLS_OID_ORG_NETSCAPE /* Netscape OID {joint-iso-itu-t(2) country(16) us(840) organization(1) netscape(113730)} */ /* ISO arc for standard certificate and CRL extensions */ #define MBEDTLS_OID_ID_CE MBEDTLS_OID_ISO_CCITT_DS "\x1D" /*< id-ce OBJECT IDENTIFIER ::= {joint-iso-ccitt(2) ds(5) 29} */ #define MBEDTLS_OID_NIST_ALG MBEDTLS_OID_GOV "\x03\x04" /** { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) */ /** * Private Internet Extensions * { iso(1) identified-organization(3) dod(6) internet(1) * security(5) mechanisms(5) pkix(7) } */ #define MBEDTLS_OID_INTERNET MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_ORG_DOD "\x01" #define MBEDTLS_OID_PKIX MBEDTLS_OID_INTERNET "\x05\x05\x07" /* * Arc for standard naming attributes */ #define MBEDTLS_OID_AT MBEDTLS_OID_ISO_CCITT_DS "\x04" /*< id-at OBJECT IDENTIFIER ::= {joint-iso-ccitt(2) ds(5) 4} */ #define MBEDTLS_OID_AT_CN MBEDTLS_OID_AT "\x03" /*< id-at-commonName AttributeType:= {id-at 3} */ #define MBEDTLS_OID_AT_SUR_NAME MBEDTLS_OID_AT "\x04" /*< id-at-surName AttributeType:= {id-at 4} */ #define MBEDTLS_OID_AT_SERIAL_NUMBER MBEDTLS_OID_AT "\x05" /*< id-at-serialNumber AttributeType:= {id-at 5} */ #define MBEDTLS_OID_AT_COUNTRY MBEDTLS_OID_AT "\x06" /*< id-at-countryName AttributeType:= {id-at 6} */ #define MBEDTLS_OID_AT_LOCALITY MBEDTLS_OID_AT "\x07" /*< id-at-locality AttributeType:= {id-at 7} */ #define MBEDTLS_OID_AT_STATE MBEDTLS_OID_AT "\x08" /*< id-at-state AttributeType:= {id-at 8} */ #define MBEDTLS_OID_AT_ORGANIZATION MBEDTLS_OID_AT "\x0A" /*< id-at-organizationName AttributeType:= {id-at 10} */ #define MBEDTLS_OID_AT_ORG_UNIT MBEDTLS_OID_AT "\x0B" /*< id-at-organizationalUnitName AttributeType:= {id-at 11} */ #define MBEDTLS_OID_AT_TITLE MBEDTLS_OID_AT "\x0C" /*< id-at-title AttributeType:= {id-at 12} */ #define MBEDTLS_OID_AT_POSTAL_ADDRESS MBEDTLS_OID_AT "\x10" /*< id-at-postalAddress AttributeType:= {id-at 16} */ #define MBEDTLS_OID_AT_POSTAL_CODE MBEDTLS_OID_AT "\x11" /*< id-at-postalCode AttributeType:= {id-at 17} */ #define MBEDTLS_OID_AT_GIVEN_NAME MBEDTLS_OID_AT "\x2A" /*< id-at-givenName AttributeType:= {id-at 42} */ #define MBEDTLS_OID_AT_INITIALS MBEDTLS_OID_AT "\x2B" /*< id-at-initials AttributeType:= {id-at 43} */ #define MBEDTLS_OID_AT_GENERATION_QUALIFIER MBEDTLS_OID_AT "\x2C" /*< id-at-generationQualifier AttributeType:= {id-at 44} */ #define MBEDTLS_OID_AT_UNIQUE_IDENTIFIER MBEDTLS_OID_AT "\x2D" /*< id-at-uniqueIdentifier AttributType:= {id-at 45} */ #define MBEDTLS_OID_AT_DN_QUALIFIER MBEDTLS_OID_AT "\x2E" /*< id-at-dnQualifier AttributeType:= {id-at 46} */ #define MBEDTLS_OID_AT_PSEUDONYM MBEDTLS_OID_AT "\x41" /*< id-at-pseudonym AttributeType:= {id-at 65} */ #define MBEDTLS_OID_DOMAIN_COMPONENT "\x09\x92\x26\x89\x93\xF2\x2C\x64\x01\x19" /** id-domainComponent AttributeType:= {itu-t(0) data(9) pss(2342) ucl(19200300) pilot(100) pilotAttributeType(1) domainComponent(25)} */ /* * OIDs for standard certificate extensions */ #define MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER MBEDTLS_OID_ID_CE "\x23" /*< id-ce-authorityKeyIdentifier OBJECT IDENTIFIER ::= { id-ce 35 } */ #define MBEDTLS_OID_SUBJECT_KEY_IDENTIFIER MBEDTLS_OID_ID_CE "\x0E" /*< id-ce-subjectKeyIdentifier OBJECT IDENTIFIER ::= { id-ce 14 } */ #define MBEDTLS_OID_KEY_USAGE MBEDTLS_OID_ID_CE "\x0F" /*< id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 } */ #define MBEDTLS_OID_CERTIFICATE_POLICIES MBEDTLS_OID_ID_CE "\x20" /*< id-ce-certificatePolicies OBJECT IDENTIFIER ::= { id-ce 32 } */ #define MBEDTLS_OID_POLICY_MAPPINGS MBEDTLS_OID_ID_CE "\x21" /*< id-ce-policyMappings OBJECT IDENTIFIER ::= { id-ce 33 } */ #define MBEDTLS_OID_SUBJECT_ALT_NAME MBEDTLS_OID_ID_CE "\x11" /*< id-ce-subjectAltName OBJECT IDENTIFIER ::= { id-ce 17 } */ #define MBEDTLS_OID_ISSUER_ALT_NAME MBEDTLS_OID_ID_CE "\x12" /*< id-ce-issuerAltName OBJECT IDENTIFIER ::= { id-ce 18 } */ #define MBEDTLS_OID_SUBJECT_DIRECTORY_ATTRS MBEDTLS_OID_ID_CE "\x09" /*< id-ce-subjectDirectoryAttributes OBJECT IDENTIFIER ::= { id-ce 9 } */ #define MBEDTLS_OID_BASIC_CONSTRAINTS MBEDTLS_OID_ID_CE "\x13" /*< id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 } */ #define MBEDTLS_OID_NAME_CONSTRAINTS MBEDTLS_OID_ID_CE "\x1E" /*< id-ce-nameConstraints OBJECT IDENTIFIER ::= { id-ce 30 } */ #define MBEDTLS_OID_POLICY_CONSTRAINTS MBEDTLS_OID_ID_CE "\x24" /*< id-ce-policyConstraints OBJECT IDENTIFIER ::= { id-ce 36 } */ #define MBEDTLS_OID_EXTENDED_KEY_USAGE MBEDTLS_OID_ID_CE "\x25" /*< id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 } */ #define MBEDTLS_OID_CRL_DISTRIBUTION_POINTS MBEDTLS_OID_ID_CE "\x1F" /*< id-ce-cRLDistributionPoints OBJECT IDENTIFIER ::= { id-ce 31 } */ #define MBEDTLS_OID_INIHIBIT_ANYPOLICY MBEDTLS_OID_ID_CE "\x36" /*< id-ce-inhibitAnyPolicy OBJECT IDENTIFIER ::= { id-ce 54 } */ #define MBEDTLS_OID_FRESHEST_CRL MBEDTLS_OID_ID_CE "\x2E" /*< id-ce-freshestCRL OBJECT IDENTIFIER ::= { id-ce 46 } */ /* * Certificate policies */ #define MBEDTLS_OID_ANY_POLICY MBEDTLS_OID_CERTIFICATE_POLICIES "\x00" /*< anyPolicy OBJECT IDENTIFIER ::= { id-ce-certificatePolicies 0 } */ /* * Netscape certificate extensions */ #define MBEDTLS_OID_NS_CERT MBEDTLS_OID_NETSCAPE "\x01" #define MBEDTLS_OID_NS_CERT_TYPE MBEDTLS_OID_NS_CERT "\x01" #define MBEDTLS_OID_NS_BASE_URL MBEDTLS_OID_NS_CERT "\x02" #define MBEDTLS_OID_NS_REVOCATION_URL MBEDTLS_OID_NS_CERT "\x03" #define MBEDTLS_OID_NS_CA_REVOCATION_URL MBEDTLS_OID_NS_CERT "\x04" #define MBEDTLS_OID_NS_RENEWAL_URL MBEDTLS_OID_NS_CERT "\x07" #define MBEDTLS_OID_NS_CA_POLICY_URL MBEDTLS_OID_NS_CERT "\x08" #define MBEDTLS_OID_NS_SSL_SERVER_NAME MBEDTLS_OID_NS_CERT "\x0C" #define MBEDTLS_OID_NS_COMMENT MBEDTLS_OID_NS_CERT "\x0D" #define MBEDTLS_OID_NS_DATA_TYPE MBEDTLS_OID_NETSCAPE "\x02" #define MBEDTLS_OID_NS_CERT_SEQUENCE MBEDTLS_OID_NS_DATA_TYPE "\x05" /* * OIDs for CRL extensions */ #define MBEDTLS_OID_PRIVATE_KEY_USAGE_PERIOD MBEDTLS_OID_ID_CE "\x10" #define MBEDTLS_OID_CRL_NUMBER MBEDTLS_OID_ID_CE "\x14" /*< id-ce-cRLNumber OBJECT IDENTIFIER ::= { id-ce 20 } */ /* * X.509 v3 Extended key usage OIDs */ #define MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE MBEDTLS_OID_EXTENDED_KEY_USAGE "\x00" /*< anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 } */ #define MBEDTLS_OID_KP MBEDTLS_OID_PKIX "\x03" /*< id-kp OBJECT IDENTIFIER ::= { id-pkix 3 } */ #define MBEDTLS_OID_SERVER_AUTH MBEDTLS_OID_KP "\x01" /*< id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 } */ #define MBEDTLS_OID_CLIENT_AUTH MBEDTLS_OID_KP "\x02" /*< id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 } */ #define MBEDTLS_OID_CODE_SIGNING MBEDTLS_OID_KP "\x03" /*< id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 } */ #define MBEDTLS_OID_EMAIL_PROTECTION MBEDTLS_OID_KP "\x04" /*< id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 } */ #define MBEDTLS_OID_TIME_STAMPING MBEDTLS_OID_KP "\x08" /*< id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 } */ #define MBEDTLS_OID_OCSP_SIGNING MBEDTLS_OID_KP "\x09" /*< id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 } */ #define MBEDTLS_OID_ON MBEDTLS_OID_PKIX "\x08" /*< id-on OBJECT IDENTIFIER ::= { id-pkix 8 } */ #define MBEDTLS_OID_ON_HW_MODULE_NAME MBEDTLS_OID_ON "\x04" /*< id-on-hardwareModuleName OBJECT IDENTIFIER ::= { id-on 4 } */ /* * PKCS definition OIDs */ #define MBEDTLS_OID_PKCS MBEDTLS_OID_RSA_COMPANY "\x01" /*< pkcs OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) 1 } */ #define MBEDTLS_OID_PKCS1 MBEDTLS_OID_PKCS "\x01" /*< pkcs-1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 } */ #define MBEDTLS_OID_PKCS5 MBEDTLS_OID_PKCS "\x05" /*< pkcs-5 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 5 } */ #define MBEDTLS_OID_PKCS9 MBEDTLS_OID_PKCS "\x09" /*< pkcs-9 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 9 } */ #define MBEDTLS_OID_PKCS12 MBEDTLS_OID_PKCS "\x0c" /*< pkcs-12 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 12 } */ /* * PKCS#1 OIDs */ #define MBEDTLS_OID_PKCS1_RSA MBEDTLS_OID_PKCS1 "\x01" /*< rsaEncryption OBJECT IDENTIFIER ::= { pkcs-1 1 } */ #define MBEDTLS_OID_PKCS1_MD2 MBEDTLS_OID_PKCS1 "\x02" /*< md2WithRSAEncryption ::= { pkcs-1 2 } */ #define MBEDTLS_OID_PKCS1_MD4 MBEDTLS_OID_PKCS1 "\x03" /*< md4WithRSAEncryption ::= { pkcs-1 3 } */ #define MBEDTLS_OID_PKCS1_MD5 MBEDTLS_OID_PKCS1 "\x04" /*< md5WithRSAEncryption ::= { pkcs-1 4 } */ #define MBEDTLS_OID_PKCS1_SHA1 MBEDTLS_OID_PKCS1 "\x05" /*< sha1WithRSAEncryption ::= { pkcs-1 5 } */ #define MBEDTLS_OID_PKCS1_SHA224 MBEDTLS_OID_PKCS1 "\x0e" /*< sha224WithRSAEncryption ::= { pkcs-1 14 } */ #define MBEDTLS_OID_PKCS1_SHA256 MBEDTLS_OID_PKCS1 "\x0b" /*< sha256WithRSAEncryption ::= { pkcs-1 11 } */ #define MBEDTLS_OID_PKCS1_SHA384 MBEDTLS_OID_PKCS1 "\x0c" /*< sha384WithRSAEncryption ::= { pkcs-1 12 } */ #define MBEDTLS_OID_PKCS1_SHA512 MBEDTLS_OID_PKCS1 "\x0d" /*< sha512WithRSAEncryption ::= { pkcs-1 13 } */ #define MBEDTLS_OID_RSA_SHA_OBS "\x2B\x0E\x03\x02\x1D" #define MBEDTLS_OID_PKCS9_EMAIL MBEDTLS_OID_PKCS9 "\x01" /*< emailAddress AttributeType ::= { pkcs-9 1 } */ /* RFC 4055 */ #define MBEDTLS_OID_RSASSA_PSS MBEDTLS_OID_PKCS1 "\x0a" /*< id-RSASSA-PSS ::= { pkcs-1 10 } */ #define MBEDTLS_OID_MGF1 MBEDTLS_OID_PKCS1 "\x08" /*< id-mgf1 ::= { pkcs-1 8 } */ /* * Digest algorithms */ #define MBEDTLS_OID_DIGEST_ALG_MD2 MBEDTLS_OID_RSA_COMPANY "\x02\x02" /*< id-mbedtls_md2 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 2 } */ #define MBEDTLS_OID_DIGEST_ALG_MD4 MBEDTLS_OID_RSA_COMPANY "\x02\x04" /*< id-mbedtls_md4 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 4 } */ #define MBEDTLS_OID_DIGEST_ALG_MD5 MBEDTLS_OID_RSA_COMPANY "\x02\x05" /*< id-mbedtls_md5 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 5 } */ #define MBEDTLS_OID_DIGEST_ALG_SHA1 MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_OIW_SECSIG_SHA1 /*< id-mbedtls_sha1 OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 26 } */ #define MBEDTLS_OID_DIGEST_ALG_SHA224 MBEDTLS_OID_NIST_ALG "\x02\x04" /*< id-sha224 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 4 } */ #define MBEDTLS_OID_DIGEST_ALG_SHA256 MBEDTLS_OID_NIST_ALG "\x02\x01" /*< id-mbedtls_sha256 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 1 } */ #define MBEDTLS_OID_DIGEST_ALG_SHA384 MBEDTLS_OID_NIST_ALG "\x02\x02" /*< id-sha384 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 2 } */ #define MBEDTLS_OID_DIGEST_ALG_SHA512 MBEDTLS_OID_NIST_ALG "\x02\x03" /*< id-mbedtls_sha512 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 3 } */ #define MBEDTLS_OID_HMAC_SHA1 MBEDTLS_OID_RSA_COMPANY "\x02\x07" /*< id-hmacWithSHA1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 7 } */ #define MBEDTLS_OID_HMAC_SHA224 MBEDTLS_OID_RSA_COMPANY "\x02\x08" /*< id-hmacWithSHA224 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 8 } */ #define MBEDTLS_OID_HMAC_SHA256 MBEDTLS_OID_RSA_COMPANY "\x02\x09" /*< id-hmacWithSHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 9 } */ #define MBEDTLS_OID_HMAC_SHA384 MBEDTLS_OID_RSA_COMPANY "\x02\x0A" /*< id-hmacWithSHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 10 } */ #define MBEDTLS_OID_HMAC_SHA512 MBEDTLS_OID_RSA_COMPANY "\x02\x0B" /*< id-hmacWithSHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 11 } */ /* * Encryption algorithms */ #define MBEDTLS_OID_DES_CBC MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_OIW_SECSIG_ALG "\x07" /*< desCBC OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 7 } */ #define MBEDTLS_OID_DES_EDE3_CBC MBEDTLS_OID_RSA_COMPANY "\x03\x07" /*< des-ede3-cbc OBJECT IDENTIFIER ::= { iso(1) member-body(2) -- us(840) rsadsi(113549) encryptionAlgorithm(3) 7 } */ #define MBEDTLS_OID_AES MBEDTLS_OID_NIST_ALG "\x01" /** aes OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) 1 } */ /* * Key Wrapping algorithms */ /* * RFC 5649 */ #define MBEDTLS_OID_AES128_KW MBEDTLS_OID_AES "\x05" /** id-aes128-wrap OBJECT IDENTIFIER ::= { aes 5 } */ #define MBEDTLS_OID_AES128_KWP MBEDTLS_OID_AES "\x08" /** id-aes128-wrap-pad OBJECT IDENTIFIER ::= { aes 8 } */ #define MBEDTLS_OID_AES192_KW MBEDTLS_OID_AES "\x19" /** id-aes192-wrap OBJECT IDENTIFIER ::= { aes 25 } */ #define MBEDTLS_OID_AES192_KWP MBEDTLS_OID_AES "\x1c" /** id-aes192-wrap-pad OBJECT IDENTIFIER ::= { aes 28 } */ #define MBEDTLS_OID_AES256_KW MBEDTLS_OID_AES "\x2d" /** id-aes256-wrap OBJECT IDENTIFIER ::= { aes 45 } */ #define MBEDTLS_OID_AES256_KWP MBEDTLS_OID_AES "\x30" /** id-aes256-wrap-pad OBJECT IDENTIFIER ::= { aes 48 } */ /* * PKCS#5 OIDs */ #define MBEDTLS_OID_PKCS5_PBKDF2 MBEDTLS_OID_PKCS5 "\x0c" /*< id-PBKDF2 OBJECT IDENTIFIER ::= {pkcs-5 12} */ #define MBEDTLS_OID_PKCS5_PBES2 MBEDTLS_OID_PKCS5 "\x0d" /*< id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13} */ #define MBEDTLS_OID_PKCS5_PBMAC1 MBEDTLS_OID_PKCS5 "\x0e" /*< id-PBMAC1 OBJECT IDENTIFIER ::= {pkcs-5 14} */ /* * PKCS#5 PBES1 algorithms */ #define MBEDTLS_OID_PKCS5_PBE_MD2_DES_CBC MBEDTLS_OID_PKCS5 "\x01" /*< pbeWithMD2AndDES-CBC OBJECT IDENTIFIER ::= {pkcs-5 1} */ #define MBEDTLS_OID_PKCS5_PBE_MD2_RC2_CBC MBEDTLS_OID_PKCS5 "\x04" /*< pbeWithMD2AndRC2-CBC OBJECT IDENTIFIER ::= {pkcs-5 4} */ #define MBEDTLS_OID_PKCS5_PBE_MD5_DES_CBC MBEDTLS_OID_PKCS5 "\x03" /*< pbeWithMD5AndDES-CBC OBJECT IDENTIFIER ::= {pkcs-5 3} */ #define MBEDTLS_OID_PKCS5_PBE_MD5_RC2_CBC MBEDTLS_OID_PKCS5 "\x06" /*< pbeWithMD5AndRC2-CBC OBJECT IDENTIFIER ::= {pkcs-5 6} */ #define MBEDTLS_OID_PKCS5_PBE_SHA1_DES_CBC MBEDTLS_OID_PKCS5 "\x0a" /*< pbeWithSHA1AndDES-CBC OBJECT IDENTIFIER ::= {pkcs-5 10} */ #define MBEDTLS_OID_PKCS5_PBE_SHA1_RC2_CBC MBEDTLS_OID_PKCS5 "\x0b" /*< pbeWithSHA1AndRC2-CBC OBJECT IDENTIFIER ::= {pkcs-5 11} */ /* * PKCS#8 OIDs */ #define MBEDTLS_OID_PKCS9_CSR_EXT_REQ MBEDTLS_OID_PKCS9 "\x0e" /*< extensionRequest OBJECT IDENTIFIER ::= {pkcs-9 14} */ /* * PKCS#12 PBE OIDs */ #define MBEDTLS_OID_PKCS12_PBE MBEDTLS_OID_PKCS12 "\x01" /*< pkcs-12PbeIds OBJECT IDENTIFIER ::= {pkcs-12 1} */ #define MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_128 MBEDTLS_OID_PKCS12_PBE "\x01" /*< pbeWithSHAAnd128BitRC4 OBJECT IDENTIFIER ::= {pkcs-12PbeIds 1} */ #define MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_40 MBEDTLS_OID_PKCS12_PBE "\x02" /*< pbeWithSHAAnd40BitRC4 OBJECT IDENTIFIER ::= {pkcs-12PbeIds 2} */ #define MBEDTLS_OID_PKCS12_PBE_SHA1_DES3_EDE_CBC MBEDTLS_OID_PKCS12_PBE "\x03" /*< pbeWithSHAAnd3-KeyTripleDES-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 3} */ #define MBEDTLS_OID_PKCS12_PBE_SHA1_DES2_EDE_CBC MBEDTLS_OID_PKCS12_PBE "\x04" /*< pbeWithSHAAnd2-KeyTripleDES-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 4} */ #define MBEDTLS_OID_PKCS12_PBE_SHA1_RC2_128_CBC MBEDTLS_OID_PKCS12_PBE "\x05" /*< pbeWithSHAAnd128BitRC2-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 5} */ #define MBEDTLS_OID_PKCS12_PBE_SHA1_RC2_40_CBC MBEDTLS_OID_PKCS12_PBE "\x06" /*< pbeWithSHAAnd40BitRC2-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 6} */ /* * EC key algorithms from RFC 5480 */ /* id-ecPublicKey OBJECT IDENTIFIER ::= { * iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 } */ #define MBEDTLS_OID_EC_ALG_UNRESTRICTED MBEDTLS_OID_ANSI_X9_62 "\x02\01" /* id-ecDH OBJECT IDENTIFIER ::= { * iso(1) identified-organization(3) certicom(132) * schemes(1) ecdh(12) } */ #define MBEDTLS_OID_EC_ALG_ECDH MBEDTLS_OID_CERTICOM "\x01\x0c" /* * ECParameters namedCurve identifiers, from RFC 5480, RFC 5639, and SEC2 */ /* secp192r1 OBJECT IDENTIFIER ::= { * iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) prime(1) 1 } */ #define MBEDTLS_OID_EC_GRP_SECP192R1 MBEDTLS_OID_ANSI_X9_62 "\x03\x01\x01" /* secp224r1 OBJECT IDENTIFIER ::= { * iso(1) identified-organization(3) certicom(132) curve(0) 33 } */ #define MBEDTLS_OID_EC_GRP_SECP224R1 MBEDTLS_OID_CERTICOM "\x00\x21" /* secp256r1 OBJECT IDENTIFIER ::= { * iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) prime(1) 7 } */ #define MBEDTLS_OID_EC_GRP_SECP256R1 MBEDTLS_OID_ANSI_X9_62 "\x03\x01\x07" /* secp384r1 OBJECT IDENTIFIER ::= { * iso(1) identified-organization(3) certicom(132) curve(0) 34 } */ #define MBEDTLS_OID_EC_GRP_SECP384R1 MBEDTLS_OID_CERTICOM "\x00\x22" /* secp521r1 OBJECT IDENTIFIER ::= { * iso(1) identified-organization(3) certicom(132) curve(0) 35 } */ #define MBEDTLS_OID_EC_GRP_SECP521R1 MBEDTLS_OID_CERTICOM "\x00\x23" /* secp192k1 OBJECT IDENTIFIER ::= { * iso(1) identified-organization(3) certicom(132) curve(0) 31 } */ #define MBEDTLS_OID_EC_GRP_SECP192K1 MBEDTLS_OID_CERTICOM "\x00\x1f" /* secp224k1 OBJECT IDENTIFIER ::= { * iso(1) identified-organization(3) certicom(132) curve(0) 32 } */ #define MBEDTLS_OID_EC_GRP_SECP224K1 MBEDTLS_OID_CERTICOM "\x00\x20" /* secp256k1 OBJECT IDENTIFIER ::= { * iso(1) identified-organization(3) certicom(132) curve(0) 10 } */ #define MBEDTLS_OID_EC_GRP_SECP256K1 MBEDTLS_OID_CERTICOM "\x00\x0a" /* RFC 5639 4.1 * ecStdCurvesAndGeneration OBJECT IDENTIFIER::= {iso(1) * identified-organization(3) teletrust(36) algorithm(3) signature- * algorithm(3) ecSign(2) 8} * ellipticCurve OBJECT IDENTIFIER ::= {ecStdCurvesAndGeneration 1} * versionOne OBJECT IDENTIFIER ::= {ellipticCurve 1} */ #define MBEDTLS_OID_EC_BRAINPOOL_V1 MBEDTLS_OID_TELETRUST "\x03\x03\x02\x08\x01\x01" /* brainpoolP256r1 OBJECT IDENTIFIER ::= {versionOne 7} */ #define MBEDTLS_OID_EC_GRP_BP256R1 MBEDTLS_OID_EC_BRAINPOOL_V1 "\x07" /* brainpoolP384r1 OBJECT IDENTIFIER ::= {versionOne 11} */ #define MBEDTLS_OID_EC_GRP_BP384R1 MBEDTLS_OID_EC_BRAINPOOL_V1 "\x0B" /* brainpoolP512r1 OBJECT IDENTIFIER ::= {versionOne 13} */ #define MBEDTLS_OID_EC_GRP_BP512R1 MBEDTLS_OID_EC_BRAINPOOL_V1 "\x0D" /* * SEC1 C.1 * * prime-field OBJECT IDENTIFIER ::= { id-fieldType 1 } * id-fieldType OBJECT IDENTIFIER ::= { ansi-X9-62 fieldType(1)} */ #define MBEDTLS_OID_ANSI_X9_62_FIELD_TYPE MBEDTLS_OID_ANSI_X9_62 "\x01" #define MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD MBEDTLS_OID_ANSI_X9_62_FIELD_TYPE "\x01" /* * ECDSA signature identifiers, from RFC 5480 */ #define MBEDTLS_OID_ANSI_X9_62_SIG MBEDTLS_OID_ANSI_X9_62 "\x04" /* signatures(4) */ #define MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 MBEDTLS_OID_ANSI_X9_62_SIG "\x03" /* ecdsa-with-SHA2(3) */ /* ecdsa-with-SHA1 OBJECT IDENTIFIER ::= { * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) 1 } */ #define MBEDTLS_OID_ECDSA_SHA1 MBEDTLS_OID_ANSI_X9_62_SIG "\x01" /* ecdsa-with-SHA224 OBJECT IDENTIFIER ::= { * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) * ecdsa-with-SHA2(3) 1 } */ #define MBEDTLS_OID_ECDSA_SHA224 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x01" /* ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) * ecdsa-with-SHA2(3) 2 } */ #define MBEDTLS_OID_ECDSA_SHA256 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x02" /* ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) * ecdsa-with-SHA2(3) 3 } */ #define MBEDTLS_OID_ECDSA_SHA384 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x03" /* ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) * ecdsa-with-SHA2(3) 4 } */ #define MBEDTLS_OID_ECDSA_SHA512 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x04" #ifdef __cplusplus extern "C" { #endif /** * \brief Base OID descriptor structure */ typedef struct mbedtls_oid_descriptor_t { const char *asn1; /*!< OID ASN.1 representation */ size_t asn1_len; /*!< length of asn1 */ const char *name; /*!< official name (e.g. from RFC) */ const char *description; /*!< human friendly description */ } mbedtls_oid_descriptor_t; /** * \brief Translate an ASN.1 OID into its numeric representation * (e.g. "\x2A\x86\x48\x86\xF7\x0D" into "1.2.840.113549") * * \param buf buffer to put representation in * \param size size of the buffer * \param oid OID to translate * * \return Length of the string written (excluding final NULL) or * MBEDTLS_ERR_OID_BUF_TOO_SMALL in case of error */ int mbedtls_oid_get_numeric_string( char *buf, size_t size, const mbedtls_asn1_buf *oid ); /** * \brief Translate an X.509 extension OID into local values * * \param oid OID to use * \param ext_type place to store the extension type * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_x509_ext_type( const mbedtls_asn1_buf *oid, int *ext_type ); /** * \brief Translate an X.509 attribute type OID into the short name * (e.g. the OID for an X520 Common Name into "CN") * * \param oid OID to use * \param short_name place to store the string pointer * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_attr_short_name( const mbedtls_asn1_buf *oid, const char **short_name ); /** * \brief Translate PublicKeyAlgorithm OID into pk_type * * \param oid OID to use * \param pk_alg place to store public key algorithm * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_pk_alg( const mbedtls_asn1_buf *oid, mbedtls_pk_type_t *pk_alg ); /** * \brief Translate pk_type into PublicKeyAlgorithm OID * * \param pk_alg Public key type to look for * \param oid place to store ASN.1 OID string pointer * \param olen length of the OID * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_oid_by_pk_alg( mbedtls_pk_type_t pk_alg, const char **oid, size_t *olen ); /** * \brief Translate NamedCurve OID into an EC group identifier * * \param oid OID to use * \param grp_id place to store group id * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_ec_grp( const mbedtls_asn1_buf *oid, mbedtls_ecp_group_id *grp_id ); /** * \brief Translate EC group identifier into NamedCurve OID * * \param grp_id EC group identifier * \param oid place to store ASN.1 OID string pointer * \param olen length of the OID * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_oid_by_ec_grp( mbedtls_ecp_group_id grp_id, const char **oid, size_t *olen ); /** * \brief Translate SignatureAlgorithm OID into md_type and pk_type * * \param oid OID to use * \param md_alg place to store message digest algorithm * \param pk_alg place to store public key algorithm * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_sig_alg( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg ); /** * \brief Translate SignatureAlgorithm OID into description * * \param oid OID to use * \param desc place to store string pointer * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_sig_alg_desc( const mbedtls_asn1_buf *oid, const char **desc ); /** * \brief Translate md_type and pk_type into SignatureAlgorithm OID * * \param md_alg message digest algorithm * \param pk_alg public key algorithm * \param oid place to store ASN.1 OID string pointer * \param olen length of the OID * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_oid_by_sig_alg( mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg, const char **oid, size_t *olen ); /** * \brief Translate hash algorithm OID into md_type * * \param oid OID to use * \param md_alg place to store message digest algorithm * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_md_alg( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_alg ); /** * \brief Translate hmac algorithm OID into md_type * * \param oid OID to use * \param md_hmac place to store message hmac algorithm * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_md_hmac( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_hmac ); /** * \brief Translate Extended Key Usage OID into description * * \param oid OID to use * \param desc place to store string pointer * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_extended_key_usage( const mbedtls_asn1_buf *oid, const char **desc ); /** * \brief Translate certificate policies OID into description * * \param oid OID to use * \param desc place to store string pointer * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_certificate_policies( const mbedtls_asn1_buf *oid, const char **desc ); /** * \brief Translate md_type into hash algorithm OID * * \param md_alg message digest algorithm * \param oid place to store ASN.1 OID string pointer * \param olen length of the OID * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_oid_by_md( mbedtls_md_type_t md_alg, const char **oid, size_t *olen ); #if defined(MBEDTLS_CIPHER_C) /** * \brief Translate encryption algorithm OID into cipher_type * * \param oid OID to use * \param cipher_alg place to store cipher algorithm * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_cipher_alg( const mbedtls_asn1_buf *oid, mbedtls_cipher_type_t *cipher_alg ); #endif /* MBEDTLS_CIPHER_C */ #if defined(MBEDTLS_PKCS12_C) /** * \brief Translate PKCS#12 PBE algorithm OID into md_type and * cipher_type * * \param oid OID to use * \param md_alg place to store message digest algorithm * \param cipher_alg place to store cipher algorithm * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_pkcs12_pbe_alg( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_alg, mbedtls_cipher_type_t *cipher_alg ); #endif /* MBEDTLS_PKCS12_C */ #ifdef __cplusplus } #endif #endif /* oid.h */
33,000
601
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/pk.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/ecdsa.h" #include "third_party/mbedtls/ecp.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/pk.h" #include "third_party/mbedtls/pk_internal.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/rsa.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /** * @fileoverview Public Key abstraction layer */ #if defined(MBEDTLS_PK_C) #define PK_VALIDATE_RET( cond ) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_PK_BAD_INPUT_DATA ) #define PK_VALIDATE( cond ) \ MBEDTLS_INTERNAL_VALIDATE( cond ) /** * \brief Initialize a #mbedtls_pk_context (as NONE). * * \param ctx The context to initialize. * This must not be \c NULL. */ void mbedtls_pk_init( mbedtls_pk_context *ctx ) { PK_VALIDATE( ctx ); ctx->pk_info = NULL; ctx->pk_ctx = NULL; } /** * \brief Free the components of a #mbedtls_pk_context. * * \param ctx The context to clear. It must have been initialized. * If this is \c NULL, this function does nothing. * * \note For contexts that have been set up with * mbedtls_pk_setup_opaque(), this does not free the underlying * PSA key and you still need to call psa_destroy_key() * independently if you want to destroy that key. */ void mbedtls_pk_free( mbedtls_pk_context *ctx ) { if( ctx == NULL ) return; if ( ctx->pk_info ) ctx->pk_info->ctx_free_func( ctx->pk_ctx ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_pk_context ) ); } #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) /** * \brief Initialize a restart context * * \param ctx The context to initialize. * This must not be \c NULL. */ void mbedtls_pk_restart_init( mbedtls_pk_restart_ctx *ctx ) { PK_VALIDATE( ctx ); ctx->pk_info = NULL; ctx->rs_ctx = NULL; } /** * \brief Free the components of a restart context * * \param ctx The context to clear. It must have been initialized. * If this is \c NULL, this function does nothing. */ void mbedtls_pk_restart_free( mbedtls_pk_restart_ctx *ctx ) { if( ctx == NULL || ctx->pk_info == NULL || ctx->pk_info->rs_free_func == NULL ) { return; } ctx->pk_info->rs_free_func( ctx->rs_ctx ); ctx->pk_info = NULL; ctx->rs_ctx = NULL; } #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ /** * \brief Return information associated with the given PK type * * \param pk_type PK type to search for. * * \return The PK info associated with the type or NULL if not found. */ const mbedtls_pk_info_t * mbedtls_pk_info_from_type( mbedtls_pk_type_t pk_type ) { switch( pk_type ) { #if defined(MBEDTLS_RSA_C) case MBEDTLS_PK_RSA: return( &mbedtls_rsa_info ); #endif #if defined(MBEDTLS_ECP_C) case MBEDTLS_PK_ECKEY: return( &mbedtls_eckey_info ); case MBEDTLS_PK_ECKEY_DH: return( &mbedtls_eckeydh_info ); #endif #if defined(MBEDTLS_ECDSA_C) case MBEDTLS_PK_ECDSA: return( &mbedtls_ecdsa_info ); #endif /* MBEDTLS_PK_RSA_ALT omitted on purpose */ default: return( NULL ); } } /** * \brief Initialize a PK context with the information given * and allocates the type-specific PK subcontext. * * \param ctx Context to initialize. It must not have been set * up yet (type #MBEDTLS_PK_NONE). * \param info Information to use * * \return 0 on success, * MBEDTLS_ERR_PK_BAD_INPUT_DATA on invalid input, * MBEDTLS_ERR_PK_ALLOC_FAILED on allocation failure. * * \note For contexts holding an RSA-alt key, use * \c mbedtls_pk_setup_rsa_alt() instead. */ int mbedtls_pk_setup( mbedtls_pk_context *ctx, const mbedtls_pk_info_t *info ) { PK_VALIDATE_RET( ctx ); if( info == NULL || ctx->pk_info ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); if( ( ctx->pk_ctx = info->ctx_alloc_func() ) == NULL ) return( MBEDTLS_ERR_PK_ALLOC_FAILED ); ctx->pk_info = info; return( 0 ); } /** * \brief Initialize an RSA-alt context * * \param ctx Context to initialize. It must not have been set * up yet (type #MBEDTLS_PK_NONE). * \param key RSA key pointer * \param decrypt_func Decryption function * \param sign_func Signing function * \param key_len_func Function returning key length in bytes * * \return 0 on success, or MBEDTLS_ERR_PK_BAD_INPUT_DATA if the * context wasn't already initialized as RSA_ALT. * * \note This function replaces \c mbedtls_pk_setup() for RSA-alt. */ int mbedtls_pk_setup_rsa_alt( mbedtls_pk_context *ctx, void * key, mbedtls_pk_rsa_alt_decrypt_func decrypt_func, mbedtls_pk_rsa_alt_sign_func sign_func, mbedtls_pk_rsa_alt_key_len_func key_len_func ) { mbedtls_rsa_alt_context *rsa_alt; const mbedtls_pk_info_t *info = &mbedtls_rsa_alt_info; PK_VALIDATE_RET( ctx ); if( ctx->pk_info ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); if( ( ctx->pk_ctx = info->ctx_alloc_func() ) == NULL ) return( MBEDTLS_ERR_PK_ALLOC_FAILED ); ctx->pk_info = info; rsa_alt = (mbedtls_rsa_alt_context *) ctx->pk_ctx; rsa_alt->key = key; rsa_alt->decrypt_func = decrypt_func; rsa_alt->sign_func = sign_func; rsa_alt->key_len_func = key_len_func; return( 0 ); } /** * \brief Tell if a context can do the operation given by type * * \param ctx The context to query. It must have been initialized. * \param type The desired type. * * \return 1 if the context can do operations on the given type. * \return 0 if the context cannot do the operations on the given * type. This is always the case for a context that has * been initialized but not set up, or that has been * cleared with mbedtls_pk_free(). */ int mbedtls_pk_can_do( const mbedtls_pk_context *ctx, mbedtls_pk_type_t type ) { /* A context with null pk_info is not set up yet and can't do anything. * For backward compatibility, also accept NULL instead of a context * pointer. */ if( ctx == NULL || ctx->pk_info == NULL ) return( 0 ); return( ctx->pk_info->can_do( type ) ); } /* * Helper for mbedtls_pk_sign and mbedtls_pk_verify */ static inline int pk_hashlen_helper( mbedtls_md_type_t md_alg, size_t *hash_len ) { const mbedtls_md_info_t *md_info; if( *hash_len != 0 ) return( 0 ); if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL ) return( -1 ); *hash_len = mbedtls_md_get_size( md_info ); return( 0 ); } #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) /* * Helper to set up a restart context if needed */ static int pk_restart_setup( mbedtls_pk_restart_ctx *ctx, const mbedtls_pk_info_t *info ) { /* Don't do anything if already set up or invalid */ if( ctx == NULL || ctx->pk_info ) return( 0 ); /* Should never happen when we're called */ if( info->rs_alloc_func == NULL || info->rs_free_func == NULL ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); if( ( ctx->rs_ctx = info->rs_alloc_func() ) == NULL ) return( MBEDTLS_ERR_PK_ALLOC_FAILED ); ctx->pk_info = info; return( 0 ); } #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ /** * \brief Restartable version of \c mbedtls_pk_verify() * * \note Performs the same job as \c mbedtls_pk_verify(), but can * return early and restart according to the limit set with * \c mbedtls_ecp_set_max_ops() to reduce blocking for ECC * operations. For RSA, same as \c mbedtls_pk_verify(). * * \param ctx The PK context to use. It must have been set up. * \param md_alg Hash algorithm used (see notes) * \param hash Hash of the message to sign * \param hash_len Hash length or 0 (see notes) * \param sig Signature to verify * \param sig_len Signature length * \param rs_ctx Restart context (NULL to disable restart) * * \return See \c mbedtls_pk_verify(), or * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of * operations was reached: see \c mbedtls_ecp_set_max_ops(). */ int mbedtls_pk_verify_restartable( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, const unsigned char *sig, size_t sig_len, mbedtls_pk_restart_ctx *rs_ctx ) { PK_VALIDATE_RET( ctx ); PK_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hash_len == 0 ) || hash ); PK_VALIDATE_RET( sig ); if( ctx->pk_info == NULL || pk_hashlen_helper( md_alg, &hash_len ) != 0 ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) /* optimization: use non-restartable version if restart disabled */ if( rs_ctx && mbedtls_ecp_restart_is_enabled() && ctx->pk_info->verify_rs_func ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( ( ret = pk_restart_setup( rs_ctx, ctx->pk_info ) ) != 0 ) return( ret ); ret = ctx->pk_info->verify_rs_func( ctx->pk_ctx, md_alg, hash, hash_len, sig, sig_len, rs_ctx->rs_ctx ); if( ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) mbedtls_pk_restart_free( rs_ctx ); return( ret ); } #else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ (void) rs_ctx; #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ if( ctx->pk_info->verify_func == NULL ) return( MBEDTLS_ERR_PK_TYPE_MISMATCH ); return( ctx->pk_info->verify_func( ctx->pk_ctx, md_alg, hash, hash_len, sig, sig_len ) ); } /** * \brief Verify signature (including padding if relevant). * * \param ctx The PK context to use. It must have been set up. * \param md_alg Hash algorithm used (see notes) * \param hash Hash of the message to sign * \param hash_len Hash length or 0 (see notes) * \param sig Signature to verify * \param sig_len Signature length * * \return 0 on success (signature is valid), * #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid * signature in sig but its length is less than \p siglen, * or a specific error code. * * \note For RSA keys, the default padding type is PKCS#1 v1.5. * Use \c mbedtls_pk_verify_ext( MBEDTLS_PK_RSASSA_PSS, ... ) * to verify RSASSA_PSS signatures. * * \note If hash_len is 0, then the length associated with md_alg * is used instead, or an error returned if it is invalid. * * \note md_alg may be MBEDTLS_MD_NONE, only if hash_len != 0 */ int mbedtls_pk_verify( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, const unsigned char *sig, size_t sig_len ) { return( mbedtls_pk_verify_restartable( ctx, md_alg, hash, hash_len, sig, sig_len, NULL ) ); } /** * \brief Verify signature, with options. * (Includes verification of the padding depending on type.) * * \param type Signature type (inc. possible padding type) to verify * \param options Pointer to type-specific options, or NULL * \param ctx The PK context to use. It must have been set up. * \param md_alg Hash algorithm used (see notes) * \param hash Hash of the message to sign * \param hash_len Hash length or 0 (see notes) * \param sig Signature to verify * \param sig_len Signature length * * \return 0 on success (signature is valid), * #MBEDTLS_ERR_PK_TYPE_MISMATCH if the PK context can't be * used for this type of signatures, * #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid * signature in sig but its length is less than \p siglen, * or a specific error code. * * \note If hash_len is 0, then the length associated with md_alg * is used instead, or an error returned if it is invalid. * * \note md_alg may be MBEDTLS_MD_NONE, only if hash_len != 0 * * \note If type is MBEDTLS_PK_RSASSA_PSS, then options must point * to a mbedtls_pk_rsassa_pss_options structure, * otherwise it must be NULL. */ int mbedtls_pk_verify_ext( mbedtls_pk_type_t type, const void *options, mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, const unsigned char *sig, size_t sig_len ) { PK_VALIDATE_RET( ctx ); PK_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hash_len == 0 ) || hash ); PK_VALIDATE_RET( sig ); if( ctx->pk_info == NULL ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); if( ! mbedtls_pk_can_do( ctx, type ) ) return( MBEDTLS_ERR_PK_TYPE_MISMATCH ); if( type == MBEDTLS_PK_RSASSA_PSS ) { #if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PKCS1_V21) int ret = MBEDTLS_ERR_THIS_CORRUPTION; const mbedtls_pk_rsassa_pss_options *pss_opts; #if SIZE_MAX > UINT_MAX if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); #endif /* SIZE_MAX > UINT_MAX */ if( options == NULL ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); pss_opts = (const mbedtls_pk_rsassa_pss_options *) options; if( sig_len < mbedtls_pk_get_len( ctx ) ) return( MBEDTLS_ERR_RSA_VERIFY_FAILED ); ret = mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_pk_rsa( *ctx ), NULL, NULL, MBEDTLS_RSA_PUBLIC, md_alg, (unsigned int) hash_len, hash, pss_opts->mgf1_hash_id, pss_opts->expected_salt_len, sig ); if( ret != 0 ) return( ret ); if( sig_len > mbedtls_pk_get_len( ctx ) ) return( MBEDTLS_ERR_PK_SIG_LEN_MISMATCH ); return( 0 ); #else return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE ); #endif /* MBEDTLS_RSA_C && MBEDTLS_PKCS1_V21 */ } /* General case: no options */ if( options ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); return( mbedtls_pk_verify( ctx, md_alg, hash, hash_len, sig, sig_len ) ); } /** * \brief Restartable version of \c mbedtls_pk_sign() * * \note Performs the same job as \c mbedtls_pk_sign(), but can * return early and restart according to the limit set with * \c mbedtls_ecp_set_max_ops() to reduce blocking for ECC * operations. For RSA, same as \c mbedtls_pk_sign(). * * \param ctx The PK context to use. It must have been set up * with a private key. * \param md_alg Hash algorithm used (see notes for mbedtls_pk_sign()) * \param hash Hash of the message to sign * \param hash_len Hash length or 0 (see notes for mbedtls_pk_sign()) * \param sig Place to write the signature. * It must have enough room for the signature. * #MBEDTLS_PK_SIGNATURE_MAX_SIZE is always enough. * You may use a smaller buffer if it is large enough * given the key type. * \param sig_len On successful return, * the number of bytes written to \p sig. * \param f_rng RNG function * \param p_rng RNG parameter * \param rs_ctx Restart context (NULL to disable restart) * * \return See \c mbedtls_pk_sign(). * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of * operations was reached: see \c mbedtls_ecp_set_max_ops(). */ int mbedtls_pk_sign_restartable( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, unsigned char *sig, size_t *sig_len, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, mbedtls_pk_restart_ctx *rs_ctx ) { PK_VALIDATE_RET( ctx ); PK_VALIDATE_RET( ( md_alg == MBEDTLS_MD_NONE && hash_len == 0 ) || hash ); PK_VALIDATE_RET( sig ); if( ctx->pk_info == NULL || pk_hashlen_helper( md_alg, &hash_len ) != 0 ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) /* optimization: use non-restartable version if restart disabled */ if( rs_ctx && mbedtls_ecp_restart_is_enabled() && ctx->pk_info->sign_rs_func ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( ( ret = pk_restart_setup( rs_ctx, ctx->pk_info ) ) != 0 ) return( ret ); ret = ctx->pk_info->sign_rs_func( ctx->pk_ctx, md_alg, hash, hash_len, sig, sig_len, f_rng, p_rng, rs_ctx->rs_ctx ); if( ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) mbedtls_pk_restart_free( rs_ctx ); return( ret ); } #else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ (void) rs_ctx; #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ if( ctx->pk_info->sign_func == NULL ) return( MBEDTLS_ERR_PK_TYPE_MISMATCH ); return( ctx->pk_info->sign_func( ctx->pk_ctx, md_alg, hash, hash_len, sig, sig_len, f_rng, p_rng ) ); } /** * \brief Make signature, including padding if relevant. * * \param ctx The PK context to use. It must have been set up * with a private key. * \param md_alg Hash algorithm used (see notes) * \param hash Hash of the message to sign * \param hash_len Hash length or 0 (see notes) * \param sig Place to write the signature. * It must have enough room for the signature. * #MBEDTLS_PK_SIGNATURE_MAX_SIZE is always enough. * You may use a smaller buffer if it is large enough * given the key type. * \param sig_len On successful return, * the number of bytes written to \p sig. * \param f_rng RNG function * \param p_rng RNG parameter * * \return 0 on success, or a specific error code. * * \note For RSA keys, the default padding type is PKCS#1 v1.5. * There is no interface in the PK module to make RSASSA-PSS * signatures yet. * * \note If hash_len is 0, then the length associated with md_alg * is used instead, or an error returned if it is invalid. * * \note For RSA, md_alg may be MBEDTLS_MD_NONE if hash_len != 0. * For ECDSA, md_alg may never be MBEDTLS_MD_NONE. */ int mbedtls_pk_sign( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, unsigned char *sig, size_t *sig_len, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { return( mbedtls_pk_sign_restartable( ctx, md_alg, hash, hash_len, sig, sig_len, f_rng, p_rng, NULL ) ); } /** * \brief Decrypt message (including padding if relevant). * * \param ctx The PK context to use. It must have been set up * with a private key. * \param input Input to decrypt * \param ilen Input size * \param output Decrypted output * \param olen Decrypted message length * \param osize Size of the output buffer * \param f_rng RNG function * \param p_rng RNG parameter * * \note For RSA keys, the default padding type is PKCS#1 v1.5. * * \return 0 on success, or a specific error code. */ int mbedtls_pk_decrypt( mbedtls_pk_context *ctx, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen, size_t osize, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { PK_VALIDATE_RET( ctx ); PK_VALIDATE_RET( input || ilen == 0 ); PK_VALIDATE_RET( output || osize == 0 ); PK_VALIDATE_RET( olen ); if( ctx->pk_info == NULL ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); if( ctx->pk_info->decrypt_func == NULL ) return( MBEDTLS_ERR_PK_TYPE_MISMATCH ); return( ctx->pk_info->decrypt_func( ctx->pk_ctx, input, ilen, output, olen, osize, f_rng, p_rng ) ); } /** * \brief Encrypt message (including padding if relevant). * * \param ctx The PK context to use. It must have been set up. * \param input Message to encrypt * \param ilen Message size * \param output Encrypted output * \param olen Encrypted output length * \param osize Size of the output buffer * \param f_rng RNG function * \param p_rng RNG parameter * * \note For RSA keys, the default padding type is PKCS#1 v1.5. * * \return 0 on success, or a specific error code. */ int mbedtls_pk_encrypt( mbedtls_pk_context *ctx, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen, size_t osize, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { PK_VALIDATE_RET( ctx ); PK_VALIDATE_RET( input || ilen == 0 ); PK_VALIDATE_RET( output || osize == 0 ); PK_VALIDATE_RET( olen ); if( ctx->pk_info == NULL ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); if( ctx->pk_info->encrypt_func == NULL ) return( MBEDTLS_ERR_PK_TYPE_MISMATCH ); return( ctx->pk_info->encrypt_func( ctx->pk_ctx, input, ilen, output, olen, osize, f_rng, p_rng ) ); } /** * \brief Check if a public-private pair of keys matches. * * \param pub Context holding a public key. * \param prv Context holding a private (and public) key. * * \return \c 0 on success (keys were checked and match each other). * \return #MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE if the keys could not * be checked - in that case they may or may not match. * \return #MBEDTLS_ERR_PK_BAD_INPUT_DATA if a context is invalid. * \return Another non-zero value if the keys do not match. */ int mbedtls_pk_check_pair( const mbedtls_pk_context *pub, const mbedtls_pk_context *prv ) { PK_VALIDATE_RET( pub ); PK_VALIDATE_RET( prv ); if( pub->pk_info == NULL || prv->pk_info == NULL ) { return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); } if( prv->pk_info->check_pair_func == NULL ) return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE ); if( prv->pk_info->type == MBEDTLS_PK_RSA_ALT ) { if( pub->pk_info->type != MBEDTLS_PK_RSA ) return( MBEDTLS_ERR_PK_TYPE_MISMATCH ); } else { if( pub->pk_info != prv->pk_info ) return( MBEDTLS_ERR_PK_TYPE_MISMATCH ); } return( prv->pk_info->check_pair_func( pub->pk_ctx, prv->pk_ctx ) ); } /** * \brief Get the size in bits of the underlying key * * \param ctx The context to query. It must have been initialized. * * \return Key size in bits, or 0 on error */ size_t mbedtls_pk_get_bitlen( const mbedtls_pk_context *ctx ) { /* For backward compatibility, accept NULL or a context that * isn't set up yet, and return a fake value that should be safe. */ if( ctx == NULL || ctx->pk_info == NULL ) return( 0 ); return( ctx->pk_info->get_bitlen( ctx->pk_ctx ) ); } /** * \brief Export debug information * * \param ctx The PK context to use. It must have been initialized. * \param items Place to write debug items * * \return 0 on success or MBEDTLS_ERR_PK_BAD_INPUT_DATA */ int mbedtls_pk_debug( const mbedtls_pk_context *ctx, mbedtls_pk_debug_item *items ) { PK_VALIDATE_RET( ctx ); if( ctx->pk_info == NULL ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); if( ctx->pk_info->debug_func == NULL ) return( MBEDTLS_ERR_PK_TYPE_MISMATCH ); ctx->pk_info->debug_func( ctx->pk_ctx, items ); return( 0 ); } /** * \brief Access the type name * * \param ctx The PK context to use. It must have been initialized. * * \return Type name on success, or "invalid PK" */ const char *mbedtls_pk_get_name( const mbedtls_pk_context *ctx ) { if( ctx == NULL || ctx->pk_info == NULL ) return( "invalid PK" ); return( ctx->pk_info->name ); } /** * \brief Get the key type * * \param ctx The PK context to use. It must have been initialized. * * \return Type on success. * \return #MBEDTLS_PK_NONE for a context that has not been set up. */ mbedtls_pk_type_t mbedtls_pk_get_type( const mbedtls_pk_context *ctx ) { if( ctx == NULL || ctx->pk_info == NULL ) return( MBEDTLS_PK_NONE ); return( ctx->pk_info->type ); } #endif /* MBEDTLS_PK_C */
27,835
722
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/ecp384.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/asan.internal.h" #include "libc/nexgen32e/x86feature.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "third_party/mbedtls/bignum_internal.h" #include "third_party/mbedtls/ecp.h" #include "third_party/mbedtls/ecp_internal.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/math.h" #include "third_party/mbedtls/profile.h" #include "third_party/mbedtls/select.h" /* clang-format off */ static bool mbedtls_p384_isz( uint64_t p[6] ) { return( !p[0] & !p[1] & !p[2] & !p[3] & !p[4] & !p[5] ); } static bool mbedtls_p384_gte( uint64_t p[7] ) { return( (((int64_t)p[6] > 0) | (!p[6] & ((p[5] > 0xffffffffffffffff) | ((p[5] == 0xffffffffffffffff) & ((p[4] > 0xffffffffffffffff) | ((p[4] == 0xffffffffffffffff) & ((p[3] > 0xffffffffffffffff) | ((p[3] == 0xffffffffffffffff) & ((p[2] > 0xfffffffffffffffe) | ((p[2] == 0xfffffffffffffffe) & ((p[1] > 0xffffffff00000000) | ((p[1] == 0xffffffff00000000) & ((p[0] > 0x00000000ffffffff) | (p[0] == 0x00000000ffffffff)))))))))))))) ); } static int mbedtls_p384_cmp( const uint64_t a[7], const uint64_t b[7] ) { int i, x, y, done = 0; // return -1 if a[6] < b[6] x = -((int64_t)a[6] < (int64_t)b[6]); done = x; // return +1 if a[6] > b[6] y = (int64_t)a[6] > (int64_t)b[6]; x = Select(x, y, done); done |= -y; for (i = 6; i--;) { y = -(a[i] < b[i]); x = Select(x, y, done); done |= y; y = a[i] > b[i]; x = Select(x, y, done); done |= -y; } return x; } static inline void mbedtls_p384_red( uint64_t p[7] ) { #if defined(__x86_64__) && !defined(__STRICT_ANSI__) asm("subq\t%1,%0\n\t" "sbbq\t%2,8+%0\n\t" "sbbq\t%3,16+%0\n\t" "sbbq\t%4,24+%0\n\t" "sbbq\t%4,32+%0\n\t" "sbbq\t%4,40+%0\n\t" "sbbq\t$0,48+%0" : "+o"(*p) : "r"(0x00000000ffffffffl), "r"(0xffffffff00000000), "i"(0xfffffffffffffffel), "i"(0xffffffffffffffff) : "memory", "cc"); #else uint64_t c; SBB( p[0], p[0], 0x00000000ffffffff, 0, c ); SBB( p[1], p[1], 0xffffffff00000000, c, c ); SBB( p[2], p[2], 0xfffffffffffffffe, c, c ); SBB( p[3], p[3], 0xffffffffffffffff, c, c ); SBB( p[4], p[4], 0xffffffffffffffff, c, c ); SBB( p[5], p[5], 0xffffffffffffffff, c, c ); SBB( p[6], p[6], 0, c, c ); #endif } static inline void mbedtls_p384_gro( uint64_t p[7] ) { #if defined(__x86_64__) && !defined(__STRICT_ANSI__) asm("addq\t%1,%0\n\t" "adcq\t%2,8+%0\n\t" "adcq\t%3,16+%0\n\t" "adcq\t%4,24+%0\n\t" "adcq\t%4,32+%0\n\t" "adcq\t%4,40+%0\n\t" "adcq\t$0,48+%0" : "+o"(*p) : "r"(0x00000000ffffffffl), "r"(0xffffffff00000000), "i"(0xfffffffffffffffel), "i"(0xffffffffffffffff) : "memory", "cc"); #else uint64_t c; ADC( p[0], p[0], 0x00000000ffffffff, 0, c ); ADC( p[1], p[1], 0xffffffff00000000, c, c ); ADC( p[2], p[2], 0xfffffffffffffffe, c, c ); ADC( p[3], p[3], 0xffffffffffffffff, c, c ); ADC( p[4], p[4], 0xffffffffffffffff, c, c ); ADC( p[5], p[5], 0xffffffffffffffff, c, c ); ADC( p[6], p[6], 0, c, c ); #endif } static inline void mbedtls_p384_rum( uint64_t p[7] ) { while( mbedtls_p384_gte( p ) ) mbedtls_p384_red( p ); } void mbedtls_p384_mod( uint64_t X[12] ) { secp384r1(X); if( (int64_t)X[6] < 0 ){ do { mbedtls_p384_gro(X); } while( (int64_t)X[6] < 0 ); } else { mbedtls_p384_rum(X); } } static inline void mbedtls_p384_sar( uint64_t p[7] ) { p[0] = p[0] >> 1 | p[1] << 63; p[1] = p[1] >> 1 | p[2] << 63; p[2] = p[2] >> 1 | p[3] << 63; p[3] = p[3] >> 1 | p[4] << 63; p[4] = p[4] >> 1 | p[5] << 63; p[5] = p[5] >> 1 | p[6] << 63; p[6] = (int64_t)p[6] >> 1; } static inline void mbedtls_p384_shl( uint64_t p[7] ) { p[6] = p[5] >> 63; p[5] = p[5] << 1 | p[4] >> 63; p[4] = p[4] << 1 | p[3] >> 63; p[3] = p[3] << 1 | p[2] >> 63; p[2] = p[2] << 1 | p[1] >> 63; p[1] = p[1] << 1 | p[0] >> 63; p[0] = p[0] << 1; mbedtls_p384_rum( p ); } static void mbedtls_p384_mul( uint64_t X[12], const uint64_t A[6], size_t n, const uint64_t B[6], size_t m ) { if( n == 6 && m == 6 && X86_HAVE(ADX) && X86_HAVE(BMI2) ) { Mul6x6Adx( X, A, B ); } else { void *f = 0; if( A == X ) { A = memcpy( malloc( 6 * 8 ), A, 6 * 8 ); f = A; } else if( B == X ) { B = memcpy( malloc( 6 * 8 ), B, 6 * 8 ); f = B; } Mul( X, A, n, B, m ); mbedtls_platform_zeroize( X + n + m, (12 - n - m) * 8 ); free( f ); } mbedtls_p384_mod( X ); } static void mbedtls_p384_plu( uint64_t A[7], const uint64_t B[7] ) { #if defined(__x86_64__) && !defined(__STRICT_ANSI__) asm("mov\t%1,%%rax\n\t" "add\t%%rax,%0\n\t" "mov\t8+%1,%%rax\n\t" "adc\t%%rax,8+%0\n\t" "mov\t16+%1,%%rax\n\t" "adc\t%%rax,16+%0\n\t" "mov\t24+%1,%%rax\n\t" "adc\t%%rax,24+%0\n\t" "mov\t32+%1,%%rax\n\t" "adc\t%%rax,32+%0\n\t" "mov\t40+%1,%%rax\n\t" "adc\t%%rax,40+%0\n\t" "mov\t48+%1,%%rax\n\t" "adc\t%%rax,48+%0" : /* no outputs */ : "o"(*A), "o"(*B) : "rax", "memory", "cc"); #else uint64_t c; ADC( A[0], A[0], B[0], 0, c ); ADC( A[1], A[1], B[1], c, c ); ADC( A[2], A[2], B[2], c, c ); ADC( A[3], A[3], B[3], c, c ); ADC( A[4], A[4], B[4], c, c ); ADC( A[5], A[5], B[5], c, c ); ADC( A[6], A[6], B[6], c, c ); #endif } static void mbedtls_p384_slu( uint64_t A[7], const uint64_t B[7] ) { #if defined(__x86_64__) && !defined(__STRICT_ANSI__) asm("mov\t%1,%%rax\n\t" "sub\t%%rax,%0\n\t" "mov\t8+%1,%%rax\n\t" "sbb\t%%rax,8+%0\n\t" "mov\t16+%1,%%rax\n\t" "sbb\t%%rax,16+%0\n\t" "mov\t24+%1,%%rax\n\t" "sbb\t%%rax,24+%0\n\t" "mov\t32+%1,%%rax\n\t" "sbb\t%%rax,32+%0\n\t" "mov\t40+%1,%%rax\n\t" "sbb\t%%rax,40+%0\n\t" "mov\t48+%1,%%rax\n\t" "sbb\t%%rax,48+%0" : /* no outputs */ : "o"(*A), "o"(*B) : "rax", "memory", "cc"); #else uint64_t c; SBB( A[0], A[0], B[0], 0, c ); SBB( A[1], A[1], B[1], c, c ); SBB( A[2], A[2], B[2], c, c ); SBB( A[3], A[3], B[3], c, c ); SBB( A[4], A[4], B[4], c, c ); SBB( A[5], A[5], B[5], c, c ); SBB( A[6], A[6], B[6], c, c ); #endif } static void mbedtls_p384_add( uint64_t X[7], const uint64_t A[6], const uint64_t B[6] ) { #if defined(__x86_64__) && !defined(__STRICT_ANSI__) asm("xor\t%%rcx,%%rcx\n\t" "mov\t%1,%%rax\n\t" "add\t%2,%%rax\n\t" "mov\t%%rax,%0\n\t" "mov\t8+%1,%%rax\n\t" "adc\t8+%2,%%rax\n\t" "mov\t%%rax,8+%0\n\t" "mov\t16+%1,%%rax\n\t" "adc\t16+%2,%%rax\n\t" "mov\t%%rax,16+%0\n\t" "mov\t24+%1,%%rax\n\t" "adc\t24+%2,%%rax\n\t" "mov\t%%rax,24+%0\n\t" "mov\t32+%1,%%rax\n\t" "adc\t32+%2,%%rax\n\t" "mov\t%%rax,32+%0\n\t" "mov\t40+%1,%%rax\n\t" "adc\t40+%2,%%rax\n\t" "mov\t%%rax,40+%0\n\t" "adc\t$0,%%rcx\n\t" "mov\t%%rcx,48+%0" : "+o"(*X) : "o"(*A), "o"(*B) : "rax", "rcx", "memory", "cc"); #else uint64_t c; ADC( X[0], A[0], B[0], 0, c ); ADC( X[1], A[1], B[1], c, c ); ADC( X[2], A[2], B[2], c, c ); ADC( X[3], A[3], B[3], c, c ); ADC( X[4], A[4], B[4], c, c ); ADC( X[5], A[5], B[5], c, X[6] ); #endif mbedtls_p384_rum( X ); MBEDTLS_ASSERT(0 == X[6]); } static void mbedtls_p384_sub( uint64_t X[7], const uint64_t A[6], const uint64_t B[6] ) { #if defined(__x86_64__) && !defined(__STRICT_ANSI__) asm("xor\t%%rcx,%%rcx\n\t" "mov\t%1,%%rax\n\t" "sub\t%2,%%rax\n\t" "mov\t%%rax,%0\n\t" "mov\t8+%1,%%rax\n\t" "sbb\t8+%2,%%rax\n\t" "mov\t%%rax,8+%0\n\t" "mov\t16+%1,%%rax\n\t" "sbb\t16+%2,%%rax\n\t" "mov\t%%rax,16+%0\n\t" "mov\t24+%1,%%rax\n\t" "sbb\t24+%2,%%rax\n\t" "mov\t%%rax,24+%0\n\t" "mov\t32+%1,%%rax\n\t" "sbb\t32+%2,%%rax\n\t" "mov\t%%rax,32+%0\n\t" "mov\t40+%1,%%rax\n\t" "sbb\t40+%2,%%rax\n\t" "mov\t%%rax,40+%0\n\t" "sbb\t$0,%%rcx\n\t" "mov\t%%rcx,48+%0" : "+o"(*X) : "o"(*A), "o"(*B) : "rax", "rcx", "memory", "cc"); #else uint64_t c; SBB( X[0], A[0], B[0], 0, c ); SBB( X[1], A[1], B[1], c, c ); SBB( X[2], A[2], B[2], c, c ); SBB( X[3], A[3], B[3], c, c ); SBB( X[4], A[4], B[4], c, c ); SBB( X[5], A[5], B[5], c, c ); X[6] = -c; #endif while( (int64_t)X[6] < 0 ) mbedtls_p384_gro( X ); MBEDTLS_ASSERT(0 == X[6]); } static void mbedtls_p384_hub( uint64_t A[7], const uint64_t B[6] ) { #if defined(__x86_64__) && !defined(__STRICT_ANSI__) asm("xor\t%%rcx,%%rcx\n\t" "mov\t%1,%%rax\n\t" "sub\t%%rax,%0\n\t" "mov\t8+%1,%%rax\n\t" "sbb\t%%rax,8+%0\n\t" "mov\t16+%1,%%rax\n\t" "sbb\t%%rax,16+%0\n\t" "mov\t24+%1,%%rax\n\t" "sbb\t%%rax,24+%0\n\t" "mov\t32+%1,%%rax\n\t" "sbb\t%%rax,32+%0\n\t" "mov\t40+%1,%%rax\n\t" "sbb\t%%rax,40+%0\n\t" "sbb\t$0,%%rcx\n\t" "mov\t%%rcx,48+%0" : "+o"(*A) : "o"(*B) : "rax", "rcx", "memory", "cc"); while( (int64_t)A[6] < 0 ) mbedtls_p384_gro( A ); MBEDTLS_ASSERT(0 == A[6]); #else mbedtls_p384_sub(A, A, B); #endif } static inline void mbedtls_p384_cop( uint64_t X[6], const uint64_t Y[6] ) { memcpy( X, Y, 6*8 ); } static int mbedtls_p384_dim( mbedtls_ecp_point *R ) { int ret; if( R->X.n < 6 && ( ret = mbedtls_mpi_grow( &R->X, 6 ) ) ) return( ret ); if( R->Y.n < 6 && ( ret = mbedtls_mpi_grow( &R->Y, 6 ) ) ) return( ret ); if( R->Z.n < 6 && ( ret = mbedtls_mpi_grow( &R->Z, 6 ) ) ) return( ret ); return( 0 ); } int mbedtls_p384_double_jac( const mbedtls_ecp_group *G, const mbedtls_ecp_point *P, mbedtls_ecp_point *R ) { int ret; uint64_t T[4][12]; if( IsAsan() ) __asan_verify( P, sizeof( *P ) ); if( IsAsan() ) __asan_verify( R, sizeof( *R ) ); if( ( ret = mbedtls_p384_dim( R ) ) ) return( ret ); if( ( ret = mbedtls_p384_dim( P ) ) ) return( ret ); mbedtls_platform_zeroize( T, sizeof( T ) ); mbedtls_p384_mul( T[1], P->Z.p, 6, P->Z.p, 6 ); mbedtls_p384_add( T[2], P->X.p, T[1] ); mbedtls_p384_sub( T[3], P->X.p, T[1] ); mbedtls_p384_mul( T[1], T[2], 6, T[3], 6 ); mbedtls_mpi_mul_hlp1( 6, T[1], T[0], 3 ); mbedtls_p384_rum( T[0] ); mbedtls_p384_mul( T[2], P->Y.p, 6, P->Y.p, 6 ); mbedtls_p384_shl( T[2] ); mbedtls_p384_mul( T[1], P->X.p, 6, T[2], 6 ); mbedtls_p384_shl( T[1] ); mbedtls_p384_mul( T[3], T[2], 6, T[2], 6 ); mbedtls_p384_shl( T[3] ); mbedtls_p384_mul( T[2], T[0], 6, T[0], 6 ); mbedtls_p384_hub( T[2], T[1] ); mbedtls_p384_hub( T[2], T[1] ); mbedtls_p384_hub( T[1], T[2] ); mbedtls_p384_mul( T[1], T[1], 6, T[0], 6 ); mbedtls_p384_hub( T[1], T[3] ); mbedtls_p384_mul( T[3], P->Y.p, 6, P->Z.p, 6 ); mbedtls_p384_shl( T[3] ); mbedtls_p384_cop( R->X.p, T[2] ); mbedtls_p384_cop( R->Y.p, T[1] ); mbedtls_p384_cop( R->Z.p, T[3] ); return( 0 ); } int mbedtls_p384_add_mixed( const mbedtls_ecp_group *G, const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q, mbedtls_ecp_point *R ) { int ret; struct { uint64_t X[12], Y[12], Z[12]; uint64_t T1[12], T2[12], T3[12], T4[12]; size_t Xn, Yn, Zn, QXn, QYn; } s; if( IsAsan() ) __asan_verify( G, sizeof( *G ) ); if( IsAsan() ) __asan_verify( P, sizeof( *P ) ); if( IsAsan() ) __asan_verify( Q, sizeof( *Q ) ); if( IsAsan() ) __asan_verify( R, sizeof( *R ) ); if( ( ret = mbedtls_p384_dim( R ) ) ) return( ret ); mbedtls_platform_zeroize( &s, sizeof( s ) ); s.Xn = mbedtls_mpi_limbs( &P->X ); s.Yn = mbedtls_mpi_limbs( &P->Y ); s.Zn = mbedtls_mpi_limbs( &P->Z ); s.QXn = mbedtls_mpi_limbs( &Q->X ); s.QYn = mbedtls_mpi_limbs( &Q->Y ); MBEDTLS_ASSERT( s.Xn <= 6 ); MBEDTLS_ASSERT( s.Yn <= 6 ); MBEDTLS_ASSERT( s.Zn <= 6 ); MBEDTLS_ASSERT( s.QXn <= 6 ); MBEDTLS_ASSERT( s.QYn <= 6 ); memcpy( s.X, P->X.p, s.Xn * 8 ); memcpy( s.Y, P->Y.p, s.Yn * 8 ); memcpy( s.Z, P->Z.p, s.Zn * 8 ); mbedtls_p384_mul( s.T1, s.Z, s.Zn, s.Z, s.Zn ); mbedtls_p384_mul( s.T2, s.T1, 6, s.Z, s.Zn ); mbedtls_p384_mul( s.T1, s.T1, 6, Q->X.p, s.QXn ); mbedtls_p384_mul( s.T2, s.T2, 6, Q->Y.p, s.QYn ); mbedtls_p384_hub( s.T1, s.X ); mbedtls_p384_hub( s.T2, s.Y ); if( mbedtls_p384_isz( s.T1 ) ) { if( mbedtls_p384_isz( s.T2 ) ) return( mbedtls_p384_double_jac( G, P, R ) ); else return( mbedtls_ecp_set_zero( R ) ); } mbedtls_p384_mul( s.Z, s.Z, s.Zn, s.T1, 6 ); mbedtls_p384_mul( s.T3, s.T1, 6, s.T1, 6 ); mbedtls_p384_mul( s.T4, s.T3, 6, s.T1, 6 ); mbedtls_p384_mul( s.T3, s.T3, 6, s.X, s.Xn ); mbedtls_p384_cop( s.T1, s.T3 ); mbedtls_p384_shl( s.T1 ); mbedtls_p384_mul( s.X, s.T2, 6, s.T2, 6 ); mbedtls_p384_hub( s.X, s.T1 ); mbedtls_p384_hub( s.X, s.T4 ); mbedtls_p384_hub( s.T3, s.X ); mbedtls_p384_mul( s.T3, s.T3, 6, s.T2, 6 ); mbedtls_p384_mul( s.T4, s.T4, 6, s.Y, s.Yn ); mbedtls_p384_sub( s.Y, s.T3, s.T4 ); mbedtls_p384_cop( R->X.p, s.X ); mbedtls_p384_cop( R->Y.p, s.Y ); mbedtls_p384_cop( R->Z.p, s.Z ); mbedtls_platform_zeroize( &s, sizeof( s ) ); return( 0 ); } static void mbedtls_p384_inv( uint64_t X[6], const uint64_t A[6], const uint64_t N[6] ) { uint64_t TA[7], TU[7], TV[7], UV[4][7]; mbedtls_platform_zeroize( UV, sizeof( UV ) ); *(uint64_t *)mempcpy( TA, A, 6*8 ) = 0; *(uint64_t *)mempcpy( TU, A, 6*8 ) = 0; *(uint64_t *)mempcpy( TV, N, 6*8 ) = 0; UV[0][0] = 1; UV[3][0] = 1; do { while( ~TU[0] & 1 ){ mbedtls_p384_sar( TU ); if( ( UV[0][0] | UV[1][0] ) & 1 ){ mbedtls_p384_gro( UV[0] ); mbedtls_p384_slu( UV[1], TA ); } mbedtls_p384_sar( UV[0] ); mbedtls_p384_sar( UV[1] ); } while( ~TV[0] & 1 ){ mbedtls_p384_sar( TV ); if( ( UV[2][0] | UV[3][0] ) & 1 ){ mbedtls_p384_gro( UV[2] ); mbedtls_p384_slu( UV[3], TA ); } mbedtls_p384_sar( UV[2] ); mbedtls_p384_sar( UV[3] ); } if( mbedtls_p384_cmp( TU, TV ) >= 0 ){ mbedtls_p384_slu( TU, TV ); mbedtls_p384_slu( UV[0], UV[2] ); mbedtls_p384_slu( UV[1], UV[3] ); } else { mbedtls_p384_slu( TV, TU ); mbedtls_p384_slu( UV[2], UV[0] ); mbedtls_p384_slu( UV[3], UV[1] ); } } while( TU[0] | TU[1] | TU[2] | TU[3] | TU[4] | TU[5] | TU[6] ); while( (int64_t)UV[2][6] < 0 ) mbedtls_p384_gro( UV[2] ); while( mbedtls_p384_gte( UV[2] ) ) mbedtls_p384_red( UV[2] ); mbedtls_p384_cop( X, UV[2] ); } int mbedtls_p384_normalize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt ) { int ret; uint64_t t[12], Zi[12], ZZi[12]; if(( ret = mbedtls_p384_dim(pt)) ) return( ret ); mbedtls_p384_inv( Zi, pt->Z.p, grp->P.p ); mbedtls_p384_mul( ZZi, Zi, 6, Zi, 6 ); mbedtls_p384_mul( t, pt->X.p, 6, ZZi, 6 ); mbedtls_p384_cop( pt->X.p, t ); mbedtls_p384_mul( t, pt->Y.p, 6, ZZi, 6 ); mbedtls_p384_mul( t, t, 6, Zi, 6 ); mbedtls_p384_cop( pt->Y.p, t ); mbedtls_mpi_lset( &pt->Z, 1 ); return( 0 ); } int mbedtls_p384_normalize_jac_many( const mbedtls_ecp_group *grp, mbedtls_ecp_point *T[], size_t n ) { size_t i; uint64_t *c, u[12], ta[12], Zi[12], ZZi[12]; if( !( c = mbedtls_calloc( n, 12*8 ) ) ) return( MBEDTLS_ERR_ECP_ALLOC_FAILED ); memcpy( c, T[0]->Z.p, T[0]->Z.n*8 ); for( i = 1; i < n; i++ ) mbedtls_p384_mul( c+i*12, c+(i-1)*12, 6, T[i]->Z.p, 6 ); mbedtls_p384_inv( u, c+(n-1)*12, grp->P.p ); for( i = n - 1; ; i-- ){ if( !i ){ mbedtls_p384_cop( Zi, u ); } else { mbedtls_p384_mul( Zi, u, 6, c+(i-1)*12, 6 ); mbedtls_p384_mul( u, u, 6, T[i]->Z.p, 6 ); } mbedtls_p384_mul( ZZi, Zi, 6, Zi, 6 ); mbedtls_p384_mul( ta, T[i]->X.p, 6, ZZi, 6 ); memcpy( T[i]->X.p, ta, 6 * 8 ); mbedtls_p384_mul( ta, T[i]->Y.p, 6, ZZi, 6 ); mbedtls_p384_mul( ta, ta, 6, Zi, 6 ); memcpy( T[i]->Y.p, ta, 6 * 8 ); mbedtls_mpi_free( &T[i]->Z ); if( !i ) break; } mbedtls_platform_zeroize( ta, sizeof( ta ) ); mbedtls_platform_zeroize( c, n*12*8 ); mbedtls_free( c ); return( 0 ); }
20,054
608
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/md.h
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_MD_H_ #define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_MD_H_ #include "third_party/mbedtls/config.h" COSMOPOLITAN_C_START_ /* clang-format off */ #define MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE -0x5080 /*< The selected feature is not available. */ #define MBEDTLS_ERR_MD_BAD_INPUT_DATA -0x5100 /*< Bad input parameters to function. */ #define MBEDTLS_ERR_MD_ALLOC_FAILED -0x5180 /*< Failed to allocate memory. */ #define MBEDTLS_ERR_MD_FILE_IO_ERROR -0x5200 /*< Opening or reading of file failed. */ /* MBEDTLS_ERR_MD_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_MD_HW_ACCEL_FAILED -0x5280 /*< MD hardware accelerator failed. */ /** * \brief Supported message digests. * * \warning MD2, MD4, MD5 and SHA-1 are considered weak message digests and * their use constitutes a security risk. We recommend considering * stronger message digests instead. */ typedef enum { MBEDTLS_MD_NONE=0, /*< None. */ MBEDTLS_MD_SHA1, /*< The SHA-1 message digest. */ MBEDTLS_MD_SHA224, /*< The SHA-224 message digest. */ MBEDTLS_MD_SHA256, /*< The SHA-256 message digest. */ MBEDTLS_MD_SHA384, /*< The SHA-384 message digest. */ MBEDTLS_MD_SHA512, /*< The SHA-512 message digest. */ MBEDTLS_MD_BLAKE2B256, /*< The BLAKE2B256 message digest. */ MBEDTLS_MD_RIPEMD160, /*< The RIPEMD-160 message digest. */ MBEDTLS_MD_MD2, /*< The MD2 message digest. */ MBEDTLS_MD_MD4, /*< The MD4 message digest. */ MBEDTLS_MD_MD5, /*< The MD5 message digest. */ } mbedtls_md_type_t; #if defined(MBEDTLS_SHA512_C) #define MBEDTLS_MD_MAX_SIZE 64 /* longest known is SHA512 */ #else #define MBEDTLS_MD_MAX_SIZE 32 /* longest known is SHA256 or less */ #endif #if defined(MBEDTLS_SHA512_C) #define MBEDTLS_MD_MAX_BLOCK_SIZE 128 #else #define MBEDTLS_MD_MAX_BLOCK_SIZE 64 #endif /** * Message digest information. * Allows message digest functions to be called in a generic way. */ typedef struct mbedtls_md_info_t { const char *name; /** Name of the message digest */ mbedtls_md_type_t type; /** Digest identifier */ unsigned char size; /** Output length of the digest function in bytes */ unsigned char block_size; /** Block length of the digest function in bytes */ int (*f_starts)(void *); int (*f_update)(void *, const void *, size_t); int (*f_process)(void *, const void *); int (*f_finish)(void *, void *); int (*f_md)(const void *, size_t, unsigned char *); } mbedtls_md_info_t; /** * The generic message-digest context. */ typedef struct mbedtls_md_context_t { const mbedtls_md_info_t *md_info; /** Information about the associated message digest. */ void *md_ctx; /** The digest-specific context. */ void *hmac_ctx; /** The HMAC part of the context. */ } mbedtls_md_context_t; const uint8_t *mbedtls_md_list( void ); const mbedtls_md_info_t *mbedtls_md_info_from_string( const char * ); const mbedtls_md_info_t *mbedtls_md_info_from_type( mbedtls_md_type_t ); int mbedtls_md_clone( mbedtls_md_context_t *, const mbedtls_md_context_t * ); int mbedtls_md_setup( mbedtls_md_context_t *, const mbedtls_md_info_t *, int ); void mbedtls_md_free( mbedtls_md_context_t * ); void mbedtls_md_init( mbedtls_md_context_t * ); /** * \brief This function extracts the message-digest size from the * message-digest information structure. * * \param md_info The information structure of the message-digest algorithm * to use. * * \return The size of the message-digest output in Bytes. */ forceinline unsigned char mbedtls_md_get_size( const mbedtls_md_info_t *md_info ) { if( !md_info ) return( 0 ); return md_info->size; } /** * \brief This function extracts the message-digest size from the * message-digest information structure. * * \param md_info The information structure of the message-digest algorithm * to use. * * \return The size of the message-digest output in Bytes. */ forceinline unsigned char mbedtls_md_get_block_size( const mbedtls_md_info_t *md_info ) { if( !md_info ) return( 0 ); return md_info->block_size; } /** * \brief This function extracts the message-digest type from the * message-digest information structure. * * \param md_info The information structure of the message-digest algorithm * to use. * * \return The type of the message digest. */ forceinline mbedtls_md_type_t mbedtls_md_get_type( const mbedtls_md_info_t *md_info ) { if( !md_info ) return( MBEDTLS_MD_NONE ); return md_info->type; } /** * \brief This function extracts the message-digest name from the * message-digest information structure. * * \param md_info The information structure of the message-digest algorithm * to use. * * \return The name of the message digest. */ forceinline const char *mbedtls_md_get_name( const mbedtls_md_info_t *md_info ) { if( !md_info ) return( NULL ); return md_info->name; } /** * \brief This function starts a message-digest computation. * * You must call this function after setting up the context * with mbedtls_md_setup(), and before passing data with * mbedtls_md_update(). * * \param ctx The generic message-digest context. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. */ forceinline int mbedtls_md_starts( mbedtls_md_context_t *ctx ) { if( !ctx || !ctx->md_info ) return( MBEDTLS_ERR_MD_BAD_INPUT_DATA ); return ctx->md_info->f_starts( ctx->md_ctx ); } /** * \brief This function feeds an input buffer into an ongoing * message-digest computation. * * You must call mbedtls_md_starts() before calling this * function. You may call this function multiple times. * Afterwards, call mbedtls_md_finish(). * * \param ctx The generic message-digest context. * \param input The buffer holding the input data. * \param ilen The length of the input data. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. */ forceinline int mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen ) { if( !ctx || !ctx->md_info ) return( MBEDTLS_ERR_MD_BAD_INPUT_DATA ); return ctx->md_info->f_update( ctx->md_ctx, input, ilen ); } /** * \brief This function finishes the digest operation, * and writes the result to the output buffer. * * Call this function after a call to mbedtls_md_starts(), * followed by any number of calls to mbedtls_md_update(). * Afterwards, you may either clear the context with * mbedtls_md_free(), or call mbedtls_md_starts() to reuse * the context for another digest operation with the same * algorithm. * * \param ctx The generic message-digest context. * \param output The buffer for the generic message-digest checksum result. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. */ forceinline int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output ) { if( !ctx || !ctx->md_info ) return( MBEDTLS_ERR_MD_BAD_INPUT_DATA ); return ctx->md_info->f_finish( ctx->md_ctx, output ); } /** * \brief This function calculates the message-digest of a buffer, * with respect to a configurable message-digest algorithm * in a single call. * * The result is calculated as * Output = message_digest(input buffer). * * \param md_info The information structure of the message-digest algorithm * to use. * \param input The buffer holding the data. * \param ilen The length of the input data. * \param output The generic message-digest checksum result. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. */ forceinline int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, size_t ilen, unsigned char *output ) { if( !md_info ) return( MBEDTLS_ERR_MD_BAD_INPUT_DATA ); return md_info->f_md(input, ilen, output ); } int mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path, unsigned char *output ); int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key, size_t keylen ); /** * \brief This function feeds an input buffer into an ongoing HMAC * computation. * * Call mbedtls_md_hmac_starts() or mbedtls_md_hmac_reset() * before calling this function. * You may call this function multiple times to pass the * input piecewise. * Afterwards, call mbedtls_md_hmac_finish(). * * \param ctx The message digest context containing an embedded HMAC * context. * \param input The buffer holding the input data. * \param ilen The length of the input data. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. */ forceinline int mbedtls_md_hmac_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen ) { if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL ) return( MBEDTLS_ERR_MD_BAD_INPUT_DATA ); return( mbedtls_md_update( ctx, input, ilen ) ); } int mbedtls_md_hmac_finish( mbedtls_md_context_t *, unsigned char *); int mbedtls_md_hmac_reset( mbedtls_md_context_t * ); int mbedtls_md_hmac( const mbedtls_md_info_t *, const unsigned char *, size_t, const unsigned char *, size_t, unsigned char * ); forceinline int mbedtls_md_process( mbedtls_md_context_t *ctx, const unsigned char *data ) { if( !ctx || !ctx->md_info ) return( MBEDTLS_ERR_MD_BAD_INPUT_DATA ); return ctx->md_info->f_process( ctx->md_ctx, data ); } const char *mbedtls_md_type_name(mbedtls_md_type_t); extern const mbedtls_md_info_t mbedtls_md2_info; extern const mbedtls_md_info_t mbedtls_md4_info; extern const mbedtls_md_info_t mbedtls_md5_info; extern const mbedtls_md_info_t mbedtls_sha1_info; extern const mbedtls_md_info_t mbedtls_sha224_info; extern const mbedtls_md_info_t mbedtls_sha256_info; extern const mbedtls_md_info_t mbedtls_sha384_info; extern const mbedtls_md_info_t mbedtls_sha512_info; extern const mbedtls_md_info_t mbedtls_blake2b256_info; COSMOPOLITAN_C_END_ #endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_MD_H_ */
11,616
301
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/base64.h
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_BASE64_H_ #define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_BASE64_H_ #include "third_party/mbedtls/config.h" COSMOPOLITAN_C_START_ /* clang-format off */ #define MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL -0x002A /*< Output buffer too small. */ #define MBEDTLS_ERR_BASE64_INVALID_CHARACTER -0x002C /*< Invalid character in input. */ int mbedtls_base64_encode(unsigned char *, size_t, size_t *, const unsigned char *, size_t); int mbedtls_base64_decode(unsigned char *, size_t, size_t *, const unsigned char *, size_t); int mbedtls_base64_self_test(int); COSMOPOLITAN_C_END_ #endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_BASE64_H_ */
664
16
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/everest.h
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_EVEREST_H_ #define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_EVEREST_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void curve25519(uint8_t[32], const uint8_t[32], const uint8_t[32]); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_EVEREST_H_ */
358
11
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/pktype.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/mbedtls/pk.h" const char *mbedtls_pk_type_name(mbedtls_pk_type_t t) { switch (t) { case MBEDTLS_PK_NONE: return "NONE"; case MBEDTLS_PK_RSA: return "RSA"; case MBEDTLS_PK_ECKEY: return "ECKEY"; case MBEDTLS_PK_ECKEY_DH: return "ECKEY_DH"; case MBEDTLS_PK_ECDSA: return "ECDSA"; case MBEDTLS_PK_RSA_ALT: return "RSA_ALT"; case MBEDTLS_PK_RSASSA_PSS: return "RSASSA_PSS"; case MBEDTLS_PK_OPAQUE: return "OPAQUE"; default: return 0; } }
2,387
43
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/net_sockets.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/calls/struct/sigaction.h" #include "libc/dns/dns.h" #include "libc/errno.h" #include "libc/sock/select.h" #include "libc/sock/struct/sockaddr6.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/f.h" #include "libc/sysv/consts/ipproto.h" #include "libc/sysv/consts/msg.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/consts/so.h" #include "libc/sysv/consts/sock.h" #include "libc/sysv/consts/sol.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/net_sockets.h" #include "third_party/mbedtls/ssl.h" #define IS_EINTR(ret) ((ret) == EINTR) static int net_prepare(void) { signal(SIGPIPE, SIG_IGN); return 0; } /** * \brief Initialize a context * Just makes the context ready to be used or freed safely. * * \param ctx Context to initialize */ void mbedtls_net_init(mbedtls_net_context *ctx) { ctx->fd = -1; } /** * \brief Initiate a connection with host:port in the given protocol * * \param ctx Socket to use * \param host Host to connect to * \param port Port to connect to * \param proto Protocol: MBEDTLS_NET_PROTO_TCP or MBEDTLS_NET_PROTO_UDP * * \return 0 if successful, or one of: * MBEDTLS_ERR_NET_SOCKET_FAILED, * MBEDTLS_ERR_NET_UNKNOWN_HOST, * MBEDTLS_ERR_NET_CONNECT_FAILED * * \note Sets the socket in connected mode even with UDP. */ int mbedtls_net_connect(mbedtls_net_context *ctx, const char *host, const char *port, int proto) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; struct addrinfo hints, *addr_list, *cur; if ((ret = net_prepare()) != 0) return ret; /* Do name resolution with both IPv6 and IPv4 */ mbedtls_platform_zeroize(&hints, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM; hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP; if (getaddrinfo(host, port, &hints, &addr_list) != 0) return MBEDTLS_ERR_NET_UNKNOWN_HOST; /* Try the sockaddrs until a connection succeeds */ ret = MBEDTLS_ERR_NET_UNKNOWN_HOST; for (cur = addr_list; cur != NULL; cur = cur->ai_next) { ctx->fd = (int)socket(cur->ai_family, cur->ai_socktype, cur->ai_protocol); if (ctx->fd < 0) { ret = MBEDTLS_ERR_NET_SOCKET_FAILED; continue; } if (connect(ctx->fd, cur->ai_addr, cur->ai_addrlen) == 0) { ret = 0; break; } close(ctx->fd); ret = MBEDTLS_ERR_NET_CONNECT_FAILED; } freeaddrinfo(addr_list); return ret; } /** * \brief Create a receiving socket on bind_ip:port in the chosen * protocol. If bind_ip == NULL, all interfaces are bound. * * \param ctx Socket to use * \param bind_ip IP to bind to, can be NULL * \param port Port number to use * \param proto Protocol: MBEDTLS_NET_PROTO_TCP or MBEDTLS_NET_PROTO_UDP * * \return 0 if successful, or one of: * MBEDTLS_ERR_NET_SOCKET_FAILED, * MBEDTLS_ERR_NET_UNKNOWN_HOST, * MBEDTLS_ERR_NET_BIND_FAILED, * MBEDTLS_ERR_NET_LISTEN_FAILED * * \note Regardless of the protocol, opens the sockets and binds it. * In addition, make the socket listening if protocol is TCP. */ int mbedtls_net_bind(mbedtls_net_context *ctx, const char *bind_ip, const char *port, int proto) { int n, ret; struct addrinfo hints, *addr_list, *cur; if ((ret = net_prepare()) != 0) return ret; /* Bind to IPv6 and/or IPv4, but only in the desired protocol */ mbedtls_platform_zeroize(&hints, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM; hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP; if (bind_ip == NULL) hints.ai_flags = AI_PASSIVE; if (getaddrinfo(bind_ip, port, &hints, &addr_list) != 0) return MBEDTLS_ERR_NET_UNKNOWN_HOST; /* Try the sockaddrs until a binding succeeds */ ret = MBEDTLS_ERR_NET_UNKNOWN_HOST; for (cur = addr_list; cur != NULL; cur = cur->ai_next) { ctx->fd = (int)socket(cur->ai_family, cur->ai_socktype, cur->ai_protocol); if (ctx->fd < 0) { ret = MBEDTLS_ERR_NET_SOCKET_FAILED; continue; } n = 1; if (setsockopt(ctx->fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&n, sizeof(n)) != 0) { close(ctx->fd); ret = MBEDTLS_ERR_NET_SOCKET_FAILED; continue; } if (bind(ctx->fd, cur->ai_addr, cur->ai_addrlen) != 0) { close(ctx->fd); ret = MBEDTLS_ERR_NET_BIND_FAILED; continue; } /* Listen only makes sense for TCP */ if (proto == MBEDTLS_NET_PROTO_TCP) { if (listen(ctx->fd, MBEDTLS_NET_LISTEN_BACKLOG) != 0) { close(ctx->fd); ret = MBEDTLS_ERR_NET_LISTEN_FAILED; continue; } } /* Bind was successful */ ret = 0; break; } freeaddrinfo(addr_list); return ret; } /* * Check if the requested operation would be blocking on a non-blocking socket * and thus 'failed' with a negative return value. * * Note: on a blocking socket this function always returns 0! */ static int net_would_block(const mbedtls_net_context *ctx) { int err = errno; /* * Never return 'WOULD BLOCK' on a blocking socket */ if ((fcntl(ctx->fd, F_GETFL) & O_NONBLOCK) != O_NONBLOCK) { errno = err; return 0; } errno = err; if (err == EAGAIN || err == EWOULDBLOCK) return 1; return 0; } /** * \brief Accept a connection from a remote client * * \param bind_ctx Relevant socket * \param client_ctx Will contain the connected client socket * \param client_ip Will contain the client IP address, can be NULL * \param buf_size Size of the client_ip buffer * \param ip_len Will receive the size of the client IP written, * can be NULL if client_ip is null * * \return 0 if successful, or * MBEDTLS_ERR_NET_SOCKET_FAILED, * MBEDTLS_ERR_NET_BIND_FAILED, * MBEDTLS_ERR_NET_ACCEPT_FAILED, or * MBEDTLS_ERR_NET_BUFFER_TOO_SMALL if buf_size is too small, * MBEDTLS_ERR_SSL_WANT_READ if bind_fd was set to * non-blocking and accept() would block. */ int mbedtls_net_accept(mbedtls_net_context *bind_ctx, mbedtls_net_context *client_ctx, void *client_ip, size_t buf_size, size_t *ip_len) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; int type; struct sockaddr_storage client_addr; #if defined(__socklen_t_defined) || defined(_SOCKLEN_T) || \ defined(_SOCKLEN_T_DECLARED) || defined(__DEFINED_socklen_t) || \ defined(socklen_t) || \ (defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L) socklen_t n = (socklen_t)sizeof(client_addr); socklen_t type_len = (socklen_t)sizeof(type); #else int n = (int)sizeof(client_addr); int type_len = (int)sizeof(type); #endif /* Is this a TCP or UDP socket? */ if (getsockopt(bind_ctx->fd, SOL_SOCKET, SO_TYPE, (void *)&type, &type_len) != 0 || (type != SOCK_STREAM && type != SOCK_DGRAM)) { return MBEDTLS_ERR_NET_ACCEPT_FAILED; } if (type == SOCK_STREAM) { /* TCP: actual accept() */ ret = client_ctx->fd = (int)accept(bind_ctx->fd, (struct sockaddr *)&client_addr, &n); } else { /* UDP: wait for a message, but keep it in the queue */ char buf[1] = {0}; ret = (int)recvfrom(bind_ctx->fd, buf, sizeof(buf), MSG_PEEK, (struct sockaddr *)&client_addr, &n); #if defined(_WIN32) if (ret == SOCKET_ERROR && WSAGetLastError() == WSAEMSGSIZE) { /* We know buf is too small, thanks, just peeking here */ ret = 0; } #endif } if (ret < 0) { if (net_would_block(bind_ctx) != 0) return MBEDTLS_ERR_SSL_WANT_READ; return MBEDTLS_ERR_NET_ACCEPT_FAILED; } /* UDP: hijack the listening socket to communicate with the client, * then bind a new socket to accept new connections */ if (type != SOCK_STREAM) { struct sockaddr_storage local_addr; int one = 1; if (connect(bind_ctx->fd, (struct sockaddr *)&client_addr, n) != 0) return MBEDTLS_ERR_NET_ACCEPT_FAILED; client_ctx->fd = bind_ctx->fd; bind_ctx->fd = -1; /* In case we exit early */ n = sizeof(struct sockaddr_storage); if (getsockname(client_ctx->fd, (struct sockaddr *)&local_addr, &n) != 0 || (bind_ctx->fd = (int)socket(local_addr.ss_family, SOCK_DGRAM, IPPROTO_UDP)) < 0 || setsockopt(bind_ctx->fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&one, sizeof(one)) != 0) { return MBEDTLS_ERR_NET_SOCKET_FAILED; } if (bind(bind_ctx->fd, (struct sockaddr *)&local_addr, n) != 0) { return MBEDTLS_ERR_NET_BIND_FAILED; } } if (client_ip != NULL) { if (client_addr.ss_family == AF_INET) { struct sockaddr_in *addr4 = (struct sockaddr_in *)&client_addr; *ip_len = sizeof(addr4->sin_addr.s_addr); if (buf_size < *ip_len) return MBEDTLS_ERR_NET_BUFFER_TOO_SMALL; memcpy(client_ip, &addr4->sin_addr.s_addr, *ip_len); } else { struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&client_addr; *ip_len = sizeof(addr6->sin6_addr.s6_addr); if (buf_size < *ip_len) return MBEDTLS_ERR_NET_BUFFER_TOO_SMALL; memcpy(client_ip, &addr6->sin6_addr.s6_addr, *ip_len); } } return 0; } /** * \brief Set the socket blocking * * \param ctx Socket to set * * \return 0 if successful, or a non-zero error code */ int mbedtls_net_set_block(mbedtls_net_context *ctx) { return fcntl(ctx->fd, F_SETFL, fcntl(ctx->fd, F_GETFL) & ~O_NONBLOCK); } /** * \brief Set the socket non-blocking * * \param ctx Socket to set * * \return 0 if successful, or a non-zero error code */ int mbedtls_net_set_nonblock(mbedtls_net_context *ctx) { return fcntl(ctx->fd, F_SETFL, fcntl(ctx->fd, F_GETFL) | O_NONBLOCK); } /** * \brief Check and wait for the context to be ready for read/write * * \note The current implementation of this function uses * select() and returns an error if the file descriptor * is \c FD_SETSIZE or greater. * * \param ctx Socket to check * \param rw Bitflag composed of MBEDTLS_NET_POLL_READ and * MBEDTLS_NET_POLL_WRITE specifying the events * to wait for: * - If MBEDTLS_NET_POLL_READ is set, the function * will return as soon as the net context is available * for reading. * - If MBEDTLS_NET_POLL_WRITE is set, the function * will return as soon as the net context is available * for writing. * \param timeout Maximal amount of time to wait before returning, * in milliseconds. If \c timeout is zero, the * function returns immediately. If \c timeout is * -1u, the function blocks potentially indefinitely. * * \return Bitmask composed of MBEDTLS_NET_POLL_READ/WRITE * on success or timeout, or a negative return code otherwise. */ int mbedtls_net_poll(mbedtls_net_context *ctx, uint32_t rw, uint32_t timeout) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; struct timeval tv; fd_set read_fds; fd_set write_fds; int fd = ctx->fd; if (fd < 0) return MBEDTLS_ERR_NET_INVALID_CONTEXT; /* A limitation of select() is that it only works with file descriptors * that are strictly less than FD_SETSIZE. This is a limitation of the * fd_set type. Error out early, because attempting to call FD_SET on a * large file descriptor is a buffer overflow on typical platforms. */ if (fd >= FD_SETSIZE) return MBEDTLS_ERR_NET_POLL_FAILED; #if defined(__has_feature) #if __has_feature(memory_sanitizer) /* Ensure that memory sanitizers consider read_fds and write_fds as * initialized even on platforms such as Glibc/x86_64 where FD_ZERO * is implemented in assembly. */ mbedtls_platform_zeroize(&read_fds, sizeof(read_fds)); mbedtls_platform_zeroize(&write_fds, sizeof(write_fds)); #endif #endif FD_ZERO(&read_fds); if (rw & MBEDTLS_NET_POLL_READ) { rw &= ~MBEDTLS_NET_POLL_READ; FD_SET(fd, &read_fds); } FD_ZERO(&write_fds); if (rw & MBEDTLS_NET_POLL_WRITE) { rw &= ~MBEDTLS_NET_POLL_WRITE; FD_SET(fd, &write_fds); } if (rw != 0) return MBEDTLS_ERR_NET_BAD_INPUT_DATA; tv.tv_sec = timeout / 1000; tv.tv_usec = (timeout % 1000) * 1000; do { ret = select(fd + 1, &read_fds, &write_fds, NULL, timeout == (uint32_t)-1 ? NULL : &tv); } while (IS_EINTR(ret)); if (ret < 0) return MBEDTLS_ERR_NET_POLL_FAILED; ret = 0; if (FD_ISSET(fd, &read_fds)) ret |= MBEDTLS_NET_POLL_READ; if (FD_ISSET(fd, &write_fds)) ret |= MBEDTLS_NET_POLL_WRITE; return ret; } /** * \brief Portable usleep helper * * \param usec Amount of microseconds to sleep * * \note Real amount of time slept will not be less than * select()'s timeout granularity (typically, 10ms). */ void mbedtls_net_usleep(unsigned long usec) { usleep(usec); } /** * \brief Read at most 'len' characters. If no error occurs, * the actual amount read is returned. * * \param ctx Socket * \param buf The buffer to write to * \param len Maximum length of the buffer * * \return the number of bytes received, * or a non-zero error code; with a non-blocking socket, * MBEDTLS_ERR_SSL_WANT_READ indicates read() would block. */ int mbedtls_net_recv(void *ctx, unsigned char *buf, size_t len) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; int fd = ((mbedtls_net_context *)ctx)->fd; if (fd < 0) return MBEDTLS_ERR_NET_INVALID_CONTEXT; ret = (int)read(fd, buf, len); if (ret < 0) { if (net_would_block(ctx) != 0) return MBEDTLS_ERR_SSL_WANT_READ; if (errno == EPIPE || errno == ECONNRESET) return MBEDTLS_ERR_NET_CONN_RESET; if (errno == EINTR) return MBEDTLS_ERR_SSL_WANT_READ; return MBEDTLS_ERR_NET_RECV_FAILED; } return ret; } /** * \brief Read at most 'len' characters, blocking for at most * 'timeout' seconds. If no error occurs, the actual amount * read is returned. * * \note The current implementation of this function uses * select() and returns an error if the file descriptor * is \c FD_SETSIZE or greater. * * \param ctx Socket * \param buf The buffer to write to * \param len Maximum length of the buffer * \param timeout Maximum number of milliseconds to wait for data * 0 means no timeout (wait forever) * * \return The number of bytes received if successful. * MBEDTLS_ERR_SSL_TIMEOUT if the operation timed out. * MBEDTLS_ERR_SSL_WANT_READ if interrupted by a signal. * Another negative error code (MBEDTLS_ERR_NET_xxx) * for other failures. * * \note This function will block (until data becomes available or * timeout is reached) even if the socket is set to * non-blocking. Handling timeouts with non-blocking reads * requires a different strategy. */ int mbedtls_net_recv_timeout(void *ctx, unsigned char *buf, size_t len, uint32_t timeout) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; struct timeval tv; fd_set read_fds; int fd = ((mbedtls_net_context *)ctx)->fd; if (fd < 0) return MBEDTLS_ERR_NET_INVALID_CONTEXT; /* A limitation of select() is that it only works with file descriptors * that are strictly less than FD_SETSIZE. This is a limitation of the * fd_set type. Error out early, because attempting to call FD_SET on a * large file descriptor is a buffer overflow on typical platforms. */ if (fd >= FD_SETSIZE) return (MBEDTLS_ERR_NET_POLL_FAILED); FD_ZERO(&read_fds); FD_SET(fd, &read_fds); tv.tv_sec = timeout / 1000; tv.tv_usec = (timeout % 1000) * 1000; ret = select(fd + 1, &read_fds, NULL, NULL, timeout == 0 ? NULL : &tv); /* Zero fds ready means we timed out */ if (ret == 0) return MBEDTLS_ERR_SSL_TIMEOUT; if (ret < 0) { if (errno == EINTR) return MBEDTLS_ERR_SSL_WANT_READ; return MBEDTLS_ERR_NET_RECV_FAILED; } /* This call will not block */ return mbedtls_net_recv(ctx, buf, len); } /** * \brief Write at most 'len' characters. If no error occurs, * the actual amount read is returned. * * \param ctx Socket * \param buf The buffer to read from * \param len The length of the buffer * * \return the number of bytes sent, * or a non-zero error code; with a non-blocking socket, * MBEDTLS_ERR_SSL_WANT_WRITE indicates write() would block. */ int mbedtls_net_send(void *ctx, const unsigned char *buf, size_t len) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; int fd = ((mbedtls_net_context *)ctx)->fd; if (fd < 0) return MBEDTLS_ERR_NET_INVALID_CONTEXT; ret = (int)write(fd, buf, len); if (ret < 0) { if (net_would_block(ctx) != 0) return MBEDTLS_ERR_SSL_WANT_WRITE; if (errno == EPIPE || errno == ECONNRESET) return MBEDTLS_ERR_NET_CONN_RESET; if (errno == EINTR) return MBEDTLS_ERR_SSL_WANT_WRITE; return MBEDTLS_ERR_NET_SEND_FAILED; } return ret; } /** * \brief Closes down the connection and free associated data * * \param ctx The context to close */ void mbedtls_net_close(mbedtls_net_context *ctx) { if (ctx->fd == -1) return; close(ctx->fd); ctx->fd = -1; } /** * \brief Gracefully shutdown the connection and free associated data * * \param ctx The context to free */ void mbedtls_net_free(mbedtls_net_context *ctx) { if (ctx->fd == -1) return; shutdown(ctx->fd, 2); close(ctx->fd); ctx->fd = -1; }
20,130
519
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/zeroize.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "third_party/mbedtls/platform.h" // disable ubsan because n=0 is defined behavior in cosmopolitan noubsan void mbedtls_platform_zeroize(void *p, size_t n) { MBEDTLS_INTERNAL_VALIDATE(!n || p); bzero(p, n); }
2,084
27
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/ssl_internal.h
#ifndef MBEDTLS_SSL_INTERNAL_H #define MBEDTLS_SSL_INTERNAL_H #include "third_party/mbedtls/cipher.h" #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/md5.h" #include "third_party/mbedtls/sha1.h" #include "third_party/mbedtls/sha256.h" #include "third_party/mbedtls/sha512.h" #include "third_party/mbedtls/ssl.h" #include "third_party/zlib/zlib.h" /* clang-format off */ /* Determine minimum supported version */ #define MBEDTLS_SSL_MIN_MAJOR_VERSION MBEDTLS_SSL_MAJOR_VERSION_3 #if defined(MBEDTLS_SSL_PROTO_SSL3) #define MBEDTLS_SSL_MIN_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_0 #else #if defined(MBEDTLS_SSL_PROTO_TLS1) #define MBEDTLS_SSL_MIN_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_1 #else #if defined(MBEDTLS_SSL_PROTO_TLS1_1) #define MBEDTLS_SSL_MIN_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_2 #else #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #define MBEDTLS_SSL_MIN_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_3 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #endif /* MBEDTLS_SSL_PROTO_TLS1_1 */ #endif /* MBEDTLS_SSL_PROTO_TLS1 */ #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #define MBEDTLS_SSL_MIN_VALID_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_1 #define MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION MBEDTLS_SSL_MAJOR_VERSION_3 /* Determine maximum supported version */ #define MBEDTLS_SSL_MAX_MAJOR_VERSION MBEDTLS_SSL_MAJOR_VERSION_3 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #define MBEDTLS_SSL_MAX_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_3 #else #if defined(MBEDTLS_SSL_PROTO_TLS1_1) #define MBEDTLS_SSL_MAX_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_2 #else #if defined(MBEDTLS_SSL_PROTO_TLS1) #define MBEDTLS_SSL_MAX_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_1 #else #if defined(MBEDTLS_SSL_PROTO_SSL3) #define MBEDTLS_SSL_MAX_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_0 #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #endif /* MBEDTLS_SSL_PROTO_TLS1 */ #endif /* MBEDTLS_SSL_PROTO_TLS1_1 */ #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #define MBEDTLS_SSL_INITIAL_HANDSHAKE 0 #define MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS 1 /* In progress */ #define MBEDTLS_SSL_RENEGOTIATION_DONE 2 /* Done or aborted */ #define MBEDTLS_SSL_RENEGOTIATION_PENDING 3 /* Requested (server only) */ /* * DTLS retransmission states, see RFC 6347 4.2.4 * * The SENDING state is merged in PREPARING for initial sends, * but is distinct for resends. * * Note: initial state is wrong for server, but is not used anyway. */ #define MBEDTLS_SSL_RETRANS_PREPARING 0 #define MBEDTLS_SSL_RETRANS_SENDING 1 #define MBEDTLS_SSL_RETRANS_WAITING 2 #define MBEDTLS_SSL_RETRANS_FINISHED 3 /* * Allow extra bytes for record, authentication and encryption overhead: * counter (8) + header (5) + IV(16) + MAC (16-48) + padding (0-256) * and allow for a maximum of 1024 of compression expansion if * enabled. */ #if defined(MBEDTLS_ZLIB_SUPPORT) #define MBEDTLS_SSL_COMPRESSION_ADD 1024 #else #define MBEDTLS_SSL_COMPRESSION_ADD 0 #endif #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) /* Ciphersuites using HMAC */ #if defined(MBEDTLS_SHA512_C) #define MBEDTLS_SSL_MAC_ADD 48 /* SHA-384 used for HMAC */ #elif defined(MBEDTLS_SHA256_C) #define MBEDTLS_SSL_MAC_ADD 32 /* SHA-256 used for HMAC */ #else #define MBEDTLS_SSL_MAC_ADD 20 /* SHA-1 used for HMAC */ #endif #else /* MBEDTLS_SSL_SOME_MODES_USE_MAC */ /* AEAD ciphersuites: GCM and CCM use a 128 bits tag */ #define MBEDTLS_SSL_MAC_ADD 16 #endif #if defined(MBEDTLS_CIPHER_MODE_CBC) #define MBEDTLS_SSL_PADDING_ADD 256 #else #define MBEDTLS_SSL_PADDING_ADD 0 #endif #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) #define MBEDTLS_SSL_MAX_CID_EXPANSION MBEDTLS_SSL_CID_PADDING_GRANULARITY #else #define MBEDTLS_SSL_MAX_CID_EXPANSION 0 #endif #define MBEDTLS_SSL_PAYLOAD_OVERHEAD ( MBEDTLS_SSL_COMPRESSION_ADD + \ MBEDTLS_MAX_IV_LENGTH + \ MBEDTLS_SSL_MAC_ADD + \ MBEDTLS_SSL_PADDING_ADD + \ MBEDTLS_SSL_MAX_CID_EXPANSION \ ) #define MBEDTLS_SSL_IN_PAYLOAD_LEN ( MBEDTLS_SSL_PAYLOAD_OVERHEAD + \ ( MBEDTLS_SSL_IN_CONTENT_LEN ) ) #define MBEDTLS_SSL_OUT_PAYLOAD_LEN ( MBEDTLS_SSL_PAYLOAD_OVERHEAD + \ ( MBEDTLS_SSL_OUT_CONTENT_LEN ) ) /* The maximum number of buffered handshake messages. */ #define MBEDTLS_SSL_MAX_BUFFERED_HS 4 /* Maximum length we can advertise as our max content length for RFC 6066 max_fragment_length extension negotiation purposes (the lesser of both sizes, if they are unequal.) */ #define MBEDTLS_TLS_EXT_ADV_CONTENT_LEN ( \ (MBEDTLS_SSL_IN_CONTENT_LEN > MBEDTLS_SSL_OUT_CONTENT_LEN) \ ? ( MBEDTLS_SSL_OUT_CONTENT_LEN ) \ : ( MBEDTLS_SSL_IN_CONTENT_LEN ) \ ) /* Maximum size in bytes of list in sig-hash algorithm ext., RFC 5246 */ #define MBEDTLS_SSL_MAX_SIG_HASH_ALG_LIST_LEN 65534 /* Maximum size in bytes of list in supported elliptic curve ext., RFC 4492 */ #define MBEDTLS_SSL_MAX_CURVE_LIST_LEN 65535 /* * Check that we obey the standard's message size bounds */ #if MBEDTLS_SSL_MAX_CONTENT_LEN > 16384 #error "Bad configuration - record content too large." #endif #if MBEDTLS_SSL_IN_CONTENT_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN #error "Bad configuration - incoming record content should not be larger than MBEDTLS_SSL_MAX_CONTENT_LEN." #endif #if MBEDTLS_SSL_OUT_CONTENT_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN #error "Bad configuration - outgoing record content should not be larger than MBEDTLS_SSL_MAX_CONTENT_LEN." #endif #if MBEDTLS_SSL_IN_PAYLOAD_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN + 2048 #error "Bad configuration - incoming protected record payload too large." #endif #if MBEDTLS_SSL_OUT_PAYLOAD_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN + 2048 #error "Bad configuration - outgoing protected record payload too large." #endif /* Calculate buffer sizes */ /* Note: Even though the TLS record header is only 5 bytes long, we're internally using 8 bytes to store the implicit sequence number. */ #define MBEDTLS_SSL_HEADER_LEN 13 #if !defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) #define MBEDTLS_SSL_IN_BUFFER_LEN \ ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_IN_PAYLOAD_LEN ) ) #else #define MBEDTLS_SSL_IN_BUFFER_LEN \ ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_IN_PAYLOAD_LEN ) \ + ( MBEDTLS_SSL_CID_IN_LEN_MAX ) ) #endif #if !defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) #define MBEDTLS_SSL_OUT_BUFFER_LEN \ ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_OUT_PAYLOAD_LEN ) ) #else #define MBEDTLS_SSL_OUT_BUFFER_LEN \ ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_OUT_PAYLOAD_LEN ) \ + ( MBEDTLS_SSL_CID_OUT_LEN_MAX ) ) #endif #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) static inline size_t mbedtls_ssl_get_output_buflen( const mbedtls_ssl_context *ctx ) { #if defined (MBEDTLS_SSL_DTLS_CONNECTION_ID) return mbedtls_ssl_get_output_max_frag_len( ctx ) + MBEDTLS_SSL_HEADER_LEN + MBEDTLS_SSL_PAYLOAD_OVERHEAD + MBEDTLS_SSL_CID_OUT_LEN_MAX; #else return mbedtls_ssl_get_output_max_frag_len( ctx ) + MBEDTLS_SSL_HEADER_LEN + MBEDTLS_SSL_PAYLOAD_OVERHEAD; #endif } static inline size_t mbedtls_ssl_get_input_buflen( const mbedtls_ssl_context *ctx ) { #if defined (MBEDTLS_SSL_DTLS_CONNECTION_ID) return mbedtls_ssl_get_input_max_frag_len( ctx ) + MBEDTLS_SSL_HEADER_LEN + MBEDTLS_SSL_PAYLOAD_OVERHEAD + MBEDTLS_SSL_CID_IN_LEN_MAX; #else return mbedtls_ssl_get_input_max_frag_len( ctx ) + MBEDTLS_SSL_HEADER_LEN + MBEDTLS_SSL_PAYLOAD_OVERHEAD; #endif } #endif #ifdef MBEDTLS_ZLIB_SUPPORT /* Compression buffer holds both IN and OUT buffers, so should be size of the larger */ #define MBEDTLS_SSL_COMPRESS_BUFFER_LEN ( \ ( MBEDTLS_SSL_IN_BUFFER_LEN > MBEDTLS_SSL_OUT_BUFFER_LEN ) \ ? MBEDTLS_SSL_IN_BUFFER_LEN \ : MBEDTLS_SSL_OUT_BUFFER_LEN \ ) #endif /* * TLS extension flags (for extensions with outgoing ServerHello content * that need it (e.g. for RENEGOTIATION_INFO the server already knows because * of state of the renegotiation flag, so no indicator is required) */ #define MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT (1 << 0) #define MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK (1 << 1) /** * \brief This function checks if the remaining size in a buffer is * greater or equal than a needed space. * * \param cur Pointer to the current position in the buffer. * \param end Pointer to one past the end of the buffer. * \param need Needed space in bytes. * * \return Zero if the needed space is available in the buffer, non-zero * otherwise. */ static inline int mbedtls_ssl_chk_buf_ptr( const uint8_t *cur, const uint8_t *end, size_t need ) { return( ( cur > end ) || ( need > (size_t)( end - cur ) ) ); } /** * \brief This macro checks if the remaining size in a buffer is * greater or equal than a needed space. If it is not the case, * it returns an SSL_BUFFER_TOO_SMALL error. * * \param cur Pointer to the current position in the buffer. * \param end Pointer to one past the end of the buffer. * \param need Needed space in bytes. * */ #define MBEDTLS_SSL_CHK_BUF_PTR( cur, end, need ) \ do { \ if( mbedtls_ssl_chk_buf_ptr( ( cur ), ( end ), ( need ) ) != 0 ) \ { \ return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); \ } \ } while( 0 ) #ifdef __cplusplus extern "C" { #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /* * Abstraction for a grid of allowed signature-hash-algorithm pairs. */ struct mbedtls_ssl_sig_hash_set_t { /* At the moment, we only need to remember a single suitable * hash algorithm per signature algorithm. As long as that's * the case - and we don't need a general lookup function - * we can implement the sig-hash-set as a map from signatures * to hash algorithms. */ mbedtls_md_type_t rsa; mbedtls_md_type_t ecdsa; }; #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ typedef int mbedtls_ssl_tls_prf_cb( const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ); /* cipher.h exports the maximum IV, key and block length from * all ciphers enabled in the config, regardless of whether those * ciphers are actually usable in SSL/TLS. Notably, XTS is enabled * in the default configuration and uses 64 Byte keys, but it is * not used for record protection in SSL/TLS. * * In order to prevent unnecessary inflation of key structures, * we introduce SSL-specific variants of the max-{key,block,IV} * macros here which are meant to only take those ciphers into * account which can be negotiated in SSL/TLS. * * Since the current definitions of MBEDTLS_MAX_{KEY|BLOCK|IV}_LENGTH * in cipher.h are rough overapproximations of the real maxima, here * we content ourselves with replicating those overapproximations * for the maximum block and IV length, and excluding XTS from the * computation of the maximum key length. */ #define MBEDTLS_SSL_MAX_BLOCK_LENGTH 16 #define MBEDTLS_SSL_MAX_IV_LENGTH 16 #define MBEDTLS_SSL_MAX_KEY_LENGTH 32 /** * \brief The data structure holding the cryptographic material (key and IV) * used for record protection in TLS 1.3. */ struct mbedtls_ssl_key_set { /*! The key for client->server records. */ unsigned char client_write_key[ MBEDTLS_SSL_MAX_KEY_LENGTH ]; /*! The key for server->client records. */ unsigned char server_write_key[ MBEDTLS_SSL_MAX_KEY_LENGTH ]; /*! The IV for client->server records. */ unsigned char client_write_iv[ MBEDTLS_SSL_MAX_IV_LENGTH ]; /*! The IV for server->client records. */ unsigned char server_write_iv[ MBEDTLS_SSL_MAX_IV_LENGTH ]; size_t key_len; /*!< The length of client_write_key and * server_write_key, in Bytes. */ size_t iv_len; /*!< The length of client_write_iv and * server_write_iv, in Bytes. */ }; typedef struct mbedtls_ssl_key_set mbedtls_ssl_key_set; /* * This structure contains the parameters only needed during handshake. */ struct mbedtls_ssl_handshake_params { /* * Handshake specific crypto variables */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) mbedtls_ssl_sig_hash_set_t hash_algs; /*!< Set of suitable sig-hash pairs */ #endif #if defined(MBEDTLS_DHM_C) mbedtls_dhm_context dhm_ctx; /*!< DHM key exchange */ #endif /* Adding guard for MBEDTLS_ECDSA_C to ensure no compile errors due * to guards also being in ssl_srv.c and ssl_cli.c. There is a gap * in functionality that access to ecdh_ctx structure is needed for * MBEDTLS_ECDSA_C which does not seem correct. */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) mbedtls_ecdh_context ecdh_ctx; /*!< ECDH key exchange */ #if defined(MBEDTLS_USE_PSA_CRYPTO) psa_key_type_t ecdh_psa_type; uint16_t ecdh_bits; psa_key_id_t ecdh_psa_privkey; unsigned char ecdh_psa_peerkey[MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH]; size_t ecdh_psa_peerkey_len; #endif /* MBEDTLS_USE_PSA_CRYPTO */ #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) mbedtls_ecjpake_context ecjpake_ctx; /*!< EC J-PAKE key exchange */ #if defined(MBEDTLS_SSL_CLI_C) unsigned char *ecjpake_cache; /*!< Cache for ClientHello ext */ size_t ecjpake_cache_len; /*!< Length of cached data */ #endif #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) const mbedtls_ecp_curve_info **curves; /*!< Supported elliptic curves */ #endif #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) #if defined(MBEDTLS_USE_PSA_CRYPTO) psa_key_id_t psk_opaque; /*!< Opaque PSK from the callback */ #endif /* MBEDTLS_USE_PSA_CRYPTO */ unsigned char *psk; /*!< PSK from the callback */ size_t psk_len; /*!< Length of PSK from callback */ #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #if defined(MBEDTLS_X509_CRT_PARSE_C) mbedtls_ssl_key_cert *key_cert; /*!< chosen key/cert pair (server) */ #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) int sni_authmode; /*!< authmode from SNI callback */ mbedtls_ssl_key_cert *sni_key_cert; /*!< key/cert list from SNI */ mbedtls_x509_crt *sni_ca_chain; /*!< trusted CAs from SNI callback */ mbedtls_x509_crl *sni_ca_crl; /*!< trusted CAs CRLs from SNI */ #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) int ecrs_enabled; /*!< Handshake supports EC restart? */ mbedtls_x509_crt_restart_ctx ecrs_ctx; /*!< restart context */ enum { /* this complements ssl->state with info on intra-state operations */ ssl_ecrs_none = 0, /*!< nothing going on (yet) */ ssl_ecrs_crt_verify, /*!< Certificate: crt_verify() */ ssl_ecrs_ske_start_processing, /*!< ServerKeyExchange: pk_verify() */ ssl_ecrs_cke_ecdh_calc_secret, /*!< ClientKeyExchange: ECDH step 2 */ ssl_ecrs_crt_vrfy_sign, /*!< CertificateVerify: pk_sign() */ } ecrs_state; /*!< current (or last) operation */ mbedtls_x509_crt *ecrs_peer_cert; /*!< The peer's CRT chain. */ size_t ecrs_n; /*!< place for saving a length */ #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) && \ !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) mbedtls_pk_context peer_pubkey; /*!< The public key from the peer. */ #endif /* MBEDTLS_X509_CRT_PARSE_C && !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ #if defined(MBEDTLS_SSL_PROTO_DTLS) unsigned int out_msg_seq; /*!< Outgoing handshake sequence number */ unsigned int in_msg_seq; /*!< Incoming handshake sequence number */ unsigned char *verify_cookie; /*!< Cli: HelloVerifyRequest cookie Srv: unused */ unsigned char verify_cookie_len; /*!< Cli: cookie length Srv: flag for sending a cookie */ uint32_t retransmit_timeout; /*!< Current value of timeout */ unsigned char retransmit_state; /*!< Retransmission state */ mbedtls_ssl_flight_item *flight; /*!< Current outgoing flight */ mbedtls_ssl_flight_item *cur_msg; /*!< Current message in flight */ unsigned char *cur_msg_p; /*!< Position in current message */ unsigned int in_flight_start_seq; /*!< Minimum message sequence in the flight being received */ mbedtls_ssl_transform *alt_transform_out; /*!< Alternative transform for resending messages */ unsigned char alt_out_ctr[8]; /*!< Alternative record epoch/counter for resending messages */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) /* The state of CID configuration in this handshake. */ uint8_t cid_in_use; /*!< This indicates whether the use of the CID extension * has been negotiated. Possible values are * #MBEDTLS_SSL_CID_ENABLED and * #MBEDTLS_SSL_CID_DISABLED. */ unsigned char peer_cid[ MBEDTLS_SSL_CID_OUT_LEN_MAX ]; /*! The peer's CID */ uint8_t peer_cid_len; /*!< The length of * \c peer_cid. */ #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ struct { size_t total_bytes_buffered; /*!< Cumulative size of heap allocated * buffers used for message buffering. */ uint8_t seen_ccs; /*!< Indicates if a CCS message has * been seen in the current flight. */ struct mbedtls_ssl_hs_buffer { unsigned is_valid : 1; unsigned is_fragmented : 1; unsigned is_complete : 1; unsigned char *data; size_t data_len; } hs[MBEDTLS_SSL_MAX_BUFFERED_HS]; struct { unsigned char *data; size_t len; unsigned epoch; } future_record; } buffering; uint16_t mtu; /*!< Handshake mtu, used to fragment outgoing messages */ #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* * Checksum contexts */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) mbedtls_md5_context fin_md5; mbedtls_sha1_context fin_sha1; #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) mbedtls_sha256_context fin_sha256; #endif #if defined(MBEDTLS_SHA512_C) mbedtls_sha512_context fin_sha512; #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ void (*update_checksum)(mbedtls_ssl_context *, const unsigned char *, size_t); void (*calc_verify)(const mbedtls_ssl_context *, unsigned char *, size_t *); void (*calc_finished)(mbedtls_ssl_context *, unsigned char *, int); mbedtls_ssl_tls_prf_cb *tls_prf; mbedtls_ssl_ciphersuite_t const *ciphersuite_info; size_t pmslen; /*!< premaster length */ unsigned char randbytes[64]; /*!< random bytes */ unsigned char premaster[MBEDTLS_PREMASTER_SIZE]; /*!< premaster secret */ int resume; /*!< session resume indicator*/ int max_major_ver; /*!< max. major version client*/ int max_minor_ver; /*!< max. minor version client*/ int cli_exts; /*!< client extension presence*/ #if defined(MBEDTLS_SSL_SESSION_TICKETS) int new_session_ticket; /*!< use NewSessionTicket? */ #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) int extended_ms; /*!< use Extended Master Secret? */ #endif #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) unsigned int async_in_progress : 1; /*!< an asynchronous operation is in progress */ #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) /** Asynchronous operation context. This field is meant for use by the * asynchronous operation callbacks (mbedtls_ssl_config::f_async_sign_start, * mbedtls_ssl_config::f_async_decrypt_start, * mbedtls_ssl_config::f_async_resume, mbedtls_ssl_config::f_async_cancel). * The library does not use it internally. */ void *user_async_ctx; #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ }; typedef struct mbedtls_ssl_hs_buffer mbedtls_ssl_hs_buffer; /* * Representation of decryption/encryption transformations on records * * There are the following general types of record transformations: * - Stream transformations (TLS versions <= 1.2 only) * Transformation adding a MAC and applying a stream-cipher * to the authenticated message. * - CBC block cipher transformations ([D]TLS versions <= 1.2 only) * In addition to the distinction of the order of encryption and * authentication, there's a fundamental difference between the * handling in SSL3 & TLS 1.0 and TLS 1.1 and TLS 1.2: For SSL3 * and TLS 1.0, the final IV after processing a record is used * as the IV for the next record. No explicit IV is contained * in an encrypted record. The IV for the first record is extracted * at key extraction time. In contrast, for TLS 1.1 and 1.2, no * IV is generated at key extraction time, but every encrypted * record is explicitly prefixed by the IV with which it was encrypted. * - AEAD transformations ([D]TLS versions >= 1.2 only) * These come in two fundamentally different versions, the first one * used in TLS 1.2, excluding ChaChaPoly ciphersuites, and the second * one used for ChaChaPoly ciphersuites in TLS 1.2 as well as for TLS 1.3. * In the first transformation, the IV to be used for a record is obtained * as the concatenation of an explicit, static 4-byte IV and the 8-byte * record sequence number, and explicitly prepending this sequence number * to the encrypted record. In contrast, in the second transformation * the IV is obtained by XOR'ing a static IV obtained at key extraction * time with the 8-byte record sequence number, without prepending the * latter to the encrypted record. * * Additionally, DTLS 1.2 + CID as well as TLS 1.3 use an inner plaintext * which allows to add flexible length padding and to hide a record's true * content type. * * In addition to type and version, the following parameters are relevant: * - The symmetric cipher algorithm to be used. * - The (static) encryption/decryption keys for the cipher. * - For stream/CBC, the type of message digest to be used. * - For stream/CBC, (static) encryption/decryption keys for the digest. * - For AEAD transformations, the size (potentially 0) of an explicit, * random initialization vector placed in encrypted records. * - For some transformations (currently AEAD and CBC in SSL3 and TLS 1.0) * an implicit IV. It may be static (e.g. AEAD) or dynamic (e.g. CBC) * and (if present) is combined with the explicit IV in a transformation- * dependent way (e.g. appending in TLS 1.2 and XOR'ing in TLS 1.3). * - For stream/CBC, a flag determining the order of encryption and MAC. * - The details of the transformation depend on the SSL/TLS version. * - The length of the authentication tag. * * Note: Except for CBC in SSL3 and TLS 1.0, these parameters are * constant across multiple encryption/decryption operations. * For CBC, the implicit IV needs to be updated after each * operation. * * The struct below refines this abstract view as follows: * - The cipher underlying the transformation is managed in * cipher contexts cipher_ctx_{enc/dec}, which must have the * same cipher type. The mode of these cipher contexts determines * the type of the transformation in the sense above: e.g., if * the type is MBEDTLS_CIPHER_AES_256_CBC resp. MBEDTLS_CIPHER_AES_192_GCM * then the transformation has type CBC resp. AEAD. * - The cipher keys are never stored explicitly but * are maintained within cipher_ctx_{enc/dec}. * - For stream/CBC transformations, the message digest contexts * used for the MAC's are stored in md_ctx_{enc/dec}. These contexts * are unused for AEAD transformations. * - For stream/CBC transformations and versions > SSL3, the * MAC keys are not stored explicitly but maintained within * md_ctx_{enc/dec}. * - For stream/CBC transformations and version SSL3, the MAC * keys are stored explicitly in mac_enc, mac_dec and have * a fixed size of 20 bytes. These fields are unused for * AEAD transformations or transformations >= TLS 1.0. * - For transformations using an implicit IV maintained within * the transformation context, its contents are stored within * iv_{enc/dec}. * - The value of ivlen indicates the length of the IV. * This is redundant in case of stream/CBC transformations * which always use 0 resp. the cipher's block length as the * IV length, but is needed for AEAD ciphers and may be * different from the underlying cipher's block length * in this case. * - The field fixed_ivlen is nonzero for AEAD transformations only * and indicates the length of the static part of the IV which is * constant throughout the communication, and which is stored in * the first fixed_ivlen bytes of the iv_{enc/dec} arrays. * Note: For CBC in SSL3 and TLS 1.0, the fields iv_{enc/dec} * still store IV's for continued use across multiple transformations, * so it is not true that fixed_ivlen == 0 means that iv_{enc/dec} are * not being used! * - minor_ver denotes the SSL/TLS version * - For stream/CBC transformations, maclen denotes the length of the * authentication tag, while taglen is unused and 0. * - For AEAD transformations, taglen denotes the length of the * authentication tag, while maclen is unused and 0. * - For CBC transformations, encrypt_then_mac determines the * order of encryption and authentication. This field is unused * in other transformations. * */ struct mbedtls_ssl_transform { /* * Session specific crypto layer */ size_t minlen; /*!< min. ciphertext length */ size_t ivlen; /*!< IV length */ size_t fixed_ivlen; /*!< Fixed part of IV (AEAD) */ size_t maclen; /*!< MAC(CBC) len */ size_t taglen; /*!< TAG(AEAD) len */ unsigned char iv_enc[16]; /*!< IV (encryption) */ unsigned char iv_dec[16]; /*!< IV (decryption) */ #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) #if defined(MBEDTLS_SSL_PROTO_SSL3) /* Needed only for SSL v3.0 secret */ unsigned char mac_enc[20]; /*!< SSL v3.0 secret (enc) */ unsigned char mac_dec[20]; /*!< SSL v3.0 secret (dec) */ #endif /* MBEDTLS_SSL_PROTO_SSL3 */ mbedtls_md_context_t md_ctx_enc; /*!< MAC (encryption) */ mbedtls_md_context_t md_ctx_dec; /*!< MAC (decryption) */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) int encrypt_then_mac; /*!< flag for EtM activation */ #endif #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */ mbedtls_cipher_context_t cipher_ctx_enc; /*!< encryption context */ mbedtls_cipher_context_t cipher_ctx_dec; /*!< decryption context */ int minor_ver; #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) uint8_t in_cid_len; uint8_t out_cid_len; unsigned char in_cid [ MBEDTLS_SSL_CID_OUT_LEN_MAX ]; unsigned char out_cid[ MBEDTLS_SSL_CID_OUT_LEN_MAX ]; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ /* * Session specific compression layer */ #if defined(MBEDTLS_ZLIB_SUPPORT) z_stream ctx_deflate; /*!< compression context */ z_stream ctx_inflate; /*!< decompression context */ #endif #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION) /* We need the Hello random bytes in order to re-derive keys from the * Master Secret and other session info, see ssl_populate_transform() */ unsigned char randbytes[64]; /*!< ServerHello.random+ClientHello.random */ #endif /* MBEDTLS_SSL_CONTEXT_SERIALIZATION */ }; /* * Return 1 if the transform uses an AEAD cipher, 0 otherwise. * Equivalently, return 0 if a separate MAC is used, 1 otherwise. */ static inline int mbedtls_ssl_transform_uses_aead( const mbedtls_ssl_transform *transform ) { #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) return( transform->maclen == 0 && transform->taglen != 0 ); #else (void) transform; return( 1 ); #endif } /* * Internal representation of record frames * * Instances come in two flavors: * (1) Encrypted * These always have data_offset = 0 * (2) Unencrypted * These have data_offset set to the amount of * pre-expansion during record protection. Concretely, * this is the length of the fixed part of the explicit IV * used for encryption, or 0 if no explicit IV is used * (e.g. for CBC in TLS 1.0, or stream ciphers). * * The reason for the data_offset in the unencrypted case * is to allow for in-place conversion of an unencrypted to * an encrypted record. If the offset wasn't included, the * encrypted content would need to be shifted afterwards to * make space for the fixed IV. * */ #if MBEDTLS_SSL_CID_OUT_LEN_MAX > MBEDTLS_SSL_CID_IN_LEN_MAX #define MBEDTLS_SSL_CID_LEN_MAX MBEDTLS_SSL_CID_OUT_LEN_MAX #else #define MBEDTLS_SSL_CID_LEN_MAX MBEDTLS_SSL_CID_IN_LEN_MAX #endif typedef struct { uint8_t ctr[8]; /* In TLS: The implicit record sequence number. * In DTLS: The 2-byte epoch followed by * the 6-byte sequence number. * This is stored as a raw big endian byte array * as opposed to a uint64_t because we rarely * need to perform arithmetic on this, but do * need it as a Byte array for the purpose of * MAC computations. */ uint8_t type; /* The record content type. */ uint8_t ver[2]; /* SSL/TLS version as present on the wire. * Convert to internal presentation of versions * using mbedtls_ssl_read_version() and * mbedtls_ssl_write_version(). * Keep wire-format for MAC computations. */ unsigned char *buf; /* Memory buffer enclosing the record content */ size_t buf_len; /* Buffer length */ size_t data_offset; /* Offset of record content */ size_t data_len; /* Length of record content */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) uint8_t cid_len; /* Length of the CID (0 if not present) */ unsigned char cid[ MBEDTLS_SSL_CID_LEN_MAX ]; /* The CID */ #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ } mbedtls_record; #if defined(MBEDTLS_X509_CRT_PARSE_C) /* * List of certificate + private key pairs */ struct mbedtls_ssl_key_cert { mbedtls_x509_crt *cert; /*!< cert */ mbedtls_pk_context *key; /*!< private key */ mbedtls_ssl_key_cert *next; /*!< next key/cert pair */ }; #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_SSL_PROTO_DTLS) /* * List of handshake messages kept around for resending */ struct mbedtls_ssl_flight_item { unsigned char *p; /*!< message, including handshake headers */ size_t len; /*!< length of p */ unsigned char type; /*!< type of the message: handshake or CCS */ mbedtls_ssl_flight_item *next; /*!< next handshake message(s) */ }; #endif /* MBEDTLS_SSL_PROTO_DTLS */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /* Find an entry in a signature-hash set matching a given hash algorithm. */ mbedtls_md_type_t mbedtls_ssl_sig_hash_set_find( mbedtls_ssl_sig_hash_set_t *set, mbedtls_pk_type_t sig_alg ); /* Allow exactly one hash algorithm for each signature. */ void mbedtls_ssl_sig_hash_set_const_hash( mbedtls_ssl_sig_hash_set_t *set, mbedtls_md_type_t md_alg ); /* Setup an empty signature-hash set */ static inline void mbedtls_ssl_sig_hash_set_init( mbedtls_ssl_sig_hash_set_t *set ) { mbedtls_ssl_sig_hash_set_const_hash( set, MBEDTLS_MD_NONE ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_2) && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ void mbedtls_ssl_transform_free( mbedtls_ssl_transform * ); void mbedtls_ssl_handshake_free( mbedtls_ssl_context * ); void mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context * ); int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context * ); void mbedtls_ssl_reset_checksum( mbedtls_ssl_context * ); int mbedtls_ssl_derive_keys( mbedtls_ssl_context * ); int mbedtls_ssl_handle_message_type( mbedtls_ssl_context * ); int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context * ); void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context * ); int mbedtls_ssl_read_record( mbedtls_ssl_context *, unsigned ); int mbedtls_ssl_fetch_input( mbedtls_ssl_context *, size_t ); int mbedtls_ssl_write_handshake_msg( mbedtls_ssl_context * ); int mbedtls_ssl_write_record( mbedtls_ssl_context *, uint8_t ); int mbedtls_ssl_flush_output( mbedtls_ssl_context * ); int mbedtls_ssl_parse_certificate( mbedtls_ssl_context * ); int mbedtls_ssl_write_certificate( mbedtls_ssl_context * ); int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context * ); int mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context * ); int mbedtls_ssl_parse_finished( mbedtls_ssl_context * ); int mbedtls_ssl_write_finished( mbedtls_ssl_context * ); void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *, const mbedtls_ssl_ciphersuite_t * ); #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *, mbedtls_key_exchange_type_t ); /** * Get the first defined PSK by order of precedence: * 1. handshake PSK set by \c mbedtls_ssl_set_hs_psk() in the PSK callback * 2. static PSK configured by \c mbedtls_ssl_conf_psk() * Return a code and update the pair (PSK, PSK length) passed to this function */ static inline int mbedtls_ssl_get_psk( const mbedtls_ssl_context *ssl, const unsigned char **psk, size_t *psk_len ) { if( ssl->handshake->psk != NULL && ssl->handshake->psk_len > 0 ) { *psk = ssl->handshake->psk; *psk_len = ssl->handshake->psk_len; } else if( ssl->conf->psk != NULL && ssl->conf->psk_len > 0 ) { *psk = ssl->conf->psk; *psk_len = ssl->conf->psk_len; } else { *psk = NULL; *psk_len = 0; return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); } return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #if defined(MBEDTLS_PK_C) unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context * ); unsigned char mbedtls_ssl_sig_from_pk_alg( mbedtls_pk_type_t ); #endif unsigned char mbedtls_ssl_hash_from_md_alg( int ); int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *, int ); #if defined(MBEDTLS_ECP_C) int mbedtls_ssl_check_curve( const mbedtls_ssl_context *, mbedtls_ecp_group_id ); #endif #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) int mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl, mbedtls_md_type_t md ); #endif #if defined(MBEDTLS_SSL_DTLS_SRTP) static inline mbedtls_ssl_srtp_profile mbedtls_ssl_check_srtp_profile_value ( const uint16_t srtp_profile_value ) { switch( srtp_profile_value ) { case MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_80: case MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_32: case MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_80: case MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_32: return srtp_profile_value; default: break; } return( MBEDTLS_TLS_SRTP_UNSET ); } #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) static inline mbedtls_pk_context *mbedtls_ssl_own_key( mbedtls_ssl_context *ssl ) { mbedtls_ssl_key_cert *key_cert; if( ssl->handshake != NULL && ssl->handshake->key_cert != NULL ) key_cert = ssl->handshake->key_cert; else key_cert = ssl->conf->key_cert; return( key_cert == NULL ? NULL : key_cert->key ); } static inline mbedtls_x509_crt *mbedtls_ssl_own_cert( mbedtls_ssl_context *ssl ) { mbedtls_ssl_key_cert *key_cert; if( ssl->handshake != NULL && ssl->handshake->key_cert != NULL ) key_cert = ssl->handshake->key_cert; else key_cert = ssl->conf->key_cert; return( key_cert == NULL ? NULL : key_cert->cert ); } /* * Check usage of a certificate wrt extensions: * keyUsage, extendedKeyUsage (later), and nSCertType (later). * * Warning: cert_endpoint is the endpoint of the cert (ie, of our peer when we * check a cert we received from them)! * * Return 0 if everything is OK, -1 if not. */ int mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert, const mbedtls_ssl_ciphersuite_t *ciphersuite, int cert_endpoint, uint32_t *flags ); #endif /* MBEDTLS_X509_CRT_PARSE_C */ void mbedtls_ssl_write_version( int major, int minor, int transport, unsigned char ver[2] ); void mbedtls_ssl_read_version( int *major, int *minor, int transport, const unsigned char ver[2] ); static inline size_t mbedtls_ssl_in_hdr_len( const mbedtls_ssl_context *ssl ) { #if !defined(MBEDTLS_SSL_PROTO_DTLS) ((void) ssl); #endif #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { return( 13 ); } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ { return( 5 ); } } static inline size_t mbedtls_ssl_out_hdr_len( const mbedtls_ssl_context *ssl ) { return( (size_t) ( ssl->out_iv - ssl->out_hdr ) ); } static inline size_t mbedtls_ssl_hs_hdr_len( const mbedtls_ssl_context *ssl ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) return( 12 ); #else ((void) ssl); #endif return( 4 ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context * ); void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context * ); int mbedtls_ssl_resend( mbedtls_ssl_context * ); int mbedtls_ssl_flight_transmit( mbedtls_ssl_context * ); #endif /* Visible for testing purposes only */ #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) int mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context const * ); void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context * ); #endif int mbedtls_ssl_session_copy( mbedtls_ssl_session *, const mbedtls_ssl_session * ); #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) int mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl, unsigned char *output, unsigned char *data, size_t data_len ); #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \ MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) /* The hash buffer must have at least MBEDTLS_MD_MAX_SIZE bytes of length. */ int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl, unsigned char *hash, size_t *hashlen, unsigned char *data, size_t data_len, mbedtls_md_type_t md_alg ); #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ #ifdef __cplusplus } #endif void mbedtls_ssl_transform_init( mbedtls_ssl_transform * ); int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *, mbedtls_ssl_transform *, mbedtls_record *, int (*)(void *, unsigned char *, size_t), void * ); int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context const *, mbedtls_ssl_transform *, mbedtls_record * ); /* Length of the "epoch" field in the record header */ static inline size_t mbedtls_ssl_ep_len( const mbedtls_ssl_context *ssl ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) return( 2 ); #else ((void) ssl); #endif return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) int mbedtls_ssl_resend_hello_request( mbedtls_ssl_context *ssl ); #endif /* MBEDTLS_SSL_PROTO_DTLS */ void mbedtls_ssl_set_timer( mbedtls_ssl_context *ssl, uint32_t millisecs ); int mbedtls_ssl_check_timer( mbedtls_ssl_context *ssl ); void mbedtls_ssl_reset_in_out_pointers( mbedtls_ssl_context *ssl ); void mbedtls_ssl_update_out_pointers( mbedtls_ssl_context *ssl, mbedtls_ssl_transform *transform ); void mbedtls_ssl_update_in_pointers( mbedtls_ssl_context *ssl ); int mbedtls_ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial ); #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) void mbedtls_ssl_dtls_replay_reset( mbedtls_ssl_context *ssl ); #endif void mbedtls_ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl ); #if defined(MBEDTLS_SSL_RENEGOTIATION) int mbedtls_ssl_start_renegotiation( mbedtls_ssl_context *ssl ); #endif /* MBEDTLS_SSL_RENEGOTIATION */ #if defined(MBEDTLS_SSL_PROTO_DTLS) size_t mbedtls_ssl_get_current_mtu( const mbedtls_ssl_context *ssl ); void mbedtls_ssl_buffering_free( mbedtls_ssl_context *ssl ); void mbedtls_ssl_flight_free( mbedtls_ssl_flight_item *flight ); #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* * Convert from MBEDTLS_SSL_HASH_XXX to MBEDTLS_MD_XXX */ forceinline mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash ) { switch( hash ) { #if defined(MBEDTLS_MD5_C) case MBEDTLS_SSL_HASH_MD5: return( MBEDTLS_MD_MD5 ); #endif #if defined(MBEDTLS_SHA1_C) case MBEDTLS_SSL_HASH_SHA1: return( MBEDTLS_MD_SHA1 ); #endif #if defined(MBEDTLS_SHA256_C) case MBEDTLS_SSL_HASH_SHA224: return( MBEDTLS_MD_SHA224 ); case MBEDTLS_SSL_HASH_SHA256: return( MBEDTLS_MD_SHA256 ); #endif #if defined(MBEDTLS_SHA512_C) case MBEDTLS_SSL_HASH_SHA384: return( MBEDTLS_MD_SHA384 ); case MBEDTLS_SSL_HASH_SHA512: return( MBEDTLS_MD_SHA512 ); #endif default: return( MBEDTLS_MD_NONE ); } } forceinline mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig ) { switch( sig ) { #if defined(MBEDTLS_RSA_C) case MBEDTLS_SSL_SIG_RSA: return( MBEDTLS_PK_RSA ); #endif #if defined(MBEDTLS_ECDSA_C) case MBEDTLS_SSL_SIG_ECDSA: return( MBEDTLS_PK_ECDSA ); #endif default: return( MBEDTLS_PK_NONE ); } } #endif /* ssl_internal.h */
45,448
1,100
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/cipher.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "third_party/mbedtls/ccm.h" #include "third_party/mbedtls/chacha20.h" #include "third_party/mbedtls/chachapoly.h" #include "third_party/mbedtls/cipher.h" #include "third_party/mbedtls/cipher_internal.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/gcm.h" #include "third_party/mbedtls/nist_kw.h" #include "third_party/mbedtls/platform.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ #if defined(MBEDTLS_CIPHER_C) #define CIPHER_VALIDATE_RET( cond ) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ) #define CIPHER_VALIDATE( cond ) \ MBEDTLS_INTERNAL_VALIDATE( cond ) static int supported_init = 0; const int *mbedtls_cipher_list( void ) { const mbedtls_cipher_definition_t *def; int *type; if( ! supported_init ) { def = mbedtls_cipher_definitions; type = mbedtls_cipher_supported; while( def->type != 0 ) *type++ = (*def++).type; *type = 0; supported_init = 1; } return( mbedtls_cipher_supported ); } const mbedtls_cipher_info_t *mbedtls_cipher_info_from_type( const mbedtls_cipher_type_t cipher_type ) { const mbedtls_cipher_definition_t *def; for( def = mbedtls_cipher_definitions; def->info != NULL; def++ ) if( def->type == cipher_type ) return( def->info ); return( NULL ); } const mbedtls_cipher_info_t *mbedtls_cipher_info_from_string( const char *cipher_name ) { const mbedtls_cipher_definition_t *def; if( NULL == cipher_name ) return( NULL ); for( def = mbedtls_cipher_definitions; def->info != NULL; def++ ) if( ! strcmp( def->info->name, cipher_name ) ) return( def->info ); return( NULL ); } const mbedtls_cipher_info_t *mbedtls_cipher_info_from_values( const mbedtls_cipher_id_t cipher_id, int key_bitlen, const mbedtls_cipher_mode_t mode ) { const mbedtls_cipher_definition_t *def; for( def = mbedtls_cipher_definitions; def->info != NULL; def++ ) if( def->info->base->cipher == cipher_id && def->info->key_bitlen == (unsigned) key_bitlen && def->info->mode == mode ) return( def->info ); return( NULL ); } void mbedtls_cipher_init( mbedtls_cipher_context_t *ctx ) { CIPHER_VALIDATE( ctx != NULL ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_cipher_context_t ) ); } void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx ) { if( ctx == NULL ) return; #if defined(MBEDTLS_USE_PSA_CRYPTO) if( ctx->psa_enabled == 1 ) { if( ctx->cipher_ctx != NULL ) { mbedtls_cipher_context_psa * const cipher_psa = (mbedtls_cipher_context_psa *) ctx->cipher_ctx; if( cipher_psa->slot_state == MBEDTLS_CIPHER_PSA_KEY_OWNED ) { /* xxx_free() doesn't allow to return failures. */ (void) psa_destroy_key( cipher_psa->slot ); } mbedtls_platform_zeroize( cipher_psa, sizeof( *cipher_psa ) ); mbedtls_free( cipher_psa ); } mbedtls_platform_zeroize( ctx, sizeof(mbedtls_cipher_context_t) ); return; } #endif /* MBEDTLS_USE_PSA_CRYPTO */ #if defined(MBEDTLS_CMAC_C) if( ctx->cmac_ctx ) { mbedtls_platform_zeroize( ctx->cmac_ctx, sizeof( mbedtls_cmac_context_t ) ); mbedtls_free( ctx->cmac_ctx ); } #endif if( ctx->cipher_ctx ) ctx->cipher_info->base->ctx_free_func( ctx->cipher_ctx ); mbedtls_platform_zeroize( ctx, sizeof(mbedtls_cipher_context_t) ); } int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_info_t *cipher_info ) { CIPHER_VALIDATE_RET( ctx != NULL ); if( cipher_info == NULL ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_cipher_context_t ) ); if( NULL == ( ctx->cipher_ctx = cipher_info->base->ctx_alloc_func() ) ) return( MBEDTLS_ERR_CIPHER_ALLOC_FAILED ); ctx->cipher_info = cipher_info; #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING) /* * Ignore possible errors caused by a cipher mode that doesn't use padding */ #if defined(MBEDTLS_CIPHER_PADDING_PKCS7) (void) mbedtls_cipher_set_padding_mode( ctx, MBEDTLS_PADDING_PKCS7 ); #else (void) mbedtls_cipher_set_padding_mode( ctx, MBEDTLS_PADDING_NONE ); #endif #endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */ return( 0 ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) int mbedtls_cipher_setup_psa( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_info_t *cipher_info, size_t taglen ) { psa_algorithm_t alg; mbedtls_cipher_context_psa *cipher_psa; if( NULL == cipher_info || NULL == ctx ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); /* Check that the underlying cipher mode and cipher type are * supported by the underlying PSA Crypto implementation. */ alg = mbedtls_psa_translate_cipher_mode( cipher_info->mode, taglen ); if( alg == 0 ) return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); if( mbedtls_psa_translate_cipher_type( cipher_info->type ) == 0 ) return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_cipher_context_t ) ); cipher_psa = mbedtls_calloc( 1, sizeof(mbedtls_cipher_context_psa ) ); if( cipher_psa == NULL ) return( MBEDTLS_ERR_CIPHER_ALLOC_FAILED ); cipher_psa->alg = alg; ctx->cipher_ctx = cipher_psa; ctx->cipher_info = cipher_info; ctx->psa_enabled = 1; return( 0 ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *key, int key_bitlen, const mbedtls_operation_t operation ) { CIPHER_VALIDATE_RET( ctx != NULL ); CIPHER_VALIDATE_RET( key != NULL ); CIPHER_VALIDATE_RET( operation == MBEDTLS_ENCRYPT || operation == MBEDTLS_DECRYPT ); if( ctx->cipher_info == NULL ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); #if defined(MBEDTLS_USE_PSA_CRYPTO) if( ctx->psa_enabled == 1 ) { mbedtls_cipher_context_psa * const cipher_psa = (mbedtls_cipher_context_psa *) ctx->cipher_ctx; size_t const key_bytelen = ( (size_t) key_bitlen + 7 ) / 8; psa_status_t status; psa_key_type_t key_type; psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; /* PSA Crypto API only accepts byte-aligned keys. */ if( key_bitlen % 8 != 0 ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); /* Don't allow keys to be set multiple times. */ if( cipher_psa->slot_state != MBEDTLS_CIPHER_PSA_KEY_UNSET ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); key_type = mbedtls_psa_translate_cipher_type( ctx->cipher_info->type ); if( key_type == 0 ) return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); psa_set_key_type( &attributes, key_type ); /* Mbed TLS' cipher layer doesn't enforce the mode of operation * (encrypt vs. decrypt): it is possible to setup a key for encryption * and use it for AEAD decryption. Until tests relying on this * are changed, allow any usage in PSA. */ psa_set_key_usage_flags( &attributes, /* mbedtls_psa_translate_cipher_operation( operation ); */ PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT ); psa_set_key_algorithm( &attributes, cipher_psa->alg ); status = psa_import_key( &attributes, key, key_bytelen, &cipher_psa->slot ); switch( status ) { case PSA_SUCCESS: break; case PSA_ERROR_INSUFFICIENT_MEMORY: return( MBEDTLS_ERR_CIPHER_ALLOC_FAILED ); case PSA_ERROR_NOT_SUPPORTED: return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); default: return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED ); } /* Indicate that we own the key slot and need to * destroy it in mbedtls_cipher_free(). */ cipher_psa->slot_state = MBEDTLS_CIPHER_PSA_KEY_OWNED; ctx->key_bitlen = key_bitlen; ctx->operation = operation; return( 0 ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ if( ( ctx->cipher_info->flags & MBEDTLS_CIPHER_VARIABLE_KEY_LEN ) == 0 && (int) ctx->cipher_info->key_bitlen != key_bitlen ) { return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } ctx->key_bitlen = key_bitlen; ctx->operation = operation; /* * For OFB, CFB and CTR mode always use the encryption key schedule */ if( MBEDTLS_ENCRYPT == operation || MBEDTLS_MODE_CFB == ctx->cipher_info->mode || MBEDTLS_MODE_OFB == ctx->cipher_info->mode || MBEDTLS_MODE_CTR == ctx->cipher_info->mode ) { return( ctx->cipher_info->base->setkey_enc_func( ctx->cipher_ctx, key, ctx->key_bitlen ) ); } if( MBEDTLS_DECRYPT == operation ) return( ctx->cipher_info->base->setkey_dec_func( ctx->cipher_ctx, key, ctx->key_bitlen ) ); return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len ) { size_t actual_iv_size; CIPHER_VALIDATE_RET( ctx != NULL ); CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL ); if( ctx->cipher_info == NULL ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); #if defined(MBEDTLS_USE_PSA_CRYPTO) if( ctx->psa_enabled == 1 ) { /* While PSA Crypto has an API for multipart * operations, we currently don't make it * accessible through the cipher layer. */ return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ /* avoid buffer overflow in ctx->iv */ if( iv_len > MBEDTLS_MAX_IV_LENGTH ) return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); if( ( ctx->cipher_info->flags & MBEDTLS_CIPHER_VARIABLE_IV_LEN ) != 0 ) actual_iv_size = iv_len; else { actual_iv_size = ctx->cipher_info->iv_size; /* avoid reading past the end of input buffer */ if( actual_iv_size > iv_len ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } #if defined(MBEDTLS_CHACHA20_C) if ( ctx->cipher_info->type == MBEDTLS_CIPHER_CHACHA20 ) { if ( 0 != mbedtls_chacha20_starts( (mbedtls_chacha20_context*)ctx->cipher_ctx, iv, 0U ) ) /* Initial counter value */ { return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } } #endif if ( actual_iv_size != 0 ) { memcpy( ctx->iv, iv, actual_iv_size ); ctx->iv_size = actual_iv_size; } return( 0 ); } int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx ) { CIPHER_VALIDATE_RET( ctx != NULL ); if( ctx->cipher_info == NULL ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); #if defined(MBEDTLS_USE_PSA_CRYPTO) if( ctx->psa_enabled == 1 ) { /* We don't support resetting PSA-based * cipher contexts, yet. */ return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ ctx->unprocessed_len = 0; return( 0 ); } #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C) int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx, const unsigned char *ad, size_t ad_len ) { CIPHER_VALIDATE_RET( ctx != NULL ); CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL ); if( ctx->cipher_info == NULL ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); #if defined(MBEDTLS_USE_PSA_CRYPTO) if( ctx->psa_enabled == 1 ) { /* While PSA Crypto has an API for multipart * operations, we currently don't make it * accessible through the cipher layer. */ return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ #if defined(MBEDTLS_GCM_C) if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode ) { return( mbedtls_gcm_starts( (mbedtls_gcm_context *) ctx->cipher_ctx, ctx->operation, ctx->iv, ctx->iv_size, ad, ad_len ) ); } #endif #if defined(MBEDTLS_CHACHAPOLY_C) if (MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type ) { int result; mbedtls_chachapoly_mode_t mode; mode = ( ctx->operation == MBEDTLS_ENCRYPT ) ? MBEDTLS_CHACHAPOLY_ENCRYPT : MBEDTLS_CHACHAPOLY_DECRYPT; result = mbedtls_chachapoly_starts( (mbedtls_chachapoly_context*) ctx->cipher_ctx, ctx->iv, mode ); if ( result != 0 ) return( result ); return( mbedtls_chachapoly_update_aad( (mbedtls_chachapoly_context*) ctx->cipher_ctx, ad, ad_len ) ); } #endif return( 0 ); } #endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t block_size; CIPHER_VALIDATE_RET( ctx != NULL ); CIPHER_VALIDATE_RET( ilen == 0 || input != NULL ); CIPHER_VALIDATE_RET( output != NULL ); CIPHER_VALIDATE_RET( olen != NULL ); if( ctx->cipher_info == NULL ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); *olen = 0; block_size = mbedtls_cipher_get_block_size( ctx ); if ( 0 == block_size ) { return( MBEDTLS_ERR_CIPHER_INVALID_CONTEXT ); } if( ctx->cipher_info->mode == MBEDTLS_MODE_ECB ) { if( ilen != block_size ) return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED ); *olen = ilen; if( ( ret = ctx->cipher_info->base->ecb_func( ctx->cipher_ctx, ctx->operation, input, output ) ) ) { return( ret ); } return( 0 ); } #if defined(MBEDTLS_GCM_C) if( ctx->cipher_info->mode == MBEDTLS_MODE_GCM ) { *olen = ilen; return( mbedtls_gcm_update( (mbedtls_gcm_context *) ctx->cipher_ctx, ilen, input, output ) ); } #endif #if defined(MBEDTLS_CHACHAPOLY_C) if ( ctx->cipher_info->type == MBEDTLS_CIPHER_CHACHA20_POLY1305 ) { *olen = ilen; return( mbedtls_chachapoly_update( (mbedtls_chachapoly_context*) ctx->cipher_ctx, ilen, input, output ) ); } #endif if( input == output && ( ctx->unprocessed_len != 0 || ilen % block_size ) ) { return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } #if defined(MBEDTLS_CIPHER_MODE_CBC) if( ctx->cipher_info->mode == MBEDTLS_MODE_CBC ) { size_t copy_len = 0; /* * If there is not enough data for a full block, cache it. */ if( ( ctx->operation == MBEDTLS_DECRYPT && NULL != ctx->add_padding && ilen <= block_size - ctx->unprocessed_len ) || ( ctx->operation == MBEDTLS_DECRYPT && NULL == ctx->add_padding && ilen < block_size - ctx->unprocessed_len ) || ( ctx->operation == MBEDTLS_ENCRYPT && ilen < block_size - ctx->unprocessed_len ) ) { memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ), input, ilen ); ctx->unprocessed_len += ilen; return( 0 ); } /* * Process cached data first */ if( 0 != ctx->unprocessed_len ) { copy_len = block_size - ctx->unprocessed_len; memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ), input, copy_len ); if( 0 != ( ret = ctx->cipher_info->base->cbc_func( ctx->cipher_ctx, ctx->operation, block_size, ctx->iv, ctx->unprocessed_data, output ) ) ) { return( ret ); } *olen += block_size; output += block_size; ctx->unprocessed_len = 0; input += copy_len; ilen -= copy_len; } /* * Cache final, incomplete block */ if( 0 != ilen ) { /* Encryption: only cache partial blocks * Decryption w/ padding: always keep at least one whole block * Decryption w/o padding: only cache partial blocks */ copy_len = ilen % block_size; if( copy_len == 0 && ctx->operation == MBEDTLS_DECRYPT && NULL != ctx->add_padding) { copy_len = block_size; } memcpy( ctx->unprocessed_data, &( input[ilen - copy_len] ), copy_len ); ctx->unprocessed_len += copy_len; ilen -= copy_len; } /* * Process remaining full blocks */ if( ilen ) { if( 0 != ( ret = ctx->cipher_info->base->cbc_func( ctx->cipher_ctx, ctx->operation, ilen, ctx->iv, input, output ) ) ) { return( ret ); } *olen += ilen; } return( 0 ); } #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_CIPHER_MODE_CFB) if( ctx->cipher_info->mode == MBEDTLS_MODE_CFB ) { if( 0 != ( ret = ctx->cipher_info->base->cfb_func( ctx->cipher_ctx, ctx->operation, ilen, &ctx->unprocessed_len, ctx->iv, input, output ) ) ) { return( ret ); } *olen = ilen; return( 0 ); } #endif /* MBEDTLS_CIPHER_MODE_CFB */ #if defined(MBEDTLS_CIPHER_MODE_OFB) if( ctx->cipher_info->mode == MBEDTLS_MODE_OFB ) { if( 0 != ( ret = ctx->cipher_info->base->ofb_func( ctx->cipher_ctx, ilen, &ctx->unprocessed_len, ctx->iv, input, output ) ) ) { return( ret ); } *olen = ilen; return( 0 ); } #endif /* MBEDTLS_CIPHER_MODE_OFB */ #if defined(MBEDTLS_CIPHER_MODE_CTR) if( ctx->cipher_info->mode == MBEDTLS_MODE_CTR ) { if( 0 != ( ret = ctx->cipher_info->base->ctr_func( ctx->cipher_ctx, ilen, &ctx->unprocessed_len, ctx->iv, ctx->unprocessed_data, input, output ) ) ) { return( ret ); } *olen = ilen; return( 0 ); } #endif /* MBEDTLS_CIPHER_MODE_CTR */ #if defined(MBEDTLS_CIPHER_MODE_XTS) if( ctx->cipher_info->mode == MBEDTLS_MODE_XTS ) { if( ctx->unprocessed_len > 0 ) { /* We can only process an entire data unit at a time. */ return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); } ret = ctx->cipher_info->base->xts_func( ctx->cipher_ctx, ctx->operation, ilen, ctx->iv, input, output ); if( ret != 0 ) { return( ret ); } *olen = ilen; return( 0 ); } #endif /* MBEDTLS_CIPHER_MODE_XTS */ #if defined(MBEDTLS_CIPHER_MODE_STREAM) if( ctx->cipher_info->mode == MBEDTLS_MODE_STREAM ) { if( 0 != ( ret = ctx->cipher_info->base->stream_func( ctx->cipher_ctx, ilen, input, output ) ) ) { return( ret ); } *olen = ilen; return( 0 ); } #endif /* MBEDTLS_CIPHER_MODE_STREAM */ return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); } #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING) #if defined(MBEDTLS_CIPHER_PADDING_PKCS7) /* * PKCS7 (and PKCS5) padding: fill with ll bytes, with ll = padding_len */ static void add_pkcs_padding( unsigned char *output, size_t output_len, size_t data_len ) { size_t padding_len = output_len - data_len; unsigned char i; for( i = 0; i < padding_len; i++ ) output[data_len + i] = (unsigned char) padding_len; } static int get_pkcs_padding( unsigned char *input, size_t input_len, size_t *data_len ) { size_t i, pad_idx; unsigned char padding_len, bad = 0; if( NULL == input || NULL == data_len ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); padding_len = input[input_len - 1]; *data_len = input_len - padding_len; /* Avoid logical || since it results in a branch */ bad |= padding_len > input_len; bad |= padding_len == 0; /* The number of bytes checked must be independent of padding_len, * so pick input_len, which is usually 8 or 16 (one block) */ pad_idx = input_len - padding_len; for( i = 0; i < input_len; i++ ) bad |= ( input[i] ^ padding_len ) * ( i >= pad_idx ); return( MBEDTLS_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) ); } #endif /* MBEDTLS_CIPHER_PADDING_PKCS7 */ #if defined(MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS) /* * One and zeros padding: fill with 80 00 ... 00 */ static void add_one_and_zeros_padding( unsigned char *output, size_t output_len, size_t data_len ) { size_t padding_len = output_len - data_len; unsigned char i = 0; output[data_len] = 0x80; for( i = 1; i < padding_len; i++ ) output[data_len + i] = 0x00; } static int get_one_and_zeros_padding( unsigned char *input, size_t input_len, size_t *data_len ) { size_t i; unsigned char done = 0, prev_done, bad; if( NULL == input || NULL == data_len ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); bad = 0x80; *data_len = 0; for( i = input_len; i > 0; i-- ) { prev_done = done; done |= ( input[i - 1] != 0 ); *data_len |= ( i - 1 ) * ( done != prev_done ); bad ^= input[i - 1] * ( done != prev_done ); } return( MBEDTLS_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) ); } #endif /* MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS */ #if defined(MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN) /* * Zeros and len padding: fill with 00 ... 00 ll, where ll is padding length */ static void add_zeros_and_len_padding( unsigned char *output, size_t output_len, size_t data_len ) { size_t padding_len = output_len - data_len; unsigned char i = 0; for( i = 1; i < padding_len; i++ ) output[data_len + i - 1] = 0x00; output[output_len - 1] = (unsigned char) padding_len; } static int get_zeros_and_len_padding( unsigned char *input, size_t input_len, size_t *data_len ) { size_t i, pad_idx; unsigned char padding_len, bad = 0; if( NULL == input || NULL == data_len ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); padding_len = input[input_len - 1]; *data_len = input_len - padding_len; /* Avoid logical || since it results in a branch */ bad |= padding_len > input_len; bad |= padding_len == 0; /* The number of bytes checked must be independent of padding_len */ pad_idx = input_len - padding_len; for( i = 0; i < input_len - 1; i++ ) bad |= input[i] * ( i >= pad_idx ); return( MBEDTLS_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) ); } #endif /* MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN */ #if defined(MBEDTLS_CIPHER_PADDING_ZEROS) /* * Zero padding: fill with 00 ... 00 */ static void add_zeros_padding( unsigned char *output, size_t output_len, size_t data_len ) { size_t i; for( i = data_len; i < output_len; i++ ) output[i] = 0x00; } static int get_zeros_padding( unsigned char *input, size_t input_len, size_t *data_len ) { size_t i; unsigned char done = 0, prev_done; if( NULL == input || NULL == data_len ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); *data_len = 0; for( i = input_len; i > 0; i-- ) { prev_done = done; done |= ( input[i-1] != 0 ); *data_len |= i * ( done != prev_done ); } return( 0 ); } #endif /* MBEDTLS_CIPHER_PADDING_ZEROS */ /* * No padding: don't pad :) * * There is no add_padding function (check for NULL in mbedtls_cipher_finish) * but a trivial get_padding function */ static int get_no_padding( unsigned char *input, size_t input_len, size_t *data_len ) { if( NULL == input || NULL == data_len ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); *data_len = input_len; return( 0 ); } #endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */ int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx, unsigned char *output, size_t *olen ) { CIPHER_VALIDATE_RET( ctx != NULL ); CIPHER_VALIDATE_RET( output != NULL ); CIPHER_VALIDATE_RET( olen != NULL ); if( ctx->cipher_info == NULL ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); #if defined(MBEDTLS_USE_PSA_CRYPTO) if( ctx->psa_enabled == 1 ) { /* While PSA Crypto has an API for multipart * operations, we currently don't make it * accessible through the cipher layer. */ return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ *olen = 0; if( MBEDTLS_MODE_CFB == ctx->cipher_info->mode || MBEDTLS_MODE_OFB == ctx->cipher_info->mode || MBEDTLS_MODE_CTR == ctx->cipher_info->mode || MBEDTLS_MODE_GCM == ctx->cipher_info->mode || MBEDTLS_MODE_XTS == ctx->cipher_info->mode || MBEDTLS_MODE_STREAM == ctx->cipher_info->mode ) { return( 0 ); } if ( ( MBEDTLS_CIPHER_CHACHA20 == ctx->cipher_info->type ) || ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type ) ) { return( 0 ); } if( MBEDTLS_MODE_ECB == ctx->cipher_info->mode ) { if( ctx->unprocessed_len != 0 ) return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED ); return( 0 ); } #if defined(MBEDTLS_CIPHER_MODE_CBC) if( MBEDTLS_MODE_CBC == ctx->cipher_info->mode ) { int ret = 0; if( MBEDTLS_ENCRYPT == ctx->operation ) { /* check for 'no padding' mode */ if( NULL == ctx->add_padding ) { if( 0 != ctx->unprocessed_len ) return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED ); return( 0 ); } ctx->add_padding( ctx->unprocessed_data, mbedtls_cipher_get_iv_size( ctx ), ctx->unprocessed_len ); } else if( mbedtls_cipher_get_block_size( ctx ) != ctx->unprocessed_len ) { /* * For decrypt operations, expect a full block, * or an empty block if no padding */ if( NULL == ctx->add_padding && 0 == ctx->unprocessed_len ) return( 0 ); return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED ); } /* cipher block */ if( 0 != ( ret = ctx->cipher_info->base->cbc_func( ctx->cipher_ctx, ctx->operation, mbedtls_cipher_get_block_size( ctx ), ctx->iv, ctx->unprocessed_data, output ) ) ) { return( ret ); } /* Set output size for decryption */ if( MBEDTLS_DECRYPT == ctx->operation ) return( ctx->get_padding( output, mbedtls_cipher_get_block_size( ctx ), olen ) ); /* Set output size for encryption */ *olen = mbedtls_cipher_get_block_size( ctx ); return( 0 ); } #else ((void) output); #endif /* MBEDTLS_CIPHER_MODE_CBC */ return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); } #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING) int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, mbedtls_cipher_padding_t mode ) { CIPHER_VALIDATE_RET( ctx != NULL ); if( NULL == ctx->cipher_info || MBEDTLS_MODE_CBC != ctx->cipher_info->mode ) { return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) if( ctx->psa_enabled == 1 ) { /* While PSA Crypto knows about CBC padding * schemes, we currently don't make them * accessible through the cipher layer. */ if( mode != MBEDTLS_PADDING_NONE ) return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); return( 0 ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ switch( mode ) { #if defined(MBEDTLS_CIPHER_PADDING_PKCS7) case MBEDTLS_PADDING_PKCS7: ctx->add_padding = add_pkcs_padding; ctx->get_padding = get_pkcs_padding; break; #endif #if defined(MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS) case MBEDTLS_PADDING_ONE_AND_ZEROS: ctx->add_padding = add_one_and_zeros_padding; ctx->get_padding = get_one_and_zeros_padding; break; #endif #if defined(MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN) case MBEDTLS_PADDING_ZEROS_AND_LEN: ctx->add_padding = add_zeros_and_len_padding; ctx->get_padding = get_zeros_and_len_padding; break; #endif #if defined(MBEDTLS_CIPHER_PADDING_ZEROS) case MBEDTLS_PADDING_ZEROS: ctx->add_padding = add_zeros_padding; ctx->get_padding = get_zeros_padding; break; #endif case MBEDTLS_PADDING_NONE: ctx->add_padding = NULL; ctx->get_padding = get_no_padding; break; default: return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); } return( 0 ); } #endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */ #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C) int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx, unsigned char *tag, size_t tag_len ) { CIPHER_VALIDATE_RET( ctx != NULL ); CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL ); if( ctx->cipher_info == NULL ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); if( MBEDTLS_ENCRYPT != ctx->operation ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); #if defined(MBEDTLS_USE_PSA_CRYPTO) if( ctx->psa_enabled == 1 ) { /* While PSA Crypto has an API for multipart * operations, we currently don't make it * accessible through the cipher layer. */ return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ #if defined(MBEDTLS_GCM_C) if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode ) return( mbedtls_gcm_finish( (mbedtls_gcm_context *) ctx->cipher_ctx, tag, tag_len ) ); #endif #if defined(MBEDTLS_CHACHAPOLY_C) if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type ) { /* Don't allow truncated MAC for Poly1305 */ if ( tag_len != 16U ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); return( mbedtls_chachapoly_finish( (mbedtls_chachapoly_context*) ctx->cipher_ctx, tag ) ); } #endif return( 0 ); } int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx, const unsigned char *tag, size_t tag_len ) { unsigned char check_tag[16]; int ret = MBEDTLS_ERR_THIS_CORRUPTION; CIPHER_VALIDATE_RET( ctx != NULL ); CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL ); if( ctx->cipher_info == NULL ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); if( MBEDTLS_DECRYPT != ctx->operation ) { return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) if( ctx->psa_enabled == 1 ) { /* While PSA Crypto has an API for multipart * operations, we currently don't make it * accessible through the cipher layer. */ return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ #if defined(MBEDTLS_GCM_C) if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode ) { if( tag_len > sizeof( check_tag ) ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); if( 0 != ( ret = mbedtls_gcm_finish( (mbedtls_gcm_context *) ctx->cipher_ctx, check_tag, tag_len ) ) ) { return( ret ); } /* Check the tag in "constant-time" */ if( timingsafe_bcmp( tag, check_tag, tag_len ) != 0 ) return( MBEDTLS_ERR_CIPHER_AUTH_FAILED ); return( 0 ); } #endif /* MBEDTLS_GCM_C */ #if defined(MBEDTLS_CHACHAPOLY_C) if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type ) { /* Don't allow truncated MAC for Poly1305 */ if ( tag_len != sizeof( check_tag ) ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); ret = mbedtls_chachapoly_finish( (mbedtls_chachapoly_context*) ctx->cipher_ctx, check_tag ); if ( ret != 0 ) { return( ret ); } /* Check the tag in "constant-time" */ if( timingsafe_bcmp( tag, check_tag, tag_len ) != 0 ) return( MBEDTLS_ERR_CIPHER_AUTH_FAILED ); return( 0 ); } #endif /* MBEDTLS_CHACHAPOLY_C */ return( 0 ); } #endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */ /* * Packet-oriented wrapper for non-AEAD modes */ int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t finish_olen; CIPHER_VALIDATE_RET( ctx != NULL ); CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL ); CIPHER_VALIDATE_RET( ilen == 0 || input != NULL ); CIPHER_VALIDATE_RET( output != NULL ); CIPHER_VALIDATE_RET( olen != NULL ); #if defined(MBEDTLS_USE_PSA_CRYPTO) if( ctx->psa_enabled == 1 ) { /* As in the non-PSA case, we don't check that * a key has been set. If not, the key slot will * still be in its default state of 0, which is * guaranteed to be invalid, hence the PSA-call * below will gracefully fail. */ mbedtls_cipher_context_psa * const cipher_psa = (mbedtls_cipher_context_psa *) ctx->cipher_ctx; psa_status_t status; psa_cipher_operation_t cipher_op = PSA_CIPHER_OPERATION_INIT; size_t part_len; if( ctx->operation == MBEDTLS_DECRYPT ) { status = psa_cipher_decrypt_setup( &cipher_op, cipher_psa->slot, cipher_psa->alg ); } else if( ctx->operation == MBEDTLS_ENCRYPT ) { status = psa_cipher_encrypt_setup( &cipher_op, cipher_psa->slot, cipher_psa->alg ); } else return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); /* In the following, we can immediately return on an error, * because the PSA Crypto API guarantees that cipher operations * are terminated by unsuccessful calls to psa_cipher_update(), * and by any call to psa_cipher_finish(). */ if( status != PSA_SUCCESS ) return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED ); status = psa_cipher_set_iv( &cipher_op, iv, iv_len ); if( status != PSA_SUCCESS ) return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED ); status = psa_cipher_update( &cipher_op, input, ilen, output, ilen, olen ); if( status != PSA_SUCCESS ) return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED ); status = psa_cipher_finish( &cipher_op, output + *olen, ilen - *olen, &part_len ); if( status != PSA_SUCCESS ) return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED ); *olen += part_len; return( 0 ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ if( ( ret = mbedtls_cipher_set_iv( ctx, iv, iv_len ) ) != 0 ) return( ret ); if( ( ret = mbedtls_cipher_reset( ctx ) ) != 0 ) return( ret ); if( ( ret = mbedtls_cipher_update( ctx, input, ilen, output, olen ) ) != 0 ) return( ret ); if( ( ret = mbedtls_cipher_finish( ctx, output + *olen, &finish_olen ) ) != 0 ) return( ret ); *olen += finish_olen; return( 0 ); } #if defined(MBEDTLS_CIPHER_MODE_AEAD) /* * Packet-oriented encryption for AEAD modes: internal function shared by * mbedtls_cipher_auth_encrypt() and mbedtls_cipher_auth_encrypt_ext(). */ static int mbedtls_cipher_aead_encrypt( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, const unsigned char *ad, size_t ad_len, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen, unsigned char *tag, size_t tag_len ) { #if defined(MBEDTLS_USE_PSA_CRYPTO) if( ctx->psa_enabled == 1 ) { /* As in the non-PSA case, we don't check that * a key has been set. If not, the key slot will * still be in its default state of 0, which is * guaranteed to be invalid, hence the PSA-call * below will gracefully fail. */ mbedtls_cipher_context_psa * const cipher_psa = (mbedtls_cipher_context_psa *) ctx->cipher_ctx; psa_status_t status; /* PSA Crypto API always writes the authentication tag * at the end of the encrypted message. */ if( output == NULL || tag != output + ilen ) return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); status = psa_aead_encrypt( cipher_psa->slot, cipher_psa->alg, iv, iv_len, ad, ad_len, input, ilen, output, ilen + tag_len, olen ); if( status != PSA_SUCCESS ) return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED ); *olen -= tag_len; return( 0 ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ #if defined(MBEDTLS_GCM_C) if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode ) { *olen = ilen; return( mbedtls_gcm_crypt_and_tag( ctx->cipher_ctx, MBEDTLS_GCM_ENCRYPT, ilen, iv, iv_len, ad, ad_len, input, output, tag_len, tag ) ); } #endif /* MBEDTLS_GCM_C */ #if defined(MBEDTLS_CCM_C) if( MBEDTLS_MODE_CCM == ctx->cipher_info->mode ) { *olen = ilen; return( mbedtls_ccm_encrypt_and_tag( ctx->cipher_ctx, ilen, iv, iv_len, ad, ad_len, input, output, tag, tag_len ) ); } #endif /* MBEDTLS_CCM_C */ #if defined(MBEDTLS_CHACHAPOLY_C) if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type ) { /* ChachaPoly has fixed length nonce and MAC (tag) */ if ( ( iv_len != ctx->cipher_info->iv_size ) || ( tag_len != 16U ) ) { return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } *olen = ilen; return( mbedtls_chachapoly_encrypt_and_tag( ctx->cipher_ctx, ilen, iv, ad, ad_len, input, output, tag ) ); } #endif /* MBEDTLS_CHACHAPOLY_C */ return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); } /* * Packet-oriented encryption for AEAD modes: internal function shared by * mbedtls_cipher_auth_encrypt() and mbedtls_cipher_auth_encrypt_ext(). */ static int mbedtls_cipher_aead_decrypt( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, const unsigned char *ad, size_t ad_len, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen, const unsigned char *tag, size_t tag_len ) { #if defined(MBEDTLS_USE_PSA_CRYPTO) if( ctx->psa_enabled == 1 ) { /* As in the non-PSA case, we don't check that * a key has been set. If not, the key slot will * still be in its default state of 0, which is * guaranteed to be invalid, hence the PSA-call * below will gracefully fail. */ mbedtls_cipher_context_psa * const cipher_psa = (mbedtls_cipher_context_psa *) ctx->cipher_ctx; psa_status_t status; /* PSA Crypto API always writes the authentication tag * at the end of the encrypted message. */ if( input == NULL || tag != input + ilen ) return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); status = psa_aead_decrypt( cipher_psa->slot, cipher_psa->alg, iv, iv_len, ad, ad_len, input, ilen + tag_len, output, ilen, olen ); if( status == PSA_ERROR_INVALID_SIGNATURE ) return( MBEDTLS_ERR_CIPHER_AUTH_FAILED ); else if( status != PSA_SUCCESS ) return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED ); return( 0 ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ #if defined(MBEDTLS_GCM_C) if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; *olen = ilen; ret = mbedtls_gcm_auth_decrypt( ctx->cipher_ctx, ilen, iv, iv_len, ad, ad_len, tag, tag_len, input, output ); if( ret == MBEDTLS_ERR_GCM_AUTH_FAILED ) ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED; return( ret ); } #endif /* MBEDTLS_GCM_C */ #if defined(MBEDTLS_CCM_C) if( MBEDTLS_MODE_CCM == ctx->cipher_info->mode ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; *olen = ilen; ret = mbedtls_ccm_auth_decrypt( ctx->cipher_ctx, ilen, iv, iv_len, ad, ad_len, input, output, tag, tag_len ); if( ret == MBEDTLS_ERR_CCM_AUTH_FAILED ) ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED; return( ret ); } #endif /* MBEDTLS_CCM_C */ #if defined(MBEDTLS_CHACHAPOLY_C) if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; /* ChachaPoly has fixed length nonce and MAC (tag) */ if ( ( iv_len != ctx->cipher_info->iv_size ) || ( tag_len != 16U ) ) { return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } *olen = ilen; ret = mbedtls_chachapoly_auth_decrypt( ctx->cipher_ctx, ilen, iv, ad, ad_len, tag, input, output ); if( ret == MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED ) ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED; return( ret ); } #endif /* MBEDTLS_CHACHAPOLY_C */ return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); } /* * Packet-oriented encryption for AEAD modes: public legacy function. */ int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, const unsigned char *ad, size_t ad_len, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen, unsigned char *tag, size_t tag_len ) { CIPHER_VALIDATE_RET( ctx != NULL ); CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL ); CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL ); CIPHER_VALIDATE_RET( ilen == 0 || input != NULL ); CIPHER_VALIDATE_RET( ilen == 0 || output != NULL ); CIPHER_VALIDATE_RET( olen != NULL ); CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL ); return( mbedtls_cipher_aead_encrypt( ctx, iv, iv_len, ad, ad_len, input, ilen, output, olen, tag, tag_len ) ); } /* * Packet-oriented decryption for AEAD modes: public legacy function. */ int mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, const unsigned char *ad, size_t ad_len, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen, const unsigned char *tag, size_t tag_len ) { CIPHER_VALIDATE_RET( ctx != NULL ); CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL ); CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL ); CIPHER_VALIDATE_RET( ilen == 0 || input != NULL ); CIPHER_VALIDATE_RET( ilen == 0 || output != NULL ); CIPHER_VALIDATE_RET( olen != NULL ); CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL ); return( mbedtls_cipher_aead_decrypt( ctx, iv, iv_len, ad, ad_len, input, ilen, output, olen, tag, tag_len ) ); } #endif /* MBEDTLS_CIPHER_MODE_AEAD */ #if defined(MBEDTLS_CIPHER_MODE_AEAD) || defined(MBEDTLS_NIST_KW_C) /* * Packet-oriented encryption for AEAD/NIST_KW: public function. */ int mbedtls_cipher_auth_encrypt_ext( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, const unsigned char *ad, size_t ad_len, const unsigned char *input, size_t ilen, unsigned char *output, size_t output_len, size_t *olen, size_t tag_len ) { CIPHER_VALIDATE_RET( ctx != NULL ); CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL ); CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL ); CIPHER_VALIDATE_RET( ilen == 0 || input != NULL ); CIPHER_VALIDATE_RET( output != NULL ); CIPHER_VALIDATE_RET( olen != NULL ); #if defined(MBEDTLS_NIST_KW_C) if( #if defined(MBEDTLS_USE_PSA_CRYPTO) ctx->psa_enabled == 0 && #endif ( MBEDTLS_MODE_KW == ctx->cipher_info->mode || MBEDTLS_MODE_KWP == ctx->cipher_info->mode ) ) { mbedtls_nist_kw_mode_t mode = ( MBEDTLS_MODE_KW == ctx->cipher_info->mode ) ? MBEDTLS_KW_MODE_KW : MBEDTLS_KW_MODE_KWP; /* There is no iv, tag or ad associated with KW and KWP, * so these length should be 0 as documented. */ if( iv_len != 0 || tag_len != 0 || ad_len != 0 ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); (void) iv; (void) ad; return( mbedtls_nist_kw_wrap( ctx->cipher_ctx, mode, input, ilen, output, olen, output_len ) ); } #endif /* MBEDTLS_NIST_KW_C */ #if defined(MBEDTLS_CIPHER_MODE_AEAD) /* AEAD case: check length before passing on to shared function */ if( output_len < ilen + tag_len ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); int ret = mbedtls_cipher_aead_encrypt( ctx, iv, iv_len, ad, ad_len, input, ilen, output, olen, output + ilen, tag_len ); *olen += tag_len; return( ret ); #else return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); #endif /* MBEDTLS_CIPHER_MODE_AEAD */ } /* * Packet-oriented decryption for AEAD/NIST_KW: public function. */ int mbedtls_cipher_auth_decrypt_ext( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, const unsigned char *ad, size_t ad_len, const unsigned char *input, size_t ilen, unsigned char *output, size_t output_len, size_t *olen, size_t tag_len ) { CIPHER_VALIDATE_RET( ctx != NULL ); CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL ); CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL ); CIPHER_VALIDATE_RET( ilen == 0 || input != NULL ); CIPHER_VALIDATE_RET( output_len == 0 || output != NULL ); CIPHER_VALIDATE_RET( olen != NULL ); #if defined(MBEDTLS_NIST_KW_C) if( #if defined(MBEDTLS_USE_PSA_CRYPTO) ctx->psa_enabled == 0 && #endif ( MBEDTLS_MODE_KW == ctx->cipher_info->mode || MBEDTLS_MODE_KWP == ctx->cipher_info->mode ) ) { mbedtls_nist_kw_mode_t mode = ( MBEDTLS_MODE_KW == ctx->cipher_info->mode ) ? MBEDTLS_KW_MODE_KW : MBEDTLS_KW_MODE_KWP; /* There is no iv, tag or ad associated with KW and KWP, * so these length should be 0 as documented. */ if( iv_len != 0 || tag_len != 0 || ad_len != 0 ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); (void) iv; (void) ad; return( mbedtls_nist_kw_unwrap( ctx->cipher_ctx, mode, input, ilen, output, olen, output_len ) ); } #endif /* MBEDTLS_NIST_KW_C */ #if defined(MBEDTLS_CIPHER_MODE_AEAD) /* AEAD case: check length before passing on to shared function */ if( ilen < tag_len || output_len < ilen - tag_len ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); return( mbedtls_cipher_aead_decrypt( ctx, iv, iv_len, ad, ad_len, input, ilen - tag_len, output, olen, input + ilen - tag_len, tag_len ) ); #else return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); #endif /* MBEDTLS_CIPHER_MODE_AEAD */ } #endif /* MBEDTLS_CIPHER_MODE_AEAD || MBEDTLS_NIST_KW_C */ #endif /* MBEDTLS_CIPHER_C */
52,682
1,566
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/sha256.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/dce.h" #include "libc/intrin/asan.internal.h" #include "libc/macros.internal.h" #include "libc/nexgen32e/nexgen32e.h" #include "libc/nexgen32e/sha.h" #include "libc/nexgen32e/x86feature.h" #include "libc/str/str.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/endian.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/md.h" #include "third_party/mbedtls/sha256.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /** * @fileoverview FIPS-180-2 compliant SHA-256 implementation * * The SHA-256 Secure Hash Standard was published by NIST in 2002. * * @see http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf */ #define SHA256_VALIDATE_RET(cond) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_SHA256_BAD_INPUT_DATA ) #define SHA256_VALIDATE(cond) MBEDTLS_INTERNAL_VALIDATE( cond ) #if !defined(MBEDTLS_SHA256_ALT) /** * \brief This function clones the state of a SHA-256 context. * * \param dst The destination context. This must be initialized. * \param src The context to clone. This must be initialized. */ void mbedtls_sha256_clone( mbedtls_sha256_context *dst, const mbedtls_sha256_context *src ) { SHA256_VALIDATE( dst ); SHA256_VALIDATE( src ); *dst = *src; } int mbedtls_sha256_starts_224( mbedtls_sha256_context *ctx ) { SHA256_VALIDATE_RET( ctx ); ctx->total[0] = 0; ctx->total[1] = 0; ctx->state[0] = 0xC1059ED8; ctx->state[1] = 0x367CD507; ctx->state[2] = 0x3070DD17; ctx->state[3] = 0xF70E5939; ctx->state[4] = 0xFFC00B31; ctx->state[5] = 0x68581511; ctx->state[6] = 0x64F98FA7; ctx->state[7] = 0xBEFA4FA4; ctx->is224 = true; return( 0 ); } int mbedtls_sha256_starts_256( mbedtls_sha256_context *ctx ) { SHA256_VALIDATE_RET( ctx ); ctx->total[0] = 0; ctx->total[1] = 0; ctx->state[0] = 0x6A09E667; ctx->state[1] = 0xBB67AE85; ctx->state[2] = 0x3C6EF372; ctx->state[3] = 0xA54FF53A; ctx->state[4] = 0x510E527F; ctx->state[5] = 0x9B05688C; ctx->state[6] = 0x1F83D9AB; ctx->state[7] = 0x5BE0CD19; ctx->is224 = false; return( 0 ); } /** * \brief This function starts a SHA-224 or SHA-256 checksum * calculation. * * \param ctx The context to use. This must be initialized. * \param is224 This determines which function to use. This must be * either \c 0 for SHA-256, or \c 1 for SHA-224. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_sha256_starts_ret( mbedtls_sha256_context *ctx, int is224 ) { SHA256_VALIDATE_RET( ctx ); SHA256_VALIDATE_RET( is224 == 0 || is224 == 1 ); if( !is224 ) return mbedtls_sha256_starts_256( ctx ); else return mbedtls_sha256_starts_224( ctx ); } #if !defined(MBEDTLS_SHA256_PROCESS_ALT) #define K kSha256 #define SHR(x,n) (((x) & 0xFFFFFFFF) >> (n)) #define ROTR(x,n) (SHR(x,n) | ((x) << (32 - (n)))) #define S0(x) (ROTR(x, 7) ^ ROTR(x,18) ^ SHR(x, 3)) #define S1(x) (ROTR(x,17) ^ ROTR(x,19) ^ SHR(x,10)) #define S2(x) (ROTR(x, 2) ^ ROTR(x,13) ^ ROTR(x,22)) #define S3(x) (ROTR(x, 6) ^ ROTR(x,11) ^ ROTR(x,25)) #define F0(x,y,z) (((x) & (y)) | ((z) & ((x) | (y)))) #define F1(x,y,z) ((z) ^ ((x) & ((y) ^ (z)))) #define R(t) \ ( \ local.W[t] = S1(local.W[(t) - 2]) + local.W[(t) - 7] + \ S0(local.W[(t) - 15]) + local.W[(t) - 16] \ ) #define P(a,b,c,d,e,f,g,h,x,K) \ do \ { \ local.temp1 = (h) + S3(e) + F1((e),(f),(g)) + (K) + (x); \ local.temp2 = S2(a) + F0((a),(b),(c)); \ (d) += local.temp1; (h) = local.temp1 + local.temp2; \ } while( 0 ) /** * \brief This function processes a single data block within * the ongoing SHA-256 computation. This function is for * internal use only. * * \param ctx The SHA-256 context. This must be initialized. * \param data The buffer holding one block of data. This must * be a readable buffer of length \c 64 Bytes. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_internal_sha256_process( mbedtls_sha256_context *ctx, const unsigned char data[64] ) { struct { uint32_t temp1, temp2, W[64]; uint32_t A[8]; } local; unsigned int i; SHA256_VALIDATE_RET( ctx != NULL ); SHA256_VALIDATE_RET( (const unsigned char *)data != NULL ); if( !IsTiny() || X86_NEED( SHA ) ) { if( X86_HAVE( SHA ) && X86_HAVE( SSE2 ) && X86_HAVE( SSSE3 ) ) { if( IsAsan() ) __asan_verify( data, 64 ); sha256_transform_ni( ctx->state, data, 1 ); return( 0 ); } if( X86_HAVE( BMI2 ) && X86_HAVE( AVX ) && X86_HAVE( AVX2 ) ) { if( IsAsan() ) __asan_verify( data, 64 ); sha256_transform_rorx( ctx->state, data, 1 ); return( 0 ); } } for( i = 0; i < 8; i++ ) local.A[i] = ctx->state[i]; #if defined(MBEDTLS_SHA256_SMALLER) for( i = 0; i < 64; i++ ) { if( i < 16 ) GET_UINT32_BE( local.W[i], data, 4 * i ); else R( i ); P( local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.W[i], K[i] ); local.temp1 = local.A[7]; local.A[7] = local.A[6]; local.A[6] = local.A[5]; local.A[5] = local.A[4]; local.A[4] = local.A[3]; local.A[3] = local.A[2]; local.A[2] = local.A[1]; local.A[1] = local.A[0]; local.A[0] = local.temp1; } #else /* MBEDTLS_SHA256_SMALLER */ for( i = 0; i < 16; i++ ) GET_UINT32_BE( local.W[i], data, 4 * i ); for( i = 0; i < 16; i += 8 ) { P( local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.W[i+0], K[i+0] ); P( local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.W[i+1], K[i+1] ); P( local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.W[i+2], K[i+2] ); P( local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.W[i+3], K[i+3] ); P( local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.W[i+4], K[i+4] ); P( local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.W[i+5], K[i+5] ); P( local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.W[i+6], K[i+6] ); P( local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.W[i+7], K[i+7] ); } for( i = 16; i < 64; i += 8 ) { P( local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], R(i+0), K[i+0] ); P( local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], R(i+1), K[i+1] ); P( local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], R(i+2), K[i+2] ); P( local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], local.A[4], R(i+3), K[i+3] ); P( local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], local.A[3], R(i+4), K[i+4] ); P( local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], local.A[2], R(i+5), K[i+5] ); P( local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], local.A[1], R(i+6), K[i+6] ); P( local.A[1], local.A[2], local.A[3], local.A[4], local.A[5], local.A[6], local.A[7], local.A[0], R(i+7), K[i+7] ); } #endif /* MBEDTLS_SHA256_SMALLER */ for( i = 0; i < 8; i++ ) ctx->state[i] += local.A[i]; /* Zeroise buffers and variables to clear sensitive data from memory. */ mbedtls_platform_zeroize( &local, sizeof( local ) ); return( 0 ); } #endif /* !MBEDTLS_SHA256_PROCESS_ALT */ /** * \brief This function feeds an input buffer into an ongoing * SHA-256 checksum calculation. * * \param ctx The SHA-256 context. This must be initialized * and have a hash operation started. * \param input The buffer holding the data. This must be a readable * buffer of length \p ilen Bytes. * \param ilen The length of the input data in Bytes. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_sha256_update_ret( mbedtls_sha256_context *ctx, const unsigned char *input, size_t ilen ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t fill; uint32_t left; SHA256_VALIDATE_RET( ctx != NULL ); SHA256_VALIDATE_RET( ilen == 0 || input != NULL ); if( ilen == 0 ) return( 0 ); left = ctx->total[0] & 0x3F; fill = 64 - left; ctx->total[0] += (uint32_t) ilen; ctx->total[0] &= 0xFFFFFFFF; if( ctx->total[0] < (uint32_t) ilen ) ctx->total[1]++; if( left && ilen >= fill ) { memcpy( (void *) (ctx->buffer + left), input, fill ); if( ( ret = mbedtls_internal_sha256_process( ctx, ctx->buffer ) ) != 0 ) return( ret ); input += fill; ilen -= fill; left = 0; } if( ilen >= 64 ) { if( !IsTiny() && X86_HAVE( SHA ) && X86_HAVE( SSE2 ) && X86_HAVE( SSSE3 ) ) { if( IsAsan() ) __asan_verify( input, ilen ); sha256_transform_ni( ctx->state, input, ilen / 64 ); input += ROUNDDOWN( ilen, 64 ); ilen -= ROUNDDOWN( ilen, 64 ); } else if( !IsTiny() && X86_HAVE( BMI ) && X86_HAVE( BMI2 ) && X86_HAVE( AVX2 ) ) { if( IsAsan() ) __asan_verify( input, ilen ); sha256_transform_rorx( ctx->state, input, ilen / 64 ); input += ROUNDDOWN( ilen, 64 ); ilen -= ROUNDDOWN( ilen, 64 ); } else { do { if(( ret = mbedtls_internal_sha256_process( ctx, input ) )) return( ret ); input += 64; ilen -= 64; } while( ilen >= 64 ); } } if( ilen > 0 ) memcpy( (void *) (ctx->buffer + left), input, ilen ); return( 0 ); } /** * \brief This function finishes the SHA-256 operation, and writes * the result to the output buffer. * * \param ctx The SHA-256 context. This must be initialized * and have a hash operation started. * \param output The SHA-224 or SHA-256 checksum result. * This must be a writable buffer of length \c 32 Bytes. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_sha256_finish_ret( mbedtls_sha256_context *ctx, unsigned char output[32] ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; uint32_t used; uint32_t high, low; SHA256_VALIDATE_RET( ctx != NULL ); SHA256_VALIDATE_RET( (unsigned char *)output != NULL ); /* * Add padding: 0x80 then 0x00 until 8 bytes remain for the length */ used = ctx->total[0] & 0x3F; ctx->buffer[used++] = 0x80; if( used <= 56 ) { /* Enough room for padding + length in current block */ mbedtls_platform_zeroize( ctx->buffer + used, 56 - used ); } else { /* We'll need an extra block */ mbedtls_platform_zeroize( ctx->buffer + used, 64 - used ); if( ( ret = mbedtls_internal_sha256_process( ctx, ctx->buffer ) ) != 0 ) return( ret ); mbedtls_platform_zeroize( ctx->buffer, 56 ); } /* * Add message length */ high = ( ctx->total[0] >> 29 ) | ( ctx->total[1] << 3 ); low = ( ctx->total[0] << 3 ); PUT_UINT32_BE( high, ctx->buffer, 56 ); PUT_UINT32_BE( low, ctx->buffer, 60 ); if( ( ret = mbedtls_internal_sha256_process( ctx, ctx->buffer ) ) != 0 ) return( ret ); /* * Output final state */ PUT_UINT32_BE( ctx->state[0], output, 0 ); PUT_UINT32_BE( ctx->state[1], output, 4 ); PUT_UINT32_BE( ctx->state[2], output, 8 ); PUT_UINT32_BE( ctx->state[3], output, 12 ); PUT_UINT32_BE( ctx->state[4], output, 16 ); PUT_UINT32_BE( ctx->state[5], output, 20 ); PUT_UINT32_BE( ctx->state[6], output, 24 ); if( ctx->is224 == 0 ) PUT_UINT32_BE( ctx->state[7], output, 28 ); return( 0 ); } #endif /* !MBEDTLS_SHA256_ALT */ /** * \brief This function calculates the SHA-224 or SHA-256 * checksum of a buffer. * * The function allocates the context, performs the * calculation, and frees the context. * * The SHA-256 result is calculated as * output = SHA-256(input buffer). * * \param input The buffer holding the data. This must be a readable * buffer of length \p ilen Bytes. * \param ilen The length of the input data in Bytes. * \param output The SHA-224 or SHA-256 checksum result. This must * be a writable buffer of length \c 32 Bytes. * \param is224 Determines which function to use. This must be * either \c 0 for SHA-256, or \c 1 for SHA-224. */ int mbedtls_sha256_ret( const void *input, size_t ilen, unsigned char output[32], int is224 ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_sha256_context ctx; SHA256_VALIDATE_RET( is224 == 0 || is224 == 1 ); SHA256_VALIDATE_RET( ilen == 0 || input != NULL ); SHA256_VALIDATE_RET( (unsigned char *)output != NULL ); mbedtls_sha256_init( &ctx ); if( ( ret = mbedtls_sha256_starts_ret( &ctx, is224 ) ) != 0 ) goto exit; if( ( ret = mbedtls_sha256_update_ret( &ctx, input, ilen ) ) != 0 ) goto exit; if( ( ret = mbedtls_sha256_finish_ret( &ctx, output ) ) != 0 ) goto exit; exit: mbedtls_sha256_free( &ctx ); return( ret ); } noinstrument int mbedtls_sha256_ret_224( const void *input, size_t ilen, unsigned char *output ) { return mbedtls_sha256_ret( input, ilen, output, true ); } noinstrument int mbedtls_sha256_ret_256( const void *input, size_t ilen, unsigned char *output ) { return mbedtls_sha256_ret( input, ilen, output, false ); } const mbedtls_md_info_t mbedtls_sha224_info = { "SHA224", MBEDTLS_MD_SHA224, 28, 64, (void *)mbedtls_sha256_starts_224, (void *)mbedtls_sha256_update_ret, (void *)mbedtls_internal_sha256_process, (void *)mbedtls_sha256_finish_ret, mbedtls_sha256_ret_224, }; const mbedtls_md_info_t mbedtls_sha256_info = { "SHA256", MBEDTLS_MD_SHA256, 32, 64, (void *)mbedtls_sha256_starts_256, (void *)mbedtls_sha256_update_ret, (void *)mbedtls_internal_sha256_process, (void *)mbedtls_sha256_finish_ret, mbedtls_sha256_ret_256, };
18,074
512
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/ssl_tls13_keys.h
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_SSL_TLS13_KEYS_H_ #define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_SSL_TLS13_KEYS_H_ #include "third_party/mbedtls/md.h" #include "third_party/mbedtls/ssl_internal.h" COSMOPOLITAN_C_START_ #define MBEDTLS_SSL_TLS1_3_CONTEXT_UNHASHED 0 #define MBEDTLS_SSL_TLS1_3_CONTEXT_HASHED 1 /* The maximum length of HKDF contexts used in the TLS 1.3 standard. * Since contexts are always hashes of message transcripts, this can * be approximated from above by the maximum hash size. */ #define MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_CONTEXT_LEN MBEDTLS_MD_MAX_SIZE /* Maximum desired length for expanded key material generated * by HKDF-Expand-Label. * * Warning: If this ever needs to be increased, the implementation * ssl_tls1_3_hkdf_encode_label() in ssl_tls13_keys.c needs to be * adjusted since it currently assumes that HKDF key expansion * is never used with more than 255 Bytes of output. */ #define MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_EXPANSION_LEN 255 /* This requires MBEDTLS_SSL_TLS1_3_LABEL( idx, name, string ) to be defined at * the point of use. See e.g. the definition of mbedtls_ssl_tls1_3_labels_union * below. */ #define MBEDTLS_SSL_TLS1_3_LABEL_LIST \ MBEDTLS_SSL_TLS1_3_LABEL(finished, "finished") \ MBEDTLS_SSL_TLS1_3_LABEL(resumption, "resumption") \ MBEDTLS_SSL_TLS1_3_LABEL(traffic_upd, "traffic upd") \ MBEDTLS_SSL_TLS1_3_LABEL(exporter, "exporter") \ MBEDTLS_SSL_TLS1_3_LABEL(key, "key") \ MBEDTLS_SSL_TLS1_3_LABEL(iv, "iv") \ MBEDTLS_SSL_TLS1_3_LABEL(c_hs_traffic, "c hs traffic") \ MBEDTLS_SSL_TLS1_3_LABEL(c_ap_traffic, "c ap traffic") \ MBEDTLS_SSL_TLS1_3_LABEL(c_e_traffic, "c e traffic") \ MBEDTLS_SSL_TLS1_3_LABEL(s_hs_traffic, "s hs traffic") \ MBEDTLS_SSL_TLS1_3_LABEL(s_ap_traffic, "s ap traffic") \ MBEDTLS_SSL_TLS1_3_LABEL(s_e_traffic, "s e traffic") \ MBEDTLS_SSL_TLS1_3_LABEL(e_exp_master, "e exp master") \ MBEDTLS_SSL_TLS1_3_LABEL(res_master, "res master") \ MBEDTLS_SSL_TLS1_3_LABEL(exp_master, "exp master") \ MBEDTLS_SSL_TLS1_3_LABEL(ext_binder, "ext binder") \ MBEDTLS_SSL_TLS1_3_LABEL(res_binder, "res binder") \ MBEDTLS_SSL_TLS1_3_LABEL(derived, "derived") #define MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(LABEL) \ mbedtls_ssl_tls1_3_labels.LABEL, sizeof(mbedtls_ssl_tls1_3_labels.LABEL) #define MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_LABEL_LEN \ sizeof(union mbedtls_ssl_tls1_3_labels_union) #define MBEDTLS_SSL_TLS1_3_LABEL(name, string) \ const unsigned char name[sizeof(string) - 1]; union mbedtls_ssl_tls1_3_labels_union { MBEDTLS_SSL_TLS1_3_LABEL_LIST }; struct mbedtls_ssl_tls1_3_labels_struct { MBEDTLS_SSL_TLS1_3_LABEL_LIST }; #undef MBEDTLS_SSL_TLS1_3_LABEL extern const struct mbedtls_ssl_tls1_3_labels_struct mbedtls_ssl_tls1_3_labels; int mbedtls_ssl_tls1_3_hkdf_expand_label(mbedtls_md_type_t, const unsigned char *, size_t, const unsigned char *, size_t, const unsigned char *, size_t, unsigned char *, size_t); int mbedtls_ssl_tls1_3_make_traffic_keys(mbedtls_md_type_t, const unsigned char *, const unsigned char *, size_t, size_t, size_t, mbedtls_ssl_key_set *); int mbedtls_ssl_tls1_3_derive_secret(mbedtls_md_type_t, const unsigned char *, size_t, const unsigned char *, size_t, const unsigned char *, size_t, int, unsigned char *, size_t); int mbedtls_ssl_tls1_3_evolve_secret(mbedtls_md_type_t, const unsigned char *, const unsigned char *, size_t, unsigned char *); COSMOPOLITAN_C_END_ #endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_SSL_TLS13_KEYS_H_ */
4,069
84
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/ecdsa.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "third_party/mbedtls/asn1write.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/ecdsa.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/hmac_drbg.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/profile.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /** * @fileoverview Elliptic curve Digital Signature Algorithm * * @see SEC1 http://www.secg.org/index.php?action=secg,docs_secg */ #if defined(MBEDTLS_ECDSA_C) /* Parameter validation macros based on platform_util.h */ #define ECDSA_VALIDATE_RET( cond ) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_ECP_BAD_INPUT_DATA ) #define ECDSA_VALIDATE( cond ) \ MBEDTLS_INTERNAL_VALIDATE( cond ) #if defined(MBEDTLS_ECP_RESTARTABLE) /* * Sub-context for ecdsa_verify() */ struct mbedtls_ecdsa_restart_ver { mbedtls_mpi u1, u2; /* intermediate values */ enum { /* what to do next? */ ecdsa_ver_init = 0, /* getting started */ ecdsa_ver_muladd, /* muladd step */ } state; }; /* * Init verify restart sub-context */ static void ecdsa_restart_ver_init( mbedtls_ecdsa_restart_ver_ctx *ctx ) { mbedtls_mpi_init( &ctx->u1 ); mbedtls_mpi_init( &ctx->u2 ); ctx->state = ecdsa_ver_init; } /* * Free the components of a verify restart sub-context */ static void ecdsa_restart_ver_free( mbedtls_ecdsa_restart_ver_ctx *ctx ) { if( ctx == NULL ) return; mbedtls_mpi_free( &ctx->u1 ); mbedtls_mpi_free( &ctx->u2 ); ecdsa_restart_ver_init( ctx ); } /* * Sub-context for ecdsa_sign() */ struct mbedtls_ecdsa_restart_sig { int sign_tries; int key_tries; mbedtls_mpi k; /* per-signature random */ mbedtls_mpi r; /* r value */ enum { /* what to do next? */ ecdsa_sig_init = 0, /* getting started */ ecdsa_sig_mul, /* doing ecp_mul() */ ecdsa_sig_modn, /* mod N computations */ } state; }; /* * Init verify sign sub-context */ static void ecdsa_restart_sig_init( mbedtls_ecdsa_restart_sig_ctx *ctx ) { ctx->sign_tries = 0; ctx->key_tries = 0; mbedtls_mpi_init( &ctx->k ); mbedtls_mpi_init( &ctx->r ); ctx->state = ecdsa_sig_init; } /* * Free the components of a sign restart sub-context */ static void ecdsa_restart_sig_free( mbedtls_ecdsa_restart_sig_ctx *ctx ) { if( ctx == NULL ) return; mbedtls_mpi_free( &ctx->k ); mbedtls_mpi_free( &ctx->r ); } #if defined(MBEDTLS_ECDSA_DETERMINISTIC) /* * Sub-context for ecdsa_sign_det() */ struct mbedtls_ecdsa_restart_det { mbedtls_hmac_drbg_context rng_ctx; /* DRBG state */ enum { /* what to do next? */ ecdsa_det_init = 0, /* getting started */ ecdsa_det_sign, /* make signature */ } state; }; /* * Init verify sign_det sub-context */ static void ecdsa_restart_det_init( mbedtls_ecdsa_restart_det_ctx *ctx ) { mbedtls_hmac_drbg_init( &ctx->rng_ctx ); ctx->state = ecdsa_det_init; } /* * Free the components of a sign_det restart sub-context */ static void ecdsa_restart_det_free( mbedtls_ecdsa_restart_det_ctx *ctx ) { if( ctx == NULL ) return; mbedtls_hmac_drbg_free( &ctx->rng_ctx ); ecdsa_restart_det_init( ctx ); } #endif /* MBEDTLS_ECDSA_DETERMINISTIC */ #define ECDSA_RS_ECP ( rs_ctx == NULL ? NULL : &rs_ctx->ecp ) /* Utility macro for checking and updating ops budget */ #define ECDSA_BUDGET( ops ) \ MBEDTLS_MPI_CHK( mbedtls_ecp_check_budget( grp, ECDSA_RS_ECP, ops ) ); /* Call this when entering a function that needs its own sub-context */ #define ECDSA_RS_ENTER( SUB ) do { \ /* reset ops count for this call if top-level */ \ if( rs_ctx != NULL && rs_ctx->ecp.depth++ == 0 ) \ rs_ctx->ecp.ops_done = 0; \ \ /* set up our own sub-context if needed */ \ if( mbedtls_ecp_restart_is_enabled() && \ rs_ctx != NULL && rs_ctx->SUB == NULL ) \ { \ rs_ctx->SUB = mbedtls_calloc( 1, sizeof( *rs_ctx->SUB ) ); \ if( rs_ctx->SUB == NULL ) \ return( MBEDTLS_ERR_ECP_ALLOC_FAILED ); \ \ ecdsa_restart_## SUB ##_init( rs_ctx->SUB ); \ } \ } while( 0 ) /* Call this when leaving a function that needs its own sub-context */ #define ECDSA_RS_LEAVE( SUB ) do { \ /* clear our sub-context when not in progress (done or error) */ \ if( rs_ctx != NULL && rs_ctx->SUB != NULL && \ ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) \ { \ ecdsa_restart_## SUB ##_free( rs_ctx->SUB ); \ mbedtls_free( rs_ctx->SUB ); \ rs_ctx->SUB = NULL; \ } \ \ if( rs_ctx != NULL ) \ rs_ctx->ecp.depth--; \ } while( 0 ) #else /* MBEDTLS_ECP_RESTARTABLE */ #define ECDSA_RS_ECP NULL #define ECDSA_BUDGET( ops ) /* no-op; for compatibility */ #define ECDSA_RS_ENTER( SUB ) (void) rs_ctx #define ECDSA_RS_LEAVE( SUB ) (void) rs_ctx #endif /* MBEDTLS_ECP_RESTARTABLE */ #if defined(MBEDTLS_ECDSA_DETERMINISTIC) || \ !defined(MBEDTLS_ECDSA_SIGN_ALT) || \ !defined(MBEDTLS_ECDSA_VERIFY_ALT) /* * Derive a suitable integer for group grp from a buffer of length len * SEC1 4.1.3 step 5 aka SEC1 4.1.4 step 3 */ static int derive_mpi( const mbedtls_ecp_group *grp, mbedtls_mpi *x, const unsigned char *buf, size_t blen ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t n_size = ( grp->nbits + 7 ) / 8; size_t use_size = blen > n_size ? n_size : blen; MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( x, buf, use_size ) ); if( use_size * 8 > grp->nbits ) MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( x, use_size * 8 - grp->nbits ) ); /* While at it, reduce modulo N */ if( mbedtls_mpi_cmp_mpi( x, &grp->N ) >= 0 ) MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( x, x, &grp->N ) ); cleanup: return( ret ); } #endif /* ECDSA_DETERMINISTIC || !ECDSA_SIGN_ALT || !ECDSA_VERIFY_ALT */ #if !defined(MBEDTLS_ECDSA_SIGN_ALT) /* * Compute ECDSA signature of a hashed message (SEC1 4.1.3) * Obviously, compared to SEC1 4.1.3, we skip step 4 (hash message) */ static int ecdsa_sign_restartable( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int (*f_rng_blind)(void *, unsigned char *, size_t), void *p_rng_blind, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret, key_tries, sign_tries; int *p_sign_tries = &sign_tries, *p_key_tries = &key_tries; mbedtls_ecp_point R; mbedtls_mpi k, e, t; mbedtls_mpi *pk = &k, *pr = r; /* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */ if( ! mbedtls_ecdsa_can_do( grp->id ) || grp->N.p == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); /* Make sure d is in range 1..n-1 */ if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 ) return( MBEDTLS_ERR_ECP_INVALID_KEY ); mbedtls_ecp_point_init( &R ); mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t ); ECDSA_RS_ENTER( sig ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->sig != NULL ) { /* redirect to our context */ p_sign_tries = &rs_ctx->sig->sign_tries; p_key_tries = &rs_ctx->sig->key_tries; pk = &rs_ctx->sig->k; pr = &rs_ctx->sig->r; /* jump to current step */ if( rs_ctx->sig->state == ecdsa_sig_mul ) goto mul; if( rs_ctx->sig->state == ecdsa_sig_modn ) goto modn; } #endif /* MBEDTLS_ECP_RESTARTABLE */ *p_sign_tries = 0; do { if( (*p_sign_tries)++ > 10 ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } /* * Steps 1-3: generate a suitable ephemeral keypair * and set r = xR mod n */ *p_key_tries = 0; do { if( (*p_key_tries)++ > 10 ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, pk, f_rng, p_rng ) ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->sig != NULL ) rs_ctx->sig->state = ecdsa_sig_mul; mul: #endif MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, &R, pk, &grp->G, f_rng_blind, p_rng_blind, ECDSA_RS_ECP ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pr, &R.X, &grp->N ) ); } while( mbedtls_mpi_cmp_int( pr, 0 ) == 0 ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->sig != NULL ) rs_ctx->sig->state = ecdsa_sig_modn; modn: #endif /* * Accounting for everything up to the end of the loop * (step 6, but checking now avoids saving e and t) */ ECDSA_BUDGET( MBEDTLS_ECP_OPS_INV + 4 ); /* * Step 5: derive MPI from hashed message */ MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) ); /* * Generate a random value to blind inv_mod in next step, * avoiding a potential timing leak. */ MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, &t, f_rng_blind, p_rng_blind ) ); /* * Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, pr, d ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pk, pk, &t ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pk, pk, &grp->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, pk, &grp->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) ); } while( mbedtls_mpi_cmp_int( s, 0 ) == 0 ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->sig != NULL ) mbedtls_mpi_copy( r, pr ); #endif cleanup: mbedtls_ecp_point_free( &R ); mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t ); ECDSA_RS_LEAVE( sig ); return( ret ); } int mbedtls_ecdsa_can_do( mbedtls_ecp_group_id gid ) { switch( gid ) { #ifdef MBEDTLS_ECP_DP_CURVE25519_ENABLED case MBEDTLS_ECP_DP_CURVE25519: return 0; #endif #ifdef MBEDTLS_ECP_DP_CURVE448_ENABLED case MBEDTLS_ECP_DP_CURVE448: return 0; #endif default: return 1; } } /* * Compute ECDSA signature of a hashed message */ int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { ECDSA_VALIDATE_RET( grp != NULL ); ECDSA_VALIDATE_RET( r != NULL ); ECDSA_VALIDATE_RET( s != NULL ); ECDSA_VALIDATE_RET( d != NULL ); ECDSA_VALIDATE_RET( f_rng != NULL ); ECDSA_VALIDATE_RET( buf != NULL || blen == 0 ); /* Use the same RNG for both blinding and ephemeral key generation */ return( ecdsa_sign_restartable( grp, r, s, d, buf, blen, f_rng, p_rng, f_rng, p_rng, NULL ) ); } #endif /* !MBEDTLS_ECDSA_SIGN_ALT */ #if defined(MBEDTLS_ECDSA_DETERMINISTIC) /* * Deterministic signature wrapper */ static int ecdsa_sign_det_restartable( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg, int (*f_rng_blind)(void *, unsigned char *, size_t), void *p_rng_blind, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_hmac_drbg_context rng_ctx; mbedtls_hmac_drbg_context *p_rng = &rng_ctx; unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES]; size_t grp_len = ( grp->nbits + 7 ) / 8; const mbedtls_md_info_t *md_info; mbedtls_mpi h; if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); mbedtls_mpi_init( &h ); mbedtls_hmac_drbg_init( &rng_ctx ); ECDSA_RS_ENTER( det ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->det != NULL ) { /* redirect to our context */ p_rng = &rs_ctx->det->rng_ctx; /* jump to current step */ if( rs_ctx->det->state == ecdsa_det_sign ) goto sign; } #endif /* MBEDTLS_ECP_RESTARTABLE */ /* Use private key and message hash (reduced) to initialize HMAC_DRBG */ MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( d, data, grp_len ) ); MBEDTLS_MPI_CHK( derive_mpi( grp, &h, buf, blen ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, data + grp_len, grp_len ) ); mbedtls_hmac_drbg_seed_buf( p_rng, md_info, data, 2 * grp_len ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->det != NULL ) rs_ctx->det->state = ecdsa_det_sign; sign: #endif #if defined(MBEDTLS_ECDSA_SIGN_ALT) (void) f_rng_blind; (void) p_rng_blind; ret = mbedtls_ecdsa_sign( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng ); #else if( f_rng_blind != NULL ) ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng, f_rng_blind, p_rng_blind, rs_ctx ); else { mbedtls_hmac_drbg_context *p_rng_blind_det; #if !defined(MBEDTLS_ECP_RESTARTABLE) /* * To avoid reusing rng_ctx and risking incorrect behavior we seed a * second HMAC-DRBG with the same seed. We also apply a label to avoid * reusing the bits of the ephemeral key for blinding and eliminate the * risk that they leak this way. */ const char* blind_label = "BLINDING CONTEXT"; mbedtls_hmac_drbg_context rng_ctx_blind; mbedtls_hmac_drbg_init( &rng_ctx_blind ); p_rng_blind_det = &rng_ctx_blind; mbedtls_hmac_drbg_seed_buf( p_rng_blind_det, md_info, data, 2 * grp_len ); ret = mbedtls_hmac_drbg_update_ret( p_rng_blind_det, (const unsigned char*) blind_label, strlen( blind_label ) ); if( ret != 0 ) { mbedtls_hmac_drbg_free( &rng_ctx_blind ); goto cleanup; } #else /* * In the case of restartable computations we would either need to store * the second RNG in the restart context too or set it up at every * restart. The first option would penalize the correct application of * the function and the second would defeat the purpose of the * restartable feature. * * Therefore in this case we reuse the original RNG. This comes with the * price that the resulting signature might not be a valid deterministic * ECDSA signature with a very low probability (same magnitude as * successfully guessing the private key). However even then it is still * a valid ECDSA signature. */ p_rng_blind_det = p_rng; #endif /* MBEDTLS_ECP_RESTARTABLE */ /* * Since the output of the RNGs is always the same for the same key and * message, this limits the efficiency of blinding and leaks information * through side channels. After mbedtls_ecdsa_sign_det() is removed NULL * won't be a valid value for f_rng_blind anymore. Therefore it should * be checked by the caller and this branch and check can be removed. */ ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng, mbedtls_hmac_drbg_random, p_rng_blind_det, rs_ctx ); #if !defined(MBEDTLS_ECP_RESTARTABLE) mbedtls_hmac_drbg_free( &rng_ctx_blind ); #endif } #endif /* MBEDTLS_ECDSA_SIGN_ALT */ cleanup: mbedtls_hmac_drbg_free( &rng_ctx ); mbedtls_mpi_free( &h ); ECDSA_RS_LEAVE( det ); return( ret ); } /* * Deterministic signature wrappers */ int mbedtls_ecdsa_sign_det_ext( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg, int (*f_rng_blind)(void *, unsigned char *, size_t), void *p_rng_blind ) { ECDSA_VALIDATE_RET( grp != NULL ); ECDSA_VALIDATE_RET( r != NULL ); ECDSA_VALIDATE_RET( s != NULL ); ECDSA_VALIDATE_RET( d != NULL ); ECDSA_VALIDATE_RET( buf != NULL || blen == 0 ); ECDSA_VALIDATE_RET( f_rng_blind != NULL ); return( ecdsa_sign_det_restartable( grp, r, s, d, buf, blen, md_alg, f_rng_blind, p_rng_blind, NULL ) ); } #endif /* MBEDTLS_ECDSA_DETERMINISTIC */ #if !defined(MBEDTLS_ECDSA_VERIFY_ALT) /* * Verify ECDSA signature of hashed message (SEC1 4.1.4) * Obviously, compared to SEC1 4.1.3, we skip step 2 (hash message) */ static int ecdsa_verify_restartable( mbedtls_ecp_group *grp, const unsigned char *buf, size_t blen, const mbedtls_ecp_point *Q, const mbedtls_mpi *r, const mbedtls_mpi *s, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_mpi e, s_inv, u1, u2; mbedtls_ecp_point R; mbedtls_mpi *pu1 = &u1, *pu2 = &u2; mbedtls_ecp_point_init( &R ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &s_inv ); mbedtls_mpi_init( &u1 ); mbedtls_mpi_init( &u2 ); /* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */ if( ! mbedtls_ecdsa_can_do( grp->id ) || grp->N.p == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); ECDSA_RS_ENTER( ver ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->ver != NULL ) { /* redirect to our context */ pu1 = &rs_ctx->ver->u1; pu2 = &rs_ctx->ver->u2; /* jump to current step */ if( rs_ctx->ver->state == ecdsa_ver_muladd ) goto muladd; } #endif /* MBEDTLS_ECP_RESTARTABLE */ /* * Step 1: make sure r and s are in range 1..n-1 */ if( mbedtls_mpi_cmp_int( r, 1 ) < 0 || mbedtls_mpi_cmp_mpi( r, &grp->N ) >= 0 || mbedtls_mpi_cmp_int( s, 1 ) < 0 || mbedtls_mpi_cmp_mpi( s, &grp->N ) >= 0 ) { ret = MBEDTLS_ERR_ECP_VERIFY_FAILED; goto cleanup; } /* * Step 3: derive MPI from hashed message */ MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) ); /* * Step 4: u1 = e / s mod n, u2 = r / s mod n */ ECDSA_BUDGET( MBEDTLS_ECP_OPS_CHK + MBEDTLS_ECP_OPS_INV + 2 ); MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &s_inv, s, &grp->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pu1, &e, &s_inv ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pu1, pu1, &grp->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pu2, r, &s_inv ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pu2, pu2, &grp->N ) ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->ver != NULL ) rs_ctx->ver->state = ecdsa_ver_muladd; muladd: #endif /* * Step 5: R = u1 G + u2 Q */ MBEDTLS_MPI_CHK( mbedtls_ecp_muladd_restartable( grp, &R, pu1, &grp->G, pu2, Q, ECDSA_RS_ECP ) ); if( mbedtls_ecp_is_zero( &R ) ) { ret = MBEDTLS_ERR_ECP_VERIFY_FAILED; goto cleanup; } /* * Step 6: convert xR to an integer (no-op) * Step 7: reduce xR mod n (gives v) */ MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &R.X, &R.X, &grp->N ) ); /* * Step 8: check if v (that is, R.X) is equal to r */ if( mbedtls_mpi_cmp_mpi( &R.X, r ) != 0 ) { ret = MBEDTLS_ERR_ECP_VERIFY_FAILED; goto cleanup; } cleanup: mbedtls_ecp_point_free( &R ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &s_inv ); mbedtls_mpi_free( &u1 ); mbedtls_mpi_free( &u2 ); ECDSA_RS_LEAVE( ver ); return( ret ); } /* * Verify ECDSA signature of hashed message */ int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp, const unsigned char *buf, size_t blen, const mbedtls_ecp_point *Q, const mbedtls_mpi *r, const mbedtls_mpi *s) { ECDSA_VALIDATE_RET( grp != NULL ); ECDSA_VALIDATE_RET( Q != NULL ); ECDSA_VALIDATE_RET( r != NULL ); ECDSA_VALIDATE_RET( s != NULL ); ECDSA_VALIDATE_RET( buf != NULL || blen == 0 ); return( ecdsa_verify_restartable( grp, buf, blen, Q, r, s, NULL ) ); } #endif /* !MBEDTLS_ECDSA_VERIFY_ALT */ /* * Convert a signature (given by context) to ASN.1 */ static int ecdsa_signature_to_asn1( const mbedtls_mpi *r, const mbedtls_mpi *s, unsigned char *sig, size_t *slen ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char buf[MBEDTLS_ECDSA_MAX_LEN]; unsigned char *p = buf + sizeof( buf ); size_t len = 0; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &p, buf, s ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &p, buf, r ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &p, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &p, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); memcpy( sig, p, len ); *slen = len; return( 0 ); } /* * Compute and write signature */ int mbedtls_ecdsa_write_signature_restartable( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hlen, unsigned char *sig, size_t *slen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_mpi r, s; ECDSA_VALIDATE_RET( ctx != NULL ); ECDSA_VALIDATE_RET( hash != NULL ); ECDSA_VALIDATE_RET( sig != NULL ); ECDSA_VALIDATE_RET( slen != NULL ); mbedtls_mpi_init( &r ); mbedtls_mpi_init( &s ); #if defined(MBEDTLS_ECDSA_DETERMINISTIC) MBEDTLS_MPI_CHK( ecdsa_sign_det_restartable( &ctx->grp, &r, &s, &ctx->d, hash, hlen, md_alg, f_rng, p_rng, rs_ctx ) ); #else (void) md_alg; #if defined(MBEDTLS_ECDSA_SIGN_ALT) (void) rs_ctx; MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d, hash, hlen, f_rng, p_rng ) ); #else /* Use the same RNG for both blinding and ephemeral key generation */ MBEDTLS_MPI_CHK( ecdsa_sign_restartable( &ctx->grp, &r, &s, &ctx->d, hash, hlen, f_rng, p_rng, f_rng, p_rng, rs_ctx ) ); #endif /* MBEDTLS_ECDSA_SIGN_ALT */ #endif /* MBEDTLS_ECDSA_DETERMINISTIC */ MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) ); cleanup: mbedtls_mpi_free( &r ); mbedtls_mpi_free( &s ); return( ret ); } /* * Compute and write signature */ int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hlen, unsigned char *sig, size_t *slen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { ECDSA_VALIDATE_RET( ctx != NULL ); ECDSA_VALIDATE_RET( hash != NULL ); ECDSA_VALIDATE_RET( sig != NULL ); ECDSA_VALIDATE_RET( slen != NULL ); return( mbedtls_ecdsa_write_signature_restartable( ctx, md_alg, hash, hlen, sig, slen, f_rng, p_rng, NULL ) ); } /* * Read and check signature */ int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx, const unsigned char *hash, size_t hlen, const unsigned char *sig, size_t slen ) { ECDSA_VALIDATE_RET( ctx != NULL ); ECDSA_VALIDATE_RET( hash != NULL ); ECDSA_VALIDATE_RET( sig != NULL ); return( mbedtls_ecdsa_read_signature_restartable( ctx, hash, hlen, sig, slen, NULL ) ); } /* * Restartable read and check signature */ int mbedtls_ecdsa_read_signature_restartable( mbedtls_ecdsa_context *ctx, const unsigned char *hash, size_t hlen, const unsigned char *sig, size_t slen, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char *p = (unsigned char *) sig; const unsigned char *end = sig + slen; size_t len; mbedtls_mpi r, s; ECDSA_VALIDATE_RET( ctx != NULL ); ECDSA_VALIDATE_RET( hash != NULL ); ECDSA_VALIDATE_RET( sig != NULL ); mbedtls_mpi_init( &r ); mbedtls_mpi_init( &s ); if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { ret += MBEDTLS_ERR_ECP_BAD_INPUT_DATA; goto cleanup; } if( p + len != end ) { ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH; goto cleanup; } if( ( ret = mbedtls_asn1_get_mpi( &p, end, &r ) ) != 0 || ( ret = mbedtls_asn1_get_mpi( &p, end, &s ) ) != 0 ) { ret += MBEDTLS_ERR_ECP_BAD_INPUT_DATA; goto cleanup; } #if defined(MBEDTLS_ECDSA_VERIFY_ALT) (void) rs_ctx; if( ( ret = mbedtls_ecdsa_verify( &ctx->grp, hash, hlen, &ctx->Q, &r, &s ) ) != 0 ) goto cleanup; #else if( ( ret = ecdsa_verify_restartable( &ctx->grp, hash, hlen, &ctx->Q, &r, &s, rs_ctx ) ) != 0 ) goto cleanup; #endif /* MBEDTLS_ECDSA_VERIFY_ALT */ /* At this point we know that the buffer starts with a valid signature. * Return 0 if the buffer just contains the signature, and a specific * error code if the valid signature is followed by more data. */ if( p != end ) ret = MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH; cleanup: mbedtls_mpi_free( &r ); mbedtls_mpi_free( &s ); return( ret ); } #if !defined(MBEDTLS_ECDSA_GENKEY_ALT) /* * Generate key pair */ int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = 0; ECDSA_VALIDATE_RET( ctx != NULL ); ECDSA_VALIDATE_RET( f_rng != NULL ); ret = mbedtls_ecp_group_load( &ctx->grp, gid ); if( ret != 0 ) return( ret ); return( mbedtls_ecp_gen_keypair( &ctx->grp, &ctx->d, &ctx->Q, f_rng, p_rng ) ); } #endif /* !MBEDTLS_ECDSA_GENKEY_ALT */ /* * Set context from an mbedtls_ecp_keypair */ int mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, const mbedtls_ecp_keypair *key ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; ECDSA_VALIDATE_RET( ctx != NULL ); ECDSA_VALIDATE_RET( key != NULL ); if( ( ret = mbedtls_ecp_group_copy( &ctx->grp, &key->grp ) ) != 0 || ( ret = mbedtls_mpi_copy( &ctx->d, &key->d ) ) != 0 || ( ret = mbedtls_ecp_copy( &ctx->Q, &key->Q ) ) != 0 ) { mbedtls_ecdsa_free( ctx ); } return( ret ); } /* * Initialize context */ void mbedtls_ecdsa_init( mbedtls_ecdsa_context *ctx ) { ECDSA_VALIDATE( ctx != NULL ); mbedtls_ecp_keypair_init( ctx ); } /* * Free context */ void mbedtls_ecdsa_free( mbedtls_ecdsa_context *ctx ) { if( ctx == NULL ) return; mbedtls_ecp_keypair_free( ctx ); } #if defined(MBEDTLS_ECP_RESTARTABLE) /* * Initialize a restart context */ void mbedtls_ecdsa_restart_init( mbedtls_ecdsa_restart_ctx *ctx ) { ECDSA_VALIDATE( ctx != NULL ); mbedtls_ecp_restart_init( &ctx->ecp ); ctx->ver = NULL; ctx->sig = NULL; #if defined(MBEDTLS_ECDSA_DETERMINISTIC) ctx->det = NULL; #endif } /* * Free the components of a restart context */ void mbedtls_ecdsa_restart_free( mbedtls_ecdsa_restart_ctx *ctx ) { if( ctx == NULL ) return; mbedtls_ecp_restart_free( &ctx->ecp ); ecdsa_restart_ver_free( ctx->ver ); mbedtls_free( ctx->ver ); ctx->ver = NULL; ecdsa_restart_sig_free( ctx->sig ); mbedtls_free( ctx->sig ); ctx->sig = NULL; #if defined(MBEDTLS_ECDSA_DETERMINISTIC) ecdsa_restart_det_free( ctx->det ); mbedtls_free( ctx->det ); ctx->det = NULL; #endif } #endif /* MBEDTLS_ECP_RESTARTABLE */ #endif /* MBEDTLS_ECDSA_C */
32,776
972
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/ccm.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "third_party/mbedtls/ccm.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/platform.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /** * @fileoverview NIST SP800-38C compliant CCM implementation * * This file provides an API for the CCM authenticated encryption mode * for block ciphers. * * CCM combines Counter mode encryption with CBC-MAC authentication * for 128-bit block ciphers. * * Input to CCM includes the following elements: * <ul><li>Payload - data that is both authenticated and encrypted.</li> * <li>Associated data (Adata) - data that is authenticated but not * encrypted, For example, a header.</li> * <li>Nonce - A unique value that is assigned to the payload and the * associated data.</li></ul> * * Definition of CCM: * http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C_updated-July20_2007.pdf * RFC 3610 "Counter with CBC-MAC (CCM)" * * Related: * RFC 5116 "An Interface and Algorithms for Authenticated Encryption" * * Definition of CCM*: * IEEE 802.15.4 - IEEE Standard for Local and metropolitan area networks * Integer representation is fixed most-significant-octet-first order and * the representation of octets is most-significant-bit-first order. This is * consistent with RFC 3610. */ #define CCM_VALIDATE_RET( cond ) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_CCM_BAD_INPUT ) #define CCM_VALIDATE( cond ) \ MBEDTLS_INTERNAL_VALIDATE( cond ) #define CCM_ENCRYPT 0 #define CCM_DECRYPT 1 /** * \brief This function initializes the specified CCM context, * to make references valid, and prepare the context * for mbedtls_ccm_setkey() or mbedtls_ccm_free(). * * \param ctx The CCM context to initialize. This must not be \c NULL. */ void mbedtls_ccm_init( mbedtls_ccm_context *ctx ) { CCM_VALIDATE( ctx ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ccm_context ) ); } /** * \brief This function initializes the CCM context set in the * \p ctx parameter and sets the encryption key. * * \param ctx The CCM context to initialize. This must be an initialized * context. * \param cipher The 128-bit block cipher to use. * \param key The encryption key. This must not be \c NULL. * \param keybits The key size in bits. This must be acceptable by the cipher. * * \return \c 0 on success. * \return A CCM or cipher-specific error code on failure. */ int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx, mbedtls_cipher_id_t cipher, const unsigned char *key, unsigned int keybits ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; const mbedtls_cipher_info_t *cipher_info; CCM_VALIDATE_RET( ctx ); CCM_VALIDATE_RET( key ); cipher_info = mbedtls_cipher_info_from_values( cipher, keybits, MBEDTLS_MODE_ECB ); if( cipher_info == NULL ) return( MBEDTLS_ERR_CCM_BAD_INPUT ); if( cipher_info->block_size != 16 ) return( MBEDTLS_ERR_CCM_BAD_INPUT ); mbedtls_cipher_free( &ctx->cipher_ctx ); if( ( ret = mbedtls_cipher_setup( &ctx->cipher_ctx, cipher_info ) ) != 0 ) return( ret ); if( ( ret = mbedtls_cipher_setkey( &ctx->cipher_ctx, key, keybits, MBEDTLS_ENCRYPT ) ) != 0 ) { return( ret ); } return( 0 ); } /** * \brief This function releases and clears the specified CCM context * and underlying cipher sub-context. * * \param ctx The CCM context to clear. If this is \c NULL, the function * has no effect. Otherwise, this must be initialized. */ void mbedtls_ccm_free( mbedtls_ccm_context *ctx ) { if( ctx == NULL ) return; mbedtls_cipher_free( &ctx->cipher_ctx ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ccm_context ) ); } /* * Macros for common operations. * Results in smaller compiled code than static inline functions. */ /* * Update the CBC-MAC state in y using a block in b * (Always using b as the source helps the compiler optimise a bit better.) */ #define UPDATE_CBC_MAC \ for( i = 0; i < 16; i++ ) \ y[i] ^= b[i]; \ \ if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, y, 16, y, &olen ) ) != 0 ) \ return( ret ); /* * Encrypt or decrypt a partial block with CTR * Warning: using b for temporary storage! src and dst must not be b! * This avoids allocating one more 16 bytes buffer while allowing src == dst. */ #define CTR_CRYPT( dst, src, len ) \ do \ { \ if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, ctr, \ 16, b, &olen ) ) != 0 ) \ { \ return( ret ); \ } \ \ for( i = 0; i < (len); i++ ) \ (dst)[i] = (src)[i] ^ b[i]; \ } while( 0 ) /* * Authenticated encryption or decryption */ static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length, const unsigned char *iv, size_t iv_len, const unsigned char *add, size_t add_len, const unsigned char *input, unsigned char *output, unsigned char *tag, size_t tag_len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char i; unsigned char q; size_t len_left, olen; unsigned char b[16]; unsigned char y[16]; unsigned char ctr[16]; const unsigned char *src; unsigned char *dst; /* * Check length requirements: SP800-38C A.1 * Additional requirement: a < 2^16 - 2^8 to simplify the code. * 'length' checked later (when writing it to the first block) * * Also, loosen the requirements to enable support for CCM* (IEEE 802.15.4). */ if( tag_len == 2 || tag_len > 16 || tag_len % 2 != 0 ) return( MBEDTLS_ERR_CCM_BAD_INPUT ); /* Also implies q is within bounds */ if( iv_len < 7 || iv_len > 13 ) return( MBEDTLS_ERR_CCM_BAD_INPUT ); if( add_len >= 0xFF00 ) return( MBEDTLS_ERR_CCM_BAD_INPUT ); q = 16 - 1 - (unsigned char) iv_len; /* * First block B_0: * 0 .. 0 flags * 1 .. iv_len nonce (aka iv) * iv_len+1 .. 15 length * * With flags as (bits): * 7 0 * 6 add present? * 5 .. 3 (t - 2) / 2 * 2 .. 0 q - 1 */ b[0] = 0; b[0] |= ( add_len > 0 ) << 6; b[0] |= ( ( tag_len - 2 ) / 2 ) << 3; b[0] |= q - 1; memcpy( b + 1, iv, iv_len ); for( i = 0, len_left = length; i < q; i++, len_left >>= 8 ) b[15-i] = (unsigned char)( len_left & 0xFF ); if( len_left > 0 ) return( MBEDTLS_ERR_CCM_BAD_INPUT ); /* Start CBC-MAC with first block */ memset( y, 0, 16 ); UPDATE_CBC_MAC; /* * If there is additional data, update CBC-MAC with * add_len, add, 0 (padding to a block boundary) */ if( add_len > 0 ) { size_t use_len; len_left = add_len; src = add; memset( b, 0, 16 ); b[0] = (unsigned char)( ( add_len >> 8 ) & 0xFF ); b[1] = (unsigned char)( ( add_len ) & 0xFF ); use_len = len_left < 16 - 2 ? len_left : 16 - 2; memcpy( b + 2, src, use_len ); len_left -= use_len; src += use_len; UPDATE_CBC_MAC; while( len_left > 0 ) { use_len = len_left > 16 ? 16 : len_left; memset( b, 0, 16 ); memcpy( b, src, use_len ); UPDATE_CBC_MAC; len_left -= use_len; src += use_len; } } /* * Prepare counter block for encryption: * 0 .. 0 flags * 1 .. iv_len nonce (aka iv) * iv_len+1 .. 15 counter (initially 1) * * With flags as (bits): * 7 .. 3 0 * 2 .. 0 q - 1 */ ctr[0] = q - 1; memcpy( ctr + 1, iv, iv_len ); memset( ctr + 1 + iv_len, 0, q ); ctr[15] = 1; /* * Authenticate and {en,de}crypt the message. * * The only difference between encryption and decryption is * the respective order of authentication and {en,de}cryption. */ len_left = length; src = input; dst = output; while( len_left > 0 ) { size_t use_len = len_left > 16 ? 16 : len_left; if( mode == CCM_ENCRYPT ) { memset( b, 0, 16 ); memcpy( b, src, use_len ); UPDATE_CBC_MAC; } CTR_CRYPT( dst, src, use_len ); if( mode == CCM_DECRYPT ) { memset( b, 0, 16 ); memcpy( b, dst, use_len ); UPDATE_CBC_MAC; } dst += use_len; src += use_len; len_left -= use_len; /* * Increment counter. * No need to check for overflow thanks to the length check above. */ for( i = 0; i < q; i++ ) if( ++ctr[15-i] != 0 ) break; } /* * Authentication: reset counter and crypt/mask internal tag */ for( i = 0; i < q; i++ ) ctr[15-i] = 0; CTR_CRYPT( y, y, 16 ); memcpy( tag, y, tag_len ); return( 0 ); } /** * \brief This function encrypts a buffer using CCM*. * * \note The tag is written to a separate buffer. To concatenate * the \p tag with the \p output, as done in <em>RFC-3610: * Counter with CBC-MAC (CCM)</em>, use * \p tag = \p output + \p length, and make sure that the * output buffer is at least \p length + \p tag_len wide. * * \note When using this function in a variable tag length context, * the tag length has to be encoded into the \p iv passed to * this function. * * \param ctx The CCM context to use for encryption. This must be * initialized and bound to a key. * \param length The length of the input data in Bytes. * \param iv The initialization vector (nonce). This must be a readable * buffer of at least \p iv_len Bytes. * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12, * or 13. The length L of the message length field is * 15 - \p iv_len. * \param add The additional data field. This must be a readable buffer of * at least \p add_len Bytes. * \param add_len The length of additional data in Bytes. * This must be less than 2^16 - 2^8. * \param input The buffer holding the input data. If \p length is greater * than zero, \p input must be a readable buffer of at least * that length. * \param output The buffer holding the output data. If \p length is greater * than zero, \p output must be a writable buffer of at least * that length. * \param tag The buffer holding the authentication field. This must be a * writable buffer of at least \p tag_len Bytes. * \param tag_len The length of the authentication field to generate in Bytes: * 0, 4, 6, 8, 10, 12, 14 or 16. * * \warning Passing \c 0 as \p tag_len means that the message is no * longer authenticated. * * \return \c 0 on success. * \return A CCM or cipher-specific error code on failure. */ int mbedtls_ccm_star_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length, const unsigned char *iv, size_t iv_len, const unsigned char *add, size_t add_len, const unsigned char *input, unsigned char *output, unsigned char *tag, size_t tag_len ) { CCM_VALIDATE_RET( ctx ); CCM_VALIDATE_RET( iv ); CCM_VALIDATE_RET( add_len == 0 || add ); CCM_VALIDATE_RET( length == 0 || input ); CCM_VALIDATE_RET( length == 0 || output ); CCM_VALIDATE_RET( tag_len == 0 || tag ); return( ccm_auth_crypt( ctx, CCM_ENCRYPT, length, iv, iv_len, add, add_len, input, output, tag, tag_len ) ); } /** * \brief This function encrypts a buffer using CCM. * * \note The tag is written to a separate buffer. To concatenate * the \p tag with the \p output, as done in <em>RFC-3610: * Counter with CBC-MAC (CCM)</em>, use * \p tag = \p output + \p length, and make sure that the * output buffer is at least \p length + \p tag_len wide. * * \param ctx The CCM context to use for encryption. This must be * initialized and bound to a key. * \param length The length of the input data in Bytes. * \param iv The initialization vector (nonce). This must be a readable * buffer of at least \p iv_len Bytes. * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12, * or 13. The length L of the message length field is * 15 - \p iv_len. * \param add The additional data field. If \p add_len is greater than * zero, \p add must be a readable buffer of at least that * length. * \param add_len The length of additional data in Bytes. * This must be less than `2^16 - 2^8`. * \param input The buffer holding the input data. If \p length is greater * than zero, \p input must be a readable buffer of at least * that length. * \param output The buffer holding the output data. If \p length is greater * than zero, \p output must be a writable buffer of at least * that length. * \param tag The buffer holding the authentication field. This must be a * writable buffer of at least \p tag_len Bytes. * \param tag_len The length of the authentication field to generate in Bytes: * 4, 6, 8, 10, 12, 14 or 16. * * \return \c 0 on success. * \return A CCM or cipher-specific error code on failure. */ int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length, const unsigned char *iv, size_t iv_len, const unsigned char *add, size_t add_len, const unsigned char *input, unsigned char *output, unsigned char *tag, size_t tag_len ) { CCM_VALIDATE_RET( ctx ); CCM_VALIDATE_RET( iv ); CCM_VALIDATE_RET( add_len == 0 || add ); CCM_VALIDATE_RET( length == 0 || input ); CCM_VALIDATE_RET( length == 0 || output ); CCM_VALIDATE_RET( tag_len == 0 || tag ); if( tag_len == 0 ) return( MBEDTLS_ERR_CCM_BAD_INPUT ); return( mbedtls_ccm_star_encrypt_and_tag( ctx, length, iv, iv_len, add, add_len, input, output, tag, tag_len ) ); } /** * \brief This function performs a CCM* authenticated decryption of a * buffer. * * \note When using this function in a variable tag length context, * the tag length has to be decoded from \p iv and passed to * this function as \p tag_len. (\p tag needs to be adjusted * accordingly.) * * \param ctx The CCM context to use for decryption. This must be * initialized and bound to a key. * \param length The length of the input data in Bytes. * \param iv The initialization vector (nonce). This must be a readable * buffer of at least \p iv_len Bytes. * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12, * or 13. The length L of the message length field is * 15 - \p iv_len. * \param add The additional data field. This must be a readable buffer of * at least that \p add_len Bytes. * \param add_len The length of additional data in Bytes. * This must be less than 2^16 - 2^8. * \param input The buffer holding the input data. If \p length is greater * than zero, \p input must be a readable buffer of at least * that length. * \param output The buffer holding the output data. If \p length is greater * than zero, \p output must be a writable buffer of at least * that length. * \param tag The buffer holding the authentication field. This must be a * readable buffer of at least \p tag_len Bytes. * \param tag_len The length of the authentication field in Bytes. * 0, 4, 6, 8, 10, 12, 14 or 16. * * \warning Passing \c 0 as \p tag_len means that the message is nos * longer authenticated. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CCM_AUTH_FAILED if the tag does not match. * \return A cipher-specific error code on calculation failure. */ int mbedtls_ccm_star_auth_decrypt( mbedtls_ccm_context *ctx, size_t length, const unsigned char *iv, size_t iv_len, const unsigned char *add, size_t add_len, const unsigned char *input, unsigned char *output, const unsigned char *tag, size_t tag_len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; unsigned char check_tag[16]; unsigned char i; int diff; CCM_VALIDATE_RET( ctx ); CCM_VALIDATE_RET( iv ); CCM_VALIDATE_RET( add_len == 0 || add ); CCM_VALIDATE_RET( length == 0 || input ); CCM_VALIDATE_RET( length == 0 || output ); CCM_VALIDATE_RET( tag_len == 0 || tag ); if( ( ret = ccm_auth_crypt( ctx, CCM_DECRYPT, length, iv, iv_len, add, add_len, input, output, check_tag, tag_len ) ) != 0 ) { return( ret ); } /* Check tag in "constant-time" */ for( diff = 0, i = 0; i < tag_len; i++ ) diff |= tag[i] ^ check_tag[i]; if( diff != 0 ) { mbedtls_platform_zeroize( output, length ); return( MBEDTLS_ERR_CCM_AUTH_FAILED ); } return( 0 ); } /** * \brief This function performs a CCM authenticated decryption of a * buffer. * * \param ctx The CCM context to use for decryption. This must be * initialized and bound to a key. * \param length The length of the input data in Bytes. * \param iv The initialization vector (nonce). This must be a readable * buffer of at least \p iv_len Bytes. * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12, * or 13. The length L of the message length field is * 15 - \p iv_len. * \param add The additional data field. This must be a readable buffer * of at least that \p add_len Bytes.. * \param add_len The length of additional data in Bytes. * This must be less than 2^16 - 2^8. * \param input The buffer holding the input data. If \p length is greater * than zero, \p input must be a readable buffer of at least * that length. * \param output The buffer holding the output data. If \p length is greater * than zero, \p output must be a writable buffer of at least * that length. * \param tag The buffer holding the authentication field. This must be a * readable buffer of at least \p tag_len Bytes. * \param tag_len The length of the authentication field to generate in Bytes: * 4, 6, 8, 10, 12, 14 or 16. * * \return \c 0 on success. This indicates that the message is * authentic. \return #MBEDTLS_ERR_CCM_AUTH_FAILED if the tag does not * match. \return A cipher-specific error code on calculation failure. */ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length, const unsigned char *iv, size_t iv_len, const unsigned char *add, size_t add_len, const unsigned char *input, unsigned char *output, const unsigned char *tag, size_t tag_len ) { CCM_VALIDATE_RET( ctx ); CCM_VALIDATE_RET( iv ); CCM_VALIDATE_RET( add || !add_len ); CCM_VALIDATE_RET( input || !length ); CCM_VALIDATE_RET( output || !length ); CCM_VALIDATE_RET( tag || !tag_len ); if( !tag_len ) return( MBEDTLS_ERR_CCM_BAD_INPUT ); return( mbedtls_ccm_star_auth_decrypt( ctx, length, iv, iv_len, add, add_len, input, output, tag, tag_len ) ); } #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C) /* * Examples 1 to 3 from SP800-38C Appendix C */ #define NB_TESTS 3 #define CCM_SELFTEST_PT_MAX_LEN 24 #define CCM_SELFTEST_CT_MAX_LEN 32 /* * The data is the same for all tests, only the used length changes */ static const unsigned char key_test_data[] = { 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f }; static const unsigned char iv_test_data[] = { 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b }; static const unsigned char ad_test_data[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13 }; static const unsigned char msg_test_data[CCM_SELFTEST_PT_MAX_LEN] = { 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, }; static const size_t iv_len_test_data [NB_TESTS] = { 7, 8, 12 }; static const size_t add_len_test_data[NB_TESTS] = { 8, 16, 20 }; static const size_t msg_len_test_data[NB_TESTS] = { 4, 16, 24 }; static const size_t tag_len_test_data[NB_TESTS] = { 4, 6, 8 }; static const unsigned char res_test_data[NB_TESTS][CCM_SELFTEST_CT_MAX_LEN] = { { 0x71, 0x62, 0x01, 0x5b, 0x4d, 0xac, 0x25, 0x5d }, { 0xd2, 0xa1, 0xf0, 0xe0, 0x51, 0xea, 0x5f, 0x62, 0x08, 0x1a, 0x77, 0x92, 0x07, 0x3d, 0x59, 0x3d, 0x1f, 0xc6, 0x4f, 0xbf, 0xac, 0xcd }, { 0xe3, 0xb2, 0x01, 0xa9, 0xf5, 0xb7, 0x1a, 0x7a, 0x9b, 0x1c, 0xea, 0xec, 0xcd, 0x97, 0xe7, 0x0b, 0x61, 0x76, 0xaa, 0xd9, 0xa4, 0x42, 0x8a, 0xa5, 0x48, 0x43, 0x92, 0xfb, 0xc1, 0xb0, 0x99, 0x51 } }; /** * \brief The CCM checkup routine. * * \return \c 0 on success. * \return \c 1 on failure. */ int mbedtls_ccm_self_test( int verbose ) { mbedtls_ccm_context ctx; /* * Some hardware accelerators require the input and output buffers * would be in RAM, because the flash is not accessible. * Use buffers on the stack to hold the test vectors data. */ unsigned char plaintext[CCM_SELFTEST_PT_MAX_LEN]; unsigned char ciphertext[CCM_SELFTEST_CT_MAX_LEN]; size_t i; int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_ccm_init( &ctx ); if( mbedtls_ccm_setkey( &ctx, MBEDTLS_CIPHER_ID_AES, key_test_data, 8 * sizeof key_test_data ) != 0 ) { if( verbose != 0 ) mbedtls_printf( " CCM: setup failed" ); return( 1 ); } for( i = 0; i < NB_TESTS; i++ ) { if( verbose != 0 ) mbedtls_printf( " CCM-AES #%u: ", (unsigned int) i + 1 ); mbedtls_platform_zeroize( plaintext, CCM_SELFTEST_PT_MAX_LEN ); mbedtls_platform_zeroize( ciphertext, CCM_SELFTEST_CT_MAX_LEN ); memcpy( plaintext, msg_test_data, msg_len_test_data[i] ); ret = mbedtls_ccm_encrypt_and_tag( &ctx, msg_len_test_data[i], iv_test_data, iv_len_test_data[i], ad_test_data, add_len_test_data[i], plaintext, ciphertext, ciphertext + msg_len_test_data[i], tag_len_test_data[i] ); if( ret != 0 || timingsafe_bcmp( ciphertext, res_test_data[i], msg_len_test_data[i] + tag_len_test_data[i] ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); return( 1 ); } mbedtls_platform_zeroize( plaintext, CCM_SELFTEST_PT_MAX_LEN ); ret = mbedtls_ccm_auth_decrypt( &ctx, msg_len_test_data[i], iv_test_data, iv_len_test_data[i], ad_test_data, add_len_test_data[i], ciphertext, plaintext, ciphertext + msg_len_test_data[i], tag_len_test_data[i] ); if( ret != 0 || timingsafe_bcmp( plaintext, msg_test_data, msg_len_test_data[i] ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); return( 1 ); } if( verbose != 0 ) mbedtls_printf( "passed\n" ); } mbedtls_ccm_free( &ctx ); if( verbose != 0 ) mbedtls_printf( "\n" ); return( 0 ); } #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
28,489
716
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/cipher_internal.h
#ifndef MBEDTLS_CIPHER_WRAP_H #define MBEDTLS_CIPHER_WRAP_H #include "third_party/mbedtls/cipher.h" #include "third_party/mbedtls/config.h" COSMOPOLITAN_C_START_ /* clang-format off */ /** * Base cipher information. The non-mode specific functions and values. */ struct mbedtls_cipher_base_t { /** Base Cipher type (e.g. MBEDTLS_CIPHER_ID_AES) */ mbedtls_cipher_id_t cipher; /** Encrypt using ECB */ int (*ecb_func)( void *ctx, mbedtls_operation_t mode, const unsigned char *input, unsigned char *output ); #if defined(MBEDTLS_CIPHER_MODE_CBC) /** Encrypt using CBC */ int (*cbc_func)( void *ctx, mbedtls_operation_t mode, size_t length, unsigned char *iv, const unsigned char *input, unsigned char *output ); #endif #if defined(MBEDTLS_CIPHER_MODE_CFB) /** Encrypt using CFB (Full length) */ int (*cfb_func)( void *ctx, mbedtls_operation_t mode, size_t length, size_t *iv_off, unsigned char *iv, const unsigned char *input, unsigned char *output ); #endif #if defined(MBEDTLS_CIPHER_MODE_OFB) /** Encrypt using OFB (Full length) */ int (*ofb_func)( void *ctx, size_t length, size_t *iv_off, unsigned char *iv, const unsigned char *input, unsigned char *output ); #endif #if defined(MBEDTLS_CIPHER_MODE_CTR) /** Encrypt using CTR */ int (*ctr_func)( void *ctx, size_t length, size_t *nc_off, unsigned char *nonce_counter, unsigned char *stream_block, const unsigned char *input, unsigned char *output ); #endif #if defined(MBEDTLS_CIPHER_MODE_XTS) /** Encrypt or decrypt using XTS. */ int (*xts_func)( void *ctx, mbedtls_operation_t mode, size_t length, const unsigned char data_unit[16], const unsigned char *input, unsigned char *output ); #endif #if defined(MBEDTLS_CIPHER_MODE_STREAM) /** Encrypt using STREAM */ int (*stream_func)( void *ctx, size_t length, const unsigned char *input, unsigned char *output ); #endif /** Set key for encryption purposes */ int (*setkey_enc_func)( void *ctx, const unsigned char *key, unsigned int key_bitlen ); /** Set key for decryption purposes */ int (*setkey_dec_func)( void *ctx, const unsigned char *key, unsigned int key_bitlen); /** Allocate a new context */ void * (*ctx_alloc_func)( void ); /** Free the given context */ void (*ctx_free_func)( void *ctx ); }; typedef struct { mbedtls_cipher_type_t type; const mbedtls_cipher_info_t *info; } mbedtls_cipher_definition_t; extern const mbedtls_cipher_definition_t mbedtls_cipher_definitions[]; extern int mbedtls_cipher_supported[]; COSMOPOLITAN_C_END_ #endif /* MBEDTLS_CIPHER_WRAP_H */
2,940
90
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/poly1305.h
#ifndef MBEDTLS_POLY1305_H #define MBEDTLS_POLY1305_H #include "third_party/mbedtls/config.h" /* clang-format off */ #define MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA -0x0057 /*< Invalid input parameter(s). */ /* MBEDTLS_ERR_POLY1305_FEATURE_UNAVAILABLE is deprecated and should not be * used. */ #define MBEDTLS_ERR_POLY1305_FEATURE_UNAVAILABLE -0x0059 /*< Feature not available. For example, s part of the API is not implemented. */ /* MBEDTLS_ERR_POLY1305_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_POLY1305_HW_ACCEL_FAILED -0x005B /*< Poly1305 hardware accelerator failed. */ #ifdef __cplusplus extern "C" { #endif #if !defined(MBEDTLS_POLY1305_ALT) typedef struct mbedtls_poly1305_context { uint32_t r[4]; /** The value for 'r' (low 128 bits of the key). */ uint32_t s[4]; /** The value for 's' (high 128 bits of the key). */ uint32_t acc[5]; /** The accumulator number. */ uint8_t queue[16]; /** The current partial block of data. */ size_t queue_len; /** The number of bytes stored in 'queue'. */ } mbedtls_poly1305_context; #endif /* MBEDTLS_POLY1305_ALT */ /** * \brief This function initializes the specified Poly1305 context. * * It must be the first API called before using * the context. * * It is usually followed by a call to * \c mbedtls_poly1305_starts(), then one or more calls to * \c mbedtls_poly1305_update(), then one call to * \c mbedtls_poly1305_finish(), then finally * \c mbedtls_poly1305_free(). * * \param ctx The Poly1305 context to initialize. This must * not be \c NULL. */ void mbedtls_poly1305_init( mbedtls_poly1305_context *ctx ); /** * \brief This function releases and clears the specified * Poly1305 context. * * \param ctx The Poly1305 context to clear. This may be \c NULL, in which * case this function is a no-op. If it is not \c NULL, it must * point to an initialized Poly1305 context. */ void mbedtls_poly1305_free( mbedtls_poly1305_context *ctx ); /** * \brief This function sets the one-time authentication key. * * \warning The key must be unique and unpredictable for each * invocation of Poly1305. * * \param ctx The Poly1305 context to which the key should be bound. * This must be initialized. * \param key The buffer containing the \c 32 Byte (\c 256 Bit) key. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_poly1305_starts( mbedtls_poly1305_context *ctx, const unsigned char key[32] ); /** * \brief This functions feeds an input buffer into an ongoing * Poly1305 computation. * * It is called between \c mbedtls_cipher_poly1305_starts() and * \c mbedtls_cipher_poly1305_finish(). * It can be called repeatedly to process a stream of data. * * \param ctx The Poly1305 context to use for the Poly1305 operation. * This must be initialized and bound to a key. * \param ilen The length of the input data in Bytes. * Any value is accepted. * \param input The buffer holding the input data. * This pointer can be \c NULL if `ilen == 0`. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_poly1305_update( mbedtls_poly1305_context *ctx, const unsigned char *input, size_t ilen ); /** * \brief This function generates the Poly1305 Message * Authentication Code (MAC). * * \param ctx The Poly1305 context to use for the Poly1305 operation. * This must be initialized and bound to a key. * \param mac The buffer to where the MAC is written. This must * be a writable buffer of length \c 16 Bytes. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_poly1305_finish( mbedtls_poly1305_context *ctx, unsigned char mac[16] ); /** * \brief This function calculates the Poly1305 MAC of the input * buffer with the provided key. * * \warning The key must be unique and unpredictable for each * invocation of Poly1305. * * \param key The buffer containing the \c 32 Byte (\c 256 Bit) key. * \param ilen The length of the input data in Bytes. * Any value is accepted. * \param input The buffer holding the input data. * This pointer can be \c NULL if `ilen == 0`. * \param mac The buffer to where the MAC is written. This must be * a writable buffer of length \c 16 Bytes. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_poly1305_mac( const unsigned char key[32], const unsigned char *input, size_t ilen, unsigned char mac[16] ); #if defined(MBEDTLS_SELF_TEST) /** * \brief The Poly1305 checkup routine. * * \return \c 0 on success. * \return \c 1 on failure. */ int mbedtls_poly1305_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST */ #ifdef __cplusplus } #endif #endif /* MBEDTLS_POLY1305_H */
5,692
152
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/hmac_drbg.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/hmac_drbg.h" #include "third_party/mbedtls/platform.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /* * HMAC_DRBG implementation (NIST SP 800-90) * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * The NIST SP 800-90A DRBGs are described in the following publication. * http://csrc.nist.gov/publications/nistpubs/800-90A/SP800-90A.pdf * References below are based on rev. 1 (January 2012). */ #if defined(MBEDTLS_HMAC_DRBG_C) /** * \brief HMAC_DRBG context initialization. * * This function makes the context ready for mbedtls_hmac_drbg_seed(), * mbedtls_hmac_drbg_seed_buf() or mbedtls_hmac_drbg_free(). * * \note The reseed interval is #MBEDTLS_HMAC_DRBG_RESEED_INTERVAL * by default. Override this value by calling * mbedtls_hmac_drbg_set_reseed_interval(). * * \param ctx HMAC_DRBG context to be initialized. */ void mbedtls_hmac_drbg_init( mbedtls_hmac_drbg_context *ctx ) { mbedtls_platform_zeroize( ctx, sizeof( mbedtls_hmac_drbg_context ) ); ctx->reseed_interval = MBEDTLS_HMAC_DRBG_RESEED_INTERVAL; } /** * \brief This function updates the state of the HMAC_DRBG context. * * \note This function is not thread-safe. It is not safe * to call this function if another thread might be * concurrently obtaining random numbers from the same * context or updating or reseeding the same context. * * \param ctx The HMAC_DRBG context. * \param additional The data to update the state with. * If this is \c NULL, there is no additional data. * \param add_len Length of \p additional in bytes. * Unused if \p additional is \c NULL. * * \return \c 0 on success, or an error from the underlying * hash calculation. */ int mbedtls_hmac_drbg_update_ret( mbedtls_hmac_drbg_context *ctx, const unsigned char *additional, size_t add_len ) { size_t md_len = mbedtls_md_get_size( ctx->md_ctx.md_info ); unsigned char rounds = ( additional != NULL && add_len != 0 ) ? 2 : 1; unsigned char sep[1]; unsigned char K[MBEDTLS_MD_MAX_SIZE]; int ret = MBEDTLS_ERR_MD_BAD_INPUT_DATA; for( sep[0] = 0; sep[0] < rounds; sep[0]++ ) { /* Step 1 or 4 */ if( ( ret = mbedtls_md_hmac_reset( &ctx->md_ctx ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx, ctx->V, md_len ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx, sep, 1 ) ) != 0 ) goto exit; if( rounds == 2 ) { if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx, additional, add_len ) ) != 0 ) goto exit; } if( ( ret = mbedtls_md_hmac_finish( &ctx->md_ctx, K ) ) != 0 ) goto exit; /* Step 2 or 5 */ if( ( ret = mbedtls_md_hmac_starts( &ctx->md_ctx, K, md_len ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx, ctx->V, md_len ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_hmac_finish( &ctx->md_ctx, ctx->V ) ) != 0 ) goto exit; } exit: mbedtls_platform_zeroize( K, sizeof( K ) ); return( ret ); } /** * \brief Initilisation of simpified HMAC_DRBG (never reseeds). * * This function is meant for use in algorithms that need a pseudorandom * input such as deterministic ECDSA. * * \param ctx HMAC_DRBG context to be initialised. * \param md_info MD algorithm to use for HMAC_DRBG. * \param data Concatenation of the initial entropy string and * the additional data. * \param data_len Length of \p data in bytes. * * \return \c 0 if successful. or * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info is * invalid. * \return #MBEDTLS_ERR_MD_ALLOC_FAILED if there was not enough * memory to allocate context data. */ int mbedtls_hmac_drbg_seed_buf( mbedtls_hmac_drbg_context *ctx, const mbedtls_md_info_t * md_info, const unsigned char *data, size_t data_len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; if( ( ret = mbedtls_md_setup( &ctx->md_ctx, md_info, 1 ) ) != 0 ) return( ret ); /* * Set initial working state. * Use the V memory location, which is currently all 0, to initialize the * MD context with an all-zero key. Then set V to its initial value. */ if( ( ret = mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V, mbedtls_md_get_size( md_info ) ) ) != 0 ) return( ret ); memset( ctx->V, 0x01, mbedtls_md_get_size( md_info ) ); if( ( ret = mbedtls_hmac_drbg_update_ret( ctx, data, data_len ) ) != 0 ) return( ret ); return( 0 ); } /* * Internal function used both for seeding and reseeding the DRBG. * Comments starting with arabic numbers refer to section 10.1.2.4 * of SP800-90A, while roman numbers refer to section 9.2. */ static int hmac_drbg_reseed_core( mbedtls_hmac_drbg_context *ctx, const unsigned char *additional, size_t len, int use_nonce ) { unsigned char seed[MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT]; size_t seedlen = 0; int ret = MBEDTLS_ERR_THIS_CORRUPTION; { size_t total_entropy_len; if( use_nonce == 0 ) total_entropy_len = ctx->entropy_len; else total_entropy_len = ctx->entropy_len * 3 / 2; /* III. Check input length */ if( len > MBEDTLS_HMAC_DRBG_MAX_INPUT || total_entropy_len + len > MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT ) { return( MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG ); } } mbedtls_platform_zeroize( seed, MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT ); /* IV. Gather entropy_len bytes of entropy for the seed */ if( ( ret = ctx->f_entropy( ctx->p_entropy, seed, ctx->entropy_len ) ) != 0 ) { return( MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED ); } seedlen += ctx->entropy_len; /* For initial seeding, allow adding of nonce generated * from the entropy source. See Sect 8.6.7 in SP800-90A. */ if( use_nonce ) { /* Note: We don't merge the two calls to f_entropy() in order * to avoid requesting too much entropy from f_entropy() * at once. Specifically, if the underlying digest is not * SHA-1, 3 / 2 * entropy_len is at least 36 Bytes, which * is larger than the maximum of 32 Bytes that our own * entropy source implementation can emit in a single * call in configurations disabling SHA-512. */ if( ( ret = ctx->f_entropy( ctx->p_entropy, seed + seedlen, ctx->entropy_len / 2 ) ) != 0 ) { return( MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED ); } seedlen += ctx->entropy_len / 2; } /* 1. Concatenate entropy and additional data if any */ if( additional != NULL && len != 0 ) { memcpy( seed + seedlen, additional, len ); seedlen += len; } /* 2. Update state */ if( ( ret = mbedtls_hmac_drbg_update_ret( ctx, seed, seedlen ) ) != 0 ) goto exit; /* 3. Reset reseed_counter */ ctx->reseed_counter = 1; exit: /* 4. Done */ mbedtls_platform_zeroize( seed, seedlen ); return( ret ); } /** * \brief This function reseeds the HMAC_DRBG context, that is * extracts data from the entropy source. * * \note This function is not thread-safe. It is not safe * to call this function if another thread might be * concurrently obtaining random numbers from the same * context or updating or reseeding the same context. * * \param ctx The HMAC_DRBG context. * \param additional Additional data to add to the state. * If this is \c NULL, there is no additional data * and \p len should be \c 0. * \param len The length of the additional data. * This must be at most #MBEDTLS_HMAC_DRBG_MAX_INPUT * and also at most * #MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT - \p entropy_len * where \p entropy_len is the entropy length * (see mbedtls_hmac_drbg_set_entropy_len()). * * \return \c 0 if successful. * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED * if a call to the entropy function failed. */ int mbedtls_hmac_drbg_reseed( mbedtls_hmac_drbg_context *ctx, const unsigned char *additional, size_t len ) { return( hmac_drbg_reseed_core( ctx, additional, len, 0 ) ); } /** * \brief HMAC_DRBG initial seeding. * * Set the initial seed and set up the entropy source for future reseeds. * * A typical choice for the \p f_entropy and \p p_entropy parameters is * to use the entropy module: * - \p f_entropy is mbedtls_entropy_func(); * - \p p_entropy is an instance of ::mbedtls_entropy_context initialized * with mbedtls_entropy_init() (which registers the platform's default * entropy sources). * * You can provide a personalization string in addition to the * entropy source, to make this instantiation as unique as possible. * * \note By default, the security strength as defined by NIST is: * - 128 bits if \p md_info is SHA-1; * - 192 bits if \p md_info is SHA-224; * - 256 bits if \p md_info is SHA-256, SHA-384 or SHA-512. * Note that SHA-256 is just as efficient as SHA-224. * The security strength can be reduced if a smaller * entropy length is set with * mbedtls_hmac_drbg_set_entropy_len(). * * \note The default entropy length is the security strength * (converted from bits to bytes). You can override * it by calling mbedtls_hmac_drbg_set_entropy_len(). * * \note During the initial seeding, this function calls * the entropy source to obtain a nonce * whose length is half the entropy length. * * \param ctx HMAC_DRBG context to be seeded. * \param md_info MD algorithm to use for HMAC_DRBG. * \param f_entropy The entropy callback, taking as arguments the * \p p_entropy context, the buffer to fill, and the * length of the buffer. * \p f_entropy is always called with a length that is * less than or equal to the entropy length. * \param p_entropy The entropy context to pass to \p f_entropy. * \param custom The personalization string. * This can be \c NULL, in which case the personalization * string is empty regardless of the value of \p len. * \param len The length of the personalization string. * This must be at most #MBEDTLS_HMAC_DRBG_MAX_INPUT * and also at most * #MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT - \p entropy_len * 3 / 2 * where \p entropy_len is the entropy length * described above. * * \return \c 0 if successful. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info is * invalid. * \return #MBEDTLS_ERR_MD_ALLOC_FAILED if there was not enough * memory to allocate context data. * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED * if the call to \p f_entropy failed. */ int mbedtls_hmac_drbg_seed( mbedtls_hmac_drbg_context *ctx, const mbedtls_md_info_t * md_info, int (*f_entropy)(void *, unsigned char *, size_t), void *p_entropy, const unsigned char *custom, size_t len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t md_size; if( ( ret = mbedtls_md_setup( &ctx->md_ctx, md_info, 1 ) ) != 0 ) return( ret ); md_size = mbedtls_md_get_size( md_info ); /* * Set initial working state. * Use the V memory location, which is currently all 0, to initialize the * MD context with an all-zero key. Then set V to its initial value. */ if( ( ret = mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V, md_size ) ) != 0 ) return( ret ); memset( ctx->V, 0x01, md_size ); ctx->f_entropy = f_entropy; ctx->p_entropy = p_entropy; if( ctx->entropy_len == 0 ) { /* * See SP800-57 5.6.1 (p. 65-66) for the security strength provided by * each hash function, then according to SP800-90A rev1 10.1 table 2, * min_entropy_len (in bits) is security_strength. * * (This also matches the sizes used in the NIST test vectors.) */ ctx->entropy_len = md_size <= 20 ? 16 : /* 160-bits hash -> 128 bits */ md_size <= 28 ? 24 : /* 224-bits hash -> 192 bits */ 32; /* better (256+) -> 256 bits */ } if( ( ret = hmac_drbg_reseed_core( ctx, custom, len, 1 /* add nonce */ ) ) != 0 ) { return( ret ); } return( 0 ); } /** * \brief This function turns prediction resistance on or off. * The default value is off. * * \note If enabled, entropy is gathered at the beginning of * every call to mbedtls_hmac_drbg_random_with_add() * or mbedtls_hmac_drbg_random(). * Only use this if your entropy source has sufficient * throughput. * * \param ctx The HMAC_DRBG context. * \param resistance #MBEDTLS_HMAC_DRBG_PR_ON or #MBEDTLS_HMAC_DRBG_PR_OFF. */ void mbedtls_hmac_drbg_set_prediction_resistance( mbedtls_hmac_drbg_context *ctx, int resistance ) { ctx->prediction_resistance = resistance; } /** * \brief This function sets the amount of entropy grabbed on each * seed or reseed. * * See the documentation of mbedtls_hmac_drbg_seed() for the default value. * * \param ctx The HMAC_DRBG context. * \param len The amount of entropy to grab, in bytes. */ void mbedtls_hmac_drbg_set_entropy_len( mbedtls_hmac_drbg_context *ctx, size_t len ) { ctx->entropy_len = len; } /** * \brief Set the reseed interval. * * The reseed interval is the number of calls to mbedtls_hmac_drbg_random() * or mbedtls_hmac_drbg_random_with_add() after which the entropy function * is called again. * * The default value is #MBEDTLS_HMAC_DRBG_RESEED_INTERVAL. * * \param ctx The HMAC_DRBG context. * \param interval The reseed interval. */ void mbedtls_hmac_drbg_set_reseed_interval( mbedtls_hmac_drbg_context *ctx, int interval ) { ctx->reseed_interval = interval; } /** * \brief This function updates an HMAC_DRBG instance with additional * data and uses it to generate random data. * * This function automatically reseeds if the reseed counter is exceeded * or prediction resistance is enabled. * * \note This function is not thread-safe. It is not safe * to call this function if another thread might be * concurrently obtaining random numbers from the same * context or updating or reseeding the same context. * * \param p_rng The HMAC_DRBG context. This must be a pointer to a * #mbedtls_hmac_drbg_context structure. * \param output The buffer to fill. * \param output_len The length of the buffer in bytes. * This must be at most #MBEDTLS_HMAC_DRBG_MAX_REQUEST. * \param additional Additional data to update with. * If this is \c NULL, there is no additional data * and \p add_len should be \c 0. * \param add_len The length of the additional data. * This must be at most #MBEDTLS_HMAC_DRBG_MAX_INPUT. * * \return \c 0 if successful. * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED * if a call to the entropy source failed. * \return #MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG if * \p output_len > #MBEDTLS_HMAC_DRBG_MAX_REQUEST. * \return #MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG if * \p add_len > #MBEDTLS_HMAC_DRBG_MAX_INPUT. */ int mbedtls_hmac_drbg_random_with_add( void *p_rng, unsigned char *output, size_t out_len, const unsigned char *additional, size_t add_len ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; mbedtls_hmac_drbg_context *ctx = (mbedtls_hmac_drbg_context *) p_rng; size_t md_len = mbedtls_md_get_size( ctx->md_ctx.md_info ); size_t left = out_len; unsigned char *out = output; /* II. Check request length */ if( out_len > MBEDTLS_HMAC_DRBG_MAX_REQUEST ) return( MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG ); /* III. Check input length */ if( add_len > MBEDTLS_HMAC_DRBG_MAX_INPUT ) return( MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG ); /* 1. (aka VII and IX) Check reseed counter and PR */ if( ctx->f_entropy != NULL && /* For no-reseeding instances */ ( ctx->prediction_resistance == MBEDTLS_HMAC_DRBG_PR_ON || ctx->reseed_counter > ctx->reseed_interval ) ) { if( ( ret = mbedtls_hmac_drbg_reseed( ctx, additional, add_len ) ) != 0 ) return( ret ); add_len = 0; /* VII.4 */ } /* 2. Use additional data if any */ if( additional != NULL && add_len != 0 ) { if( ( ret = mbedtls_hmac_drbg_update_ret( ctx, additional, add_len ) ) != 0 ) goto exit; } /* 3, 4, 5. Generate bytes */ while( left != 0 ) { size_t use_len = left > md_len ? md_len : left; if( ( ret = mbedtls_md_hmac_reset( &ctx->md_ctx ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx, ctx->V, md_len ) ) != 0 ) goto exit; if( ( ret = mbedtls_md_hmac_finish( &ctx->md_ctx, ctx->V ) ) != 0 ) goto exit; memcpy( out, ctx->V, use_len ); out += use_len; left -= use_len; } /* 6. Update */ if( ( ret = mbedtls_hmac_drbg_update_ret( ctx, additional, add_len ) ) != 0 ) goto exit; /* 7. Update reseed counter */ ctx->reseed_counter++; exit: /* 8. Done */ return( ret ); } /** * \brief This function uses HMAC_DRBG to generate random data. * * This function automatically reseeds if the reseed counter is exceeded * or prediction resistance is enabled. * * \param p_rng The HMAC_DRBG context. This must be a pointer to a * #mbedtls_hmac_drbg_context structure. * \param output The buffer to fill. * \param out_len The length of the buffer in bytes. * This must be at most #MBEDTLS_HMAC_DRBG_MAX_REQUEST. * * \return \c 0 if successful. * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED * if a call to the entropy source failed. * \return #MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG if * \p out_len > #MBEDTLS_HMAC_DRBG_MAX_REQUEST. */ int mbedtls_hmac_drbg_random( void *p_rng, unsigned char *output, size_t out_len ) { mbedtls_hmac_drbg_context *ctx = (mbedtls_hmac_drbg_context *) p_rng; return mbedtls_hmac_drbg_random_with_add( ctx, output, out_len, NULL, 0 ); } /** * \brief This function resets HMAC_DRBG context to the state immediately * after initial call of mbedtls_hmac_drbg_init(). * * \param ctx The HMAC_DRBG context to free. */ void mbedtls_hmac_drbg_free( mbedtls_hmac_drbg_context *ctx ) { if( ctx == NULL ) return; mbedtls_md_free( &ctx->md_ctx ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_hmac_drbg_context ) ); ctx->reseed_interval = MBEDTLS_HMAC_DRBG_RESEED_INTERVAL; } #if defined(MBEDTLS_FS_IO) /** * \brief This function writes a seed file. * * \param ctx The HMAC_DRBG context. * \param path The name of the file. * * \return \c 0 on success. * \return #MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR on file error. * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED on reseed * failure. */ int mbedtls_hmac_drbg_write_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; FILE *f; unsigned char buf[ MBEDTLS_HMAC_DRBG_MAX_INPUT ]; if( ( f = fopen( path, "wb" ) ) == NULL ) return( MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR ); if( ( ret = mbedtls_hmac_drbg_random( ctx, buf, sizeof( buf ) ) ) != 0 ) goto exit; if( fwrite( buf, 1, sizeof( buf ), f ) != sizeof( buf ) ) { ret = MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR; goto exit; } ret = 0; exit: fclose( f ); mbedtls_platform_zeroize( buf, sizeof( buf ) ); return( ret ); } /** * \brief This function reads and updates a seed file. The seed * is added to this instance. * * \param ctx The HMAC_DRBG context. * \param path The name of the file. * * \return \c 0 on success. * \return #MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR on file error. * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED on * reseed failure. * \return #MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG if the existing * seed file is too large. */ int mbedtls_hmac_drbg_update_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path ) { int ret = 0; FILE *f = NULL; size_t n; unsigned char buf[ MBEDTLS_HMAC_DRBG_MAX_INPUT ]; unsigned char c; if( ( f = fopen( path, "rb" ) ) == NULL ) return( MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR ); n = fread( buf, 1, sizeof( buf ), f ); if( fread( &c, 1, 1, f ) != 0 ) { ret = MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG; goto exit; } if( n == 0 || ferror( f ) ) { ret = MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR; goto exit; } fclose( f ); f = NULL; ret = mbedtls_hmac_drbg_update_ret( ctx, buf, n ); exit: mbedtls_platform_zeroize( buf, sizeof( buf ) ); if( f != NULL ) fclose( f ); if( ret != 0 ) return( ret ); return( mbedtls_hmac_drbg_write_seed_file( ctx, path ) ); } #endif /* MBEDTLS_FS_IO */ #if defined(MBEDTLS_SELF_TEST) #if defined(MBEDTLS_SHA1_C) #define OUTPUT_LEN 80 /* From a NIST PR=true test vector */ static const unsigned char entropy_pr[] = { 0xa0, 0xc9, 0xab, 0x58, 0xf1, 0xe2, 0xe5, 0xa4, 0xde, 0x3e, 0xbd, 0x4f, 0xf7, 0x3e, 0x9c, 0x5b, 0x64, 0xef, 0xd8, 0xca, 0x02, 0x8c, 0xf8, 0x11, 0x48, 0xa5, 0x84, 0xfe, 0x69, 0xab, 0x5a, 0xee, 0x42, 0xaa, 0x4d, 0x42, 0x17, 0x60, 0x99, 0xd4, 0x5e, 0x13, 0x97, 0xdc, 0x40, 0x4d, 0x86, 0xa3, 0x7b, 0xf5, 0x59, 0x54, 0x75, 0x69, 0x51, 0xe4 }; static const unsigned char result_pr[OUTPUT_LEN] = { 0x9a, 0x00, 0xa2, 0xd0, 0x0e, 0xd5, 0x9b, 0xfe, 0x31, 0xec, 0xb1, 0x39, 0x9b, 0x60, 0x81, 0x48, 0xd1, 0x96, 0x9d, 0x25, 0x0d, 0x3c, 0x1e, 0x94, 0x10, 0x10, 0x98, 0x12, 0x93, 0x25, 0xca, 0xb8, 0xfc, 0xcc, 0x2d, 0x54, 0x73, 0x19, 0x70, 0xc0, 0x10, 0x7a, 0xa4, 0x89, 0x25, 0x19, 0x95, 0x5e, 0x4b, 0xc6, 0x00, 0x1d, 0x7f, 0x4e, 0x6a, 0x2b, 0xf8, 0xa3, 0x01, 0xab, 0x46, 0x05, 0x5c, 0x09, 0xa6, 0x71, 0x88, 0xf1, 0xa7, 0x40, 0xee, 0xf3, 0xe1, 0x5c, 0x02, 0x9b, 0x44, 0xaf, 0x03, 0x44 }; /* From a NIST PR=false test vector */ static const unsigned char entropy_nopr[] = { 0x79, 0x34, 0x9b, 0xbf, 0x7c, 0xdd, 0xa5, 0x79, 0x95, 0x57, 0x86, 0x66, 0x21, 0xc9, 0x13, 0x83, 0x11, 0x46, 0x73, 0x3a, 0xbf, 0x8c, 0x35, 0xc8, 0xc7, 0x21, 0x5b, 0x5b, 0x96, 0xc4, 0x8e, 0x9b, 0x33, 0x8c, 0x74, 0xe3, 0xe9, 0x9d, 0xfe, 0xdf }; static const unsigned char result_nopr[OUTPUT_LEN] = { 0xc6, 0xa1, 0x6a, 0xb8, 0xd4, 0x20, 0x70, 0x6f, 0x0f, 0x34, 0xab, 0x7f, 0xec, 0x5a, 0xdc, 0xa9, 0xd8, 0xca, 0x3a, 0x13, 0x3e, 0x15, 0x9c, 0xa6, 0xac, 0x43, 0xc6, 0xf8, 0xa2, 0xbe, 0x22, 0x83, 0x4a, 0x4c, 0x0a, 0x0a, 0xff, 0xb1, 0x0d, 0x71, 0x94, 0xf1, 0xc1, 0xa5, 0xcf, 0x73, 0x22, 0xec, 0x1a, 0xe0, 0x96, 0x4e, 0xd4, 0xbf, 0x12, 0x27, 0x46, 0xe0, 0x87, 0xfd, 0xb5, 0xb3, 0xe9, 0x1b, 0x34, 0x93, 0xd5, 0xbb, 0x98, 0xfa, 0xed, 0x49, 0xe8, 0x5f, 0x13, 0x0f, 0xc8, 0xa4, 0x59, 0xb7 }; /* "Entropy" from buffer */ static size_t test_offset; static int hmac_drbg_self_test_entropy( void *data, unsigned char *buf, size_t len ) { const unsigned char *p = data; memcpy( buf, p + test_offset, len ); test_offset += len; return( 0 ); } #define CHK( c ) if( (c) != 0 ) \ { \ if( verbose != 0 ) \ mbedtls_printf( "failed\n" ); \ return( 1 ); \ } /** * \brief The HMAC_DRBG Checkup routine. * * \return \c 0 if successful. * \return \c 1 if the test failed. */ int mbedtls_hmac_drbg_self_test( int verbose ) { mbedtls_hmac_drbg_context ctx; unsigned char buf[OUTPUT_LEN]; const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ); mbedtls_hmac_drbg_init( &ctx ); /* * PR = True */ if( verbose != 0 ) mbedtls_printf( " HMAC_DRBG (PR = True) : " ); test_offset = 0; CHK( mbedtls_hmac_drbg_seed( &ctx, md_info, hmac_drbg_self_test_entropy, (void *) entropy_pr, NULL, 0 ) ); mbedtls_hmac_drbg_set_prediction_resistance( &ctx, MBEDTLS_HMAC_DRBG_PR_ON ); CHK( mbedtls_hmac_drbg_random( &ctx, buf, OUTPUT_LEN ) ); CHK( mbedtls_hmac_drbg_random( &ctx, buf, OUTPUT_LEN ) ); CHK( timingsafe_bcmp( buf, result_pr, OUTPUT_LEN ) ); mbedtls_hmac_drbg_free( &ctx ); mbedtls_hmac_drbg_free( &ctx ); if( verbose != 0 ) mbedtls_printf( "passed\n" ); /* * PR = False */ if( verbose != 0 ) mbedtls_printf( " HMAC_DRBG (PR = False) : " ); mbedtls_hmac_drbg_init( &ctx ); test_offset = 0; CHK( mbedtls_hmac_drbg_seed( &ctx, md_info, hmac_drbg_self_test_entropy, (void *) entropy_nopr, NULL, 0 ) ); CHK( mbedtls_hmac_drbg_reseed( &ctx, NULL, 0 ) ); CHK( mbedtls_hmac_drbg_random( &ctx, buf, OUTPUT_LEN ) ); CHK( mbedtls_hmac_drbg_random( &ctx, buf, OUTPUT_LEN ) ); CHK( timingsafe_bcmp( buf, result_nopr, OUTPUT_LEN ) ); mbedtls_hmac_drbg_free( &ctx ); mbedtls_hmac_drbg_free( &ctx ); if( verbose != 0 ) mbedtls_printf( "passed\n" ); if( verbose != 0 ) mbedtls_printf( "\n" ); return( 0 ); } #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_HMAC_DRBG_C */
31,294
802
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/cipher.h
#ifndef MBEDTLS_CIPHER_H #define MBEDTLS_CIPHER_H #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/platform.h" /* clang-format off */ #define MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE -0x6080 /*< The selected feature is not available. */ #define MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA -0x6100 /*< Bad input parameters. */ #define MBEDTLS_ERR_CIPHER_ALLOC_FAILED -0x6180 /*< Failed to allocate memory. */ #define MBEDTLS_ERR_CIPHER_INVALID_PADDING -0x6200 /*< Input data contains invalid padding and is rejected. */ #define MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED -0x6280 /*< Decryption of block requires a full block. */ #define MBEDTLS_ERR_CIPHER_AUTH_FAILED -0x6300 /*< Authentication failed (for AEAD modes). */ #define MBEDTLS_ERR_CIPHER_INVALID_CONTEXT -0x6380 /*< The context is invalid. For example, because it was freed. */ /* MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED -0x6400 /*< Cipher hardware accelerator failed. */ #define MBEDTLS_CIPHER_VARIABLE_IV_LEN 0x01 /*< Cipher accepts IVs of variable length. */ #define MBEDTLS_CIPHER_VARIABLE_KEY_LEN 0x02 /*< Cipher accepts keys of variable length. */ #ifdef __cplusplus extern "C" { #endif /** * \brief Supported cipher types. * * \warning RC4 and DES are considered weak ciphers and their use * constitutes a security risk. Arm recommends considering stronger * ciphers instead. */ typedef enum { MBEDTLS_CIPHER_ID_NONE = 0, /*< Placeholder to mark the end of cipher ID lists. */ MBEDTLS_CIPHER_ID_NULL, /*< The identity cipher, treated as a stream cipher. */ MBEDTLS_CIPHER_ID_AES, /*< The AES cipher. */ MBEDTLS_CIPHER_ID_DES, /*< The DES cipher. */ MBEDTLS_CIPHER_ID_3DES, /*< The Triple DES cipher. */ MBEDTLS_CIPHER_ID_CAMELLIA, /*< The Camellia cipher. */ MBEDTLS_CIPHER_ID_BLOWFISH, /*< The Blowfish cipher. */ MBEDTLS_CIPHER_ID_ARC4, /*< The RC4 cipher. */ MBEDTLS_CIPHER_ID_ARIA, /*< The Aria cipher. */ MBEDTLS_CIPHER_ID_CHACHA20, /*< The ChaCha20 cipher. */ } mbedtls_cipher_id_t; /** * \brief Supported {cipher type, cipher mode} pairs. * * \warning RC4 and DES are considered weak ciphers and their use * constitutes a security risk. Arm recommends considering stronger * ciphers instead. */ typedef enum { MBEDTLS_CIPHER_NONE = 0, /*< Placeholder to mark the end of cipher-pair lists. */ MBEDTLS_CIPHER_NULL, /*< The identity stream cipher. */ MBEDTLS_CIPHER_AES_128_ECB, /*< AES cipher with 128-bit ECB mode. */ MBEDTLS_CIPHER_AES_192_ECB, /*< AES cipher with 192-bit ECB mode. */ MBEDTLS_CIPHER_AES_256_ECB, /*< AES cipher with 256-bit ECB mode. */ MBEDTLS_CIPHER_AES_128_CBC, /*< AES cipher with 128-bit CBC mode. */ MBEDTLS_CIPHER_AES_192_CBC, /*< AES cipher with 192-bit CBC mode. */ MBEDTLS_CIPHER_AES_256_CBC, /*< AES cipher with 256-bit CBC mode. */ MBEDTLS_CIPHER_AES_128_CFB128, /*< AES cipher with 128-bit CFB128 mode. */ MBEDTLS_CIPHER_AES_192_CFB128, /*< AES cipher with 192-bit CFB128 mode. */ MBEDTLS_CIPHER_AES_256_CFB128, /*< AES cipher with 256-bit CFB128 mode. */ MBEDTLS_CIPHER_AES_128_CTR, /*< AES cipher with 128-bit CTR mode. */ MBEDTLS_CIPHER_AES_192_CTR, /*< AES cipher with 192-bit CTR mode. */ MBEDTLS_CIPHER_AES_256_CTR, /*< AES cipher with 256-bit CTR mode. */ MBEDTLS_CIPHER_AES_128_GCM, /*< AES cipher with 128-bit GCM mode. */ MBEDTLS_CIPHER_AES_192_GCM, /*< AES cipher with 192-bit GCM mode. */ MBEDTLS_CIPHER_AES_256_GCM, /*< AES cipher with 256-bit GCM mode. */ MBEDTLS_CIPHER_CAMELLIA_128_ECB, /*< Camellia cipher with 128-bit ECB mode. */ MBEDTLS_CIPHER_CAMELLIA_192_ECB, /*< Camellia cipher with 192-bit ECB mode. */ MBEDTLS_CIPHER_CAMELLIA_256_ECB, /*< Camellia cipher with 256-bit ECB mode. */ MBEDTLS_CIPHER_CAMELLIA_128_CBC, /*< Camellia cipher with 128-bit CBC mode. */ MBEDTLS_CIPHER_CAMELLIA_192_CBC, /*< Camellia cipher with 192-bit CBC mode. */ MBEDTLS_CIPHER_CAMELLIA_256_CBC, /*< Camellia cipher with 256-bit CBC mode. */ MBEDTLS_CIPHER_CAMELLIA_128_CFB128, /*< Camellia cipher with 128-bit CFB128 mode. */ MBEDTLS_CIPHER_CAMELLIA_192_CFB128, /*< Camellia cipher with 192-bit CFB128 mode. */ MBEDTLS_CIPHER_CAMELLIA_256_CFB128, /*< Camellia cipher with 256-bit CFB128 mode. */ MBEDTLS_CIPHER_CAMELLIA_128_CTR, /*< Camellia cipher with 128-bit CTR mode. */ MBEDTLS_CIPHER_CAMELLIA_192_CTR, /*< Camellia cipher with 192-bit CTR mode. */ MBEDTLS_CIPHER_CAMELLIA_256_CTR, /*< Camellia cipher with 256-bit CTR mode. */ MBEDTLS_CIPHER_CAMELLIA_128_GCM, /*< Camellia cipher with 128-bit GCM mode. */ MBEDTLS_CIPHER_CAMELLIA_192_GCM, /*< Camellia cipher with 192-bit GCM mode. */ MBEDTLS_CIPHER_CAMELLIA_256_GCM, /*< Camellia cipher with 256-bit GCM mode. */ MBEDTLS_CIPHER_DES_ECB, /*< DES cipher with ECB mode. */ MBEDTLS_CIPHER_DES_CBC, /*< DES cipher with CBC mode. */ MBEDTLS_CIPHER_DES_EDE_ECB, /*< DES cipher with EDE ECB mode. */ MBEDTLS_CIPHER_DES_EDE_CBC, /*< DES cipher with EDE CBC mode. */ MBEDTLS_CIPHER_DES_EDE3_ECB, /*< DES cipher with EDE3 ECB mode. */ MBEDTLS_CIPHER_DES_EDE3_CBC, /*< DES cipher with EDE3 CBC mode. */ MBEDTLS_CIPHER_BLOWFISH_ECB, /*< Blowfish cipher with ECB mode. */ MBEDTLS_CIPHER_BLOWFISH_CBC, /*< Blowfish cipher with CBC mode. */ MBEDTLS_CIPHER_BLOWFISH_CFB64, /*< Blowfish cipher with CFB64 mode. */ MBEDTLS_CIPHER_BLOWFISH_CTR, /*< Blowfish cipher with CTR mode. */ MBEDTLS_CIPHER_ARC4_128, /*< RC4 cipher with 128-bit mode. */ MBEDTLS_CIPHER_AES_128_CCM, /*< AES cipher with 128-bit CCM mode. */ MBEDTLS_CIPHER_AES_192_CCM, /*< AES cipher with 192-bit CCM mode. */ MBEDTLS_CIPHER_AES_256_CCM, /*< AES cipher with 256-bit CCM mode. */ MBEDTLS_CIPHER_CAMELLIA_128_CCM, /*< Camellia cipher with 128-bit CCM mode. */ MBEDTLS_CIPHER_CAMELLIA_192_CCM, /*< Camellia cipher with 192-bit CCM mode. */ MBEDTLS_CIPHER_CAMELLIA_256_CCM, /*< Camellia cipher with 256-bit CCM mode. */ MBEDTLS_CIPHER_ARIA_128_ECB, /*< Aria cipher with 128-bit key and ECB mode. */ MBEDTLS_CIPHER_ARIA_192_ECB, /*< Aria cipher with 192-bit key and ECB mode. */ MBEDTLS_CIPHER_ARIA_256_ECB, /*< Aria cipher with 256-bit key and ECB mode. */ MBEDTLS_CIPHER_ARIA_128_CBC, /*< Aria cipher with 128-bit key and CBC mode. */ MBEDTLS_CIPHER_ARIA_192_CBC, /*< Aria cipher with 192-bit key and CBC mode. */ MBEDTLS_CIPHER_ARIA_256_CBC, /*< Aria cipher with 256-bit key and CBC mode. */ MBEDTLS_CIPHER_ARIA_128_CFB128, /*< Aria cipher with 128-bit key and CFB-128 mode. */ MBEDTLS_CIPHER_ARIA_192_CFB128, /*< Aria cipher with 192-bit key and CFB-128 mode. */ MBEDTLS_CIPHER_ARIA_256_CFB128, /*< Aria cipher with 256-bit key and CFB-128 mode. */ MBEDTLS_CIPHER_ARIA_128_CTR, /*< Aria cipher with 128-bit key and CTR mode. */ MBEDTLS_CIPHER_ARIA_192_CTR, /*< Aria cipher with 192-bit key and CTR mode. */ MBEDTLS_CIPHER_ARIA_256_CTR, /*< Aria cipher with 256-bit key and CTR mode. */ MBEDTLS_CIPHER_ARIA_128_GCM, /*< Aria cipher with 128-bit key and GCM mode. */ MBEDTLS_CIPHER_ARIA_192_GCM, /*< Aria cipher with 192-bit key and GCM mode. */ MBEDTLS_CIPHER_ARIA_256_GCM, /*< Aria cipher with 256-bit key and GCM mode. */ MBEDTLS_CIPHER_ARIA_128_CCM, /*< Aria cipher with 128-bit key and CCM mode. */ MBEDTLS_CIPHER_ARIA_192_CCM, /*< Aria cipher with 192-bit key and CCM mode. */ MBEDTLS_CIPHER_ARIA_256_CCM, /*< Aria cipher with 256-bit key and CCM mode. */ MBEDTLS_CIPHER_AES_128_OFB, /*< AES 128-bit cipher in OFB mode. */ MBEDTLS_CIPHER_AES_192_OFB, /*< AES 192-bit cipher in OFB mode. */ MBEDTLS_CIPHER_AES_256_OFB, /*< AES 256-bit cipher in OFB mode. */ MBEDTLS_CIPHER_AES_128_XTS, /*< AES 128-bit cipher in XTS block mode. */ MBEDTLS_CIPHER_AES_256_XTS, /*< AES 256-bit cipher in XTS block mode. */ MBEDTLS_CIPHER_CHACHA20, /*< ChaCha20 stream cipher. */ MBEDTLS_CIPHER_CHACHA20_POLY1305, /*< ChaCha20-Poly1305 AEAD cipher. */ MBEDTLS_CIPHER_AES_128_KW, /*< AES cipher with 128-bit NIST KW mode. */ MBEDTLS_CIPHER_AES_192_KW, /*< AES cipher with 192-bit NIST KW mode. */ MBEDTLS_CIPHER_AES_256_KW, /*< AES cipher with 256-bit NIST KW mode. */ MBEDTLS_CIPHER_AES_128_KWP, /*< AES cipher with 128-bit NIST KWP mode. */ MBEDTLS_CIPHER_AES_192_KWP, /*< AES cipher with 192-bit NIST KWP mode. */ MBEDTLS_CIPHER_AES_256_KWP, /*< AES cipher with 256-bit NIST KWP mode. */ } mbedtls_cipher_type_t; /** Supported cipher modes. */ typedef enum { MBEDTLS_MODE_NONE = 0, /*< None. */ MBEDTLS_MODE_ECB, /*< The ECB cipher mode. */ MBEDTLS_MODE_CBC, /*< The CBC cipher mode. */ MBEDTLS_MODE_CFB, /*< The CFB cipher mode. */ MBEDTLS_MODE_OFB, /*< The OFB cipher mode. */ MBEDTLS_MODE_CTR, /*< The CTR cipher mode. */ MBEDTLS_MODE_GCM, /*< The GCM cipher mode. */ MBEDTLS_MODE_STREAM, /*< The stream cipher mode. */ MBEDTLS_MODE_CCM, /*< The CCM cipher mode. */ MBEDTLS_MODE_XTS, /*< The XTS cipher mode. */ MBEDTLS_MODE_CHACHAPOLY, /*< The ChaCha-Poly cipher mode. */ MBEDTLS_MODE_KW, /*< The SP800-38F KW mode */ MBEDTLS_MODE_KWP, /*< The SP800-38F KWP mode */ } mbedtls_cipher_mode_t; /** Supported cipher padding types. */ typedef enum { MBEDTLS_PADDING_PKCS7 = 0, /*< PKCS7 padding (default). */ MBEDTLS_PADDING_ONE_AND_ZEROS, /*< ISO/IEC 7816-4 padding. */ MBEDTLS_PADDING_ZEROS_AND_LEN, /*< ANSI X.923 padding. */ MBEDTLS_PADDING_ZEROS, /*< Zero padding (not reversible). */ MBEDTLS_PADDING_NONE, /*< Never pad (full blocks only). */ } mbedtls_cipher_padding_t; /** Type of operation. */ typedef enum { MBEDTLS_OPERATION_NONE = -1, MBEDTLS_DECRYPT = 0, MBEDTLS_ENCRYPT, } mbedtls_operation_t; enum { /** Undefined key length. */ MBEDTLS_KEY_LENGTH_NONE = 0, /** Key length, in bits (including parity), for DES keys. */ MBEDTLS_KEY_LENGTH_DES = 64, /** Key length in bits, including parity, for DES in two-key EDE. */ MBEDTLS_KEY_LENGTH_DES_EDE = 128, /** Key length in bits, including parity, for DES in three-key EDE. */ MBEDTLS_KEY_LENGTH_DES_EDE3 = 192, }; /** Maximum length of any IV, in Bytes. */ /* This should ideally be derived automatically from list of ciphers. * This should be kept in sync with MBEDTLS_SSL_MAX_IV_LENGTH defined * in ssl_internal.h. */ #define MBEDTLS_MAX_IV_LENGTH 16 /** Maximum block size of any cipher, in Bytes. */ /* This should ideally be derived automatically from list of ciphers. * This should be kept in sync with MBEDTLS_SSL_MAX_BLOCK_LENGTH defined * in ssl_internal.h. */ #define MBEDTLS_MAX_BLOCK_LENGTH 16 /** Maximum key length, in Bytes. */ /* This should ideally be derived automatically from list of ciphers. * For now, only check whether XTS is enabled which uses 64 Byte keys, * and use 32 Bytes as an upper bound for the maximum key length otherwise. * This should be kept in sync with MBEDTLS_SSL_MAX_BLOCK_LENGTH defined * in ssl_internal.h, which however deliberately ignores the case of XTS * since the latter isn't used in SSL/TLS. */ #if defined(MBEDTLS_CIPHER_MODE_XTS) #define MBEDTLS_MAX_KEY_LENGTH 64 #else #define MBEDTLS_MAX_KEY_LENGTH 32 #endif /* MBEDTLS_CIPHER_MODE_XTS */ /** * Base cipher information (opaque struct). */ typedef struct mbedtls_cipher_base_t mbedtls_cipher_base_t; /** * CMAC context (opaque struct). */ typedef struct mbedtls_cmac_context_t mbedtls_cmac_context_t; /** * Cipher information. Allows calling cipher functions * in a generic way. */ typedef struct mbedtls_cipher_info_t { /** Full cipher identifier. For example, * MBEDTLS_CIPHER_AES_256_CBC. */ mbedtls_cipher_type_t type; /** The cipher mode. For example, MBEDTLS_MODE_CBC. */ mbedtls_cipher_mode_t mode; /** The cipher key length, in bits. This is the * default length for variable sized ciphers. * Includes parity bits for ciphers like DES. */ unsigned int key_bitlen; /** Name of the cipher. */ const char * name; /** IV or nonce size, in Bytes. * For ciphers that accept variable IV sizes, * this is the recommended size. */ unsigned int iv_size; /** Bitflag comprised of MBEDTLS_CIPHER_VARIABLE_IV_LEN and * MBEDTLS_CIPHER_VARIABLE_KEY_LEN indicating whether the * cipher supports variable IV or variable key sizes, respectively. */ int flags; /** The block size, in Bytes. */ unsigned int block_size; /** Struct for base cipher information and functions. */ const mbedtls_cipher_base_t *base; } mbedtls_cipher_info_t; /** * Generic cipher context. */ typedef struct mbedtls_cipher_context_t { /** Information about the associated cipher. */ const mbedtls_cipher_info_t *cipher_info; /** Key length to use. */ int key_bitlen; /** Operation that the key of the context has been * initialized for. */ mbedtls_operation_t operation; #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING) /** Padding functions to use, if relevant for * the specific cipher mode. */ void (*add_padding)( unsigned char *output, size_t olen, size_t data_len ); int (*get_padding)( unsigned char *input, size_t ilen, size_t *data_len ); #endif /** Buffer for input that has not been processed yet. */ unsigned char unprocessed_data[MBEDTLS_MAX_BLOCK_LENGTH]; /** Number of Bytes that have not been processed yet. */ size_t unprocessed_len; /** Current IV or NONCE_COUNTER for CTR-mode, data unit (or sector) number * for XTS-mode. */ unsigned char iv[MBEDTLS_MAX_IV_LENGTH]; /** IV size in Bytes, for ciphers with variable-length IVs. */ size_t iv_size; /** The cipher-specific context. */ void *cipher_ctx; #if defined(MBEDTLS_CMAC_C) /** CMAC-specific context. */ mbedtls_cmac_context_t *cmac_ctx; #endif } mbedtls_cipher_context_t; /** * \brief This function retrieves the list of ciphers supported * by the generic cipher module. * * For any cipher identifier in the returned list, you can * obtain the corresponding generic cipher information structure * via mbedtls_cipher_info_from_type(), which can then be used * to prepare a cipher context via mbedtls_cipher_setup(). * * * \return A statically-allocated array of cipher identifiers * of type cipher_type_t. The last entry is zero. */ const int *mbedtls_cipher_list( void ); /** * \brief This function retrieves the cipher-information * structure associated with the given cipher name. * * \param cipher_name Name of the cipher to search for. This must not be * \c NULL. * * \return The cipher information structure associated with the * given \p cipher_name. * \return \c NULL if the associated cipher information is not found. */ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_string( const char *cipher_name ); /** * \brief This function retrieves the cipher-information * structure associated with the given cipher type. * * \param cipher_type Type of the cipher to search for. * * \return The cipher information structure associated with the * given \p cipher_type. * \return \c NULL if the associated cipher information is not found. */ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_type( const mbedtls_cipher_type_t cipher_type ); /** * \brief This function retrieves the cipher-information * structure associated with the given cipher ID, * key size and mode. * * \param cipher_id The ID of the cipher to search for. For example, * #MBEDTLS_CIPHER_ID_AES. * \param key_bitlen The length of the key in bits. * \param mode The cipher mode. For example, #MBEDTLS_MODE_CBC. * * \return The cipher information structure associated with the * given \p cipher_id. * \return \c NULL if the associated cipher information is not found. */ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_values( const mbedtls_cipher_id_t cipher_id, int key_bitlen, const mbedtls_cipher_mode_t mode ); /** * \brief This function initializes a \p cipher_context as NONE. * * \param ctx The context to be initialized. This must not be \c NULL. */ void mbedtls_cipher_init( mbedtls_cipher_context_t *ctx ); /** * \brief This function frees and clears the cipher-specific * context of \p ctx. Freeing \p ctx itself remains the * responsibility of the caller. * * \param ctx The context to be freed. If this is \c NULL, the * function has no effect, otherwise this must point to an * initialized context. */ void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx ); /** * \brief This function initializes a cipher context for * use with the given cipher primitive. * * \param ctx The context to initialize. This must be initialized. * \param cipher_info The cipher to use. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on * parameter-verification failure. * \return #MBEDTLS_ERR_CIPHER_ALLOC_FAILED if allocation of the * cipher-specific context fails. * * \internal Currently, the function also clears the structure. * In future versions, the caller will be required to call * mbedtls_cipher_init() on the structure first. */ int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_info_t *cipher_info ); /** * \brief This function returns the block size of the given cipher. * * \param ctx The context of the cipher. This must be initialized. * * \return The block size of the underlying cipher. * \return \c 0 if \p ctx has not been initialized. */ static inline unsigned int mbedtls_cipher_get_block_size( const mbedtls_cipher_context_t *ctx ) { MBEDTLS_INTERNAL_VALIDATE_RET( ctx != NULL, 0 ); if( ctx->cipher_info == NULL ) return 0; return ctx->cipher_info->block_size; } /** * \brief This function returns the mode of operation for * the cipher. For example, MBEDTLS_MODE_CBC. * * \param ctx The context of the cipher. This must be initialized. * * \return The mode of operation. * \return #MBEDTLS_MODE_NONE if \p ctx has not been initialized. */ static inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode( const mbedtls_cipher_context_t *ctx ) { MBEDTLS_INTERNAL_VALIDATE_RET( ctx != NULL, MBEDTLS_MODE_NONE ); if( ctx->cipher_info == NULL ) return MBEDTLS_MODE_NONE; return ctx->cipher_info->mode; } /** * \brief This function returns the size of the IV or nonce * of the cipher, in Bytes. * * \param ctx The context of the cipher. This must be initialized. * * \return The recommended IV size if no IV has been set. * \return \c 0 for ciphers not using an IV or a nonce. * \return The actual size if an IV has been set. */ static inline int mbedtls_cipher_get_iv_size( const mbedtls_cipher_context_t *ctx ) { MBEDTLS_INTERNAL_VALIDATE_RET( ctx != NULL, 0 ); if( ctx->cipher_info == NULL ) return 0; if( ctx->iv_size != 0 ) return (int) ctx->iv_size; return (int) ctx->cipher_info->iv_size; } /** * \brief This function returns the type of the given cipher. * * \param ctx The context of the cipher. This must be initialized. * * \return The type of the cipher. * \return #MBEDTLS_CIPHER_NONE if \p ctx has not been initialized. */ static inline mbedtls_cipher_type_t mbedtls_cipher_get_type( const mbedtls_cipher_context_t *ctx ) { MBEDTLS_INTERNAL_VALIDATE_RET( ctx != NULL, MBEDTLS_CIPHER_NONE ); if( ctx->cipher_info == NULL ) return MBEDTLS_CIPHER_NONE; return ctx->cipher_info->type; } /** * \brief This function returns the name of the given cipher * as a string. * * \param ctx The context of the cipher. This must be initialized. * * \return The name of the cipher. * \return NULL if \p ctx has not been not initialized. */ static inline const char *mbedtls_cipher_get_name( const mbedtls_cipher_context_t *ctx ) { MBEDTLS_INTERNAL_VALIDATE_RET( ctx != NULL, 0 ); if( ctx->cipher_info == NULL ) return 0; return ctx->cipher_info->name; } /** * \brief This function returns the key length of the cipher. * * \param ctx The context of the cipher. This must be initialized. * * \return The key length of the cipher in bits. * \return #MBEDTLS_KEY_LENGTH_NONE if ctx \p has not been * initialized. */ static inline int mbedtls_cipher_get_key_bitlen( const mbedtls_cipher_context_t *ctx ) { MBEDTLS_INTERNAL_VALIDATE_RET( ctx != NULL, MBEDTLS_KEY_LENGTH_NONE ); if( ctx->cipher_info == NULL ) return MBEDTLS_KEY_LENGTH_NONE; return (int) ctx->cipher_info->key_bitlen; } /** * \brief This function returns the operation of the given cipher. * * \param ctx The context of the cipher. This must be initialized. * * \return The type of operation: #MBEDTLS_ENCRYPT or #MBEDTLS_DECRYPT. * \return #MBEDTLS_OPERATION_NONE if \p ctx has not been initialized. */ static inline mbedtls_operation_t mbedtls_cipher_get_operation( const mbedtls_cipher_context_t *ctx ) { MBEDTLS_INTERNAL_VALIDATE_RET( ctx != NULL, MBEDTLS_OPERATION_NONE ); if( ctx->cipher_info == NULL ) return MBEDTLS_OPERATION_NONE; return ctx->operation; } /** * \brief This function sets the key to use with the given context. * * \param ctx The generic cipher context. This must be initialized and * bound to a cipher information structure. * \param key The key to use. This must be a readable buffer of at * least \p key_bitlen Bits. * \param key_bitlen The key length to use, in Bits. * \param operation The operation that the key will be used for: * #MBEDTLS_ENCRYPT or #MBEDTLS_DECRYPT. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on * parameter-verification failure. * \return A cipher-specific error code on failure. */ int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *key, int key_bitlen, const mbedtls_operation_t operation ); #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING) /** * \brief This function sets the padding mode, for cipher modes * that use padding. * * The default passing mode is PKCS7 padding. * * \param ctx The generic cipher context. This must be initialized and * bound to a cipher information structure. * \param mode The padding mode. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE * if the selected padding mode is not supported. * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if the cipher mode * does not support padding. */ int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, mbedtls_cipher_padding_t mode ); #endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */ /** * \brief This function sets the initialization vector (IV) * or nonce. * * \note Some ciphers do not use IVs nor nonce. For these * ciphers, this function has no effect. * * \param ctx The generic cipher context. This must be initialized and * bound to a cipher information structure. * \param iv The IV to use, or NONCE_COUNTER for CTR-mode ciphers. This * must be a readable buffer of at least \p iv_len Bytes. * \param iv_len The IV length for ciphers with variable-size IV. * This parameter is discarded by ciphers with fixed-size IV. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on * parameter-verification failure. */ int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len ); /** * \brief This function resets the cipher state. * * \param ctx The generic cipher context. This must be initialized. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on * parameter-verification failure. */ int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx ); #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C) /** * \brief This function adds additional data for AEAD ciphers. * Currently supported with GCM and ChaCha20+Poly1305. * This must be called exactly once, after * mbedtls_cipher_reset(). * * \param ctx The generic cipher context. This must be initialized. * \param ad The additional data to use. This must be a readable * buffer of at least \p ad_len Bytes. * \param ad_len The length of \p ad in Bytes. * * \return \c 0 on success. * \return A specific error code on failure. */ int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx, const unsigned char *ad, size_t ad_len ); #endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */ /** * \brief The generic cipher update function. It encrypts or * decrypts using the given cipher context. Writes as * many block-sized blocks of data as possible to output. * Any data that cannot be written immediately is either * added to the next block, or flushed when * mbedtls_cipher_finish() is called. * Exception: For MBEDTLS_MODE_ECB, expects a single block * in size. For example, 16 Bytes for AES. * * \note If the underlying cipher is used in GCM mode, all calls * to this function, except for the last one before * mbedtls_cipher_finish(), must have \p ilen as a * multiple of the block size of the cipher. * * \param ctx The generic cipher context. This must be initialized and * bound to a key. * \param input The buffer holding the input data. This must be a * readable buffer of at least \p ilen Bytes. * \param ilen The length of the input data. * \param output The buffer for the output data. This must be able to * hold at least `ilen + block_size`. This must not be the * same buffer as \p input. * \param olen The length of the output data, to be updated with the * actual number of Bytes written. This must not be * \c NULL. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on * parameter-verification failure. * \return #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE on an * unsupported mode for a cipher. * \return A cipher-specific error code on failure. */ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen ); /** * \brief The generic cipher finalization function. If data still * needs to be flushed from an incomplete block, the data * contained in it is padded to the size of * the last block, and written to the \p output buffer. * * \param ctx The generic cipher context. This must be initialized and * bound to a key. * \param output The buffer to write data to. This needs to be a writable * buffer of at least \p block_size Bytes. * \param olen The length of the data written to the \p output buffer. * This may not be \c NULL. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on * parameter-verification failure. * \return #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED on decryption * expecting a full block but not receiving one. * \return #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding * while decrypting. * \return A cipher-specific error code on failure. */ int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx, unsigned char *output, size_t *olen ); #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C) /** * \brief This function writes a tag for AEAD ciphers. * Currently supported with GCM and ChaCha20+Poly1305. * This must be called after mbedtls_cipher_finish(). * * \param ctx The generic cipher context. This must be initialized, * bound to a key, and have just completed a cipher * operation through mbedtls_cipher_finish() the tag for * which should be written. * \param tag The buffer to write the tag to. This must be a writable * buffer of at least \p tag_len Bytes. * \param tag_len The length of the tag to write. * * \return \c 0 on success. * \return A specific error code on failure. */ int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx, unsigned char *tag, size_t tag_len ); /** * \brief This function checks the tag for AEAD ciphers. * Currently supported with GCM and ChaCha20+Poly1305. * This must be called after mbedtls_cipher_finish(). * * \param ctx The generic cipher context. This must be initialized. * \param tag The buffer holding the tag. This must be a readable * buffer of at least \p tag_len Bytes. * \param tag_len The length of the tag to check. * * \return \c 0 on success. * \return A specific error code on failure. */ int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx, const unsigned char *tag, size_t tag_len ); #endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */ /** * \brief The generic all-in-one encryption/decryption function, * for all ciphers except AEAD constructs. * * \param ctx The generic cipher context. This must be initialized. * \param iv The IV to use, or NONCE_COUNTER for CTR-mode ciphers. * This must be a readable buffer of at least \p iv_len * Bytes. * \param iv_len The IV length for ciphers with variable-size IV. * This parameter is discarded by ciphers with fixed-size * IV. * \param input The buffer holding the input data. This must be a * readable buffer of at least \p ilen Bytes. * \param ilen The length of the input data in Bytes. * \param output The buffer for the output data. This must be able to * hold at least `ilen + block_size`. This must not be the * same buffer as \p input. * \param olen The length of the output data, to be updated with the * actual number of Bytes written. This must not be * \c NULL. * * \note Some ciphers do not use IVs nor nonce. For these * ciphers, use \p iv = NULL and \p iv_len = 0. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on * parameter-verification failure. * \return #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED on decryption * expecting a full block but not receiving one. * \return #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding * while decrypting. * \return A cipher-specific error code on failure. */ int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen ); /** * \brief The generic authenticated encryption (AEAD) function. * * \deprecated Superseded by mbedtls_cipher_auth_encrypt_ext(). * * \note This function only supports AEAD algorithms, not key * wrapping algorithms such as NIST_KW; for this, see * mbedtls_cipher_auth_encrypt_ext(). * * \param ctx The generic cipher context. This must be initialized and * bound to a key associated with an AEAD algorithm. * \param iv The nonce to use. This must be a readable buffer of * at least \p iv_len Bytes and must not be \c NULL. * \param iv_len The length of the nonce. This must satisfy the * constraints imposed by the AEAD cipher used. * \param ad The additional data to authenticate. This must be a * readable buffer of at least \p ad_len Bytes, and may * be \c NULL is \p ad_len is \c 0. * \param ad_len The length of \p ad. * \param input The buffer holding the input data. This must be a * readable buffer of at least \p ilen Bytes, and may be * \c NULL if \p ilen is \c 0. * \param ilen The length of the input data. * \param output The buffer for the output data. This must be a * writable buffer of at least \p ilen Bytes, and must * not be \c NULL. * \param olen This will be filled with the actual number of Bytes * written to the \p output buffer. This must point to a * writable object of type \c size_t. * \param tag The buffer for the authentication tag. This must be a * writable buffer of at least \p tag_len Bytes. See note * below regarding restrictions with PSA-based contexts. * \param tag_len The desired length of the authentication tag. This * must match the constraints imposed by the AEAD cipher * used, and in particular must not be \c 0. * * \note If the context is based on PSA (that is, it was set up * with mbedtls_cipher_setup_psa()), then it is required * that \c tag == output + ilen. That is, the tag must be * appended to the ciphertext as recommended by RFC 5116. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on * parameter-verification failure. * \return A cipher-specific error code on failure. */ int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, const unsigned char *ad, size_t ad_len, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen, unsigned char *tag, size_t tag_len ); /** * \brief The generic authenticated decryption (AEAD) function. * * \deprecated Superseded by mbedtls_cipher_auth_decrypt_ext(). * * \note This function only supports AEAD algorithms, not key * wrapping algorithms such as NIST_KW; for this, see * mbedtls_cipher_auth_decrypt_ext(). * * \note If the data is not authentic, then the output buffer * is zeroed out to prevent the unauthentic plaintext being * used, making this interface safer. * * \param ctx The generic cipher context. This must be initialized and * bound to a key associated with an AEAD algorithm. * \param iv The nonce to use. This must be a readable buffer of * at least \p iv_len Bytes and must not be \c NULL. * \param iv_len The length of the nonce. This must satisfy the * constraints imposed by the AEAD cipher used. * \param ad The additional data to authenticate. This must be a * readable buffer of at least \p ad_len Bytes, and may * be \c NULL is \p ad_len is \c 0. * \param ad_len The length of \p ad. * \param input The buffer holding the input data. This must be a * readable buffer of at least \p ilen Bytes, and may be * \c NULL if \p ilen is \c 0. * \param ilen The length of the input data. * \param output The buffer for the output data. This must be a * writable buffer of at least \p ilen Bytes, and must * not be \c NULL. * \param olen This will be filled with the actual number of Bytes * written to the \p output buffer. This must point to a * writable object of type \c size_t. * \param tag The buffer for the authentication tag. This must be a * readable buffer of at least \p tag_len Bytes. See note * below regarding restrictions with PSA-based contexts. * \param tag_len The length of the authentication tag. This must match * the constraints imposed by the AEAD cipher used, and in * particular must not be \c 0. * * \note If the context is based on PSA (that is, it was set up * with mbedtls_cipher_setup_psa()), then it is required * that \c tag == input + len. That is, the tag must be * appended to the ciphertext as recommended by RFC 5116. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on * parameter-verification failure. * \return #MBEDTLS_ERR_CIPHER_AUTH_FAILED if data is not authentic. * \return A cipher-specific error code on failure. */ int mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, const unsigned char *ad, size_t ad_len, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen, const unsigned char *tag, size_t tag_len ); #if defined(MBEDTLS_CIPHER_MODE_AEAD) || defined(MBEDTLS_NIST_KW_C) /** * \brief The authenticated encryption (AEAD/NIST_KW) function. * * \note For AEAD modes, the tag will be appended to the * ciphertext, as recommended by RFC 5116. * (NIST_KW doesn't have a separate tag.) * * \param ctx The generic cipher context. This must be initialized and * bound to a key, with an AEAD algorithm or NIST_KW. * \param iv The nonce to use. This must be a readable buffer of * at least \p iv_len Bytes and may be \c NULL if \p * iv_len is \c 0. * \param iv_len The length of the nonce. For AEAD ciphers, this must * satisfy the constraints imposed by the cipher used. * For NIST_KW, this must be \c 0. * \param ad The additional data to authenticate. This must be a * readable buffer of at least \p ad_len Bytes, and may * be \c NULL is \p ad_len is \c 0. * \param ad_len The length of \p ad. For NIST_KW, this must be \c 0. * \param input The buffer holding the input data. This must be a * readable buffer of at least \p ilen Bytes, and may be * \c NULL if \p ilen is \c 0. * \param ilen The length of the input data. * \param output The buffer for the output data. This must be a * writable buffer of at least \p output_len Bytes, and * must not be \c NULL. * \param output_len The length of the \p output buffer in Bytes. For AEAD * ciphers, this must be at least \p ilen + \p tag_len. * For NIST_KW, this must be at least \p ilen + 8 * (rounded up to a multiple of 8 if KWP is used); * \p ilen + 15 is always a safe value. * \param olen This will be filled with the actual number of Bytes * written to the \p output buffer. This must point to a * writable object of type \c size_t. * \param tag_len The desired length of the authentication tag. For AEAD * ciphers, this must match the constraints imposed by * the cipher used, and in particular must not be \c 0. * For NIST_KW, this must be \c 0. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on * parameter-verification failure. * \return A cipher-specific error code on failure. */ int mbedtls_cipher_auth_encrypt_ext( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, const unsigned char *ad, size_t ad_len, const unsigned char *input, size_t ilen, unsigned char *output, size_t output_len, size_t *olen, size_t tag_len ); /** * \brief The authenticated encryption (AEAD/NIST_KW) function. * * \note If the data is not authentic, then the output buffer * is zeroed out to prevent the unauthentic plaintext being * used, making this interface safer. * * \note For AEAD modes, the tag must be appended to the * ciphertext, as recommended by RFC 5116. * (NIST_KW doesn't have a separate tag.) * * \param ctx The generic cipher context. This must be initialized and * bound to a key, with an AEAD algorithm or NIST_KW. * \param iv The nonce to use. This must be a readable buffer of * at least \p iv_len Bytes and may be \c NULL if \p * iv_len is \c 0. * \param iv_len The length of the nonce. For AEAD ciphers, this must * satisfy the constraints imposed by the cipher used. * For NIST_KW, this must be \c 0. * \param ad The additional data to authenticate. This must be a * readable buffer of at least \p ad_len Bytes, and may * be \c NULL is \p ad_len is \c 0. * \param ad_len The length of \p ad. For NIST_KW, this must be \c 0. * \param input The buffer holding the input data. This must be a * readable buffer of at least \p ilen Bytes, and may be * \c NULL if \p ilen is \c 0. * \param ilen The length of the input data. For AEAD ciphers this * must be at least \p tag_len. For NIST_KW this must be * at least \c 8. * \param output The buffer for the output data. This must be a * writable buffer of at least \p output_len Bytes, and * may be \c NULL if \p output_len is \c 0. * \param output_len The length of the \p output buffer in Bytes. For AEAD * ciphers, this must be at least \p ilen - \p tag_len. * For NIST_KW, this must be at least \p ilen - 8. * \param olen This will be filled with the actual number of Bytes * written to the \p output buffer. This must point to a * writable object of type \c size_t. * \param tag_len The actual length of the authentication tag. For AEAD * ciphers, this must match the constraints imposed by * the cipher used, and in particular must not be \c 0. * For NIST_KW, this must be \c 0. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on * parameter-verification failure. * \return #MBEDTLS_ERR_CIPHER_AUTH_FAILED if data is not authentic. * \return A cipher-specific error code on failure. */ int mbedtls_cipher_auth_decrypt_ext( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, const unsigned char *ad, size_t ad_len, const unsigned char *input, size_t ilen, unsigned char *output, size_t output_len, size_t *olen, size_t tag_len ); #endif /* MBEDTLS_CIPHER_MODE_AEAD || MBEDTLS_NIST_KW_C */ #ifdef __cplusplus } #endif #endif /* MBEDTLS_CIPHER_H */
48,248
992
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/oid.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/fmt/fmt.h" #include "libc/str/str.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/oid.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/rsa.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /** * @fileoverview Object Identifier (OID) database */ #if defined(MBEDTLS_OID_C) /* * Macro to automatically add the size of #define'd OIDs */ #define ADD_LEN(s) s, MBEDTLS_OID_SIZE(s) /* * Macro to generate an internal function for oid_XXX_from_asn1() (used by * the other functions) */ #define FN_OID_TYPED_FROM_ASN1( TYPE_T, NAME, LIST ) \ static const TYPE_T * oid_ ## NAME ## _from_asn1( \ const mbedtls_asn1_buf *oid ) \ { \ const TYPE_T *p = (LIST); \ const mbedtls_oid_descriptor_t *cur = \ (const mbedtls_oid_descriptor_t *) p; \ if( p == NULL || oid == NULL ) return( NULL ); \ while( cur->asn1 != NULL ) { \ if( cur->asn1_len == oid->len && \ timingsafe_bcmp( cur->asn1, oid->p, oid->len ) == 0 ) { \ return( p ); \ } \ p++; \ cur = (const mbedtls_oid_descriptor_t *) p; \ } \ return( NULL ); \ } /* * Macro to generate a function for retrieving a single attribute from the * descriptor of an mbedtls_oid_descriptor_t wrapper. */ #define FN_OID_GET_DESCRIPTOR_ATTR1(FN_NAME, TYPE_T, TYPE_NAME, ATTR1_TYPE, ATTR1) \ int FN_NAME( const mbedtls_asn1_buf *oid, ATTR1_TYPE * ATTR1 ) \ { \ const TYPE_T *data = oid_ ## TYPE_NAME ## _from_asn1( oid ); \ if( data == NULL ) return( MBEDTLS_ERR_OID_NOT_FOUND ); \ *ATTR1 = data->descriptor.ATTR1; \ return( 0 ); \ } /* * Macro to generate a function for retrieving a single attribute from an * mbedtls_oid_descriptor_t wrapper. */ #define FN_OID_GET_ATTR1(FN_NAME, TYPE_T, TYPE_NAME, ATTR1_TYPE, ATTR1) \ int FN_NAME( const mbedtls_asn1_buf *oid, ATTR1_TYPE * ATTR1 ) \ { \ const TYPE_T *data = oid_ ## TYPE_NAME ## _from_asn1( oid ); \ if( data == NULL ) return( MBEDTLS_ERR_OID_NOT_FOUND ); \ *ATTR1 = data->ATTR1; \ return( 0 ); \ } /* * Macro to generate a function for retrieving two attributes from an * mbedtls_oid_descriptor_t wrapper. */ #define FN_OID_GET_ATTR2(FN_NAME, TYPE_T, TYPE_NAME, ATTR1_TYPE, ATTR1, \ ATTR2_TYPE, ATTR2) \ int FN_NAME( const mbedtls_asn1_buf *oid, ATTR1_TYPE * ATTR1, \ ATTR2_TYPE * ATTR2 ) \ { \ const TYPE_T *data = oid_ ## TYPE_NAME ## _from_asn1( oid ); \ if( data == NULL ) return( MBEDTLS_ERR_OID_NOT_FOUND ); \ *(ATTR1) = data->ATTR1; \ *(ATTR2) = data->ATTR2; \ return( 0 ); \ } /* * Macro to generate a function for retrieving the OID based on a single * attribute from a mbedtls_oid_descriptor_t wrapper. */ #define FN_OID_GET_OID_BY_ATTR1(FN_NAME, TYPE_T, LIST, ATTR1_TYPE, ATTR1) \ int FN_NAME( ATTR1_TYPE ATTR1, const char **oid, size_t *olen ) \ { \ const TYPE_T *cur = (LIST); \ while( cur->descriptor.asn1 != NULL ) { \ if( cur->ATTR1 == (ATTR1) ) { \ *oid = cur->descriptor.asn1; \ *olen = cur->descriptor.asn1_len; \ return( 0 ); \ } \ cur++; \ } \ return( MBEDTLS_ERR_OID_NOT_FOUND ); \ } /* * Macro to generate a function for retrieving the OID based on two * attributes from a mbedtls_oid_descriptor_t wrapper. */ #define FN_OID_GET_OID_BY_ATTR2(FN_NAME, TYPE_T, LIST, ATTR1_TYPE, ATTR1, \ ATTR2_TYPE, ATTR2) \ int FN_NAME( ATTR1_TYPE ATTR1, ATTR2_TYPE ATTR2, const char **oid , \ size_t *olen ) \ { \ const TYPE_T *cur = (LIST); \ while( cur->descriptor.asn1 != NULL ) { \ if( cur->ATTR1 == (ATTR1) && cur->ATTR2 == (ATTR2) ) { \ *oid = cur->descriptor.asn1; \ *olen = cur->descriptor.asn1_len; \ return( 0 ); \ } \ cur++; \ } \ return( MBEDTLS_ERR_OID_NOT_FOUND ); \ } /* * For X520 attribute types */ typedef struct { mbedtls_oid_descriptor_t descriptor; const char *short_name; } oid_x520_attr_t; static const oid_x520_attr_t oid_x520_attr_type[] = { { { ADD_LEN( MBEDTLS_OID_AT_CN ), "id-at-commonName", "Common Name" }, "CN", }, { { ADD_LEN( MBEDTLS_OID_AT_COUNTRY ), "id-at-countryName", "Country" }, "C", }, { { ADD_LEN( MBEDTLS_OID_AT_LOCALITY ), "id-at-locality", "Locality" }, "L", }, { { ADD_LEN( MBEDTLS_OID_AT_STATE ), "id-at-state", "State" }, "ST", }, { { ADD_LEN( MBEDTLS_OID_AT_ORGANIZATION ),"id-at-organizationName", "Organization" }, "O", }, { { ADD_LEN( MBEDTLS_OID_AT_ORG_UNIT ), "id-at-organizationalUnitName", "Org Unit" }, "OU", }, { { ADD_LEN( MBEDTLS_OID_PKCS9_EMAIL ), "emailAddress", "E-mail address" }, "emailAddress", }, { { ADD_LEN( MBEDTLS_OID_AT_SERIAL_NUMBER ),"id-at-serialNumber", "Serial number" }, "serialNumber", }, { { ADD_LEN( MBEDTLS_OID_AT_POSTAL_ADDRESS ),"id-at-postalAddress", "Postal address" }, "postalAddress", }, { { ADD_LEN( MBEDTLS_OID_AT_POSTAL_CODE ), "id-at-postalCode", "Postal code" }, "postalCode", }, { { ADD_LEN( MBEDTLS_OID_AT_SUR_NAME ), "id-at-surName", "Surname" }, "SN", }, { { ADD_LEN( MBEDTLS_OID_AT_GIVEN_NAME ), "id-at-givenName", "Given name" }, "GN", }, { { ADD_LEN( MBEDTLS_OID_AT_INITIALS ), "id-at-initials", "Initials" }, "initials", }, { { ADD_LEN( MBEDTLS_OID_AT_GENERATION_QUALIFIER ), "id-at-generationQualifier", "Generation qualifier" }, "generationQualifier", }, { { ADD_LEN( MBEDTLS_OID_AT_TITLE ), "id-at-title", "Title" }, "title", }, { { ADD_LEN( MBEDTLS_OID_AT_DN_QUALIFIER ),"id-at-dnQualifier", "Distinguished Name qualifier" }, "dnQualifier", }, { { ADD_LEN( MBEDTLS_OID_AT_PSEUDONYM ), "id-at-pseudonym", "Pseudonym" }, "pseudonym", }, { { ADD_LEN( MBEDTLS_OID_DOMAIN_COMPONENT ), "id-domainComponent", "Domain component" }, "DC", }, { { ADD_LEN( MBEDTLS_OID_AT_UNIQUE_IDENTIFIER ), "id-at-uniqueIdentifier", "Unique Identifier" }, "uniqueIdentifier", }, { { NULL, 0, NULL, NULL }, NULL, } }; FN_OID_TYPED_FROM_ASN1(oid_x520_attr_t, x520_attr, oid_x520_attr_type) FN_OID_GET_ATTR1(mbedtls_oid_get_attr_short_name, oid_x520_attr_t, x520_attr, const char *, short_name) /* * For X509 extensions */ typedef struct { mbedtls_oid_descriptor_t descriptor; int ext_type; } oid_x509_ext_t; static const oid_x509_ext_t oid_x509_ext[] = { { { ADD_LEN( MBEDTLS_OID_BASIC_CONSTRAINTS ), "id-ce-basicConstraints", "Basic Constraints" }, MBEDTLS_OID_X509_EXT_BASIC_CONSTRAINTS, }, { { ADD_LEN( MBEDTLS_OID_KEY_USAGE ), "id-ce-keyUsage", "Key Usage" }, MBEDTLS_OID_X509_EXT_KEY_USAGE, }, { { ADD_LEN( MBEDTLS_OID_EXTENDED_KEY_USAGE ), "id-ce-extKeyUsage", "Extended Key Usage" }, MBEDTLS_OID_X509_EXT_EXTENDED_KEY_USAGE, }, { { ADD_LEN( MBEDTLS_OID_SUBJECT_ALT_NAME ), "id-ce-subjectAltName", "Subject Alt Name" }, MBEDTLS_OID_X509_EXT_SUBJECT_ALT_NAME, }, { { ADD_LEN( MBEDTLS_OID_NS_CERT_TYPE ), "id-netscape-certtype", "Netscape Certificate Type" }, MBEDTLS_OID_X509_EXT_NS_CERT_TYPE, }, { { ADD_LEN( MBEDTLS_OID_CERTIFICATE_POLICIES ), "id-ce-certificatePolicies", "Certificate Policies" }, MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES, }, { { NULL, 0, NULL, NULL }, 0, }, }; FN_OID_TYPED_FROM_ASN1(oid_x509_ext_t, x509_ext, oid_x509_ext) FN_OID_GET_ATTR1(mbedtls_oid_get_x509_ext_type, oid_x509_ext_t, x509_ext, int, ext_type) static const mbedtls_oid_descriptor_t oid_ext_key_usage[] = { { ADD_LEN( MBEDTLS_OID_SERVER_AUTH ), "id-kp-serverAuth", "TLS Web Server Authentication" }, { ADD_LEN( MBEDTLS_OID_CLIENT_AUTH ), "id-kp-clientAuth", "TLS Web Client Authentication" }, { ADD_LEN( MBEDTLS_OID_CODE_SIGNING ), "id-kp-codeSigning", "Code Signing" }, { ADD_LEN( MBEDTLS_OID_EMAIL_PROTECTION ), "id-kp-emailProtection", "E-mail Protection" }, { ADD_LEN( MBEDTLS_OID_TIME_STAMPING ), "id-kp-timeStamping", "Time Stamping" }, { ADD_LEN( MBEDTLS_OID_OCSP_SIGNING ), "id-kp-OCSPSigning", "OCSP Signing" }, { NULL, 0, NULL, NULL }, }; FN_OID_TYPED_FROM_ASN1(mbedtls_oid_descriptor_t, ext_key_usage, oid_ext_key_usage) FN_OID_GET_ATTR1(mbedtls_oid_get_extended_key_usage, mbedtls_oid_descriptor_t, ext_key_usage, const char *, description) static const mbedtls_oid_descriptor_t oid_certificate_policies[] = { { ADD_LEN( MBEDTLS_OID_ANY_POLICY ), "anyPolicy", "Any Policy" }, { NULL, 0, NULL, NULL }, }; FN_OID_TYPED_FROM_ASN1(mbedtls_oid_descriptor_t, certificate_policies, oid_certificate_policies) FN_OID_GET_ATTR1(mbedtls_oid_get_certificate_policies, mbedtls_oid_descriptor_t, certificate_policies, const char *, description) #if defined(MBEDTLS_MD_C) /* * For SignatureAlgorithmIdentifier */ typedef struct { mbedtls_oid_descriptor_t descriptor; mbedtls_md_type_t md_alg; mbedtls_pk_type_t pk_alg; } oid_sig_alg_t; static const oid_sig_alg_t oid_sig_alg[] = { #if defined(MBEDTLS_RSA_C) #if defined(MBEDTLS_MD2_C) { { ADD_LEN( MBEDTLS_OID_PKCS1_MD2 ), "md2WithRSAEncryption", "RSA with MD2" }, MBEDTLS_MD_MD2, MBEDTLS_PK_RSA, }, #endif /* MBEDTLS_MD2_C */ #if defined(MBEDTLS_MD4_C) { { ADD_LEN( MBEDTLS_OID_PKCS1_MD4 ), "md4WithRSAEncryption", "RSA with MD4" }, MBEDTLS_MD_MD4, MBEDTLS_PK_RSA, }, #endif /* MBEDTLS_MD4_C */ #if defined(MBEDTLS_MD5_C) { { ADD_LEN( MBEDTLS_OID_PKCS1_MD5 ), "md5WithRSAEncryption", "RSA with MD5" }, MBEDTLS_MD_MD5, MBEDTLS_PK_RSA, }, #endif /* MBEDTLS_MD5_C */ #if defined(MBEDTLS_SHA1_C) { { ADD_LEN( MBEDTLS_OID_PKCS1_SHA1 ), "sha-1WithRSAEncryption", "RSA with SHA1" }, MBEDTLS_MD_SHA1, MBEDTLS_PK_RSA, }, #endif /* MBEDTLS_SHA1_C */ #if defined(MBEDTLS_SHA256_C) { { ADD_LEN( MBEDTLS_OID_PKCS1_SHA224 ), "sha224WithRSAEncryption", "RSA with SHA-224" }, MBEDTLS_MD_SHA224, MBEDTLS_PK_RSA, }, { { ADD_LEN( MBEDTLS_OID_PKCS1_SHA256 ), "sha256WithRSAEncryption", "RSA with SHA-256" }, MBEDTLS_MD_SHA256, MBEDTLS_PK_RSA, }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { { ADD_LEN( MBEDTLS_OID_PKCS1_SHA384 ), "sha384WithRSAEncryption", "RSA with SHA-384" }, MBEDTLS_MD_SHA384, MBEDTLS_PK_RSA, }, { { ADD_LEN( MBEDTLS_OID_PKCS1_SHA512 ), "sha512WithRSAEncryption", "RSA with SHA-512" }, MBEDTLS_MD_SHA512, MBEDTLS_PK_RSA, }, #endif /* MBEDTLS_SHA512_C */ #if defined(MBEDTLS_SHA1_C) { { ADD_LEN( MBEDTLS_OID_RSA_SHA_OBS ), "sha-1WithRSAEncryption", "RSA with SHA1" }, MBEDTLS_MD_SHA1, MBEDTLS_PK_RSA, }, #endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_ECDSA_C) #if defined(MBEDTLS_SHA1_C) { { ADD_LEN( MBEDTLS_OID_ECDSA_SHA1 ), "ecdsa-with-SHA1", "ECDSA with SHA1" }, MBEDTLS_MD_SHA1, MBEDTLS_PK_ECDSA, }, #endif /* MBEDTLS_SHA1_C */ #if defined(MBEDTLS_SHA256_C) { { ADD_LEN( MBEDTLS_OID_ECDSA_SHA224 ), "ecdsa-with-SHA224", "ECDSA with SHA224" }, MBEDTLS_MD_SHA224, MBEDTLS_PK_ECDSA, }, { { ADD_LEN( MBEDTLS_OID_ECDSA_SHA256 ), "ecdsa-with-SHA256", "ECDSA with SHA256" }, MBEDTLS_MD_SHA256, MBEDTLS_PK_ECDSA, }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { { ADD_LEN( MBEDTLS_OID_ECDSA_SHA384 ), "ecdsa-with-SHA384", "ECDSA with SHA384" }, MBEDTLS_MD_SHA384, MBEDTLS_PK_ECDSA, }, { { ADD_LEN( MBEDTLS_OID_ECDSA_SHA512 ), "ecdsa-with-SHA512", "ECDSA with SHA512" }, MBEDTLS_MD_SHA512, MBEDTLS_PK_ECDSA, }, #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_ECDSA_C */ #if defined(MBEDTLS_RSA_C) { { ADD_LEN( MBEDTLS_OID_RSASSA_PSS ), "RSASSA-PSS", "RSASSA-PSS" }, MBEDTLS_MD_NONE, MBEDTLS_PK_RSASSA_PSS, }, #endif /* MBEDTLS_RSA_C */ { { NULL, 0, NULL, NULL }, MBEDTLS_MD_NONE, MBEDTLS_PK_NONE, }, }; FN_OID_TYPED_FROM_ASN1(oid_sig_alg_t, sig_alg, oid_sig_alg) FN_OID_GET_DESCRIPTOR_ATTR1(mbedtls_oid_get_sig_alg_desc, oid_sig_alg_t, sig_alg, const char *, description) FN_OID_GET_ATTR2(mbedtls_oid_get_sig_alg, oid_sig_alg_t, sig_alg, mbedtls_md_type_t, md_alg, mbedtls_pk_type_t, pk_alg) FN_OID_GET_OID_BY_ATTR2(mbedtls_oid_get_oid_by_sig_alg, oid_sig_alg_t, oid_sig_alg, mbedtls_pk_type_t, pk_alg, mbedtls_md_type_t, md_alg) #endif /* MBEDTLS_MD_C */ /* * For PublicKeyInfo (PKCS1, RFC 5480) */ typedef struct { mbedtls_oid_descriptor_t descriptor; mbedtls_pk_type_t pk_alg; } oid_pk_alg_t; static const oid_pk_alg_t oid_pk_alg[] = { { { ADD_LEN( MBEDTLS_OID_PKCS1_RSA ), "rsaEncryption", "RSA" }, MBEDTLS_PK_RSA, }, { { ADD_LEN( MBEDTLS_OID_EC_ALG_UNRESTRICTED ), "id-ecPublicKey", "Generic EC key" }, MBEDTLS_PK_ECKEY, }, { { ADD_LEN( MBEDTLS_OID_EC_ALG_ECDH ), "id-ecDH", "EC key for ECDH" }, MBEDTLS_PK_ECKEY_DH, }, { { NULL, 0, NULL, NULL }, MBEDTLS_PK_NONE, }, }; FN_OID_TYPED_FROM_ASN1(oid_pk_alg_t, pk_alg, oid_pk_alg) FN_OID_GET_ATTR1(mbedtls_oid_get_pk_alg, oid_pk_alg_t, pk_alg, mbedtls_pk_type_t, pk_alg) FN_OID_GET_OID_BY_ATTR1(mbedtls_oid_get_oid_by_pk_alg, oid_pk_alg_t, oid_pk_alg, mbedtls_pk_type_t, pk_alg) #if defined(MBEDTLS_ECP_C) /* * For namedCurve (RFC 5480) */ typedef struct { mbedtls_oid_descriptor_t descriptor; mbedtls_ecp_group_id grp_id; } oid_ecp_grp_t; static const oid_ecp_grp_t oid_ecp_grp[] = { #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) { { ADD_LEN( MBEDTLS_OID_EC_GRP_SECP192R1 ), "secp192r1", "secp192r1" }, MBEDTLS_ECP_DP_SECP192R1, }, #endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) { { ADD_LEN( MBEDTLS_OID_EC_GRP_SECP224R1 ), "secp224r1", "secp224r1" }, MBEDTLS_ECP_DP_SECP224R1, }, #endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) { { ADD_LEN( MBEDTLS_OID_EC_GRP_SECP256R1 ), "secp256r1", "secp256r1" }, MBEDTLS_ECP_DP_SECP256R1, }, #endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) { { ADD_LEN( MBEDTLS_OID_EC_GRP_SECP384R1 ), "secp384r1", "secp384r1" }, MBEDTLS_ECP_DP_SECP384R1, }, #endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) { { ADD_LEN( MBEDTLS_OID_EC_GRP_SECP521R1 ), "secp521r1", "secp521r1" }, MBEDTLS_ECP_DP_SECP521R1, }, #endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) { { ADD_LEN( MBEDTLS_OID_EC_GRP_SECP192K1 ), "secp192k1", "secp192k1" }, MBEDTLS_ECP_DP_SECP192K1, }, #endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) { { ADD_LEN( MBEDTLS_OID_EC_GRP_SECP224K1 ), "secp224k1", "secp224k1" }, MBEDTLS_ECP_DP_SECP224K1, }, #endif /* MBEDTLS_ECP_DP_SECP224K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) { { ADD_LEN( MBEDTLS_OID_EC_GRP_SECP256K1 ), "secp256k1", "secp256k1" }, MBEDTLS_ECP_DP_SECP256K1, }, #endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) { { ADD_LEN( MBEDTLS_OID_EC_GRP_BP256R1 ), "brainpoolP256r1","brainpool256r1" }, MBEDTLS_ECP_DP_BP256R1, }, #endif /* MBEDTLS_ECP_DP_BP256R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) { { ADD_LEN( MBEDTLS_OID_EC_GRP_BP384R1 ), "brainpoolP384r1","brainpool384r1" }, MBEDTLS_ECP_DP_BP384R1, }, #endif /* MBEDTLS_ECP_DP_BP384R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) { { ADD_LEN( MBEDTLS_OID_EC_GRP_BP512R1 ), "brainpoolP512r1","brainpool512r1" }, MBEDTLS_ECP_DP_BP512R1, }, #endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */ { { NULL, 0, NULL, NULL }, MBEDTLS_ECP_DP_NONE, }, }; FN_OID_TYPED_FROM_ASN1(oid_ecp_grp_t, grp_id, oid_ecp_grp) FN_OID_GET_ATTR1(mbedtls_oid_get_ec_grp, oid_ecp_grp_t, grp_id, mbedtls_ecp_group_id, grp_id) FN_OID_GET_OID_BY_ATTR1(mbedtls_oid_get_oid_by_ec_grp, oid_ecp_grp_t, oid_ecp_grp, mbedtls_ecp_group_id, grp_id) #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_CIPHER_C) /* * For PKCS#5 PBES2 encryption algorithm */ typedef struct { mbedtls_oid_descriptor_t descriptor; mbedtls_cipher_type_t cipher_alg; } oid_cipher_alg_t; static const oid_cipher_alg_t oid_cipher_alg[] = { { { ADD_LEN( MBEDTLS_OID_DES_CBC ), "desCBC", "DES-CBC" }, MBEDTLS_CIPHER_DES_CBC, }, { { ADD_LEN( MBEDTLS_OID_DES_EDE3_CBC ), "des-ede3-cbc", "DES-EDE3-CBC" }, MBEDTLS_CIPHER_DES_EDE3_CBC, }, { { NULL, 0, NULL, NULL }, MBEDTLS_CIPHER_NONE, }, }; FN_OID_TYPED_FROM_ASN1(oid_cipher_alg_t, cipher_alg, oid_cipher_alg) FN_OID_GET_ATTR1(mbedtls_oid_get_cipher_alg, oid_cipher_alg_t, cipher_alg, mbedtls_cipher_type_t, cipher_alg) #endif /* MBEDTLS_CIPHER_C */ #if defined(MBEDTLS_MD_C) /* * For digestAlgorithm */ typedef struct { mbedtls_oid_descriptor_t descriptor; mbedtls_md_type_t md_alg; } oid_md_alg_t; static const oid_md_alg_t oid_md_alg[] = { #if defined(MBEDTLS_MD2_C) { { ADD_LEN( MBEDTLS_OID_DIGEST_ALG_MD2 ), "id-md2", "MD2" }, MBEDTLS_MD_MD2, }, #endif /* MBEDTLS_MD2_C */ #if defined(MBEDTLS_MD4_C) { { ADD_LEN( MBEDTLS_OID_DIGEST_ALG_MD4 ), "id-md4", "MD4" }, MBEDTLS_MD_MD4, }, #endif /* MBEDTLS_MD4_C */ #if defined(MBEDTLS_MD5_C) { { ADD_LEN( MBEDTLS_OID_DIGEST_ALG_MD5 ), "id-md5", "MD5" }, MBEDTLS_MD_MD5, }, #endif /* MBEDTLS_MD5_C */ #if defined(MBEDTLS_SHA1_C) { { ADD_LEN( MBEDTLS_OID_DIGEST_ALG_SHA1 ), "id-sha1", "SHA-1" }, MBEDTLS_MD_SHA1, }, #endif /* MBEDTLS_SHA1_C */ #if defined(MBEDTLS_SHA256_C) { { ADD_LEN( MBEDTLS_OID_DIGEST_ALG_SHA224 ), "id-sha224", "SHA-224" }, MBEDTLS_MD_SHA224, }, { { ADD_LEN( MBEDTLS_OID_DIGEST_ALG_SHA256 ), "id-sha256", "SHA-256" }, MBEDTLS_MD_SHA256, }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { { ADD_LEN( MBEDTLS_OID_DIGEST_ALG_SHA384 ), "id-sha384", "SHA-384" }, MBEDTLS_MD_SHA384, }, { { ADD_LEN( MBEDTLS_OID_DIGEST_ALG_SHA512 ), "id-sha512", "SHA-512" }, MBEDTLS_MD_SHA512, }, #endif /* MBEDTLS_SHA512_C */ { { NULL, 0, NULL, NULL }, MBEDTLS_MD_NONE, }, }; FN_OID_TYPED_FROM_ASN1(oid_md_alg_t, md_alg, oid_md_alg) FN_OID_GET_ATTR1(mbedtls_oid_get_md_alg, oid_md_alg_t, md_alg, mbedtls_md_type_t, md_alg) FN_OID_GET_OID_BY_ATTR1(mbedtls_oid_get_oid_by_md, oid_md_alg_t, oid_md_alg, mbedtls_md_type_t, md_alg) /* * For HMAC digestAlgorithm */ typedef struct { mbedtls_oid_descriptor_t descriptor; mbedtls_md_type_t md_hmac; } oid_md_hmac_t; static const oid_md_hmac_t oid_md_hmac[] = { #if defined(MBEDTLS_SHA1_C) { { ADD_LEN( MBEDTLS_OID_HMAC_SHA1 ), "hmacSHA1", "HMAC-SHA-1" }, MBEDTLS_MD_SHA1, }, #endif /* MBEDTLS_SHA1_C */ #if defined(MBEDTLS_SHA256_C) { { ADD_LEN( MBEDTLS_OID_HMAC_SHA224 ), "hmacSHA224", "HMAC-SHA-224" }, MBEDTLS_MD_SHA224, }, { { ADD_LEN( MBEDTLS_OID_HMAC_SHA256 ), "hmacSHA256", "HMAC-SHA-256" }, MBEDTLS_MD_SHA256, }, #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) { { ADD_LEN( MBEDTLS_OID_HMAC_SHA384 ), "hmacSHA384", "HMAC-SHA-384" }, MBEDTLS_MD_SHA384, }, { { ADD_LEN( MBEDTLS_OID_HMAC_SHA512 ), "hmacSHA512", "HMAC-SHA-512" }, MBEDTLS_MD_SHA512, }, #endif /* MBEDTLS_SHA512_C */ { { NULL, 0, NULL, NULL }, MBEDTLS_MD_NONE, }, }; FN_OID_TYPED_FROM_ASN1(oid_md_hmac_t, md_hmac, oid_md_hmac) FN_OID_GET_ATTR1(mbedtls_oid_get_md_hmac, oid_md_hmac_t, md_hmac, mbedtls_md_type_t, md_hmac) #endif /* MBEDTLS_MD_C */ #if defined(MBEDTLS_PKCS12_C) /* * For PKCS#12 PBEs */ typedef struct { mbedtls_oid_descriptor_t descriptor; mbedtls_md_type_t md_alg; mbedtls_cipher_type_t cipher_alg; } oid_pkcs12_pbe_alg_t; static const oid_pkcs12_pbe_alg_t oid_pkcs12_pbe_alg[] = { { { ADD_LEN( MBEDTLS_OID_PKCS12_PBE_SHA1_DES3_EDE_CBC ), "pbeWithSHAAnd3-KeyTripleDES-CBC", "PBE with SHA1 and 3-Key 3DES" }, MBEDTLS_MD_SHA1, MBEDTLS_CIPHER_DES_EDE3_CBC, }, { { ADD_LEN( MBEDTLS_OID_PKCS12_PBE_SHA1_DES2_EDE_CBC ), "pbeWithSHAAnd2-KeyTripleDES-CBC", "PBE with SHA1 and 2-Key 3DES" }, MBEDTLS_MD_SHA1, MBEDTLS_CIPHER_DES_EDE_CBC, }, { { NULL, 0, NULL, NULL }, MBEDTLS_MD_NONE, MBEDTLS_CIPHER_NONE, }, }; FN_OID_TYPED_FROM_ASN1(oid_pkcs12_pbe_alg_t, pkcs12_pbe_alg, oid_pkcs12_pbe_alg) FN_OID_GET_ATTR2(mbedtls_oid_get_pkcs12_pbe_alg, oid_pkcs12_pbe_alg_t, pkcs12_pbe_alg, mbedtls_md_type_t, md_alg, mbedtls_cipher_type_t, cipher_alg) #endif /* MBEDTLS_PKCS12_C */ #define OID_SAFE_SNPRINTF \ do { \ if( ret < 0 || (size_t) ret >= n ) \ return( MBEDTLS_ERR_OID_BUF_TOO_SMALL ); \ \ n -= (size_t) ret; \ p += (size_t) ret; \ } while( 0 ) /* Return the x.y.z.... style numeric string for the given OID */ int mbedtls_oid_get_numeric_string( char *buf, size_t size, const mbedtls_asn1_buf *oid ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t i, n; unsigned int value; char *p; p = buf; n = size; /* First byte contains first two dots */ if( oid->len > 0 ) { ret = mbedtls_snprintf( p, n, "%d.%d", oid->p[0] / 40, oid->p[0] % 40 ); OID_SAFE_SNPRINTF; } value = 0; for( i = 1; i < oid->len; i++ ) { /* Prevent overflow in value. */ if( ( ( value << 7 ) >> 7 ) != value ) return( MBEDTLS_ERR_OID_BUF_TOO_SMALL ); value <<= 7; value += oid->p[i] & 0x7F; if( !( oid->p[i] & 0x80 ) ) { /* Last byte */ ret = mbedtls_snprintf( p, n, ".%u", value ); OID_SAFE_SNPRINTF; value = 0; } } return( (int) ( size - n ) ); } #endif /* MBEDTLS_OID_C */
28,376
761
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/aes.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:4;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright The Mbed TLS Contributors │ │ │ │ Licensed under the Apache License, Version 2.0 (the "License"); │ │ you may not use this file except in compliance with the License. │ │ You may obtain a copy of the License at │ │ │ │ http://www.apache.org/licenses/LICENSE-2.0 │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/bits.h" #include "libc/nexgen32e/x86feature.h" #include "libc/str/str.h" #include "third_party/mbedtls/aes.h" #include "third_party/mbedtls/aesni.h" #include "third_party/mbedtls/common.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/platform.h" asm(".ident\t\"\\n\\n\ Mbed TLS (Apache 2.0)\\n\ Copyright ARM Limited\\n\ Copyright Mbed TLS Contributors\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ /** * @fileoverview FIPS-197 compliant AES implementation * * The AES block cipher was designed by Vincent Rijmen and Joan Daemen. * The true name of this algorithm is Rijndael. * * @see http://csrc.nist.gov/encryption/aes/rijndael/Rijndael.pdf * @see http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf */ #if defined(MBEDTLS_AES_C) #if !defined(MBEDTLS_AES_ALT) #define AES_VALIDATE_RET( cond ) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_AES_BAD_INPUT_DATA ) #define AES_VALIDATE( cond ) \ MBEDTLS_INTERNAL_VALIDATE( cond ) #define GET_UINT32_LE(n,b,i) (n) = READ32LE((b) + (i)) #define PUT_UINT32_LE(n,b,i) WRITE32LE((b) + (i), n) #if defined(MBEDTLS_PADLOCK_C) && \ ( defined(MBEDTLS_HAVE_X86) || defined(MBEDTLS_PADLOCK_ALIGN16) ) static int aes_padlock_ace = -1; #endif #if defined(MBEDTLS_AES_ROM_TABLES) /* * Forward S-box */ static const unsigned char FSb[256] = { 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 }; /* * Forward tables */ #define FT \ \ V(A5,63,63,C6), V(84,7C,7C,F8), V(99,77,77,EE), V(8D,7B,7B,F6), \ V(0D,F2,F2,FF), V(BD,6B,6B,D6), V(B1,6F,6F,DE), V(54,C5,C5,91), \ V(50,30,30,60), V(03,01,01,02), V(A9,67,67,CE), V(7D,2B,2B,56), \ V(19,FE,FE,E7), V(62,D7,D7,B5), V(E6,AB,AB,4D), V(9A,76,76,EC), \ V(45,CA,CA,8F), V(9D,82,82,1F), V(40,C9,C9,89), V(87,7D,7D,FA), \ V(15,FA,FA,EF), V(EB,59,59,B2), V(C9,47,47,8E), V(0B,F0,F0,FB), \ V(EC,AD,AD,41), V(67,D4,D4,B3), V(FD,A2,A2,5F), V(EA,AF,AF,45), \ V(BF,9C,9C,23), V(F7,A4,A4,53), V(96,72,72,E4), V(5B,C0,C0,9B), \ V(C2,B7,B7,75), V(1C,FD,FD,E1), V(AE,93,93,3D), V(6A,26,26,4C), \ V(5A,36,36,6C), V(41,3F,3F,7E), V(02,F7,F7,F5), V(4F,CC,CC,83), \ V(5C,34,34,68), V(F4,A5,A5,51), V(34,E5,E5,D1), V(08,F1,F1,F9), \ V(93,71,71,E2), V(73,D8,D8,AB), V(53,31,31,62), V(3F,15,15,2A), \ V(0C,04,04,08), V(52,C7,C7,95), V(65,23,23,46), V(5E,C3,C3,9D), \ V(28,18,18,30), V(A1,96,96,37), V(0F,05,05,0A), V(B5,9A,9A,2F), \ V(09,07,07,0E), V(36,12,12,24), V(9B,80,80,1B), V(3D,E2,E2,DF), \ V(26,EB,EB,CD), V(69,27,27,4E), V(CD,B2,B2,7F), V(9F,75,75,EA), \ V(1B,09,09,12), V(9E,83,83,1D), V(74,2C,2C,58), V(2E,1A,1A,34), \ V(2D,1B,1B,36), V(B2,6E,6E,DC), V(EE,5A,5A,B4), V(FB,A0,A0,5B), \ V(F6,52,52,A4), V(4D,3B,3B,76), V(61,D6,D6,B7), V(CE,B3,B3,7D), \ V(7B,29,29,52), V(3E,E3,E3,DD), V(71,2F,2F,5E), V(97,84,84,13), \ V(F5,53,53,A6), V(68,D1,D1,B9), V(00,00,00,00), V(2C,ED,ED,C1), \ V(60,20,20,40), V(1F,FC,FC,E3), V(C8,B1,B1,79), V(ED,5B,5B,B6), \ V(BE,6A,6A,D4), V(46,CB,CB,8D), V(D9,BE,BE,67), V(4B,39,39,72), \ V(DE,4A,4A,94), V(D4,4C,4C,98), V(E8,58,58,B0), V(4A,CF,CF,85), \ V(6B,D0,D0,BB), V(2A,EF,EF,C5), V(E5,AA,AA,4F), V(16,FB,FB,ED), \ V(C5,43,43,86), V(D7,4D,4D,9A), V(55,33,33,66), V(94,85,85,11), \ V(CF,45,45,8A), V(10,F9,F9,E9), V(06,02,02,04), V(81,7F,7F,FE), \ V(F0,50,50,A0), V(44,3C,3C,78), V(BA,9F,9F,25), V(E3,A8,A8,4B), \ V(F3,51,51,A2), V(FE,A3,A3,5D), V(C0,40,40,80), V(8A,8F,8F,05), \ V(AD,92,92,3F), V(BC,9D,9D,21), V(48,38,38,70), V(04,F5,F5,F1), \ V(DF,BC,BC,63), V(C1,B6,B6,77), V(75,DA,DA,AF), V(63,21,21,42), \ V(30,10,10,20), V(1A,FF,FF,E5), V(0E,F3,F3,FD), V(6D,D2,D2,BF), \ V(4C,CD,CD,81), V(14,0C,0C,18), V(35,13,13,26), V(2F,EC,EC,C3), \ V(E1,5F,5F,BE), V(A2,97,97,35), V(CC,44,44,88), V(39,17,17,2E), \ V(57,C4,C4,93), V(F2,A7,A7,55), V(82,7E,7E,FC), V(47,3D,3D,7A), \ V(AC,64,64,C8), V(E7,5D,5D,BA), V(2B,19,19,32), V(95,73,73,E6), \ V(A0,60,60,C0), V(98,81,81,19), V(D1,4F,4F,9E), V(7F,DC,DC,A3), \ V(66,22,22,44), V(7E,2A,2A,54), V(AB,90,90,3B), V(83,88,88,0B), \ V(CA,46,46,8C), V(29,EE,EE,C7), V(D3,B8,B8,6B), V(3C,14,14,28), \ V(79,DE,DE,A7), V(E2,5E,5E,BC), V(1D,0B,0B,16), V(76,DB,DB,AD), \ V(3B,E0,E0,DB), V(56,32,32,64), V(4E,3A,3A,74), V(1E,0A,0A,14), \ V(DB,49,49,92), V(0A,06,06,0C), V(6C,24,24,48), V(E4,5C,5C,B8), \ V(5D,C2,C2,9F), V(6E,D3,D3,BD), V(EF,AC,AC,43), V(A6,62,62,C4), \ V(A8,91,91,39), V(A4,95,95,31), V(37,E4,E4,D3), V(8B,79,79,F2), \ V(32,E7,E7,D5), V(43,C8,C8,8B), V(59,37,37,6E), V(B7,6D,6D,DA), \ V(8C,8D,8D,01), V(64,D5,D5,B1), V(D2,4E,4E,9C), V(E0,A9,A9,49), \ V(B4,6C,6C,D8), V(FA,56,56,AC), V(07,F4,F4,F3), V(25,EA,EA,CF), \ V(AF,65,65,CA), V(8E,7A,7A,F4), V(E9,AE,AE,47), V(18,08,08,10), \ V(D5,BA,BA,6F), V(88,78,78,F0), V(6F,25,25,4A), V(72,2E,2E,5C), \ V(24,1C,1C,38), V(F1,A6,A6,57), V(C7,B4,B4,73), V(51,C6,C6,97), \ V(23,E8,E8,CB), V(7C,DD,DD,A1), V(9C,74,74,E8), V(21,1F,1F,3E), \ V(DD,4B,4B,96), V(DC,BD,BD,61), V(86,8B,8B,0D), V(85,8A,8A,0F), \ V(90,70,70,E0), V(42,3E,3E,7C), V(C4,B5,B5,71), V(AA,66,66,CC), \ V(D8,48,48,90), V(05,03,03,06), V(01,F6,F6,F7), V(12,0E,0E,1C), \ V(A3,61,61,C2), V(5F,35,35,6A), V(F9,57,57,AE), V(D0,B9,B9,69), \ V(91,86,86,17), V(58,C1,C1,99), V(27,1D,1D,3A), V(B9,9E,9E,27), \ V(38,E1,E1,D9), V(13,F8,F8,EB), V(B3,98,98,2B), V(33,11,11,22), \ V(BB,69,69,D2), V(70,D9,D9,A9), V(89,8E,8E,07), V(A7,94,94,33), \ V(B6,9B,9B,2D), V(22,1E,1E,3C), V(92,87,87,15), V(20,E9,E9,C9), \ V(49,CE,CE,87), V(FF,55,55,AA), V(78,28,28,50), V(7A,DF,DF,A5), \ V(8F,8C,8C,03), V(F8,A1,A1,59), V(80,89,89,09), V(17,0D,0D,1A), \ V(DA,BF,BF,65), V(31,E6,E6,D7), V(C6,42,42,84), V(B8,68,68,D0), \ V(C3,41,41,82), V(B0,99,99,29), V(77,2D,2D,5A), V(11,0F,0F,1E), \ V(CB,B0,B0,7B), V(FC,54,54,A8), V(D6,BB,BB,6D), V(3A,16,16,2C) #define V(a,b,c,d) 0x##a##b##c##d static const uint32_t FT0[256] = { FT }; #undef V #if !defined(MBEDTLS_AES_FEWER_TABLES) #define V(a,b,c,d) 0x##b##c##d##a static const uint32_t FT1[256] = { FT }; #undef V #define V(a,b,c,d) 0x##c##d##a##b static const uint32_t FT2[256] = { FT }; #undef V #define V(a,b,c,d) 0x##d##a##b##c static const uint32_t FT3[256] = { FT }; #undef V #endif /* !MBEDTLS_AES_FEWER_TABLES */ #undef FT /* * Reverse S-box */ static const unsigned char RSb[256] = { 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D }; /* * Reverse tables */ #define RT \ \ V(50,A7,F4,51), V(53,65,41,7E), V(C3,A4,17,1A), V(96,5E,27,3A), \ V(CB,6B,AB,3B), V(F1,45,9D,1F), V(AB,58,FA,AC), V(93,03,E3,4B), \ V(55,FA,30,20), V(F6,6D,76,AD), V(91,76,CC,88), V(25,4C,02,F5), \ V(FC,D7,E5,4F), V(D7,CB,2A,C5), V(80,44,35,26), V(8F,A3,62,B5), \ V(49,5A,B1,DE), V(67,1B,BA,25), V(98,0E,EA,45), V(E1,C0,FE,5D), \ V(02,75,2F,C3), V(12,F0,4C,81), V(A3,97,46,8D), V(C6,F9,D3,6B), \ V(E7,5F,8F,03), V(95,9C,92,15), V(EB,7A,6D,BF), V(DA,59,52,95), \ V(2D,83,BE,D4), V(D3,21,74,58), V(29,69,E0,49), V(44,C8,C9,8E), \ V(6A,89,C2,75), V(78,79,8E,F4), V(6B,3E,58,99), V(DD,71,B9,27), \ V(B6,4F,E1,BE), V(17,AD,88,F0), V(66,AC,20,C9), V(B4,3A,CE,7D), \ V(18,4A,DF,63), V(82,31,1A,E5), V(60,33,51,97), V(45,7F,53,62), \ V(E0,77,64,B1), V(84,AE,6B,BB), V(1C,A0,81,FE), V(94,2B,08,F9), \ V(58,68,48,70), V(19,FD,45,8F), V(87,6C,DE,94), V(B7,F8,7B,52), \ V(23,D3,73,AB), V(E2,02,4B,72), V(57,8F,1F,E3), V(2A,AB,55,66), \ V(07,28,EB,B2), V(03,C2,B5,2F), V(9A,7B,C5,86), V(A5,08,37,D3), \ V(F2,87,28,30), V(B2,A5,BF,23), V(BA,6A,03,02), V(5C,82,16,ED), \ V(2B,1C,CF,8A), V(92,B4,79,A7), V(F0,F2,07,F3), V(A1,E2,69,4E), \ V(CD,F4,DA,65), V(D5,BE,05,06), V(1F,62,34,D1), V(8A,FE,A6,C4), \ V(9D,53,2E,34), V(A0,55,F3,A2), V(32,E1,8A,05), V(75,EB,F6,A4), \ V(39,EC,83,0B), V(AA,EF,60,40), V(06,9F,71,5E), V(51,10,6E,BD), \ V(F9,8A,21,3E), V(3D,06,DD,96), V(AE,05,3E,DD), V(46,BD,E6,4D), \ V(B5,8D,54,91), V(05,5D,C4,71), V(6F,D4,06,04), V(FF,15,50,60), \ V(24,FB,98,19), V(97,E9,BD,D6), V(CC,43,40,89), V(77,9E,D9,67), \ V(BD,42,E8,B0), V(88,8B,89,07), V(38,5B,19,E7), V(DB,EE,C8,79), \ V(47,0A,7C,A1), V(E9,0F,42,7C), V(C9,1E,84,F8), V(00,00,00,00), \ V(83,86,80,09), V(48,ED,2B,32), V(AC,70,11,1E), V(4E,72,5A,6C), \ V(FB,FF,0E,FD), V(56,38,85,0F), V(1E,D5,AE,3D), V(27,39,2D,36), \ V(64,D9,0F,0A), V(21,A6,5C,68), V(D1,54,5B,9B), V(3A,2E,36,24), \ V(B1,67,0A,0C), V(0F,E7,57,93), V(D2,96,EE,B4), V(9E,91,9B,1B), \ V(4F,C5,C0,80), V(A2,20,DC,61), V(69,4B,77,5A), V(16,1A,12,1C), \ V(0A,BA,93,E2), V(E5,2A,A0,C0), V(43,E0,22,3C), V(1D,17,1B,12), \ V(0B,0D,09,0E), V(AD,C7,8B,F2), V(B9,A8,B6,2D), V(C8,A9,1E,14), \ V(85,19,F1,57), V(4C,07,75,AF), V(BB,DD,99,EE), V(FD,60,7F,A3), \ V(9F,26,01,F7), V(BC,F5,72,5C), V(C5,3B,66,44), V(34,7E,FB,5B), \ V(76,29,43,8B), V(DC,C6,23,CB), V(68,FC,ED,B6), V(63,F1,E4,B8), \ V(CA,DC,31,D7), V(10,85,63,42), V(40,22,97,13), V(20,11,C6,84), \ V(7D,24,4A,85), V(F8,3D,BB,D2), V(11,32,F9,AE), V(6D,A1,29,C7), \ V(4B,2F,9E,1D), V(F3,30,B2,DC), V(EC,52,86,0D), V(D0,E3,C1,77), \ V(6C,16,B3,2B), V(99,B9,70,A9), V(FA,48,94,11), V(22,64,E9,47), \ V(C4,8C,FC,A8), V(1A,3F,F0,A0), V(D8,2C,7D,56), V(EF,90,33,22), \ V(C7,4E,49,87), V(C1,D1,38,D9), V(FE,A2,CA,8C), V(36,0B,D4,98), \ V(CF,81,F5,A6), V(28,DE,7A,A5), V(26,8E,B7,DA), V(A4,BF,AD,3F), \ V(E4,9D,3A,2C), V(0D,92,78,50), V(9B,CC,5F,6A), V(62,46,7E,54), \ V(C2,13,8D,F6), V(E8,B8,D8,90), V(5E,F7,39,2E), V(F5,AF,C3,82), \ V(BE,80,5D,9F), V(7C,93,D0,69), V(A9,2D,D5,6F), V(B3,12,25,CF), \ V(3B,99,AC,C8), V(A7,7D,18,10), V(6E,63,9C,E8), V(7B,BB,3B,DB), \ V(09,78,26,CD), V(F4,18,59,6E), V(01,B7,9A,EC), V(A8,9A,4F,83), \ V(65,6E,95,E6), V(7E,E6,FF,AA), V(08,CF,BC,21), V(E6,E8,15,EF), \ V(D9,9B,E7,BA), V(CE,36,6F,4A), V(D4,09,9F,EA), V(D6,7C,B0,29), \ V(AF,B2,A4,31), V(31,23,3F,2A), V(30,94,A5,C6), V(C0,66,A2,35), \ V(37,BC,4E,74), V(A6,CA,82,FC), V(B0,D0,90,E0), V(15,D8,A7,33), \ V(4A,98,04,F1), V(F7,DA,EC,41), V(0E,50,CD,7F), V(2F,F6,91,17), \ V(8D,D6,4D,76), V(4D,B0,EF,43), V(54,4D,AA,CC), V(DF,04,96,E4), \ V(E3,B5,D1,9E), V(1B,88,6A,4C), V(B8,1F,2C,C1), V(7F,51,65,46), \ V(04,EA,5E,9D), V(5D,35,8C,01), V(73,74,87,FA), V(2E,41,0B,FB), \ V(5A,1D,67,B3), V(52,D2,DB,92), V(33,56,10,E9), V(13,47,D6,6D), \ V(8C,61,D7,9A), V(7A,0C,A1,37), V(8E,14,F8,59), V(89,3C,13,EB), \ V(EE,27,A9,CE), V(35,C9,61,B7), V(ED,E5,1C,E1), V(3C,B1,47,7A), \ V(59,DF,D2,9C), V(3F,73,F2,55), V(79,CE,14,18), V(BF,37,C7,73), \ V(EA,CD,F7,53), V(5B,AA,FD,5F), V(14,6F,3D,DF), V(86,DB,44,78), \ V(81,F3,AF,CA), V(3E,C4,68,B9), V(2C,34,24,38), V(5F,40,A3,C2), \ V(72,C3,1D,16), V(0C,25,E2,BC), V(8B,49,3C,28), V(41,95,0D,FF), \ V(71,01,A8,39), V(DE,B3,0C,08), V(9C,E4,B4,D8), V(90,C1,56,64), \ V(61,84,CB,7B), V(70,B6,32,D5), V(74,5C,6C,48), V(42,57,B8,D0) #define V(a,b,c,d) 0x##a##b##c##d static const uint32_t RT0[256] = { RT }; #undef V #if !defined(MBEDTLS_AES_FEWER_TABLES) #define V(a,b,c,d) 0x##b##c##d##a static const uint32_t RT1[256] = { RT }; #undef V #define V(a,b,c,d) 0x##c##d##a##b static const uint32_t RT2[256] = { RT }; #undef V #define V(a,b,c,d) 0x##d##a##b##c static const uint32_t RT3[256] = { RT }; #undef V #endif /* !MBEDTLS_AES_FEWER_TABLES */ #undef RT /* * Round constants */ static const uint32_t RCON[10] = { 0x00000001, 0x00000002, 0x00000004, 0x00000008, 0x00000010, 0x00000020, 0x00000040, 0x00000080, 0x0000001B, 0x00000036 }; #else /* MBEDTLS_AES_ROM_TABLES */ /* * Forward S-box & tables */ static unsigned char FSb[256]; static uint32_t FT0[256]; #if !defined(MBEDTLS_AES_FEWER_TABLES) static uint32_t FT1[256]; static uint32_t FT2[256]; static uint32_t FT3[256]; #endif /* !MBEDTLS_AES_FEWER_TABLES */ /* * Reverse S-box & tables */ static unsigned char RSb[256]; static uint32_t RT0[256]; #if !defined(MBEDTLS_AES_FEWER_TABLES) static uint32_t RT1[256]; static uint32_t RT2[256]; static uint32_t RT3[256]; #endif /* !MBEDTLS_AES_FEWER_TABLES */ /* * Round constants */ static uint32_t RCON[10]; /* * Tables generation code */ #define ROTL8(x) ( ( (x) << 8 ) & 0xFFFFFFFF ) | ( (x) >> 24 ) #define XTIME(x) ( ( (x) << 1 ) ^ ( ( (x) & 0x80 ) ? 0x1B : 0x00 ) ) #define MUL(x,y) ( ( (x) && (y) ) ? pow[(log[(x)]+log[(y)]) % 255] : 0 ) static int aes_init_done; static dontinline void aes_gen_tables( void ) { int i, x, y, z; int pow[256]; int log[256]; /* * compute pow and log tables over GF(2^8) */ for( i = 0, x = 1; i < 256; i++ ) { pow[i] = x; log[x] = i; x = ( x ^ XTIME( x ) ) & 0xFF; } /* * calculate the round constants */ for( i = 0, x = 1; i < 10; i++ ) { RCON[i] = (uint32_t) x; x = XTIME( x ) & 0xFF; } /* * generate the forward and reverse S-boxes */ FSb[0x00] = 0x63; RSb[0x63] = 0x00; for( i = 1; i < 256; i++ ) { x = pow[255 - log[i]]; y = x; y = ( ( y << 1 ) | ( y >> 7 ) ) & 0xFF; x ^= y; y = ( ( y << 1 ) | ( y >> 7 ) ) & 0xFF; x ^= y; y = ( ( y << 1 ) | ( y >> 7 ) ) & 0xFF; x ^= y; y = ( ( y << 1 ) | ( y >> 7 ) ) & 0xFF; x ^= y ^ 0x63; FSb[i] = (unsigned char) x; RSb[x] = (unsigned char) i; } /* * generate the forward and reverse tables */ for( i = 0; i < 256; i++ ) { x = FSb[i]; y = XTIME( x ) & 0xFF; z = ( y ^ x ) & 0xFF; FT0[i] = ( (uint32_t) y ) ^ ( (uint32_t) x << 8 ) ^ ( (uint32_t) x << 16 ) ^ ( (uint32_t) z << 24 ); #if !defined(MBEDTLS_AES_FEWER_TABLES) FT1[i] = ROTL8( FT0[i] ); FT2[i] = ROTL8( FT1[i] ); FT3[i] = ROTL8( FT2[i] ); #endif /* !MBEDTLS_AES_FEWER_TABLES */ x = RSb[i]; RT0[i] = ( (uint32_t) MUL( 0x0E, x ) ) ^ ( (uint32_t) MUL( 0x09, x ) << 8 ) ^ ( (uint32_t) MUL( 0x0D, x ) << 16 ) ^ ( (uint32_t) MUL( 0x0B, x ) << 24 ); #if !defined(MBEDTLS_AES_FEWER_TABLES) RT1[i] = ROTL8( RT0[i] ); RT2[i] = ROTL8( RT1[i] ); RT3[i] = ROTL8( RT2[i] ); #endif /* !MBEDTLS_AES_FEWER_TABLES */ } } #undef ROTL8 #endif /* MBEDTLS_AES_ROM_TABLES */ #if defined(MBEDTLS_AES_FEWER_TABLES) #define ROTL8(x) ( (uint32_t)( ( x ) << 8 ) + (uint32_t)( ( x ) >> 24 ) ) #define ROTL16(x) ( (uint32_t)( ( x ) << 16 ) + (uint32_t)( ( x ) >> 16 ) ) #define ROTL24(x) ( (uint32_t)( ( x ) << 24 ) + (uint32_t)( ( x ) >> 8 ) ) #define AES_RT0(idx) RT0[idx] #define AES_RT1(idx) ROTL8( RT0[idx] ) #define AES_RT2(idx) ROTL16( RT0[idx] ) #define AES_RT3(idx) ROTL24( RT0[idx] ) #define AES_FT0(idx) FT0[idx] #define AES_FT1(idx) ROTL8( FT0[idx] ) #define AES_FT2(idx) ROTL16( FT0[idx] ) #define AES_FT3(idx) ROTL24( FT0[idx] ) #else /* MBEDTLS_AES_FEWER_TABLES */ #define AES_RT0(idx) RT0[idx] #define AES_RT1(idx) RT1[idx] #define AES_RT2(idx) RT2[idx] #define AES_RT3(idx) RT3[idx] #define AES_FT0(idx) FT0[idx] #define AES_FT1(idx) FT1[idx] #define AES_FT2(idx) FT2[idx] #define AES_FT3(idx) FT3[idx] #endif /* MBEDTLS_AES_FEWER_TABLES */ void mbedtls_aes_init( mbedtls_aes_context *ctx ) { AES_VALIDATE( ctx != NULL ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_aes_context ) ); } void mbedtls_aes_free( mbedtls_aes_context *ctx ) { if( ctx == NULL ) return; mbedtls_platform_zeroize( ctx, sizeof( mbedtls_aes_context ) ); } #if defined(MBEDTLS_CIPHER_MODE_XTS) void mbedtls_aes_xts_init( mbedtls_aes_xts_context *ctx ) { AES_VALIDATE( ctx != NULL ); mbedtls_aes_init( &ctx->crypt ); mbedtls_aes_init( &ctx->tweak ); } void mbedtls_aes_xts_free( mbedtls_aes_xts_context *ctx ) { if( ctx == NULL ) return; mbedtls_aes_free( &ctx->crypt ); mbedtls_aes_free( &ctx->tweak ); } #endif /* MBEDTLS_CIPHER_MODE_XTS */ /* * AES key schedule (encryption) */ #if !defined(MBEDTLS_AES_SETKEY_ENC_ALT) int mbedtls_aes_setkey_enc( mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits ) { unsigned int i; uint32_t *RK; AES_VALIDATE_RET( ctx != NULL ); AES_VALIDATE_RET( key != NULL ); switch( keybits ) { case 128: ctx->nr = 10; break; case 192: ctx->nr = 12; break; case 256: ctx->nr = 14; break; default : return( MBEDTLS_ERR_AES_INVALID_KEY_LENGTH ); } #if !defined(MBEDTLS_AES_ROM_TABLES) if( aes_init_done == 0 ) { aes_gen_tables(); aes_init_done = 1; } #endif #if defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_PADLOCK_ALIGN16) if( aes_padlock_ace == -1 ) aes_padlock_ace = mbedtls_padlock_has_support( MBEDTLS_PADLOCK_ACE ); if( aes_padlock_ace ) ctx->rk = RK = MBEDTLS_PADLOCK_ALIGN16( ctx->buf ); else #endif ctx->rk = RK = ctx->buf; #if defined(MBEDTLS_AESNI_C) && defined(MBEDTLS_HAVE_X86_64) if( X86_HAVE( AES ) ) return( mbedtls_aesni_setkey_enc( (unsigned char *) ctx->rk, key, keybits ) ); #endif for( i = 0; i < ( keybits >> 5 ); i++ ) { GET_UINT32_LE( RK[i], key, i << 2 ); } switch( ctx->nr ) { case 10: for( i = 0; i < 10; i++, RK += 4 ) { RK[4] = RK[0] ^ RCON[i] ^ ( (uint32_t) FSb[ ( RK[3] >> 8 ) & 0xFF ] ) ^ ( (uint32_t) FSb[ ( RK[3] >> 16 ) & 0xFF ] << 8 ) ^ ( (uint32_t) FSb[ ( RK[3] >> 24 ) & 0xFF ] << 16 ) ^ ( (uint32_t) FSb[ ( RK[3] ) & 0xFF ] << 24 ); RK[5] = RK[1] ^ RK[4]; RK[6] = RK[2] ^ RK[5]; RK[7] = RK[3] ^ RK[6]; } break; case 12: for( i = 0; i < 8; i++, RK += 6 ) { RK[6] = RK[0] ^ RCON[i] ^ ( (uint32_t) FSb[ ( RK[5] >> 8 ) & 0xFF ] ) ^ ( (uint32_t) FSb[ ( RK[5] >> 16 ) & 0xFF ] << 8 ) ^ ( (uint32_t) FSb[ ( RK[5] >> 24 ) & 0xFF ] << 16 ) ^ ( (uint32_t) FSb[ ( RK[5] ) & 0xFF ] << 24 ); RK[7] = RK[1] ^ RK[6]; RK[8] = RK[2] ^ RK[7]; RK[9] = RK[3] ^ RK[8]; RK[10] = RK[4] ^ RK[9]; RK[11] = RK[5] ^ RK[10]; } break; case 14: for( i = 0; i < 7; i++, RK += 8 ) { RK[8] = RK[0] ^ RCON[i] ^ ( (uint32_t) FSb[ ( RK[7] >> 8 ) & 0xFF ] ) ^ ( (uint32_t) FSb[ ( RK[7] >> 16 ) & 0xFF ] << 8 ) ^ ( (uint32_t) FSb[ ( RK[7] >> 24 ) & 0xFF ] << 16 ) ^ ( (uint32_t) FSb[ ( RK[7] ) & 0xFF ] << 24 ); RK[9] = RK[1] ^ RK[8]; RK[10] = RK[2] ^ RK[9]; RK[11] = RK[3] ^ RK[10]; RK[12] = RK[4] ^ ( (uint32_t) FSb[ ( RK[11] ) & 0xFF ] ) ^ ( (uint32_t) FSb[ ( RK[11] >> 8 ) & 0xFF ] << 8 ) ^ ( (uint32_t) FSb[ ( RK[11] >> 16 ) & 0xFF ] << 16 ) ^ ( (uint32_t) FSb[ ( RK[11] >> 24 ) & 0xFF ] << 24 ); RK[13] = RK[5] ^ RK[12]; RK[14] = RK[6] ^ RK[13]; RK[15] = RK[7] ^ RK[14]; } break; } return( 0 ); } #endif /* !MBEDTLS_AES_SETKEY_ENC_ALT */ /* * AES key schedule (decryption) */ #if !defined(MBEDTLS_AES_SETKEY_DEC_ALT) int mbedtls_aes_setkey_dec( mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits ) { int i, j, ret; mbedtls_aes_context cty; uint32_t *RK; uint32_t *SK; AES_VALIDATE_RET( ctx != NULL ); AES_VALIDATE_RET( key != NULL ); mbedtls_aes_init( &cty ); #if defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_PADLOCK_ALIGN16) if( aes_padlock_ace == -1 ) aes_padlock_ace = mbedtls_padlock_has_support( MBEDTLS_PADLOCK_ACE ); if( aes_padlock_ace ) ctx->rk = RK = MBEDTLS_PADLOCK_ALIGN16( ctx->buf ); else #endif ctx->rk = RK = ctx->buf; /* Also checks keybits */ if( ( ret = mbedtls_aes_setkey_enc( &cty, key, keybits ) ) != 0 ) goto exit; ctx->nr = cty.nr; #if defined(MBEDTLS_AESNI_C) && defined(MBEDTLS_HAVE_X86_64) if( X86_HAVE( AES ) ) { mbedtls_aesni_inverse_key( (unsigned char *) ctx->rk, (const unsigned char *) cty.rk, ctx->nr ); goto exit; } #endif SK = cty.rk + cty.nr * 4; *RK++ = *SK++; *RK++ = *SK++; *RK++ = *SK++; *RK++ = *SK++; for( i = ctx->nr - 1, SK -= 8; i > 0; i--, SK -= 8 ) { for( j = 0; j < 4; j++, SK++ ) { *RK++ = AES_RT0( FSb[ ( *SK ) & 0xFF ] ) ^ AES_RT1( FSb[ ( *SK >> 8 ) & 0xFF ] ) ^ AES_RT2( FSb[ ( *SK >> 16 ) & 0xFF ] ) ^ AES_RT3( FSb[ ( *SK >> 24 ) & 0xFF ] ); } } *RK++ = *SK++; *RK++ = *SK++; *RK++ = *SK++; *RK++ = *SK++; exit: mbedtls_aes_free( &cty ); return( ret ); } #endif /* !MBEDTLS_AES_SETKEY_DEC_ALT */ #if defined(MBEDTLS_CIPHER_MODE_XTS) static int mbedtls_aes_xts_decode_keys( const unsigned char *key, unsigned int keybits, const unsigned char **key1, unsigned int *key1bits, const unsigned char **key2, unsigned int *key2bits ) { const unsigned int half_keybits = keybits / 2; const unsigned int half_keybytes = half_keybits / 8; switch( keybits ) { case 256: break; case 512: break; default : return( MBEDTLS_ERR_AES_INVALID_KEY_LENGTH ); } *key1bits = half_keybits; *key2bits = half_keybits; *key1 = &key[0]; *key2 = &key[half_keybytes]; return 0; } int mbedtls_aes_xts_setkey_enc( mbedtls_aes_xts_context *ctx, const unsigned char *key, unsigned int keybits) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; const unsigned char *key1, *key2; unsigned int key1bits, key2bits; AES_VALIDATE_RET( ctx != NULL ); AES_VALIDATE_RET( key != NULL ); ret = mbedtls_aes_xts_decode_keys( key, keybits, &key1, &key1bits, &key2, &key2bits ); if( ret != 0 ) return( ret ); /* Set the tweak key. Always set tweak key for the encryption mode. */ ret = mbedtls_aes_setkey_enc( &ctx->tweak, key2, key2bits ); if( ret != 0 ) return( ret ); /* Set crypt key for encryption. */ return mbedtls_aes_setkey_enc( &ctx->crypt, key1, key1bits ); } int mbedtls_aes_xts_setkey_dec( mbedtls_aes_xts_context *ctx, const unsigned char *key, unsigned int keybits) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; const unsigned char *key1, *key2; unsigned int key1bits, key2bits; AES_VALIDATE_RET( ctx != NULL ); AES_VALIDATE_RET( key != NULL ); ret = mbedtls_aes_xts_decode_keys( key, keybits, &key1, &key1bits, &key2, &key2bits ); if( ret != 0 ) return( ret ); /* Set the tweak key. Always set tweak key for encryption. */ ret = mbedtls_aes_setkey_enc( &ctx->tweak, key2, key2bits ); if( ret != 0 ) return( ret ); /* Set crypt key for decryption. */ return mbedtls_aes_setkey_dec( &ctx->crypt, key1, key1bits ); } #endif /* MBEDTLS_CIPHER_MODE_XTS */ #define AES_FROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3) \ do \ { \ (X0) = *RK++ ^ AES_FT0( ( (Y0) ) & 0xFF ) ^ \ AES_FT1( ( (Y1) >> 8 ) & 0xFF ) ^ \ AES_FT2( ( (Y2) >> 16 ) & 0xFF ) ^ \ AES_FT3( ( (Y3) >> 24 ) & 0xFF ); \ (X1) = *RK++ ^ AES_FT0( ( (Y1) ) & 0xFF ) ^ \ AES_FT1( ( (Y2) >> 8 ) & 0xFF ) ^ \ AES_FT2( ( (Y3) >> 16 ) & 0xFF ) ^ \ AES_FT3( ( (Y0) >> 24 ) & 0xFF ); \ (X2) = *RK++ ^ AES_FT0( ( (Y2) ) & 0xFF ) ^ \ AES_FT1( ( (Y3) >> 8 ) & 0xFF ) ^ \ AES_FT2( ( (Y0) >> 16 ) & 0xFF ) ^ \ AES_FT3( ( (Y1) >> 24 ) & 0xFF ); \ (X3) = *RK++ ^ AES_FT0( ( (Y3) ) & 0xFF ) ^ \ AES_FT1( ( (Y0) >> 8 ) & 0xFF ) ^ \ AES_FT2( ( (Y1) >> 16 ) & 0xFF ) ^ \ AES_FT3( ( (Y2) >> 24 ) & 0xFF ); \ } while( 0 ) #define AES_RROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3) \ do \ { \ (X0) = *RK++ ^ AES_RT0( ( (Y0) ) & 0xFF ) ^ \ AES_RT1( ( (Y3) >> 8 ) & 0xFF ) ^ \ AES_RT2( ( (Y2) >> 16 ) & 0xFF ) ^ \ AES_RT3( ( (Y1) >> 24 ) & 0xFF ); \ (X1) = *RK++ ^ AES_RT0( ( (Y1) ) & 0xFF ) ^ \ AES_RT1( ( (Y0) >> 8 ) & 0xFF ) ^ \ AES_RT2( ( (Y3) >> 16 ) & 0xFF ) ^ \ AES_RT3( ( (Y2) >> 24 ) & 0xFF ); \ (X2) = *RK++ ^ AES_RT0( ( (Y2) ) & 0xFF ) ^ \ AES_RT1( ( (Y1) >> 8 ) & 0xFF ) ^ \ AES_RT2( ( (Y0) >> 16 ) & 0xFF ) ^ \ AES_RT3( ( (Y3) >> 24 ) & 0xFF ); \ (X3) = *RK++ ^ AES_RT0( ( (Y3) ) & 0xFF ) ^ \ AES_RT1( ( (Y2) >> 8 ) & 0xFF ) ^ \ AES_RT2( ( (Y1) >> 16 ) & 0xFF ) ^ \ AES_RT3( ( (Y0) >> 24 ) & 0xFF ); \ } while( 0 ) /* * AES-ECB block encryption */ #if !defined(MBEDTLS_AES_ENCRYPT_ALT) int mbedtls_internal_aes_encrypt( mbedtls_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ) { int i; uint32_t *RK = ctx->rk; struct { uint32_t X[4]; uint32_t Y[4]; } t; GET_UINT32_LE( t.X[0], input, 0 ); t.X[0] ^= *RK++; GET_UINT32_LE( t.X[1], input, 4 ); t.X[1] ^= *RK++; GET_UINT32_LE( t.X[2], input, 8 ); t.X[2] ^= *RK++; GET_UINT32_LE( t.X[3], input, 12 ); t.X[3] ^= *RK++; for( i = ( ctx->nr >> 1 ) - 1; i > 0; i-- ) { AES_FROUND( t.Y[0], t.Y[1], t.Y[2], t.Y[3], t.X[0], t.X[1], t.X[2], t.X[3] ); AES_FROUND( t.X[0], t.X[1], t.X[2], t.X[3], t.Y[0], t.Y[1], t.Y[2], t.Y[3] ); } AES_FROUND( t.Y[0], t.Y[1], t.Y[2], t.Y[3], t.X[0], t.X[1], t.X[2], t.X[3] ); t.X[0] = *RK++ ^ \ ( (uint32_t) FSb[ ( t.Y[0] ) & 0xFF ] ) ^ ( (uint32_t) FSb[ ( t.Y[1] >> 8 ) & 0xFF ] << 8 ) ^ ( (uint32_t) FSb[ ( t.Y[2] >> 16 ) & 0xFF ] << 16 ) ^ ( (uint32_t) FSb[ ( t.Y[3] >> 24 ) & 0xFF ] << 24 ); t.X[1] = *RK++ ^ \ ( (uint32_t) FSb[ ( t.Y[1] ) & 0xFF ] ) ^ ( (uint32_t) FSb[ ( t.Y[2] >> 8 ) & 0xFF ] << 8 ) ^ ( (uint32_t) FSb[ ( t.Y[3] >> 16 ) & 0xFF ] << 16 ) ^ ( (uint32_t) FSb[ ( t.Y[0] >> 24 ) & 0xFF ] << 24 ); t.X[2] = *RK++ ^ \ ( (uint32_t) FSb[ ( t.Y[2] ) & 0xFF ] ) ^ ( (uint32_t) FSb[ ( t.Y[3] >> 8 ) & 0xFF ] << 8 ) ^ ( (uint32_t) FSb[ ( t.Y[0] >> 16 ) & 0xFF ] << 16 ) ^ ( (uint32_t) FSb[ ( t.Y[1] >> 24 ) & 0xFF ] << 24 ); t.X[3] = *RK++ ^ \ ( (uint32_t) FSb[ ( t.Y[3] ) & 0xFF ] ) ^ ( (uint32_t) FSb[ ( t.Y[0] >> 8 ) & 0xFF ] << 8 ) ^ ( (uint32_t) FSb[ ( t.Y[1] >> 16 ) & 0xFF ] << 16 ) ^ ( (uint32_t) FSb[ ( t.Y[2] >> 24 ) & 0xFF ] << 24 ); PUT_UINT32_LE( t.X[0], output, 0 ); PUT_UINT32_LE( t.X[1], output, 4 ); PUT_UINT32_LE( t.X[2], output, 8 ); PUT_UINT32_LE( t.X[3], output, 12 ); mbedtls_platform_zeroize( &t, sizeof( t ) ); return( 0 ); } #endif /* !MBEDTLS_AES_ENCRYPT_ALT */ /* * AES-ECB block decryption */ #if !defined(MBEDTLS_AES_DECRYPT_ALT) int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ) { int i; uint32_t *RK = ctx->rk; struct { uint32_t X[4]; uint32_t Y[4]; } t; GET_UINT32_LE( t.X[0], input, 0 ); t.X[0] ^= *RK++; GET_UINT32_LE( t.X[1], input, 4 ); t.X[1] ^= *RK++; GET_UINT32_LE( t.X[2], input, 8 ); t.X[2] ^= *RK++; GET_UINT32_LE( t.X[3], input, 12 ); t.X[3] ^= *RK++; for( i = ( ctx->nr >> 1 ) - 1; i > 0; i-- ) { AES_RROUND( t.Y[0], t.Y[1], t.Y[2], t.Y[3], t.X[0], t.X[1], t.X[2], t.X[3] ); AES_RROUND( t.X[0], t.X[1], t.X[2], t.X[3], t.Y[0], t.Y[1], t.Y[2], t.Y[3] ); } AES_RROUND( t.Y[0], t.Y[1], t.Y[2], t.Y[3], t.X[0], t.X[1], t.X[2], t.X[3] ); t.X[0] = *RK++ ^ \ ( (uint32_t) RSb[ ( t.Y[0] ) & 0xFF ] ) ^ ( (uint32_t) RSb[ ( t.Y[3] >> 8 ) & 0xFF ] << 8 ) ^ ( (uint32_t) RSb[ ( t.Y[2] >> 16 ) & 0xFF ] << 16 ) ^ ( (uint32_t) RSb[ ( t.Y[1] >> 24 ) & 0xFF ] << 24 ); t.X[1] = *RK++ ^ \ ( (uint32_t) RSb[ ( t.Y[1] ) & 0xFF ] ) ^ ( (uint32_t) RSb[ ( t.Y[0] >> 8 ) & 0xFF ] << 8 ) ^ ( (uint32_t) RSb[ ( t.Y[3] >> 16 ) & 0xFF ] << 16 ) ^ ( (uint32_t) RSb[ ( t.Y[2] >> 24 ) & 0xFF ] << 24 ); t.X[2] = *RK++ ^ \ ( (uint32_t) RSb[ ( t.Y[2] ) & 0xFF ] ) ^ ( (uint32_t) RSb[ ( t.Y[1] >> 8 ) & 0xFF ] << 8 ) ^ ( (uint32_t) RSb[ ( t.Y[0] >> 16 ) & 0xFF ] << 16 ) ^ ( (uint32_t) RSb[ ( t.Y[3] >> 24 ) & 0xFF ] << 24 ); t.X[3] = *RK++ ^ \ ( (uint32_t) RSb[ ( t.Y[3] ) & 0xFF ] ) ^ ( (uint32_t) RSb[ ( t.Y[2] >> 8 ) & 0xFF ] << 8 ) ^ ( (uint32_t) RSb[ ( t.Y[1] >> 16 ) & 0xFF ] << 16 ) ^ ( (uint32_t) RSb[ ( t.Y[0] >> 24 ) & 0xFF ] << 24 ); PUT_UINT32_LE( t.X[0], output, 0 ); PUT_UINT32_LE( t.X[1], output, 4 ); PUT_UINT32_LE( t.X[2], output, 8 ); PUT_UINT32_LE( t.X[3], output, 12 ); mbedtls_platform_zeroize( &t, sizeof( t ) ); return( 0 ); } #endif /* !MBEDTLS_AES_DECRYPT_ALT */ /* * AES-ECB block encryption/decryption */ int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx, int mode, const unsigned char input[16], unsigned char output[16] ) { AES_VALIDATE_RET( ctx != NULL ); AES_VALIDATE_RET( input != NULL ); AES_VALIDATE_RET( output != NULL ); AES_VALIDATE_RET( mode == MBEDTLS_AES_ENCRYPT || mode == MBEDTLS_AES_DECRYPT ); #if defined(MBEDTLS_AESNI_C) && defined(MBEDTLS_HAVE_X86_64) if( X86_HAVE( AES ) ) return( mbedtls_aesni_crypt_ecb( ctx, mode, input, output ) ); #endif #if defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_HAVE_X86) if( aes_padlock_ace ) { if( mbedtls_padlock_xcryptecb( ctx, mode, input, output ) == 0 ) return( 0 ); // If padlock data misaligned, we just fall back to // unaccelerated mode // } #endif if( mode == MBEDTLS_AES_ENCRYPT ) return( mbedtls_internal_aes_encrypt( ctx, input, output ) ); else return( mbedtls_internal_aes_decrypt( ctx, input, output ) ); } #if defined(MBEDTLS_CIPHER_MODE_CBC) /* * AES-CBC buffer encryption/decryption */ int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx, int mode, size_t length, unsigned char iv[16], const unsigned char *input, unsigned char *output ) { int i; unsigned char temp[16]; AES_VALIDATE_RET( ctx != NULL ); AES_VALIDATE_RET( mode == MBEDTLS_AES_ENCRYPT || mode == MBEDTLS_AES_DECRYPT ); AES_VALIDATE_RET( iv != NULL ); AES_VALIDATE_RET( input != NULL ); AES_VALIDATE_RET( output != NULL ); if( length % 16 ) return( MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH ); #if defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_HAVE_X86) if( aes_padlock_ace ) { if( mbedtls_padlock_xcryptcbc( ctx, mode, length, iv, input, output ) == 0 ) return( 0 ); // If padlock data misaligned, we just fall back to // unaccelerated mode // } #endif if( mode == MBEDTLS_AES_DECRYPT ) { while( length > 0 ) { memcpy( temp, input, 16 ); mbedtls_aes_crypt_ecb( ctx, mode, input, output ); for( i = 0; i < 16; i++ ) output[i] = (unsigned char)( output[i] ^ iv[i] ); memcpy( iv, temp, 16 ); input += 16; output += 16; length -= 16; } } else { while( length > 0 ) { for( i = 0; i < 16; i++ ) output[i] = (unsigned char)( input[i] ^ iv[i] ); mbedtls_aes_crypt_ecb( ctx, mode, output, output ); memcpy( iv, output, 16 ); input += 16; output += 16; length -= 16; } } return( 0 ); } #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_CIPHER_MODE_XTS) typedef unsigned char mbedtls_be128[16]; /* * GF(2^128) multiplication function * * This function multiplies a field element by x in the polynomial field * representation. It uses 64-bit word operations to gain speed but compensates * for machine endianess and hence works correctly on both big and little * endian machines. */ static void mbedtls_gf128mul_x_ble( unsigned char r[16], const unsigned char x[16] ) { uint64_t a, b, ra, rb; a = READ64LE(x + 0); b = READ64LE(x + 8); ra = ( a << 1 ) ^ 0x0087 >> ( 8 - ( ( b >> 63 ) << 3 ) ); rb = ( a >> 63 ) | ( b << 1 ); WRITE64LE(r + 0, ra ); WRITE64LE(r + 8, rb ); } /* * AES-XTS buffer encryption/decryption */ int mbedtls_aes_crypt_xts( mbedtls_aes_xts_context *ctx, int mode, size_t length, const unsigned char data_unit[16], const unsigned char *input, unsigned char *output ) { int ret = MBEDTLS_ERR_THIS_CORRUPTION; size_t blocks = length / 16; size_t leftover = length % 16; unsigned char tweak[16]; unsigned char prev_tweak[16]; unsigned char tmp[16]; AES_VALIDATE_RET( ctx != NULL ); AES_VALIDATE_RET( mode == MBEDTLS_AES_ENCRYPT || mode == MBEDTLS_AES_DECRYPT ); AES_VALIDATE_RET( data_unit != NULL ); AES_VALIDATE_RET( input != NULL ); AES_VALIDATE_RET( output != NULL ); /* Data units must be at least 16 bytes long. */ if( length < 16 ) return MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH; /* NIST SP 800-38E disallows data units larger than 2**20 blocks. */ if( length > ( 1 << 20 ) * 16 ) return MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH; /* Compute the tweak. */ ret = mbedtls_aes_crypt_ecb( &ctx->tweak, MBEDTLS_AES_ENCRYPT, data_unit, tweak ); if( ret != 0 ) return( ret ); while( blocks-- ) { size_t i; if( leftover && ( mode == MBEDTLS_AES_DECRYPT ) && blocks == 0 ) { /* We are on the last block in a decrypt operation that has * leftover bytes, so we need to use the next tweak for this block, * and this tweak for the lefover bytes. Save the current tweak for * the leftovers and then update the current tweak for use on this, * the last full block. */ memcpy( prev_tweak, tweak, sizeof( tweak ) ); mbedtls_gf128mul_x_ble( tweak, tweak ); } for( i = 0; i < 16; i++ ) tmp[i] = input[i] ^ tweak[i]; ret = mbedtls_aes_crypt_ecb( &ctx->crypt, mode, tmp, tmp ); if( ret != 0 ) return( ret ); for( i = 0; i < 16; i++ ) output[i] = tmp[i] ^ tweak[i]; /* Update the tweak for the next block. */ mbedtls_gf128mul_x_ble( tweak, tweak ); output += 16; input += 16; } if( leftover ) { /* If we are on the leftover bytes in a decrypt operation, we need to * use the previous tweak for these bytes (as saved in prev_tweak). */ unsigned char *t = mode == MBEDTLS_AES_DECRYPT ? prev_tweak : tweak; /* We are now on the final part of the data unit, which doesn't divide * evenly by 16. It's time for ciphertext stealing. */ size_t i; unsigned char *prev_output = output - 16; /* Copy ciphertext bytes from the previous block to our output for each * byte of cyphertext we won't steal. At the same time, copy the * remainder of the input for this final round (since the loop bounds * are the same). */ for( i = 0; i < leftover; i++ ) { output[i] = prev_output[i]; tmp[i] = input[i] ^ t[i]; } /* Copy ciphertext bytes from the previous block for input in this * round. */ for( ; i < 16; i++ ) tmp[i] = prev_output[i] ^ t[i]; ret = mbedtls_aes_crypt_ecb( &ctx->crypt, mode, tmp, tmp ); if( ret != 0 ) return ret; /* Write the result back to the previous block, overriding the previous * output we copied. */ for( i = 0; i < 16; i++ ) prev_output[i] = tmp[i] ^ t[i]; } return( 0 ); } #endif /* MBEDTLS_CIPHER_MODE_XTS */ #if defined(MBEDTLS_CIPHER_MODE_CFB) /* * AES-CFB128 buffer encryption/decryption */ int mbedtls_aes_crypt_cfb128( mbedtls_aes_context *ctx, int mode, size_t length, size_t *iv_off, unsigned char iv[16], const unsigned char *input, unsigned char *output ) { int c; size_t n; AES_VALIDATE_RET( ctx != NULL ); AES_VALIDATE_RET( mode == MBEDTLS_AES_ENCRYPT || mode == MBEDTLS_AES_DECRYPT ); AES_VALIDATE_RET( iv_off != NULL ); AES_VALIDATE_RET( iv != NULL ); AES_VALIDATE_RET( input != NULL ); AES_VALIDATE_RET( output != NULL ); n = *iv_off; if( n > 15 ) return( MBEDTLS_ERR_AES_BAD_INPUT_DATA ); if( mode == MBEDTLS_AES_DECRYPT ) { while( length-- ) { if( n == 0 ) mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, iv, iv ); c = *input++; *output++ = (unsigned char)( c ^ iv[n] ); iv[n] = (unsigned char) c; n = ( n + 1 ) & 0x0F; } } else { while( length-- ) { if( n == 0 ) mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, iv, iv ); iv[n] = *output++ = (unsigned char)( iv[n] ^ *input++ ); n = ( n + 1 ) & 0x0F; } } *iv_off = n; return( 0 ); } /* * AES-CFB8 buffer encryption/decryption */ int mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx, int mode, size_t length, unsigned char iv[16], const unsigned char *input, unsigned char *output ) { unsigned char c; unsigned char ov[17]; AES_VALIDATE_RET( ctx != NULL ); AES_VALIDATE_RET( mode == MBEDTLS_AES_ENCRYPT || mode == MBEDTLS_AES_DECRYPT ); AES_VALIDATE_RET( iv != NULL ); AES_VALIDATE_RET( input != NULL ); AES_VALIDATE_RET( output != NULL ); while( length-- ) { memcpy( ov, iv, 16 ); mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, iv, iv ); if( mode == MBEDTLS_AES_DECRYPT ) ov[16] = *input; c = *output++ = (unsigned char)( iv[0] ^ *input++ ); if( mode == MBEDTLS_AES_ENCRYPT ) ov[16] = c; memcpy( iv, ov + 1, 16 ); } return( 0 ); } #endif /* MBEDTLS_CIPHER_MODE_CFB */ #if defined(MBEDTLS_CIPHER_MODE_OFB) /* * AES-OFB (Output Feedback Mode) buffer encryption/decryption */ int mbedtls_aes_crypt_ofb( mbedtls_aes_context *ctx, size_t length, size_t *iv_off, unsigned char iv[16], const unsigned char *input, unsigned char *output ) { int ret = 0; size_t n; AES_VALIDATE_RET( ctx != NULL ); AES_VALIDATE_RET( iv_off != NULL ); AES_VALIDATE_RET( iv != NULL ); AES_VALIDATE_RET( input != NULL ); AES_VALIDATE_RET( output != NULL ); n = *iv_off; if( n > 15 ) return( MBEDTLS_ERR_AES_BAD_INPUT_DATA ); while( length-- ) { if( n == 0 ) { ret = mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, iv, iv ); if( ret != 0 ) goto exit; } *output++ = *input++ ^ iv[n]; n = ( n + 1 ) & 0x0F; } *iv_off = n; exit: return( ret ); } #endif /* MBEDTLS_CIPHER_MODE_OFB */ #if defined(MBEDTLS_CIPHER_MODE_CTR) /* * AES-CTR buffer encryption/decryption */ int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx, size_t length, size_t *nc_off, unsigned char nonce_counter[16], unsigned char stream_block[16], const unsigned char *input, unsigned char *output ) { int c, i; size_t n; AES_VALIDATE_RET( ctx != NULL ); AES_VALIDATE_RET( nc_off != NULL ); AES_VALIDATE_RET( nonce_counter != NULL ); AES_VALIDATE_RET( stream_block != NULL ); AES_VALIDATE_RET( input != NULL ); AES_VALIDATE_RET( output != NULL ); n = *nc_off; if ( n > 0x0F ) return( MBEDTLS_ERR_AES_BAD_INPUT_DATA ); while( length-- ) { if( n == 0 ) { mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, nonce_counter, stream_block ); for( i = 16; i > 0; i-- ) if( ++nonce_counter[i - 1] != 0 ) break; } c = *input++; *output++ = (unsigned char)( c ^ stream_block[n] ); n = ( n + 1 ) & 0x0F; } *nc_off = n; return( 0 ); } #endif /* MBEDTLS_CIPHER_MODE_CTR */ #endif /* !MBEDTLS_AES_ALT */ #if defined(MBEDTLS_SELF_TEST) /* * AES test vectors from: * * http://csrc.nist.gov/archive/aes/rijndael/rijndael-vals.zip */ static const unsigned char aes_test_ecb_dec[3][16] = { { 0x44, 0x41, 0x6A, 0xC2, 0xD1, 0xF5, 0x3C, 0x58, 0x33, 0x03, 0x91, 0x7E, 0x6B, 0xE9, 0xEB, 0xE0 }, { 0x48, 0xE3, 0x1E, 0x9E, 0x25, 0x67, 0x18, 0xF2, 0x92, 0x29, 0x31, 0x9C, 0x19, 0xF1, 0x5B, 0xA4 }, { 0x05, 0x8C, 0xCF, 0xFD, 0xBB, 0xCB, 0x38, 0x2D, 0x1F, 0x6F, 0x56, 0x58, 0x5D, 0x8A, 0x4A, 0xDE } }; static const unsigned char aes_test_ecb_enc[3][16] = { { 0xC3, 0x4C, 0x05, 0x2C, 0xC0, 0xDA, 0x8D, 0x73, 0x45, 0x1A, 0xFE, 0x5F, 0x03, 0xBE, 0x29, 0x7F }, { 0xF3, 0xF6, 0x75, 0x2A, 0xE8, 0xD7, 0x83, 0x11, 0x38, 0xF0, 0x41, 0x56, 0x06, 0x31, 0xB1, 0x14 }, { 0x8B, 0x79, 0xEE, 0xCC, 0x93, 0xA0, 0xEE, 0x5D, 0xFF, 0x30, 0xB4, 0xEA, 0x21, 0x63, 0x6D, 0xA4 } }; #if defined(MBEDTLS_CIPHER_MODE_CBC) static const unsigned char aes_test_cbc_dec[3][16] = { { 0xFA, 0xCA, 0x37, 0xE0, 0xB0, 0xC8, 0x53, 0x73, 0xDF, 0x70, 0x6E, 0x73, 0xF7, 0xC9, 0xAF, 0x86 }, { 0x5D, 0xF6, 0x78, 0xDD, 0x17, 0xBA, 0x4E, 0x75, 0xB6, 0x17, 0x68, 0xC6, 0xAD, 0xEF, 0x7C, 0x7B }, { 0x48, 0x04, 0xE1, 0x81, 0x8F, 0xE6, 0x29, 0x75, 0x19, 0xA3, 0xE8, 0x8C, 0x57, 0x31, 0x04, 0x13 } }; static const unsigned char aes_test_cbc_enc[3][16] = { { 0x8A, 0x05, 0xFC, 0x5E, 0x09, 0x5A, 0xF4, 0x84, 0x8A, 0x08, 0xD3, 0x28, 0xD3, 0x68, 0x8E, 0x3D }, { 0x7B, 0xD9, 0x66, 0xD5, 0x3A, 0xD8, 0xC1, 0xBB, 0x85, 0xD2, 0xAD, 0xFA, 0xE8, 0x7B, 0xB1, 0x04 }, { 0xFE, 0x3C, 0x53, 0x65, 0x3E, 0x2F, 0x45, 0xB5, 0x6F, 0xCD, 0x88, 0xB2, 0xCC, 0x89, 0x8F, 0xF0 } }; #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_CIPHER_MODE_CFB) /* * AES-CFB128 test vectors from: * * http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf */ static const unsigned char aes_test_cfb128_key[3][32] = { { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C }, { 0x8E, 0x73, 0xB0, 0xF7, 0xDA, 0x0E, 0x64, 0x52, 0xC8, 0x10, 0xF3, 0x2B, 0x80, 0x90, 0x79, 0xE5, 0x62, 0xF8, 0xEA, 0xD2, 0x52, 0x2C, 0x6B, 0x7B }, { 0x60, 0x3D, 0xEB, 0x10, 0x15, 0xCA, 0x71, 0xBE, 0x2B, 0x73, 0xAE, 0xF0, 0x85, 0x7D, 0x77, 0x81, 0x1F, 0x35, 0x2C, 0x07, 0x3B, 0x61, 0x08, 0xD7, 0x2D, 0x98, 0x10, 0xA3, 0x09, 0x14, 0xDF, 0xF4 } }; static const unsigned char aes_test_cfb128_iv[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; static const unsigned char aes_test_cfb128_pt[64] = { 0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96, 0xE9, 0x3D, 0x7E, 0x11, 0x73, 0x93, 0x17, 0x2A, 0xAE, 0x2D, 0x8A, 0x57, 0x1E, 0x03, 0xAC, 0x9C, 0x9E, 0xB7, 0x6F, 0xAC, 0x45, 0xAF, 0x8E, 0x51, 0x30, 0xC8, 0x1C, 0x46, 0xA3, 0x5C, 0xE4, 0x11, 0xE5, 0xFB, 0xC1, 0x19, 0x1A, 0x0A, 0x52, 0xEF, 0xF6, 0x9F, 0x24, 0x45, 0xDF, 0x4F, 0x9B, 0x17, 0xAD, 0x2B, 0x41, 0x7B, 0xE6, 0x6C, 0x37, 0x10 }; static const unsigned char aes_test_cfb128_ct[3][64] = { { 0x3B, 0x3F, 0xD9, 0x2E, 0xB7, 0x2D, 0xAD, 0x20, 0x33, 0x34, 0x49, 0xF8, 0xE8, 0x3C, 0xFB, 0x4A, 0xC8, 0xA6, 0x45, 0x37, 0xA0, 0xB3, 0xA9, 0x3F, 0xCD, 0xE3, 0xCD, 0xAD, 0x9F, 0x1C, 0xE5, 0x8B, 0x26, 0x75, 0x1F, 0x67, 0xA3, 0xCB, 0xB1, 0x40, 0xB1, 0x80, 0x8C, 0xF1, 0x87, 0xA4, 0xF4, 0xDF, 0xC0, 0x4B, 0x05, 0x35, 0x7C, 0x5D, 0x1C, 0x0E, 0xEA, 0xC4, 0xC6, 0x6F, 0x9F, 0xF7, 0xF2, 0xE6 }, { 0xCD, 0xC8, 0x0D, 0x6F, 0xDD, 0xF1, 0x8C, 0xAB, 0x34, 0xC2, 0x59, 0x09, 0xC9, 0x9A, 0x41, 0x74, 0x67, 0xCE, 0x7F, 0x7F, 0x81, 0x17, 0x36, 0x21, 0x96, 0x1A, 0x2B, 0x70, 0x17, 0x1D, 0x3D, 0x7A, 0x2E, 0x1E, 0x8A, 0x1D, 0xD5, 0x9B, 0x88, 0xB1, 0xC8, 0xE6, 0x0F, 0xED, 0x1E, 0xFA, 0xC4, 0xC9, 0xC0, 0x5F, 0x9F, 0x9C, 0xA9, 0x83, 0x4F, 0xA0, 0x42, 0xAE, 0x8F, 0xBA, 0x58, 0x4B, 0x09, 0xFF }, { 0xDC, 0x7E, 0x84, 0xBF, 0xDA, 0x79, 0x16, 0x4B, 0x7E, 0xCD, 0x84, 0x86, 0x98, 0x5D, 0x38, 0x60, 0x39, 0xFF, 0xED, 0x14, 0x3B, 0x28, 0xB1, 0xC8, 0x32, 0x11, 0x3C, 0x63, 0x31, 0xE5, 0x40, 0x7B, 0xDF, 0x10, 0x13, 0x24, 0x15, 0xE5, 0x4B, 0x92, 0xA1, 0x3E, 0xD0, 0xA8, 0x26, 0x7A, 0xE2, 0xF9, 0x75, 0xA3, 0x85, 0x74, 0x1A, 0xB9, 0xCE, 0xF8, 0x20, 0x31, 0x62, 0x3D, 0x55, 0xB1, 0xE4, 0x71 } }; #endif /* MBEDTLS_CIPHER_MODE_CFB */ #if defined(MBEDTLS_CIPHER_MODE_OFB) /* * AES-OFB test vectors from: * * https://csrc.nist.gov/publications/detail/sp/800-38a/final */ static const unsigned char aes_test_ofb_key[3][32] = { { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C }, { 0x8E, 0x73, 0xB0, 0xF7, 0xDA, 0x0E, 0x64, 0x52, 0xC8, 0x10, 0xF3, 0x2B, 0x80, 0x90, 0x79, 0xE5, 0x62, 0xF8, 0xEA, 0xD2, 0x52, 0x2C, 0x6B, 0x7B }, { 0x60, 0x3D, 0xEB, 0x10, 0x15, 0xCA, 0x71, 0xBE, 0x2B, 0x73, 0xAE, 0xF0, 0x85, 0x7D, 0x77, 0x81, 0x1F, 0x35, 0x2C, 0x07, 0x3B, 0x61, 0x08, 0xD7, 0x2D, 0x98, 0x10, 0xA3, 0x09, 0x14, 0xDF, 0xF4 } }; static const unsigned char aes_test_ofb_iv[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; static const unsigned char aes_test_ofb_pt[64] = { 0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96, 0xE9, 0x3D, 0x7E, 0x11, 0x73, 0x93, 0x17, 0x2A, 0xAE, 0x2D, 0x8A, 0x57, 0x1E, 0x03, 0xAC, 0x9C, 0x9E, 0xB7, 0x6F, 0xAC, 0x45, 0xAF, 0x8E, 0x51, 0x30, 0xC8, 0x1C, 0x46, 0xA3, 0x5C, 0xE4, 0x11, 0xE5, 0xFB, 0xC1, 0x19, 0x1A, 0x0A, 0x52, 0xEF, 0xF6, 0x9F, 0x24, 0x45, 0xDF, 0x4F, 0x9B, 0x17, 0xAD, 0x2B, 0x41, 0x7B, 0xE6, 0x6C, 0x37, 0x10 }; static const unsigned char aes_test_ofb_ct[3][64] = { { 0x3B, 0x3F, 0xD9, 0x2E, 0xB7, 0x2D, 0xAD, 0x20, 0x33, 0x34, 0x49, 0xF8, 0xE8, 0x3C, 0xFB, 0x4A, 0x77, 0x89, 0x50, 0x8d, 0x16, 0x91, 0x8f, 0x03, 0xf5, 0x3c, 0x52, 0xda, 0xc5, 0x4e, 0xd8, 0x25, 0x97, 0x40, 0x05, 0x1e, 0x9c, 0x5f, 0xec, 0xf6, 0x43, 0x44, 0xf7, 0xa8, 0x22, 0x60, 0xed, 0xcc, 0x30, 0x4c, 0x65, 0x28, 0xf6, 0x59, 0xc7, 0x78, 0x66, 0xa5, 0x10, 0xd9, 0xc1, 0xd6, 0xae, 0x5e }, { 0xCD, 0xC8, 0x0D, 0x6F, 0xDD, 0xF1, 0x8C, 0xAB, 0x34, 0xC2, 0x59, 0x09, 0xC9, 0x9A, 0x41, 0x74, 0xfc, 0xc2, 0x8b, 0x8d, 0x4c, 0x63, 0x83, 0x7c, 0x09, 0xe8, 0x17, 0x00, 0xc1, 0x10, 0x04, 0x01, 0x8d, 0x9a, 0x9a, 0xea, 0xc0, 0xf6, 0x59, 0x6f, 0x55, 0x9c, 0x6d, 0x4d, 0xaf, 0x59, 0xa5, 0xf2, 0x6d, 0x9f, 0x20, 0x08, 0x57, 0xca, 0x6c, 0x3e, 0x9c, 0xac, 0x52, 0x4b, 0xd9, 0xac, 0xc9, 0x2a }, { 0xDC, 0x7E, 0x84, 0xBF, 0xDA, 0x79, 0x16, 0x4B, 0x7E, 0xCD, 0x84, 0x86, 0x98, 0x5D, 0x38, 0x60, 0x4f, 0xeb, 0xdc, 0x67, 0x40, 0xd2, 0x0b, 0x3a, 0xc8, 0x8f, 0x6a, 0xd8, 0x2a, 0x4f, 0xb0, 0x8d, 0x71, 0xab, 0x47, 0xa0, 0x86, 0xe8, 0x6e, 0xed, 0xf3, 0x9d, 0x1c, 0x5b, 0xba, 0x97, 0xc4, 0x08, 0x01, 0x26, 0x14, 0x1d, 0x67, 0xf3, 0x7b, 0xe8, 0x53, 0x8f, 0x5a, 0x8b, 0xe7, 0x40, 0xe4, 0x84 } }; #endif /* MBEDTLS_CIPHER_MODE_OFB */ #if defined(MBEDTLS_CIPHER_MODE_CTR) /* * AES-CTR test vectors from: * * http://www.faqs.org/rfcs/rfc3686.html */ static const unsigned char aes_test_ctr_key[3][16] = { { 0xAE, 0x68, 0x52, 0xF8, 0x12, 0x10, 0x67, 0xCC, 0x4B, 0xF7, 0xA5, 0x76, 0x55, 0x77, 0xF3, 0x9E }, { 0x7E, 0x24, 0x06, 0x78, 0x17, 0xFA, 0xE0, 0xD7, 0x43, 0xD6, 0xCE, 0x1F, 0x32, 0x53, 0x91, 0x63 }, { 0x76, 0x91, 0xBE, 0x03, 0x5E, 0x50, 0x20, 0xA8, 0xAC, 0x6E, 0x61, 0x85, 0x29, 0xF9, 0xA0, 0xDC } }; static const unsigned char aes_test_ctr_nonce_counter[3][16] = { { 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }, { 0x00, 0x6C, 0xB6, 0xDB, 0xC0, 0x54, 0x3B, 0x59, 0xDA, 0x48, 0xD9, 0x0B, 0x00, 0x00, 0x00, 0x01 }, { 0x00, 0xE0, 0x01, 0x7B, 0x27, 0x77, 0x7F, 0x3F, 0x4A, 0x17, 0x86, 0xF0, 0x00, 0x00, 0x00, 0x01 } }; static const unsigned char aes_test_ctr_pt[3][48] = { { 0x53, 0x69, 0x6E, 0x67, 0x6C, 0x65, 0x20, 0x62, 0x6C, 0x6F, 0x63, 0x6B, 0x20, 0x6D, 0x73, 0x67 }, { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }, { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23 } }; static const unsigned char aes_test_ctr_ct[3][48] = { { 0xE4, 0x09, 0x5D, 0x4F, 0xB7, 0xA7, 0xB3, 0x79, 0x2D, 0x61, 0x75, 0xA3, 0x26, 0x13, 0x11, 0xB8 }, { 0x51, 0x04, 0xA1, 0x06, 0x16, 0x8A, 0x72, 0xD9, 0x79, 0x0D, 0x41, 0xEE, 0x8E, 0xDA, 0xD3, 0x88, 0xEB, 0x2E, 0x1E, 0xFC, 0x46, 0xDA, 0x57, 0xC8, 0xFC, 0xE6, 0x30, 0xDF, 0x91, 0x41, 0xBE, 0x28 }, { 0xC1, 0xCF, 0x48, 0xA8, 0x9F, 0x2F, 0xFD, 0xD9, 0xCF, 0x46, 0x52, 0xE9, 0xEF, 0xDB, 0x72, 0xD7, 0x45, 0x40, 0xA4, 0x2B, 0xDE, 0x6D, 0x78, 0x36, 0xD5, 0x9A, 0x5C, 0xEA, 0xAE, 0xF3, 0x10, 0x53, 0x25, 0xB2, 0x07, 0x2F } }; static const int aes_test_ctr_len[3] = { 16, 32, 36 }; #endif /* MBEDTLS_CIPHER_MODE_CTR */ #if defined(MBEDTLS_CIPHER_MODE_XTS) /* * AES-XTS test vectors from: * * IEEE P1619/D16 Annex B * https://web.archive.org/web/20150629024421/http://grouper.ieee.org/groups/1619/email/pdf00086.pdf * (Archived from original at http://grouper.ieee.org/groups/1619/email/pdf00086.pdf) */ static const unsigned char aes_test_xts_key[][32] = { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22 }, { 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22 }, }; static const unsigned char aes_test_xts_pt32[][32] = { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44 }, { 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44 }, }; static const unsigned char aes_test_xts_ct32[][32] = { { 0x91, 0x7c, 0xf6, 0x9e, 0xbd, 0x68, 0xb2, 0xec, 0x9b, 0x9f, 0xe9, 0xa3, 0xea, 0xdd, 0xa6, 0x92, 0xcd, 0x43, 0xd2, 0xf5, 0x95, 0x98, 0xed, 0x85, 0x8c, 0x02, 0xc2, 0x65, 0x2f, 0xbf, 0x92, 0x2e }, { 0xc4, 0x54, 0x18, 0x5e, 0x6a, 0x16, 0x93, 0x6e, 0x39, 0x33, 0x40, 0x38, 0xac, 0xef, 0x83, 0x8b, 0xfb, 0x18, 0x6f, 0xff, 0x74, 0x80, 0xad, 0xc4, 0x28, 0x93, 0x82, 0xec, 0xd6, 0xd3, 0x94, 0xf0 }, { 0xaf, 0x85, 0x33, 0x6b, 0x59, 0x7a, 0xfc, 0x1a, 0x90, 0x0b, 0x2e, 0xb2, 0x1e, 0xc9, 0x49, 0xd2, 0x92, 0xdf, 0x4c, 0x04, 0x7e, 0x0b, 0x21, 0x53, 0x21, 0x86, 0xa5, 0x97, 0x1a, 0x22, 0x7a, 0x89 }, }; static const unsigned char aes_test_xts_data_unit[][16] = { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x33, 0x33, 0x33, 0x33, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x33, 0x33, 0x33, 0x33, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, }; #endif /* MBEDTLS_CIPHER_MODE_XTS */ /* * Checkup routine */ int mbedtls_aes_self_test( int verbose ) { int ret = 0, i, j, u, mode; unsigned int keybits; unsigned char key[32]; unsigned char buf[64]; const unsigned char *aes_tests; #if defined(MBEDTLS_CIPHER_MODE_CBC) || defined(MBEDTLS_CIPHER_MODE_CFB) unsigned char iv[16]; #endif #if defined(MBEDTLS_CIPHER_MODE_CBC) unsigned char prv[16]; #endif #if defined(MBEDTLS_CIPHER_MODE_CTR) || defined(MBEDTLS_CIPHER_MODE_CFB) || \ defined(MBEDTLS_CIPHER_MODE_OFB) size_t offset; #endif #if defined(MBEDTLS_CIPHER_MODE_CTR) || defined(MBEDTLS_CIPHER_MODE_XTS) int len; #endif #if defined(MBEDTLS_CIPHER_MODE_CTR) unsigned char nonce_counter[16]; unsigned char stream_block[16]; #endif mbedtls_aes_context ctx; mbedtls_platform_zeroize( key, 32 ); mbedtls_aes_init( &ctx ); /* * ECB mode */ for( i = 0; i < 6; i++ ) { u = i >> 1; keybits = 128 + u * 64; mode = i & 1; if( verbose != 0 ) mbedtls_printf( " AES-ECB-%3u (%s): ", keybits, ( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" ); mbedtls_platform_zeroize( buf, 16 ); if( mode == MBEDTLS_AES_DECRYPT ) { mbedtls_aes_setkey_dec( &ctx, key, keybits ); aes_tests = aes_test_ecb_dec[u]; } else { mbedtls_aes_setkey_enc( &ctx, key, keybits ); aes_tests = aes_test_ecb_enc[u]; } for( j = 0; j < 10000; j++ ) { ret = mbedtls_aes_crypt_ecb( &ctx, mode, buf, buf ); if( ret != 0 ) goto exit; } if( timingsafe_bcmp( buf, aes_tests, 16 ) != 0 ) { ret = 1; goto exit; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); } if( verbose != 0 ) mbedtls_printf( "\n" ); #if defined(MBEDTLS_CIPHER_MODE_CBC) /* * CBC mode */ for( i = 0; i < 6; i++ ) { u = i >> 1; keybits = 128 + u * 64; mode = i & 1; if( verbose != 0 ) mbedtls_printf( " AES-CBC-%3u (%s): ", keybits, ( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" ); mbedtls_platform_zeroize( iv , 16 ); mbedtls_platform_zeroize( prv, 16 ); mbedtls_platform_zeroize( buf, 16 ); if( mode == MBEDTLS_AES_DECRYPT ) { ret = mbedtls_aes_setkey_dec( &ctx, key, keybits ); aes_tests = aes_test_cbc_dec[u]; } else { ret = mbedtls_aes_setkey_enc( &ctx, key, keybits ); aes_tests = aes_test_cbc_enc[u]; } /* * AES-192 is an optional feature that may be unavailable when * there is an alternative underlying implementation i.e. when * MBEDTLS_AES_ALT is defined. */ if( ret != 0 ) { goto exit; } for( j = 0; j < 10000; j++ ) { if( mode == MBEDTLS_AES_ENCRYPT ) { unsigned char tmp[16]; memcpy( tmp, prv, 16 ); memcpy( prv, buf, 16 ); memcpy( buf, tmp, 16 ); } ret = mbedtls_aes_crypt_cbc( &ctx, mode, 16, iv, buf, buf ); if( ret != 0 ) goto exit; } if( timingsafe_bcmp( buf, aes_tests, 16 ) != 0 ) { ret = 1; goto exit; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); } if( verbose != 0 ) mbedtls_printf( "\n" ); #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_CIPHER_MODE_CFB) /* * CFB128 mode */ for( i = 0; i < 6; i++ ) { u = i >> 1; keybits = 128 + u * 64; mode = i & 1; if( verbose != 0 ) mbedtls_printf( " AES-CFB128-%3u (%s): ", keybits, ( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" ); memcpy( iv, aes_test_cfb128_iv, 16 ); memcpy( key, aes_test_cfb128_key[u], keybits / 8 ); offset = 0; ret = mbedtls_aes_setkey_enc( &ctx, key, keybits ); /* * AES-192 is an optional feature that may be unavailable when * there is an alternative underlying implementation i.e. when * MBEDTLS_AES_ALT is defined. */ if( ret != 0 ) { goto exit; } if( mode == MBEDTLS_AES_DECRYPT ) { memcpy( buf, aes_test_cfb128_ct[u], 64 ); aes_tests = aes_test_cfb128_pt; } else { memcpy( buf, aes_test_cfb128_pt, 64 ); aes_tests = aes_test_cfb128_ct[u]; } ret = mbedtls_aes_crypt_cfb128( &ctx, mode, 64, &offset, iv, buf, buf ); if( ret != 0 ) goto exit; if( timingsafe_bcmp( buf, aes_tests, 64 ) != 0 ) { ret = 1; goto exit; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); } if( verbose != 0 ) mbedtls_printf( "\n" ); #endif /* MBEDTLS_CIPHER_MODE_CFB */ #if defined(MBEDTLS_CIPHER_MODE_OFB) /* * OFB mode */ for( i = 0; i < 6; i++ ) { u = i >> 1; keybits = 128 + u * 64; mode = i & 1; if( verbose != 0 ) mbedtls_printf( " AES-OFB-%3u (%s): ", keybits, ( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" ); memcpy( iv, aes_test_ofb_iv, 16 ); memcpy( key, aes_test_ofb_key[u], keybits / 8 ); offset = 0; ret = mbedtls_aes_setkey_enc( &ctx, key, keybits ); /* * AES-192 is an optional feature that may be unavailable when * there is an alternative underlying implementation i.e. when * MBEDTLS_AES_ALT is defined. */ if( ret != 0 ) { goto exit; } if( mode == MBEDTLS_AES_DECRYPT ) { memcpy( buf, aes_test_ofb_ct[u], 64 ); aes_tests = aes_test_ofb_pt; } else { memcpy( buf, aes_test_ofb_pt, 64 ); aes_tests = aes_test_ofb_ct[u]; } ret = mbedtls_aes_crypt_ofb( &ctx, 64, &offset, iv, buf, buf ); if( ret != 0 ) goto exit; if( timingsafe_bcmp( buf, aes_tests, 64 ) != 0 ) { ret = 1; goto exit; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); } if( verbose != 0 ) mbedtls_printf( "\n" ); #endif /* MBEDTLS_CIPHER_MODE_OFB */ #if defined(MBEDTLS_CIPHER_MODE_CTR) /* * CTR mode */ for( i = 0; i < 6; i++ ) { u = i >> 1; mode = i & 1; if( verbose != 0 ) mbedtls_printf( " AES-CTR-128 (%s): ", ( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" ); memcpy( nonce_counter, aes_test_ctr_nonce_counter[u], 16 ); memcpy( key, aes_test_ctr_key[u], 16 ); offset = 0; if( ( ret = mbedtls_aes_setkey_enc( &ctx, key, 128 ) ) != 0 ) goto exit; len = aes_test_ctr_len[u]; if( mode == MBEDTLS_AES_DECRYPT ) { memcpy( buf, aes_test_ctr_ct[u], len ); aes_tests = aes_test_ctr_pt[u]; } else { memcpy( buf, aes_test_ctr_pt[u], len ); aes_tests = aes_test_ctr_ct[u]; } ret = mbedtls_aes_crypt_ctr( &ctx, len, &offset, nonce_counter, stream_block, buf, buf ); if( ret != 0 ) goto exit; if( timingsafe_bcmp( buf, aes_tests, len ) != 0 ) { ret = 1; goto exit; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); } if( verbose != 0 ) mbedtls_printf( "\n" ); #endif /* MBEDTLS_CIPHER_MODE_CTR */ #if defined(MBEDTLS_CIPHER_MODE_XTS) { static const int num_tests = sizeof(aes_test_xts_key) / sizeof(*aes_test_xts_key); mbedtls_aes_xts_context ctx_xts; /* * XTS mode */ mbedtls_aes_xts_init( &ctx_xts ); for( i = 0; i < num_tests << 1; i++ ) { const unsigned char *data_unit; u = i >> 1; mode = i & 1; if( verbose != 0 ) mbedtls_printf( " AES-XTS-128 (%s): ", ( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" ); mbedtls_platform_zeroize( key, sizeof( key ) ); memcpy( key, aes_test_xts_key[u], 32 ); data_unit = aes_test_xts_data_unit[u]; len = sizeof( *aes_test_xts_ct32 ); if( mode == MBEDTLS_AES_DECRYPT ) { ret = mbedtls_aes_xts_setkey_dec( &ctx_xts, key, 256 ); if( ret != 0) goto exit; memcpy( buf, aes_test_xts_ct32[u], len ); aes_tests = aes_test_xts_pt32[u]; } else { ret = mbedtls_aes_xts_setkey_enc( &ctx_xts, key, 256 ); if( ret != 0) goto exit; memcpy( buf, aes_test_xts_pt32[u], len ); aes_tests = aes_test_xts_ct32[u]; } ret = mbedtls_aes_crypt_xts( &ctx_xts, mode, len, data_unit, buf, buf ); if( ret != 0 ) goto exit; if( timingsafe_bcmp( buf, aes_tests, len ) != 0 ) { ret = 1; goto exit; } if( verbose != 0 ) mbedtls_printf( "passed\n" ); } if( verbose != 0 ) mbedtls_printf( "\n" ); mbedtls_aes_xts_free( &ctx_xts ); } #endif /* MBEDTLS_CIPHER_MODE_XTS */ ret = 0; exit: if( ret != 0 && verbose != 0 ) mbedtls_printf( "failed\n" ); mbedtls_aes_free( &ctx ); return( ret ); } #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_AES_C */
70,681
1,893
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/net_sockets.h
#ifndef COSMOPOLITAN_THIRD_PARTY_MBEDTLS_NET_SOCKETS_H_ #define COSMOPOLITAN_THIRD_PARTY_MBEDTLS_NET_SOCKETS_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ /* clang-format off */ #define MBEDTLS_ERR_NET_SOCKET_FAILED -0x0042 /*< Failed to open a socket. */ #define MBEDTLS_ERR_NET_CONNECT_FAILED -0x0044 /*< The connection to the given server / port failed. */ #define MBEDTLS_ERR_NET_BIND_FAILED -0x0046 /*< Binding of the socket failed. */ #define MBEDTLS_ERR_NET_LISTEN_FAILED -0x0048 /*< Could not listen on the socket. */ #define MBEDTLS_ERR_NET_ACCEPT_FAILED -0x004A /*< Could not accept the incoming connection. */ #define MBEDTLS_ERR_NET_RECV_FAILED -0x004C /*< Reading information from the socket failed. */ #define MBEDTLS_ERR_NET_SEND_FAILED -0x004E /*< Sending information through the socket failed. */ #define MBEDTLS_ERR_NET_CONN_RESET -0x0050 /*< Connection was reset by peer. */ #define MBEDTLS_ERR_NET_UNKNOWN_HOST -0x0052 /*< Failed to get an IP address for the given hostname. */ #define MBEDTLS_ERR_NET_BUFFER_TOO_SMALL -0x0043 /*< Buffer is too small to hold the data. */ #define MBEDTLS_ERR_NET_INVALID_CONTEXT -0x0045 /*< The context is invalid, eg because it was free()ed. */ #define MBEDTLS_ERR_NET_POLL_FAILED -0x0047 /*< Polling the net context failed. */ #define MBEDTLS_ERR_NET_BAD_INPUT_DATA -0x0049 /*< Input invalid. */ #define MBEDTLS_NET_LISTEN_BACKLOG 10 /*< The backlog that listen() should use. */ #define MBEDTLS_NET_PROTO_TCP 0 /*< The TCP transport protocol */ #define MBEDTLS_NET_PROTO_UDP 1 /*< The UDP transport protocol */ #define MBEDTLS_NET_POLL_READ 1 /*< Used in \c mbedtls_net_poll to check for pending data */ #define MBEDTLS_NET_POLL_WRITE 2 /*< Used in \c mbedtls_net_poll to check if write possible */ /** * Wrapper type for sockets. * * Currently backed by just a file descriptor, but might be more in the future * (eg two file descriptors for combined IPv4 + IPv6 support, or additional * structures for hand-made UDP demultiplexing). */ typedef struct mbedtls_net_context { int fd; /*< The underlying file descriptor */ } mbedtls_net_context; int mbedtls_net_accept( mbedtls_net_context *, mbedtls_net_context *, void *, size_t, size_t * ); int mbedtls_net_bind( mbedtls_net_context *, const char *, const char *, int ); int mbedtls_net_connect( mbedtls_net_context *, const char *, const char *, int ); int mbedtls_net_poll( mbedtls_net_context *, uint32_t, uint32_t ); int mbedtls_net_recv( void *, unsigned char *, size_t ); int mbedtls_net_recv_timeout( void *, unsigned char *, size_t, uint32_t ); int mbedtls_net_send( void *, const unsigned char *, size_t ); int mbedtls_net_set_block( mbedtls_net_context * ); int mbedtls_net_set_nonblock( mbedtls_net_context * ); void mbedtls_net_close( mbedtls_net_context * ); void mbedtls_net_free( mbedtls_net_context * ); void mbedtls_net_init( mbedtls_net_context * ); void mbedtls_net_usleep( unsigned long ); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_THIRD_PARTY_MBEDTLS_NET_SOCKETS_H_ */
3,552
59
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/formatclientciphers.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/bits.h" #include "libc/macros.internal.h" #include "libc/stdio/append.h" #include "third_party/mbedtls/iana.h" /** * Returns string of joined list of first 𝑘 client preferred ciphers. * @return string that must be free'd, or null if none set */ dontdiscard char *FormatSslClientCiphers(const mbedtls_ssl_context *ssl) { int i; char *b = 0; for (i = 0; i < ARRAYLEN(ssl->client_ciphers); ++i) { if (!ssl->client_ciphers[i]) break; if (i) appendw(&b, READ16LE(", ")); appendf(&b, "%s[0x%04x]", GetCipherSuiteName(ssl->client_ciphers[i]), ssl->client_ciphers[i]); } if (i == ARRAYLEN(ssl->client_ciphers)) { appends(&b, ", ..."); } return b; }
2,548
42
jart/cosmopolitan
false
cosmopolitan/third_party/mbedtls/x509_crt.h
#ifndef MBEDTLS_X509_CRT_H_ #define MBEDTLS_X509_CRT_H_ #include "third_party/mbedtls/bignum.h" #include "third_party/mbedtls/config.h" #include "third_party/mbedtls/x509.h" #include "third_party/mbedtls/x509_crl.h" COSMOPOLITAN_C_START_ /* clang-format off */ /** * Container for an X.509 certificate. The certificate may be chained. */ typedef struct mbedtls_x509_crt { int own_buffer; /*< Indicates if \c raw is owned * by the structure or not. */ mbedtls_x509_buf raw; /*< The raw certificate data (DER). */ mbedtls_x509_buf tbs; /*< The raw certificate body (DER). The part that is To Be Signed. */ int version; /*< The X.509 version. (1=v1, 2=v2, 3=v3) */ mbedtls_x509_buf serial; /*< Unique id for certificate issued by a specific CA. */ mbedtls_x509_buf sig_oid; /*< Signature algorithm, e.g. sha1RSA */ mbedtls_x509_buf issuer_raw; /*< The raw issuer data (DER). Used for quick comparison. */ mbedtls_x509_buf subject_raw; /*< The raw subject data (DER). Used for quick comparison. */ mbedtls_x509_name issuer; /*< The parsed issuer data (named information object). */ mbedtls_x509_name subject; /*< The parsed subject data (named information object). */ mbedtls_x509_time valid_from; /*< Start time of certificate validity. */ mbedtls_x509_time valid_to; /*< End time of certificate validity. */ mbedtls_x509_buf pk_raw; mbedtls_pk_context pk; /*< Container for the public key context. */ mbedtls_x509_buf issuer_id; /*< Optional X.509 v2/v3 issuer unique identifier. */ mbedtls_x509_buf subject_id; /*< Optional X.509 v2/v3 subject unique identifier. */ mbedtls_x509_buf v3_ext; /*< Optional X.509 v3 extensions. */ mbedtls_x509_sequence subject_alt_names; /*< Optional list of raw entries of Subject Alternative Names extension (currently only dNSName and OtherName are listed). */ mbedtls_x509_sequence certificate_policies; /*< Optional list of certificate policies (Only anyPolicy is printed and enforced, however the rest of the policies are still listed). */ int ext_types; /*< Bit string containing detected and parsed extensions */ int ca_istrue; /*< Optional Basic Constraint extension value: 1 if this certificate belongs to a CA, 0 otherwise. */ int max_pathlen; /*< Optional Basic Constraint extension value: The maximum path length to the root certificate. Path length is 1 higher than RFC 5280 'meaning', so 1+ */ unsigned int key_usage; /*< Optional key usage extension value: See the values in x509.h */ mbedtls_x509_sequence ext_key_usage; /*< Optional list of extended key usage OIDs. */ unsigned char ns_cert_type; /*< Optional Netscape certificate type extension value: See the values in x509.h */ mbedtls_x509_buf sig; /*< Signature: hash of the tbs part signed with the private key. */ mbedtls_md_type_t sig_md; /*< Internal representation of the MD algorithm of the signature algorithm, e.g. MBEDTLS_MD_SHA256 */ mbedtls_pk_type_t sig_pk; /*< Internal representation of the Public Key algorithm of the signature algorithm, e.g. MBEDTLS_PK_RSA */ void *sig_opts; /*< Signature options to be passed to mbedtls_pk_verify_ext(), e.g. for RSASSA-PSS */ struct mbedtls_x509_crt *next; /*< Next certificate in the CA-chain. */ } mbedtls_x509_crt; /** * From RFC 5280 section 4.2.1.6: * OtherName ::= SEQUENCE { * type-id OBJECT IDENTIFIER, * value [0] EXPLICIT ANY DEFINED BY type-id } */ typedef struct mbedtls_x509_san_other_name { /** * The type_id is an OID as deifned in RFC 5280. * To check the value of the type id, you should use * \p MBEDTLS_OID_CMP with a known OID mbedtls_x509_buf. */ mbedtls_x509_buf type_id; /*< The type id. */ union { /** * From RFC 4108 section 5: * HardwareModuleName ::= SEQUENCE { * hwType OBJECT IDENTIFIER, * hwSerialNum OCTET STRING } */ struct { mbedtls_x509_buf oid; /*< The object identifier. */ mbedtls_x509_buf val; /*< The named value. */ } hardware_module_name; } value; } mbedtls_x509_san_other_name; /** * A structure for holding the parsed Subject Alternative Name, according to type */ typedef struct mbedtls_x509_subject_alternative_name { int type; /*< The SAN type, value of MBEDTLS_X509_SAN_XXX. */ union { mbedtls_x509_san_other_name other_name; /*< The otherName supported type. */ mbedtls_x509_buf unstructured_name; /*< The buffer for the un constructed types. Only dnsName currently supported */ uint32_t ip; } san; /*< A union of the supported SAN types */ } mbedtls_x509_subject_alternative_name; /** * Build flag from an algorithm/curve identifier (pk, md, ecp) * Since 0 is always XXX_NONE, ignore it. */ #define MBEDTLS_X509_ID_FLAG( id ) ( 1 << ( (id) - 1 ) ) /** * Security profile for certificate verification. * * All lists are bitfields, built by ORing flags from MBEDTLS_X509_ID_FLAG(). */ typedef struct mbedtls_x509_crt_profile { uint32_t allowed_mds; /*< MDs for signatures */ uint32_t allowed_pks; /*< PK algs for signatures */ uint32_t allowed_curves; /*< Elliptic curves for ECDSA */ uint32_t rsa_min_bitlen; /*< Minimum size for RSA keys */ } mbedtls_x509_crt_profile; #define MBEDTLS_X509_CRT_VERSION_1 0 #define MBEDTLS_X509_CRT_VERSION_2 1 #define MBEDTLS_X509_CRT_VERSION_3 2 #define MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN 32 #define MBEDTLS_X509_RFC5280_UTC_TIME_LEN 15 #if !defined( MBEDTLS_X509_MAX_FILE_PATH_LEN ) #define MBEDTLS_X509_MAX_FILE_PATH_LEN 512 #endif /** * Container for writing a certificate (CRT) */ typedef struct mbedtls_x509write_cert { int version; mbedtls_mpi serial; mbedtls_pk_context *subject_key; mbedtls_pk_context *issuer_key; mbedtls_asn1_named_data *subject; mbedtls_asn1_named_data *issuer; mbedtls_md_type_t md_alg; char not_before[MBEDTLS_X509_RFC5280_UTC_TIME_LEN + 1]; char not_after[MBEDTLS_X509_RFC5280_UTC_TIME_LEN + 1]; mbedtls_asn1_named_data *extensions; } mbedtls_x509write_cert; /** * Item in a verification chain: cert and flags for it */ typedef struct { mbedtls_x509_crt *crt; uint32_t flags; } mbedtls_x509_crt_verify_chain_item; /** * Max size of verification chain: end-entity + intermediates + trusted root */ #define MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE ( MBEDTLS_X509_MAX_INTERMEDIATE_CA + 2 ) /** * Verification chain as built by \c mbedtls_crt_verify_chain() */ typedef struct { mbedtls_x509_crt_verify_chain_item items[MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE]; unsigned len; #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK) /* This stores the list of potential trusted signers obtained from * the CA callback used for the CRT verification, if configured. * We must track it somewhere because the callback passes its * ownership to the caller. */ mbedtls_x509_crt *trust_ca_cb_result; #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */ } mbedtls_x509_crt_verify_chain; #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) /** * \brief Context for resuming X.509 verify operations */ typedef struct { /* for check_signature() */ mbedtls_pk_restart_ctx pk; /* for find_parent_in() */ mbedtls_x509_crt *parent; /* non-null iff parent_in in progress */ mbedtls_x509_crt *fallback_parent; int fallback_signature_is_good; /* for find_parent() */ int parent_is_trusted; /* -1 if find_parent is not in progress */ /* for verify_chain() */ enum { x509_crt_rs_none, x509_crt_rs_find_parent, } in_progress; /* none if no operation is in progress */ int self_cnt; mbedtls_x509_crt_verify_chain ver_chain; } mbedtls_x509_crt_restart_ctx; #else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ /* Now we can declare functions that take a pointer to that */ typedef void mbedtls_x509_crt_restart_ctx; #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ /** * Default security profile. Should provide a good balance between security * and compatibility with current deployments. */ extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default; /** * Expected next default profile. Recommended for new deployments. * Currently targets a 128-bit security level, except for RSA-2048. */ extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next; /** * NSA Suite B profile. */ extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb; /** * \brief The type of certificate extension callbacks. * * Callbacks of this type are passed to and used by the * mbedtls_x509_crt_parse_der_with_ext_cb() routine when * it encounters either an unsupported extension or a * "certificate policies" extension containing any * unsupported certificate policies. * Future versions of the library may invoke the callback * in other cases, if and when the need arises. * * \param p_ctx An opaque context passed to the callback. * \param crt The certificate being parsed. * \param oid The OID of the extension. * \param critical Whether the extension is critical. * \param p Pointer to the start of the extension value * (the content of the OCTET STRING). * \param end End of extension value. * * \note The callback must fail and return a negative error code * if it can not parse or does not support the extension. * When the callback fails to parse a critical extension * mbedtls_x509_crt_parse_der_with_ext_cb() also fails. * When the callback fails to parse a non critical extension * mbedtls_x509_crt_parse_der_with_ext_cb() simply skips * the extension and continues parsing. * * \return \c 0 on success. * \return A negative error code on failure. */ typedef int (*mbedtls_x509_crt_ext_cb_t)( void *p_ctx, mbedtls_x509_crt const *crt, mbedtls_x509_buf const *oid, int critical, const unsigned char *p, const unsigned char *end ); /** * \brief The type of trusted certificate callbacks. * * Callbacks of this type are passed to and used by the CRT * verification routine mbedtls_x509_crt_verify_with_ca_cb() * when looking for trusted signers of a given certificate. * * On success, the callback returns a list of trusted * certificates to be considered as potential signers * for the input certificate. * * \param p_ctx An opaque context passed to the callback. * \param child The certificate for which to search a potential signer. * This will point to a readable certificate. * \param candidate_cas The address at which to store the address of the first * entry in the generated linked list of candidate signers. * This will not be \c NULL. * * \note The callback must only return a non-zero value on a * fatal error. If, in contrast, the search for a potential * signer completes without a single candidate, the * callback must return \c 0 and set \c *candidate_cas * to \c NULL. * * \return \c 0 on success. In this case, \c *candidate_cas points * to a heap-allocated linked list of instances of * ::mbedtls_x509_crt, and ownership of this list is passed * to the caller. * \return A negative error code on failure. */ typedef int (*mbedtls_x509_crt_ca_cb_t)( void *p_ctx, mbedtls_x509_crt const *child, mbedtls_x509_crt **candidate_cas ); int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *, const char *, size_t ); int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *, unsigned int ); int mbedtls_x509_crt_check_parent( const mbedtls_x509_crt *, const mbedtls_x509_crt *, int ); int mbedtls_x509_crt_check_signature( const mbedtls_x509_crt *, mbedtls_x509_crt *, mbedtls_x509_crt_restart_ctx * ); int mbedtls_x509_crt_info( char *, size_t, const char *, const mbedtls_x509_crt * ); int mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *, const mbedtls_x509_crl * ); int mbedtls_x509_crt_parse( mbedtls_x509_crt *, const unsigned char *, size_t ); int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *, const unsigned char *, size_t ); int mbedtls_x509_crt_parse_der_nocopy( mbedtls_x509_crt *, const unsigned char *, size_t ); int mbedtls_x509_crt_parse_der_with_ext_cb( mbedtls_x509_crt *, const unsigned char *, size_t, int, mbedtls_x509_crt_ext_cb_t, void * ); int mbedtls_x509_crt_parse_file( mbedtls_x509_crt *, const char * ); int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *, const char * ); int mbedtls_x509_crt_verify( mbedtls_x509_crt *, mbedtls_x509_crt *, mbedtls_x509_crl *, const char *, uint32_t *, int (*)(void *, mbedtls_x509_crt *, int, uint32_t *), void * ); int mbedtls_x509_crt_verify_info( char *, size_t, const char *, uint32_t ); int mbedtls_x509_crt_verify_restartable( mbedtls_x509_crt *, mbedtls_x509_crt *, mbedtls_x509_crl *, const mbedtls_x509_crt_profile *, const char *, uint32_t *, int (*)(void *, mbedtls_x509_crt *, int, uint32_t *), void *, mbedtls_x509_crt_restart_ctx * ); int mbedtls_x509_crt_verify_with_ca_cb( mbedtls_x509_crt *, mbedtls_x509_crt_ca_cb_t, void *, const mbedtls_x509_crt_profile *, const char *, uint32_t *, int (*)(void *, mbedtls_x509_crt *, int, uint32_t *), void * ); int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *, mbedtls_x509_crt *, mbedtls_x509_crl *, const mbedtls_x509_crt_profile *, const char *, uint32_t *, int (*)(void *, mbedtls_x509_crt *, int, uint32_t *), void * ); int mbedtls_x509_name_cmp( const mbedtls_x509_name *, const mbedtls_x509_name * ); int mbedtls_x509_parse_subject_alt_name( const mbedtls_x509_buf *, mbedtls_x509_subject_alternative_name * ); int mbedtls_x509write_crt_der( mbedtls_x509write_cert *, unsigned char *, size_t, int (*)(void *, unsigned char *, size_t), void * ); int mbedtls_x509write_crt_pem( mbedtls_x509write_cert *, unsigned char *, size_t, int (*)(void *, unsigned char *, size_t), void * ); int mbedtls_x509write_crt_set_authority_key_identifier( mbedtls_x509write_cert * ); int mbedtls_x509write_crt_set_basic_constraints( mbedtls_x509write_cert *, int, int ); int mbedtls_x509write_crt_set_ext_key_usage(mbedtls_x509write_cert *, int); int mbedtls_x509write_crt_set_extension( mbedtls_x509write_cert *, const char *, size_t, int, const unsigned char *, size_t ); int mbedtls_x509write_crt_set_issuer_name( mbedtls_x509write_cert *, const char * ); int mbedtls_x509write_crt_set_key_usage( mbedtls_x509write_cert *, unsigned int ); int mbedtls_x509write_crt_set_ns_cert_type( mbedtls_x509write_cert *, unsigned char ); int mbedtls_x509write_crt_set_serial( mbedtls_x509write_cert *, const mbedtls_mpi * ); int mbedtls_x509write_crt_set_subject_key_identifier( mbedtls_x509write_cert * ); int mbedtls_x509write_crt_set_subject_name( mbedtls_x509write_cert *, const char * ); int mbedtls_x509write_crt_set_validity( mbedtls_x509write_cert *, const char *, const char * ); void mbedtls_x509_crt_free( mbedtls_x509_crt * ); void mbedtls_x509_crt_init( mbedtls_x509_crt * ); void mbedtls_x509_crt_restart_free( mbedtls_x509_crt_restart_ctx * ); void mbedtls_x509_crt_restart_init( mbedtls_x509_crt_restart_ctx * ); void mbedtls_x509write_crt_free( mbedtls_x509write_cert * ); void mbedtls_x509write_crt_init( mbedtls_x509write_cert * ); void mbedtls_x509write_crt_set_issuer_key( mbedtls_x509write_cert *, mbedtls_pk_context * ); void mbedtls_x509write_crt_set_md_alg( mbedtls_x509write_cert *, mbedtls_md_type_t ); void mbedtls_x509write_crt_set_subject_key( mbedtls_x509write_cert *, mbedtls_pk_context * ); void mbedtls_x509write_crt_set_version( mbedtls_x509write_cert *, int ); COSMOPOLITAN_C_END_ #endif /* MBEDTLS_X509_CRT_H */
17,117
357
jart/cosmopolitan
false