From e28d25619767f3578625f553e2ee84c0e47b5646 Mon Sep 17 00:00:00 2001 From: Takashi Kojo Date: Fri, 31 Jan 2014 08:44:42 +0900 Subject: [PATCH] CyaSSL master, 2.8.6 --- .gitignore | 7 + IDE/IAR-EWARM/CyaSSL/HTTPS-main.h | 34 + IDE/MDK5-ARM/Projects/CryptTest/test.c | 6 +- IDE/MDK5-ARM/Projects/CyaSSL-Full/server.c | 8 +- IDE/MDK5-ARM/Projects/CyaSSL-Full/test.c | 6 +- Makefile.am | 1 + README | 9 + configure.ac | 112 +- ctaocrypt/benchmark/benchmark.c | 43 +- ctaocrypt/src/aes.c | 128 +- ctaocrypt/src/asm.c | 12 +- ctaocrypt/src/asn.c | 927 +++++-- ctaocrypt/src/coding.c | 154 +- ctaocrypt/src/des3.c | 181 ++ ctaocrypt/src/ecc.c | 337 ++- ctaocrypt/src/error.c | 20 + ctaocrypt/src/fp_sqr_comba_12.i | 4 +- ctaocrypt/src/fp_sqr_comba_17.i | 3 + ctaocrypt/src/fp_sqr_comba_3.i | 3 + ctaocrypt/src/fp_sqr_comba_4.i | 3 + ctaocrypt/src/fp_sqr_comba_6.i | 3 + ctaocrypt/src/fp_sqr_comba_7.i | 3 + ctaocrypt/src/fp_sqr_comba_8.i | 3 + ctaocrypt/src/fp_sqr_comba_9.i | 3 + ctaocrypt/src/integer.c | 2 +- ctaocrypt/src/md5.c | 24 +- ctaocrypt/src/pkcs7.c | 1348 +++++++++++ ctaocrypt/src/sha.c | 45 +- ctaocrypt/src/sha256.c | 51 +- ctaocrypt/src/sha512.c | 26 +- ctaocrypt/test/test.c | 575 ++++- cyassl-ntru.vcproj | 20 + cyassl.vcproj | 20 + cyassl/ctaocrypt/aes.h | 3 + cyassl/ctaocrypt/asn.h | 99 +- cyassl/ctaocrypt/asn_public.h | 27 +- cyassl/ctaocrypt/coding.h | 3 + cyassl/ctaocrypt/des3.h | 8 +- cyassl/ctaocrypt/ecc.h | 44 +- cyassl/ctaocrypt/error.h | 8 + cyassl/ctaocrypt/include.am | 1 + cyassl/ctaocrypt/integer.h | 5 +- cyassl/ctaocrypt/pkcs7.h | 123 + cyassl/ctaocrypt/settings.h | 54 +- cyassl/ctaocrypt/tfm.h | 68 +- cyassl/ctaocrypt/types.h | 20 +- cyassl/include.am | 5 +- cyassl/internal.h | 101 +- cyassl/internal.h.orig | 2121 +++++++++++++++++ cyassl/ocsp.h | 8 +- cyassl/ssl.h | 66 +- cyassl/version.h | 4 +- examples/client/client.c | 15 +- examples/echoclient/echoclient.c | 4 +- examples/echoserver/echoserver.c | 4 +- examples/server/server.c | 23 +- m4/ax_debug.m4 | 1 - m4/ax_tls.m4 | 76 + .../nbproject/configurations.xml | 22 - .../nbproject/configurations.xml | 22 - mcapi/ctaocrypt_test.X/nbproject/include.am | 3 +- mcapi/cyassl.X/nbproject/include.am | 1 - mcapi/include.am | 7 +- mcapi/mcapi_test.c | 6 +- .../nbproject/configurations.xml | 27 +- .../nbproject/include.am | 3 +- .../nbproject/configurations.xml | 5 +- mplabx/ctaocrypt_test.X/nbproject/include.am | 3 +- mplabx/cyassl.X/nbproject/configurations.xml | 29 +- mplabx/cyassl.X/nbproject/include.am | 1 - mplabx/include.am | 10 + src/include.am | 4 + src/internal.c | 273 ++- src/io.c | 129 +- src/ocsp.c | 121 +- src/sniffer.c | 7 + src/ssl.c | 692 +++++- src/tls.c | 146 +- sslSniffer/sslSnifferTest/include.am | 2 +- sslSniffer/sslSnifferTest/snifftest.c | 24 +- tests/api.c | 88 + tests/unit.c | 6 +- testsuite/testsuite.c | 23 +- 83 files changed, 7807 insertions(+), 859 deletions(-) create mode 100644 IDE/IAR-EWARM/CyaSSL/HTTPS-main.h create mode 100644 ctaocrypt/src/pkcs7.c create mode 100644 cyassl/ctaocrypt/pkcs7.h create mode 100644 cyassl/internal.h.orig create mode 100644 m4/ax_tls.m4 create mode 100644 mplabx/include.am diff --git a/.gitignore b/.gitignore index e4c4d2d48..ee2053048 100644 --- a/.gitignore +++ b/.gitignore @@ -46,10 +46,17 @@ testsuite/*.pem testsuite/*.raw cert.der cert.pem +certecc.der +certecc.pem othercert.der othercert.pem key.der key.pem +certreq.der +certreq.pem +pkcs7cert.der +pkcs7signedData.der +pkcs7envelopedData.der diff sslSniffer/sslSnifferTest/tracefile.txt *.gz diff --git a/IDE/IAR-EWARM/CyaSSL/HTTPS-main.h b/IDE/IAR-EWARM/CyaSSL/HTTPS-main.h new file mode 100644 index 000000000..4cd54ab74 --- /dev/null +++ b/IDE/IAR-EWARM/CyaSSL/HTTPS-main.h @@ -0,0 +1,34 @@ +/* HTTPS-main.h + * + * Copyright (C) 2006-2014 wolfSSL Inc. + * + * This file is part of CyaSSL. + * + * CyaSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * CyaSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#ifndef __HTTPS_MAIN_H__ +#define __HTTPS_MAIN_H__ + +extern CYASSL_HTTPS_NB CyaSSL_HTTPS_Client_1 ; +extern CYASSL_HTTPS_NB CyaSSL_HTTPS_Client_2 ; +extern CYASSL_HTTPS_NB CyaSSL_HTTPS_Client_3 ; +extern CYASSL_HTTPS_NB CyaSSL_HTTPS_Client_4 ; +extern CYASSL_HTTPS_NB CyaSSL_HTTPS_Client_5 ; + +extern void HTTPS_Clinet_main_init(void) ; +extern void HTTPS_Clinet_main(void) ; + +#endif diff --git a/IDE/MDK5-ARM/Projects/CryptTest/test.c b/IDE/MDK5-ARM/Projects/CryptTest/test.c index 7ba1b0b39..086032ab7 100644 --- a/IDE/MDK5-ARM/Projects/CryptTest/test.c +++ b/IDE/MDK5-ARM/Projects/CryptTest/test.c @@ -2779,7 +2779,8 @@ int rsa_test(void) if (certSz < 0) return -407; - certSz = SignCert(&myCert, derCert, FOURK_BUF, &caKey, &rng); + certSz = SignCert(myCert.bodySz, myCert.sigType, derCert, FOURK_BUF, + &caKey, &rng); if (certSz < 0) return -408; @@ -2891,7 +2892,8 @@ int rsa_test(void) if (certSz < 0) return -456; - certSz = SignCert(&myCert, derCert, FOURK_BUF, &caKey, &rng); + certSz = SignCert(myCert.bodySz, myCert.sigType, derCert, FOURK_BUF, + &caKey, &rng); if (certSz < 0) return -457; diff --git a/IDE/MDK5-ARM/Projects/CyaSSL-Full/server.c b/IDE/MDK5-ARM/Projects/CyaSSL-Full/server.c index 8e155f30a..88a6064b4 100644 --- a/IDE/MDK5-ARM/Projects/CyaSSL-Full/server.c +++ b/IDE/MDK5-ARM/Projects/CyaSSL-Full/server.c @@ -347,6 +347,10 @@ THREAD_RETURN CYASSL_THREAD server_test(void* args) usePsk = 1; #endif +#ifdef OPENSSL_EXTRA + SSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack); +#endif + if (fewerPackets) CyaSSL_CTX_set_group_messages(ctx); @@ -404,10 +408,6 @@ THREAD_RETURN CYASSL_THREAD server_test(void* args) } #endif -#ifdef OPENSSL_EXTRA - SSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack); -#endif - #if defined(CYASSL_SNIFFER) && !defined(HAVE_NTRU) && !defined(HAVE_ECC) /* don't use EDH, can't sniff tmp keys */ if (cipherList == NULL) { diff --git a/IDE/MDK5-ARM/Projects/CyaSSL-Full/test.c b/IDE/MDK5-ARM/Projects/CyaSSL-Full/test.c index 6165cee31..22b4070eb 100644 --- a/IDE/MDK5-ARM/Projects/CyaSSL-Full/test.c +++ b/IDE/MDK5-ARM/Projects/CyaSSL-Full/test.c @@ -2550,7 +2550,8 @@ int rsa_test(void) if (certSz < 0) return -407; - certSz = SignCert(&myCert, derCert, FOURK_BUF, &caKey, &rng); + certSz = SignCert(myCert.bodySz, myCert.sigType, derCert, FOURK_BUF, + &caKey, &rng); if (certSz < 0) return -408; @@ -2662,7 +2663,8 @@ int rsa_test(void) if (certSz < 0) return -456; - certSz = SignCert(&myCert, derCert, FOURK_BUF, &caKey, &rng); + certSz = SignCert(myCert.bodySz, myCert.sigType, derCert, FOURK_BUF, + &caKey, &rng); if (certSz < 0) return -457; diff --git a/Makefile.am b/Makefile.am index 651b60afb..02fea25cc 100644 --- a/Makefile.am +++ b/Makefile.am @@ -62,6 +62,7 @@ include mqx/ctaocrypt_test/Sources/include.am include mqx/cyassl/include.am include mqx/cyassl_client/Sources/include.am include mqx/util_lib/Sources/include.am +include mplabx/include.am include mplabx/ctaocrypt_benchmark.X/nbproject/include.am include mplabx/ctaocrypt_test.X/nbproject/include.am include mplabx/cyassl.X/nbproject/include.am diff --git a/README b/README index 98a59480d..f0c02b584 100644 --- a/README +++ b/README @@ -37,10 +37,19 @@ before calling SSL_new(); Though it's not recommended. CyaSSL Release 2.9.0 (X/XX/XXXX) +Release 2.9.0 CyaSSL has bug fixes and new features including: +- Freescale Kinetis RNGB support +- Freescale Kinetis mmCAU support + The Freescale Kinetis K53 RNGB documentation can be found in Chapter 33 of the K53 Sub-Family Reference Manual: http://cache.freescale.com/files/32bit/doc/ref_manual/K53P144M100SF2RM.pdf +Freescale Kinetis K60 mmCAU (AES, DES, 3DES, MD5, SHA, SHA256) documentation +can be found in the "ColdFire/ColdFire+ CAU and Kinetis mmCAU Software Library +User Guide": +http://cache.freescale.com/files/32bit/doc/user_guide/CAUAPIUG.pdf + *****************CyaSSL Release 2.8.0 (8/30/2013) diff --git a/configure.ac b/configure.ac index 55169de1b..eda0bd416 100644 --- a/configure.ac +++ b/configure.ac @@ -6,7 +6,7 @@ # # -AC_INIT([cyassl],[2.8.3],[https://github.com/cyassl/cyassl/issues],[cyassl],[http://www.yassl.com]) +AC_INIT([cyassl],[2.8.6],[https://github.com/cyassl/cyassl/issues],[cyassl],[http://www.yassl.com]) AC_CONFIG_AUX_DIR([build-aux]) @@ -103,6 +103,8 @@ OPTIMIZE_FAST_CFLAGS="-O2 -fomit-frame-pointer" OPTIMIZE_HUGE_CFLAGS="-funroll-loops -DTFM_SMALL_SET -DTFM_HUGE_SET" DEBUG_CFLAGS="-g -DDEBUG -DDEBUG_CYASSL" +# Thread local storage +AX_TLS([AM_CFLAGS="$AM_CFLAGS -DHAVE_THREAD_LS"]) # DEBUG AX_DEBUG @@ -308,17 +310,20 @@ fi # SNIFFER +ENABLED_SNIFFTEST=no AC_ARG_ENABLE([sniffer], - [AS_HELP_STRING([--enable-sniffer],[ Enable CyaSSL sniffer support (default: disabled) ])],[ - AS_IF([ test "x$enableval" = "xyes" ],[ AC_CHECK_HEADERS([pcap/pcap.h],[ - ENABLED_SNIFFER=yes - AM_CFLAGS="$AM_CFLAGS -DCYASSL_SNIFFER -DOPENSSL_EXTRA" - ],[ ENABLED_SNIFFER=no ]) ]) - ],[ - ENABLED_SNIFFER=no - ]) + [AS_HELP_STRING([--enable-sniffer],[ Enable CyaSSL sniffer support (default: disabled) ])],[ + ENABLED_SNIFFER=yes + AM_CFLAGS="$AM_CFLAGS -DCYASSL_SNIFFER -DOPENSSL_EXTRA" + AS_IF([ test "x$enableval" = "xyes" ],[ AC_CHECK_HEADERS([pcap/pcap.h],[ + ENABLED_SNIFFTEST=yes + ],[ AC_MSG_WARN([cannot enable sniffer test without having libpcap available.]) ]) ]) + ],[ + ENABLED_SNIFFER=no + ]) -AM_CONDITIONAL([BUILD_SNIFFER], [ test "x$ENABLED_SNIFFER" = "xyes" ]) +AM_CONDITIONAL([BUILD_SNIFFER], [ test "x$ENABLED_SNIFFER" = "xyes" ]) +AM_CONDITIONAL([BUILD_SNIFFTEST], [ test "x$ENABLED_SNIFFTEST" = "xyes" ]) # AES-GCM AC_ARG_ENABLE([aesgcm], @@ -526,6 +531,23 @@ then fi +# CERT REQUEST GENERATION +AC_ARG_ENABLE([certreq], + [ --enable-certreq Enable cert request generation (default: disabled)], + [ ENABLED_CERTREQ=$enableval ], + [ ENABLED_CERTREQ=no ] + ) + +if test "$ENABLED_CERTREQ" = "yes" +then + if test "$ENABLED_CERTGEN" = "no" + then + AC_MSG_ERROR([cannot enable certreq without enabling certgen.]) + fi + AM_CFLAGS="$AM_CFLAGS -DCYASSL_CERT_REQ" +fi + + # SEP AC_ARG_ENABLE([sep], [ --enable-sep Enable sep extensions (default: disabled)], @@ -1178,6 +1200,18 @@ then AM_CFLAGS="$AM_CFLAGS -DHAVE_TLS_EXTENSIONS -DHAVE_TRUNCATED_HMAC" fi +# Renegotiation Indication +AC_ARG_ENABLE([renegotiation-indication], + [ --enable-renegotiation-indication Enable Renegotiation Indication (default: disabled)], + [ ENABLED_RENEGOTIATION_INDICATION=$enableval ], + [ ENABLED_RENEGOTIATION_INDICATION=no ] + ) + +if test "x$ENABLED_RENEGOTIATION_INDICATION" = "xyes" +then + AM_CFLAGS="$AM_CFLAGS -DHAVE_TLS_EXTENSIONS -DHAVE_RENEGOTIATION_INDICATION" +fi + # TLS Extensions AC_ARG_ENABLE([tlsx], [ --enable-tlsx Enable all TLS Extensions (default: disabled)], @@ -1189,9 +1223,60 @@ if test "x$ENABLED_TLSX" = "xyes" then ENABLED_SNI=yes ENABLED_MAX_FRAGMENT=yes - AM_CFLAGS="$AM_CFLAGS -DHAVE_TLS_EXTENSIONS -DHAVE_SNI -DHAVE_MAX_FRAGMENT" + ENABLED_TRUNCATED_HMAC=yes + ENABLED_RENEGOTIATION_INDICATION=yes + AM_CFLAGS="$AM_CFLAGS -DHAVE_TLS_EXTENSIONS -DHAVE_SNI -DHAVE_MAX_FRAGMENT -DHAVE_TRUNCATED_HMAC -DHAVE_RENEGOTIATION_INDICATION" fi +# PKCS7 +AC_ARG_ENABLE([pkcs7], + [ --enable-pkcs7 Enable PKCS7 (default: disabled)], + [ ENABLED_PKCS7=$enableval ], + [ ENABLED_PKCS7=no ], + ) + +if test "$ENABLED_PKCS7" = "yes" +then + AM_CFLAGS="$AM_CFLAGS -DHAVE_PKCS7" +fi + +AM_CONDITIONAL([BUILD_PKCS7], [test "x$ENABLED_PKCS7" = "xyes"]) + + +# Simple Certificate Enrollment Protocol (SCEP) +AC_ARG_ENABLE([scep], + [ --enable-scep Enable wolfSCEP (default: disabled)], + [ ENABLED_WOLFSCEP=$enableval ], + [ ENABLED_WOLFSCEP=no ] + ) +if test "$ENABLED_WOLFSCEP" = "yes" +then + # Enable prereqs if not already enabled + if test "x$ENABLED_KEYGEN" = "xno" + then + ENABLED_KEYGEN="yes" + AM_CFLAGS="$AM_CFLAGS -DCYASSL_KEY_GEN" + fi + if test "x$ENABLED_CERTGEN" = "xno" + then + ENABLED_CERTGEN="yes" + AM_CFLAGS="$AM_CFLAGS -DCYASSL_CERT_GEN" + fi + if test "x$ENABLED_CERTREQ" = "xno" + then + ENABLED_CERTREQ="yes" + AM_CFLAGS="$AM_CFLAGS -DCYASSL_CERT_REQ" + fi + if test "x$ENABLED_PKCS7" = "xno" + then + ENABLED_PKCS7="yes" + AM_CFLAGS="$AM_CFLAGS -DHAVE_PKCS7" + AM_CONDITIONAL([BUILD_PKCS7], [test "x$ENABLED_PKCS7" = "xyes"]) + fi + AM_CFLAGS="$AM_CFLAGS -DCYASSL_HAVE_WOLFSCEP" +fi + + #valgrind AC_ARG_ENABLE([valgrind], [ --enable-valgrind Enable valgrind for unit tests (default: disabled)], @@ -1529,6 +1614,7 @@ echo " * Filesystem: $ENABLED_FILESYSTEM" echo " * OpenSSL Extra API: $ENABLED_OPENSSLEXTRA" echo " * fastmath: $ENABLED_FASTMATH" echo " * sniffer: $ENABLED_SNIFFER" +echo " * snifftest: $ENABLED_SNIFFTEST" echo " * ARC4: $ENABLED_ARC4" echo " * AES: $ENABLED_AES" echo " * AES-NI: $ENABLED_AESNI" @@ -1544,6 +1630,7 @@ echo " * SHA-512: $ENABLED_SHA512" echo " * BLAKE2: $ENABLED_BLAKE2" echo " * keygen: $ENABLED_KEYGEN" echo " * certgen: $ENABLED_CERTGEN" +echo " * certreq: $ENABLED_CERTREQ" echo " * HC-128: $ENABLED_HC128" echo " * RABBIT: $ENABLED_RABBIT" echo " * PWDBASED: $ENABLED_PWDBASED" @@ -1574,7 +1661,10 @@ echo " * NTRU: $ENABLED_NTRU" echo " * SNI: $ENABLED_SNI" echo " * Maximum Fragment Length: $ENABLED_MAX_FRAGMENT" echo " * Truncated HMAC: $ENABLED_TRUNCATED_HMAC" +echo " * Renegotiation Indication: $ENABLED_RENEGOTIATION_INDICATION" echo " * All TLS Extensions: $ENABLED_TLSX" +echo " * PKCS#7 $ENABLED_PKCS7" +echo " * wolfSCEP $ENABLED_WOLFSCEP" echo " * valgrind unit tests: $ENABLED_VALGRIND" echo " * LIBZ: $ENABLED_LIBZ" echo " * Examples: $ENABLED_EXAMPLES" diff --git a/ctaocrypt/benchmark/benchmark.c b/ctaocrypt/benchmark/benchmark.c index f1264a7c7..2086aaf10 100644 --- a/ctaocrypt/benchmark/benchmark.c +++ b/ctaocrypt/benchmark/benchmark.c @@ -221,13 +221,13 @@ int benchmark_test(void *args) #ifdef BENCH_EMBEDDED const int numBlocks = 25; /* how many kB/megs to test (en/de)cryption */ const char blockType[] = "kB"; /* used in printf output */ -const int times = 1; /* public key iterations */ +const int ntimes = 1; /* public key iterations */ const int genTimes = 5; const int agreeTimes = 5; #else const int numBlocks = 5; const char blockType[] = "megs"; -const int times = 100; +const int ntimes = 100; const int genTimes = 100; const int agreeTimes = 100; #endif @@ -742,15 +742,15 @@ void bench_rsa(void) start = current_time(1); - for (i = 0; i < times; i++) + for (i = 0; i < ntimes; i++) ret = RsaPublicEncrypt(message,len,enc,sizeof(enc), &rsaKey, &rng); total = current_time(0) - start; - each = total / times; /* per second */ + each = total / ntimes; /* per second */ milliEach = each * 1000; /* milliseconds */ printf("RSA %d encryption took %6.2f milliseconds, avg over %d" - " iterations\n", rsaKeySz, milliEach, times); + " iterations\n", rsaKeySz, milliEach, ntimes); if (ret < 0) { printf("Rsa Public Encrypt failed\n"); @@ -759,17 +759,17 @@ void bench_rsa(void) start = current_time(1); - for (i = 0; i < times; i++) { + for (i = 0; i < ntimes; i++) { byte out[512]; /* for up to 4096 bit */ RsaPrivateDecrypt(enc, (word32)ret, out, sizeof(out), &rsaKey); } total = current_time(0) - start; - each = total / times; /* per second */ + each = total / ntimes; /* per second */ milliEach = each * 1000; /* milliseconds */ printf("RSA %d decryption took %6.2f milliseconds, avg over %d" - " iterations\n", rsaKeySz, milliEach, times); + " iterations\n", rsaKeySz, milliEach, ntimes); FreeRsaKey(&rsaKey); #ifdef HAVE_CAVIUM @@ -847,28 +847,28 @@ void bench_dh(void) start = current_time(1); - for (i = 0; i < times; i++) + for (i = 0; i < ntimes; i++) DhGenerateKeyPair(&dhKey, &rng, priv, &privSz, pub, &pubSz); total = current_time(0) - start; - each = total / times; /* per second */ + each = total / ntimes; /* per second */ milliEach = each * 1000; /* milliseconds */ printf("DH %d key generation %6.2f milliseconds, avg over %d" - " iterations\n", dhKeySz, milliEach, times); + " iterations\n", dhKeySz, milliEach, ntimes); DhGenerateKeyPair(&dhKey, &rng, priv2, &privSz2, pub2, &pubSz2); start = current_time(1); - for (i = 0; i < times; i++) + for (i = 0; i < ntimes; i++) DhAgree(&dhKey, agree, &agreeSz, priv, privSz, pub2, pubSz2); total = current_time(0) - start; - each = total / times; /* per second */ + each = total / ntimes; /* per second */ milliEach = each * 1000; /* milliseconds */ printf("DH %d key agreement %6.2f milliseconds, avg over %d" - " iterations\n", dhKeySz, milliEach, times); + " iterations\n", dhKeySz, milliEach, ntimes); #if !defined(USE_CERT_BUFFERS_1024) && !defined(USE_CERT_BUFFERS_2048) fclose(file); @@ -1087,7 +1087,22 @@ void bench_eccKeyAgree(void) } #elif defined CYASSL_MDK_ARM + extern double current_time(int reset) ; + +#elif defined FREERTOS + + double current_time(int reset) + { + (void) reset; + + portTickType tickCount; + + /* tick count == ms, if configTICK_RATE_HZ is set to 1000 */ + tickCount = xTaskGetTickCount(); + return (double)tickCount / 1000; + } + #else #include diff --git a/ctaocrypt/src/aes.c b/ctaocrypt/src/aes.c index 8f5e357d7..4cb723d31 100644 --- a/ctaocrypt/src/aes.c +++ b/ctaocrypt/src/aes.c @@ -62,8 +62,8 @@ * document (See note in README). */ #include "stm32f2xx.h" - #include "stm32f2xx_cryp.h" - + #include "stm32f2xx_cryp.h" + int AesSetKey(Aes* aes, const byte* userKey, word32 keylen, const byte* iv, int dir) { @@ -553,6 +553,96 @@ int AesSetKey(Aes* aes, const byte* userKey, word32 keylen, const byte* iv, return 0; } +#elif defined FREESCALE_MMCAU + /* + * Freescale mmCAU hardware AES support through the CAU/mmCAU library. + * Documentation located in ColdFire/ColdFire+ CAU and Kinetis mmCAU + * Software Library User Guide (See note in README). + */ + #include "cau_api.h" + + int AesSetKey(Aes* aes, const byte* userKey, word32 keylen, const byte* iv, + int dir) + { + byte *rk = (byte*)aes->key; + + if (!((keylen == 16) || (keylen == 24) || (keylen == 32))) + return BAD_FUNC_ARG; + + if (rk == NULL) + return BAD_FUNC_ARG; + + aes->rounds = keylen/4 + 6; + cau_aes_set_key(userKey, keylen*8, rk); + + return AesSetIV(aes, iv); + } + + int AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) + { + int i; + int offset = 0; + int len = sz; + + byte *iv, *enc_key; + byte temp_block[AES_BLOCK_SIZE]; + + iv = (byte*)aes->reg; + enc_key = (byte*)aes->key; + + while (len > 0) + { + XMEMCPY(temp_block, in + offset, AES_BLOCK_SIZE); + + /* XOR block with IV for CBC */ + for (i = 0; i < AES_BLOCK_SIZE; i++) + temp_block[i] ^= iv[i]; + + cau_aes_encrypt(temp_block, enc_key, aes->rounds, out + offset); + + len -= AES_BLOCK_SIZE; + offset += AES_BLOCK_SIZE; + + /* store IV for next block */ + XMEMCPY(iv, out + offset - AES_BLOCK_SIZE, AES_BLOCK_SIZE); + } + + return 0; + } + + int AesCbcDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) + { + int i; + int offset = 0; + int len = sz; + + byte* iv, *dec_key; + byte temp_block[AES_BLOCK_SIZE]; + + iv = (byte*)aes->reg; + dec_key = (byte*)aes->key; + + while (len > 0) + { + XMEMCPY(temp_block, in + offset, AES_BLOCK_SIZE); + + cau_aes_decrypt(in + offset, dec_key, aes->rounds, out + offset); + + /* XOR block with IV for CBC */ + for (i = 0; i < AES_BLOCK_SIZE; i++) + (out + offset)[i] ^= iv[i]; + + /* store IV for next block */ + XMEMCPY(iv, temp_block, AES_BLOCK_SIZE); + + len -= AES_BLOCK_SIZE; + offset += AES_BLOCK_SIZE; + } + + return 0; + } + + #else /* CTaoCrypt software implementation */ static const word32 rcon[] = { @@ -1386,6 +1476,10 @@ static int AesSetKeyLocal(Aes* aes, const byte* userKey, word32 keylen, #ifdef CYASSL_AESNI aes->use_aesni = 0; #endif /* CYASSL_AESNI */ + #ifdef CYASSL_AES_COUNTER + aes->left = 0; + #endif /* CYASSL_AES_COUNTER */ + aes->rounds = keylen/4 + 6; XMEMCPY(rk, userKey, keylen); @@ -2039,15 +2133,39 @@ static INLINE void IncrementAesCounter(byte* inOutCtr) void AesCtrEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) { - word32 blocks = sz / AES_BLOCK_SIZE; + byte* tmp = (byte*)aes->tmp + AES_BLOCK_SIZE - aes->left; - while (blocks--) { + /* consume any unused bytes left in aes->tmp */ + while (aes->left && sz) { + *(out++) = *(in++) ^ *(tmp++); + aes->left--; + sz--; + } + + /* do as many block size ops as possible */ + while (sz >= AES_BLOCK_SIZE) { AesEncrypt(aes, (byte*)aes->reg, out); IncrementAesCounter((byte*)aes->reg); xorbuf(out, in, AES_BLOCK_SIZE); out += AES_BLOCK_SIZE; - in += AES_BLOCK_SIZE; + in += AES_BLOCK_SIZE; + sz -= AES_BLOCK_SIZE; + aes->left = 0; + } + + /* handle non block size remaining and sotre unused byte count in left */ + if (sz) { + AesEncrypt(aes, (byte*)aes->reg, (byte*)aes->tmp); + IncrementAesCounter((byte*)aes->reg); + + aes->left = AES_BLOCK_SIZE; + tmp = (byte*)aes->tmp; + + while (sz--) { + *(out++) = *(in++) ^ *(tmp++); + aes->left--; + } } } diff --git a/ctaocrypt/src/asm.c b/ctaocrypt/src/asm.c index e19410e8a..941478a42 100644 --- a/ctaocrypt/src/asm.c +++ b/ctaocrypt/src/asm.c @@ -1004,15 +1004,17 @@ __asm__( \ #define SQRADDAC(i, j) \ do { fp_word t; \ - t = sc0 + ((fp_word)i) * ((fp_word)j); sc0 = t; \ - t = sc1 + (t >> DIGIT_BIT); sc1 = t; sc2 += t >> DIGIT_BIT; \ + t = sc0 + ((fp_word)i) * ((fp_word)j); sc0 = (fp_digit)t; \ + t = sc1 + (t >> DIGIT_BIT); sc1 = (fp_digit)t; \ + sc2 += (fp_digit)(t >> DIGIT_BIT); \ } while (0); #define SQRADDDB \ do { fp_word t; \ - t = ((fp_word)sc0) + ((fp_word)sc0) + c0; c0 = t; \ - t = ((fp_word)sc1) + ((fp_word)sc1) + c1 + (t >> DIGIT_BIT); c1 = t; \ - c2 = c2 + ((fp_word)sc2) + ((fp_word)sc2) + (t >> DIGIT_BIT); \ + t = ((fp_word)sc0) + ((fp_word)sc0) + c0; c0 = (fp_digit)t; \ + t = ((fp_word)sc1) + ((fp_word)sc1) + c1 + (t >> DIGIT_BIT); \ + c1 = (fp_digit)t; \ + c2 = c2 + (fp_digit)(((fp_word)sc2) + ((fp_word)sc2) + (t >> DIGIT_BIT)); \ } while (0); #endif diff --git a/ctaocrypt/src/asn.c b/ctaocrypt/src/asn.c index 65ff0a660..d1c82f8e1 100644 --- a/ctaocrypt/src/asn.c +++ b/ctaocrypt/src/asn.c @@ -398,8 +398,8 @@ CPU_INT32S NetSecure_ValidateDateHandler(CPU_INT08U *date, CPU_INT08U format, #endif /* MICRIUM */ -static int GetLength(const byte* input, word32* inOutIdx, int* len, - word32 maxIdx) +CYASSL_LOCAL int GetLength(const byte* input, word32* inOutIdx, int* len, + word32 maxIdx) { int length = 0; word32 i = *inOutIdx; @@ -439,8 +439,8 @@ static int GetLength(const byte* input, word32* inOutIdx, int* len, } -static int GetSequence(const byte* input, word32* inOutIdx, int* len, - word32 maxIdx) +CYASSL_LOCAL int GetSequence(const byte* input, word32* inOutIdx, int* len, + word32 maxIdx) { int length = -1; word32 idx = *inOutIdx; @@ -456,7 +456,8 @@ static int GetSequence(const byte* input, word32* inOutIdx, int* len, } -static int GetSet(const byte* input, word32* inOutIdx, int* len, word32 maxIdx) +CYASSL_LOCAL int GetSet(const byte* input, word32* inOutIdx, int* len, + word32 maxIdx) { int length = -1; word32 idx = *inOutIdx; @@ -473,7 +474,7 @@ static int GetSet(const byte* input, word32* inOutIdx, int* len, word32 maxIdx) /* winodws header clash for WinCE using GetVersion */ -static int GetMyVersion(const byte* input, word32* inOutIdx, int* version) +CYASSL_LOCAL int GetMyVersion(const byte* input, word32* inOutIdx, int* version) { word32 idx = *inOutIdx; @@ -537,7 +538,7 @@ static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version) } -static int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, +CYASSL_LOCAL int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, word32 maxIdx) { word32 i = *inOutIdx; @@ -593,7 +594,7 @@ static int GetObjectId(const byte* input, word32* inOutIdx, word32* oid, } -static int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid, +CYASSL_LOCAL int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid, word32 maxIdx) { int length; @@ -764,7 +765,7 @@ int ToTraditional(byte* input, word32 sz) XMEMMOVE(input, input + inOutIdx, length); - return 0; + return length; } @@ -1280,6 +1281,10 @@ void InitDecodedCert(DecodedCert* cert, byte* source, word32 inSz, void* heap) XMEMSET(cert->extAuthKeyId, 0, SHA_SIZE); cert->extAuthKeyIdSet = 0; cert->isCA = 0; +#ifdef HAVE_PKCS7 + cert->issuerRaw = NULL; + cert->issuerRawLen = 0; +#endif #ifdef CYASSL_CERT_GEN cert->subjectSN = 0; cert->subjectSNLen = 0; @@ -1303,6 +1308,24 @@ void InitDecodedCert(DecodedCert* cert, byte* source, word32 inSz, void* heap) #ifdef OPENSSL_EXTRA XMEMSET(&cert->issuerName, 0, sizeof(DecodedName)); XMEMSET(&cert->subjectName, 0, sizeof(DecodedName)); + cert->extBasicConstSet = 0; + cert->extBasicConstCrit = 0; + cert->extBasicConstPlSet = 0; + cert->pathLength = 0; + cert->extSubjAltNameSet = 0; + cert->extSubjAltNameCrit = 0; + cert->extAuthKeyIdCrit = 0; + cert->extSubjKeyIdCrit = 0; + cert->extKeyUsageSet = 0; + cert->extKeyUsageCrit = 0; + cert->extKeyUsage = 0; + cert->extAuthKeyIdSrc = NULL; + cert->extAuthKeyIdSz = 0; + cert->extSubjKeyIdSrc = NULL; + cert->extSubjKeyIdSz = 0; + #ifdef HAVE_ECC + cert->pkCurveOID = 0; + #endif /* HAVE_ECC */ #endif /* OPENSSL_EXTRA */ #ifdef CYASSL_SEP cert->deviceTypeSz = 0; @@ -1311,6 +1334,10 @@ void InitDecodedCert(DecodedCert* cert, byte* source, word32 inSz, void* heap) cert->hwType = NULL; cert->hwSerialNumSz = 0; cert->hwSerialNum = NULL; + #ifdef OPENSSL_EXTRA + cert->extCertPolicySet = 0; + cert->extCertPolicyCrit = 0; + #endif /* OPENSSL_EXTRA */ #endif /* CYASSL_SEP */ } @@ -1434,7 +1461,7 @@ static int GetKey(DecodedCert* cert) if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0) return ASN_PARSE_E; - + if (GetAlgoId(cert->source, &cert->srcIdx, &cert->keyOID, cert->maxIdx) < 0) return ASN_PARSE_E; @@ -1509,6 +1536,9 @@ static int GetKey(DecodedCert* cert) oid += cert->source[cert->srcIdx++]; if (CheckCurve(oid) < 0) return ECC_CURVE_OID_E; + #ifdef OPENSSL_EXTRA + cert->pkCurveOID = oid; + #endif /* OPENSSL_EXTRA */ /* key header */ b = cert->source[cert->srcIdx++]; @@ -1586,6 +1616,14 @@ static int GetName(DecodedCert* cert, int nameType) length += cert->srcIdx; idx = 0; +#ifdef HAVE_PKCS7 + /* store pointer to raw issuer */ + if (nameType == ISSUER) { + cert->issuerRaw = &cert->source[cert->srcIdx]; + cert->issuerRawLen = length - cert->srcIdx; + } +#endif + while (cert->srcIdx < (word32)length) { byte b; byte joint[2]; @@ -2128,10 +2166,14 @@ int DecodeToKey(DecodedCert* cert, int verify) if ( (ret = GetCertHeader(cert)) < 0) return ret; + CYASSL_MSG("Got Cert Header"); + if ( (ret = GetAlgoId(cert->source, &cert->srcIdx, &cert->signatureOID, cert->maxIdx)) < 0) return ret; + CYASSL_MSG("Got Algo ID"); + if ( (ret = GetName(cert, ISSUER)) < 0) return ret; @@ -2141,9 +2183,13 @@ int DecodeToKey(DecodedCert* cert, int verify) if ( (ret = GetName(cert, SUBJECT)) < 0) return ret; + CYASSL_MSG("Got Subject Name"); + if ( (ret = GetKey(cert)) < 0) return ret; + CYASSL_MSG("Got Key"); + if (badDate != 0) return badDate; @@ -2197,7 +2243,7 @@ static word32 BytePrecision(word32 value) } -static word32 SetLength(word32 length, byte* output) +CYASSL_LOCAL word32 SetLength(word32 length, byte* output) { word32 i = 0, j; @@ -2216,14 +2262,114 @@ static word32 SetLength(word32 length, byte* output) } -static word32 SetSequence(word32 len, byte* output) +CYASSL_LOCAL word32 SetSequence(word32 len, byte* output) { output[0] = ASN_SEQUENCE | ASN_CONSTRUCTED; return SetLength(len, output + 1) + 1; } +CYASSL_LOCAL word32 SetOctetString(word32 len, byte* output) +{ + output[0] = ASN_OCTET_STRING; + return SetLength(len, output + 1) + 1; +} -static word32 SetAlgoID(int algoOID, byte* output, int type) +/* Write a set header to output */ +CYASSL_LOCAL word32 SetSet(word32 len, byte* output) +{ + output[0] = ASN_SET | ASN_CONSTRUCTED; + return SetLength(len, output + 1) + 1; +} + +CYASSL_LOCAL word32 SetImplicit(byte tag, byte number, word32 len, byte* output) +{ + + output[0] = ((tag == ASN_SEQUENCE || tag == ASN_SET) ? ASN_CONSTRUCTED : 0) + | ASN_CONTEXT_SPECIFIC | number; + return SetLength(len, output + 1) + 1; +} + +CYASSL_LOCAL word32 SetExplicit(byte number, word32 len, byte* output) +{ + output[0] = ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | number; + return SetLength(len, output + 1) + 1; +} + + +#if defined(HAVE_ECC) && defined(CYASSL_CERT_GEN) + +static word32 SetCurve(ecc_key* key, byte* output) +{ + + /* curve types */ + static const byte ECC_192v1_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE, 0x3d, + 0x03, 0x01, 0x01}; + static const byte ECC_256v1_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE, 0x3d, + 0x03, 0x01, 0x07}; + static const byte ECC_160r1_AlgoID[] = { 0x2b, 0x81, 0x04, 0x00, + 0x02}; + static const byte ECC_224r1_AlgoID[] = { 0x2b, 0x81, 0x04, 0x00, + 0x21}; + static const byte ECC_384r1_AlgoID[] = { 0x2b, 0x81, 0x04, 0x00, + 0x22}; + static const byte ECC_521r1_AlgoID[] = { 0x2b, 0x81, 0x04, 0x00, + 0x23}; + + int oidSz = 0; + int idx = 0; + int lenSz = 0; + const byte* oid = 0; + + output[0] = ASN_OBJECT_ID; + idx++; + + switch (key->dp->size) { + case 20: + oidSz = sizeof(ECC_160r1_AlgoID); + oid = ECC_160r1_AlgoID; + break; + + case 24: + oidSz = sizeof(ECC_192v1_AlgoID); + oid = ECC_192v1_AlgoID; + break; + + case 28: + oidSz = sizeof(ECC_224r1_AlgoID); + oid = ECC_224r1_AlgoID; + break; + + case 32: + oidSz = sizeof(ECC_256v1_AlgoID); + oid = ECC_256v1_AlgoID; + break; + + case 48: + oidSz = sizeof(ECC_384r1_AlgoID); + oid = ECC_384r1_AlgoID; + break; + + case 66: + oidSz = sizeof(ECC_521r1_AlgoID); + oid = ECC_521r1_AlgoID; + break; + + default: + return ASN_UNKNOWN_OID_E; + } + lenSz = SetLength(oidSz, output+idx); + idx += lenSz; + + XMEMCPY(output+idx, oid, oidSz); + idx += oidSz; + + return idx; +} + +#endif /* HAVE_ECC && CYASSL_CERT_GEN */ + + +CYASSL_LOCAL word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz) { /* adding TAG_NULL and 0 to end */ @@ -2241,7 +2387,12 @@ static word32 SetAlgoID(int algoOID, byte* output, int type) static const byte md2AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x02, 0x05, 0x00}; - /* sigTypes */ + /* blkTypes, no NULL tags because IV is there instead */ + static const byte desCbcAlgoID[] = { 0x2B, 0x0E, 0x03, 0x02, 0x07 }; + static const byte des3CbcAlgoID[] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, + 0x0D, 0x03, 0x07 }; + + /* RSA sigTypes */ #ifndef NO_RSA static const byte md5wRSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x04, 0x05, 0x00}; @@ -2255,13 +2406,33 @@ static word32 SetAlgoID(int algoOID, byte* output, int type) 0x0d, 0x01, 0x01, 0x0d, 0x05, 0x00}; #endif /* NO_RSA */ - /* keyTypes */ + /* ECDSA sigTypes */ + #ifdef HAVE_ECC + static const byte shawECDSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE, 0x3d, + 0x04, 0x01, 0x05, 0x00}; + static const byte sha256wECDSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE,0x3d, + 0x04, 0x03, 0x02, 0x05, 0x00}; + static const byte sha384wECDSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE,0x3d, + 0x04, 0x03, 0x03, 0x05, 0x00}; + static const byte sha512wECDSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE,0x3d, + 0x04, 0x03, 0x04, 0x05, 0x00}; + #endif /* HAVE_ECC */ + + /* RSA keyType */ #ifndef NO_RSA static const byte RSA_AlgoID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00}; #endif /* NO_RSA */ + #ifdef HAVE_ECC + /* ECC keyType */ + /* no tags, so set tagSz smaller later */ + static const byte ECC_AlgoID[] = { 0x2a, 0x86, 0x48, 0xCE, 0x3d, + 0x02, 0x01}; + #endif /* HAVE_ECC */ + int algoSz = 0; + int tagSz = 2; /* tag null and terminator */ word32 idSz, seqSz; const byte* algoName = 0; byte ID_Length[MAX_LENGTH_SZ]; @@ -2304,6 +2475,23 @@ static word32 SetAlgoID(int algoOID, byte* output, int type) return 0; /* UNKOWN_HASH_E; */ } } + else if (type == blkType) { + switch (algoOID) { + case DESb: + algoSz = sizeof(desCbcAlgoID); + algoName = desCbcAlgoID; + tagSz = 0; + break; + case DES3b: + algoSz = sizeof(des3CbcAlgoID); + algoName = des3CbcAlgoID; + tagSz = 0; + break; + default: + CYASSL_MSG("Unknown Block Algo"); + return 0; + } + } else if (type == sigType) { /* sigType */ switch (algoOID) { #ifndef NO_RSA @@ -2332,6 +2520,27 @@ static word32 SetAlgoID(int algoOID, byte* output, int type) algoName = sha512wRSA_AlgoID; break; #endif /* NO_RSA */ + #ifdef HAVE_ECC + case CTC_SHAwECDSA: + algoSz = sizeof(shawECDSA_AlgoID); + algoName = shawECDSA_AlgoID; + break; + + case CTC_SHA256wECDSA: + algoSz = sizeof(sha256wECDSA_AlgoID); + algoName = sha256wECDSA_AlgoID; + break; + + case CTC_SHA384wECDSA: + algoSz = sizeof(sha384wECDSA_AlgoID); + algoName = sha384wECDSA_AlgoID; + break; + + case CTC_SHA512wECDSA: + algoSz = sizeof(sha512wECDSA_AlgoID); + algoName = sha512wECDSA_AlgoID; + break; + #endif /* HAVE_ECC */ default: CYASSL_MSG("Unknown Signature Algo"); return 0; @@ -2345,6 +2554,13 @@ static word32 SetAlgoID(int algoOID, byte* output, int type) algoName = RSA_AlgoID; break; #endif /* NO_RSA */ + #ifdef HAVE_ECC + case ECDSAk: + algoSz = sizeof(ECC_AlgoID); + algoName = ECC_AlgoID; + tagSz = 0; + break; + #endif /* HAVE_ECC */ default: CYASSL_MSG("Unknown Key Algo"); return 0; @@ -2355,8 +2571,9 @@ static word32 SetAlgoID(int algoOID, byte* output, int type) return 0; } - idSz = SetLength(algoSz - 2, ID_Length); /* don't include TAG_NULL/0 */ - seqSz = SetSequence(idSz + algoSz + 1, seqArray); + idSz = SetLength(algoSz - tagSz, ID_Length); /* don't include tags */ + seqSz = SetSequence(idSz + algoSz + 1 + curveSz, seqArray); + /* +1 for object id, curveID of curveSz follows for ecc */ seqArray[seqSz++] = ASN_OBJECT_ID; XMEMCPY(output, seqArray, seqSz); @@ -2376,7 +2593,7 @@ word32 EncodeSignature(byte* out, const byte* digest, word32 digSz, int hashOID) word32 encDigSz, algoSz, seqSz; encDigSz = SetDigest(digest, digSz, digArray); - algoSz = SetAlgoID(hashOID, algoArray, hashType); + algoSz = SetAlgoID(hashOID, algoArray, hashType, 0); seqSz = SetSequence(encDigSz + algoSz, seqArray); XMEMCPY(out, seqArray, seqSz); @@ -2491,6 +2708,7 @@ static int ConfirmSignature(const byte* buf, word32 bufSz, CYASSL_MSG("Verify Signautre has unsupported type"); return 0; } + (void)typeH; /* some builds won't read */ switch (keyOID) { #ifndef NO_RSA @@ -2752,8 +2970,28 @@ static void DecodeBasicCaConstraint(byte* input, int sz, DecodedCert* cert) return; } - if (input[idx]) + if (input[idx++]) cert->isCA = 1; + + #ifdef OPENSSL_EXTRA + /* If there isn't any more data, return. */ + if (idx >= (word32)sz) + return; + + /* Anything left should be the optional pathlength */ + if (input[idx++] != ASN_INTEGER) { + CYASSL_MSG("\tfail: pathlen not INTEGER"); + return; + } + + if (input[idx++] != 1) { + CYASSL_MSG("\tfail: pathlen too long"); + return; + } + + cert->pathLength = input[idx]; + cert->extBasicConstPlSet = 1; + #endif /* OPENSSL_EXTRA */ } @@ -2906,6 +3144,11 @@ static void DecodeAuthKeyId(byte* input, int sz, DecodedCert* cert) return; } + #ifdef OPENSSL_EXTRA + cert->extAuthKeyIdSrc = &input[idx]; + cert->extAuthKeyIdSz = length; + #endif /* OPENSSL_EXTRA */ + if (length == SHA_SIZE) { XMEMCPY(cert->extAuthKeyId, input + idx, length); } @@ -2915,7 +3158,6 @@ static void DecodeAuthKeyId(byte* input, int sz, DecodedCert* cert) ShaUpdate(&sha, input + idx, length); ShaFinal(&sha, cert->extAuthKeyId); } - cert->extAuthKeyIdSet = 1; return; } @@ -2938,6 +3180,11 @@ static void DecodeSubjKeyId(byte* input, int sz, DecodedCert* cert) return; } + #ifdef OPENSSL_EXTRA + cert->extSubjKeyIdSrc = &input[idx]; + cert->extSubjKeyIdSz = length; + #endif /* OPENSSL_EXTRA */ + if (length == SIGNER_DIGEST_SIZE) { XMEMCPY(cert->extSubjKeyId, input + idx, length); } @@ -2947,12 +3194,44 @@ static void DecodeSubjKeyId(byte* input, int sz, DecodedCert* cert) ShaUpdate(&sha, input + idx, length); ShaFinal(&sha, cert->extSubjKeyId); } - cert->extSubjKeyIdSet = 1; return; } +#ifdef OPENSSL_EXTRA + static void DecodeKeyUsage(byte* input, int sz, DecodedCert* cert) + { + word32 idx = 0; + int length; + byte unusedBits; + CYASSL_ENTER("DecodeKeyUsage"); + + if (input[idx++] != ASN_BIT_STRING) { + CYASSL_MSG("\tfail: key usage expected bit string"); + return; + } + + if (GetLength(input, &idx, &length, sz) < 0) { + CYASSL_MSG("\tfail: key usage bad length"); + return; + } + + unusedBits = input[idx++]; + length--; + + if (length == 2) { + cert->extKeyUsage = (input[idx] << 8) | input[idx+1]; + cert->extKeyUsage >>= unusedBits; + } + else if (length == 1) + cert->extKeyUsage = (input[idx] << 1); + + return; + } +#endif /* OPENSSL_EXTRA */ + + #ifdef CYASSL_SEP static void DecodeCertPolicy(byte* input, int sz, DecodedCert* cert) { @@ -3008,6 +3287,9 @@ static void DecodeCertExtensions(DecodedCert* cert) byte* input = cert->extensions; int length; word32 oid; + byte critical; + + (void)critical; CYASSL_ENTER("DecodeCertExtensions"); @@ -3032,9 +3314,16 @@ static void DecodeCertExtensions(DecodedCert* cert) } /* check for critical flag */ + critical = 0; if (input[idx] == ASN_BOOLEAN) { - CYASSL_MSG("\tfound optional critical flag, moving past"); - idx += (ASN_BOOL_SIZE + 1); + int boolLength = 0; + idx++; + if (GetLength(input, &idx, &boolLength, sz) < 0) { + CYASSL_MSG("\tfail: critical boolean length"); + return; + } + if (input[idx++]) + critical = 1; } /* process the extension based on the OID */ @@ -3050,6 +3339,10 @@ static void DecodeCertExtensions(DecodedCert* cert) switch (oid) { case BASIC_CA_OID: + #ifdef OPENSSL_EXTRA + cert->extBasicConstSet = 1; + cert->extBasicConstCrit = critical; + #endif DecodeBasicCaConstraint(&input[idx], length, cert); break; @@ -3062,29 +3355,54 @@ static void DecodeCertExtensions(DecodedCert* cert) break; case ALT_NAMES_OID: + #ifdef OPENSSL_EXTRA + cert->extSubjAltNameSet = 1; + cert->extSubjAltNameCrit = critical; + #endif DecodeAltNames(&input[idx], length, cert); break; case AUTH_KEY_OID: + cert->extAuthKeyIdSet = 1; + #ifdef OPENSSL_EXTRA + cert->extAuthKeyIdCrit = critical; + #endif DecodeAuthKeyId(&input[idx], length, cert); break; case SUBJ_KEY_OID: + cert->extSubjKeyIdSet = 1; + #ifdef OPENSSL_EXTRA + cert->extSubjKeyIdCrit = critical; + #endif DecodeSubjKeyId(&input[idx], length, cert); break; #ifdef CYASSL_SEP case CERT_POLICY_OID: + #ifdef OPENSSL_EXTRA + cert->extCertPolicySet = 1; + cert->extCertPolicyCrit = critical; + #endif DecodeCertPolicy(&input[idx], length, cert); break; #endif + #ifdef OPENSSL_EXTRA + case KEY_USAGE_OID: + cert->extKeyUsageSet = 1; + cert->extKeyUsageCrit = critical; + DecodeKeyUsage(&input[idx], length, cert); + break; + #endif + default: CYASSL_MSG("\tExtension type not handled, skipping"); break; } idx += length; } + (void)critical; CYASSL_LEAVE("DecodeCertExtensions", 0); return; @@ -3151,6 +3469,8 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) return ret; } + CYASSL_MSG("Parsed Past Key"); + if (cert->srcIdx != cert->sigIndex) { if (cert->srcIdx < cert->sigIndex) { /* save extensions */ @@ -3180,7 +3500,6 @@ int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm) InitSha(&sha); ShaUpdate(&sha, cert->publicKey, cert->pubKeySize); ShaFinal(&sha, cert->extSubjKeyId); - cert->extSubjKeyIdSet = 1; } #endif @@ -3277,9 +3596,7 @@ void FreeSignerTable(Signer** table, int rows, void* heap) } -#if defined(CYASSL_KEY_GEN) || defined(CYASSL_CERT_GEN) - -static int SetMyVersion(word32 version, byte* output, int header) +CYASSL_LOCAL int SetMyVersion(word32 version, byte* output, int header) { int i = 0; @@ -3295,6 +3612,39 @@ static int SetMyVersion(word32 version, byte* output, int header) } +CYASSL_LOCAL int SetSerialNumber(const byte* sn, word32 snSz, byte* output) +{ + int result = 0; + + CYASSL_ENTER("SetSerialNumber"); + + if (snSz <= EXTERNAL_SERIAL_SIZE) { + output[0] = ASN_INTEGER; + /* The serial number is always positive. When encoding the + * INTEGER, if the MSB is 1, add a padding zero to keep the + * number positive. */ + if (sn[0] & 0x80) { + output[1] = (byte)snSz + 1; + output[2] = 0; + XMEMCPY(&output[3], sn, snSz); + result = snSz + 3; + } + else { + output[1] = (byte)snSz; + XMEMCPY(&output[2], sn, snSz); + result = snSz + 2; + } + } + return result; +} + + + + +#if defined(CYASSL_KEY_GEN) || defined(CYASSL_CERT_GEN) + +/* convert der buffer to pem into output, can't do inplace, der and output + need to be different */ int DerToPem(const byte* der, word32 derSz, byte* output, word32 outSz, int type) { @@ -3307,6 +3657,9 @@ int DerToPem(const byte* der, word32 derSz, byte* output, word32 outSz, int err; int outLen; /* return length or error */ + if (der == output) /* no in place conversion */ + return BAD_FUNC_ARG; + if (type == CERT_TYPE) { XSTRNCPY(header, "-----BEGIN CERTIFICATE-----\n", sizeof(header)); XSTRNCPY(footer, "-----END CERTIFICATE-----\n", sizeof(footer)); @@ -3321,6 +3674,14 @@ int DerToPem(const byte* der, word32 derSz, byte* output, word32 outSz, XSTRNCPY(footer, "-----END EC PRIVATE KEY-----\n", sizeof(footer)); } #endif + #ifdef CYASSL_CERT_REQ + else if (type == CERTREQ_TYPE) + { + XSTRNCPY(header, + "-----BEGIN CERTIFICATE REQUEST-----\n", sizeof(header)); + XSTRNCPY(footer, "-----END CERTIFICATE REQUEST-----\n", sizeof(footer)); + } + #endif else return BAD_FUNC_ARG; @@ -3532,6 +3893,10 @@ void InitCert(Cert* cert) cert->subject.unit[0] = '\0'; cert->subject.commonName[0] = '\0'; cert->subject.email[0] = '\0'; + +#ifdef CYASSL_CERT_REQ + cert->challengePw[0] ='\0'; +#endif } @@ -3547,6 +3912,9 @@ typedef struct DerCert { byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa / ntru public key encoded */ byte ca[MAX_CA_SZ]; /* basic constraint CA true size */ byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */ +#ifdef CYASSL_CERT_REQ + byte attrib[MAX_ATTRIB_SZ]; /* Cert req attributes encoded */ +#endif int sizeSz; /* encoded size length */ int versionSz; /* encoded version length */ int serialSz; /* encoded serial length */ @@ -3558,16 +3926,23 @@ typedef struct DerCert { int caSz; /* encoded CA extension length */ int extensionsSz; /* encoded extensions total length */ int total; /* total encoded lengths */ +#ifdef CYASSL_CERT_REQ + int attribSz; +#endif } DerCert; +#ifdef CYASSL_CERT_REQ + /* Write a set header to output */ -static word32 SetSet(word32 len, byte* output) +static word32 SetUTF8String(word32 len, byte* output) { - output[0] = ASN_SET | ASN_CONSTRUCTED; + output[0] = ASN_UTF8STRING; return SetLength(len, output + 1) + 1; } +#endif /* CYASSL_CERT_REQ */ + /* Write a serial number to output */ static int SetSerial(const byte* serial, byte* output) @@ -3582,8 +3957,59 @@ static int SetSerial(const byte* serial, byte* output) } +#ifdef HAVE_ECC + +/* Write a public ECC key to output */ +static int SetEccPublicKey(byte* output, ecc_key* key) +{ + byte algo[MAX_ALGO_SZ]; + byte curve[MAX_ALGO_SZ]; + byte len[MAX_LENGTH_SZ + 1]; /* trailing 0 */ + byte pub[ECC_BUFSIZE]; + int algoSz; + int curveSz; + int lenSz; + int idx; + word32 pubSz = sizeof(pub); + + int ret = ecc_export_x963(key, pub, &pubSz); + if (ret != 0) return ret; + + /* headers */ + curveSz = SetCurve(key, curve); + if (curveSz <= 0) return curveSz; + + algoSz = SetAlgoID(ECDSAk, algo, keyType, curveSz); + lenSz = SetLength(pubSz + 1, len); + len[lenSz++] = 0; /* trailing 0 */ + + /* write */ + idx = SetSequence(pubSz + curveSz + lenSz + 1 + algoSz, output); + /* 1 is for ASN_BIT_STRING */ + /* algo */ + XMEMCPY(output + idx, algo, algoSz); + idx += algoSz; + /* curve */ + XMEMCPY(output + idx, curve, curveSz); + idx += curveSz; + /* bit string */ + output[idx++] = ASN_BIT_STRING; + /* length */ + XMEMCPY(output + idx, len, lenSz); + idx += lenSz; + /* pub */ + XMEMCPY(output + idx, pub, pubSz); + idx += pubSz; + + return idx; +} + + +#endif /* HAVE_ECC */ + + /* Write a public RSA key to output */ -static int SetPublicKey(byte* output, RsaKey* key) +static int SetRsaPublicKey(byte* output, RsaKey* key) { byte n[MAX_RSA_INT_SZ]; byte e[MAX_RSA_E_SZ]; @@ -3597,14 +4023,19 @@ static int SetPublicKey(byte* output, RsaKey* key) int lenSz; int idx; int rawLen; + int leadingBit; + int err; /* n */ - rawLen = mp_unsigned_bin_size(&key->n); + leadingBit = mp_leading_bit(&key->n); + rawLen = mp_unsigned_bin_size(&key->n) + leadingBit; n[0] = ASN_INTEGER; nSz = SetLength(rawLen, n + 1) + 1; /* int tag */ if ( (nSz + rawLen) < (int)sizeof(n)) { - int err = mp_to_unsigned_bin(&key->n, n + nSz); + if (leadingBit) + n[nSz] = 0; + err = mp_to_unsigned_bin(&key->n, n + nSz + leadingBit); if (err == MP_OKAY) nSz += rawLen; else @@ -3614,12 +4045,15 @@ static int SetPublicKey(byte* output, RsaKey* key) return BUFFER_E; /* e */ - rawLen = mp_unsigned_bin_size(&key->e); + leadingBit = mp_leading_bit(&key->e); + rawLen = mp_unsigned_bin_size(&key->e) + leadingBit; e[0] = ASN_INTEGER; eSz = SetLength(rawLen, e + 1) + 1; /* int tag */ if ( (eSz + rawLen) < (int)sizeof(e)) { - int err = mp_to_unsigned_bin(&key->e, e + eSz); + if (leadingBit) + e[eSz] = 0; + err = mp_to_unsigned_bin(&key->e, e + eSz + leadingBit); if (err == MP_OKAY) eSz += rawLen; else @@ -3629,7 +4063,7 @@ static int SetPublicKey(byte* output, RsaKey* key) return BUFFER_E; /* headers */ - algoSz = SetAlgoID(RSAk, algo, keyType); + algoSz = SetAlgoID(RSAk, algo, keyType, 0); seqSz = SetSequence(nSz + eSz, seq); lenSz = SetLength(seqSz + nSz + eSz + 1, len); len[lenSz++] = 0; /* trailing 0 */ @@ -3852,19 +4286,21 @@ static byte GetNameId(int idx) /* encode all extensions, return total bytes written */ -static int SetExtensions(byte* output, const byte* ext, int extSz) +static int SetExtensions(byte* output, const byte* ext, int extSz, int header) { byte sequence[MAX_SEQ_SZ]; byte len[MAX_LENGTH_SZ]; int sz = 0; int seqSz = SetSequence(extSz, sequence); - int lenSz = SetLength(seqSz + extSz, len); - output[0] = ASN_EXTENSIONS; /* extensions id */ - sz++; - XMEMCPY(&output[sz], len, lenSz); /* length */ - sz += lenSz; + if (header) { + int lenSz = SetLength(seqSz + extSz, len); + output[0] = ASN_EXTENSIONS; /* extensions id */ + sz++; + XMEMCPY(&output[sz], len, lenSz); /* length */ + sz += lenSz; + } XMEMCPY(&output[sz], sequence, seqSz); /* sequence */ sz += seqSz; XMEMCPY(&output[sz], ext, extSz); /* extensions */ @@ -3957,12 +4393,16 @@ static int SetName(byte* output, CertName* name) } else { /* joint id */ + byte bType = GetNameId(i); names[i].encoded[idx++] = 0x55; names[i].encoded[idx++] = 0x04; /* id type */ - names[i].encoded[idx++] = GetNameId(i); + names[i].encoded[idx++] = bType; /* str type */ - names[i].encoded[idx++] = 0x13; + if (bType == ASN_COUNTRY_NAME) + names[i].encoded[idx++] = 0x13; /* printable */ + else + names[i].encoded[idx++] = 0x0c; /* utf8 */ } /* second length */ XMEMCPY(names[i].encoded + idx, secondLen, secondSz); @@ -3994,15 +4434,11 @@ static int SetName(byte* output, CertName* name) return totalBytes; } -/* encode info from cert into DER enocder format */ -static int EncodeCert( -Cert* cert, -DerCert* der, -RsaKey* rsaKey, -RNG* rng, - const byte* ntruKey, -word16 ntruSz) +/* encode info from cert into DER encoded format */ +static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey, + RNG* rng, const byte* ntruKey, word16 ntruSz) { + (void)eccKey; (void)ntruKey; (void)ntruSz; @@ -4018,18 +4454,31 @@ word16 ntruSz) der->serialSz = SetSerial(cert->serial, der->serial); /* signature algo */ - der->sigAlgoSz = SetAlgoID(cert->sigType, der->sigAlgo, sigType); + der->sigAlgoSz = SetAlgoID(cert->sigType, der->sigAlgo, sigType, 0); if (der->sigAlgoSz == 0) return ALGO_ID_E; /* public key */ if (cert->keyType == RSA_KEY) { - der->publicKeySz = SetPublicKey(der->publicKey, rsaKey); - if (der->publicKeySz == 0) + if (rsaKey == NULL) + return PUBLIC_KEY_E; + der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey); + if (der->publicKeySz <= 0) return PUBLIC_KEY_E; } - else { + +#ifdef HAVE_ECC + if (cert->keyType == ECC_KEY) { + if (eccKey == NULL) + return PUBLIC_KEY_E; + der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey); + if (der->publicKeySz <= 0) + return PUBLIC_KEY_E; + } +#endif /* HAVE_ECC */ + #ifdef HAVE_NTRU + if (cert->keyType == NTRU_KEY) { word32 rc; word16 encodedSz; @@ -4046,8 +4495,8 @@ word16 ntruSz) return PUBLIC_KEY_E; der->publicKeySz = encodedSz; -#endif } +#endif /* HAVE_NTRU */ der->validitySz = 0; #ifdef CYASSL_ALT_NAMES @@ -4088,7 +4537,8 @@ word16 ntruSz) /* extensions, just CA now */ if (cert->isCA) { - der->extensionsSz = SetExtensions(der->extensions, der->ca, der->caSz); + der->extensionsSz = SetExtensions(der->extensions, + der->ca, der->caSz, TRUE); if (der->extensionsSz == 0) return EXTENSIONS_E; } @@ -4098,7 +4548,7 @@ word16 ntruSz) #ifdef CYASSL_ALT_NAMES if (der->extensionsSz == 0 && cert->altNamesSz) { der->extensionsSz = SetExtensions(der->extensions, cert->altNames, - cert->altNamesSz); + cert->altNamesSz, TRUE); if (der->extensionsSz == 0) return EXTENSIONS_E; } @@ -4153,12 +4603,15 @@ static int WriteCertBody(DerCert* der, byte* buffer) /* Make RSA signature from buffer (sz), write to sig (sigSz) */ static int MakeSignature(const byte* buffer, int sz, byte* sig, int sigSz, - RsaKey* key, RNG* rng, int sigAlgoType) + RsaKey* rsaKey, ecc_key* eccKey, RNG* rng, + int sigAlgoType) { byte digest[SHA256_DIGEST_SIZE]; /* max size */ byte encSig[MAX_ENCODED_DIG_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ]; int encSigSz, digestSz, typeH; + (void)eccKey; + if (sigAlgoType == CTC_MD5wRSA) { Md5 md5; InitMd5(&md5); @@ -4167,7 +4620,7 @@ static int MakeSignature(const byte* buffer, int sz, byte* sig, int sigSz, digestSz = MD5_DIGEST_SIZE; typeH = MD5h; } - else if (sigAlgoType == CTC_SHAwRSA) { + else if (sigAlgoType == CTC_SHAwRSA || sigAlgoType == CTC_SHAwECDSA) { Sha sha; InitSha(&sha); ShaUpdate(&sha, buffer, sz); @@ -4175,7 +4628,7 @@ static int MakeSignature(const byte* buffer, int sz, byte* sig, int sigSz, digestSz = SHA_DIGEST_SIZE; typeH = SHAh; } - else if (sigAlgoType == CTC_SHA256wRSA) { + else if (sigAlgoType == CTC_SHA256wRSA || sigAlgoType == CTC_SHA256wECDSA) { Sha256 sha256; InitSha256(&sha256); Sha256Update(&sha256, buffer, sz); @@ -4186,9 +4639,23 @@ static int MakeSignature(const byte* buffer, int sz, byte* sig, int sigSz, else return ALGO_ID_E; - /* signature */ - encSigSz = EncodeSignature(encSig, digest, digestSz, typeH); - return RsaSSL_Sign(encSig, encSigSz, sig, sigSz, key, rng); + if (rsaKey) { + /* signature */ + encSigSz = EncodeSignature(encSig, digest, digestSz, typeH); + return RsaSSL_Sign(encSig, encSigSz, sig, sigSz, rsaKey, rng); + } +#ifdef HAVE_ECC + else if (eccKey) { + word32 outSz = sigSz; + int ret = ecc_sign_hash(digest, digestSz, sig, &outSz, rng, eccKey); + + if (ret != 0) + return ret; + return outSz; + } +#endif /* HAVE_ECC */ + + return ALGO_ID_E; } @@ -4201,7 +4668,7 @@ static int AddSignature(byte* buffer, int bodySz, const byte* sig, int sigSz, int idx = bodySz, seqSz; /* algo */ - idx += SetAlgoID(sigAlgoType, buffer + idx, sigType); + idx += SetAlgoID(sigAlgoType, buffer + idx, sigType, 0); /* bit string */ buffer[idx++] = ASN_BIT_STRING; /* length */ @@ -4222,13 +4689,17 @@ static int AddSignature(byte* buffer, int bodySz, const byte* sig, int sigSz, /* Make an x509 Certificate v3 any key type from cert input, write to buffer */ static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz, - RsaKey* rsaKey, RNG* rng, const byte* ntruKey, word16 ntruSz) + RsaKey* rsaKey, ecc_key* eccKey, RNG* rng, + const byte* ntruKey, word16 ntruSz) { DerCert der; int ret; - cert->keyType = rsaKey ? RSA_KEY : NTRU_KEY; - ret = EncodeCert(cert, &der, rsaKey, rng, ntruKey, ntruSz); + if (eccKey) + cert->keyType = ECC_KEY; + else + cert->keyType = rsaKey ? RSA_KEY : NTRU_KEY; + ret = EncodeCert(cert, &der, rsaKey, eccKey, rng, ntruKey, ntruSz); if (ret != 0) return ret; @@ -4239,10 +4710,11 @@ static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz, } -/* Make an x509 Certificate v3 RSA from cert input, write to buffer */ -int MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,RNG* rng) +/* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */ +int MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey, + ecc_key* eccKey, RNG* rng) { - return MakeAnyCert(cert, derBuffer, derSz, rsaKey, rng, NULL, 0); + return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, 0); } @@ -4251,41 +4723,231 @@ int MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,RNG* rng) int MakeNtruCert(Cert* cert, byte* derBuffer, word32 derSz, const byte* ntruKey, word16 keySz, RNG* rng) { - return MakeAnyCert(cert, derBuffer, derSz, NULL, rng, ntruKey, keySz); + return MakeAnyCert(cert, derBuffer, derSz, NULL, NULL, rng, ntruKey, keySz); } #endif /* HAVE_NTRU */ -int SignCert(Cert* cert, byte* buffer, word32 buffSz, RsaKey* key, RNG* rng) +#ifdef CYASSL_CERT_REQ + +static int SetReqAttrib(byte* output, char* pw, int extSz) +{ + static const byte cpOid[] = + { ASN_OBJECT_ID, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, + 0x09, 0x07 }; + static const byte erOid[] = + { ASN_OBJECT_ID, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, + 0x09, 0x0e }; + + int sz = 0; /* overall size */ + int cpSz = 0; /* Challenge Password section size */ + int cpSeqSz = 0; + int cpSetSz = 0; + int cpStrSz = 0; + int pwSz = 0; + int erSz = 0; /* Extension Request section size */ + int erSeqSz = 0; + int erSetSz = 0; + byte cpSeq[MAX_SEQ_SZ]; + byte cpSet[MAX_SET_SZ]; + byte cpStr[MAX_PRSTR_SZ]; + byte erSeq[MAX_SEQ_SZ]; + byte erSet[MAX_SET_SZ]; + + output[0] = 0xa0; + sz++; + + if (pw && pw[0]) { + pwSz = (int)XSTRLEN(pw); + cpStrSz = SetUTF8String(pwSz, cpStr); + cpSetSz = SetSet(cpStrSz + pwSz, cpSet); + cpSeqSz = SetSequence(sizeof(cpOid) + cpSetSz + cpStrSz + pwSz, cpSeq); + cpSz = cpSeqSz + sizeof(cpOid) + cpSetSz + cpStrSz + pwSz; + } + + if (extSz) { + erSetSz = SetSet(extSz, erSet); + erSeqSz = SetSequence(erSetSz + sizeof(erOid) + extSz, erSeq); + erSz = extSz + erSetSz + erSeqSz + sizeof(erOid); + } + + /* Put the pieces together. */ + sz += SetLength(cpSz + erSz, &output[sz]); + + if (cpSz) { + XMEMCPY(&output[sz], cpSeq, cpSeqSz); + sz += cpSeqSz; + XMEMCPY(&output[sz], cpOid, sizeof(cpOid)); + sz += sizeof(cpOid); + XMEMCPY(&output[sz], cpSet, cpSetSz); + sz += cpSetSz; + XMEMCPY(&output[sz], cpStr, cpStrSz); + sz += cpStrSz; + XMEMCPY(&output[sz], pw, pwSz); + sz += pwSz; + } + + if (erSz) { + XMEMCPY(&output[sz], erSeq, erSeqSz); + sz += erSeqSz; + XMEMCPY(&output[sz], erOid, sizeof(erOid)); + sz += sizeof(erOid); + XMEMCPY(&output[sz], erSet, erSetSz); + sz += erSetSz; + /* The actual extension data will be tacked onto the output later. */ + } + + return sz; +} + + +/* encode info from cert into DER encoded format */ +static int EncodeCertReq(Cert* cert, DerCert* der, + RsaKey* rsaKey, ecc_key* eccKey) +{ + (void)eccKey; + + /* init */ + XMEMSET(der, 0, sizeof(DerCert)); + + /* version */ + der->versionSz = SetMyVersion(cert->version, der->version, FALSE); + + /* subject name */ + der->subjectSz = SetName(der->subject, &cert->subject); + if (der->subjectSz == 0) + return SUBJECT_E; + + /* public key */ + if (cert->keyType == RSA_KEY) { + if (rsaKey == NULL) + return PUBLIC_KEY_E; + der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey); + if (der->publicKeySz <= 0) + return PUBLIC_KEY_E; + } + +#ifdef HAVE_ECC + if (cert->keyType == ECC_KEY) { + if (eccKey == NULL) + return PUBLIC_KEY_E; + der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey); + if (der->publicKeySz <= 0) + return PUBLIC_KEY_E; + } +#endif /* HAVE_ECC */ + + /* CA */ + if (cert->isCA) { + der->caSz = SetCa(der->ca); + if (der->caSz == 0) + return CA_TRUE_E; + } + else + der->caSz = 0; + + /* extensions, just CA now */ + if (cert->isCA) { + der->extensionsSz = SetExtensions(der->extensions, + der->ca, der->caSz, FALSE); + if (der->extensionsSz == 0) + return EXTENSIONS_E; + } + else + der->extensionsSz = 0; + + der->attribSz = SetReqAttrib(der->attrib, + cert->challengePw, der->extensionsSz); + if (der->attribSz == 0) + return REQ_ATTRIBUTE_E; + + der->total = der->versionSz + der->subjectSz + der->publicKeySz + + der->extensionsSz + der->attribSz; + + return 0; +} + + +/* write DER encoded cert req to buffer, size already checked */ +static int WriteCertReqBody(DerCert* der, byte* buffer) +{ + int idx; + + /* signed part header */ + idx = SetSequence(der->total, buffer); + /* version */ + XMEMCPY(buffer + idx, der->version, der->versionSz); + idx += der->versionSz; + /* subject */ + XMEMCPY(buffer + idx, der->subject, der->subjectSz); + idx += der->subjectSz; + /* public key */ + XMEMCPY(buffer + idx, der->publicKey, der->publicKeySz); + idx += der->publicKeySz; + /* attributes */ + XMEMCPY(buffer + idx, der->attrib, der->attribSz); + idx += der->attribSz; + /* extensions */ + if (der->extensionsSz) { + XMEMCPY(buffer + idx, der->extensions, min(der->extensionsSz, + sizeof(der->extensions))); + idx += der->extensionsSz; + } + + return idx; +} + + +int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz, + RsaKey* rsaKey, ecc_key* eccKey) +{ + DerCert der; + int ret; + + cert->keyType = (eccKey != NULL) ? ECC_KEY : RSA_KEY; + ret = EncodeCertReq(cert, &der, rsaKey, eccKey); + if (ret != 0) + return ret; + + if (der.total + MAX_SEQ_SZ * 2 > (int)derSz) + return BUFFER_E; + + return cert->bodySz = WriteCertReqBody(&der, derBuffer); +} + +#endif /* CYASSL_CERT_REQ */ + + +int SignCert(int requestSz, int sType, byte* buffer, word32 buffSz, + RsaKey* rsaKey, ecc_key* eccKey, RNG* rng) { byte sig[MAX_ENCODED_SIG_SZ]; int sigSz; - int bodySz = cert->bodySz; - if (bodySz < 0) - return bodySz; + if (requestSz < 0) + return requestSz; - sigSz = MakeSignature(buffer, bodySz, sig, sizeof(sig), key, rng, - cert->sigType); + sigSz = MakeSignature(buffer, requestSz, sig, sizeof(sig), rsaKey, eccKey, + rng, sType); if (sigSz < 0) return sigSz; - if (bodySz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz) + if (requestSz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz) return BUFFER_E; - return AddSignature(buffer, bodySz, sig, sigSz, cert->sigType); + return AddSignature(buffer, requestSz, sig, sigSz, sType); } int MakeSelfCert(Cert* cert, byte* buffer, word32 buffSz, RsaKey* key, RNG* rng) { - int ret = MakeCert(cert, buffer, buffSz, key, rng); + int ret = MakeCert(cert, buffer, buffSz, key, NULL, rng); if (ret < 0) return ret; - return SignCert(cert, buffer, buffSz, key, rng); + return SignCert(cert->bodySz, cert->sigType, buffer, buffSz, key, NULL,rng); } @@ -4611,7 +5273,8 @@ int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s) int sLen = mp_unsigned_bin_size(s); int err; - if (*outLen < (rLen + sLen + headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */ + if (*outLen < (rLen + rLeadingZero + sLen + sLeadingZero + + headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */ return BAD_FUNC_ARG; idx = SetSequence(rLen+rLeadingZero+sLen+sLeadingZero+headerSz, out); @@ -5215,33 +5878,6 @@ int OcspResponseDecode(OcspResponse* resp) } -static int SetSerialNumber(const byte* sn, word32 snSz, byte* output) -{ - int result = 0; - - CYASSL_ENTER("SetSerialNumber"); - - if (snSz <= EXTERNAL_SERIAL_SIZE) { - output[0] = ASN_INTEGER; - /* The serial number is always positive. When encoding the - * INTEGER, if the MSB is 1, add a padding zero to keep the - * number positive. */ - if (sn[0] & 0x80) { - output[1] = (byte)snSz + 1; - output[2] = 0; - XMEMCPY(&output[3], sn, snSz); - result = snSz + 3; - } - else { - output[1] = (byte)snSz; - XMEMCPY(&output[2], sn, snSz); - result = snSz + 2; - } - } - return result; -} - - static word32 SetOcspReqExtensions(word32 extSz, byte* output, const byte* nonce, word32 nonceSz) { @@ -5310,7 +5946,7 @@ int EncodeOcspRequest(OcspRequest* req) CYASSL_ENTER("EncodeOcspRequest"); - algoSz = SetAlgoID(SHAh, algoArray, hashType); + algoSz = SetAlgoID(SHAh, algoArray, hashType, 0); req->issuerHash = req->cert->issuerHash; issuerSz = SetDigest(req->cert->issuerHash, SHA_SIZE, issuerArray); @@ -5398,7 +6034,9 @@ int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp) return 1; } - if (req->useNonce) { + /* Nonces are not critical. The responder may not necessarily add + * the nonce to the response. */ + if (req->useNonce && resp->nonceSz != 0) { cmp = req->nonceSz - resp->nonceSz; if (cmp != 0) { @@ -5448,39 +6086,9 @@ int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp) #endif -#ifdef HAVE_CRL - -/* initialize decoded CRL */ -void InitDecodedCRL(DecodedCRL* dcrl) -{ - CYASSL_MSG("InitDecodedCRL"); - - dcrl->certBegin = 0; - dcrl->sigIndex = 0; - dcrl->sigLength = 0; - dcrl->signatureOID = 0; - dcrl->certs = NULL; - dcrl->totalCerts = 0; -} - - -/* free decoded CRL resources */ -void FreeDecodedCRL(DecodedCRL* dcrl) -{ - RevokedCert* tmp = dcrl->certs; - - CYASSL_MSG("FreeDecodedCRL"); - - while(tmp) { - RevokedCert* next = tmp->next; - XFREE(tmp, NULL, DYNAMIC_TYPE_REVOKED); - tmp = next; - } -} - - /* store SHA1 hash of NAME */ -static int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx) +CYASSL_LOCAL int GetNameHash(const byte* source, word32* idx, byte* hash, + int maxIdx) { Sha sha; int length; /* length of all distinguished names */ @@ -5515,6 +6123,37 @@ static int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx) } +#ifdef HAVE_CRL + +/* initialize decoded CRL */ +void InitDecodedCRL(DecodedCRL* dcrl) +{ + CYASSL_MSG("InitDecodedCRL"); + + dcrl->certBegin = 0; + dcrl->sigIndex = 0; + dcrl->sigLength = 0; + dcrl->signatureOID = 0; + dcrl->certs = NULL; + dcrl->totalCerts = 0; +} + + +/* free decoded CRL resources */ +void FreeDecodedCRL(DecodedCRL* dcrl) +{ + RevokedCert* tmp = dcrl->certs; + + CYASSL_MSG("FreeDecodedCRL"); + + while(tmp) { + RevokedCert* next = tmp->next; + XFREE(tmp, NULL, DYNAMIC_TYPE_REVOKED); + tmp = next; + } +} + + /* Get Revoked Cert list, 0 on success */ static int GetRevoked(const byte* buff, word32* idx, DecodedCRL* dcrl, int maxIdx) diff --git a/ctaocrypt/src/coding.c b/ctaocrypt/src/coding.c index 78286faae..8add2d59a 100644 --- a/ctaocrypt/src/coding.c +++ b/ctaocrypt/src/coding.c @@ -147,16 +147,101 @@ const byte base64Encode[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', }; -/* porting assistance from yaSSL by Raphael HUCK */ -int Base64_Encode(const byte* in, word32 inLen, byte* out, word32* outLen) +/* make sure *i (idx) won't exceed max, store and possibly escape to out, + * raw means use e w/o decode, 0 on success */ +static int CEscape(int escaped, byte e, byte* out, word32* i, word32 max, + int raw) { + int doEscape = 0; + word32 needed = 1; + word32 idx = *i; + + byte basic; + byte plus = 0; + byte equals = 0; + byte newline = 0; + + if (raw) + basic = e; + else + basic = base64Encode[e]; + + /* check whether to escape */ + if (escaped) { + switch ((char)basic) { + case '+' : + plus = 1; + doEscape = 1; + needed += 2; + break; + case '=' : + equals = 1; + doEscape = 1; + needed += 2; + break; + case '\n' : + newline = 1; + doEscape = 1; + needed += 2; + break; + default: + /* do nothing */ + break; + } + } + + /* check size */ + if ( (idx+needed) > max) { + CYASSL_MSG("Escape buffer max too small"); + return BUFFER_E; + } + + /* store it */ + if (doEscape == 0) { + out[idx++] = basic; + } + else { + out[idx++] = '%'; /* start escape */ + + if (plus) { + out[idx++] = '2'; + out[idx++] = 'B'; + } + else if (equals) { + out[idx++] = '3'; + out[idx++] = 'D'; + } + else if (newline) { + out[idx++] = '0'; + out[idx++] = 'A'; + } + + } + *i = idx; + + return 0; +} + + +/* internal worker, handles both escaped and normal line endings */ +static int DoBase64_Encode(const byte* in, word32 inLen, byte* out, + word32* outLen, int escaped) +{ + int ret = 0; word32 i = 0, j = 0, n = 0; /* new line counter */ word32 outSz = (inLen + 3 - 1) / 3 * 4; - outSz += (outSz + PEM_LINE_SZ - 1) / PEM_LINE_SZ; /* new lines */ + word32 addSz = (outSz + PEM_LINE_SZ - 1) / PEM_LINE_SZ; /* new lines */ + if (escaped) + addSz *= 3; /* instead of just \n, we're doing %0A triplet */ + + outSz += addSz; + + /* if escaped we can't predetermine size for one pass encoding, but + * make sure we have enough if no escapes are in input */ if (outSz > *outLen) return BAD_FUNC_ARG; while (inLen > 2) { @@ -171,19 +256,25 @@ int Base64_Encode(const byte* in, word32 inLen, byte* out, word32* outLen) byte e4 = b3 & 0x3F; /* store */ - out[i++] = base64Encode[e1]; - out[i++] = base64Encode[e2]; - out[i++] = base64Encode[e3]; - out[i++] = base64Encode[e4]; + ret = CEscape(escaped, e1, out, &i, *outLen, 0); + if (ret != 0) break; + ret = CEscape(escaped, e2, out, &i, *outLen, 0); + if (ret != 0) break; + ret = CEscape(escaped, e3, out, &i, *outLen, 0); + if (ret != 0) break; + ret = CEscape(escaped, e4, out, &i, *outLen, 0); + if (ret != 0) break; inLen -= 3; - if ((++n % (PEM_LINE_SZ / 4)) == 0 && inLen) - out[i++] = '\n'; + if ((++n % (PEM_LINE_SZ / 4)) == 0 && inLen) { + ret = CEscape(escaped, '\n', out, &i, *outLen, 1); + if (ret != 0) break; + } } /* last integral */ - if (inLen) { + if (inLen && ret == 0) { int twoBytes = (inLen == 2); byte b1 = in[j++]; @@ -193,18 +284,43 @@ int Base64_Encode(const byte* in, word32 inLen, byte* out, word32* outLen) byte e2 = ((b1 & 0x3) << 4) | (b2 >> 4); byte e3 = (b2 & 0xF) << 2; - out[i++] = base64Encode[e1]; - out[i++] = base64Encode[e2]; - out[i++] = (twoBytes) ? base64Encode[e3] : PAD; - out[i++] = PAD; + ret = CEscape(escaped, e1, out, &i, *outLen, 0); + if (ret == 0) + ret = CEscape(escaped, e2, out, &i, *outLen, 0); + if (ret == 0) { + /* third */ + if (twoBytes) + ret = CEscape(escaped, e3, out, &i, *outLen, 0); + else + ret = CEscape(escaped, '=', out, &i, *outLen, 1); + } + /* fourth always pad */ + if (ret == 0) + ret = CEscape(escaped, '=', out, &i, *outLen, 1); } - out[i++] = '\n'; - if (i != outSz) - return ASN_INPUT_E; - *outLen = outSz; + if (ret == 0) + ret = CEscape(escaped, '\n', out, &i, *outLen, 1); - return 0; + if (i != outSz && escaped == 0 && ret == 0) + return ASN_INPUT_E; + + *outLen = i; + return ret; +} + + +/* Base64 Encode, PEM style, with \n line endings */ +int Base64_Encode(const byte* in, word32 inLen, byte* out, word32* outLen) +{ + return DoBase64_Encode(in, inLen, out, outLen, 0); +} + + +/* Base64 Encode, with %0A esacped line endings instead of \n */ +int Base64_EncodeEsc(const byte* in, word32 inLen, byte* out, word32* outLen) +{ + return DoBase64_Encode(in, inLen, out, outLen, 1); } diff --git a/ctaocrypt/src/des3.c b/ctaocrypt/src/des3.c index c5e7ef580..cdccaaaea 100644 --- a/ctaocrypt/src/des3.c +++ b/ctaocrypt/src/des3.c @@ -413,6 +413,187 @@ void Des3_SetKey(Des3* des3, const byte* key, const byte* iv, int dir) } } +#elif defined FREESCALE_MMCAU + /* + * Freescale mmCAU hardware DES/3DES support through the CAU/mmCAU library. + * Documentation located in ColdFire/ColdFire+ CAU and Kinetis mmCAU + * Software Library User Guide (See note in README). + */ + #include "cau_api.h" + + const unsigned char parityLookup[128] = + { + 1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0, + 0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1, + 0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1, + 1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0 + }; + + void Des_SetKey(Des* des, const byte* key, const byte* iv, int dir) + { + int i = 0; + byte* dkey = (byte*)des->key; + + XMEMCPY(dkey, key, 8); + + Des_SetIV(des, iv); + + /* fix key parity, if needed */ + for (i = 0; i < 8; i++) { + dkey[i] = ((dkey[i] & 0xFE) | parityLookup[dkey[i] >> 1]); + } + } + + void Des3_SetKey(Des3* des, const byte* key, const byte* iv, int dir) + { + int i = 0; + byte* dkey1 = (byte*)des->key[0]; + byte* dkey2 = (byte*)des->key[1]; + byte* dkey3 = (byte*)des->key[2]; + + XMEMCPY(dkey1, key, 8); /* set key 1 */ + XMEMCPY(dkey2, key + 8, 8); /* set key 2 */ + XMEMCPY(dkey3, key + 16, 8); /* set key 3 */ + + Des3_SetIV(des, iv); + + /* fix key parity if needed */ + for (i = 0; i < 8; i++) + dkey1[i] = ((dkey1[i] & 0xFE) | parityLookup[dkey1[i] >> 1]); + + for (i = 0; i < 8; i++) + dkey2[i] = ((dkey2[i] & 0xFE) | parityLookup[dkey2[i] >> 1]); + + for (i = 0; i < 8; i++) + dkey3[i] = ((dkey3[i] & 0xFE) | parityLookup[dkey3[i] >> 1]); + } + + void Des_CbcEncrypt(Des* des, byte* out, const byte* in, word32 sz) + { + int i; + int offset = 0; + int len = sz; + byte *iv; + byte temp_block[DES_BLOCK_SIZE]; + + iv = (byte*)des->reg; + + while (len > 0) + { + XMEMCPY(temp_block, in + offset, DES_BLOCK_SIZE); + + /* XOR block with IV for CBC */ + for (i = 0; i < DES_BLOCK_SIZE; i++) + temp_block[i] ^= iv[i]; + + cau_des_encrypt(temp_block, (byte*)des->key, out + offset); + + len -= DES_BLOCK_SIZE; + offset += DES_BLOCK_SIZE; + + /* store IV for next block */ + XMEMCPY(iv, out + offset - DES_BLOCK_SIZE, DES_BLOCK_SIZE); + } + + return; + } + + void Des_CbcDecrypt(Des* des, byte* out, const byte* in, word32 sz) + { + int i; + int offset = 0; + int len = sz; + byte* iv; + byte temp_block[DES_BLOCK_SIZE]; + + iv = (byte*)des->reg; + + while (len > 0) + { + XMEMCPY(temp_block, in + offset, DES_BLOCK_SIZE); + + cau_des_decrypt(in + offset, (byte*)des->key, out + offset); + + /* XOR block with IV for CBC */ + for (i = 0; i < DES_BLOCK_SIZE; i++) + (out + offset)[i] ^= iv[i]; + + /* store IV for next block */ + XMEMCPY(iv, temp_block, DES_BLOCK_SIZE); + + len -= DES_BLOCK_SIZE; + offset += DES_BLOCK_SIZE; + } + + return; + } + + void Des3_CbcEncrypt(Des3* des, byte* out, const byte* in, word32 sz) + { + int i; + int offset = 0; + int len = sz; + + byte *iv; + byte temp_block[DES_BLOCK_SIZE]; + + iv = (byte*)des->reg; + + while (len > 0) + { + XMEMCPY(temp_block, in + offset, DES_BLOCK_SIZE); + + /* XOR block with IV for CBC */ + for (i = 0; i < DES_BLOCK_SIZE; i++) + temp_block[i] ^= iv[i]; + + cau_des_encrypt(temp_block , (byte*)des->key[0], out + offset); + cau_des_decrypt(out + offset, (byte*)des->key[1], out + offset); + cau_des_encrypt(out + offset, (byte*)des->key[2], out + offset); + + len -= DES_BLOCK_SIZE; + offset += DES_BLOCK_SIZE; + + /* store IV for next block */ + XMEMCPY(iv, out + offset - DES_BLOCK_SIZE, DES_BLOCK_SIZE); + } + + return; + } + + void Des3_CbcDecrypt(Des3* des, byte* out, const byte* in, word32 sz) + { + int i; + int offset = 0; + int len = sz; + + byte* iv; + byte temp_block[DES_BLOCK_SIZE]; + + iv = (byte*)des->reg; + + while (len > 0) + { + XMEMCPY(temp_block, in + offset, DES_BLOCK_SIZE); + + cau_des_decrypt(in + offset , (byte*)des->key[2], out + offset); + cau_des_encrypt(out + offset, (byte*)des->key[1], out + offset); + cau_des_decrypt(out + offset, (byte*)des->key[0], out + offset); + + /* XOR block with IV for CBC */ + for (i = 0; i < DES_BLOCK_SIZE; i++) + (out + offset)[i] ^= iv[i]; + + /* store IV for next block */ + XMEMCPY(iv, temp_block, DES_BLOCK_SIZE); + + len -= DES_BLOCK_SIZE; + offset += DES_BLOCK_SIZE; + } + + return; + } + #else /* CTaoCrypt software implementation */ /* permuted choice table (key) */ diff --git a/ctaocrypt/src/ecc.c b/ctaocrypt/src/ecc.c index 0a87e00cb..609a386f8 100644 --- a/ctaocrypt/src/ecc.c +++ b/ctaocrypt/src/ecc.c @@ -1997,7 +1997,6 @@ int ecc_export_x963(ecc_key* key, byte* out, word32* outLen) int ecc_import_x963(const byte* in, word32 inLen, ecc_key* key) { int x, err; - if (in == NULL || key == NULL) return ECC_BAD_ARG_E; @@ -2144,17 +2143,22 @@ int ecc_sig_size(ecc_key* key) /** Our FP cache */ -static struct { +typedef struct { ecc_point* g; /* cached COPY of base point */ ecc_point* LUT[1U<encAlgo = ecAES_128_CBC; - options->kdfAlgo = ecHKDF_SHA256; - options->macAlgo = ecHMAC_SHA256; +enum ecCliState { + ecCLI_INIT = 1, + ecCLI_SALT_GET = 2, + ecCLI_SALT_SET = 3, + ecCLI_SENT_REQ = 4, + ecCLI_RECV_RESP = 5, + ecCLI_BAD_STATE = 99 +}; + +enum ecSrvState { + ecSRV_INIT = 1, + ecSRV_SALT_GET = 2, + ecSRV_SALT_SET = 3, + ecSRV_RECV_REQ = 4, + ecSRV_SENT_RESP = 5, + ecSRV_BAD_STATE = 99 +}; + + +struct ecEncCtx { + byte* kdfSalt; /* optional salt for kdf */ + byte* kdfInfo; /* optional info for kdf */ + byte* macSalt; /* optional salt for mac */ + word32 kdfSaltSz; /* size of kdfSalt */ + word32 kdfInfoSz; /* size of kdfInfo */ + word32 macSaltSz; /* size of macSalt */ + byte clientSalt[EXCHANGE_SALT_SZ]; /* for msg exchange */ + byte serverSalt[EXCHANGE_SALT_SZ]; /* for msg exchange */ + byte encAlgo; /* which encryption type */ + byte kdfAlgo; /* which key derivation function type */ + byte macAlgo; /* which mac function type */ + byte protocol; /* are we REQ_RESP client or server ? */ + byte cliSt; /* protocol state, for sanity checks */ + byte srvSt; /* protocol state, for sanity checks */ +}; + + +const byte* ecc_ctx_get_own_salt(ecEncCtx* ctx) +{ + if (ctx == NULL || ctx->protocol == 0) + return NULL; + + if (ctx->protocol == REQ_RESP_CLIENT) { + if (ctx->cliSt == ecCLI_INIT) { + ctx->cliSt = ecCLI_SALT_GET; + return ctx->clientSalt; + } + else { + ctx->cliSt = ecCLI_BAD_STATE; + return NULL; + } } + else if (ctx->protocol == REQ_RESP_SERVER) { + if (ctx->srvSt == ecSRV_INIT) { + ctx->srvSt = ecSRV_SALT_GET; + return ctx->serverSalt; + } + else { + ctx->srvSt = ecSRV_BAD_STATE; + return NULL; + } + } + + return NULL; +} + + +static const char* exchange_info = "Secure Message Exchange"; + +int ecc_ctx_set_peer_salt(ecEncCtx* ctx, const byte* salt) +{ + byte tmp[EXCHANGE_SALT_SZ/2]; + int halfSz = EXCHANGE_SALT_SZ/2; + + if (ctx == NULL || ctx->protocol == 0 || salt == NULL) + return BAD_FUNC_ARG; + + if (ctx->protocol == REQ_RESP_CLIENT) { + XMEMCPY(ctx->serverSalt, salt, EXCHANGE_SALT_SZ); + if (ctx->cliSt == ecCLI_SALT_GET) + ctx->cliSt = ecCLI_SALT_SET; + else { + ctx->cliSt = ecCLI_BAD_STATE; + return BAD_ENC_STATE_E; + } + } + else { + XMEMCPY(ctx->clientSalt, salt, EXCHANGE_SALT_SZ); + if (ctx->srvSt == ecSRV_SALT_GET) + ctx->srvSt = ecSRV_SALT_SET; + else { + ctx->srvSt = ecSRV_BAD_STATE; + return BAD_ENC_STATE_E; + } + } + + /* mix half and half */ + /* tmp stores 2nd half of client before overwrite */ + XMEMCPY(tmp, ctx->clientSalt + halfSz, halfSz); + XMEMCPY(ctx->clientSalt + halfSz, ctx->serverSalt, halfSz); + XMEMCPY(ctx->serverSalt, tmp, halfSz); + + ctx->kdfSalt = ctx->clientSalt; + ctx->kdfSaltSz = EXCHANGE_SALT_SZ; + + ctx->macSalt = ctx->serverSalt; + ctx->macSaltSz = EXCHANGE_SALT_SZ; + + ctx->kdfInfo = (byte*)exchange_info; + ctx->kdfInfoSz = EXCHANGE_INFO_SZ; + + return 0; +} + + +static int ecc_ctx_set_salt(ecEncCtx* ctx, int flags, RNG* rng) +{ + byte* saltBuffer = NULL; + + if (ctx == NULL || rng == NULL || flags == 0) + return BAD_FUNC_ARG; + + saltBuffer = (flags == REQ_RESP_CLIENT) ? ctx->clientSalt : ctx->serverSalt; + RNG_GenerateBlock(rng, saltBuffer, EXCHANGE_SALT_SZ); + + return 0; +} + + +static void ecc_ctx_init(ecEncCtx* ctx, int flags) +{ + if (ctx) { + XMEMSET(ctx, 0, sizeof(ecEncCtx)); + + ctx->encAlgo = ecAES_128_CBC; + ctx->kdfAlgo = ecHKDF_SHA256; + ctx->macAlgo = ecHMAC_SHA256; + ctx->protocol = (byte)flags; + + if (flags == REQ_RESP_CLIENT) + ctx->cliSt = ecCLI_INIT; + if (flags == REQ_RESP_SERVER) + ctx->srvSt = ecSRV_INIT; + } +} + + +/* alloc/init and set defaults, return new Context */ +ecEncCtx* ecc_ctx_new(int flags, RNG* rng) +{ + int ret = 0; + ecEncCtx* ctx = (ecEncCtx*)XMALLOC(sizeof(ecEncCtx), 0, DYNAMIC_TYPE_ECC); + + ecc_ctx_init(ctx, flags); + + if (ctx && flags) + ret = ecc_ctx_set_salt(ctx, flags, rng); + + if (ret != 0) { + ecc_ctx_free(ctx); + ctx = NULL; + } + + return ctx; } /* free any resources, clear any keys */ -void ecc_encrypt_free_options(ecEncOptions* options) +void ecc_ctx_free(ecEncCtx* ctx) { - if (options) { - XMEMSET(options, 0, sizeof(ecEncOptions)); + if (ctx) { + XMEMSET(ctx, 0, sizeof(ecEncCtx)); + XFREE(ctx, 0, DYNAMIC_TYPE_ECC); } } -static int ecc_get_key_sizes(ecEncOptions* options, int* encKeySz, int* ivSz, +static int ecc_get_key_sizes(ecEncCtx* ctx, int* encKeySz, int* ivSz, int* keysLen, word32* digestSz, word32* blockSz) { - if (options) { - switch (options->encAlgo) { + if (ctx) { + switch (ctx->encAlgo) { case ecAES_128_CBC: *encKeySz = KEY_SIZE_128; *ivSz = IV_SIZE_64; @@ -3529,7 +3701,7 @@ static int ecc_get_key_sizes(ecEncOptions* options, int* encKeySz, int* ivSz, return BAD_FUNC_ARG; } - switch (options->macAlgo) { + switch (ctx->macAlgo) { case ecHMAC_SHA256: *digestSz = SHA256_DIGEST_SIZE; break; @@ -3546,22 +3718,23 @@ static int ecc_get_key_sizes(ecEncOptions* options, int* encKeySz, int* ivSz, /* ecc encrypt with shared secret run through kdf - options holds non default algos and inputs + ctx holds non default algos and inputs msgSz should be the right size for encAlgo, i.e., already padded return 0 on success */ int ecc_encrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, - word32 msgSz, byte* out, word32* outSz, ecEncOptions* opts) + word32 msgSz, byte* out, word32* outSz, ecEncCtx* ctx) { int ret; word32 blockSz; word32 digestSz; - ecEncOptions options; + ecEncCtx localCtx; byte sharedSecret[ECC_MAXSIZE]; /* 521 max size */ byte keys[ECC_BUFSIZE]; /* max size */ word32 sharedSz = sizeof(sharedSecret); int keysLen; int encKeySz; int ivSz; + int offset = 0; /* keys offset if doing msg exchange */ byte* encKey; byte* encIv; byte* macKey; @@ -3570,19 +3743,37 @@ int ecc_encrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, outSz == NULL) return BAD_FUNC_ARG; - if (opts) - options = *opts; - else { - ecc_encrypt_init_options(&options); /* defaults */ + if (ctx == NULL) { /* use defaults */ + ecc_ctx_init(&localCtx, 0); + ctx = &localCtx; } - ret = ecc_get_key_sizes(&options, &encKeySz, &ivSz, &keysLen, &digestSz, + ret = ecc_get_key_sizes(ctx, &encKeySz, &ivSz, &keysLen, &digestSz, &blockSz); if (ret != 0) return ret; + + if (ctx->protocol == REQ_RESP_SERVER) { + offset = keysLen; + keysLen *= 2; + + if (ctx->srvSt != ecSRV_RECV_REQ) + return BAD_ENC_STATE_E; + + ctx->srvSt = ecSRV_BAD_STATE; /* we're done no more ops allowed */ + } + else if (ctx->protocol == REQ_RESP_CLIENT) { + if (ctx->cliSt != ecCLI_SALT_SET) + return BAD_ENC_STATE_E; + + ctx->cliSt = ecCLI_SENT_REQ; /* only do this once */ + } + + if (keysLen > (int)sizeof(keys)) + return BUFFER_E; if ( (msgSz%blockSz) != 0) - return BAD_FUNC_ARG; + return BAD_PADDING_E; if (*outSz < (msgSz + digestSz)) return BUFFER_E; @@ -3591,11 +3782,11 @@ int ecc_encrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, if (ret != 0) return ret; - switch (options.kdfAlgo) { + switch (ctx->kdfAlgo) { case ecHKDF_SHA256 : - ret = HKDF(SHA256, sharedSecret, sharedSz, options.kdfSalt, - options.kdfSaltSz, options.kdfInfo, - options.kdfInfoSz, keys, keysLen); + ret = HKDF(SHA256, sharedSecret, sharedSz, ctx->kdfSalt, + ctx->kdfSaltSz, ctx->kdfInfo, + ctx->kdfInfoSz, keys, keysLen); if (ret != 0) return ret; break; @@ -3604,11 +3795,11 @@ int ecc_encrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, return BAD_FUNC_ARG; } - encKey = keys; + encKey = keys + offset; encIv = encKey + encKeySz; macKey = encKey + encKeySz + ivSz; - switch (options.encAlgo) { + switch (ctx->encAlgo) { case ecAES_128_CBC: { Aes aes; @@ -3625,7 +3816,7 @@ int ecc_encrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, return BAD_FUNC_ARG; } - switch (options.macAlgo) { + switch (ctx->macAlgo) { case ecHMAC_SHA256: { Hmac hmac; @@ -3633,7 +3824,7 @@ int ecc_encrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, if (ret != 0) return ret; HmacUpdate(&hmac, out, msgSz); - HmacUpdate(&hmac, options.macSalt, options.macSaltSz); + HmacUpdate(&hmac, ctx->macSalt, ctx->macSaltSz); HmacFinal(&hmac, out+msgSz); } break; @@ -3648,19 +3839,23 @@ int ecc_encrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, } +/* ecc decrypt with shared secret run through kdf + ctx holds non default algos and inputs + return 0 on success */ int ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, - word32 msgSz, byte* out, word32* outSz, ecEncOptions* opts) + word32 msgSz, byte* out, word32* outSz, ecEncCtx* ctx) { int ret; word32 blockSz; word32 digestSz; - ecEncOptions options; + ecEncCtx localCtx; byte sharedSecret[ECC_MAXSIZE]; /* 521 max size */ byte keys[ECC_BUFSIZE]; /* max size */ word32 sharedSz = sizeof(sharedSecret); int keysLen; int encKeySz; int ivSz; + int offset = 0; /* in case using msg exchange */ byte* encKey; byte* encIv; byte* macKey; @@ -3669,19 +3864,37 @@ int ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, outSz == NULL) return BAD_FUNC_ARG; - if (opts) - options = *opts; - else { - ecc_encrypt_init_options(&options); /* defaults */ + if (ctx == NULL) { /* use defaults */ + ecc_ctx_init(&localCtx, 0); + ctx = &localCtx; } - - ret = ecc_get_key_sizes(&options, &encKeySz, &ivSz, &keysLen, &digestSz, + + ret = ecc_get_key_sizes(ctx, &encKeySz, &ivSz, &keysLen, &digestSz, &blockSz); if (ret != 0) return ret; + if (ctx->protocol == REQ_RESP_CLIENT) { + offset = keysLen; + keysLen *= 2; + + if (ctx->cliSt != ecCLI_SENT_REQ) + return BAD_ENC_STATE_E; + + ctx->cliSt = ecSRV_BAD_STATE; /* we're done no more ops allowed */ + } + else if (ctx->protocol == REQ_RESP_SERVER) { + if (ctx->srvSt != ecSRV_SALT_SET) + return BAD_ENC_STATE_E; + + ctx->srvSt = ecSRV_RECV_REQ; /* only do this once */ + } + + if (keysLen > (int)sizeof(keys)) + return BUFFER_E; + if ( ((msgSz-digestSz) % blockSz) != 0) - return BAD_FUNC_ARG; + return BAD_PADDING_E; if (*outSz < (msgSz - digestSz)) return BUFFER_E; @@ -3690,11 +3903,11 @@ int ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, if (ret != 0) return ret; - switch (options.kdfAlgo) { + switch (ctx->kdfAlgo) { case ecHKDF_SHA256 : - ret = HKDF(SHA256, sharedSecret, sharedSz, options.kdfSalt, - options.kdfSaltSz, options.kdfInfo, - options.kdfInfoSz, keys, keysLen); + ret = HKDF(SHA256, sharedSecret, sharedSz, ctx->kdfSalt, + ctx->kdfSaltSz, ctx->kdfInfo, + ctx->kdfInfoSz, keys, keysLen); if (ret != 0) return ret; break; @@ -3703,11 +3916,11 @@ int ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, return BAD_FUNC_ARG; } - encKey = keys; + encKey = keys + offset; encIv = encKey + encKeySz; macKey = encKey + encKeySz + ivSz; - switch (options.macAlgo) { + switch (ctx->macAlgo) { case ecHMAC_SHA256: { byte verify[SHA256_DIGEST_SIZE]; @@ -3716,7 +3929,7 @@ int ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, if (ret != 0) return ret; HmacUpdate(&hmac, msg, msgSz-digestSz); - HmacUpdate(&hmac, options.macSalt, options.macSaltSz); + HmacUpdate(&hmac, ctx->macSalt, ctx->macSaltSz); HmacFinal(&hmac, verify); if (memcmp(verify, msg + msgSz - digestSz, digestSz) != 0) { @@ -3729,7 +3942,7 @@ int ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, return BAD_FUNC_ARG; } - switch (options.encAlgo) { + switch (ctx->encAlgo) { case ecAES_128_CBC: { Aes aes; diff --git a/ctaocrypt/src/error.c b/ctaocrypt/src/error.c index e6b4eaf3b..d7ed45194 100644 --- a/ctaocrypt/src/error.c +++ b/ctaocrypt/src/error.c @@ -323,6 +323,26 @@ void CTaoCryptErrorString(int error, char* buffer) XSTRNCPY(buffer, "ASN OCSP sig error, confirm failure", max); break; + case BAD_ENC_STATE_E: + XSTRNCPY(buffer, "Bad ecc encrypt state operation", max); + break; + + case BAD_PADDING_E: + XSTRNCPY(buffer, "Bad padding, message wrong length", max); + break; + + case REQ_ATTRIBUTE_E: + XSTRNCPY(buffer, "Setting cert request attributes error", max); + break; + + case PKCS7_OID_E: + XSTRNCPY(buffer, "PKCS#7 error: mismatched OID value", max); + break; + + case PKCS7_RECIP_E: + XSTRNCPY(buffer, "PKCS#7 error: no matching recipient found", max); + break; + default: XSTRNCPY(buffer, "unknown error number", max); diff --git a/ctaocrypt/src/fp_sqr_comba_12.i b/ctaocrypt/src/fp_sqr_comba_12.i index 7ecb7c9e1..2f068c7d9 100644 --- a/ctaocrypt/src/fp_sqr_comba_12.i +++ b/ctaocrypt/src/fp_sqr_comba_12.i @@ -24,7 +24,9 @@ void fp_sqr_comba12(fp_int *A, fp_int *B) { fp_digit *a, b[24], c0, c1, c2, sc0, sc1, sc2; - +#ifdef TFM_ISO + fp_word tt; +#endif a = A->dp; COMBA_START; diff --git a/ctaocrypt/src/fp_sqr_comba_17.i b/ctaocrypt/src/fp_sqr_comba_17.i index fcd4daa5e..db34b1a78 100644 --- a/ctaocrypt/src/fp_sqr_comba_17.i +++ b/ctaocrypt/src/fp_sqr_comba_17.i @@ -24,6 +24,9 @@ void fp_sqr_comba17(fp_int *A, fp_int *B) { fp_digit *a, b[34], c0, c1, c2, sc0, sc1, sc2; +#ifdef TFM_ISO + fp_word tt; +#endif a = A->dp; COMBA_START; diff --git a/ctaocrypt/src/fp_sqr_comba_3.i b/ctaocrypt/src/fp_sqr_comba_3.i index 6cf7faf1a..fea21d183 100644 --- a/ctaocrypt/src/fp_sqr_comba_3.i +++ b/ctaocrypt/src/fp_sqr_comba_3.i @@ -24,6 +24,9 @@ void fp_sqr_comba3(fp_int *A, fp_int *B) { fp_digit *a, b[6], c0, c1, c2; +#ifdef TFM_ISO + fp_word tt; +#endif a = A->dp; COMBA_START; diff --git a/ctaocrypt/src/fp_sqr_comba_4.i b/ctaocrypt/src/fp_sqr_comba_4.i index 71c3c87af..7b7eefa6f 100644 --- a/ctaocrypt/src/fp_sqr_comba_4.i +++ b/ctaocrypt/src/fp_sqr_comba_4.i @@ -24,6 +24,9 @@ void fp_sqr_comba4(fp_int *A, fp_int *B) { fp_digit *a, b[8], c0, c1, c2; +#ifdef TFM_ISO + fp_word tt; +#endif a = A->dp; COMBA_START; diff --git a/ctaocrypt/src/fp_sqr_comba_6.i b/ctaocrypt/src/fp_sqr_comba_6.i index 189f339a4..dc7028138 100644 --- a/ctaocrypt/src/fp_sqr_comba_6.i +++ b/ctaocrypt/src/fp_sqr_comba_6.i @@ -24,6 +24,9 @@ void fp_sqr_comba6(fp_int *A, fp_int *B) { fp_digit *a, b[12], c0, c1, c2, sc0, sc1, sc2; +#ifdef TFM_ISO + fp_word tt; +#endif a = A->dp; COMBA_START; diff --git a/ctaocrypt/src/fp_sqr_comba_7.i b/ctaocrypt/src/fp_sqr_comba_7.i index 1a0cd2c19..7ba664e2f 100644 --- a/ctaocrypt/src/fp_sqr_comba_7.i +++ b/ctaocrypt/src/fp_sqr_comba_7.i @@ -24,6 +24,9 @@ void fp_sqr_comba7(fp_int *A, fp_int *B) { fp_digit *a, b[14], c0, c1, c2, sc0, sc1, sc2; +#ifdef TFM_ISO + fp_word tt; +#endif a = A->dp; COMBA_START; diff --git a/ctaocrypt/src/fp_sqr_comba_8.i b/ctaocrypt/src/fp_sqr_comba_8.i index b71feae3b..24efa52cb 100644 --- a/ctaocrypt/src/fp_sqr_comba_8.i +++ b/ctaocrypt/src/fp_sqr_comba_8.i @@ -24,6 +24,9 @@ void fp_sqr_comba8(fp_int *A, fp_int *B) { fp_digit *a, b[16], c0, c1, c2, sc0, sc1, sc2; +#ifdef TFM_ISO + fp_word tt; +#endif a = A->dp; COMBA_START; diff --git a/ctaocrypt/src/fp_sqr_comba_9.i b/ctaocrypt/src/fp_sqr_comba_9.i index 1db06de22..e9cc21665 100644 --- a/ctaocrypt/src/fp_sqr_comba_9.i +++ b/ctaocrypt/src/fp_sqr_comba_9.i @@ -24,6 +24,9 @@ void fp_sqr_comba9(fp_int *A, fp_int *B) { fp_digit *a, b[18], c0, c1, c2, sc0, sc1, sc2; +#ifdef TFM_ISO + fp_word tt; +#endif a = A->dp; COMBA_START; diff --git a/ctaocrypt/src/integer.c b/ctaocrypt/src/integer.c index d3cb044b8..88e16d57c 100644 --- a/ctaocrypt/src/integer.c +++ b/ctaocrypt/src/integer.c @@ -3765,7 +3765,7 @@ int mp_sqrmod (mp_int * a, mp_int * b, mp_int * c) #endif -#if defined(HAVE_ECC) || !defined(NO_PWDBASED) || defined(CYASSL_SNIFFER) +#if defined(HAVE_ECC) || !defined(NO_PWDBASED) || defined(CYASSL_SNIFFER) || defined(CYASSL_HAVE_WOLFSCEP) /* single digit addition */ int mp_add_d (mp_int* a, mp_digit b, mp_int* c) diff --git a/ctaocrypt/src/md5.c b/ctaocrypt/src/md5.c index 176bf44cd..7d2fe1429 100644 --- a/ctaocrypt/src/md5.c +++ b/ctaocrypt/src/md5.c @@ -36,6 +36,13 @@ #include #endif +#ifdef FREESCALE_MMCAU + #include "cau_api.h" + #define XTRANSFORM(S,B) cau_md5_hash_n((B), 1, (unsigned char*)(S)->digest) +#else + #define XTRANSFORM(S,B) Transform((S)) +#endif + #ifdef STM32F2_HASH /* @@ -174,6 +181,7 @@ void InitMd5(Md5* md5) md5->hiLen = 0; } +#ifndef FREESCALE_MMCAU static void Transform(Md5* md5) { @@ -266,6 +274,8 @@ static void Transform(Md5* md5) md5->digest[3] += d; } +#endif /* FREESCALE_MMCAU */ + static INLINE void AddLength(Md5* md5, word32 len) { @@ -289,10 +299,10 @@ void Md5Update(Md5* md5, const byte* data, word32 len) len -= add; if (md5->buffLen == MD5_BLOCK_SIZE) { - #ifdef BIG_ENDIAN_ORDER + #if defined(BIG_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU) ByteReverseBytes(local, local, MD5_BLOCK_SIZE); #endif - Transform(md5); + XTRANSFORM(md5, local); AddLength(md5, MD5_BLOCK_SIZE); md5->buffLen = 0; } @@ -304,7 +314,7 @@ void Md5Final(Md5* md5, byte* hash) { byte* local = (byte*)md5->buffer; - AddLength(md5, md5->buffLen); /* before adding pads */ + AddLength(md5, md5->buffLen); /* before adding pads */ local[md5->buffLen++] = 0x80; /* add 1 */ @@ -313,10 +323,10 @@ void Md5Final(Md5* md5, byte* hash) XMEMSET(&local[md5->buffLen], 0, MD5_BLOCK_SIZE - md5->buffLen); md5->buffLen += MD5_BLOCK_SIZE - md5->buffLen; - #ifdef BIG_ENDIAN_ORDER + #if defined(BIG_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU) ByteReverseBytes(local, local, MD5_BLOCK_SIZE); #endif - Transform(md5); + XTRANSFORM(md5, local); md5->buffLen = 0; } XMEMSET(&local[md5->buffLen], 0, MD5_PAD_SIZE - md5->buffLen); @@ -327,14 +337,14 @@ void Md5Final(Md5* md5, byte* hash) md5->loLen = md5->loLen << 3; /* store lengths */ - #ifdef BIG_ENDIAN_ORDER + #if defined(BIG_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU) ByteReverseBytes(local, local, MD5_BLOCK_SIZE); #endif /* ! length ordering dependent on digest endian type ! */ XMEMCPY(&local[MD5_PAD_SIZE], &md5->loLen, sizeof(word32)); XMEMCPY(&local[MD5_PAD_SIZE + sizeof(word32)], &md5->hiLen, sizeof(word32)); - Transform(md5); + XTRANSFORM(md5, local); #ifdef BIG_ENDIAN_ORDER ByteReverseWords(md5->digest, md5->digest, MD5_DIGEST_SIZE); #endif diff --git a/ctaocrypt/src/pkcs7.c b/ctaocrypt/src/pkcs7.c new file mode 100644 index 000000000..d1f79eefb --- /dev/null +++ b/ctaocrypt/src/pkcs7.c @@ -0,0 +1,1348 @@ +/* pkcs7.c + * + * Copyright (C) 2006-2013 wolfSSL Inc. + * + * This file is part of CyaSSL. + * + * CyaSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * CyaSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#ifdef HAVE_CONFIG_H + #include +#endif + +#include + +#ifdef HAVE_PKCS7 + +#include +#include +#include + +#ifndef min + static INLINE word32 min(word32 a, word32 b) + { + return a > b ? b : a; + } +#endif + + +/* placed ASN.1 contentType OID into *output, return idx on success, + * 0 upon failure */ +CYASSL_LOCAL int SetContentType(int pkcs7TypeOID, byte* output) +{ + /* PKCS#7 content types, RFC 2315, section 14 */ + static const byte pkcs7[] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, + 0x0D, 0x01, 0x07 }; + static const byte data[] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, + 0x0D, 0x01, 0x07, 0x01 }; + static const byte signedData[] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, + 0x0D, 0x01, 0x07, 0x02}; + static const byte envelopedData[] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, + 0x0D, 0x01, 0x07, 0x03 }; + static const byte signedAndEnveloped[] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, + 0x0D, 0x01, 0x07, 0x04 }; + static const byte digestedData[] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, + 0x0D, 0x01, 0x07, 0x05 }; + static const byte encryptedData[] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, + 0x0D, 0x01, 0x07, 0x06 }; + + int idSz; + int typeSz = 0, idx = 0; + const byte* typeName = 0; + byte ID_Length[MAX_LENGTH_SZ]; + + switch (pkcs7TypeOID) { + case PKCS7_MSG: + typeSz = sizeof(pkcs7); + typeName = pkcs7; + break; + + case DATA: + typeSz = sizeof(data); + typeName = data; + break; + + case SIGNED_DATA: + typeSz = sizeof(signedData); + typeName = signedData; + break; + + case ENVELOPED_DATA: + typeSz = sizeof(envelopedData); + typeName = envelopedData; + break; + + case SIGNED_AND_ENVELOPED_DATA: + typeSz = sizeof(signedAndEnveloped); + typeName = signedAndEnveloped; + break; + + case DIGESTED_DATA: + typeSz = sizeof(digestedData); + typeName = digestedData; + break; + + case ENCRYPTED_DATA: + typeSz = sizeof(encryptedData); + typeName = encryptedData; + break; + + default: + CYASSL_MSG("Unknown PKCS#7 Type"); + return 0; + }; + + idSz = SetLength(typeSz, ID_Length); + output[idx++] = ASN_OBJECT_ID; + XMEMCPY(output + idx, ID_Length, idSz); + idx += idSz; + XMEMCPY(output + idx, typeName, typeSz); + idx += typeSz; + + return idx; + +} + + +/* get ASN.1 contentType OID sum, return 0 on success, <0 on failure */ +int GetContentType(const byte* input, word32* inOutIdx, word32* oid, + word32 maxIdx) +{ + int length; + word32 i = *inOutIdx; + byte b; + *oid = 0; + + CYASSL_ENTER("GetContentType"); + + b = input[i++]; + if (b != ASN_OBJECT_ID) + return ASN_OBJECT_ID_E; + + if (GetLength(input, &i, &length, maxIdx) < 0) + return ASN_PARSE_E; + + while(length--) { + *oid += input[i]; + i++; + } + + *inOutIdx = i; + + return 0; +} + + +/* init PKCS7 struct with recipient cert, decode into DecodedCert */ +int PKCS7_InitWithCert(PKCS7* pkcs7, byte* cert, word32 certSz) +{ + int ret = 0; + + XMEMSET(pkcs7, 0, sizeof(PKCS7)); + if (cert != NULL && certSz > 0) { + DecodedCert dCert; + + pkcs7->singleCert = cert; + pkcs7->singleCertSz = certSz; + InitDecodedCert(&dCert, cert, certSz, 0); + + ret = ParseCert(&dCert, CA_TYPE, NO_VERIFY, 0); + if (ret < 0) { + FreeDecodedCert(&dCert); + return ret; + } + XMEMCPY(pkcs7->publicKey, dCert.publicKey, dCert.pubKeySize); + pkcs7->publicKeySz = dCert.pubKeySize; + XMEMCPY(pkcs7->issuerHash, dCert.issuerHash, SHA_SIZE); + pkcs7->issuer = dCert.issuerRaw; + pkcs7->issuerSz = dCert.issuerRawLen; + XMEMCPY(pkcs7->issuerSn, dCert.serial, dCert.serialSz); + pkcs7->issuerSnSz = dCert.serialSz; + FreeDecodedCert(&dCert); + } + + return ret; +} + + +/* releases any memory allocated by a PKCS7 initializer */ +void PKCS7_Free(PKCS7* pkcs7) +{ + (void)pkcs7; +} + + +/* build PKCS#7 data content type */ +int PKCS7_EncodeData(PKCS7* pkcs7, byte* output, word32 outputSz) +{ + static const byte oid[] = + { ASN_OBJECT_ID, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, + 0x07, 0x01 }; + byte seq[MAX_SEQ_SZ]; + byte octetStr[MAX_OCTET_STR_SZ]; + word32 seqSz; + word32 octetStrSz; + word32 oidSz = (word32)sizeof(oid); + int idx = 0; + + octetStrSz = SetOctetString(pkcs7->contentSz, octetStr); + seqSz = SetSequence(pkcs7->contentSz + octetStrSz + oidSz, seq); + + if (outputSz < pkcs7->contentSz + octetStrSz + oidSz + seqSz) + return BUFFER_E; + + XMEMCPY(output, seq, seqSz); + idx += seqSz; + XMEMCPY(output + idx, oid, oidSz); + idx += oidSz; + XMEMCPY(output + idx, octetStr, octetStrSz); + idx += octetStrSz; + XMEMCPY(output + idx, pkcs7->content, pkcs7->contentSz); + idx += pkcs7->contentSz; + + return idx; +} + + +typedef struct EncodedAttrib { + byte valueSeq[MAX_SEQ_SZ]; + const byte* oid; + byte valueSet[MAX_SET_SZ]; + const byte* value; + word32 valueSeqSz, oidSz, idSz, valueSetSz, valueSz, totalSz; +} EncodedAttrib; + + +typedef struct ESD { + Sha sha; + byte contentDigest[SHA_DIGEST_SIZE + 2]; /* content only + ASN.1 heading */ + byte contentAttribsDigest[SHA_DIGEST_SIZE]; + byte encContentDigest[512]; + + byte outerSeq[MAX_SEQ_SZ]; + byte outerContent[MAX_EXP_SZ]; + byte innerSeq[MAX_SEQ_SZ]; + byte version[MAX_VERSION_SZ]; + byte digAlgoIdSet[MAX_SET_SZ]; + byte singleDigAlgoId[MAX_ALGO_SZ]; + + byte contentInfoSeq[MAX_SEQ_SZ]; + byte innerContSeq[MAX_EXP_SZ]; + byte innerOctets[MAX_OCTET_STR_SZ]; + + byte certsSet[MAX_SET_SZ]; + + byte signerInfoSet[MAX_SET_SZ]; + byte signerInfoSeq[MAX_SEQ_SZ]; + byte signerVersion[MAX_VERSION_SZ]; + byte issuerSnSeq[MAX_SEQ_SZ]; + byte issuerName[MAX_SEQ_SZ]; + byte issuerSn[MAX_SN_SZ]; + byte signerDigAlgoId[MAX_ALGO_SZ]; + byte digEncAlgoId[MAX_ALGO_SZ]; + byte signedAttribSet[MAX_SET_SZ]; + EncodedAttrib signedAttribs[6]; + byte signerDigest[MAX_OCTET_STR_SZ]; + word32 innerOctetsSz, innerContSeqSz, contentInfoSeqSz; + word32 outerSeqSz, outerContentSz, innerSeqSz, versionSz, digAlgoIdSetSz, + singleDigAlgoIdSz, certsSetSz; + word32 signerInfoSetSz, signerInfoSeqSz, signerVersionSz, + issuerSnSeqSz, issuerNameSz, issuerSnSz, + signerDigAlgoIdSz, digEncAlgoIdSz, signerDigestSz; + word32 encContentDigestSz, signedAttribsSz, signedAttribsCount, + signedAttribSetSz; +} ESD; + + +static int EncodeAttributes(EncodedAttrib* ea, int eaSz, + PKCS7Attrib* attribs, int attribsSz) +{ + int i; + int maxSz = min(eaSz, attribsSz); + int allAttribsSz = 0; + + for (i = 0; i < maxSz; i++) + { + int attribSz = 0; + + ea[i].value = attribs[i].value; + ea[i].valueSz = attribs[i].valueSz; + attribSz += ea[i].valueSz; + ea[i].valueSetSz = SetSet(attribSz, ea[i].valueSet); + attribSz += ea[i].valueSetSz; + ea[i].oid = attribs[i].oid; + ea[i].oidSz = attribs[i].oidSz; + attribSz += ea[i].oidSz; + ea[i].valueSeqSz = SetSequence(attribSz, ea[i].valueSeq); + attribSz += ea[i].valueSeqSz; + ea[i].totalSz = attribSz; + + allAttribsSz += attribSz; + } + return allAttribsSz; +} + + +static int FlattenAttributes(byte* output, EncodedAttrib* ea, int eaSz) +{ + int i, idx; + + idx = 0; + for (i = 0; i < eaSz; i++) { + XMEMCPY(output + idx, ea[i].valueSeq, ea[i].valueSeqSz); + idx += ea[i].valueSeqSz; + XMEMCPY(output + idx, ea[i].oid, ea[i].oidSz); + idx += ea[i].oidSz; + XMEMCPY(output + idx, ea[i].valueSet, ea[i].valueSetSz); + idx += ea[i].valueSetSz; + XMEMCPY(output + idx, ea[i].value, ea[i].valueSz); + idx += ea[i].valueSz; + } + return 0; +} + + +/* build PKCS#7 signedData content type */ +int PKCS7_EncodeSignedData(PKCS7* pkcs7, byte* output, word32 outputSz) +{ + static const byte outerOid[] = + { ASN_OBJECT_ID, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, + 0x07, 0x02 }; + static const byte innerOid[] = + { ASN_OBJECT_ID, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, + 0x07, 0x01 }; + + ESD esd; + word32 signerInfoSz = 0; + word32 totalSz = 0; + int idx = 0; + byte* flatSignedAttribs = NULL; + word32 flatSignedAttribsSz = 0; + word32 innerOidSz = sizeof(innerOid); + word32 outerOidSz = sizeof(outerOid); + + if (pkcs7 == NULL || pkcs7->content == NULL || pkcs7->contentSz == 0 || + pkcs7->encryptOID == 0 || pkcs7->hashOID == 0 || pkcs7->rng == 0 || + pkcs7->singleCert == NULL || pkcs7->singleCertSz == 0 || + pkcs7->privateKey == NULL || pkcs7->privateKeySz == 0 || + output == NULL || outputSz == 0) + return BAD_FUNC_ARG; + + XMEMSET(&esd, 0, sizeof(esd)); + InitSha(&esd.sha); + + if (pkcs7->contentSz != 0) + { + ShaUpdate(&esd.sha, pkcs7->content, pkcs7->contentSz); + esd.contentDigest[0] = ASN_OCTET_STRING; + esd.contentDigest[1] = SHA_DIGEST_SIZE; + ShaFinal(&esd.sha, &esd.contentDigest[2]); + } + + esd.innerOctetsSz = SetOctetString(pkcs7->contentSz, esd.innerOctets); + esd.innerContSeqSz = SetExplicit(0, esd.innerOctetsSz + pkcs7->contentSz, + esd.innerContSeq); + esd.contentInfoSeqSz = SetSequence(pkcs7->contentSz + esd.innerOctetsSz + + innerOidSz + esd.innerContSeqSz, + esd.contentInfoSeq); + + esd.issuerSnSz = SetSerialNumber(pkcs7->issuerSn, pkcs7->issuerSnSz, + esd.issuerSn); + signerInfoSz += esd.issuerSnSz; + esd.issuerNameSz = SetSequence(pkcs7->issuerSz, esd.issuerName); + signerInfoSz += esd.issuerNameSz + pkcs7->issuerSz; + esd.issuerSnSeqSz = SetSequence(signerInfoSz, esd.issuerSnSeq); + signerInfoSz += esd.issuerSnSeqSz; + esd.signerVersionSz = SetMyVersion(1, esd.signerVersion, 0); + signerInfoSz += esd.signerVersionSz; + esd.signerDigAlgoIdSz = SetAlgoID(pkcs7->hashOID, esd.signerDigAlgoId, + hashType, 0); + signerInfoSz += esd.signerDigAlgoIdSz; + esd.digEncAlgoIdSz = SetAlgoID(pkcs7->encryptOID, esd.digEncAlgoId, + keyType, 0); + signerInfoSz += esd.digEncAlgoIdSz; + + if (pkcs7->signedAttribsSz != 0) { + byte contentTypeOid[] = + { ASN_OBJECT_ID, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xF7, 0x0d, 0x01, + 0x09, 0x03 }; + byte contentType[] = + { ASN_OBJECT_ID, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, + 0x07, 0x01 }; + byte messageDigestOid[] = + { ASN_OBJECT_ID, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, + 0x09, 0x04 }; + + PKCS7Attrib cannedAttribs[2] = + { + { contentTypeOid, sizeof(contentTypeOid), + contentType, sizeof(contentType) }, + { messageDigestOid, sizeof(messageDigestOid), + esd.contentDigest, sizeof(esd.contentDigest) } + }; + word32 cannedAttribsCount = sizeof(cannedAttribs)/sizeof(PKCS7Attrib); + + esd.signedAttribsCount += cannedAttribsCount; + esd.signedAttribsSz += EncodeAttributes(&esd.signedAttribs[0], 2, + cannedAttribs, cannedAttribsCount); + + esd.signedAttribsCount += pkcs7->signedAttribsSz; + esd.signedAttribsSz += EncodeAttributes(&esd.signedAttribs[2], 4, + pkcs7->signedAttribs, pkcs7->signedAttribsSz); + + flatSignedAttribs = (byte*)XMALLOC(esd.signedAttribsSz, 0, NULL); + flatSignedAttribsSz = esd.signedAttribsSz; + if (flatSignedAttribs == NULL) + return MEMORY_E; + FlattenAttributes(flatSignedAttribs, + esd.signedAttribs, esd.signedAttribsCount); + esd.signedAttribSetSz = SetImplicit(ASN_SET, 0, esd.signedAttribsSz, + esd.signedAttribSet); + } + /* Calculate the final hash and encrypt it. */ + { + RsaKey privKey; + int result; + word32 scratch = 0; + + byte digestInfo[MAX_SEQ_SZ + MAX_ALGO_SZ + + MAX_OCTET_STR_SZ + SHA_DIGEST_SIZE]; + byte digestInfoSeq[MAX_SEQ_SZ]; + byte digestStr[MAX_OCTET_STR_SZ]; + word32 digestInfoSeqSz, digestStrSz; + int digIdx = 0; + + if (pkcs7->signedAttribsSz != 0) { + byte attribSet[MAX_SET_SZ]; + word32 attribSetSz; + + attribSetSz = SetSet(flatSignedAttribsSz, attribSet); + + InitSha(&esd.sha); + ShaUpdate(&esd.sha, attribSet, attribSetSz); + ShaUpdate(&esd.sha, flatSignedAttribs, flatSignedAttribsSz); + } + ShaFinal(&esd.sha, esd.contentAttribsDigest); + + digestStrSz = SetOctetString(SHA_DIGEST_SIZE, digestStr); + digestInfoSeqSz = SetSequence(esd.signerDigAlgoIdSz + + digestStrSz + SHA_DIGEST_SIZE, + digestInfoSeq); + + XMEMCPY(digestInfo + digIdx, digestInfoSeq, digestInfoSeqSz); + digIdx += digestInfoSeqSz; + XMEMCPY(digestInfo + digIdx, + esd.signerDigAlgoId, esd.signerDigAlgoIdSz); + digIdx += esd.signerDigAlgoIdSz; + XMEMCPY(digestInfo + digIdx, digestStr, digestStrSz); + digIdx += digestStrSz; + XMEMCPY(digestInfo + digIdx, esd.contentAttribsDigest, SHA_DIGEST_SIZE); + digIdx += SHA_DIGEST_SIZE; + + InitRsaKey(&privKey, NULL); + result = RsaPrivateKeyDecode(pkcs7->privateKey, &scratch, &privKey, + pkcs7->privateKeySz); + if (result < 0) { + XFREE(flatSignedAttribs, 0, NULL); + return PUBLIC_KEY_E; + } + result = RsaSSL_Sign(digestInfo, digIdx, + esd.encContentDigest, sizeof(esd.encContentDigest), + &privKey, pkcs7->rng); + FreeRsaKey(&privKey); + if (result < 0) { + XFREE(flatSignedAttribs, 0, NULL); + return result; + } + esd.encContentDigestSz = (word32)result; + } + signerInfoSz += flatSignedAttribsSz + esd.signedAttribSetSz; + + esd.signerDigestSz = SetOctetString(esd.encContentDigestSz, + esd.signerDigest); + signerInfoSz += esd.signerDigestSz + esd.encContentDigestSz; + + esd.signerInfoSeqSz = SetSequence(signerInfoSz, esd.signerInfoSeq); + signerInfoSz += esd.signerInfoSeqSz; + esd.signerInfoSetSz = SetSet(signerInfoSz, esd.signerInfoSet); + signerInfoSz += esd.signerInfoSetSz; + + esd.certsSetSz = SetImplicit(ASN_SET, 0, pkcs7->singleCertSz, esd.certsSet); + + esd.singleDigAlgoIdSz = SetAlgoID(pkcs7->hashOID, esd.singleDigAlgoId, + hashType, 0); + esd.digAlgoIdSetSz = SetSet(esd.singleDigAlgoIdSz, esd.digAlgoIdSet); + + + esd.versionSz = SetMyVersion(1, esd.version, 0); + + totalSz = esd.versionSz + esd.singleDigAlgoIdSz + esd.digAlgoIdSetSz + + esd.contentInfoSeqSz + esd.certsSetSz + pkcs7->singleCertSz + + esd.innerOctetsSz + esd.innerContSeqSz + + innerOidSz + pkcs7->contentSz + + signerInfoSz; + esd.innerSeqSz = SetSequence(totalSz, esd.innerSeq); + totalSz += esd.innerSeqSz; + esd.outerContentSz = SetExplicit(0, totalSz, esd.outerContent); + totalSz += esd.outerContentSz + outerOidSz; + esd.outerSeqSz = SetSequence(totalSz, esd.outerSeq); + totalSz += esd.outerSeqSz; + + if (outputSz < totalSz) + return BUFFER_E; + + idx = 0; + XMEMCPY(output + idx, esd.outerSeq, esd.outerSeqSz); + idx += esd.outerSeqSz; + XMEMCPY(output + idx, outerOid, outerOidSz); + idx += outerOidSz; + XMEMCPY(output + idx, esd.outerContent, esd.outerContentSz); + idx += esd.outerContentSz; + XMEMCPY(output + idx, esd.innerSeq, esd.innerSeqSz); + idx += esd.innerSeqSz; + XMEMCPY(output + idx, esd.version, esd.versionSz); + idx += esd.versionSz; + XMEMCPY(output + idx, esd.digAlgoIdSet, esd.digAlgoIdSetSz); + idx += esd.digAlgoIdSetSz; + XMEMCPY(output + idx, esd.singleDigAlgoId, esd.singleDigAlgoIdSz); + idx += esd.singleDigAlgoIdSz; + XMEMCPY(output + idx, esd.contentInfoSeq, esd.contentInfoSeqSz); + idx += esd.contentInfoSeqSz; + XMEMCPY(output + idx, innerOid, innerOidSz); + idx += innerOidSz; + XMEMCPY(output + idx, esd.innerContSeq, esd.innerContSeqSz); + idx += esd.innerContSeqSz; + XMEMCPY(output + idx, esd.innerOctets, esd.innerOctetsSz); + idx += esd.innerOctetsSz; + XMEMCPY(output + idx, pkcs7->content, pkcs7->contentSz); + idx += pkcs7->contentSz; + XMEMCPY(output + idx, esd.certsSet, esd.certsSetSz); + idx += esd.certsSetSz; + XMEMCPY(output + idx, pkcs7->singleCert, pkcs7->singleCertSz); + idx += pkcs7->singleCertSz; + XMEMCPY(output + idx, esd.signerInfoSet, esd.signerInfoSetSz); + idx += esd.signerInfoSetSz; + XMEMCPY(output + idx, esd.signerInfoSeq, esd.signerInfoSeqSz); + idx += esd.signerInfoSeqSz; + XMEMCPY(output + idx, esd.signerVersion, esd.signerVersionSz); + idx += esd.signerVersionSz; + XMEMCPY(output + idx, esd.issuerSnSeq, esd.issuerSnSeqSz); + idx += esd.issuerSnSeqSz; + XMEMCPY(output + idx, esd.issuerName, esd.issuerNameSz); + idx += esd.issuerNameSz; + XMEMCPY(output + idx, pkcs7->issuer, pkcs7->issuerSz); + idx += pkcs7->issuerSz; + XMEMCPY(output + idx, esd.issuerSn, esd.issuerSnSz); + idx += esd.issuerSnSz; + XMEMCPY(output + idx, esd.signerDigAlgoId, esd.signerDigAlgoIdSz); + idx += esd.signerDigAlgoIdSz; + + /* SignerInfo:Attributes */ + if (pkcs7->signedAttribsSz != 0) { + XMEMCPY(output + idx, esd.signedAttribSet, esd.signedAttribSetSz); + idx += esd.signedAttribSetSz; + XMEMCPY(output + idx, flatSignedAttribs, flatSignedAttribsSz); + idx += flatSignedAttribsSz; + XFREE(flatSignedAttribs, 0, NULL); + } + + XMEMCPY(output + idx, esd.digEncAlgoId, esd.digEncAlgoIdSz); + idx += esd.digEncAlgoIdSz; + XMEMCPY(output + idx, esd.signerDigest, esd.signerDigestSz); + idx += esd.signerDigestSz; + XMEMCPY(output + idx, esd.encContentDigest, esd.encContentDigestSz); + idx += esd.encContentDigestSz; + + return idx; +} + + +/* Finds the certificates in the message and saves it. */ +int PKCS7_VerifySignedData(PKCS7* pkcs7, byte* pkiMsg, word32 pkiMsgSz) +{ + word32 idx, contentType; + int length, version; + byte* content = NULL; + byte* sig = NULL; + byte* cert = NULL; + byte* signedAttr = NULL; + int contentSz = 0, sigSz = 0, certSz = 0, signedAttrSz = 0; + + (void)signedAttr; /* not used yet, just set */ + (void)signedAttrSz; + + if (pkcs7 == NULL || pkiMsg == NULL || pkiMsgSz == 0) + return BAD_FUNC_ARG; + + idx = 0; + + /* Get the contentInfo sequence */ + if (GetSequence(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + /* Get the contentInfo contentType */ + if (GetContentType(pkiMsg, &idx, &contentType, pkiMsgSz) < 0) + return ASN_PARSE_E; + + if (contentType != SIGNED_DATA) { + CYASSL_MSG("PKCS#7 input not of type SignedData"); + return PKCS7_OID_E; + } + + /* get the ContentInfo content */ + if (pkiMsg[idx++] != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0)) + return ASN_PARSE_E; + + if (GetLength(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + /* Get the signedData sequence */ + if (GetSequence(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + /* Get the version */ + if (GetMyVersion(pkiMsg, &idx, &version) < 0) + return ASN_PARSE_E; + + if (version != 1) { + CYASSL_MSG("PKCS#7 signedData needs to be of version 1"); + return ASN_VERSION_E; + } + + /* Get the set of DigestAlgorithmIdentifiers */ + if (GetSet(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + /* Skip the set. */ + idx += length; + + /* Get the inner ContentInfo sequence */ + if (GetSequence(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + /* Get the inner ContentInfo contentType */ + if (GetContentType(pkiMsg, &idx, &contentType, pkiMsgSz) < 0) + return ASN_PARSE_E; + + if (contentType != DATA) { + CYASSL_MSG("PKCS#7 inner input not of type Data"); + return PKCS7_OID_E; + } + + if (pkiMsg[idx++] != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0)) + return ASN_PARSE_E; + + if (GetLength(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + if (pkiMsg[idx++] != ASN_OCTET_STRING) + return ASN_PARSE_E; + + if (GetLength(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + /* Save the inner data as the content. */ + if (length > 0) { + /* Local pointer for calculating hashes later */ + pkcs7->content = content = &pkiMsg[idx]; + pkcs7->contentSz = contentSz = length; + idx += length; + } + + /* Get the implicit[0] set of certificates */ + if (pkiMsg[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0)) { + idx++; + if (GetLength(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + if (length > 0) { + /* At this point, idx is at the first certificate in + * a set of certificates. There may be more than one, + * or none, or they may be a PKCS 6 extended + * certificate. We want to save the first cert if it + * is X.509. */ + + word32 certIdx = idx; + + if (pkiMsg[certIdx++] == (ASN_CONSTRUCTED | ASN_SEQUENCE)) { + if (GetLength(pkiMsg, &certIdx, &certSz, pkiMsgSz) < 0) + return ASN_PARSE_E; + + cert = &pkiMsg[idx]; + certSz += (certIdx - idx); + } + PKCS7_InitWithCert(pkcs7, cert, certSz); + } + idx += length; + } + + /* Get the implicit[1] set of crls */ + if (pkiMsg[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1)) { + idx++; + if (GetLength(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + /* Skip the set */ + idx += length; + } + + /* Get the set of signerInfos */ + if (GetSet(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + if (length > 0) { + RsaKey key; + word32 scratch = 0; + int plainSz = 0; + byte digest[MAX_SEQ_SZ+MAX_ALGO_SZ+MAX_OCTET_STR_SZ+SHA_DIGEST_SIZE]; + + /* Get the sequence of the first signerInfo */ + if (GetSequence(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + /* Get the version */ + if (GetMyVersion(pkiMsg, &idx, &version) < 0) + return ASN_PARSE_E; + + if (version != 1) { + CYASSL_MSG("PKCS#7 signerInfo needs to be of version 1"); + return ASN_VERSION_E; + } + + /* Get the sequence of IssuerAndSerialNumber */ + if (GetSequence(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + /* Skip it */ + idx += length; + + /* Get the sequence of digestAlgorithm */ + if (GetSequence(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + /* Skip it */ + idx += length; + + /* Get the IMPLICIT[0] SET OF signedAttributes */ + if (pkiMsg[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0)) { + idx++; + + if (GetLength(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + /* save pointer and length */ + signedAttr = &pkiMsg[idx]; + signedAttrSz = length; + + idx += length; + } + + /* Get the sequence of digestEncryptionAlgorithm */ + if (GetSequence(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + /* Skip it */ + idx += length; + + /* Get the signature */ + if (pkiMsg[idx] == ASN_OCTET_STRING) { + idx++; + + if (GetLength(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + /* save pointer and length */ + sig = &pkiMsg[idx]; + sigSz = length; + + idx += length; + } + + XMEMSET(digest, 0, sizeof(digest)); + pkcs7->content = content; + pkcs7->contentSz = contentSz; + + InitRsaKey(&key, NULL); + if (RsaPublicKeyDecode(pkcs7->publicKey, &scratch, &key, + pkcs7->publicKeySz) < 0) { + CYASSL_MSG("ASN RSA key decode error"); + return PUBLIC_KEY_E; + } + plainSz = RsaSSL_Verify(sig, sigSz, digest, sizeof(digest), &key); + FreeRsaKey(&key); + if (plainSz < 0) + return plainSz; + } + + return 0; +} + + +/* create ASN.1 fomatted RecipientInfo structure, returns sequence size */ +CYASSL_LOCAL int CreateRecipientInfo(const byte* cert, word32 certSz, + int keyEncAlgo, int blockKeySz, + RNG* rng, byte* contentKeyPlain, + byte* contentKeyEnc, + int* keyEncSz, byte* out, word32 outSz) +{ + word32 idx = 0; + int ret = 0, totalSz = 0; + int verSz, issuerSz, snSz, keyEncAlgSz; + int issuerSeqSz, recipSeqSz, issuerSerialSeqSz; + int encKeyOctetStrSz; + + byte ver[MAX_VERSION_SZ]; + byte serial[MAX_SN_SZ]; + byte issuerSerialSeq[MAX_SEQ_SZ]; + byte recipSeq[MAX_SEQ_SZ]; + byte issuerSeq[MAX_SEQ_SZ]; + byte keyAlgArray[MAX_ALGO_SZ]; + byte encKeyOctetStr[MAX_OCTET_STR_SZ]; + + RsaKey pubKey; + DecodedCert decoded; + + InitDecodedCert(&decoded, (byte*)cert, certSz, 0); + ret = ParseCert(&decoded, CA_TYPE, NO_VERIFY, 0); + if (ret < 0) { + FreeDecodedCert(&decoded); + return ret; + } + + /* version */ + verSz = SetMyVersion(0, ver, 0); + + /* IssuerAndSerialNumber */ + if (decoded.issuerRaw == NULL || decoded.issuerRawLen == 0) { + CYASSL_MSG("DecodedCert lacks raw issuer pointer and length"); + FreeDecodedCert(&decoded); + return -1; + } + issuerSz = decoded.issuerRawLen; + issuerSeqSz = SetSequence(issuerSz, issuerSeq); + + if (decoded.serial == NULL || decoded.serialSz == 0) { + CYASSL_MSG("DecodedCert missing serial number"); + FreeDecodedCert(&decoded); + return -1; + } + snSz = SetSerialNumber(decoded.serial, decoded.serialSz, serial); + + issuerSerialSeqSz = SetSequence(issuerSeqSz + issuerSz + snSz, + issuerSerialSeq); + + /* KeyEncryptionAlgorithmIdentifier, only support RSA now */ + if (keyEncAlgo != RSAk) + return ALGO_ID_E; + + keyEncAlgSz = SetAlgoID(keyEncAlgo, keyAlgArray, keyType, 0); + if (keyEncAlgSz == 0) + return BAD_FUNC_ARG; + + /* EncryptedKey */ + InitRsaKey(&pubKey, 0); + if (RsaPublicKeyDecode(decoded.publicKey, &idx, &pubKey, + decoded.pubKeySize) < 0) { + CYASSL_MSG("ASN RSA key decode error"); + return PUBLIC_KEY_E; + } + + *keyEncSz = RsaPublicEncrypt(contentKeyPlain, blockKeySz, contentKeyEnc, + MAX_ENCRYPTED_KEY_SZ, &pubKey, rng); + FreeRsaKey(&pubKey); + if (*keyEncSz < 0) { + CYASSL_MSG("RSA Public Encrypt failed"); + return *keyEncSz; + } + + encKeyOctetStrSz = SetOctetString(*keyEncSz, encKeyOctetStr); + + /* RecipientInfo */ + recipSeqSz = SetSequence(verSz + issuerSerialSeqSz + issuerSeqSz + + issuerSz + snSz + keyEncAlgSz + encKeyOctetStrSz + + *keyEncSz, recipSeq); + + if (recipSeqSz + verSz + issuerSerialSeqSz + issuerSeqSz + snSz + + keyEncAlgSz + encKeyOctetStrSz + *keyEncSz > (int)outSz) { + CYASSL_MSG("RecipientInfo output buffer too small"); + return BUFFER_E; + } + + XMEMCPY(out + totalSz, recipSeq, recipSeqSz); + totalSz += recipSeqSz; + XMEMCPY(out + totalSz, ver, verSz); + totalSz += verSz; + XMEMCPY(out + totalSz, issuerSerialSeq, issuerSerialSeqSz); + totalSz += issuerSerialSeqSz; + XMEMCPY(out + totalSz, issuerSeq, issuerSeqSz); + totalSz += issuerSeqSz; + XMEMCPY(out + totalSz, decoded.issuerRaw, issuerSz); + totalSz += issuerSz; + XMEMCPY(out + totalSz, serial, snSz); + totalSz += snSz; + XMEMCPY(out + totalSz, keyAlgArray, keyEncAlgSz); + totalSz += keyEncAlgSz; + XMEMCPY(out + totalSz, encKeyOctetStr, encKeyOctetStrSz); + totalSz += encKeyOctetStrSz; + XMEMCPY(out + totalSz, contentKeyEnc, *keyEncSz); + totalSz += *keyEncSz; + + FreeDecodedCert(&decoded); + + return totalSz; +} + + +/* build PKCS#7 envelopedData content type, return enveloped size */ +int PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz) +{ + int i, idx = 0; + int totalSz = 0, padSz = 0, desOutSz = 0; + + int contentInfoSeqSz, outerContentTypeSz, outerContentSz; + byte contentInfoSeq[MAX_SEQ_SZ]; + byte outerContentType[MAX_ALGO_SZ]; + byte outerContent[MAX_SEQ_SZ]; + + int envDataSeqSz, verSz; + byte envDataSeq[MAX_SEQ_SZ]; + byte ver[MAX_VERSION_SZ]; + + RNG rng; + int contentKeyEncSz, blockKeySz; + int dynamicFlag = 0; + byte contentKeyPlain[MAX_CONTENT_KEY_LEN]; + byte contentKeyEnc[MAX_ENCRYPTED_KEY_SZ]; + byte* plain; + byte* encryptedContent; + + int recipSz, recipSetSz; + byte recip[MAX_RECIP_SZ]; + byte recipSet[MAX_SET_SZ]; + + int encContentOctetSz, encContentSeqSz, contentTypeSz; + int contentEncAlgoSz, ivOctetStringSz; + byte encContentSeq[MAX_SEQ_SZ]; + byte contentType[MAX_ALGO_SZ]; + byte contentEncAlgo[MAX_ALGO_SZ]; + byte tmpIv[DES_BLOCK_SIZE]; + byte ivOctetString[MAX_OCTET_STR_SZ]; + byte encContentOctet[MAX_OCTET_STR_SZ]; + + if (pkcs7 == NULL || pkcs7->content == NULL || pkcs7->contentSz == 0 || + pkcs7->encryptOID == 0 || pkcs7->singleCert == NULL) + return BAD_FUNC_ARG; + + if (output == NULL || outputSz == 0) + return BAD_FUNC_ARG; + + /* PKCS#7 only supports DES, 3DES for now */ + switch (pkcs7->encryptOID) { + case DESb: + blockKeySz = DES_KEYLEN; + break; + + case DES3b: + blockKeySz = DES3_KEYLEN; + break; + + default: + CYASSL_MSG("Unsupported content cipher type"); + return ALGO_ID_E; + }; + + /* outer content type */ + outerContentTypeSz = SetContentType(ENVELOPED_DATA, outerContentType); + + /* version, defined as 0 in RFC 2315 */ + verSz = SetMyVersion(0, ver, 0); + + /* generate random content encryption key */ + InitRng(&rng); + RNG_GenerateBlock(&rng, contentKeyPlain, blockKeySz); + + /* build RecipientInfo, only handle 1 for now */ + recipSz = CreateRecipientInfo(pkcs7->singleCert, pkcs7->singleCertSz, RSAk, + blockKeySz, &rng, contentKeyPlain, + contentKeyEnc, &contentKeyEncSz, recip, + MAX_RECIP_SZ); + + if (recipSz < 0) { + CYASSL_MSG("Failed to create RecipientInfo"); + return recipSz; + } + recipSetSz = SetSet(recipSz, recipSet); + + /* EncryptedContentInfo */ + contentTypeSz = SetContentType(pkcs7->contentOID, contentType); + if (contentTypeSz == 0) + return BAD_FUNC_ARG; + + /* allocate encrypted content buffer, pad if necessary, PKCS#7 padding */ + padSz = DES_BLOCK_SIZE - (pkcs7->contentSz % DES_BLOCK_SIZE); + desOutSz = pkcs7->contentSz + padSz; + + if (padSz != 0) { + plain = XMALLOC(desOutSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (plain == NULL) { + return MEMORY_E; + } + XMEMCPY(plain, pkcs7->content, pkcs7->contentSz); + dynamicFlag = 1; + + for (i = 0; i < padSz; i++) { + plain[pkcs7->contentSz + i] = padSz; + } + + } else { + plain = pkcs7->content; + desOutSz = pkcs7->contentSz; + } + + encryptedContent = XMALLOC(desOutSz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (encryptedContent == NULL) { + if (dynamicFlag) + XFREE(plain, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return MEMORY_E; + } + + /* generate IV for block cipher */ + RNG_GenerateBlock(&rng, tmpIv, DES_BLOCK_SIZE); + + /* put together IV OCTET STRING */ + ivOctetStringSz = SetOctetString(DES_BLOCK_SIZE, ivOctetString); + + /* build up our ContentEncryptionAlgorithmIdentifier sequence, + * adding (ivOctetStringSz + DES_BLOCK_SIZE) for IV OCTET STRING */ + contentEncAlgoSz = SetAlgoID(pkcs7->encryptOID, contentEncAlgo, + blkType, ivOctetStringSz + DES_BLOCK_SIZE); + if (contentEncAlgoSz == 0) + return BAD_FUNC_ARG; + + /* encrypt content */ + if (pkcs7->encryptOID == DESb) { + Des des; + Des_SetKey(&des, contentKeyPlain, tmpIv, DES_ENCRYPTION); + Des_CbcEncrypt(&des, encryptedContent, plain, desOutSz); + + } else if (pkcs7->encryptOID == DES3b) { + Des3 des3; + Des3_SetKey(&des3, contentKeyPlain, tmpIv, DES_ENCRYPTION); + Des3_CbcEncrypt(&des3, encryptedContent, plain, desOutSz); + } + + encContentOctetSz = SetImplicit(ASN_OCTET_STRING, 0, + desOutSz, encContentOctet); + + encContentSeqSz = SetSequence(contentTypeSz + contentEncAlgoSz + + ivOctetStringSz + DES_BLOCK_SIZE + + encContentOctetSz + desOutSz, encContentSeq); + + /* keep track of sizes for outer wrapper layering */ + totalSz = verSz + recipSetSz + recipSz + encContentSeqSz + contentTypeSz + + contentEncAlgoSz + ivOctetStringSz + DES_BLOCK_SIZE + + encContentOctetSz + desOutSz; + + /* EnvelopedData */ + envDataSeqSz = SetSequence(totalSz, envDataSeq); + totalSz += envDataSeqSz; + + /* outer content */ + outerContentSz = SetExplicit(0, totalSz, outerContent); + totalSz += outerContentTypeSz; + totalSz += outerContentSz; + + /* ContentInfo */ + contentInfoSeqSz = SetSequence(totalSz, contentInfoSeq); + totalSz += contentInfoSeqSz; + + if (totalSz > (int)outputSz) { + CYASSL_MSG("Pkcs7_encrypt output buffer too small"); + XFREE(encryptedContent, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (dynamicFlag) + XFREE(plain, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return BUFFER_E; + } + + XMEMCPY(output + idx, contentInfoSeq, contentInfoSeqSz); + idx += contentInfoSeqSz; + XMEMCPY(output + idx, outerContentType, outerContentTypeSz); + idx += outerContentTypeSz; + XMEMCPY(output + idx, outerContent, outerContentSz); + idx += outerContentSz; + XMEMCPY(output + idx, envDataSeq, envDataSeqSz); + idx += envDataSeqSz; + XMEMCPY(output + idx, ver, verSz); + idx += verSz; + XMEMCPY(output + idx, recipSet, recipSetSz); + idx += recipSetSz; + XMEMCPY(output + idx, recip, recipSz); + idx += recipSz; + XMEMCPY(output + idx, encContentSeq, encContentSeqSz); + idx += encContentSeqSz; + XMEMCPY(output + idx, contentType, contentTypeSz); + idx += contentTypeSz; + XMEMCPY(output + idx, contentEncAlgo, contentEncAlgoSz); + idx += contentEncAlgoSz; + XMEMCPY(output + idx, ivOctetString, ivOctetStringSz); + idx += ivOctetStringSz; + XMEMCPY(output + idx, tmpIv, DES_BLOCK_SIZE); + idx += DES_BLOCK_SIZE; + XMEMCPY(output + idx, encContentOctet, encContentOctetSz); + idx += encContentOctetSz; + XMEMCPY(output + idx, encryptedContent, desOutSz); + idx += desOutSz; + +#ifdef NO_RC4 + FreeRng(&rng); +#endif + + XMEMSET(contentKeyPlain, 0, MAX_CONTENT_KEY_LEN); + XMEMSET(contentKeyEnc, 0, MAX_ENCRYPTED_KEY_SZ); + + if (dynamicFlag) + XFREE(plain, NULL, DYNAMMIC_TYPE_TMP_BUFFER); + XFREE(encryptedContent, NULL, DYNAMIC_TYPE_TMP_BUFFER); + + return idx; +} + +/* unwrap and decrypt PKCS#7 envelopedData object, return decoded size */ +CYASSL_API int PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* pkiMsg, + word32 pkiMsgSz, byte* output, + word32 outputSz) +{ + int recipFound = 0; + int ret, version, length; + word32 savedIdx = 0, idx = 0; + word32 contentType, encOID; + byte issuerHash[SHA_DIGEST_SIZE]; + mp_int serialNum; + + int encryptedKeySz, keySz; + byte tmpIv[DES_BLOCK_SIZE]; + byte encryptedKey[MAX_ENCRYPTED_KEY_SZ]; + byte* decryptedKey = NULL; + + RsaKey privKey; + int encryptedContentSz; + byte padLen; + byte* encryptedContent = NULL; + + if (pkcs7 == NULL || pkcs7->singleCert == NULL || + pkcs7->singleCertSz == 0 || pkcs7->privateKey == NULL || + pkcs7->privateKeySz == 0) + return BAD_FUNC_ARG; + + if (pkiMsg == NULL || pkiMsgSz == 0 || + output == NULL || outputSz == 0) + return BAD_FUNC_ARG; + + /* load private key */ + InitRsaKey(&privKey, 0); + ret = RsaPrivateKeyDecode(pkcs7->privateKey, &idx, &privKey, + pkcs7->privateKeySz); + if (ret != 0) { + CYASSL_MSG("Failed to decode RSA private key"); + return ret; + } + + idx = 0; + + /* read past ContentInfo, verify type is envelopedData */ + if (GetSequence(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + if (GetContentType(pkiMsg, &idx, &contentType, pkiMsgSz) < 0) + return ASN_PARSE_E; + + if (contentType != ENVELOPED_DATA) { + CYASSL_MSG("PKCS#7 input not of type EnvelopedData"); + return PKCS7_OID_E; + } + + if (pkiMsg[idx++] != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0)) + return ASN_PARSE_E; + + if (GetLength(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + /* remove EnvelopedData and version */ + if (GetSequence(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + if (GetMyVersion(pkiMsg, &idx, &version) < 0) + return ASN_PARSE_E; + + if (version != 0) { + CYASSL_MSG("PKCS#7 envelopedData needs to be of version 0"); + return ASN_VERSION_E; + } + + /* walk through RecipientInfo set, find correct recipient */ + if (GetSet(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + savedIdx = idx; + recipFound = 0; + + /* when looking for next recipient, use first sequence and version to + * indicate there is another, if not, move on */ + while(recipFound == 0) { + + /* remove RecipientInfo, if we don't have a SEQUENCE, back up idx to + * last good saved one */ + if (GetSequence(pkiMsg, &idx, &length, pkiMsgSz) < 0) { + idx = savedIdx; + break; + } + + if (GetMyVersion(pkiMsg, &idx, &version) < 0) { + idx = savedIdx; + break; + } + + if (version != 0) + return ASN_VERSION_E; + + /* remove IssuerAndSerialNumber */ + if (GetSequence(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + if (GetNameHash(pkiMsg, &idx, issuerHash, pkiMsgSz) < 0) + return ASN_PARSE_E; + + /* if we found correct recipient, issuer hashes will match */ + if (XMEMCMP(issuerHash, pkcs7->issuerHash, SHA_DIGEST_SIZE) == 0) { + recipFound = 1; + } + + if (GetInt(&serialNum, pkiMsg, &idx, pkiMsgSz) < 0) + return ASN_PARSE_E; + mp_clear(&serialNum); + + if (GetAlgoId(pkiMsg, &idx, &encOID, pkiMsgSz) < 0) + return ASN_PARSE_E; + + /* key encryption algorithm must be RSA for now */ + if (encOID != RSAk) + return ALGO_ID_E; + + /* read encryptedKey */ + if (pkiMsg[idx++] != ASN_OCTET_STRING) + return ASN_PARSE_E; + + if (GetLength(pkiMsg, &idx, &encryptedKeySz, pkiMsgSz) < 0) + return ASN_PARSE_E; + + if (recipFound == 1) + XMEMCPY(encryptedKey, &pkiMsg[idx], encryptedKeySz); + idx += encryptedKeySz; + + /* update good idx */ + savedIdx = idx; + } + + if (recipFound == 0) { + CYASSL_MSG("No recipient found in envelopedData that matches input"); + return PKCS7_RECIP_E; + } + + /* remove EncryptedContentInfo */ + if (GetSequence(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + if (GetContentType(pkiMsg, &idx, &contentType, pkiMsgSz) < 0) + return ASN_PARSE_E; + + if (GetAlgoId(pkiMsg, &idx, &encOID, pkiMsgSz) < 0) + return ASN_PARSE_E; + + /* get block cipher IV, stored in OPTIONAL parameter of AlgoID */ + if (pkiMsg[idx++] != ASN_OCTET_STRING) + return ASN_PARSE_E; + + if (GetLength(pkiMsg, &idx, &length, pkiMsgSz) < 0) + return ASN_PARSE_E; + + if (length != DES_BLOCK_SIZE) { + CYASSL_MSG("Incorrect IV length, must be of DES_BLOCK_SIZE"); + return ASN_PARSE_E; + } + + XMEMCPY(tmpIv, &pkiMsg[idx], length); + idx += length; + + /* read encryptedContent, cont[0] */ + if (pkiMsg[idx++] != (ASN_CONTEXT_SPECIFIC | 0)) + return ASN_PARSE_E; + + if (GetLength(pkiMsg, &idx, &encryptedContentSz, pkiMsgSz) < 0) + return ASN_PARSE_E; + + encryptedContent = XMALLOC(encryptedContentSz, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + + XMEMCPY(encryptedContent, &pkiMsg[idx], encryptedContentSz); + + /* decrypt encryptedKey */ + keySz = RsaPrivateDecryptInline(encryptedKey, encryptedKeySz, + &decryptedKey, &privKey); + FreeRsaKey(&privKey); + if (keySz <= 0) + return keySz; + + /* decrypt encryptedContent */ + if (encOID == DESb) { + Des des; + Des_SetKey(&des, decryptedKey, tmpIv, DES_DECRYPTION); + Des_CbcDecrypt(&des, encryptedContent, encryptedContent, + encryptedContentSz); + } else if (encOID == DES3b) { + Des3 des; + Des3_SetKey(&des, decryptedKey, tmpIv, DES_DECRYPTION); + Des3_CbcDecrypt(&des, encryptedContent, encryptedContent, + encryptedContentSz); + } else { + CYASSL_MSG("Unsupported content encryption OID type"); + return ALGO_ID_E; + } + + padLen = encryptedContent[encryptedContentSz-1]; + + /* copy plaintext to output */ + XMEMCPY(output, encryptedContent, encryptedContentSz - padLen); + + /* free memory, zero out keys */ + XMEMSET(encryptedKey, 0, MAX_ENCRYPTED_KEY_SZ); + XMEMSET(encryptedContent, 0, encryptedContentSz); + XFREE(encryptedContent, NULL, DYNAMIC_TYPE_TMP_BUFFER); + + return encryptedContentSz - padLen; +} + + +#else /* HAVE_PKCS7 */ + + +#ifdef _MSC_VER + /* 4206 warning for blank file */ + #pragma warning(disable: 4206) +#endif + + +#endif /* HAVE_PKCS7 */ + diff --git a/ctaocrypt/src/sha.c b/ctaocrypt/src/sha.c index 20d2261f5..30b669341 100644 --- a/ctaocrypt/src/sha.c +++ b/ctaocrypt/src/sha.c @@ -35,6 +35,13 @@ #include #endif +#ifdef FREESCALE_MMCAU + #include "cau_api.h" + #define XTRANSFORM(S,B) cau_sha1_hash_n((B), 1, ((S))->digest) +#else + #define XTRANSFORM(S,B) Transform((S)) +#endif + #ifdef STM32F2_HASH /* @@ -164,17 +171,23 @@ void InitSha(Sha* sha) { - sha->digest[0] = 0x67452301L; - sha->digest[1] = 0xEFCDAB89L; - sha->digest[2] = 0x98BADCFEL; - sha->digest[3] = 0x10325476L; - sha->digest[4] = 0xC3D2E1F0L; + #ifdef FREESCALE_MMCAU + cau_sha1_initialize_output(sha->digest); + #else + sha->digest[0] = 0x67452301L; + sha->digest[1] = 0xEFCDAB89L; + sha->digest[2] = 0x98BADCFEL; + sha->digest[3] = 0x10325476L; + sha->digest[4] = 0xC3D2E1F0L; + #endif sha->buffLen = 0; sha->loLen = 0; sha->hiLen = 0; } +#ifndef FREESCALE_MMCAU + #define blk0(i) (W[i] = sha->buffer[i]) #define blk1(i) (W[i&15] = \ rotlFixed(W[(i+13)&15]^W[(i+8)&15]^W[(i+2)&15]^W[i&15],1)) @@ -272,6 +285,8 @@ static void Transform(Sha* sha) sha->digest[4] += e; } +#endif /* FREESCALE_MMCAU */ + static INLINE void AddLength(Sha* sha, word32 len) { @@ -295,10 +310,10 @@ void ShaUpdate(Sha* sha, const byte* data, word32 len) len -= add; if (sha->buffLen == SHA_BLOCK_SIZE) { - #ifdef LITTLE_ENDIAN_ORDER + #if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU) ByteReverseBytes(local, local, SHA_BLOCK_SIZE); #endif - Transform(sha); + XTRANSFORM(sha, local); AddLength(sha, SHA_BLOCK_SIZE); sha->buffLen = 0; } @@ -310,7 +325,7 @@ void ShaFinal(Sha* sha, byte* hash) { byte* local = (byte*)sha->buffer; - AddLength(sha, sha->buffLen); /* before adding pads */ + AddLength(sha, sha->buffLen); /* before adding pads */ local[sha->buffLen++] = 0x80; /* add 1 */ @@ -319,10 +334,10 @@ void ShaFinal(Sha* sha, byte* hash) XMEMSET(&local[sha->buffLen], 0, SHA_BLOCK_SIZE - sha->buffLen); sha->buffLen += SHA_BLOCK_SIZE - sha->buffLen; - #ifdef LITTLE_ENDIAN_ORDER + #if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU) ByteReverseBytes(local, local, SHA_BLOCK_SIZE); #endif - Transform(sha); + XTRANSFORM(sha, local); sha->buffLen = 0; } XMEMSET(&local[sha->buffLen], 0, SHA_PAD_SIZE - sha->buffLen); @@ -333,14 +348,20 @@ void ShaFinal(Sha* sha, byte* hash) sha->loLen = sha->loLen << 3; /* store lengths */ - #ifdef LITTLE_ENDIAN_ORDER + #if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU) ByteReverseBytes(local, local, SHA_BLOCK_SIZE); #endif /* ! length ordering dependent on digest endian type ! */ XMEMCPY(&local[SHA_PAD_SIZE], &sha->hiLen, sizeof(word32)); XMEMCPY(&local[SHA_PAD_SIZE + sizeof(word32)], &sha->loLen, sizeof(word32)); - Transform(sha); + #ifdef FREESCALE_MMCAU + /* Kinetis requires only these bytes reversed */ + ByteReverseBytes(&local[SHA_PAD_SIZE], &local[SHA_PAD_SIZE], + 2 * sizeof(word32)); + #endif + + XTRANSFORM(sha, local); #ifdef LITTLE_ENDIAN_ORDER ByteReverseWords(sha->digest, sha->digest, SHA_DIGEST_SIZE); #endif diff --git a/ctaocrypt/src/sha256.c b/ctaocrypt/src/sha256.c index baa379059..97f64a3ca 100644 --- a/ctaocrypt/src/sha256.c +++ b/ctaocrypt/src/sha256.c @@ -37,6 +37,13 @@ #include #endif +#ifdef FREESCALE_MMCAU + #include "cau_api.h" + #define XTRANSFORM(S,B) cau_sha256_hash_n((B), 1, ((S))->digest) +#else + #define XTRANSFORM(S,B) Transform((S)) +#endif + #ifndef min @@ -50,20 +57,26 @@ void InitSha256(Sha256* sha256) { - sha256->digest[0] = 0x6A09E667L; - sha256->digest[1] = 0xBB67AE85L; - sha256->digest[2] = 0x3C6EF372L; - sha256->digest[3] = 0xA54FF53AL; - sha256->digest[4] = 0x510E527FL; - sha256->digest[5] = 0x9B05688CL; - sha256->digest[6] = 0x1F83D9ABL; - sha256->digest[7] = 0x5BE0CD19L; + #ifdef FREESCALE_MMCAU + cau_sha256_initialize_output(sha256->digest); + #else + sha256->digest[0] = 0x6A09E667L; + sha256->digest[1] = 0xBB67AE85L; + sha256->digest[2] = 0x3C6EF372L; + sha256->digest[3] = 0xA54FF53AL; + sha256->digest[4] = 0x510E527FL; + sha256->digest[5] = 0x9B05688CL; + sha256->digest[6] = 0x1F83D9ABL; + sha256->digest[7] = 0x5BE0CD19L; + #endif sha256->buffLen = 0; sha256->loLen = 0; sha256->hiLen = 0; } +#ifndef FREESCALE_MMCAU + static const word32 K[64] = { 0x428A2F98L, 0x71374491L, 0xB5C0FBCFL, 0xE9B5DBA5L, 0x3956C25BL, 0x59F111F1L, 0x923F82A4L, 0xAB1C5ED5L, 0xD807AA98L, 0x12835B01L, @@ -128,6 +141,8 @@ static void Transform(Sha256* sha256) } } +#endif /* FREESCALE_MMCAU */ + static INLINE void AddLength(Sha256* sha256, word32 len) { @@ -151,10 +166,10 @@ void Sha256Update(Sha256* sha256, const byte* data, word32 len) len -= add; if (sha256->buffLen == SHA256_BLOCK_SIZE) { - #ifdef LITTLE_ENDIAN_ORDER + #if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU) ByteReverseBytes(local, local, SHA256_BLOCK_SIZE); #endif - Transform(sha256); + XTRANSFORM(sha256, local); AddLength(sha256, SHA256_BLOCK_SIZE); sha256->buffLen = 0; } @@ -168,17 +183,17 @@ void Sha256Final(Sha256* sha256, byte* hash) AddLength(sha256, sha256->buffLen); /* before adding pads */ - local[sha256->buffLen++] = 0x80; /* add 1 */ + local[sha256->buffLen++] = 0x80; /* add 1 */ /* pad with zeros */ if (sha256->buffLen > SHA256_PAD_SIZE) { XMEMSET(&local[sha256->buffLen], 0, SHA256_BLOCK_SIZE - sha256->buffLen); sha256->buffLen += SHA256_BLOCK_SIZE - sha256->buffLen; - #ifdef LITTLE_ENDIAN_ORDER + #if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU) ByteReverseBytes(local, local, SHA256_BLOCK_SIZE); #endif - Transform(sha256); + XTRANSFORM(sha256, local); sha256->buffLen = 0; } XMEMSET(&local[sha256->buffLen], 0, SHA256_PAD_SIZE - sha256->buffLen); @@ -189,7 +204,7 @@ void Sha256Final(Sha256* sha256, byte* hash) sha256->loLen = sha256->loLen << 3; /* store lengths */ - #ifdef LITTLE_ENDIAN_ORDER + #if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU) ByteReverseBytes(local, local, SHA256_BLOCK_SIZE); #endif /* ! length ordering dependent on digest endian type ! */ @@ -197,7 +212,13 @@ void Sha256Final(Sha256* sha256, byte* hash) XMEMCPY(&local[SHA256_PAD_SIZE + sizeof(word32)], &sha256->loLen, sizeof(word32)); - Transform(sha256); + #ifdef FREESCALE_MMCAU + /* Kinetis requires only these bytes reversed */ + ByteReverseBytes(&local[SHA256_PAD_SIZE], &local[SHA256_PAD_SIZE], + 2 * sizeof(word32)); + #endif + + XTRANSFORM(sha256, local); #ifdef LITTLE_ENDIAN_ORDER ByteReverseWords(sha256->digest, sha256->digest, SHA256_DIGEST_SIZE); #endif diff --git a/ctaocrypt/src/sha512.c b/ctaocrypt/src/sha512.c index b8d57085f..2766f0a0a 100644 --- a/ctaocrypt/src/sha512.c +++ b/ctaocrypt/src/sha512.c @@ -146,13 +146,24 @@ static void Transform(Sha512* sha512) /* Copy digest to working vars */ XMEMCPY(T, sha512->digest, sizeof(T)); - /* 64 operations, partially loop unrolled */ +#ifdef USE_SLOW_SHA2 + /* over twice as small, but 50% slower */ + /* 80 operations, not unrolled */ + for (j = 0; j < 80; j += 16) { + int m; + for (m = 0; m < 16; m++) { /* braces needed here for macros {} */ + R(m); + } + } +#else + /* 80 operations, partially loop unrolled */ for (j = 0; j < 80; j += 16) { R( 0); R( 1); R( 2); R( 3); R( 4); R( 5); R( 6); R( 7); R( 8); R( 9); R(10); R(11); R(12); R(13); R(14); R(15); } +#endif /* USE_SLOW_SHA2 */ /* Add the working vars back into digest */ @@ -280,13 +291,24 @@ static void Transform384(Sha384* sha384) /* Copy digest to working vars */ XMEMCPY(T, sha384->digest, sizeof(T)); - /* 64 operations, partially loop unrolled */ +#ifdef USE_SLOW_SHA2 + /* over twice as small, but 50% slower */ + /* 80 operations, not unrolled */ + for (j = 0; j < 80; j += 16) { + int m; + for (m = 0; m < 16; m++) { /* braces needed for macros {} */ + R2(m); + } + } +#else + /* 80 operations, partially loop unrolled */ for (j = 0; j < 80; j += 16) { R2( 0); R2( 1); R2( 2); R2( 3); R2( 4); R2( 5); R2( 6); R2( 7); R2( 8); R2( 9); R2(10); R2(11); R2(12); R2(13); R2(14); R2(15); } +#endif /* USE_SLOW_SHA2 */ /* Add the working vars back into digest */ diff --git a/ctaocrypt/test/test.c b/ctaocrypt/test/test.c index 5ba050838..293879c03 100644 --- a/ctaocrypt/test/test.c +++ b/ctaocrypt/test/test.c @@ -61,6 +61,9 @@ #ifdef HAVE_LIBZ #include #endif +#ifdef HAVE_PKCS7 + #include +#endif #ifdef _MSC_VER /* 4996 warning to use MS extensions e.g., strcpy_s instead of strncpy */ @@ -174,6 +177,10 @@ int pbkdf2_test(void); #ifdef HAVE_LIBZ int compress_test(void); #endif +#ifdef HAVE_PKCS7 + int pkcs7enveloped_test(void); + int pkcs7signed_test(void); +#endif @@ -458,6 +465,18 @@ void ctaocrypt_test(void* args) printf( "COMPRESS test passed!\n"); #endif +#ifdef HAVE_PKCS7 + if ( (ret = pkcs7enveloped_test()) != 0) + err_sys("PKCS7enveloped test failed!\n", ret); + else + printf( "PKCS7enveloped test passed!\n"); + + if ( (ret = pkcs7signed_test()) != 0) + err_sys("PKCS7signed test failed!\n", ret); + else + printf( "PKCS7signed test passed!\n"); +#endif + ((func_args*)args)->return_code = ret; } @@ -1897,6 +1916,12 @@ int aes_test(void) 0x79,0x21,0x70,0xa0,0xf3,0x00,0x9c,0xee }; + const byte oddCipher[] = + { + 0xb9,0xd7,0xcb,0x08,0xb0,0xe1,0x7b,0xa0, + 0xc2 + }; + AesSetKeyDirect(&enc, ctrKey, AES_BLOCK_SIZE, ctrIv, AES_ENCRYPTION); /* Ctr only uses encrypt, even on key setup */ AesSetKeyDirect(&dec, ctrKey, AES_BLOCK_SIZE, ctrIv, AES_ENCRYPTION); @@ -1909,6 +1934,30 @@ int aes_test(void) if (memcmp(cipher, ctrCipher, AES_BLOCK_SIZE*4)) return -67; + + /* let's try with just 9 bytes, non block size test */ + AesSetKeyDirect(&enc, ctrKey, AES_BLOCK_SIZE, ctrIv, AES_ENCRYPTION); + /* Ctr only uses encrypt, even on key setup */ + AesSetKeyDirect(&dec, ctrKey, AES_BLOCK_SIZE, ctrIv, AES_ENCRYPTION); + + AesCtrEncrypt(&enc, cipher, ctrPlain, 9); + AesCtrEncrypt(&dec, plain, cipher, 9); + + if (memcmp(plain, ctrPlain, 9)) + return -68; + + if (memcmp(cipher, ctrCipher, 9)) + return -69; + + /* and an additional 9 bytes to reuse tmp left buffer */ + AesCtrEncrypt(&enc, cipher, ctrPlain, 9); + AesCtrEncrypt(&dec, plain, cipher, 9); + + if (memcmp(plain, ctrPlain, 9)) + return -70; + + if (memcmp(cipher, oddCipher, 9)) + return -71; } #endif /* CYASSL_AES_COUNTER */ @@ -2487,17 +2536,27 @@ byte GetEntropy(ENTROPY_CMD cmd, byte* out) #ifdef CYASSL_CERT_GEN static const char* caKeyFile = "a:\\certs\\ca-key.der"; static const char* caCertFile = "a:\\certs\\ca-cert.pem"; + #ifdef HAVE_ECC + static const char* eccCaKeyFile = "a:\\certs\\ecc-key.der"; + static const char* eccCaCertFile = "a:\\certs\\server-ecc.pem"; + #endif #endif #elif defined(CYASSL_MKD_SHELL) static char* clientKey = "certs/client-key.der"; static char* clientCert = "certs/client-cert.der"; - void set_clientKey(char *key) { clientKey = key ; } /* set by shell command */ - void set_clientCert(char *cert) { clientCert = cert ; } /* set by shell command */ + void set_clientKey(char *key) { clientKey = key ; } + void set_clientCert(char *cert) { clientCert = cert ; } #ifdef CYASSL_CERT_GEN static char* caKeyFile = "certs/ca-key.der"; static char* caCertFile = "certs/ca-cert.pem"; - void set_caKeyFile (char * key) { caKeyFile = key ; } /* set by shell command */ - void set_caCertFile(char * cert) { caCertFile = cert ; } /* set by shell command */ + void set_caKeyFile (char * key) { caKeyFile = key ; } + void set_caCertFile(char * cert) { caCertFile = cert ; } + #ifdef HAVE_ECC + static const char* eccCaKeyFile = "certs/ecc-key.der"; + static const char* eccCaCertFile = "certs/server-ecc.pem"; + void set_eccCaKeyFile (char * key) { eccCaKeyFile = key ; } + void set_eccCaCertFile(char * cert) { eccCaCertFile = cert ; } + #endif #endif #else static const char* clientKey = "./certs/client-key.der"; @@ -2505,6 +2564,10 @@ byte GetEntropy(ENTROPY_CMD cmd, byte* out) #ifdef CYASSL_CERT_GEN static const char* caKeyFile = "./certs/ca-key.der"; static const char* caCertFile = "./certs/ca-cert.pem"; + #ifdef HAVE_ECC + static const char* eccCaKeyFile = "./certs/ecc-key.der"; + static const char* eccCaCertFile = "./certs/server-ecc.pem"; + #endif #endif #endif #endif @@ -2784,11 +2847,12 @@ int rsa_test(void) if (ret < 0) return -405; - certSz = MakeCert(&myCert, derCert, FOURK_BUF, &key, &rng); + certSz = MakeCert(&myCert, derCert, FOURK_BUF, &key, NULL, &rng); if (certSz < 0) return -407; - certSz = SignCert(&myCert, derCert, FOURK_BUF, &caKey, &rng); + certSz = SignCert(myCert.bodySz, myCert.sigType, derCert, FOURK_BUF, + &caKey, NULL, &rng); if (certSz < 0) return -408; @@ -2820,6 +2884,95 @@ int rsa_test(void) free(derCert); FreeRsaKey(&caKey); } +#ifdef HAVE_ECC + /* ECC CA style */ + { + ecc_key caKey; + Cert myCert; + byte* derCert; + byte* pem; + FILE* derFile; + FILE* pemFile; + int certSz; + int pemSz; + size_t bytes3; + word32 idx3 = 0; + FILE* file3 ; +#ifdef CYASSL_TEST_CERT + DecodedCert decode; +#endif + + derCert = (byte*)malloc(FOURK_BUF); + if (derCert == NULL) + return -5311; + pem = (byte*)malloc(FOURK_BUF); + if (pem == NULL) + return -5312; + + file3 = fopen(eccCaKeyFile, "rb"); + + if (!file3) + return -5412; + + bytes3 = fread(tmp, 1, FOURK_BUF, file3); + fclose(file3); + + ecc_init(&caKey); + ret = EccPrivateKeyDecode(tmp, &idx3, &caKey, (word32)bytes3); + if (ret != 0) return -5413; + + InitCert(&myCert); + myCert.sigType = CTC_SHA256wECDSA; + + strncpy(myCert.subject.country, "US", CTC_NAME_SIZE); + strncpy(myCert.subject.state, "OR", CTC_NAME_SIZE); + strncpy(myCert.subject.locality, "Portland", CTC_NAME_SIZE); + strncpy(myCert.subject.org, "wolfSSL", CTC_NAME_SIZE); + strncpy(myCert.subject.unit, "Development", CTC_NAME_SIZE); + strncpy(myCert.subject.commonName, "www.wolfssl.com", CTC_NAME_SIZE); + strncpy(myCert.subject.email, "info@wolfssl.com", CTC_NAME_SIZE); + + ret = SetIssuer(&myCert, eccCaCertFile); + if (ret < 0) + return -5405; + + certSz = MakeCert(&myCert, derCert, FOURK_BUF, NULL, &caKey, &rng); + if (certSz < 0) + return -5407; + + certSz = SignCert(myCert.bodySz, myCert.sigType, derCert, FOURK_BUF, + NULL, &caKey, &rng); + if (certSz < 0) + return -5408; + +#ifdef CYASSL_TEST_CERT + InitDecodedCert(&decode, derCert, certSz, 0); + ret = ParseCert(&decode, CERT_TYPE, NO_VERIFY, 0); + if (ret != 0) + return -5409; + FreeDecodedCert(&decode); +#endif + + derFile = fopen("./certecc.der", "wb"); + if (!derFile) + return -5410; + ret = (int)fwrite(derCert, certSz, 1, derFile); + fclose(derFile); + + pemSz = DerToPem(derCert, certSz, pem, FOURK_BUF, CERT_TYPE); + if (pemSz < 0) + return -5411; + + pemFile = fopen("./certecc.pem", "wb"); + if (!pemFile) + return -5412; + ret = (int)fwrite(pem, pemSz, 1, pemFile); + fclose(pemFile); + free(pem); + free(derCert); + ecc_free(&caKey); + } +#endif /* HAVE_ECC */ #ifdef HAVE_NTRU { RsaKey caKey; @@ -2900,7 +3053,8 @@ int rsa_test(void) if (certSz < 0) return -456; - certSz = SignCert(&myCert, derCert, FOURK_BUF, &caKey, &rng); + certSz = SignCert(myCert.bodySz, myCert.sigType, derCert, FOURK_BUF, + &caKey, NULL, &rng); if (certSz < 0) return -457; @@ -2938,6 +3092,66 @@ int rsa_test(void) FreeRsaKey(&caKey); } #endif /* HAVE_NTRU */ +#ifdef CYASSL_CERT_REQ + { + Cert req; + byte* der; + byte* pem; + int derSz; + int pemSz; + FILE* reqFile; + + der = (byte*)malloc(FOURK_BUF); + if (der == NULL) + return -463; + pem = (byte*)malloc(FOURK_BUF); + if (pem == NULL) + return -464; + + InitCert(&req); + + req.version = 0; + req.isCA = 1; + strncpy(req.challengePw, "yassl123", CTC_NAME_SIZE); + strncpy(req.subject.country, "US", CTC_NAME_SIZE); + strncpy(req.subject.state, "OR", CTC_NAME_SIZE); + strncpy(req.subject.locality, "Portland", CTC_NAME_SIZE); + strncpy(req.subject.org, "yaSSL", CTC_NAME_SIZE); + strncpy(req.subject.unit, "Development", CTC_NAME_SIZE); + strncpy(req.subject.commonName, "www.yassl.com", CTC_NAME_SIZE); + strncpy(req.subject.email, "info@yassl.com", CTC_NAME_SIZE); + req.sigType = CTC_SHA256wRSA; + + derSz = MakeCertReq(&req, der, FOURK_BUF, &key, NULL); + if (derSz < 0) + return -465; + + derSz = SignCert(req.bodySz, req.sigType, der, FOURK_BUF, + &key, NULL, &rng); + if (derSz < 0) + return -466; + + pemSz = DerToPem(der, derSz, pem, FOURK_BUF, CERTREQ_TYPE); + if (pemSz < 0) + return -467; + + reqFile = fopen("./certreq.der", "wb"); + if (!reqFile) + return -468; + + ret = (int)fwrite(der, derSz, 1, reqFile); + fclose(reqFile); + + reqFile = fopen("./certreq.pem", "wb"); + if (!reqFile) + return -469; + ret = (int)fwrite(pem, pemSz, 1, reqFile); + fclose(reqFile); + + free(pem); + free(der); + } +#endif /* CYASSL_CERT_REQ */ #endif /* CYASSL_CERT_GEN */ FreeRsaKey(&key); @@ -3628,12 +3842,12 @@ int ecc_encrypt_test(void) for (i = 0; i < 48; i++) msg[i] = i; - /* send encrypted msg to B */ + /* encrypt msg to B */ ret = ecc_encrypt(&userA, &userB, msg, sizeof(msg), out, &outSz, NULL); if (ret != 0) return -3003; - /* decrypted msg to B */ + /* decrypt msg from A */ ret = ecc_decrypt(&userB, &userA, out, outSz, plain, &plainSz, NULL); if (ret != 0) return -3004; @@ -3641,6 +3855,84 @@ int ecc_encrypt_test(void) if (memcmp(plain, msg, sizeof(msg)) != 0) return -3005; + + { /* let's verify message exchange works, A is client, B is server */ + ecEncCtx* cliCtx = ecc_ctx_new(REQ_RESP_CLIENT, &rng); + ecEncCtx* srvCtx = ecc_ctx_new(REQ_RESP_SERVER, &rng); + + byte cliSalt[EXCHANGE_SALT_SZ]; + byte srvSalt[EXCHANGE_SALT_SZ]; + const byte* tmpSalt; + + if (cliCtx == NULL || srvCtx == NULL) + return -3006; + + /* get salt to send to peer */ + tmpSalt = ecc_ctx_get_own_salt(cliCtx); + if (tmpSalt == NULL) + return -3007; + memcpy(cliSalt, tmpSalt, EXCHANGE_SALT_SZ); + + tmpSalt = ecc_ctx_get_own_salt(srvCtx); + if (tmpSalt == NULL) + return -3007; + memcpy(srvSalt, tmpSalt, EXCHANGE_SALT_SZ); + + /* in actual use, we'd get the peer's salt over the transport */ + ret = ecc_ctx_set_peer_salt(cliCtx, srvSalt); + ret += ecc_ctx_set_peer_salt(srvCtx, cliSalt); + + if (ret != 0) + return -3008; + + /* get encrypted msg (request) to send to B */ + outSz = sizeof(out); + ret = ecc_encrypt(&userA, &userB, msg, sizeof(msg), out, &outSz,cliCtx); + if (ret != 0) + return -3009; + + /* B decrypts msg (request) from A */ + plainSz = sizeof(plain); + ret = ecc_decrypt(&userB, &userA, out, outSz, plain, &plainSz, srvCtx); + if (ret != 0) + return -3010; + + if (memcmp(plain, msg, sizeof(msg)) != 0) + return -3011; + + { + /* msg2 (response) from B to A */ + byte msg2[48]; + byte plain2[48]; + byte out2[80]; + word32 outSz2 = sizeof(out2); + word32 plainSz2 = sizeof(plain2); + + for (i = 0; i < 48; i++) + msg2[i] = i+48; + + /* get encrypted msg (response) to send to B */ + ret = ecc_encrypt(&userB, &userA, msg2, sizeof(msg2), out2, + &outSz2, srvCtx); + if (ret != 0) + return -3012; + + /* A decrypts msg (response) from B */ + ret = ecc_decrypt(&userA, &userB, out2, outSz2, plain2, &plainSz2, + cliCtx); + if (ret != 0) + return -3013; + + if (memcmp(plain2, msg2, sizeof(msg2)) != 0) + return -3014; + } + + /* cleanup */ + ecc_ctx_free(srvCtx); + ecc_ctx_free(cliCtx); + } + + /* cleanup */ ecc_free(&userB); ecc_free(&userA); @@ -3766,4 +4058,269 @@ int compress_test(void) #endif /* HAVE_LIBZ */ +#ifdef HAVE_PKCS7 + +int pkcs7enveloped_test(void) +{ + int ret = 0; + + int cipher = DES3b; + int envelopedSz, decodedSz; + PKCS7 pkcs7; + byte* cert; + byte* privKey; + byte enveloped[2048]; + byte decoded[2048]; + + size_t certSz; + size_t privKeySz; + FILE* certFile; + FILE* keyFile; + FILE* pkcs7File; + const char* pkcs7OutFile = "pkcs7envelopedData.der"; + + const byte data[] = { /* Hello World */ + 0x48,0x65,0x6c,0x6c,0x6f,0x20,0x57,0x6f, + 0x72,0x6c,0x64 + }; + + /* read client cert and key in DER format */ + cert = (byte*)malloc(FOURK_BUF); + if (cert == NULL) + return -201; + + privKey = (byte*)malloc(FOURK_BUF); + if (privKey == NULL) + return -202; + + certFile = fopen(clientCert, "rb"); + if (!certFile) + err_sys("can't open ./certs/client-cert.der, " + "Please run from CyaSSL home dir", -42); + + certSz = fread(cert, 1, FOURK_BUF, certFile); + fclose(certFile); + + keyFile = fopen(clientKey, "rb"); + if (!keyFile) + err_sys("can't open ./certs/client-key.der, " + "Please run from CyaSSL home dir", -43); + + privKeySz = fread(privKey, 1, FOURK_BUF, keyFile); + fclose(keyFile); + + PKCS7_InitWithCert(&pkcs7, cert, (word32)certSz); + pkcs7.content = (byte*)data; + pkcs7.contentSz = (word32)sizeof(data); + pkcs7.contentOID = DATA; + pkcs7.encryptOID = cipher; + pkcs7.privateKey = privKey; + pkcs7.privateKeySz = (word32)privKeySz; + + /* encode envelopedData */ + envelopedSz = PKCS7_EncodeEnvelopedData(&pkcs7, enveloped, + sizeof(enveloped)); + if (envelopedSz <= 0) + return -203; + + /* decode envelopedData */ + decodedSz = PKCS7_DecodeEnvelopedData(&pkcs7, enveloped, envelopedSz, + decoded, sizeof(decoded)); + if (decodedSz <= 0) + return -204; + + /* test decode result */ + if (memcmp(decoded, data, sizeof(data)) != 0) { + return -205; + } + + /* output pkcs7 envelopedData for external testing */ + pkcs7File = fopen(pkcs7OutFile, "wb"); + if (!pkcs7File) + return -206; + + ret = (int)fwrite(enveloped, envelopedSz, 1, pkcs7File); + fclose(pkcs7File); + + free(cert); + free(privKey); + PKCS7_Free(&pkcs7); + + if (ret > 0) + return 0; + + return ret; +} + +int pkcs7signed_test(void) +{ + int ret = 0; + + FILE* file; + byte* certDer; + byte* keyDer; + byte* out; + char data[] = "Hello World"; + word32 dataSz, outSz, certDerSz, keyDerSz; + PKCS7 msg; + RNG rng; + + byte transIdOid[] = + { 0x06, 0x0a, 0x60, 0x86, 0x48, 0x01, 0x86, 0xF8, 0x45, 0x01, + 0x09, 0x07 }; + byte messageTypeOid[] = + { 0x06, 0x0a, 0x60, 0x86, 0x48, 0x01, 0x86, 0xF8, 0x45, 0x01, + 0x09, 0x02 }; + byte senderNonceOid[] = + { 0x06, 0x0a, 0x60, 0x86, 0x48, 0x01, 0x86, 0xF8, 0x45, 0x01, + 0x09, 0x05 }; + byte transId[(SHA_DIGEST_SIZE + 1) * 2 + 1]; + byte messageType[] = { 0x13, 2, '1', '9' }; + byte senderNonce[PKCS7_NONCE_SZ + 2]; + + PKCS7Attrib attribs[] = + { + { transIdOid, sizeof(transIdOid), + transId, sizeof(transId) - 1 }, /* take off the null */ + { messageTypeOid, sizeof(messageTypeOid), + messageType, sizeof(messageType) }, + { senderNonceOid, sizeof(senderNonceOid), + senderNonce, sizeof(senderNonce) } + }; + + dataSz = (word32) strlen(data); + outSz = FOURK_BUF; + + certDer = (byte*)malloc(FOURK_BUF); + keyDer = (byte*)malloc(FOURK_BUF); + out = (byte*)malloc(FOURK_BUF); + + if (certDer == NULL) + return -207; + if (keyDer == NULL) + return -208; + if (out == NULL) + return -209; + + /* read in DER cert of recipient, into cert of size certSz */ + file = fopen(clientCert, "rb"); + if (!file) { + free(certDer); + free(keyDer); + free(out); + err_sys("can't open ./certs/client-cert.der, " + "Please run from CyaSSL home dir", -44); + } + certDerSz = (word32)fread(certDer, 1, FOURK_BUF, file); + fclose(file); + + file = fopen(clientKey, "rb"); + if (!file) { + free(certDer); + free(keyDer); + free(out); + err_sys("can't open ./certs/client-key.der, " + "Please run from CyaSSL home dir", -45); + } + keyDerSz = (word32)fread(keyDer, 1, FOURK_BUF, file); + fclose(file); + + ret = InitRng(&rng); + senderNonce[0] = 0x04; + senderNonce[1] = PKCS7_NONCE_SZ; + RNG_GenerateBlock(&rng, &senderNonce[2], PKCS7_NONCE_SZ); + + PKCS7_InitWithCert(&msg, certDer, certDerSz); + msg.privateKey = keyDer; + msg.privateKeySz = keyDerSz; + msg.content = (byte*)data; + msg.contentSz = dataSz; + msg.hashOID = SHAh; + msg.encryptOID = RSAk; + msg.signedAttribs = attribs; + msg.signedAttribsSz = sizeof(attribs)/sizeof(PKCS7Attrib); + msg.rng = &rng; + { + Sha sha; + byte digest[SHA_DIGEST_SIZE]; + int i,j; + + transId[0] = 0x13; + transId[1] = SHA_DIGEST_SIZE * 2; + + InitSha(&sha); + ShaUpdate(&sha, msg.publicKey, msg.publicKeySz); + ShaFinal(&sha, digest); + + for (i = 0, j = 2; i < SHA_DIGEST_SIZE; i++, j += 2) { + snprintf((char*)&transId[j], 3, "%02x", digest[i]); + } + } + ret = PKCS7_EncodeSignedData(&msg, out, outSz); + if (ret < 0) { + free(certDer); + free(keyDer); + free(out); + PKCS7_Free(&msg); + return -210; + } + else + outSz = ret; + + /* write PKCS#7 to output file for more testing */ + file = fopen("./pkcs7signedData.der", "wb"); + if (!file) { + free(certDer); + free(keyDer); + free(out); + PKCS7_Free(&msg); + return -211; + } + ret = (int)fwrite(out, 1, outSz, file); + fclose(file); + + PKCS7_Free(&msg); + PKCS7_InitWithCert(&msg, NULL, 0); + + ret = PKCS7_VerifySignedData(&msg, out, outSz); + if (ret < 0) { + free(certDer); + free(keyDer); + free(out); + PKCS7_Free(&msg); + return -212; + } + + if (msg.singleCert == NULL || msg.singleCertSz == 0) { + free(certDer); + free(keyDer); + free(out); + PKCS7_Free(&msg); + return -213; + } + + file = fopen("./pkcs7cert.der", "wb"); + if (!file) { + free(certDer); + free(keyDer); + free(out); + PKCS7_Free(&msg); + return -214; + } + ret = (int)fwrite(msg.singleCert, 1, msg.singleCertSz, file); + fclose(file); + + free(certDer); + free(keyDer); + free(out); + PKCS7_Free(&msg); + + if (ret > 0) + return 0; + + return ret; +} + +#endif /* HAVE_PKCS7 */ + #endif /* NO_CRYPT_TEST */ diff --git a/cyassl-ntru.vcproj b/cyassl-ntru.vcproj index 57720a52d..0813acdc7 100755 --- a/cyassl-ntru.vcproj +++ b/cyassl-ntru.vcproj @@ -166,10 +166,22 @@ RelativePath=".\ctaocrypt\src\asn.c" > + + + + + + @@ -182,6 +194,10 @@ RelativePath=".\ctaocrypt\src\dsa.c" > + + @@ -230,6 +246,10 @@ RelativePath=".\ctaocrypt\src\misc.c" > + + diff --git a/cyassl.vcproj b/cyassl.vcproj index 958f3ab61..82f919d25 100755 --- a/cyassl.vcproj +++ b/cyassl.vcproj @@ -162,10 +162,22 @@ RelativePath=".\ctaocrypt\src\asn.c" > + + + + + + @@ -178,6 +190,10 @@ RelativePath=".\ctaocrypt\src\dsa.c" > + + @@ -222,6 +238,10 @@ RelativePath=".\ctaocrypt\src\memory.c" > + + diff --git a/cyassl/ctaocrypt/aes.h b/cyassl/ctaocrypt/aes.h index 37861903e..e280e006b 100644 --- a/cyassl/ctaocrypt/aes.h +++ b/cyassl/ctaocrypt/aes.h @@ -92,6 +92,9 @@ typedef struct Aes { word32 magic; /* using cavium magic */ word64 contextHandle; /* nitrox context memory handle */ #endif +#ifdef CYASSL_AES_COUNTER + word32 left; /* unsued bytes left from last call */ +#endif } Aes; diff --git a/cyassl/ctaocrypt/asn.h b/cyassl/ctaocrypt/asn.h index 70dbfbe09..90ba8c7a1 100644 --- a/cyassl/ctaocrypt/asn.h +++ b/cyassl/ctaocrypt/asn.h @@ -59,6 +59,7 @@ enum ASN_Tags { ASN_TAG_NULL = 0x05, ASN_OBJECT_ID = 0x06, ASN_ENUMERATED = 0x0a, + ASN_UTF8STRING = 0x0c, ASN_SEQUENCE = 0x10, ASN_SET = 0x11, ASN_UTC_TIME = 0x17, @@ -125,6 +126,9 @@ enum Misc_ASN { MAX_ALGO_SZ = 20, MAX_SEQ_SZ = 5, /* enum(seq | con) + length(4) */ MAX_SET_SZ = 5, /* enum(set | con) + length(4) */ + MAX_OCTET_STR_SZ = 5, /* enum(set | con) + length(4) */ + MAX_EXP_SZ = 5, /* enum(contextspec|con|exp) + length(4) */ + MAX_PRSTR_SZ = 5, /* enum(prstr) + length(4) */ MAX_VERSION_SZ = 5, /* enum + id + version(byte) + (header(2))*/ MAX_ENCODED_DIG_SZ = 73, /* sha512 + enum(bit or octet) + legnth(4) */ MAX_RSA_INT_SZ = 517, /* RSA raw sz 4096 for bits + tag + len(4) */ @@ -135,6 +139,11 @@ enum Misc_ASN { MAX_CA_SZ = 32, /* Max encoded CA basic constraint length */ MAX_SN_SZ = 35, /* Max encoded serial number (INT) length */ #ifdef CYASSL_CERT_GEN + #ifdef CYASSL_CERT_REQ + /* Max encoded cert req attributes length */ + MAX_ATTRIB_SZ = MAX_SEQ_SZ * 3 + (11 + MAX_SEQ_SZ) * 2 + + MAX_PRSTR_SZ + CTC_NAME_SIZE, /* 11 is the OID size */ + #endif #ifdef CYASSL_ALT_NAMES MAX_EXTENSIONS_SZ = 1 + MAX_LENGTH_SZ + CTC_MAX_ALT_SIZE, #else @@ -151,9 +160,11 @@ enum Misc_ASN { enum Oid_Types { - hashType = 0, - sigType = 1, - keyType = 2 + hashType = 0, + sigType = 1, + keyType = 2, + curveType = 3, + blkType = 4 }; @@ -167,6 +178,12 @@ enum Hash_Sum { }; +enum Block_Sum { + DESb = 69, + DES3b = 652 +}; + + enum Key_Sum { DSAk = 515, RSAk = 645, @@ -198,7 +215,8 @@ enum Extensions_Sum { CA_ISSUER_OID = 117, AUTH_KEY_OID = 149, SUBJ_KEY_OID = 128, - CERT_POLICY_OID = 146 + CERT_POLICY_OID = 146, + KEY_USAGE_OID = 129 /* 2.5.29.15 */ }; enum CertificatePolicy_Sum { @@ -216,6 +234,18 @@ enum VerifyType { }; +/* Key usage extension bits */ +#define KEYUSE_DIGITAL_SIG 0x0100 +#define KEYUSE_CONTENT_COMMIT 0x0080 +#define KEYUSE_KEY_ENCIPHER 0x0040 +#define KEYUSE_DATA_ENCIPHER 0x0020 +#define KEYUSE_KEY_AGREE 0x0010 +#define KEYUSE_KEY_CERT_SIGN 0x0008 +#define KEYUSE_CRL_SIGN 0x0004 +#define KEYUSE_ENCIPHER_ONLY 0x0002 +#define KEYUSE_DECIPHER_ONLY 0x0001 + + typedef struct DNS_entry DNS_entry; struct DNS_entry { @@ -296,11 +326,35 @@ struct DecodedCert { byte extSubjKeyIdSet; /* Set when the SKID was read from cert */ byte extAuthKeyId[SHA_SIZE]; /* Authority Key ID */ byte extAuthKeyIdSet; /* Set when the AKID was read from cert */ - byte isCA; /* CA basic constraint true */ + byte isCA; /* CA basic constraint true */ +#ifdef OPENSSL_EXTRA + byte extBasicConstSet; + byte extBasicConstCrit; + byte extBasicConstPlSet; + word32 pathLength; /* CA basic constraint path length, opt */ + byte extSubjAltNameSet; + byte extSubjAltNameCrit; + byte extAuthKeyIdCrit; + byte extSubjKeyIdCrit; + byte extKeyUsageSet; + byte extKeyUsageCrit; + word16 extKeyUsage; /* Key usage bitfield */ + byte* extAuthKeyIdSrc; + word32 extAuthKeyIdSz; + byte* extSubjKeyIdSrc; + word32 extSubjKeyIdSz; + #ifdef HAVE_ECC + word32 pkCurveOID; /* Public Key's curve OID */ + #endif /* HAVE_ECC */ +#endif byte* beforeDate; int beforeDateLen; byte* afterDate; int afterDateLen; +#ifdef HAVE_PKCS7 + byte* issuerRaw; /* pointer to issuer inside source */ + int issuerRawLen; +#endif #if defined(CYASSL_CERT_GEN) /* easy access to subject info for other sign */ char* subjectSN; @@ -329,6 +383,10 @@ struct DecodedCert { byte* hwType; int hwSerialNumSz; byte* hwSerialNum; + #ifdef OPENSSL_EXTRA + byte extCertPolicySet; + byte extCertPolicyCrit; + #endif /* OPENSSL_EXTRA */ #endif /* CYASSL_SEP */ }; @@ -385,15 +443,37 @@ CYASSL_LOCAL int ToTraditionalEnc(byte* buffer, word32 length,const char*, int); CYASSL_LOCAL int ValidateDate(const byte* date, byte format, int dateType); +/* ASN.1 helper functions */ +CYASSL_LOCAL int GetLength(const byte* input, word32* inOutIdx, int* len, + word32 maxIdx); +CYASSL_LOCAL int GetSequence(const byte* input, word32* inOutIdx, int* len, + word32 maxIdx); +CYASSL_LOCAL int GetSet(const byte* input, word32* inOutIdx, int* len, + word32 maxIdx); +CYASSL_LOCAL int GetMyVersion(const byte* input, word32* inOutIdx, + int* version); +CYASSL_LOCAL int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, + word32 maxIdx); +CYASSL_LOCAL int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid, + word32 maxIdx); +CYASSL_LOCAL word32 SetLength(word32 length, byte* output); +CYASSL_LOCAL word32 SetSequence(word32 len, byte* output); +CYASSL_LOCAL word32 SetOctetString(word32 len, byte* output); +CYASSL_LOCAL word32 SetImplicit(byte tag, byte number, word32 len,byte* output); +CYASSL_LOCAL word32 SetExplicit(byte number, word32 len, byte* output); +CYASSL_LOCAL word32 SetSet(word32 len, byte* output); +CYASSL_LOCAL word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz); +CYASSL_LOCAL int SetMyVersion(word32 version, byte* output, int header); +CYASSL_LOCAL int SetSerialNumber(const byte* sn, word32 snSz, byte* output); +CYASSL_LOCAL int GetNameHash(const byte* source, word32* idx, byte* hash, + int maxIdx); + #ifdef HAVE_ECC /* ASN sig helpers */ CYASSL_LOCAL int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s); CYASSL_LOCAL int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s); - /* private key helpers */ - CYASSL_API int EccPrivateKeyDecode(const byte* input,word32* inOutIdx, - ecc_key*,word32); #endif #ifdef CYASSL_CERT_GEN @@ -403,7 +483,8 @@ enum cert_enums { JOINT_LEN = 2, EMAIL_JOINT_LEN = 9, RSA_KEY = 10, - NTRU_KEY = 11 + NTRU_KEY = 11, + ECC_KEY = 12 }; diff --git a/cyassl/ctaocrypt/asn_public.h b/cyassl/ctaocrypt/asn_public.h index f824fbb36..24c6a79e5 100644 --- a/cyassl/ctaocrypt/asn_public.h +++ b/cyassl/ctaocrypt/asn_public.h @@ -24,6 +24,7 @@ #define CTAO_CRYPT_ASN_PUBLIC_H #include +#include #ifdef CYASSL_CERT_GEN #include #endif @@ -41,7 +42,8 @@ enum CertType { DH_PARAM_TYPE, CRL_TYPE, CA_TYPE, - ECC_PRIVATEKEY_TYPE + ECC_PRIVATEKEY_TYPE, + CERTREQ_TYPE }; @@ -63,6 +65,10 @@ enum Ctc_SigType { #ifdef CYASSL_CERT_GEN +#ifndef HAVE_ECC + typedef struct ecc_key ecc_key; +#endif + enum Ctc_Misc { CTC_NAME_SIZE = 64, CTC_DATE_SIZE = 32, @@ -103,6 +109,9 @@ typedef struct Cert { byte afterDate[CTC_DATE_SIZE]; /* after date copy */ int afterDateSz; /* size of copy */ #endif +#ifdef CYASSL_CERT_REQ + char challengePw[CTC_NAME_SIZE]; +#endif } Cert; @@ -120,8 +129,14 @@ typedef struct Cert { keyType = RSA_KEY (default) */ CYASSL_API void InitCert(Cert*); -CYASSL_API int MakeCert(Cert*, byte* derBuffer, word32 derSz, RsaKey*, RNG*); -CYASSL_API int SignCert(Cert*, byte* derBuffer, word32 derSz, RsaKey*, RNG*); +CYASSL_API int MakeCert(Cert*, byte* derBuffer, word32 derSz, RsaKey*, + ecc_key*, RNG*); +#ifdef CYASSL_CERT_REQ + CYASSL_API int MakeCertReq(Cert*, byte* derBuffer, word32 derSz, RsaKey*, + ecc_key*); +#endif +CYASSL_API int SignCert(int requestSz, int sigType, byte* derBuffer, + word32 derSz, RsaKey*, ecc_key*, RNG*); CYASSL_API int MakeSelfCert(Cert*, byte* derBuffer, word32 derSz, RsaKey*, RNG*); CYASSL_API int SetIssuer(Cert*, const char*); @@ -147,6 +162,12 @@ CYASSL_API int SetDatesBuffer(Cert*, const byte*, int); word32 outputSz, int type); #endif +#ifdef HAVE_ECC + /* private key helpers */ + CYASSL_API int EccPrivateKeyDecode(const byte* input,word32* inOutIdx, + ecc_key*,word32); +#endif + #ifdef __cplusplus } /* extern "C" */ diff --git a/cyassl/ctaocrypt/coding.h b/cyassl/ctaocrypt/coding.h index a22cd3801..911163794 100644 --- a/cyassl/ctaocrypt/coding.h +++ b/cyassl/ctaocrypt/coding.h @@ -39,6 +39,9 @@ CYASSL_LOCAL int Base64_Decode(const byte* in, word32 inLen, byte* out, CYASSL_API int Base64_Encode(const byte* in, word32 inLen, byte* out, word32* outLen); + CYASSL_API + int Base64_EncodeEsc(const byte* in, word32 inLen, byte* out, + word32* outLen); CYASSL_LOCAL int Base16_Decode(const byte* in, word32 inLen, byte* out, word32* outLen); #endif diff --git a/cyassl/ctaocrypt/des3.h b/cyassl/ctaocrypt/des3.h index 219fa3ed9..fe931960e 100644 --- a/cyassl/ctaocrypt/des3.h +++ b/cyassl/ctaocrypt/des3.h @@ -63,22 +63,22 @@ enum { typedef struct Des { word32 reg[DES_BLOCK_SIZE / sizeof(word32)]; /* for CBC mode */ word32 tmp[DES_BLOCK_SIZE / sizeof(word32)]; /* same */ - #ifdef COLDFIRE_SEC +#ifdef HAVE_COLDFIRE_SEC byte keylen ; /* for Coldfire SEC */ byte ivlen ; /* for Coldfire SEC */ byte iv[DES3_IVLEN]; /* for Coldfire SEC */ - #endif +#endif word32 key[DES_KS_SIZE]; } Des; /* DES3 encryption and decryption */ typedef struct Des3 { - #ifdef COLDFIRE_SEC +#ifdef HAVE_COLDFIRE_SEC byte keylen ; /* for Coldfire SEC */ byte ivlen ; /* for Coldfire SEC */ byte iv[DES3_IVLEN]; /* for Coldfire SEC */ - #endif +#endif word32 key[3][DES_KS_SIZE]; word32 reg[DES_BLOCK_SIZE / sizeof(word32)]; /* for CBC mode */ word32 tmp[DES_BLOCK_SIZE / sizeof(word32)]; /* same */ diff --git a/cyassl/ctaocrypt/ecc.h b/cyassl/ctaocrypt/ecc.h index 683429fec..2434a6844 100644 --- a/cyassl/ctaocrypt/ecc.h +++ b/cyassl/ctaocrypt/ecc.h @@ -49,7 +49,7 @@ typedef struct { int size; /* The size of the curve in octets */ const char* name; /* name of this curve */ const char* prime; /* prime that defines the field, curve is in (hex) */ - const char* B; /* fields B param (hex) */ + const char* Bf; /* fields B param (hex) */ const char* order; /* order of the curve (hex) */ const char* Gx; /* x coordinate of the base point on curve (hex) */ const char* Gy; /* y coordinate of the base point on curve (hex) */ @@ -119,6 +119,7 @@ CYASSL_API int ecc_sig_size(ecc_key* key); +#ifdef HAVE_ECC_ENCRYPT /* ecc encrypt */ enum ecEncAlgo { @@ -137,34 +138,39 @@ enum ecMacAlgo { }; enum { - KEY_SIZE_128 = 16, - KEY_SIZE_256 = 32, - IV_SIZE_64 = 8 + KEY_SIZE_128 = 16, + KEY_SIZE_256 = 32, + IV_SIZE_64 = 8, + EXCHANGE_SALT_SZ = 16, + EXCHANGE_INFO_SZ = 23 }; -typedef struct ecEncOptions { - byte encAlgo; /* which encryption type */ - byte kdfAlgo; /* which key derivation function type */ - byte macAlgo; /* which mac function type */ - byte* kdfSalt; /* optional salt for kdf */ - byte* kdfInfo; /* optional info for kdf */ - byte* macSalt; /* optional salt for mac */ - word32 kdfSaltSz; /* size of kdfSalt */ - word32 kdfInfoSz; /* size of kdfInfo */ - word32 macSaltSz; /* size of macSalt */ -} ecEncOptions; +enum ecFlags { + REQ_RESP_CLIENT = 1, + REQ_RESP_SERVER = 2 +}; + + +typedef struct ecEncCtx ecEncCtx; CYASSL_API -void ecc_encrypt_init_options(ecEncOptions*); /* init and set to defaults */ +ecEncCtx* ecc_ctx_new(int flags, RNG* rng); CYASSL_API -void ecc_encrypt_free_options(ecEncOptions*); /* release/clear options */ +void ecc_ctx_free(ecEncCtx*); + +CYASSL_API +const byte* ecc_ctx_get_own_salt(ecEncCtx*); +CYASSL_API +int ecc_ctx_set_peer_salt(ecEncCtx*, const byte* salt); CYASSL_API int ecc_encrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, - word32 msgSz, byte* out, word32* outSz, ecEncOptions* options); + word32 msgSz, byte* out, word32* outSz, ecEncCtx* ctx); CYASSL_API int ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, - word32 msgSz, byte* out, word32* outSz, ecEncOptions* options); + word32 msgSz, byte* out, word32* outSz, ecEncCtx* ctx); + +#endif /* HAVE_ECC_ENCRYPT */ #ifdef __cplusplus } /* extern "C" */ diff --git a/cyassl/ctaocrypt/error.h b/cyassl/ctaocrypt/error.h index 7bb7960c3..af4d8e9c8 100644 --- a/cyassl/ctaocrypt/error.h +++ b/cyassl/ctaocrypt/error.h @@ -114,6 +114,14 @@ enum { ASN_CRL_NO_SIGNER_E = -190, /* ASN CRL no signer to confirm failure */ ASN_OCSP_CONFIRM_E = -191, /* ASN OCSP signature confirm failure */ + BAD_ENC_STATE_E = -192, /* Bad ecc enc state operation */ + BAD_PADDING_E = -193, /* Bad padding, msg not correct length */ + + REQ_ATTRIBUTE_E = -194, /* setting cert request attributes error */ + + PKCS7_OID_E = -195, /* PKCS#7, mismatched OID error */ + PKCS7_RECIP_E = -196, /* PKCS#7, recipient error */ + MIN_CODE_E = -200 /* errors -101 - -199 */ }; diff --git a/cyassl/ctaocrypt/include.am b/cyassl/ctaocrypt/include.am index 8be43c5e1..5c38659ef 100644 --- a/cyassl/ctaocrypt/include.am +++ b/cyassl/ctaocrypt/include.am @@ -21,6 +21,7 @@ nobase_include_HEADERS+= \ cyassl/ctaocrypt/md4.h \ cyassl/ctaocrypt/md5.h \ cyassl/ctaocrypt/misc.h \ + cyassl/ctaocrypt/pkcs7.h \ cyassl/ctaocrypt/port.h \ cyassl/ctaocrypt/pwdbased.h \ cyassl/ctaocrypt/rabbit.h \ diff --git a/cyassl/ctaocrypt/integer.h b/cyassl/ctaocrypt/integer.h index 2f7ab84fa..707eff7bf 100644 --- a/cyassl/ctaocrypt/integer.h +++ b/cyassl/ctaocrypt/integer.h @@ -286,6 +286,7 @@ int mp_2expt (mp_int * a, int b); int mp_reduce_2k_setup(mp_int *a, mp_digit *d); int mp_add_d (mp_int* a, mp_digit b, mp_int* c); int mp_set_int (mp_int * a, unsigned long b); +int mp_sub_d (mp_int * a, mp_digit b, mp_int * c); /* end support added functions */ /* added */ @@ -305,10 +306,6 @@ int mp_init_multi(mp_int* a, mp_int* b, mp_int* c, mp_int* d, mp_int* e, int mp_lcm (mp_int * a, mp_int * b, mp_int * c); #endif -#if defined(HAVE_ECC) || !defined(NO_PWDBASED) || defined(CYASSL_SNIFFER) - int mp_sub_d (mp_int * a, mp_digit b, mp_int * c); -#endif - #ifdef __cplusplus } #endif diff --git a/cyassl/ctaocrypt/pkcs7.h b/cyassl/ctaocrypt/pkcs7.h new file mode 100644 index 000000000..b4313f399 --- /dev/null +++ b/cyassl/ctaocrypt/pkcs7.h @@ -0,0 +1,123 @@ +/* pkcs7.h + * + * Copyright (C) 2006-2013 wolfSSL Inc. + * + * This file is part of CyaSSL. + * + * CyaSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * CyaSSL is distributed in the hope that it will be useful, + * * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + + +#ifdef HAVE_PKCS7 + +#ifndef CTAO_CRYPT_PKCS7_H +#define CTAO_CRYPT_PKCS7_H + +#include +#include +#include +#include +#include + +#ifdef __cplusplus + extern "C" { +#endif + +/* PKCS#7 content types, ref RFC 2315 (Section 14) */ +enum PKCS7_TYPES { + PKCS7_MSG = 650, /* 1.2.840.113549.1.7 */ + DATA = 651, /* 1.2.840.113549.1.7.1 */ + SIGNED_DATA = 652, /* 1.2.840.113549.1.7.2 */ + ENVELOPED_DATA = 653, /* 1.2.840.113549.1.7.3 */ + SIGNED_AND_ENVELOPED_DATA = 654, /* 1.2.840.113549.1.7.4 */ + DIGESTED_DATA = 655, /* 1.2.840.113549.1.7.5 */ + ENCRYPTED_DATA = 656 /* 1.2.840.113549.1.7.6 */ +}; + +enum Pkcs7_Misc { + PKCS7_NONCE_SZ = 16, + MAX_ENCRYPTED_KEY_SZ = 512, /* max enc. key size, RSA <= 4096 */ + MAX_CONTENT_KEY_LEN = DES3_KEYLEN, /* highest current cipher is 3DES */ + MAX_RECIP_SZ = MAX_VERSION_SZ + + MAX_SEQ_SZ + ASN_NAME_MAX + MAX_SN_SZ + + MAX_SEQ_SZ + MAX_ALGO_SZ + 1 + MAX_ENCRYPTED_KEY_SZ +}; + + +typedef struct PKCS7Attrib { + byte* oid; + word32 oidSz; + byte* value; + word32 valueSz; +} PKCS7Attrib; + + +typedef struct PKCS7 { + byte* content; /* inner content, not owner */ + word32 contentSz; /* content size */ + int contentOID; /* PKCS#7 content type OID sum */ + + RNG* rng; + + int hashOID; + int encryptOID; /* key encryption algorithm OID */ + + byte* singleCert; /* recipient cert, DER, not owner */ + word32 singleCertSz; /* size of recipient cert buffer, bytes */ + byte issuerHash[SHA_SIZE]; /* hash of all alt Names */ + byte* issuer; /* issuer name of singleCert */ + word32 issuerSz; /* length of issuer name */ + byte issuerSn[MAX_SN_SZ]; /* singleCert's serial number */ + word32 issuerSnSz; /* length of serial number */ + byte publicKey[512]; + word32 publicKeySz; + byte* privateKey; /* private key, DER, not owner */ + word32 privateKeySz; /* size of private key buffer, bytes */ + + PKCS7Attrib* signedAttribs; + word32 signedAttribsSz; +} PKCS7; + + +CYASSL_LOCAL int SetContentType(int pkcs7TypeOID, byte* output); +CYASSL_LOCAL int GetContentType(const byte* input, word32* inOutIdx, + word32* oid, word32 maxIdx); +CYASSL_LOCAL int CreateRecipientInfo(const byte* cert, word32 certSz, + int keyEncAlgo, int blockKeySz, + RNG* rng, byte* contentKeyPlain, + byte* contentKeyEnc, + int* keyEncSz, byte* out, word32 outSz); + +CYASSL_API int PKCS7_InitWithCert(PKCS7* pkcs7, byte* cert, word32 certSz); +CYASSL_API void PKCS7_Free(PKCS7* pkcs7); +CYASSL_API int PKCS7_EncodeData(PKCS7* pkcs7, byte* output, word32 outputSz); +CYASSL_API int PKCS7_EncodeSignedData(PKCS7* pkcs7, + byte* output, word32 outputSz); +CYASSL_API int PKCS7_VerifySignedData(PKCS7* pkcs7, + byte* pkiMsg, word32 pkiMsgSz); +CYASSL_API int PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, + byte* output, word32 outputSz); +CYASSL_API int PKCS7_DecodeEnvelopedData(PKCS7* pkcs7, byte* pkiMsg, + word32 pkiMsgSz, byte* output, + word32 outputSz); + +#ifdef __cplusplus + } /* extern "C" */ +#endif + +#endif /* CTAO_CRYPT_PKCS7_H */ + +#endif /* HAVE_PKCS7 */ + diff --git a/cyassl/ctaocrypt/settings.h b/cyassl/ctaocrypt/settings.h index d61c5484a..22dea06d0 100644 --- a/cyassl/ctaocrypt/settings.h +++ b/cyassl/ctaocrypt/settings.h @@ -78,6 +78,9 @@ /* Uncomment next line if using Comverge settings */ /* #define COMVERGE */ +/* Uncomment next line if using QL SEP settings */ +/* #define CYASSL_QL */ + #include @@ -149,10 +152,26 @@ #endif /* MBED */ #ifdef CYASSL_TYTO + #include "rand.h" #define FREERTOS #define NO_FILESYSTEM #define CYASSL_USER_IO #define NO_DEV_RANDOM + #define HAVE_ECC + #define HAVE_ECC_ENCRYPT + #define ECC_SHAMIR + #define HAVE_HKDF + #define USE_FAST_MATH + #define TFM_TIMING_RESISTANT + #define FP_MAX_BITS 512 + #define NO_OLD_TLS + #define NO_MD4 + #define NO_RABBIT + #define NO_HC128 + #define NO_RSA + #define NO_DSA + #define NO_PWDBASED + #define NO_PSK #endif #ifdef FREERTOS_WINSIM @@ -313,8 +332,8 @@ #include "mutex.h" #endif - #define XMALLOC(s, h, type) (void *)_mem_alloc_system((s)) - #define XFREE(p, h, type) _mem_free(p) + #define XMALLOC(s, h, t) (void *)_mem_alloc_system((s)) + #define XFREE(p, h, t) {void* xp = (p); if ((xp)) _mem_free((xp));} /* Note: MQX has no realloc, using fastmath above */ #endif @@ -524,6 +543,37 @@ #endif /* MICRIUM */ +#ifdef CYASSL_QL + #ifndef CYASSL_SEP + #define CYASSL_SEP + #endif + #ifndef OPENSSL_EXTRA + #define OPENSSL_EXTRA + #endif + #ifndef SESSION_CERTS + #define SESSION_CERTS + #endif + #ifndef HAVE_AESCCM + #define HAVE_AESCCM + #endif + #ifndef ATOMIC_USER + #define ATOMIC_USER + #endif + #ifndef CYASSL_DER_LOAD + #define CYASSL_DER_LOAD + #endif + #ifndef KEEP_PEER_CERT + #define KEEP_PEER_CERT + #endif + #ifndef HAVE_ECC + #define HAVE_ECC + #endif + #ifndef SESSION_INDEX + #define SESSION_INDEX + #endif +#endif /* CYASSL_QL */ + + #if !defined(XMALLOC_USER) && !defined(MICRIUM_MALLOC) && \ !defined(CYASSL_LEANPSK) && !defined(NO_CYASSL_MEMORY) #define USE_CYASSL_MEMORY diff --git a/cyassl/ctaocrypt/tfm.h b/cyassl/ctaocrypt/tfm.h index 2495f67ab..e1b16e2d3 100644 --- a/cyassl/ctaocrypt/tfm.h +++ b/cyassl/ctaocrypt/tfm.h @@ -510,104 +510,104 @@ void s_fp_add(fp_int *a, fp_int *b, fp_int *c); void s_fp_sub(fp_int *a, fp_int *b, fp_int *c); void fp_reverse(unsigned char *s, int len); -void fp_mul_comba(fp_int *A, fp_int *B, fp_int *C); +void fp_mul_comba(fp_int *a, fp_int *b, fp_int *c); #ifdef TFM_SMALL_SET -void fp_mul_comba_small(fp_int *A, fp_int *B, fp_int *C); +void fp_mul_comba_small(fp_int *a, fp_int *b, fp_int *c); #endif #ifdef TFM_MUL3 -void fp_mul_comba3(fp_int *A, fp_int *B, fp_int *C); +void fp_mul_comba3(fp_int *a, fp_int *b, fp_int *c); #endif #ifdef TFM_MUL4 -void fp_mul_comba4(fp_int *A, fp_int *B, fp_int *C); +void fp_mul_comba4(fp_int *a, fp_int *b, fp_int *c); #endif #ifdef TFM_MUL6 -void fp_mul_comba6(fp_int *A, fp_int *B, fp_int *C); +void fp_mul_comba6(fp_int *a, fp_int *b, fp_int *c); #endif #ifdef TFM_MUL7 -void fp_mul_comba7(fp_int *A, fp_int *B, fp_int *C); +void fp_mul_comba7(fp_int *a, fp_int *b, fp_int *c); #endif #ifdef TFM_MUL8 -void fp_mul_comba8(fp_int *A, fp_int *B, fp_int *C); +void fp_mul_comba8(fp_int *a, fp_int *b, fp_int *c); #endif #ifdef TFM_MUL9 -void fp_mul_comba9(fp_int *A, fp_int *B, fp_int *C); +void fp_mul_comba9(fp_int *a, fp_int *b, fp_int *c); #endif #ifdef TFM_MUL12 -void fp_mul_comba12(fp_int *A, fp_int *B, fp_int *C); +void fp_mul_comba12(fp_int *a, fp_int *b, fp_int *c); #endif #ifdef TFM_MUL17 -void fp_mul_comba17(fp_int *A, fp_int *B, fp_int *C); +void fp_mul_comba17(fp_int *a, fp_int *b, fp_int *c); #endif #ifdef TFM_MUL20 -void fp_mul_comba20(fp_int *A, fp_int *B, fp_int *C); +void fp_mul_comba20(fp_int *a, fp_int *b, fp_int *c); #endif #ifdef TFM_MUL24 -void fp_mul_comba24(fp_int *A, fp_int *B, fp_int *C); +void fp_mul_comba24(fp_int *a, fp_int *b, fp_int *c); #endif #ifdef TFM_MUL28 -void fp_mul_comba28(fp_int *A, fp_int *B, fp_int *C); +void fp_mul_comba28(fp_int *a, fp_int *b, fp_int *c); #endif #ifdef TFM_MUL32 -void fp_mul_comba32(fp_int *A, fp_int *B, fp_int *C); +void fp_mul_comba32(fp_int *a, fp_int *b, fp_int *c); #endif #ifdef TFM_MUL48 -void fp_mul_comba48(fp_int *A, fp_int *B, fp_int *C); +void fp_mul_comba48(fp_int *a, fp_int *b, fp_int *c); #endif #ifdef TFM_MUL64 -void fp_mul_comba64(fp_int *A, fp_int *B, fp_int *C); +void fp_mul_comba64(fp_int *a, fp_int *b, fp_int *c); #endif -void fp_sqr_comba(fp_int *A, fp_int *B); +void fp_sqr_comba(fp_int *a, fp_int *b); #ifdef TFM_SMALL_SET -void fp_sqr_comba_small(fp_int *A, fp_int *B); +void fp_sqr_comba_small(fp_int *a, fp_int *b); #endif #ifdef TFM_SQR3 -void fp_sqr_comba3(fp_int *A, fp_int *B); +void fp_sqr_comba3(fp_int *a, fp_int *b); #endif #ifdef TFM_SQR4 -void fp_sqr_comba4(fp_int *A, fp_int *B); +void fp_sqr_comba4(fp_int *a, fp_int *b); #endif #ifdef TFM_SQR6 -void fp_sqr_comba6(fp_int *A, fp_int *B); +void fp_sqr_comba6(fp_int *a, fp_int *b); #endif #ifdef TFM_SQR7 -void fp_sqr_comba7(fp_int *A, fp_int *B); +void fp_sqr_comba7(fp_int *a, fp_int *b); #endif #ifdef TFM_SQR8 -void fp_sqr_comba8(fp_int *A, fp_int *B); +void fp_sqr_comba8(fp_int *a, fp_int *b); #endif #ifdef TFM_SQR9 -void fp_sqr_comba9(fp_int *A, fp_int *B); +void fp_sqr_comba9(fp_int *a, fp_int *b); #endif #ifdef TFM_SQR12 -void fp_sqr_comba12(fp_int *A, fp_int *B); +void fp_sqr_comba12(fp_int *a, fp_int *b); #endif #ifdef TFM_SQR17 -void fp_sqr_comba17(fp_int *A, fp_int *B); +void fp_sqr_comba17(fp_int *a, fp_int *b); #endif #ifdef TFM_SQR20 -void fp_sqr_comba20(fp_int *A, fp_int *B); +void fp_sqr_comba20(fp_int *a, fp_int *b); #endif #ifdef TFM_SQR24 -void fp_sqr_comba24(fp_int *A, fp_int *B); +void fp_sqr_comba24(fp_int *a, fp_int *b); #endif #ifdef TFM_SQR28 -void fp_sqr_comba28(fp_int *A, fp_int *B); +void fp_sqr_comba28(fp_int *a, fp_int *b); #endif #ifdef TFM_SQR32 -void fp_sqr_comba32(fp_int *A, fp_int *B); +void fp_sqr_comba32(fp_int *a, fp_int *b); #endif #ifdef TFM_SQR48 -void fp_sqr_comba48(fp_int *A, fp_int *B); +void fp_sqr_comba48(fp_int *a, fp_int *b); #endif #ifdef TFM_SQR64 -void fp_sqr_comba64(fp_int *A, fp_int *B); +void fp_sqr_comba64(fp_int *a, fp_int *b); #endif /*extern const char *fp_s_rmap;*/ @@ -642,7 +642,7 @@ int mp_mul (mp_int * a, mp_int * b, mp_int * c); int mp_mulmod (mp_int * a, mp_int * b, mp_int * c, mp_int * d); int mp_mod(mp_int *a, mp_int *b, mp_int *c); int mp_invmod(mp_int *a, mp_int *b, mp_int *c); -int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y); +int mp_exptmod (mp_int * g, mp_int * x, mp_int * p, mp_int * y); int mp_cmp(mp_int *a, mp_int *b); int mp_cmp_d(mp_int *a, mp_digit b); @@ -663,7 +663,7 @@ void mp_rshb(mp_int *a, int x); #ifdef HAVE_ECC int mp_read_radix(mp_int* a, const char* str, int radix); int mp_set(fp_int *a, fp_digit b); - int mp_sqr(fp_int *A, fp_int *B); + int mp_sqr(fp_int *a, fp_int *b); int mp_montgomery_reduce(fp_int *a, fp_int *m, fp_digit mp); int mp_montgomery_setup(fp_int *a, fp_digit *rho); int mp_div_2(fp_int * a, fp_int * b); diff --git a/cyassl/ctaocrypt/types.h b/cyassl/ctaocrypt/types.h index 8c44bb89f..ea9cf8c11 100644 --- a/cyassl/ctaocrypt/types.h +++ b/cyassl/ctaocrypt/types.h @@ -139,6 +139,18 @@ enum { #endif +/* set up thread local storage if available */ +#ifdef HAVE_THREAD_LS + #if defined(_MSC_VER) + #define THREAD_LS_T __declspec(thread) + #else + #define THREAD_LS_T __thread + #endif +#else + #define THREAD_LS_T +#endif + + /* Micrium will use Visual Studio for compilation but not the Win32 API */ #if defined(_WIN32) && !defined(MICRIUM) && !defined(FREERTOS) \ && !defined(EBSNET) @@ -205,6 +217,11 @@ enum { #define XISALPHA(c) isalpha((c)) #endif /* needed by CyaSSL_check_domain_name() */ + #ifdef __CYGWIN__ + /* Cygwin uses a macro version of tolower() by default, use the + * function version. */ + #undef tolower + #endif #define XTOLOWER(c) tolower((c)) #endif @@ -253,7 +270,8 @@ enum { DYNAMIC_TYPE_CAVIUM_TMP = 40, DYNAMIC_TYPE_CAVIUM_RSA = 41, DYNAMIC_TYPE_X509 = 42, - DYNAMIC_TYPE_TLSX = 43 + DYNAMIC_TYPE_TLSX = 43, + DYNAMIC_TYPE_OCSP = 44 }; /* max error buffer string size */ diff --git a/cyassl/include.am b/cyassl/include.am index 0cd892a37..9784ab249 100644 --- a/cyassl/include.am +++ b/cyassl/include.am @@ -9,7 +9,6 @@ EXTRA_DIST+= cyassl/sniffer_error.rc nobase_include_HEADERS+= \ cyassl/error.h \ - cyassl/internal.h \ cyassl/ssl.h \ cyassl/sniffer_error.h \ cyassl/sniffer.h \ @@ -20,3 +19,7 @@ nobase_include_HEADERS+= \ cyassl/options.h \ cyassl/ocsp.h \ cyassl/crl.h + +noinst_HEADERS+= \ + cyassl/internal.h + diff --git a/cyassl/internal.h b/cyassl/internal.h index 32b8964bf..085d2a393 100644 --- a/cyassl/internal.h +++ b/cyassl/internal.h @@ -483,7 +483,6 @@ enum { TLS_RSA_WITH_AES_256_CBC_B2B256 = 0xF9, TLS_RSA_WITH_HC_128_B2B256 = 0xFA, /* eSTREAM too */ - /* CyaSSL extension - NTRU */ TLS_NTRU_RSA_WITH_RC4_128_SHA = 0xe5, TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA = 0xe6, @@ -533,8 +532,10 @@ enum { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA = 0x45, TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA = 0x88, TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 = 0xbe, - TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 = 0xc4 + TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 = 0xc4, + /* Renegotiation Indication Extension Special Suite */ + TLS_EMPTY_RENEGOTIATION_INFO_SCSV = 0xff }; @@ -608,6 +609,7 @@ enum Misc { CERT_HEADER_SZ = 3, /* always 3 bytes */ REQ_HEADER_SZ = 2, /* cert request header sz */ HINT_LEN_SZ = 2, /* length of hint size field */ + TRUNCATED_HMAC_SZ = 10, /* length of hmac w/ truncated hmac extension */ HELLO_EXT_TYPE_SZ = 2, /* length of a hello extension type */ HELLO_EXT_SZ = 8, /* total length of the lazy hello extensions */ HELLO_EXT_LEN = 6, /* length of the lazy hello extensions */ @@ -981,24 +983,22 @@ typedef struct OCSP_Entry OCSP_Entry; #endif struct OCSP_Entry { - OCSP_Entry* next; /* next entry */ + OCSP_Entry* next; /* next entry */ byte issuerHash[OCSP_DIGEST_SIZE]; /* issuer hash */ byte issuerKeyHash[OCSP_DIGEST_SIZE]; /* issuer public key hash */ - CertStatus* status; /* OCSP response list */ - int totalStatus; /* number on list */ + CertStatus* status; /* OCSP response list */ + int totalStatus; /* number on list */ }; +#ifndef HAVE_OCSP + typedef struct CYASSL_OCSP CYASSL_OCSP; +#endif + /* CyaSSL OCSP controller */ struct CYASSL_OCSP { - byte enabled; - byte useOverrideUrl; - byte useNonce; - char overrideUrl[80]; - OCSP_Entry* ocspList; - void* IOCB_OcspCtx; - CallbackIOOcsp CBIOOcsp; - CallbackIOOcspRespFree CBIOOcspRespFree; + CYASSL_CERT_MANAGER* cm; /* pointer back to cert manager */ + OCSP_Entry* ocspList; /* OCSP response list */ }; #ifndef MAX_DATE_SIZE @@ -1076,6 +1076,14 @@ struct CYASSL_CERT_MANAGER { byte crlEnabled; /* is CRL on ? */ byte crlCheckAll; /* always leaf, but all ? */ CbMissingCRL cbMissingCRL; /* notify through cb of missing crl */ + CYASSL_OCSP* ocsp; /* OCSP checker */ + byte ocspEnabled; /* is OCSP on ? */ + byte ocspSendNonce; /* send the OCSP nonce ? */ + byte ocspUseOverrideURL; /* ignore cert's responder, override */ + char* ocspOverrideURL; /* use this responder */ + void* ocspIOCtx; /* I/O callback CTX */ + CbOCSPIO ocspIOCb; /* I/O callback for OCSP lookup */ + CbOCSPRespFree ocspRespFreeCb; /* Frees OCSP Response from IO Cb */ }; CYASSL_LOCAL int CM_SaveCertCache(CYASSL_CERT_MANAGER*, const char*); @@ -1153,6 +1161,8 @@ CYASSL_LOCAL void TLSX_SNI_SetOptions(TLSX* extensions, byte type, CYASSL_LOCAL byte TLSX_SNI_Status(TLSX* extensions, byte type); CYASSL_LOCAL word16 TLSX_SNI_GetRequest(TLSX* extensions, byte type, void** data); +CYASSL_LOCAL int TLSX_SNI_GetFromBuffer(const byte* buffer, word32 bufferSz, + byte type, byte* sni, word32* inOutSz); #endif #endif /* HAVE_SNI */ @@ -1166,8 +1176,6 @@ CYASSL_LOCAL int TLSX_UseMaxFragment(TLSX** extensions, byte mfl); #ifdef HAVE_TRUNCATED_HMAC -#define TRUNCATED_HMAC_SIZE 10 - CYASSL_LOCAL int TLSX_UseTruncatedHMAC(TLSX** extensions); #endif /* HAVE_TRUNCATED_HMAC */ @@ -1360,6 +1368,30 @@ enum ClientCertificateType { enum CipherType { stream, block, aead }; +#ifdef CYASSL_DTLS + + #ifdef WORD64_AVAILABLE + typedef word64 DtlsSeq; + #else + typedef word32 DtlsSeq; + #endif + #define DTLS_SEQ_BITS (sizeof(DtlsSeq) * CHAR_BIT) + + typedef struct DtlsState { + DtlsSeq window; /* Sliding window for current epoch */ + word16 nextEpoch; /* Expected epoch in next record */ + word32 nextSeq; /* Expected sequence in next record */ + + word16 curEpoch; /* Received epoch in current record */ + word32 curSeq; /* Received sequence in current record */ + + DtlsSeq prevWindow; /* Sliding window for old epoch */ + word32 prevSeq; /* Next sequence in allowed old epoch */ + } DtlsState; + +#endif /* CYASSL_DTLS */ + + /* keys and secrets */ typedef struct Keys { byte client_write_MAC_secret[MAX_DIGEST_SIZE]; /* max sizes */ @@ -1378,15 +1410,13 @@ typedef struct Keys { word32 sequence_number; #ifdef CYASSL_DTLS - word32 dtls_sequence_number; - word32 dtls_peer_sequence_number; - word32 dtls_expected_peer_sequence_number; - word16 dtls_handshake_number; + DtlsState dtls_state; /* Peer's state */ word16 dtls_peer_handshake_number; word16 dtls_expected_peer_handshake_number; - word16 dtls_epoch; - word16 dtls_peer_epoch; - word16 dtls_expected_peer_epoch; + + word16 dtls_epoch; /* Current tx epoch */ + word32 dtls_sequence_number; /* Current tx sequence */ + word16 dtls_handshake_number; /* Current tx handshake seq */ #endif word32 encryptSz; /* last size of encrypted data */ @@ -1661,6 +1691,10 @@ struct CYASSL_X509 { byte hwType[EXTERNAL_SERIAL_SIZE]; int hwSerialNumSz; byte hwSerialNum[EXTERNAL_SERIAL_SIZE]; + #ifdef OPENSSL_EXTRA + byte certPolicySet; + byte certPolicyCrit; + #endif /* OPENSSL_EXTRA */ #endif int notBeforeSz; byte notBefore[MAX_DATE_SZ]; @@ -1670,10 +1704,33 @@ struct CYASSL_X509 { buffer sig; int pubKeyOID; buffer pubKey; + #ifdef HAVE_ECC + word32 pkCurveOID; + #endif /* HAVE_ECC */ buffer derCert; /* may need */ DNS_entry* altNames; /* alt names list */ DNS_entry* altNamesNext; /* hint for retrieval */ byte dynamicMemory; /* dynamic memory flag */ + byte isCa; +#ifdef OPENSSL_EXTRA + word32 pathLength; + word16 keyUsage; + byte basicConstSet; + byte basicConstCrit; + byte basicConstPlSet; + byte subjAltNameSet; + byte subjAltNameCrit; + byte authKeyIdSet; + byte authKeyIdCrit; + byte* authKeyId; + word32 authKeyIdSz; + byte subjKeyIdSet; + byte subjKeyIdCrit; + byte* subjKeyId; + word32 subjKeyIdSz; + byte keyUsageSet; + byte keyUsageCrit; +#endif /* OPENSSL_EXTRA */ }; diff --git a/cyassl/internal.h.orig b/cyassl/internal.h.orig new file mode 100644 index 000000000..085d2a393 --- /dev/null +++ b/cyassl/internal.h.orig @@ -0,0 +1,2121 @@ +/* internal.h + * + * Copyright (C) 2006-2013 wolfSSL Inc. + * + * This file is part of CyaSSL. + * + * CyaSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * CyaSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + + +#ifndef CYASSL_INT_H +#define CYASSL_INT_H + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef NO_RC4 + #include +#endif +#ifdef HAVE_ECC + #include +#endif +#ifndef NO_SHA256 + #include +#endif +#ifdef HAVE_OCSP + #include +#endif +#ifdef CYASSL_SHA512 + #include +#endif + +#ifdef HAVE_AESGCM + #include +#endif + +#ifdef CYASSL_RIPEMD + #include +#endif + +#ifdef CYASSL_CALLBACKS + #include + #include +#endif + +#ifdef USE_WINDOWS_API + #ifdef CYASSL_GAME_BUILD + #include "system/xtl.h" + #else + #if defined(_WIN32_WCE) || defined(WIN32_LEAN_AND_MEAN) + /* On WinCE winsock2.h must be included before windows.h */ + #include + #endif + #include + #endif +#elif defined(THREADX) + #ifndef SINGLE_THREADED + #include "tx_api.h" + #endif +#elif defined(MICRIUM) + /* do nothing, just don't pick Unix */ +#elif defined(FREERTOS) || defined(CYASSL_SAFERTOS) + /* do nothing */ +#elif defined(EBSNET) + /* do nothing */ +#elif defined(FREESCALE_MQX) + /* do nothing */ +#elif defined(CYASSL_MDK_ARM) + #if defined(CYASSL_MDK5) + #include "cmsis_os.h" + #else + #include + #endif +#else + #ifndef SINGLE_THREADED + #define CYASSL_PTHREADS + #include + #endif + #if defined(OPENSSL_EXTRA) || defined(GOAHEAD_WS) + #include /* for close of BIO */ + #endif +#endif + + +#ifdef HAVE_LIBZ + #include "zlib.h" +#endif + +#ifdef _MSC_VER + /* 4996 warning to use MS extensions e.g., strcpy_s instead of strncpy */ + #pragma warning(disable: 4996) +#endif + +#ifdef NO_AES + #if !defined (ALIGN16) + #define ALIGN16 + #endif +#endif + +#ifdef NO_SHA + #define SHA_DIGEST_SIZE 20 +#endif + +#ifdef NO_SHA256 + #define SHA256_DIGEST_SIZE 32 +#endif + + +#ifdef __cplusplus + extern "C" { +#endif + + +#ifdef USE_WINDOWS_API + typedef unsigned int SOCKET_T; +#else + typedef int SOCKET_T; +#endif + + +typedef byte word24[3]; + +/* used by ssl.c and cyassl_int.c */ +void c32to24(word32 in, word24 out); + +/* Define or comment out the cipher suites you'd like to be compiled in + make sure to use at least one BUILD_SSL_xxx or BUILD_TLS_xxx is defined + + When adding cipher suites, add name to cipher_names, idx to cipher_name_idx +*/ +#if !defined(NO_RSA) && !defined(NO_RC4) + #if !defined(NO_SHA) + #define BUILD_SSL_RSA_WITH_RC4_128_SHA + #endif + #if !defined(NO_MD5) + #define BUILD_SSL_RSA_WITH_RC4_128_MD5 + #endif + #if !defined(NO_TLS) && defined(HAVE_NTRU) && !defined(NO_SHA) + #define BUILD_TLS_NTRU_RSA_WITH_RC4_128_SHA + #endif +#endif + +#if !defined(NO_RSA) && !defined(NO_DES3) + #if !defined(NO_SHA) + #define BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA + #if !defined(NO_TLS) && defined(HAVE_NTRU) + #define BUILD_TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA + #endif + #endif +#endif + +#if !defined(NO_RSA) && !defined(NO_AES) && !defined(NO_TLS) + #if !defined(NO_SHA) + #define BUILD_TLS_RSA_WITH_AES_128_CBC_SHA + #define BUILD_TLS_RSA_WITH_AES_256_CBC_SHA + #if defined(HAVE_NTRU) + #define BUILD_TLS_NTRU_RSA_WITH_AES_128_CBC_SHA + #define BUILD_TLS_NTRU_RSA_WITH_AES_256_CBC_SHA + #endif + #endif + #if !defined (NO_SHA256) + #define BUILD_TLS_RSA_WITH_AES_128_CBC_SHA256 + #define BUILD_TLS_RSA_WITH_AES_256_CBC_SHA256 + #endif + #if defined (HAVE_AESGCM) + #define BUILD_TLS_RSA_WITH_AES_128_GCM_SHA256 + #if defined (CYASSL_SHA384) + #define BUILD_TLS_RSA_WITH_AES_256_GCM_SHA384 + #endif + #endif + #if defined (HAVE_AESCCM) + #define BUILD_TLS_RSA_WITH_AES_128_CCM_8 + #define BUILD_TLS_RSA_WITH_AES_256_CCM_8 + #endif + #if defined(HAVE_BLAKE2) + #define BUILD_TLS_RSA_WITH_AES_128_CBC_B2B256 + #define BUILD_TLS_RSA_WITH_AES_256_CBC_B2B256 + #endif +#endif + +#if defined(HAVE_CAMELLIA) && !defined(NO_TLS) + #ifndef NO_RSA + #if !defined(NO_SHA) + #define BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA + #define BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA + #endif + #ifndef NO_SHA256 + #define BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 + #define BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 + #endif + #if !defined(NO_DH) && defined(OPENSSL_EXTRA) + #if !defined(NO_SHA) + #define BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA + #define BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA + #endif + #ifndef NO_SHA256 + #define BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 + #define BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 + #endif + #endif + #endif +#endif + +#if !defined(NO_PSK) && !defined(NO_AES) && !defined(NO_TLS) + #if !defined(NO_SHA) + #define BUILD_TLS_PSK_WITH_AES_128_CBC_SHA + #define BUILD_TLS_PSK_WITH_AES_256_CBC_SHA + #endif + #ifndef NO_SHA256 + #define BUILD_TLS_PSK_WITH_AES_128_CBC_SHA256 + #ifdef HAVE_AESCCM + #define BUILD_TLS_PSK_WITH_AES_128_CCM_8 + #define BUILD_TLS_PSK_WITH_AES_256_CCM_8 + #endif + #endif +#endif + +#if !defined(NO_TLS) && defined(HAVE_NULL_CIPHER) + #if !defined(NO_RSA) + #if !defined(NO_SHA) + #define BUILD_TLS_RSA_WITH_NULL_SHA + #endif + #ifndef NO_SHA256 + #define BUILD_TLS_RSA_WITH_NULL_SHA256 + #endif + #endif + #if !defined(NO_PSK) + #if !defined(NO_SHA) + #define BUILD_TLS_PSK_WITH_NULL_SHA + #endif + #ifndef NO_SHA256 + #define BUILD_TLS_PSK_WITH_NULL_SHA256 + #endif + #endif +#endif + +#if !defined(NO_HC128) && !defined(NO_RSA) && !defined(NO_TLS) + #define BUILD_TLS_RSA_WITH_HC_128_MD5 + #if !defined(NO_SHA) + #define BUILD_TLS_RSA_WITH_HC_128_SHA + #endif + #if defined(HAVE_BLAKE2) + #define BUILD_TLS_RSA_WITH_HC_128_B2B256 + #endif +#endif + +#if !defined(NO_RABBIT) && !defined(NO_TLS) && !defined(NO_RSA) + #if !defined(NO_SHA) + #define BUILD_TLS_RSA_WITH_RABBIT_SHA + #endif +#endif + +#if !defined(NO_DH) && !defined(NO_AES) && !defined(NO_TLS) && \ + !defined(NO_RSA) && defined(OPENSSL_EXTRA) + #if !defined(NO_SHA) + #define BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA + #define BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA + #endif + #if !defined (NO_SHA256) + #define BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 + #define BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 + #if defined (HAVE_AESGCM) + #define BUILD_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 + #if defined (CYASSL_SHA384) + #define BUILD_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 + #endif + #endif + #endif +#endif + +#if defined(HAVE_ECC) && !defined(NO_TLS) + #if !defined(NO_AES) + #if !defined(NO_SHA) + #if !defined(NO_RSA) + #define BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA + #define BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA + #define BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA + #define BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA + #endif + + #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA + #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA + + #define BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA + #define BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA + #endif /* NO_SHA */ + #ifndef NO_SHA256 + #if !defined(NO_RSA) + #define BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 + #define BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 + #endif + #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 + #define BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 + #endif + + #ifdef CYASSL_SHA384 + #if !defined(NO_RSA) + #define BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 + #define BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 + #endif + #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 + #define BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 + #endif + + #if defined (HAVE_AESGCM) + #if !defined(NO_RSA) + #define BUILD_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 + #define BUILD_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 + #if defined(CYASSL_SHA384) + #define BUILD_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 + #define BUILD_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 + #endif + #endif + + #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 + #define BUILD_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 + + #if defined(CYASS_SHA384) + #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 + #define BUILD_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 + #endif + #endif + #if defined (HAVE_AESCCM) + #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 + #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 + #endif + #endif /* NO_AES */ + #if !defined(NO_RC4) + #if !defined(NO_SHA) + #if !defined(NO_RSA) + #define BUILD_TLS_ECDHE_RSA_WITH_RC4_128_SHA + #define BUILD_TLS_ECDH_RSA_WITH_RC4_128_SHA + #endif + + #define BUILD_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA + #define BUILD_TLS_ECDH_ECDSA_WITH_RC4_128_SHA + #endif + #endif + #if !defined(NO_DES3) + #if !defined(NO_RSA) + #define BUILD_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA + #define BUILD_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA + #endif + + #define BUILD_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA + #define BUILD_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA + #endif +#endif + + +#if defined(BUILD_SSL_RSA_WITH_RC4_128_SHA) || \ + defined(BUILD_SSL_RSA_WITH_RC4_128_MD5) + #define BUILD_ARC4 +#endif + +#if defined(BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA) + #define BUILD_DES3 +#endif + +#if defined(BUILD_TLS_RSA_WITH_AES_128_CBC_SHA) || \ + defined(BUILD_TLS_RSA_WITH_AES_256_CBC_SHA) || \ + defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) + #undef BUILD_AES + #define BUILD_AES +#endif + +#if defined(BUILD_TLS_RSA_WITH_AES_128_GCM_SHA256) || \ + defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) + #define BUILD_AESGCM +#endif + +#if defined(BUILD_TLS_RSA_WITH_HC_128_SHA) || \ + defined(BUILD_TLS_RSA_WITH_HC_128_MD5) || \ + defined(BUILD_TLS_RSA_WITH_HC_128_B2B256) + #define BUILD_HC128 +#endif + +#if defined(BUILD_TLS_RSA_WITH_RABBIT_SHA) + #define BUILD_RABBIT +#endif + +#ifdef NO_DES3 + #define DES_BLOCK_SIZE 8 +#else + #undef BUILD_DES3 + #define BUILD_DES3 +#endif + +#ifdef NO_AES + #define AES_BLOCK_SIZE 16 +#else + #undef BUILD_AES + #define BUILD_AES +#endif + +#ifndef NO_RC4 + #undef BUILD_ARC4 + #define BUILD_ARC4 +#endif + + + +#if defined(BUILD_AESGCM) || defined(HAVE_AESCCM) + #define HAVE_AEAD +#endif + + +/* actual cipher values, 2nd byte */ +enum { + TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x39, + TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x33, + TLS_RSA_WITH_AES_256_CBC_SHA = 0x35, + TLS_RSA_WITH_AES_128_CBC_SHA = 0x2F, + TLS_RSA_WITH_NULL_SHA = 0x02, + TLS_PSK_WITH_AES_256_CBC_SHA = 0x8d, + TLS_PSK_WITH_AES_128_CBC_SHA256 = 0xae, + TLS_PSK_WITH_AES_128_CBC_SHA = 0x8c, + TLS_PSK_WITH_NULL_SHA256 = 0xb0, + TLS_PSK_WITH_NULL_SHA = 0x2c, + SSL_RSA_WITH_RC4_128_SHA = 0x05, + SSL_RSA_WITH_RC4_128_MD5 = 0x04, + SSL_RSA_WITH_3DES_EDE_CBC_SHA = 0x0A, + + /* ECC suites, first byte is 0xC0 (ECC_BYTE) */ + TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0x14, + TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0x13, + TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0x0A, + TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0x09, + TLS_ECDHE_RSA_WITH_RC4_128_SHA = 0x11, + TLS_ECDHE_ECDSA_WITH_RC4_128_SHA = 0x07, + TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x12, + TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA = 0x08, + TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = 0x27, + TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0x23, + TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = 0x28, + TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0x24, + + /* static ECDH, first byte is 0xC0 (ECC_BYTE) */ + TLS_ECDH_RSA_WITH_AES_256_CBC_SHA = 0x0F, + TLS_ECDH_RSA_WITH_AES_128_CBC_SHA = 0x0E, + TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA = 0x05, + TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA = 0x04, + TLS_ECDH_RSA_WITH_RC4_128_SHA = 0x0C, + TLS_ECDH_ECDSA_WITH_RC4_128_SHA = 0x02, + TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA = 0x0D, + TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA = 0x03, + TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 = 0x29, + TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 = 0x25, + TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 = 0x2A, + TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 = 0x26, + + /* CyaSSL extension - eSTREAM */ + TLS_RSA_WITH_HC_128_MD5 = 0xFB, + TLS_RSA_WITH_HC_128_SHA = 0xFC, + TLS_RSA_WITH_RABBIT_SHA = 0xFD, + + /* CyaSSL extension - Blake2b 256 */ + TLS_RSA_WITH_AES_128_CBC_B2B256 = 0xF8, + TLS_RSA_WITH_AES_256_CBC_B2B256 = 0xF9, + TLS_RSA_WITH_HC_128_B2B256 = 0xFA, /* eSTREAM too */ + + /* CyaSSL extension - NTRU */ + TLS_NTRU_RSA_WITH_RC4_128_SHA = 0xe5, + TLS_NTRU_RSA_WITH_3DES_EDE_CBC_SHA = 0xe6, + TLS_NTRU_RSA_WITH_AES_128_CBC_SHA = 0xe7, /* clases w/ official SHA-256 */ + TLS_NTRU_RSA_WITH_AES_256_CBC_SHA = 0xe8, + + /* SHA256 */ + TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x6b, + TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x67, + TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x3d, + TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x3c, + TLS_RSA_WITH_NULL_SHA256 = 0x3b, + + /* AES-GCM */ + TLS_RSA_WITH_AES_128_GCM_SHA256 = 0x9c, + TLS_RSA_WITH_AES_256_GCM_SHA384 = 0x9d, + TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = 0x9e, + TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = 0x9f, + + /* ECC AES-GCM, first byte is 0xC0 (ECC_BYTE) */ + TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0x2b, + TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0x2c, + TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 = 0x2d, + TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 = 0x2e, + TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0x2f, + TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0x30, + TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 = 0x31, + TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 = 0x32, + + /* AES-CCM, first byte is 0xC0 but isn't ECC, + * also, in some of the other AES-CCM suites + * there will be second byte number conflicts + * with non-ECC AES-GCM */ + TLS_RSA_WITH_AES_128_CCM_8 = 0xa0, + TLS_RSA_WITH_AES_256_CCM_8 = 0xa1, + TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 = 0xc6, /* Still TBD, made up */ + TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 = 0xc7, /* Still TBD, made up */ + TLS_PSK_WITH_AES_128_CCM = 0xa4, + TLS_PSK_WITH_AES_256_CCM = 0xa5, + TLS_PSK_WITH_AES_128_CCM_8 = 0xa8, + TLS_PSK_WITH_AES_256_CCM_8 = 0xa9, + + TLS_RSA_WITH_CAMELLIA_128_CBC_SHA = 0x41, + TLS_RSA_WITH_CAMELLIA_256_CBC_SHA = 0x84, + TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 = 0xba, + TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 = 0xc0, + TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA = 0x45, + TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA = 0x88, + TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 = 0xbe, + TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 = 0xc4, + + /* Renegotiation Indication Extension Special Suite */ + TLS_EMPTY_RENEGOTIATION_INFO_SCSV = 0xff +}; + + +enum Misc { + ECC_BYTE = 0xC0, /* ECC first cipher suite byte */ + + SEND_CERT = 1, + SEND_BLANK_CERT = 2, + + DTLS_MAJOR = 0xfe, /* DTLS major version number */ + DTLS_MINOR = 0xff, /* DTLS minor version number */ + DTLSv1_2_MINOR = 0xfd, /* DTLS minor version number */ + SSLv3_MAJOR = 3, /* SSLv3 and TLSv1+ major version number */ + SSLv3_MINOR = 0, /* TLSv1 minor version number */ + TLSv1_MINOR = 1, /* TLSv1 minor version number */ + TLSv1_1_MINOR = 2, /* TLSv1_1 minor version number */ + TLSv1_2_MINOR = 3, /* TLSv1_2 minor version number */ + INVALID_BYTE = 0xff, /* Used to initialize cipher specs values */ + NO_COMPRESSION = 0, + ZLIB_COMPRESSION = 221, /* CyaSSL zlib compression */ + HELLO_EXT_SIG_ALGO = 13, /* ID for the sig_algo hello extension */ + SECRET_LEN = 48, /* pre RSA and all master */ + ENCRYPT_LEN = 512, /* allow 4096 bit static buffer */ + SIZEOF_SENDER = 4, /* clnt or srvr */ + FINISHED_SZ = 36, /* MD5_DIGEST_SIZE + SHA_DIGEST_SIZE */ + MAX_RECORD_SIZE = 16384, /* 2^14, max size by standard */ + MAX_MSG_EXTRA = 38 + MAX_DIGEST_SIZE, + /* max added to msg, mac + pad from */ + /* RECORD_HEADER_SZ + BLOCK_SZ (pad) + Max + digest sz + BLOC_SZ (iv) + pad byte (1) */ + MAX_COMP_EXTRA = 1024, /* max compression extra */ + MAX_MTU = 1500, /* max expected MTU */ + MAX_UDP_SIZE = 8192 - 100, /* was MAX_MTU - 100 */ + MAX_DH_SZ = 612, /* 2240 p, pub, g + 2 byte size for each */ + MAX_STR_VERSION = 8, /* string rep of protocol version */ + + PAD_MD5 = 48, /* pad length for finished */ + PAD_SHA = 40, /* pad length for finished */ + MAX_PAD_SIZE = 256, /* maximum length of padding */ + COMPRESS_DUMMY_SIZE = 64, /* compression dummy round size */ + COMPRESS_CONSTANT = 13, /* compression calc constant */ + COMPRESS_UPPER = 55, /* compression calc numerator */ + COMPRESS_LOWER = 64, /* compression calc denominator */ + + PEM_LINE_LEN = 80, /* PEM line max + fudge */ + LENGTH_SZ = 2, /* length field for HMAC, data only */ + VERSION_SZ = 2, /* length of proctocol version */ + SEQ_SZ = 8, /* 64 bit sequence number */ + BYTE3_LEN = 3, /* up to 24 bit byte lengths */ + ALERT_SIZE = 2, /* level + description */ + REQUEST_HEADER = 2, /* always use 2 bytes */ + VERIFY_HEADER = 2, /* always use 2 bytes */ + EXT_ID_SZ = 2, /* always use 2 bytes */ + MAX_DH_SIZE = 513, /* 4096 bit plus possible leading 0 */ + + MAX_SUITE_SZ = 200, /* 100 suites for now! */ + RAN_LEN = 32, /* random length */ + SEED_LEN = RAN_LEN * 2, /* tls prf seed length */ + ID_LEN = 32, /* session id length */ + MAX_COOKIE_LEN = 32, /* max dtls cookie size */ + COOKIE_SZ = 20, /* use a 20 byte cookie */ + SUITE_LEN = 2, /* cipher suite sz length */ + ENUM_LEN = 1, /* always a byte */ + OPAQUE16_LEN = 2, /* always 2 bytes */ + COMP_LEN = 1, /* compression length */ + CURVE_LEN = 2, /* ecc named curve length */ + SERVER_ID_LEN = 20, /* server session id length */ + + HANDSHAKE_HEADER_SZ = 4, /* type + length(3) */ + RECORD_HEADER_SZ = 5, /* type + version + len(2) */ + CERT_HEADER_SZ = 3, /* always 3 bytes */ + REQ_HEADER_SZ = 2, /* cert request header sz */ + HINT_LEN_SZ = 2, /* length of hint size field */ + TRUNCATED_HMAC_SZ = 10, /* length of hmac w/ truncated hmac extension */ + HELLO_EXT_TYPE_SZ = 2, /* length of a hello extension type */ + HELLO_EXT_SZ = 8, /* total length of the lazy hello extensions */ + HELLO_EXT_LEN = 6, /* length of the lazy hello extensions */ + HELLO_EXT_SIGALGO_SZ = 2, /* length of signature algo extension */ + HELLO_EXT_SIGALGO_MAX = 32, /* number of items in the signature algo list */ + + DTLS_HANDSHAKE_HEADER_SZ = 12, /* normal + seq(2) + offset(3) + length(3) */ + DTLS_RECORD_HEADER_SZ = 13, /* normal + epoch(2) + seq_num(6) */ + DTLS_HANDSHAKE_EXTRA = 8, /* diff from normal */ + DTLS_RECORD_EXTRA = 8, /* diff from normal */ + DTLS_HANDSHAKE_SEQ_SZ = 2, /* handshake header sequence number */ + DTLS_HANDSHAKE_FRAG_SZ = 3, /* fragment offset and length are 24 bit */ + DTLS_POOL_SZ = 5, /* buffers to hold in the retry pool */ + + FINISHED_LABEL_SZ = 15, /* TLS finished label size */ + TLS_FINISHED_SZ = 12, /* TLS has a shorter size */ + MASTER_LABEL_SZ = 13, /* TLS master secret label sz */ + KEY_LABEL_SZ = 13, /* TLS key block expansion sz */ + MAX_PRF_HALF = 128, /* Maximum half secret len */ + MAX_PRF_LABSEED = 128, /* Maximum label + seed len */ + MAX_PRF_DIG = 224, /* Maximum digest len */ + MAX_REQUEST_SZ = 256, /* Maximum cert req len (no auth yet */ + SESSION_FLUSH_COUNT = 256, /* Flush session cache unless user turns off */ + + RC4_KEY_SIZE = 16, /* always 128bit */ + DES_KEY_SIZE = 8, /* des */ + DES3_KEY_SIZE = 24, /* 3 des ede */ + DES_IV_SIZE = DES_BLOCK_SIZE, + AES_256_KEY_SIZE = 32, /* for 256 bit */ + AES_192_KEY_SIZE = 24, /* for 192 bit */ + AES_IV_SIZE = 16, /* always block size */ + AES_128_KEY_SIZE = 16, /* for 128 bit */ + + AEAD_SEQ_OFFSET = 4, /* Auth Data: Sequence number */ + AEAD_TYPE_OFFSET = 8, /* Auth Data: Type */ + AEAD_VMAJ_OFFSET = 9, /* Auth Data: Major Version */ + AEAD_VMIN_OFFSET = 10, /* Auth Data: Minor Version */ + AEAD_LEN_OFFSET = 11, /* Auth Data: Length */ + AEAD_AUTH_DATA_SZ = 13, /* Size of the data to authenticate */ + AEAD_IMP_IV_SZ = 4, /* Size of the implicit IV */ + AEAD_EXP_IV_SZ = 8, /* Size of the explicit IV */ + AEAD_NONCE_SZ = AEAD_EXP_IV_SZ + AEAD_IMP_IV_SZ, + + AES_GCM_AUTH_SZ = 16, /* AES-GCM Auth Tag length */ + AES_CCM_16_AUTH_SZ = 16, /* AES-CCM-16 Auth Tag length */ + AES_CCM_8_AUTH_SZ = 8, /* AES-CCM-8 Auth Tag Length */ + + CAMELLIA_128_KEY_SIZE = 16, /* for 128 bit */ + CAMELLIA_192_KEY_SIZE = 24, /* for 192 bit */ + CAMELLIA_256_KEY_SIZE = 32, /* for 256 bit */ + CAMELLIA_IV_SIZE = 16, /* always block size */ + + HC_128_KEY_SIZE = 16, /* 128 bits */ + HC_128_IV_SIZE = 16, /* also 128 bits */ + + RABBIT_KEY_SIZE = 16, /* 128 bits */ + RABBIT_IV_SIZE = 8, /* 64 bits for iv */ + + EVP_SALT_SIZE = 8, /* evp salt size 64 bits */ + + ECDHE_SIZE = 32, /* ECHDE server size defaults to 256 bit */ + MAX_EXPORT_ECC_SZ = 256, /* Export ANS X9.62 max future size */ + + MAX_HELLO_SZ = 128, /* max client or server hello */ + MAX_CERT_VERIFY_SZ = 1024, /* max */ + CLIENT_HELLO_FIRST = 35, /* Protocol + RAN_LEN + sizeof(id_len) */ + MAX_SUITE_NAME = 48, /* maximum length of cipher suite string */ + DEFAULT_TIMEOUT = 500, /* default resumption timeout in seconds */ + + DTLS_TIMEOUT_INIT = 1, /* default timeout init for DTLS receive */ + DTLS_TIMEOUT_MAX = 64, /* default max timeout for DTLS receive */ + DTLS_TIMEOUT_MULTIPLIER = 2, /* default timeout multiplier for DTLS recv */ + + MAX_PSK_ID_LEN = 128, /* max psk identity/hint supported */ + MAX_PSK_KEY_LEN = 64, /* max psk key supported */ + + MAX_CYASSL_FILE_SIZE = 1024 * 1024 * 4, /* 4 mb file size alloc limit */ + +#ifdef FORTRESS + MAX_EX_DATA = 3, /* allow for three items of ex_data */ +#endif + + MAX_X509_SIZE = 2048, /* max static x509 buffer size */ + CERT_MIN_SIZE = 256, /* min PEM cert size with header/footer */ + MAX_FILENAME_SZ = 256, /* max file name length */ + FILE_BUFFER_SIZE = 1024, /* default static file buffer size for input, + will use dynamic buffer if not big enough */ + + MAX_NTRU_PUB_KEY_SZ = 1027, /* NTRU max for now */ + MAX_NTRU_ENCRYPT_SZ = 1027, /* NTRU max for now */ + MAX_NTRU_BITS = 256, /* max symmetric bit strength */ + NO_SNIFF = 0, /* not sniffing */ + SNIFF = 1, /* currently sniffing */ + + HASH_SIG_SIZE = 2, /* default SHA1 RSA */ + + NO_CAVIUM_DEVICE = -2, /* invalid cavium device id */ + + NO_COPY = 0, /* should we copy static buffer for write */ + COPY = 1 /* should we copy static buffer for write */ +}; + + +#ifdef SESSION_INDEX +/* Shift values for making a session index */ +#define SESSIDX_ROW_SHIFT 4 +#define SESSIDX_IDX_MASK 0x0F +#endif + + +/* max cert chain peer depth */ +#ifndef MAX_CHAIN_DEPTH + #define MAX_CHAIN_DEPTH 9 +#endif + + +/* don't use extra 3/4k stack space unless need to */ +#ifdef HAVE_NTRU + #define MAX_ENCRYPT_SZ MAX_NTRU_ENCRYPT_SZ +#else + #define MAX_ENCRYPT_SZ ENCRYPT_LEN +#endif + + +/* states */ +enum states { + NULL_STATE = 0, + + SERVER_HELLOVERIFYREQUEST_COMPLETE, + SERVER_HELLO_COMPLETE, + SERVER_CERT_COMPLETE, + SERVER_KEYEXCHANGE_COMPLETE, + SERVER_HELLODONE_COMPLETE, + SERVER_FINISHED_COMPLETE, + + CLIENT_HELLO_COMPLETE, + CLIENT_KEYEXCHANGE_COMPLETE, + CLIENT_FINISHED_COMPLETE, + + HANDSHAKE_DONE +}; + + +#if defined(__GNUC__) + #define CYASSL_PACK __attribute__ ((packed)) +#else + #define CYASSL_PACK +#endif + +/* SSL Version */ +typedef struct ProtocolVersion { + byte major; + byte minor; +} CYASSL_PACK ProtocolVersion; + + +CYASSL_LOCAL ProtocolVersion MakeSSLv3(void); +CYASSL_LOCAL ProtocolVersion MakeTLSv1(void); +CYASSL_LOCAL ProtocolVersion MakeTLSv1_1(void); +CYASSL_LOCAL ProtocolVersion MakeTLSv1_2(void); + +#ifdef CYASSL_DTLS + CYASSL_LOCAL ProtocolVersion MakeDTLSv1(void); + CYASSL_LOCAL ProtocolVersion MakeDTLSv1_2(void); +#endif + + +enum BIO_TYPE { + BIO_BUFFER = 1, + BIO_SOCKET = 2, + BIO_SSL = 3, + BIO_MEMORY = 4 +}; + + +/* CyaSSL BIO_METHOD type */ +struct CYASSL_BIO_METHOD { + byte type; /* method type */ +}; + + +/* CyaSSL BIO type */ +struct CYASSL_BIO { + byte type; /* method type */ + byte close; /* close flag */ + byte eof; /* eof flag */ + CYASSL* ssl; /* possible associated ssl */ + byte* mem; /* memory buffer */ + int memLen; /* memory buffer length */ + int fd; /* possible file descriptor */ + CYASSL_BIO* prev; /* previous in chain */ + CYASSL_BIO* next; /* next in chain */ +}; + + +/* CyaSSL method type */ +struct CYASSL_METHOD { + ProtocolVersion version; + byte side; /* connection side, server or client */ + byte downgrade; /* whether to downgrade version, default no */ +}; + + +/* defautls to client */ +CYASSL_LOCAL void InitSSL_Method(CYASSL_METHOD*, ProtocolVersion); + +/* for sniffer */ +CYASSL_LOCAL int DoFinished(CYASSL* ssl, const byte* input, word32* inOutIdx, + int sniff); +CYASSL_LOCAL int DoApplicationData(CYASSL* ssl, byte* input, word32* inOutIdx); + + +/* CyaSSL buffer type */ +typedef struct buffer { + word32 length; + byte* buffer; +} buffer; + + +enum { + FORCED_FREE = 1, + NO_FORCED_FREE = 0 +}; + + +/* only use compression extra if using compression */ +#ifdef HAVE_LIBZ + #define COMP_EXTRA MAX_COMP_EXTRA +#else + #define COMP_EXTRA 0 +#endif + +/* only the sniffer needs space in the buffer for extra MTU record(s) */ +#ifdef CYASSL_SNIFFER + #define MTU_EXTRA MAX_MTU * 3 +#else + #define MTU_EXTRA 0 +#endif + + +/* embedded callbacks require large static buffers, make sure on */ +#ifdef CYASSL_CALLBACKS + #undef LARGE_STATIC_BUFFERS + #define LARGE_STATIC_BUFFERS +#endif + + +/* give user option to use 16K static buffers */ +#if defined(LARGE_STATIC_BUFFERS) + #define RECORD_SIZE MAX_RECORD_SIZE +#else + #ifdef CYASSL_DTLS + #define RECORD_SIZE MAX_MTU + #else + #define RECORD_SIZE 128 + #endif +#endif + + +/* user option to turn off 16K output option */ +/* if using small static buffers (default) and SSL_write tries to write data + larger than the record we have, dynamically get it, unless user says only + write in static buffer chuncks */ +#ifndef STATIC_CHUNKS_ONLY + #define OUTPUT_RECORD_SIZE MAX_RECORD_SIZE +#else + #define OUTPUT_RECORD_SIZE RECORD_SIZE +#endif + +/* CyaSSL input buffer + + RFC 2246: + + length + The length (in bytes) of the following TLSPlaintext.fragment. + The length should not exceed 2^14. +*/ +#if defined(LARGE_STATIC_BUFFERS) + #define STATIC_BUFFER_LEN RECORD_HEADER_SZ + RECORD_SIZE + COMP_EXTRA + \ + MTU_EXTRA + MAX_MSG_EXTRA +#else + /* zero length arrays may not be supported */ + #define STATIC_BUFFER_LEN 1 +#endif + +typedef struct { + word32 length; /* total buffer length used */ + word32 idx; /* idx to part of length already consumed */ + byte* buffer; /* place holder for static or dynamic buffer */ + word32 bufferSize; /* current buffer size */ + ALIGN16 byte staticBuffer[STATIC_BUFFER_LEN]; + byte dynamicFlag; /* dynamic memory currently in use */ + byte offset; /* alignment offset attempt */ +} bufferStatic; + +/* Cipher Suites holder */ +typedef struct Suites { + int setSuites; /* user set suites from default */ + byte suites[MAX_SUITE_SZ]; + word16 suiteSz; /* suite length in bytes */ + byte hashSigAlgo[HELLO_EXT_SIGALGO_MAX]; /* sig/algo to offer */ + word16 hashSigAlgoSz; /* SigAlgo extension length in bytes */ + byte hashAlgo; /* selected hash algorithm */ + byte sigAlgo; /* selected sig algorithm */ +} Suites; + + +CYASSL_LOCAL +void InitSuites(Suites*, ProtocolVersion, + byte, byte, byte, byte, byte, byte, int); +CYASSL_LOCAL +int SetCipherList(Suites*, const char* list); + +#ifndef PSK_TYPES_DEFINED + typedef unsigned int (*psk_client_callback)(CYASSL*, const char*, char*, + unsigned int, unsigned char*, unsigned int); + typedef unsigned int (*psk_server_callback)(CYASSL*, const char*, + unsigned char*, unsigned int); +#endif /* PSK_TYPES_DEFINED */ + + +#ifndef CYASSL_USER_IO + /* default IO callbacks */ + CYASSL_LOCAL + int EmbedReceive(CYASSL *ssl, char *buf, int sz, void *ctx); + CYASSL_LOCAL + int EmbedSend(CYASSL *ssl, char *buf, int sz, void *ctx); + + #ifdef HAVE_OCSP + CYASSL_LOCAL + int EmbedOcspLookup(void*, const char*, int, byte*, int, byte**); + CYASSL_LOCAL + void EmbedOcspRespFree(void*, byte*); + #endif + + #ifdef CYASSL_DTLS + CYASSL_LOCAL + int EmbedReceiveFrom(CYASSL *ssl, char *buf, int sz, void *ctx); + CYASSL_LOCAL + int EmbedSendTo(CYASSL *ssl, char *buf, int sz, void *ctx); + CYASSL_LOCAL + int EmbedGenerateCookie(CYASSL* ssl, byte *buf, int sz, void *ctx); + CYASSL_LOCAL + int IsUDP(void*); + #endif /* CYASSL_DTLS */ +#endif /* CYASSL_USER_IO */ + +#ifdef HAVE_NETX + CYASSL_LOCAL int NetX_Receive(CYASSL *ssl, char *buf, int sz, void *ctx); + CYASSL_LOCAL int NetX_Send(CYASSL *ssl, char *buf, int sz, void *ctx); +#endif /* HAVE_NETX */ + + +/* CyaSSL Cipher type just points back to SSL */ +struct CYASSL_CIPHER { + CYASSL* ssl; +}; + + +typedef struct OCSP_Entry OCSP_Entry; + +#ifdef SHA_DIGEST_SIZE + #define OCSP_DIGEST_SIZE SHA_DIGEST_SIZE +#else + #define OCSP_DIGEST_SIZE 160 +#endif + +#ifdef NO_ASN + /* no_asn won't have */ + typedef struct CertStatus CertStatus; +#endif + +struct OCSP_Entry { + OCSP_Entry* next; /* next entry */ + byte issuerHash[OCSP_DIGEST_SIZE]; /* issuer hash */ + byte issuerKeyHash[OCSP_DIGEST_SIZE]; /* issuer public key hash */ + CertStatus* status; /* OCSP response list */ + int totalStatus; /* number on list */ +}; + + +#ifndef HAVE_OCSP + typedef struct CYASSL_OCSP CYASSL_OCSP; +#endif + +/* CyaSSL OCSP controller */ +struct CYASSL_OCSP { + CYASSL_CERT_MANAGER* cm; /* pointer back to cert manager */ + OCSP_Entry* ocspList; /* OCSP response list */ +}; + +#ifndef MAX_DATE_SIZE +#define MAX_DATE_SIZE 32 +#endif + +typedef struct CRL_Entry CRL_Entry; + +#ifdef SHA_DIGEST_SIZE + #define CRL_DIGEST_SIZE SHA_DIGEST_SIZE +#else + #define CRL_DIGEST_SIZE 160 +#endif + +#ifdef NO_ASN + typedef struct RevokedCert RevokedCert; +#endif + +/* Complete CRL */ +struct CRL_Entry { + CRL_Entry* next; /* next entry */ + byte issuerHash[CRL_DIGEST_SIZE]; /* issuer hash */ + /* byte crlHash[CRL_DIGEST_SIZE]; raw crl data hash */ + /* restore the hash here if needed for optimized comparisons */ + byte lastDate[MAX_DATE_SIZE]; /* last date updated */ + byte nextDate[MAX_DATE_SIZE]; /* next update date */ + byte lastDateFormat; /* last date format */ + byte nextDateFormat; /* next date format */ + RevokedCert* certs; /* revoked cert list */ + int totalCerts; /* number on list */ +}; + + +typedef struct CRL_Monitor CRL_Monitor; + +/* CRL directory monitor */ +struct CRL_Monitor { + char* path; /* full dir path, if valid pointer we're using */ + int type; /* PEM or ASN1 type */ +}; + + +#ifndef HAVE_CRL + typedef struct CYASSL_CRL CYASSL_CRL; +#endif + +/* CyaSSL CRL controller */ +struct CYASSL_CRL { + CYASSL_CERT_MANAGER* cm; /* pointer back to cert manager */ + CRL_Entry* crlList; /* our CRL list */ + CyaSSL_Mutex crlLock; /* CRL list lock */ + CRL_Monitor monitors[2]; /* PEM and DER possible */ +#ifdef HAVE_CRL_MONITOR + pthread_t tid; /* monitoring thread */ +#endif +}; + + +#ifdef NO_ASN + typedef struct Signer Signer; +#endif + + +#ifndef CA_TABLE_SIZE + #define CA_TABLE_SIZE 11 +#endif + +/* CyaSSL Certificate Manager */ +struct CYASSL_CERT_MANAGER { + Signer* caTable[CA_TABLE_SIZE]; /* the CA signer table */ + CyaSSL_Mutex caLock; /* CA list lock */ + CallbackCACache caCacheCallback; /* CA cache addition callback */ + void* heap; /* heap helper */ + CYASSL_CRL* crl; /* CRL checker */ + byte crlEnabled; /* is CRL on ? */ + byte crlCheckAll; /* always leaf, but all ? */ + CbMissingCRL cbMissingCRL; /* notify through cb of missing crl */ + CYASSL_OCSP* ocsp; /* OCSP checker */ + byte ocspEnabled; /* is OCSP on ? */ + byte ocspSendNonce; /* send the OCSP nonce ? */ + byte ocspUseOverrideURL; /* ignore cert's responder, override */ + char* ocspOverrideURL; /* use this responder */ + void* ocspIOCtx; /* I/O callback CTX */ + CbOCSPIO ocspIOCb; /* I/O callback for OCSP lookup */ + CbOCSPRespFree ocspRespFreeCb; /* Frees OCSP Response from IO Cb */ +}; + +CYASSL_LOCAL int CM_SaveCertCache(CYASSL_CERT_MANAGER*, const char*); +CYASSL_LOCAL int CM_RestoreCertCache(CYASSL_CERT_MANAGER*, const char*); +CYASSL_LOCAL int CM_MemSaveCertCache(CYASSL_CERT_MANAGER*, void*, int, int*); +CYASSL_LOCAL int CM_MemRestoreCertCache(CYASSL_CERT_MANAGER*, const void*, int); +CYASSL_LOCAL int CM_GetCertCacheMemSize(CYASSL_CERT_MANAGER*); + +/* CyaSSL Sock Addr */ +struct CYASSL_SOCKADDR { + unsigned int sz; /* sockaddr size */ + void* sa; /* pointer to the sockaddr_in or sockaddr_in6 */ +}; + +typedef struct CYASSL_DTLS_CTX { + CYASSL_SOCKADDR peer; + int fd; +} CYASSL_DTLS_CTX; + +/* RFC 6066 TLS Extensions */ +#ifdef HAVE_TLS_EXTENSIONS + +typedef enum { + SERVER_NAME_INDICATION = 0, + MAX_FRAGMENT_LENGTH = 1, + /*CLIENT_CERTIFICATE_URL = 2, + TRUSTED_CA_KEYS = 3,*/ + TRUNCATED_HMAC = 4, + /*STATUS_REQUEST = 5, + SIGNATURE_ALGORITHMS = 13,*/ +} TLSX_Type; + +typedef struct TLSX { + TLSX_Type type; /* Extension Type */ + void* data; /* Extension Data */ + byte resp; /* IsResponse Flag */ + struct TLSX* next; /* List Behavior */ +} TLSX; + +CYASSL_LOCAL TLSX* TLSX_Find(TLSX* list, TLSX_Type type); +CYASSL_LOCAL void TLSX_FreeAll(TLSX* list); + +#ifndef NO_CYASSL_CLIENT +CYASSL_LOCAL word16 TLSX_GetRequestSize(CYASSL* ssl); +CYASSL_LOCAL word16 TLSX_WriteRequest(CYASSL* ssl, byte* output); +#endif + +#ifndef NO_CYASSL_SERVER +CYASSL_LOCAL word16 TLSX_GetResponseSize(CYASSL* ssl); +CYASSL_LOCAL word16 TLSX_WriteResponse(CYASSL* ssl, byte* output); +#endif + +CYASSL_LOCAL int TLSX_Parse(CYASSL* ssl, byte* input, word16 length, + byte isRequest, Suites *suites); + +/* Server Name Indication */ +#ifdef HAVE_SNI + +typedef struct SNI { + byte type; /* SNI Type */ + union { char* host_name; } data; /* SNI Data */ + struct SNI* next; /* List Behavior */ +#ifndef NO_CYASSL_SERVER + byte options; /* Behaviour options */ + byte status; /* Matching result */ +#endif +} SNI; + +CYASSL_LOCAL int TLSX_UseSNI(TLSX** extensions, byte type, const void* data, + word16 size); + +#ifndef NO_CYASSL_SERVER +CYASSL_LOCAL void TLSX_SNI_SetOptions(TLSX* extensions, byte type, + byte options); +CYASSL_LOCAL byte TLSX_SNI_Status(TLSX* extensions, byte type); +CYASSL_LOCAL word16 TLSX_SNI_GetRequest(TLSX* extensions, byte type, + void** data); +CYASSL_LOCAL int TLSX_SNI_GetFromBuffer(const byte* buffer, word32 bufferSz, + byte type, byte* sni, word32* inOutSz); +#endif + +#endif /* HAVE_SNI */ + +/* Maximum Fragment Length */ +#ifdef HAVE_MAX_FRAGMENT + +CYASSL_LOCAL int TLSX_UseMaxFragment(TLSX** extensions, byte mfl); + +#endif /* HAVE_MAX_FRAGMENT */ + +#ifdef HAVE_TRUNCATED_HMAC + +CYASSL_LOCAL int TLSX_UseTruncatedHMAC(TLSX** extensions); + +#endif /* HAVE_TRUNCATED_HMAC */ + +#endif /* HAVE_TLS_EXTENSIONS */ + +/* CyaSSL context type */ +struct CYASSL_CTX { + CYASSL_METHOD* method; + CyaSSL_Mutex countMutex; /* reference count mutex */ + int refCount; /* reference count */ +#ifndef NO_CERTS + buffer certificate; + buffer certChain; + /* chain after self, in DER, with leading size for each cert */ + buffer privateKey; + buffer serverDH_P; + buffer serverDH_G; + CYASSL_CERT_MANAGER* cm; /* our cert manager, ctx owns SSL will use */ +#endif + Suites suites; + void* heap; /* for user memory overrides */ + byte verifyPeer; + byte verifyNone; + byte failNoCert; + byte sessionCacheOff; + byte sessionCacheFlushOff; + byte sendVerify; /* for client side */ + byte haveRSA; /* RSA available */ + byte haveDH; /* server DH parms set by user */ + byte haveNTRU; /* server private NTRU key loaded */ + byte haveECDSAsig; /* server cert signed w/ ECDSA */ + byte haveStaticECC; /* static server ECC private key */ + byte partialWrite; /* only one msg per write call */ + byte quietShutdown; /* don't send close notify */ + byte groupMessages; /* group handshake messages before sending */ + CallbackIORecv CBIORecv; + CallbackIOSend CBIOSend; +#ifdef CYASSL_DTLS + CallbackGenCookie CBIOCookie; /* gen cookie callback */ +#endif + VerifyCallback verifyCallback; /* cert verification callback */ + word32 timeout; /* session timeout */ +#ifdef HAVE_ECC + word16 eccTempKeySz; /* in octets 20 - 66 */ +#endif +#ifndef NO_PSK + byte havePSK; /* psk key set by user */ + psk_client_callback client_psk_cb; /* client callback */ + psk_server_callback server_psk_cb; /* server callback */ + char server_hint[MAX_PSK_ID_LEN]; +#endif /* NO_PSK */ +#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) + pem_password_cb passwd_cb; + void* userdata; +#endif /* OPENSSL_EXTRA */ +#ifdef HAVE_OCSP + CYASSL_OCSP ocsp; +#endif +#ifdef HAVE_CAVIUM + int devId; /* cavium device id to use */ +#endif +#ifdef HAVE_TLS_EXTENSIONS + TLSX* extensions; /* RFC 6066 TLS Extensions data */ +#endif +#ifdef ATOMIC_USER + CallbackMacEncrypt MacEncryptCb; /* Atomic User Mac/Encrypt Cb */ + CallbackDecryptVerify DecryptVerifyCb; /* Atomic User Decrypt/Verify Cb */ +#endif +#ifdef HAVE_PK_CALLBACKS + #ifdef HAVE_ECC + CallbackEccSign EccSignCb; /* User EccSign Callback handler */ + CallbackEccVerify EccVerifyCb; /* User EccVerify Callback handler */ + #endif /* HAVE_ECC */ + #ifndef NO_RSA + CallbackRsaSign RsaSignCb; /* User RsaSign Callback handler */ + CallbackRsaVerify RsaVerifyCb; /* User RsaVerify Callback handler */ + CallbackRsaEnc RsaEncCb; /* User Rsa Public Encrypt handler */ + CallbackRsaDec RsaDecCb; /* User Rsa Private Decrypt handler */ + #endif /* NO_RSA */ +#endif /* HAVE_PK_CALLBACKS */ +}; + + +CYASSL_LOCAL +int InitSSL_Ctx(CYASSL_CTX*, CYASSL_METHOD*); +CYASSL_LOCAL +void FreeSSL_Ctx(CYASSL_CTX*); +CYASSL_LOCAL +void SSL_CtxResourceFree(CYASSL_CTX*); + +CYASSL_LOCAL +int DeriveTlsKeys(CYASSL* ssl); +CYASSL_LOCAL +int ProcessOldClientHello(CYASSL* ssl, const byte* input, word32* inOutIdx, + word32 inSz, word16 sz); +#ifndef NO_CERTS + CYASSL_LOCAL + int AddCA(CYASSL_CERT_MANAGER* ctx, buffer der, int type, int verify); + CYASSL_LOCAL + int AlreadySigner(CYASSL_CERT_MANAGER* cm, byte* hash); +#endif + +/* All cipher suite related info */ +typedef struct CipherSpecs { + byte bulk_cipher_algorithm; + byte cipher_type; /* block, stream, or aead */ + byte mac_algorithm; + byte kea; /* key exchange algo */ + byte sig_algo; + byte hash_size; + byte pad_size; + byte static_ecdh; + word16 key_size; + word16 iv_size; + word16 block_size; + word16 aead_mac_size; +} CipherSpecs; + + +void InitCipherSpecs(CipherSpecs* cs); + + +/* Supported Message Authentication Codes from page 43 */ +enum MACAlgorithm { + no_mac, + md5_mac, + sha_mac, + sha224_mac, + sha256_mac, + sha384_mac, + sha512_mac, + rmd_mac, + blake2b_mac +}; + + +/* Supported Key Exchange Protocols */ +enum KeyExchangeAlgorithm { + no_kea, + rsa_kea, + diffie_hellman_kea, + fortezza_kea, + psk_kea, + ntru_kea, + ecc_diffie_hellman_kea, + ecc_static_diffie_hellman_kea /* for verify suite only */ +}; + + +/* Supported Authentication Schemes */ +enum SignatureAlgorithm { + anonymous_sa_algo, + rsa_sa_algo, + dsa_sa_algo, + ecc_dsa_sa_algo +}; + + +/* Supprted ECC Curve Types */ +enum EccCurves { + named_curve = 3 +}; + + +/* Supprted ECC Named Curves */ +enum EccNamedCurves { + secp256r1 = 0x17, /* default, OpenSSL also calls it prime256v1 */ + secp384r1 = 0x18, + secp521r1 = 0x19, + + secp160r1 = 0x10, + secp192r1 = 0x13, /* Openssl also call it prime192v1 */ + secp224r1 = 0x15 +}; + + +/* Valid client certificate request types from page 27 */ +enum ClientCertificateType { + rsa_sign = 1, + dss_sign = 2, + rsa_fixed_dh = 3, + dss_fixed_dh = 4, + rsa_ephemeral_dh = 5, + dss_ephemeral_dh = 6, + fortezza_kea_cert = 20 +}; + + +enum CipherType { stream, block, aead }; + + +#ifdef CYASSL_DTLS + + #ifdef WORD64_AVAILABLE + typedef word64 DtlsSeq; + #else + typedef word32 DtlsSeq; + #endif + #define DTLS_SEQ_BITS (sizeof(DtlsSeq) * CHAR_BIT) + + typedef struct DtlsState { + DtlsSeq window; /* Sliding window for current epoch */ + word16 nextEpoch; /* Expected epoch in next record */ + word32 nextSeq; /* Expected sequence in next record */ + + word16 curEpoch; /* Received epoch in current record */ + word32 curSeq; /* Received sequence in current record */ + + DtlsSeq prevWindow; /* Sliding window for old epoch */ + word32 prevSeq; /* Next sequence in allowed old epoch */ + } DtlsState; + +#endif /* CYASSL_DTLS */ + + +/* keys and secrets */ +typedef struct Keys { + byte client_write_MAC_secret[MAX_DIGEST_SIZE]; /* max sizes */ + byte server_write_MAC_secret[MAX_DIGEST_SIZE]; + byte client_write_key[AES_256_KEY_SIZE]; /* max sizes */ + byte server_write_key[AES_256_KEY_SIZE]; + byte client_write_IV[AES_IV_SIZE]; /* max sizes */ + byte server_write_IV[AES_IV_SIZE]; +#ifdef HAVE_AEAD + byte aead_exp_IV[AEAD_EXP_IV_SZ]; + byte aead_enc_imp_IV[AEAD_IMP_IV_SZ]; + byte aead_dec_imp_IV[AEAD_IMP_IV_SZ]; +#endif + + word32 peer_sequence_number; + word32 sequence_number; + +#ifdef CYASSL_DTLS + DtlsState dtls_state; /* Peer's state */ + word16 dtls_peer_handshake_number; + word16 dtls_expected_peer_handshake_number; + + word16 dtls_epoch; /* Current tx epoch */ + word32 dtls_sequence_number; /* Current tx sequence */ + word16 dtls_handshake_number; /* Current tx handshake seq */ +#endif + + word32 encryptSz; /* last size of encrypted data */ + word32 padSz; /* how much to advance after decrypt part */ + byte encryptionOn; /* true after change cipher spec */ + byte decryptedCur; /* only decrypt current record once */ +} Keys; + + +/* cipher for now */ +typedef struct Ciphers { +#ifdef BUILD_ARC4 + Arc4* arc4; +#endif +#ifdef BUILD_DES3 + Des3* des3; +#endif +#if defined(BUILD_AES) || defined(BUILD_AESGCM) + Aes* aes; +#endif +#ifdef HAVE_CAMELLIA + Camellia* cam; +#endif +#ifdef HAVE_HC128 + HC128* hc128; +#endif +#ifdef BUILD_RABBIT + Rabbit* rabbit; +#endif + byte setup; /* have we set it up flag for detection */ +} Ciphers; + + +CYASSL_LOCAL void InitCiphers(CYASSL* ssl); +CYASSL_LOCAL void FreeCiphers(CYASSL* ssl); + + +/* hashes type */ +typedef struct Hashes { + #ifndef NO_OLD_TLS + byte md5[MD5_DIGEST_SIZE]; + #endif + byte sha[SHA_DIGEST_SIZE]; + #ifndef NO_SHA256 + byte sha256[SHA256_DIGEST_SIZE]; + #endif + #ifdef CYASSL_SHA384 + byte sha384[SHA384_DIGEST_SIZE]; + #endif +} Hashes; + + +/* Static x509 buffer */ +typedef struct x509_buffer { + int length; /* actual size */ + byte buffer[MAX_X509_SIZE]; /* max static cert size */ +} x509_buffer; + + +/* CyaSSL X509_CHAIN, for no dynamic memory SESSION_CACHE */ +struct CYASSL_X509_CHAIN { + int count; /* total number in chain */ + x509_buffer certs[MAX_CHAIN_DEPTH]; /* only allow max depth 4 for now */ +}; + + +/* CyaSSL session type */ +struct CYASSL_SESSION { + byte sessionID[ID_LEN]; /* id for protocol */ + byte masterSecret[SECRET_LEN]; /* stored secret */ + word32 bornOn; /* create time in seconds */ + word32 timeout; /* timeout in seconds */ +#ifdef SESSION_CERTS + CYASSL_X509_CHAIN chain; /* peer cert chain, static */ + ProtocolVersion version; /* which version was used */ + byte cipherSuite0; /* first byte, normally 0 */ + byte cipherSuite; /* 2nd byte, actual suite */ +#endif +#ifndef NO_CLIENT_CACHE + byte serverID[SERVER_ID_LEN]; /* for easier client lookup */ + word16 idLen; /* serverID length */ +#endif +}; + + +CYASSL_LOCAL +CYASSL_SESSION* GetSession(CYASSL*, byte*); +CYASSL_LOCAL +int SetSession(CYASSL*, CYASSL_SESSION*); + +typedef void (*hmacfp) (CYASSL*, byte*, const byte*, word32, int, int); + +#ifndef NO_CLIENT_CACHE + CYASSL_SESSION* GetSessionClient(CYASSL*, const byte*, int); +#endif + +/* client connect state for nonblocking restart */ +enum ConnectState { + CONNECT_BEGIN = 0, + CLIENT_HELLO_SENT, + HELLO_AGAIN, /* HELLO_AGAIN s for DTLS case */ + HELLO_AGAIN_REPLY, + FIRST_REPLY_DONE, + FIRST_REPLY_FIRST, + FIRST_REPLY_SECOND, + FIRST_REPLY_THIRD, + FIRST_REPLY_FOURTH, + FINISHED_DONE, + SECOND_REPLY_DONE +}; + + +/* server accept state for nonblocking restart */ +enum AcceptState { + ACCEPT_BEGIN = 0, + ACCEPT_CLIENT_HELLO_DONE, + HELLO_VERIFY_SENT, + ACCEPT_FIRST_REPLY_DONE, + SERVER_HELLO_SENT, + CERT_SENT, + KEY_EXCHANGE_SENT, + CERT_REQ_SENT, + SERVER_HELLO_DONE, + ACCEPT_SECOND_REPLY_DONE, + CHANGE_CIPHER_SENT, + ACCEPT_FINISHED_DONE, + ACCEPT_THIRD_REPLY_DONE +}; + + +typedef struct Buffers { +#ifndef NO_CERTS + buffer certificate; /* CYASSL_CTX owns, unless we own */ + buffer key; /* CYASSL_CTX owns, unless we own */ + buffer certChain; /* CYASSL_CTX owns */ + /* chain after self, in DER, with leading size for each cert */ + buffer serverDH_P; /* CYASSL_CTX owns, unless we own */ + buffer serverDH_G; /* CYASSL_CTX owns, unless we own */ + buffer serverDH_Pub; + buffer serverDH_Priv; +#endif + buffer domainName; /* for client check */ + bufferStatic inputBuffer; + bufferStatic outputBuffer; + buffer clearOutputBuffer; + int prevSent; /* previous plain text bytes sent + when got WANT_WRITE */ + int plainSz; /* plain text bytes in buffer to send + when got WANT_WRITE */ + byte weOwnCert; /* SSL own cert flag */ + byte weOwnKey; /* SSL own key flag */ + byte weOwnDH; /* SSL own dh (p,g) flag */ +#ifdef CYASSL_DTLS + CYASSL_DTLS_CTX dtlsCtx; /* DTLS connection context */ +#endif +#ifdef HAVE_PK_CALLBACKS + #ifdef HAVE_ECC + buffer peerEccDsaKey; /* we own for Ecc Verify Callbacks */ + #endif /* HAVE_ECC */ + #ifndef NO_RSA + buffer peerRsaKey; /* we own for Rsa Verify Callbacks */ + #endif /* NO_RSA */ +#endif /* HAVE_PK_CALLBACKS */ +} Buffers; + +typedef struct Options { + byte sessionCacheOff; + byte sessionCacheFlushOff; + byte cipherSuite0; /* first byte, normally 0 */ + byte cipherSuite; /* second byte, actual suite */ + byte serverState; + byte clientState; + byte handShakeState; + byte side; /* client or server end */ + byte verifyPeer; + byte verifyNone; + byte failNoCert; + byte downgrade; /* allow downgrade of versions */ + byte sendVerify; /* false = 0, true = 1, sendBlank = 2 */ + byte resuming; + byte haveSessionId; /* server may not send */ + byte tls; /* using TLS ? */ + byte tls1_1; /* using TLSv1.1+ ? */ + byte dtls; /* using datagrams ? */ + byte connReset; /* has the peer reset */ + byte isClosed; /* if we consider conn closed */ + byte closeNotify; /* we've recieved a close notify */ + byte sentNotify; /* we've sent a close notify */ + byte connectState; /* nonblocking resume */ + byte acceptState; /* nonblocking resume */ + byte usingCompression; /* are we using compression */ + byte haveRSA; /* RSA available */ + byte haveDH; /* server DH parms set by user */ + byte haveNTRU; /* server NTRU private key loaded */ + byte haveECDSAsig; /* server ECDSA signed cert */ + byte haveStaticECC; /* static server ECC private key */ + byte havePeerCert; /* do we have peer's cert */ + byte havePeerVerify; /* and peer's cert verify */ + byte usingPSK_cipher; /* whether we're using psk as cipher */ + byte sendAlertState; /* nonblocking resume */ + byte processReply; /* nonblocking resume */ + byte partialWrite; /* only one msg per write call */ + byte quietShutdown; /* don't send close notify */ + byte certOnly; /* stop once we get cert */ + byte groupMessages; /* group handshake messages */ + byte usingNonblock; /* set when using nonblocking socket */ + byte saveArrays; /* save array Memory for user get keys + or psk */ +#ifndef NO_PSK + byte havePSK; /* psk key set by user */ + psk_client_callback client_psk_cb; + psk_server_callback server_psk_cb; +#endif /* NO_PSK */ +} Options; + +typedef struct Arrays { + byte clientRandom[RAN_LEN]; + byte serverRandom[RAN_LEN]; + byte sessionID[ID_LEN]; + byte preMasterSecret[ENCRYPT_LEN]; + byte masterSecret[SECRET_LEN]; +#ifdef CYASSL_DTLS + byte cookie[MAX_COOKIE_LEN]; + byte cookieSz; +#endif +#ifndef NO_PSK + char client_identity[MAX_PSK_ID_LEN]; + char server_hint[MAX_PSK_ID_LEN]; + byte psk_key[MAX_PSK_KEY_LEN]; + word32 psk_keySz; /* acutal size */ +#endif + word32 preMasterSz; /* differs for DH, actual size */ +} Arrays; + +#ifndef ASN_NAME_MAX +#define ASN_NAME_MAX 256 +#endif + +#ifndef MAX_DATE_SZ +#define MAX_DATE_SZ 32 +#endif + +struct CYASSL_X509_NAME { + char *name; + char staticName[ASN_NAME_MAX]; + int dynamicName; + int sz; +#ifdef OPENSSL_EXTRA + DecodedName fullName; +#endif /* OPENSSL_EXTRA */ +}; + +#ifndef EXTERNAL_SERIAL_SIZE + #define EXTERNAL_SERIAL_SIZE 32 +#endif + +#ifdef NO_ASN + typedef struct DNS_entry DNS_entry; +#endif + +struct CYASSL_X509 { + int version; + CYASSL_X509_NAME issuer; + CYASSL_X509_NAME subject; + int serialSz; + byte serial[EXTERNAL_SERIAL_SIZE]; + char subjectCN[ASN_NAME_MAX]; /* common name short cut */ +#ifdef CYASSL_SEP + int deviceTypeSz; + byte deviceType[EXTERNAL_SERIAL_SIZE]; + int hwTypeSz; + byte hwType[EXTERNAL_SERIAL_SIZE]; + int hwSerialNumSz; + byte hwSerialNum[EXTERNAL_SERIAL_SIZE]; + #ifdef OPENSSL_EXTRA + byte certPolicySet; + byte certPolicyCrit; + #endif /* OPENSSL_EXTRA */ +#endif + int notBeforeSz; + byte notBefore[MAX_DATE_SZ]; + int notAfterSz; + byte notAfter[MAX_DATE_SZ]; + int sigOID; + buffer sig; + int pubKeyOID; + buffer pubKey; + #ifdef HAVE_ECC + word32 pkCurveOID; + #endif /* HAVE_ECC */ + buffer derCert; /* may need */ + DNS_entry* altNames; /* alt names list */ + DNS_entry* altNamesNext; /* hint for retrieval */ + byte dynamicMemory; /* dynamic memory flag */ + byte isCa; +#ifdef OPENSSL_EXTRA + word32 pathLength; + word16 keyUsage; + byte basicConstSet; + byte basicConstCrit; + byte basicConstPlSet; + byte subjAltNameSet; + byte subjAltNameCrit; + byte authKeyIdSet; + byte authKeyIdCrit; + byte* authKeyId; + word32 authKeyIdSz; + byte subjKeyIdSet; + byte subjKeyIdCrit; + byte* subjKeyId; + word32 subjKeyIdSz; + byte keyUsageSet; + byte keyUsageCrit; +#endif /* OPENSSL_EXTRA */ +}; + + +/* record layer header for PlainText, Compressed, and CipherText */ +typedef struct RecordLayerHeader { + byte type; + byte pvMajor; + byte pvMinor; + byte length[2]; +} RecordLayerHeader; + + +/* record layer header for DTLS PlainText, Compressed, and CipherText */ +typedef struct DtlsRecordLayerHeader { + byte type; + byte pvMajor; + byte pvMinor; + byte epoch[2]; /* increment on cipher state change */ + byte sequence_number[6]; /* per record */ + byte length[2]; +} DtlsRecordLayerHeader; + + +typedef struct DtlsPool { + buffer buf[DTLS_POOL_SZ]; + int used; +} DtlsPool; + +typedef struct DtlsMsg { + struct DtlsMsg* next; + word32 seq; /* Handshake sequence number */ + word32 sz; /* Length of whole mesage */ + word32 fragSz; /* Length of fragments received */ + byte type; + byte* buf; + byte* msg; +} DtlsMsg; + + +#ifdef HAVE_NETX + + /* NETX I/O Callback default */ + typedef struct NetX_Ctx { + NX_TCP_SOCKET* nxSocket; /* send/recv socket handle */ + NX_PACKET* nxPacket; /* incoming packet handle for short reads */ + ULONG nxOffset; /* offset already read from nxPacket */ + ULONG nxWait; /* wait option flag */ + } NetX_Ctx; + +#endif + + +/* CyaSSL ssl type */ +struct CYASSL { + CYASSL_CTX* ctx; + int error; + ProtocolVersion version; /* negotiated version */ + ProtocolVersion chVersion; /* client hello version */ + Suites* suites; /* only need during handshake */ + Ciphers encrypt; + Ciphers decrypt; + CipherSpecs specs; + Keys keys; + int rfd; /* read file descriptor */ + int wfd; /* write file descriptor */ + int rflags; /* user read flags */ + int wflags; /* user write flags */ + CYASSL_BIO* biord; /* socket bio read to free/close */ + CYASSL_BIO* biowr; /* socket bio write to free/close */ + void* IOCB_ReadCtx; + void* IOCB_WriteCtx; + RNG* rng; +#ifndef NO_OLD_TLS +#ifndef NO_SHA + Sha hashSha; /* sha hash of handshake msgs */ +#endif +#ifndef NO_MD5 + Md5 hashMd5; /* md5 hash of handshake msgs */ +#endif +#endif +#ifndef NO_SHA256 + Sha256 hashSha256; /* sha256 hash of handshake msgs */ +#endif +#ifdef CYASSL_SHA384 + Sha384 hashSha384; /* sha384 hash of handshake msgs */ +#endif + Hashes verifyHashes; + Hashes certHashes; /* for cert verify */ + Buffers buffers; + Options options; + Arrays* arrays; + CYASSL_SESSION session; + VerifyCallback verifyCallback; /* cert verification callback */ + void* verifyCbCtx; /* cert verify callback user ctx*/ +#ifndef NO_RSA + RsaKey* peerRsaKey; + byte peerRsaKeyPresent; +#endif +#ifdef HAVE_NTRU + word16 peerNtruKeyLen; + byte peerNtruKey[MAX_NTRU_PUB_KEY_SZ]; + byte peerNtruKeyPresent; +#endif +#ifdef HAVE_ECC + ecc_key* peerEccKey; /* peer's ECDHE key */ + ecc_key* peerEccDsaKey; /* peer's ECDSA key */ + ecc_key* eccTempKey; /* private ECDHE key */ + ecc_key* eccDsaKey; /* private ECDSA key */ + word16 eccTempKeySz; /* in octets 20 - 66 */ + byte peerEccKeyPresent; + byte peerEccDsaKeyPresent; + byte eccTempKeyPresent; + byte eccDsaKeyPresent; +#endif + hmacfp hmac; + void* heap; /* for user overrides */ + RecordLayerHeader curRL; + word16 curSize; + word32 timeout; /* session timeout */ + CYASSL_CIPHER cipher; +#ifdef HAVE_LIBZ + z_stream c_stream; /* compression stream */ + z_stream d_stream; /* decompression stream */ + byte didStreamInit; /* for stream init and end */ +#endif +#ifdef CYASSL_DTLS + int dtls_timeout_init; /* starting timeout vaule */ + int dtls_timeout_max; /* maximum timeout value */ + int dtls_timeout; /* current timeout value, changes */ + DtlsPool* dtls_pool; + DtlsMsg* dtls_msg_list; + void* IOCB_CookieCtx; /* gen cookie ctx */ + word32 dtls_expected_rx; +#endif +#ifdef CYASSL_CALLBACKS + HandShakeInfo handShakeInfo; /* info saved during handshake */ + TimeoutInfo timeoutInfo; /* info saved during handshake */ + byte hsInfoOn; /* track handshake info */ + byte toInfoOn; /* track timeout info */ +#endif +#ifdef KEEP_PEER_CERT + CYASSL_X509 peerCert; /* X509 peer cert */ +#endif +#ifdef FORTRESS + void* ex_data[MAX_EX_DATA]; /* external data, for Fortress */ +#endif +#ifdef HAVE_CAVIUM + int devId; /* cavium device id to use */ +#endif +#ifdef HAVE_TLS_EXTENSIONS + TLSX* extensions; /* RFC 6066 TLS Extensions data */ +#ifdef HAVE_MAX_FRAGMENT + word16 max_fragment; +#endif +#ifdef HAVE_TRUNCATED_HMAC + byte truncated_hmac; +#endif +#endif +#ifdef HAVE_NETX + NetX_Ctx nxCtx; /* NetX IO Context */ +#endif +#ifdef SESSION_INDEX + int sessionIndex; /* Session's location in the cache. */ +#endif + CYASSL_ALERT_HISTORY alert_history; +#ifdef ATOMIC_USER + void* MacEncryptCtx; /* Atomic User Mac/Encrypt Callback Context */ + void* DecryptVerifyCtx; /* Atomic User Decrypt/Verify Callback Context */ +#endif +#ifdef HAVE_PK_CALLBACKS + #ifdef HAVE_ECC + void* EccSignCtx; /* Ecc Sign Callback Context */ + void* EccVerifyCtx; /* Ecc Verify Callback Context */ + #endif /* HAVE_ECC */ + #ifndef NO_RSA + void* RsaSignCtx; /* Rsa Sign Callback Context */ + void* RsaVerifyCtx; /* Rsa Verify Callback Context */ + void* RsaEncCtx; /* Rsa Public Encrypt Callback Context */ + void* RsaDecCtx; /* Rsa Private Decrypt Callback Context */ + #endif /* NO_RSA */ +#endif /* HAVE_PK_CALLBACKS */ +}; + + +CYASSL_LOCAL +int InitSSL(CYASSL*, CYASSL_CTX*); +CYASSL_LOCAL +void FreeSSL(CYASSL*); +CYASSL_API void SSL_ResourceFree(CYASSL*); /* Micrium uses */ + + +enum { + IV_SZ = 32, /* max iv sz */ + NAME_SZ = 80 /* max one line */ +}; + + +typedef struct EncryptedInfo { + char name[NAME_SZ]; /* encryption name */ + byte iv[IV_SZ]; /* encrypted IV */ + word32 ivSz; /* encrypted IV size */ + long consumed; /* tracks PEM bytes consumed */ + byte set; /* if encryption set */ + CYASSL_CTX* ctx; /* CTX owner */ +} EncryptedInfo; + + +#ifndef NO_CERTS + CYASSL_LOCAL int PemToDer(const unsigned char* buff, long sz, int type, + buffer* der, void* heap, EncryptedInfo* info, + int* eccKey); + + CYASSL_LOCAL int ProcessFile(CYASSL_CTX* ctx, const char* fname, int format, + int type, CYASSL* ssl, int userChain, + CYASSL_CRL* crl); +#endif + + +#ifdef CYASSL_CALLBACKS + CYASSL_LOCAL + void InitHandShakeInfo(HandShakeInfo*); + CYASSL_LOCAL + void FinishHandShakeInfo(HandShakeInfo*, const CYASSL*); + CYASSL_LOCAL + void AddPacketName(const char*, HandShakeInfo*); + + CYASSL_LOCAL + void InitTimeoutInfo(TimeoutInfo*); + CYASSL_LOCAL + void FreeTimeoutInfo(TimeoutInfo*, void*); + CYASSL_LOCAL + void AddPacketInfo(const char*, TimeoutInfo*, const byte*, int, void*); + CYASSL_LOCAL + void AddLateName(const char*, TimeoutInfo*); + CYASSL_LOCAL + void AddLateRecordHeader(const RecordLayerHeader* rl, TimeoutInfo* info); +#endif + + +/* Record Layer Header identifier from page 12 */ +enum ContentType { + no_type = 0, + change_cipher_spec = 20, + alert = 21, + handshake = 22, + application_data = 23 +}; + + +/* handshake header, same for each message type, pgs 20/21 */ +typedef struct HandShakeHeader { + byte type; + word24 length; +} HandShakeHeader; + + +/* DTLS handshake header, same for each message type */ +typedef struct DtlsHandShakeHeader { + byte type; + word24 length; + byte message_seq[2]; /* start at 0, restransmit gets same # */ + word24 fragment_offset; /* bytes in previous fragments */ + word24 fragment_length; /* length of this fragment */ +} DtlsHandShakeHeader; + + +enum HandShakeType { + no_shake = -1, + hello_request = 0, + client_hello = 1, + server_hello = 2, + hello_verify_request = 3, /* DTLS addition */ + session_ticket = 4, + certificate = 11, + server_key_exchange = 12, + certificate_request = 13, + server_hello_done = 14, + certificate_verify = 15, + client_key_exchange = 16, + finished = 20 +}; + + +static const byte client[SIZEOF_SENDER] = { 0x43, 0x4C, 0x4E, 0x54 }; +static const byte server[SIZEOF_SENDER] = { 0x53, 0x52, 0x56, 0x52 }; + +static const byte tls_client[FINISHED_LABEL_SZ + 1] = "client finished"; +static const byte tls_server[FINISHED_LABEL_SZ + 1] = "server finished"; + + +/* internal functions */ +CYASSL_LOCAL int SendChangeCipher(CYASSL*); +CYASSL_LOCAL int SendData(CYASSL*, const void*, int); +CYASSL_LOCAL int SendCertificate(CYASSL*); +CYASSL_LOCAL int SendCertificateRequest(CYASSL*); +CYASSL_LOCAL int SendServerKeyExchange(CYASSL*); +CYASSL_LOCAL int SendBuffered(CYASSL*); +CYASSL_LOCAL int ReceiveData(CYASSL*, byte*, int, int); +CYASSL_LOCAL int SendFinished(CYASSL*); +CYASSL_LOCAL int SendAlert(CYASSL*, int, int); +CYASSL_LOCAL int ProcessReply(CYASSL*); + +CYASSL_LOCAL int SetCipherSpecs(CYASSL*); +CYASSL_LOCAL int MakeMasterSecret(CYASSL*); + +CYASSL_LOCAL int AddSession(CYASSL*); +CYASSL_LOCAL int DeriveKeys(CYASSL* ssl); +CYASSL_LOCAL int StoreKeys(CYASSL* ssl, const byte* keyData); + +CYASSL_LOCAL int IsTLS(const CYASSL* ssl); +CYASSL_LOCAL int IsAtLeastTLSv1_2(const CYASSL* ssl); + +CYASSL_LOCAL void FreeHandshakeResources(CYASSL* ssl); +CYASSL_LOCAL void ShrinkInputBuffer(CYASSL* ssl, int forcedFree); +CYASSL_LOCAL void ShrinkOutputBuffer(CYASSL* ssl); +#ifndef NO_CERTS + CYASSL_LOCAL Signer* GetCA(void* cm, byte* hash); + #ifndef NO_SKID + CYASSL_LOCAL Signer* GetCAByName(void* cm, byte* hash); + #endif +#endif +CYASSL_LOCAL void BuildTlsFinished(CYASSL* ssl, Hashes* hashes, + const byte* sender); +CYASSL_LOCAL void FreeArrays(CYASSL* ssl, int keep); +CYASSL_LOCAL int CheckAvailableSize(CYASSL *ssl, int size); +CYASSL_LOCAL int GrowInputBuffer(CYASSL* ssl, int size, int usedLength); + +#ifndef NO_TLS + CYASSL_LOCAL int MakeTlsMasterSecret(CYASSL*); + CYASSL_LOCAL void TLS_hmac(CYASSL* ssl, byte* digest, const byte* in, + word32 sz, int content, int verify); +#endif + +#ifndef NO_CYASSL_CLIENT + CYASSL_LOCAL int SendClientHello(CYASSL*); + CYASSL_LOCAL int SendClientKeyExchange(CYASSL*); + CYASSL_LOCAL int SendCertificateVerify(CYASSL*); +#endif /* NO_CYASSL_CLIENT */ + +#ifndef NO_CYASSL_SERVER + CYASSL_LOCAL int SendServerHello(CYASSL*); + CYASSL_LOCAL int SendServerHelloDone(CYASSL*); + #ifdef CYASSL_DTLS + CYASSL_LOCAL int SendHelloVerifyRequest(CYASSL*); + #endif +#endif /* NO_CYASSL_SERVER */ + +#ifdef CYASSL_DTLS + CYASSL_LOCAL int DtlsPoolInit(CYASSL*); + CYASSL_LOCAL int DtlsPoolSave(CYASSL*, const byte*, int); + CYASSL_LOCAL int DtlsPoolTimeout(CYASSL*); + CYASSL_LOCAL int DtlsPoolSend(CYASSL*); + CYASSL_LOCAL void DtlsPoolReset(CYASSL*); + + CYASSL_LOCAL DtlsMsg* DtlsMsgNew(word32, void*); + CYASSL_LOCAL void DtlsMsgDelete(DtlsMsg*, void*); + CYASSL_LOCAL void DtlsMsgListDelete(DtlsMsg*, void*); + CYASSL_LOCAL void DtlsMsgSet(DtlsMsg*, word32, const byte*, byte, + word32, word32); + CYASSL_LOCAL DtlsMsg* DtlsMsgFind(DtlsMsg*, word32); + CYASSL_LOCAL DtlsMsg* DtlsMsgStore(DtlsMsg*, word32, const byte*, word32, + byte, word32, word32, void*); + CYASSL_LOCAL DtlsMsg* DtlsMsgInsert(DtlsMsg*, DtlsMsg*); +#endif /* CYASSL_DTLS */ + +#ifndef NO_TLS + + +#endif /* NO_TLS */ + + +CYASSL_LOCAL word32 LowResTimer(void); + +CYASSL_LOCAL void InitX509Name(CYASSL_X509_NAME*, int); +CYASSL_LOCAL void FreeX509Name(CYASSL_X509_NAME* name); +CYASSL_LOCAL void InitX509(CYASSL_X509*, int); +CYASSL_LOCAL void FreeX509(CYASSL_X509*); +#ifndef NO_CERTS + CYASSL_LOCAL int CopyDecodedToX509(CYASSL_X509*, DecodedCert*); +#endif + + +#ifdef __cplusplus + } /* extern "C" */ +#endif + +#endif /* CyaSSL_INT_H */ + diff --git a/cyassl/ocsp.h b/cyassl/ocsp.h index f47f671b1..f6931bd98 100644 --- a/cyassl/ocsp.h +++ b/cyassl/ocsp.h @@ -36,12 +36,10 @@ typedef struct CYASSL_OCSP CYASSL_OCSP; -CYASSL_LOCAL int CyaSSL_OCSP_Init(CYASSL_OCSP*); -CYASSL_LOCAL void CyaSSL_OCSP_Cleanup(CYASSL_OCSP*); - -CYASSL_LOCAL int CyaSSL_OCSP_set_override_url(CYASSL_OCSP*, const char*); -CYASSL_LOCAL int CyaSSL_OCSP_Lookup_Cert(CYASSL_OCSP*, DecodedCert*); +CYASSL_LOCAL int InitOCSP(CYASSL_OCSP*, CYASSL_CERT_MANAGER*); +CYASSL_LOCAL void FreeOCSP(CYASSL_OCSP*, int dynamic); +CYASSL_LOCAL int CheckCertOCSP(CYASSL_OCSP*, DecodedCert*); #ifdef __cplusplus } /* extern "C" */ diff --git a/cyassl/ssl.h b/cyassl/ssl.h index bd5f25c38..049e0d5eb 100644 --- a/cyassl/ssl.h +++ b/cyassl/ssl.h @@ -99,6 +99,9 @@ typedef struct CYASSL_EVP_PKEY { union { char* ptr; } pkey; + #ifdef HAVE_ECC + int pkey_curve; + #endif } CYASSL_EVP_PKEY; typedef struct CYASSL_MD4_CTX { @@ -413,6 +416,16 @@ CYASSL_API int CyaSSL_X509_STORE_CTX_get_error_depth(CYASSL_X509_STORE_CTX*); CYASSL_API char* CyaSSL_X509_NAME_oneline(CYASSL_X509_NAME*, char*, int); CYASSL_API CYASSL_X509_NAME* CyaSSL_X509_get_issuer_name(CYASSL_X509*); CYASSL_API CYASSL_X509_NAME* CyaSSL_X509_get_subject_name(CYASSL_X509*); +CYASSL_API int CyaSSL_X509_ext_isSet_by_NID(CYASSL_X509*, int); +CYASSL_API int CyaSSL_X509_ext_get_critical_by_NID(CYASSL_X509*, int); +CYASSL_API int CyaSSL_X509_get_isCA(CYASSL_X509*); +CYASSL_API int CyaSSL_X509_get_isSet_pathLength(CYASSL_X509*); +CYASSL_API unsigned int CyaSSL_X509_get_pathLength(CYASSL_X509*); +CYASSL_API unsigned int CyaSSL_X509_get_keyUsage(CYASSL_X509*); +CYASSL_API unsigned char* CyaSSL_X509_get_authorityKeyID( + CYASSL_X509*, unsigned char*, int*); +CYASSL_API unsigned char* CyaSSL_X509_get_subjectKeyID( + CYASSL_X509*, unsigned char*, int*); CYASSL_API int CyaSSL_X509_NAME_entry_count(CYASSL_X509_NAME*); CYASSL_API int CyaSSL_X509_NAME_get_text_by_NID( CYASSL_X509_NAME*, int, char*, int); @@ -530,6 +543,9 @@ enum { OCSP_RESPONSE = 8, OCSP_BASICRESP = 16, + CYASSL_OCSP_URL_OVERRIDE = 1, + CYASSL_OCSP_NO_NONCE = 2, + CYASSL_CRL_CHECKALL = 1, ASN1_GENERALIZEDTIME = 4, @@ -810,9 +826,9 @@ CYASSL_API CYASSL_X509* #ifndef NO_FILESYSTEM CYASSL_API CYASSL_X509* CyaSSL_X509_d2i_fp(CYASSL_X509** x509, FILE* file); -#endif CYASSL_API CYASSL_X509* CyaSSL_X509_load_certificate_file(const char* fname, int format); +#endif #ifdef CYASSL_SEP CYASSL_API unsigned char* @@ -930,15 +946,6 @@ CYASSL_API void CyaSSL_CTX_SetGenCookie(CYASSL_CTX*, CallbackGenCookie); CYASSL_API void CyaSSL_SetCookieCtx(CYASSL* ssl, void *ctx); CYASSL_API void* CyaSSL_GetCookieCtx(CYASSL* ssl); -typedef int (*CallbackIOOcsp)(void*, const char*, int, - unsigned char*, int, unsigned char**); -typedef void (*CallbackIOOcspRespFree)(void*,unsigned char*); -#ifdef HAVE_OCSP -CYASSL_API void CyaSSL_SetIOOcsp(CYASSL_CTX *ocsp, CallbackIOOcsp cb); -CYASSL_API void CyaSSL_SetIOOcspRespFree(CYASSL_CTX *ocsp, - CallbackIOOcspRespFree cb); -CYASSL_API void CyaSSL_SetIOOcspCtx(CYASSL_CTX *ocsp, void *octx); -#endif /* I/O Callback default errors */ enum IOerrors { @@ -966,9 +973,14 @@ CYASSL_API int CyaSSL_GetObjectSize(void); /* object size based on build */ CYASSL_API int CyaSSL_SetVersion(CYASSL* ssl, int version); CYASSL_API int CyaSSL_KeyPemToDer(const unsigned char*, int sz, unsigned char*, int, const char*); +CYASSL_API int CyaSSL_CertPemToDer(const unsigned char*, int sz, unsigned char*, + int, int); typedef void (*CallbackCACache)(unsigned char* der, int sz, int type); typedef void (*CbMissingCRL)(const char* url); +typedef int (*CbOCSPIO)(void*, const char*, int, + unsigned char*, int, unsigned char**); +typedef void (*CbOCSPRespFree)(void*,unsigned char*); /* User Atomic Record Layer CallBacks */ typedef int (*CallbackMacEncrypt)(CYASSL* ssl, unsigned char* macOut, @@ -994,6 +1006,7 @@ CYASSL_API const unsigned char* CyaSSL_GetClientWriteIV(CYASSL*); CYASSL_API const unsigned char* CyaSSL_GetServerWriteKey(CYASSL*); CYASSL_API const unsigned char* CyaSSL_GetServerWriteIV(CYASSL*); CYASSL_API int CyaSSL_GetKeySize(CYASSL*); +CYASSL_API int CyaSSL_GetIVSize(CYASSL*); CYASSL_API int CyaSSL_GetSide(CYASSL*); CYASSL_API int CyaSSL_IsTLSv1_1(CYASSL*); CYASSL_API int CyaSSL_GetBulkCipher(CYASSL*); @@ -1113,16 +1126,34 @@ CYASSL_API void* CyaSSL_GetRsaDecCtx(CYASSL* ssl); int, int); CYASSL_API int CyaSSL_CertManagerSetCRL_Cb(CYASSL_CERT_MANAGER*, CbMissingCRL); + CYASSL_API int CyaSSL_CertManagerCheckOCSP(CYASSL_CERT_MANAGER*, + unsigned char*, int sz); + CYASSL_API int CyaSSL_CertManagerEnableOCSP(CYASSL_CERT_MANAGER*, + int options); + CYASSL_API int CyaSSL_CertManagerDisableOCSP(CYASSL_CERT_MANAGER*); + CYASSL_API int CyaSSL_CertManagerSetOCSPOverrideURL(CYASSL_CERT_MANAGER*, + const char*); + CYASSL_API int CyaSSL_CertManagerSetOCSP_Cb(CYASSL_CERT_MANAGER*, + CbOCSPIO, CbOCSPRespFree, void*); CYASSL_API int CyaSSL_EnableCRL(CYASSL* ssl, int options); CYASSL_API int CyaSSL_DisableCRL(CYASSL* ssl); CYASSL_API int CyaSSL_LoadCRL(CYASSL*, const char*, int, int); CYASSL_API int CyaSSL_SetCRL_Cb(CYASSL*, CbMissingCRL); + CYASSL_API int CyaSSL_EnableOCSP(CYASSL*, int options); + CYASSL_API int CyaSSL_DisableOCSP(CYASSL*); + CYASSL_API int CyaSSL_SetOCSP_OverrideURL(CYASSL*, const char*); + CYASSL_API int CyaSSL_SetOCSP_Cb(CYASSL*, CbOCSPIO, CbOCSPRespFree, void*); CYASSL_API int CyaSSL_CTX_EnableCRL(CYASSL_CTX* ctx, int options); CYASSL_API int CyaSSL_CTX_DisableCRL(CYASSL_CTX* ctx); CYASSL_API int CyaSSL_CTX_LoadCRL(CYASSL_CTX*, const char*, int, int); CYASSL_API int CyaSSL_CTX_SetCRL_Cb(CYASSL_CTX*, CbMissingCRL); + CYASSL_API int CyaSSL_CTX_EnableOCSP(CYASSL_CTX*, int options); + CYASSL_API int CyaSSL_CTX_DisableOCSP(CYASSL_CTX*); + CYASSL_API int CyaSSL_CTX_SetOCSP_OverrideURL(CYASSL_CTX*, const char*); + CYASSL_API int CyaSSL_CTX_SetOCSP_Cb(CYASSL_CTX*, + CbOCSPIO, CbOCSPRespFree, void*); #endif /* !NO_CERTS */ /* end of handshake frees temporary arrays, if user needs for get_keys or @@ -1174,6 +1205,10 @@ CYASSL_API unsigned char CyaSSL_SNI_Status(CYASSL* ssl, unsigned char type); CYASSL_API unsigned short CyaSSL_SNI_GetRequest(CYASSL *ssl, unsigned char type, void** data); +CYASSL_API int CyaSSL_SNI_GetFromBuffer( + const unsigned char* clientHello, unsigned int helloSz, + unsigned char type, unsigned char* sni, unsigned int* inOutSz); + #endif /* NO_CYASSL_SERVER */ #endif /* HAVE_SNI */ @@ -1227,14 +1262,9 @@ CYASSL_API int CyaSSL_accept_ex(CYASSL*, HandShakeCallBack, TimeoutCallBack, #endif /* CYASSL_CALLBACKS */ -CYASSL_API int CyaSSL_CTX_OCSP_set_options(CYASSL_CTX*, int); -CYASSL_API int CyaSSL_CTX_OCSP_set_override_url(CYASSL_CTX*, const char*); - -/* OCSP Options */ -#define CYASSL_OCSP_ENABLE 0x0001 /* Enable OCSP lookups */ -#define CYASSL_OCSP_URL_OVERRIDE 0x0002 /* Use the override URL instead of URL - * in certificate */ -#define CYASSL_OCSP_NO_NONCE 0x0004 /* Disables the request nonce. */ +#ifdef CYASSL_HAVE_WOLFSCEP +CYASSL_API void CyaSSL_wolfSCEP(void); +#endif /* CYASSL_HAVE_WOLFSCEP */ #ifdef __cplusplus diff --git a/cyassl/version.h b/cyassl/version.h index e66d54a0d..192ff9874 100644 --- a/cyassl/version.h +++ b/cyassl/version.h @@ -26,8 +26,8 @@ extern "C" { #endif -#define LIBCYASSL_VERSION_STRING "2.8.3" -#define LIBCYASSL_VERSION_HEX 0x02008003 +#define LIBCYASSL_VERSION_STRING "2.8.6" +#define LIBCYASSL_VERSION_HEX 0x02008006 #ifdef __cplusplus } diff --git a/examples/client/client.c b/examples/client/client.c index 6c82d627c..ff0e9848f 100644 --- a/examples/client/client.c +++ b/examples/client/client.c @@ -505,10 +505,13 @@ THREAD_RETURN CYASSL_THREAD client_test(void* args) #ifdef HAVE_OCSP if (useOcsp) { - CyaSSL_CTX_OCSP_set_options(ctx, - CYASSL_OCSP_ENABLE | CYASSL_OCSP_NO_NONCE); - if (ocspUrl != NULL) - CyaSSL_CTX_OCSP_set_override_url(ctx, ocspUrl); + if (ocspUrl != NULL) { + CyaSSL_CTX_SetOCSP_OverrideURL(ctx, ocspUrl); + CyaSSL_CTX_EnableOCSP(ctx, CYASSL_OCSP_NO_NONCE + | CYASSL_OCSP_URL_OVERRIDE); + } + else + CyaSSL_CTX_EnableOCSP(ctx, CYASSL_OCSP_NO_NONCE); } #endif @@ -803,8 +806,10 @@ THREAD_RETURN CYASSL_THREAD client_test(void* args) #if defined(DEBUG_CYASSL) && !defined(CYASSL_MDK_SHELL) && !defined(STACK_TRAP) CyaSSL_Debugging_ON(); #endif - if (CurrentDir("client") || CurrentDir("build")) + if (CurrentDir("client")) ChangeDirBack(2); + else if (CurrentDir("Debug") || CurrentDir("Release")) + ChangeDirBack(3); #ifdef HAVE_STACK_SIZE StackSizeCheck(&args, client_test); diff --git a/examples/echoclient/echoclient.c b/examples/echoclient/echoclient.c index 0c444a2a2..ee654d481 100644 --- a/examples/echoclient/echoclient.c +++ b/examples/echoclient/echoclient.c @@ -255,8 +255,10 @@ void echoclient_test(void* args) CyaSSL_Debugging_ON(); #endif - if (CurrentDir("echoclient") || CurrentDir("build")) + if (CurrentDir("echoclient")) ChangeDirBack(2); + else if (CurrentDir("Debug") || CurrentDir("Release")) + ChangeDirBack(3); echoclient_test(&args); CyaSSL_Cleanup(); diff --git a/examples/echoserver/echoserver.c b/examples/echoserver/echoserver.c index cc4ed7200..1eac9b5a9 100644 --- a/examples/echoserver/echoserver.c +++ b/examples/echoserver/echoserver.c @@ -339,8 +339,10 @@ THREAD_RETURN CYASSL_THREAD echoserver_test(void* args) #if defined(DEBUG_CYASSL) && !defined(CYASSL_MDK_SHELL) CyaSSL_Debugging_ON(); #endif - if (CurrentDir("echoserver") || CurrentDir("build")) + if (CurrentDir("echoserver")) ChangeDirBack(2); + else if (CurrentDir("Debug") || CurrentDir("Release")) + ChangeDirBack(3); echoserver_test(&args); CyaSSL_Cleanup(); diff --git a/examples/server/server.c b/examples/server/server.c index 9be9c4802..365418d5d 100644 --- a/examples/server/server.c +++ b/examples/server/server.c @@ -374,6 +374,10 @@ THREAD_RETURN CYASSL_THREAD server_test(void* args) if (fewerPackets) CyaSSL_CTX_set_group_messages(ctx); +#ifdef OPENSSL_EXTRA + SSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack); +#endif + #if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) if (!usePsk) { if (SSL_CTX_use_certificate_file(ctx, ourCert, SSL_FILETYPE_PEM) @@ -428,10 +432,6 @@ THREAD_RETURN CYASSL_THREAD server_test(void* args) } #endif -#ifdef OPENSSL_EXTRA - SSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack); -#endif - #if defined(CYASSL_SNIFFER) && !defined(HAVE_NTRU) && !defined(HAVE_ECC) /* don't use EDH, can't sniff tmp keys */ if (cipherList == NULL) { @@ -459,10 +459,13 @@ THREAD_RETURN CYASSL_THREAD server_test(void* args) #endif #ifdef HAVE_OCSP if (useOcsp) { - CyaSSL_CTX_OCSP_set_options(ctx, - CYASSL_OCSP_ENABLE | CYASSL_OCSP_NO_NONCE); - if (ocspUrl != NULL) - CyaSSL_CTX_OCSP_set_override_url(ctx, ocspUrl); + if (ocspUrl != NULL) { + CyaSSL_CTX_SetOCSP_OverrideURL(ctx, ocspUrl); + CyaSSL_CTX_EnableOCSP(ctx, CYASSL_OCSP_NO_NONCE + | CYASSL_OCSP_URL_OVERRIDE); + } + else + CyaSSL_CTX_EnableOCSP(ctx, CYASSL_OCSP_NO_NONCE); } #endif #ifdef HAVE_PK_CALLBACKS @@ -556,8 +559,10 @@ THREAD_RETURN CYASSL_THREAD server_test(void* args) #if defined(DEBUG_CYASSL) && !defined(CYASSL_MDK_SHELL) CyaSSL_Debugging_ON(); #endif - if (CurrentDir("server") || CurrentDir("build")) + if (CurrentDir("server")) ChangeDirBack(2); + else if (CurrentDir("Debug") || CurrentDir("Release")) + ChangeDirBack(3); #ifdef HAVE_STACK_SIZE StackSizeCheck(&args, server_test); diff --git a/m4/ax_debug.m4 b/m4/ax_debug.m4 index 5522d7215..5ea3c3594 100644 --- a/m4/ax_debug.m4 +++ b/m4/ax_debug.m4 @@ -52,7 +52,6 @@ AC_DEFUN([AX_DEBUG], [Add debug code/turns off optimizations (yes|no) @<:@default=no@:>@])], [ax_enable_debug=yes AC_DEFINE([DEBUG],[1],[Define to 1 to enable debugging code.]) - AX_CHECK_LIBRARY([MCHECK],[mcheck.h],[mcheck],[AX_APPEND_LINK_FLAGS([-lmcheck])]) AX_ADD_AM_MACRO([--debug],[AM_YFLAGS]) AX_ADD_AM_MACRO([-D_GLIBCXX_DEBUG],[AM_CPPFLAGS])], [ax_enable_debug=no diff --git a/m4/ax_tls.m4 b/m4/ax_tls.m4 new file mode 100644 index 000000000..033e3b135 --- /dev/null +++ b/m4/ax_tls.m4 @@ -0,0 +1,76 @@ +# =========================================================================== +# http://www.gnu.org/software/autoconf-archive/ax_tls.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_TLS([action-if-found], [action-if-not-found]) +# +# DESCRIPTION +# +# Provides a test for the compiler support of thread local storage (TLS) +# extensions. Defines TLS if it is found. Currently knows about GCC/ICC +# and MSVC. I think SunPro uses the same as GCC, and Borland apparently +# supports either. +# +# LICENSE +# +# Copyright (c) 2008 Alan Woodland +# Copyright (c) 2010 Diego Elio Petteno` +# +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the +# Free Software Foundation, either version 3 of the License, or (at your +# option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +# +# As a special exception, the respective Autoconf Macro's copyright owner +# gives unlimited permission to copy, distribute and modify the configure +# scripts that are the output of Autoconf when processing the Macro. You +# need not follow the terms of the GNU General Public License when using +# or distributing such scripts, even though portions of the text of the +# Macro appear in them. The GNU General Public License (GPL) does govern +# all other use of the material that constitutes the Autoconf Macro. +# +# This special exception to the GPL applies to versions of the Autoconf +# Macro released by the Autoconf Archive. When you make and distribute a +# modified version of the Autoconf Macro, you may extend this special +# exception to the GPL to apply to your modified version as well. + +#serial 10 + +AC_DEFUN([AX_TLS], [ + AC_MSG_CHECKING(for thread local storage (TLS) class) + AC_CACHE_VAL(ac_cv_tls, [ + ax_tls_keywords="__thread __declspec(thread) none" + for ax_tls_keyword in $ax_tls_keywords; do + AS_CASE([$ax_tls_keyword], + [none], [ac_cv_tls=none ; break], + [AC_TRY_COMPILE( + [#include + static void + foo(void) { + static ] $ax_tls_keyword [ int bar; + exit(1); + }], + [], + [ac_cv_tls=$ax_tls_keyword ; break], + ac_cv_tls=none + )]) + done + ]) + AC_MSG_RESULT($ac_cv_tls) + + AS_IF([test "$ac_cv_tls" != "none"], + AC_DEFINE_UNQUOTED([TLS], $ac_cv_tls, [If the compiler supports a TLS storage class define it to that here]) + m4_ifnblank([$1], [$1]), + m4_ifnblank([$2], [$2]) + ) +]) diff --git a/mcapi/ctaocrypt_mcapi.X/nbproject/configurations.xml b/mcapi/ctaocrypt_mcapi.X/nbproject/configurations.xml index 54eef5bf8..e9792ab63 100644 --- a/mcapi/ctaocrypt_mcapi.X/nbproject/configurations.xml +++ b/mcapi/ctaocrypt_mcapi.X/nbproject/configurations.xml @@ -167,28 +167,6 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/mcapi/ctaocrypt_test.X/nbproject/configurations.xml b/mcapi/ctaocrypt_test.X/nbproject/configurations.xml index e0ee5463e..d5b8d3e85 100644 --- a/mcapi/ctaocrypt_test.X/nbproject/configurations.xml +++ b/mcapi/ctaocrypt_test.X/nbproject/configurations.xml @@ -184,28 +184,6 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/mcapi/ctaocrypt_test.X/nbproject/include.am b/mcapi/ctaocrypt_test.X/nbproject/include.am index ec09b769e..dc3d2f9a2 100644 --- a/mcapi/ctaocrypt_test.X/nbproject/include.am +++ b/mcapi/ctaocrypt_test.X/nbproject/include.am @@ -3,8 +3,7 @@ # EXTRA_DIST += \ - mcapi/ctaocrypt_test.X/Makefile \ - mcapi/ctaocrypt_test.X/main.c + mcapi/ctaocrypt_test.X/Makefile EXTRA_DIST += \ mcapi/ctaocrypt_test.X/nbproject/configurations.xml \ diff --git a/mcapi/cyassl.X/nbproject/include.am b/mcapi/cyassl.X/nbproject/include.am index 163090026..fc7e8d972 100644 --- a/mcapi/cyassl.X/nbproject/include.am +++ b/mcapi/cyassl.X/nbproject/include.am @@ -3,7 +3,6 @@ # EXTRA_DIST += \ - mcapi/README \ mcapi/cyassl.X/Makefile EXTRA_DIST += \ diff --git a/mcapi/include.am b/mcapi/include.am index 7486c0fd5..993ba29c0 100644 --- a/mcapi/include.am +++ b/mcapi/include.am @@ -6,9 +6,14 @@ if BUILD_MCAPI check_PROGRAMS += mcapi/test noinst_PROGRAMS += mcapi/test mcapi_test_SOURCES = mcapi/crypto.c \ - mcapi/test.c + mcapi/mcapi_test.c mcapi_test_LDADD = src/libcyassl.la mcapi_test_DEPENDENCIES = src/libcyassl.la endif noinst_HEADERS += mcapi/crypto.h + +EXTRA_DIST += \ + mcapi/README \ + mcapi/PIC32MZ-serial.h + diff --git a/mcapi/mcapi_test.c b/mcapi/mcapi_test.c index c22618772..24e69174d 100644 --- a/mcapi/mcapi_test.c +++ b/mcapi/mcapi_test.c @@ -53,7 +53,7 @@ #include #include "PIC32MZ-serial.h" #define SYSTEMConfigPerformance /* void out SYSTEMConfigPerformance(); */ -#else +#elif defined(MICROCHIP_PIC32) #define PIC32_STARTER_KIT #include #include @@ -61,6 +61,8 @@ #include #include #define init_serial() /* void out init_serial() */ +#else + #include /* order matters above ? */ #endif #define OUR_DATA_SIZE 1024 static byte ourData[OUR_DATA_SIZE]; @@ -93,9 +95,11 @@ int main(int argc, char** argv) (void)argc; (void)argv; +#if defined(MICROCHIP_PIC32) init_serial() ; /* initialize PIC32MZ serial I/O */ SYSTEMConfigPerformance(80000000); DBINIT(); +#endif /* align key, iv pointers */ key = (byte*)XMALLOC(32, NULL, DYNAMIC_TYPE_KEY); diff --git a/mplabx/ctaocrypt_benchmark.X/nbproject/configurations.xml b/mplabx/ctaocrypt_benchmark.X/nbproject/configurations.xml index d1facedfd..13faa6bc4 100644 --- a/mplabx/ctaocrypt_benchmark.X/nbproject/configurations.xml +++ b/mplabx/ctaocrypt_benchmark.X/nbproject/configurations.xml @@ -32,7 +32,7 @@ PIC32MX795F512L - SKDEPIC32PlatformTool + PKOBSKDEPlatformTool XC32 1.30 3 @@ -166,9 +166,28 @@ - - - + + + + + + + + + + + + + + + + + + + + + diff --git a/mplabx/ctaocrypt_benchmark.X/nbproject/include.am b/mplabx/ctaocrypt_benchmark.X/nbproject/include.am index 567fbba38..9af74c3b8 100644 --- a/mplabx/ctaocrypt_benchmark.X/nbproject/include.am +++ b/mplabx/ctaocrypt_benchmark.X/nbproject/include.am @@ -3,8 +3,7 @@ # EXTRA_DIST += \ - mplabx/ctaocrypt_benchmark.X/Makefile \ - mplabx/ctaocrypt_benchmark.X/main.c + mplabx/ctaocrypt_benchmark.X/Makefile EXTRA_DIST += \ mplabx/ctaocrypt_benchmark.X/nbproject/configurations.xml \ diff --git a/mplabx/ctaocrypt_test.X/nbproject/configurations.xml b/mplabx/ctaocrypt_test.X/nbproject/configurations.xml index 1aa064df0..7ffe44c26 100644 --- a/mplabx/ctaocrypt_test.X/nbproject/configurations.xml +++ b/mplabx/ctaocrypt_test.X/nbproject/configurations.xml @@ -33,7 +33,7 @@ PIC32MX795F512L - SKDEPIC32PlatformTool + PKOBSKDEPlatformTool XC32 1.30 3 @@ -189,9 +189,6 @@ - - - diff --git a/mplabx/ctaocrypt_test.X/nbproject/include.am b/mplabx/ctaocrypt_test.X/nbproject/include.am index e7d868de8..ea0df611c 100644 --- a/mplabx/ctaocrypt_test.X/nbproject/include.am +++ b/mplabx/ctaocrypt_test.X/nbproject/include.am @@ -3,8 +3,7 @@ # EXTRA_DIST += \ - mplabx/ctaocrypt_test.X/Makefile \ - mplabx/ctaocrypt_test.X/main.c + mplabx/ctaocrypt_test.X/Makefile EXTRA_DIST += \ mplabx/ctaocrypt_test.X/nbproject/configurations.xml \ diff --git a/mplabx/cyassl.X/nbproject/configurations.xml b/mplabx/cyassl.X/nbproject/configurations.xml index 1482f8f65..1a141bb22 100644 --- a/mplabx/cyassl.X/nbproject/configurations.xml +++ b/mplabx/cyassl.X/nbproject/configurations.xml @@ -70,7 +70,7 @@ PIC32MX795F512L - SKDEPIC32PlatformTool + PKOBSKDEPlatformTool XC32 1.30 3 @@ -104,7 +104,7 @@ + value="CYASSL_SHA512;CYASSL_SHA384;HAVE_ECC"/> @@ -181,9 +181,28 @@ - - - + + + + + + + + + + + + + + + + + + + + + diff --git a/mplabx/cyassl.X/nbproject/include.am b/mplabx/cyassl.X/nbproject/include.am index 4db3841b2..7d0b98793 100644 --- a/mplabx/cyassl.X/nbproject/include.am +++ b/mplabx/cyassl.X/nbproject/include.am @@ -3,7 +3,6 @@ # EXTRA_DIST += \ - mplabx/README \ mplabx/cyassl.X/Makefile EXTRA_DIST += \ diff --git a/mplabx/include.am b/mplabx/include.am new file mode 100644 index 000000000..b63cdecaa --- /dev/null +++ b/mplabx/include.am @@ -0,0 +1,10 @@ +# vim:ft=automake +# All paths should be given relative to the root +# + +EXTRA_DIST += \ + mplabx/PIC32MZ-serial.h \ + mplabx/README \ + mplabx/benchmark_main.c \ + mplabx/test_main.c + diff --git a/src/include.am b/src/include.am index d187ab0d6..e57f0f6fc 100644 --- a/src/include.am +++ b/src/include.am @@ -136,3 +136,7 @@ if BUILD_LIBZ src_libcyassl_la_SOURCES += ctaocrypt/src/compress.c endif +if BUILD_PKCS7 +src_libcyassl_la_SOURCES += ctaocrypt/src/pkcs7.c +endif + diff --git a/src/internal.c b/src/internal.c index 53e0645ec..0f438dd1b 100644 --- a/src/internal.c +++ b/src/internal.c @@ -87,6 +87,13 @@ CYASSL_CALLBACKS needs LARGE_STATIC_BUFFERS, please add LARGE_STATIC_BUFFERS #endif #endif + +#ifdef CYASSL_DTLS + static INLINE int DtlsCheckWindow(DtlsState* state); + static INLINE int DtlsUpdateWindow(DtlsState* state); +#endif + + typedef enum { doProcessInit = 0, #ifndef NO_CYASSL_SERVER @@ -419,9 +426,6 @@ int InitSSL_Ctx(CYASSL_CTX* ctx, CYASSL_METHOD* method) ctx->sendVerify = 0; ctx->quietShutdown = 0; ctx->groupMessages = 0; -#ifdef HAVE_OCSP - CyaSSL_OCSP_Init(&ctx->ocsp); -#endif #ifdef HAVE_CAVIUM ctx->devId = NO_CAVIUM_DEVICE; #endif @@ -472,9 +476,6 @@ void SSL_CtxResourceFree(CYASSL_CTX* ctx) XFREE(ctx->certChain.buffer, ctx->heap, DYNAMIC_TYPE_CERT); CyaSSL_CertManagerFree(ctx->cm); #endif -#ifdef HAVE_OCSP - CyaSSL_OCSP_Cleanup(&ctx->ocsp); -#endif #ifdef HAVE_TLS_EXTENSIONS TLSX_FreeAll(ctx->extensions); #endif @@ -628,8 +629,10 @@ void InitSuites(Suites* suites, ProtocolVersion pv, byte haveRSA, byte havePSK, if (suites->setSuites) return; /* trust user settings, don't override */ - if (side == CYASSL_SERVER_END && haveStaticECC) + if (side == CYASSL_SERVER_END && haveStaticECC) { haveRSA = 0; /* can't do RSA with ECDSA key */ + (void)haveRSA; /* some builds won't read */ + } if (side == CYASSL_SERVER_END && haveECDSAsig) { haveRSAsig = 0; /* can't have RSA sig if signed by ECDSA */ @@ -643,6 +646,13 @@ void InitSuites(Suites* suites, ProtocolVersion pv, byte haveRSA, byte havePSK, } #endif +#ifdef HAVE_RENEGOTIATION_INDICATION + if (side == CYASSL_CLIENT_END) { + suites->suites[idx++] = 0; + suites->suites[idx++] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV; + } +#endif + #ifdef BUILD_TLS_NTRU_RSA_WITH_AES_256_CBC_SHA if (tls && haveNTRU && haveRSA) { suites->suites[idx++] = 0; @@ -1271,6 +1281,33 @@ void InitX509(CYASSL_X509* x509, int dynamicFlag) x509->altNames = NULL; x509->altNamesNext = NULL; x509->dynamicMemory = (byte)dynamicFlag; + x509->isCa = 0; +#ifdef OPENSSL_EXTRA + x509->pathLength = 0; + x509->basicConstSet = 0; + x509->basicConstCrit = 0; + x509->basicConstPlSet = 0; + x509->subjAltNameSet = 0; + x509->subjAltNameCrit = 0; + x509->authKeyIdSet = 0; + x509->authKeyIdCrit = 0; + x509->authKeyId = NULL; + x509->authKeyIdSz = 0; + x509->subjKeyIdSet = 0; + x509->subjKeyIdCrit = 0; + x509->subjKeyId = NULL; + x509->subjKeyIdSz = 0; + x509->keyUsageSet = 0; + x509->keyUsageCrit = 0; + x509->keyUsage = 0; + #ifdef HAVE_ECC + x509->pkCurveOID = 0; + #endif /* HAVE_ECC */ + #ifdef CYASSL_SEP + x509->certPolicySet = 0; + x509->certPolicyCrit = 0; + #endif /* CYASSL_SEP */ +#endif /* OPENSSL_EXTRA */ } @@ -1286,6 +1323,10 @@ void FreeX509(CYASSL_X509* x509) XFREE(x509->pubKey.buffer, NULL, DYNAMIC_TYPE_PUBLIC_KEY); XFREE(x509->derCert.buffer, NULL, DYNAMIC_TYPE_SUBJECT_CN); XFREE(x509->sig.buffer, NULL, 0); + #ifdef OPENSSL_EXTRA + XFREE(x509->authKeyId, NULL, 0); + XFREE(x509->subjKeyId, NULL, 0); + #endif /* OPENSSL_EXTRA */ if (x509->altNames) FreeAltNames(x509->altNames, NULL); if (x509->dynamicMemory) @@ -1390,6 +1431,9 @@ int InitSSL(CYASSL* ssl, CYASSL_CTX* ctx) #ifdef CYASSL_DTLS ssl->IOCB_CookieCtx = NULL; /* we don't use for default cb */ ssl->dtls_expected_rx = MAX_MTU; + ssl->keys.dtls_state.window = 0; + ssl->keys.dtls_state.nextEpoch = 0; + ssl->keys.dtls_state.nextSeq = 0; #endif #ifndef NO_OLD_TLS @@ -1447,13 +1491,13 @@ int InitSSL(CYASSL* ssl, CYASSL_CTX* ctx) #ifdef CYASSL_DTLS ssl->keys.dtls_sequence_number = 0; - ssl->keys.dtls_peer_sequence_number = 0; - ssl->keys.dtls_expected_peer_sequence_number = 0; + ssl->keys.dtls_state.curSeq = 0; + ssl->keys.dtls_state.nextSeq = 0; ssl->keys.dtls_handshake_number = 0; ssl->keys.dtls_expected_peer_handshake_number = 0; ssl->keys.dtls_epoch = 0; - ssl->keys.dtls_peer_epoch = 0; - ssl->keys.dtls_expected_peer_epoch = 0; + ssl->keys.dtls_state.curEpoch = 0; + ssl->keys.dtls_state.nextEpoch = 0; ssl->dtls_timeout_init = DTLS_TIMEOUT_INIT; ssl->dtls_timeout_max = DTLS_TIMEOUT_MAX; ssl->dtls_timeout = ssl->dtls_timeout_init; @@ -1595,6 +1639,7 @@ int InitSSL(CYASSL* ssl, CYASSL_CTX* ctx) CYASSL_MSG("Arrays Memory error"); return MEMORY_E; } + XMEMSET(ssl->arrays, 0, sizeof(Arrays)); #ifndef NO_PSK ssl->arrays->client_identity[0] = 0; @@ -2731,9 +2776,9 @@ static int GetRecordHeader(CYASSL* ssl, const byte* input, word32* inOutIdx, /* type and version in same sport */ XMEMCPY(rh, input + *inOutIdx, ENUM_LEN + VERSION_SZ); *inOutIdx += ENUM_LEN + VERSION_SZ; - ato16(input + *inOutIdx, &ssl->keys.dtls_peer_epoch); + ato16(input + *inOutIdx, &ssl->keys.dtls_state.curEpoch); *inOutIdx += 4; /* advance past epoch, skip first 2 seq bytes for now */ - ato32(input + *inOutIdx, &ssl->keys.dtls_peer_sequence_number); + ato32(input + *inOutIdx, &ssl->keys.dtls_state.curSeq); *inOutIdx += 4; /* advance past rest of seq */ ato16(input + *inOutIdx, size); *inOutIdx += LENGTH_SZ; @@ -2754,27 +2799,14 @@ static int GetRecordHeader(CYASSL* ssl, const byte* input, word32* inOutIdx, return VERSION_ERROR; /* only use requested version */ } } -#if 0 - /* Instead of this, check the datagram against the sliding window of - * received datagram goodness. */ + #ifdef CYASSL_DTLS - /* If DTLS, check the sequence number against expected. If out of - * order, drop the record. Allows newer records in and resets the - * expected to the next record. */ if (ssl->options.dtls) { - if ((ssl->keys.dtls_expected_peer_epoch == - ssl->keys.dtls_peer_epoch) && - (ssl->keys.dtls_peer_sequence_number >= - ssl->keys.dtls_expected_peer_sequence_number)) { - ssl->keys.dtls_expected_peer_sequence_number = - ssl->keys.dtls_peer_sequence_number + 1; - } - else { + if (DtlsCheckWindow(&ssl->keys.dtls_state) != 1) return SEQUENCE_ERROR; - } } #endif -#endif + /* record layer length check */ #ifdef HAVE_MAX_FRAGMENT if (*size > (ssl->max_fragment + MAX_COMP_EXTRA + MAX_MSG_EXTRA)) @@ -3156,6 +3188,51 @@ int CopyDecodedToX509(CYASSL_X509* x509, DecodedCert* dCert) dCert->altNames = NULL; /* takes ownership */ x509->altNamesNext = x509->altNames; /* index hint */ + x509->isCa = dCert->isCA; +#ifdef OPENSSL_EXTRA + x509->pathLength = dCert->pathLength; + x509->keyUsage = dCert->extKeyUsage; + + x509->basicConstSet = dCert->extBasicConstSet; + x509->basicConstCrit = dCert->extBasicConstCrit; + x509->basicConstPlSet = dCert->extBasicConstPlSet; + x509->subjAltNameSet = dCert->extSubjAltNameSet; + x509->subjAltNameCrit = dCert->extSubjAltNameCrit; + x509->authKeyIdSet = dCert->extAuthKeyIdSet; + x509->authKeyIdCrit = dCert->extAuthKeyIdCrit; + if (dCert->extAuthKeyIdSrc != NULL && dCert->extAuthKeyIdSz != 0) { + x509->authKeyId = (byte*)XMALLOC(dCert->extAuthKeyIdSz, NULL, 0); + if (x509->authKeyId != NULL) { + XMEMCPY(x509->authKeyId, + dCert->extAuthKeyIdSrc, dCert->extAuthKeyIdSz); + x509->authKeyIdSz = dCert->extAuthKeyIdSz; + } + else + ret = MEMORY_E; + } + x509->subjKeyIdSet = dCert->extSubjKeyIdSet; + x509->subjKeyIdCrit = dCert->extSubjKeyIdCrit; + if (dCert->extSubjKeyIdSrc != NULL && dCert->extSubjKeyIdSz != 0) { + x509->subjKeyId = (byte*)XMALLOC(dCert->extSubjKeyIdSz, NULL, 0); + if (x509->subjKeyId != NULL) { + XMEMCPY(x509->subjKeyId, + dCert->extSubjKeyIdSrc, dCert->extSubjKeyIdSz); + x509->subjKeyIdSz = dCert->extSubjKeyIdSz; + } + else + ret = MEMORY_E; + } + x509->keyUsageSet = dCert->extKeyUsageSet; + x509->keyUsageCrit = dCert->extKeyUsageCrit; + #ifdef HAVE_ECC + x509->pkCurveOID = dCert->pkCurveOID; + #endif /* HAVE_ECC */ + #ifdef CYASSL_SEP + x509->certPolicySet = dCert->extCertPolicySet; + x509->certPolicyCrit = dCert->extCertPolicyCrit; + #endif /* CYASSL_SEP */ +#endif /* OPENSSL_EXTRA */ + return ret; } @@ -3317,8 +3394,8 @@ static int DoCertificate(CYASSL* ssl, byte* input, word32* inOutIdx) } #ifdef HAVE_OCSP - if (fatal == 0) { - ret = CyaSSL_OCSP_Lookup_Cert(&ssl->ctx->ocsp, &dCert); + if (fatal == 0 && ssl->ctx->cm->ocspEnabled) { + ret = CheckCertOCSP(ssl->ctx->cm->ocsp, &dCert); if (ret != 0) { CYASSL_MSG("\tOCSP Lookup not ok"); fatal = 0; @@ -3331,7 +3408,7 @@ static int DoCertificate(CYASSL* ssl, byte* input, word32* inOutIdx) int doCrlLookup = 1; #ifdef HAVE_OCSP - if (ssl->ctx->ocsp.enabled) { + if (ssl->ctx->cm->ocspEnabled) { doCrlLookup = (ret == OCSP_CERT_UNKNOWN); } #endif /* HAVE_OCSP */ @@ -3792,6 +3869,68 @@ static int DoHandShakeMsg(CYASSL* ssl, byte* input, word32* inOutIdx, #ifdef CYASSL_DTLS + +static INLINE int DtlsCheckWindow(DtlsState* state) +{ + word32 cur; + word32 next; + DtlsSeq window; + + if (state->curEpoch == state->nextEpoch) { + next = state->nextSeq; + window = state->window; + } + else if (state->curEpoch < state->nextEpoch) { + next = state->prevSeq; + window = state->prevWindow; + } + else { + return 0; + } + + cur = state->curSeq; + + if ((next > DTLS_SEQ_BITS) && (cur < next - DTLS_SEQ_BITS)) { + return 0; + } + else if ((cur < next) && (window & (1 << (next - cur - 1)))) { + return 0; + } + + return 1; +} + + +static INLINE int DtlsUpdateWindow(DtlsState* state) +{ + word32 cur; + word32* next; + DtlsSeq* window; + + if (state->curEpoch == state->nextEpoch) { + next = &state->nextSeq; + window = &state->window; + } + else { + next = &state->prevSeq; + window = &state->prevWindow; + } + + cur = state->curSeq; + + if (cur < *next) { + *window |= (1 << (*next - cur - 1)); + } + else { + *window <<= (1 + cur - *next); + *window |= 1; + *next = cur + 1; + } + + return 1; +} + + static int DtlsMsgDrain(CYASSL* ssl) { DtlsMsg* item = ssl->dtls_msg_list; @@ -4191,23 +4330,27 @@ static INLINE int Decrypt(CYASSL* ssl, byte* plain, const byte* input, /* check cipher text size for sanity */ static int SanityCheckCipherText(CYASSL* ssl, word32 encryptSz) { - word32 minLength = 0; +#ifdef HAVE_TRUNCATED_HMAC + word32 minLength = ssl->truncated_hmac ? TRUNCATED_HMAC_SZ + : ssl->specs.hash_size; +#else + word32 minLength = ssl->specs.hash_size; /* covers stream */ +#endif if (ssl->specs.cipher_type == block) { if (encryptSz % ssl->specs.block_size) { CYASSL_MSG("Block ciphertext not block size"); return SANITY_CIPHER_E; } - minLength = ssl->specs.hash_size + 1; /* pad byte */ + + minLength++; /* pad byte */ + if (ssl->specs.block_size > minLength) minLength = ssl->specs.block_size; if (ssl->options.tls1_1) minLength += ssl->specs.block_size; /* explicit IV */ } - else if (ssl->specs.cipher_type == stream) { - minLength = ssl->specs.hash_size; - } else if (ssl->specs.cipher_type == aead) { minLength = ssl->specs.block_size; /* explicit IV + implicit IV + CTR */ } @@ -4651,7 +4794,12 @@ static INLINE int VerifyMac(CYASSL* ssl, const byte* input, word32 msgSz, int ret; word32 pad = 0; word32 padByte = 0; +#ifdef HAVE_TRUNCATED_HMAC + word32 digestSz = ssl->truncated_hmac ? TRUNCATED_HMAC_SZ + : ssl->specs.hash_size; +#else word32 digestSz = ssl->specs.hash_size; +#endif byte verify[MAX_DIGEST_SIZE]; if (ssl->specs.cipher_type == block) { @@ -4803,8 +4951,6 @@ int ProcessReply(CYASSL* ssl) &ssl->curRL, &ssl->curSize); #ifdef CYASSL_DTLS if (ssl->options.dtls && ret == SEQUENCE_ERROR) { - /* This message is out of order. If we are handshaking, save - *it for later. Otherwise go ahead and process it. */ ssl->options.processReply = doProcessInit; ssl->buffers.inputBuffer.length = 0; ssl->buffers.inputBuffer.idx = 0; @@ -4840,7 +4986,14 @@ int ProcessReply(CYASSL* ssl) /* the record layer is here */ case runProcessingOneMessage: - if (ssl->keys.encryptionOn && ssl->keys.decryptedCur == 0) { + #ifdef CYASSL_DTLS + if (ssl->options.dtls && + ssl->keys.dtls_state.curEpoch < ssl->keys.dtls_state.nextEpoch) + ssl->keys.decryptedCur = 1; + #endif + + if (ssl->keys.encryptionOn && ssl->keys.decryptedCur == 0) + { ret = SanityCheckCipherText(ssl, ssl->curSize); if (ret < 0) return ret; @@ -4890,6 +5043,12 @@ int ProcessReply(CYASSL* ssl) ssl->keys.decryptedCur = 1; } + if (ssl->options.dtls) { + #ifdef CYASSL_DTLS + DtlsUpdateWindow(&ssl->keys.dtls_state); + #endif /* CYASSL_DTLS */ + } + CYASSL_MSG("received record layer msg"); switch (ssl->curRL.type) { @@ -4949,8 +5108,8 @@ int ProcessReply(CYASSL* ssl) #ifdef CYASSL_DTLS if (ssl->options.dtls) { DtlsPoolReset(ssl); - ssl->keys.dtls_expected_peer_epoch++; - ssl->keys.dtls_expected_peer_sequence_number = 0; + ssl->keys.dtls_state.nextEpoch++; + ssl->keys.dtls_state.nextSeq = 0; } #endif @@ -5236,7 +5395,12 @@ static void BuildCertHashes(CYASSL* ssl, Hashes* hashes) static int BuildMessage(CYASSL* ssl, byte* output, const byte* input, int inSz, int type) { +#ifdef HAVE_TRUNCATED_HMAC + word32 digestSz = min(ssl->specs.hash_size, + ssl->truncated_hmac ? TRUNCATED_HMAC_SZ : ssl->specs.hash_size); +#else word32 digestSz = ssl->specs.hash_size; +#endif word32 sz = RECORD_HEADER_SZ + inSz + digestSz; word32 pad = 0, i; word32 idx = RECORD_HEADER_SZ; @@ -5312,8 +5476,19 @@ static int BuildMessage(CYASSL* ssl, byte* output, const byte* input, int inSz, #endif } else { - if (ssl->specs.cipher_type != aead) - ssl->hmac(ssl, output+idx, output + headerSz + ivSz, inSz, type, 0); + if (ssl->specs.cipher_type != aead) { +#ifdef HAVE_TRUNCATED_HMAC + if (ssl->truncated_hmac && ssl->specs.hash_size > digestSz) { + byte hmac[MAX_DIGEST_SIZE]; + + ssl->hmac(ssl, hmac, output + headerSz + ivSz, inSz, type, 0); + + XMEMCPY(output + idx, hmac, digestSz); + } else +#endif + ssl->hmac(ssl, output+idx, output + headerSz + ivSz, inSz, + type, 0); + } if ( (ret = Encrypt(ssl, output + headerSz, output+headerSz,size)) != 0) return ret; @@ -7946,7 +8121,7 @@ static void PickHashSigAlgo(CYASSL* ssl, case ecc_diffie_hellman_kea: { ecc_key myKey; - ecc_key* peerKey = &myKey; + ecc_key* peerKey = NULL; word32 size = sizeof(encSecret); if (ssl->specs.static_ecdh) { @@ -7961,6 +8136,9 @@ static void PickHashSigAlgo(CYASSL* ssl, peerKey = ssl->peerEccKey; } + if (peerKey == NULL) + return NO_PEER_KEY; + ecc_init(&myKey); ret = ecc_make_key(ssl->rng, peerKey->dp->size, &myKey); if (ret != 0) @@ -9130,7 +9308,7 @@ static void PickHashSigAlgo(CYASSL* ssl, return 1; break; -#ifndef NO_3DES +#ifndef NO_DES3 case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA : if (requirement == REQUIRES_RSA) return 1; @@ -9159,7 +9337,7 @@ static void PickHashSigAlgo(CYASSL* ssl, #endif #endif /* NO_RSA */ -#ifndef NO_3DES +#ifndef NO_DES3 case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA : if (requirement == REQUIRES_ECC_DSA) return 1; @@ -9715,6 +9893,7 @@ static void PickHashSigAlgo(CYASSL* ssl, if (clSuites.suiteSz > MAX_SUITE_SZ) return BUFFER_ERROR; + clSuites.hashSigAlgoSz = 0; /* session size */ ato16(&input[idx], &sessionSz); diff --git a/src/io.c b/src/io.c index ca620d4ad..55f28eed3 100644 --- a/src/io.c +++ b/src/io.c @@ -352,7 +352,7 @@ int EmbedReceiveFrom(CYASSL *ssl, char *buf, int sz, void *ctx) int err; int sd = dtlsCtx->fd; int dtls_timeout = CyaSSL_dtls_get_current_timeout(ssl); - struct sockaddr_in6 peer; + struct sockaddr_storage peer; XSOCKLENT peerSz = sizeof(peer); CYASSL_ENTER("EmbedReceiveFrom()"); @@ -471,34 +471,21 @@ int EmbedSendTo(CYASSL* ssl, char *buf, int sz, void *ctx) int EmbedGenerateCookie(CYASSL* ssl, byte *buf, int sz, void *ctx) { int sd = ssl->wfd; - struct sockaddr_in6 peer; + struct sockaddr_storage peer; XSOCKLENT peerSz = sizeof(peer); Sha sha; byte digest[SHA_DIGEST_SIZE]; (void)ctx; + XMEMSET(&peer, 0, sizeof(peer)); if (getpeername(sd, (struct sockaddr*)&peer, &peerSz) != 0) { CYASSL_MSG("getpeername failed in EmbedGenerateCookie"); return GEN_COOKIE_E; } InitSha(&sha); - - if (peer.sin6_family == AF_INET6) { - ShaUpdate(&sha, (byte*)&peer.sin6_port, sizeof(peer.sin6_port)); - ShaUpdate(&sha, (byte*)&peer.sin6_addr, sizeof(peer.sin6_addr)); - } - else if (peer.sin6_family == AF_INET) { - struct sockaddr_in *s = (struct sockaddr_in*)&peer; - ShaUpdate(&sha, (byte*)&s->sin_port, sizeof(s->sin_port)); - ShaUpdate(&sha, (byte*)&s->sin_addr, sizeof(s->sin_addr)); - } - else { - CYASSL_MSG("peer sin_family unknown type in EmbedGenerateCookie"); - return GEN_COOKIE_E; - } - + ShaUpdate(&sha, (byte*)&peer, peerSz); ShaFinal(&sha, digest); if (sz > SHA_DIGEST_SIZE) @@ -512,52 +499,62 @@ int EmbedGenerateCookie(CYASSL* ssl, byte *buf, int sz, void *ctx) #ifdef HAVE_OCSP -#ifdef TEST_IPV6 - typedef struct sockaddr_in6 SOCKADDR_IN_T; - #define AF_INET_V AF_INET6 -#else - typedef struct sockaddr_in SOCKADDR_IN_T; - #define AF_INET_V AF_INET -#endif - -static INLINE int tcp_connect(SOCKET_T* sockfd, const char* ip, word16 port) +static int tcp_connect(SOCKET_T* sockfd, const char* ip, word16 port) { - SOCKADDR_IN_T addr; - const char* host = ip; + struct sockaddr_storage addr; + int sockaddr_len = sizeof(struct sockaddr_in); + XMEMSET(&addr, 0, sizeof(addr)); - /* peer could be in human readable form */ - if (ip != INADDR_ANY && isalpha(ip[0])) { + #ifdef HAVE_GETADDRINFO + { + struct addrinfo hints; + struct addrinfo* answer = NULL; + char strPort[8]; + + XMEMSET(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + + XSNPRINTF(strPort, sizeof(strPort), "%d", port); + strPort[7] = '\0'; + + if (getaddrinfo(ip, strPort, &hints, &answer) < 0 || answer == NULL) { + CYASSL_MSG("no addr info for OCSP responder"); + return -1; + } + + sockaddr_len = answer->ai_addrlen; + XMEMCPY(&addr, answer->ai_addr, sockaddr_len); + freeaddrinfo(answer); + + } + #else /* HAVE_GETADDRINFO */ + { struct hostent* entry = gethostbyname(ip); + struct sockaddr_in *sin = (struct sockaddr_in *)&addr; if (entry) { - struct sockaddr_in tmp; - XMEMSET(&tmp, 0, sizeof(struct sockaddr_in)); - XMEMCPY(&tmp.sin_addr.s_addr, entry->h_addr_list[0], - entry->h_length); - host = inet_ntoa(tmp.sin_addr); + sin->sin_family = AF_INET; + sin->sin_port = htons(port); + XMEMCPY(&sin->sin_addr.s_addr, entry->h_addr_list[0], + entry->h_length); } else { - CYASSL_MSG("no addr entry for OCSP responder"); + CYASSL_MSG("no addr info for OCSP responder"); return -1; } } + #endif /* HAVE_GETADDRINFO */ - *sockfd = socket(AF_INET_V, SOCK_STREAM, 0); + *sockfd = socket(addr.ss_family, SOCK_STREAM, 0); if (*sockfd < 0) { CYASSL_MSG("bad socket fd, out of fds?"); return -1; } - XMEMSET(&addr, 0, sizeof(SOCKADDR_IN_T)); - addr.sin_family = AF_INET_V; - addr.sin_port = htons(port); - if (host == INADDR_ANY) - addr.sin_addr.s_addr = INADDR_ANY; - else - addr.sin_addr.s_addr = inet_addr(host); - - if (connect(*sockfd, (const struct sockaddr*)&addr, sizeof(addr)) != 0) { + if (connect(*sockfd, (struct sockaddr *)&addr, sockaddr_len) != 0) { CYASSL_MSG("OCSP responder tcp connect failed"); return -1; } @@ -597,15 +594,26 @@ static int decode_url(const char* url, int urlSz, int i, cur; /* need to break the url down into scheme, address, and port */ - /* "http://example.com:8080/" */ + /* "http://example.com:8080/" */ + /* "http://[::1]:443/" */ if (XSTRNCMP(url, "http://", 7) == 0) { cur = 7; } else cur = 0; i = 0; - while (url[cur] != 0 && url[cur] != ':' && + if (url[cur] == '[') { + cur++; + /* copy until ']' */ + while (url[cur] != 0 && url[cur] != ']' && cur < urlSz) { + outName[i++] = url[cur++]; + } + cur++; /* skip ']' */ + } + else { + while (url[cur] != 0 && url[cur] != ':' && url[cur] != '/' && cur < urlSz) { - outName[i++] = url[cur++]; + outName[i++] = url[cur++]; + } } outName[i] = 0; /* Need to pick out the path after the domain name */ @@ -670,7 +678,7 @@ static int process_http_response(int sfd, byte** respBuf, if (result > 0) { len += result; start = (char*)httpBuf; - start[len+1] = 0; + start[len] = 0; } else { CYASSL_MSG("process_http_response recv http from peer failed"); @@ -929,27 +937,6 @@ CYASSL_API void* CyaSSL_GetCookieCtx(CYASSL* ssl) #endif /* CYASSL_DTLS */ -#ifdef HAVE_OCSP - -CYASSL_API void CyaSSL_SetIOOcsp(CYASSL_CTX* ctx, CallbackIOOcsp cb) -{ - ctx->ocsp.CBIOOcsp = cb; -} - -CYASSL_API void CyaSSL_SetIOOcspRespFree(CYASSL_CTX* ctx, - CallbackIOOcspRespFree cb) -{ - ctx->ocsp.CBIOOcspRespFree = cb; -} - -CYASSL_API void CyaSSL_SetIOOcspCtx(CYASSL_CTX* ctx, void *octx) -{ - ctx->ocsp.IOCB_OcspCtx = octx; -} - -#endif - - #ifdef HAVE_NETX /* The NetX receive callback diff --git a/src/ocsp.c b/src/ocsp.c index 6933e9748..f24fc48b5 100644 --- a/src/ocsp.c +++ b/src/ocsp.c @@ -27,55 +27,32 @@ #ifdef HAVE_OCSP -#ifdef EBSNET - #include "rtip.h" - #include "socket.h" -#endif - #include #include #include -#include - -#include - -#ifndef EBSNET - #include - #include - #include - #include - #include - #include - #include - #include - #include -#endif -CYASSL_API int ocsp_test(unsigned char* buf, int sz); -#define CYASSL_OCSP_ENABLE 0x0001 /* Enable OCSP lookups */ -#define CYASSL_OCSP_URL_OVERRIDE 0x0002 /* Use the override URL instead of URL - * in certificate */ -#define CYASSL_OCSP_NO_NONCE 0x0004 /* Disables the request nonce */ - -typedef struct sockaddr_in SOCKADDR_IN_T; -#define AF_INET_V AF_INET -#define SOCKET_T unsigned int - - -int CyaSSL_OCSP_Init(CYASSL_OCSP* ocsp) +int InitOCSP(CYASSL_OCSP* ocsp, CYASSL_CERT_MANAGER* cm) { - if (ocsp != NULL) { - XMEMSET(ocsp, 0, sizeof(*ocsp)); - ocsp->useNonce = 1; - #ifndef CYASSL_USER_IO - ocsp->CBIOOcsp = EmbedOcspLookup; - ocsp->CBIOOcspRespFree = EmbedOcspRespFree; - #endif - return 0; - } + CYASSL_ENTER("InitOCSP"); + XMEMSET(ocsp, 0, sizeof(*ocsp)); + ocsp->cm = cm; - return -1; + return 0; +} + + +static int InitOCSP_Entry(OCSP_Entry* ocspe, DecodedCert* cert) +{ + CYASSL_ENTER("InitOCSP_Entry"); + + ocspe->next = NULL; + XMEMCPY(ocspe->issuerHash, cert->issuerHash, SHA_DIGEST_SIZE); + XMEMCPY(ocspe->issuerKeyHash, cert->issuerKeyHash, SHA_DIGEST_SIZE); + ocspe->status = NULL; + ocspe->totalStatus = 0; + + return 0; } @@ -93,45 +70,21 @@ static void FreeOCSP_Entry(OCSP_Entry* ocspe) } -void CyaSSL_OCSP_Cleanup(CYASSL_OCSP* ocsp) +void FreeOCSP(CYASSL_OCSP* ocsp, int dynamic) { OCSP_Entry* tmp = ocsp->ocspList; - ocsp->enabled = 0; + CYASSL_ENTER("FreeOCSP"); + while (tmp) { OCSP_Entry* next = tmp->next; FreeOCSP_Entry(tmp); XFREE(tmp, NULL, DYNAMIC_TYPE_OCSP_ENTRY); tmp = next; } -} - -int CyaSSL_OCSP_set_override_url(CYASSL_OCSP* ocsp, const char* url) -{ - if (ocsp != NULL) { - int urlSz = (int)XSTRLEN(url); - if (urlSz < (int)sizeof(ocsp->overrideUrl)) { - XSTRNCPY(ocsp->overrideUrl, url, urlSz); - return 1; - } - } - - return 0; -} - - -static int InitOCSP_Entry(OCSP_Entry* ocspe, DecodedCert* cert) -{ - CYASSL_ENTER("InitOCSP_Entry"); - - ocspe->next = NULL; - XMEMCPY(ocspe->issuerHash, cert->issuerHash, SHA_DIGEST_SIZE); - XMEMCPY(ocspe->issuerKeyHash, cert->issuerKeyHash, SHA_DIGEST_SIZE); - ocspe->status = NULL; - ocspe->totalStatus = 0; - - return 0; + if (dynamic) + XFREE(ocsp, NULL, DYNAMIC_TYPE_OCSP); } @@ -224,7 +177,7 @@ static int xstat2err(int stat) } -int CyaSSL_OCSP_Lookup_Cert(CYASSL_OCSP* ocsp, DecodedCert* cert) +int CheckCertOCSP(CYASSL_OCSP* ocsp, DecodedCert* cert) { byte* ocspReqBuf = NULL; int ocspReqSz = 2048; @@ -237,11 +190,7 @@ int CyaSSL_OCSP_Lookup_Cert(CYASSL_OCSP* ocsp, DecodedCert* cert) const char *url; int urlSz; - /* If OCSP lookups are disabled, return success. */ - if (!ocsp->enabled) { - CYASSL_MSG("OCSP lookup disabled, assuming CERT_GOOD"); - return 0; - } + CYASSL_ENTER("CheckCertOCSP"); ocspe = find_ocsp_entry(ocsp, cert); if (ocspe == NULL) { @@ -275,11 +224,10 @@ int CyaSSL_OCSP_Lookup_Cert(CYASSL_OCSP* ocsp, DecodedCert* cert) } } - if (ocsp->useOverrideUrl) { - if (ocsp->overrideUrl[0] != '\0') { - url = ocsp->overrideUrl; + if (ocsp->cm->ocspUseOverrideURL) { + url = ocsp->cm->ocspOverrideURL; + if (url != NULL && url[0] != '\0') urlSz = (int)XSTRLEN(url); - } else return OCSP_NEED_URL; } @@ -297,11 +245,12 @@ int CyaSSL_OCSP_Lookup_Cert(CYASSL_OCSP* ocsp, DecodedCert* cert) CYASSL_MSG("\talloc OCSP request buffer failed"); return MEMORY_ERROR; } - InitOcspRequest(&ocspRequest, cert, ocsp->useNonce, ocspReqBuf, ocspReqSz); + InitOcspRequest(&ocspRequest, cert, ocsp->cm->ocspSendNonce, + ocspReqBuf, ocspReqSz); ocspReqSz = EncodeOcspRequest(&ocspRequest); - if (ocsp->CBIOOcsp) { - result = ocsp->CBIOOcsp(ocsp->IOCB_OcspCtx, url, urlSz, + if (ocsp->cm->ocspIOCb) { + result = ocsp->cm->ocspIOCb(ocsp->cm->ocspIOCtx, url, urlSz, ocspReqBuf, ocspReqSz, &ocspRespBuf); } @@ -331,8 +280,8 @@ int CyaSSL_OCSP_Lookup_Cert(CYASSL_OCSP* ocsp, DecodedCert* cert) if (ocspReqBuf != NULL) { XFREE(ocspReqBuf, NULL, DYNAMIC_TYPE_IN_BUFFER); } - if (ocspRespBuf != NULL && ocsp->CBIOOcspRespFree) { - ocsp->CBIOOcspRespFree(ocsp->IOCB_OcspCtx, ocspRespBuf); + if (ocspRespBuf != NULL && ocsp->cm->ocspRespFreeCb) { + ocsp->cm->ocspRespFreeCb(ocsp->cm->ocspIOCtx, ocspRespBuf); } return result; diff --git a/src/sniffer.c b/src/sniffer.c index 7eb272f87..8e0bff995 100644 --- a/src/sniffer.c +++ b/src/sniffer.c @@ -417,6 +417,13 @@ void ssl_FreeSniffer(void) FreeMutex(&SessionMutex); FreeMutex(&ServerListMutex); + + if (TraceFile) { + TraceOn = 0; + fclose(TraceFile); + TraceFile = NULL; + } + CyaSSL_Cleanup(); } diff --git a/src/ssl.c b/src/ssl.c index f17449376..e12e66f9e 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -568,6 +568,15 @@ word16 CyaSSL_SNI_GetRequest(CYASSL* ssl, byte type, void** data) return 0; } +int CyaSSL_SNI_GetFromBuffer(const byte* clientHello, word32 helloSz, byte type, + byte* sni, word32* inOutSz) +{ + if (clientHello && helloSz > 0 && sni && inOutSz && *inOutSz > 0) + return TLSX_SNI_GetFromBuffer(clientHello, helloSz, type, sni, inOutSz); + + return BAD_FUNC_ARG; +} + #endif /* NO_CYASSL_SERVER */ #endif /* HAVE_SNI */ @@ -901,6 +910,15 @@ int CyaSSL_GetKeySize(CYASSL* ssl) } +int CyaSSL_GetIVSize(CYASSL* ssl) +{ + if (ssl) + return ssl->specs.iv_size; + + return BAD_FUNC_ARG; +} + + int CyaSSL_GetBulkCipher(CYASSL* ssl) { if (ssl) @@ -967,8 +985,9 @@ int CyaSSL_GetSide(CYASSL* ssl) int CyaSSL_GetHmacSize(CYASSL* ssl) { + /* AEAD ciphers don't have HMAC keys */ if (ssl) - return ssl->specs.hash_size; + return (ssl->specs.cipher_type != aead) ? ssl->specs.hash_size : 0; return BAD_FUNC_ARG; } @@ -986,16 +1005,7 @@ CYASSL_CERT_MANAGER* CyaSSL_CertManagerNew(void) cm = (CYASSL_CERT_MANAGER*) XMALLOC(sizeof(CYASSL_CERT_MANAGER), 0, DYNAMIC_TYPE_CERT_MANAGER); if (cm) { - int i; - - for (i = 0; i < CA_TABLE_SIZE; i++) - cm->caTable[i] = NULL; - cm->heap = NULL; - cm->caCacheCallback = NULL; - cm->crl = NULL; - cm->crlEnabled = 0; - cm->crlCheckAll = 0; - cm->cbMissingCRL = NULL; + XMEMSET(cm, 0, sizeof(CYASSL_CERT_MANAGER)); if (InitMutex(&cm->caLock) != 0) { CYASSL_MSG("Bad mutex init"); @@ -1017,6 +1027,10 @@ void CyaSSL_CertManagerFree(CYASSL_CERT_MANAGER* cm) if (cm->crl) FreeCRL(cm->crl, 1); #endif + #ifdef HAVE_OCSP + if (cm->ocsp) + FreeOCSP(cm->ocsp, 1); + #endif FreeSignerTable(cm->caTable, CA_TABLE_SIZE, NULL); FreeMutex(&cm->caLock); XFREE(cm, NULL, DYNAMIC_TYPE_CERT_MANAGER); @@ -1045,6 +1059,124 @@ int CyaSSL_CertManagerUnloadCAs(CYASSL_CERT_MANAGER* cm) } +/* Return bytes written to buff or < 0 for error */ +int CyaSSL_CertPemToDer(const unsigned char* pem, int pemSz, + unsigned char* buff, int buffSz, + int type) +{ + EncryptedInfo info; + int eccKey = 0; + int ret; + buffer der; + + CYASSL_ENTER("CyaSSL_CertPemToDer"); + + if (pem == NULL || buff == NULL || buffSz <= 0) { + CYASSL_MSG("Bad pem der args"); + return BAD_FUNC_ARG; + } + + if (type != CERT_TYPE && type != CA_TYPE && type != CERTREQ_TYPE) { + CYASSL_MSG("Bad cert type"); + return BAD_FUNC_ARG; + } + + info.set = 0; + info.ctx = NULL; + info.consumed = 0; + der.buffer = NULL; + + ret = PemToDer(pem, pemSz, type, &der, NULL, &info, &eccKey); + if (ret < 0) { + CYASSL_MSG("Bad Pem To Der"); + } + else { + if (der.length <= (word32)buffSz) { + XMEMCPY(buff, der.buffer, der.length); + ret = der.length; + } + else { + CYASSL_MSG("Bad der length"); + ret = BAD_FUNC_ARG; + } + } + + XFREE(der.buffer, NULL, DYNAMIC_TYPE_KEY); + + return ret; +} + + +/* our KeyPemToDer password callback, password in userData */ +static INLINE int OurPasswordCb(char* passwd, int sz, int rw, void* userdata) +{ + (void)rw; + + if (userdata == NULL) + return 0; + + XSTRNCPY(passwd, (char*)userdata, sz); + return min((word32)sz, (word32)XSTRLEN((char*)userdata)); +} + + +/* Return bytes written to buff or < 0 for error */ +int CyaSSL_KeyPemToDer(const unsigned char* pem, int pemSz, unsigned char* buff, + int buffSz, const char* pass) +{ + EncryptedInfo info; + int eccKey = 0; + int ret; + buffer der; + + (void)pass; + + CYASSL_ENTER("CyaSSL_KeyPemToDer"); + + if (pem == NULL || buff == NULL || buffSz <= 0) { + CYASSL_MSG("Bad pem der args"); + return BAD_FUNC_ARG; + } + + info.set = 0; + info.ctx = NULL; + info.consumed = 0; + der.buffer = NULL; + +#ifdef OPENSSL_EXTRA + if (pass) { + info.ctx = CyaSSL_CTX_new(CyaSSLv23_client_method()); + if (info.ctx == NULL) + return MEMORY_E; + CyaSSL_CTX_set_default_passwd_cb(info.ctx, OurPasswordCb); + CyaSSL_CTX_set_default_passwd_cb_userdata(info.ctx, (void*)pass); + } +#endif + + ret = PemToDer(pem, pemSz, PRIVATEKEY_TYPE, &der, NULL, &info, &eccKey); + if (ret < 0) { + CYASSL_MSG("Bad Pem To Der"); + } + else { + if (der.length <= (word32)buffSz) { + XMEMCPY(buff, der.buffer, der.length); + ret = der.length; + } + else { + CYASSL_MSG("Bad der length"); + ret = BAD_FUNC_ARG; + } + } + + XFREE(der.buffer, NULL, DYNAMIC_TYPE_KEY); + + if (info.ctx) + CyaSSL_CTX_free(info.ctx); + + return ret; +} + + #endif /* !NO_CERTS */ @@ -1484,6 +1616,7 @@ int CyaSSL_Init(void) char* consumedEnd; char* bufferEnd = (char*)(buff + longSz); long neededSz; + int ret = 0; int pkcs8 = 0; int pkcs8Enc = 0; int dynamicType = 0; @@ -1497,6 +1630,12 @@ int CyaSSL_Init(void) XSTRNCPY(footer, "-----END CERTIFICATE-----", sizeof(footer)); dynamicType = (type == CA_TYPE) ? DYNAMIC_TYPE_CA : DYNAMIC_TYPE_CERT; + } else if (type == CERTREQ_TYPE) { + XSTRNCPY(header, "-----BEGIN CERTIFICATE REQUEST-----", + sizeof(header)); + XSTRNCPY(footer, "-----END CERTIFICATE REQUEST-----", + sizeof(footer)); + dynamicType = DYNAMIC_TYPE_KEY; } else if (type == DH_PARAM_TYPE) { XSTRNCPY(header, "-----BEGIN DH PARAMETERS-----", sizeof(header)); XSTRNCPY(footer, "-----END DH PARAMETERS-----", sizeof(footer)); @@ -1635,8 +1774,15 @@ int CyaSSL_Init(void) &der->length) < 0) return SSL_BAD_FILE; - if (pkcs8) - return ToTraditional(der->buffer, der->length); + if (pkcs8) { + /* convert and adjust length */ + if ( (ret = ToTraditional(der->buffer, der->length)) < 0 ) { + return ret; + } else { + der->length = ret; + return 0; + } + } #if defined(OPENSSL_EXTRA) && !defined(NO_PWDBASED) if (pkcs8Enc) { @@ -1647,8 +1793,14 @@ int CyaSSL_Init(void) return SSL_BAD_FILE; /* no callback error */ passwordSz = info->ctx->passwd_cb(password, sizeof(password), 0, info->ctx->userdata); - return ToTraditionalEnc(der->buffer, der->length, password, - passwordSz); + /* convert and adjust length */ + if ( (ret = ToTraditionalEnc(der->buffer, der->length, password, + passwordSz)) < 0 ) { + return ret; + } else { + der->length = ret; + return 0; + } } #endif @@ -1677,6 +1829,7 @@ int CyaSSL_Init(void) der.buffer = 0; (void)dynamicType; + (void)rsaKey; if (used) *used = sz; /* used bytes default to sz, PEM chain may shorten*/ @@ -1927,7 +2080,8 @@ int CyaSSL_Init(void) } ecc_free(&key); eccKey = 1; - ctx->haveStaticECC = 1; + if (ctx) + ctx->haveStaticECC = 1; if (ssl) ssl->options.haveStaticECC = 1; } @@ -2399,6 +2553,62 @@ int CyaSSL_CertManagerDisableCRL(CYASSL_CERT_MANAGER* cm) } +/* turn on OCSP if off and compiled in, set options */ +int CyaSSL_CertManagerEnableOCSP(CYASSL_CERT_MANAGER* cm, int options) +{ + int ret = SSL_SUCCESS; + + (void)options; + + CYASSL_ENTER("CyaSSL_CertManagerEnableOCSP"); + if (cm == NULL) + return BAD_FUNC_ARG; + + #ifdef HAVE_OCSP + if (cm->ocsp == NULL) { + cm->ocsp = (CYASSL_OCSP*)XMALLOC(sizeof(CYASSL_OCSP), cm->heap, + DYNAMIC_TYPE_OCSP); + if (cm->ocsp == NULL) + return MEMORY_E; + + if (InitOCSP(cm->ocsp, cm) != 0) { + CYASSL_MSG("Init OCSP failed"); + FreeOCSP(cm->ocsp, 1); + cm->ocsp = NULL; + return SSL_FAILURE; + } + } + cm->ocspEnabled = 1; + if (options & CYASSL_OCSP_URL_OVERRIDE) + cm->ocspUseOverrideURL = 1; + if (options & CYASSL_OCSP_NO_NONCE) + cm->ocspSendNonce = 0; + else + cm->ocspSendNonce = 1; + #ifndef CYASSL_USER_IO + cm->ocspIOCb = EmbedOcspLookup; + cm->ocspRespFreeCb = EmbedOcspRespFree; + #endif /* CYASSL_USER_IO */ + #else + ret = NOT_COMPILED_IN; + #endif + + return ret; +} + + +int CyaSSL_CertManagerDisableOCSP(CYASSL_CERT_MANAGER* cm) +{ + CYASSL_ENTER("CyaSSL_CertManagerDisableOCSP"); + if (cm == NULL) + return BAD_FUNC_ARG; + + cm->ocspEnabled = 0; + + return SSL_SUCCESS; +} + + int CyaSSL_CTX_check_private_key(CYASSL_CTX* ctx) { /* TODO: check private against public for RSA match */ @@ -2561,6 +2771,171 @@ int CyaSSL_CTX_SetCRL_Cb(CYASSL_CTX* ctx, CbMissingCRL cb) #endif /* HAVE_CRL */ +#ifdef HAVE_OCSP + + +/* check CRL if enabled, SSL_SUCCESS */ +int CyaSSL_CertManagerCheckOCSP(CYASSL_CERT_MANAGER* cm, byte* der, int sz) +{ + int ret; + DecodedCert cert; + + CYASSL_ENTER("CyaSSL_CertManagerCheckOCSP"); + + if (cm == NULL) + return BAD_FUNC_ARG; + + if (cm->ocspEnabled == 0) + return SSL_SUCCESS; + + InitDecodedCert(&cert, der, sz, NULL); + + ret = ParseCertRelative(&cert, CERT_TYPE, NO_VERIFY, cm); + if (ret != 0) { + CYASSL_MSG("ParseCert failed"); + return ret; + } + else { + ret = CheckCertOCSP(cm->ocsp, &cert); + if (ret != 0) { + CYASSL_MSG("CheckCertOCSP failed"); + } + } + + FreeDecodedCert(&cert); + + if (ret == 0) + return SSL_SUCCESS; /* convert */ + + return ret; +} + + +int CyaSSL_CertManagerSetOCSPOverrideURL(CYASSL_CERT_MANAGER* cm, + const char* url) +{ + CYASSL_ENTER("CyaSSL_CertManagerSetOCSPOverrideURL"); + if (cm == NULL) + return BAD_FUNC_ARG; + + XFREE(cm->ocspOverrideURL, cm->heap, 0); + if (url != NULL) { + int urlSz = (int)XSTRLEN(url) + 1; + cm->ocspOverrideURL = (char*)XMALLOC(urlSz, cm->heap, 0); + if (cm->ocspOverrideURL != NULL) { + XMEMCPY(cm->ocspOverrideURL, url, urlSz); + } + else + return MEMORY_E; + } + else + cm->ocspOverrideURL = NULL; + + return SSL_SUCCESS; +} + + +int CyaSSL_CertManagerSetOCSP_Cb(CYASSL_CERT_MANAGER* cm, + CbOCSPIO ioCb, CbOCSPRespFree respFreeCb, void* ioCbCtx) +{ + CYASSL_ENTER("CyaSSL_CertManagerSetOCSP_Cb"); + if (cm == NULL) + return BAD_FUNC_ARG; + + cm->ocspIOCb = ioCb; + cm->ocspRespFreeCb = respFreeCb; + cm->ocspIOCtx = ioCbCtx; + + return SSL_SUCCESS; +} + + +int CyaSSL_EnableOCSP(CYASSL* ssl, int options) +{ + CYASSL_ENTER("CyaSSL_EnableOCSP"); + if (ssl) + return CyaSSL_CertManagerEnableOCSP(ssl->ctx->cm, options); + else + return BAD_FUNC_ARG; +} + + +int CyaSSL_DisableOCSP(CYASSL* ssl) +{ + CYASSL_ENTER("CyaSSL_DisableOCSP"); + if (ssl) + return CyaSSL_CertManagerDisableOCSP(ssl->ctx->cm); + else + return BAD_FUNC_ARG; +} + + +int CyaSSL_SetOCSP_OverrideURL(CYASSL* ssl, const char* url) +{ + CYASSL_ENTER("CyaSSL_SetOCSP_OverrideURL"); + if (ssl) + return CyaSSL_CertManagerSetOCSPOverrideURL(ssl->ctx->cm, url); + else + return BAD_FUNC_ARG; +} + + +int CyaSSL_SetOCSP_Cb(CYASSL* ssl, + CbOCSPIO ioCb, CbOCSPRespFree respFreeCb, void* ioCbCtx) +{ + CYASSL_ENTER("CyaSSL_SetOCSP_Cb"); + if (ssl) + return CyaSSL_CertManagerSetOCSP_Cb(ssl->ctx->cm, + ioCb, respFreeCb, ioCbCtx); + else + return BAD_FUNC_ARG; +} + + +int CyaSSL_CTX_EnableOCSP(CYASSL_CTX* ctx, int options) +{ + CYASSL_ENTER("CyaSSL_CTX_EnableOCSP"); + if (ctx) + return CyaSSL_CertManagerEnableOCSP(ctx->cm, options); + else + return BAD_FUNC_ARG; +} + + +int CyaSSL_CTX_DisableOCSP(CYASSL_CTX* ctx) +{ + CYASSL_ENTER("CyaSSL_CTX_DisableOCSP"); + if (ctx) + return CyaSSL_CertManagerDisableOCSP(ctx->cm); + else + return BAD_FUNC_ARG; +} + + +int CyaSSL_CTX_SetOCSP_OverrideURL(CYASSL_CTX* ctx, const char* url) +{ + CYASSL_ENTER("CyaSSL_SetOCSP_OverrideURL"); + if (ctx) + return CyaSSL_CertManagerSetOCSPOverrideURL(ctx->cm, url); + else + return BAD_FUNC_ARG; +} + + +int CyaSSL_CTX_SetOCSP_Cb(CYASSL_CTX* ctx, + CbOCSPIO ioCb, CbOCSPRespFree respFreeCb, void* ioCbCtx) +{ + CYASSL_ENTER("CyaSSL_CTX_SetOCSP_Cb"); + if (ctx) + return CyaSSL_CertManagerSetOCSP_Cb(ctx->cm, ioCb, respFreeCb, ioCbCtx); + else + return BAD_FUNC_ARG; +} + + +#endif /* HAVE_OCSP */ + + #ifdef CYASSL_DER_LOAD /* Add format parameter to allow DER load of CA files */ @@ -7048,28 +7423,170 @@ int CyaSSL_set_compression(CYASSL* ssl) } - /* copy name into in buffer, at most sz bytes, if buffer is null will - malloc buffer, call responsible for freeing */ - char* CyaSSL_X509_NAME_oneline(CYASSL_X509_NAME* name, char* in, int sz) + int CyaSSL_X509_get_isCA(CYASSL_X509* x509) { - int copySz = min(sz, name->sz); + int isCA = 0; - CYASSL_ENTER("CyaSSL_X509_NAME_oneline"); - if (!name->sz) return in; + CYASSL_ENTER("CyaSSL_X509_get_isCA"); - if (!in) { - in = (char*)XMALLOC(name->sz, 0, DYNAMIC_TYPE_OPENSSL); - if (!in ) return in; - copySz = name->sz; + if (x509 != NULL) + isCA = x509->isCa; + + CYASSL_LEAVE("CyaSSL_X509_get_isCA", isCA); + + return isCA; + } + + +#ifdef OPENSSL_EXTRA + int CyaSSL_X509_ext_isSet_by_NID(CYASSL_X509* x509, int nid) + { + int isSet = 0; + + CYASSL_ENTER("CyaSSL_X509_ext_isSet_by_NID"); + + if (x509 != NULL) { + switch (nid) { + case BASIC_CA_OID: isSet = x509->basicConstSet; break; + case ALT_NAMES_OID: isSet = x509->subjAltNameSet; break; + case AUTH_KEY_OID: isSet = x509->authKeyIdSet; break; + case SUBJ_KEY_OID: isSet = x509->subjKeyIdSet; break; + case KEY_USAGE_OID: isSet = x509->keyUsageSet; break; + #ifdef CYASSL_SEP + case CERT_POLICY_OID: isSet = x509->certPolicySet; break; + #endif /* CYASSL_SEP */ + } } - if (copySz == 0) - return in; + CYASSL_LEAVE("CyaSSL_X509_ext_isSet_by_NID", isSet); - XMEMCPY(in, name->name, copySz - 1); - in[copySz - 1] = 0; + return isSet; + } - return in; + + int CyaSSL_X509_ext_get_critical_by_NID(CYASSL_X509* x509, int nid) + { + int crit = 0; + + CYASSL_ENTER("CyaSSL_X509_ext_get_critical_by_NID"); + + if (x509 != NULL) { + switch (nid) { + case BASIC_CA_OID: crit = x509->basicConstCrit; break; + case ALT_NAMES_OID: crit = x509->subjAltNameCrit; break; + case AUTH_KEY_OID: crit = x509->authKeyIdCrit; break; + case SUBJ_KEY_OID: crit = x509->subjKeyIdCrit; break; + case KEY_USAGE_OID: crit = x509->keyUsageCrit; break; + #ifdef CYASSL_SEP + case CERT_POLICY_OID: crit = x509->certPolicyCrit; break; + #endif /* CYASSL_SEP */ + } + } + + CYASSL_LEAVE("CyaSSL_X509_ext_get_critical_by_NID", crit); + + return crit; + } + + + int CyaSSL_X509_get_isSet_pathLength(CYASSL_X509* x509) + { + int isSet = 0; + + CYASSL_ENTER("CyaSSL_X509_get_isSet_pathLength"); + + if (x509 != NULL) + isSet = x509->basicConstPlSet; + + CYASSL_LEAVE("CyaSSL_X509_get_isSet_pathLength", isSet); + + return isSet; + } + + + word32 CyaSSL_X509_get_pathLength(CYASSL_X509* x509) + { + word32 pathLength = 0; + + CYASSL_ENTER("CyaSSL_X509_get_pathLength"); + + if (x509 != NULL) + pathLength = x509->pathLength; + + CYASSL_LEAVE("CyaSSL_X509_get_pathLength", pathLength); + + return pathLength; + } + + + unsigned int CyaSSL_X509_get_keyUsage(CYASSL_X509* x509) + { + word16 usage = 0; + + CYASSL_ENTER("CyaSSL_X509_get_keyUsage"); + + if (x509 != NULL) + usage = x509->keyUsage; + + CYASSL_LEAVE("CyaSSL_X509_get_keyUsage", usage); + + return usage; + } + + + byte* CyaSSL_X509_get_authorityKeyID( + CYASSL_X509* x509, byte* dst, int* dstLen) + { + byte *id = NULL; + int copySz = 0; + + CYASSL_ENTER("CyaSSL_X509_get_authorityKeyID"); + + if (x509 != NULL) { + if (x509->authKeyIdSet) { + copySz = min(dstLen != NULL ? *dstLen : 0, + (int)x509->authKeyIdSz); + id = x509->authKeyId; + } + + if (dst != NULL && dstLen != NULL && id != NULL && copySz > 0) { + XMEMCPY(dst, id, copySz); + id = dst; + *dstLen = copySz; + } + } + + CYASSL_LEAVE("CyaSSL_X509_get_authorityKeyID", copySz); + + return id; + } + + + byte* CyaSSL_X509_get_subjectKeyID( + CYASSL_X509* x509, byte* dst, int* dstLen) + { + byte *id = NULL; + int copySz = 0; + + CYASSL_ENTER("CyaSSL_X509_get_subjectKeyID"); + + if (x509 != NULL) { + if (x509->subjKeyIdSet) { + copySz = min(dstLen != NULL ? *dstLen : 0, + (int)x509->subjKeyIdSz); + id = x509->subjKeyId; + } + + if (dst != NULL && dstLen != NULL && id != NULL && copySz > 0) { + XMEMCPY(dst, id, copySz); + id = dst; + *dstLen = copySz; + } + } + + CYASSL_LEAVE("CyaSSL_X509_get_subjectKeyID", copySz); + + return id; } @@ -7141,6 +7658,32 @@ int CyaSSL_set_compression(CYASSL* ssl) CYASSL_LEAVE("CyaSSL_X509_NAME_get_text_by_NID", textSz); return textSz; } +#endif + + + /* copy name into in buffer, at most sz bytes, if buffer is null will + malloc buffer, call responsible for freeing */ + char* CyaSSL_X509_NAME_oneline(CYASSL_X509_NAME* name, char* in, int sz) + { + int copySz = min(sz, name->sz); + + CYASSL_ENTER("CyaSSL_X509_NAME_oneline"); + if (!name->sz) return in; + + if (!in) { + in = (char*)XMALLOC(name->sz, 0, DYNAMIC_TYPE_OPENSSL); + if (!in ) return in; + copySz = name->sz; + } + + if (copySz == 0) + return in; + + XMEMCPY(in, name->name, copySz - 1); + in[copySz - 1] = 0; + + return in; + } int CyaSSL_X509_get_signature_type(CYASSL_X509* x509) @@ -7340,6 +7883,8 @@ CYASSL_X509* CyaSSL_X509_d2i(CYASSL_X509** x509, const byte* in, int len) } +#ifndef NO_FILESYSTEM + CYASSL_X509* CyaSSL_X509_d2i_fp(CYASSL_X509** x509, XFILE file) { CYASSL_X509* newX509 = NULL; @@ -7463,6 +8008,7 @@ CYASSL_X509* CyaSSL_X509_load_certificate_file(const char* fname, int format) return x509; } +#endif /* NO_FILESYSTEM */ #endif /* KEEP_PEER_CERT || SESSION_CERTS */ @@ -8329,6 +8875,9 @@ CYASSL_X509* CyaSSL_X509_load_certificate_file(const char* fname, int format) XMEMCPY(key->pkey.ptr, x509->pubKey.buffer, x509->pubKey.length); key->pkey_sz = x509->pubKey.length; + #ifdef HAVE_ECC + key->pkey_curve = (int)x509->pkCurveOID; + #endif /* HAVE_ECC */ } } return key; @@ -10430,49 +10979,6 @@ static int initGlobalRNG = 0; -/* Return bytes written to buff or < 0 for error */ -int CyaSSL_KeyPemToDer(const unsigned char* pem, int pemSz, unsigned char* buff, - int buffSz, const char* pass) -{ - EncryptedInfo info; - int eccKey = 0; - int ret; - buffer der; - - (void)pass; - - CYASSL_ENTER("CyaSSL_KeyPemToDer"); - - if (pem == NULL || buff == NULL || buffSz <= 0) { - CYASSL_MSG("Bad pem der args"); - return BAD_FUNC_ARG; - } - - info.set = 0; - info.ctx = NULL; - info.consumed = 0; - der.buffer = NULL; - - ret = PemToDer(pem, pemSz, PRIVATEKEY_TYPE, &der, NULL, &info, &eccKey); - if (ret < 0) { - CYASSL_MSG("Bad Pem To Der"); - } - else { - if (der.length <= (word32)buffSz) { - XMEMCPY(buff, der.buffer, der.length); - ret = der.length; - } - else { - CYASSL_MSG("Bad der length"); - ret = BAD_FUNC_ARG; - } - } - - XFREE(der.buffer, NULL, DYNAMIC_TYPE_KEY); - - return ret; -} - /* Load RSA from Der, SSL_SUCCESS on success < 0 on error */ int CyaSSL_RSA_LoadDer(CYASSL_RSA* rsa, const unsigned char* der, int derSz) @@ -10685,38 +11191,6 @@ const byte* CyaSSL_get_sessionID(const CYASSL_SESSION* session) #endif /* SESSION_CERTS */ -int CyaSSL_CTX_OCSP_set_options(CYASSL_CTX* ctx, int options) -{ - CYASSL_ENTER("CyaSSL_CTX_OCSP_set_options"); -#ifdef HAVE_OCSP - if (ctx != NULL) { - ctx->ocsp.enabled = (options & CYASSL_OCSP_ENABLE) != 0; - ctx->ocsp.useOverrideUrl = (options & CYASSL_OCSP_URL_OVERRIDE) != 0; - ctx->ocsp.useNonce = (options & CYASSL_OCSP_NO_NONCE) == 0; - return SSL_SUCCESS; - } - return SSL_FAILURE; -#else - (void)ctx; - (void)options; - return NOT_COMPILED_IN; -#endif -} - - -int CyaSSL_CTX_OCSP_set_override_url(CYASSL_CTX* ctx, const char* url) -{ - CYASSL_ENTER("CyaSSL_CTX_OCSP_set_override_url"); -#ifdef HAVE_OCSP - return CyaSSL_OCSP_set_override_url(&ctx->ocsp, url); -#else - (void)ctx; - (void)url; - return NOT_COMPILED_IN; -#endif -} - - #ifndef NO_CERTS #ifdef HAVE_PK_CALLBACKS @@ -10866,3 +11340,9 @@ void* CyaSSL_GetRsaDecCtx(CYASSL* ssl) #endif /* HAVE_PK_CALLBACKS */ #endif /* NO_CERTS */ + +#ifdef CYASSL_HAVE_WOLFSCEP + /* Used by autoconf to see if wolfSCEP is available */ + void CyaSSL_wolfSCEP(void) {} +#endif + diff --git a/src/tls.c b/src/tls.c index 878e2e003..482271ba6 100644 --- a/src/tls.c +++ b/src/tls.c @@ -376,6 +376,14 @@ static INLINE void ato16(const byte* c, word16* u16) { *u16 = (c[0] << 8) | (c[1]); } + +#ifdef HAVE_SNI +/* convert a 24 bit integer into a 32 bit one */ +static INLINE void c24to32(const word24 u24, word32* u32) +{ + *u32 = (u24[0] << 16) | (u24[1] << 8) | u24[2]; +} +#endif #endif /* convert 32 bit integer to opaque */ @@ -393,7 +401,7 @@ static INLINE word32 GetSEQIncrement(CYASSL* ssl, int verify) #ifdef CYASSL_DTLS if (ssl->options.dtls) { if (verify) - return ssl->keys.dtls_peer_sequence_number; /* explicit from peer */ + return ssl->keys.dtls_state.curSeq; /* explicit from peer */ else return ssl->keys.dtls_sequence_number - 1; /* already incremented */ } @@ -410,9 +418,9 @@ static INLINE word32 GetSEQIncrement(CYASSL* ssl, int verify) static INLINE word32 GetEpoch(CYASSL* ssl, int verify) { if (verify) - return ssl->keys.dtls_peer_epoch; + return ssl->keys.dtls_state.curEpoch; else - return ssl->keys.dtls_epoch; + return ssl->keys.dtls_epoch; } #endif /* CYASSL_DTLS */ @@ -854,6 +862,135 @@ void TLSX_SNI_SetOptions(TLSX* extensions, byte type, byte options) if (sni) sni->options = options; } + +int TLSX_SNI_GetFromBuffer(const byte* clientHello, word32 helloSz, + byte type, byte* sni, word32* inOutSz) +{ + word32 offset = 0; + word32 len32 = 0; + word16 len16 = 0; + + if (helloSz < RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ + CLIENT_HELLO_FIRST) + return INCOMPLETE_DATA; + + /* TLS record header */ + if ((enum ContentType) clientHello[offset++] != handshake) + return BUFFER_ERROR; + + if (clientHello[offset++] != SSLv3_MAJOR) + return BUFFER_ERROR; + + if (clientHello[offset++] < TLSv1_MINOR) + return BUFFER_ERROR; + + ato16(clientHello + offset, &len16); + offset += OPAQUE16_LEN; + + if (offset + len16 > helloSz) + return INCOMPLETE_DATA; + + /* Handshake header */ + if ((enum HandShakeType) clientHello[offset] != client_hello) + return BUFFER_ERROR; + + c24to32(clientHello + offset + 1, &len32); + offset += HANDSHAKE_HEADER_SZ; + + if (offset + len32 > helloSz) + return INCOMPLETE_DATA; + + /* client hello */ + offset += VERSION_SZ + RAN_LEN; /* version, random */ + + if (helloSz < offset + clientHello[offset]) + return INCOMPLETE_DATA; + + offset += ENUM_LEN + clientHello[offset]; /* skip session id */ + + /* cypher suites */ + if (helloSz < offset + OPAQUE16_LEN) + return INCOMPLETE_DATA; + + ato16(clientHello + offset, &len16); + offset += OPAQUE16_LEN; + + if (helloSz < offset + len16) + return INCOMPLETE_DATA; + + offset += len16; /* skip cypher suites */ + + /* compression methods */ + if (helloSz < offset + 1) + return INCOMPLETE_DATA; + + if (helloSz < offset + clientHello[offset]) + return INCOMPLETE_DATA; + + offset += ENUM_LEN + clientHello[offset]; /* skip compression methods */ + + /* extensions */ + if (helloSz < offset + OPAQUE16_LEN) + return 0; /* no extensions in client hello. */ + + ato16(clientHello + offset, &len16); + offset += OPAQUE16_LEN; + + if (helloSz < offset + len16) + return INCOMPLETE_DATA; + + while (len16 > OPAQUE16_LEN + OPAQUE16_LEN) { + word16 extType; + word16 extLen; + + ato16(clientHello + offset, &extType); + offset += OPAQUE16_LEN; + + ato16(clientHello + offset, &extLen); + offset += OPAQUE16_LEN; + + if (helloSz < offset + extLen) + return INCOMPLETE_DATA; + + if (extType != SERVER_NAME_INDICATION) { + offset += extLen; /* skip extension */ + } else { + word16 listLen; + + ato16(clientHello + offset, &listLen); + offset += OPAQUE16_LEN; + + if (helloSz < offset + listLen) + return INCOMPLETE_DATA; + + while (listLen > ENUM_LEN + OPAQUE16_LEN) { + byte sniType = clientHello[offset++]; + word16 sniLen; + + ato16(clientHello + offset, &sniLen); + offset += OPAQUE16_LEN; + + if (helloSz < offset + sniLen) + return INCOMPLETE_DATA; + + if (sniType != type) { + offset += sniLen; + listLen -= min(ENUM_LEN + OPAQUE16_LEN + sniLen, listLen); + continue; + } + + *inOutSz = min(sniLen, *inOutSz); + XMEMCPY(sni, clientHello + offset, *inOutSz); + + return SSL_SUCCESS; + } + } + + len16 -= min(2 * OPAQUE16_LEN + extLen, len16); + } + + return len16 ? BUFFER_ERROR : SSL_SUCCESS; +} + #endif #define SNI_FREE_ALL TLSX_SNI_FreeAll @@ -1004,9 +1141,6 @@ static int TLSX_THM_Parse(CYASSL* ssl, byte* input, word16 length, ssl->truncated_hmac = 1; -#error "TRUNCATED HMAC IS NOT FINISHED YET \ -(contact moises@wolfssl.com for more info)" - return 0; } diff --git a/sslSniffer/sslSnifferTest/include.am b/sslSniffer/sslSnifferTest/include.am index 44349f976..d4c90accc 100644 --- a/sslSniffer/sslSnifferTest/include.am +++ b/sslSniffer/sslSnifferTest/include.am @@ -2,7 +2,7 @@ # included from Top Level Makefile.am # All paths should be given relative to the root -if BUILD_SNIFFER +if BUILD_SNIFFTEST noinst_PROGRAMS += sslSniffer/sslSnifferTest/snifftest sslSniffer_sslSnifferTest_snifftest_SOURCES = sslSniffer/sslSnifferTest/snifftest.c sslSniffer_sslSnifferTest_snifftest_LDADD = src/libcyassl.la -lpcap diff --git a/sslSniffer/sslSnifferTest/snifftest.c b/sslSniffer/sslSnifferTest/snifftest.c index 7d5a7561e..2570a65bc 100755 --- a/sslSniffer/sslSnifferTest/snifftest.c +++ b/sslSniffer/sslSnifferTest/snifftest.c @@ -69,18 +69,25 @@ enum { }; -pcap_t* pcap = 0; -pcap_if_t *alldevs; +pcap_t* pcap = NULL; +pcap_if_t* alldevs = NULL; + + +static void FreeAll(void) +{ + if (pcap) + pcap_close(pcap); + if (alldevs) + pcap_freealldevs(alldevs); +#ifndef _WIN32 + ssl_FreeSniffer(); +#endif +} static void sig_handler(const int sig) { printf("SIGINT handled = %d.\n", sig); - if (pcap) - pcap_close(pcap); - pcap_freealldevs(alldevs); -#ifndef _WIN32 - ssl_FreeSniffer(); -#endif + FreeAll(); if (sig) exit(EXIT_SUCCESS); } @@ -286,6 +293,7 @@ int main(int argc, char** argv) else if (saveFile) break; /* we're done reading file */ } + FreeAll(); return EXIT_SUCCESS; } diff --git a/tests/api.c b/tests/api.c index ecd89a5ba..3dadad7a1 100644 --- a/tests/api.c +++ b/tests/api.c @@ -332,6 +332,88 @@ static void verify_SNI_fake_matching(CYASSL* ssl) AssertStrEQ(name, request); } +static void test_CyaSSL_SNI_GetFromBuffer(void) +{ + byte buffer[] = { /* www.paypal.com */ + 0x00, 0x00, 0x00, 0x00, 0xff, 0x01, 0x00, 0x00, 0x60, 0x03, 0x03, 0x5c, + 0xc4, 0xb3, 0x8c, 0x87, 0xef, 0xa4, 0x09, 0xe0, 0x02, 0xab, 0x86, 0xca, + 0x76, 0xf0, 0x9e, 0x01, 0x65, 0xf6, 0xa6, 0x06, 0x13, 0x1d, 0x0f, 0xa5, + 0x79, 0xb0, 0xd4, 0x77, 0x22, 0xeb, 0x1a, 0x00, 0x00, 0x16, 0x00, 0x6b, + 0x00, 0x67, 0x00, 0x39, 0x00, 0x33, 0x00, 0x3d, 0x00, 0x3c, 0x00, 0x35, + 0x00, 0x2f, 0x00, 0x05, 0x00, 0x04, 0x00, 0x0a, 0x01, 0x00, 0x00, 0x21, + 0x00, 0x00, 0x00, 0x13, 0x00, 0x11, 0x00, 0x00, 0x0e, 0x77, 0x77, 0x77, + 0x2e, 0x70, 0x61, 0x79, 0x70, 0x61, 0x6c, 0x2e, 0x63, 0x6f, 0x6d, 0x00, + 0x0d, 0x00, 0x06, 0x00, 0x04, 0x04, 0x01, 0x02, 0x01 + }; + + byte buffer2[] = { /* api.textmate.org */ + 0x16, 0x03, 0x01, 0x00, 0xc6, 0x01, 0x00, 0x00, 0xc2, 0x03, 0x03, 0x52, + 0x8b, 0x7b, 0xca, 0x69, 0xec, 0x97, 0xd5, 0x08, 0x03, 0x50, 0xfe, 0x3b, + 0x99, 0xc3, 0x20, 0xce, 0xa5, 0xf6, 0x99, 0xa5, 0x71, 0xf9, 0x57, 0x7f, + 0x04, 0x38, 0xf6, 0x11, 0x0b, 0xb8, 0xd3, 0x00, 0x00, 0x5e, 0x00, 0xff, + 0xc0, 0x24, 0xc0, 0x23, 0xc0, 0x0a, 0xc0, 0x09, 0xc0, 0x07, 0xc0, 0x08, + 0xc0, 0x28, 0xc0, 0x27, 0xc0, 0x14, 0xc0, 0x13, 0xc0, 0x11, 0xc0, 0x12, + 0xc0, 0x26, 0xc0, 0x25, 0xc0, 0x2a, 0xc0, 0x29, 0xc0, 0x05, 0xc0, 0x04, + 0xc0, 0x02, 0xc0, 0x03, 0xc0, 0x0f, 0xc0, 0x0e, 0xc0, 0x0c, 0xc0, 0x0d, + 0x00, 0x3d, 0x00, 0x3c, 0x00, 0x2f, 0x00, 0x05, 0x00, 0x04, 0x00, 0x35, + 0x00, 0x0a, 0x00, 0x67, 0x00, 0x6b, 0x00, 0x33, 0x00, 0x39, 0x00, 0x16, + 0x00, 0xaf, 0x00, 0xae, 0x00, 0x8d, 0x00, 0x8c, 0x00, 0x8a, 0x00, 0x8b, + 0x00, 0xb1, 0x00, 0xb0, 0x00, 0x2c, 0x00, 0x3b, 0x01, 0x00, 0x00, 0x3b, + 0x00, 0x00, 0x00, 0x15, 0x00, 0x13, 0x00, 0x00, 0x10, 0x61, 0x70, 0x69, + 0x2e, 0x74, 0x65, 0x78, 0x74, 0x6d, 0x61, 0x74, 0x65, 0x2e, 0x6f, 0x72, + 0x67, 0x00, 0x0a, 0x00, 0x08, 0x00, 0x06, 0x00, 0x17, 0x00, 0x18, 0x00, + 0x19, 0x00, 0x0b, 0x00, 0x02, 0x01, 0x00, 0x00, 0x0d, 0x00, 0x0c, 0x00, + 0x0a, 0x05, 0x01, 0x04, 0x01, 0x02, 0x01, 0x04, 0x03, 0x02, 0x03 + }; + + byte buffer3[] = { /* no sni extension */ + 0x16, 0x03, 0x03, 0x00, 0x4d, 0x01, 0x00, 0x00, 0x49, 0x03, 0x03, 0xea, + 0xa1, 0x9f, 0x60, 0xdd, 0x52, 0x12, 0x13, 0xbd, 0x84, 0x34, 0xd5, 0x1c, + 0x38, 0x25, 0xa8, 0x97, 0xd2, 0xd5, 0xc6, 0x45, 0xaf, 0x1b, 0x08, 0xe4, + 0x1e, 0xbb, 0xdf, 0x9d, 0x39, 0xf0, 0x65, 0x00, 0x00, 0x16, 0x00, 0x6b, + 0x00, 0x67, 0x00, 0x39, 0x00, 0x33, 0x00, 0x3d, 0x00, 0x3c, 0x00, 0x35, + 0x00, 0x2f, 0x00, 0x05, 0x00, 0x04, 0x00, 0x0a, 0x01, 0x00, 0x00, 0x0a, + 0x00, 0x0d, 0x00, 0x06, 0x00, 0x04, 0x04, 0x01, 0x02, 0x01 + }; + + byte result[32] = {0}; + word32 length = 32; + + AssertIntEQ(SSL_SUCCESS, CyaSSL_SNI_GetFromBuffer(buffer3, sizeof(buffer3), + 0, result, &length)); + + AssertIntEQ(SSL_SUCCESS, CyaSSL_SNI_GetFromBuffer(buffer2, sizeof(buffer2), + 1, result, &length)); + + AssertIntEQ(-228, CyaSSL_SNI_GetFromBuffer(buffer, sizeof(buffer), 0, + result, &length)); + buffer[0] = 0x16; + + AssertIntEQ(-228, CyaSSL_SNI_GetFromBuffer(buffer, sizeof(buffer), 0, + result, &length)); + buffer[1] = 0x03; + + AssertIntEQ(-228, CyaSSL_SNI_GetFromBuffer(buffer, sizeof(buffer), 0, + result, &length)); + buffer[2] = 0x03; + + AssertIntEQ(-210, CyaSSL_SNI_GetFromBuffer(buffer, sizeof(buffer), 0, + result, &length)); + buffer[4] = 0x64; + + AssertIntEQ(1, CyaSSL_SNI_GetFromBuffer(buffer, sizeof(buffer), 0, + result, &length)); + result[length] = 0; + AssertStrEQ("www.paypal.com", (const char*) result); + + length = 32; + + AssertIntEQ(1, CyaSSL_SNI_GetFromBuffer(buffer2, sizeof(buffer2), 0, + result, &length)); + result[length] = 0; + AssertStrEQ("api.textmate.org", (const char*) result); +} + void test_CyaSSL_UseSNI(void) { callback_functions client_callbacks = {CyaSSLv23_client_method, 0, 0, 0}; @@ -358,6 +440,8 @@ void test_CyaSSL_UseSNI(void) CyaSSL_free(ssl); CyaSSL_CTX_free(ctx); +#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS) + /* Testing success case at ctx */ client_callbacks.ctx_ready = server_callbacks.ctx_ready = use_SNI_at_ctx; server_callbacks.on_result = verify_SNI_real_matching; @@ -390,6 +474,10 @@ void test_CyaSSL_UseSNI(void) server_callbacks.on_result = verify_SNI_fake_matching; test_CyaSSL_client_server(&client_callbacks, &server_callbacks); + +#endif + + test_CyaSSL_SNI_GetFromBuffer(); } #endif /* HAVE_SNI */ diff --git a/tests/unit.c b/tests/unit.c index 72f14ff68..f1926f2e9 100644 --- a/tests/unit.c +++ b/tests/unit.c @@ -27,10 +27,10 @@ int main(int argc, char** argv) err_sys("Cavium OpenNitroxDevice failed"); #endif /* HAVE_CAVIUM */ - if (CurrentDir("tests")) + if (CurrentDir("tests") || CurrentDir("_build")) ChangeDirBack(1); - else if (CurrentDir("build")) - ChangeDirBack(2); + else if (CurrentDir("Debug") || CurrentDir("Release")) + ChangeDirBack(3); if ( (ret = ApiTest()) != 0) { printf("api test failed with %d\n", ret); diff --git a/testsuite/testsuite.c b/testsuite/testsuite.c index 351a7471f..6d6cc8921 100644 --- a/testsuite/testsuite.c +++ b/testsuite/testsuite.c @@ -51,11 +51,16 @@ enum { NUMARGS = 3 }; +#ifndef USE_WINDOWS_API + const char outputName[] = "/tmp/output"; +#else + const char outputName[] = "output"; +#endif + int myoptind = 0; char* myoptarg = NULL; - int main(int argc, char** argv) { func_args server_args; @@ -79,11 +84,13 @@ int main(int argc, char** argv) CyaSSL_Debugging_ON(); #endif - if (CurrentDir("testsuite")) + if (CurrentDir("testsuite") || CurrentDir("_build")) ChangeDirBack(1); - else if (CurrentDir("build")) /* Xcode->Preferences->Locations->Build */ - ChangeDirBack(2); /* Location "Place build product in locations - specified by targets", uses build/Debug */ + else if (CurrentDir("Debug") || CurrentDir("Release")) + ChangeDirBack(3); /* Xcode->Preferences->Locations->Locations*/ + /* Derived Data Advanced -> Custom */ + /* Relative to Workspace, Build/Products */ + /* Debug or Release */ server_args.signal = &ready; InitTcpReady(&ready); @@ -115,8 +122,8 @@ int main(int argc, char** argv) strcpy(echo_args.argv[0], "echoclient"); strcpy(echo_args.argv[1], "input"); - strcpy(echo_args.argv[2], "output"); - remove("output"); + strcpy(echo_args.argv[2], outputName); + remove(outputName); /* Share the signal, it has the new port number in it. */ echo_args.signal = server_args.signal; @@ -144,7 +151,7 @@ int main(int argc, char** argv) byte output[SHA256_DIGEST_SIZE]; file_test("input", input); - file_test("output", output); + file_test(outputName, output); if (memcmp(input, output, sizeof(input)) != 0) return EXIT_FAILURE; }