From 11f68ee3ae1403623cd33cabc4f119ddca274c98 Mon Sep 17 00:00:00 2001 From: zhongkaizhu Date: Sun, 10 Apr 2022 23:24:37 +0800 Subject: [PATCH 1/3] corecrypto: add header files for macOS porting from: git@github.com:rileytestut/AltSign.git **without any change** commit-id: 2856e479c3447b361b98b --- .../corecrypto/Sources/CoreCryptoMacros.swift | 55 ++ libraries/corecrypto/Sources/ccsrp.m | 30 + libraries/corecrypto/include/corecrypto/cc.h | 164 ++++ .../corecrypto/include/corecrypto/cc_config.h | 560 +++++++++++ .../corecrypto/include/corecrypto/cc_debug.h | 126 +++ .../corecrypto/include/corecrypto/cc_memory.h | 189 ++++ .../corecrypto/include/corecrypto/cc_priv.h | 530 ++++++++++ .../include/corecrypto/cc_runtime_config.h | 102 ++ .../corecrypto/include/corecrypto/ccaes.h | 175 ++++ .../corecrypto/include/corecrypto/ccansikdf.h | 89 ++ .../corecrypto/include/corecrypto/ccasn1.h | 150 +++ .../include/corecrypto/ccblowfish.h | 96 ++ .../corecrypto/include/corecrypto/cccast.h | 96 ++ .../include/corecrypto/ccchacha20poly1305.h | 352 +++++++ .../corecrypto/ccchacha20poly1305_priv.h | 91 ++ .../corecrypto/include/corecrypto/cccmac.h | 266 +++++ .../corecrypto/include/corecrypto/ccder.h | 370 +++++++ .../include/corecrypto/ccder_decode_eckey.h | 73 ++ .../include/corecrypto/ccder_encode_eckey.h | 72 ++ .../include/corecrypto/ccder_priv.h | 113 +++ .../corecrypto/include/corecrypto/ccder_rsa.h | 77 ++ .../corecrypto/include/corecrypto/ccdes.h | 121 +++ .../corecrypto/include/corecrypto/ccdh.h | 516 ++++++++++ .../corecrypto/include/corecrypto/ccdh_gp.h | 88 ++ .../corecrypto/include/corecrypto/ccdh_priv.h | 105 ++ .../corecrypto/include/corecrypto/ccdigest.h | 245 +++++ .../include/corecrypto/ccdigest_priv.h | 90 ++ .../corecrypto/include/corecrypto/ccdrbg.h | 191 ++++ .../include/corecrypto/ccdrbg_factory.h | 68 ++ .../include/corecrypto/ccdrbg_impl.h | 123 +++ .../corecrypto/include/corecrypto/ccec.h | 888 +++++++++++++++++ .../corecrypto/include/corecrypto/ccec25519.h | 189 ++++ .../include/corecrypto/ccec25519_priv.h | 86 ++ .../corecrypto/include/corecrypto/ccec_priv.h | 504 ++++++++++ .../corecrypto/include/corecrypto/ccecies.h | 217 ++++ .../include/corecrypto/ccecies_priv.h | 70 ++ .../corecrypto/include/corecrypto/cchkdf.h | 93 ++ .../corecrypto/include/corecrypto/cchmac.h | 161 +++ .../corecrypto/include/corecrypto/ccmd2.h | 84 ++ .../corecrypto/include/corecrypto/ccmd4.h | 82 ++ .../corecrypto/include/corecrypto/ccmd5.h | 82 ++ .../corecrypto/include/corecrypto/ccmode.h | 926 ++++++++++++++++++ .../include/corecrypto/ccmode_factory.h | 646 ++++++++++++ .../include/corecrypto/ccmode_impl.h | 264 +++++ .../include/corecrypto/ccmode_siv.h | 192 ++++ .../include/corecrypto/ccmode_siv_priv.h | 129 +++ libraries/corecrypto/include/corecrypto/ccn.h | 704 +++++++++++++ .../corecrypto/include/corecrypto/ccn_priv.h | 212 ++++ .../corecrypto/include/corecrypto/ccnistkdf.h | 175 ++++ .../corecrypto/include/corecrypto/ccpad.h | 127 +++ .../corecrypto/include/corecrypto/ccpbkdf2.h | 96 ++ .../corecrypto/include/corecrypto/ccperf.h | 226 +++++ .../corecrypto/include/corecrypto/ccprime.h | 81 ++ .../corecrypto/include/corecrypto/ccrc2.h | 92 ++ .../corecrypto/include/corecrypto/ccrc4.h | 98 ++ .../corecrypto/include/corecrypto/ccripemd.h | 95 ++ .../corecrypto/include/corecrypto/ccrng.h | 114 +++ .../include/corecrypto/ccrng_drbg.h | 92 ++ .../include/corecrypto/ccrng_ecfips_test.h | 83 ++ .../include/corecrypto/ccrng_pbkdf2_prng.h | 91 ++ .../include/corecrypto/ccrng_priv.h | 78 ++ .../include/corecrypto/ccrng_rsafips_test.h | 89 ++ .../include/corecrypto/ccrng_sequence.h | 81 ++ .../include/corecrypto/ccrng_system.h | 96 ++ .../include/corecrypto/ccrng_test.h | 83 ++ .../corecrypto/include/corecrypto/ccrsa.h | 663 +++++++++++++ .../include/corecrypto/ccrsa_priv.h | 571 +++++++++++ .../corecrypto/include/corecrypto/ccsha1.h | 106 ++ .../corecrypto/include/corecrypto/ccsha2.h | 137 +++ .../corecrypto/include/corecrypto/ccsrp.h | 651 ++++++++++++ .../corecrypto/include/corecrypto/ccsrp_gp.h | 76 ++ .../corecrypto/include/corecrypto/cctest.h | 91 ++ .../corecrypto/include/corecrypto/ccwrap.h | 191 ++++ libraries/corecrypto/include/corecrypto/ccz.h | 314 ++++++ .../corecrypto/include/corecrypto/ccz_priv.h | 135 +++ .../corecrypto/include/corecrypto/cczp.h | 392 ++++++++ .../corecrypto/include/corecrypto/cczp_priv.h | 142 +++ .../corecrypto/include/corecrypto/fipspost.h | 133 +++ libraries/corecrypto/include/module.modulemap | 14 + 79 files changed, 16265 insertions(+) create mode 100644 libraries/corecrypto/Sources/CoreCryptoMacros.swift create mode 100644 libraries/corecrypto/Sources/ccsrp.m create mode 100644 libraries/corecrypto/include/corecrypto/cc.h create mode 100644 libraries/corecrypto/include/corecrypto/cc_config.h create mode 100644 libraries/corecrypto/include/corecrypto/cc_debug.h create mode 100644 libraries/corecrypto/include/corecrypto/cc_memory.h create mode 100644 libraries/corecrypto/include/corecrypto/cc_priv.h create mode 100644 libraries/corecrypto/include/corecrypto/cc_runtime_config.h create mode 100644 libraries/corecrypto/include/corecrypto/ccaes.h create mode 100644 libraries/corecrypto/include/corecrypto/ccansikdf.h create mode 100644 libraries/corecrypto/include/corecrypto/ccasn1.h create mode 100644 libraries/corecrypto/include/corecrypto/ccblowfish.h create mode 100644 libraries/corecrypto/include/corecrypto/cccast.h create mode 100644 libraries/corecrypto/include/corecrypto/ccchacha20poly1305.h create mode 100644 libraries/corecrypto/include/corecrypto/ccchacha20poly1305_priv.h create mode 100644 libraries/corecrypto/include/corecrypto/cccmac.h create mode 100644 libraries/corecrypto/include/corecrypto/ccder.h create mode 100644 libraries/corecrypto/include/corecrypto/ccder_decode_eckey.h create mode 100644 libraries/corecrypto/include/corecrypto/ccder_encode_eckey.h create mode 100644 libraries/corecrypto/include/corecrypto/ccder_priv.h create mode 100644 libraries/corecrypto/include/corecrypto/ccder_rsa.h create mode 100644 libraries/corecrypto/include/corecrypto/ccdes.h create mode 100644 libraries/corecrypto/include/corecrypto/ccdh.h create mode 100644 libraries/corecrypto/include/corecrypto/ccdh_gp.h create mode 100644 libraries/corecrypto/include/corecrypto/ccdh_priv.h create mode 100644 libraries/corecrypto/include/corecrypto/ccdigest.h create mode 100644 libraries/corecrypto/include/corecrypto/ccdigest_priv.h create mode 100644 libraries/corecrypto/include/corecrypto/ccdrbg.h create mode 100644 libraries/corecrypto/include/corecrypto/ccdrbg_factory.h create mode 100644 libraries/corecrypto/include/corecrypto/ccdrbg_impl.h create mode 100644 libraries/corecrypto/include/corecrypto/ccec.h create mode 100644 libraries/corecrypto/include/corecrypto/ccec25519.h create mode 100644 libraries/corecrypto/include/corecrypto/ccec25519_priv.h create mode 100644 libraries/corecrypto/include/corecrypto/ccec_priv.h create mode 100644 libraries/corecrypto/include/corecrypto/ccecies.h create mode 100644 libraries/corecrypto/include/corecrypto/ccecies_priv.h create mode 100644 libraries/corecrypto/include/corecrypto/cchkdf.h create mode 100644 libraries/corecrypto/include/corecrypto/cchmac.h create mode 100644 libraries/corecrypto/include/corecrypto/ccmd2.h create mode 100644 libraries/corecrypto/include/corecrypto/ccmd4.h create mode 100644 libraries/corecrypto/include/corecrypto/ccmd5.h create mode 100644 libraries/corecrypto/include/corecrypto/ccmode.h create mode 100644 libraries/corecrypto/include/corecrypto/ccmode_factory.h create mode 100644 libraries/corecrypto/include/corecrypto/ccmode_impl.h create mode 100644 libraries/corecrypto/include/corecrypto/ccmode_siv.h create mode 100644 libraries/corecrypto/include/corecrypto/ccmode_siv_priv.h create mode 100644 libraries/corecrypto/include/corecrypto/ccn.h create mode 100644 libraries/corecrypto/include/corecrypto/ccn_priv.h create mode 100644 libraries/corecrypto/include/corecrypto/ccnistkdf.h create mode 100644 libraries/corecrypto/include/corecrypto/ccpad.h create mode 100644 libraries/corecrypto/include/corecrypto/ccpbkdf2.h create mode 100644 libraries/corecrypto/include/corecrypto/ccperf.h create mode 100644 libraries/corecrypto/include/corecrypto/ccprime.h create mode 100644 libraries/corecrypto/include/corecrypto/ccrc2.h create mode 100644 libraries/corecrypto/include/corecrypto/ccrc4.h create mode 100644 libraries/corecrypto/include/corecrypto/ccripemd.h create mode 100644 libraries/corecrypto/include/corecrypto/ccrng.h create mode 100644 libraries/corecrypto/include/corecrypto/ccrng_drbg.h create mode 100644 libraries/corecrypto/include/corecrypto/ccrng_ecfips_test.h create mode 100644 libraries/corecrypto/include/corecrypto/ccrng_pbkdf2_prng.h create mode 100644 libraries/corecrypto/include/corecrypto/ccrng_priv.h create mode 100644 libraries/corecrypto/include/corecrypto/ccrng_rsafips_test.h create mode 100644 libraries/corecrypto/include/corecrypto/ccrng_sequence.h create mode 100644 libraries/corecrypto/include/corecrypto/ccrng_system.h create mode 100644 libraries/corecrypto/include/corecrypto/ccrng_test.h create mode 100644 libraries/corecrypto/include/corecrypto/ccrsa.h create mode 100644 libraries/corecrypto/include/corecrypto/ccrsa_priv.h create mode 100644 libraries/corecrypto/include/corecrypto/ccsha1.h create mode 100644 libraries/corecrypto/include/corecrypto/ccsha2.h create mode 100644 libraries/corecrypto/include/corecrypto/ccsrp.h create mode 100644 libraries/corecrypto/include/corecrypto/ccsrp_gp.h create mode 100644 libraries/corecrypto/include/corecrypto/cctest.h create mode 100644 libraries/corecrypto/include/corecrypto/ccwrap.h create mode 100644 libraries/corecrypto/include/corecrypto/ccz.h create mode 100644 libraries/corecrypto/include/corecrypto/ccz_priv.h create mode 100644 libraries/corecrypto/include/corecrypto/cczp.h create mode 100644 libraries/corecrypto/include/corecrypto/cczp_priv.h create mode 100644 libraries/corecrypto/include/corecrypto/fipspost.h create mode 100644 libraries/corecrypto/include/module.modulemap diff --git a/libraries/corecrypto/Sources/CoreCryptoMacros.swift b/libraries/corecrypto/Sources/CoreCryptoMacros.swift new file mode 100644 index 0000000..9069c30 --- /dev/null +++ b/libraries/corecrypto/Sources/CoreCryptoMacros.swift @@ -0,0 +1,55 @@ +// +// CoreCryptoMacros.swift +// AltSign +// +// Created by Riley Testut on 8/20/20. +// Copyright © 2020 Riley Testut. All rights reserved. +// + +@_exported import CCoreCrypto + +/// Reimplementations of various CoreCrypto macros that are unavailable in Swift. + +public func ccdigest_ctx_size(_ stateSize: Int, _ blockSize: Int) -> Int +{ + (stateSize + MemoryLayout.size + blockSize + MemoryLayout.size) +} + +public func ccdigest_di_size(_ digestInfo: UnsafePointer) -> Int +{ + ccdigest_ctx_size(digestInfo.pointee.state_size, digestInfo.pointee.block_size) +} + +public func ccsrp_gpbuf_size(_ group: ccdh_const_gp_t) -> Int +{ + ccdh_ccn_size(group) * 4 +} + +public func ccsrp_dibuf_size(_ digestInfo: UnsafePointer) -> Int +{ + digestInfo.pointee.output_size * 4 +} + +public func ccsrp_sizeof_srp(_ digestInfo: UnsafePointer, _ group: ccdh_const_gp_t) -> Int +{ + MemoryLayout.size + ccsrp_gpbuf_size(group) + ccsrp_dibuf_size(digestInfo) +} + +public func cchmac_ctx_size(_ stateSize: Int, _ blockSize: Int) -> Int +{ + ccdigest_ctx_size(stateSize, blockSize) + stateSize +} + +public func cchmac_di_size(_ digestInfo: UnsafePointer) -> Int +{ + if #available(iOS 14, macOS 11, *) + { + // CoreCrypto headers aren't accurate for iOS 14 or macOS 11 yet, + // so return bigger buffer size to ensure against invalid memory access. + return cchmac_ctx_size(digestInfo.pointee.state_size, digestInfo.pointee.block_size) * 2 + } + else + { + return cchmac_ctx_size(digestInfo.pointee.state_size, digestInfo.pointee.block_size) + } +} diff --git a/libraries/corecrypto/Sources/ccsrp.m b/libraries/corecrypto/Sources/ccsrp.m new file mode 100644 index 0000000..922bdda --- /dev/null +++ b/libraries/corecrypto/Sources/ccsrp.m @@ -0,0 +1,30 @@ +// +// ccsrp.c +// AltSign +// +// Created by Riley Testut on 6/25/20. +// Copyright © 2020 Riley Testut. All rights reserved. +// + +#include "ccsrp.h" + +#import + +cc_unit *srp_ccn(void *srp) +{ + // Memory layout of ccsrp_ctx changed between iOS 13/macOS 10.15 and iOS 14/macOS 11. + // Dynamically cast to correct memory layout to ensure we access valid memory. + +#if TARGET_OS_IPHONE + if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){ 14, 0, 0 }]) +#else + if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){ 10, 16, 0 }]) +#endif + { + return SRP_CCN((ccsrp_ctx_t)(srp)); + } + else + { + return SRP_CCN((ccsrp_ctx_t_legacy)(srp)); + } +} diff --git a/libraries/corecrypto/include/corecrypto/cc.h b/libraries/corecrypto/include/corecrypto/cc.h new file mode 100644 index 0000000..df98a5f --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/cc.h @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2010,2011,2012,2014,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CC_H_ +#define _CORECRYPTO_CC_H_ + +#include +#include +#include + +/* Provide a general purpose macro concat method. */ +#define cc_concat_(a, b) a##b +#define cc_concat(a, b) cc_concat_(a, b) + +/* Manage asserts here because a few functions in header public files do use asserts */ +#define cc_assert(x) assert(x) +#if CC_KERNEL +#include +#elif CC_USE_S3 +#define assert(args) // No assert in S3 +#else +#include +#endif + +/* Provide a static assert that can be used to create compile-type failures. */ +#define cc_static_assert(e,m) \ + ;enum { cc_concat(static_assert_, __COUNTER__) = 1/(int)(!!(e)) } + +/* Declare a struct element with a guarenteed alignment of _alignment_. + The resulting struct can be used to create arrays that are aligned by + a certain amount. */ +#define cc_aligned_struct(_alignment_) \ +typedef struct { \ +uint8_t b[_alignment_]; \ +} CC_ALIGNED(_alignment_) + +/* number of array elements used in a cc_ctx_decl */ +#define cc_ctx_n(_type_, _size_) ((_size_ + sizeof(_type_) - 1) / sizeof(_type_)) + +/* sizeof of a context declared with cc_ctx_decl */ +#define cc_ctx_sizeof(_type_, _size_) sizeof(_type_[cc_ctx_n(_type_, _size_)]) + +/* + 1. _alloca cannot be removed becasue this header file is compiled with both MSVC++ and with clang. + 2. The _MSC_VER version of cc_ctx_decl() is not compatible with the way *_decl macros as used in CommonCrypto, AppleKeyStore and SecurityFrameworks. To observe the incompatibilities and errors, use below definition. Corecrypto itself, accepts both deinitions + #define cc_ctx_decl(_type_, _size_, _name_) _type_ _name_ ## _array[cc_ctx_n(_type_, (_size_))]; _type_ *_name_ = _name_ ## _array + 3. Never use sizeof() operator for the variables declared with cc_ctx_decl(), because it is not be compatible with the _MSC_VER version of cc_ctx_decl(). + */ +#if defined(_MSC_VER) +#define cc_ctx_decl(_type_, _size_, _name_) _type_ * _name_ = (_type_ *) _alloca(sizeof(_type_) * cc_ctx_n(_type_, _size_) ) +#else +#define cc_ctx_decl(_type_, _size_, _name_) _type_ _name_ [cc_ctx_n(_type_, _size_)] +#endif + +/* bzero is deprecated. memset is the way to go */ +/* FWIW, L4, HEXAGON and ARMCC even with gnu compatibility mode don't have bzero */ +#define cc_zero(_size_,_data_) memset((_data_),0 ,(_size_)) + +/*! + @brief cc_clear(len, dst) zeroizes array dst and it will not be optimized out. + @discussion It is used to clear sensitive data, particularly when the are defined in the stack + @param len number of bytes to be cleared in dst + @param dst input array + */ +CC_NONNULL2 +void cc_clear(size_t len, void *dst); + +#define cc_copy(_size_, _dst_, _src_) memcpy(_dst_, _src_, _size_) + +CC_INLINE CC_NONNULL2 CC_NONNULL3 CC_NONNULL4 +void cc_xor(size_t size, void *r, const void *s, const void *t) { + uint8_t *_r=(uint8_t *)r; + const uint8_t *_s=(const uint8_t *)s; + const uint8_t *_t=(const uint8_t *)t; + while (size--) { + _r[size] = _s[size] ^ _t[size]; + } +} + +/*! + @brief cc_cmp_safe(num, pt1, pt2) compares two array ptr1 and ptr2 of num bytes. + @discussion The execution time/cycles is independent of the data and therefore guarantees no leak about the data. However, the execution time depends on num. + @param num number of bytes in each array + @param ptr1 input array + @param ptr2 input array + @return returns 0 if the num bytes starting at ptr1 are identical to the num bytes starting at ptr2 and 1 if they are different or if num is 0 (empty arrays). + */ +CC_NONNULL2 CC_NONNULL3 +int cc_cmp_safe (size_t num, const void * ptr1, const void * ptr2); + +/* Exchange S and T of any type. NOTE: Both and S and T are evaluated + mutliple times and MUST NOT be expressions. */ +#define CC_SWAP(S,T) do { \ + __typeof__(S) _cc_swap_tmp = S; S = T; T = _cc_swap_tmp; \ +} while(0) + +/* Return the maximum value between S and T. */ +#define CC_MAX(S, T) ({__typeof__(S) _cc_max_s = S; __typeof__(T) _cc_max_t = T; _cc_max_s > _cc_max_t ? _cc_max_s : _cc_max_t;}) + +/* Return the minimum value between S and T. */ +#define CC_MIN(S, T) ({__typeof__(S) _cc_min_s = S; __typeof__(T) _cc_min_t = T; _cc_min_s <= _cc_min_t ? _cc_min_s : _cc_min_t;}) + +#endif /* _CORECRYPTO_CC_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/cc_config.h b/libraries/corecrypto/include/corecrypto/cc_config.h new file mode 100644 index 0000000..2c7733c --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/cc_config.h @@ -0,0 +1,560 @@ +/* + * Copyright (c) 2010,2011,2012,2013,2014,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CC_CONFIG_H_ +#define _CORECRYPTO_CC_CONFIG_H_ + +/* A word about configuration macros: + + Conditional configuration macros specific to corecrypto should be named CORECRYPTO_xxx + or CCxx_yyy and be defined to be either 0 or 1 in this file. You can add an + #ifndef #error construct at the end of this file to make sure it's always defined. + + They should always be tested using the #if directive, never the #ifdef directive. + + No other conditional macros shall ever be used (except in this file) + + Configuration Macros that are defined outside of corecrypto (eg: KERNEL, DEBUG, ...) + shall only be used in this file to define CCxxx macros. + + External macros should be assumed to be either undefined, defined with no value, + or defined as true or false. We shall strive to build with -Wundef whenever possible, + so the following construct should be used to test external macros in this file: + + #if defined(DEBUG) && (DEBUG) + #define CORECRYPTO_DEBUG 1 + #else + #define CORECRYPTO_DEBUG 0 + #endif + + + It is acceptable to define a conditional CC_xxxx macro in an implementation file, + to be used only in this file. + + The current code is not guaranteed to follow those rules, but should be fixed to. + + Corecrypto requires GNU and C99 compatibility. + Typically enabled by passing --gnu --c99 to the compiler (eg. armcc) + +*/ + +#define CORECRYPTO_PUBLIC_SDK 1 + +//Do not set this macros to 1, unless you are developing/testing for Linux under macOS +#define CORECRYPTO_SIMULATE_POSIX_ENVIRONMENT 0 + +//Do not set these macros to 1, unless you are developing/testing for Windows under macOS +#define CORECRYPTO_SIMULATE_WINDOWS_ENVIRONMENT 0 +#define CORECRYPTO_HACK_FOR_WINDOWS_DEVELOPMENT 0 + +//this macro is used to turn on/off usage of transparent union in corecrypto +//it should be commented out in corecrypto and be used only by the software that use corecrypto +//#define CORECRYPTO_DONOT_USE_TRANSPARENT_UNION +#if defined(__cplusplus) +#define CORECRYPTO_USE_TRANSPARENT_UNION 0 +#elif defined(CORECRYPTO_DONOT_USE_TRANSPARENT_UNION) + #define CORECRYPTO_USE_TRANSPARENT_UNION !CORECRYPTO_DONOT_USE_TRANSPARENT_UNION +#else + #define CORECRYPTO_USE_TRANSPARENT_UNION 1 +#endif + +#if (defined(DEBUG) && (DEBUG)) || defined(_DEBUG) //MSVC defines _DEBUG +/* CC_DEBUG is already used in CommonCrypto */ + #define CORECRYPTO_DEBUG 1 +#else + #define CORECRYPTO_DEBUG 0 +#endif + +// This macro can be used to enable prints when a condition in the macro "cc_require" +// is false. This is especially useful to confirm that negative testing fails +// at the intended location +#define CORECRYPTO_DEBUG_ENABLE_CC_REQUIRE_PRINTS 0 + +#if defined(KERNEL) && (KERNEL) + #define CC_KERNEL 1 // KEXT, XNU repo or kernel components such as AppleKeyStore +#else + #define CC_KERNEL 0 +#endif + +#if defined(__linux__) || CORECRYPTO_SIMULATE_POSIX_ENVIRONMENT + #define CC_LINUX 1 +#else + #define CC_LINUX 0 +#endif + +#if defined(USE_L4) && (USE_L4) + #define CC_USE_L4 1 +#else + #define CC_USE_L4 0 +#endif + +#if defined(USE_SEPROM) && (USE_SEPROM) + #define CC_USE_SEPROM 1 +#else + #define CC_USE_SEPROM 0 +#endif + +#if defined(USE_S3) && (USE_S3) + #define CC_USE_S3 1 +#else + #define CC_USE_S3 0 +#endif + +#if (defined(ICE_FEATURES_ENABLED)) || (defined(MAVERICK) && (MAVERICK)) + #define CC_BASEBAND 1 +#else + #define CC_BASEBAND 0 +#endif + +#if defined(EFI) && (EFI) + #define CC_EFI 1 +#else + #define CC_EFI 0 +#endif + +#if defined(IBOOT) && (IBOOT) + #define CC_IBOOT 1 +#else + #define CC_IBOOT 0 +#endif + +// Defined by the XNU build scripts +// Applies to code embedded in XNU but NOT to the kext +#if defined(XNU_KERNEL_PRIVATE) + #define CC_XNU_KERNEL_PRIVATE 1 +#else + #define CC_XNU_KERNEL_PRIVATE 0 +#endif + +// handle unaligned data, if the cpu cannot. Currently for gladman AES and the C version of the SHA256 +#define CC_HANDLE_UNALIGNED_DATA CC_BASEBAND + +// BaseBand configuration +#if CC_BASEBAND + +// -- ENDIANESS +#if !defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__) + #if defined(ENDIAN_LITTLE) || (defined(__arm__) && !defined(__BIG_ENDIAN)) + #define __LITTLE_ENDIAN__ + #elif !defined(ENDIAN_BIG) && !defined(__BIG_ENDIAN) + #error Baseband endianess not defined. + #endif + #define AESOPT_ENDIAN_NO_FILE +#endif + +// -- Architecture + #define CCN_UNIT_SIZE 4 // 32 bits + +// -- External function + #define assert ASSERT // sanity + +// -- Warnings +// Ignore irrelevant warnings after verification +// #1254-D: arithmetic on pointer to void or function type +// #186-D: pointless comparison of unsigned integer with zero +// #546-D: transfer of control bypasses initialization of + #ifdef __arm__ + #pragma diag_suppress 186, 1254,546 + #elif defined(__GNUC__) +// warning: pointer of type 'void *' used in arithmetic + #pragma GCC diagnostic ignored "-Wpointer-arith" + #endif // __arm__ +#endif // CC_BASEBAND + +//CC_XNU_KERNEL_AVAILABLE indicates the availibity of XNU kernel functions, +//like what we have on OSX, iOS, tvOS, Watch OS +#if defined(__APPLE__) && defined(__MACH__) + #define CC_XNU_KERNEL_AVAILABLE 1 +#else + #define CC_XNU_KERNEL_AVAILABLE 0 +#endif + +//arm arch64 definition for gcc +#if defined(__GNUC__) && defined(__aarch64__) && !defined(__arm64__) + #define __arm64__ +#endif + +#if !defined(CCN_UNIT_SIZE) + #if defined(__arm64__) || defined(__x86_64__) || defined(_WIN64) + #define CCN_UNIT_SIZE 8 + #elif defined(__arm__) || defined(__i386__) || defined(_WIN32) + #define CCN_UNIT_SIZE 4 + #else + #error undefined architecture + #endif +#endif /* !defined(CCN_UNIT_SIZE) */ + + +//this allows corecrypto Windows development using xcode +#if defined(CORECRYPTO_SIMULATE_WINDOWS_ENVIRONMENT) + #if CORECRYPTO_SIMULATE_WINDOWS_ENVIRONMENT && CC_XNU_KERNEL_AVAILABLE && CORECRYPTO_DEBUG + #define CC_USE_ASM 0 + #define CC_USE_HEAP_FOR_WORKSPACE 1 + #if (CCN_UNIT_SIZE==8) + #define CCN_UINT128_SUPPORT_FOR_64BIT_ARCH 0 + #else + #define CCN_UINT128_SUPPORT_FOR_64BIT_ARCH 1 + #endif + #endif +#endif + +#if !defined(CCN_UINT128_SUPPORT_FOR_64BIT_ARCH) + #if defined(_WIN64) && defined(_WIN32) && (CCN_UNIT_SIZE==8) + #define CCN_UINT128_SUPPORT_FOR_64BIT_ARCH 0 + #elif defined(_WIN32) + #define CCN_UINT128_SUPPORT_FOR_64BIT_ARCH 1//should not be a problem + #else + #define CCN_UINT128_SUPPORT_FOR_64BIT_ARCH 1 + #endif +#endif + +#if defined(_MSC_VER) + #if defined(__clang__) + #define CC_ALIGNED(x) __attribute__ ((aligned(x))) //clang compiler + #else + #define CC_ALIGNED(x) __declspec(align(x)) //MS complier + #endif +#else + #if __clang__ || CCN_UNIT_SIZE==8 + #define CC_ALIGNED(x) __attribute__ ((aligned(x))) + #else + #define CC_ALIGNED(x) __attribute__ ((aligned((x)>8?8:(x)))) + #endif +#endif + +#if defined(__arm__) +//this is copied from , because is not available on SEPROM environment + #if defined (__ARM_ARCH_7A__) || defined (__ARM_ARCH_7S__) || defined (__ARM_ARCH_7F__) || defined (__ARM_ARCH_7K__) + #define _ARM_ARCH_7 + #endif + + #if defined(__ARM_ARCH_6M__) || defined(__TARGET_ARCH_6S_M) || defined (__armv6m__) + #define _ARM_ARCH_6M + #endif +#endif + +#if defined(__arm64__) || defined(__arm__) + #define CCN_IOS 1 + #define CCN_OSX 0 +#elif defined(__x86_64__) || defined(__i386__) + #define CCN_IOS 0 + #define CCN_OSX 1 +#endif + +#if CC_USE_L4 || CC_USE_S3 +/* No dynamic linking allowed in L4, e.g. avoid nonlazy symbols */ +/* For corecrypto kext, CC_STATIC should be undefined */ + #define CC_STATIC 1 +#endif + +#if !defined(CC_USE_HEAP_FOR_WORKSPACE) + #if CC_USE_S3 || CC_USE_SEPROM + #define CC_USE_HEAP_FOR_WORKSPACE 0 + #else + #define CC_USE_HEAP_FOR_WORKSPACE 1 + #endif +#endif + +/* memset_s is only available in few target */ +#if CC_USE_SEPROM || defined(__CC_ARM) \ + || defined(__hexagon__) || CC_EFI + #define CC_HAS_MEMSET_S 0 +#else + #define CC_HAS_MEMSET_S 1 +#endif + +// Include target conditionals if available. +#if defined(__has_include) /* portability */ +#if __has_include() +#include +#endif /* __has_include() */ +#endif /* defined(__has_include) */ + +// Disable RSA Keygen on iBridge +#if defined(TARGET_OS_BRIDGE) && TARGET_OS_BRIDGE && CC_KERNEL +#define CC_DISABLE_RSAKEYGEN 1 /* for iBridge */ +#else +#define CC_DISABLE_RSAKEYGEN 0 /* default */ +#endif + +//- functions implemented in assembly ------------------------------------------ +//this the list of corecrypto clients that use assembly and the clang compiler +#if !(CC_XNU_KERNEL_AVAILABLE || CC_KERNEL || CC_USE_L4 || CC_IBOOT || CC_USE_SEPROM || CC_USE_S3) && !defined(_WIN32) && CORECRYPTO_DEBUG + #warning "You are using the default corecrypto configuration, assembly optimizations may not be available for your platform" +#endif + +// Use this macro to strictly disable assembly regardless of cpu/os/compiler/etc. +// Our assembly code is not gcc compatible. Clang defines the __GNUC__ macro as well. +#if !defined(CC_USE_ASM) + #if defined(_WIN32) || CC_EFI || CC_BASEBAND || CC_XNU_KERNEL_PRIVATE || (defined(__GNUC__) && !defined(__clang__)) + #define CC_USE_ASM 0 + #else + #define CC_USE_ASM 1 + #endif +#endif + +//-(1) ARM V7 +#if defined(_ARM_ARCH_7) && __clang__ && CC_USE_ASM + #define CCN_DEDICATED_SQR 1 + #define CCN_MUL_KARATSUBA 0 // no performance improvement + #define CCN_ADD_ASM 1 + #define CCN_SUB_ASM 1 + #define CCN_MUL_ASM 0 + #define CCN_ADDMUL1_ASM 1 + #define CCN_MUL1_ASM 1 + #define CCN_CMP_ASM 1 + #define CCN_ADD1_ASM 0 + #define CCN_SUB1_ASM 0 + #define CCN_N_ASM 1 + #define CCN_SET_ASM 1 + #define CCN_SHIFT_RIGHT_ASM 1 + #define CCAES_ARM_ASM 1 + #define CCAES_INTEL_ASM 0 + #if CC_KERNEL || CC_USE_L4 || CC_IBOOT || CC_USE_SEPROM || CC_USE_S3 + #define CCAES_MUX 0 + #else + #define CCAES_MUX 1 + #endif + #define CCN_USE_BUILTIN_CLZ 1 + #define CCSHA1_VNG_INTEL 0 + #define CCSHA2_VNG_INTEL 0 + + #if defined(__ARM_NEON__) || CC_KERNEL + #define CCSHA1_VNG_ARMV7NEON 1 + #define CCSHA2_VNG_ARMV7NEON 1 + #else /* !defined(__ARM_NEON__) */ + #define CCSHA1_VNG_ARMV7NEON 0 + #define CCSHA2_VNG_ARMV7NEON 0 + #endif /* !defined(__ARM_NEON__) */ + #define CCSHA256_ARMV6M_ASM 0 + +//-(2) ARM 64 +#elif defined(__arm64__) && __clang__ && CC_USE_ASM + #define CCN_DEDICATED_SQR 1 + #define CCN_MUL_KARATSUBA 1 // 4*n CCN_UNIT extra memory required. + #define CCN_ADD_ASM 1 + #define CCN_SUB_ASM 1 + #define CCN_MUL_ASM 1 + #define CCN_ADDMUL1_ASM 0 + #define CCN_MUL1_ASM 0 + #define CCN_CMP_ASM 1 + #define CCN_ADD1_ASM 0 + #define CCN_SUB1_ASM 0 + #define CCN_N_ASM 1 + #define CCN_SET_ASM 0 + #define CCN_SHIFT_RIGHT_ASM 1 + #define CCAES_ARM_ASM 1 + #define CCAES_INTEL_ASM 0 + #define CCAES_MUX 0 // On 64bit SoC, asm is much faster than HW + #define CCN_USE_BUILTIN_CLZ 1 + #define CCSHA1_VNG_INTEL 0 + #define CCSHA2_VNG_INTEL 0 + #define CCSHA1_VNG_ARMV7NEON 1 // reused this to avoid making change to xcode project, put arm64 assembly code with armv7 code + #define CCSHA2_VNG_ARMV7NEON 1 + #define CCSHA256_ARMV6M_ASM 0 + +//-(3) Intel 32/64 +#elif (defined(__x86_64__) || defined(__i386__)) && __clang__ && CC_USE_ASM + #define CCN_DEDICATED_SQR 1 + #define CCN_MUL_KARATSUBA 1 // 4*n CCN_UNIT extra memory required. + /* These assembly routines only work for a single CCN_UNIT_SIZE. */ + #if (defined(__x86_64__) && CCN_UNIT_SIZE == 8) || (defined(__i386__) && CCN_UNIT_SIZE == 4) + #define CCN_ADD_ASM 1 + #define CCN_SUB_ASM 1 + #define CCN_MUL_ASM 1 + #else + #define CCN_ADD_ASM 0 + #define CCN_SUB_ASM 0 + #define CCN_MUL_ASM 0 + #endif + + #if (defined(__x86_64__) && CCN_UNIT_SIZE == 8) + #define CCN_CMP_ASM 1 + #define CCN_N_ASM 1 + #define CCN_SHIFT_RIGHT_ASM 1 + #else + #define CCN_CMP_ASM 0 + #define CCN_N_ASM 0 + #define CCN_SHIFT_RIGHT_ASM 0 + #endif + + #define CCN_ADDMUL1_ASM 0 + #define CCN_MUL1_ASM 0 + #define CCN_ADD1_ASM 0 + #define CCN_SUB1_ASM 0 + #define CCN_SET_ASM 0 + #define CCAES_ARM_ASM 0 + #define CCAES_INTEL_ASM 1 + #define CCAES_MUX 0 + #define CCN_USE_BUILTIN_CLZ 0 + #define CCSHA1_VNG_INTEL 1 + #define CCSHA2_VNG_INTEL 1 + #define CCSHA1_VNG_ARMV7NEON 0 + #define CCSHA2_VNG_ARMV7NEON 0 + #define CCSHA256_ARMV6M_ASM 0 + +//-(4) disable assembly +#else + #if CCN_UINT128_SUPPORT_FOR_64BIT_ARCH + #define CCN_DEDICATED_SQR 1 + #else + #define CCN_DEDICATED_SQR 0 //when assembly is off and 128-bit integers are not supported, dedicated square is off. This is the case on Windows + #endif + #define CCN_MUL_KARATSUBA 1 // 4*n CCN_UNIT extra memory required. + #define CCN_ADD_ASM 0 + #define CCN_SUB_ASM 0 + #define CCN_MUL_ASM 0 + #define CCN_ADDMUL1_ASM 0 + #define CCN_MUL1_ASM 0 + #define CCN_CMP_ASM 0 + #define CCN_ADD1_ASM 0 + #define CCN_SUB1_ASM 0 + #define CCN_N_ASM 0 + #define CCN_SET_ASM 0 + #define CCN_SHIFT_RIGHT_ASM 0 + #define CCAES_ARM_ASM 0 + #define CCAES_INTEL_ASM 0 + #define CCAES_MUX 0 + #define CCN_USE_BUILTIN_CLZ 0 + #define CCSHA1_VNG_INTEL 0 + #define CCSHA2_VNG_INTEL 0 + #define CCSHA1_VNG_ARMV7NEON 0 + #define CCSHA2_VNG_ARMV7NEON 0 + #define CCSHA256_ARMV6M_ASM 0 + +#endif + +#define CC_INLINE static inline + +#if CORECRYPTO_USE_TRANSPARENT_UNION +// Non null for transparent unions is ambiguous and cause problems +// for most tools (GCC and others: 23919290). + #define CC_NONNULL_TU(N) +#else + #define CC_NONNULL_TU(N) CC_NONNULL(N) +#endif + +#ifdef __GNUC__ + #define CC_NORETURN __attribute__((__noreturn__)) + #define CC_NOTHROW __attribute__((__nothrow__)) + #define CC_NONNULL(N) __attribute__((__nonnull__ N)) + #define CC_NONNULL1 __attribute__((__nonnull__(1))) + #define CC_NONNULL2 __attribute__((__nonnull__(2))) + #define CC_NONNULL3 __attribute__((__nonnull__(3))) + #define CC_NONNULL4 __attribute__((__nonnull__(4))) + #define CC_NONNULL5 __attribute__((__nonnull__(5))) + #define CC_NONNULL6 __attribute__((__nonnull__(6))) + #define CC_NONNULL7 __attribute__((__nonnull__(7))) + #define CC_NONNULL_ALL __attribute__((__nonnull__)) + #define CC_SENTINEL __attribute__((__sentinel__)) + #define CC_CONST __attribute__((__const__)) + #define CC_PURE __attribute__((__pure__)) + #define CC_WARN_RESULT __attribute__((__warn_unused_result__)) + #define CC_MALLOC __attribute__((__malloc__)) + #define CC_UNUSED __attribute__((unused)) +#else /* !__GNUC__ */ +/*! @parseOnly */ + #define CC_UNUSED +/*! @parseOnly */ + #define CC_NONNULL(N) +/*! @parseOnly */ + #define CC_NORETURN +/*! @parseOnly */ + #define CC_NOTHROW +/*! @parseOnly */ + #define CC_NONNULL1 +/*! @parseOnly */ + #define CC_NONNULL2 +/*! @parseOnly */ + #define CC_NONNULL3 +/*! @parseOnly */ + #define CC_NONNULL4 +/*! @parseOnly */ + #define CC_NONNULL5 +/*! @parseOnly */ + #define CC_NONNULL6 +/*! @parseOnly */ + #define CC_NONNULL7 +/*! @parseOnly */ + #define CC_NONNULL_ALL +/*! @parseOnly */ + #define CC_SENTINEL +/*! @parseOnly */ + #define CC_CONST +/*! @parseOnly */ + #define CC_PURE +/*! @parseOnly */ + #define CC_WARN_RESULT +/*! @parseOnly */ + #define CC_MALLOC +#endif /* !__GNUC__ */ + +// Enable FIPSPOST function tracing only when supported. */ +#ifdef CORECRYPTO_POST_TRACE +#define CC_FIPSPOST_TRACE 1 +#else +#define CC_FIPSPOST_TRACE 0 +#endif + +#endif /* _CORECRYPTO_CC_CONFIG_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/cc_debug.h b/libraries/corecrypto/include/corecrypto/cc_debug.h new file mode 100644 index 0000000..5a5f1b9 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/cc_debug.h @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2012,2014,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +//debug configuration header file +#ifndef _CORECRYPTO_CCN_DEBUG_H_ +#define _CORECRYPTO_CCN_DEBUG_H_ + +#include + +// DO NOT INCLUDE this HEADER file in CoreCrypto files added for XNU project or headers +// included by external clients. + +// ======================== +// Printf for corecrypto +// ======================== +#if CC_KERNEL + #include + #define cc_printf(x...) kprintf(x) + #if !CONFIG_EMBEDDED + extern int printf(const char *format, ...) __printflike(1,2); + #endif +#elif CC_USE_S3 || CC_IBOOT + #include + #define cc_printf(x...) printf(x) +#else + #include + #define cc_printf(x...) fprintf(stderr, x) +#endif + +// ======================== +// Integer types +// ======================== + +#if CC_KERNEL +/* Those are not defined in libkern */ +#define PRIx64 "llx" +#define PRIx32 "x" +#define PRIx16 "hx" +#define PRIx8 "hhx" +#else +#include +#endif + +#if CCN_UNIT_SIZE == 8 +#define CCPRIx_UNIT ".016" PRIx64 +#elif CCN_UNIT_SIZE == 4 +#define CCPRIx_UNIT ".08" PRIx32 +#elif CCN_UNIT_SIZE == 2 +#define CCPRIx_UNIT ".04" PRIx16 +#elif CCN_UNIT_SIZE == 1 +#define CCPRIx_UNIT ".02" PRIx8 +#else +#error invalid CCN_UNIT_SIZE +#endif + +// ======================== +// Print utilities for corecrypto +// ======================== + +#include + +/* Print a byte array of arbitrary size */ +void cc_print(const char *label, size_t count, const uint8_t *s); + +#endif /* _CORECRYPTO_CCN_DEBUG_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/cc_memory.h b/libraries/corecrypto/include/corecrypto/cc_memory.h new file mode 100644 index 0000000..4a0712b --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/cc_memory.h @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2014,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef corecrypto_cc_memory_h +#define corecrypto_cc_memory_h + +#if CORECRYPTO_DEBUG +extern void *g_ws_start; +#endif + +#include +#include "cc_debug.h" +#include + + +CC_INLINE void cc_alloc_debug(CC_UNUSED void *p) { +#if CORECRYPTO_DEBUG + // Contract for some client is to have a single malloc at a time + cc_assert(g_ws_start==NULL); + g_ws_start=p; +#endif +} + +CC_INLINE void cc_free_debug(CC_UNUSED void *p) { +#if CORECRYPTO_DEBUG + // Contract for some client is to have a single malloc at a time + cc_assert(g_ws_start==p); // Free the address we allocated + g_ws_start=NULL; +#endif +} + +// Add specific error for memory allocation failure +// which does not overlap with others +#define CCERR_MEMORY_ALLOC_FAIL -200 + +// ============================================================================= +// Declare workspace with memory in STACK +// This is the least preferred option since most corecrypto client have +// small stack. It is still useful when needing small allocations and errors +// can't be easily propagated +// ============================================================================= + +// Declare a variable in stack and use its address +// Only uses this when we don't have a way to propagate error +#define CC_DECL_WORKSPACE_STACK(ws,n) \ + cc_unit tmp_##__FILE__##__LINE__[(n)]; \ + cc_ws _ws={&tmp_##__FILE__##__LINE__[0],&tmp_##__FILE__##__LINE__[(n)]}; \ + cc_ws_t ws=&_ws; \ + cc_alloc_debug(ws->start); + +// Reset pointers to avoid future reference +#define CC_FREE_WORKSPACE_STACK(_ws) \ + cc_free_debug(ws->start); \ + ws->start=NULL; \ + ws->end=NULL; + +#define CC_CLEAR_AND_FREE_WORKSPACE_STACK(ws) { \ + cc_assert(ws->startend); \ + ccn_clear(ws->end - ws->start,ws->start); \ + CC_FREE_WORKSPACE_STACK(ws);} + +// ============================================================================= +// Declare workspace in the region correspding to HEAP or STACK +// depending on the setting of CC_USE_HEAP_FOR_WORKSPACE +// This should be the preference for large memory allocations but it requires +// to propagate error in case of allocation failure +// ============================================================================= +#if CC_USE_HEAP_FOR_WORKSPACE + +// Malloc/free functions to be used +#if CC_KERNEL +#include +CC_INLINE void *cc_malloc(size_t s) +{ + return IOMalloc(s); +} +CC_INLINE void cc_free(void *p,size_t size) +{ + IOFree(p,size); +} +#else +#include +CC_INLINE void *cc_malloc(size_t s) +{ + return malloc(s); +} +CC_INLINE void cc_free(void *p,size_t size CC_UNUSED) +{ + free(p); +} + +#endif + +#define CC_DECL_WORKSPACE_OR_FAIL(ws,n) \ + cc_unit* tmp_##__FILE__##__LINE__=cc_malloc(ccn_sizeof_n((n))); \ + cc_ws _ws={&tmp_##__FILE__##__LINE__[0],&tmp_##__FILE__##__LINE__[(n)]}; \ + cc_ws_t ws=&_ws; \ + if (NULL == ws->start) return CCERR_MEMORY_ALLOC_FAIL; \ + cc_alloc_debug(ws->start); + +// Free and reset pointers to avoid future references +#define CC_FREE_WORKSPACE(ws) \ + cc_free_debug(ws->start); \ + cc_free(ws->start,(ws->end - ws->start)*sizeof(ws->start[0])); \ + ws->start=NULL; \ + ws->end=NULL; + +#else // not CC_USE_HEAP_FOR_WORKSPACE + +// Declare a variable in stack and use its address +// Could use alloca but alloca is not so portable, and not secure. +#define CC_DECL_WORKSPACE_OR_FAIL CC_DECL_WORKSPACE_STACK + +// Reset pointers to avoid future reference +#define CC_FREE_WORKSPACE CC_FREE_WORKSPACE_STACK + +#endif // CC_USE_HEAP_FOR_WORKSPACE + +// ============================================================================= +// Common +// ============================================================================= + +#define CC_CLEAR_AND_FREE_WORKSPACE(ws) { \ + cc_assert(ws->startend); \ + ccn_clear(ws->end - ws->start,ws->start); \ + CC_FREE_WORKSPACE(ws);} + +#endif // corecrypto_cc_memory_h diff --git a/libraries/corecrypto/include/corecrypto/cc_priv.h b/libraries/corecrypto/include/corecrypto/cc_priv.h new file mode 100644 index 0000000..2065c44 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/cc_priv.h @@ -0,0 +1,530 @@ +/* + * Copyright (c) 2010,2011,2012,2014,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CC_PRIV_H_ +#define _CORECRYPTO_CC_PRIV_H_ + +#include +#include + +/* defines the following macros : + + CC_MEMCPY : optimized memcpy. + CC_MEMMOVE : optimized memmove. + CC_MEMSET : optimized memset. + + CC_STORE32_BE : store 32 bit value in big endian in unaligned buffer. + CC_STORE32_LE : store 32 bit value in little endian in unaligned buffer. + CC_STORE64_BE : store 64 bit value in big endian in unaligned buffer. + CC_STORE64_LE : store 64 bit value in little endian in unaligned buffer. + + CC_LOAD32_BE : load 32 bit value in big endian from unaligned buffer. + CC_LOAD32_LE : load 32 bit value in little endian from unaligned buffer. + CC_LOAD64_BE : load 64 bit value in big endian from unaligned buffer. + CC_LOAD64_LE : load 64 bit value in little endian from unaligned buffer. + + CC_ROR : Rotate Right 32 bits. Rotate count can be a variable. + CC_ROL : Rotate Left 32 bits. Rotate count can be a variable. + CC_RORc : Rotate Right 32 bits. Rotate count must be a constant. + CC_ROLc : Rotate Left 32 bits. Rotate count must be a constant. + + CC_ROR64 : Rotate Right 64 bits. Rotate count can be a variable. + CC_ROL64 : Rotate Left 64 bits. Rotate count can be a variable. + CC_ROR64c : Rotate Right 64 bits. Rotate count must be a constant. + CC_ROL64c : Rotate Left 64 bits. Rotate count must be a constant. + + CC_BSWAP : byte swap a 32 bits variable. + + CC_H2BE32 : convert a 32 bits value between host and big endian order. + CC_H2LE32 : convert a 32 bits value between host and little endian order. + +The following are not defined yet... define them if needed. + + CC_BSWAPc : byte swap a 32 bits constant + + CC_BSWAP64 : byte swap a 64 bits variable + CC_BSWAP64c : byte swap a 64 bits constant + + CC_READ_LE32 : read a 32 bits little endian value + + CC_WRITE_LE32 : write a 32 bits little endian value + CC_WRITE_LE64 : write a 64 bits little endian value + + CC_H2BE64 : convert a 64 bits value between host and big endian order + CC_H2LE64 : convert a 64 bits value between host and little endian order + +*/ + +/* TODO: optimized versions */ +#define CC_MEMCPY(D,S,L) memcpy((D),(S),(L)) +#define CC_MEMMOVE(D,S,L) memmove((D),(S),(L)) +#define CC_MEMSET(D,V,L) memset((D),(V),(L)) + +// MARK: - Loads and Store + +// MARK: -- 32 bits - little endian + +// MARK: --- Default version + +#define CC_STORE32_LE(x, y) do { \ + ((unsigned char *)(y))[3] = (unsigned char)(((x)>>24)&255); \ + ((unsigned char *)(y))[2] = (unsigned char)(((x)>>16)&255); \ + ((unsigned char *)(y))[1] = (unsigned char)(((x)>>8)&255); \ + ((unsigned char *)(y))[0] = (unsigned char)((x)&255); \ +} while(0) + +#define CC_LOAD32_LE(x, y) do { \ +x = ((uint32_t)(((const unsigned char *)(y))[3] & 255)<<24) | \ + ((uint32_t)(((const unsigned char *)(y))[2] & 255)<<16) | \ + ((uint32_t)(((const unsigned char *)(y))[1] & 255)<<8) | \ + ((uint32_t)(((const unsigned char *)(y))[0] & 255)); \ +} while(0) + +// MARK: -- 64 bits - little endian + +#define CC_STORE64_LE(x, y) do { \ + ((unsigned char *)(y))[7] = (unsigned char)(((x)>>56)&255); \ + ((unsigned char *)(y))[6] = (unsigned char)(((x)>>48)&255); \ + ((unsigned char *)(y))[5] = (unsigned char)(((x)>>40)&255); \ + ((unsigned char *)(y))[4] = (unsigned char)(((x)>>32)&255); \ + ((unsigned char *)(y))[3] = (unsigned char)(((x)>>24)&255); \ + ((unsigned char *)(y))[2] = (unsigned char)(((x)>>16)&255); \ + ((unsigned char *)(y))[1] = (unsigned char)(((x)>>8)&255); \ + ((unsigned char *)(y))[0] = (unsigned char)((x)&255); \ +} while(0) + +#define CC_LOAD64_LE(x, y) do { \ +x = (((uint64_t)(((const unsigned char *)(y))[7] & 255))<<56) | \ + (((uint64_t)(((const unsigned char *)(y))[6] & 255))<<48) | \ + (((uint64_t)(((const unsigned char *)(y))[5] & 255))<<40) | \ + (((uint64_t)(((const unsigned char *)(y))[4] & 255))<<32) | \ + (((uint64_t)(((const unsigned char *)(y))[3] & 255))<<24) | \ + (((uint64_t)(((const unsigned char *)(y))[2] & 255))<<16) | \ + (((uint64_t)(((const unsigned char *)(y))[1] & 255))<<8) | \ + (((uint64_t)(((const unsigned char *)(y))[0] & 255))); \ +} while(0) + +// MARK: -- 32 bits - big endian +// MARK: --- intel version + +#if (defined(__i386__) || defined(__x86_64__)) && !defined(_MSC_VER) + +#define CC_STORE32_BE(x, y) \ + __asm__ __volatile__ ( \ + "bswapl %0 \n\t" \ + "movl %0,(%1)\n\t" \ + "bswapl %0 \n\t" \ + ::"r"(x), "r"(y)) + +#define CC_LOAD32_BE(x, y) \ + __asm__ __volatile__ ( \ + "movl (%1),%0\n\t" \ + "bswapl %0\n\t" \ + :"=r"(x): "r"(y)) + +#else +// MARK: --- default version +#define CC_STORE32_BE(x, y) do { \ + ((unsigned char *)(y))[0] = (unsigned char)(((x)>>24)&255); \ + ((unsigned char *)(y))[1] = (unsigned char)(((x)>>16)&255); \ + ((unsigned char *)(y))[2] = (unsigned char)(((x)>>8)&255); \ + ((unsigned char *)(y))[3] = (unsigned char)((x)&255); \ +} while(0) + +#define CC_LOAD32_BE(x, y) do { \ +x = ((uint32_t)(((const unsigned char *)(y))[0] & 255)<<24) | \ + ((uint32_t)(((const unsigned char *)(y))[1] & 255)<<16) | \ + ((uint32_t)(((const unsigned char *)(y))[2] & 255)<<8) | \ + ((uint32_t)(((const unsigned char *)(y))[3] & 255)); \ +} while(0) + +#endif + +// MARK: -- 64 bits - big endian + +// MARK: --- intel 64 bits version + +#if defined(__x86_64__) && !defined (_MSC_VER) + +#define CC_STORE64_BE(x, y) \ +__asm__ __volatile__ ( \ +"bswapq %0 \n\t" \ +"movq %0,(%1)\n\t" \ +"bswapq %0 \n\t" \ +::"r"(x), "r"(y)) + +#define CC_LOAD64_BE(x, y) \ +__asm__ __volatile__ ( \ +"movq (%1),%0\n\t" \ +"bswapq %0\n\t" \ +:"=r"(x): "r"(y)) + +#else + +// MARK: --- default version + +#define CC_STORE64_BE(x, y) do { \ + ((unsigned char *)(y))[0] = (unsigned char)(((x)>>56)&255); \ + ((unsigned char *)(y))[1] = (unsigned char)(((x)>>48)&255); \ + ((unsigned char *)(y))[2] = (unsigned char)(((x)>>40)&255); \ + ((unsigned char *)(y))[3] = (unsigned char)(((x)>>32)&255); \ + ((unsigned char *)(y))[4] = (unsigned char)(((x)>>24)&255); \ + ((unsigned char *)(y))[5] = (unsigned char)(((x)>>16)&255); \ + ((unsigned char *)(y))[6] = (unsigned char)(((x)>>8)&255); \ + ((unsigned char *)(y))[7] = (unsigned char)((x)&255); \ +} while(0) + +#define CC_LOAD64_BE(x, y) do { \ +x = (((uint64_t)(((const unsigned char *)(y))[0] & 255))<<56) | \ + (((uint64_t)(((const unsigned char *)(y))[1] & 255))<<48) | \ + (((uint64_t)(((const unsigned char *)(y))[2] & 255))<<40) | \ + (((uint64_t)(((const unsigned char *)(y))[3] & 255))<<32) | \ + (((uint64_t)(((const unsigned char *)(y))[4] & 255))<<24) | \ + (((uint64_t)(((const unsigned char *)(y))[5] & 255))<<16) | \ + (((uint64_t)(((const unsigned char *)(y))[6] & 255))<<8) | \ + (((uint64_t)(((const unsigned char *)(y))[7] & 255))); \ +} while(0) + +#endif + +// MARK: - 32-bit Rotates + +#if defined(_MSC_VER) +// MARK: -- MSVC version + +#include +#if !defined(__clang__) + #pragma intrinsic(_lrotr,_lrotl) +#endif +#define CC_ROR(x,n) _lrotr(x,n) +#define CC_ROL(x,n) _lrotl(x,n) +#define CC_RORc(x,n) _lrotr(x,n) +#define CC_ROLc(x,n) _lrotl(x,n) + +#elif (defined(__i386__) || defined(__x86_64__)) +// MARK: -- intel asm version + +CC_INLINE uint32_t CC_ROL(uint32_t word, int i) +{ + __asm__ ("roll %%cl,%0" + :"=r" (word) + :"0" (word),"c" (i)); + return word; +} + +CC_INLINE uint32_t CC_ROR(uint32_t word, int i) +{ + __asm__ ("rorl %%cl,%0" + :"=r" (word) + :"0" (word),"c" (i)); + return word; +} + +/* Need to be a macro here, because 'i' is an immediate (constant) */ +#define CC_ROLc(word, i) \ +({ uint32_t _word=(word); \ + __asm__ __volatile__ ("roll %2,%0" \ + :"=r" (_word) \ + :"0" (_word),"I" (i)); \ + _word; \ +}) + + +#define CC_RORc(word, i) \ +({ uint32_t _word=(word); \ + __asm__ __volatile__ ("rorl %2,%0" \ + :"=r" (_word) \ + :"0" (_word),"I" (i)); \ + _word; \ +}) + +#else + +// MARK: -- default version + +CC_INLINE uint32_t CC_ROL(uint32_t word, int i) +{ + return ( (word<<(i&31)) | (word>>(32-(i&31))) ); +} + +CC_INLINE uint32_t CC_ROR(uint32_t word, int i) +{ + return ( (word>>(i&31)) | (word<<(32-(i&31))) ); +} + +#define CC_ROLc(x, y) CC_ROL(x, y) +#define CC_RORc(x, y) CC_ROR(x, y) + +#endif + +// MARK: - 64 bits rotates + +#if defined(__x86_64__) && !defined(_MSC_VER) //clang _MSVC doesn't support GNU-style inline assembly +// MARK: -- intel 64 asm version + +CC_INLINE uint64_t CC_ROL64(uint64_t word, int i) +{ + __asm__("rolq %%cl,%0" + :"=r" (word) + :"0" (word),"c" (i)); + return word; +} + +CC_INLINE uint64_t CC_ROR64(uint64_t word, int i) +{ + __asm__("rorq %%cl,%0" + :"=r" (word) + :"0" (word),"c" (i)); + return word; +} + +/* Need to be a macro here, because 'i' is an immediate (constant) */ +#define CC_ROL64c(word, i) \ +({ \ + uint64_t _word=(word); \ + __asm__("rolq %2,%0" \ + :"=r" (_word) \ + :"0" (_word),"J" (i)); \ + _word; \ +}) + +#define CC_ROR64c(word, i) \ +({ \ + uint64_t _word=(word); \ + __asm__("rorq %2,%0" \ + :"=r" (_word) \ + :"0" (_word),"J" (i)); \ + _word; \ +}) + + +#else /* Not x86_64 */ + +// MARK: -- default C version + +CC_INLINE uint64_t CC_ROL64(uint64_t word, int i) +{ + return ( (word<<(i&63)) | (word>>(64-(i&63))) ); +} + +CC_INLINE uint64_t CC_ROR64(uint64_t word, int i) +{ + return ( (word>>(i&63)) | (word<<(64-(i&63))) ); +} + +#define CC_ROL64c(x, y) CC_ROL64(x, y) +#define CC_ROR64c(x, y) CC_ROR64(x, y) + +#endif + + +// MARK: - Byte Swaps + +CC_INLINE uint32_t CC_BSWAP(uint32_t x) +{ + return ( + ((x>>24)&0x000000FF) | + ((x<<24)&0xFF000000) | + ((x>>8) &0x0000FF00) | + ((x<<8) &0x00FF0000) + ); +} + +#define CC_BSWAP64(x) \ +((uint64_t)((((uint64_t)(x) & 0xff00000000000000ULL) >> 56) | \ +(((uint64_t)(x) & 0x00ff000000000000ULL) >> 40) | \ +(((uint64_t)(x) & 0x0000ff0000000000ULL) >> 24) | \ +(((uint64_t)(x) & 0x000000ff00000000ULL) >> 8) | \ +(((uint64_t)(x) & 0x00000000ff000000ULL) << 8) | \ +(((uint64_t)(x) & 0x0000000000ff0000ULL) << 24) | \ +(((uint64_t)(x) & 0x000000000000ff00ULL) << 40) | \ +(((uint64_t)(x) & 0x00000000000000ffULL) << 56))) + +#ifdef __LITTLE_ENDIAN__ +#define CC_H2BE32(x) CC_BSWAP(x) +#define CC_H2LE32(x) (x) +#else +#define CC_H2BE32(x) (x) +#define CC_H2LE32(x) CC_BSWAP(x) +#endif + +#define CC_READ_LE32(ptr) \ +( (uint32_t)( \ +((uint32_t)((const uint8_t *)(ptr))[0]) | \ +(((uint32_t)((const uint8_t *)(ptr))[1]) << 8) | \ +(((uint32_t)((const uint8_t *)(ptr))[2]) << 16) | \ +(((uint32_t)((const uint8_t *)(ptr))[3]) << 24))) + +#define CC_WRITE_LE32(ptr, x) \ +do { \ +((uint8_t *)(ptr))[0] = (uint8_t)( (x) & 0xFF); \ +((uint8_t *)(ptr))[1] = (uint8_t)(((x) >> 8) & 0xFF); \ +((uint8_t *)(ptr))[2] = (uint8_t)(((x) >> 16) & 0xFF); \ +((uint8_t *)(ptr))[3] = (uint8_t)(((x) >> 24) & 0xFF); \ +} while(0) + +#define CC_WRITE_LE64(ptr, x) \ +do { \ +((uint8_t *)(ptr))[0] = (uint8_t)( (x) & 0xFF); \ +((uint8_t *)(ptr))[1] = (uint8_t)(((x) >> 8) & 0xFF); \ +((uint8_t *)(ptr))[2] = (uint8_t)(((x) >> 16) & 0xFF); \ +((uint8_t *)(ptr))[3] = (uint8_t)(((x) >> 24) & 0xFF); \ +((uint8_t *)(ptr))[4] = (uint8_t)(((x) >> 32) & 0xFF); \ +((uint8_t *)(ptr))[5] = (uint8_t)(((x) >> 40) & 0xFF); \ +((uint8_t *)(ptr))[6] = (uint8_t)(((x) >> 48) & 0xFF); \ +((uint8_t *)(ptr))[7] = (uint8_t)(((x) >> 56) & 0xFF); \ +} while(0) + +/* extract a byte portably */ +#ifdef _MSC_VER +#define cc_byte(x, n) ((unsigned char)((x) >> (8 * (n)))) +#else +#define cc_byte(x, n) (((x) >> (8 * (n))) & 255) +#endif + +/* HEAVISIDE_STEP (shifted by one) + function f(x): x->0, when x=0 + x->1, when x>0 + Can also be seen as a bitwise operation: + f(x): x -> y + y[0]=(OR x[i]) for all i (all bits) + y[i]=0 for all i>0 + Run in constant time (log2()) + Useful to run constant time checks +*/ +#define HEAVISIDE_STEP_UINT64(r,s) {uint64_t _t=s; \ + _t=(((_t)>>32) | (_t)); \ + _t=(0xFFFFFFFF + (_t & 0xFFFFFFFF)); \ + r=_t >> 32;} + +#define HEAVISIDE_STEP_UINT32(r,s) {uint32_t _t=s; \ + _t=(((_t)>>16) | (_t)); \ + _t=(0xFFFF + (_t & 0xFFFF)); \ + r=_t >> 16;} + +#define HEAVISIDE_STEP_UINT16(r,s) {uint32_t _t=s; \ + _t=(0xFFFF + ((_t) & 0xFFFF)); \ + r=_t >> 16;} + +#define HEAVISIDE_STEP_UINT8(r,s) {uint16_t _t=s; \ + _t=(0xFF + ((_t) & 0xFF)); \ + r=_t >> 8;} + +#define CC_HEAVISIDE_STEP(r,s) { \ + if (sizeof(s) == 1) {HEAVISIDE_STEP_UINT8(r,s);} \ + else if (sizeof(s) == 2) {HEAVISIDE_STEP_UINT16(r,s);} \ + else if (sizeof(s) == 4) {HEAVISIDE_STEP_UINT32(r,s);} \ + else if (sizeof(s) == 8) {HEAVISIDE_STEP_UINT64(r,s);} \ + else {r=(((s)==0)?0:1);} \ + } + +/* Return 1 if x mod 4 =1,2,3, 0 otherwise */ +#define CC_CARRY_2BITS(x) (((x>>1) | x) & 0x1) +#define CC_CARRY_3BITS(x) (((x>>2) | (x>>1) | x) & 0x1) + +/* Set a variable to the biggest power of 2 which can be represented */ +#define MAX_POWER_OF_2(x) ((__typeof__(x))1<<(8*sizeof(x)-1)) +#define cc_ceiling(a,b) (((a)+((b)-1))/(b)) +#define CC_BITLEN_TO_BYTELEN(x) cc_ceiling((x), 8) + +//cc_try_abort() is implemented to comply with FIPS 140-2. +void cc_try_abort(const char * msg , ...); + +/*! + @brief cc_muxp(s, a, b) is equivalent to z = s ? a : b, but it executes in constant time + @param a input pointer + @param b input pointer + @param s The selection parameter s must be 0 or 1. if s is integer 1 a is returned. If s is integer 0, b is returned. Otherwise, the output is undefined. + @return Returns a, if s is 1 and b if s is 0 + */ +void *cc_muxp(int s, const void *a, const void *b); + +/*! + @brief cc_mux2p + @param a input pointer + @param b input pointer + @param r_true output pointer: if s is integer 1 r_true=a is returned, otherwise r_true=b + @param r_false output pointer: if s is integer 1 r_false=b is returned, otherwise r_false=a + @param s The selection parameter s must be 0 or 1. + @discussion Executes in constant time + */ +void cc_mux2p(int s, void **r_true, void **r_false, const void *a, const void *b); + +/*! + @brief CC_MUXU(s, a, b) is equivalent to z = s ? a : b, but it executes in constant time + @param a input unsigned type + @param b input unsigned type + @param s The selection parameter s must be 0 or 1. if s is integer 1 a is returned. If s is integer 0, b is returned. Otherwise, the output is undefined. + @param r output + @return r = a, if s is 1 and b if s is 0 + */ +#define CC_MUXU(r, s, a, b) \ +{ \ + __typeof__(r) _cond = ((__typeof__(r))(s)-(__typeof__(r))1); \ + r = (~_cond&(a))|(_cond&(b)); \ +} + +int cc_is_compiled_with_tu(void); + +#endif /* _CORECRYPTO_CC_PRIV_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/cc_runtime_config.h b/libraries/corecrypto/include/corecrypto/cc_runtime_config.h new file mode 100644 index 0000000..c7b82a2 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/cc_runtime_config.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2012,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef CORECRYPTO_CC_RUNTIME_CONFIG_H_ +#define CORECRYPTO_CC_RUNTIME_CONFIG_H_ + +#include + +/* Only intel systems have these runtime switches today. */ +#if (CCSHA1_VNG_INTEL || CCSHA2_VNG_INTEL || CCAES_INTEL_ASM) \ + && (defined(__x86_64__) || defined(__i386__)) + +#if CC_KERNEL + #include + #define CC_HAS_AESNI() ((cpuid_features() & CPUID_FEATURE_AES) != 0) + #define CC_HAS_SupplementalSSE3() ((cpuid_features() & CPUID_FEATURE_SSSE3) != 0) + #define CC_HAS_AVX1() ((cpuid_features() & CPUID_FEATURE_AVX1_0) != 0) + #define CC_HAS_AVX2() ((cpuid_info()->cpuid_leaf7_features & CPUID_LEAF7_FEATURE_AVX2) != 0) + +#elif CC_XNU_KERNEL_AVAILABLE && !CORECRYPTO_PUBLIC_SDK + #include + + #ifndef kHasAVX2_0 /* 10.8 doesn't have kHasAVX2_0 defined */ + #define kHasAVX2_0 0 + #endif + + extern int _cpu_capabilities; + #define CC_HAS_AESNI() (_cpu_capabilities & kHasAES) + #define CC_HAS_SupplementalSSE3() (_cpu_capabilities & kHasSupplementalSSE3) + #define CC_HAS_AVX1() (_cpu_capabilities & kHasAVX1_0) + #define CC_HAS_AVX2() (_cpu_capabilities & kHasAVX2_0) +#else + #define CC_HAS_AESNI() 0 + #define CC_HAS_SupplementalSSE3() 0 + #define CC_HAS_AVX1() 0 + #define CC_HAS_AVX2() 0 +#endif + +#endif /* !(defined(__x86_64__) || defined(__i386__)) */ + +#endif /* CORECRYPTO_CC_RUNTIME_CONFIG_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccaes.h b/libraries/corecrypto/include/corecrypto/ccaes.h new file mode 100644 index 0000000..8070eb6 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccaes.h @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2010,2011,2012,2013,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ +#ifndef _CORECRYPTO_CCAES_H_ +#define _CORECRYPTO_CCAES_H_ + +#include +#include + +#define CCAES_BLOCK_SIZE 16 +#define CCAES_KEY_SIZE_128 16 +#define CCAES_KEY_SIZE_192 24 +#define CCAES_KEY_SIZE_256 32 + +#define CCAES_CTR_MAX_PARALLEL_NBLOCKS 8 + +extern const struct ccmode_ecb ccaes_ltc_ecb_decrypt_mode; +extern const struct ccmode_ecb ccaes_ltc_ecb_encrypt_mode; + +extern const struct ccmode_cbc ccaes_gladman_cbc_encrypt_mode; +extern const struct ccmode_cbc ccaes_gladman_cbc_decrypt_mode; + +#if CCAES_ARM_ASM +extern const struct ccmode_ecb ccaes_arm_ecb_encrypt_mode; +extern const struct ccmode_ecb ccaes_arm_ecb_decrypt_mode; + +extern const struct ccmode_cbc ccaes_arm_cbc_encrypt_mode; +extern const struct ccmode_cbc ccaes_arm_cbc_decrypt_mode; + +extern const struct ccmode_xts ccaes_arm_xts_encrypt_mode; +extern const struct ccmode_xts ccaes_arm_xts_decrypt_mode; + +extern const struct ccmode_cfb ccaes_arm_cfb_encrypt_mode; +extern const struct ccmode_cfb ccaes_arm_cfb_decrypt_mode; + +extern const struct ccmode_ofb ccaes_arm_ofb_crypt_mode; + +#endif + +#if CCAES_MUX +extern const struct ccmode_cbc ccaes_ios_hardware_cbc_encrypt_mode; +extern const struct ccmode_cbc ccaes_ios_hardware_cbc_decrypt_mode; + +extern const struct ccmode_ctr ccaes_ios_hardware_ctr_crypt_mode; + +extern const struct ccmode_cbc *ccaes_ios_mux_cbc_encrypt_mode(void); +extern const struct ccmode_cbc *ccaes_ios_mux_cbc_decrypt_mode(void); + +extern const struct ccmode_ctr *ccaes_ios_mux_ctr_crypt_mode(void); + +#endif + +#if CCAES_INTEL_ASM +//extern const struct ccmode_ecb ccaes_intel_ecb_encrypt_mode; +//extern const struct ccmode_ecb ccaes_intel_ecb_decrypt_mode; + +extern const struct ccmode_ecb ccaes_intel_ecb_encrypt_opt_mode; +extern const struct ccmode_ecb ccaes_intel_ecb_encrypt_aesni_mode; + +extern const struct ccmode_ecb ccaes_intel_ecb_decrypt_opt_mode; +extern const struct ccmode_ecb ccaes_intel_ecb_decrypt_aesni_mode; + +//extern const struct ccmode_cbc ccaes_intel_cbc_encrypt_mode; +//extern const struct ccmode_cbc ccaes_intel_cbc_decrypt_mode; + +extern const struct ccmode_cbc ccaes_intel_cbc_encrypt_opt_mode; +extern const struct ccmode_cbc ccaes_intel_cbc_encrypt_aesni_mode; + +extern const struct ccmode_cbc ccaes_intel_cbc_decrypt_opt_mode; +extern const struct ccmode_cbc ccaes_intel_cbc_decrypt_aesni_mode; + +//extern const struct ccmode_xts ccaes_intel_xts_encrypt_mode; +//extern const struct ccmode_xts ccaes_intel_xts_decrypt_mode; + +extern const struct ccmode_xts ccaes_intel_xts_encrypt_opt_mode; +extern const struct ccmode_xts ccaes_intel_xts_encrypt_aesni_mode; + +extern const struct ccmode_xts ccaes_intel_xts_decrypt_opt_mode; +extern const struct ccmode_xts ccaes_intel_xts_decrypt_aesni_mode; +#endif + +#if CC_USE_L4 +extern const struct ccmode_cbc ccaes_skg_cbc_encrypt_mode; +extern const struct ccmode_cbc ccaes_skg_cbc_decrypt_mode; + +extern const struct ccmode_ecb ccaes_skg_ecb_encrypt_mode; +extern const struct ccmode_ecb ccaes_skg_ecb_decrypt_mode; + +extern const struct ccmode_ecb ccaes_trng_ecb_encrypt_mode; +#endif + +/* Implementation Selectors: */ +const struct ccmode_ecb *ccaes_ecb_encrypt_mode(void); +const struct ccmode_cbc *ccaes_cbc_encrypt_mode(void); +const struct ccmode_cfb *ccaes_cfb_encrypt_mode(void); +const struct ccmode_cfb8 *ccaes_cfb8_encrypt_mode(void); +const struct ccmode_xts *ccaes_xts_encrypt_mode(void); +const struct ccmode_gcm *ccaes_gcm_encrypt_mode(void); +const struct ccmode_ccm *ccaes_ccm_encrypt_mode(void); + +const struct ccmode_ecb *ccaes_ecb_decrypt_mode(void); +const struct ccmode_cbc *ccaes_cbc_decrypt_mode(void); +const struct ccmode_cfb *ccaes_cfb_decrypt_mode(void); +const struct ccmode_cfb8 *ccaes_cfb8_decrypt_mode(void); +const struct ccmode_xts *ccaes_xts_decrypt_mode(void); +const struct ccmode_gcm *ccaes_gcm_decrypt_mode(void); +const struct ccmode_ccm *ccaes_ccm_decrypt_mode(void); + +const struct ccmode_ctr *ccaes_ctr_crypt_mode(void); +const struct ccmode_ofb *ccaes_ofb_crypt_mode(void); + +const struct ccmode_siv *ccaes_siv_encrypt_mode(void); +const struct ccmode_siv *ccaes_siv_decrypt_mode(void); + +#endif /* _CORECRYPTO_CCAES_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccansikdf.h b/libraries/corecrypto/include/corecrypto/ccansikdf.h new file mode 100644 index 0000000..97f0ed5 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccansikdf.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2014,2015,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ +#ifndef corecrypto_ccansikdf_h +#define corecrypto_ccansikdf_h + +#include +#include + +/* + ANSI x9.63 KDF as per x9.63-2011 specification. + with granularity in bytes. + + Input: The input to the key derivation function is: + 1. A byte string Z that is the shared secret value, of byte length lenZ. + 2. An integer keydatalen that is the length in byte of the keying data to be generated. keydatalen shall be less than (2^32–1) hashlen + 3. A byte string SharedInfo that consists of some data shared by the two entities intended to share the secret value Z. The total byte length of Z and SharedInfo must be at most maxhashlen – 4. + + Approved digest functions are for output >= 224bit that is SHA-224 and beyond. + SHA-1 is not forbidden but should only be used for interroperability requirements. + */ + +CC_NONNULL((1, 3, 7)) +int ccansikdf_x963(const struct ccdigest_info *di, + const size_t Z_len, const unsigned char *Z, + const size_t sharedinfo_byte_len, const void *sharedinfo, + const size_t key_len, uint8_t *key); + +#endif diff --git a/libraries/corecrypto/include/corecrypto/ccasn1.h b/libraries/corecrypto/include/corecrypto/ccasn1.h new file mode 100644 index 0000000..a8316a7 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccasn1.h @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2010,2011,2012,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ +#ifndef _CORECRYPTO_CCASN1_H_ +#define _CORECRYPTO_CCASN1_H_ + +#include +#include +#include + +/* ASN.1 types for on the fly ASN.1 BER/DER encoding/decoding. Don't use + these with the ccder interface, use the CCDER_ types instead. */ +enum { + CCASN1_EOL = 0x00, + CCASN1_BOOLEAN = 0x01, + CCASN1_INTEGER = 0x02, + CCASN1_BIT_STRING = 0x03, + CCASN1_OCTET_STRING = 0x04, + CCASN1_NULL = 0x05, + CCASN1_OBJECT_IDENTIFIER = 0x06, + CCASN1_OBJECT_DESCRIPTOR = 0x07, + /* External or instance-of 0x08 */ + CCASN1_REAL = 0x09, + CCASN1_ENUMERATED = 0x0a, + CCASN1_EMBEDDED_PDV = 0x0b, + CCASN1_UTF8_STRING = 0x0c, + /* 0x0d */ + /* 0x0e */ + /* 0x0f */ + CCASN1_SEQUENCE = 0x10, + CCASN1_SET = 0x11, + CCASN1_NUMERIC_STRING = 0x12, + CCASN1_PRINTABLE_STRING = 0x13, + CCASN1_T61_STRING = 0x14, + CCASN1_VIDEOTEX_STRING = 0x15, + CCASN1_IA5_STRING = 0x16, + CCASN1_UTC_TIME = 0x17, + CCASN1_GENERALIZED_TIME = 0x18, + CCASN1_GRAPHIC_STRING = 0x19, + CCASN1_VISIBLE_STRING = 0x1a, + CCASN1_GENERAL_STRING = 0x1b, + CCASN1_UNIVERSAL_STRING = 0x1c, + /* 0x1d */ + CCASN1_BMP_STRING = 0x1e, + CCASN1_HIGH_TAG_NUMBER = 0x1f, + CCASN1_TELETEX_STRING = CCASN1_T61_STRING, + + CCASN1_TAG_MASK = 0xff, + CCASN1_TAGNUM_MASK = 0x1f, + + CCASN1_METHOD_MASK = 0x20, + CCASN1_PRIMITIVE = 0x00, + CCASN1_CONSTRUCTED = 0x20, + + CCASN1_CLASS_MASK = 0xc0, + CCASN1_UNIVERSAL = 0x00, + CCASN1_APPLICATION = 0x40, + CCASN1_CONTEXT_SPECIFIC = 0x80, + CCASN1_PRIVATE = 0xc0, + + CCASN1_CONSTRUCTED_SET = CCASN1_SET | CCASN1_CONSTRUCTED, + CCASN1_CONSTRUCTED_SEQUENCE = CCASN1_SEQUENCE | CCASN1_CONSTRUCTED, +}; + +#if CORECRYPTO_USE_TRANSPARENT_UNION +typedef union { + const unsigned char * oid; +} __attribute__((transparent_union)) ccoid_t; +#define CCOID(x) ((x).oid) +#else + typedef const unsigned char * ccoid_t; +#define CCOID(oid) (oid) +#endif + +/* Returns *der iff *der points to a DER encoded oid that fits within *der_len. */ +ccoid_t ccoid_for_der(size_t *der_len, const uint8_t **der); + +/* Returns the size of an oid including it's tag and length. */ +CC_INLINE CC_PURE CC_NONNULL_TU((1)) +size_t ccoid_size(ccoid_t oid) { + return 2 + CCOID(oid)[1]; +} + +CC_INLINE CC_PURE CC_NONNULL_TU((1)) CC_NONNULL_TU((2)) +bool ccoid_equal(ccoid_t oid1, ccoid_t oid2) { + return (ccoid_size(oid1) == ccoid_size(oid2) + && memcmp(CCOID(oid1), CCOID(oid2), ccoid_size(oid1))== 0); +} + +#endif /* _CORECRYPTO_CCASN1_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccblowfish.h b/libraries/corecrypto/include/corecrypto/ccblowfish.h new file mode 100644 index 0000000..bcfafef --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccblowfish.h @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2010,2012,2015,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ +#ifndef _CORECRYPTO_CCBLOWFISH_H_ +#define _CORECRYPTO_CCBLOWFISH_H_ + +#include + +#define CCBLOWFISH_BLOCK_SIZE 8 + +#define CCBLOWFISH_KEY_SIZE_MIN 8 +#define CCBLOWFISH_KEY_SIZE_MAX 56 + +extern const struct ccmode_ecb ccblowfish_ltc_ecb_decrypt_mode; +extern const struct ccmode_ecb ccblowfish_ltc_ecb_encrypt_mode; + + + +const struct ccmode_ecb *ccblowfish_ecb_decrypt_mode(void); +const struct ccmode_ecb *ccblowfish_ecb_encrypt_mode(void); + +const struct ccmode_cbc *ccblowfish_cbc_decrypt_mode(void); +const struct ccmode_cbc *ccblowfish_cbc_encrypt_mode(void); + +const struct ccmode_cfb *ccblowfish_cfb_decrypt_mode(void); +const struct ccmode_cfb *ccblowfish_cfb_encrypt_mode(void); + +const struct ccmode_cfb8 *ccblowfish_cfb8_decrypt_mode(void); +const struct ccmode_cfb8 *ccblowfish_cfb8_encrypt_mode(void); + +const struct ccmode_ctr *ccblowfish_ctr_crypt_mode(void); + +const struct ccmode_ofb *ccblowfish_ofb_crypt_mode(void); + + +#endif /* _CORECRYPTO_CCBLOWFISH_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/cccast.h b/libraries/corecrypto/include/corecrypto/cccast.h new file mode 100644 index 0000000..71b5fd6 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/cccast.h @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2011,2012,2015,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCCAST_H_ +#define _CORECRYPTO_CCCAST_H_ + +#include + +#define CCCAST_BLOCK_SIZE 8 /* block size in bytes */ +#define CCCAST_KEY_LENGTH 16 /* MAX key size in bytes */ +#define CCCAST_MIN_KEY_LENGTH 5 /* MIN key size in bytes */ + +/* Selectors: */ +const struct ccmode_ecb *cccast_ecb_decrypt_mode(void); +const struct ccmode_ecb *cccast_ecb_encrypt_mode(void); + +const struct ccmode_cbc *cccast_cbc_decrypt_mode(void); +const struct ccmode_cbc *cccast_cbc_encrypt_mode(void); + +const struct ccmode_cfb *cccast_cfb_decrypt_mode(void); +const struct ccmode_cfb *cccast_cfb_encrypt_mode(void); + +const struct ccmode_cfb8 *cccast_cfb8_decrypt_mode(void); +const struct ccmode_cfb8 *cccast_cfb8_encrypt_mode(void); + +const struct ccmode_ctr *cccast_ctr_crypt_mode(void); + +const struct ccmode_ofb *cccast_ofb_crypt_mode(void); + +/* Implementations: */ +extern const struct ccmode_ecb cccast_eay_ecb_decrypt_mode; +extern const struct ccmode_ecb cccast_eay_ecb_encrypt_mode; + + +#endif /* _CORECRYPTO_CCCAST_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccchacha20poly1305.h b/libraries/corecrypto/include/corecrypto/ccchacha20poly1305.h new file mode 100644 index 0000000..a496abe --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccchacha20poly1305.h @@ -0,0 +1,352 @@ +/* + * Copyright (c) 2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCCHACHA20POLY1305_H_ +#define _CORECRYPTO_CCCHACHA20POLY1305_H_ + +#include +#include +#include + +#define CCCHACHA20_KEY_NBYTES 32 +#define CCCHACHA20_BLOCK_NBYTES 64 +#define CCCHACHA20_BLOCK_NBITS (CCCHACHA20_BLOCK_NBYTES * 8) +#define CCCHACHA20_NONCE_NBYTES 12 + +typedef struct { + uint32_t state[16]; + uint8_t buffer[CCCHACHA20_BLOCK_NBYTES]; + size_t leftover; +} ccchacha20_ctx; + +#define CCPOLY1305_TAG_NBYTES 16 + +typedef struct { + uint32_t r0, r1, r2, r3, r4; + uint32_t s1, s2, s3, s4; + uint32_t h0, h1, h2, h3, h4; + uint8_t buf[16]; + size_t buf_used; + uint8_t key[16]; +} ccpoly1305_ctx; + + +/*! + @group ccchacha20poly1305 + @abstract Encrypts and authenticates or decrypts and verifies data. + @discussion See RFC 7539 for details. + + @warning The key-nonce pair must be unique per encryption. + + @warning A single message can be at most (2^38 - 64) bytes in length. + + The correct sequence of calls to encrypt is: + + @code ccchacha20poly1305_init(...) + ccchacha20poly1305_setnonce(...) + ccchacha20poly1305_aad(...) (may be called zero or more times) + ccchacha20poly1305_encrypt(...) (may be called zero or more times) + ccchacha20poly1305_finalize(...) + + To reuse the context for additional encryptions, follow this sequence: + + @code ccchacha20poly1305_reset(...) + ccchacha20poly1305_setnonce(...) + ccchacha20poly1305_aad(...) (may be called zero or more times) + ccchacha20poly1305_encrypt(...) (may be called zero or more times) + ccchacha20poly1305_finalize(...) + + To decrypt, follow this call sequence: + + @code ccchacha20poly1305_init(...) + ccchacha20poly1305_setnonce(...) + ccchacha20poly1305_aad(...) (may be called zero or more times) + ccchacha20poly1305_decrypt(...) (may be called zero or more times) + ccchacha20poly1305_verify(...) (returns zero on successful decryption) + + To reuse the context for additional encryptions, follow this sequence: + + @code ccchacha20poly1305_reset(...) + ccchacha20poly1305_setnonce(...) + ccchacha20poly1305_aad(...) (may be called zero or more times) + ccchacha20poly1305_decrypt(...) (may be called zero or more times) + ccchacha20poly1305_verify(...) (returns zero on successful decryption) +*/ + +#define CCCHACHA20POLY1305_KEY_NBYTES (CCCHACHA20_KEY_NBYTES) +#define CCCHACHA20POLY1305_NONCE_NBYTES (CCCHACHA20_NONCE_NBYTES) +#define CCCHACHA20POLY1305_TAG_NBYTES (CCPOLY1305_TAG_NBYTES) + +/* (2^32 - 1) blocks */ +/* (2^38 - 64) bytes */ +/* (2^41 - 512) bits */ +/* Exceeding this figure breaks confidentiality and authenticity. */ +#define CCCHACHA20POLY1305_TEXT_MAX_NBYTES ((1ULL << 38) - 64ULL) + +#define CCCHACHA20POLY1305_STATE_SETNONCE 1 +#define CCCHACHA20POLY1305_STATE_AAD 2 +#define CCCHACHA20POLY1305_STATE_ENCRYPT 3 +#define CCCHACHA20POLY1305_STATE_DECRYPT 4 +#define CCCHACHA20POLY1305_STATE_FINAL 5 + +typedef struct { + ccchacha20_ctx chacha20_ctx; + ccpoly1305_ctx poly1305_ctx; + uint64_t aad_nbytes; + uint64_t text_nbytes; + uint8_t state; +} ccchacha20poly1305_ctx; + +// This is just a stub right now. +// Eventually we will optimize by platform. +struct ccchacha20poly1305_info { + +}; + +extern const struct ccchacha20poly1305_info ccchacha20poly1305_info_default; + +const struct ccchacha20poly1305_info *ccchacha20poly1305_info(void); + +/*! + @function ccchacha20poly1305_init + @abstract Initialize a chacha20poly1305 context. + + @param info Implementation descriptor + @param ctx Context for this instance + @param key Secret chacha20 key + + @result 0 iff successful. + + @discussion The key is 32 bytes in length. + + @warning The key-nonce pair must be unique per encryption. + */ +int ccchacha20poly1305_init(const struct ccchacha20poly1305_info *info, ccchacha20poly1305_ctx *ctx, const uint8_t *key); + +/*! + @function ccchacha20poly1305_reset + @abstract Reset a chacha20poly1305 context for reuse. + + @param info Implementation descriptor + @param ctx Context for this instance + + @result 0 iff successful. + */ +int ccchacha20poly1305_reset(const struct ccchacha20poly1305_info *info, ccchacha20poly1305_ctx *ctx); + +/*! + @function ccchacha20poly1305_setnonce + @abstract Set the nonce for encryption or decryption. + + @param info Implementation descriptor + @param ctx Context for this instance + @param nonce Unique nonce per encryption + + @result 0 iff successful. + + @discussion The nonce is 12 bytes in length. + + @warning The key-nonce pair must be unique per encryption. + */ +int ccchacha20poly1305_setnonce(const struct ccchacha20poly1305_info *info, ccchacha20poly1305_ctx *ctx, const uint8_t *nonce); +int ccchacha20poly1305_incnonce(const struct ccchacha20poly1305_info *info, ccchacha20poly1305_ctx *ctx, uint8_t *nonce); + +/*! + @function ccchacha20poly1305_aad + @abstract Authenticate additional data. + + @param info Descriptor for the mode + @param ctx Context for this instance + @param nbytes Length of the additional data in bytes + @param aad Additional data to authenticate + + @result 0 iff successful. + + @discussion This is typically used to authenticate data that cannot be encrypted (e.g. packet headers). + + This function may be called zero or more times. + */ +int ccchacha20poly1305_aad(const struct ccchacha20poly1305_info *info, ccchacha20poly1305_ctx *ctx, size_t nbytes, const void *aad); + +/*! + @function ccchacha20poly1305_encrypt + @abstract Encrypt data. + + @param info Descriptor for the mode + @param ctx Context for this instance + @param nbytes Length of the plaintext in bytes + @param ptext Input plaintext + @param ctext Output ciphertext + + @result 0 iff successful. + + @discussion In-place processing is supported. + + This function may be called zero or more times. + */ +int ccchacha20poly1305_encrypt(const struct ccchacha20poly1305_info *info, ccchacha20poly1305_ctx *ctx, size_t nbytes, const void *ptext, void *ctext); + +/*! + @function ccchacha20poly1305_finalize + @abstract Finalize encryption. + + @param info Descriptor for the mode + @param ctx Context for this instance + @param tag Generated authentication tag + + @result 0 iff successful. + + @discussion The generated tag is 16 bytes in length. + */ +int ccchacha20poly1305_finalize(const struct ccchacha20poly1305_info *info, ccchacha20poly1305_ctx *ctx, uint8_t *tag); + +/*! + @function ccchacha20poly1305_decrypt + @abstract Decrypt data. + + @param info Descriptor for the mode + @param ctx Context for this instance + @param nbytes Length of the ciphertext in bytes + @param ctext Input ciphertext + @param ptext Output plaintext + + @result 0 iff successful. + + @discussion In-place processing is supported. + + This function may be called zero or more times. + */ +int ccchacha20poly1305_decrypt(const struct ccchacha20poly1305_info *info, ccchacha20poly1305_ctx *ctx, size_t nbytes, const void *ctext, void *ptext); + +/*! + @function ccchacha20poly1305_verify + @abstract Verify authenticity. + + @param info Descriptor for the mode + @param ctx Context for this instance + @param tag Expected authentication tag + + @result 0 iff authentic and otherwise successful. + + @discussion The expected tag is 16 bytes in length. + */ +int ccchacha20poly1305_verify(const struct ccchacha20poly1305_info *info, ccchacha20poly1305_ctx *ctx, const uint8_t *tag); + +/*! + @function ccchacha20poly1305_encrypt_oneshot + @abstract Encrypt with chacha20poly1305. + + @param info Descriptor for the mode + @param key Secret chacha20 key + @param nonce Unique nonce per encryption + @param aad_nbytes Length of the additional data in bytes + @param aad Additional data to authenticate + @param ptext_nbytes Length of the plaintext in bytes + @param ptext Input plaintext + @param ctext Output ciphertext + @param tag Generated authentication tag + + @discussion See RFC 7539 for details. + + The key is 32 bytes in length. + + The nonce is 12 bytes in length. + + The generated tag is 16 bytes in length. + + In-place processing is supported. + + @warning The key-nonce pair must be unique per encryption. + + @warning A single message can be at most (2^38 - 64) bytes in length. + */ +int ccchacha20poly1305_encrypt_oneshot(const struct ccchacha20poly1305_info *info, const uint8_t *key, const uint8_t *nonce, size_t aad_nbytes, const void *aad, size_t ptext_nbytes, const void *ptext, void *ctext, uint8_t *tag); + +/*! + @function ccchacha20poly1305_decrypt_oneshot + @abstract Decrypt with chacha20poly1305. + + @param info Descriptor for the mode + @param key Secret chacha20 key + @param nonce Unique nonce per encryption + @param aad_nbytes Length of the additional data in bytes + @param aad Additional data to authenticate + @param ctext_nbytes Length of the ciphertext in bytes + @param ctext Input ciphertext + @param ptext Output plaintext + @param tag Expected authentication tag + + @discussion See RFC 7539 for details. + + The key is 32 bytes in length. + + The nonce is 12 bytes in length. + + The generated tag is 16 bytes in length. + + In-place processing is supported. + */ +int ccchacha20poly1305_decrypt_oneshot(const struct ccchacha20poly1305_info *info, const uint8_t *key, const uint8_t *nonce, size_t aad_nbytes, const void *aad, size_t ctext_nbytes, const void *ctext, void *ptext, const uint8_t *tag); + +#endif diff --git a/libraries/corecrypto/include/corecrypto/ccchacha20poly1305_priv.h b/libraries/corecrypto/include/corecrypto/ccchacha20poly1305_priv.h new file mode 100644 index 0000000..d030db9 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccchacha20poly1305_priv.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCCHACHA20POLY1305_PRIV_H_ +#define _CORECRYPTO_CCCHACHA20POLY1305_PRIV_H_ + +/*! @group ccchacha20 + @abstract Encrypts/decrypts N bytes of data with a 32-byte key and 8-byte nonce starting from an 8-byte counter. + @discussion See DJB's page on ChaCha20 . + */ + +int ccchacha20_init(ccchacha20_ctx *ctx, const uint8_t *key); +int ccchacha20_reset(ccchacha20_ctx *ctx); +int ccchacha20_setnonce(ccchacha20_ctx *ctx, const uint8_t *nonce); +int ccchacha20_setcounter(ccchacha20_ctx *ctx, uint32_t counter); +int ccchacha20_update(ccchacha20_ctx *ctx, size_t nbytes, const void *in, void *out); +int ccchacha20_final(ccchacha20_ctx *ctx); +int ccchacha20(const uint8_t *key, const uint8_t *nonce, uint32_t counter, size_t nbytes, const void *in, void *out); + +/*! @group poly1305 + @abstract Generates a 16-byte Poly1305 Message Authentication Code from N bytes of data and a 32-byte key. + @discussion See DJB's paper on Poly1305 for details. + */ + +int ccpoly1305_init(ccpoly1305_ctx *ctx, const uint8_t *key); +int ccpoly1305_update(ccpoly1305_ctx *ctx, size_t nbytes, const uint8_t *data); +int ccpoly1305_final(ccpoly1305_ctx *ctx, uint8_t *tag); +int ccpoly1305(const uint8_t *key, size_t nbytes, const uint8_t *data, uint8_t *tag); + +#endif /* _CORECRYPTO_CCCHACHA20POLY1305_PRIV_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/cccmac.h b/libraries/corecrypto/include/corecrypto/cccmac.h new file mode 100644 index 0000000..7ff7a0c --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/cccmac.h @@ -0,0 +1,266 @@ +/* + * Copyright (c) 2013,2014,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_cccmac_H_ +#define _CORECRYPTO_cccmac_H_ + +#include +#include +#include + +#define CMAC_BLOCKSIZE 16 + +#if CORECRYPTO_USE_TRANSPARENT_UNION +struct cccmac_ctx { + uint8_t b[8]; +} CC_ALIGNED(8); + +typedef struct cccmac_ctx_hdr { + uint8_t k1[CMAC_BLOCKSIZE]; + uint8_t k2[CMAC_BLOCKSIZE]; + uint8_t block[CMAC_BLOCKSIZE]; + size_t block_nbytes; // Number of byte occupied in block buf + size_t cumulated_nbytes; // Total size processed + const struct ccmode_cbc *cbc; + uint8_t ctx[8]; +} CC_ALIGNED(8) cccmac_ctx_hdr; + + +typedef union { + struct cccmac_ctx *b; + cccmac_ctx_hdr *hdr; +} cccmac_ctx_t __attribute__((transparent_union)); +#define cccmac_hdr_size sizeof(struct cccmac_ctx_hdr) + +#else + +struct cccmac_ctx { + uint8_t k1[CMAC_BLOCKSIZE]; + uint8_t k2[CMAC_BLOCKSIZE]; + uint8_t block[CMAC_BLOCKSIZE]; + size_t block_nbytes; // Number of byte occupied in block + size_t cumulated_nbytes; // Total size processed + const struct ccmode_cbc *cbc; + uint8_t ctx[8]; +} CC_ALIGNED(8);// cccmac_ctx_hdr; + +typedef struct cccmac_ctx* cccmac_ctx_t; + +#define cccmac_hdr_size sizeof(struct cccmac_ctx) + +#endif + + +#define cccmac_iv_size(_mode_) ((_mode_)->block_size) +#define cccmac_cbc_size(_mode_) ((_mode_)->size) + +#define cccmac_ctx_size(_mode_) (cccmac_hdr_size + cccmac_iv_size(_mode_) + cccmac_cbc_size(_mode_)) +#define cccmac_ctx_n(_mode_) ccn_nof_size(cccmac_ctx_size(_mode_)) + +#define cccmac_mode_decl(_mode_, _name_) cc_ctx_decl(struct cccmac_ctx, cccmac_ctx_size(_mode_), _name_) +#define cccmac_mode_clear(_mode_, _name_) cc_clear(cccmac_ctx_size(_mode_), _name_) + +#if CORECRYPTO_USE_TRANSPARENT_UNION +/* Return a cccbc_ctx * which can be accesed with the macros in ccmode.h */ +#define cccmac_mode_ctx_start(_mode_, HC) (((HC).hdr)->ctx) +#define CCCMAC_HDR(HC) (((cccmac_ctx_t)(HC)).hdr) +#else +/* Return a cccbc_ctx * which can be accesed with the macros in ccmode.h */ +#define cccmac_mode_ctx_start(_mode_, HC) (HC->ctx) +#define CCCMAC_HDR(HC) (HC) +#endif + +#define cccmac_mode_sym_ctx(_mode_, HC) (cccbc_ctx *)(cccmac_mode_ctx_start(_mode_, HC)) +#define cccmac_mode_iv(_mode_, HC) (cccbc_iv *)(cccmac_mode_ctx_start(_mode_, HC)+cccmac_cbc_size(_mode_)) +#define cccmac_k1(HC) (CCCMAC_HDR(HC)->k1) +#define cccmac_k2(HC) (CCCMAC_HDR(HC)->k2) +#define cccmac_block(HC) (CCCMAC_HDR(HC)->block) +#define cccmac_cbc(HC) (CCCMAC_HDR(HC)->cbc) +#define cccmac_block_nbytes(HC) (CCCMAC_HDR(HC)->block_nbytes) +#define cccmac_cumulated_nbytes(HC) (CCCMAC_HDR(HC)->cumulated_nbytes) + + +/* CMAC as defined in NIST SP800-38B - 2005 */ + +/* ============================================================================= + + ONE SHOT + + ==============================================================================*/ + +/*! + @function cccmac_one_shot_generate + @abstract CMAC generation in one call + + @param cbc CBC and block cipher specification + @param key_nbytes Length of the key in bytes + @param key Pointer to the key of length key_nbytes + @param data_nbytes Length of the data in bytes + @param data Pointer to the data in bytes + @param mac_nbytes Length in byte of the mac, > 0 + @param mac Output of length cbc->block_size + + @result 0 iff successful. + + @discussion Only supports CMAC_BLOCKSIZE block ciphers + */ +int cccmac_one_shot_generate(const struct ccmode_cbc *cbc, + size_t key_nbytes, const void *key, + size_t data_nbytes, const void *data, + size_t mac_nbytes, void *mac); + +/*! + @function cccmac_one_shot_verify + @abstract CMAC verification in one call + + @param cbc CBC and block cipher specification + @param key_nbytes Length of the key in bytes + @param key Pointer to the key of length key_nbytes + @param data_nbytes Length of the data in bytes + @param data Pointer to the data in bytes + @param expected_mac_nbytes Length in byte of the mac, > 0 + @param expected_mac Mac value expected + + @result 0 iff successful. + + @discussion Only supports CMAC_BLOCKSIZE block ciphers + */ +int cccmac_one_shot_verify(const struct ccmode_cbc *cbc, + size_t key_nbytes, const void *key, + size_t data_nbytes, const void *data, + size_t expected_mac_nbytes, const void *expected_mac); + +/* ============================================================================= + + STREAMING + + Init - Update - Final + +==============================================================================*/ + +/*! + @function cccmac_init + @abstract Init CMAC context with CBC mode and key + + @param cbc CBC and block cipher specification + @param ctx Context use to store internal state + @param key_nbytes Length of the key in bytes + @param key Full key + + @result 0 iff successful. + + @discussion Only supports CMAC_BLOCKSIZE block ciphers + */ + +int cccmac_init(const struct ccmode_cbc *cbc, + cccmac_ctx_t ctx, + size_t key_nbytes, const void *key); + +/*! + @function cccmac_update + @abstract Process data + + @param ctx Context use to store internal state + @param data_nbytes Length in byte of the data + @param data Data to process + + @result 0 iff successful. + + @discussion Only supports CMAC_BLOCKSIZE block ciphers + */ + +int cccmac_update(cccmac_ctx_t ctx, + size_t data_nbytes, const void *data); + +/*! + @function cccmac_final_generate + @abstract Final step for generation + + @param ctx Context use to store internal state + @param mac_nbytes Length in byte of the mac, > 0 + @param mac Output of length mac_nbytes + + @result 0 iff successful. + + @discussion Only supports CMAC_BLOCKSIZE block ciphers + */ +int cccmac_final_generate(cccmac_ctx_t ctx, + size_t mac_nbytes, void *mac); + +/*! + @function cccmac_final_verify + @abstract Final step and verification + + @param ctx Context use to store internal state + @param expected_mac_nbytes Length in byte of the mac, > 0 + @param expected_mac Mac value expected + + @result 0 iff successful. + + @discussion Only supports CMAC_BLOCKSIZE block ciphers + */ +int cccmac_final_verify(cccmac_ctx_t ctx, + size_t expected_mac_nbytes, const void *expected_mac); + +#endif /* _CORECRYPTO_cccmac_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccder.h b/libraries/corecrypto/include/corecrypto/ccder.h new file mode 100644 index 0000000..1971a8d --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccder.h @@ -0,0 +1,370 @@ +/* + * Copyright (c) 2012,2013,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ +#ifndef _CORECRYPTO_CCDER_H_ +#define _CORECRYPTO_CCDER_H_ + +#include +#include + +#define CCDER_MULTIBYTE_TAGS 1 + +#ifdef CCDER_MULTIBYTE_TAGS +typedef unsigned long ccder_tag; +#else +typedef uint8_t ccder_tag; +#endif + +/* DER types to be used with ccder_decode and ccder_encode functions. */ +#define CCDER_EOL CCASN1_EOL +#define CCDER_BOOLEAN CCASN1_BOOLEAN +#define CCDER_INTEGER CCASN1_INTEGER +#define CCDER_BIT_STRING CCASN1_BIT_STRING +#define CCDER_OCTET_STRING CCASN1_OCTET_STRING +#define CCDER_NULL CCASN1_NULL +#define CCDER_OBJECT_IDENTIFIER CCASN1_OBJECT_IDENTIFIER +#define CCDER_OBJECT_DESCRIPTOR CCASN1_OBJECT_DESCRIPTOR + /* External or instance-of 0x08 */ +#define CCDER_REAL CCASN1_REAL +#define CCDER_ENUMERATED CCASN1_ENUMERATED +#define CCDER_EMBEDDED_PDV CCASN1_EMBEDDED_PDV +#define CCDER_UTF8_STRING CCASN1_UTF8_STRING + /* 0x0d */ + /* 0x0e */ + /* 0x0f */ +#define CCDER_SEQUENCE CCASN1_SEQUENCE +#define CCDER_SET CCASN1_SET +#define CCDER_NUMERIC_STRING CCASN1_NUMERIC_STRING +#define CCDER_PRINTABLE_STRING CCASN1_PRINTABLE_STRING +#define CCDER_T61_STRING CCASN1_T61_STRING +#define CCDER_VIDEOTEX_STRING CCASN1_VIDEOTEX_STRING +#define CCDER_IA5_STRING CCASN1_IA5_STRING +#define CCDER_UTC_TIME CCASN1_UTC_TIME +#define CCDER_GENERALIZED_TIME CCASN1_GENERALIZED_TIME +#define CCDER_GRAPHIC_STRING CCASN1_GRAPHIC_STRING +#define CCDER_VISIBLE_STRING CCASN1_VISIBLE_STRING +#define CCDER_GENERAL_STRING CCASN1_GENERAL_STRING +#define CCDER_UNIVERSAL_STRING CCASN1_UNIVERSAL_STRING + /* 0x1d */ +#define CCDER_BMP_STRING CCASN1_BMP_STRING +#define CCDER_HIGH_TAG_NUMBER CCASN1_HIGH_TAG_NUMBER +#define CCDER_TELETEX_STRING CCDER_T61_STRING + +#ifdef CCDER_MULTIBYTE_TAGS +#define CCDER_TAG_MASK ((ccder_tag)~0) +#define CCDER_TAGNUM_MASK ((ccder_tag)~((ccder_tag)7 << (sizeof(ccder_tag) * 8 - 3))) + +#define CCDER_METHOD_MASK ((ccder_tag)1 << (sizeof(ccder_tag) * 8 - 3)) +#define CCDER_PRIMITIVE ((ccder_tag)0 << (sizeof(ccder_tag) * 8 - 3)) +#define CCDER_CONSTRUCTED ((ccder_tag)1 << (sizeof(ccder_tag) * 8 - 3)) + +#define CCDER_CLASS_MASK ((ccder_tag)3 << (sizeof(ccder_tag) * 8 - 2)) +#define CCDER_UNIVERSAL ((ccder_tag)0 << (sizeof(ccder_tag) * 8 - 2)) +#define CCDER_APPLICATION ((ccder_tag)1 << (sizeof(ccder_tag) * 8 - 2)) +#define CCDER_CONTEXT_SPECIFIC ((ccder_tag)2 << (sizeof(ccder_tag) * 8 - 2)) +#define CCDER_PRIVATE ((ccder_tag)3 << (sizeof(ccder_tag) * 8 - 2)) +#else /* !CCDER_MULTIBYTE_TAGS */ +#define CCDER_TAG_MASK CCASN1_TAG_MASK +#define CCDER_TAGNUM_MASK CCASN1_TAGNUM_MASK + +#define CCDER_METHOD_MASK CCASN1_METHOD_MASK +#define CCDER_PRIMITIVE CCASN1_PRIMITIVE +#define CCDER_CONSTRUCTED CCASN1_CONSTRUCTED + +#define CCDER_CLASS_MASK CCASN1_CLASS_MASK +#define CCDER_UNIVERSAL CCASN1_UNIVERSAL +#define CCDER_APPLICATION CCASN1_APPLICATION +#define CCDER_CONTEXT_SPECIFIC CCASN1_CONTEXT_SPECIFIC +#define CCDER_PRIVATE CCASN1_PRIVATE +#endif /* !CCDER_MULTIBYTE_TAGS */ +#define CCDER_CONSTRUCTED_SET (CCDER_SET | CCDER_CONSTRUCTED) +#define CCDER_CONSTRUCTED_SEQUENCE (CCDER_SEQUENCE | CCDER_CONSTRUCTED) + + +// MARK: ccder_sizeof_ functions + +/* Returns the size of an asn1 encoded item of length l in bytes. */ +CC_CONST +size_t ccder_sizeof(ccder_tag tag, size_t len); + +CC_PURE +size_t ccder_sizeof_implicit_integer(ccder_tag implicit_tag, + cc_size n, const cc_unit *s); + +CC_PURE +size_t ccder_sizeof_implicit_octet_string(ccder_tag implicit_tag, + cc_size n, const cc_unit *s); + +CC_CONST +size_t ccder_sizeof_implicit_raw_octet_string(ccder_tag implicit_tag, + size_t s_size); +CC_CONST +size_t ccder_sizeof_implicit_uint64(ccder_tag implicit_tag, uint64_t value); + +CC_PURE +size_t ccder_sizeof_integer(cc_size n, const cc_unit *s); + +CC_CONST +size_t ccder_sizeof_len(size_t len); + +CC_PURE +size_t ccder_sizeof_octet_string(cc_size n, const cc_unit *s); + +CC_PURE +size_t ccder_sizeof_oid(ccoid_t oid); + +CC_CONST +size_t ccder_sizeof_raw_octet_string(size_t s_size); + +CC_CONST +size_t ccder_sizeof_tag(ccder_tag tag); + +CC_CONST +size_t ccder_sizeof_uint64(uint64_t value); + +// MARK: ccder_encode_ functions. + +/* Encode a tag backwards, der_end should point to one byte past the end of + destination for the tag, returns a pointer to the first byte of the tag. + Returns NULL if there is an encoding error. */ +CC_NONNULL2 +uint8_t *ccder_encode_tag(ccder_tag tag, const uint8_t *der, uint8_t *der_end); + +/* Returns a pointer to the start of the len field. returns NULL if there + is an encoding error. */ +CC_NONNULL2 +uint8_t * +ccder_encode_len(size_t len, const uint8_t *der, uint8_t *der_end); + +/* der_end should point to the first byte of the content of this der item. */ +CC_NONNULL3 +uint8_t * +ccder_encode_tl(ccder_tag tag, size_t len, const uint8_t *der, uint8_t *der_end); + +CC_PURE CC_NONNULL2 +uint8_t * +ccder_encode_body_nocopy(size_t size, const uint8_t *der, uint8_t *der_end); + +/* Encode the tag and length of a constructed object. der is the lower + bound, der_end is one byte paste where we want to write the length and + body_end is one byte past the end of the body of the der object we are + encoding the tag and length of. */ +CC_NONNULL((2, 3)) +uint8_t * +ccder_encode_constructed_tl(ccder_tag tag, const uint8_t *body_end, + const uint8_t *der, uint8_t *der_end); + +/* Encodes oid into der and returns + der + ccder_sizeof_oid(oid). */ +CC_NONNULL_TU((1)) CC_NONNULL2 +uint8_t *ccder_encode_oid(ccoid_t oid, const uint8_t *der, uint8_t *der_end); + +CC_NONNULL((3, 4)) +uint8_t *ccder_encode_implicit_integer(ccder_tag implicit_tag, + cc_size n, const cc_unit *s, + const uint8_t *der, uint8_t *der_end); + +CC_NONNULL((2, 3)) +uint8_t *ccder_encode_integer(cc_size n, const cc_unit *s, + const uint8_t *der, uint8_t *der_end); + +CC_NONNULL3 +uint8_t *ccder_encode_implicit_uint64(ccder_tag implicit_tag, + uint64_t value, + const uint8_t *der, uint8_t *der_end); + +CC_NONNULL2 +uint8_t *ccder_encode_uint64(uint64_t value, + const uint8_t *der, uint8_t *der_end); + +CC_NONNULL((3, 4)) +uint8_t *ccder_encode_implicit_octet_string(ccder_tag implicit_tag, + cc_size n, const cc_unit *s, + const uint8_t *der, + uint8_t *der_end); + +CC_NONNULL((2, 3)) +uint8_t *ccder_encode_octet_string(cc_size n, const cc_unit *s, + const uint8_t *der, uint8_t *der_end); + +CC_NONNULL((3, 4)) +uint8_t *ccder_encode_implicit_raw_octet_string(ccder_tag implicit_tag, + size_t s_size, const uint8_t *s, + const uint8_t *der, + uint8_t *der_end); + +CC_NONNULL((2, 3)) +uint8_t *ccder_encode_raw_octet_string(size_t s_size, const uint8_t *s, + const uint8_t *der, uint8_t *der_end); + +size_t ccder_encode_eckey_size(size_t priv_size, ccoid_t oid, size_t pub_size); + +CC_NONNULL2 CC_NONNULL5 CC_NONNULL6 CC_NONNULL7 +uint8_t *ccder_encode_eckey(size_t priv_size, const uint8_t *priv_key, + ccoid_t oid, + size_t pub_size, const uint8_t *pub_key, + uint8_t *der, uint8_t *der_end); + +/* ccder_encode_body COPIES the body into the der. + It's inefficient – especially when you already have to convert to get to + the form for the body. + see encode integer for the right way to unify conversion and insertion */ +CC_NONNULL3 +uint8_t * +ccder_encode_body(size_t size, const uint8_t* body, + const uint8_t *der, uint8_t *der_end); + +// MARK: ccder_decode_ functions. + +/* Returns a pointer to the start of the length field, and returns the decoded tag in tag. + returns NULL if there is a decoding error. */ +CC_NONNULL((1, 3)) +const uint8_t *ccder_decode_tag(ccder_tag *tagp, const uint8_t *der, const uint8_t *der_end); + +CC_NONNULL((1, 3)) +const uint8_t *ccder_decode_len(size_t *lenp, const uint8_t *der, const uint8_t *der_end); + +/* Returns a pointer to the start of the der object, and returns the length in len. + returns NULL if there is a decoding error. */ +CC_NONNULL((2, 4)) +const uint8_t *ccder_decode_tl(ccder_tag expected_tag, size_t *lenp, + const uint8_t *der, const uint8_t *der_end); + +CC_NONNULL((2, 4)) +const uint8_t * +ccder_decode_constructed_tl(ccder_tag expected_tag, const uint8_t **body_end, + const uint8_t *der, const uint8_t *der_end); + +CC_NONNULL((1, 3)) +const uint8_t * +ccder_decode_sequence_tl(const uint8_t **body_end, + const uint8_t *der, const uint8_t *der_end); + +/*! + @function ccder_decode_uint_n + @abstract length in cc_unit of a der unsigned integer after skipping the leading zeroes + + @param der Beginning of input DER buffer + @param der_end End of input DER buffer + @param n Output the number of cc_unit required to represent the number + + @result First byte after the parsed integer or + NULL if the integer is not valid (negative) or reach der_end when reading the integer + */ + +CC_NONNULL((3)) +const uint8_t *ccder_decode_uint_n(cc_size *n, + const uint8_t *der, const uint8_t *der_end); + +/*! + @function ccder_decode_uint + @abstract Represent in cc_unit a der unsigned integer after skipping the leading zeroes + + @param der Beginning of input DER buffer + @param der_end End of input DER buffer + @param n Number of cc_unit allocated for r + @param r Allocated array of cc_unit to copy the integer into. + + @result First byte after the parsed integer or + NULL if the integer is not valid (negative) + reach der_end when reading the integer + n cc_unit is not enough to represent the integer + */ +CC_NONNULL((4)) +const uint8_t *ccder_decode_uint(cc_size n, cc_unit *r, + const uint8_t *der, const uint8_t *der_end); + +CC_NONNULL((3)) +const uint8_t *ccder_decode_uint64(uint64_t* r, + const uint8_t *der, const uint8_t *der_end); + +/* Decode SEQUENCE { r, s -- (unsigned)integer } in der into r and s. + Returns NULL on decode errors, returns pointer just past the end of the + sequence of integers otherwise. */ +CC_NONNULL((2, 3, 5)) +const uint8_t *ccder_decode_seqii(cc_size n, cc_unit *r, cc_unit *s, + const uint8_t *der, const uint8_t *der_end); +CC_NONNULL_TU((1)) CC_NONNULL((3)) +const uint8_t *ccder_decode_oid(ccoid_t *oidp, + const uint8_t *der, const uint8_t *der_end); + +CC_NONNULL((1,2,4)) +const uint8_t *ccder_decode_bitstring(const uint8_t **bit_string, + size_t *bit_length, + const uint8_t *der, const uint8_t *der_end); + +CC_NONNULL_TU((4)) CC_NONNULL((1,2,3,5,6,8)) +const uint8_t *ccder_decode_eckey(uint64_t *version, + size_t *priv_size, const uint8_t **priv_key, + ccoid_t *oid, + size_t *pub_size, const uint8_t **pub_key, + const uint8_t *der, const uint8_t *der_end); + +#define CC_EC_OID_SECP192R1 {((unsigned char *)"\x06\x08\x2a\x86\x48\xce\x3d\x03\x01\x01")} +#define CC_EC_OID_SECP256R1 {((unsigned char *)"\x06\x08\x2a\x86\x48\xce\x3d\x03\x01\x07")} +#define CC_EC_OID_SECP224R1 {((unsigned char *)"\x06\x05\x2B\x81\x04\x00\x21")} +#define CC_EC_OID_SECP384R1 {((unsigned char *)"\x06\x05\x2B\x81\x04\x00\x22")} +#define CC_EC_OID_SECP521R1 {((unsigned char *)"\x06\x05\x2B\x81\x04\x00\x23")} + + +#endif /* _CORECRYPTO_CCDER_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccder_decode_eckey.h b/libraries/corecrypto/include/corecrypto/ccder_decode_eckey.h new file mode 100644 index 0000000..891bb7e --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccder_decode_eckey.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2012,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCDER_DECODE_ECKEY_H_ +#define _CORECRYPTO_CCDER_DECODE_ECKEY_H_ + +// This header is used by a few external clients. +// Clients all need to move to + +#include + +#endif /* _CORECRYPTO_CCDER_DECODE_ECKEY_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccder_encode_eckey.h b/libraries/corecrypto/include/corecrypto/ccder_encode_eckey.h new file mode 100644 index 0000000..88f8890 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccder_encode_eckey.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2014,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ +#ifndef _CORECRYPTO_CCDER_ENCODE_ECKEY_H_ +#define _CORECRYPTO_CCDER_ENCODE_ECKEY_H_ + +// This header is used by a few external clients. +// Clients all need to move to + +#include + +#endif /* _CORECRYPTO_CCDER_ENCODE_ECKEY_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccder_priv.h b/libraries/corecrypto/include/corecrypto/ccder_priv.h new file mode 100644 index 0000000..cf0331d --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccder_priv.h @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ +#ifndef ccder_priv_h +#define ccder_priv_h + +/*! + @function ccder_decode_uint_skip_leading_zeroes + @abstract Return the pointer on the most significant byte + Caller must ensure there is no overread (der + *len < der_end) prior + to calling this. + Per ITU-T Rec. X.690 (07/2002), section 8.3 "If the contents octets of an integer value + encoding consist of more than one octet, then the bits of the first octet + and bit 8 of the second octet, Shall not all be ones and shall not be zero". + Here we only allow unsigned integers. + + @param der Beginning of input DER buffer + @param len Pointer to the length. Update to the number of remaining byte + it may contain 0 as input/output. + + @result Pointer on the most significant byte + NULL is too many leading zeroes + */ + +CC_NONNULL((1, 2)) +CC_INLINE const uint8_t *ccder_decode_uint_skip_leading_zeroes( + size_t *len, + const uint8_t *der) +{ + if (!(*len)) { + // ISO/IEC 8825-1:2003 (E) 8.3.1 The encoding of an integer value shall be primitive + // The contents octets shall consist of one or more octets. + return NULL; + } + // Sign + if (der[0] & 0x80) { + // Negative value, not authorized for unsigned integer + return NULL; + } + // Leading byte + if (der[0] == 0) { + (*len)--; + der++; + + // At this point, we expect the most significant bit set + if ((*len) + && !(der[0] & 0x80)) return NULL; + } + + return der; +} + +#endif /* ccder_priv_h */ diff --git a/libraries/corecrypto/include/corecrypto/ccder_rsa.h b/libraries/corecrypto/include/corecrypto/ccder_rsa.h new file mode 100644 index 0000000..1955601 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccder_rsa.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2012,2015,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef corecrypto_ccder_rsa_h +#define corecrypto_ccder_rsa_h + +#include +#include + +CC_INLINE uint8_t * +ccder_encode_cczp_as_integer(cczp_t zp, const uint8_t *der, uint8_t *der_end) { + return ccder_encode_integer(cczp_n(zp), cczp_prime(zp), der, der_end); +} + + +#endif diff --git a/libraries/corecrypto/include/corecrypto/ccdes.h b/libraries/corecrypto/include/corecrypto/ccdes.h new file mode 100644 index 0000000..9550a6c --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccdes.h @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2010,2012,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCDES_H_ +#define _CORECRYPTO_CCDES_H_ + +#include + +#define CCDES_BLOCK_SIZE 8 +#define CCDES_KEY_SIZE 8 + +extern const struct ccmode_ecb ccdes_ltc_ecb_decrypt_mode; +extern const struct ccmode_ecb ccdes_ltc_ecb_encrypt_mode; + +extern const struct ccmode_ecb ccdes3_ltc_ecb_decrypt_mode; +extern const struct ccmode_ecb ccdes3_ltc_ecb_encrypt_mode; +extern const struct ccmode_ecb ccdes168_ltc_ecb_encrypt_mode; + +const struct ccmode_ecb *ccdes_ecb_decrypt_mode(void); +const struct ccmode_ecb *ccdes_ecb_encrypt_mode(void); + +const struct ccmode_cbc *ccdes_cbc_decrypt_mode(void); +const struct ccmode_cbc *ccdes_cbc_encrypt_mode(void); + +const struct ccmode_cfb *ccdes_cfb_decrypt_mode(void); +const struct ccmode_cfb *ccdes_cfb_encrypt_mode(void); + +const struct ccmode_cfb8 *ccdes_cfb8_decrypt_mode(void); +const struct ccmode_cfb8 *ccdes_cfb8_encrypt_mode(void); + +const struct ccmode_ctr *ccdes_ctr_crypt_mode(void); + +const struct ccmode_ofb *ccdes_ofb_crypt_mode(void); + + +const struct ccmode_ecb *ccdes3_ecb_decrypt_mode(void); +const struct ccmode_ecb *ccdes3_ecb_encrypt_mode(void); + +const struct ccmode_cbc *ccdes3_cbc_decrypt_mode(void); +const struct ccmode_cbc *ccdes3_cbc_encrypt_mode(void); + +const struct ccmode_cfb *ccdes3_cfb_decrypt_mode(void); +const struct ccmode_cfb *ccdes3_cfb_encrypt_mode(void); + +const struct ccmode_cfb8 *ccdes3_cfb8_decrypt_mode(void); +const struct ccmode_cfb8 *ccdes3_cfb8_encrypt_mode(void); + +const struct ccmode_ctr *ccdes3_ctr_crypt_mode(void); + +const struct ccmode_ofb *ccdes3_ofb_crypt_mode(void); + +int ccdes_key_is_weak( void *key, size_t length); +void ccdes_key_set_odd_parity(void *key, size_t length); + +uint32_t +ccdes_cbc_cksum(void *in, void *out, size_t length, + void *key, size_t keylen, void *ivec); + + +#endif /* _CORECRYPTO_CCDES_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccdh.h b/libraries/corecrypto/include/corecrypto/ccdh.h new file mode 100644 index 0000000..fdb5360 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccdh.h @@ -0,0 +1,516 @@ +/* + * Copyright (c) 2011,2012,2013,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCDH_H_ +#define _CORECRYPTO_CCDH_H_ + +#include +#include +#include + +/* Error codes */ +#define CCDH_ERROR_DEFAULT -1 +#define CCDH_GENERATE_KEY_TOO_MANY_TRIES -2 +#define CCDH_NOT_SUPPORTED_CONFIGURATION -3 +#define CCDH_SAFETY_CHECK -4 +#define CCDH_PUBLIC_KEY_MISSING -5 +#define CCDH_INVALID_DOMAIN_PARAMETER -6 +#define CCDH_INVALID_INPUT -7 +#define CCDH_DOMAIN_PARAMETER_MISMATCH -8 +#define CCDH_GENERATE_KEY_CONSISTENCY -9 + +#if CORECRYPTO_USE_TRANSPARENT_UNION + +cc_aligned_struct(16) ccdh_gp; + +/* A ccdh_gp_t is a pointer to a set of DH parameters. + The first entry is a (short) prime field. */ +typedef union { + cczp_t zp; + ccdh_gp *gp; +} __attribute__((transparent_union)) ccdh_gp_t; + +/* A ccdh_const_gp_t is a const pointer to a set of DH parameters. + The first entry is a const prime field. */ +typedef union { + cczp_const_t zp; + const ccdh_gp *gp; + ccdh_gp_t _ncgp; // Non const variant +} __attribute__((transparent_union)) ccdh_const_gp_t; + + +/* Every dh context (a public or private key) starts with this. */ +struct ccdh_ctx_header { + ccdh_const_gp_t gp; + uint8_t pad[16 - sizeof(ccdh_const_gp_t *)]; +} CC_ALIGNED(16); + +struct ccdh_ctx_body { + struct ccdh_ctx_header hdr; + cc_unit xy[]; +} CC_ALIGNED(16); + +struct ccdh_ctx_public { + struct ccdh_ctx_header hdr; + cc_unit pub[]; +} CC_ALIGNED(16); + +/* The ccdh_full_ctx_decl macro allocates an array of ccdh_full_ctx */ +typedef struct ccdh_full_ctx { + struct ccdh_ctx_header hdr; +} CC_ALIGNED(16) ccdh_full_ctx; + +/* The ccdh_pub_ctx_decl macro allocates an array of ccdh_pub_ctx */ +typedef struct ccdh_pub_ctx { + struct ccdh_ctx_header hdr; +} CC_ALIGNED(16) ccdh_pub_ctx; + +/* A ccdh_full_ctx_t is a pointer to a dh key pair. It should be + allocated to be sizeof(ccdh_full_ctx_decl()) bytes. Each of the + ccns within a dh key is always ccdh_ctx_n() cc_units long. */ +typedef union { + ccdh_full_ctx *_full; // Constructor + struct ccdh_ctx_header *hdr; + struct ccdh_ctx_body *body; + struct ccdh_ctx_public *pub; +} __attribute__((transparent_union)) ccdh_full_ctx_t; + +typedef union { + ccdh_pub_ctx *_pub; // Constructor + ccdh_full_ctx *_full; // Constructor + struct ccdh_ctx_header *hdr; + struct ccdh_ctx_body *body; + struct ccdh_ctx_public *pub; + ccdh_full_ctx_t fullt; // Conversion constructor fk->pk +} __attribute__((transparent_union)) ccdh_pub_ctx_t; + +#else //================================================= NO transparent union + +struct ccdh_gp { + __CCZP_ELEMENTS_DEFINITIONS() +} CC_ALIGNED(CCN_UNIT_SIZE); + +/* A ccdh_gp_t is a pointer to a set of DH parameters. + The first entry is a (short) prime field. */ +typedef struct ccdh_gp *ccdh_gp_t; + +/* A ccdh_const_gp_t is a const pointer to a set of DH parameters. + The first entry is a const prime field. */ +typedef const struct ccdh_gp *ccdh_const_gp_t; + +/* The ccdh_full_ctx_decl macro allocates an array of ccdh_full_ctx */ +struct ccdh_full_ctx { + ccdh_const_gp_t gp; + uint8_t pad[16 - sizeof(ccdh_const_gp_t *)]; + cc_unit xy[]; +} CC_ALIGNED(16) ; + +/* The ccdh_pub_ctx_decl macro allocates an array of ccdh_pub_ctx */ +struct ccdh_pub_ctx { + ccdh_const_gp_t gp; + uint8_t pad[16 - sizeof(ccdh_const_gp_t *)]; + cc_unit xy[]; +} CC_ALIGNED(16) ; + +/* A ccdh_full_ctx_t is a pointer to a dh key pair. It should be + allocated to be sizeof(ccdh_full_ctx_decl()) bytes. Each of the + ccns within a dh key is always ccdh_ctx_n() cc_units long. */ + +typedef struct ccdh_full_ctx *ccdh_full_ctx_t; +typedef struct ccdh_pub_ctx *ccdh_pub_ctx_t; + +#endif //================================================= NO transparent union + +#if CORECRYPTO_USE_TRANSPARENT_UNION + /* Return the size of an ccdh_full_ctx where each ccn is _size_ bytes. */ + /* Full has x and y */ + #define ccdh_full_ctx_size(_size_) (sizeof(struct ccdh_ctx_header) + 2 * (_size_)) + /* Pub has only y */ + #define ccdh_pub_ctx_size(_size_) (sizeof(struct ccdh_ctx_header) + 1 * (_size_)) + + /* Declare a fully scheduled dh key. Size is the size in bytes each ccn in + the key. For example to declare (on the stack or in a struct) a 1024 bit + dh public key named foo use ccdh_pub_ctx_decl(ccn_sizeof(1024), foo). */ + #define ccdh_full_ctx_decl(_size_, _name_) cc_ctx_decl(ccdh_full_ctx, ccdh_full_ctx_size(_size_), _name_) + #define ccdh_pub_ctx_decl(_size_, _name_) cc_ctx_decl(ccdh_pub_ctx, ccdh_pub_ctx_size(_size_), _name_) +#else + /* Return the size of an ccdh_full_ctx where each ccn is _size_ bytes. */ + /* Full has x and y */ + #define ccdh_full_ctx_size(_size_) (sizeof(struct ccdh_full_ctx) + 2 * (_size_)) + /* Pub has only y */ + #define ccdh_pub_ctx_size(_size_) (sizeof(struct ccdh_pub_ctx) + 1 * (_size_)) + + /* Declare a fully scheduled dh key. Size is the size in bytes each ccn in + the key. For example to declare (on the stack or in a struct) a 1024 bit + dh public key named foo use ccdh_pub_ctx_decl(ccn_sizeof(1024), foo). */ + #define ccdh_full_ctx_decl(_size_, _name_) cc_ctx_decl(struct ccdh_full_ctx, ccdh_full_ctx_size(_size_), _name_) + #define ccdh_pub_ctx_decl(_size_, _name_) cc_ctx_decl(struct ccdh_pub_ctx, ccdh_pub_ctx_size(_size_), _name_) +#endif + +#define ccdh_pub_ctx_clear(_size_, _name_) cc_clear(ccdh_pub_ctx_size(_size_), _name_) +#define ccdh_full_ctx_clear(_size_, _name_) cc_clear(ccdh_full_ctx_size(_size_), _name_) +/* Declare storage for a fully scheduled dh key for a given set of dh parameters. */ +#define ccdh_full_ctx_decl_gp(_gp_, _name_) ccdh_full_ctx_decl(ccdh_ccn_size(_gp_), _name_) +#define ccdh_pub_ctx_decl_gp(_gp_, _name_) ccdh_pub_ctx_decl(ccdh_ccn_size(_gp_), _name_) + +/* Return the length of the prime for gp in bits. */ +#define ccdh_gp_prime_bitlen(GP) (ccn_bitlen(ccdh_gp_n(GP), ccdh_gp_prime(GP))) + +/* Return the sizeof the prime for gp. */ +#define ccdh_gp_prime_size(GP) (ccdh_ccn_size(GP)) + +#if CORECRYPTO_USE_TRANSPARENT_UNION +/* Group parameters accessors */ +/* If you set the structure manually, you must set it to zero to be + future proof */ +#define CCDH_GP_N(_gp_) (CCZP_N((_gp_).zp)) +#define CCDH_GP_PRIME(_gp_) (CCZP_PRIME((_gp_).zp)) +#define CCDH_GP_ZP(_gp_) ((_gp_).zp) +static inline cczp_const_t ccdh_gp_zp(ccdh_const_gp_t gp) { return gp.zp;} +#define CCDH_GP_RECIP(_gp_) (CCZP_RECIP((_gp_).zp)) +/* l must be chosen wisely to avoid the private key to be recoverable with the Pohlig-Hellman algorithm for example. "Small" l is only possible for special groups for example when p is a safe prime. */ +#else +/* Group parameters accessors */ +/* If you set the structure manually, you must set it to zero to be + future proof */ +#define CCDH_GP_N(_gp_) (CCZP_N(_gp_)) +#define CCDH_GP_PRIME(_gp_) (CCZP_PRIME(_gp_)) +#define CCDH_GP_ZP(_gp_) ((cczp_t)(_gp_)) +static inline cczp_const_t ccdh_gp_zp(ccdh_const_gp_t gp) { return (cczp_const_t) gp;} +#define CCDH_GP_RECIP(_gp_) (CCZP_RECIP((_gp_))) +#endif + +#define CCDH_GP_G(_gp_) (CCDH_GP_RECIP(_gp_) + 1 + ccdh_gp_n(_gp_)) // recip size is n+1 +#define CCDH_GP_L(_gp_) (*((CCDH_GP_Q(_gp_) + ccdh_gp_n(_gp_)))) // Size of the private key in bit. +#define CCDH_GP_Q(_gp_) (CCDH_GP_G(_gp_) + ccdh_gp_n(_gp_)) // generator size is n +/* l must be chosen wisely to avoid the private key to be recoverable with the Pohlig-Hellman algorithm for example. "Small" l is only possible for special groups for example when p is a safe prime. */ + +/* Return the size of a ccdh_gp where the prime is of _size_ bytes. */ +#define ccdh_gp_size(_size_) (cczp_size(_size_) + 2 * (_size_) + ccn_sizeof_n(1)) + +#if CORECRYPTO_USE_TRANSPARENT_UNION + +/* Declare a gp */ +#define ccdh_gp_decl(_size_, _name_) cc_ctx_decl(ccdh_gp, ccdh_gp_size(_size_), _name_) + +/* lvalue accessors to ccdh_ctx fields. (only a ccdh_full_ctx_t has y). */ +/* gp: group parameter */ +#define ccdh_ctx_gp(KEY) (((ccdh_pub_ctx_t)(KEY)).hdr->gp) +//we do not call ccdh_ctx_public(), because ccdh_ctx_gp may be called with ccdh_pub_ctx_t KEY +/* n: size of group */ +#define ccdh_ctx_n(KEY) (ccdh_gp_n(ccdh_ctx_gp(KEY))) +/* prime: group prime */ +#define ccdh_ctx_prime(KEY) (ccdh_gp_prime(ccdh_ctx_gp(KEY))) +/* y: the public key */ +#define ccdh_ctx_y(KEY) (((ccdh_pub_ctx_t)(KEY)).body->xy) +/* x: the private key */ +#define ccdh_ctx_x(KEY) (((ccdh_full_ctx_t)(KEY)).body->xy + 1 * ccdh_ctx_n(KEY)) +#else + +/* Declare a gp */ +#define ccdh_gp_decl(_size_, _name_) cc_ctx_decl(struct ccdh_gp, ccdh_gp_size(_size_), _name_) + +/* lvalue accessors to ccdh_ctx fields. (only a ccdh_full_ctx_t has y). */ +/* gp: group parameter */ +#define ccdh_ctx_gp(KEY) (((ccdh_pub_ctx_t)(KEY))->gp) +/* n: size of group */ +#define ccdh_ctx_n(KEY) (ccdh_gp_n(ccdh_ctx_gp(KEY))) +/* prime: group prime */ +#define ccdh_ctx_prime(KEY) (ccdh_gp_prime(ccdh_ctx_gp(KEY))) +/* y: the public key */ +#define ccdh_ctx_y(KEY) ((KEY)->xy) +/* x: the private key */ +#define ccdh_ctx_x(KEY) (ccdh_ctx_y(KEY) + 1 * ccdh_ctx_n(KEY)) + +#endif + +CC_INLINE +ccdh_pub_ctx_t ccdh_ctx_public(ccdh_full_ctx_t key) { + return (ccdh_pub_ctx_t)key; +} + +#if CORECRYPTO_USE_TRANSPARENT_UNION + +/* Callers must call this function to initialze a ccdh_full_ctx or + ccdh_pub_ctx before using most of the macros in this file. */ +CC_INLINE CC_NONNULL_TU((1)) +void ccdh_ctx_init(ccdh_const_gp_t gp, ccdh_pub_ctx_t key) { + key.hdr->gp = gp; +} + +/* rvalue accessors to ccdh_ctx fields. */ + +/* Return count (n) of a ccn for gp. */ +CC_CONST CC_INLINE CC_NONNULL_TU((1)) +cc_size ccdh_gp_n(ccdh_const_gp_t gp) { + return cczp_n(gp.zp); +} + +CC_CONST CC_INLINE CC_NONNULL_TU((1)) +const cc_unit *ccdh_gp_prime(ccdh_const_gp_t gp) { + return cczp_prime(gp.zp); +} + +CC_CONST CC_INLINE CC_NONNULL_TU((1)) +const cc_unit *ccdh_gp_recip(ccdh_const_gp_t gp) { + return cczp_recip(gp.zp); +} + +CC_CONST CC_INLINE CC_NONNULL_TU((1)) +const cc_unit ccdh_gp_options(ccdh_const_gp_t gp) { + return cczp_options(gp.zp); +} + +CC_CONST CC_INLINE CC_NONNULL_TU((1)) +const cc_unit *ccdh_gp_g(ccdh_const_gp_t gp) { + return CCDH_GP_G(gp._ncgp); +} + +CC_CONST CC_INLINE CC_NONNULL_TU((1)) +const cc_unit *ccdh_gp_order(ccdh_const_gp_t gp) { + return CCDH_GP_Q(gp._ncgp); +} + +CC_CONST CC_INLINE CC_NONNULL_TU((1)) +cc_size ccdh_gp_l(ccdh_const_gp_t gp) { + return CCDH_GP_L(gp._ncgp); +} +/* Return sizeof a ccn for gp. */ +CC_CONST CC_INLINE CC_NONNULL_TU((1)) +size_t ccdh_ccn_size(ccdh_const_gp_t gp) { + return ccn_sizeof_n(cczp_n(gp.zp)); +} + +#else //================================================================================= +/* Callers must call this function to initialze a ccdh_full_ctx or + ccdh_pub_ctx before using most of the macros in this file. */ +CC_INLINE CC_NONNULL_TU((1)) +void ccdh_ctx_init(ccdh_const_gp_t gp, ccdh_pub_ctx_t key) { + key->gp = gp; +} + +/* rvalue accessors to ccdh_ctx fields. */ + +/* Return count (n) of a ccn for gp. */ +CC_CONST CC_INLINE CC_NONNULL_TU((1)) +cc_size ccdh_gp_n(ccdh_const_gp_t gp) { + return cczp_n((cczp_const_t)gp); +} + +CC_CONST CC_INLINE CC_NONNULL_TU((1)) +const cc_unit *ccdh_gp_prime(ccdh_const_gp_t gp) { + return cczp_prime((cczp_const_t)gp); +} + +CC_CONST CC_INLINE CC_NONNULL_TU((1)) +const cc_unit *ccdh_gp_recip(ccdh_const_gp_t gp) { + return cczp_recip((cczp_const_t)gp); +} + +CC_CONST CC_INLINE CC_NONNULL_TU((1)) +const cc_unit ccdh_gp_options(ccdh_const_gp_t gp) { + return cczp_options((cczp_const_t)gp); +} + +CC_CONST CC_INLINE CC_NONNULL_TU((1)) +const cc_unit *ccdh_gp_g(ccdh_const_gp_t gp) { + return CCDH_GP_G(gp); +} + +CC_CONST CC_INLINE CC_NONNULL_TU((1)) +const cc_unit *ccdh_gp_order(ccdh_const_gp_t gp) { + return CCDH_GP_Q(gp); +} + +CC_CONST CC_INLINE CC_NONNULL_TU((1)) +cc_size ccdh_gp_l(ccdh_const_gp_t gp) { + return CCDH_GP_L((ccdh_const_gp_t)gp); +} + +/* Return sizeof a ccn for gp. */ +CC_CONST CC_INLINE CC_NONNULL_TU((1)) +size_t ccdh_ccn_size(ccdh_const_gp_t gp) { + return ccn_sizeof_n(CCZP_N(gp)); +} + +#endif//================================================================================= + +CC_INLINE CC_NONNULL_TU((1)) +size_t ccdh_gp_order_bitlen(ccdh_const_gp_t gp) { + return ccn_bitlen(ccdh_gp_n(gp),ccdh_gp_order(gp)); +} + + + +/* DH group parameter initialization */ + +/* + * Group paramters must be well chosen to avoid serious security issues. + * a) ccdh_init_gp with l>0 is to be used for group parameter where p is a safe prime. + * l should be at least twice the security level desired (128bit security => l=256). + * If you are not sure, set l=0, it is slow but it is safe against attacks using the + * Pohlig-Hellman algorithm for example. + * b) ccdh_init_gp_with_order is to be used when the group prime is not a safe prime: + * the order is necessary to avoid small subgroup attacks and generate the private key + * efficiently + * c) ccdh_init_gp_with_order to set the group from byte. + * If the group prime is not a safe prime, the order MUST be provided to avoid small subgroup attacks + * If the group prime is a safe prime, l should be at least twice the security level desired (128bit security => l=256). + * If you are not sure, set l=0, it is slow but it is safe against attacks using the + * Pohlig-Hellman algorithm for example. + */ +CC_NONNULL_TU((1)) CC_NONNULL((3, 4)) +int ccdh_init_gp(ccdh_gp_t gp, cc_size n, + const cc_unit *p, + const cc_unit *g, + cc_size l); + +CC_NONNULL_TU((1)) CC_NONNULL((3, 4, 5)) +int ccdh_init_gp_with_order(ccdh_gp_t gp, cc_size n, + const cc_unit *p, + const cc_unit *g, + const cc_unit *q); + +CC_NONNULL_TU((1)) CC_NONNULL((4, 6)) +int ccdh_init_gp_from_bytes(ccdh_gp_t gp, cc_size n, + size_t p_len, const uint8_t *p, + size_t g_len, const uint8_t *g, + size_t q_len, const uint8_t *q, + cc_size l); + +/* + * Generate a DH private/public key pair from the group parameter + */ +CC_NONNULL_TU((1)) CC_NONNULL2 +int ccdh_generate_key(ccdh_const_gp_t gp, struct ccrng_state *rng, + ccdh_full_ctx_t key); + +/* + * Compute an DH shared secret between private_key and public_key after validation the public key. + * Returns the result in computed_key, which must be an array of ccdh_ctx_n(private_key) cc_units + * DEPRECATED - use ccdh_compute_key + */ + +CC_NONNULL_TU((1,2)) CC_NONNULL3 +int ccdh_compute_key(ccdh_full_ctx_t private_key, ccdh_pub_ctx_t public_key, + cc_unit *computed_key); + +/* Leading bytes of computed_shared_secret (a.k.a. Z) that contain all zero bits + are stripped before it is used as the shared secret. Match common specs such as TLS */ +CC_NONNULL_TU((1,2)) CC_NONNULL4 +int ccdh_compute_shared_secret(ccdh_full_ctx_t private_key, + ccdh_pub_ctx_t public_key, + size_t *computed_shared_secret_len, + uint8_t *computed_shared_secret, + struct ccrng_state *blinding_rng); + + +/* Import a public key. The imported key is an Octet String, as defined in PKCS#3 */ +CC_NONNULL_TU((1)) CC_NONNULL3 +int ccdh_import_pub(ccdh_const_gp_t gp, size_t in_len, const uint8_t *in, + ccdh_pub_ctx_t key); + +/* Import a private key. The imported key is an Octet String, as defined in PKCS#3 */ +CC_NONNULL_TU((1)) CC_NONNULL3 +int ccdh_import_priv(ccdh_const_gp_t gp, size_t in_len, const uint8_t *in, + ccdh_full_ctx_t key); + +/* Import a private key. The imported key is an Octet String, as defined in PKCS#3 */ +CC_NONNULL_TU((1)) CC_NONNULL3 +int ccdh_import_full(ccdh_const_gp_t gp, + size_t in_priv_len, const uint8_t *in_priv, + size_t in_pub_len, const uint8_t *in_pub, + ccdh_full_ctx_t key); + +/* Return the sizeof a buffer needed to exported public key to. */ +CC_INLINE CC_CONST CC_NONNULL_TU((1)) +size_t ccdh_export_pub_size(ccdh_pub_ctx_t key) { + return ccdh_gp_prime_size(ccdh_ctx_gp(key)); +} + +/* Export public key to out. Out must be ccdh_export_pub_size(key) bytes long. + The key is exported as an Octet String, as defined in PKCS#3 */ +CC_NONNULL_TU((1)) CC_NONNULL2 +void ccdh_export_pub(ccdh_pub_ctx_t key, void *out); + +/* + * ASN.1/DER glue from PKCS #3 : + * prime p, generator g, and optional privateValueLength l + */ + +CC_NONNULL_TU((1)) +size_t ccder_encode_dhparams_size(const ccdh_const_gp_t gp); + +CC_NONNULL_TU((1)) CC_NONNULL((2)) CC_NONNULL((3)) +uint8_t * ccder_encode_dhparams(const ccdh_const_gp_t gp, uint8_t *der, uint8_t *der_end); + +/* CCZP_N(gpfoo.zp) must be set before decoding */ +CC_NONNULL_TU((1)) CC_NONNULL((2)) +const uint8_t *ccder_decode_dhparams(ccdh_gp_t gp, const uint8_t *der, const uint8_t *der_end); + +/* returns the n needed for ccdh_gp_decl/heap allocation of a ccdh_gp_t, can be larger then the actual size used */ +CC_NONNULL((1)) +cc_size ccder_decode_dhparam_n(const uint8_t *der, const uint8_t *der_end); + +#endif /* _CORECRYPTO_CCDH_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccdh_gp.h b/libraries/corecrypto/include/corecrypto/ccdh_gp.h new file mode 100644 index 0000000..e84885d --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccdh_gp.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2011,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +/* Autogenerated file - Use scheme ccdh_gen_gp to regenerate */ +#ifndef _CORECRYPTO_CCDH_GP_H_ +#define _CORECRYPTO_CCDH_GP_H_ + +#include + +ccdh_const_gp_t ccdh_gp_apple768(void); +ccdh_const_gp_t ccdh_gp_rfc5114_MODP_1024_160(void); +ccdh_const_gp_t ccdh_gp_rfc5114_MODP_2048_224(void); +ccdh_const_gp_t ccdh_gp_rfc5114_MODP_2048_256(void); +ccdh_const_gp_t ccdh_gp_rfc2409group02(void); +ccdh_const_gp_t ccdh_gp_rfc3526group05(void); +ccdh_const_gp_t ccdh_gp_rfc3526group14(void); +ccdh_const_gp_t ccdh_gp_rfc3526group15(void); +ccdh_const_gp_t ccdh_gp_rfc3526group16(void); +ccdh_const_gp_t ccdh_gp_rfc3526group17(void); +ccdh_const_gp_t ccdh_gp_rfc3526group18(void); +ccdh_const_gp_t ccsrp_gp_rfc5054_1024(void); +ccdh_const_gp_t ccsrp_gp_rfc5054_2048(void); +ccdh_const_gp_t ccsrp_gp_rfc5054_3072(void); +ccdh_const_gp_t ccsrp_gp_rfc5054_4096(void); +ccdh_const_gp_t ccsrp_gp_rfc5054_8192(void); + +#endif /* _CORECRYPTO_CCDH_GP_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccdh_priv.h b/libraries/corecrypto/include/corecrypto/ccdh_priv.h new file mode 100644 index 0000000..f054738 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccdh_priv.h @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2011,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCDH_PRIV_H_ +#define _CORECRYPTO_CCDH_PRIV_H_ + +#include + +#define ccdh_gp_decl_n(_n_) \ +struct { \ + struct cczp_hd hp; \ + cc_unit p[(_n_)]; /* Prime */ \ + cc_unit recip[((_n_)+1)]; /* precomp for field ops */ \ + cc_unit g[(_n_)]; /* Generator */ \ + cc_unit q[(_n_)]; /* Order */ \ + cc_size l; /* Size of the private key */ \ +} + +#define ccdh_gp_decl_static(_bits_) ccdh_gp_decl_n(ccn_nof(_bits_)) + +int ccdh_generate_private_key(ccdh_const_gp_t gp, cc_unit *x, + struct ccrng_state *rng); + +int ccdh_check_pub(ccdh_const_gp_t gp, ccdh_pub_ctx_t public_key); + +int ccdh_power_blinded(struct ccrng_state *blinding_rng, + ccdh_const_gp_t gp, + cc_unit *r, const cc_unit *s, const cc_unit *e) ; + +/*! + @function ccdh_pairwise_consistency_check + @abstract Does a DH with a constant key to confirm the newly generated key is + correct. + @param gp Group parameters + @param rng For key generation and internal countermeasures + @param key DH key pair + @return true if no error, false otherwise. + */ +bool ccdh_pairwise_consistency_check(ccdh_const_gp_t gp, + struct ccrng_state *rng, + ccdh_full_ctx_t key); + + +#endif /* _CORECRYPTO_CCDH_GP_PRIV_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccdigest.h b/libraries/corecrypto/include/corecrypto/ccdigest.h new file mode 100644 index 0000000..5177a96 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccdigest.h @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2010,2011,2012,2014,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCDIGEST_H_ +#define _CORECRYPTO_CCDIGEST_H_ + +#include +#include + +/* To malloc a digest context for a given di, use malloc(ccdigest_di_size(di)) + and assign the result to a pointer to a struct ccdigest_ctx. */ +#if CORECRYPTO_USE_TRANSPARENT_UNION +struct ccdigest_ctx { + union { + uint8_t u8; + uint32_t u32; + uint64_t u64; + cc_unit ccn; + } state; +} CC_ALIGNED(8); + +typedef union { + struct ccdigest_ctx *hdr; +} ccdigest_ctx_t __attribute__((transparent_union)); + +struct ccdigest_state { + union { + uint8_t u8; + uint32_t u32; + uint64_t u64; + cc_unit ccn; + } state; +} CC_ALIGNED(8); + +typedef union { + struct ccdigest_state *hdr; + struct ccdigest_ctx *_ctx; + ccdigest_ctx_t _ctxt; +} ccdigest_state_t __attribute__((transparent_union)); +#else //======================================================= +struct ccdigest_ctx { + union { + uint8_t u8; + uint32_t u32; + uint64_t u64; + cc_unit ccn; + } state; +} CC_ALIGNED(8); + +typedef struct ccdigest_ctx *ccdigest_ctx_t ; + +struct ccdigest_state { + union { + uint8_t u8; + uint32_t u32; + uint64_t u64; + cc_unit ccn; + } state; +} CC_ALIGNED(8); + +typedef struct ccdigest_state *ccdigest_state_t; +#endif //======================================================= + + +struct ccdigest_info { + size_t output_size; + size_t state_size; + size_t block_size; + size_t oid_size; + const unsigned char *oid; + const void *initial_state; + void(*compress)(ccdigest_state_t state, size_t nblocks, + const void *data); + void(*final)(const struct ccdigest_info *di, ccdigest_ctx_t ctx, + unsigned char *digest); +}; + +/* Return sizeof a ccdigest_ctx for a given size_t _state_size_ and + size_t _block_size_. */ +#define ccdigest_ctx_size(_state_size_, _block_size_) ((_state_size_) + sizeof(uint64_t) + (_block_size_) + sizeof(unsigned int)) +/* Return sizeof a ccdigest_ctx for a given struct ccdigest_info *_di_. */ +#define ccdigest_di_size(_di_) (ccdigest_ctx_size((_di_)->state_size, (_di_)->block_size)) + +/* Declare a ccdigest_ctx for a given size_t _state_size_ and + size_t _block_size_, named _name_. Can be used in structs or on the + stack. */ +#define ccdigest_ctx_decl(_state_size_, _block_size_, _name_) cc_ctx_decl(struct ccdigest_ctx, ccdigest_ctx_size(_state_size_, _block_size_), _name_) +#define ccdigest_ctx_clear(_state_size_, _block_size_, _name_) cc_clear(ccdigest_ctx_size(_state_size_, _block_size_), _name_) +/* Declare a ccdigest_ctx for a given size_t _state_size_ and + size_t _block_size_, named _name_. Can be used on the stack. */ +#define ccdigest_di_decl(_di_, _name_) cc_ctx_decl(struct ccdigest_ctx, ccdigest_di_size(_di_), _name_) +#define ccdigest_di_clear(_di_, _name_) cc_clear(ccdigest_di_size(_di_), _name_) + +/* Digest context field accessors. Consider the implementation private. */ +#if CORECRYPTO_USE_TRANSPARENT_UNION +#define ccdigest_state(_di_, _ctx_) ((struct ccdigest_state *)(&((ccdigest_ctx_t)(_ctx_)).hdr->state.u8 + sizeof(uint64_t))) +#else +#define ccdigest_state(_di_, _ctx_) ((struct ccdigest_state *)(&((ccdigest_ctx_t)(_ctx_))->state.u8 + sizeof(uint64_t))) +#endif + +#define ccdigest_state_u8(_di_, _ctx_) ccdigest_u8(ccdigest_state((_di_), (_ctx_))) +#define ccdigest_state_u32(_di_, _ctx_) ccdigest_u32(ccdigest_state((_di_), (_ctx_))) +#define ccdigest_state_u64(_di_, _ctx_) ccdigest_u64(ccdigest_state((_di_), (_ctx_))) +#define ccdigest_state_ccn(_di_, _ctx_) ccdigest_ccn(ccdigest_state((_di_), (_ctx_))) + +#if CORECRYPTO_USE_TRANSPARENT_UNION +#define ccdigest_nbits(_di_, _ctx_) (((uint64_t *)(&((ccdigest_ctx_t)(_ctx_)).hdr->state.u8))[0]) +#define ccdigest_data(_di_, _ctx_) (&((ccdigest_ctx_t)(_ctx_)).hdr->state.u8 + (_di_)->state_size + sizeof(uint64_t)) +#define ccdigest_num(_di_, _ctx_) (((unsigned int *)(&((ccdigest_ctx_t)(_ctx_)).hdr->state.u8 + (_di_)->state_size + sizeof(uint64_t) + (_di_)->block_size))[0]) +#else +#define ccdigest_nbits(_di_, _ctx_) (((uint64_t *)(&((ccdigest_ctx_t)(_ctx_))->state.u8))[0]) +#define ccdigest_data(_di_, _ctx_) (&((ccdigest_ctx_t)(_ctx_))->state.u8 + (_di_)->state_size + sizeof(uint64_t)) +#define ccdigest_num(_di_, _ctx_) (((unsigned int *)(&((ccdigest_ctx_t)(_ctx_))->state.u8 + (_di_)->state_size + sizeof(uint64_t) + (_di_)->block_size))[0]) +#endif + +#if CORECRYPTO_USE_TRANSPARENT_UNION +/* Digest state field accessors. Consider the implementation private. */ +#define ccdigest_u8(_state_) (&((ccdigest_state_t)(_state_)).hdr->state.u8) +#define ccdigest_u32(_state_) (&((ccdigest_state_t)(_state_)).hdr->state.u32) +#define ccdigest_u64(_state_) (&((ccdigest_state_t)(_state_)).hdr->state.u64) +#define ccdigest_ccn(_state_) (&((ccdigest_state_t)(_state_)).hdr->state.ccn) +#else +/* Digest state field accessors. Consider the implementation private. */ +#define ccdigest_u8(_state_) (&((ccdigest_state_t)(_state_))->state.u8) +#define ccdigest_u32(_state_) (&((ccdigest_state_t)(_state_))->state.u32) +#define ccdigest_u64(_state_) (&((ccdigest_state_t)(_state_))->state.u64) +#define ccdigest_ccn(_state_) (&((ccdigest_state_t)(_state_))->state.ccn) +#endif + +/* We could just use memcpy instead of this special macro, but this allows us + to use the optimized ccn_set() assembly routine if we have one, which for + 32 bit arm is about 200% quicker than generic memcpy(). */ +#if CCN_SET_ASM && CCN_UNIT_SIZE <= 4 +#define ccdigest_copy_state(_di_, _dst_, _src_) ccn_set((_di_)->state_size / CCN_UNIT_SIZE, _dst_, _src_) +#else +#define ccdigest_copy_state(_di_, _dst_, _src_) CC_MEMCPY(_dst_, _src_, (_di_)->state_size) +#endif + +void ccdigest_init(const struct ccdigest_info *di, ccdigest_ctx_t ctx); +void ccdigest_update(const struct ccdigest_info *di, ccdigest_ctx_t ctx, + size_t len, const void *data); + +CC_INLINE +void ccdigest_final(const struct ccdigest_info *di, ccdigest_ctx_t ctx, unsigned char *digest) +{ + di->final(di,ctx,digest); +} + +void ccdigest(const struct ccdigest_info *di, size_t len, + const void *data, void *digest); + +/* test functions */ +int ccdigest_test(const struct ccdigest_info *di, size_t len, + const void *data, const void *digest); + +int ccdigest_test_chunk(const struct ccdigest_info *di, size_t len, + const void *data, const void *digest, size_t chunk); + +struct ccdigest_vector { + size_t len; + const void *message; + const void *digest; +}; + +int ccdigest_test_vector(const struct ccdigest_info *di, const struct ccdigest_vector *v); +int ccdigest_test_chunk_vector(const struct ccdigest_info *di, const struct ccdigest_vector *v, size_t chunk); + + +#define OID_DEF(_VALUE_) ((const unsigned char *)_VALUE_) + +#define CC_DIGEST_OID_MD2 OID_DEF("\x06\x08\x2A\x86\x48\x86\xF7\x0D\x02\x02") +#define CC_DIGEST_OID_MD4 OID_DEF("\x06\x08\x2A\x86\x48\x86\xF7\x0D\x02\x04") +#define CC_DIGEST_OID_MD5 OID_DEF("\x06\x08\x2A\x86\x48\x86\xF7\x0D\x02\x05") +#define CC_DIGEST_OID_SHA1 OID_DEF("\x06\x05\x2b\x0e\x03\x02\x1a") +#define CC_DIGEST_OID_SHA224 OID_DEF("\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04") +#define CC_DIGEST_OID_SHA256 OID_DEF("\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01") +#define CC_DIGEST_OID_SHA384 OID_DEF("\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02") +#define CC_DIGEST_OID_SHA512 OID_DEF("\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03") +#define CC_DIGEST_OID_RMD128 OID_DEF("\x06\x06\x28\xCF\x06\x03\x00\x32") +#define CC_DIGEST_OID_RMD160 OID_DEF("\x06\x05\x2B\x24\x03\x02\x01") +#define CC_DIGEST_OID_RMD256 OID_DEF("\x06\x05\x2B\x24\x03\x02\x03") +#define CC_DIGEST_OID_RMD320 OID_DEF(NULL) + +#endif /* _CORECRYPTO_CCDIGEST_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccdigest_priv.h b/libraries/corecrypto/include/corecrypto/ccdigest_priv.h new file mode 100644 index 0000000..63632f4 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccdigest_priv.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2010,2011,2012,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCDIGEST_PRIV_H_ +#define _CORECRYPTO_CCDIGEST_PRIV_H_ + +#include +#include + +void ccdigest_final_common(const struct ccdigest_info *di, + ccdigest_ctx_t ctx, void *digest); +void ccdigest_final_64be(const struct ccdigest_info *di, ccdigest_ctx_t, + unsigned char *digest); +void ccdigest_final_64le(const struct ccdigest_info *di, ccdigest_ctx_t, + unsigned char *digest); + +CC_INLINE CC_NONNULL_TU((1)) +bool ccdigest_oid_equal(const struct ccdigest_info *di, ccoid_t oid) { + if(di->oid == NULL && CCOID(oid) == NULL) return true; + if(di->oid == NULL || CCOID(oid) == NULL) return false; + return ccoid_equal(di->oid, oid); +} + +typedef const struct ccdigest_info *(ccdigest_lookup)(ccoid_t oid); + +#include +const struct ccdigest_info *ccdigest_oid_lookup(ccoid_t oid, ...); + +#endif /* _CORECRYPTO_CCDIGEST_PRIV_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccdrbg.h b/libraries/corecrypto/include/corecrypto/ccdrbg.h new file mode 100644 index 0000000..9692e9c --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccdrbg.h @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2010,2011,2012,2014,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +/*! + @header corecrypto/ccdrbg.h + @abstract The functions provided in ccdrbg.h implement high-level accessors + to cryptographically secure random numbers. + + */ + +#ifndef _CORECRYPTO_CCDRBG_H_ +#define _CORECRYPTO_CCDRBG_H_ + +#include +#include + +/* error codes */ +#define CCDRBG_STATUS_OK 0 +#define CCDRBG_STATUS_ERROR (-1) +#define CCDRBG_STATUS_NEED_RESEED (-2) +#define CCDRBG_STATUS_PARAM_ERROR (-3) +// If this value is returned, the caller must abort or panic the process for security reasons. +// for example in the case of catastrophic error in +// http://csrc.nist.gov/publications/drafts/800-90/sp800_90a_r1_draft.pdf +// ccdrbg calls abort() or panic(), if they are available in the system. +#define CCDRBG_STATUS_ABORT (-4) +/* + * The maximum length of the entropy_input, additional_input (max_additional_input_length) , personalization string + * (max_personalization_string_length) and max_number_of_bits_per_request are implementation dependent + * but shall fit in a 32 bit register and be be less than or equal to the specified maximum length for the + * selected DRBG mechanism (NIST 800-90A Section 10). + */ + +#define CCDRBG_MAX_ENTROPY_SIZE ((uint32_t)1<<16) +#define CCDRBG_MAX_ADDITIONALINPUT_SIZE ((uint32_t)1<<16) +#define CCDRBG_MAX_PSINPUT_SIZE ((uint32_t)1<<16) +#define CCDRBG_MAX_REQUEST_SIZE ((uint32_t)1<<16) //this is the absolute maximum in NIST 800-90A +#define CCDRBG_RESEED_INTERVAL ((uint64_t)1<<30) // must be able to fit the NIST maximum of 2^48 + + +/* + * The entropyLength is forced to be greater or equal than the security strength. + * Nonce is not forced. It either needs to have 0.5*security strength entropy. Or, a vale that is repeated + * less than a 0.5*security strength bit random string. + * see below or NIST 800-90A for the definition of security strength + */ + +CC_INLINE int ccdrbg_init(const struct ccdrbg_info *info, + struct ccdrbg_state *drbg, + size_t entropyLength, const void* entropy, + size_t nonceLength, const void* nonce, + size_t psLength, const void* ps) +{ + return info->init(info, drbg, entropyLength, entropy, nonceLength, nonce, psLength, ps); +} + +/* + * The entropyLength is forced to be greater or equal than the security strength. + */ +CC_INLINE int ccdrbg_reseed(const struct ccdrbg_info *info, + struct ccdrbg_state *drbg, + size_t entropyLength, const void *entropy, + size_t additionalLength, const void *additional) +{ + return info->reseed(drbg, entropyLength, entropy, additionalLength, additional); +} + + +CC_INLINE int ccdrbg_generate(const struct ccdrbg_info *info, + struct ccdrbg_state *drbg, + size_t dataOutLength, void *dataOut, + size_t additionalLength, const void *additional) +{ + return info->generate(drbg, dataOutLength, dataOut, additionalLength, additional); +} + +CC_INLINE void ccdrbg_done(const struct ccdrbg_info *info, + struct ccdrbg_state *drbg) +{ + info->done(drbg); +} + +CC_INLINE size_t ccdrbg_context_size(const struct ccdrbg_info *info) +{ + return info->size; +} + + +/* + * NIST SP 800-90 CTR_DRBG + * the maximum security strengh of drbg equals to the block size of the corresponding ECB. + */ +struct ccdrbg_nistctr_custom { + const struct ccmode_ctr *ctr_info; + size_t keylen; + int strictFIPS; + int use_df; +}; + +void ccdrbg_factory_nistctr(struct ccdrbg_info *info, const struct ccdrbg_nistctr_custom *custom); + +/* + * NIST SP 800-90 HMAC_DRBG + * the maximum security strengh of drbg is half of output size of the input hash function and it internally is limited to 256 bits + */ +extern struct ccdrbg_info ccdrbg_nistdigest_info; + +struct ccdrbg_nisthmac_custom { + const struct ccdigest_info *di; + int strictFIPS; +}; + +void ccdrbg_factory_nisthmac(struct ccdrbg_info *info, const struct ccdrbg_nisthmac_custom *custom); + +/* + * NIST SP 800-90 TRNG DRBG + * + * Call into the SEP DRBG and perform a SP 800-90 test operation. + */ +void ccdrbg_factory_trng(struct ccdrbg_info *info); + +/* Required length of the various TRNG entropy and personalization inputs. */ +#define CCDRBG_TRNG_VECTOR_LEN 48 + +/* + * Dummy DRBG + */ +extern struct ccdrbg_info ccdrbg_dummy_info; + +#endif /* _CORECRYPTO_CCDRBG_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccdrbg_factory.h b/libraries/corecrypto/include/corecrypto/ccdrbg_factory.h new file mode 100644 index 0000000..226164d --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccdrbg_factory.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCDRBG_FACTORY_H_ +#define _CORECRYPTO_CCDRBG_FACTORY_H_ + +#endif /* _CORECRYPTO_CCDRBG_FACTORY_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccdrbg_impl.h b/libraries/corecrypto/include/corecrypto/ccdrbg_impl.h new file mode 100644 index 0000000..64506b8 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccdrbg_impl.h @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2012,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCDRBG_IMPL_H_ +#define _CORECRYPTO_CCDRBG_IMPL_H_ + +/* opaque drbg structure */ +struct ccdrbg_state; + +struct ccdrbg_info { + /*! Size of the DRBG state in bytes **/ + size_t size; + + /*! Instantiate the PRNG + @param prng The PRNG state + @param entropylen Length of entropy + @param entropy Entropy bytes + @param inlen Length of additional input + @param in Additional input bytes + @return 0 if successful + */ + int (*init)(const struct ccdrbg_info *info, struct ccdrbg_state *drbg, + size_t entropyLength, const void* entropy, + size_t nonceLength, const void* nonce, + size_t psLength, const void* ps); + + /*! Add entropy to the PRNG + @param prng The PRNG state + @param entropylen Length of entropy + @param entropy Entropy bytes + @param inlen Length of additional input + @param in Additional input bytes + @return 0 if successful + */ + int (*reseed)(struct ccdrbg_state *prng, + size_t entropylen, const void *entropy, + size_t inlen, const void *in); + + /*! Read from the PRNG in a FIPS Testing compliant manor + @param prng The PRNG state to read from + @param out [out] Where to store the data + @param outlen Length of data desired (octets) + @param inlen Length of additional input + @param in Additional input bytes + @return 0 if successfull + */ + int (*generate)(struct ccdrbg_state *prng, + size_t outlen, void *out, + size_t inlen, const void *in); + + /*! Terminate a PRNG state + @param prng The PRNG state to terminate + */ + void (*done)(struct ccdrbg_state *prng); + + /** private parameters */ + const void *custom; +}; + + + +#endif // _CORECRYPTO_CCDRBG_IMPL_H_ diff --git a/libraries/corecrypto/include/corecrypto/ccec.h b/libraries/corecrypto/include/corecrypto/ccec.h new file mode 100644 index 0000000..54d056a --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccec.h @@ -0,0 +1,888 @@ +/* + * Copyright (c) 2010,2011,2012,2014,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCEC_H_ +#define _CORECRYPTO_CCEC_H_ +#include +#include +#include +#include +#include +#include + + +/* An ec_point. A ccec_projective_point_t is a point with x,y and z. + A ccec_affine_point_t only has x and y. */ + +struct ccec_projective_point { + cc_unit xyz[1]; +} CC_ALIGNED(8); +typedef struct ccec_projective_point ccec_projective_point; + +struct ccec_cp { + __CCZP_ELEMENTS_DEFINITIONS() +} CC_ALIGNED(CCN_UNIT_SIZE); + +#if CORECRYPTO_USE_TRANSPARENT_UNION + struct ccec_point_hdr { + cc_unit x; + }; + + typedef union { + struct ccec_point_hdr *hdr; + ccec_projective_point *_p; + } __attribute__((transparent_union)) ccec_projective_point_t; + + typedef union { + const struct ccec_point_hdr *hdr; + ccec_projective_point_t point; + ccec_projective_point *_p; + const ccec_projective_point *_cp; + const cc_unit *x; + } __attribute__((transparent_union)) ccec_const_projective_point_t; + + #define ccec_affine_point_t ccec_projective_point_t + #define ccec_affine_point ccec_projective_point + #define ccec_const_affine_point_t ccec_const_projective_point_t + + typedef union { + const struct ccec_cp *just_a_filler; + const struct cczp *zp; //security framework wants it this way + } __attribute__((transparent_union)) ccec_const_cp_t; +#else + + struct ccec_affine_point { + cc_unit xyz[1]; + } CC_ALIGNED(8); + typedef struct ccec_affine_point ccec_affine_point; + typedef ccec_projective_point* ccec_projective_point_t; + typedef ccec_affine_point* ccec_affine_point_t; + + typedef const struct ccec_affine_point* ccec_const_affine_point_t; + typedef const struct ccec_projective_point* ccec_const_projective_point_t; + + typedef const struct ccec_cp* ccec_const_cp_t; + +#endif + +/* Use ccec_full_ctx_decl to declare full ecc context */ +struct ccec_full_ctx { + ccec_const_cp_t cp; + uint8_t pad[16 - sizeof(ccec_const_cp_t *)]; + struct ccec_projective_point point[]; +} CC_ALIGNED(16) ; + +struct ccec_pub_ctx { + ccec_const_cp_t cp; + uint8_t pad[16 - sizeof(ccec_const_cp_t *)]; + struct ccec_projective_point point[]; +} CC_ALIGNED(16) ; + +#if CORECRYPTO_USE_TRANSPARENT_UNION +#define ccec_ctx_public ccec_pub_ctx //this is just for compatibility + typedef union { + struct ccec_pub_ctx* pub; + struct ccec_pub_ctx* _pub; + struct ccec_pub_ctx* body; + struct ccec_full_ctx *_full; + struct ccec_full_ctx *full; + struct ccec_full_ctx *fullt; + struct ccec_full_ctx *hdr; + } ccec_full_ctx_t __attribute__((transparent_union)); + #define ccec_full(x) ((x).full) + typedef struct ccec_full_ctx ccec_full_ctx; + + typedef ccec_full_ctx_t ccec_pub_ctx_t; + typedef struct ccec_pub_ctx ccec_pub_ctx; +#else + typedef struct ccec_full_ctx* ccec_full_ctx_t; + typedef struct ccec_pub_ctx* ccec_pub_ctx_t; + CC_INLINE + ccec_pub_ctx_t ccec_ctx_public(ccec_full_ctx_t fk) { + return (ccec_pub_ctx_t) fk; + } +#endif + + +/* Return the size of an ccec_full_ctx where each ccn is _size_ bytes. */ +#define ccec_full_ctx_size(_size_) (sizeof(struct ccec_full_ctx) + 4 * (_size_)) +#define ccec_pub_ctx_size(_size_) (sizeof(struct ccec_pub_ctx) + 3 * (_size_)) + +/* declare full and public context, when curve paramters cp are not known and will be assigned later*/ +#define ccec_full_ctx_decl(_size_, _name_) cc_ctx_decl( struct ccec_full_ctx, ccec_full_ctx_size(_size_), _name_) +#define ccec_full_ctx_clear(_size_, _name_) cc_clear(ccec_full_ctx_size(_size_), _name_) +#define ccec_pub_ctx_decl(_size_, _name_) cc_ctx_decl( struct ccec_pub_ctx, ccec_pub_ctx_size(_size_), _name_) +#define ccec_pub_ctx_clear(_size_, _name_) cc_clear(ccec_pub_ctx_size(_size_), _name_) + +/* declare full and public context, when curve paramters cp are known */ +#define ccec_full_ctx_decl_cp(_cp_, _name_) ccec_full_ctx_decl(ccec_ccn_size(_cp_), _name_) +#define ccec_full_ctx_clear_cp(_cp_, _name_) ccec_full_ctx_clear(ccec_ccn_size(_cp_), _name_) +#define ccec_pub_ctx_decl_cp(_cp_, _name_) ccec_pub_ctx_decl(ccec_ccn_size(_cp_), _name_) +#define ccec_pub_ctx_clear_cp(_cp_, _name_) ccec_pub_ctx_clear(ccec_ccn_size(_cp_), _name_) + +/* Declare storage for a projected or affine point respectively. */ +#define ccec_point_size_n(_cp_) (3 * ccec_cp_n(cp)) +#define ccec_point_sizeof(_cp_) ccn_sizeof_n(ccec_point_size_n(cp)) +#define ccec_point_decl_cp(_cp_, _name_) cc_ctx_decl(struct ccec_projective_point, ccec_point_sizeof(_cp_), _name_) +#define ccec_point_clear_cp(_cp_, _name_) cc_clear(ccec_point_sizeof(_cp_), _name_) +#define ccec_affine_decl_cp(_cp_, _name_) cc_ctx_decl(struct ccec_affine_point, 2 * ccec_ccn_size(_cp_), _name_) +#define ccec_affine_clear_cp(_cp_, _name_) cc_clear(2 * ccec_ccn_size(_cp_), _name_) + +/* lvalue accessors to ccec_ctx fields. (only a ccec_full_ctx_t has K). */ +#if CORECRYPTO_USE_TRANSPARENT_UNION + #define ccec_ctx_cp(KEY) (((ccec_pub_ctx_t)(KEY)).hdr->cp) + CC_INLINE void ccec_ctx_init(ccec_const_cp_t cp, ccec_full_ctx_t key) {(key.full)->cp = cp;} + //CC_INLINE struct ccec_projective_point *ccec_ctx_point(ccec_full_ctx_t key){return key.full->point;} // The public key as a projected point on the curve + #define ccec_ctx_point(KEY) ((ccec_projective_point_t)(((ccec_full_ctx_t)KEY).full->point)) + #define ccec_ctx_n(KEY) (ccec_ctx_cp(KEY).zp->n) + #define ccec_ctx_prime(KEY) (ccec_ctx_cp(KEY).zp->ccn) + + CC_INLINE cc_size ccec_cp_n(ccec_const_cp_t cp) { return cp.zp->n; } + //CC_INLINE cczp_const_t ccec_cp_zp(ccec_const_cp_t cp){ return cp.zp; } + #define ccec_cp_zp(_cp_) ((_cp_).zp) + +#define ccec_ctx_x(KEY) (ccec_ctx_point(KEY)._p->xyz) // The x, y and z of the public key as a projected point on the curve. +#define ccec_ctx_y(KEY) (ccec_ctx_point(KEY)._p->xyz+ 1 * ccec_ctx_n(KEY)) +#define ccec_ctx_z(KEY) (ccec_ctx_point(KEY)._p->xyz+ 2 * ccec_ctx_n(KEY)) + +#else + /* Callers must use this macro to initialze a ccec_full_ctx or + ccec_pub_ctx before using most of the macros in this file. */ + #define ccec_ctx_cp(KEY) ((KEY)->cp) + #define ccec_ctx_init(_cp_, _key_) ((_key_)->cp = (_cp_)) + #define ccec_ctx_point(KEY) ((KEY)->point) // The public key as a projected point on the curve. + #define ccec_ctx_n(KEY) (ccec_ctx_cp(KEY)->n) // Return count (n) of a ccn for cp. + #define ccec_ctx_prime(KEY) (ccec_ctx_cp(KEY)->ccn) + + CC_CONST CC_INLINE cc_size ccec_cp_n(ccec_const_cp_t cp) { return cp->n; } + CC_CONST CC_INLINE cczp_const_t ccec_cp_zp(ccec_const_cp_t cp){ return (cczp_const_t)cp; } + + #define ccec_ctx_x(KEY) (ccec_ctx_point(KEY)->xyz) // The x, y and z of the public key as a projected point on the curve. + #define ccec_ctx_y(KEY) (ccec_ctx_point(KEY)->xyz+ 1 * ccec_ctx_n(KEY)) + #define ccec_ctx_z(KEY) (ccec_ctx_point(KEY)->xyz+ 2 * ccec_ctx_n(KEY)) +#endif + + +/***************************************************************************/ +/* EC Sizes */ +/***************************************************************************/ +/* Return the length of the prime for cp in bits. */ +#if CORECRYPTO_USE_TRANSPARENT_UNION + #define ccec_cp_prime_bitlen(CP) (ccn_bitlen((CP).zp->n, (CP).zp->ccn)) +#else + #define ccec_cp_prime_bitlen(CP) (ccn_bitlen((CP)->n, (CP)->ccn)) +#endif +/* Return the sizeof the prime for cp. */ +#define ccec_cp_prime_size(CP) ((ccec_cp_prime_bitlen(CP)+7)/8) +/* Return the ec keysize in bits. */ +#define ccec_ctx_bitlen(KEY) (ccec_cp_prime_bitlen(ccec_ctx_cp(KEY))) +/* Return the ec keysize in bytes. */ +#define ccec_ctx_size(KEY) (ccec_cp_prime_size(ccec_ctx_cp(KEY))) + + + + +/* The k of a full key which makes up the private key. + It is only accessible through full key + */ +CC_INLINE +cc_unit *ccec_ctx_k( ccec_full_ctx_t key) { + return (ccec_ctx_x(key)+ 3 * ccec_ctx_n(key)); +} + +CC_INLINE +ccec_pub_ctx_t ccec_ctx_pub( ccec_full_ctx_t key) { + return (ccec_pub_ctx_t) key; +} + + +/* Return sizeof a ccn for cp. */ +CC_CONST CC_INLINE +size_t ccec_ccn_size(ccec_const_cp_t cp) { + return ccn_sizeof_n(ccec_cp_n(cp)); +} + +/***************************************************************************/ +/* EC Curve Parameters */ +/***************************************************************************/ + +CC_CONST ccec_const_cp_t ccec_cp_192(void); +CC_CONST ccec_const_cp_t ccec_cp_224(void); +CC_CONST ccec_const_cp_t ccec_cp_256(void); +CC_CONST ccec_const_cp_t ccec_cp_384(void); +CC_CONST ccec_const_cp_t ccec_cp_521(void); + +/***************************************************************************/ +/* EC Wrap Params */ +/***************************************************************************/ + +struct ccec_rfc6637_curve; +struct ccec_rfc6637_wrap; +struct ccec_rfc6637_unwrap; + +extern struct ccec_rfc6637_wrap ccec_rfc6637_wrap_sha256_kek_aes128; +extern struct ccec_rfc6637_wrap ccec_rfc6637_wrap_sha512_kek_aes256; +extern struct ccec_rfc6637_unwrap ccec_rfc6637_unwrap_sha256_kek_aes128; +extern struct ccec_rfc6637_unwrap ccec_rfc6637_unwrap_sha512_kek_aes256; +extern struct ccec_rfc6637_curve ccec_rfc6637_dh_curve_p256; +extern struct ccec_rfc6637_curve ccec_rfc6637_dh_curve_p521; + +/***************************************************************************/ +/* EC Key Generation */ +/***************************************************************************/ + +/*! + @function ccec_generate_key + @abstract Default - Currently invokes the FIPS version + The behavior this function is not deterministic, + the number of random bytes it consumes may vary + @param cp Curve Parameters + @param rng Random for the key generation as well as consistency signature + @param key Full key containing the newly generated key pair + @returns 0 if no error, an error code otherwise. + */ + +CC_NONNULL_TU((1,3)) CC_NONNULL2 +int ccec_generate_key(ccec_const_cp_t cp, struct ccrng_state *rng, + ccec_full_ctx_t key); + +/*! + @function ccec_generate_key_legacy + @abstract NOT recommended: For legacy purposes in order to re-generate + deterministic keys previously generated. + 2 * ccn_sizeof(ccec_cp_order_bitlen(cp)) of random bytes needed + @param cp Curve Parameters + @param rng Random for the key generation as well as consistency signature + @param key Full key containing the newly generated key pair + @returns 0 if no error, an error code otherwise. + */ + +CC_NONNULL_TU((1,3)) CC_NONNULL2 +int ccec_generate_key_legacy(ccec_const_cp_t cp, struct ccrng_state *rng, + ccec_full_ctx_t key); + +/*! + @function ccec_generate_key_fips + @abstract Guarantees FIPS compliant key pair. RECOMMENDED + Use a non deterministic amount of random bytes + @param cp Curve Parameters + @param rng Random for the key generation as well as consistency signature + @param key Full key containing the newly generated key pair + @returns 0 if no error, an error code otherwise. + */ + +CC_NONNULL_TU((1,3)) CC_NONNULL2 +int ccec_generate_key_fips(ccec_const_cp_t cp, struct ccrng_state *rng, + ccec_full_ctx_t key); + +/*! + @function ccec_compact_generate_key + @abstract Generate a compact key pair according to + https://tools.ietf.org/html/draft-jivsov-ecc-compact-05 and follows FIPS guideline + @param cp Curve Parameters + @param rng Random for the key generation as well as consistency signature + @param key Full key containing the newly generated key pair + @returns 0 if no error, an error code otherwise. + */ + +/* Based on FIPS compliant version. Output a compact key */ +/* Use a non deterministic amount of random bytes */ +CC_NONNULL_TU((1,3)) CC_NONNULL2 +int ccec_compact_generate_key(ccec_const_cp_t cp, struct ccrng_state *rng, + ccec_full_ctx_t key); + +/*! + @function ccec_generate_key_deterministic + @abstract Generate a key pair from the provided entropy buffer. + requires cryptographic DRBG/KDF prior to calling + @param cp Curve Parameters + @param entropy_len Length in byte of the entropy buffer + @param entropy Pointer to the entropy buffer of size entropy_len + @param rng Real random for the signature and internal countermeasures + @param flag Bitmask: options as explained below + @param key Full key containing the newly generated key pair + @returns 0 if no error, an error code otherwise. + */ + +#define CCEC_GENKEY_DETERMINISTIC_FIPS (1<<0) +/* FIPS consumes all of the entropy and requires a minimum of ceiling(qbitlen+64 / 8) bytes of entropy. + It computes the secret key in [1,q-1] as (("entropy" mod (q-1)) + 1). "Entropy" is processed as a big endian number. + Provided the entropy is FIPS compliant and no other option is set this method is FIPS compliant. + If COMPACT option is used, the key is not strictly FIPS compliant */ + +#define CCEC_GENKEY_DETERMINISTIC_PKA (1<<1) +/* RAW consumes all of the entropy and requires a minimum of ceiling(qbitlen+64 / 8) bytes of entropy. + It computes the secret key in [2,q-1] as (("entropy" mod (q-2)) + 2). "Entropy" is processed as a big endian number. + Provided the entropy is FIPS compliant, this method is FIPS compliant. */ + +#define CCEC_GENKEY_DETERMINISTIC_LEGACY (1<<2) +/* LEGACY requires a minimum of ccn_sizeof_n(n) byte of entropy, but ignores bytes after ccn_sizeof_n(n) */ +/* Use them in the same sequence as the output of ccrng_generate that is used in ccec_generate_legacy */ + +#define CCEC_GENKEY_DETERMINISTIC_COMPACT ((1<<3) | CCEC_GENKEY_DETERMINISTIC_FIPS) +/* generate key that is compatible with compact export format. Compatible with all of the options above */ + +#define CCEC_GENKEY_DETERMINISTIC_SECBKP ((1<<4) | CCEC_GENKEY_DETERMINISTIC_COMPACT) +/* Compatibility flag for Secure Backup generated keys */ + +CC_NONNULL_TU((1,6)) CC_NONNULL((3,4)) +int ccec_generate_key_deterministic(ccec_const_cp_t cp, + size_t entropy_len, const uint8_t *entropy, + struct ccrng_state *rng, // For masking and signature + uint32_t flags, + ccec_full_ctx_t key); // Revisioning of the DRBG + + +/* Implementation per FIPS186-4 */ +#define CCEC_GENERATE_KEY_DEFAULT_ERR -1 +#define CCEC_GENERATE_KEY_TOO_MANY_TRIES -10 +#define CCEC_GENERATE_KEY_MULT_FAIL -11 +#define CCEC_GENERATE_KEY_AFF_FAIL -12 +#define CCEC_GENERATE_KEY_CONSISTENCY -13 +#define CCEC_GENERATE_NOT_ON_CURVE -14 +#define CCEC_GENERATE_NOT_ENOUGH_ENTROPY -15 +#define CCEC_GENERATE_NOT_SUPPORTED -16 +#define CCEC_GENERATE_INVALID_INPUT -17 + +/***************************************************************************/ +/* EC SIGN/VERIFY (ECDSA) */ +/***************************************************************************/ + +/* Return the maximum buffer size needed to hold a signature for key. */ +CC_INLINE CC_PURE CC_NONNULL_TU((1)) +size_t ccec_sign_max_size(ccec_const_cp_t cp) { + /* tag + 2 byte len + 2 * (tag + 1 byte len + optional leading zero + ccec_cp_prime_size) */ + return 3 + 2 * (3 + ccec_cp_prime_size(cp)); +} + +/* + Signature in DER format +*/ +CC_NONNULL_TU((1)) CC_NONNULL((3, 4, 5, 6)) +int ccec_sign(ccec_full_ctx_t key, size_t digest_len, const uint8_t *digest, + size_t *sig_len, uint8_t *sig, struct ccrng_state *rng); +CC_NONNULL_TU((1)) CC_NONNULL((3, 5, 6)) +int ccec_verify(ccec_pub_ctx_t key, size_t digest_len, const uint8_t *digest, + size_t sig_len, const uint8_t *sig, bool *valid); + + +/* + Raw signature, big endian, padded to the key size. + */ +CC_NONNULL_TU((1)) +size_t +ccec_signature_r_s_size(ccec_pub_ctx_t key); + +CC_NONNULL_TU((1)) CC_NONNULL((3, 4, 5, 6)) +int ccec_sign_composite(ccec_full_ctx_t key, size_t digest_len, const uint8_t *digest, + uint8_t *sig_r, uint8_t *sig_s, struct ccrng_state *rng); + +CC_NONNULL_TU((1)) CC_NONNULL((3, 4, 5, 6)) +int ccec_verify_composite(ccec_pub_ctx_t key, size_t digest_len, const uint8_t *digest, + uint8_t *sig_r, uint8_t *sig_s, bool *valid); + +/***************************************************************************/ +/* EC Diffie-Hellman */ +/***************************************************************************/ + +/* + Deprecated. Do not use. + Migrate existing calls to ccecdh_compute_shared_secret + */ + +/*! + @function ccec_compute_key + @abstract DEPRECATED. Use ccecdh_compute_shared_secret. + */ + +CC_NONNULL_TU((1,2)) CC_NONNULL((3, 4)) +int ccec_compute_key(ccec_full_ctx_t private_key, ccec_pub_ctx_t public_key, + size_t *computed_key_len, uint8_t *computed_key); + +/*! + @function ccecdh_compute_shared_secret + @abstract Elliptic Curve Diffie-Hellman + from ANSI X9.63 and NIST SP800-56A, section 5.7.1.2 + + @param private_key Input: EC private key + @param public_key Input: EC public key + @param computed_shared_secret_len Input: Size of allocation for computed_shared_secret. + Output: Effective size of data in computed_shared_secret + @param computed_shared_secret Output: DH shared secret + @param masking_rng Input: Handle on RNG to be used for the randomization of the computation + + @result 0 iff successful + + @discussion The shared secret MUST be transformed with a KDF function or at + least Hash (SHA-256 or above) before being used. + It shall not be used directly as a key. + */ + +CC_NONNULL_TU((1,2)) CC_NONNULL((3, 4)) +int ccecdh_compute_shared_secret(ccec_full_ctx_t private_key, + ccec_pub_ctx_t public_key, + size_t *computed_shared_secret_len, uint8_t *computed_shared_secret, + struct ccrng_state *masking_rng); + +/***************************************************************************/ +/* EC WRAP/UNWRAP */ +/***************************************************************************/ + +/* + * Use rfc6637 style PGP wrapping for using EC keys + */ + +CC_NONNULL_TU((1)) +size_t ccec_rfc6637_wrap_key_size(ccec_pub_ctx_t public_key, + unsigned long flags, + size_t key_len); + +/* + * When CCEC_RFC6637_COMPACT_KEYS flag is used, the wrapping is NOT + * compatible with RFC6637 so make sure the peer supports this mode + * before using it. It currently saves half of the public key size + * which for P256 is 32 bytes which end up being about 1/4 of the + * wrapping size. + * Macros are bit masks + */ +#define CCEC_RFC6637_COMPACT_KEYS 1 +#define CCEC_RFC6637_DEBUG_KEYS 2 +#define CCEC_EXPORT_COMPACT_DIVERSIFIED_KEYS 4 + +/*! + @function ccec_rfc6637_wrap_key + @abstract Key wraping based on rfc6637 + + @param public_key Input: EC public key + @param wrapped_key Output: Buffer for the wrapped key of length ccec_rfc6637_wrap_key_size + @param flags Input: Option flags + @param algid Input: Algorithm id + @param keylen Input: Length of the key to wrap (<=37 bytes) + @param key Input: Pointer to the key to wrap + @param curve Input: Definiton of the curve + @param curve Input: Definiton of the wrap + @param fingerprint Input: Point to a 20byte buffer used as fingerprint during wrapping. + @param rng Input: Handle on a RNG for ephemeral key generation and computation randomization + + @result 0 iff successful + + @discussion + This implementation hides the length of the key to wrap. + It only supports wrapping keys up to 37bytes. + */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 6, 7, 8, 9, 10)) +int +ccec_rfc6637_wrap_key(ccec_pub_ctx_t public_key, + void *wrapped_key, + unsigned long flags, + uint8_t algid, + size_t key_len, + const void *key, + const struct ccec_rfc6637_curve *curve, + const struct ccec_rfc6637_wrap *wrap, + const uint8_t *fingerprint, + struct ccrng_state *rng); + +/*! + @function ccec_diversify_pub + @abstract diversified public key with scalar r. + r = entropy mod (q-1)) + 1, where entropy is interpreted as big endian. + + entropy_len must be greater or equal to ccec_diversify_min_entropy_len + the entropy must be a well uniformly distributed number, such as random byte, + output of a DRBG or output of a KDF. + + @param cp Input: Curve parameter + @param pub_key Input: Original public key P. + @param entropy_len Input: byte length of the entropy + @param entropy Input: point to the entropy + @param masking_rng Input: Random for randomizing the computation + @param diversified_generator Output: New generator (r.G). + @param diversified_pub_key Output: New public key (r.P). + + @result 0 iff unwrapping was successful + + @discussion + Diversified keys is the process of multiplying the generator and the public key + by a same random number. + This does not preserve properties of the key with respect to compact format + However, this method is valid with compact points when using ECDH and when only X coordinate is used + Therefore this is valid with ccec_rfc6637 wrap / unwrap. + + Compact here refers to https://datatracker.ietf.org/doc/draft-jivsov-ecc-compact/ + */ +int ccec_diversify_pub(ccec_const_cp_t cp, + ccec_pub_ctx_t pub_key, + size_t entropy_len, const uint8_t *entropy, + struct ccrng_state *masking_rng, + ccec_pub_ctx_t diversified_generator, + ccec_pub_ctx_t diversified_pub_key + ); + +/*! + @function ccec_diversify_min_entropy_len + @abstract Minimum length of entropy to be passed to ccec_diversify_pub + + @param cp Input: Curve parameter + + @result Minimal entropy length in bytes to be used in ccec_diversify_pub + + */ +size_t ccec_diversify_min_entropy_len(ccec_const_cp_t cp); + +/*! + @function ccec_rfc6637_wrap_key_diversified + @abstract Key wraping based on rfc6637 + + @param generator Input: Generator, represented as a public key + @param public_key Input: EC public key + @param wrapped_key Output: Buffer for the wrapped key of length ccec_rfc6637_wrap_key_size + @param flags Input: Option flags + @param algid Input: Algorithm id + @param keylen Input: Length of the key to wrap (<=38 bytes) + @param key Input: Pointer to the key to wrap + @param curve Input: Definiton of the curve + @param wrap Input: Definiton of the wrap + @param fingerprint Input: Point to a 20byte buffer used as fingerprint during wrapping. + @param rng Input: Handle on a RNG for ephemeral key generation and computation randomization + + @result 0 iff successful + + @discussion + Diversified keys is the process of multiplying the generator and the public key + by a same number. + This implementation hides the length of the key to wrap. + It only supports wrapping keys up to 37bytes. + */ + +CC_NONNULL_TU((1,2)) CC_NONNULL((3, 7, 8, 9, 10, 11)) +int +ccec_rfc6637_wrap_key_diversified(ccec_pub_ctx_t generator, + ccec_pub_ctx_t public_key, + void *wrapped_key, + unsigned long flags, + uint8_t symm_alg_id, + size_t key_len, + const void *key, + const struct ccec_rfc6637_curve *curve, + const struct ccec_rfc6637_wrap *wrap, + const uint8_t *fingerprint, /* 20 bytes */ + struct ccrng_state *rng); + +/*! + @function ccec_rfc6637_unwrap_key + @abstract Key unwraping based on rfc6637 + + @param private_key Input: Private key to unwrap the key + @param key_len Input/Output: Size of the allocated buffer / size of the key + @param key Output: Buffer for the unwrapped key + @param flags Input: Option flags + @param symm_key_alg Output: Algorithm id + @param curve Input: Definiton of the curve + @param wrap Input: Definiton of the unwrap + @param fingerprint Input: Point to a 20byte buffer used as fingerprint during wrapping. + @param wrapped_key_len Input: Size in byte of the wrapped key + @param wrapped_key Input: Pointer to the wrapped key + + @result 0 iff successful + + @discussion + Diversified keys is the process of multiplying the generator and the public key + by a same number. + */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 5, 6, 7, 8, 10)) +int +ccec_rfc6637_unwrap_key(ccec_full_ctx_t private_key, + size_t *key_len, + void *key, + unsigned long flags, + uint8_t *symm_key_alg, + const struct ccec_rfc6637_curve *curve, + const struct ccec_rfc6637_unwrap *unwrap, + const uint8_t *fingerprint, + size_t wrapped_key_len, + const void *wrapped_key); + +/***************************************************************************/ +/* EC Import/Export */ +/***************************************************************************/ + +CC_NONNULL_TU((1,4)) CC_NONNULL((3)) +int ccec_import_pub(ccec_const_cp_t cp, size_t in_len, const uint8_t *in, ccec_pub_ctx_t key); + +/* Return the sizeof a buffer needed to exported public key to. */ +CC_INLINE CC_CONST CC_NONNULL_TU((1)) +size_t ccec_export_pub_size(ccec_pub_ctx_t key) { + return 1 + 2 * ccec_cp_prime_size(ccec_ctx_cp(key)); +} + +/* Export key to out. Out must be ccec_export_pub_size(key) bytes long. */ +CC_NONNULL_TU((1)) CC_NONNULL2 +void ccec_export_pub(ccec_pub_ctx_t key, void *out); + +/* ---------------------------------*/ +/* x963 */ +/* ---------------------------------*/ + +/* Export 9.63 */ +CC_INLINE CC_CONST CC_NONNULL_TU((2)) +size_t ccec_x963_export_size(const int fullkey, ccec_pub_ctx_t key){ + return (((ccec_ctx_bitlen(key)+7)/8) * ((fullkey == 1) + 2)) + 1; +} + +CC_NONNULL_TU((3)) CC_NONNULL2 +void ccec_x963_export(const int fullkey, void *out, ccec_full_ctx_t key); + +/* Import 9.63 */ +size_t ccec_x963_import_pub_size(size_t in_len); + +CC_NONNULL_TU((1,4)) CC_NONNULL3 +/* Import an EC public key with x9.63 format */ +int ccec_x963_import_pub(ccec_const_cp_t cp, size_t in_len, const uint8_t *in, ccec_pub_ctx_t key); + +size_t ccec_x963_import_priv_size(size_t in_len); + +CC_NONNULL_TU((1,4)) CC_NONNULL3 +/* Import the full key (private and public part of the key) with x9.63 format */ +int ccec_x963_import_priv(ccec_const_cp_t cp, size_t in_len, const uint8_t *in, ccec_full_ctx_t key); +/* ---------------------------------*/ +/* Compact */ +/* ---------------------------------*/ + +/* Compact here refers to https://datatracker.ietf.org/doc/draft-jivsov-ecc-compact/ */ + +/* Export Compact + Output as the same bitlen than p */ +CC_NONNULL_TU((3)) CC_NONNULL2 +void ccec_compact_export(const int fullkey, void *out, ccec_full_ctx_t key); + +CC_INLINE CC_CONST CC_NONNULL_TU((2)) +size_t ccec_compact_export_size(const int fullkey, ccec_pub_ctx_t key){ + return (((ccec_ctx_bitlen(key)+7)/8) * ((fullkey == 1) + 1)); +} + +/* Import Compact + The public key is the x coordinate, in big endian, of length the byte length of p + No preambule byte */ + +size_t ccec_compact_import_pub_size(size_t in_len); + +CC_NONNULL_TU((1,4)) CC_NONNULL3 +int ccec_compact_import_pub(ccec_const_cp_t cp, size_t in_len, const uint8_t *in, ccec_pub_ctx_t key); + +size_t ccec_compact_import_priv_size(size_t in_len); + +CC_NONNULL_TU((1,4)) CC_NONNULL3 +int ccec_compact_import_priv(ccec_const_cp_t cp, size_t in_len, const uint8_t *in, ccec_full_ctx_t key); + +/* ---------------------------------*/ +/* DER (RFC 5915) */ +/* ---------------------------------*/ + +/* Export EC priv to DER (RFC 5915) */ +CC_NONNULL_TU((1)) +size_t +ccec_der_export_priv_size(ccec_full_ctx_t key, ccoid_t key_oid, int includePublic); + +CC_NONNULL_TU((1)) CC_NONNULL5 +int +ccec_der_export_priv(ccec_full_ctx_t key, ccoid_t key_oid, int includePublic, size_t out_len, void *out); + +/* import EC priv from DER (RFC 5915) */ + +CC_NONNULL((2,4)) +int ccec_der_import_priv_keytype(size_t len, const uint8_t * data, ccoid_t *oid, size_t *n); + +CC_NONNULL_TU((1,4)) CC_NONNULL((3)) +int ccec_der_import_priv(ccec_const_cp_t cp, size_t length, const uint8_t *data, ccec_full_ctx_t full_key); + +/* ---------------------------------*/ +/* DER (custom) for diversified keys*/ +/* ---------------------------------*/ + +/*! + @function ccec_der_export_diversified_pub_size + @abstract DER export of a diversified public key + + @param diversified_generator Input: Generator, represented as a public key + @param diversified_key Input: EC public key + @param flags Input: Option flags (compact keys) + + @result sizeof a buffer needed to exported public key if successful, 0 otherwise. + + @discussion + Diversified keys is the process of multiplying the generator and the public key + by a same number. + + Compact here refers to https://datatracker.ietf.org/doc/draft-jivsov-ecc-compact/ + + */ +size_t ccec_der_export_diversified_pub_size( + ccec_pub_ctx_t diversified_generator, + ccec_pub_ctx_t diversified_key, + unsigned long flags); +/*! + @function ccec_der_export_diversified_pub + @abstract DER export of a diversified public key + + @param diversified_generator Input: Generator, represented as a public key + @param diversified_key Input: EC public key + @param flags Input: Option flags (compact keys) + @param der_len Input: Size of the destination buffer + @param der Output: Pointer to the destination buffer, must be ccec_export_pub_size(key) bytes long. + + @result NULL is error, pointer in the der buffer otherwise. + + @discussion + Diversified keys is the process of multiplying the generator and the public key + by a same number. + + Compact here refers to https://datatracker.ietf.org/doc/draft-jivsov-ecc-compact/ + */ +uint8_t *ccec_der_export_diversified_pub( + ccec_pub_ctx_t diversified_generator, + ccec_pub_ctx_t diversified_key, + unsigned long flags, + size_t der_len, uint8_t *der); + +/*! + @function ccec_der_export_diversified_pub + @abstract DER export of a diversified public key + + @param diversified_generator Output: Diversified generator, represented as a public key + @param diversified_key Output: Diversified EC public key + @param outflags Output: Output flags telling how the data was parsed. + @param der_len Input: Size of the destination buffer + @param der Output: Pointer to the destination buffer, must be ccec_export_pub_size(key) bytes long. + + @result 0 iff unwrapping was successful + + @discussion + Diversified keys is the process of multiplying the generator and the public key + by a same number. Currently the only valid output flag is CCEC_EXPORT_COMPACT_DIVERSIFIED_KEYS. + The generator and the public point a required to be encoded in the same format, either standard + or compact format. Mixing form is not allowed and that output is never generated + by ccec_der_export_diversified_pub. + + Compact here refers to https://datatracker.ietf.org/doc/draft-jivsov-ecc-compact/ + */ +int ccec_der_import_diversified_pub( + ccec_const_cp_t cp, + size_t length, const uint8_t *data, + int *outflags, + ccec_pub_ctx_t diversified_generator, + ccec_pub_ctx_t diversified_key); + +#define CCEC_IMPORT_DIVERSIFIED_KEYS_SUPPORT_FLAGS 1 + +/***************************************************************************/ +/* EC Construction and Validation */ +/***************************************************************************/ + +CC_NONNULL_TU((1)) +int ccec_get_pubkey_components(ccec_pub_ctx_t key, size_t *nbits, + uint8_t *x, size_t *xsize, + uint8_t *y, size_t *ysize); + +CC_NONNULL_TU((1)) +int ccec_get_fullkey_components(ccec_full_ctx_t key, size_t *nbits, + uint8_t *x, size_t *xsize, + uint8_t *y, size_t *ysize, + uint8_t *d, size_t *dsize); + +CC_NONNULL_TU((6)) +int ccec_make_pub(size_t nbits, + size_t xlength, const uint8_t *x, + size_t ylength, const uint8_t *y, + ccec_pub_ctx_t key); + +CC_NONNULL_TU((8)) +int ccec_make_priv(size_t nbits, + size_t xlength, const uint8_t *x, + size_t ylength, const uint8_t *y, + size_t klength, const uint8_t *k, + ccec_full_ctx_t key); + +/*! + @function ccec_validate_pub + @abstract Perform validation of the public key + @param key elliptic curve public key + @result true if the key is valid + @discussion + Perform the public key validation from FIPS: x,y are within range and + the point is on the curve. Point at infinity is considered as invalid here. + */ +CC_NONNULL_TU((1)) +bool ccec_validate_pub(ccec_pub_ctx_t key); + +int ccec_keysize_is_supported(size_t keysize); + +ccec_const_cp_t ccec_get_cp(size_t keysize); + +CC_NONNULL_TU((1)) CC_NONNULL2 +bool ccec_pairwise_consistency_check(const ccec_full_ctx_t full_key, struct ccrng_state *rng); + +ccec_const_cp_t ccec_curve_for_length_lookup(size_t keylen, ...); + +#endif /* _CORECRYPTO_CCEC_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccec25519.h b/libraries/corecrypto/include/corecrypto/ccec25519.h new file mode 100644 index 0000000..7b71c8f --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccec25519.h @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2014,2015,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCEC25519_H_ +#define _CORECRYPTO_CCEC25519_H_ + +#include +#include +#include + +typedef uint8_t ccec25519key[32]; +typedef ccec25519key ccec25519secretkey; +typedef ccec25519key ccec25519pubkey; +typedef ccec25519key ccec25519base; + +typedef uint8_t ccec25519signature[64]; + +/*! + @function cccurve25519 + @abstract Perform Curve25519 Diffie-Hellman. + http://cr.yp.to/ecdh.html + + @param out Output shared secret or public key. + @param sk Input secret key. + @param base Input basepoint (for computing a shared secret) + or NULL (for computing a public key). + */ + +void cccurve25519(ccec25519key out, + const ccec25519secretkey sk, + const ccec25519base base); + +/*! + @function cccurve25519_make_priv + @abstract Generates a random, montgomery curve 25519 private key. + + @param rng An initialized random number generator + @param sk Receives 32-byte secret key. + */ + +CC_INLINE void cccurve25519_make_priv(struct ccrng_state *rng, + ccec25519secretkey sk) { + ccrng_generate(rng,32,sk); + sk[0] &= 248; + sk[31] &= 127; + sk[31] |= 64; +} + +/*! + @function cccurve25519_make_pub + @abstract Creates a montgomery curve 25519 public key from a private key. + + @param pk Receives 32-byte public key. + @param sk Receives 32-byte secret key. + */ + +CC_INLINE void cccurve25519_make_pub(ccec25519pubkey pk, + const ccec25519secretkey sk) { + cccurve25519(pk, sk, NULL); +} + +/*! + @function cccurve25519_make_key_pair + @abstract Generates a random, montgomery curve 25519 key pair. + + @param rng An initialized random number generator + @param pk Receives 32-byte public key. + @param sk Receives 32-byte secret key. + */ + +CC_INLINE void cccurve25519_make_key_pair(struct ccrng_state *rng, + ccec25519pubkey pk, + ccec25519secretkey sk) { + cccurve25519_make_priv(rng, sk); + cccurve25519_make_pub(pk, sk); +} + + +/*! + @function cced25519_make_key_pair + @abstract Generates a random, Ed25519 key pair. + + @param di A valid descriptor for a 512 bit hash function for the platform + @param rng An initialized random number generator + @param pk Receives 32-byte public key. + @param sk Receives 32-byte secret key. + */ +void cced25519_make_key_pair(const struct ccdigest_info *di, + struct ccrng_state *rng, + ccec25519pubkey pk, + ccec25519secretkey sk); + +/*! + @function cced25519_sign + @abstract Signs a message using a secret key. + + @param di A valid descriptor for a 512 bit hash function for the platform + @param sig Receives the 64-byte signature. + @param len Number of bytes to sign. + @param msg Data to sign. + @param pk 32-byte public key as generated by cced25519_make_key_pair(). + @param sk 32-byte secret key as generated by cced25519_make_key_pair(). +*/ +void cced25519_sign(const struct ccdigest_info *di, + ccec25519signature sig, + size_t len, const void *msg, + const ccec25519pubkey pk, + const ccec25519secretkey sk); + +/*! + @function cced25519_verify + @abstract Verifies a signed message using a public key. + + @param di A valid descriptor for a 512 bit hash function for the platform + @param len Number of bytes of data to verify. + @param msg Data to verify. + @param sig 64-byte signature to verify data against. + @param pk 32-byte public key. Should have been generated by the peer using + cced25519_make_key_pair(). + + @result 0=Signed message is valid. Non-zero=Bad message. +*/ +int cced25519_verify(const struct ccdigest_info *di, + size_t len, const void *msg, + const ccec25519signature sig, + const ccec25519pubkey pk); + +#endif /* _CORECRYPTO_CCEC25519_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccec25519_priv.h b/libraries/corecrypto/include/corecrypto/ccec25519_priv.h new file mode 100644 index 0000000..72e3abd --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccec25519_priv.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCEC25519_PRIV_H_ +#define _CORECRYPTO_CCEC25519_PRIV_H_ + +/*! + @function cced25519_make_pub + @abstract Creates a montgomery curve 25519 public key from a private key. + + @param di A valid descriptor for a 512 bit hash function for the platform + @param pk Output 32-byte public key. + @param sk Input 32-byte secret key. + + @discussion Not safe for general use. For internal use only (eg. FIPS CAVS): + - Public key must be stored along side the private key, private key should not + be stored alone. + - It may be unsafe to use a same private key with different digests + */ + +int cced25519_make_pub(const struct ccdigest_info *di, + ccec25519pubkey pk, + const ccec25519secretkey sk); + +#endif /* _CORECRYPTO_CCEC25519_PRIV_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccec_priv.h b/libraries/corecrypto/include/corecrypto/ccec_priv.h new file mode 100644 index 0000000..78ca717 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccec_priv.h @@ -0,0 +1,504 @@ +/* + * Copyright (c) 2010,2011,2013,2014,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCEC_PRIV_H_ +#define _CORECRYPTO_CCEC_PRIV_H_ + +#include +#include +#include +#include + +/* Configuration */ +#define CCEC_MASKING 1 + +/* Define this to 1 to use ccec_twin_mult for ccec_verify. This gives you a + big speedup for about 1500-2000 bytes of extra code. */ +#define CCEC_USE_TWIN_MULT 1 + +/* Define the condition for Montgomery arithmetic support */ +#define CCEC_ZP_IS_MONTGOMERY(cp) (cczp_is_montgomery(ccec_cp_zp(cp))) + +#define CCEC_DEBUG 0 + +/* Low level ec functions and types. */ + +/* Macros for accessing X and Y in an ccec_affine_point and X Y and Z in + an ccec_projective_point. */ + +#if CORECRYPTO_USE_TRANSPARENT_UNION + #define ccec_const_point_x(EP, _cp_) (&((ccec_const_affine_point_t)(EP)).hdr->x) + #define ccec_const_point_y(EP, _cp_) ((&((ccec_const_affine_point_t)(EP)).hdr->x) + ccec_cp_n(_cp_)) + #define ccec_const_point_z(EP, _cp_) ((&((ccec_const_projective_point_t)(EP)).hdr->x) + ccec_cp_n(_cp_) * 2) + + #define ccec_point_x(EP, _cp_) (&((ccec_affine_point_t)(EP)).hdr->x) + #define ccec_point_y(EP, _cp_) ((&((ccec_affine_point_t)(EP)).hdr->x) + ccec_cp_n(_cp_)) + #define ccec_point_z(EP, _cp_) ((&((ccec_projective_point_t)(EP)).hdr->x) + ccec_cp_n(_cp_) * 2) +#else + #define ccec_const_point_x(EP, _cp_) ((const cc_unit *)((EP)->xyz + ccec_cp_n(_cp_) * 0)) + #define ccec_const_point_y(EP, _cp_) ((const cc_unit *)((EP)->xyz + ccec_cp_n(_cp_) * 1)) + #define ccec_const_point_z(EP, _cp_) ((const cc_unit *)((EP)->xyz + ccec_cp_n(_cp_) * 2)) + + #define ccec_point_x(EP, _cp_) ((EP)->xyz + ccec_cp_n(_cp_) * 0) + #define ccec_point_y(EP, _cp_) ((EP)->xyz + ccec_cp_n(_cp_) * 1) + #define ccec_point_z(EP, _cp_) ((EP)->xyz + ccec_cp_n(_cp_) * 2) +#endif + +/* Macro to define a struct for a ccec_cp of _n_ units. This is + only to be used for static initializers of curve parameters. + Note that _n_ is evaluated multiple times. */ +#define ccec_cp_decl_n(_n_) struct { \ + struct cczp_hd hp; \ + cc_unit p[(_n_)]; \ + cc_unit pr[(_n_) + 1]; \ + cc_unit b[(_n_)]; \ + cc_unit gx[(_n_)]; \ + cc_unit gy[(_n_)]; \ + struct cczp_hd hq; \ + cc_unit q[(_n_)];\ + cc_unit qr[(_n_) + 1];\ +} + +/* Macro to define a struct for a ccec_cp of _bits_ bits. This is + only to be used for static initializers of curve parameters. */ +#define ccec_cp_decl(_bits_) ccec_cp_decl_n(ccn_nof(_bits_)) + +#if CORECRYPTO_USE_TRANSPARENT_UNION + #define ccec_cp_p(_cp_) ((_cp_).zp->ccn) + #define ccec_cp_b(_cp_) ((_cp_).zp->ccn + 1 + 2 * ccec_cp_n(_cp_)) + #define ccec_cp_g(_cp_) ((ccec_const_affine_point_t)(const ccec_affine_point *)((_cp_).zp->ccn + 1 + ccec_cp_n(_cp_) * 3)) + #define ccec_cp_zq(_cp_) ((cczp_const_t)((_cp_).zp->ccn + 1 + ccec_cp_n(_cp_) * 5)) + #define ccec_cp_options(_cp_) (*(ccec_cp_zq(_cp_).zp->ccn + 1 + 2 * ccec_cp_n(_cp_))) +#else + #define ccec_cp_p(_cp_) ((_cp_)->ccn) + #define ccec_cp_b(_cp_) ((_cp_)->ccn + 1 + 2 * ccec_cp_n(_cp_)) + #define ccec_cp_g(_cp_) ((const ccec_affine_point *)((_cp_)->ccn + 1 + ccec_cp_n(_cp_) * 3)) + #define ccec_cp_zq(_cp_) ((cczp_const_t)((_cp_)->ccn + 1 + ccec_cp_n(_cp_) * 5)) + #define ccec_cp_options(_cp_) (*(ccec_cp_zq(_cp_)->ccn + 1 + 2 * ccec_cp_n(_cp_))) +#endif + +/* Return the length of the order for cp in bits. */ +#define ccec_cp_order_bitlen(CP) (ccn_bitlen(cczp_n(ccec_cp_zq(cp)), cczp_prime(ccec_cp_zq(cp)))) +/* Return the length of the order for cp in bytes. */ +#define ccec_cp_order_size(cp) ((ccec_cp_order_bitlen(cp)+7)/8) + +/* accept an affine point S and set R equal to its projective representation. */ +int ccec_projectify(ccec_const_cp_t cp, ccec_projective_point_t r, ccec_const_affine_point_t s, + struct ccrng_state *masking_rng); + +/* accept a projective point S and set R equal to its affine representation. */ +int ccec_affinify(ccec_const_cp_t cp, ccec_affine_point_t r, ccec_const_projective_point_t s); + +/* accept a projective point S and output the x coordinate only of its affine representation. */ +int ccec_affinify_x_only(ccec_const_cp_t cp, cc_unit* sx, ccec_const_projective_point_t s, int secure) ; + +/* Take a x coordinate a recompute the point. No particular convention for y */ +int ccec_affine_point_from_x(ccec_const_cp_t cp, ccec_affine_point_t r, cc_unit *x, cc_unit *work2n); + +/* Return true if the point is on the curve. Requires curve with a=-3 */ +/* Z must be initialized. Set to 1 for points in affine representation */ +bool ccec_is_point(ccec_const_cp_t cp, ccec_const_projective_point_t s); + +/* accept an affine point S = (Sx,Sy) and return true if it is on the curve, (i.e., if SY2 = SX3 − 3SX.SZ^4 + bSZ^6 (mod p)), otherwise return false. */ +bool ccec_is_point_projective(ccec_const_cp_t cp, ccec_const_projective_point_t s); + +/* Validate the public key with respect to the curve information */ +int ccec_validate_pub_and_projectify(ccec_const_cp_t cp, + ccec_projective_point_t r, + ccec_const_affine_point_t public_point, + struct ccrng_state *masking_rng); + +/* Validate the private scalar with respect to the curve information */ +int ccec_validate_scalar(ccec_const_cp_t cp, const cc_unit* k); + +/* accept a projective point S and set R equal to the projective point 2S. Routine 2.2.6 performs no checks on its inputs. */ +#define CCEC_DOUBLE_WORKSPACE_SIZE(n)(6*(n)) +void ccec_double_ws(cc_ws_t ws, ccec_const_cp_t cp, ccec_projective_point_t r, ccec_const_projective_point_t s); + +/* accept two projective points S, T and set R equal to the projective point S + T. S and T must not be point at infinity. + Require r!=t. Ok with r==s */ +#define T_NORMALIZED 1 // expect T to be normalized (Z=1) +#define T_NEGATIVE 2 // use -T (point substration) +#define CCEC_ADD_SUB_WORKSPACE_SIZE(n) (7*(n)) +void ccec_add_ws(cc_ws_t ws, ccec_const_cp_t cp, + ccec_projective_point_t r, + ccec_const_projective_point_t s, + ccec_const_projective_point_t t, + uint32_t t_flags); + +/* accept two projective points S, T and set R equal to the projective point S + T . Routine 2.2.8 checks whether one of S or T is the point at infinity or whether S == T, and if so, takes the appropriate action. + + Require r!=t. Ok with r==s */ +void ccec_full_add_ws(cc_ws_t ws, ccec_const_cp_t cp, + ccec_projective_point_t r, + ccec_const_projective_point_t s, + ccec_const_projective_point_t t); + +/* accept two projective points S, T and set R equal to the projective point S + T . Routine 2.2.8 checks whether one of S or T is the point at infinity or whether S == T, and if so, takes the appropriate action. + T is required to be the neutral element (1 or R if Montgomery) */ +void ccec_full_add_normalized_ws(cc_ws_t ws, ccec_const_cp_t cp, + ccec_projective_point_t r, + ccec_const_projective_point_t s, + ccec_const_projective_point_t t); + +/* accept two projective points S, T and set R equal to the projective point S − T . Routine 2.2.9 checks whether one of S or T is the point at infinity or whether S == T, and if so, takes the appropriate action. */ +void ccec_full_sub_ws(cc_ws_t ws, ccec_const_cp_t cp, + ccec_projective_point_t r, + ccec_const_projective_point_t s, + ccec_const_projective_point_t t); + +/* accept two projective points S, T and set R equal to the projective point S − T . Routine 2.2.9 checks whether one of S or T is the point at infinity or whether S == T, and if so, takes the appropriate action. + T is required to be the neutral element (1 or R if Montgomery)*/ +void ccec_full_sub_normalized_ws(cc_ws_t ws, ccec_const_cp_t cp, + ccec_projective_point_t r, + ccec_const_projective_point_t s, + ccec_const_projective_point_t t); + + +/* accept a projective point S, an integer 1 ≤ d < q and 2 set R equal to the projective point dS. + Requires the point s to have been generated by "ccec_projectify" */ +int ccec_mult(ccec_const_cp_t cp, ccec_projective_point_t r, const cc_unit *d, + ccec_const_projective_point_t s, + struct ccrng_state *masking_rng); + +/* accept two projective points S, T , two integers 0 ≤ d0, d1 < p, and set R equal to the projective point d0S + d1T. */ +int ccec_twin_mult(ccec_const_cp_t cp, ccec_projective_point_t r, const cc_unit *d0, + ccec_const_projective_point_t s, + const cc_unit *d1, + ccec_const_projective_point_t t); + +/* Debugging */ +void ccec_alprint(ccec_const_cp_t cp, const char *label, ccec_const_affine_point_t s); +void ccec_plprint(ccec_const_cp_t cp, const char *label, ccec_const_projective_point_t s); + +void ccec_print_full_key(const char *label, ccec_full_ctx_t key); +void ccec_print_public_key(const char *label, ccec_pub_ctx_t key); +void ccec_print_sig(const char *label, size_t count, const uint8_t *s); + +/* + * EC key generation + */ + +/*! + @function ccec_generate_scalar_fips + @abstract Generate a random scalar k (private key) per FIPS "TestingCandidates" methodology + Faster than the extra bit generation + + @param cp Curve parameters + @param rng For the scalar k + @param k scalar of size ccec_cp_n(cp) + @param tmp buffer of size ccec_cp_n(cp) for intermediate values + @returns 0 if no error, an error code otherwise. + */ +int +ccec_generate_scalar_fips_retry(ccec_const_cp_t cp, struct ccrng_state *rng, cc_unit *k, cc_unit *tmp); + +/*! + @function ccec_generate_scalar_legacy + @abstract Generate a random scalar k (private key) with legacy method + Used for legacy purpose to reconstruct existing keys. + Behavior can not be changed + + @param cp Curve parameters + @param entropy_len Byte length of entropy + @param entropy Entropy for the scalar k + @param k scalar of size ccec_cp_n(cp) + @returns 0 if no error, an error code otherwise. + */ +int +ccec_generate_scalar_legacy(ccec_const_cp_t cp, + size_t entropy_len, const uint8_t *entropy, + cc_unit *k); + +/*! + @function ccec_generate_scalar_fips_extrabits + @abstract Generate a random scalar k (private key) per FIPS methodology + Slower than the "TestingCandidates" method + Behavior can not be changed + + @param cp Curve parameters + @param entropy_len Byte length of entropy + @param entropy Entropy for the scalar k + @param k scalar of size ccec_cp_n(cp) + @param tmp buffer of size ccec_cp_n(cp) for intermediate values + @returns 0 if no error, an error code otherwise. + */ +int +ccec_generate_scalar_fips_extrabits(ccec_const_cp_t cp, + size_t entropy_len, const uint8_t *entropy, + cc_unit *k, cc_unit *tmp); + +/*! + @function ccec_scalar_fips_extrabits_min_entropy_len + @abstract Return the minimum size of the entropy to be passed to + ccec_generate_scalar_fips_extrabits + + @param cp Curve parameters + @returns minimal value for entropy_len + */ +size_t ccec_scalar_fips_extrabits_min_entropy_len(ccec_const_cp_t cp); + +/*! + @function ccec_generate_scalar_pka + @abstract Generate a random scalar k (private key) per FIPS methodology + Similar to PKA behavior + Behavior can not be changed + + @param cp Curve parameters + @param entropy_len Byte length of entropy + @param entropy Entropy for the scalar k + @param k scalar of size ccec_cp_n(cp) + @param tmp buffer of size ccec_cp_n(cp) for intermediate values + @returns 0 if no error, an error code otherwise. + */ +int +ccec_generate_scalar_pka(ccec_const_cp_t cp, + size_t entropy_len, const uint8_t *entropy, + cc_unit *k, cc_unit *tmp); + +/*! + @function ccec_make_pub_from_priv + @abstract The public key from the input scalar k (private key) + This internal function does not perform the consistent check + Which guarantees that the key is valid. + @param cp Curve parameters + @param masking_rng For internal countermeasures + @param k scalar of size ccec_cp_n(cp), in range [1..q-1] and with no statistical bias. + @param key Resulting public key + @param generator Generator point / NULL if default + @returns 0 if no error, an error code otherwise. + */ +int +ccec_make_pub_from_priv(ccec_const_cp_t cp, + struct ccrng_state *masking_rng, + cc_unit *k, + ccec_const_affine_point_t generator, + ccec_pub_ctx_t key); + +/*! + @function ccec_generate_key_internal_legacy + @abstract Generate key pair for compatiblity purposes or deterministic keys + NOT RECOMMENDED. This internal function does not perform the consistent check + Which guarantees that the key is valid. + @param cp Curve parameters + @param rng For internal countermeasures + @param key Resulting key pair + @returns 0 if no error, an error code otherwise. + */ +int +ccec_generate_key_internal_legacy(ccec_const_cp_t cp, struct ccrng_state *rng, + ccec_full_ctx_t key); + +/* FIPS compliant and more secure */ +/*! + @function ccec_generate_key_internal_fips + @abstract Follows FIPS guideline and more secure. + This internal function does not perform the consistent check + which guarantees that the key is valid (required by FIPS). + @param cp Curve parameters + @param rng key generation and internal countermeasures + @param key Resulting key pair + @returns 0 if no error, an error code otherwise. + */ +int +ccec_generate_key_internal_fips(ccec_const_cp_t cp, struct ccrng_state *rng, + ccec_full_ctx_t key); + +/*! + @function ccec_compact_transform_key + @abstract Follow instructions from https://datatracker.ietf.org/doc/draft-jivsov-ecc-compact/ + to make a key compatible with the compact export format. + @param cp Curve parameters + @param key Input/Output full key + @returns 0 if no error, an error code otherwise. + */ +int ccec_compact_transform_key(ccec_full_ctx_t key); + +/*! + @function ccecdh_generate_key + @abstract Key generation used for ephemeral key pairs used in ECDH + This function may not perform all steps such as the FIPS consistency check. + @param cp Curve parameters + @param rng For key generation and internal countermeasures + @param key Resulting key pair + @returns 0 if no error, an error code otherwise. + */ +int ccecdh_generate_key(ccec_const_cp_t cp, struct ccrng_state *rng, ccec_full_ctx_t key); + + +/*! + @function ccecdh_pairwise_consistency_check + @abstract Does a DH with a constant key to confirm the newly generated key is + correct. + @param key Resulting key pair + @param generator Generator point / NULL if default + @param rng For key generation and internal countermeasures + @returns true if no error, false otherwise. + */ +bool ccecdh_pairwise_consistency_check(ccec_full_ctx_t full_key, + ccec_const_affine_point_t generator, + struct ccrng_state *rng); + +/* + * EC Digital Signature - ECDSA + */ + +/*! + @function ccec_verify_internal + @abstract ECDSA signature verification. + @param key Public key + @param digest_len Byte length of the digest + @param digest Pointer to the digest + @param r Pointer to input buffer for r + @param s Pointer to input buffer for s + @param valid Pointer to output boolean. + *valid=true if the input {r,s} is valid. + @returns 0 if no error, an error code otherwise. + */ + +int ccec_verify_internal(ccec_pub_ctx_t key, size_t digest_len, const uint8_t *digest, + const cc_unit *r, const cc_unit *s, bool *valid); + +/*! + @function ccec_sign_internal + @abstract ECDSA signature creation. + @param key Public key + @param digest_len Byte length of the digest + @param digest Pointer to the digest + @param r Pointer to output buffer for r + @param s Pointer to output buffer for s + @returns 0 if no error, an error code otherwise. + */ +int ccec_sign_internal(ccec_full_ctx_t key, size_t digest_len, const uint8_t *digest, + cc_unit *r, cc_unit *s, struct ccrng_state *rng); + + +/* + * RFC6637 wrap/unwrap + */ + +#define ccec_rfc6637_ecdh_public_key_id 18 +#define ccec_rfc6637_ecdsa_public_key_id 19 + +#define ccpgp_digest_sha256 8 +#define ccpgp_digest_sha384 9 +#define ccpgp_digest_sha512 10 + +#define ccpgp_cipher_aes128 7 +#define ccpgp_cipher_aes192 8 +#define ccpgp_cipher_aes256 9 + +struct ccec_rfc6637 { + const char *name; + const uint8_t kdfhash_id; + const struct ccdigest_info * (*difun)(void); + const uint8_t kek_id; + const size_t keysize; +}; + +struct ccec_rfc6637_curve { + const uint8_t *curve_oid; + uint8_t public_key_alg; +}; + +extern struct ccec_rfc6637 ccec_rfc6637_sha256_kek_aes128; +extern struct ccec_rfc6637 ccec_rfc6637_sha512_kek_aes256; + +void +ccec_rfc6637_kdf(const struct ccdigest_info *di, + const struct ccec_rfc6637_curve *curve, + const struct ccec_rfc6637 *wrap, + size_t epkey_size, const void *epkey, + size_t fingerprint_size, const void *fingerprint, + void *hash); + +size_t +ccec_rfc6637_wrap_pub_size(ccec_pub_ctx_t public_key, + unsigned long flags); + +int +ccec_rfc6637_wrap_core(ccec_pub_ctx_t public_key, + ccec_full_ctx_t ephemeral_key, + void *wrapped_key, + unsigned long flags, + uint8_t symm_alg_id, + size_t key_len, + const void *key, + const struct ccec_rfc6637_curve *curve, + const struct ccec_rfc6637_wrap *wrap, + const uint8_t *fingerprint, /* 20 bytes */ + struct ccrng_state *rng); + +uint16_t +pgp_key_checksum(size_t key_len, const uint8_t *key); + + +//imports the x and y from the in array in big-endian, sets z to 1 +CC_NONNULL_TU((1,4)) CC_NONNULL((3)) +int ccec_raw_import_pub(ccec_const_cp_t cp, size_t in_len, const uint8_t *in, ccec_pub_ctx_t key); +//imports the ecc private key k, and sets x an y to all ones. +CC_NONNULL_TU((1,4)) CC_NONNULL((3)) +int ccec_raw_import_priv_only(ccec_const_cp_t cp, size_t in_len, const uint8_t *in, ccec_full_ctx_t key); + +#endif /* _CORECRYPTO_CCEC_PRIV_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccecies.h b/libraries/corecrypto/include/corecrypto/ccecies.h new file mode 100644 index 0000000..47abff9 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccecies.h @@ -0,0 +1,217 @@ +/* + * Copyright (c) 2014,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +/* Elliptic Curve Integrated Encryption Scheme implementation using AES-GCM for + encryption/authentication. + Terminology borrowed from http://www.secg.org/index.php?action=secg,docs_secg + sharedinfo_1 is diversifier for the KDF: + In original design of DHIES, it needs to be set to the ephemeral public + key to address malleability concerns, which are limited for ECIES. + Even on ECIES, the mission of the public key appears to loosen the + security bounds of certain security proofs (cf p28 http://shoup.net/papers/iso-2_1.pdf) + Use option ECIES_EPH_PUBKEY_IN_SHAREDINFO1 to achieve this. + Still considered optional per standards SEC1 and x9.63 + sharedinfo_2 is diversifier for the MAC + Potential security threat when attacker controled. + */ + +#ifndef corecrypto_ccecies_h +#define corecrypto_ccecies_h + +// bit mask +#define ECIES_EPH_PUBKEY_IN_SHAREDINFO1 1 +#define ECIES_EXPORT_PUB_STANDARD 2 +#define ECIES_EXPORT_PUB_COMPACT 4 +//#define ECIES_EXPORT_PUB_COMPRESSES 8 // not supported +#define ECIES_LEGACY_IV 16 + +#include +#include +#include +#include + +typedef struct ccecies_gcm { + const struct ccdigest_info *di; + struct ccrng_state *rng; + const struct ccmode_gcm *gcm; + uint32_t key_length; + uint32_t mac_length; + uint32_t options; // bit mask +} *ccecies_gcm_t; + +/* set the structure from the argument passed */ +CC_NONNULL((1, 2, 3, 4)) +void +ccecies_encrypt_gcm_setup(ccecies_gcm_t ecies, + const struct ccdigest_info *di, + struct ccrng_state *rng, + const struct ccmode_gcm *aes_gcm_enc, + uint32_t cipher_key_size, + uint32_t mac_tag_nbytes, + uint32_t options + ); + +/* Return the size of the ciphertext from ccecies_encrypt_aes_gcm + It requires ecies to have been initialized with the setup function */ +CC_NONNULL_TU((1)) CC_NONNULL((2)) +size_t +ccecies_encrypt_gcm_ciphertext_size(ccec_pub_ctx_t public_key, + ccecies_gcm_t ecies, + size_t plaintext_nbytes + ); + +/* Encrypt using the provided public key and elliptic curve info + It requires ecies to have been initialized with the setup function. + ciphertext_nbytes must be at least "ccecies_encrypt_gcm_cipher_size" bytes + If ECIES_EPH_PUBKEY_IN_SHAREDINFO1 is set, sharedinfo1_nbytes is ignored */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 4, 9, 10)) +int +ccecies_encrypt_gcm( ccec_pub_ctx_t public_key, + const ccecies_gcm_t ecies, + size_t plaintext_nbytes, const uint8_t *plaintext, + size_t sharedinfo1_nbytes, const void *sharedinfo_1, + size_t sharedinfo2_nbytes, const void *sharedinfo_2, + size_t *encrypted_blob_nbytes, uint8_t *encrypted_blob + ); + +/* set the structure from the argument passed */ +CC_NONNULL((1, 2, 3)) +void +ccecies_decrypt_gcm_setup(ccecies_gcm_t ecies, + const struct ccdigest_info *di, + const struct ccmode_gcm *aes_gcm_dec, + uint32_t cipher_key_nbytes, + uint32_t mac_tag_nbytes, + uint32_t options + ); + +/* Return the size of the plaintext output of ccecies_decrypt_aes_gcm + It requires ecies to have been initialized with the setup function */ +CC_NONNULL_TU((1)) CC_NONNULL((2)) +size_t +ccecies_decrypt_gcm_plaintext_size(ccec_full_ctx_t full_key, + ccecies_gcm_t ecies, + size_t ciphertext_nbytes + ); + + +/* Decrypt using the provided private key and elliptic curve info + It requires ecies to have been initialized with the setup function. + ciphertext_nbytes must be at least "ccecies_encrypt_gcm_cipher_size" bytes + If ECIES_EPH_PUBKEY_IN_SHAREDINFO1 is set, sharedinfo1_nbytes is ignored */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 4, 9, 10)) +int +ccecies_decrypt_gcm(ccec_full_ctx_t full_key, + const ccecies_gcm_t ecies, + size_t encrypted_blob_nbytes, const uint8_t *encrypted_blob, + size_t sharedinfo1_nbytes, const void *sharedinfo_1, + size_t sharedinfo2_nbytes, const void *sharedinfo_2, + size_t *plaintext_nbytes, uint8_t *plaintext + ); + + + + +/* Return the size of the returned/expected exported public key */ +CC_NONNULL_TU((1)) CC_NONNULL((2)) +size_t +ccecies_pub_key_size(ccec_pub_ctx_t public_key, + ccecies_gcm_t ecies); + +/* Encrypt using the provided public key and elliptic curve info + It requires ecies to have been initialized with the setup function. + ciphertext_nbytes must be at least "ccecies_encrypt_gcm_cipher_size" bytes + If ECIES_EPH_PUBKEY_IN_SHAREDINFO1 is set, sharedinfo1_nbytes is ignored + Composite because ciphertext, mac and publickey are separate output */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 4, 5, 7)) +int +ccecies_encrypt_gcm_composite(ccec_pub_ctx_t public_key, + const ccecies_gcm_t ecies, + uint8_t *exported_public_key, /* output - length from ccecies_pub_key_size */ + uint8_t *ciphertext, /* output - length same as plaintext_nbytes */ + uint8_t *mac_tag, /* output - length ecies->mac_length */ + size_t plaintext_nbytes, const uint8_t *plaintext, + size_t sharedinfo1_nbytes, const void *sharedinfo_1, + size_t sharedinfo2_nbytes, const void *sharedinfo_2 + ); + +/* Decrypt using the provided private key and elliptic curve info + It requires ecies to have been initialized with the setup function. + ciphertext_nbytes must be at least "ccecies_encrypt_gcm_cipher_size" bytes + If ECIES_EPH_PUBKEY_IN_SHAREDINFO1 is set, sharedinfo1_nbytes is ignored + Composite because ciphertext, mac and publickey are separate input */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 10, 11)) +int +ccecies_decrypt_gcm_composite(ccec_full_ctx_t full_key, + const ccecies_gcm_t ecies, + uint8_t *plaintext, /* output - length same as ciphertext_nbytes */ + size_t sharedinfo1_nbytes, const void *sharedinfo_1, + size_t sharedinfo2_nbytes, const void *sharedinfo_2, + size_t ciphertext_nbytes, const uint8_t *ciphertext, + const uint8_t *imported_public_key, /* expect length from ccecies_pub_key_size */ + const uint8_t *mac_tag /* expect length ecies->mac_nbytesgth */ + ); + + +#endif diff --git a/libraries/corecrypto/include/corecrypto/ccecies_priv.h b/libraries/corecrypto/include/corecrypto/ccecies_priv.h new file mode 100644 index 0000000..379d05f --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccecies_priv.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2014,2015,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef corecrypto_ccecies_priv_h +#define corecrypto_ccecies_priv_h + +#define ECIES_CIPHERIV_SIZE 16 + +#endif diff --git a/libraries/corecrypto/include/corecrypto/cchkdf.h b/libraries/corecrypto/include/corecrypto/cchkdf.h new file mode 100644 index 0000000..ef18b91 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/cchkdf.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2014,2015,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCHKDF_H_ +#define _CORECRYPTO_CCHKDF_H_ + +#include + +/*! + @function cchkdf + @abstract Perform a NIST SP800-56C HKDF. + http://csrc.nist.gov/publications/nistpubs/800-56C/SP-800-56C.pdf + @discussion Derives output key data from input key data, optional salt, and info. + + @param di Hash function to use. + @param kdkLen Input key material length in bytes + @param kdk Input key material used to derive the new key + @param saltLen Salt length length + @param salt Salt data + @param infoLen Info string length + @param info Info string + @param dkLen Derived Key Length in bytes. + @param dk Derived key buffer to receive results of KDF + */ + +int cchkdf(const struct ccdigest_info *di, + size_t ikmLen, const void *ikm, + size_t saltLen, const void *salt, + size_t infoLen, const void *info, + size_t dkLen, void *dk); + +#endif /* _CORECRYPTO_CCHKDF_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/cchmac.h b/libraries/corecrypto/include/corecrypto/cchmac.h new file mode 100644 index 0000000..0a48245 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/cchmac.h @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2010,2011,2012,2014,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCHMAC_H_ +#define _CORECRYPTO_CCHMAC_H_ + +#include +#include + +/* An hmac_ctx_t is normally allocated as an array of these. */ +struct cchmac_ctx { + uint8_t b[8]; +} CC_ALIGNED(8); + +#if CORECRYPTO_USE_TRANSPARENT_UNION +typedef union { + struct cchmac_ctx *hdr; + ccdigest_ctx_t digest; +} cchmac_ctx_t __attribute__((transparent_union)); +#else +typedef struct cchmac_ctx* cchmac_ctx_t; +#endif + +#define cchmac_ctx_size(STATE_SIZE, BLOCK_SIZE) (ccdigest_ctx_size(STATE_SIZE, BLOCK_SIZE) + (STATE_SIZE)) +#define cchmac_di_size(_di_) (cchmac_ctx_size((_di_)->state_size, (_di_)->block_size)) + +#define cchmac_ctx_n(STATE_SIZE, BLOCK_SIZE) ccn_nof_size(cchmac_ctx_size((STATE_SIZE), (BLOCK_SIZE))) + +#define cchmac_ctx_decl(STATE_SIZE, BLOCK_SIZE, _name_) cc_ctx_decl(struct cchmac_ctx, cchmac_ctx_size(STATE_SIZE, BLOCK_SIZE), _name_) +#define cchmac_ctx_clear(STATE_SIZE, BLOCK_SIZE, _name_) cc_clear(cchmac_ctx_size(STATE_SIZE, BLOCK_SIZE), _name_) +#define cchmac_di_decl(_di_, _name_) cchmac_ctx_decl((_di_)->state_size, (_di_)->block_size, _name_) +#define cchmac_di_clear(_di_, _name_) cchmac_ctx_clear((_di_)->state_size, (_di_)->block_size, _name_) + +/* Return a ccdigest_ctx_t which can be accesed with the macros in ccdigest.h */ +#if CORECRYPTO_USE_TRANSPARENT_UNION +#define cchmac_digest_ctx(_di_, HC) (((cchmac_ctx_t)(HC)).digest) +#else +#define cchmac_digest_ctx(_di_, HC) ((ccdigest_ctx_t)(HC)) +#endif + +/* Accesors for ostate fields, this is all cchmac_ctx_t adds to the ccdigest_ctx_t. */ +#if CORECRYPTO_USE_TRANSPARENT_UNION +#define cchmac_ostate(_di_, HC) ((struct ccdigest_state *)(((cchmac_ctx_t)(HC)).hdr->b + ccdigest_di_size(_di_))) +#else +#define cchmac_ostate(_di_, HC) ((struct ccdigest_state *)(((cchmac_ctx_t)(HC))->b + ccdigest_di_size(_di_))) +#endif +#define cchmac_ostate8(_di_, HC) (ccdigest_u8(cchmac_ostate(_di_, HC))) +#define cchmac_ostate32(_di_, HC) (ccdigest_u32(cchmac_ostate(_di_, HC))) +#define cchmac_ostate64(_di_, HC) (ccdigest_u64(cchmac_ostate(_di_, HC))) +#define cchmac_ostateccn(_di_, HC) (ccdigest_ccn(cchmac_ostate(_di_, HC))) + +/* Convenience accessors for ccdigest_ctx_t fields. */ +#if CORECRYPTO_USE_TRANSPARENT_UNION +#define cchmac_istate(_di_, HC) ccdigest_state(_di_, ((cchmac_ctx_t)(HC)).digest) +#else +#define cchmac_istate(_di_, HC) ccdigest_state(_di_, ((ccdigest_ctx_t)(HC))) +#endif +#define cchmac_istate8(_di_, HC) ccdigest_u8(cchmac_istate(_di_, HC)) +#define cchmac_istate32(_di_, HC) ccdigest_u32(cchmac_istate(_di_, HC)) +#define cchmac_istate64(_di_, HC) ccdigest_u64(cchmac_istate(_di_, HC)) +#define cchmac_istateccn(_di_, HC) ccdigest_ccn(cchmac_istate(_di_, HC)) + +#if CORECRYPTO_USE_TRANSPARENT_UNION +#define cchmac_data(_di_, HC) ccdigest_data(_di_, ((cchmac_ctx_t)(HC)).digest) +#define cchmac_num(_di_, HC) ccdigest_num(_di_, ((cchmac_ctx_t)(HC)).digest) +#define cchmac_nbits(_di_, HC) ccdigest_nbits(_di_, ((cchmac_ctx_t)(HC)).digest) +#else +#define cchmac_data(_di_, HC) ccdigest_data(_di_, ((ccdigest_ctx_t)(HC))) +#define cchmac_num(_di_, HC) ccdigest_num(_di_, ((ccdigest_ctx_t)(HC))) +#define cchmac_nbits(_di_, HC) ccdigest_nbits(_di_, ((ccdigest_ctx_t)(HC))) +#endif + +void cchmac_init(const struct ccdigest_info *di, cchmac_ctx_t ctx, + size_t key_len, const void *key); +void cchmac_update(const struct ccdigest_info *di, cchmac_ctx_t ctx, + size_t data_len, const void *data); +void cchmac_final(const struct ccdigest_info *di, cchmac_ctx_t ctx, + unsigned char *mac); + +void cchmac(const struct ccdigest_info *di, size_t key_len, + const void *key, size_t data_len, const void *data, + unsigned char *mac); + +/* Test functions */ + +struct cchmac_test_input { + const struct ccdigest_info *di; + size_t key_len; + const void *key; + size_t data_len; + const void *data; + size_t mac_len; + const void *expected_mac; +}; + +int cchmac_test(const struct cchmac_test_input *input); +int cchmac_test_chunks(const struct cchmac_test_input *input, size_t chunk_size); + + +#endif /* _CORECRYPTO_CCHMAC_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccmd2.h b/libraries/corecrypto/include/corecrypto/ccmd2.h new file mode 100644 index 0000000..d21149b --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccmd2.h @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2010,2011,2015,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCMD2_H_ +#define _CORECRYPTO_CCMD2_H_ + +#include + +#define CCMD2_BLOCK_SIZE 16 +#define CCMD2_OUTPUT_SIZE 16 +#define CCMD2_STATE_SIZE 64 + +extern const uint32_t ccmd2_initial_state[16]; + +extern const struct ccdigest_info ccmd2_ltc_di; + +/* default is libtomcrypt */ +#define ccmd2_di ccmd2_ltc_di + +void ccmd2_final(const struct ccdigest_info *di, ccdigest_ctx_t, + unsigned char *digest); + +#endif /* _CORECRYPTO_CCMD2_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccmd4.h b/libraries/corecrypto/include/corecrypto/ccmd4.h new file mode 100644 index 0000000..f8bb54a --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccmd4.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2010,2015,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCMD4_H_ +#define _CORECRYPTO_CCMD4_H_ + +#include + +#define CCMD4_BLOCK_SIZE 64 +#define CCMD4_OUTPUT_SIZE 16 +#define CCMD4_STATE_SIZE 16 + +/* Works for MD5 as well */ +extern const uint32_t ccmd4_initial_state[4]; + +extern const struct ccdigest_info ccmd4_ltc_di; + +/* default is libtomcrypt */ +#define ccmd4_di ccmd4_ltc_di + +#endif /* _CORECRYPTO_CCMD4_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccmd5.h b/libraries/corecrypto/include/corecrypto/ccmd5.h new file mode 100644 index 0000000..ae4be4a --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccmd5.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2010,2012,2015,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCMD5_H_ +#define _CORECRYPTO_CCMD5_H_ + +#include + +#define CCMD5_BLOCK_SIZE 64 +#define CCMD5_OUTPUT_SIZE 16 +#define CCMD5_STATE_SIZE 16 + +extern const uint32_t ccmd5_initial_state[4]; + +/* Selector */ +const struct ccdigest_info *ccmd5_di(void); + +/* Implementations */ +extern const struct ccdigest_info ccmd5_ltc_di; + +#endif /* _CORECRYPTO_CCMD5_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccmode.h b/libraries/corecrypto/include/corecrypto/ccmode.h new file mode 100644 index 0000000..7148577 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccmode.h @@ -0,0 +1,926 @@ +/* + * Copyright (c) 2010,2011,2012,2014,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCMODE_H_ +#define _CORECRYPTO_CCMODE_H_ + +#include +#include +#include + +/* ECB mode. */ + +/* Declare a ecb key named _name_. Pass the size field of a struct ccmode_ecb + for _size_. */ +#define ccecb_ctx_decl(_size_, _name_) cc_ctx_decl(ccecb_ctx, _size_, _name_) +#define ccecb_ctx_clear(_size_, _name_) cc_clear(_size_, _name_) + +CC_INLINE size_t ccecb_context_size(const struct ccmode_ecb *mode) +{ + return mode->size; +} + +CC_INLINE size_t ccecb_block_size(const struct ccmode_ecb *mode) +{ + return mode->block_size; +} + +CC_INLINE int ccecb_init(const struct ccmode_ecb *mode, ccecb_ctx *ctx, + size_t key_len, const void *key) +{ + return mode->init(mode, ctx, key_len, key); +} + +CC_INLINE int ccecb_update(const struct ccmode_ecb *mode, const ccecb_ctx *ctx, + size_t nblocks, const void *in, void *out) +{ + return mode->ecb(ctx, nblocks, in, out); +} + +CC_INLINE int ccecb_one_shot(const struct ccmode_ecb *mode, + size_t key_len, const void *key, + size_t nblocks, const void *in, void *out) +{ + int rc; + ccecb_ctx_decl(mode->size, ctx); + rc = mode->init(mode, ctx, key_len, key); + mode->ecb(ctx, nblocks, in, out); + ccecb_ctx_clear(mode->size, ctx); + return rc; +} + +/* CBC mode. */ + +/* Declare a cbc key named _name_. Pass the size field of a struct ccmode_cbc + for _size_. */ +#define cccbc_ctx_decl(_size_, _name_) cc_ctx_decl(cccbc_ctx, _size_, _name_) +#define cccbc_ctx_clear(_size_, _name_) cc_clear(_size_, _name_) + +/* Declare a cbc iv tweak named _name_. Pass the blocksize field of a + struct ccmode_cbc for _size_. */ +#define cccbc_iv_decl(_size_, _name_) cc_ctx_decl(cccbc_iv, _size_, _name_) +#define cccbc_iv_clear(_size_, _name_) cc_clear(_size_, _name_) + +/* Actual symmetric algorithm implementation can provide you one of these. + + Alternatively you can create a ccmode_cbc instance from any ccmode_ecb + cipher. To do so, statically initialize a struct ccmode_cbc using the + CCMODE_FACTORY_CBC_DECRYPT or CCMODE_FACTORY_CBC_ENCRYPT macros. + Alternatively you can dynamically initialize a struct ccmode_cbc + ccmode_factory_cbc_decrypt() or ccmode_factory_cbc_encrypt(). */ + +CC_INLINE size_t cccbc_context_size(const struct ccmode_cbc *mode) +{ + return mode->size; +} + +CC_INLINE size_t cccbc_block_size(const struct ccmode_cbc *mode) +{ + return mode->block_size; +} + +CC_INLINE int cccbc_init(const struct ccmode_cbc *mode, cccbc_ctx *ctx, + size_t key_len, const void *key) +{ + return mode->init(mode, ctx, key_len, key); +} + +CC_INLINE int cccbc_set_iv(const struct ccmode_cbc *mode, cccbc_iv *iv_ctx, + const void *iv) +{ + if (iv) + cc_copy(mode->block_size, iv_ctx, iv); + else + cc_zero(mode->block_size, iv_ctx); + return 0; +} + +CC_INLINE int cccbc_update(const struct ccmode_cbc *mode, cccbc_ctx *ctx, + cccbc_iv *iv, size_t nblocks, + const void *in, void *out) +{ + return mode->cbc(ctx, iv, nblocks, in, out); +} + +int cccbc_one_shot(const struct ccmode_cbc *mode, + size_t key_len, const void *key, + const void *iv, size_t nblocks, + const void *in, void *out); + +/* CFB mode. */ + +/* Declare a cfb key named _name_. Pass the size field of a struct ccmode_cfb + for _size_. */ +#define cccfb_ctx_decl(_size_, _name_) cc_ctx_decl(cccfb_ctx, _size_, _name_) +#define cccfb_ctx_clear(_size_, _name_) cc_clear(_size_, _name_) + +CC_INLINE size_t cccfb_context_size(const struct ccmode_cfb *mode) +{ + return mode->size; +} + +CC_INLINE size_t cccfb_block_size(const struct ccmode_cfb *mode) +{ + return mode->block_size; +} + +CC_INLINE int cccfb_init(const struct ccmode_cfb *mode, cccfb_ctx *ctx, + size_t key_len, const void *key, + const void *iv) +{ + return mode->init(mode, ctx, key_len, key, iv); +} + +CC_INLINE int cccfb_update(const struct ccmode_cfb *mode, cccfb_ctx *ctx, + size_t nbytes, const void *in, void *out) +{ + return mode->cfb(ctx, nbytes, in, out); +} + +CC_INLINE int cccfb_one_shot(const struct ccmode_cfb *mode, + size_t key_len, const void *key, const void *iv, + size_t nbytes, const void *in, void *out) +{ + int rc; + cccfb_ctx_decl(mode->size, ctx); + rc = mode->init(mode, ctx, key_len, key, iv); + mode->cfb(ctx, nbytes, in, out); + cccfb_ctx_clear(mode->size, ctx); + return rc; +} + +/* CFB8 mode. */ + +/* Declare a cfb8 key named _name_. Pass the size field of a struct ccmode_cfb8 + for _size_. */ +#define cccfb8_ctx_decl(_size_, _name_) cc_ctx_decl(cccfb8_ctx, _size_, _name_) +#define cccfb8_ctx_clear(_size_, _name_) cc_clear(_size_, _name_) + +CC_INLINE size_t cccfb8_context_size(const struct ccmode_cfb8 *mode) +{ + return mode->size; +} + +CC_INLINE size_t cccfb8_block_size(const struct ccmode_cfb8 *mode) +{ + return mode->block_size; +} + +CC_INLINE int cccfb8_init(const struct ccmode_cfb8 *mode, cccfb8_ctx *ctx, + size_t key_len, const void *key, const void *iv) +{ + return mode->init(mode, ctx, key_len, key, iv); +} + +CC_INLINE int cccfb8_update(const struct ccmode_cfb8 *mode, cccfb8_ctx *ctx, + size_t nbytes, const void *in, void *out) +{ + return mode->cfb8(ctx, nbytes, in, out); +} + +CC_INLINE int cccfb8_one_shot(const struct ccmode_cfb8 *mode, + size_t key_len, const void *key, const void *iv, + size_t nbytes, const void *in, void *out) +{ + int rc; + cccfb8_ctx_decl(mode->size, ctx); + rc = mode->init(mode, ctx, key_len, key, iv); + mode->cfb8(ctx, nbytes, in, out); + cccfb8_ctx_clear(mode->size, ctx); + return rc; +} + +/* CTR mode. */ + +/* Declare a ctr key named _name_. Pass the size field of a struct ccmode_ctr + for _size_. */ +#define ccctr_ctx_decl(_size_, _name_) cc_ctx_decl(ccctr_ctx, _size_, _name_) +#define ccctr_ctx_clear(_size_, _name_) cc_clear(_size_, _name_) + +/* This is Integer Counter Mode: The IV is the initial value of the counter + that is incremented by 1 for each new block. Use the mode flags to select + if the IV/Counter is stored in big or little endian. */ + +CC_INLINE size_t ccctr_context_size(const struct ccmode_ctr *mode) +{ + return mode->size; +} + +CC_INLINE size_t ccctr_block_size(const struct ccmode_ctr *mode) +{ + return mode->block_size; +} + +CC_INLINE int ccctr_init(const struct ccmode_ctr *mode, ccctr_ctx *ctx, + size_t key_len, const void *key, const void *iv) +{ + return mode->init(mode, ctx, key_len, key, iv); +} + +CC_INLINE int ccctr_update(const struct ccmode_ctr *mode, ccctr_ctx *ctx, + size_t nbytes, const void *in, void *out) +{ + return mode->ctr(ctx, nbytes, in, out); +} + +CC_INLINE int ccctr_one_shot(const struct ccmode_ctr *mode, + size_t key_len, const void *key, const void *iv, + size_t nbytes, const void *in, void *out) +{ + int rc; + ccctr_ctx_decl(mode->size, ctx); + rc = mode->init(mode, ctx, key_len, key, iv); + if (rc) return rc; + rc = mode->ctr(ctx, nbytes, in, out); + ccctr_ctx_clear(mode->size, ctx); + return rc; +} + + +/* OFB mode. */ + +/* Declare a ofb key named _name_. Pass the size field of a struct ccmode_ofb + for _size_. */ +#define ccofb_ctx_decl(_size_, _name_) cc_ctx_decl(ccofb_ctx, _size_, _name_) +#define ccofb_ctx_clear(_size_, _name_) cc_clear(_size_, _name_) + +CC_INLINE size_t ccofb_context_size(const struct ccmode_ofb *mode) +{ + return mode->size; +} + +CC_INLINE size_t ccofb_block_size(const struct ccmode_ofb *mode) +{ + return mode->block_size; +} + +CC_INLINE int ccofb_init(const struct ccmode_ofb *mode, ccofb_ctx *ctx, + size_t key_len, const void *key, const void *iv) +{ + return mode->init(mode, ctx, key_len, key, iv); +} + +CC_INLINE int ccofb_update(const struct ccmode_ofb *mode, ccofb_ctx *ctx, + size_t nbytes, const void *in, void *out) +{ + return mode->ofb(ctx, nbytes, in, out); +} + +CC_INLINE int ccofb_one_shot(const struct ccmode_ofb *mode, + size_t key_len, const void *key, const void *iv, + size_t nbytes, const void *in, void *out) +{ + int rc; + ccofb_ctx_decl(mode->size, ctx); + rc = mode->init(mode, ctx, key_len, key, iv); + mode->ofb(ctx, nbytes, in, out); + ccofb_ctx_clear(mode->size, ctx); + return rc; +} + +/* XTS mode. */ + +/* Declare a xts key named _name_. Pass the size field of a struct ccmode_xts + for _size_. */ +#define ccxts_ctx_decl(_size_, _name_) cc_ctx_decl(ccxts_ctx, _size_, _name_) +#define ccxts_ctx_clear(_size_, _name_) cc_clear(_size_, _name_) + +/* Declare a xts tweak named _name_. Pass the tweak_size field of a + struct ccmode_xts for _size_. */ +#define ccxts_tweak_decl(_size_, _name_) cc_ctx_decl(ccxts_tweak, _size_, _name_) +#define ccxts_tweak_clear(_size_, _name_) cc_clear(_size_, _name_) + +/* Actual symmetric algorithm implementation can provide you one of these. + + Alternatively you can create a ccmode_xts instance from any ccmode_ecb + cipher. To do so, statically initialize a struct ccmode_xts using the + CCMODE_FACTORY_XTS_DECRYPT or CCMODE_FACTORY_XTS_ENCRYPT macros. Alternatively + you can dynamically initialize a struct ccmode_xts + ccmode_factory_xts_decrypt() or ccmode_factory_xts_encrypt(). */ + +/* NOTE that xts mode does not do cts padding. It's really an xex mode. + If you need cts padding use the ccpad_xts_encrypt and ccpad_xts_decrypt + functions. Also note that xts only works for ecb modes with a block_size + of 16. */ + +CC_INLINE size_t ccxts_context_size(const struct ccmode_xts *mode) +{ + return mode->size; +} + +CC_INLINE size_t ccxts_block_size(const struct ccmode_xts *mode) +{ + return mode->block_size; +} + +/*! + @function ccxts_init + @abstract Initialize an XTS context. + + @param mode Descriptor for the mode + @param ctx Context for this instance + @param key_nbytes Length of the key arguments in bytes + @param data_key Key for data encryption + @param tweak_key Key for tweak generation + + @result 0 iff successful. + + @discussion For security reasons, the two keys must be different. + */ +CC_INLINE int ccxts_init(const struct ccmode_xts *mode, ccxts_ctx *ctx, + size_t key_nbytes, const void *data_key, + const void *tweak_key) +{ + return mode->init(mode, ctx, key_nbytes, data_key, tweak_key); +} + +/*! + @function ccxts_set_tweak + @abstract Initialize the tweak for a sector. + + @param mode Descriptor for the mode + @param ctx Context for this instance + @param tweak Context for the tweak for this sector + @param iv Data used to generate the tweak + + @discussion The IV must be exactly one block in length. + */ +CC_INLINE int ccxts_set_tweak(const struct ccmode_xts *mode, ccxts_ctx *ctx, + ccxts_tweak *tweak, const void *iv) +{ + return mode->set_tweak(ctx, tweak, iv); +} + +/*! + @function ccxts_update + @abstract Encrypt or decrypt data. + + @param mode Descriptor for the mode + @param ctx Context for an instance + @param tweak Context for the tweak for this sector + @param nblocks Length of the data in blocks + @param in Input data + @param out Output buffer + + @result The updated internal buffer of the tweak context. May be ignored. + */ +CC_INLINE void *ccxts_update(const struct ccmode_xts *mode, ccxts_ctx *ctx, + ccxts_tweak *tweak, size_t nblocks, const void *in, void *out) +{ + return mode->xts(ctx, tweak, nblocks, in, out); +} + +/*! + @function ccxts_one_shot + @abstract Encrypt or decrypt data in XTS mode. + + @param mode Descriptor for the mode + @param key_nbytes Length of the key arguments in bytes + @param data_key Key for data encryption + @param tweak_key Key for tweak generation + @param iv Data used to generate the tweak + @param nblocks Length of the data in blocks + @param in Input data + @param out Output buffer + + @result 0 iff successful. + + @discussion For security reasons, the two keys must be different. + */ +int ccxts_one_shot(const struct ccmode_xts *mode, + size_t key_nbytes, const void *data_key, + const void *tweak_key, const void *iv, + size_t nblocks, const void *in, void *out); + +/* Authenticated cipher modes. */ + +/* GCM mode. */ + +/* Declare a gcm key named _name_. Pass the size field of a struct ccmode_gcm + for _size_. */ +#define ccgcm_ctx_decl(_size_, _name_) cc_ctx_decl(ccgcm_ctx, _size_, _name_) +#define ccgcm_ctx_clear(_size_, _name_) cc_clear(_size_, _name_) + +#define CCGCM_IV_NBYTES 12 +#define CCGCM_BLOCK_NBYTES 16 + +/* (2^32 - 2) blocks */ +/* (2^36 - 32) bytes */ +/* (2^39 - 256) bits */ +/* Exceeding this figure breaks confidentiality and authenticity. */ +#define CCGCM_TEXT_MAX_NBYTES ((1ULL << 36) - 32ULL) + +CC_INLINE size_t ccgcm_context_size(const struct ccmode_gcm *mode) +{ + return mode->size; +} + +CC_INLINE size_t ccgcm_block_size(const struct ccmode_gcm *mode) +{ + return mode->block_size; +} + +/*! + @function ccgcm_init + @abstract Initialize a GCM context. + + @param mode Descriptor for the mode + @param ctx Context for this instance + @param key_nbytes Length of the key in bytes + @param key Key for the underlying blockcipher (AES) + + @result 0 iff successful. + + @discussion The correct sequence of calls is: + + @code ccgcm_init(...) + ccgcm_set_iv(...) + ccgcm_aad(...) (may be called zero or more times) + ccgcm_update(...) (may be called zero or more times) + ccgcm_finalize(...) + + To reuse the context for additional encryptions, follow this sequence: + + @code ccgcm_reset(...) + ccgcm_set_iv(...) + ccgcm_aad(...) (may be called zero or more times) + ccgcm_update(...) (may be called zero or more times) + ccgcm_finalize(...) + + @warning The key-IV pair must be unique per encryption. The IV must be nonzero in length. + + @warning It is not permitted to call @p ccgcm_inc_iv after initializing the cipher via the @p ccgcm_init interface. Nonzero is returned in the event of an improper call sequence. + + @warning This function is not FIPS-compliant. Use @p ccgcm_init_with_iv instead. + */ +CC_INLINE int ccgcm_init(const struct ccmode_gcm *mode, ccgcm_ctx *ctx, + size_t key_nbytes, const void *key) +{ + return mode->init(mode, ctx, key_nbytes, key); +} + +/*! + @function ccgcm_init_with_iv + @abstract Initialize a GCM context to manage IVs internally. + + @param mode Descriptor for the mode + @param ctx Context for this instance + @param key_nbytes Length of the key in bytes + @param key Key for the underlying blockcipher (AES) + @param iv IV for the first encryption + + @result 0 iff successful. + + @discussion The correct sequence of calls is: + + @code ccgcm_init_with_iv(...) + ccgcm_aad(...) (may be called zero or more times) + ccgcm_update(...) (may be called zero or more times) + ccgcm_finalize(...) + + To reuse the context for additional encryptions, follow this sequence: + + @code ccgcm_reset(...) + ccgcm_inc_iv(...) + ccgcm_aad(...) (may be called zero or more times) + ccgcm_update(...) (may be called zero or more times) + ccgcm_finalize(...) + + The IV must be exactly 12 bytes in length. + + Internally, the IV is treated as a four-byte salt followed by an eight-byte counter. This is to match the behavior of certain protocols (e.g. TLS). In the call to @p ccgcm_inc_iv, the counter component will be interpreted as a big-endian, unsigned value and incremented in place. + + @warning It is not permitted to call @p ccgcm_set_iv after initializing the cipher via the @p ccgcm_init_with_iv interface. Nonzero is returned in the event of an improper call sequence. + + @warning The security of GCM depends on the uniqueness of key-IV pairs. To avoid key-IV repetition, callers should not initialize multiple contexts with the same key material via the @p ccgcm_init_with_iv interface. + */ +int ccgcm_init_with_iv(const struct ccmode_gcm *mode, ccgcm_ctx *ctx, + size_t key_nbytes, const void *key, + const void *iv); + +/*! + @function ccgcm_set_iv + @abstract Set the IV for encryption. + + @param mode Descriptor for the mode + @param ctx Context for this instance + @param iv_nbytes Length of the IV in bytes + @param iv Initialization vector + + @result 0 iff successful. + + @discussion Set the initialization vector for encryption. + + @warning The key-IV pair must be unique per encryption. The IV must be nonzero in length. + + In stateful protocols, if each packet exposes a guaranteed-unique value, it is recommended to format this as a 12-byte value for use as the IV. + + In stateless protocols, it is recommended to choose a 16-byte value using a cryptographically-secure pseudorandom number generator (e.g. @p ccrng). + + @warning This function may not be used after initializing the cipher via @p ccgcm_init_with_iv. Nonzero is returned in the event of an improper call sequence. + + @warning This function is not FIPS-compliant. Use @p ccgcm_init_with_iv instead. + */ +CC_INLINE int ccgcm_set_iv(const struct ccmode_gcm *mode, ccgcm_ctx *ctx, + size_t iv_nbytes, const void *iv) +{ + return mode->set_iv(ctx, iv_nbytes, iv); +} + +/*! + @function ccgcm_set_iv_legacy + @abstract Set the IV for encryption. + + @param mode Descriptor for the mode + @param ctx Context for this instance + @param iv_nbytes Length of the IV in bytes + @param iv Initialization vector + + @result 0 iff successful. + + @discussion Identical to @p ccgcm_set_iv except that it allows zero-length IVs. + + @warning Zero-length IVs nullify the authenticity guarantees of GCM. + + @warning Do not use this function in new applications. + */ +int ccgcm_set_iv_legacy(const struct ccmode_gcm *mode, ccgcm_ctx *ctx, + size_t iv_nbytes, const void *iv); + +/*! + @function ccgcm_inc_iv + @abstract Increment the IV for another encryption. + + @param mode Descriptor for the mode + @param ctx Context for this instance + @param iv Updated initialization vector + + @result 0 iff successful. + + @discussion Updates the IV internally for another encryption. + + Internally, the IV is treated as a four-byte salt followed by an eight-byte counter. This is to match the behavior of certain protocols (e.g. TLS). The counter component is interpreted as a big-endian, unsigned value and incremented in place. + + The updated IV is copied to @p iv. This is to support protocols that require part of the IV to be specified explicitly in each packet (e.g. TLS). + + @warning This function may be used only after initializing the cipher via @p ccgcm_init_with_iv. + */ +int ccgcm_inc_iv(const struct ccmode_gcm *mode, ccgcm_ctx *ctx, void *iv); + + +/*! + @function ccgcm_aad + @abstract Authenticate additional data. + + @param mode Descriptor for the mode + @param ctx Context for this instance + @param nbytes Length of the additional data in bytes + @param additional_data Additional data to authenticate + + @result 0 iff successful. + + @discussion This is typically used to authenticate data that cannot be encrypted (e.g. packet headers). + + This function may be called zero or more times. + */ +CC_INLINE int ccgcm_aad(const struct ccmode_gcm *mode, ccgcm_ctx *ctx, + size_t nbytes, const void *additional_data) +{ + return mode->gmac(ctx, nbytes, additional_data); +} + +/*! + @function ccgcm_gmac + + @discussion See @p ccgcm_aad. + */ +CC_INLINE int ccgcm_gmac(const struct ccmode_gcm *mode, ccgcm_ctx *ctx, + size_t nbytes, const void *in) +{ + return mode->gmac(ctx, nbytes, in); +} + +/*! + @function ccgcm_update + @abstract Encrypt or decrypt data. + + @param mode Descriptor for the mode + @param ctx Context for this instance + @param nbytes Length of the data in bytes + @param in Input plaintext or ciphertext + @param out Output ciphertext or plaintext + + @result 0 iff successful. + + @discussion In-place processing is supported. + + This function may be called zero or more times. + */ +CC_INLINE int ccgcm_update(const struct ccmode_gcm *mode, ccgcm_ctx *ctx, + size_t nbytes, const void *in, void *out) +{ + return mode->gcm(ctx, nbytes, in, out); +} + +/*! + @function ccgcm_finalize + @abstract Finish processing and authenticate. + + @param mode Descriptor for the mode + @param ctx Context for this instance + @param tag_nbytes Length of the tag in bytes + @param tag Authentication tag + + @result 0 iff successful. + + @discussion Finish processing a packet and generate the authentication tag. + + On encryption, @p tag is purely an output parameter. The generated tag is written to @p tag. + + On decryption, @p tag is both an input and an output parameter. Well-behaved callers should provide the authentication tag generated during encryption. The function will return nonzero if the input tag does not match the generated tag. The generated tag will be written into the @p tag buffer whether authentication succeeds or fails. + + @warning The generated tag is written to @p tag to support legacy applications that perform authentication manually. Do not follow this usage pattern in new applications. Rely on the function's error code to verify authenticity. + */ +CC_INLINE int ccgcm_finalize(const struct ccmode_gcm *mode, ccgcm_ctx *ctx, + size_t tag_nbytes, void *tag) +{ + return mode->finalize(ctx, tag_nbytes, tag); +} + +/*! + @function ccgcm_reset + @abstract Reset the context for another encryption. + + @param mode Descriptor for the mode + @param ctx Context for this instance + + @result 0 iff successful. + + @discussion Refer to @p ccgcm_init for correct usage. + */ +CC_INLINE int ccgcm_reset(const struct ccmode_gcm *mode, ccgcm_ctx *ctx) +{ + return mode->reset(ctx); +} + + +/*! + @function ccgcm_one_shot + @abstract Encrypt or decrypt with GCM. + + @param mode Descriptor for the mode + @param key_nbytes Length of the key in bytes + @param key Key for the underlying blockcipher (AES) + @param iv_nbytes Length of the IV in bytes + @param iv Initialization vector + @param adata_nbytes Length of the additional data in bytes + @param adata Additional data to authenticate + @param nbytes Length of the data in bytes + @param in Input plaintext or ciphertext + @param out Output ciphertext or plaintext + @param tag_nbytes Length of the tag in bytes + @param tag Authentication tag + + @result 0 iff successful. + + @discussion Perform GCM encryption or decryption. + + @warning The key-IV pair must be unique per encryption. The IV must be nonzero in length. + + In stateful protocols, if each packet exposes a guaranteed-unique value, it is recommended to format this as a 12-byte value for use as the IV. + + In stateless protocols, it is recommended to choose a 16-byte value using a cryptographically-secure pseudorandom number generator (e.g. @p ccrng). + + In-place processing is supported. + + On encryption, @p tag is purely an output parameter. The generated tag is written to @p tag. + + On decryption, @p tag is primarily an input parameter. The caller should provide the authentication tag generated during encryption. The function will return nonzero if the input tag does not match the generated tag. + + @warning To support legacy applications, @p tag is also an output parameter during decryption. The generated tag is written to @p tag. Legacy callers may choose to compare this to the tag generated during encryption. Do not follow this usage pattern in new applications. + */ +int ccgcm_one_shot(const struct ccmode_gcm *mode, + size_t key_nbytes, const void *key, + size_t iv_nbytes, const void *iv, + size_t adata_nbytes, const void *adata, + size_t nbytes, const void *in, void *out, + size_t tag_nbytes, void *tag); + + +/*! + @function ccgcm_one_shot_legacy + @abstract Encrypt or decrypt with GCM. + + @param mode Descriptor for the mode + @param key_nbytes Length of the key in bytes + @param key Key for the underlying blockcipher (AES) + @param iv_nbytes Length of the IV in bytes + @param iv Initialization vector + @param adata_nbytes Length of the additional data in bytes + @param adata Additional data to authenticate + @param nbytes Length of the data in bytes + @param in Input plaintext or ciphertext + @param out Output ciphertext or plaintext + @param tag_nbytes Length of the tag in bytes + @param tag Authentication tag + + @result 0 iff successful. + + @discussion Identical to @p ccgcm_one_shot except that it allows zero-length IVs. + + @warning Zero-length IVs nullify the authenticity guarantees of GCM. + + @warning Do not use this function in new applications. + */ +int ccgcm_one_shot_legacy(const struct ccmode_gcm *mode, + size_t key_nbytes, const void *key, + size_t iv_nbytes, const void *iv, + size_t adata_nbytes, const void *adata, + size_t nbytes, const void *in, void *out, + size_t tag_nbytes, void *tag); + + +/* CCM */ + +#define ccccm_ctx_decl(_size_, _name_) cc_ctx_decl(ccccm_ctx, _size_, _name_) +#define ccccm_ctx_clear(_size_, _name_) cc_clear(_size_, _name_) + +/* Declare a ccm nonce named _name_. Pass the mode->nonce_ctx_size for _size_. */ +#define ccccm_nonce_decl(_size_, _name_) cc_ctx_decl(ccccm_nonce, _size_, _name_) +#define ccccm_nonce_clear(_size_, _name_) cc_clear(_size_, _name_) + + +CC_INLINE size_t ccccm_context_size(const struct ccmode_ccm *mode) +{ + return mode->size; +} + +CC_INLINE size_t ccccm_block_size(const struct ccmode_ccm *mode) +{ + return mode->block_size; +} + +CC_INLINE int ccccm_init(const struct ccmode_ccm *mode, ccccm_ctx *ctx, + size_t key_len, const void *key) +{ + return mode->init(mode, ctx, key_len, key); +} + +CC_INLINE int ccccm_set_iv(const struct ccmode_ccm *mode, ccccm_ctx *ctx, ccccm_nonce *nonce_ctx, + size_t nonce_len, const void *nonce, + size_t mac_size, size_t auth_len, size_t data_len) +{ + return mode->set_iv(ctx, nonce_ctx, nonce_len, nonce, mac_size, auth_len, data_len); +} + +CC_INLINE int ccccm_cbcmac(const struct ccmode_ccm *mode, ccccm_ctx *ctx, ccccm_nonce *nonce_ctx, + size_t nbytes, const void *in) +{ + return mode->cbcmac(ctx, nonce_ctx, nbytes, in); +} + +CC_INLINE int ccccm_update(const struct ccmode_ccm *mode, ccccm_ctx *ctx, ccccm_nonce *nonce_ctx, + size_t nbytes, const void *in, void *out) +{ + return mode->ccm(ctx, nonce_ctx, nbytes, in, out); +} + +CC_INLINE int ccccm_finalize(const struct ccmode_ccm *mode, ccccm_ctx *ctx, ccccm_nonce *nonce_ctx, + void *mac) +{ + return mode->finalize(ctx, nonce_ctx, mac); +} + +CC_INLINE int ccccm_reset(const struct ccmode_ccm *mode, ccccm_ctx *ctx, ccccm_nonce *nonce_ctx) +{ + return mode->reset(ctx, nonce_ctx); +} + + +CC_INLINE int ccccm_one_shot(const struct ccmode_ccm *mode, + size_t key_len, const void *key, + size_t nonce_len, const void *nonce, + size_t nbytes, const void *in, void *out, + size_t adata_len, const void* adata, + size_t mac_size, void *mac) +{ + int rc=0; + ccccm_ctx_decl(mode->size, ctx); + ccccm_nonce_decl(mode->nonce_size, nonce_ctx); + rc = mode->init(mode, ctx, key_len, key); + if(rc==0) rc=mode->set_iv(ctx, nonce_ctx, nonce_len, nonce, mac_size, adata_len, nbytes); + if(rc==0) rc=mode->cbcmac(ctx, nonce_ctx, adata_len, adata); + if(rc==0) rc=mode->ccm(ctx, nonce_ctx, nbytes, in, out); + if(rc==0) rc=mode->finalize(ctx, nonce_ctx, mac); + ccccm_ctx_clear(mode->size, ctx); + ccccm_nonce_clear(mode->nonce_size, nonce_ctx); + + return rc; +} + + +/* OMAC mode. */ + + +/* Declare a omac key named _name_. Pass the size field of a struct ccmode_omac + for _size_. */ +#define ccomac_ctx_decl(_size_, _name_) cc_ctx_decl(ccomac_ctx, _size_, _name_) +#define ccomac_ctx_clear(_size_, _name_) cc_clear(_size_, _name_) + +CC_INLINE size_t ccomac_context_size(const struct ccmode_omac *mode) +{ + return mode->size; +} + +CC_INLINE size_t ccomac_block_size(const struct ccmode_omac *mode) +{ + return mode->block_size; +} + +CC_INLINE int ccomac_init(const struct ccmode_omac *mode, ccomac_ctx *ctx, + size_t tweak_len, size_t key_len, const void *key) +{ + return mode->init(mode, ctx, tweak_len, key_len, key); +} + +CC_INLINE int ccomac_update(const struct ccmode_omac *mode, ccomac_ctx *ctx, + size_t nblocks, const void *tweak, const void *in, void *out) +{ + return mode->omac(ctx, nblocks, tweak, in, out); +} + +CC_INLINE int ccomac_one_shot(const struct ccmode_omac *mode, + size_t tweak_len, size_t key_len, const void *key, + const void *tweak, size_t nblocks, const void *in, void *out) +{ + int rc; + ccomac_ctx_decl(mode->size, ctx); + rc = mode->init(mode, ctx, tweak_len, key_len, key); + if (rc == 0) rc = mode->omac(ctx, nblocks, tweak, in, out); + ccomac_ctx_clear(mode->size, ctx); + return rc; +} + + +#endif /* _CORECRYPTO_CCMODE_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccmode_factory.h b/libraries/corecrypto/include/corecrypto/ccmode_factory.h new file mode 100644 index 0000000..a868cee --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccmode_factory.h @@ -0,0 +1,646 @@ +/* + * Copyright (c) 2011,2012,2013,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCMODE_FACTORY_H_ +#define _CORECRYPTO_CCMODE_FACTORY_H_ + +#include /* TODO: Remove dependency on this header. */ +#include + +/* Function and macros defined in this file are only to be used + within corecrypto files. + */ + +/* For CBC, direction of underlying ecb is the same as the cbc direction */ +#define CCMODE_CBC_FACTORY(_cipher_, _dir_) \ +static struct ccmode_cbc cbc_##_cipher_##_##_dir_; \ + \ +const struct ccmode_cbc *cc##_cipher_##_cbc_##_dir_##_mode(void) \ +{ \ + const struct ccmode_ecb *ecb=cc##_cipher_##_ecb_##_dir_##_mode(); \ + ccmode_factory_cbc_##_dir_(&cbc_##_cipher_##_##_dir_, ecb); \ + return &cbc_##_cipher_##_##_dir_; \ +} + +/* For CTR, only one direction, underlying ecb is always encrypt */ +#define CCMODE_CTR_FACTORY(_cipher_) \ +static struct ccmode_ctr ctr_##_cipher_; \ + \ +const struct ccmode_ctr *cc##_cipher_##_ctr_crypt_mode(void) \ +{ \ + const struct ccmode_ecb *ecb=cc##_cipher_##_ecb_encrypt_mode(); \ + ccmode_factory_ctr_crypt(&ctr_##_cipher_, ecb); \ + return &ctr_##_cipher_; \ +} + +/* OFB, same as CTR */ +#define CCMODE_OFB_FACTORY(_cipher_) \ +static struct ccmode_ofb ofb_##_cipher_; \ + \ +const struct ccmode_ofb *cc##_cipher_##_ofb_crypt_mode(void) \ +{ \ + const struct ccmode_ecb *ecb=cc##_cipher_##_ecb_encrypt_mode(); \ + ccmode_factory_ofb_crypt(&ofb_##_cipher_, ecb); \ + return &ofb_##_cipher_; \ +} + + +/* For CFB, the underlying ecb operation is encrypt for both directions */ +#define CCMODE_CFB_FACTORY(_cipher_, _mode_, _dir_) \ +static struct ccmode_##_mode_ _mode_##_##_cipher_##_##_dir_; \ + \ +const struct ccmode_##_mode_ *cc##_cipher_##_##_mode_##_##_dir_##_mode(void) \ +{ \ + const struct ccmode_ecb *ecb=cc##_cipher_##_ecb_encrypt_mode(); \ + ccmode_factory_##_mode_##_##_dir_(&_mode_##_##_cipher_##_##_dir_, ecb); \ + return &_mode_##_##_cipher_##_##_dir_; \ +} + +/* For GCM, same as CFB */ +#define CCMODE_GCM_FACTORY(_cipher_, _dir_) CCMODE_CFB_FACTORY(_cipher_, gcm, _dir_) + +/* For CCM, same as CFB */ +#define CCMODE_CCM_FACTORY(_cipher_, _dir_) CCMODE_CFB_FACTORY(_cipher_, ccm, _dir_) + + +/* Fot XTS, you always need an ecb encrypt */ +#define CCMODE_XTS_FACTORY(_cipher_ , _dir_) \ +static struct ccmode_xts xts##_cipher_##_##_dir_; \ + \ +const struct ccmode_xts *cc##_cipher_##_xts_##_dir_##_mode(void) \ +{ \ + const struct ccmode_ecb *ecb=cc##_cipher_##_ecb_##_dir_##_mode(); \ + const struct ccmode_ecb *ecb_enc=cc##_cipher_##_ecb_encrypt_mode(); \ + \ + ccmode_factory_xts_##_dir_(&xts##_cipher_##_##_dir_, ecb, ecb_enc); \ + return &xts##_cipher_##_##_dir_; \ +} + +#if 0 + +/* example of how to make the selection function thread safe */ + +struct ccmode_cbc cc3des_cbc_mode_encrypt; +dispatch_once_t cc3des_mode_encrypt_init_once; + +void cc3des_mode_encrypt_init(void *ctx) { + struct ccmode_ecb *ecb = cc3des_ecb_encrypt_mode(); + ccmode_factory_cbc_encrypt(&cc3des_mode_encrypt, ecb); +} + +const struct ccmode_cbc *cc3des_cbc_encrypt_mode(void) { + dispatch_once_f(&cc3des_mode_encrypt_init_once, NULL, cc3des_mode_encrypt_init); + return &cc3des_mode_encrypt; +} + +struct ccmode_cbc cc3des_cbc_mode_encrypt = { + .n = CC3DES_LTC_ECB_ENCRYPT_N, + .init = ccmode_cbc_init, + .cbc = ccmode_cbc_encrypt, + .custom = &cc3des_ltc_ecb_encrypt +}; + +const struct ccmode_cbc *cc3des_cbc_encrypt_mode(void) { + return &cc3des_mode_encrypt; +} + +#endif + + + +int ccmode_cbc_init(const struct ccmode_cbc *cbc, cccbc_ctx *ctx, + size_t rawkey_len, const void *rawkey); +int ccmode_cbc_decrypt(const cccbc_ctx *ctx, cccbc_iv *iv, size_t nblocks, + const void *in, void *out); +int ccmode_cbc_encrypt(const cccbc_ctx *ctx, cccbc_iv *iv, size_t nblocks, + const void *in, void *out); + +struct _ccmode_cbc_key { + const struct ccmode_ecb *ecb; + cc_unit u[]; +}; + +/* Use this to statically initialize a ccmode_cbc object for decryption. */ +#define CCMODE_FACTORY_CBC_DECRYPT(ECB) { \ +.size = ccn_sizeof_size(sizeof(struct _ccmode_cbc_key)) + ccn_sizeof_size((ECB)->block_size) + ccn_sizeof_size((ECB)->size), \ +.block_size = (ECB)->block_size, \ +.init = ccmode_cbc_init, \ +.cbc = ccmode_cbc_decrypt, \ +.custom = (ECB) \ +} + +/* Use this to statically initialize a ccmode_cbc object for encryption. */ +#define CCMODE_FACTORY_CBC_ENCRYPT(ECB) { \ +.size = ccn_sizeof_size(sizeof(struct _ccmode_cbc_key)) + ccn_sizeof_size((ECB)->block_size) + ccn_sizeof_size((ECB)->size), \ +.block_size = (ECB)->block_size, \ +.init = ccmode_cbc_init, \ +.cbc = ccmode_cbc_encrypt, \ +.custom = (ECB) \ +} + +/* Use these function to runtime initialize a ccmode_cbc decrypt object (for + example if it's part of a larger structure). Normally you would pass a + ecb decrypt mode implementation of some underlying algorithm as the ecb + parameter. */ +void ccmode_factory_cbc_decrypt(struct ccmode_cbc *cbc, + const struct ccmode_ecb *ecb); + +/* Use these function to runtime initialize a ccmode_cbc encrypt object (for + example if it's part of a larger structure). Normally you would pass a + ecb encrypt mode implementation of some underlying algorithm as the ecb + parameter. */ +void ccmode_factory_cbc_encrypt(struct ccmode_cbc *cbc, + const struct ccmode_ecb *ecb); + + +int ccmode_cfb_init(const struct ccmode_cfb *cfb, cccfb_ctx *ctx, + size_t rawkey_len, const void *rawkey, + const void *iv); +int ccmode_cfb_decrypt(cccfb_ctx *ctx, size_t nbytes, + const void *in, void *out); +int ccmode_cfb_encrypt(cccfb_ctx *ctx, size_t nbytes, + const void *in, void *out); +struct _ccmode_cfb_key { + const struct ccmode_ecb *ecb; + size_t pad_len; + cc_unit u[]; +}; + +/* Use this to statically initialize a ccmode_cfb object for decryption. */ +#define CCMODE_FACTORY_CFB_DECRYPT(ECB) { \ +.size = ccn_sizeof_size(sizeof(struct _ccmode_cfb_key)) + 2 * ccn_sizeof_size((ECB)->block_size) + ccn_sizeof_size((ECB)->size), \ +.block_size = 1, \ +.init = ccmode_cfb_init, \ +.cfb = ccmode_cfb_decrypt, \ +.custom = (ECB) \ +} + +/* Use this to statically initialize a ccmode_cfb object for encryption. */ +#define CCMODE_FACTORY_CFB_ENCRYPT(ECB) { \ +.size = ccn_sizeof_size(sizeof(struct _ccmode_cfb_key)) + 2 * ccn_sizeof_size((ECB)->block_size) + ccn_sizeof_size((ECB)->size), \ +.block_size = 1, \ +.init = ccmode_cfb_init, \ +.cfb = ccmode_cfb_encrypt, \ +.custom = (ECB) \ +} + +/* Use these function to runtime initialize a ccmode_cfb decrypt object (for + example if it's part of a larger structure). Normally you would pass a + ecb encrypt mode implementation of some underlying algorithm as the ecb + parameter. */ +void ccmode_factory_cfb_decrypt(struct ccmode_cfb *cfb, + const struct ccmode_ecb *ecb); + +/* Use these function to runtime initialize a ccmode_cfb encrypt object (for + example if it's part of a larger structure). Normally you would pass a + ecb encrypt mode implementation of some underlying algorithm as the ecb + parameter. */ +void ccmode_factory_cfb_encrypt(struct ccmode_cfb *cfb, + const struct ccmode_ecb *ecb); + +int ccmode_cfb8_init(const struct ccmode_cfb8 *cfb8, cccfb8_ctx *ctx, + size_t rawkey_len, const void *rawkey, const void *iv); +int ccmode_cfb8_decrypt(cccfb8_ctx *ctx, size_t nbytes, + const void *in, void *out); +int ccmode_cfb8_encrypt(cccfb8_ctx *ctx, size_t nbytes, + const void *in, void *out); + +struct _ccmode_cfb8_key { + const struct ccmode_ecb *ecb; + cc_unit u[]; +}; + +/* Use this to statically initialize a ccmode_cfb8 object for decryption. */ +#define CCMODE_FACTORY_CFB8_DECRYPT(ECB) { \ +.size = ccn_sizeof_size(sizeof(struct _ccmode_cfb8_key)) + 2 * ccn_sizeof_size((ECB)->block_size) + ccn_sizeof_size((ECB)->size), \ +.block_size = 1, \ +.init = ccmode_cfb8_init, \ +.cfb8 = ccmode_cfb8_decrypt, \ +.custom = (ECB) \ +} + +/* Use this to statically initialize a ccmode_cfb8 object for encryption. */ +#define CCMODE_FACTORY_CFB8_ENCRYPT(ECB) { \ +.size = ccn_sizeof_size(sizeof(struct _ccmode_cfb8_key)) + 2 * ccn_sizeof_size((ECB)->block_size) + ccn_sizeof_size((ECB)->size), \ +.block_size = 1, \ +.init = ccmode_cfb8_init, \ +.cfb8 = ccmode_cfb8_encrypt, \ +.custom = (ECB) \ +} + +/* Use these function to runtime initialize a ccmode_cfb8 decrypt object (for + example if it's part of a larger structure). Normally you would pass a + ecb decrypt mode implementation of some underlying algorithm as the ecb + parameter. */ +void ccmode_factory_cfb8_decrypt(struct ccmode_cfb8 *cfb8, + const struct ccmode_ecb *ecb); + +/* Use these function to runtime initialize a ccmode_cfb8 encrypt object (for + example if it's part of a larger structure). Normally you would pass a + ecb encrypt mode implementation of some underlying algorithm as the ecb + parameter. */ +void ccmode_factory_cfb8_encrypt(struct ccmode_cfb8 *cfb8, + const struct ccmode_ecb *ecb); + +int ccmode_ctr_init(const struct ccmode_ctr *ctr, ccctr_ctx *ctx, + size_t rawkey_len, const void *rawkey, const void *iv); +int ccmode_ctr_setctr(const struct ccmode_ctr *mode, ccctr_ctx *ctx, const void *ctr); +int ccmode_ctr_crypt(ccctr_ctx *ctx, size_t nbytes, + const void *in, void *out); + +struct _ccmode_ctr_key { + const struct ccmode_ecb *ecb; + size_t pad_offset; + cc_unit u[]; +}; + +/* Use this to statically initialize a ccmode_ctr object for decryption. */ +#define CCMODE_FACTORY_CTR_CRYPT(ECB_ENCRYPT) { \ +.size = ccn_sizeof_size(sizeof(struct _ccmode_ctr_key)) + 2 * ccn_sizeof_size((ECB_ENCRYPT)->block_size) + ccn_sizeof_size((ECB_ENCRYPT)->size), \ +.block_size = 1, \ +.ecb_block_size = (ECB_ENCRYPT)->block_size, \ +.init = ccmode_ctr_init, \ +.setctr = ccmode_ctr_setctr, \ +.ctr = ccmode_ctr_crypt, \ +.custom = (ECB_ENCRYPT) \ +} + +/* Use these function to runtime initialize a ccmode_ctr decrypt object (for + example if it's part of a larger structure). Normally you would pass a + ecb encrypt mode implementation of some underlying algorithm as the ecb + parameter. */ +void ccmode_factory_ctr_crypt(struct ccmode_ctr *ctr, + const struct ccmode_ecb *ecb); + + +/* Create a gcm key from a gcm mode object. + key must point to at least sizeof(CCMODE_GCM_KEY(ecb)) bytes of free + storage. */ +int ccmode_gcm_init(const struct ccmode_gcm *gcm, ccgcm_ctx *ctx, + size_t rawkey_len, const void *rawkey); +int ccmode_gcm_set_iv(ccgcm_ctx *ctx, size_t iv_nbytes, const void *iv); +int ccmode_gcm_aad(ccgcm_ctx *ctx, size_t nbytes, const void *in); +int ccmode_gcm_decrypt(ccgcm_ctx *ctx, size_t nbytes, const void *in, + void *out); +int ccmode_gcm_encrypt(ccgcm_ctx *ctx, size_t nbytes, const void *in, + void *out); + +/*! + @function ccmode_gcm_finalize() finalizes AES-GCM call sequence + @param key encryption or decryption key + @param tag_nbytes length of tag in bytes + @param tag authentication tag + @result 0=success or non zero= error + @discussion For decryption, the tag parameter must be the expected-tag. A secure compare is performed between the provided expected-tag and the computed-tag. If they are the same, 0 is returned. Otherwise, non zero is returned. For encryption, tag is output and provides the authentication tag. + + */ +int ccmode_gcm_finalize(ccgcm_ctx *key, size_t tag_nbytes, void *tag); +int ccmode_gcm_reset(ccgcm_ctx *key); + +#define CCGCM_FLAGS_INIT_WITH_IV 1 + +// Here is what the structure looks like in memory +// [ temp space | length | *ecb | *ecb_key | table | ecb_key ] +// size of table depends on the implementation (VNG vs factory) +// currently, VNG and factory share the same "header" described here +// VNG may add additional data after the header +struct _ccmode_gcm_key { + // 5 blocks of temp space. + unsigned char H[16]; /* multiplier */ + unsigned char X[16]; /* accumulator */ + unsigned char Y[16]; /* counter */ + unsigned char Y_0[16]; /* initial counter */ + unsigned char buf[16]; /* buffer for stuff */ + + // State and length + uint16_t state; /* state the GCM code is in */ + uint16_t flags; /* flags (persistent across reset) */ + uint32_t buf_nbytes; /* length of data in buf */ + + uint64_t aad_nbytes; /* 64-bit counter used for IV and AAD */ + uint64_t text_nbytes; /* 64-bit counter for the plaintext PT */ + + // ECB + const struct ccmode_ecb *ecb; // ecb mode + // Pointer to the ECB key in the buffer + void *ecb_key; // address of the ecb_key in u, set in init function + int encdec; //is it an encrypt or decrypt object + + // Buffer with ECB key and H table if applicable + CC_ALIGNED(16) unsigned char u[]; // ecb key + tables +}; + +#define GCM_ECB_KEY_SIZE(ECB_ENCRYPT) \ + ((5 * ccn_sizeof_size((ECB_ENCRYPT)->block_size)) \ + + ccn_sizeof_size((ECB_ENCRYPT)->size)) + +/* Use these function to runtime initialize a ccmode_gcm decrypt object (for + example if it's part of a larger structure). For GCM you always pass a + ecb encrypt mode implementation of some underlying algorithm as the ecb + parameter. */ +void ccmode_factory_gcm_decrypt(struct ccmode_gcm *gcm, + const struct ccmode_ecb *ecb_encrypt); + +/* Use these function to runtime initialize a ccmode_gcm encrypt object (for + example if it's part of a larger structure). For GCM you always pass a + ecb encrypt mode implementation of some underlying algorithm as the ecb + parameter. */ +void ccmode_factory_gcm_encrypt(struct ccmode_gcm *gcm, + const struct ccmode_ecb *ecb_encrypt); + + +/* CCM (only NIST approved with AES) */ +int ccmode_ccm_init(const struct ccmode_ccm *ccm, ccccm_ctx *ctx, + size_t rawkey_len, const void *rawkey); +int ccmode_ccm_set_iv(ccccm_ctx *ctx, ccccm_nonce *nonce_ctx, size_t nonce_len, const void *nonce, + size_t mac_size, size_t auth_len, size_t data_len); +/* internal function */ +void ccmode_ccm_macdata(ccccm_ctx *key, ccccm_nonce *nonce_ctx, unsigned new_block, size_t nbytes, const void *in); +/* api function - disallows only mac'd data after data to encrypt was sent */ +int ccmode_ccm_cbcmac(ccccm_ctx *ctx, ccccm_nonce *nonce_ctx, size_t nbytes, const void *in); +/* internal function */ +void ccmode_ccm_crypt(ccccm_ctx *key, ccccm_nonce *nonce_ctx, size_t nbytes, const void *in, void *out); +int ccmode_ccm_decrypt(ccccm_ctx *ctx, ccccm_nonce *nonce_ctx, size_t nbytes, const void *in, + void *out); +int ccmode_ccm_encrypt(ccccm_ctx *ctx, ccccm_nonce *nonce_ctx, size_t nbytes, const void *in, + void *out); +int ccmode_ccm_finalize(ccccm_ctx *key, ccccm_nonce *nonce_ctx, void *mac); +int ccmode_ccm_reset(ccccm_ctx *key, ccccm_nonce *nonce_ctx); + +struct _ccmode_ccm_key { + const struct ccmode_ecb *ecb; + cc_unit u[]; +}; + +struct _ccmode_ccm_nonce { + unsigned char A_i[16]; /* crypto block iv */ + unsigned char B_i[16]; /* mac block iv */ + unsigned char MAC[16]; /* crypted mac */ + unsigned char buf[16]; /* crypt buffer */ + + uint32_t mode; /* mode: IV -> AD -> DATA */ + uint32_t buflen; /* length of data in buf */ + uint32_t b_i_len; /* length of cbcmac data in B_i */ + + size_t nonce_size; + size_t mac_size; +}; + +/* Use this to statically initialize a ccmode_ccm object for decryption. */ +#define CCMODE_FACTORY_CCM_DECRYPT(ECB_ENCRYPT) { \ +.size = ccn_sizeof_size(sizeof(struct _ccmode_ccm_key)) + ccn_sizeof_size((ECB_ENCRYPT)->block_size) + ccn_sizeof_size((ECB_ENCRYPT)->size), \ +.nonce_size = ccn_sizeof_size(sizeof(struct _ccmode_ccm_nonce)), \ +.block_size = 1, \ +.init = ccmode_ccm_init, \ +.set_iv = ccmode_ccm_set_iv, \ +.cbcmac = ccmode_ccm_cbcmac, \ +.ccm = ccmode_ccm_decrypt, \ +.finalize = ccmode_ccm_finalize, \ +.reset = ccmode_ccm_reset, \ +.custom = (ECB_ENCRYPT) \ +} + +/* Use this to statically initialize a ccmode_ccm object for encryption. */ +#define CCMODE_FACTORY_CCM_ENCRYPT(ECB_ENCRYPT) { \ +.size = ccn_sizeof_size(sizeof(struct _ccmode_ccm_key)) + ccn_sizeof_size((ECB_ENCRYPT)->block_size) + ccn_sizeof_size((ECB_ENCRYPT)->size), \ +.nonce_size = ccn_sizeof_size(sizeof(struct _ccmode_ccm_nonce)), \ +.block_size = 1, \ +.init = ccmode_ccm_init, \ +.set_iv = ccmode_ccm_set_iv, \ +.cbcmac = ccmode_ccm_cbcmac, \ +.ccm = ccmode_ccm_encrypt, \ +.finalize = ccmode_ccm_finalize, \ +.reset = ccmode_ccm_reset, \ +.custom = (ECB_ENCRYPT) \ +} + +/* Use these function to runtime initialize a ccmode_ccm decrypt object (for + example if it's part of a larger structure). For CCM you always pass a + ecb encrypt mode implementation of some underlying algorithm as the ecb + parameter. */ + +void ccmode_factory_ccm_decrypt(struct ccmode_ccm *ccm, + const struct ccmode_ecb *ecb_encrypt); + +/* Use these function to runtime initialize a ccmode_ccm encrypt object (for + example if it's part of a larger structure). For CCM you always pass a + ecb encrypt mode implementation of some underlying algorithm as the ecb + parameter. */ +void ccmode_factory_ccm_encrypt(struct ccmode_ccm *ccm, + const struct ccmode_ecb *ecb_encrypt); + + +int ccmode_ofb_init(const struct ccmode_ofb *ofb, ccofb_ctx *ctx, + size_t rawkey_len, const void *rawkey, + const void *iv); +int ccmode_ofb_crypt(ccofb_ctx *ctx, size_t nbytes, + const void *in, void *out); + +struct _ccmode_ofb_key { + const struct ccmode_ecb *ecb; + size_t pad_len; + cc_unit u[]; +}; + +/* Use this to statically initialize a ccmode_ofb object. */ +#define CCMODE_FACTORY_OFB_CRYPT(ECB) { \ +.size = ccn_sizeof_size(sizeof(struct _ccmode_ofb_key)) + ccn_sizeof_size((ECB)->block_size) + ccn_sizeof_size((ECB)->size), \ +.block_size = 1, \ +.init = ccmode_ofb_init, \ +.ofb = ccmode_ofb_crypt, \ +.custom = (ECB) \ +} + +/* Use these function to runtime initialize a ccmode_ofb encrypt object (for + example if it's part of a larger structure). Normally you would pass a + ecb encrypt mode implementation of some underlying algorithm as the ecb + parameter. */ +void ccmode_factory_ofb_crypt(struct ccmode_ofb *ofb, + const struct ccmode_ecb *ecb); + +int ccmode_omac_decrypt(ccomac_ctx *ctx, size_t nblocks, + const void *tweak, const void *in, void *out); +int ccmode_omac_encrypt(ccomac_ctx *ctx, size_t nblocks, + const void *tweak, const void *in, void *out); + +/* Create a omac key from a omac mode object. The tweak_len here + determines how long the tweak is in bytes, for each subsequent call to + ccmode_omac->omac(). + key must point to at least sizeof(CCMODE_OMAC_KEY(ecb)) bytes of free + storage. */ +int ccmode_omac_init(const struct ccmode_omac *omac, ccomac_ctx *ctx, + size_t tweak_len, size_t rawkey_len, + const void *rawkey); + +struct _ccmode_omac_key { + const struct ccmode_ecb *ecb; + size_t tweak_len; + cc_unit u[]; +}; + +/* Use this to statically initialize a ccmode_omac object for decryption. */ +#define CCMODE_FACTORY_OMAC_DECRYPT(ECB) { \ +.size = ccn_sizeof_size(sizeof(struct _ccmode_omac_key)) + 2 * ccn_sizeof_size((ECB)->size), \ +.block_size = (ECB)->block_size, \ +.init = ccmode_omac_init, \ +.omac = ccmode_omac_decrypt, \ +.custom = (ECB) \ +} + +/* Use this to statically initialize a ccmode_omac object for encryption. */ +#define CCMODE_FACTORY_OMAC_ENCRYPT(ECB) { \ +.size = ccn_sizeof_size(sizeof(struct _ccmode_omac_key)) + 2 * ccn_sizeof_size((ECB)->size), \ +.block_size = (ECB)->block_size, \ +.init = ccmode_omac_init, \ +.omac = ccmode_omac_encrypt, \ +.custom = (ECB) \ +} + +/* Use these function to runtime initialize a ccmode_omac decrypt object (for + example if it's part of a larger structure). Normally you would pass a + ecb decrypt mode implementation of some underlying algorithm as the ecb + parameter. */ +void ccmode_factory_omac_decrypt(struct ccmode_omac *omac, + const struct ccmode_ecb *ecb); + +/* Use these function to runtime initialize a ccmode_omac encrypt object (for + example if it's part of a larger structure). Normally you would pass a + ecb encrypt mode implementation of some underlying algorithm as the ecb + parameter. */ +void ccmode_factory_omac_encrypt(struct ccmode_omac *omac, + const struct ccmode_ecb *ecb); + + +/* Function prototypes used by the macros below, do not call directly. */ +int ccmode_xts_init(const struct ccmode_xts *xts, ccxts_ctx *ctx, + size_t key_nbytes, const void *data_key, + const void *tweak_key); +void ccmode_xts_key_sched(const struct ccmode_xts *xts, ccxts_ctx *ctx, + size_t key_nbytes, const void *data_key, + const void *tweak_key); +void *ccmode_xts_crypt(const ccxts_ctx *ctx, ccxts_tweak *tweak, + size_t nblocks, const void *in, void *out); +int ccmode_xts_set_tweak(const ccxts_ctx *ctx, ccxts_tweak *tweak, + const void *iv); + + +struct _ccmode_xts_key { + const struct ccmode_ecb *ecb; + const struct ccmode_ecb *ecb_encrypt; + cc_unit u[]; +}; + +struct _ccmode_xts_tweak { + // FIPS requires that for XTS that no more that 2^20 AES blocks may be processed for any given + // Key, Tweak Key, and tweak combination + // the bytes_processed field in the context will accumuate the number of blocks processed and + // will fail the encrypt/decrypt if the size is violated. This counter will be reset to 0 + // when set_tweak is called. + size_t blocks_processed; + cc_unit u[]; +}; + +/* Use this to statically initialize a ccmode_xts object for decryption. */ +#define CCMODE_FACTORY_XTS_DECRYPT(ECB, ECB_ENCRYPT) { \ +.size = ccn_sizeof_size(sizeof(struct _ccmode_xts_key)) + 2 * ccn_sizeof_size((ECB)->size), \ +.tweak_size = ccn_sizeof_size(sizeof(struct _ccmode_xts_tweak)) + ccn_sizeof_size(ecb->block_size), \ +.block_size = ecb->block_size, \ +.init = ccmode_xts_init, \ +.key_sched = ccmode_xts_key_sched, \ +.set_tweak = ccmode_xts_set_tweak, \ +.xts = ccmode_xts_crypt, \ +.custom = (ECB), \ +.custom1 = (ECB_ENCRYPT) \ +} + +/* Use this to statically initialize a ccmode_xts object for encryption. */ +#define CCMODE_FACTORY_XTS_ENCRYPT(ECB, ECB_ENCRYPT) { \ +.size = ccn_sizeof_size(sizeof(struct _ccmode_xts_key)) + 2 * ccn_sizeof_size((ECB)->size), \ +.tweak_size = ccn_sizeof_size(sizeof(struct _ccmode_xts_tweak)) + ccn_sizeof_size(ecb->block_size), \ +.block_size = ecb->block_size, \ +.init = ccmode_xts_init, \ +.key_sched = ccmode_xts_key_sched, \ +.set_tweak = ccmode_xts_set_tweak, \ +.xts = ccmode_xts_crypt, \ +.custom = (ECB), \ +.custom1 = (ECB_ENCRYPT) \ +} + +/* Use these function to runtime initialize a ccmode_xts decrypt object (for + example if it's part of a larger structure). Normally you would pass a + ecb decrypt mode implementation of some underlying algorithm as the ecb + parameter. */ +void ccmode_factory_xts_decrypt(struct ccmode_xts *xts, + const struct ccmode_ecb *ecb, + const struct ccmode_ecb *ecb_encrypt); + +/* Use these function to runtime initialize a ccmode_xts encrypt object (for + example if it's part of a larger structure). Normally you would pass a + ecb encrypt mode implementation of some underlying algorithm as the ecb + parameter. */ +void ccmode_factory_xts_encrypt(struct ccmode_xts *xts, + const struct ccmode_ecb *ecb, + const struct ccmode_ecb *ecb_encrypt); + +#endif /* _CORECRYPTO_CCMODE_FACTORY_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccmode_impl.h b/libraries/corecrypto/include/corecrypto/ccmode_impl.h new file mode 100644 index 0000000..b1aebf7 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccmode_impl.h @@ -0,0 +1,264 @@ +/* + * Copyright (c) 2012,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCMODE_IMPL_H_ +#define _CORECRYPTO_CCMODE_IMPL_H_ + +#include + +/* ECB mode. */ +cc_aligned_struct(16) ccecb_ctx; + + +/* Actual symmetric algorithm implementation should provide you one of these. */ +struct ccmode_ecb { + size_t size; /* first argument to ccecb_ctx_decl(). */ + size_t block_size; + int (*init)(const struct ccmode_ecb *ecb, ccecb_ctx *ctx, + size_t key_nbytes, const void *key); + int (*ecb)(const ccecb_ctx *ctx, size_t nblocks, const void *in, + void *out); +}; + +/*! + * @brief corecrypto symmetrical encryption and decryption modes + * + * corecrypto supports 6 stateless en(de)cryption modes and 2 stateful authenticated en(de)cryption modes + * stateless modes CBC, CFB, CFB8, CTR, OFB, XTS: They provide 3 interface functions that do not return errors codes + * 1- ccmod_xxx_init() + * 2- ccmod_xxx_decrypt() + * 3- ccmod_xxx_encrypt() + * + * stateful modes CCM and GCM: They provide 7 interface functions that return error codes if a function is called out of state + * 1- ccmod_xxx_init() + * 2- ccmod_xxx_setiv() + * 3- ccmod_xxx_aad() + * 4- ccmod_xxx_decrypt() + * 5- ccmod_xxx_encrypt() + * 6- ccmod_xxx_finalize() + * 7- ccmod_xxx_reset() + * + * the correct call sequences are: + * + * calls to 1, 2 and 6 arerequired + * 2 and 3 can be called as mant times as needed + * calls to 3, 4, 5 can be skipped + * + * 1, 2*n, 3*n, 4|5, 6 + * 1, 2*n, , 4|5, 6 + * 1, 2*n, , , 6 + * 1, 2*n, 3*n, , 6 + */ + +// 1- CBC mode, stateless +cc_aligned_struct(16) cccbc_ctx; +cc_aligned_struct(16) cccbc_iv; + +struct ccmode_cbc { + size_t size; /* first argument to cccbc_ctx_decl(). */ + size_t block_size; + int (*init)(const struct ccmode_cbc *cbc, cccbc_ctx *ctx, + size_t key_len, const void *key); + /* cbc encrypt or decrypt nblocks from in to out, iv will be used and updated. */ + int (*cbc)(const cccbc_ctx *ctx, cccbc_iv *iv, + size_t nblocks, const void *in, void *out); + const void *custom; +}; + +// 2- CFB mode, stateless +cc_aligned_struct(16) cccfb_ctx; + +struct ccmode_cfb { + size_t size; /* first argument to cccfb_ctx_decl(). */ + size_t block_size; + int (*init)(const struct ccmode_cfb *cfb, cccfb_ctx *ctx, + size_t key_len, const void *key, const void *iv); + int (*cfb)(cccfb_ctx *ctx, size_t nbytes, const void *in, void *out); + const void *custom; +}; + +// 3- CFB8 mode, stateless +cc_aligned_struct(16) cccfb8_ctx; + +struct ccmode_cfb8 { + size_t size; /* first argument to cccfb8_ctx_decl(). */ + size_t block_size; + int (*init)(const struct ccmode_cfb8 *cfb8, cccfb8_ctx *ctx, + size_t key_len, const void *key, const void *iv); + int (*cfb8)(cccfb8_ctx *ctx, size_t nbytes, const void *in, void *out); + const void *custom; +}; + +// 4- CTR mode, stateless +cc_aligned_struct(16) ccctr_ctx; + +struct ccmode_ctr { + size_t size; /* first argument to ccctr_ctx_decl(). */ + size_t block_size; /* for historical reasons, this is set to 1 */ + size_t ecb_block_size; /* the actual block size of the underlying cipher */ + int (*init)(const struct ccmode_ctr *mode, ccctr_ctx *ctx, + size_t key_len, const void *key, const void *iv); + int (*setctr)(const struct ccmode_ctr *mode, ccctr_ctx *ctx, const void *ctr); + int (*ctr)(ccctr_ctx *ctx, size_t nbytes, const void *in, void *out); + const void *custom; +}; + +// 5- OFB mode, stateless +cc_aligned_struct(16) ccofb_ctx; + +struct ccmode_ofb { + size_t size; /* first argument to ccofb_ctx_decl(). */ + size_t block_size; + int (*init)(const struct ccmode_ofb *ofb, ccofb_ctx *ctx, + size_t key_len, const void *key, const void *iv); + int (*ofb)(ccofb_ctx *ctx, size_t nbytes, const void *in, void *out); + const void *custom; +}; + +// 6- XTS mode, stateless +cc_aligned_struct(16) ccxts_ctx; +cc_aligned_struct(16) ccxts_tweak; + +struct ccmode_xts { + size_t size; /* first argument to ccxts_ctx_decl(). Size of the ctx data structure */ + size_t tweak_size; /* first argument to ccxts_tweak_decl(). Size of the tweak structure, not the expected tweak size */ + size_t block_size; + + /* Create a xts key from a xts mode object. + key must point to at least 'size' bytes of free storage. + tweak_key must point to at least 'tweak_size' bytes of free storage. + key and tweak_key must differ. + Returns nonzero on failure. + */ + int (*init)(const struct ccmode_xts *xts, ccxts_ctx *ctx, + size_t key_nbytes, const void *data_key, const void *tweak_key); + + void (*key_sched)(const struct ccmode_xts *xts, ccxts_ctx *ctx, + size_t key_nbytes, const void *data_key, const void *tweak_key); + + /* Set the tweak (sector number), the block within the sector zero. */ + int (*set_tweak)(const ccxts_ctx *ctx, ccxts_tweak *tweak, const void *iv); + + /* Encrypt blocks for a sector, clients must call set_tweak before calling + this function. Return a pointer to the tweak buffer */ + void *(*xts)(const ccxts_ctx *ctx, ccxts_tweak *tweak, + size_t nblocks, const void *in, void *out); + + const void *custom; + const void *custom1; +}; + +//7- GCM mode, statful +cc_aligned_struct(16) ccgcm_ctx; +#define CCMODE_GCM_DECRYPTOR 78647 +#define CCMODE_GCM_ENCRYPTOR 4073947 + +struct ccmode_gcm { + size_t size; /* first argument to ccgcm_ctx_decl(). */ + int encdec; //is it encrypt or decrypt object + size_t block_size; + int (*init)(const struct ccmode_gcm *gcm, ccgcm_ctx *ctx, + size_t key_nbytes, const void *key); + int (*set_iv)(ccgcm_ctx *ctx, size_t iv_nbytes, const void *iv); + int (*gmac)(ccgcm_ctx *ctx, size_t nbytes, const void *in); // could just be gcm with NULL out + int (*gcm)(ccgcm_ctx *ctx, size_t nbytes, const void *in, void *out); + int (*finalize)(ccgcm_ctx *key, size_t tag_nbytes, void *tag); + int (*reset)(ccgcm_ctx *ctx); + const void *custom; +}; + +//8- GCM mode, statful +cc_aligned_struct(16) ccccm_ctx; +cc_aligned_struct(16) ccccm_nonce; + +struct ccmode_ccm { + size_t size; /* first argument to ccccm_ctx_decl(). */ + size_t nonce_size; /* first argument to ccccm_nonce_decl(). */ + size_t block_size; + int (*init)(const struct ccmode_ccm *ccm, ccccm_ctx *ctx, + size_t key_len, const void *key); + int (*set_iv)(ccccm_ctx *ctx, ccccm_nonce *nonce_ctx, size_t nonce_len, const void *nonce, + size_t mac_size, size_t auth_len, size_t data_len); + int (*cbcmac)(ccccm_ctx *ctx, ccccm_nonce *nonce_ctx, size_t nbytes, const void *in); // could just be ccm with NULL out + int (*ccm)(ccccm_ctx *ctx, ccccm_nonce *nonce_ctx, size_t nbytes, const void *in, void *out); + int (*finalize)(ccccm_ctx *key, ccccm_nonce *nonce_ctx, void *mac); + int (*reset)(ccccm_ctx *key, ccccm_nonce *nonce_ctx); + const void *custom; +}; + + +/* OMAC mode. */ +cc_aligned_struct(16) ccomac_ctx; + +struct ccmode_omac { + size_t size; /* first argument to ccomac_ctx_decl(). */ + size_t block_size; + int (*init)(const struct ccmode_omac *omac, ccomac_ctx *ctx, + size_t tweak_len, size_t key_len, const void *key); + int (*omac)(ccomac_ctx *ctx, size_t nblocks, + const void *tweak, const void *in, void *out); + const void *custom; +}; + +#endif /* _CORECRYPTO_CCMODE_IMPL_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccmode_siv.h b/libraries/corecrypto/include/corecrypto/ccmode_siv.h new file mode 100644 index 0000000..1834c23 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccmode_siv.h @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCMODE_SIV_H_ +#define _CORECRYPTO_CCMODE_SIV_H_ + +#include +#include +#include + +#include + +/* This provide an implementation of SIV + as specified in https://tools.ietf.org/html/rfc5297 + also in http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/siv/siv.pdf + Counter Mode where IV is based on CMAC + */ + +cc_aligned_struct(16) ccsiv_ctx; + +struct ccmode_siv { + size_t size; /* first argument to ccsiv_ctx_decl(). */ + size_t block_size; + int (*init)(const struct ccmode_siv *siv, ccsiv_ctx *ctx, + size_t key_len, const uint8_t *key); + int (*set_nonce)(ccsiv_ctx *ctx, size_t nbytes, const uint8_t *in); // could just be ccm with NULL out + int (*auth)(ccsiv_ctx *ctx, size_t nbytes, const uint8_t *in); // could just be ccm with NULL out + int (*crypt)(ccsiv_ctx *ctx, size_t nbytes, const uint8_t *in, uint8_t *out); + int (*reset)(ccsiv_ctx *ctx); + const struct ccmode_cbc *cbc; + const struct ccmode_ctr *ctr; +}; + +#define ccsiv_ctx_decl(_size_, _name_) cc_ctx_decl(ccsiv_ctx, _size_, _name_) +#define ccsiv_ctx_clear(_size_, _name_) cc_clear(_size_, _name_) + +// Functions + +CC_INLINE size_t ccsiv_context_size(const struct ccmode_siv *mode) +{ + return mode->size; +} + +CC_INLINE size_t ccsiv_block_size(const struct ccmode_siv *mode) +{ + return mode->block_size; +} + +CC_INLINE size_t ccsiv_ciphertext_size(const struct ccmode_siv *mode, + size_t plaintext_size) +{ + return plaintext_size+mode->cbc->block_size; +} + +CC_INLINE size_t ccsiv_plaintext_size(const struct ccmode_siv *mode, + size_t ciphertext_size) +{ + if (ciphertext_sizecbc->block_size) { + return 0; // error + } + return ciphertext_size-mode->cbc->block_size; +} + +// Supported key sizes are 32, 48, 64 bytes +CC_INLINE int ccsiv_init(const struct ccmode_siv *mode, ccsiv_ctx *ctx, + size_t key_byte_len, const uint8_t *key) +{ + return mode->init(mode, ctx, key_byte_len, key); +} + +// Process nonce. it is actually just an authenticated data +CC_INLINE int ccsiv_set_nonce(const struct ccmode_siv *mode, ccsiv_ctx *ctx, + size_t nbytes, const uint8_t *in) +{ + return mode->set_nonce(ctx, nbytes, in); +} + +// Process authenticated data. Taken into account for authentication but not +// encrypted +CC_INLINE int ccsiv_aad(const struct ccmode_siv *mode, ccsiv_ctx *ctx, + size_t nbytes, const uint8_t *in) +{ + return mode->auth(ctx, nbytes, in); +} + +// Encryption data. Authenticated and encrypted. +// Encrypt/Decrypt can only be called once +CC_INLINE int ccsiv_crypt(const struct ccmode_siv *mode, ccsiv_ctx *ctx, + size_t nbytes, const uint8_t *in, uint8_t *out) +{ + return mode->crypt(ctx, nbytes, in, out); +} + +// Clear all context for reuse. +// Key is clear to avoid leaking it +CC_INLINE int ccsiv_reset(const struct ccmode_siv *mode, ccsiv_ctx *ctx) +{ + return mode->reset(ctx); +} + +// One shot with only one vector of adata +CC_INLINE int ccsiv_one_shot(const struct ccmode_siv *mode, + size_t key_len, const uint8_t *key, + unsigned nonce_nbytes, const uint8_t* nonce, + unsigned adata_nbytes, const uint8_t* adata, + size_t in_nbytes, const uint8_t *in, uint8_t *out) +{ + int rc; + ccsiv_ctx_decl(mode->size, ctx); + rc=mode->init(mode, ctx, key_len, key); + if (rc) {return rc;} + rc=mode->set_nonce(ctx, nonce_nbytes, nonce); + if (rc) {return rc;} + rc=mode->auth(ctx, adata_nbytes, adata); + if (rc) {return rc;} + rc=mode->crypt(ctx, in_nbytes, in, out); + if (rc) {return rc;} + ccsiv_ctx_clear(mode->size, ctx); + return rc; +} + +void ccmode_factory_siv_encrypt(struct ccmode_siv *siv, + const struct ccmode_cbc *cbc, + const struct ccmode_ctr *ctr); + +void ccmode_factory_siv_decrypt(struct ccmode_siv *siv, + const struct ccmode_cbc *cbc, + const struct ccmode_ctr *ctr); + + +#endif /* _CORECRYPTO_CCMODE_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccmode_siv_priv.h b/libraries/corecrypto/include/corecrypto/ccmode_siv_priv.h new file mode 100644 index 0000000..7608e6a --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccmode_siv_priv.h @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2015,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCMODE_SIV_PRIV_H_ +#define _CORECRYPTO_CCMODE_SIV_PRIV_H_ + +#include +#include +#include + +#include + +// Maximum size for the key is 512 +#define CCSIV_MAX_BLOCK_BYTESIZE 128/8 + +// Maximum size for the key is 512 +#define CCSIV_MAX_KEY_BYTESIZE 512/8 + +struct _ccmode_siv_ctx { + const struct ccmode_siv *siv; + size_t key_bytesize; + cc_unit state; + cc_unit k1[ccn_nof_size(CCSIV_MAX_KEY_BYTESIZE/2)]; // cmac key + cc_unit k2[ccn_nof_size(CCSIV_MAX_KEY_BYTESIZE/2)]; // ctr key + cc_unit block[ccn_nof_size(CCSIV_MAX_BLOCK_BYTESIZE)]; +}; + +int ccmode_siv_init(const struct ccmode_siv *siv, ccsiv_ctx *ctx, + size_t rawkey_byte_len, const uint8_t *rawkey); + +// Authentication of the adata +int ccmode_siv_auth(ccsiv_ctx *ctx, + size_t nbytes, const uint8_t *in); + +// Authentication of the last vector (the encrypted part) +int ccmode_siv_auth_last(ccsiv_ctx *ctx, + size_t nbytes, const uint8_t *in, uint8_t* V); + +int ccmode_siv_encrypt(ccsiv_ctx *ctx, + size_t nbytes, const uint8_t *in, uint8_t *out); + +int ccmode_siv_decrypt(ccsiv_ctx *ctx, + size_t nbytes, const uint8_t *in, uint8_t *out); + +int ccmode_siv_reset(ccsiv_ctx *ctx); + +/* Macros for accessing a CCMODE_SIV. + { + const struct ccmode_siv *siv; + uint8_t key[512/8]; + uint8_t d[512/8]; + cc_unit cmac_ctx[cbc->n]; + cc_unit ctr_ctx[ctr->n]; + } */ +#define _CCMODE_SIV_CTX(K) ((struct _ccmode_siv_ctx *)(K)) +#define _CCMODE_SIV_CBC_MODE(K) (_CCMODE_SIV_CTX(K)->siv->cbc) +#define _CCMODE_SIV_CTR_MODE(K) (_CCMODE_SIV_CTX(K)->siv->ctr) +#define _CCMODE_SIV_STATE(K) (_CCMODE_SIV_CTX(K)->state) +#define _CCMODE_SIV_KEYSIZE(K) (_CCMODE_SIV_CTX(K)->key_bytesize) +#define _CCMODE_SIV_K1(K) ((uint8_t *)_CCMODE_SIV_CTX(K)->k1) +#define _CCMODE_SIV_K2(K) ((uint8_t *)_CCMODE_SIV_CTX(K)->k2) +#define _CCMODE_SIV_D(K) ((uint8_t *)_CCMODE_SIV_CTX(K)->block) + + + + + +#endif /* _CORECRYPTO_CCMODE_SIV_PRIV_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccn.h b/libraries/corecrypto/include/corecrypto/ccn.h new file mode 100644 index 0000000..9cc442b --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccn.h @@ -0,0 +1,704 @@ +/* + * Copyright (c) 2010,2011,2012,2013,2014,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCN_H_ +#define _CORECRYPTO_CCN_H_ + +#include +#include +#include + +typedef uint8_t cc_byte; +typedef size_t cc_size; + +#if CCN_UNIT_SIZE == 8 +typedef uint64_t cc_unit; // 64 bit unit +typedef int64_t cc_int; +#define CCN_LOG2_BITS_PER_UNIT 6 // 2^6 = 64 bits +#define CC_UNIT_C(x) UINT64_C(x) + #if CCN_UINT128_SUPPORT_FOR_64BIT_ARCH + typedef unsigned cc_dunit __attribute__((mode(TI))); // 128 bit double width unit + typedef signed cc_dint __attribute__((mode(TI))); + #else + typedef struct cc_dunit { + uint64_t l; //do not change the order of the variables. cc_dunit must be little endian + uint64_t h; + } cc_dunit; + + typedef struct cc_dint { + uint64_t l; + uint64_t h; + } cc_dint; + #endif + +#elif CCN_UNIT_SIZE == 4 +typedef uint32_t cc_unit; // 32 bit unit +typedef uint64_t cc_dunit; // 64 bit double width unit +typedef int64_t cc_dint; +typedef int32_t cc_int; +#define CCN_LOG2_BITS_PER_UNIT 5 // 2^5 = 32 bits +#define CC_UNIT_C(x) UINT32_C(x) + +#elif CCN_UNIT_SIZE == 2 +typedef uint16_t cc_unit; // 16 bit unit +typedef uint32_t cc_dunit; // 32 bit double width unit +#define CCN_LOG2_BITS_PER_UNIT 4 // 2^4 = 16 bits +#define CC_UNIT_C(x) UINT16_C(x) + +#elif CCN_UNIT_SIZE == 1 +typedef uint8_t cc_unit; // 8 bit unit +typedef uint16_t cc_dunit; // 16 bit double width unit +#define CCN_LOG2_BITS_PER_UNIT 3 // 2^3 = 8 bits +#define CC_UNIT_C(x) UINT8_C(x) + +#else +#error invalid CCN_UNIT_SIZE +#endif + +// All mp types have units in little endian unit order. +typedef cc_unit *ccn_t; // n unit long mp +typedef cc_unit *ccnp1_t; // n + 1 unit long mp +typedef cc_unit *cc2n_t; // 2 * n unit long mp +typedef cc_unit *cc2np2_t; // 2 * n + 2 unit long mp +typedef const cc_unit *ccn_in_t; // n unit long mp +typedef const cc_unit *ccnp1_in_t; // n + 1 unit long mp +typedef const cc_unit *cc2n_in_t; // 2 * n unit long mp +typedef const cc_unit *cc2np2_in_t; // 2 * n + 2 unit long mp + +#define CCN_UNIT_BITS (sizeof(cc_unit) * 8) +#define CCN_UNIT_MASK ((cc_unit)~0) + +typedef struct { + cc_unit *start; // First cc_unit of the workspace + cc_unit *end; // address and beyond NOT TO BE TOUCHED +} cc_ws,*cc_ws_t; + +/* Conversions between n sizeof and bits */ + +/* Returns the sizeof a ccn vector of length _n_ units. */ +#define ccn_sizeof_n(_n_) (sizeof(cc_unit) * (_n_)) + +/* Returns the count (n) of a ccn vector that can represent _bits_. */ +#define ccn_nof(_bits_) (((_bits_) + CCN_UNIT_BITS - 1) >> CCN_LOG2_BITS_PER_UNIT) + +/* Returns the sizeof a ccn vector that can represent _bits_. */ +#define ccn_sizeof(_bits_) (ccn_sizeof_n(ccn_nof(_bits_))) + +/* Returns the count (n) of a ccn vector that can represent _size_ bytes. */ +#define ccn_nof_size(_size_) (((_size_) + CCN_UNIT_SIZE - 1) / CCN_UNIT_SIZE) + +/* Return the max number of bits a ccn vector of _n_ units can hold. */ +#define ccn_bitsof_n(_n_) ((_n_) * CCN_UNIT_BITS) + +/* Return the max number of bits a ccn vector of _size_ bytes can hold. */ +#define ccn_bitsof_size(_size_) ((_size_) * 8) + +/* Return the size of a ccn of size bytes in bytes. */ +#define ccn_sizeof_size(_size_) ccn_sizeof_n(ccn_nof_size(_size_)) + +/* Returns the value of bit _k_ of _ccn_, both are only evaluated once. */ +#define ccn_bit(_ccn_, _k_) ({__typeof__ (_k_) __k = (_k_); \ + 1 & ((_ccn_)[ __k >> CCN_LOG2_BITS_PER_UNIT] >> (__k & (CCN_UNIT_BITS - 1)));}) + +/* Set the value of bit _k_ of _ccn_ to the value _v_ */ +#define ccn_set_bit(_ccn_, _k_, _v_) ({__typeof__ (_k_) __k = (_k_); \ + if (_v_) \ + (_ccn_)[ __k >> CCN_LOG2_BITS_PER_UNIT] |= CC_UNIT_C(1) << (__k & (CCN_UNIT_BITS - 1)); \ + else \ + (_ccn_)[ __k >> CCN_LOG2_BITS_PER_UNIT] &= ~(CC_UNIT_C(1) << (__k & (CCN_UNIT_BITS - 1))); \ + }) + +/* Macros for making ccn constants. You must use list of CCN64_C() instances + separated by commas, with an optional smaller sized CCN32_C, CCN16_C, or + CCN8_C() instance at the end of the list, when making macros to declare + larger sized constants. */ +#define CCN8_C(a0) CC_UNIT_C(0x##a0) + +#if CCN_UNIT_SIZE >= 2 +#define CCN16_C(a1,a0) CC_UNIT_C(0x##a1##a0) +#define ccn16_v(a0) (a0) +#elif CCN_UNIT_SIZE == 1 +#define CCN16_C(a1,a0) CCN8_C(a0),CCN8_C(a1) +#define ccn16_v(a0) (a0 & UINT8_C(0xff)),(a0 >> 8) +#endif + +#if CCN_UNIT_SIZE >= 4 +#define CCN32_C(a3,a2,a1,a0) CC_UNIT_C(0x##a3##a2##a1##a0) +#define ccn32_v(a0) (a0) +#else +#define CCN32_C(a3,a2,a1,a0) CCN16_C(a1,a0),CCN16_C(a3,a2) +#define ccn32_v(a0) ccn16_v(a0 & UINT16_C(0xffff)),ccn16_v(a0 >> 16) +#endif + +#if CCN_UNIT_SIZE == 8 +#define CCN64_C(a7,a6,a5,a4,a3,a2,a1,a0) CC_UNIT_C(0x##a7##a6##a5##a4##a3##a2##a1##a0) +#define CCN40_C(a4,a3,a2,a1,a0) CC_UNIT_C(0x##a4##a3##a2##a1##a0) +#define ccn64_v(a0) (a0) +//#define ccn64_32(a1,a0) ((a1 << 32) | a0) +//#define ccn_uint64(a,i) (a[i]) +#else +#define CCN64_C(a7,a6,a5,a4,a3,a2,a1,a0) CCN32_C(a3,a2,a1,a0),CCN32_C(a7,a6,a5,a4) +#define CCN40_C(a4,a3,a2,a1,a0) CCN32_C(a3,a2,a1,a0),CCN8_C(a4) +#define ccn64_v(a0) ccn32_v((uint64_t)a0 & UINT32_C(0xffffffff)),ccn32_v((uint64_t)a0 >> 32) +//#define ccn64_32(a1,a0) ccn32_v(a0),ccn32_v(a1) +//#define ccn_uint64(a,i) ((uint64_t)ccn_uint32(a, i << 1 + 1) << 32 | (uint64_t)ccn_uint32(a, i << 1)) +#endif + +/* Macro's for reading uint32_t and uint64_t from ccns, the index is in 32 or + 64 bit units respectively. */ +#if CCN_UNIT_SIZE == 8 +/* #define ccn_uint16(a,i) ((i & 3) == 3 ? ((uint16_t)(a[i >> 2] >> 48)) : \ + (i & 3) == 2 ? ((uint16_t)(a[i >> 2] >> 32) & UINT16_C(0xffff)) : \ + (i & 3) == 1 ? ((uint16_t)(a[i >> 2] >> 16) & UINT16_C(0xffff)) : \ + ((uint16_t)(a[i >> 1] & UINT16_C(0xffff)))) +*/ +//#define ccn_uint32(a,i) (i & 1 ? ((uint32_t)(a[i >> 1] >> 32)) : ((uint32_t)(a[i >> 1] & UINT32_C(0xffffffff)))) +#elif CCN_UNIT_SIZE == 4 +//#define ccn16_v(a0) (a0) +//#define ccn32_v(a0) (a0) +//#define ccn_uint16(a,i) (i & 1 ? ((uint16_t)(a[i >> 1] >> 16)) : ((uint16_t)(a[i >> 1] & UINT16_C(0xffff)))) +//#define ccn_uint32(a,i) (a[i]) +#elif CCN_UNIT_SIZE == 2 +//#define ccn16_v(a0) (a0) +//#define ccn32_v(a0,a1) (a1,a0) +//#define ccn_uint16(a,i) (a[i]) +//#define ccn_uint32(a,i) (((uint32_t)a[i << 1 + 1]) << 16 | (uint32_t)a[i << 1])) +#elif CCN_UNIT_SIZE == 1 +//#define ccn16_v(a0) (a0 & UINT8_C(0xff)),(a0 >> 8) +//#define ccn_uint16(a,i) ((uint16_t)((a[i << 1 + 1] << 8) | a[i << 1])) +//#define ccn_uint32(a,i) ((uint32_t)ccn_uint16(a, i << 1 + 1) << 16 | (uint32_t)ccn_uint16(a, i << 1)) +#endif + +/* Macro's for reading uint32_t and uint64_t from ccns, the index is in 32 or + 64 bit units respectively. */ +#if CCN_UNIT_SIZE == 8 + +#define ccn64_32(a1,a0) (((const cc_unit)a1) << 32 | ((const cc_unit)a0)) +#define ccn32_32(a0) a0 +#if __LITTLE_ENDIAN__ +#define ccn32_32_parse(p,i) (((const uint32_t *)p)[i]) +#else +#define ccn32_32_parse(p,i) (((const uint32_t *)p)[i^1]) +#endif +#define ccn32_32_null 0 + +#define ccn64_64(a0) a0 +#define ccn64_64_parse(p,i) p[i] +#define ccn64_64_null 0 + +#elif CCN_UNIT_SIZE == 4 + +#define ccn32_32(a0) a0 +#define ccn32_32_parse(p,i) p[i] +#define ccn32_32_null 0 +#define ccn64_32(a1,a0) ccn32_32(a0),ccn32_32(a1) + +#define ccn64_64(a1,a0) a0,a1 +#define ccn64_64_parse(p,i) p[1+(i<<1)],p[i<<1] +#define ccn64_64_null 0,0 + +#elif CCN_UNIT_SIZE == 2 + +#define ccn32_32(a1,a0) a0,a1 +#define ccn32_32_parse(p,i) p[1+(i<<1)],p[i<<1] +#define ccn32_32_null 0,0 +#define ccn64_32(a3,a2,a1,a0) ccn32_32(a1,a0),ccn32_32(a3,a2) + +#define ccn64_64(a3,a2,a1,a0) a0,a1,a2,a3 +#define ccn64_64_parse(p,i) p[3+(i<<2)],p[2+(i<<2)],p[1+(i<<2)],p[i<<2] +#define ccn64_64_null 0,0,0,0 + +#elif CCN_UNIT_SIZE == 1 + +#define ccn32_32(a3,a2,a1,a0) a0,a1,a2,a3 +#define ccn32_32_parse(p,i) p[3+(i<<2)],p[2+(i<<2)],p[1+(i<<2)],p[i<<2] +#define ccn32_32_null 0,0,0,0 +#define ccn64_32(a7,a6,a5,a4,a3,a2,a1,a0) ccn32_32(a3,a2,a1,a0),ccn32_32(a7,a6,a5,a4) + +#define ccn64_64(a7,a6,a5,a4,a3,a2,a1,a0) a0,a1,a2,a3,a4,a5,a6,a7 +#define ccn64_64_parse(p,i) p[7+(i<<3)],p[6+(i<<3)],p[5+(i<<3)],p[4+(i<<3)],p[3+(i<<3)],p[2+(i<<3)],p[1+(i<<3)],p[i<<3] +#define ccn64_64_null 0,0,0,0,0,0,0,0 + +#endif + + +/* Macros to construct fixed size ccn arrays from 64 or 32 bit quantities. */ +#define ccn192_64(a2,a1,a0) ccn64_64(a0),ccn64_64(a1),ccn64_64(a2) +#define ccn224_32(a6,a5,a4,a3,a2,a1,a0) ccn64_32(a1,a0),ccn64_32(a3,a2),ccn64_32(a5,a4),ccn32_32(a6) +#define ccn256_32(a7,a6,a5,a4,a3,a2,a1,a0) ccn64_32(a1,a0),ccn64_32(a3,a2),ccn64_32(a5,a4),ccn64_32(a7,a6) +#define ccn384_32(a11,a10,a9,a8,a7,a6,a5,a4,a3,a2,a1,a0) ccn64_32(a1,a0),ccn64_32(a3,a2),ccn64_32(a5,a4),ccn64_32(a7,a6),ccn64_32(a9,a8),ccn64_32(a11,a10) + + +#define CCN192_C(c7,c6,c5,c4,c3,c2,c1,c0,b7,b6,b5,b4,b3,b2,b1,b0,a7,a6,a5,a4,a3,a2,a1,a0) \ + CCN64_C(a7,a6,a5,a4,a3,a2,a1,a0),\ + CCN64_C(b7,b6,b5,b4,b3,b2,b1,b0),\ + CCN64_C(c7,c6,c5,c4,c3,c2,c1,c0) + +#define CCN200_C(d0,c7,c6,c5,c4,c3,c2,c1,c0,b7,b6,b5,b4,b3,b2,b1,b0,a7,a6,a5,a4,a3,a2,a1,a0) \ + CCN192_C(c7,c6,c5,c4,c3,c2,c1,c0,b7,b6,b5,b4,b3,b2,b1,b0,a7,a6,a5,a4,a3,a2,a1,a0),\ + CCN8_C(d0) + +#define CCN224_C(d3,d2,d1,d0,c7,c6,c5,c4,c3,c2,c1,c0,b7,b6,b5,b4,b3,b2,b1,b0,a7,a6,a5,a4,a3,a2,a1,a0) \ + CCN192_C(c7,c6,c5,c4,c3,c2,c1,c0,b7,b6,b5,b4,b3,b2,b1,b0,a7,a6,a5,a4,a3,a2,a1,a0),\ + CCN32_C(d3,d2,d1,d0) + +#define CCN232_C(d4,d3,d2,d1,d0,c7,c6,c5,c4,c3,c2,c1,c0,b7,b6,b5,b4,b3,b2,b1,b0,a7,a6,a5,a4,a3,a2,a1,a0) \ + CCN192_C(c7,c6,c5,c4,c3,c2,c1,c0,b7,b6,b5,b4,b3,b2,b1,b0,a7,a6,a5,a4,a3,a2,a1,a0),\ + CCN40_C(d4,d3,d2,d1,d0) + +#define CCN256_C(d7,d6,d5,d4,d3,d2,d1,d0,c7,c6,c5,c4,c3,c2,c1,c0,b7,b6,b5,b4,b3,b2,b1,b0,a7,a6,a5,a4,a3,a2,a1,a0) \ + CCN192_C(c7,c6,c5,c4,c3,c2,c1,c0,b7,b6,b5,b4,b3,b2,b1,b0,a7,a6,a5,a4,a3,a2,a1,a0),\ + CCN64_C(d7,d6,d5,d4,d3,d2,d1,d0) + +#define CCN264_C(e0,d7,d6,d5,d4,d3,d2,d1,d0,c7,c6,c5,c4,c3,c2,c1,c0,b7,b6,b5,b4,b3,b2,b1,b0,a7,a6,a5,a4,a3,a2,a1,a0) \ + CCN256_C(d7,d6,d5,d4,d3,d2,d1,d0,c7,c6,c5,c4,c3,c2,c1,c0,b7,b6,b5,b4,b3,b2,b1,b0,a7,a6,a5,a4,a3,a2,a1,a0),\ + CCN8_C(e0) + +#define CCN384_C(f7,f6,f5,f4,f3,f2,f1,f0,e7,e6,e5,e4,e3,e2,e1,e0,d7,d6,d5,d4,d3,d2,d1,d0,c7,c6,c5,c4,c3,c2,c1,c0,b7,b6,b5,b4,b3,b2,b1,b0,a7,a6,a5,a4,a3,a2,a1,a0) \ + CCN256_C(d7,d6,d5,d4,d3,d2,d1,d0,c7,c6,c5,c4,c3,c2,c1,c0,b7,b6,b5,b4,b3,b2,b1,b0,a7,a6,a5,a4,a3,a2,a1,a0),\ + CCN64_C(e7,e6,e5,e4,e3,e2,e1,e0),\ + CCN64_C(f7,f6,f5,f4,f3,f2,f1,f0) + +#define CCN392_C(g0,f7,f6,f5,f4,f3,f2,f1,f0,e7,e6,e5,e4,e3,e2,e1,e0,d7,d6,d5,d4,d3,d2,d1,d0,c7,c6,c5,c4,c3,c2,c1,c0,b7,b6,b5,b4,b3,b2,b1,b0,a7,a6,a5,a4,a3,a2,a1,a0) \ + CCN384_C(f7,f6,f5,f4,f3,f2,f1,f0,e7,e6,e5,e4,e3,e2,e1,e0,d7,d6,d5,d4,d3,d2,d1,d0,c7,c6,c5,c4,c3,c2,c1,c0,b7,b6,b5,b4,b3,b2,b1,b0,a7,a6,a5,a4,a3,a2,a1,a0),\ + CCN8_C(g0) + +#define CCN528_C(i1,i0,h7,h6,h5,h4,h3,h2,h1,h0,g7,g6,g5,g4,g3,g2,g1,g0,f7,f6,f5,f4,f3,f2,f1,f0,e7,e6,e5,e4,e3,e2,e1,e0,d7,d6,d5,d4,d3,d2,d1,d0,c7,c6,c5,c4,c3,c2,c1,c0,b7,b6,b5,b4,b3,b2,b1,b0,a7,a6,a5,a4,a3,a2,a1,a0) \ + CCN256_C(d7,d6,d5,d4,d3,d2,d1,d0,c7,c6,c5,c4,c3,c2,c1,c0,b7,b6,b5,b4,b3,b2,b1,b0,a7,a6,a5,a4,a3,a2,a1,a0),\ + CCN256_C(h7,h6,h5,h4,h3,h2,h1,h0,g7,g6,g5,g4,g3,g2,g1,g0,f7,f6,f5,f4,f3,f2,f1,f0,e7,e6,e5,e4,e3,e2,e1,e0),\ + CCN16_C(i1,i0) + +#define CCN192_N ccn_nof(192) +#define CCN224_N ccn_nof(224) +#define CCN256_N ccn_nof(256) +#define CCN384_N ccn_nof(384) +#define CCN512_N ccn_nof(512) +#define CCN521_N ccn_nof(521) + +/* Return the number of used units after stripping leading 0 units. */ +CC_PURE CC_NONNULL2 +cc_size ccn_n(cc_size n, const cc_unit *s); + +/* s >> k -> r return bits shifted out of least significant word in bits [0, n> + { N bit, scalar -> N bit } N = n * sizeof(cc_unit) * 8 + the _multi version doesn't return the shifted bits, but does support multiple + word shifts. */ +CC_NONNULL((2, 3)) +cc_unit ccn_shift_right(cc_size n, cc_unit *r, const cc_unit *s, size_t k); +CC_NONNULL((2, 3)) +void ccn_shift_right_multi(cc_size n, cc_unit *r,const cc_unit *s, size_t k); + +/* s << k -> r return bits shifted out of most significant word in bits [0, n> + { N bit, scalar -> N bit } N = n * sizeof(cc_unit) * 8 + the _multi version doesn't return the shifted bits, but does support multiple + word shifts */ +CC_NONNULL((2, 3)) +cc_unit ccn_shift_left(cc_size n, cc_unit *r, const cc_unit *s, size_t k); +CC_NONNULL((2, 3)) +void ccn_shift_left_multi(cc_size n, cc_unit *r, const cc_unit *s, size_t k); + +/* s == 0 -> return 0 | s > 0 -> return index (starting at 1) of most + significant bit that is 1. + { N bit } N = n * sizeof(cc_unit) * 8 */ +CC_NONNULL2 +size_t ccn_bitlen(cc_size n, const cc_unit *s); + +/* Returns the number of bits which are zero before the first one bit + counting from least to most significant bit. */ +CC_NONNULL2 +size_t ccn_trailing_zeros(cc_size n, const cc_unit *s); + +/* s == 0 -> return true | s != 0 -> return false + { N bit } N = n * sizeof(cc_unit) * 8 */ +#define ccn_is_zero(_n_, _s_) (!ccn_n(_n_, _s_)) + +/* s == 1 -> return true | s != 1 -> return false + { N bit } N = n * sizeof(cc_unit) * 8 */ +#define ccn_is_one(_n_, _s_) (ccn_n(_n_, _s_) == 1 && _s_[0] == 1) + +#define ccn_is_zero_or_one(_n_, _s_) (((_n_)==0) || ((ccn_n(_n_, _s_) <= 1) && (_s_[0] <= 1))) + +/* s < t -> return - 1 | s == t -> return 0 | s > t -> return 1 + { N bit, N bit -> int } N = n * sizeof(cc_unit) * 8 */ +CC_PURE CC_NONNULL((2, 3)) +int ccn_cmp(cc_size n, const cc_unit *s, const cc_unit *t); + +/* s < t -> return - 1 | s == t -> return 0 | s > t -> return 1 + { N bit, M bit -> int } N = ns * sizeof(cc_unit) * 8 M = nt * sizeof(cc_unit) * 8 */ +CC_INLINE CC_NONNULL((2, 4)) +int ccn_cmpn(cc_size ns, const cc_unit *s, + cc_size nt, const cc_unit *t) { + if (ns > nt) { + return 1; + } else if (ns < nt) { + return -1; + } + return ccn_cmp(ns, s, t); +} + +/* s - t -> r return 1 iff t > s + { N bit, N bit -> N bit } N = n * sizeof(cc_unit) * 8 */ +CC_NONNULL((2, 3, 4)) +cc_unit ccn_sub(cc_size n, cc_unit *r, const cc_unit *s, const cc_unit *t); + +/* |s - t| -> r return 1 iff t > s, 0 otherwise */ +cc_unit ccn_abs(cc_size n, cc_unit *r, const cc_unit *s, const cc_unit *t); + +/* s - v -> r return 1 iff v > s return 0 otherwise. + { N bit, sizeof(cc_unit) * 8 bit -> N bit } N = n * sizeof(cc_unit) * 8 */ +CC_NONNULL((2, 3)) +cc_unit ccn_sub1(cc_size n, cc_unit *r, const cc_unit *s, cc_unit v); + +/* s - t -> r return 1 iff t > s + { N bit, NT bit -> N bit NT <= N} N = n * sizeof(cc_unit) * 8 */ +CC_INLINE +CC_NONNULL((2, 3, 5)) +cc_unit ccn_subn(cc_size n, cc_unit *r, const cc_unit *s, + cc_size nt, const cc_unit *t) { + assert(n >= nt); + return ccn_sub1(n - nt, r + nt, s + nt, ccn_sub(nt, r, s, t)); +} + + +/* s + t -> r return carry if result doesn't fit in n bits. + { N bit, N bit -> N bit } N = n * sizeof(cc_unit) * 8 */ +CC_NONNULL((2, 3, 4)) +cc_unit ccn_add(cc_size n, cc_unit *r, const cc_unit *s, const cc_unit *t); + +/* s + v -> r return carry if result doesn't fit in n bits. + { N bit, sizeof(cc_unit) * 8 bit -> N bit } N = n * sizeof(cc_unit) * 8 */ +CC_NONNULL((2, 3)) +cc_unit ccn_add1(cc_size n, cc_unit *r, const cc_unit *s, cc_unit v); + +/* s + t -> r return carry if result doesn't fit in n bits + { N bit, NT bit -> N bit NT <= N} N = n * sizeof(cc_unit) * 8 */ +CC_INLINE +CC_NONNULL((2, 3, 5)) +cc_unit ccn_addn(cc_size n, cc_unit *r, const cc_unit *s, + cc_size nt, const cc_unit *t) { + assert(n >= nt); + return ccn_add1(n - nt, r + nt, s + nt, ccn_add(nt, r, s, t)); +} + + +CC_NONNULL((2, 3, 4)) +void ccn_lcm(cc_size n, cc_unit *r2n, const cc_unit *s, const cc_unit *t); + + +/* s * t -> r_2n r_2n must not overlap with s nor t + { n bit, n bit -> 2 * n bit } n = count * sizeof(cc_unit) * 8 + { N bit, N bit -> 2N bit } N = ccn_bitsof(n) */ +CC_NONNULL((2, 3, 4)) +void ccn_mul(cc_size n, cc_unit *r_2n, const cc_unit *s, const cc_unit *t); + +/* s * t -> r_2n r_2n must not overlap with s nor t + { n bit, n bit -> 2 * n bit } n = count * sizeof(cc_unit) * 8 + { N bit, N bit -> 2N bit } N = ccn_bitsof(n) + Provide a workspace for potential speedup */ +CC_NONNULL((1, 3, 4, 5)) +void ccn_mul_ws(cc_ws_t ws, cc_size count, cc_unit *r, const cc_unit *s, const cc_unit *t); + +/* s[0..n) * v -> r[0..n)+return value + { N bit, sizeof(cc_unit) * 8 bit -> N + sizeof(cc_unit) * 8 bit } N = n * sizeof(cc_unit) * 8 */ +CC_NONNULL((2, 3)) +cc_unit ccn_mul1(cc_size n, cc_unit *r, const cc_unit *s, const cc_unit v); + +/* s[0..n) * v + r[0..n) -> r[0..n)+return value + { N bit, sizeof(cc_unit) * 8 bit -> N + sizeof(cc_unit) * 8 bit } N = n * sizeof(cc_unit) * 8 */ +CC_NONNULL((2, 3)) +cc_unit ccn_addmul1(cc_size n, cc_unit *r, const cc_unit *s, const cc_unit v); + +#if 0 +/* a % d -> n + {2 * n bit, n bit -> n bit } n = count * sizeof(cc_unit) * 8 */ +CC_NONNULL((2, 3, 4)) +void ccn_mod(cc_size n, cc_unit *r, const cc_unit *a_2n, const cc_unit *d); +#endif + +/* r = gcd(s, t). + N bit, N bit -> N bit */ +CC_NONNULL((2, 3, 4)) +void ccn_gcd(cc_size n, cc_unit *r, const cc_unit *s, const cc_unit *t); + +/* r = gcd(s, t). + N bit, N bit -> O bit */ +CC_NONNULL((2, 4, 6)) +void ccn_gcdn(cc_size rn, cc_unit *r, cc_size sn, const cc_unit *s, cc_size tn, const cc_unit *t); + +/* r = (data, len) treated as a big endian byte array, return -1 if data + doesn't fit in r, return 0 otherwise. */ +CC_NONNULL((2, 4)) +int ccn_read_uint(cc_size n, cc_unit *r, size_t data_size, const uint8_t *data); + +/* r = (data, len) treated as a big endian byte array, return -1 if data + doesn't fit in r, return 0 otherwise. + ccn_read_uint strips leading zeroes and doesn't care about sign. */ +#define ccn_read_int(n, r, data_size, data) ccn_read_uint(n, r, data_size, data) + +/* Return actual size in bytes needed to serialize s. */ +CC_PURE CC_NONNULL2 +size_t ccn_write_uint_size(cc_size n, const cc_unit *s); + +/* Serialize s, to out. + First byte of byte stream is the m.s. byte of s, + regardless of the size of cc_unit. + + No assumption is made about the alignment of out. + + The out_size argument should be the value returned from ccn_write_uint_size, + and is also the exact number of bytes this function will write to out. + If out_size if less than the value returned by ccn_write_uint_size, only the + first out_size non-zero most significant octets of s will be written. */ +CC_NONNULL((2, 4)) +void ccn_write_uint(cc_size n, const cc_unit *s, size_t out_size, void *out); + + +CC_INLINE CC_NONNULL((2, 4)) +cc_size ccn_write_uint_padded(cc_size n, const cc_unit* s, size_t out_size, uint8_t* to) +{ + size_t bytesInKey = ccn_write_uint_size(n, s); + cc_size offset = (out_size > bytesInKey) ? out_size - bytesInKey : 0; + + cc_zero(offset, to); + ccn_write_uint(n, s, out_size - offset, to + offset); + + return offset; +} + + +/* Return actual size in bytes needed to serialize s as int + (adding leading zero if high bit is set). */ +CC_PURE CC_NONNULL2 +size_t ccn_write_int_size(cc_size n, const cc_unit *s); + +/* Serialize s, to out. + First byte of byte stream is the m.s. byte of s, + regardless of the size of cc_unit. + + No assumption is made about the alignment of out. + + The out_size argument should be the value returned from ccn_write_int_size, + and is also the exact number of bytes this function will write to out. + If out_size if less than the value returned by ccn_write_int_size, only the + first out_size non-zero most significant octets of s will be written. */ +CC_NONNULL((2, 4)) +void ccn_write_int(cc_size n, const cc_unit *s, size_t out_size, void *out); + +#if CCN_DEDICATED_SQR + +/* s^2 -> r + { n bit -> 2 * n bit } */ +CC_NONNULL((2, 3)) +void ccn_sqr(cc_size n, cc_unit *r, const cc_unit *s); + +/* s^2 -> r + { n bit -> 2 * n bit } */ +CC_NONNULL((1, 3, 4)) +void ccn_sqr_ws(cc_ws_t ws, cc_size n, cc_unit *r, const cc_unit *s); + +#else + +/* s^2 -> r + { n bit -> 2 * n bit } */ +CC_INLINE CC_NONNULL((2, 3)) +void ccn_sqr(cc_size n, cc_unit *r, const cc_unit *s) { + ccn_mul(n, r, s, s); +} + +/* s^2 -> r + { n bit -> 2 * n bit } */ +CC_INLINE CC_NONNULL((2, 3, 4)) +void ccn_sqr_ws(cc_ws_t ws, cc_size n, cc_unit *r, const cc_unit *s) { + ccn_mul_ws(ws, n, r, s, s); +} + +#endif + +/* s -> r + { n bit -> n bit } */ +CC_NONNULL((2, 3)) +void ccn_set(cc_size n, cc_unit *r, const cc_unit *s); + +CC_INLINE CC_NONNULL2 +void ccn_zero(cc_size n, cc_unit *r) { + cc_zero(ccn_sizeof_n(n),r); +} + +CC_INLINE CC_NONNULL2 +void ccn_clear(cc_size n, cc_unit *r) { + cc_clear(ccn_sizeof_n(n),r); +} + +CC_NONNULL2 +void ccn_zero_multi(cc_size n, cc_unit *r, ...); + +CC_INLINE CC_NONNULL2 +void ccn_seti(cc_size n, cc_unit *r, cc_unit v) { + /* assert(n > 0); */ + r[0] = v; + ccn_zero(n - 1, r + 1); +} + +CC_INLINE CC_NONNULL((2, 4)) +void ccn_setn(cc_size n, cc_unit *r, const cc_size s_size, const cc_unit *s) { + /* FIXME: assert not available in kernel. + assert(n > 0); + assert(s_size > 0); + assert(s_size <= n); + */ + ccn_set(s_size, r, s); + ccn_zero(n - s_size, r + s_size); +} + +#define CC_SWAP_HOST_BIG_64(x) \ + ((uint64_t)((((uint64_t)(x) & 0xff00000000000000ULL) >> 56) | \ + (((uint64_t)(x) & 0x00ff000000000000ULL) >> 40) | \ + (((uint64_t)(x) & 0x0000ff0000000000ULL) >> 24) | \ + (((uint64_t)(x) & 0x000000ff00000000ULL) >> 8) | \ + (((uint64_t)(x) & 0x00000000ff000000ULL) << 8) | \ + (((uint64_t)(x) & 0x0000000000ff0000ULL) << 24) | \ + (((uint64_t)(x) & 0x000000000000ff00ULL) << 40) | \ + (((uint64_t)(x) & 0x00000000000000ffULL) << 56))) +#define CC_SWAP_HOST_BIG_32(x) \ + ((((x) & 0xff000000) >> 24) | \ + (((x) & 0x00ff0000) >> 8) | \ + (((x) & 0x0000ff00) << 8) | \ + (((x) & 0x000000ff) << 24)) +#define CC_SWAP_HOST_BIG_16(x) \ + ((((x) & 0xff00) >> 8) | \ + (((x) & 0x00ff) << 8)) + +/* This should probably move if we move ccn_swap out of line. */ +#if CCN_UNIT_SIZE == 8 +#define CC_UNIT_TO_BIG(x) CC_SWAP_HOST_BIG_64(x) +#elif CCN_UNIT_SIZE == 4 +#define CC_UNIT_TO_BIG(x) CC_SWAP_HOST_BIG_32(x) +#elif CCN_UNIT_SIZE == 2 +#define CC_UNIT_TO_BIG(x) CC_SWAP_HOST_BIG_16(x) +#elif CCN_UNIT_SIZE == 1 +#define CC_UNIT_TO_BIG(x) (x) +#else +#error unsupported CCN_UNIT_SIZE +#endif + +/* Swap units in r in place from cc_unit vector byte order to big endian byte order (or back). */ +CC_INLINE CC_NONNULL2 +void ccn_swap(cc_size n, cc_unit *r) { + cc_unit *e; + for (e = r + n - 1; r < e; ++r, --e) { + cc_unit t = CC_UNIT_TO_BIG(*r); + *r = CC_UNIT_TO_BIG(*e); + *e = t; + } + if (n & 1) + *r = CC_UNIT_TO_BIG(*r); +} + +CC_INLINE CC_NONNULL((2, 3, 4)) +void ccn_xor(cc_size n, cc_unit *r, const cc_unit *s, const cc_unit *t) { + while (n--) { + r[n] = s[n] ^ t[n]; + } +} + +/* Debugging */ +CC_NONNULL2 +void ccn_print(cc_size n, const cc_unit *s); +CC_NONNULL3 +void ccn_lprint(cc_size n, const char *label, const cc_unit *s); + +/* Forward declaration so we don't depend on ccrng.h. */ +struct ccrng_state; + +#if 0 +CC_INLINE CC_NONNULL((2, 3)) +int ccn_random(cc_size n, cc_unit *r, struct ccrng_state *rng) { + return (RNG)->generate((RNG), ccn_sizeof_n(n), (unsigned char *)r); +} +#else +#define ccn_random(_n_,_r_,_ccrng_ctx_) \ + ccrng_generate(_ccrng_ctx_, ccn_sizeof_n(_n_), (unsigned char *)_r_) +#endif + +/* Make a ccn of size ccn_nof(nbits) units with up to nbits sized random value. */ +CC_NONNULL((2, 3)) +int ccn_random_bits(cc_size nbits, cc_unit *r, struct ccrng_state *rng); + +/*! + @brief ccn_make_recip(cc_size nd, cc_unit *recip, const cc_unit *d) computes the reciprocal of d: recip = 2^2b/d where b=bitlen(d) + + @param nd length of array d + @param recip returned reciprocal of size nd+1 + @param d input number d +*/ +CC_NONNULL((2, 3)) +int ccn_make_recip(cc_size nd, cc_unit *recip, const cc_unit *d); + +CC_NONNULL((6, 8)) +int ccn_div_euclid(cc_size nq, cc_unit *q, cc_size nr, cc_unit *r, cc_size na, const cc_unit *a, cc_size nd, const cc_unit *d); + +#define ccn_div(nq, q, na, a, nd, d) ccn_div_euclid(nq, q, 0, NULL, na, a, nd, d) +#define ccn_mod(nr, r, na, a, nd, d) ccn_div_euclid(0 , NULL, nr, r, na, a, nd, d) + +#endif /* _CORECRYPTO_CCN_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccn_priv.h b/libraries/corecrypto/include/corecrypto/ccn_priv.h new file mode 100644 index 0000000..6f1b0bc --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccn_priv.h @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2014,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef corecrypto_ccn_priv_h +#define corecrypto_ccn_priv_h + +#include +#include +#include + +#define CCN_MUL_WS_WORKSPACE_N(n) (4*((n)+1)) + +#if CCN_DEDICATED_SQR +#define CCN_SQR_WS_WORKSPACE_N(n) (2*(n)) +#else +#define CCN_SQR_WS_WORKSPACE_N(n) CCN_MUL_WS_WORKSPACE_N((n)) +#endif + +// Same ccn_make_recip, takes a ws +//#define CCN_MAKE_RECIP_WORKSPACE_SIZE(n) (3*(n)) /* shift sub */ +#define CCN_MAKE_RECIP_WORKSPACE_SIZE(n) (7*n+CCN_MUL_WS_WORKSPACE_N(n+1)) /* newtonraphson */ +void ccn_make_recip_ws(cc_ws_t ws, cc_size nd, cc_unit *recip, const cc_unit *d); + +// Same ccn_div_euclid, takes a ws +//#define CCN_DIV_EUCLID_WORKSPACE_SIZE(na,nd) (nd+1 + CC_MAX(CCN_MAKE_RECIP_WORKSPACE_SIZE(nd),CCN_DIV_USE_RECIP_WORKSPACE_SIZE(na,nd))) +#define CCN_DIV_EUCLID_WORKSPACE_SIZE(na,nd) (nd+1 + 4+CCN_DIV_USE_RECIP_WORKSPACE_SIZE(na,nd)) +int ccn_div_euclid_ws(cc_ws_t ws, cc_size nq, cc_unit *q, cc_size nr, cc_unit *r, cc_size na, const cc_unit *a, cc_size nd, const cc_unit *d); + +/*! + @brief ccn_div_use_recip(nq, q, nr, r, na, a, nd, d) computes q=a/d and r=a%d + @discussion q and rcan be NULL. Reads na from a and nd from d. Writes nq in q and nr in r. nq and nr must be large enough to accomodate results, otherwise error is retuned. Execution time depends on the size of a. Computation is perfomed on of fixedsize and the leadig zeros of a of q are are also used in the computation. + @param nq length of array q that hold the quotients. The maximum length of quotient is the actual length of dividend a + @param q returned quotient. If nq is larger than needed, it is filled with leading zeros. If it is smaller, error is returned. q can be set to NULL, if not needed. + @param nr length of array r that hold the remainder. The maximum length of remainder is the actual length of divisor d + @param r returned remainder. If nr is larger than needed, it is filled with leading zeros. Ifi is smaller error is returned. r can be set to NULL if not required. + @param na length of dividend. Dividend may have leading zeros. + @param a input Dividend + @param nd length of input divisor. Divisor may have leading zeros. + @param d input Divisor + @param recip_d The reciprocal of d, of length nd+1. + + @return returns 0 if successful, negative of error. + */ +CC_NONNULL((7, 9, 10)) +#define CCN_DIV_USE_RECIP_WORKSPACE_SIZE(na,nd) (6*(CC_MAX(2*nd,na)) + 4 + na) +int ccn_div_use_recip_ws(cc_ws_t ws, cc_size nq, cc_unit *q, cc_size nr, cc_unit *r, cc_size na, const cc_unit *a, cc_size nd, const cc_unit *d, const cc_unit *recip_d); + + +/*! + @brief ccn_make_recip_newtonraphson(cc_size nd, cc_unit *recip, const cc_unit *d) computes the reciprocal of d: recip = 2^2b/d where b=bitlen(d) + @discussion This use the NewtonRaphson method. + @param nd length of array d + @param recip returned reciprocal of size nd+1 + @param d input integer + */ + +CC_NONNULL((3, 4)) +void ccn_make_recip_newtonraphson(cc_ws_t ws, cc_size nd, cc_unit *recip, const cc_unit *d); + + +/*! + @brief ccn_make_recip_shift_sub(cc_size nd, cc_unit *recip, const cc_unit *d) computes the reciprocal of d: recip = 2^2b/d where b=bitlen(d) + @discussion This use the Shift/Sub (binary division) method. + @param nd length of array d + @param recip returned reciprocal of size nd+1 + @param d input integer + */ +CC_NONNULL((3, 4)) +void ccn_make_recip_shift_sub(cc_ws_t ws, cc_size nd, cc_unit *recip, const cc_unit *d); + + +#if defined(_WIN32) + #include + #include + #if (CCN_UNIT_SIZE==8) + CC_INLINE cc_size clz64_win( uint64_t value ) + { + DWORD leading_zero; + _BitScanReverse64( &leading_zero, value ); + return 63 - leading_zero; + } + #define clz_win(x) clz64_win(x) + #elif (CCN_UNIT_SIZE<=4) + CC_INLINE cc_size clz32_win( uint32_t value ) + { + DWORD leading_zero; + _BitScanReverse( &leading_zero, value ); + return 31 - leading_zero; + } + #define clz_win(x) clz32_win(x) + #endif +#else //for clang * GNU + #if (CCN_UNIT_SIZE==8) + #define CC_BUILTIN_CLZ __builtin_clzll + #elif (CCN_UNIT_SIZE<=4) + #define CC_BUILTIN_CLZ __builtin_clzl + #endif +#endif + +/* Counts leading zeros in data, under the assumption that data is non-zero. */ +CC_INLINE CC_CONST cc_size cc_clz_nonzero(cc_unit data) { + cc_assert(data != 0); +#if defined(_WIN32) + return clz_win(data); +#elif defined __x86_64__ || defined __i386__ + /* On i386 and x86_64, we know clang and GCC will generate BSR for + * __builtin_clzl. This instruction IS NOT constant time on all micro- + * architectures, but it *is* constant time on all micro-architectures that + * have been used by Apple, and we expect that to continue to be the case. + * + * When building for x86_64h with clang, this produces LZCNT, which is exactly + * what we want. */ + return CC_BUILTIN_CLZ(data); +#elif defined __arm64__ || defined __arm__ + /* On arm and arm64, we know that clang and GCC generate the constant-time CLZ + * instruction from __builtin_clzl( ). */ + return CC_BUILTIN_CLZ(data); +#elif defined __GNUC__ +# warning Using __builtin_clzl( ) on an unknown architecture; it may not be constant-time. + /* If you find yourself seeing this warning, file a radar for someone to + * check whether or not __builtin_clzl( ) generates a constant-time + * implementation on the architecture you are targeting. If it does, append + * the name of that architecture to the list of "safe" architectures above. */ + return CC_BUILTIN_CLZ(data); +#else + #warning Using a non-constant time implementation of cc_clz_nonzero( ). + /* If you find yourself seeing this warning, the function ccn_bitlen will not + * be constant time in the resulting build of corecrypto. Please file a radar + * for someone to implement a constant-time cc_clz_nonzero for your targeted + * architecture and compiler pair. */ + cc_unit mask = CC_UNIT_C(1) << (CCN_UNIT_BITS - 1); + size_t b = 0; + while ((data & mask >> b) == 0) b++; + return b; +#endif +} + +// perform division the division a/d, whne size n of a are d are the same. Returns remainder r and +// a cc_unit quotient. To be used only in xgcd. Exported here for test purpose only. +CC_NONNULL((2, 3, 4)) +cc_unit ccn_div_equal_size(cc_size n, cc_unit *r, const cc_unit *a, const cc_unit *d); + +// Conditionally swap the content of r0 and r1 buffers in constant time +// r0:r1 <- r1*k1 + s0*(k1-1) +void ccn_cond_swap(cc_size n, + int ki, + cc_unit *r0, + cc_unit *r1); + + +#endif diff --git a/libraries/corecrypto/include/corecrypto/ccnistkdf.h b/libraries/corecrypto/include/corecrypto/ccnistkdf.h new file mode 100644 index 0000000..ba8f55a --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccnistkdf.h @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2013,2015,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCNISTKDF_H_ +#define _CORECRYPTO_CCNISTKDF_H_ + +#include + +/*! @function ccnistkdf_ctr_hmac + + @abstract Perform a NIST SP800-108 KDF in Counter Mode with an HMAC PRF. + http://csrc.nist.gov/publications/nistpubs/800-108/sp800-108.pdf + @discussion This performs the transformation of password and salt through + an HMAC PRF of the callers slection (any Digest, typically SHA-256) + returning dkLen bytes containing the entropy. + + + @param prf Pseudo-random function to be used + @param kdkLen Key Derivation Key Length + @param kdk Key derivation key, a key that is used as an input to a key derivation function + (along with other input data) to derive keying material. + @param labelLen label length + @param label A string that identifies the purpose for the derived keying material, + which is encoded as a binary string. The encoding method for the Label + is defined in a larger context, for example, in the protocol that uses a KDF. + @param contextLen context length + @param context A binary string containing the information related to the derived keying material. + It may include identities of parties who are deriving and/or using the derived + keying material and, optionally, a nonce known by the parties who derive the keys. + @param dkLen Derived Key Length + @param dk buffer for the results of the KDF transformation, must be dkLen big + + */ + +int ccnistkdf_ctr_hmac(const struct ccdigest_info *di, + size_t kdkLen, const void *kdk, + size_t labelLen, const void *label, + size_t contextLen, const void *context, + size_t dkLen, void *dk); + +int ccnistkdf_ctr_hmac_fixed(const struct ccdigest_info *di, + size_t kdkLen, const void *kdk, + size_t fixedDataLen, const void *fixedData, + size_t dkLen, void *dk); + +/*! @function ccnistkdf_fb_hmac + + @abstract Perform a NIST SP800-108 KDF in Feedback Mode with an HMAC PRF. + http://csrc.nist.gov/publications/nistpubs/800-108/sp800-108.pdf + + @param di digest info defining the digest type to use in the PRF. + @param use_counter determines whether a counter will be used for each round through the PRF (0 = off). + @param kdkLen Key Derivation Key Length + @param kdk Key derivation key, a key that is used as an input to a key derivation function + (along with other input data) to derive keying material. + @param labelLen label length + @param label A string that identifies the purpose for the derived keying material, + which is encoded as a binary string. The encoding method for the Label + is defined in a larger context, for example, in the protocol that uses a KDF. + @param contextLen context length + @param context A binary string containing the information related to the derived keying material. + It may include identities of parties who are deriving and/or using the derived + keying material and, optionally, a nonce known by the parties who derive the keys. + @param ivLen iv length + @param iv A binary string that is used as an initial value in computing the first iteration in + the feedback mode. It can be either public or secret. It may be an empty string. + @param dkLen Derived Key Length + @param dk buffer for the results of the KDF transformation, must be dkLen big + + */ + +int ccnistkdf_fb_hmac(const struct ccdigest_info *di, int use_counter, + size_t kdkLen, const void *kdk, + size_t labelLen, const void *label, + size_t contextLen, const void *context, + size_t ivLen, const void *iv, + size_t dkLen, void *dk); + +int ccnistkdf_fb_hmac_fixed(CC_UNUSED const struct ccdigest_info *di, int use_counter, + CC_UNUSED size_t kdkLen, CC_UNUSED const void *kdk, + CC_UNUSED size_t fixedDataLen, CC_UNUSED const void *fixedData, + CC_UNUSED size_t ivLen, CC_UNUSED const void *iv, + CC_UNUSED size_t dkLen, CC_UNUSED void *dk); + +/*! @function ccnistkdf_dpi_hmac + + @abstract Perform a NIST SP800-108 KDF in Double Pipeline Iteration Mode with an HMAC PRF. + http://csrc.nist.gov/publications/nistpubs/800-108/sp800-108.pdf + + @param di digest info defining the digest type to use in the PRF. + @param kdkLen Key Derivation Key Length + @param kdk Key derivation key, a key that is used as an input to a key derivation function + (along with other input data) to derive keying material. + @param labelLen label length + @param label A string that identifies the purpose for the derived keying material, + which is encoded as a binary string. The encoding method for the Label + is defined in a larger context, for example, in the protocol that uses a KDF. + @param contextLen context length + @param context A binary string containing the information related to the derived keying material. + It may include identities of parties who are deriving and/or using the derived + keying material and, optionally, a nonce known by the parties who derive the keys. + @param dkLen Derived Key Length + @param dk buffer for the results of the KDF transformation, must be dkLen big + + */ + +int ccnistkdf_dpi_hmac(const struct ccdigest_info *di, + size_t kdkLen, const void *kdk, + size_t labelLen, const void *label, + size_t contextLen, const void *context, + size_t dkLen, void *dk); + + +#endif /* _CORECRYPTO_CCNISTKDF_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccpad.h b/libraries/corecrypto/include/corecrypto/ccpad.h new file mode 100644 index 0000000..07fa19e --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccpad.h @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2010,2011,2012,2014,2015,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCPAD_H_ +#define _CORECRYPTO_CCPAD_H_ + +#include + +// CTS1,2,3 are defined in Addendum to 800-38A, +// "Cipher Modes of Operation: Three Variants of Ciphertext Stealing for CBC Mode" +// CTS3 is also known as "CTS" in RFC3962 + +/* Contract is nbytes is at least 1 block + 1 byte. Also in is nbytes long out is nbytes long. */ +size_t ccpad_cts1_decrypt(const struct ccmode_cbc *cbc, cccbc_ctx *ctx, cccbc_iv *iv, + size_t nbytes, const void *in, void *out); + +/* Contract is nbytes is at least 1 block + 1 byte. Also in is nbytes long out is nbytes long. */ +size_t ccpad_cts1_encrypt(const struct ccmode_cbc *cbc, cccbc_ctx *ctx, cccbc_iv *iv, + size_t nbytes, const void *in, void *out); +/* Contract is nbytes is at least 1 block + 1 byte. Also in is nbytes long out is nbytes long. */ +size_t ccpad_cts2_decrypt(const struct ccmode_cbc *cbc, cccbc_ctx *ctx, cccbc_iv *iv, + size_t nbytes, const void *in, void *out); + +/* Contract is nbytes is at least 1 block + 1 byte. Also in is nbytes long out is nbytes long. */ +size_t ccpad_cts2_encrypt(const struct ccmode_cbc *cbc, cccbc_ctx *ctx, cccbc_iv *iv, + size_t nbytes, const void *in, void *out); +/* Contract is nbytes is at least 1 block + 1 byte. Also in is nbytes long out is nbytes long. */ +size_t ccpad_cts3_decrypt(const struct ccmode_cbc *cbc, cccbc_ctx *ctx, cccbc_iv *iv, + size_t nbytes, const void *in, void *out); + +/* Contract is nbytes is at least 1 block + 1 byte. Also in is nbytes long out is nbytes long. */ +size_t ccpad_cts3_encrypt(const struct ccmode_cbc *cbc, cccbc_ctx *ctx, cccbc_iv *iv, + size_t nbytes, const void *in, void *out); + +/* Contract is nbytes is non zero and a multiple of block_size. Furthermore in is nbytes long and out is nbytes long. Returns number of bytes written to out (technically we always write nbytes to out but the returned value is the number of bytes decrypted after removal of padding. + + To be safe we remove the entire offending block if the pkcs7 padding checks failed. However we purposely don't report the failure to decode the padding since any use of this error leads to potential security exploits. So currently there is no way to distinguish between a full block of padding and bad padding. + */ +size_t ccpad_pkcs7_decrypt(const struct ccmode_cbc *cbc, cccbc_ctx *ctx, cccbc_iv *iv, + size_t nbytes, const void *in, void *out); + +/* Contract is in is nbytes long. Writes (nbytes / block_size) + 1 times block_size to out. In other words, out must be nbytes rounded down to the closest multiple of block_size plus block_size bytes. */ +size_t ccpad_pkcs7_encrypt(const struct ccmode_cbc *cbc, cccbc_ctx *ctx, cccbc_iv *iv, + size_t nbytes, const void *in, void *out); + +/* Contract is 'don't break CommonCrypto functionality that allows PKCS7 padding with ECB mode'. This is basically the same routines above, without an IV, because calling + crypt with an IV makes ecb cry (and crash) */ + +size_t ccpad_pkcs7_ecb_decrypt(const struct ccmode_ecb *ecb, ccecb_ctx *ecb_key, + size_t nbytes, const void *in, void *out); + +size_t ccpad_pkcs7_ecb_encrypt(const struct ccmode_ecb *ecb, ccecb_ctx *ctx, + size_t nbytes, const void *in, void *out); + +/* Function common to ccpad_pkcs7_ecb_decrypt and ccpad_pkcs7_decrypt */ +size_t ccpad_pkcs7_decode(const size_t block_size, const uint8_t* last_block); + +/* Contract is nbytes is at least 1 block + 1 byte. Also in is nbytes long out is nbytes long. */ +size_t ccpad_xts_decrypt(const struct ccmode_xts *xts, ccxts_ctx *ctx, ccxts_tweak *tweak, + size_t nbytes, const void *in, void *out); + +/* Contract is nbytes is at least 1 block + 1 byte. Also in is nbytes long out is nbytes long. */ +void ccpad_xts_encrypt(const struct ccmode_xts *xts, ccxts_ctx *ctx, ccxts_tweak *tweak, + size_t nbytes, const void *in, void *out); + +#endif /* _CORECRYPTO_CCPAD_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccpbkdf2.h b/libraries/corecrypto/include/corecrypto/ccpbkdf2.h new file mode 100644 index 0000000..f8f09fa --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccpbkdf2.h @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2010,2011,2012,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCPBKDF2_H_ +#define _CORECRYPTO_CCPBKDF2_H_ + +#include + +/*! @function ccpbkdf2_hmac + @abstract perform a pbkdf2 using HMAC(di) for the PRF (see PKCS#5 for specification) + @discussion This performs a standard PBKDF2 transformation of password and salt through +an HMAC PRF of the callers slection (any Digest, typically SHA-1) returning dkLen bytes +containing the entropy. + +Considerations: +The salt used should be at least 8 bytes long. Each session should use it's own salt. +We use the password as the key for the HMAC and the running data as the text for the HMAC to make a PRF. +SHA-1 is a good hash to use for the core of the HMAC PRF. + @param di digest info defining the digest type to use in the PRF. + @param passwordLen amount of data to be fed in + @param password data to be fed into the PBKDF + @param saltLen length of the salt + @param salt salt to be used in pbkdf + @param iterations itrations to go + @param dkLen length of the results + @param dk buffer for the results of the PBKDF tranformation, must be dkLen big + + */ +int ccpbkdf2_hmac(const struct ccdigest_info *di, + size_t passwordLen, const void *password, + size_t saltLen, const void *salt, + size_t iterations, + size_t dkLen, void *dk); + +#endif /* _CORECRYPTO_CCPBKDF2_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccperf.h b/libraries/corecrypto/include/corecrypto/ccperf.h new file mode 100644 index 0000000..78038f2 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccperf.h @@ -0,0 +1,226 @@ +/* + * Copyright (c) 2010,2011,2013,2014,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCPERF_H_ +#define _CORECRYPTO_CCPERF_H_ + +#include +#include +#include "cctime.h" +#include "ccstats.h" +#include + +/** RNG instance used for perf tests */ +extern struct ccrng_state *rng; + + +struct ccperf_test { + const char *name; +}; + +/** perf family **/ + +enum ccperf_size_kind { + ccperf_size_bytes = 0, + ccperf_size_bits, + ccperf_size_iterations, + ccperf_size_units, +}; + +struct ccperf_family { + const char *name; + double(*func)(size_t loops, size_t size, const void *test); + struct ccperf_test **tests; + size_t ntests; + size_t *sizes; + size_t nsizes; + size_t loops; + enum ccperf_size_kind size_kind; + size_t nruns; + double run_time; +}; + +// Stop iterating after reaching timeout +#define RUN_TIMEOUT 10.0 + +#define numof(_x_) (sizeof(_x_)/sizeof(_x_[0])) + +/* Some macros used by family factories */ + +#define F_ARGS(_f) _f##_perf_tests +#define F_FUNC(_f) perf_##_f +#define F_SZ(_f) sizeof(F_ARGS(_f)[0]) +#define F_N(_f) numof(F_ARGS(_f)) + +#define F_GET_ALL(_family, _f) \ +do { \ + _family.name = #_f; \ + _family.func=F_FUNC(_f); \ + ccperf_family_select(&_family, F_N(_f), F_ARGS(_f), F_SZ(_f), argc, argv); \ + _family.loops=1; \ +} while(0) + +#define F_GET_ALL2(_family, _f, _func) \ +do { \ + _family.name = #_func; \ + _family.func=F_FUNC(_func); \ + ccperf_family_select(&_family, F_N(_f), F_ARGS(_f), F_SZ(_f), argc, argv); \ + _family.loops=1; \ +} while(0) + +#define F_SIZES(_family, _n, _first) ccperf_family_set_pot_sizes(&_family, (_n), (_first)) + +#define F_SIZES_FROM_ARRAY(_family, _const_array) {\ + _family.nsizes=sizeof(_const_array)/sizeof(_const_array[0]); \ + _family.sizes=malloc(sizeof(_const_array)); \ + memcpy(_family.sizes,_const_array,sizeof(_const_array));\ + } + +#define F_DEFINE(_fam, _oper, _kind, _n, _first) \ +static struct ccperf_family _fam##_##_oper##_family; \ +struct ccperf_family *ccperf_family_##_fam##_##_oper(int argc, char *argv[]) \ +{ \ + ccperf_family_##_fam##_once(argc, argv); \ + F_GET_ALL2(_fam##_##_oper##_family, _fam, _fam##_##_oper); \ + F_SIZES(_fam##_##_oper##_family, _n, _first); \ + _fam##_##_oper##_family.size_kind=_kind; \ + return &_fam##_##_oper##_family; \ +} + + +/* family factories */ +struct ccperf_family *ccperf_family_ccecb_init(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccecb_update(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccecb_one_shot(int argc, char *argv[]); +struct ccperf_family *ccperf_family_cccbc_init(int argc, char *argv[]); +struct ccperf_family *ccperf_family_cccbc_update(int argc, char *argv[]); +struct ccperf_family *ccperf_family_cccbc_one_shot(int argc, char *argv[]); +struct ccperf_family *ccperf_family_cccfb8_init(int argc, char *argv[]); +struct ccperf_family *ccperf_family_cccfb8_update(int argc, char *argv[]); +struct ccperf_family *ccperf_family_cccfb8_one_shot(int argc, char *argv[]); +struct ccperf_family *ccperf_family_cccfb_init(int argc, char *argv[]); +struct ccperf_family *ccperf_family_cccfb_update(int argc, char *argv[]); +struct ccperf_family *ccperf_family_cccfb_one_shot(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccctr_init(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccctr_update(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccctr_one_shot(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccgcm_init(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccgcm_gmac(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccgcm_set_iv(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccgcm_update(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccgcm_finalize(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccgcm_one_shot(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccccm_init(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccccm_cbcmac(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccccm_set_iv(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccccm_update(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccccm_finalize(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccccm_one_shot(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccofb_init(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccofb_update(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccofb_one_shot(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccomac_init(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccomac_update(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccomac_one_shot(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccxts_init(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccxts_set_tweak(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccxts_update(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccxts_one_shot(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccchacha_init(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccchacha_update(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccchacha_one_shot(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccpoly_init(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccpoly_update(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccpoly_one_shot(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccchachapoly_encrypt_and_sign(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccchachapoly_decrypt_and_verify(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccsiv_init(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccsiv_aad_or_nonce(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccsiv_one_shot(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccdigest(int argc, char *argv[]); +struct ccperf_family *ccperf_family_cchmac(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccn(int argc, char *argv[]); +struct ccperf_family *ccperf_family_cczp(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccec(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccec25519(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccrsa(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccpbkdf2(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccsrp(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccansikdf(int argc, char *argv[]); +struct ccperf_family *ccperf_family_cccmac(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccrng(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccdrbg(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccdh_generate_key(int argc, char *argv[]); +struct ccperf_family *ccperf_family_ccdh_compute_shared_secret(int argc, char *argv[]); +struct ccperf_family *ccperf_family_cczp_inv(int argc, char *argv[]); + +/* utility functions */ + +double histogram_sieve(struct ccperf_family *f, size_t size, const void *arg); + +void ccperf_family_select(struct ccperf_family *f, size_t ntests, void *tests, size_t testsz, int argc, char **argv); +void ccperf_family_set_pot_sizes(struct ccperf_family *f, size_t nsizes, size_t first); +int ccperf_main(int argc, char **argv); + +#endif /* _CORECRYPTO_CCPERF_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccprime.h b/libraries/corecrypto/include/corecrypto/ccprime.h new file mode 100644 index 0000000..b4c862a --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccprime.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ +#ifndef _CORECRYPTO_CCPRIME_H_ +#define _CORECRYPTO_CCPRIME_H_ + +#include + +/* Perform rabin miller primality testing on zp, return 1 if p is prime + return 0 otherwise. */ +CC_NONNULL_TU((1)) +int ccprime_rabin_miller(cczp_t zp, size_t mr_depth); + +/* Generate a random nbits sized prime in zp. zp will be guaranteed + relatively prime to e. */ +CC_NONNULL_TU((2)) CC_NONNULL((3, 4)) +int ccprime_generate(cc_size nbits, cczp_t zp, const cc_unit *e, + struct ccrng_state *rng); + + +#endif //_CORECRYPTO_CCPRIME_H_ diff --git a/libraries/corecrypto/include/corecrypto/ccrc2.h b/libraries/corecrypto/include/corecrypto/ccrc2.h new file mode 100644 index 0000000..8a45016 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccrc2.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2010,2012,2015,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCRC2_H_ +#define _CORECRYPTO_CCRC2_H_ + +#include + +#define CCRC2_BLOCK_SIZE 8 + +extern const struct ccmode_ecb ccrc2_ltc_ecb_decrypt_mode; +extern const struct ccmode_ecb ccrc2_ltc_ecb_encrypt_mode; + +const struct ccmode_ecb *ccrc2_ecb_decrypt_mode(void); +const struct ccmode_ecb *ccrc2_ecb_encrypt_mode(void); + +const struct ccmode_cbc *ccrc2_cbc_decrypt_mode(void); +const struct ccmode_cbc *ccrc2_cbc_encrypt_mode(void); + +const struct ccmode_cfb *ccrc2_cfb_decrypt_mode(void); +const struct ccmode_cfb *ccrc2_cfb_encrypt_mode(void); + +const struct ccmode_cfb8 *ccrc2_cfb8_decrypt_mode(void); +const struct ccmode_cfb8 *ccrc2_cfb8_encrypt_mode(void); + +const struct ccmode_ctr *ccrc2_ctr_crypt_mode(void); + +const struct ccmode_ofb *ccrc2_ofb_crypt_mode(void); + + +#endif /* _CORECRYPTO_CCRC2_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccrc4.h b/libraries/corecrypto/include/corecrypto/ccrc4.h new file mode 100644 index 0000000..1970ab8 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccrc4.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2010,2011,2012,2013,2014,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCRC4_H_ +#define _CORECRYPTO_CCRC4_H_ + +#include + +cc_aligned_struct(16) ccrc4_ctx; + +/* Declare a rc4 key named _name_. Pass the size field of a struct ccmode_ecb + for _size_. */ +#define ccrc4_ctx_decl(_size_, _name_) cc_ctx_decl(ccrc4_ctx, _size_, _name_) +#define ccrc4_ctx_clear(_size_, _name_) cc_clear(_size_, _name_) + +struct ccrc4_info { + size_t size; /* first argument to ccrc4_ctx_decl(). */ + void (*init)(ccrc4_ctx *ctx, size_t key_len, const void *key); + void (*crypt)(ccrc4_ctx *ctx, size_t nbytes, const void *in, void *out); +}; + + +const struct ccrc4_info *ccrc4(void); + +extern const struct ccrc4_info ccrc4_eay; + +struct ccrc4_vector { + size_t keylen; + const void *key; + size_t datalen; + const void *pt; + const void *ct; +}; + +int ccrc4_test(const struct ccrc4_info *rc4, const struct ccrc4_vector *v); + +#endif /* _CORECRYPTO_CCRC4_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccripemd.h b/libraries/corecrypto/include/corecrypto/ccripemd.h new file mode 100644 index 0000000..109d3d8 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccripemd.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2010,2015,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCRIPEMD_H_ +#define _CORECRYPTO_CCRIPEMD_H_ + +#include + +#define CCRMD_BLOCK_SIZE 64 + +#define CCRMD128_OUTPUT_SIZE 16 +#define CCRMD160_OUTPUT_SIZE 20 +#define CCRMD256_OUTPUT_SIZE 32 +#define CCRMD320_OUTPUT_SIZE 40 + +#define CCRMD128_STATE_SIZE 16 +#define CCRMD160_STATE_SIZE 20 +#define CCRMD256_STATE_SIZE 32 +#define CCRMD320_STATE_SIZE 40 + +extern const uint32_t ccrmd_initial_state[4]; + +extern const struct ccdigest_info ccrmd128_ltc_di; +extern const struct ccdigest_info ccrmd160_ltc_di; +extern const struct ccdigest_info ccrmd256_ltc_di; +extern const struct ccdigest_info ccrmd320_ltc_di; + +/* default is libtomcrypt */ +#define ccrmd128_di ccrmd128_ltc_di +#define ccrmd160_di ccrmd160_ltc_di +#define ccrmd256_di ccrmd256_ltc_di +#define ccrmd320_di ccrmd320_ltc_di + +#endif /* _CORECRYPTO_CCRIPEMD_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccrng.h b/libraries/corecrypto/include/corecrypto/ccrng.h new file mode 100644 index 0000000..f4d0232 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccrng.h @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2010,2013,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCRNG_H_ +#define _CORECRYPTO_CCRNG_H_ + +#include + +#define CCERR_DEVICE -100 +#define CCERR_INTERUPTS -101 +#define CCERR_CRYPTO_CONFIG -102 +#define CCERR_PERMS -103 +#define CCERR_PARAMETER -104 +#define CCERR_MEMORY -105 +#define CCERR_FILEDESC -106 +#define CCERR_OUT_OF_ENTROPY -107 +#define CCERR_INTERNAL -108 +#define CCERR_ATFORK -109 +#define CCERR_OVERFLOW -110 + +#define CCRNG_STATE_COMMON \ + int (*generate)(struct ccrng_state *rng, size_t outlen, void *out); + +/* default state structure. Do not instantiate, ccrng() returns a reference to this structure */ +struct ccrng_state { + CCRNG_STATE_COMMON +}; + +/*! + @function ccrng + @abstract initializes a AES-CTR mode cryptographic random number generator and returns the statically alocated rng object. + Getting a pointer to a ccrng has never been simpler! + Call this function, get an rng object and then pass the object to ccrng_generate() to generate randoms. + ccrng() may be called more than once. It returns pointer to the same object on all calls. + + @result a cryptographically secure random number generator or NULL if fails + + @discussion + - It is significantly faster than using the system /dev/random + - FIPS Compliant: NIST SP800-80A + FIPS 140-2 + - Seeded from the system entropy. + - Provides at least 128bit security if the system provide 2bit of entropy / byte. + - Entropy accumulation + - Backtracing resistance + - Prediction break with frequent (asynchronous) reseed + */ + +struct ccrng_state *ccrng(int *error); + +//call this macro with the rng argument set to output of the call to the ccrng() function +#define ccrng_generate(rng, outlen, out) ((rng)->generate((struct ccrng_state *)(rng), (outlen), (out))) + +#endif /* _CORECRYPTO_CCRNG_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccrng_drbg.h b/libraries/corecrypto/include/corecrypto/ccrng_drbg.h new file mode 100644 index 0000000..2123480 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccrng_drbg.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2014,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef corecrypto_ccrng_drbg_h +#define corecrypto_ccrng_drbg_h + +#include +#include + +struct ccrng_drbg_state { + CCRNG_STATE_COMMON + const struct ccdrbg_info *drbg_info; + struct ccdrbg_state *drbg_state; +}; + +// Setup a RNG based on a DRBG. +// Init calls the init from the DRBG +int ccrng_drbg_init(struct ccrng_drbg_state *rng, + const struct ccdrbg_info *drbg_info, + struct ccdrbg_state *drbg_state, + size_t length, const void *seed); + +// Reseed underlying DRBG +int ccrng_drbg_reseed(struct ccrng_drbg_state *rng, + size_t entropylen, const void *entropy, + size_t inlen, const void *in); + +// Clear the DRBG +void ccrng_drbg_done(struct ccrng_drbg_state *rng); + +#endif diff --git a/libraries/corecrypto/include/corecrypto/ccrng_ecfips_test.h b/libraries/corecrypto/include/corecrypto/ccrng_ecfips_test.h new file mode 100644 index 0000000..66dd465 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccrng_ecfips_test.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2014,2015,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +// To be used to set the scalar to a known fix value +// May fail if value is not as expect. + +#ifndef _CORECRYPTO_CCRNG_ECFIPS_TEST_H_ +#define _CORECRYPTO_CCRNG_ECFIPS_TEST_H_ + +#include +#include + +struct ccrng_ecfips_test_state { + CCRNG_STATE_COMMON + uint8_t *state; + size_t len; +}; + +int ccrng_ecfips_test_init(struct ccrng_ecfips_test_state *rng, + size_t len, uint8_t *sequence); + +#endif /* _CORECRYPTO_CCRNG_ECFIPS_TEST_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccrng_pbkdf2_prng.h b/libraries/corecrypto/include/corecrypto/ccrng_pbkdf2_prng.h new file mode 100644 index 0000000..742f1d6 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccrng_pbkdf2_prng.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2013,2014,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef corecrypto_ccrng_pbkdf2_prng_h +#define corecrypto_ccrng_pbkdf2_prng_h + +#include +#include +#include + + +#define CCRNG_PBKDF2_BUFFER 4096 + +// This RNG is limited to provide min("CCRNG_PBKDF2_BUFFER",maxbytes) of cumulated pseudo random bytes. +// Pseudo random bytes can be obtained with one or several "generate" +// When out of random, the generate function will persistently fail until a new initialization of the context is performed. + +struct ccrng_pbkdf2_prng_state { + CCRNG_STATE_COMMON + size_t random_buffer_size; + uint8_t random_buffer[CCRNG_PBKDF2_BUFFER]; +}; + + +int ccrng_pbkdf2_prng_init(struct ccrng_pbkdf2_prng_state *rng, size_t maxbytes, + size_t passwordLen, const void *password, + size_t saltLen, const void *salt, + size_t iterations); + +#endif diff --git a/libraries/corecrypto/include/corecrypto/ccrng_priv.h b/libraries/corecrypto/include/corecrypto/ccrng_priv.h new file mode 100644 index 0000000..201347d --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccrng_priv.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCRNG_PRIV_H_ +#define _CORECRYPTO_CCRNG_PRIV_H_ + +#include +#if CC_KERNEL + #include +#else + #include +#endif + +int cc_get_entropy(size_t entropy_size, void *entropy); + + +#endif /* _CORECRYPTO_CCRNG_PRIV_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccrng_rsafips_test.h b/libraries/corecrypto/include/corecrypto/ccrng_rsafips_test.h new file mode 100644 index 0000000..ac7a4c8 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccrng_rsafips_test.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2014,2015,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCRNG_RSAFIPS_TEST_H_ +#define _CORECRYPTO_CCRNG_RSAFIPS_TEST_H_ + +#include +#include + +struct ccrng_rsafips_test_state { + CCRNG_STATE_COMMON + uint8_t *state; + cc_size index; + cc_size r1Len; + const cc_unit *r1; + cc_size r2Len; + const cc_unit *r2; + cc_size XLen; + const cc_unit *X; +}; + +int +ccrng_rsafips_test_init(struct ccrng_rsafips_test_state *rng, + const cc_size r1Len, const cc_unit *r1, + const cc_size r2Len, const cc_unit *r2, + const cc_size XLen, const cc_unit *X); + +#endif /* _CORECRYPTO_CCRNG_RSAFIPS_TEST_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccrng_sequence.h b/libraries/corecrypto/include/corecrypto/ccrng_sequence.h new file mode 100644 index 0000000..acf2023 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccrng_sequence.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2013,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCRNG_SEQUENCE_H_ +#define _CORECRYPTO_CCRNG_SEQUENCE_H_ + +#include +#include + +struct ccrng_sequence_state { + CCRNG_STATE_COMMON + const uint8_t *state; + size_t len; +}; + +int ccrng_sequence_init(struct ccrng_sequence_state *rng, size_t len, const uint8_t *sequence); + +int ccrng_sequence_non_repeat_init(struct ccrng_sequence_state *rng, size_t len, const uint8_t *sequence); + +#endif /* _CORECRYPTO_CCRNG_SEQUENCE_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccrng_system.h b/libraries/corecrypto/include/corecrypto/ccrng_system.h new file mode 100644 index 0000000..1b88222 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccrng_system.h @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2010,2013,2014,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCRNG_SYSTEM_H_ +#define _CORECRYPTO_CCRNG_SYSTEM_H_ + +#include + +struct ccrng_system_state { + CCRNG_STATE_COMMON + int fd; +}; + +/*! + @function ccrng_system_init - DEPRECATED + @abstract Default ccrng. + Please transition to ccrng() which is easier to use and with provide the fastest, most secure option + + @param rng Structure containing the state of the RNG, must remain allocated as + long as the rng is used. + @result 0 iff successful + + @discussion + This RNG require call to "init" AND "done", otherwise it may leak a file descriptor. + */ + +// Initialize ccrng +// Deprecated, if you need a rng, just call the function ccrng() +int ccrng_system_init(struct ccrng_system_state *rng); + +// Close the system RNG +// Mandatory step to avoid leaking file descriptor +void ccrng_system_done(struct ccrng_system_state *rng); + +#endif /* _CORECRYPTO_CCRNG_SYSTEM_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccrng_test.h b/libraries/corecrypto/include/corecrypto/ccrng_test.h new file mode 100644 index 0000000..8f04c18 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccrng_test.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2011,2014,2015,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCRNG_TEST_H_ +#define _CORECRYPTO_CCRNG_TEST_H_ + +#include +#include + +struct ccrng_test_state { + CCRNG_STATE_COMMON + + struct ccdrbg_info drbg_info; + struct ccdrbg_state *drbg_state; +}; + +int ccrng_test_init(struct ccrng_test_state *rng, size_t length, const void *seed, + const char *personalization_string); + +void ccrng_test_done(struct ccrng_test_state *rng); + +#endif /* _CORECRYPTO_CCRNG_TEST_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccrsa.h b/libraries/corecrypto/include/corecrypto/ccrsa.h new file mode 100644 index 0000000..7d84b52 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccrsa.h @@ -0,0 +1,663 @@ +/* + * Copyright (c) 2010,2011,2012,2014,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCRSA_H_ +#define _CORECRYPTO_CCRSA_H_ + +#include +#include +#include +#include +#include + +// Apple does not generate keys of greater than 4096 bits +// This limit is relaxed to accommodate potential third-party consumers +#define CCRSA_KEYGEN_MAX_NBITS 8192 + +// Program error: buffer too small or encrypted message is too small +#define CCRSA_INVALID_INPUT -1 +// Invalid crypto configuration: Hash length versus RSA key size +#define CCRSA_INVALID_CONFIG -2 +// The data is invalid (we won't say more for security +#define CCRSA_DECRYPTION_ERROR -3 + +#define CCRSA_ENCODING_ERROR -4 +#define CCRSA_DECODING_ERROR -5 +#define CCRSA_SIGNATURE_GEN_ERROR -6 + +struct ccrsa_full_ctx { + __CCZP_ELEMENTS_DEFINITIONS(pb_) +} CC_ALIGNED(CCN_UNIT_SIZE); + +struct ccrsa_pub_ctx { + __CCZP_ELEMENTS_DEFINITIONS(pb_) +} CC_ALIGNED(CCN_UNIT_SIZE); + +struct ccrsa_priv_ctx { + __CCZP_ELEMENTS_DEFINITIONS(pv_) +} CC_ALIGNED(CCN_UNIT_SIZE); + + +#if CORECRYPTO_USE_TRANSPARENT_UNION + typedef union { + cczp_t zp; + struct ccrsa_pub_ctx* pub; + struct ccrsa_full_ctx *full; + } ccrsa_full_ctx_t __attribute__((transparent_union)); + typedef struct ccrsa_full_ctx ccrsa_full_ctx; + typedef struct ccrsa_priv_ctx ccrsa_priv_ctx; + + typedef union { + cczp_t zp; + ccrsa_priv_ctx *priv; + } ccrsa_priv_ctx_t __attribute__((transparent_union)); + + +typedef ccrsa_full_ctx_t ccrsa_pub_ctx_t; +typedef struct ccrsa_pub_ctx ccrsa_pub_ctx; + +#else + typedef struct ccrsa_full_ctx* ccrsa_full_ctx_t; + typedef struct ccrsa_pub_ctx* ccrsa_pub_ctx_t; + typedef struct ccrsa_priv_ctx* ccrsa_priv_ctx_t; +#endif + + + +/* + public key cczp d=e^-1 mod phi(m) priv key cczp priv key cczq dp, dq, qinv + | | | | | + | | | | | + +-------+------+-------+------++------++-------+------+---------++-------+------+---------++-------+-------+---------+ + | zm_hd | m[n] |mr[n+1]| e[n] || d[n] || zp_hd |p[n/2]|pr[n/2+1]|| zq_hd |q[n/2]|qr[n/2+1]||dp[n/2]|dq[n/2]|qinv[n/2]| + +-------+------+-------+------++------++-------+------+---------++-------+------+---------++-------+-------+---------+ + */ + + /* Return the size of an ccec_full_ctx where each ccn is _size_ bytes. Get _size_ through ccn_sizeof(nbits) */ + +/* Return the size of an ccec_full_ctx where each ccn is _size_ bytes. */ + +#define ccrsa_pub_ctx_size(_size_) (sizeof(struct cczp) + CCN_UNIT_SIZE + 3 * (_size_)) +#define ccrsa_priv_ctx_size(_size_) ((sizeof(struct cczp) + CCN_UNIT_SIZE) * 2 + 7 * ccn_sizeof(ccn_bitsof_size(_size_)/2 + 1)) +#define ccrsa_full_ctx_size(_size_) (ccrsa_pub_ctx_size(_size_) + _size_ + ccrsa_priv_ctx_size(_size_)) + +/* Declare a fully scheduled rsa key. Size is the size in bytes each ccn in + the key. For example to declare (on the stack or in a struct) a 1021 bit + rsa public key named foo use ccrsa_pub_ctx_decl(ccn_sizeof(1021), foo). + */ +#define ccrsa_full_ctx_decl(_size_, _name_) cc_ctx_decl(struct ccrsa_full_ctx, ccrsa_full_ctx_size(_size_), _name_) +#define ccrsa_full_ctx_clear(_size_, _name_) cc_clear(ccrsa_full_ctx_size(_size_), _name_) +#define ccrsa_pub_ctx_decl(_size_, _name_) cc_ctx_decl(struct ccrsa_pub_ctx, ccrsa_pub_ctx_size(_size_), _name_) +#define ccrsa_pub_ctx_clear(_size_, _name_) cc_clear(ccrsa_pub_ctx_size(_size_), _name_) + +// accessors to ccrsa full and public key fields. */ +// The offsets are computed using pb_ccn. If any object other than ccrsa_full_ctx_t +// or ccrsa_pub_ctx_t is passed to the macros, compiler error is generated. + + + +#if CORECRYPTO_USE_TRANSPARENT_UNION +//#define ccrsa_ctx_zm(_ctx_) (((ccrsa_pub_ctx_t)(_ctx_)).zp) + + CC_CONST CC_INLINE cczp_t ccrsa_ctx_zm(ccrsa_full_ctx_t _ctx_) { return ((cczp_t)(struct cczp *)((_ctx_).full)); } + CC_CONST CC_INLINE cc_unit *ccrsa_ctx_m(ccrsa_full_ctx_t _ctx_){ return ((_ctx_).full->pb_ccn);} + #define ccrsa_ctx_n(_ctx_) (ccrsa_ctx_zm(_ctx_).zp->n) +#else + #define ccrsa_ctx_zm(_ctx_) ((cczp_t)(_ctx_)) + #define ccrsa_ctx_n(_ctx_) (ccrsa_ctx_zm(_ctx_)->n) + #define ccrsa_ctx_m(_ctx_) ((_ctx_)->pb_ccn) +#endif + +#define ccrsa_ctx_e(_ctx_) (ccrsa_ctx_m(_ctx_) + 2 * ccrsa_ctx_n(_ctx_) + 1) +#define ccrsa_ctx_d(_ctx_) (ccrsa_ctx_m(_ctx_) + 3 * ccrsa_ctx_n(_ctx_) + 1) + +// accessors to ccrsa private key fields +// The offsets are computed using pv_ccn. If any object other than ccrsa_priv_ctx_t +// is passed to the macros, compiler error is generated. +#if CORECRYPTO_USE_TRANSPARENT_UNION + +/* rvalue accessors to ccec_key fields. */ +CC_CONST CC_INLINE +ccrsa_priv_ctx_t ccrsa_get_private_ctx_ptr(ccrsa_full_ctx_t fk) { + cc_unit *p = (cc_unit *)fk.full; + cc_size p_size = ccrsa_ctx_n(fk); + p += ccn_nof_size(ccrsa_pub_ctx_size(ccn_sizeof_n(p_size))) + p_size; + ccrsa_priv_ctx *priv = (ccrsa_priv_ctx *)p; + return (ccrsa_priv_ctx_t)priv; +} + +CC_CONST CC_INLINE +ccrsa_pub_ctx_t ccrsa_ctx_public(ccrsa_full_ctx_t fk) { + return (ccrsa_pub_ctx_t) fk.full; +} + +#define ccrsa_ctx_private_zp(FK) ((ccrsa_get_private_ctx_ptr(FK)).zp) +#define ccrsa_ctx_private_zq(FK) ((cczp_t)((ccrsa_get_private_ctx_ptr(FK)).zp.zp->ccn + 2 * ccrsa_ctx_private_zp(FK).zp->n + 1)) +#define ccrsa_ctx_private_dp(FK) ((ccrsa_get_private_ctx_ptr(FK)).zp.zp->ccn + 4 * ccrsa_ctx_private_zp(FK).zp->n + 2 + ccn_nof_size(sizeof(struct cczp))) +#define ccrsa_ctx_private_dq(FK) ((ccrsa_get_private_ctx_ptr(FK)).zp.zp->ccn + 5 * ccrsa_ctx_private_zp(FK).zp->n + 2 + ccn_nof_size(sizeof(struct cczp))) +#define ccrsa_ctx_private_qinv(FK) ((ccrsa_get_private_ctx_ptr(FK)).zp.zp->ccn + 6 * ccrsa_ctx_private_zp(FK).zp->n + 2 + ccn_nof_size(sizeof(struct cczp))) + +#else +#define ccrsa_ctx_private_zp(FK) ((cczp_t)ccrsa_get_private_ctx_ptr(FK)) +#define ccrsa_ctx_private_zq(FK) ((cczp_t)((ccrsa_get_private_ctx_ptr(FK))->pv_ccn + 2 * ccrsa_ctx_private_zp(FK)->n + 1)) +#define ccrsa_ctx_private_dp(FK) ((ccrsa_get_private_ctx_ptr(FK))->pv_ccn + 4 * ccrsa_ctx_private_zp(FK)->n + 2 + ccn_nof_size(sizeof(struct cczp))) +#define ccrsa_ctx_private_dq(FK) ((ccrsa_get_private_ctx_ptr(FK))->pv_ccn + 5 * ccrsa_ctx_private_zp(FK)->n + 2 + ccn_nof_size(sizeof(struct cczp))) +#define ccrsa_ctx_private_qinv(FK) ((ccrsa_get_private_ctx_ptr(FK))->pv_ccn + 6 * ccrsa_ctx_private_zp(FK)->n + 2 + ccn_nof_size(sizeof(struct cczp))) + +CC_CONST CC_INLINE +ccrsa_priv_ctx_t ccrsa_get_private_ctx_ptr(ccrsa_full_ctx_t fk) { + ccrsa_priv_ctx_t priv = (ccrsa_priv_ctx_t)(ccrsa_ctx_d(fk)+ccrsa_ctx_n(fk)); + return priv; +} + +/*! + @function ccrsa_ctx_public + @abstract gets the public key from full key + @param fk RSA full key + @result Returns RSA public ker + */ +CC_CONST CC_INLINE +ccrsa_pub_ctx_t ccrsa_ctx_public(ccrsa_full_ctx_t fk) { + return (ccrsa_pub_ctx_t) fk; +} + +#endif + +/* Return exact key bit size */ +static inline size_t +ccrsa_pubkeylength(ccrsa_pub_ctx_t pubk) { + return cczp_bitlen(ccrsa_ctx_zm(pubk)); +} + +/* PKCS1 pad_markers */ +#define CCRSA_PKCS1_PAD_SIGN 1 +#define CCRSA_PKCS1_PAD_ENCRYPT 2 + +/* Initialize key based on modulus and e as cc_unit. key->zp.n must already be set. */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3)) +int ccrsa_init_pub(ccrsa_pub_ctx_t key, const cc_unit *modulus, + const cc_unit *e); + +/* Initialize key based on modulus and e as big endian byte array + key->zp.n must already be set. */ +CC_NONNULL_TU((1)) CC_NONNULL((3 ,5)) +int ccrsa_make_pub(ccrsa_pub_ctx_t pubk, + size_t exp_nbytes, const uint8_t *exp, + size_t mod_nbytes, const uint8_t *mod); + +/* Do a public key crypto operation (typically verify or encrypt) on in and put + the result in out. Both in and out should be cc_unit aligned and + ccrsa_key_n(key) units long. Clients should use ccn_read_uint() to + convert bytes to a cc_unit to use for this API.*/ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3)) +int ccrsa_pub_crypt(ccrsa_pub_ctx_t key, cc_unit *out, const cc_unit *in); + +/* Generate an nbit rsa key pair in key, which should be allocated using + ccrsa_full_ctx_decl(ccn_sizeof(1024), rsa_ctx). The unsigned big endian + byte array exponent e of length e_size is used as the exponent. It's an + error to call this function with an exponent larger than nbits. rng + must be a pointer to an initialized struct ccrng_state. */ +CC_NONNULL_TU((2)) CC_NONNULL((4, 5)) +int ccrsa_generate_key(size_t nbits, ccrsa_full_ctx_t rsa_ctx, + size_t e_size, const void *e, struct ccrng_state *rng) CC_WARN_RESULT; + +/* Generate RSA key in conformance with FIPS186-4 standard */ +CC_NONNULL_TU((2)) CC_NONNULL((4, 5, 6)) +int +ccrsa_generate_fips186_key(size_t nbits, ccrsa_full_ctx_t fk, + size_t e_size, const void *eBytes, + struct ccrng_state *rng1, struct ccrng_state *rng2) CC_WARN_RESULT; + +/* Construct RSA key from fix input in conformance with FIPS186-4 standard */ +CC_NONNULL_TU((16)) CC_NONNULL((3, 5, 7, 9, 11, 13, 15)) +int +ccrsa_make_fips186_key(size_t nbits, + const cc_size e_n, const cc_unit *e, + const cc_size xp1Len, const cc_unit *xp1, const cc_size xp2Len, const cc_unit *xp2, + const cc_size xpLen, const cc_unit *xp, + const cc_size xq1Len, const cc_unit *xq1, const cc_size xq2Len, const cc_unit *xq2, + const cc_size xqLen, const cc_unit *xq, + ccrsa_full_ctx_t fk, + cc_size *np, cc_unit *r_p, + cc_size *nq, cc_unit *r_q, + cc_size *nm, cc_unit *r_m, + cc_size *nd, cc_unit *r_d); + +/*! + * @brief ccrsa_sign_pss() generates RSASSA-PSS signature in PKCS1-V2 format + * + * note that in RSASSA-PSS, salt length is part of the signature as specified in ASN1 + * RSASSA-PSS-params ::= SEQUENCE { + * hashAlgorithm [0] HashAlgorithm DEFAULT sha1, + * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT mgf1SHA1, + * saltLength [2] INTEGER DEFAULT 20, + * trailerField [3] TrailerField DEFAULT trailerFieldBC + * + * + * FIPS 186-4 for RSASSA-PSS: + * .... Both signature schemes are approved for use, but additional constraints are imposed beyond those specified in PKCS #1 v2.1..... + * + * • If nlen = 1024 bits (i.e., 128 bytes), and the output length of the approved hash function output block is 512 bits (i.e., 64 bytes), then the length (in bytes) of the salt (sLen) shall satisfy 0 ≤ sLen ≤ hLen – 2, + * • Otherwise, the length (in bytes) of the salt (sLen) shall satisfy 0 ≤ sLen ≤ hLen, where hLen is the length of the hash function output block (in bytes). + * + * + * • CAVS test vectors are not very useful in the case of RSA-PSS, because they only validate the exponentiation part of the signature. See: http://csrc.nist.gov/groups/STM/cavp/documents/components/RSA2SP1VS.pdf + * + * @param key The RSA key + * @param hashAlgorithm The hash algorithm used to generate mHash from the original message. It is also used inside the PSS encoding function. This is also the hash function to be used in the mask generation function (MGF) + * @param MgfHashAlgorithm The hash algorithm for thr mask generation function + * @param rng Random number geberator to generate salt in PSS encoding + * @param saltSize Intended length of the salt + * @param hSize Length of message hash . Must be equal to hashAlgorithm->output_size + * @param mHash The input that needs to be signed. This is the hash of message M with length of hLen + * + * @param sig The signature output + * @param sigSize The length of generated signature in bytes, which equals the size of the RSA modulus. + * @return 0:ok, non-zero:error + */ +CC_NONNULL((2,3,5,7,8,9)) +int ccrsa_sign_pss(ccrsa_full_ctx_t key, + const struct ccdigest_info* hashAlgorithm, const struct ccdigest_info* MgfHashAlgorithm, + size_t saltSize, struct ccrng_state *rng, + size_t hSize, const uint8_t *mHash, + size_t *sigSize, uint8_t *sig); + +CC_NONNULL((2,3,5,7,9)) +int ccrsa_verify_pss(ccrsa_pub_ctx_t key, + const struct ccdigest_info* di, const struct ccdigest_info* MgfDi, + size_t digestSize, const uint8_t *digest, + size_t sigSize, const uint8_t *sig, + size_t saltSize, bool *valid); + +/*! + @function ccrsa_sign_pkcs1v15 + @abstract RSA signature with PKCS#1 v1.5 format per PKCS#1 v2.2 + + @param key Full key + @param oid OID describing the type of digest passed in + @param digest_len Byte length of the digest + @param digest Byte array of digest_len bytes containing the digest + @param sig_len Pointer to the number of byte allocate for sig. + Output the exact size of the signature. + @param sig Pointer to the allocated buffer of size *sig_len + for the output signature + + @result 0 iff successful. + + @discussion Null OID is a special case, required to support RFC 4346 where the padding + is based on SHA1+MD5. In general it is not recommended to use a NULL OID, + except when strictly required for interoperability + + */ +CC_NONNULL_TU((1)) CC_NONNULL((4, 5, 6)) +int ccrsa_sign_pkcs1v15(ccrsa_full_ctx_t key, const uint8_t *oid, + size_t digest_len, const uint8_t *digest, + size_t *sig_len, uint8_t *sig); + + +/*! + @function ccrsa_sign_pkcs1v15 + @abstract RSA signature with PKCS#1 v1.5 format per PKCS#1 v2.2 + + @param key Public key + @param oid OID describing the type of digest passed in + @param digest_len Byte length of the digest + @param digest Byte array of digest_len bytes containing the digest + @param sig_len Number of byte of the signature sig. + @param sig Pointer to the signature buffer of sig_len + @param valid Output boolean, true if the signature is valid. + + @result 0 iff successful. + + @discussion Null OID is a special case, required to support RFC 4346 where the padding + is based on SHA1+MD5. In general it is not recommended to use a NULL OID, + except when strictly required for interoperability + */ +CC_NONNULL_TU((1)) CC_NONNULL((4, 6, 7)) +int ccrsa_verify_pkcs1v15(ccrsa_pub_ctx_t key, const uint8_t *oid, + size_t digest_len, const uint8_t *digest, + size_t sig_len, const uint8_t *sig, + bool *valid); + +/*! + @function ccder_encode_rsa_pub_size + @abstract Calculate size of public key export format data package. + + @param key Public key + + @result Returns size required for encoding. + */ + +CC_NONNULL_TU((1)) +size_t ccder_encode_rsa_pub_size(const ccrsa_pub_ctx_t key); + +/*! + @function ccrsa_export_priv_pkcs1 + @abstract Export a public key. + + @param key Public key + @param der Beginning of output DER buffer + @param der_end End of output DER buffer + */ + +CC_NONNULL_TU((1)) CC_NONNULL((2)) CC_NONNULL((3)) +uint8_t *ccder_encode_rsa_pub(const ccrsa_pub_ctx_t key, uint8_t *der, uint8_t *der_end); + + +/*! + @function ccder_encode_rsa_priv_size + @abstract Calculate size of full key exported in PKCS#1 format. + + @param key Full key + + @result Returns size required for encoding. + */ + +CC_NONNULL_TU((1)) +size_t ccder_encode_rsa_priv_size(const ccrsa_full_ctx_t key); + +/*! + @function ccder_encode_rsa_priv + @abstract Export a full key in PKCS#1 format. + + @param key Full key + @param der Beginning of output DER buffer + @param der_end End of output DER buffer + */ + +CC_NONNULL_TU((1)) CC_NONNULL((2)) CC_NONNULL((3)) +uint8_t *ccder_encode_rsa_priv(const ccrsa_full_ctx_t key, const uint8_t *der, uint8_t *der_end); + +/*! + @function ccder_decode_rsa_pub_n + @abstract Calculate "n" for a public key imported from a data package. + PKCS #1 format + + @param der Beginning of input DER buffer + @param der_end End of input DER buffer + + @result the "n" of the RSA key that would result from the import. This can be used + to declare the key itself. + */ + +CC_NONNULL((1)) CC_NONNULL((2)) +cc_size ccder_decode_rsa_pub_n(const uint8_t *der, const uint8_t *der_end); + +/*! + @function ccder_decode_rsa_pub + @abstract Import a public RSA key from a package in public key format. + PKCS #1 format + + @param key Public key (n must be set) + @param der Beginning of input DER buffer + @param der_end End of input DER buffer + + @result Key is initialized using the data in the public key message. + */ + +CC_NONNULL_TU((1)) CC_NONNULL((2)) CC_NONNULL((3)) +const uint8_t *ccder_decode_rsa_pub(const ccrsa_pub_ctx_t key, const uint8_t *der, const uint8_t *der_end); + +/*! + @function ccder_decode_rsa_pub_x509_n + @abstract Calculate "n" for a public key imported from a data package in x509 format + + @param der Beginning of input DER buffer + @param der_end End of input DER buffer + + @result the "n" of the RSA key that would result from the import. This can be used + to declare the key itself. + */ + +CC_NONNULL((1)) CC_NONNULL((2)) +cc_size ccder_decode_rsa_pub_x509_n(const uint8_t *der, const uint8_t *der_end); + +/*! + @function ccder_decode_rsa_pub_x509 + @abstract Import a public RSA key from a package in x509 format. + + @param key Public key (n must be set) + @param der Beginning of input DER buffer + @param der_end End of input DER buffer + + @result Key is initialized using the data in the public key message. + */ + +CC_NONNULL_TU((1)) CC_NONNULL((2)) CC_NONNULL((3)) +const uint8_t *ccder_decode_rsa_pub_x509(const ccrsa_pub_ctx_t key, const uint8_t *der, const uint8_t *der_end); + + +/*! + @function ccder_decode_rsa_priv_n + @abstract Calculate "n" for a private key imported from a data package. + + @param der Beginning of input DER buffer + @param der_end End of input DER buffer + + @result the "n" of the RSA key that would result from the import. This can be used + to declare the key itself. + */ + +CC_NONNULL((1)) CC_NONNULL((2)) +cc_size ccder_decode_rsa_priv_n(const uint8_t *der, const uint8_t *der_end); + +/*! + @function ccder_decode_rsa_priv + @abstract Import a private RSA key from a package in PKCS#1 format. + + @param key Full key (n must be set) + @param der Beginning of input DER buffer + @param der_end End of input DER buffer + + @result Key is initialized using the data in the public key message. + */ + +CC_NONNULL_TU((1)) CC_NONNULL((2)) CC_NONNULL((3)) +const uint8_t *ccder_decode_rsa_priv(const ccrsa_full_ctx_t key, const uint8_t *der, const uint8_t *der_end); + +/*! + @function ccrsa_export_pub_size + @abstract Calculate size of public key exported data package. + + @param key Public key + + @result Returns size required for encoding. + */ + +CC_CONST CC_INLINE CC_NONNULL_TU((1)) +size_t ccrsa_export_pub_size(const ccrsa_pub_ctx_t key) { + return ccder_encode_rsa_pub_size(key); +} + +/*! + @function ccrsa_export_pub + @abstract Export a public key in public key format. + + @param key Public key + @param out_len Allocated size + @param out Output buffer + */ + +CC_NONNULL_TU((1)) CC_NONNULL((3)) +int ccrsa_export_pub(const ccrsa_pub_ctx_t key, size_t out_len, uint8_t *out); +/*! + @function ccrsa_import_pub_n + @abstract Calculate "n" for a public key imported from a data package. + + @param inlen Length of public key package data + @param der pointer to public key package data + + @result the "n" of the RSA key that would result from the import. This can be used + to declare the key itself. + */ + +CC_CONST CC_INLINE CC_NONNULL((2)) +cc_size ccrsa_import_pub_n(size_t inlen, const uint8_t *der) { + cc_size size = ccder_decode_rsa_pub_x509_n(der, der + inlen); + if(size == 0) { + size = ccder_decode_rsa_pub_n(der, der + inlen); + } + return size; +} + +/*! + @function ccrsa_import_pub + @abstract Import a public RSA key from a package in public key format. + + @param key Public key (n must be set) + @param inlen Length of public key package data + @param der pointer to public key package data + + @result Key is initialized using the data in the public key message. + */ + +CC_NONNULL_TU((1)) CC_NONNULL((3)) +int ccrsa_import_pub(ccrsa_pub_ctx_t key, size_t inlen, const uint8_t *der); + +/*! + @function ccrsa_export_priv_size + @abstract Calculate size of full key exported in PKCS#1 format. + + @param key Full key + + @result Returns size required for encoding. + */ + +CC_CONST CC_INLINE CC_NONNULL_TU((1)) +size_t ccrsa_export_priv_size(const ccrsa_full_ctx_t key) { + return ccder_encode_rsa_priv_size(key); +} + +/*! + @function ccrsa_export_priv + @abstract Export a full key in PKCS#1 format. + + @param key Full key + @param out_len Allocated size + @param out Output buffer + */ + +CC_CONST CC_INLINE CC_NONNULL_TU((1)) CC_NONNULL((3)) +int ccrsa_export_priv(const ccrsa_full_ctx_t key, size_t out_len, uint8_t *out) { + return (ccder_encode_rsa_priv(key, out, out+out_len) != out); +} + +/*! + @function ccrsa_import_priv_n + @abstract Calculate size of full key exported in PKCS#1 format. + + @param inlen Length of PKCS#1 package data + @param der pointer to PKCS#1 package data + + @result the "n" of the RSA key that would result from the import. This can be used + to declare the key itself. + */ + +CC_CONST CC_INLINE CC_NONNULL((2)) +cc_size ccrsa_import_priv_n(size_t inlen, const uint8_t *der) { + return ccder_decode_rsa_priv_n(der, der + inlen); +} + +/*! + @function ccrsa_import_priv + @abstract Import a full RSA key from a package in PKCS#1 format. + + @param key Full key (n must be set) + @param inlen Length of PKCS#1 package data + @param der pointer to PKCS#1 package data + + @result Key is initialized using the data in the PKCS#1 message. + */ + +CC_CONST CC_INLINE CC_NONNULL_TU((1)) CC_NONNULL((3)) +int ccrsa_import_priv(ccrsa_full_ctx_t key, size_t inlen, const uint8_t *der) { + return (ccder_decode_rsa_priv(key, der, der+inlen) == NULL); +} + + +CC_NONNULL_TU((1)) CC_NONNULL2 +int ccrsa_get_pubkey_components(const ccrsa_pub_ctx_t pubkey, uint8_t *modulus, size_t *modulusLength, uint8_t *exponent, size_t *exponentLength); + +CC_NONNULL_TU((1)) CC_NONNULL2 +int ccrsa_get_fullkey_components(const ccrsa_full_ctx_t key, uint8_t *modulus, size_t *modulusLength, uint8_t *exponent, size_t *exponentLength, + uint8_t *p, size_t *pLength, uint8_t *q, size_t *qLength); + + +/*! + @function ccrsa_dump_public_key + @abstract Print a rsa public key in the console (printf) + + @param key Public key + */ +void ccrsa_dump_public_key(ccrsa_pub_ctx_t key); + +/*! + @function ccrsa_dump_full_key + @abstract Print a rsa private key in the console (printf) + + @param key Public key + */ +void ccrsa_dump_full_key(ccrsa_full_ctx_t key); + +#endif /* _CORECRYPTO_CCRSA_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccrsa_priv.h b/libraries/corecrypto/include/corecrypto/ccrsa_priv.h new file mode 100644 index 0000000..f4a9cb2 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccrsa_priv.h @@ -0,0 +1,571 @@ +/* + * Copyright (c) 2011,2012,2013,2014,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCRSA_PRIV_H_ +#define _CORECRYPTO_CCRSA_PRIV_H_ + +#include +#include + +// For reference, subject to change for unification accross corecrypto. + +// Program error: buffer too small or encrypted message is too small +#define CCRSA_INVALID_INPUT -1 +// Invalid crypto configuration: Hash length versus RSA key size +#define CCRSA_INVALID_CONFIG -2 +// The data is invalid (we won't say more for security +#define CCRSA_PRIVATE_OP_ERROR -3 +#define CCRSA_ENCODING_ERROR -4 +#define CCRSA_DECODING_ERROR -5 +#define CCRSA_SIGNATURE_GEN_ERROR -6 +#define CCRSA_KEY_ERROR -7 + +// Key generation specific +#define CCRSA_KEYGEN_PRIME_NOT_FOUND -9 +#define CCRSA_KEYGEN_PRIME_NEED_NEW_SEED -10 +#define CCRSA_KEYGEN_PRIME_TOO_MANY_ITERATIONS -11 +#define CCRSA_KEYGEN_PRIME_SEED_GENERATION_ERROR -12 +#define CCRSA_KEYGEN_MODULUS_CRT_INV_ERROR -13 +#define CCRSA_KEYGEN_NEXT_PRIME_ERROR -14 +#define CCRSA_KEYGEN_SEED_X_ERROR -15 +#define CCRSA_KEYGEN_SEED_r_ERROR -16 +#define CCRSA_KEYGEN_KEYGEN_CONSISTENCY_FAIL -17 +#define CCRSA_KEYGEN_R1R2_SIZE_ERROR -18 +#define CCRSA_KEYGEN_PQ_DELTA_ERROR -19 + +#define CCRSA_FIPS_KEYGEN_DISABLED -20 +// Number of entries to trace during FIPS186 key generation +// Currently, '3072' is specified by the largest 'mod' +// value in the RSA2/KeyGen_186-3 vector test file, but +// 4K keys are expected. +#define CCRSA_FIPS186_TRACE_MAX_KEY_UNITS (ccn_nof(4096)) + +// Number of ccrsa_fips186_trace objects to supply +#define CCRSA_FIPS186_TRACE_NUM 2 + +/* + Supply an array of CCRSA_FIPS186_TRACE_NUM of these objects + to the supporting functions to receive FIPS186 key generation + intermediary values. + */ +struct ccrsa_fips186_trace { + size_t bitlen1; + size_t bitlen2; + size_t curr; + cc_unit xp1[CCRSA_FIPS186_TRACE_MAX_KEY_UNITS]; + cc_unit xp2[CCRSA_FIPS186_TRACE_MAX_KEY_UNITS]; + cc_unit p1[CCRSA_FIPS186_TRACE_MAX_KEY_UNITS]; + cc_unit p2[CCRSA_FIPS186_TRACE_MAX_KEY_UNITS]; + cc_unit xp[CCRSA_FIPS186_TRACE_MAX_KEY_UNITS]; + cc_unit p[CCRSA_FIPS186_TRACE_MAX_KEY_UNITS]; +}; + + +/*! + @brief emsa_pss_encode () encodes message M acording to EMSA-PSS in PKCS 1 V2 + + + @return 0:ok non-zero:error + + + + @param di hash function (hLen denotes the length in octets of the hash function output) + @param sLen intended length in octets of the salt + @param salt salt for encoding + @param hLen length of hash function. must be equal to di->output_size + @param mHash the input that needs to be encoded. This is the hash of message M with length of hLen + @param emBits maximal bit length of the integer OS2IP (EM) (see Section 4.2), at least 8hLen + 8sLen + 9. It is one bit smalller than modulus. + @param EM encoded message output, an octet string of length emLen = ⎡emBits/8⎤ + +
+ @textblock
+                                        +-------------+
+                                        |  M[2^61-1]  |
+                                        +-------------+
+                                               |
+                                               V
+                                            Hash[hLen]
+                                               |
+                                               V
+                               +--------+-------------+------------+
+             M'[8+hLen+sLen] = |  0[8]  | mHash[hLen] | salt[sLen] |
+                               +--------+-------------+------------+
+                  t=emLen-sLen-hLen-2          |
+                  +------+---+------------+    V
+ DB[emLen-hLen-1]=| 0[t] | 1 | salt[sLen] |  Hash[hLen]
+                  +------+---+------------+    |
+                             |                 |
+                             V dbMask[]        |
+          [emLen- hLen-1]  xor <------- MGF <--|
+                             |                 |
+                             |                 |
+                 bit 0       V                 V
+                 +------------------------+----------+--+
+      EM[emLen]= | maskedDB[emLen-hLen-1] | H[hLen]  |bc|
+                 +------------------------+----------+--+
+ @/textblock
+ 
+ */ + +CC_NONNULL((1,2,4,6,8)) +int ccrsa_emsa_pss_encode(const struct ccdigest_info* di, const struct ccdigest_info* MgfDi, + size_t sSize, const uint8_t *salt, + size_t hSize, const uint8_t *mHash, + size_t emBits, uint8_t *EM); +CC_NONNULL((1,2,5,7)) +int ccrsa_emsa_pss_decode(const struct ccdigest_info* di, const struct ccdigest_info* MgfDi, + size_t sSize, + size_t mSize, const uint8_t *mHash, + size_t emBits, const uint8_t *EM); + + +/* EMSA + + Null OID in emsa encode/verify is a special case, only for use by SecKey for legacy purposes + When oid==NULL, the padding is reduced to "0001FF..FF00", oid and following seperators are skipped. + it is critical that the caller has set the oid and + other padding characters in the input "dgst". + Failing to do so results in weak signatures that may be forgeable */ +CC_NONNULL2 CC_NONNULL4 +int ccrsa_emsa_pkcs1v15_encode(size_t emlen, uint8_t *em, + size_t dgstlen, const uint8_t *dgst, + const uint8_t *oid); + +CC_NONNULL2 CC_NONNULL4 +int ccrsa_emsa_pkcs1v15_verify(size_t emlen, uint8_t *em, + size_t dgstlen, const uint8_t *dgst, + const uint8_t *oid); + + +// MGF for OAEP + +// Seed is di->output_size bytes, r_size must be >= di>output_size +CC_NONNULL1 CC_NONNULL3 CC_NONNULL5 +int ccmgf(const struct ccdigest_info* di, + size_t r_size, void* r, + size_t seed_size, const void* seed); + + +// OAEP + +/* + r_size is the blocksize of the key for which the encoding is being done. + */ +CC_NONNULL((1, 2, 4, 6)) +int ccrsa_oaep_encode_parameter(const struct ccdigest_info* di, + struct ccrng_state *rng, + size_t r_size, cc_unit *r, + size_t message_len, const uint8_t *message, + size_t parameter_data_len, const uint8_t *parameter_data); + +/* + r_size is the blocksize of the key for which the encoding is being done. + */ + +CC_INLINE CC_NONNULL((1, 2, 4, 6)) +int ccrsa_oaep_encode(const struct ccdigest_info* di, + struct ccrng_state *rng, + size_t r_size, cc_unit *r, + size_t message_len, const uint8_t *message) +{ + return ccrsa_oaep_encode_parameter(di, rng, r_size, r, message_len, message, 0, NULL); +} + +/* + r_len is the blocksize of the key for which the decoding is being done. + */ +CC_NONNULL((1, 2, 3, 5)) +int ccrsa_oaep_decode_parameter(const struct ccdigest_info* di, + size_t *r_len, uint8_t *r, + size_t s_size, cc_unit *s, + size_t parameter_data_len, const uint8_t *parameter_data); + + +CC_INLINE CC_NONNULL((1, 2, 3, 5)) +int ccrsa_oaep_decode(const struct ccdigest_info* di, + size_t *r_len, uint8_t *r, + size_t s_size, cc_unit* s) +{ + return ccrsa_oaep_decode_parameter(di, r_len, r, s_size, s, 0, NULL); +} + +CC_NONNULL_TU((1,4,7)) CC_NONNULL((2, 3, 5, 6, 8)) +int ccrsa_crt_makekey(cczp_t zm, const cc_unit *e, cc_unit *d, cczp_t zp, cc_unit *dp, cc_unit *qinv, cczp_t zq, cc_unit *dq); + +/*! + @function ccrsa_sign_pkcs1v15_blinded + @abstract Same as ccrsa_sign_pkcs1v15, with explicit argument + for RNG used for blinding + + @param blinding_rng Random number generator blinding + @param key Full key + @param oid OID describing the type of digest passed in + @param digest_len Byte length of the digest + @param digest Byte array of digest_len bytes containing the digest + @param sig_len Pointer to the number of byte allocate for sig. + Output the exact size of the signature. + @param sig Pointer to the allocated buffer of size *sig_len + for the output signature + + @result 0 iff successful. + + @discussion Null OID is a special case, required to support RFC 4346 where the padding + is based on SHA1+MD5. In general it is not recommended to use a NULL OID, + except when strictly required for interoperability + + */ +CC_NONNULL_TU((2)) CC_NONNULL((5, 6, 7)) +int ccrsa_sign_pkcs1v15_blinded(struct ccrng_state *blinding_rng, + ccrsa_full_ctx_t key, const uint8_t *oid, + size_t digest_len, const uint8_t *digest, + size_t *sig_len, uint8_t *sig); + +/*! + @function ccrsa_sign_pss_blinded + @abstract Same as ccrsa_sign_pss, with explicit argument + for RNG used for blinding + + * @param blinding_rng Random number generator blinding + * @param key The RSA key + * @param hashAlgorithm The hash algorithm used to generate mHash from the original message. It is also used inside the PSS encoding function. This is also the hash function to be used in the mask generation function (MGF) + * @param MgfHashAlgorithm The hash algorithm for thr mask generation function + * @param rng Random number geberator to generate salt in PSS encoding + * @param saltLen Intended length of the salt + * @param hLen Length of message hash . Must be equal to hashAlgorithm->output_size + * @param mHash The input that needs to be signed. This is the hash of message M with length of hLen + * + * @param sig The signature output + * @param sigLen The length of generated signature in bytes, which equals the size of the RSA modulus. + * @return 0:ok, non-zero:error + */ +CC_NONNULL((3,4,6,8,9,10)) +int ccrsa_sign_pss_blinded( + struct ccrng_state *blinding_rng, + ccrsa_full_ctx_t key, + const struct ccdigest_info* hashAlgorithm, const struct ccdigest_info* MgfHashAlgorithm, + size_t saltSize, struct ccrng_state *rng, + size_t hSize, const uint8_t *mHash, + size_t *sigSize, uint8_t *sig); + + +/*! + @function ccrsa_eme_pkcs1v15_encode + @abstract Encode a key in PKCS1 V1.5 EME format prior to encrypting. + + @param rng A handle to an initialized rng state structure. + @param r_size (In/Out) Result buffer size. + @param r Result cc_unit buffer. + @param s_size Source (payload) length. + @param s Source buffer to be encoded. + + @result Returns 0 on success, -1 otherwise. + */ + +CC_NONNULL((1, 3, 5)) +int ccrsa_eme_pkcs1v15_encode(struct ccrng_state *rng, + size_t r_size, cc_unit *r, + size_t s_size, const uint8_t *s); + +/*! + @function ccrsa_eme_pkcs1v15_decode + @abstract Decode a payload in PKCS1 V1.5 EME format to a key after decrypting. + + @param r_size (In/Out) Result buffer size. + @param r Result buffer. + @param s_size Source (PKCS1 EME Payload) length. + @param s Source cc_unit buffer to be decoded. + + @result Returns 0 on success, -1 otherwise. + */ + +CC_NONNULL((1, 2, 4)) +int ccrsa_eme_pkcs1v15_decode(size_t *r_size, uint8_t *r, + size_t s_size, cc_unit *s); + +/*! + @function ccrsa_encrypt_eme_pkcs1v15 + @abstract Encode a key in PKCS1 V1.5 EME format and encrypt. + DO NOT USE: THIS ALGORITHM IS NOT SECURE + This algorithm is vulnerable to practical attacks leading to plaintext recovery (Bleichenbach 98, Coron Joye Naccache Pailler 2000) + + @param key A public key to use to encrypt the package. + @param rng A handle to an initialized rng state structure. + @param r_size (In/Out) Result buffer size. + @param r Result cc_unit buffer. + @param s_size Source (payload) length. + @param s Source buffer to be encoded. + + @result Returns 0 on success, -1 otherwise. + */ + +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 4, 6)) +int ccrsa_encrypt_eme_pkcs1v15(ccrsa_pub_ctx_t key, + struct ccrng_state *rng, + size_t *r_size, uint8_t *r, + size_t s_size, const uint8_t *s); + +/*! + @function ccrsa_decrypt_eme_pkcs1v15 + DO NOT USE: THIS ALGORITHM IS NOT SECURE + This algorithm is vulnerable to practical attacks leading to plaintext recovery (Bleichenbach 98, Coron Joye Naccache Pailler 2000) + + @abstract Decrypt and decode a payload in PKCS1 V1.5 EME format to a key. + + @param key A private key to use to decrypt the package. + @param r_size (In/Out) Result buffer size. + @param r Result buffer. + @param s_size Source (PKCS1 EME Payload) length. + @param s Source buffer to be decoded. + + @result Returns 0 on success, -1 otherwise. + */ + + +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 5)) +int ccrsa_decrypt_eme_pkcs1v15(ccrsa_full_ctx_t key, + size_t *r_size, uint8_t *r, + size_t s_size, const uint8_t *s); + +/*! + @function ccrsa_decrypt_eme_pkcs1v15_blinded + DO NOT USE: THIS ALGORITHM IS NOT SECURE + This algorithm is vulnerable to practical attacks leading to plaintext recovery (Bleichenbach 98, Coron Joye Naccache Pailler 2000) + + @abstract Same as ccrsa_decrypt_eme_pkcs1v15, with an explicit RNG for blinding + + @param blinding_rng A handle to an initialized rng state structure. + @param key A private key to use to decrypt the package. + @param r_size (In/Out) Result buffer size. + @param r Result buffer. + @param s_size Source (PKCS1 EME Payload) length. + @param s Source buffer to be decoded. + + @result Returns 0 on success, -1 otherwise. + */ + +CC_NONNULL_TU((2)) CC_NONNULL((3, 4, 6)) +int ccrsa_decrypt_eme_pkcs1v15_blinded(struct ccrng_state *blinding_rng, + ccrsa_full_ctx_t key, + size_t *r_size, uint8_t *r, + size_t s_size, const uint8_t *s); + +/*! + @function ccrsa_encrypt_eme_pkcs1v15 + @abstract Encode a key in PKCS1 V2.1 OAEP format and encrypt. + + @param key A public key to use to encrypt the package. + @param di A descriptor for the digest used to encode the package. + @param rng A handle to an initialized rng state structure. + @param r_size (In/Out) Result buffer size. + @param r Result cc_unit buffer. + @param s_size Source (payload) length. + @param s Source buffer to be encoded. + @param parameter_data_len Length of tag data (optional) + @param parameter_data Pointer to tag data (optional) + + @result Returns 0 on success, -1 otherwise. + */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 4, 5, 7)) +int ccrsa_encrypt_oaep(ccrsa_pub_ctx_t key, + const struct ccdigest_info* di, + struct ccrng_state *rng, + size_t *r_size, uint8_t *r, + size_t s_size, const uint8_t *s, + size_t parameter_data_len, + const uint8_t *parameter_data); + +/*! + @function ccrsa_decrypt_oaep + @abstract Decrypt and decode a payload in PKCS1 V2.1 OAEP format to a key. + + @param key A private key to use to decrypt the package. + @param di A descriptor for the digest used to encode the package. + @param r_size (In/Out) Result buffer size. + @param r Result buffer. + @param c_size Source (PKCS1 EME Payload) length. + @param c Source buffer to be decoded. + @param parameter_data_len Length of tag data (optional) + @param parameter_data Pointer to tag data (optional) + + @result Returns 0 on success, -1 otherwise. + */ + +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 4, 6)) +int ccrsa_decrypt_oaep(ccrsa_full_ctx_t key, + const struct ccdigest_info* di, + size_t *r_size, uint8_t *r, + size_t c_size, const uint8_t *c, + size_t parameter_data_len, + const uint8_t *parameter_data); + +/*! + @function ccrsa_decrypt_oaep_blinded + + @abstract Same as ccrsa_decrypt_oaep, with an explicit RNG for blinding + + @param blinding_rng A handle to an initialized rng state structure. + + @param key A private key to use to decrypt the package. + @param di A descriptor for the digest used to encode the package. + @param r_size (In/Out) Result buffer size. + @param r Result buffer. + @param c_size Source (PKCS1 EME Payload) length. + @param c Source buffer to be decoded. + @param parameter_data_len Length of tag data (optional) + @param parameter_data Pointer to tag data (optional) + + @result Returns 0 on success, -1 otherwise. + */ + +CC_NONNULL_TU((2)) CC_NONNULL((3, 4, 5, 7)) +int ccrsa_decrypt_oaep_blinded( + struct ccrng_state *blinding_rng, + ccrsa_full_ctx_t key, + const struct ccdigest_info* di, + size_t *r_size, uint8_t *r, + size_t c_size, const uint8_t *c, + size_t parameter_data_len, + const uint8_t *parameter_data); + + +/*! + @function ccrsa_private_crypt + @abstract Perform RSA operation with a private key (CRT) + Clients should use ccn_read_uint() to + convert bytes to a cc_unit to use for this function. + + @param rng A handle to an initialized rng state structure. + @param key A handle an RSA private key. + @param out Output buffer, of size ccrsa_ctx_n(key). + @param in Input buffer, of size ccrsa_ctx_n(key). + + @result Returns 0 on success, !=0 otherwise. + */ +CC_NONNULL_TU((2)) CC_NONNULL((3, 4)) +int ccrsa_priv_crypt_blinded(struct ccrng_state *blinding_rng, ccrsa_full_ctx_t key, cc_unit *out, const cc_unit *in); + +/*! + @function ccrsa_priv_crypt + @abstract Perform RSA operation with a private key + + @param key A handle an RSA private key. + @param out Output buffer, of size ccrsa_ctx_n(key). + @param in Input buffer, of size ccrsa_ctx_n(key). + + @result Returns 0 on success, !=0 otherwise. + */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3)) +int ccrsa_priv_crypt(ccrsa_full_ctx_t key, cc_unit *out, const cc_unit *in); + +/* + Generate a FIPS186-4 standard RSA key, saving the intermediary values. + + This function must only be used for internal testing, and should never be + called directly outside of those circumstances. + */ +CC_NONNULL_TU((2)) CC_NONNULL((4, 5, 6)) +int ccrsa_generate_fips186_key_trace(size_t nbits, ccrsa_full_ctx_t fk, + size_t e_size, const void *eBytes, struct ccrng_state *rng1, + struct ccrng_state *rng2, struct ccrsa_fips186_trace *trace); + +/* + Construct RSA key from fix input in conformance with FIPS186-4 standard + + This function must only be used for internal testing, and should never be + called directly outside of those circumstances. + */ +CC_NONNULL_TU((16)) CC_NONNULL((3, 5, 7, 9, 11, 13, 15)) +int ccrsa_make_fips186_key_trace(size_t nbits, const cc_size e_n, + const cc_unit *e, const cc_size xp1Len, const cc_unit *xp1, + const cc_size xp2Len, const cc_unit *xp2, const cc_size xpLen, + const cc_unit *xp, const cc_size xq1Len, const cc_unit *xq1, + const cc_size xq2Len, const cc_unit *xq2, const cc_size xqLen, + const cc_unit *xq, ccrsa_full_ctx_t fk, cc_size *np, cc_unit *r_p, + cc_size *nq, cc_unit *r_q, cc_size *nm, cc_unit *r_m, cc_size *nd, + cc_unit *r_d, struct ccrsa_fips186_trace *trace); + +CC_INLINE cc_size ccrsa_n_from_size(size_t size) { + return ccn_nof_size(size); +} + +CC_INLINE size_t ccrsa_sizeof_n_from_size(size_t size) { + return ccn_sizeof_n(ccn_nof_size(size)); +} + +CC_INLINE uint8_t *ccrsa_block_start(size_t size, cc_unit *p, int clear_to_start) { + size_t fullsize = ccrsa_sizeof_n_from_size(size); + size_t offset = fullsize - size; + if(clear_to_start) cc_zero(offset,p); + return ((uint8_t *) p) + offset; +} + +CC_INLINE size_t ccrsa_block_size(ccrsa_pub_ctx_t key) { + return ccn_write_uint_size(ccrsa_ctx_n(key), ccrsa_ctx_m(key)); +} + +CC_NONNULL_TU((1)) +bool ccrsa_pairwise_consistency_check(const ccrsa_full_ctx_t full_key, + struct ccrng_state *rng); + +#endif diff --git a/libraries/corecrypto/include/corecrypto/ccsha1.h b/libraries/corecrypto/include/corecrypto/ccsha1.h new file mode 100644 index 0000000..aeebbfa --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccsha1.h @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2010,2011,2012,2014,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCSHA1_H_ +#define _CORECRYPTO_CCSHA1_H_ + +#include +#include + +#define CCSHA1_BLOCK_SIZE 64 +#define CCSHA1_OUTPUT_SIZE 20 +#define CCSHA1_STATE_SIZE 20 + +/* sha1 selector */ +const struct ccdigest_info *ccsha1_di(void); + +extern const uint32_t ccsha1_initial_state[5]; + +/* shared between several implementations */ +void ccsha1_final(const struct ccdigest_info *di, ccdigest_ctx_t, + unsigned char *digest); + + +/* Implementations */ +extern const struct ccdigest_info ccsha1_ltc_di; +extern const struct ccdigest_info ccsha1_eay_di; + +#if CCSHA1_VNG_INTEL +//extern const struct ccdigest_info ccsha1_vng_intel_di; +#if defined(__x86_64__) +extern const struct ccdigest_info ccsha1_vng_intel_AVX2_di; +extern const struct ccdigest_info ccsha1_vng_intel_AVX1_di; +#endif +extern const struct ccdigest_info ccsha1_vng_intel_SupplementalSSE3_di; +#endif + +#if CCSHA1_VNG_ARMV7NEON +extern const struct ccdigest_info ccsha1_vng_armv7neon_di; +#endif + +/* TODO: Placeholders */ +#define ccoid_sha1 ((unsigned char *)"\x06\x05\x2b\x0e\x03\x02\x1a") +#define ccoid_sha1_len 7 + +#endif /* _CORECRYPTO_CCSHA1_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccsha2.h b/libraries/corecrypto/include/corecrypto/ccsha2.h new file mode 100644 index 0000000..9a3d18e --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccsha2.h @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2010,2011,2012,2014,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCSHA2_H_ +#define _CORECRYPTO_CCSHA2_H_ + +#include + +/* sha2 selectors */ +const struct ccdigest_info *ccsha224_di(void); +const struct ccdigest_info *ccsha256_di(void); +const struct ccdigest_info *ccsha384_di(void); +const struct ccdigest_info *ccsha512_di(void); + +/* TODO: Placeholders */ +#define ccoid_sha224 ((unsigned char *)"\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04") +#define ccoid_sha224_len 11 + +#define ccoid_sha256 ((unsigned char *)"\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01") +#define ccoid_sha256_len 11 + +#define ccoid_sha384 ((unsigned char *)"\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02") +#define ccoid_sha384_len 11 + +#define ccoid_sha512 ((unsigned char *)"\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03") +#define ccoid_sha512_len 11 + + +/* SHA256 */ +#define CCSHA256_BLOCK_SIZE 64 +#define CCSHA256_OUTPUT_SIZE 32 +#define CCSHA256_STATE_SIZE 32 +extern const struct ccdigest_info ccsha256_ltc_di; +extern const struct ccdigest_info ccsha256_v6m_di; +#if CCSHA2_VNG_INTEL +#if defined __x86_64__ +extern const struct ccdigest_info ccsha224_vng_intel_AVX2_di; +extern const struct ccdigest_info ccsha224_vng_intel_AVX1_di; +extern const struct ccdigest_info ccsha256_vng_intel_AVX2_di; +extern const struct ccdigest_info ccsha256_vng_intel_AVX1_di; +extern const struct ccdigest_info ccsha384_vng_intel_AVX2_di; +extern const struct ccdigest_info ccsha384_vng_intel_AVX1_di; +extern const struct ccdigest_info ccsha384_vng_intel_SupplementalSSE3_di; +extern const struct ccdigest_info ccsha512_vng_intel_AVX2_di; +extern const struct ccdigest_info ccsha512_vng_intel_AVX1_di; +extern const struct ccdigest_info ccsha512_vng_intel_SupplementalSSE3_di; +#endif +extern const struct ccdigest_info ccsha224_vng_intel_SupplementalSSE3_di; +extern const struct ccdigest_info ccsha256_vng_intel_SupplementalSSE3_di; +#endif +#if CCSHA2_VNG_ARMV7NEON +extern const struct ccdigest_info ccsha224_vng_armv7neon_di; +extern const struct ccdigest_info ccsha256_vng_armv7neon_di; +extern const struct ccdigest_info ccsha384_vng_arm64_di; +extern const struct ccdigest_info ccsha384_vng_armv7neon_di; +extern const struct ccdigest_info ccsha512_vng_arm64_di; +extern const struct ccdigest_info ccsha512_vng_armv7neon_di; +#endif +extern const uint32_t ccsha256_K[64]; +extern const uint64_t ccsha512_K[80]; + +/* SHA224 */ +#define CCSHA224_OUTPUT_SIZE 28 +extern const struct ccdigest_info ccsha224_ltc_di; + +/* SHA512 */ +#define CCSHA512_BLOCK_SIZE 128 +#define CCSHA512_OUTPUT_SIZE 64 +#define CCSHA512_STATE_SIZE 64 +extern const struct ccdigest_info ccsha512_ltc_di; + +/* SHA384 */ +#define CCSHA384_OUTPUT_SIZE 48 +extern const struct ccdigest_info ccsha384_ltc_di; + +#endif /* _CORECRYPTO_CCSHA2_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccsrp.h b/libraries/corecrypto/include/corecrypto/ccsrp.h new file mode 100644 index 0000000..d15f2fa --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccsrp.h @@ -0,0 +1,651 @@ +/* + * Copyright (c) 2012,2013,2014,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef SRP_H +#define SRP_H + +#include +#include +#include +#include +#include + +/* Aliases for DH-style group params for SRP */ +#if CORECRYPTO_USE_TRANSPARENT_UNION +typedef ccdh_gp ccsrp_gp; +#else +typedef struct ccdh_gp ccsrp_gp; +#endif +#define CCSRP_HDR_PAD 32 + +#if CORECRYPTO_USE_TRANSPARENT_UNION +typedef ccdh_gp_t ccsrp_gp_t; +typedef ccdh_const_gp_t ccsrp_const_gp_t; + +struct ccsrp_ctx_header { + const struct ccdigest_info *di; + ccsrp_const_gp_t gp; + struct ccrng_state *blinding_rng; + struct { + unsigned int authenticated:1; + unsigned int noUsernameInX:1; + unsigned int sessionkey:1; + unsigned int variant:16; + } flags; + uint8_t pad[CCSRP_HDR_PAD - (sizeof(struct ccdigest_info *)+ + sizeof(ccsrp_const_gp_t)+ + sizeof(struct ccrng_state *)+ + sizeof(bool))]; + cc_unit ccn[1]; +} CC_ALIGNED(16); + +typedef struct ccsrp_ctx { + struct ccsrp_ctx_header hdr; +} CC_ALIGNED(16) ccsrp_ctx; + +struct ccsrp_ctx_body { + struct ccsrp_ctx_header hdr; + cc_unit ccn[]; +} CC_ALIGNED(16); + +typedef union { + ccsrp_ctx *_full; // Constructor + struct ccsrp_ctx_header *hdr; + struct ccsrp_ctx_body *body; +} __attribute__((transparent_union)) ccsrp_ctx_t; +#else +typedef ccdh_gp_t ccsrp_gp_t; +typedef ccdh_const_gp_t ccsrp_const_gp_t; + +struct ccsrp_ctx { + const struct ccdigest_info *di; + ccsrp_const_gp_t gp; + struct ccrng_state *blinding_rng; + struct { + unsigned int authenticated:1; + unsigned int noUsernameInX:1; + unsigned int sessionkey:1; + unsigned int variant:16; + } flags; + cc_unit ccn[1]; +} CC_ALIGNED(16); +typedef struct ccsrp_ctx *ccsrp_ctx_t; + +struct ccsrp_ctx_legacy { + const struct ccdigest_info *di; + ccsrp_const_gp_t gp; + struct ccrng_state *blinding_rng; + struct { + unsigned int authenticated:1; + unsigned int noUsernameInX:1; + unsigned int sessionkey:1; + unsigned int variant:16; + } flags; + uint8_t pad[CCSRP_HDR_PAD - (sizeof(struct ccdigest_info *)+ + sizeof(ccsrp_const_gp_t)+ + sizeof(struct ccrng_state *)+ + sizeof(bool))]; + cc_unit ccn[1]; +} CC_ALIGNED(16); +typedef struct ccsrp_ctx_legacy *ccsrp_ctx_t_legacy; + +cc_unit *srp_ccn(void *srp); + +#endif + +#define ccsrp_gpbuf_size(_gp_) (ccdh_ccn_size(_gp_)*4) +#define ccsrp_dibuf_size(_di_) ((_di_)->output_size*4) + +/* Size of the context structure for the di and gp combo */ +#define ccsrp_sizeof_srp(_di_,_gp_) sizeof(struct ccsrp_ctx)+\ + ccsrp_gpbuf_size(_gp_)+ccsrp_dibuf_size(_di_) + +/* Use this to declare a context on the stack + Use ccsrp_ctx_clear when done to prevent exposing key material */ +#define ccsrp_ctx_decl(_di_, _gp_, _name_) \ + cc_ctx_decl(struct ccsrp_ctx, ccsrp_sizeof_srp(_di_,_gp_), _name_) + +#define ccsrp_ctx_clear(_di_, _gp_, _name_) \ + cc_clear(ccsrp_sizeof_srp(_di_,_gp_), _name_) + +/* + Accessors to the context structure. + */ +#if CORECRYPTO_USE_TRANSPARENT_UNION +#define HDR(srp) ((srp).hdr) +#else +#define HDR(srp) (srp) +#endif + +#define SRP_DI(srp) (HDR(srp)->di) +#define SRP_GP(srp) (HDR(srp)->gp) +#define SRP_FLG(srp) (HDR(srp)->flags) +#define SRP_CCN(srp) (HDR(srp)->ccn) +#define SRP_RNG(srp) (HDR(srp)->blinding_rng) + +#define ccsrp_ctx_gp(KEY) SRP_GP((ccsrp_ctx_t)(KEY)) +#define ccsrp_ctx_di(KEY) SRP_DI((ccsrp_ctx_t)(KEY)) +#define ccsrp_ctx_zp(KEY) ccdh_gp_zp((ccsrp_ctx_gp(KEY))) +#define ccsrp_ctx_gp_g(KEY) (ccdh_gp_g(ccsrp_ctx_gp(KEY))) +#define ccsrp_ctx_gp_l(KEY) (ccdh_gp_l(ccsrp_ctx_gp(KEY))) +#define ccsrp_ctx_n(KEY) (ccdh_gp_n(ccsrp_ctx_gp(KEY))) +#define ccsrp_ctx_prime(KEY) (ccdh_gp_prime(ccsrp_ctx_gp(KEY))) +#define ccsrp_ctx_ccn(KEY) srp_ccn(KEY) +#define ccsrp_ctx_pki_key(KEY,_N_) (ccsrp_ctx_ccn(KEY) + ccsrp_ctx_n(KEY) * _N_) +#define ccsrp_ctx_public(KEY) (ccsrp_ctx_pki_key(KEY,0)) +#define ccsrp_ctx_private(KEY) (ccsrp_ctx_pki_key(KEY,1)) +#define ccsrp_ctx_v(KEY) (ccsrp_ctx_pki_key(KEY,2)) +#define ccsrp_ctx_S(KEY) (ccsrp_ctx_pki_key(KEY,3)) +#define ccsrp_ctx_K(KEY) ((uint8_t *)(ccsrp_ctx_pki_key(KEY,4))) +#define ccsrp_ctx_M(KEY) (uint8_t *)(ccsrp_ctx_K(KEY)+\ +2*ccsrp_ctx_di(KEY)->output_size) +#define ccsrp_ctx_HAMK(KEY) (uint8_t *)(ccsrp_ctx_K(KEY)+\ +3*ccsrp_ctx_di(KEY)->output_size) + +/* Session Keys and M and HAMK are returned in this many bytes */ +#define ccsrp_ctx_keysize(KEY) ccsrp_get_session_key_length(KEY) + +#define ccsrp_ctx_M_HAMK_size(KEY) (ccsrp_ctx_di(KEY)->output_size) + +/* The public keys and the verifier are returned in this many bytes */ +#define ccsrp_ctx_sizeof_n(KEY) (ccn_sizeof_n(ccsrp_ctx_n(KEY))) + +/****************************************************************************** + * Error codes + *****************************************************************************/ + +#define CCSRP_ERROR_DEFAULT CCDH_ERROR_DEFAULT +#define CCSRP_GENERATE_KEY_TOO_MANY_TRIES CCDH_GENERATE_KEY_TOO_MANY_TRIES +#define CCSRP_NOT_SUPPORTED_CONFIGURATION CCDH_NOT_SUPPORTED_CONFIGURATION +#define CCSRP_SAFETY_CHECK CCDH_SAFETY_CHECK +#define CCSRP_PUBLIC_KEY_MISSING CCDH_PUBLIC_KEY_MISSING +#define CCSRP_INVALID_DOMAIN_PARAMETER CCDH_INVALID_DOMAIN_PARAMETER + +/****************************************************************************** + * Variant (main difference is key derivation after DH di + *****************************************************************************/ +/* OPTION + [0..2]: KDF to compute K from S + [3..5]: Variant (value of k in the computation of B) + [6..7]: Padding in Hash (leading zeroes hashed or skipped in hashes) */ + +// Do Not use these flags directly. Please use one of the "combo" flags. +// and request a new combo flag is needed. + +// Selection of KDF for the session key +#define CCSRP_OPTION_KDF_MASK (7<<0) +// K = H(S), size of K is the size of the digest output +#define CCSRP_OPTION_KDF_HASH (0<<0) +// K = MGF1(S), size of K is TWICE the size of the digest output +#define CCSRP_OPTION_KDF_MGF1 (1<<0) +// K = H_Interleave(S), size of K is TWICE the size of the digest output +#define CCSRP_OPTION_KDF_INTERLEAVED (2<<0) + +// Selection of the variant for internal computation +#define CCSRP_OPTION_VARIANT_MASK (7<<3) +// k = HASH(N | PAD(g)) and u = HASH(PAD(A) | PAD(B)) +#define CCSRP_OPTION_VARIANT_SRP6a (0<<3) +// K = 1 and u=MSB32bit(HASH(PAD(B)) +#define CCSRP_OPTION_VARIANT_RFC2945 (1<<3) + +// Selection of leading zeroes in integer hashes +#define CCSRP_OPTION_PAD_MASK (3<<6) +// Skip zeroes of A and B during hashes for the computation of k, U and X +#define CCSRP_OPTION_PAD_SKIP_ZEROES_k_U_X (1<<6) +// Skip leading zeroes when hashing A,B in M and HAMK only +// This is a hack to be compatible with AppleSRP implementation +#define CCSRP_OPTION_PAD_SKIP_ZEROES_TOKEN (2<<6) + + +// Higher level combos: +// Corecrypto default +#define CCSRP_OPTION_SRP6a_HASH (CCSRP_OPTION_VARIANT_SRP6a \ + | CCSRP_OPTION_KDF_HASH) + +// Improved SRP6a (with MGF1) compatible with SRP +// The domain parameter (g) is hashed on the exact number of bytes instead hashing +// modlen bytes. +#define CCSRP_OPTION_SRP6a_MGF1 (CCSRP_OPTION_VARIANT_SRP6a \ + | CCSRP_OPTION_KDF_MGF1 \ + | CCSRP_OPTION_PAD_SKIP_ZEROES_TOKEN) + +// TLS-SRP. Not recommended except when interoperability is required +#define CCSRP_OPTION_RFC2945_INTERLEAVED (CCSRP_OPTION_VARIANT_RFC2945 \ + | CCSRP_OPTION_KDF_INTERLEAVED \ + | CCSRP_OPTION_PAD_SKIP_ZEROES_k_U_X \ + | CCSRP_OPTION_PAD_SKIP_ZEROES_TOKEN) + + + + +/*! + @function ccsrp_ctx_init_option + @abstract Initialize the SRP context + + @param srp SRP + @param di handle on the digest to be used (ex. ccsha1_di()) + @param gp handle on DH group parameters (requires group with no small subgroups) + @param option Define variant, key derivation and padding of integers being hashed. + @param blinding_rng For randomization of internal computations, rng may be used for as long as the "srp" context is used. + + @result 0 if no error + */ +/* Init context structures with this function */ +CC_NONNULL_TU((1,3)) CC_NONNULL((2)) +CC_INLINE int +ccsrp_ctx_init_option(ccsrp_ctx_t srp, + const struct ccdigest_info *di, + ccsrp_const_gp_t gp, + uint32_t option, + struct ccrng_state *blinding_rng) { + cc_zero(ccsrp_sizeof_srp(di, gp),HDR(srp)); + SRP_DI(srp) = di; + SRP_GP(srp) = gp; + SRP_FLG(srp).authenticated = false; + SRP_FLG(srp).sessionkey = false; + SRP_RNG(srp)=blinding_rng; + // Option is a bit mask. If not a power of two, it's an error. + SRP_FLG(srp).variant = 0xFFFF & option; + return 0; // Success +} + +// Legacy function, initialize for the RFC5054 variant. +CC_NONNULL_TU((1,3)) CC_NONNULL((2)) +CC_INLINE void +ccsrp_ctx_init(ccsrp_ctx_t srp, const struct ccdigest_info *di, ccsrp_const_gp_t gp) { + ccsrp_ctx_init_option(srp,di,gp,CCSRP_OPTION_SRP6a_HASH,ccrng(NULL)); +} + +/****************************************************************************** + * Salt and Verification Generation - used to setup an account. + *****************************************************************************/ + +/*! + @function ccsrp_generate_salt_and_verification + @abstract Generate the salt and the verification token to be used for future + authentications + + @param srp SRP + @param rng handle on rng for ephemeral key generation + @param username identity + @param password_len length in byte of the password + @param password password of length password_len + @param salt_len length in byte of the salt + @param salt salt of length salt_len (output) + @param verifier password verifier known to the server (output) + + @result 0 if no error + */ +CC_NONNULL_TU((1)) CC_NONNULL((2,3,5,7,8)) +int +ccsrp_generate_salt_and_verification(ccsrp_ctx_t srp, struct ccrng_state *rng, + const char *username, + size_t password_len, const void *password, + size_t salt_len, void *salt, + void *verifier); + +/*! + @function ccsrp_generate_verifier + @abstract Generate the verification token to be used for future + authentications + + @param srp SRP + @param username identity + @param password_len length in byte of the password + @param password password of length password_len + @param salt_len length in byte of the salt + @param salt salt of length salt_len (input) + @param verifier password verifier known to the server (output) + + @result 0 if no error + */ +CC_NONNULL_TU((1)) CC_NONNULL((2,4,6,7)) +int +ccsrp_generate_verifier(ccsrp_ctx_t srp, + const char *username, + size_t password_len, const void *password, + size_t salt_len, const void *salt, + void *verifier); + +/****************************************************************************** + * Server Side Routines + *****************************************************************************/ + +/*! + @function ccsrp_server_generate_public_key + @abstract Generate the server value B. + If A is known, call directly ccsrp_server_start_authentication + + @param srp SRP + @param rng handle on rng for ephemeral key generation + @param username identity + @param verifier password verifier known to the server + @param B_bytes Value B which is the challenge to send to the client (output) + + @result 0 if no error + */ +CC_NONNULL_TU((1)) CC_NONNULL((2,3,4)) +int +ccsrp_server_generate_public_key(ccsrp_ctx_t srp, struct ccrng_state *rng, + const void *verifier, void *B_bytes); + +/*! + @function ccsrp_server_compute_session + @abstract Generate the session key material and tokens for authentication + + @param srp SRP + @param username identity + @param salt_len length in byte of the salt + @param salt salt of length salt_len + @param A_bytes Ephemeral public key received from the client + + @result 0 if no error + */ +CC_NONNULL_TU((1)) CC_NONNULL((2,4,5)) +int +ccsrp_server_compute_session(ccsrp_ctx_t srp, + const char *username, + size_t salt_len, const void *salt, + const void *A_bytes); + +/*! + @function ccsrp_server_start_authentication + @abstract Performs in one shot the server public key and the session key material + + @param srp SRP + @param rng handle on rng for ephemeral key generation + @param username identity + @param salt_len length in byte of the salt + @param salt salt of length salt_len + @param verifier password verifier known to the server + @param A_bytes Ephemeral public key received from the client + @param B_bytes Value B which is the challenge to send to the client (output) + + @result 0 if no error + */ +CC_NONNULL_TU((1)) CC_NONNULL((2,3,5,6,7,8)) +int +ccsrp_server_start_authentication(ccsrp_ctx_t srp, struct ccrng_state *rng, + const char *username, + size_t salt_len, const void *salt, + const void *verifier, const void *A_bytes, + void *B_bytes); + +/*! + @function ccsrp_server_verify_session + @abstract Verify that the token received from the client is correct and that + therefore authentication succeeded. + + @param srp SRP + @param user_M Authentication token received from the client + @param HAMK_bytes Authentication token generated to be sent to the client (output) + + @result true if client is authenticated, false otherwise (fail or incomplete protocol) + */ +CC_NONNULL_TU((1)) CC_NONNULL((2,3)) +bool +ccsrp_server_verify_session(ccsrp_ctx_t srp, const void *user_M, + void *HAMK_bytes); + +/****************************************************************************** + * Client Side Routines + *****************************************************************************/ + +/*! + @function ccsrp_client_start_authentication + @abstract Initiate protocol with an ephemeral public key + + @param srp SRP + @param rng handle on random for key generation + @param A_bytes Output public key to send to the server + + @result 0 if no error + */ +CC_NONNULL_TU((1)) CC_NONNULL((2,3)) +int +ccsrp_client_start_authentication(ccsrp_ctx_t srp, struct ccrng_state *rng, + void *A_bytes); + +/*! + @function ccsrp_client_process_challenge + @abstract Process the challenge receive from the server + + @param srp SRP + @param username identity + @param password_len length in byte of the password + @param password password of length password_len + @param salt_len length in byte of the salt + @param salt salt of length salt_len + @param B_bytes Value B received from the server + @param M_bytes Response to the challenge (output) + + @result 0 if no error + */ +CC_NONNULL_TU((1)) CC_NONNULL((2,4,6,7,8)) +int +ccsrp_client_process_challenge(ccsrp_ctx_t srp, + const char *username, + size_t password_len, const void *password, + size_t salt_len, const void *salt, + const void *B_bytes, + void *M_bytes); + +/*! + @function ccsrp_client_verify_session + @abstract Verify that the token received from the server is correct and that + therefore authentication succeeded. + + @param srp SRP + @param HAMK_bytes Authentication token received from the server + + @result true if authenticated, false otherwise (fail or incomplete protocol) + */ +CC_NONNULL_TU((1)) CC_NONNULL((2)) +bool +ccsrp_client_verify_session(ccsrp_ctx_t srp, const uint8_t *HAMK_bytes); + +CC_NONNULL_TU((1)) +CC_INLINE bool +ccsrp_client_set_noUsernameInX(ccsrp_ctx_t srp, bool flag) +{ + return HDR(srp)->flags.noUsernameInX = !!flag; +} + + +/****************************************************************************** + * Functions for both sides + *****************************************************************************/ + +/*! + @function ccsrp_is_authenticated + @abstract Returns whether authentication was successful + + @param srp SRP + + @result true if authenticated, false otherwise (fail or incomplete protocol) + */ +CC_NONNULL_TU((1)) +CC_INLINE bool +ccsrp_is_authenticated(ccsrp_ctx_t srp) { + return HDR(srp)->flags.authenticated; +} + +/*! + @function ccsrp_exchange_size + @abstract Returns the size of the public keys exchanged + + @param srp SRP + + @result The length of the public key in bytes + */ +CC_NONNULL_TU((1)) +CC_INLINE size_t +ccsrp_exchange_size(ccsrp_ctx_t srp) { + return ccsrp_ctx_sizeof_n(srp); +} + +/*! + @function ccsrp_session_size + @abstract Returns the size of the session authentication tokens M and HAMK + + @param srp SRP + + @result The length of M and HAMK in bytes + */ +CC_NONNULL_TU((1)) +CC_INLINE size_t +ccsrp_session_size(ccsrp_ctx_t srp) { + /* Session Keys and M and HAMK are returned in this many bytes */ + return (ccsrp_ctx_di(srp)->output_size); +} + +/*! + @function ccsrp_get_session_key_length + @abstract Returns the size of the session key K, which depends on the variant + + @param srp SRP + + @result The length of K + */ +CC_NONNULL_TU((1)) +CC_INLINE size_t +ccsrp_get_session_key_length(ccsrp_ctx_t srp) { + if ((HDR(srp)->flags.variant & CCSRP_OPTION_KDF_MASK) == CCSRP_OPTION_KDF_HASH) { + return (ccsrp_ctx_di(srp)->output_size); + } + else if (( (HDR(srp)->flags.variant & CCSRP_OPTION_KDF_MASK) == CCSRP_OPTION_KDF_INTERLEAVED) + || ((HDR(srp)->flags.variant & CCSRP_OPTION_KDF_MASK) == CCSRP_OPTION_KDF_MGF1)) { + return 2*(ccsrp_ctx_di(srp)->output_size); + } + return 0; // Error +} + +/*! + @function ccsrp_get_session_key + @abstract Returns a pointer to the session key and its size + + @param srp SRP context + @param key_length pointer to output the size of the session key + + @result pointer to the session key in SRP context. NULL if the key has not been + computed yet + */ +CC_NONNULL_TU((1)) CC_NONNULL((2)) +CC_INLINE const void * +ccsrp_get_session_key(ccsrp_ctx_t srp, size_t *key_length) { + *key_length = ccsrp_get_session_key_length(srp); + if (HDR(srp)->flags.sessionkey) { + return ccsrp_ctx_K(srp); + } else { + return NULL; + } +} + +/*! + @function ccsrp_get_premaster_secret + @abstract Returns a pointer to the premaster secret key + use for TLS-SRP + This value is not a cryptographic key. A KDF is needed before + use. + + @param srp SRP context + + @result pointer to the premaster secret in SRP context. + The secret is an array of ccsrp_ctx_n(srp) cc_units */ +CC_NONNULL_TU((1)) +CC_INLINE cc_unit * +ccsrp_get_premaster_secret(ccsrp_ctx_t srp) { + if (HDR(srp)->flags.sessionkey) { + return ccsrp_ctx_S(srp); + } else { + return NULL; + } +} + +/****************************************************************************** + * Component Test Interface + *****************************************************************************/ + +int +ccsrp_test_calculations(const struct ccdigest_info *di, ccsrp_const_gp_t gp, + struct ccrng_state *blinding_rng, + const char *username, uint32_t options, + size_t password_len, const void *password, + size_t salt_len, const void *salt, + size_t k_len, const void *k, + size_t x_len, const void *x, + size_t v_len, const void *v, + size_t a_len, const void *a, + size_t b_len, const void *b, + size_t A_len, const void *A, + size_t B_len, const void *B, + size_t u_len, const void *u, + size_t S_len, const void *S, + size_t K_len, const void *K, + size_t M_len, const void *M, + size_t HAMK_len, const void *HAMK + ); + +#endif /* Include Guard */ + diff --git a/libraries/corecrypto/include/corecrypto/ccsrp_gp.h b/libraries/corecrypto/include/corecrypto/ccsrp_gp.h new file mode 100644 index 0000000..b1e2794 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccsrp_gp.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2012,2014,2015,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef corecrypto_ccsrp_gp_h +#define corecrypto_ccsrp_gp_h + +#include + +ccdh_const_gp_t ccsrp_gp_rfc5054_1024(void); +ccdh_const_gp_t ccsrp_gp_rfc5054_2048(void); +ccdh_const_gp_t ccsrp_gp_rfc5054_3072(void); +ccdh_const_gp_t ccsrp_gp_rfc5054_4096(void); +ccdh_const_gp_t ccsrp_gp_rfc5054_8192(void); + +#endif diff --git a/libraries/corecrypto/include/corecrypto/cctest.h b/libraries/corecrypto/include/corecrypto/cctest.h new file mode 100644 index 0000000..729e5b9 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/cctest.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2010,2011,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCTEST_H_ +#define _CORECRYPTO_CCTEST_H_ + +#include + +/* bin is n byte buffer into which a 2n byte long hex string is converted. */ +void cc_hex2bin(size_t n, unsigned char *bin, const char *hex); + +/* bin is n byte buffer which is converted into 2n + 1 byte long 0 terminated + string in hex. */ +void cc_bin2hex(size_t n, char *hex, const unsigned char *bin); + + +#define CCTEST_MAX_MSG_SIZE 8192 + +struct cctest_result { + double duration; + const char *msg; /* points to msg_buffer in cctest_input */ +}; + +struct cctest_input { + double start; + char msg_buffer[CCTEST_MAX_MSG_SIZE]; + struct cctest_result(*cctest_function)(const struct cctest_input *input); +}; + +#endif /* _CORECRYPTO_CCTEST_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccwrap.h b/libraries/corecrypto/include/corecrypto/ccwrap.h new file mode 100644 index 0000000..82e5d5f --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccwrap.h @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2012,2015,2016,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCWRAP_H_ +#define _CORECRYPTO_CCWRAP_H_ + +#include + +#include + +#define CCWRAP_IV 0xA6A6A6A6A6A6A6A6 +#define CCWRAP_SEMIBLOCK 8 + +// chosen somewhat arbitrarily +// corresponds to 65536 bytes of key material and one eight-byte IV +#define CCWRAP_MAXSEMIBLOCKS 8193 + +/*! + + @function ccwrap_wrapped_size + + @param data_size The size of the unwrapped key + + @result The size of the key after wrapping + + */ +CC_INLINE size_t ccwrap_wrapped_size(const size_t data_size) +{ + return (data_size + CCWRAP_SEMIBLOCK); +} + +/*! + + @function ccwrap_unwrapped_size + + @param data_size The size of the wrapped key + + @result The size of the key after unwrapping + + @discussion If the input is illegal (i.e. it is smaller than the overhead imposed by wrapping), the result will be zero. + + */ +CC_INLINE size_t ccwrap_unwrapped_size(const size_t data_size) +{ + if (data_size < CCWRAP_SEMIBLOCK) { + // data is malformed and possibly malicious + // just avoid underflow for now + // actually detect and handle error in ccwrap_auth_decrypt + return 0; + } + + return (data_size - CCWRAP_SEMIBLOCK); +} + + +/*! + @function ccwrap_auth_decrypt + @abstract Recover the wrapped key. + + @param ecb_mode Definition of an ECB implementation + @param ctx An instance of the implementation + @param nbytes Length in bytes of the wrapped key + @param in Pointer to the wrapped key + @param obytes Return parameter describing the size of the unwrapped key + @param out Return parameter pointing to the unwrapped key + + @result 0 iff successful; -1 otherwise. + + @discussion The out buffer should be allocated by the caller based + on the result of ccwrap_unwrapped_size(nbytes). On a successful + invocation, *obytes == ccwrap_unwrapped_size(nbytes); the caller needn't + verify this invariant. + */ +int ccwrap_auth_decrypt(const struct ccmode_ecb *ecb_mode, ccecb_ctx *ctx, + size_t nbytes, const void *in, + size_t *obytes, void *out); + +/*! + @function ccwrap_auth_encrypt + @abstract Wrap a key. + + @param ecb_mode Definition of an ECB implementation + @param ctx An instance of the implementation + @param nbytes Length in bytes of the key + @param in Pointer to the key + @param obytes Return parameter describing the size of the wrapped key + @param out Return parameter pointing to the wrapped key + + @result 0 iff successful; -1 otherwise. + + @discussion The out buffer should be allocated by the caller based + on the result of ccwrap_wrapped_size(nbytes). On a successful + invocation, *obytes == ccwrap_wrapped_size(nbytes); the caller needn't + verify this invariant. + */ +int ccwrap_auth_encrypt(const struct ccmode_ecb *ecb_mode, ccecb_ctx *ctx, + size_t nbytes, const void *in, + size_t *obytes, void *out); + +/* + This was originally implemented according to the “AES Key Wrap Specification” + formalized in RFC 3394. + + The following publications track changes made over time: + + [AES-KW1] National Institute of Standards and Technology, AES Key + Wrap Specification, 17 November 2001. + http://csrc.nist.gov/groups/ST/toolkit/documents/kms/ + AES_key_wrap.pdf + + [AES-KW2] Schaad, J. and R. Housley, "Advanced Encryption Standard + (AES) Key Wrap Algorithm", RFC 3394, September 2002. + + Note: block size is required to be 128 bits. + + This implementation wraps plaintexts between two and (CCWRAP_MAXSEMIBLOCKS-1) + semiblocks in length to produce ciphertexts between three and + CCWRAP_MAXSEMIBLOCKS semiblocks in length. All other inputs are rejected. + + While only the original unpadded algorithm is implemented at this time, the + following documents include specifications for padded versions allowing + plaintexts of arbitrary length: + + http://tools.ietf.org/html/rfc5649 + + NIST SP800-38F + +*/ + +#endif /* _CORECRYPTO_CCWRAP_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccz.h b/libraries/corecrypto/include/corecrypto/ccz.h new file mode 100644 index 0000000..e9d561b --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccz.h @@ -0,0 +1,314 @@ +/* + * Copyright (c) 2011,2012,2015,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCZ_H_ +#define _CORECRYPTO_CCZ_H_ + +#include +#include +#include +#include + +#define CCZ_INVALID_INPUT_ERROR -1 +#define CCZ_INVALID_RADIX_ERROR -2 + +struct ccz { + size_t n; + struct ccz_class *isa; + int sac; + cc_unit *u; +}; +typedef struct ccz ccz; + +struct ccz_class { + void *ctx; + void *(*ccz_alloc)(void *, size_t); + void *(*ccz_realloc)(void *, size_t, void *, size_t); + void (*ccz_free)(void *, size_t, void *); +}; + +/* Return the size needed for a ccz big enough to hold cls type ccz's. */ +CC_NONNULL_ALL +size_t ccz_size(struct ccz_class *cls); + +/* Initialize a new ccz instance. */ +CC_NONNULL_ALL +void ccz_init(struct ccz_class *cls, ccz *r); + +/* Release the memory a ccz is holding on to. */ +CC_NONNULL_ALL +void ccz_free(ccz *r); + +/* r = 0, and clear memory accessed by r. */ +CC_NONNULL_ALL +void ccz_zero(ccz *r); + +/* r = s */ +CC_NONNULL_ALL +void ccz_set(ccz *r, const ccz *s); + +CC_NONNULL1 +void ccz_seti(ccz *r, uint64_t v); + +/* s == 0 -> return 0 | s > 0 -> return index (starting at 1) of most + significant bit that is 1. */ +CC_PURE CC_NONNULL_ALL +size_t ccz_bitlen(const ccz *s); + +/* s == 0 -> return 0 | s > 0 -> return the number of bits which are zero + before the first one bit from least to most significant bit. */ +CC_PURE CC_NONNULL_ALL +size_t ccz_trailing_zeros(const ccz *s); + +/* Return actual size in bytes needed to serialize s. */ +CC_PURE CC_NONNULL1 +size_t ccz_write_uint_size(const ccz *s); + +/* Serialize s, to out. + First byte of byte stream is the m.s. byte of s, + regardless of the size of cc_unit. + + No assumption is made about the alignment of out. + + The out_size argument should be the value returned from ccz_write_uint_size, + and is also the exact number of bytes this function will write to out. + If out_size if less than the value returned by ccz_write_uint_size, only the + first out_size non-zero most significant octets of s will be written. */ +CC_NONNULL((1,3)) +void ccz_write_uint(const ccz *s, size_t out_size, void *out); + +/* Return actual size in bytes needed to serialize s as int + (adding leading zero if high bit is set). */ +CC_PURE CC_NONNULL1 +size_t ccz_write_int_size(const ccz *s); + +/* Serialize s, to out. + First byte of byte stream is the m.s. byte of s, + regardless of the size of cc_unit. + + No assumption is made about the alignment of out. + + The out_size argument should be the value returned from ccz_write_int_size, + and is also the exact number of bytes this function will write to out. + If out_size if less than the value returned by ccz_write_int_size, only the + first out_size non-zero most significant octets of s will be written. */ +CC_NONNULL((1,3)) +void ccz_write_int(const ccz *s, size_t out_size, void *out); + +/* Return actual size in bytes needed to serialize s in base radix. Radix can be any value between 2 and 64. */ +CC_PURE CC_NONNULL1 +size_t ccz_write_radix_size(const ccz *s, unsigned radix); + +/* r = (data, len) treated as a big endian byte array, written in base radix. Radix can be any value between 2 and 64. */ +/* Not constant time. Do not use for sensitive information. */ +CC_NONNULL((1,3)) +void ccz_write_radix(const ccz *s, size_t out_size, void *out, unsigned radix); + +/* r = (data, len) treated as a big endian byte array. */ +CC_NONNULL((1,3)) +void ccz_read_uint(ccz *r, size_t data_size, const uint8_t *data); + +/* r = (data, len) treated as a two's complement signed big endian byte + array. Negative only iff high bit of first byte is set. */ +CC_NONNULL((1,3)) +void ccz_read_int(ccz *r, size_t data_size, const uint8_t *data); + +/* r = (data, len) treated as a big endian byte array. Return nonzero iff the passed in buffer isn't a valid base radix input string. Radix can be any value between 2 and 64. + Returns: 0 if no error + CCZ_INVALID_INPUT_ERROR if the input is not valid for the select radar + CCZ_INVALID_RADIX_ERROR if the radix is not supported (>64) */ +/* Not constant time. Do not use for sensitive information. */ +CC_NONNULL((1,3)) +int ccz_read_radix(ccz *r, size_t data_size, const char *data, unsigned radix); + +CC_PURE CC_NONNULL_ALL +int ccz_cmp(const ccz *s, const ccz *t); + +CC_PURE CC_NONNULL_ALL +int ccz_cmpi(const ccz *s, uint32_t v); + +/* r = -r. */ +CC_NONNULL_ALL +void ccz_neg(ccz *r); + +/* r = s + t. */ +CC_NONNULL_ALL +void ccz_add(ccz *r, const ccz *s, const ccz *t); + +/* r = s + v. */ +CC_NONNULL_ALL +void ccz_addi(ccz *r, const ccz *s, uint32_t v); + +/* r = s - t. */ +CC_NONNULL_ALL +void ccz_sub(ccz *r, const ccz *s, const ccz *t); + +/* r = s - v. */ +CC_NONNULL_ALL +void ccz_subi(ccz *r, const ccz *s, uint32_t v); + +/* r = s * t */ +CC_NONNULL_ALL +void ccz_mul(ccz *r, const ccz *s, const ccz *t); + +/* r = s * t */ +CC_NONNULL_ALL +void ccz_muli(ccz *r, const ccz *s, uint32_t v); + +/* q = s / t, r = s % t */ +CC_NONNULL((3,4)) +void ccz_divmod(ccz *q, ccz *r, const ccz *s, const ccz *t); + +/* r = s >> k */ +CC_NONNULL((1,2)) +void ccz_lsr(ccz *r, const ccz *s, size_t k); + +/* r = s << k */ +CC_NONNULL((1,2)) +void ccz_lsl(ccz *r, const ccz *s, size_t k); + +/* r = s / 2 */ +CC_INLINE CC_NONNULL_ALL +void ccz_div2(ccz *r, const ccz *s) { + ccz_lsr(r, s, 1); +} + +/* r = s % t */ +CC_NONNULL_ALL +void ccz_mod(ccz *r, const ccz *s, const ccz *t); + +/* r = s^2. */ +CC_NONNULL_ALL +void ccz_sqr(ccz *r, const ccz *s); + +/* r = gcd(s, t). */ +CC_NONNULL_ALL +void ccz_gcd(ccz *r, const ccz *s, const ccz *t); + +/* r = lcm(s, t). */ +CC_NONNULL_ALL +void ccz_lcm(ccz *r, const ccz *s, const ccz *t); + +/* r = (s * t) mod u. */ +CC_NONNULL_ALL +void ccz_mulmod(ccz *r, const ccz *s, const ccz *t, const ccz *u); + +/* r = (s^2) mod t. */ +CC_NONNULL_ALL +int ccz_sqrmod(ccz *r, const ccz *s, const ccz *t); + +/* r = (s^-1) mod t. */ +CC_NONNULL_ALL +int ccz_invmod(ccz *r, const ccz *s, const ccz *t); + +/* r = (s^t) mod u. */ +CC_NONNULL_ALL +int ccz_expmod(ccz *r, const ccz *s, const ccz *t, const ccz *u); + +/* Return the value of bit k in s. */ +CC_PURE CC_NONNULL1 +bool ccz_bit(const ccz *s, size_t k); + +/* Set the value of bit k in r to value. */ +CC_NONNULL1 +void ccz_set_bit(ccz *r, size_t k, bool value); + +/* Return true iff s a is likely prime. Using rabin miller for depth. */ +CC_NONNULL_ALL +bool ccz_is_prime(const ccz *s, unsigned depth); + +/* s == odd -> return true | s == even -> return false */ +CC_INLINE CC_PURE CC_NONNULL_ALL +bool ccz_is_odd(const ccz *s) { + return ccz_bit(s, 0); +} + +/* s == 0 -> return true | s != 0 -> return false */ +CC_PURE CC_NONNULL_ALL +bool ccz_is_zero(const ccz *s); + +/* s == 1 -> return true | s != 1 -> return false */ +CC_PURE CC_NONNULL_ALL +bool ccz_is_one(const ccz *s); + +/* s < 0 -> return true | s >= 0 -> return false */ +CC_PURE CC_NONNULL_ALL +bool ccz_is_negative(const ccz *s); + + + +/* Debugging */ +CC_NONNULL1 +void ccz_print(const ccz *s); +CC_NONNULL2 +void ccz_lprint(const char *label, const ccz *s); + +/* Forward declaration so we don't depend on ccrng.h. */ +struct ccrng_state; + +/* Make a ccz with up to nbits sized random value. */ +CC_NONNULL((1,3)) +int ccz_random_bits(ccz *r, size_t nbits, struct ccrng_state *rng); + +#endif /* _CORECRYPTO_CCZ_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/ccz_priv.h b/libraries/corecrypto/include/corecrypto/ccz_priv.h new file mode 100644 index 0000000..907f7f2 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/ccz_priv.h @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2011,2012,2015,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCZ_PRIV_H_ +#define _CORECRYPTO_CCZ_PRIV_H_ + +#include +#include +#include +#include /* For abs() */ + +#ifndef CCZ_PREC +#define CCZ_PREC 32 /* default units of precision */ +#endif + +/* Error codes. */ +enum { + CCZ_OK = 0, + CCZ_MEM, +}; + +#define ccz_zp_decl(_ccz_, _name_) \ + cczp_decl_n(ccz_n(_ccz_), _name_); \ + CCZP_N(_name_) = ccz_n(_ccz_); \ + ccn_set(ccz_n(_ccz_), CCZP_PRIME(_name_), _ccz_->u); + + +CC_INLINE CC_CONST CC_NONNULL_ALL +int ccz_sign(const ccz *s) { + return s->sac < 0 ? -1 : 1; +} + +CC_INLINE CC_NONNULL1 +void ccz_set_sign(ccz *r, int sign) +{ + if (ccz_sign(r) != sign) + r->sac = -r->sac; +} + +CC_INLINE CC_CONST CC_NONNULL_ALL +cc_size ccz_n(const ccz *s) { + return s->n; +} + +CC_INLINE CC_NONNULL1 +void ccz_set_n(ccz *r, cc_size n) { + r->n = n; +} + +CC_INLINE CC_CONST CC_NONNULL_ALL +cc_size ccz_capacity(const ccz *s) { + return (cc_size)abs(s->sac); +} + +CC_INLINE CC_NONNULL1 +void ccz_set_capacity(ccz *r, cc_size capacity) +{ + if (ccz_capacity(r) < capacity) { + size_t ncapacity = capacity + (CCZ_PREC * 2) - (capacity % CCZ_PREC); + cc_unit *t; + if (ccz_capacity(r)) + t = r->isa->ccz_realloc(r->isa->ctx, ccn_sizeof_n(ccz_capacity(r)), r->u, ccn_sizeof_n(ncapacity)); + else + t = r->isa->ccz_alloc(r->isa->ctx, ccn_sizeof_n(ncapacity)); + + r->sac = r->sac < 0 ? -(int)ncapacity : (int)ncapacity; + r->u = t; + } +} + +/* From ccn_write_radix. */ +extern const char *ccn_radix_digit_map; + +#endif /* _CORECRYPTO_CCZ_PRIV_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/cczp.h b/libraries/corecrypto/include/corecrypto/cczp.h new file mode 100644 index 0000000..fb8de7d --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/cczp.h @@ -0,0 +1,392 @@ +/* + * Copyright (c) 2010,2011,2012,2014,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef _CORECRYPTO_CCZP_H_ +#define _CORECRYPTO_CCZP_H_ + +#include +#include + +/* + Don't use cczp_hd struct directly, except in static tables such as eliptic curve parameter definitions. + + Declare cczp objects using cczp_decl_n(). It allocates cc_unit arrays of the length returned by either cczp_nof_n() or cczp_short_nof_n(). +*/ + +struct cczp; +#if CORECRYPTO_USE_TRANSPARENT_UNION + +typedef union { + cc_unit *u; + struct cczp *zp; + //cczp_const_t czp; //for automatic type cast + //struct cczp_prime *prime; +} cczp_t __attribute__((transparent_union)); + +typedef union { + const cc_unit *u; + const struct cczp *zp; + //const struct cczp_prime *prime; + cczp_t _nczp; +} cczp_const_t __attribute__((transparent_union)); + +#else + typedef struct cczp* cczp_t; + typedef const struct cczp* cczp_const_t; +#endif +typedef void (*ccmod_func_t)(cc_ws_t ws, cczp_const_t zp, cc_unit *r, const cc_unit *s); + +// keep cczp_hd and cczp structures consistent +// cczp_hd is typecasted to cczp to read EC curve params +// options field is to specify Montgomery arithmetic, bit field, etc +// make sure n is the first element see ccrsa_ctx_n macro +#define __CCZP_HEADER_ELEMENTS_DEFINITIONS(pre) \ +cc_size pre ## n;\ +cc_unit pre ## options;\ +ccmod_func_t pre ## mod_prime; + +#define __CCZP_ELEMENTS_DEFINITIONS(pre) \ +__CCZP_HEADER_ELEMENTS_DEFINITIONS(pre) \ +cc_unit pre ## ccn[]; + +//cczp_hd must be defined separetly without variable length array ccn[], because it is used in sructures such as ccdh_gp_decl_n +struct cczp_hd{ + __CCZP_HEADER_ELEMENTS_DEFINITIONS() +} CC_ALIGNED(CCN_UNIT_SIZE); + +struct cczp { + __CCZP_ELEMENTS_DEFINITIONS() +} CC_ALIGNED(CCN_UNIT_SIZE); + + +/* Return the size of an cczp where each ccn is _size_ bytes. */ +#define cczp_size(_size_) (sizeof(struct cczp) + ccn_sizeof_n(1) + 2 * (_size_)) + +/* Return number of units that a struct cczp needs to be in units for a prime + size of N units. This is large enough for all operations. */ +#define cczp_nof_n(_n_) (ccn_nof_size(sizeof(struct cczp)) + 1 + 2 * (_n_)) + +/* Return number of units that a struct cczp needs to be in units for a prime + size of _n_ units. The _short variant does not have room for CCZP_RECIP, + so it can not be used with cczp_mod, cczp_mul, cczp_sqr. It can be used + with cczp_add, cczp_sub, cczp_div2, cczp_mod_inv. */ +#define cczp_short_nof_n(_n_) (ccn_nof_size(sizeof(struct cczp)) + (_n_)) + +#define cczp_decl_n(_n_, _name_) cc_ctx_decl(struct cczp, ccn_sizeof_n(cczp_nof_n(_n_)), _name_) +#define cczp_short_decl_n(_n_, _name_) cc_ctx_decl(struct cczp_short, ccn_sizeof_n(cczp_short_nof_n(_n_)), _name_) + +#define cczp_clear_n(_n_, _name_) cc_clear(ccn_sizeof_n(cczp_nof_n(_n_)), _name_) +#define cczp_short_clear_n(_n_, _name_) cc_clear(ccn_sizeof_n(cczp_short_nof_n(_n_)), _name_) + +#if CORECRYPTO_USE_TRANSPARENT_UNION + #define CCZP_N(ZP) (((cczp_t)(ZP)).zp->n) + #define CCZP_MOD(ZP) (((cczp_t)(ZP)).zp->mod_prime) + #define CCZP_PRIME(ZP) (((cczp_t)(ZP)).zp->ccn) + #define CCZP_RECIP(ZP) (((cczp_t)(ZP)).zp->ccn + cczp_n(ZP)) + #define CCZP_OPS(ZP) ((ZP).zp->options) + #define CCZP_MOD_PRIME(ZP) CCZP_MOD(ZP) + +CC_CONST CC_NONNULL_TU((1)) +static inline cc_size cczp_n(cczp_const_t zp) { + return zp.zp->n; +} + +CC_CONST CC_NONNULL_TU((1)) +static inline cc_unit cczp_options(cczp_const_t zp) { + return zp.zp->options; +} + +CC_CONST CC_NONNULL_TU((1)) +static inline ccmod_func_t cczp_mod_prime(cczp_const_t zp) { + return zp.zp->mod_prime; +} + +CC_CONST CC_NONNULL_TU((1)) +static inline const cc_unit *cczp_prime(cczp_const_t zp) { + return zp.zp->ccn; +} + +/* Return a pointer to the Reciprocal or Montgomery constant of zp, which is + allocated cczp_n(zp) + 1 units long. */ +CC_CONST CC_NONNULL_TU((1)) + +static inline const cc_unit *cczp_recip(cczp_const_t zp) { + return zp.zp->ccn + zp.zp->n; +} + +#else + #define CCZP_N(ZP) ((ZP)->n) + #define CCZP_MOD(ZP) ((ZP)->mod_prime) + #define CCZP_MOD_PRIME(ZP) CCZP_MOD(ZP) + #define CCZP_PRIME(ZP) ((ZP)->ccn) + #define CCZP_RECIP(ZP) ((ZP)->ccn + CCZP_N(ZP)) + #define CCZP_OPS(ZP) ((ZP)->options) +CC_CONST CC_NONNULL_TU((1)) +static inline cc_size cczp_n(cczp_const_t zp) { + return zp->n; +} + +CC_CONST CC_NONNULL_TU((1)) +static inline cc_unit cczp_options(cczp_const_t zp) { + return zp->options; +} + +CC_CONST CC_NONNULL_TU((1)) +static inline ccmod_func_t cczp_mod_prime(cczp_const_t zp) { + return zp->mod_prime; +} + +CC_CONST CC_NONNULL_TU((1)) +static inline const cc_unit *cczp_prime(cczp_const_t zp) { + return zp->ccn; +} + +/* Return a pointer to the Reciprocal or Montgomery constant of zp, which is + allocated cczp_n(zp) + 1 units long. */ +CC_CONST CC_NONNULL_TU((1)) + +static inline const cc_unit *cczp_recip(cczp_const_t zp) { + return zp->ccn + zp->n; +} + +#endif + + +CC_CONST CC_NONNULL_TU((1)) +CC_INLINE size_t cczp_bitlen(cczp_const_t zp) { + return ccn_bitlen(cczp_n(zp), cczp_prime(zp)); +} + + +/* Ensure both cczp_mod_prime(zp) and cczp_recip(zp) are valid. cczp_n and + cczp_prime must have been previously initialized. */ +CC_NONNULL_TU((1)) +int cczp_init(cczp_t zp); + +/* Compute r = s2n mod cczp_prime(zp). Will write cczp_n(zp) + units to r and reads 2 * cczp_n(zp) units units from s2n. If r and s2n are not + identical they must not overlap. Before calling this function either + cczp_init(zp) must have been called or both CCZP_MOD_PRIME((cc_unit *)zp) + and CCZP_RECIP((cc_unit *)zp) must be initialized some other way. */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3)) +void cczp_mod(cc_ws_t ws, cczp_const_t zp, cc_unit *r, const cc_unit *s2n); + +/* Compute r = sn mod cczp_prime(zp), Will write cczp_n(zp) + units to r and reads sn units units from s. If r and s are not + identical they must not overlap. Before calling this function either + cczp_init(zp) must have been called or both CCZP_MOD_PRIME((cc_unit *)zp) + and CCZP_RECIP((cc_unit *)zp) must be initialized some other way. */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 4)) +int cczp_modn(cczp_const_t zp, cc_unit *r, cc_size ns, const cc_unit *s); + +/* Compute r = x * y mod cczp_prime(zp). Will write cczp_n(zp) units to r + and reads cczp_n(zp) units units from both x and y. If r and x are not + identical they must not overlap, The same holds for r and y. Before + calling this function either cczp_init(zp) must have been called or both + CCZP_MOD_PRIME((cc_unit *)zp) and CCZP_RECIP((cc_unit *)zp) must be + initialized some other way. */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 4)) +void cczp_mul(cczp_const_t zp, cc_unit *t, const cc_unit *x, const cc_unit *y); + +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 4, 5)) +void cczp_mul_ws(cc_ws_t ws, cczp_const_t zp, cc_unit *t, const cc_unit *x, const cc_unit *y); + +/* Compute r = x * x mod cczp_prime(zp). Will write cczp_n(zp) units to r + and reads cczp_n(zp) units from x. If r and x are not identical they must + not overlap. Before calling this function either cczp_init(zp) must have + been called or both CCZP_MOD_PRIME((cc_unit *)zp) and + CCZP_RECIP((cc_unit *)zp) must be initialized some other way. */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3)) +void cczp_sqr(cczp_const_t zp, cc_unit *r, const cc_unit *x); + +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 4)) +void cczp_sqr_ws(cc_ws_t ws, cczp_const_t zp, cc_unit *r, const cc_unit *x); + +/* Compute r = x^(1/2) mod cczp_prime(zp). Will write cczp_n(zp) units to r + and reads cczp_n(zp) units from x. If r and x are not identical they must + not overlap. Before calling this function either cczp_init(zp) must have + been called or both CCZP_MOD_PRIME((cc_unit *)zp) and + CCZP_RECIP((cc_unit *)zp) must be initialized some other way. + Only support prime = 3 mod 4 */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3)) +int cczp_sqrt(cczp_const_t zp, cc_unit *r, const cc_unit *x); + +/* Compute r = m ^ e mod cczp_prime(zp), using Montgomery ladder. + - writes cczp_n(zp) units to r + - reads cczp_n(zp) units units from m and e + - if r and m are not identical they must not overlap. + - r and e must not overlap nor be identical. + - before calling this function either cczp_init(zp) must have been called + or both CCZP_MOD_PRIME((cc_unit *)zp) and CCZP_RECIP((cc_unit *)zp) must + be initialized some other way. + */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 4)) +int cczp_power(cczp_const_t zp, cc_unit *r, const cc_unit *m, + const cc_unit *e); + +/* Compute r = m ^ e mod cczp_prime(zp), using Square Square Multiply Always. + - writes cczp_n(zp) units to r + - reads cczp_n(zp) units units from m and e + - if r and m are not identical they must not overlap. + - r and e must not overlap nor be identical. + - before calling this function either cczp_init(zp) must have been called + or both CCZP_MOD_PRIME((cc_unit *)zp) and CCZP_RECIP((cc_unit *)zp) must + be initialized some other way. + + Important: This function is intented to be constant time but is more likely + to leak information due to memory cache. Only used with randomized input + */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 4)) +int cczp_power_ssma(cczp_const_t zp, cc_unit *r, const cc_unit *m, + const cc_unit *e); + +int cczp_power_ssma_ws(cc_ws_t ws, cczp_const_t zp, cc_unit *r, const cc_unit *s, const cc_unit *e); + +/* Compute r = m ^ e mod cczp_prime(zp). Will write cczp_n(zp) units to r and + reads cczp_n(zp) units units from m. Reads ebitlen bits from e. + m must be <= to cczp_prime(zp). If r and m are not identical they must not + overlap. r and e must not overlap nor be identical. + Before calling this function either cczp_init(zp) must have been called + or both CCZP_MOD_PRIME((cc_unit *)zp) and CCZP_RECIP((cc_unit *)zp) must + be initialized some other way. */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 5)) +int cczp_powern(cczp_const_t zp, cc_unit *r, const cc_unit *s, + size_t ebitlen, const cc_unit *e); + +/* Compute r = x + y mod cczp_prime(zp). Will write cczp_n(zp) units to r and + reads cczp_n(zp) units units from x and y. If r and x are not identical + they must not overlap. Only cczp_n(zp) and cczp_prime(zp) need to be valid. + Can be used with cczp_short_nof_n sized cc_unit array zp. */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 4)) +void cczp_add(cczp_const_t zp, cc_unit *r, const cc_unit *x, + const cc_unit *y); + +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 4, 5)) +void cczp_add_ws(cc_ws_t ws, cczp_const_t zp, cc_unit *r, const cc_unit *x, + const cc_unit *y); + +/* Compute r = x - y mod cczp_prime(zp). Will write cczp_n(zp) units to r and + reads cczp_n(zp) units units from x and y. If r and x are not identical + they must not overlap. Only cczp_n(zp) and cczp_prime(zp) need to be valid. + Can be used with cczp_short_nof_n sized cc_unit array zp. */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 4)) +void cczp_sub(cczp_const_t zp, cc_unit *r, const cc_unit *x, const cc_unit *y); + +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 4, 5)) +void cczp_sub_ws(cc_ws_t ws, cczp_const_t zp, cc_unit *r, const cc_unit *x, + const cc_unit *y); + +/* Compute r = x / 2 mod cczp_prime(zp). Will write cczp_n(zp) units to r and + reads cczp_n(zp) units units from x. If r and x are not identical + they must not overlap. Only cczp_n(zp) and cczp_prime(zp) need to be valid. + Can be used with cczp_short_nof_n sized cc_unit array zp. */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3)) +void cczp_div2(cczp_const_t zp, cc_unit *r, const cc_unit *x); + +/* Compute q = a_2n / cczp_prime(zd) (mod cczp_prime(zd)) . Will write cczp_n(zd) + units to q and r. Will read 2 * cczp_n(zd) units units from a. If r and a + are not identical they must not overlap. Before calling this function + either cczp_init(zp) must have been called or both + CCZP_MOD_PRIME((cc_unit *)zp) and CCZP_RECIP((cc_unit *)zp) must be + initialized some other way. */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 4)) +void cczp_div(cczp_const_t zd, cc_unit *q, cc_unit *r, const cc_unit *a_2n); + + +/*! + @brief cczp_inv(zp, r, x) computes r = x^-1 (mod p) , where p=cczp_prime(zp). + @discussion It is a general function and works for any p. It validates the inputs. r and x can overlap. It writes n =cczp_n(zp) units to r, and read n units units from x and p. The output r is overwriten only if the inverse is correctly computed. This function is not constant time in absolute sense, but it does not have data dependent 'if' statements in the code. + @param zp The input zp. cczp_n(zp) and cczp_prime(zp) need to be valid. cczp_init(zp) need not to be called before invoking cczp_inv(). + @param x input big integer + @param r output big integer + @return 0 if inverse exists and correctly computed. + */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3)) + +int cczp_inv(cczp_const_t zp, cc_unit *r, const cc_unit *x); + +/*! + @brief cczp_inv_odd(zp, r, x) computes r = x^-1 (mod p) , where p=cczp_prime(zp) is an odd number. + @discussion r and x can overlap. + @param zp The input zp. cczp_n(zp) and cczp_prime(zp) need to be valid. cczp_init(zp) need not to be called before invoking. + @param x input big integer + @param r output big integer + @return 0 if successful + */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3)) +int cczp_inv_odd(cczp_const_t zp, cc_unit *r, const cc_unit *x); + +/*! + @brief cczp_inv_field(zp, r, x) computes r = x^-1 (mod p) , where p=cczp_prime(zp) is a prime number number. + @discussion r and x must NOT overlap. The excution time of the function is independent to the value of the input x. It works only if p is a field. That is, when p is a prime. It supports Montgomery and non-Montgomery form of zp. It leaks the value of the prime and should only be used be used for public (not secret) primes (ex. Elliptic Curves) + + @param zp The input zp. cczp_n(zp) and cczp_prime(zp) need to be valid. cczp_init(zp) need not to be called before invoking cczp_inv_field(). + @param x input big unteger + @param r output big integer + @return 0 if inverse exists and correctly computed. + */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3)) +int cczp_inv_field(cczp_const_t zp, cc_unit *r, const cc_unit *x); + +#endif /* _CORECRYPTO_CCZP_H_ */ diff --git a/libraries/corecrypto/include/corecrypto/cczp_priv.h b/libraries/corecrypto/include/corecrypto/cczp_priv.h new file mode 100644 index 0000000..08e2750 --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/cczp_priv.h @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2014,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ + +#ifndef corecrypto_cczp_priv_h +#define corecrypto_cczp_priv_h + +#include +#include + +#define CCZP_MOD_WORKSPACE_N(n) (6*((n)+1)+CCN_MUL_WS_WORKSPACE_N(n)) +#define CCZP_MUL_WORKSPACE_N(n) (2*(n) + CCZP_MOD_WORKSPACE_N(n)) +#define CCZP_POWER_SSMA_WORKSPACE_N(n) (5*(n) + CCZP_MUL_WORKSPACE_N(n)) +#define CCZP_SQR_WORKSPACE_N(n) (CCZP_MUL_WORKSPACE_N(n)) +#define CCZP_ADD_WORKSPACE_N(n) (1*n) +#define CCZP_SUB_WORKSPACE_N(n) (1*n) + +#define CCZP_MONTGOMERY 1 + +/* + * Same as cczp_init with workspace + */ +void cczp_init_ws(cc_ws_t ws, cczp_t zp); + +/* + * Same as cczp_modn with workspace + */ +int cczp_modn_ws(cc_ws_t ws, cczp_const_t zp, cc_unit *r, cc_size ns, const cc_unit *s); + + +/* Compute r = m ^ e (mod p), where p=cczp_prime(zp). Writes n=cczp_n(zp) units to r and + reads n units units from m and e. If r and m are not identical + they must not overlap. r and e must not overlap nor be identical. + Before calling this function either cczp_init(zp) must have been called + or both CCZP_MOD_PRIME((cc_unit *)zp) and CCZP_RECIP((cc_unit *)zp) must + be initialized some other way. + + Use this function with PUBLIC values only, it may leak the parameters + in timing / Simple power analysis + */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3, 4)) +int +cczp_power_fast(cczp_const_t zp, cc_unit *r, const cc_unit *s, const cc_unit *e); + +/* + * Montgomery representation support + */ +CC_NONNULL_TU((1)) +CC_INLINE +bool cczp_is_montgomery(cczp_const_t zp) { + return (CCZP_OPS(zp) & CCZP_MONTGOMERY) == CCZP_MONTGOMERY ; +} + +/* + * to Montgomery representation + */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3)) +CC_INLINE +void cczp_convert_to_montgomery(cczp_const_t zp,cc_unit *r, const cc_unit *x) { + //ccn_lprint(cczp_n(zp)+1, "Montgomery cst:",cczp_recip(zp));q + cc_assert(cczp_is_montgomery(zp)); + cczp_mul(zp,r,x,cczp_recip(zp)); +} + +/* + * from Montgomery representation + */ +CC_NONNULL_TU((1)) CC_NONNULL((2, 3)) +CC_INLINE +void cczp_convert_from_montgomery(cczp_const_t zp,cc_unit *r, const cc_unit *x) { + cc_unit t2[2*cczp_n(zp)];//vla + ccn_setn(2*cczp_n(zp), t2, cczp_n(zp),x); + cczp_mod_prime(zp)(NULL, zp, r, t2); +} + +#if CORECRYPTO_USE_TRANSPARENT_UNION + #define cczp_const_decl(zp, ini) cczp_const_t (zp); (zp).zp = (ini); +#else + #define cczp_const_decl(zp, ini) cczp_const_t (zp) = (ini); +#endif + +#endif diff --git a/libraries/corecrypto/include/corecrypto/fipspost.h b/libraries/corecrypto/include/corecrypto/fipspost.h new file mode 100644 index 0000000..b4b9aec --- /dev/null +++ b/libraries/corecrypto/include/corecrypto/fipspost.h @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2012,2015,2016,2017,2018 Apple Inc. All rights reserved. + * + * corecrypto Internal Use License Agreement + * + * IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") + * in consideration of your agreement to the following terms, and your download or use + * of this Apple software constitutes acceptance of these terms. If you do not agree + * with these terms, please do not download or use this Apple software. + * + * 1. As used in this Agreement, the term "Apple Software" collectively means and + * includes all of the Apple corecrypto materials provided by Apple here, including + * but not limited to the Apple corecrypto software, frameworks, libraries, documentation + * and other Apple-created materials. In consideration of your agreement to abide by the + * following terms, conditioned upon your compliance with these terms and subject to + * these terms, Apple grants you, for a period of ninety (90) days from the date you + * download the Apple Software, a limited, non-exclusive, non-sublicensable license + * under Apple’s copyrights in the Apple Software to make a reasonable number of copies + * of, compile, and run the Apple Software internally within your organization only on + * devices and computers you own or control, for the sole purpose of verifying the + * security characteristics and correct functioning of the Apple Software; provided + * that you must retain this notice and the following text and disclaimers in all + * copies of the Apple Software that you make. You may not, directly or indirectly, + * redistribute the Apple Software or any portions thereof. The Apple Software is only + * licensed and intended for use as expressly stated above and may not be used for other + * purposes or in other contexts without Apple's prior written permission. Except as + * expressly stated in this notice, no other rights or licenses, express or implied, are + * granted by Apple herein. + * + * 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES + * OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING + * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, + * SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR + * REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR + * ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE + * SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL + * OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE + * WILL CREATE A WARRANTY. + * + * 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING + * IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE + * SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING + * NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * 4. This Agreement is effective until terminated. Your rights under this Agreement will + * terminate automatically without notice from Apple if you fail to comply with any term(s) + * of this Agreement. Upon termination, you agree to cease all use of the Apple Software + * and destroy all copies, full or partial, of the Apple Software. This Agreement will be + * governed and construed in accordance with the laws of the State of California, without + * regard to its choice of law rules. + * + * You may report security issues about Apple products to product-security@apple.com, + * as described here:  https://www.apple.com/support/security/. Non-security bugs and + * enhancement requests can be made via https://bugreport.apple.com as described + * here: https://developer.apple.com/bug-reporting/ + * + * EA1350 + * 10/5/15 + */ +#ifndef _CORECRYPTO_FIPSPOST_H_ +#define _CORECRYPTO_FIPSPOST_H_ + +#include + +// Error list +#define CCERR_GENERIC_FAILURE -1 // Configuration or unexpect issue +#define CCERR_INVALID_SLICE -2 +#define CCERR_FILE_ERROR -3 +#define CCERR_LIBRARY_ERROR -4 +#define CCERR_INTEGRITY_ERROR -5 +#define CCERR_KAT_FAILURE -6 // Output of the algo is not as expect + +// Boot-Arg fips_mode Flags +// +// FIPS_MODE_FLAG_FULL is the default value when no other value is set, which +// is the case for all production devices. +// +// When performing tests, if _FORCEFAIL is set to true, then the tests +// intentionally fail and log their failure. The kernelspace and userspace +// flags can be enabled independently. +// +// If it's not desired to panic, supply the _NOPANIC flag with the +// _FORCEFAIL flag. +// +// Additional logging can be enabled by supplying the _VERBOSE flag. +// +// _NOINTEG is used to ignore just the results of the module integrity +// check process, which is very useful when setting breakpoints in the +// kext for diagnostic or auditing purposes. +// +// Supplying _TRACE causes a trace buffer to be accumulated of the instrumented +// functions for only one execution of the POST. As the POST finishes, the +// _TRACE flag is cleared from the fips_mode and no further tracing will occur. +#define FIPS_MODE_FLAG_DEBUG (1 << 0) +#define FIPS_MODE_FLAG_FULL (1 << 1) +#define FIPS_MODE_FLAG_DISABLE (1 << 2) +#define FIPS_MODE_FLAG_VERBOSE (1 << 3) +#define FIPS_MODE_FLAG_US_FORCEFAIL (1 << 4) +#define FIPS_MODE_FLAG_KS_FORCEFAIL (1 << 5) +#define FIPS_MODE_FLAG_NOINTEG (1 << 6) +#define FIPS_MODE_FLAG_TRACE (1 << 7) +#define FIPS_MODE_FLAG_NOPANIC (1 << 8) + +#define FIPS_MODE_IS_DEBUG(MODE) ((MODE) & FIPS_MODE_FLAG_DEBUG) +#define FIPS_MODE_IS_FULL(MODE) ((MODE) & FIPS_MODE_FLAG_FULL) +#define FIPS_MODE_IS_DISABLE(MODE) ((MODE) & FIPS_MODE_FLAG_DISABLE) +#define FIPS_MODE_IS_VERBOSE(MODE) ((MODE) & FIPS_MODE_FLAG_VERBOSE) +#define FIPS_MODE_IS_US_FORCEFAIL(MODE) ((MODE) & FIPS_MODE_FLAG_US_FORCEFAIL) +#define FIPS_MODE_IS_KS_FORCEFAIL(MODE) ((MODE) & FIPS_MODE_FLAG_KS_FORCEFAIL) +#define FIPS_MODE_IS_NOINTEG(MODE) ((MODE) & FIPS_MODE_FLAG_NOINTEG) +#define FIPS_MODE_IS_TRACE(MODE) ((MODE) & FIPS_MODE_FLAG_TRACE) +#define FIPS_MODE_IS_NOPANIC(MODE) ((MODE) & FIPS_MODE_FLAG_NOPANIC) + +#if CC_KERNEL +#define FIPS_MODE_FLAG_FORCEFAIL FIPS_MODE_FLAG_KS_FORCEFAIL +#define FIPS_MODE_IS_FORCEFAIL(MODE) FIPS_MODE_IS_KS_FORCEFAIL(MODE) +#else +#define FIPS_MODE_FLAG_FORCEFAIL FIPS_MODE_FLAG_US_FORCEFAIL +#define FIPS_MODE_IS_FORCEFAIL(MODE) FIPS_MODE_IS_US_FORCEFAIL(MODE) +#endif + +struct mach_header; + +/* + * Entrypoint for all POST tests. + */ +int fipspost_post(int fips_mode, struct mach_header *pmach_header); + +#endif /* _CORECRYPTO_FIPSPOST_H_ */ diff --git a/libraries/corecrypto/include/module.modulemap b/libraries/corecrypto/include/module.modulemap new file mode 100644 index 0000000..4d09cf4 --- /dev/null +++ b/libraries/corecrypto/include/module.modulemap @@ -0,0 +1,14 @@ +module CCoreCrypto [system] { + header "corecrypto/ccsrp.h" + header "corecrypto/ccdrbg.h" + header "corecrypto/ccsrp_gp.h" + header "corecrypto/ccdigest.h" + header "corecrypto/ccsha2.h" + header "corecrypto/ccpbkdf2.h" + header "corecrypto/cchmac.h" + header "corecrypto/ccaes.h" + header "corecrypto/ccpad.h" + header "corecrypto/ccn.h" + + export * +} From ee591ae7965e73acf82f5d56a65f52ee6a3159ba Mon Sep 17 00:00:00 2001 From: zhongkaizhu Date: Sun, 15 May 2022 22:52:05 +0800 Subject: [PATCH 2/3] Feature: support build with cmake, only macOS now --- CMakeLists.txt | 135 +++++++++++++++++++++++++ makefiles/AltSign-build/CMakeLists.txt | 71 +++++++++++++ 2 files changed, 206 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 makefiles/AltSign-build/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..c64762f --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,135 @@ +cmake_minimum_required(VERSION 3.4.1...3.17.2) + +project(AltServer) + +set (CMAKE_CXX_STANDARD 17) +set (CXX_STANDARD_REQUIRED ON) +set (CMAKE_CXX_EXTENSIONS OFF) + +set(NO_USBMUXD_STUB ON CACHE BOOL "NO_USBMUXD_STUB Option") +if (NO_USBMUXD_STUB) + add_definitions(-DNO_USBMUXD_STUB) +endif() + +message(STATUS "NO_USBMUXD_STUB: " ${NO_USBMUXD_STUB}) + +if (UNIX) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DHAVE_CONFIG_H -DDEBUG -O0 -g") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DHAVE_CONFIG_H -DDEBUG -O0 -g") +endif() + +if (${CMAKE_SYSTEM_NAME} MATCHES "Linux") + set(CMAKE_POSITION_INDEPENDENT_CODE ON) +endif() + +# AltSign +# add_subdirectory(upstream_repo/AltSign) +add_subdirectory(makefiles/AltSign-build) + +# main +FILE(GLOB main_src + src/AltServerMain.cpp + src/AnisetteDataManager.cpp + src/WiredConnection.cpp + shims/windows_shim.cpp + + #upstream_repo/AltServer/AltServer.cpp + upstream_repo/AltServer/AltServerApp.cpp + #upstream_repo/AltServer/AnisetteDataManager.cpp + upstream_repo/AltServer/ClientConnection.cpp + upstream_repo/AltServer/ConnectionManager.cpp + upstream_repo/AltServer/DebugConnection.cpp + upstream_repo/AltServer/DeveloperDiskManager.cpp + upstream_repo/AltServer/DeviceManager.cpp + upstream_repo/AltServer/InstalledApp.cpp + upstream_repo/AltServer/NotificationConnection.cpp + upstream_repo/AltServer/ServerError.cpp + #upstream_repo/AltServer/WiredConnection.cpp + upstream_repo/AltServer/WirelessConnection.cpp) + +# libimobiledevice +FILE(GLOB libimobiledevice_src + libraries/libimobiledevice/src/*.c + libraries/libimobiledevice/common/*.c + libraries/libimobiledevice-glue/src/*.c + libraries/libusbmuxd/src/*.c + libraries/libusbmuxd/common/*.c + ) + +# libplist +FILE(GLOB libplist_src + libraries/libplist/src/*.c + libraries/libplist/libcnary/node.c + libraries/libplist/libcnary/node_list.c) + +# dnssd_loader +set(dnssd_loader_src + libraries/dnssd_loader/dnssd_loader.cpp +) + +add_executable(AltServer + ${main_src} + ${libimobiledevice_src} + ${libplist_src} + ${dnssd_loader_src} +) + +target_include_directories(AltServer PUBLIC + ${OPENSSL_INCLUDE_DIR} + libraries + libraries/AltSign + libraries/libimobiledevice + libraries/libimobiledevice/include + libraries/libusbmuxd/include + libraries/libplist/include + libraries/libplist/libcnary/include + libraries/libplist/src + libraries/libusbmuxd/common + ) + +if (UNIX) + set(THREADS_PREFER_PTHREAD_FLAG TRUE) + find_package(Threads) + target_link_libraries(AltServer PRIVATE Threads::Threads) +endif() + +target_compile_options(AltServer PRIVATE -fpermissive -include common.h) +target_link_libraries(AltServer PRIVATE AltSign ssl crypto z cpprest boost_system boost_filesystem uuid c++) + +# Help finding Homebrew's OpenSSL on macOS +if (APPLE) + # This is for apple silicon (M1) + set(HOMEBREW_PREFIX "/opt/homebrew" + CACHE PATH "Path to Homebrew installation") + + # This is for apple x86 + # set(HOMEBREW_PREFIX "/usr/local" + # CACHE PATH "Path to Homebrew installation") + + set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} ${HOMEBREW_PREFIX}/opt/openssl/lib) + set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} ${HOMEBREW_PREFIX}/opt/openssl/include) + + # This OPENSSL_FOUND check is to help find a cmake manually configured OpenSSL + if (NOT OPENSSL_FOUND) + find_package(OpenSSL REQUIRED) + endif() + message(STATUS "OpenSSL: " ${OPENSSL_VERSION} ${OPENSSL_INCLUDE_PATH}) + + add_definitions(${OPENSSL_DEFINITIONS}) + target_include_directories(AltServer PUBLIC + ${HOMEBREW_PREFIX}/include + ${OPENSSL_INCLUDE_DIR} + libraries/libimobiledevice-glue/include/ + libraries/corecrypto/include/corecrypto + upstream_repo/AltServer + upstream_repo/AltSign + src/ + shims/ + ) + + target_link_directories(AltServer PUBLIC + ${HOMEBREW_PREFIX}/opt/openssl/lib + ${HOMEBREW_PREFIX}/lib + ) + target_link_libraries(AltServer PRIVATE "-framework Foundation") +endif() \ No newline at end of file diff --git a/makefiles/AltSign-build/CMakeLists.txt b/makefiles/AltSign-build/CMakeLists.txt new file mode 100644 index 0000000..4d4b5c5 --- /dev/null +++ b/makefiles/AltSign-build/CMakeLists.txt @@ -0,0 +1,71 @@ +cmake_minimum_required(VERSION 3.4.1...3.17.2) + +project(AltSign) + +set (CMAKE_CXX_STANDARD 17) +set (CXX_STANDARD_REQUIRED ON) +set (CMAKE_CXX_EXTENSIONS OFF) + +set(AltSignSrcPath ../../upstream_repo/AltSign/) + +if (UNIX) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mno-sse -include windows_shim.h") +endif() + +if (${CMAKE_SYSTEM_NAME} MATCHES "Linux") + set(CMAKE_POSITION_INDEPENDENT_CODE ON) +endif() + +FILE(GLOB ALTSIGN_SOURCES ${AltSignSrcPath}/*.cpp) + +list(APPEND ALTSIGN_SOURCES + ${AltSignSrcPath}/Dependencies/minizip/ioapi.c + ${AltSignSrcPath}/Dependencies/minizip/zip.c + ${AltSignSrcPath}/Dependencies/minizip/unzip.c + ${AltSignSrcPath}/../ldid/ldid.cpp + ${AltSignSrcPath}/../ldid/lookup2.c +) + +# corecrypto +if (APPLE) + list(APPEND ALTSIGN_SOURCES ${AltSignSrcPath}/../../libraries/corecrypto/Sources/ccsrp.m) + add_definitions(-DCORECRYPTO_DONOT_USE_TRANSPARENT_UNION=1) +endif() + +# Static library +add_library(AltSign + ${ALTSIGN_SOURCES} +) + +# Help finding Homebrew's OpenSSL on macOS +if (APPLE) + # This is for apple silicon (M1) + set(HOMEBREW_PREFIX "/opt/homebrew" + CACHE PATH "Path to Homebrew installation") + + # This is for apple x86 + # set(HOMEBREW_PREFIX "/usr/local" + # CACHE PATH "Path to Homebrew installation") + + set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} ${HOMEBREW_PREFIX}/opt/openssl/lib) + set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} ${HOMEBREW_PREFIX}/opt/openssl/include) + + # This OPENSSL_FOUND check is to help find a cmake manually configured OpenSSL + if (NOT OPENSSL_FOUND) + find_package(OpenSSL REQUIRED) + endif() + message(STATUS "OpenSSL: " ${OPENSSL_VERSION} ${OPENSSL_INCLUDE_PATH}) + + add_definitions(${OPENSSL_DEFINITIONS}) + target_include_directories(AltSign PUBLIC + ${HOMEBREW_PREFIX}/include + ${OPENSSL_INCLUDE_DIR} + ${AltSignSrcPath}/../../libraries/corecrypto/include/ + ${AltSignSrcPath}/../../libraries/corecrypto/include/corecrypto + #Dependencies/corecrypto + ${AltSignSrcPath}/Dependencies/minizip/ + ${AltSignSrcPath}/../libplist/include + ${AltSignSrcPath}/../ldid/ + ${AltSignSrcPath}/../../shims + ) +endif() From 3613e179a755e01052889eea9ec3ddbc99447ab1 Mon Sep 17 00:00:00 2001 From: zhongkaizhu Date: Sun, 15 May 2022 22:53:45 +0800 Subject: [PATCH 3/3] Fix build break on macOS --- libraries/dnssd_loader/dnssd_loader.cpp | 4 + makefiles/patch.py | 256 ++++++++++++++++++++++++ shims/windows_shim.h | 2 + src/AltServerMain.cpp | 4 + src/common.h | 1 + src/config.h | 44 ++++ 6 files changed, 311 insertions(+) create mode 100644 makefiles/patch.py create mode 100644 src/config.h diff --git a/libraries/dnssd_loader/dnssd_loader.cpp b/libraries/dnssd_loader/dnssd_loader.cpp index ed90b1b..8968557 100644 --- a/libraries/dnssd_loader/dnssd_loader.cpp +++ b/libraries/dnssd_loader/dnssd_loader.cpp @@ -2,7 +2,9 @@ #include #include #include +#ifdef __linux__ #include // prctl(), PR_SET_PDEATHSIG +#endif #include // signals @@ -57,8 +59,10 @@ DNSServiceErrorType DNSSD_API DNSServiceRegister return EXIT_FAILURE; } if(child == 0){ + #ifdef __linux__ int r = prctl(PR_SET_PDEATHSIG, SIGTERM); if (r == -1) { perror(0); exit(1); } + #endif // test in case the original parent exited just // before the prctl() call if (getppid() != ppid_before_fork) diff --git a/makefiles/patch.py b/makefiles/patch.py new file mode 100644 index 0000000..b098d32 --- /dev/null +++ b/makefiles/patch.py @@ -0,0 +1,256 @@ +#!/usr/bin/python3 + +import re +import sys + +def patch_altsign(source_file): + with open(source_file, 'rb') as f: + content = f.read() + + content = re.sub(br'L("([^"\\]|\\.)*")', br'U(\1)', content) + content = content.replace(b'std::wstring', b'std::string') + content = content.replace(b'boost/filesystem.hpp', b'filesystem') + content = content.replace(b'boost::filesystem', b'std::filesystem') + + content = content.replace(b'"%FT%T%z"', b'"%Y-%m-%dT%H:%M:%SZ"') + content = content.replace(b'localtime(', b'gmtime(') + + content = content.replace(b'winsock2.h', b'WinSock2.h') + + with open(source_file, 'wb') as f: + f.write(content) + + +def patch_ldid(source_file): + with open(source_file, 'rb') as f: + content = f.read() + + content = content.replace(br'\\\\', br'/') # c escape + regex escape = 2*2 + content = content.replace(br'\\', br'/') + content = re.sub(br'/(\.[A-Za-z])', br'\\\\\1', content) + + content = content.replace(br'int main(', br'int __main(') + + with open(source_file, 'wb') as f: + f.write(content) + + +def patch_altserver(source_file): + str1=br''' +#define IDCANCEL 0 +#define MessageBox(x, content, title, xx) (this->ShowAlert(title, content " (Ctrl-C to avoid)"), 1) + +// Observes all exceptions that occurred in all tasks in the given range. +template +void observe_all_exceptions(InIt first, InIt last) +{ + // TODO: FIX THIS +} +''' + str2=br''' +HWND AltServerApp::windowHandle() const +{ + return _windowHandle; +} + +HINSTANCE AltServerApp::instanceHandle() const +{ + return _instanceHandle; +} + + +bool AltServerApp::boolValueForRegistryKey(std::string key) const +{ + return false; +} + +void AltServerApp::setBoolValueForRegistryKey(bool value, std::string key) +{ + return; +} + +std::string AltServerApp::serverID() const +{ + //auto serverID = GetRegistryStringValue(SERVER_ID_KEY); + //return serverID; + return "1234567"; +} + +pplx::task, std::shared_ptr>> AltServerApp::Authenticate(std::string appleID, std::string password, std::shared_ptr anisetteData) +{ + auto verificationHandler = [=](void)->pplx::task> { + return pplx::create_task([=]() -> std::optional { + std::cout << "Enter two factor code" << std::endl; + std::string _verificationCode = ""; + std::cin >> _verificationCode; + auto verificationCode = std::make_optional(_verificationCode); + _verificationCode = ""; + + return verificationCode; + }); + }; + + return pplx::create_task([=]() { + if (anisetteData == NULL) + { + throw ServerError(ServerErrorCode::InvalidAnisetteData); + } + + return AppleAPI::getInstance()->Authenticate(appleID, password, anisetteData, verificationHandler); + }); +} + +void AltServerApp::HandleAnisetteError(AnisetteError& error) +{ + this->ShowAlert("AnisetteData error: ", error.localizedDescription()); +} + +void AltServerApp::ShowNotification(std::string title, std::string message) +{ + std::cout << "Notify: " << title << std::endl << " " << message << std::endl; +} + + +extern "C" int getchar(); +void AltServerApp::ShowAlert(std::string title, std::string message) +{ + std::cout << "Alert: " << title << std::endl << " " << message << std::endl; + std::cout << "Press any key to continue..." << std::endl; + //char a; + //std::cin >> a; + getchar(); +} + +fs::path AltServerApp::appDataDirectoryPath() const +{ + fs::path altserverDirectoryPath("./AltServerData"); + + if (!fs::exists(altserverDirectoryPath)) + { + fs::create_directory(altserverDirectoryPath); + } + + return altserverDirectoryPath; +} + +void AltServerApp::Start(HWND windowHandle, HINSTANCE instanceHandle) +{ + ConnectionManager::instance()->Start(); + + // DeviceManager only needs + const char *isNoUSB = getenv("ALTSERVER_NO_SUBSCRIBE"); + if (!isNoUSB) { + DeviceManager::instance()->Start(); + } +} + +void AltServerApp::Stop() +{ +} +''' + + with open(source_file, 'rb') as f: + content = f.read() + + content = re.sub(br'L("([^"\\]|\\.)*")', br'U(\1)', content) + content = re.sub(br'\n(std::string StringFromWideString.*?\n\{[\s\S]+?\})', br'/*\1*/', content) + content = re.sub(br'\n(std::wstring WideStringFromString.*?\n\{[\s\S]+?\})', br'/*\1*/', content) + content = content.replace(b'std::wstring', b'std::string') + content = content.replace(b'std::string_convert', b'std::wstring_convert') + + content = content.replace(b'boost/filesystem.hpp', b'filesystem') + content = content.replace(b'boost::filesystem', b'std::filesystem') + + if source_file.endswith('AltServerApp.cpp'): + + # MessageBox + # IDCANCEL + # fs::path AltServerApp::appDataDirectoryPath + content = content.replace(b'\r', b'') + + content = content.replace(b'#include \n', b'') + content = content.replace(b'#include \n', b'') + content = content.replace(b'#include \n', b'') + content = content.replace(b'#include \n', b'') + content = content.replace(b'#include \n', b'') + content = content.replace(b'#pragma comment( lib, "gdiplus.lib" ) \n', b'') + content = content.replace(b'#include \n', b'') + content = content.replace(b'#include "resource.h"\n', b'') + + def removePart(content, start, end): + content = re.sub(br'\n' + start + br'[\S\s]+?(' + end + br')', br'\1', content) + return content + content = removePart(content, br'const char\* REGISTRY_ROOT_KEY', br'\nAltServerApp\* AltServerApp::_instance') + content = removePart(content, br'static int CALLBACK BrowseFolderCallback', br'\npplx::task> AltServerApp::InstallApplication') + content = removePart(content, br'\n.*? AltServerApp::Authenticate', br'\npplx::task> AltServerApp::FetchTeam') + content = removePart(content, br'void AltServerApp::ShowNotification', br'\nvoid AltServerApp::ShowErrorAlert') + content = removePart(content, br'bool AltServerApp::CheckDependencies', br'\nfs::path AltServerApp::certificatesDirectoryPath') + + def insertBefore(content, marker, newcontent): + content = content.replace(marker, newcontent + b'\n' + marker) + return content + + content = insertBefore(content, b'AltServerApp* AltServerApp::_instance = nullptr;', str1) + content = insertBefore(content, b'fs::path AltServerApp::certificatesDirectoryPath', str2) + + with open(source_file, 'wb') as f: + f.write(content) + + +def patch_for_macOS(): + source_file = "upstream_repo/AltServer/ConnectionManager.cpp" + with open(source_file, 'rb') as f: + content = f.read() + content = content.replace(br'int addrlen = sizeof(clientAddress);', br'socklen_t addrlen = sizeof(clientAddress);') + with open(source_file, 'wb') as f: + f.write(content) + + source_file = "upstream_repo/AltSign/Archiver.cpp" + with open(source_file, 'rb') as f: + content = f.read() + content = content.replace(b'#include ', b'#include \n#include ') + with open(source_file, 'wb') as f: + f.write(content) + + source_file = "upstream_repo/AltSign/ProvisioningProfile.cpp" + with open(source_file, 'rb') as f: + content = f.read() + content = content.replace(br'timeval creationDate = { this->_creationDateSeconds, this->_creationDateMicroseconds };', + br'timeval creationDate = { this->_creationDateSeconds, static_cast(this->_creationDateMicroseconds) };') + content = content.replace(br'timeval expirationDate = { this->_expirationDateSeconds, this->_expirationDateMicroseconds };', + br'timeval expirationDate = { this->_expirationDateSeconds, static_cast(this->_expirationDateMicroseconds) };') + with open(source_file, 'wb') as f: + f.write(content) + +# patch now + +## patch altsign +altsign_files = ["AltSign/AnisetteData.cpp", + "AltSign/AppleAPI+Authentication.cpp", + "AltSign/AppleAPI.cpp", + "AltSign/AppleAPI.hpp", + "AltSign/Archiver.cpp", + "AltSign/Certificate.cpp", + "AltSign/ProvisioningProfile.cpp", + ] +for f in altsign_files: + patch_altsign("upstream_repo/" + f) + +## path ldid +patch_ldid("upstream_repo/ldid/ldid.cpp") + +## patch altserver +server_files = ["AltServer/AltServer.cpp", + "AltServer/AltServerApp.cpp", + "AltServer/AltServerApp.h", + "AltServer/AnisetteDataManager.cpp", + "AltServer/ClientConnection.cpp", + "AltServer/ConnectionManager.cpp", + "AltServer/DeveloperDiskManager.cpp", + "AltServer/DeviceManager.cpp", +] +for f in server_files: + patch_altserver("upstream_repo/" + f) + +## patch build +patch_for_macOS() diff --git a/shims/windows_shim.h b/shims/windows_shim.h index dfc70fc..d2d6572 100644 --- a/shims/windows_shim.h +++ b/shims/windows_shim.h @@ -10,7 +10,9 @@ char *_itoa(int val, char *buf, int base); #include +#ifndef __declspec #define __declspec(x) +#endif #define OutputDebugStringW(x) (std::wcout << x) #define OutputDebugStringA(x) (std::cout << x) diff --git a/src/AltServerMain.cpp b/src/AltServerMain.cpp index e169582..be308cb 100644 --- a/src/AltServerMain.cpp +++ b/src/AltServerMain.cpp @@ -28,6 +28,10 @@ #include #include +#ifndef UUID_STR_LEN +#define UUID_STR_LEN 37 +#endif + std::string make_uuid() { uuid_t b; char out[UUID_STR_LEN] = {0}; diff --git a/src/common.h b/src/common.h index 3053b68..5b7daf3 100644 --- a/src/common.h +++ b/src/common.h @@ -1,6 +1,7 @@ #pragma once #include +#include "windows_shim.h" typedef int HWND; typedef int HINSTANCE; diff --git a/src/config.h b/src/config.h new file mode 100644 index 0000000..f7c913a --- /dev/null +++ b/src/config.h @@ -0,0 +1,44 @@ +#define HAVE_ASPRINTF 1 +#define HAVE_DIRENT_D_TYPE 1 +#define HAVE_DLFCN_H 1 +#define HAVE_FVISIBILITY 1 +#define HAVE_GCRYPT_H 1 +#define HAVE_GETIFADDRS 1 +#define HAVE_GMTIME_R 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_LOCALTIME_R 1 +#define HAVE_MALLOC 1 +#define HAVE_MEMMEM 1 +#define HAVE_MEMORY_H 1 +#define HAVE_OPENSSL 1 +#define HAVE_PTHREAD 1 +#define HAVE_PTHREAD_CANCEL 1 +#define HAVE_PTHREAD_PRIO_INHERIT 1 +#define HAVE_REALLOC 1 +#define HAVE_SLEEP 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDLIB_H 1 +#define HAVE_STPCPY 1 +#define HAVE_STPNCPY 1 +#define HAVE_STRCASECMP 1 +#define HAVE_STRDUP 1 +#define HAVE_STRERROR 1 +#define HAVE_STRINGS_H 1 +#define HAVE_STRING_H 1 +#define HAVE_STRNDUP 1 +#define HAVE_STRPTIME 1 +#define HAVE_SYS_STAT_H 1 +#define HAVE_SYS_TYPES_H 1 +#define HAVE_TIMEGM 1 +#define HAVE_TM_TM_GMTOFF 1 +#define HAVE_TM_TM_ZONE 1 +#define HAVE_UNISTD_H 1 +#define HAVE_VASPRINTF 1 +#define PACKAGE_STRING "jitterbug 1.0" +#define __BIG_ENDIAN 4321 +#define __LITTLE_ENDIAN 1234 + +#ifdef __BYTE_ORDER +#undef __BYTE_ORDER +#endif +#define __BYTE_ORDER 1234