blob: 8456c5839262c173bab93f7179e8eb4dd762c790 [file] [log] [blame]
/* ssl.c
*
* Copyright (C) 2006-2012 Sawtooth Consulting Ltd.
*
* 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 <config.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#define TRUE 1
#define FALSE 0
#include <cyassl/ssl.h>
#include <cyassl/internal.h>
#include <cyassl/error.h>
#include <cyassl/ctaocrypt/coding.h>
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
#include <cyassl/openssl/evp.h>
#endif
#ifdef OPENSSL_EXTRA
/* openssl headers begin */
#include <cyassl/openssl/hmac.h>
#include <cyassl/openssl/crypto.h>
#include <cyassl/openssl/des.h>
#include <cyassl/openssl/bn.h>
#include <cyassl/openssl/dh.h>
#include <cyassl/openssl/rsa.h>
#include <cyassl/openssl/pem.h>
/* openssl headers end, cyassl internal headers next */
#include <cyassl/ctaocrypt/hmac.h>
#include <cyassl/ctaocrypt/random.h>
#include <cyassl/ctaocrypt/des3.h>
#include <cyassl/ctaocrypt/md4.h>
#include <cyassl/ctaocrypt/md5.h>
#include <cyassl/ctaocrypt/arc4.h>
#ifdef CYASSL_SHA512
#include <cyassl/ctaocrypt/sha512.h>
#endif
#endif
#ifndef NO_FILESYSTEM
#if !defined(USE_WINDOWS_API) && !defined(NO_CYASSL_DIR)
#include <dirent.h>
#endif
#endif /* NO_FILESYSTEM */
#ifndef min
static INLINE word32 min(word32 a, word32 b)
{
return a > b ? b : a;
}
#endif /* min */
char* mystrnstr(const char* s1, const char* s2, unsigned int n)
{
unsigned int s2_len = XSTRLEN(s2);
if (s2_len == 0)
return (char*)s1;
while (n >= s2_len && s1[0]) {
if (s1[0] == s2[0])
if (XMEMCMP(s1, s2, s2_len) == 0)
return (char*)s1;
s1++;
n--;
}
return NULL;
}
CYASSL_CTX* CyaSSL_CTX_new(CYASSL_METHOD* method)
{
CYASSL_CTX* ctx = NULL;
CYASSL_ENTER("CYASSL_CTX_new");
if (method == NULL)
return ctx;
ctx = (CYASSL_CTX*) XMALLOC(sizeof(CYASSL_CTX), 0, DYNAMIC_TYPE_CTX);
if (ctx) {
if (InitSSL_Ctx(ctx, method) < 0) {
CYASSL_MSG("Init CTX failed");
CyaSSL_CTX_free(ctx);
ctx = NULL;
}
}
CYASSL_LEAVE("CYASSL_CTX_new", 0);
return ctx;
}
void CyaSSL_CTX_free(CYASSL_CTX* ctx)
{
CYASSL_ENTER("SSL_CTX_free");
if (ctx)
FreeSSL_Ctx(ctx);
CYASSL_LEAVE("SSL_CTX_free", 0);
}
CYASSL* CyaSSL_new(CYASSL_CTX* ctx)
{
CYASSL* ssl = NULL;
CYASSL_ENTER("SSL_new");
if (ctx == NULL)
return ssl;
ssl = (CYASSL*) XMALLOC(sizeof(CYASSL), ctx->heap,DYNAMIC_TYPE_SSL);
if (ssl)
if (InitSSL(ssl, ctx) < 0) {
FreeSSL(ssl);
ssl = 0;
}
CYASSL_LEAVE("SSL_new", 0);
return ssl;
}
void CyaSSL_free(CYASSL* ssl)
{
CYASSL_ENTER("SSL_free");
if (ssl)
FreeSSL(ssl);
CYASSL_LEAVE("SSL_free", 0);
}
int CyaSSL_set_fd(CYASSL* ssl, int fd)
{
CYASSL_ENTER("SSL_set_fd");
ssl->rfd = fd; /* not used directly to allow IO callbacks */
ssl->wfd = fd;
ssl->IOCB_ReadCtx = &ssl->rfd;
ssl->IOCB_WriteCtx = &ssl->wfd;
CYASSL_LEAVE("SSL_set_fd", SSL_SUCCESS);
return SSL_SUCCESS;
}
int CyaSSL_get_fd(const CYASSL* ssl)
{
CYASSL_ENTER("SSL_get_fd");
CYASSL_LEAVE("SSL_get_fd", ssl->rfd);
return ssl->rfd;
}
int CyaSSL_negotiate(CYASSL* ssl)
{
int err = SSL_FATAL_ERROR;
CYASSL_ENTER("CyaSSL_negotiate");
#ifndef NO_CYASSL_SERVER
if (ssl->options.side == SERVER_END)
err = CyaSSL_accept(ssl);
#endif
#ifndef NO_CYASSL_CLIENT
if (ssl->options.side == CLIENT_END)
err = CyaSSL_connect(ssl);
#endif
CYASSL_LEAVE("CyaSSL_negotiate", err);
if (err == SSL_SUCCESS)
return 0;
else
return err;
}
/* server Diffie-Hellman parameters */
int CyaSSL_SetTmpDH(CYASSL* ssl, const unsigned char* p, int pSz,
const unsigned char* g, int gSz)
{
byte havePSK = 0;
CYASSL_ENTER("CyaSSL_SetTmpDH");
if (ssl == NULL || p == NULL || g == NULL) return BAD_FUNC_ARG;
if (ssl->options.side != SERVER_END)
return SIDE_ERROR;
if (ssl->buffers.serverDH_P.buffer && ssl->buffers.weOwnDH)
XFREE(ssl->buffers.serverDH_P.buffer, ssl->ctx->heap, DYNAMIC_TYPE_DH);
if (ssl->buffers.serverDH_G.buffer && ssl->buffers.weOwnDH)
XFREE(ssl->buffers.serverDH_G.buffer, ssl->ctx->heap, DYNAMIC_TYPE_DH);
ssl->buffers.weOwnDH = 1; /* SSL owns now */
ssl->buffers.serverDH_P.buffer = (byte*)XMALLOC(pSz, ssl->ctx->heap,
DYNAMIC_TYPE_DH);
if (ssl->buffers.serverDH_P.buffer == NULL)
return MEMORY_E;
ssl->buffers.serverDH_G.buffer = (byte*)XMALLOC(gSz, ssl->ctx->heap,
DYNAMIC_TYPE_DH);
if (ssl->buffers.serverDH_G.buffer == NULL) {
XFREE(ssl->buffers.serverDH_P.buffer, ssl->ctx->heap, DYNAMIC_TYPE_DH);
return MEMORY_E;
}
ssl->buffers.serverDH_P.length = pSz;
ssl->buffers.serverDH_G.length = gSz;
XMEMCPY(ssl->buffers.serverDH_P.buffer, p, pSz);
XMEMCPY(ssl->buffers.serverDH_G.buffer, g, gSz);
ssl->options.haveDH = 1;
#ifndef NO_PSK
havePSK = ssl->options.havePSK;
#endif
InitSuites(&ssl->suites, ssl->version, ssl->options.haveDH,
havePSK, ssl->options.haveNTRU, ssl->options.haveECDSAsig,
ssl->options.haveStaticECC, ssl->options.side);
CYASSL_LEAVE("CyaSSL_SetTmpDH", 0);
return 0;
}
int CyaSSL_write(CYASSL* ssl, const void* data, int sz)
{
int ret;
CYASSL_ENTER("SSL_write()");
#ifdef HAVE_ERRNO_H
errno = 0;
#endif
ret = SendData(ssl, data, sz);
CYASSL_LEAVE("SSL_write()", ret);
if (ret < 0)
return SSL_FATAL_ERROR;
else
return ret;
}
int CyaSSL_read(CYASSL* ssl, void* data, int sz)
{
int ret;
CYASSL_ENTER("SSL_read()");
#ifdef HAVE_ERRNO_H
errno = 0;
#endif
ret = ReceiveData(ssl, (byte*)data, min(sz, OUTPUT_RECORD_SIZE));
CYASSL_LEAVE("SSL_read()", ret);
if (ret < 0)
return SSL_FATAL_ERROR;
else
return ret;
}
int CyaSSL_shutdown(CYASSL* ssl)
{
CYASSL_ENTER("SSL_shutdown()");
if (ssl->options.quietShutdown) {
CYASSL_MSG("quiet shutdown, no close notify sent");
return 0;
}
/* try to send close notify, not an error if can't */
if (!ssl->options.isClosed && !ssl->options.connReset &&
!ssl->options.sentNotify) {
ssl->error = SendAlert(ssl, alert_warning, close_notify);
if (ssl->error < 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
ssl->options.sentNotify = 1; /* don't send close_notify twice */
}
CYASSL_LEAVE("SSL_shutdown()", ssl->error);
ssl->error = SSL_ERROR_SYSCALL; /* simulate OpenSSL behavior */
return 0;
}
int CyaSSL_get_error(CYASSL* ssl, int ret)
{
CYASSL_ENTER("SSL_get_error");
CYASSL_LEAVE("SSL_get_error", ssl->error);
if (ret > 0)
return SSL_ERROR_NONE;
if (ssl->error == WANT_READ)
return SSL_ERROR_WANT_READ; /* convert to OpenSSL type */
else if (ssl->error == WANT_WRITE)
return SSL_ERROR_WANT_WRITE; /* convert to OpenSSL type */
else if (ssl->error == ZERO_RETURN)
return SSL_ERROR_ZERO_RETURN; /* convert to OpenSSL type */
return ssl->error;
}
int CyaSSL_want_read(CYASSL* ssl)
{
CYASSL_ENTER("SSL_want_read");
if (ssl->error == WANT_READ)
return 1;
return 0;
}
int CyaSSL_want_write(CYASSL* ssl)
{
CYASSL_ENTER("SSL_want_write");
if (ssl->error == WANT_WRITE)
return 1;
return 0;
}
char* CyaSSL_ERR_error_string(unsigned long errNumber, char* data)
{
static const char* msg = "Please supply a buffer for error string";
CYASSL_ENTER("ERR_error_string");
if (data) {
SetErrorString(errNumber, data);
return data;
}
return (char*)msg;
}
void CyaSSL_ERR_error_string_n(unsigned long e, char* buf, unsigned long len)
{
CYASSL_ENTER("CyaSSL_ERR_error_string_n");
if (len) CyaSSL_ERR_error_string(e, buf);
}
CYASSL_CERT_MANAGER* CyaSSL_CertManagerNew(void)
{
CYASSL_CERT_MANAGER* cm = NULL;
CYASSL_ENTER("CyaSSL_CertManagerNew");
cm = (CYASSL_CERT_MANAGER*) XMALLOC(sizeof(CYASSL_CERT_MANAGER), 0,
DYNAMIC_TYPE_CERT_MANAGER);
if (cm) {
cm->caList = NULL;
cm->heap = NULL;
cm->caCacheCallback = NULL;
cm->crl = NULL;
cm->crlEnabled = 0;
cm->crlCheckAll = 0;
cm->cbMissingCRL = NULL;
if (InitMutex(&cm->caLock) != 0) {
CYASSL_MSG("Bad mutex init");
CyaSSL_CertManagerFree(cm);
return NULL;
}
}
return cm;
}
void CyaSSL_CertManagerFree(CYASSL_CERT_MANAGER* cm)
{
CYASSL_ENTER("CyaSSL_CertManagerFree");
if (cm) {
#ifdef HAVE_CRL
if (cm->crl)
FreeCRL(cm->crl);
#endif
FreeSigners(cm->caList, NULL);
FreeMutex(&cm->caLock);
XFREE(cm, NULL, DYNAMIC_TYPE_CERT_MANAGER);
}
}
#ifndef NO_FILESYSTEM
void CyaSSL_ERR_print_errors_fp(FILE* fp, int err)
{
char data[MAX_ERROR_SZ + 1];
CYASSL_ENTER("CyaSSL_ERR_print_errors_fp");
SetErrorString(err, data);
fprintf(fp, "%s", data);
}
#endif
int CyaSSL_pending(CYASSL* ssl)
{
CYASSL_ENTER("SSL_pending");
return ssl->buffers.clearOutputBuffer.length;
}
/* trun on handshake group messages for context */
int CyaSSL_CTX_set_group_messages(CYASSL_CTX* ctx)
{
if (ctx == NULL)
return BAD_FUNC_ARG;
ctx->groupMessages = 1;
return SSL_SUCCESS;
}
#ifndef NO_CYASSL_CLIENT
/* connect enough to get peer cert chain */
int CyaSSL_connect_cert(CYASSL* ssl)
{
int ret;
if (ssl == NULL)
return SSL_FAILURE;
ssl->options.certOnly = 1;
ret = CyaSSL_connect(ssl);
ssl->options.certOnly = 0;
return ret;
}
#endif
/* trun on handshake group messages for ssl object */
int CyaSSL_set_group_messages(CYASSL* ssl)
{
if (ssl == NULL)
return BAD_FUNC_ARG;
ssl->options.groupMessages = 1;
return SSL_SUCCESS;
}
int CyaSSL_SetVersion(CYASSL* ssl, int version)
{
byte havePSK = 0;
CYASSL_ENTER("CyaSSL_SetVersion");
if (ssl == NULL) {
CYASSL_MSG("Bad function argument");
return BAD_FUNC_ARG;
}
switch (version) {
case CYASSL_SSLV3:
ssl->version = MakeSSLv3();
break;
#ifndef NO_TLS
case CYASSL_TLSV1:
ssl->version = MakeTLSv1();
break;
case CYASSL_TLSV1_1:
ssl->version = MakeTLSv1_1();
break;
case CYASSL_TLSV1_2:
ssl->version = MakeTLSv1_2();
break;
#endif
default:
CYASSL_MSG("Bad function argument");
return BAD_FUNC_ARG;
}
#ifndef NO_PSK
havePSK = ssl->options.havePSK;
#endif
InitSuites(&ssl->suites, ssl->version, ssl->options.haveDH, havePSK,
ssl->options.haveNTRU, ssl->options.haveECDSAsig,
ssl->options.haveStaticECC, ssl->options.side);
return SSL_SUCCESS;
}
/* does CA already exist on signer list */
int AlreadySigner(CYASSL_CERT_MANAGER* cm, byte* hash)
{
Signer* signers;
int ret = 0;
if (LockMutex(&cm->caLock) != 0)
return ret;
signers = cm->caList;
while (signers) {
if (XMEMCMP(hash, signers->hash, SHA_DIGEST_SIZE) == 0) {
ret = 1;
break;
}
signers = signers->next;
}
UnLockMutex(&cm->caLock);
return ret;
}
/* return CA if found, otherwise NULL */
Signer* GetCA(void* vp, byte* hash)
{
CYASSL_CERT_MANAGER* cm = (CYASSL_CERT_MANAGER*)vp;
Signer* ret = NULL;
Signer* signers;
if (cm == NULL)
return NULL;
signers = cm->caList;
if (LockMutex(&cm->caLock) != 0)
return ret;
while (signers) {
if (XMEMCMP(hash, signers->hash, SHA_DIGEST_SIZE) == 0) {
ret = signers;
break;
}
signers = signers->next;
}
UnLockMutex(&cm->caLock);
return ret;
}
/* owns der, internal now uses too */
/* type flag ids from user or from chain received during verify
don't allow chain ones to be added w/o isCA extension */
int AddCA(CYASSL_CERT_MANAGER* cm, buffer der, int type, int verify)
{
int ret;
DecodedCert cert;
Signer* signer = 0;
CYASSL_MSG("Adding a CA");
InitDecodedCert(&cert, der.buffer, der.length, cm->heap);
ret = ParseCert(&cert, CA_TYPE, verify, cm);
CYASSL_MSG(" Parsed new CA");
if (ret == 0 && cert.isCA == 0 && type != CYASSL_USER_CA) {
CYASSL_MSG(" Can't add as CA if not actually one");
ret = NOT_CA_ERROR;
}
else if (ret == 0 && AlreadySigner(cm, cert.subjectHash)) {
CYASSL_MSG(" Already have this CA, not adding again");
(void)ret;
}
else if (ret == 0) {
/* take over signer parts */
signer = MakeSigner(cm->heap);
if (!signer)
ret = MEMORY_ERROR;
else {
signer->keyOID = cert.keyOID;
signer->publicKey = cert.publicKey;
signer->pubKeySize = cert.pubKeySize;
signer->name = cert.subjectCN;
XMEMCPY(signer->hash, cert.subjectHash, SHA_DIGEST_SIZE);
signer->next = NULL; /* in case lock fails */
cert.publicKey = 0; /* don't free here */
cert.subjectCN = 0;
if (LockMutex(&cm->caLock) == 0) {
signer->next = cm->caList;
cm->caList = signer; /* takes ownership */
UnLockMutex(&cm->caLock);
if (cm->caCacheCallback)
cm->caCacheCallback(der.buffer, (int)der.length, type);
}
else {
CYASSL_MSG(" CA Mutex Lock failed");
ret = BAD_MUTEX_ERROR;
FreeSigners(signer, cm->heap);
}
}
}
CYASSL_MSG(" Freeing Parsed CA");
FreeDecodedCert(&cert);
CYASSL_MSG(" Freeing der CA");
XFREE(der.buffer, ctx->heap, DYNAMIC_TYPE_CA);
CYASSL_MSG(" OK Freeing der CA");
CYASSL_LEAVE("AddCA", ret);
if (ret == 0) return SSL_SUCCESS;
return ret;
}
#ifndef NO_SESSION_CACHE
/* basic config gives a cache with 33 sessions, adequate for clients and
embedded servers
MEDIUM_SESSION_CACHE allows 1055 sessions, adequate for servers that
aren't under heavy load, basically allows 200 new sessions per minute
BIG_SESSION_CACHE yields 20,0027 sessions
HUGE_SESSION_CACHE yields 65,791 sessions, for servers under heavy load,
allows over 13,000 new sessions per minute or over 200 new sessions per
second
SMALL_SESSION_CACHE only stores 6 sessions, good for embedded clients
or systems where the default of nearly 3kB is too much RAM, this define
uses less than 500 bytes RAM
*/
#ifdef HUGE_SESSION_CACHE
#define SESSIONS_PER_ROW 11
#define SESSION_ROWS 5981
#elif defined(BIG_SESSION_CACHE)
#define SESSIONS_PER_ROW 7
#define SESSION_ROWS 2861
#elif defined(MEDIUM_SESSION_CACHE)
#define SESSIONS_PER_ROW 5
#define SESSION_ROWS 211
#elif defined(SMALL_SESSION_CACHE)
#define SESSIONS_PER_ROW 2
#define SESSION_ROWS 3
#else
#define SESSIONS_PER_ROW 3
#define SESSION_ROWS 11
#endif
typedef struct SessionRow {
int nextIdx; /* where to place next one */
int totalCount; /* sessions ever on this row */
CYASSL_SESSION Sessions[SESSIONS_PER_ROW];
} SessionRow;
static SessionRow SessionCache[SESSION_ROWS];
static CyaSSL_Mutex session_mutex; /* SessionCache mutex */
#endif /* NO_SESSION_CACHE */
/* Remove PEM header/footer, convert to ASN1, store any encrypted data
info->consumed tracks of PEM bytes consumed in case multiple parts */
int PemToDer(const unsigned char* buff, long sz, int type,
buffer* der, void* heap, EncryptedInfo* info, int* eccKey)
{
char header[PEM_LINE_LEN];
char footer[PEM_LINE_LEN];
char* headerEnd;
char* footerEnd;
char* consumedEnd;
long neededSz;
int pkcs8 = 0;
int pkcs8Enc = 0;
int dynamicType = 0;
(void)heap;
(void)dynamicType;
(void)pkcs8Enc;
if (type == CERT_TYPE || type == CA_TYPE) {
XSTRNCPY(header, "-----BEGIN CERTIFICATE-----", sizeof(header));
XSTRNCPY(footer, "-----END CERTIFICATE-----", sizeof(footer));
dynamicType = (type == CA_TYPE) ? DYNAMIC_TYPE_CA :
DYNAMIC_TYPE_CERT;
} else if (type == DH_PARAM_TYPE) {
XSTRNCPY(header, "-----BEGIN DH PARAMETERS-----", sizeof(header));
XSTRNCPY(footer, "-----END DH PARAMETERS-----", sizeof(footer));
dynamicType = DYNAMIC_TYPE_KEY;
} else if (type == CRL_TYPE) {
XSTRNCPY(header, "-----BEGIN X509 CRL-----", sizeof(header));
XSTRNCPY(footer, "-----END X509 CRL-----", sizeof(footer));
dynamicType = DYNAMIC_TYPE_CRL;
} else {
XSTRNCPY(header, "-----BEGIN RSA PRIVATE KEY-----", sizeof(header));
XSTRNCPY(footer, "-----END RSA PRIVATE KEY-----", sizeof(footer));
dynamicType = DYNAMIC_TYPE_KEY;
}
/* find header */
headerEnd = XSTRNSTR((char*)buff, header, sz);
if (!headerEnd && type == PRIVATEKEY_TYPE) { /* may be pkcs8 */
XSTRNCPY(header, "-----BEGIN PRIVATE KEY-----", sizeof(header));
XSTRNCPY(footer, "-----END PRIVATE KEY-----", sizeof(footer));
headerEnd = XSTRNSTR((char*)buff, header, sz);
if (headerEnd)
pkcs8 = 1;
else {
XSTRNCPY(header, "-----BEGIN ENCRYPTED PRIVATE KEY-----",
sizeof(header));
XSTRNCPY(footer, "-----END ENCRYPTED PRIVATE KEY-----",
sizeof(footer));
headerEnd = XSTRNSTR((char*)buff, header, sz);
if (headerEnd)
pkcs8Enc = 1;
}
}
if (!headerEnd && type == PRIVATEKEY_TYPE) { /* may be ecc */
XSTRNCPY(header, "-----BEGIN EC PRIVATE KEY-----", sizeof(header));
XSTRNCPY(footer, "-----END EC PRIVATE KEY-----", sizeof(footer));
headerEnd = XSTRNSTR((char*)buff, header, sz);
if (headerEnd)
*eccKey = 1;
}
if (!headerEnd && type == PRIVATEKEY_TYPE) { /* may be dsa */
XSTRNCPY(header, "-----BEGIN DSA PRIVATE KEY-----", sizeof(header));
XSTRNCPY(footer, "-----END DSA PRIVATE KEY-----", sizeof(footer));
headerEnd = XSTRNSTR((char*)buff, header, sz);
}
if (!headerEnd)
return SSL_BAD_FILE;
headerEnd += XSTRLEN(header);
/* get next line */
if (headerEnd[0] == '\n')
headerEnd++;
else if (headerEnd[1] == '\n')
headerEnd += 2;
else
return SSL_BAD_FILE;
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
{
/* remove encrypted header if there */
char encHeader[] = "Proc-Type";
char* line = XSTRNSTR((char*)buff, encHeader, PEM_LINE_LEN);
if (line) {
char* newline;
char* finish;
char* start = XSTRNSTR(line, "DES", PEM_LINE_LEN);
if (!start)
start = XSTRNSTR(line, "AES", PEM_LINE_LEN);
if (!start) return SSL_BAD_FILE;
if (!info) return SSL_BAD_FILE;
finish = XSTRNSTR(start, ",", PEM_LINE_LEN);
if (start && finish && (start < finish)) {
newline = XSTRNSTR(finish, "\r", PEM_LINE_LEN);
XMEMCPY(info->name, start, finish - start);
info->name[finish - start] = 0;
XMEMCPY(info->iv, finish + 1, sizeof(info->iv));
if (!newline) newline = XSTRNSTR(finish, "\n", PEM_LINE_LEN);
if (newline && (newline > finish)) {
info->ivSz = (word32)(newline - (finish + 1));
info->set = 1;
}
else
return SSL_BAD_FILE;
}
else
return SSL_BAD_FILE;
/* eat blank line */
while (*newline == '\r' || *newline == '\n')
newline++;
headerEnd = newline;
}
}
#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */
/* find footer */
footerEnd = XSTRNSTR((char*)buff, footer, sz);
if (!footerEnd) return SSL_BAD_FILE;
consumedEnd = footerEnd + XSTRLEN(footer);
/* get next line */
if (consumedEnd[0] == '\n')
consumedEnd++;
else if (consumedEnd[1] == '\n')
consumedEnd += 2;
else
return SSL_BAD_FILE;
if (info)
info->consumed = (long)(consumedEnd - (char*)buff);
/* set up der buffer */
neededSz = (long)(footerEnd - headerEnd);
if (neededSz > sz || neededSz < 0) return SSL_BAD_FILE;
der->buffer = (byte*) XMALLOC(neededSz, heap, dynamicType);
if (!der->buffer) return MEMORY_ERROR;
der->length = neededSz;
if (Base64_Decode((byte*)headerEnd, neededSz, der->buffer,
&der->length) < 0)
return SSL_BAD_FILE;
if (pkcs8)
return ToTraditional(der->buffer, der->length);
#ifdef OPENSSL_EXTRA
if (pkcs8Enc) {
int passwordSz;
char password[80];
if (!info->ctx || !info->ctx->passwd_cb)
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);
}
#endif
return 0;
}
/* process the buffer buff, legnth sz, into ctx of format and type
used tracks bytes consumed, userChain specifies a user cert chain
to pass during the handshake */
static int ProcessBuffer(CYASSL_CTX* ctx, const unsigned char* buff,
long sz, int format, int type, CYASSL* ssl,
long* used, int userChain)
{
EncryptedInfo info;
buffer der; /* holds DER or RAW (for NTRU) */
int dynamicType = 0;
int eccKey = 0;
info.set = 0;
info.ctx = ctx;
info.consumed = 0;
der.buffer = 0;
(void)dynamicType;
if (used)
*used = sz; /* used bytes default to sz, PEM chain may shorten*/
if (format != SSL_FILETYPE_ASN1 && format != SSL_FILETYPE_PEM
&& format != SSL_FILETYPE_RAW)
return SSL_BAD_FILETYPE;
if (type == CA_TYPE)
dynamicType = DYNAMIC_TYPE_CA;
else if (type == CERT_TYPE)
dynamicType = DYNAMIC_TYPE_CERT;
else
dynamicType = DYNAMIC_TYPE_KEY;
if (format == SSL_FILETYPE_PEM) {
int ret = PemToDer(buff, sz, type, &der, ctx->heap, &info, &eccKey);
if (ret < 0) {
XFREE(der.buffer, ctx->heap, dynamicType);
return ret;
}
if (used)
*used = info.consumed;
/* we may have a user cert chain, try to consume */
if (userChain && type == CERT_TYPE && info.consumed < sz) {
byte staticBuffer[FILE_BUFFER_SIZE]; /* tmp chain buffer */
byte* chainBuffer = staticBuffer;
int dynamicBuffer = 0;
word32 bufferSz = sizeof(staticBuffer);
long consumed = info.consumed;
word32 idx = 0;
if ( (sz - consumed) > (int)bufferSz) {
CYASSL_MSG("Growing Tmp Chain Buffer");
bufferSz = sz - consumed; /* will shrink to actual size */
chainBuffer = (byte*)XMALLOC(bufferSz, ctx->heap,
DYNAMIC_FILE_TYPE);
if (chainBuffer == NULL) {
XFREE(der.buffer, ctx->heap, dynamicType);
return MEMORY_E;
}
dynamicBuffer = 1;
}
CYASSL_MSG("Processing Cert Chain");
while (consumed < sz) {
long left;
buffer part;
info.consumed = 0;
part.buffer = 0;
ret = PemToDer(buff + consumed, sz - consumed, type, &part,
ctx->heap, &info, &eccKey);
if (ret == 0) {
if ( (idx + part.length) > bufferSz) {
CYASSL_MSG(" Cert Chain bigger than buffer");
ret = BUFFER_E;
}
else {
c32to24(part.length, &chainBuffer[idx]);
idx += CERT_HEADER_SZ;
XMEMCPY(&chainBuffer[idx], part.buffer,part.length);
idx += part.length;
consumed += info.consumed;
if (used)
*used += info.consumed;
}
}
XFREE(part.buffer, ctx->heap, dynamicType);
if (ret < 0) {
CYASSL_MSG(" Error in Cert in Chain");
XFREE(der.buffer, ctx->heap, dynamicType);
return ret;
}
CYASSL_MSG(" Consumed another Cert in Chain");
left = sz - consumed;
if (left > 0 && left < CERT_MIN_SIZE) {
CYASSL_MSG(" Non Cert at end of file");
break;
}
}
CYASSL_MSG("Finished Processing Cert Chain");
ctx->certChain.buffer = (byte*)XMALLOC(idx, ctx->heap,
dynamicType);
if (ctx->certChain.buffer) {
ctx->certChain.length = idx;
XMEMCPY(ctx->certChain.buffer, chainBuffer, idx);
}
if (dynamicBuffer)
XFREE(chainBuffer, ctx->heap, DYNAMIC_FILE_TYPE);
if (ctx->certChain.buffer == NULL) {
XFREE(der.buffer, ctx->heap, dynamicType);
return MEMORY_E;
}
}
}
else { /* ASN1 (DER) or RAW (NTRU) */
der.buffer = (byte*) XMALLOC(sz, ctx->heap, dynamicType);
if (!der.buffer) return MEMORY_ERROR;
XMEMCPY(der.buffer, buff, sz);
der.length = sz;
}
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
if (info.set) {
/* decrypt */
char password[80];
int passwordSz;
int ret;
byte key[AES_256_KEY_SIZE];
byte iv[AES_IV_SIZE];
if (!ctx->passwd_cb) {
XFREE(der.buffer, ctx->heap, dynamicType);
return NO_PASSWORD;
}
/* use file's salt for key derivation, hex decode first */
if (Base16_Decode(info.iv, info.ivSz, info.iv, &info.ivSz) != 0) {
XFREE(der.buffer, ctx->heap, dynamicType);
return ASN_INPUT_E;
}
passwordSz = ctx->passwd_cb(password, sizeof(password), 0,
ctx->userdata);
if ( (ret = EVP_BytesToKey(info.name, "MD5", info.iv,
(byte*)password, passwordSz, 1, key, iv)) <= 0) {
XFREE(der.buffer, ctx->heap, dynamicType);
return ret;
}
if (XSTRNCMP(info.name, "DES-CBC", 7) == 0) {
Des enc;
Des_SetKey(&enc, key, info.iv, DES_DECRYPTION);
Des_CbcDecrypt(&enc, der.buffer, der.buffer, der.length);
}
else if (XSTRNCMP(info.name, "DES-EDE3-CBC", 13) == 0) {
Des3 enc;
Des3_SetKey(&enc, key, info.iv, DES_DECRYPTION);
Des3_CbcDecrypt(&enc, der.buffer, der.buffer, der.length);
}
else if (XSTRNCMP(info.name, "AES-128-CBC", 13) == 0) {
Aes enc;
AesSetKey(&enc, key, AES_128_KEY_SIZE, info.iv, AES_DECRYPTION);
AesCbcDecrypt(&enc, der.buffer, der.buffer, der.length);
}
else if (XSTRNCMP(info.name, "AES-192-CBC", 13) == 0) {
Aes enc;
AesSetKey(&enc, key, AES_192_KEY_SIZE, info.iv, AES_DECRYPTION);
AesCbcDecrypt(&enc, der.buffer, der.buffer, der.length);
}
else if (XSTRNCMP(info.name, "AES-256-CBC", 13) == 0) {
Aes enc;
AesSetKey(&enc, key, AES_256_KEY_SIZE, info.iv, AES_DECRYPTION);
AesCbcDecrypt(&enc, der.buffer, der.buffer, der.length);
}
else {
XFREE(der.buffer, ctx->heap, dynamicType);
return SSL_BAD_FILE;
}
}
#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */
if (type == CA_TYPE)
return AddCA(ctx->cm, der, CYASSL_USER_CA, ctx->verifyPeer);
/* takes der over */
else if (type == CERT_TYPE) {
if (ssl) {
if (ssl->buffers.weOwnCert && ssl->buffers.certificate.buffer)
XFREE(ssl->buffers.certificate.buffer, ctx->heap,
dynamicType);
ssl->buffers.certificate = der;
ssl->buffers.weOwnCert = 1;
}
else {
if (ctx->certificate.buffer)
XFREE(ctx->certificate.buffer, ctx->heap, dynamicType);
ctx->certificate = der; /* takes der over */
}
}
else if (type == PRIVATEKEY_TYPE) {
if (ssl) {
if (ssl->buffers.weOwnKey && ssl->buffers.key.buffer)
XFREE(ssl->buffers.key.buffer, ctx->heap, dynamicType);
ssl->buffers.key = der;
ssl->buffers.weOwnKey = 1;
}
else {
if (ctx->privateKey.buffer)
XFREE(ctx->privateKey.buffer, ctx->heap, dynamicType);
ctx->privateKey = der; /* takes der over */
}
}
else {
XFREE(der.buffer, ctx->heap, dynamicType);
return SSL_BAD_CERTTYPE;
}
if (type == PRIVATEKEY_TYPE && format != SSL_FILETYPE_RAW) {
if (!eccKey) {
/* make sure RSA key can be used */
RsaKey key;
word32 idx = 0;
InitRsaKey(&key, 0);
if (RsaPrivateKeyDecode(der.buffer,&idx,&key,der.length) != 0) {
#ifdef HAVE_ECC
/* could have DER ECC (or pkcs8 ecc), no easy way to tell */
eccKey = 1; /* so try it out */
#endif
if (!eccKey) {
FreeRsaKey(&key);
return SSL_BAD_FILE;
}
}
FreeRsaKey(&key);
}
#ifdef HAVE_ECC
if (eccKey ) {
/* make sure ECC key can be used */
word32 idx = 0;
ecc_key key;
ecc_init(&key);
if (EccPrivateKeyDecode(der.buffer,&idx,&key,der.length) != 0) {
ecc_free(&key);
return SSL_BAD_FILE;
}
ecc_free(&key);
ctx->haveStaticECC = 1;
if (ssl)
ssl->options.haveStaticECC = 1;
}
#endif /* HAVE_ECC */
}
else if (type == CERT_TYPE) {
int ret;
DecodedCert cert;
CYASSL_MSG("Checking cert signature type");
InitDecodedCert(&cert, der.buffer, der.length, ctx->heap);
if ((ret = DecodeToKey(&cert, 0)) < 0) {
CYASSL_MSG("Decode to key failed");
return SSL_BAD_FILE;
}
switch (cert.signatureOID) {
case CTC_SHAwECDSA:
case CTC_SHA256wECDSA:
case CTC_SHA384wECDSA:
case CTC_SHA512wECDSA:
CYASSL_MSG("ECDSA cert signature");
ctx->haveECDSAsig = 1;
if (ssl)
ssl->options.haveECDSAsig = 1;
break;
default:
CYASSL_MSG("Not ECDSA cert signature");
break;
}
FreeDecodedCert(&cert);
}
return SSL_SUCCESS;
}
/* CA PEM file for verification, may have multiple/chain certs to process */
static int ProcessChainBuffer(CYASSL_CTX* ctx, const unsigned char* buff,
long sz, int format, int type, CYASSL* ssl)
{
long used = 0;
int ret = 0;
CYASSL_MSG("Processing CA PEM file");
while (used < sz) {
long consumed = 0;
long left;
ret = ProcessBuffer(ctx, buff + used, sz - used, format, type, ssl,
&consumed, 0);
if (ret < 0)
break;
CYASSL_MSG(" Processed a CA");
used += consumed;
left = sz - used;
if (left > 0 && left < CERT_MIN_SIZE) { /* non cert stuff at eof */
CYASSL_MSG(" Non CA cert at eof");
break;
}
}
return ret;
}
#ifndef NO_FILESYSTEM
#ifndef MICRIUM
#define XFILE FILE
#define XFOPEN fopen
#define XFSEEK fseek
#define XFTELL ftell
#define XREWIND rewind
#define XFREAD fread
#define XFCLOSE fclose
#define XSEEK_END SEEK_END
#else
#include <fs.h>
#define XFILE FS_FILE
#define XFOPEN fs_fopen
#define XFSEEK fs_fseek
#define XFTELL fs_ftell
#define XREWIND fs_rewind
#define XFREAD fs_fread
#define XFCLOSE fs_fclose
#define XSEEK_END FS_SEEK_END
#endif
/* process a file with name fname into ctx of format and type
userChain specifies a user certificate chain to pass during handshake */
int ProcessFile(CYASSL_CTX* ctx, const char* fname, int format, int type,
CYASSL* ssl, int userChain, CYASSL_CRL* crl)
{
byte staticBuffer[FILE_BUFFER_SIZE];
byte* myBuffer = staticBuffer;
int dynamic = 0;
int ret;
long sz = 0;
XFILE* file = XFOPEN(fname, "rb");
(void)crl;
if (!file) return SSL_BAD_FILE;
XFSEEK(file, 0, XSEEK_END);
sz = XFTELL(file);
XREWIND(file);
if (sz > (long)sizeof(staticBuffer)) {
CYASSL_MSG("Getting dynamic buffer");
myBuffer = (byte*) XMALLOC(sz, ctx->heap, DYNAMIC_TYPE_FILE);
if (myBuffer == NULL) {
XFCLOSE(file);
return SSL_BAD_FILE;
}
dynamic = 1;
}
if ( (ret = XFREAD(myBuffer, sz, 1, file)) < 0)
ret = SSL_BAD_FILE;
else {
if (type == CA_TYPE && format == SSL_FILETYPE_PEM)
ret = ProcessChainBuffer(ctx, myBuffer, sz, format, type, ssl);
#ifdef HAVE_CRL
else if (type == CRL_TYPE)
ret = BufferLoadCRL(crl, myBuffer, sz, format);
#endif
else
ret = ProcessBuffer(ctx, myBuffer, sz, format, type, ssl, NULL,
userChain);
}
XFCLOSE(file);
if (dynamic) XFREE(myBuffer, ctx->heap, DYNAMIC_TYPE_FILE);
return ret;
}
/* loads file then loads each file in path, no c_rehash */
int CyaSSL_CTX_load_verify_locations(CYASSL_CTX* ctx, const char* file,
const char* path)
{
int ret = SSL_SUCCESS;
CYASSL_ENTER("CyaSSL_CTX_load_verify_locations");
(void)path;
if (ctx == NULL || (file == NULL && path == NULL) )
return SSL_FAILURE;
if (file)
ret = ProcessFile(ctx, file, SSL_FILETYPE_PEM, CA_TYPE, NULL, 0, NULL);
if (ret == SSL_SUCCESS && path) {
/* try to load each regular file in path */
#ifdef USE_WINDOWS_API
WIN32_FIND_DATAA FindFileData;
HANDLE hFind;
char name[MAX_FILENAME_SZ];
XMEMSET(name, 0, sizeof(name));
XSTRNCPY(name, path, MAX_FILENAME_SZ - 4);
XSTRNCAT(name, "\\*", 3);
hFind = FindFirstFileA(name, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE) {
CYASSL_MSG("FindFirstFile for path verify locations failed");
return BAD_PATH_ERROR;
}
do {
if (FindFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY) {
XSTRNCPY(name, path, MAX_FILENAME_SZ/2 - 3);
XSTRNCAT(name, "\\", 2);
XSTRNCAT(name, FindFileData.cFileName, MAX_FILENAME_SZ/2);
ret = ProcessFile(ctx, name, SSL_FILETYPE_PEM, CA_TYPE, NULL,0,
NULL);
}
} while (ret == SSL_SUCCESS && FindNextFileA(hFind, &FindFileData));
FindClose(hFind);
#elif !defined(NO_CYASSL_DIR)
struct dirent* entry;
DIR* dir = opendir(path);
if (dir == NULL) {
CYASSL_MSG("opendir path verify locations failed");
return BAD_PATH_ERROR;
}
while ( ret == SSL_SUCCESS && (entry = readdir(dir)) != NULL) {
if (entry->d_type & DT_REG) {
char name[MAX_FILENAME_SZ];
XMEMSET(name, 0, sizeof(name));
XSTRNCPY(name, path, MAX_FILENAME_SZ/2 - 2);
XSTRNCAT(name, "/", 1);
XSTRNCAT(name, entry->d_name, MAX_FILENAME_SZ/2);
ret = ProcessFile(ctx, name, SSL_FILETYPE_PEM, CA_TYPE, NULL,0,
NULL);
}
}
closedir(dir);
#endif
}
return ret;
}
/* Verify the ceritficate, 1 for success, < 0 for error */
int CyaSSL_CertManagerVerifyBuffer(CYASSL_CERT_MANAGER* cm, const byte* buff,
int sz, int format)
{
int ret = 0;
int eccKey = 0; /* not used */
DecodedCert cert;
buffer der;
CYASSL_ENTER("CyaSSL_CertManagerVerifyBuffer");
der.buffer = NULL;
if (format == SSL_FILETYPE_PEM) {
EncryptedInfo info;
info.set = 0;
info.ctx = NULL;
info.consumed = 0;
ret = PemToDer(buff, sz, CERT_TYPE, &der, cm->heap, &info, &eccKey);
InitDecodedCert(&cert, der.buffer, der.length, cm->heap);
}
else
InitDecodedCert(&cert, (byte*)buff, sz, cm->heap);
if (ret == 0)
ret = ParseCertRelative(&cert, CERT_TYPE, 1, cm);
#ifdef HAVE_CRL
if (ret == 0 && cm->crlEnabled)
ret = CheckCertCRL(cm->crl, &cert);
#endif
FreeDecodedCert(&cert);
XFREE(der.buffer, cm->heap, DYNAMIC_TYPE_CERT);
return ret;
}
/* Verify the ceritficate, 1 for success, < 0 for error */
int CyaSSL_CertManagerVerify(CYASSL_CERT_MANAGER* cm, const char* fname,
int format)
{
int ret = SSL_FATAL_ERROR;
byte staticBuffer[FILE_BUFFER_SIZE];
byte* myBuffer = staticBuffer;
int dynamic = 0;
long sz = 0;
XFILE* file = XFOPEN(fname, "rb");
CYASSL_ENTER("CyaSSL_CertManagerVerify");
if (!file) return SSL_BAD_FILE;
XFSEEK(file, 0, XSEEK_END);
sz = XFTELL(file);
XREWIND(file);
if (sz > (long)sizeof(staticBuffer)) {
CYASSL_MSG("Getting dynamic buffer");
myBuffer = (byte*) XMALLOC(sz, cm->heap, DYNAMIC_TYPE_FILE);
if (myBuffer == NULL) {
XFCLOSE(file);
return SSL_BAD_FILE;
}
dynamic = 1;
}
if ( (ret = XFREAD(myBuffer, sz, 1, file)) < 0)
ret = SSL_BAD_FILE;
else
ret = CyaSSL_CertManagerVerifyBuffer(cm, myBuffer, sz, format);
XFCLOSE(file);
if (dynamic) XFREE(myBuffer, cm->heap, DYNAMIC_TYPE_FILE);
if (ret == 0)
return SSL_SUCCESS;
return ret;
}
/* like load verify locations, 1 for success, < 0 for error */
int CyaSSL_CertManagerLoadCA(CYASSL_CERT_MANAGER* cm, const char* file,
const char* path)
{
int ret = SSL_FATAL_ERROR;
CYASSL_CTX* tmp;
CYASSL_ENTER("CyaSSL_CertManagerLoadCA");
if (cm == NULL) {
CYASSL_MSG("No CertManager error");
return ret;
}
tmp = CyaSSL_CTX_new(CyaSSLv3_client_method());
if (tmp == NULL) {
CYASSL_MSG("CTX new failed");
return ret;
}
/* for tmp use */
CyaSSL_CertManagerFree(tmp->cm);
tmp->cm = cm;
ret = CyaSSL_CTX_load_verify_locations(tmp, file, path);
/* don't loose our good one */
tmp->cm = NULL;
CyaSSL_CTX_free(tmp);
return ret;
}
/* turn on CRL if off and compiled in, set options */
int CyaSSL_CertManagerEnableCRL(CYASSL_CERT_MANAGER* cm, int options)
{
int ret = SSL_SUCCESS;
(void)options;
CYASSL_ENTER("CyaSSL_CertManagerEnableCRL");
if (cm == NULL)
return BAD_FUNC_ARG;
#ifdef HAVE_CRL
if (cm->crl == NULL) {
cm->crl = (CYASSL_CRL*)XMALLOC(sizeof(CYASSL_CRL), cm->heap,
DYNAMIC_TYPE_CRL);
if (cm->crl == NULL)
return MEMORY_E;
if (InitCRL(cm->crl, cm) != 0) {
CYASSL_MSG("Init CRL failed");
FreeCRL(cm->crl);
cm->crl = NULL;
return SSL_FAILURE;
}
}
cm->crlEnabled = 1;
if (options & CYASSL_CRL_CHECKALL)
cm->crlCheckAll = 1;
#else
ret = NOT_COMPILED_IN;
#endif
return ret;
}
int CyaSSL_CertManagerDisableCRL(CYASSL_CERT_MANAGER* cm)
{
CYASSL_ENTER("CyaSSL_CertManagerDisableCRL");
if (cm == NULL)
return BAD_FUNC_ARG;
cm->crlEnabled = 0;
return SSL_SUCCESS;
}
int CyaSSL_CTX_check_private_key(CYASSL_CTX* ctx)
{
/* TODO: check private against public for RSA match */
(void)ctx;
CYASSL_ENTER("SSL_CTX_check_private_key");
return SSL_SUCCESS;
}
#ifdef HAVE_CRL
/* check CRL if enabled, SSL_SUCCESS */
int CyaSSL_CertManagerCheckCRL(CYASSL_CERT_MANAGER* cm, byte* der, int sz)
{
int ret;
DecodedCert cert;
CYASSL_ENTER("CyaSSL_CertManagerCheckCRL");
if (cm == NULL)
return BAD_FUNC_ARG;
if (cm->crlEnabled == 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 = CheckCertCRL(cm->crl, &cert);
if (ret != 0) {
CYASSL_MSG("CheckCertCRL failed");
}
}
FreeDecodedCert(&cert);
if (ret == 0)
return SSL_SUCCESS; /* convert */
return ret;
}
int CyaSSL_CertManagerSetCRL_Cb(CYASSL_CERT_MANAGER* cm, CbMissingCRL cb)
{
CYASSL_ENTER("CyaSSL_CertManagerSetCRL_Cb");
if (cm == NULL)
return BAD_FUNC_ARG;
cm->cbMissingCRL = cb;
return SSL_SUCCESS;
}
int CyaSSL_CertManagerLoadCRL(CYASSL_CERT_MANAGER* cm, const char* path,
int type, int monitor)
{
CYASSL_ENTER("CyaSSL_CertManagerLoadCRL");
if (cm == NULL)
return BAD_FUNC_ARG;
if (cm->crl == NULL) {
if (CyaSSL_CertManagerEnableCRL(cm, 0) != SSL_SUCCESS) {
CYASSL_MSG("Enable CRL failed");
return -1;
}
}
return LoadCRL(cm->crl, path, type, monitor);
}
int CyaSSL_EnableCRL(CYASSL* ssl, int options)
{
CYASSL_ENTER("CyaSSL_EnableCRL");
if (ssl)
return CyaSSL_CertManagerEnableCRL(ssl->ctx->cm, options);
else
return BAD_FUNC_ARG;
}
int CyaSSL_DisableCRL(CYASSL* ssl)
{
CYASSL_ENTER("CyaSSL_DisableCRL");
if (ssl)
return CyaSSL_CertManagerDisableCRL(ssl->ctx->cm);
else
return BAD_FUNC_ARG;
}
int CyaSSL_LoadCRL(CYASSL* ssl, const char* path, int type, int monitor)
{
CYASSL_ENTER("CyaSSL_LoadCRL");
if (ssl)
return CyaSSL_CertManagerLoadCRL(ssl->ctx->cm, path, type, monitor);
else
return BAD_FUNC_ARG;
}
int CyaSSL_SetCRL_Cb(CYASSL* ssl, CbMissingCRL cb)
{
CYASSL_ENTER("CyaSSL_SetCRL_Cb");
if (ssl)
return CyaSSL_CertManagerSetCRL_Cb(ssl->ctx->cm, cb);
else
return BAD_FUNC_ARG;
}
int CyaSSL_CTX_EnableCRL(CYASSL_CTX* ctx, int options)
{
CYASSL_ENTER("CyaSSL_CTX_EnableCRL");
if (ctx)
return CyaSSL_CertManagerEnableCRL(ctx->cm, options);
else
return BAD_FUNC_ARG;
}
int CyaSSL_CTX_DisableCRL(CYASSL_CTX* ctx)
{
CYASSL_ENTER("CyaSSL_CTX_DisableCRL");
if (ctx)
return CyaSSL_CertManagerDisableCRL(ctx->cm);
else
return BAD_FUNC_ARG;
}
int CyaSSL_CTX_LoadCRL(CYASSL_CTX* ctx, const char* path, int type, int monitor)
{
CYASSL_ENTER("CyaSSL_CTX_LoadCRL");
if (ctx)
return CyaSSL_CertManagerLoadCRL(ctx->cm, path, type, monitor);
else
return BAD_FUNC_ARG;
}
int CyaSSL_CTX_SetCRL_Cb(CYASSL_CTX* ctx, CbMissingCRL cb)
{
CYASSL_ENTER("CyaSSL_CTX_SetCRL_Cb");
if (ctx)
return CyaSSL_CertManagerSetCRL_Cb(ctx->cm, cb);
else
return BAD_FUNC_ARG;
}
#endif /* HAVE_CRL */
#ifdef CYASSL_DER_LOAD
/* Add format parameter to allow DER load of CA files */
int CyaSSL_CTX_der_load_verify_locations(CYASSL_CTX* ctx, const char* file,
int format)
{
CYASSL_ENTER("CyaSSL_CTX_der_load_verify_locations");
if (ctx == NULL || file == NULL)
return SSL_FAILURE;
if (ProcessFile(ctx, file, format, CA_TYPE, NULL, 0, NULL) == SSL_SUCCESS)
return SSL_SUCCESS;
return SSL_FAILURE;
}
#endif /* CYASSL_DER_LOAD */
#ifdef CYASSL_CERT_GEN
/* load pem cert from file into der buffer, return der size or error */
int CyaSSL_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz)
{
byte staticBuffer[FILE_BUFFER_SIZE];
byte* fileBuf = staticBuffer;
int dynamic = 0;
int ret;
int ecc = 0;
long sz = 0;
XFILE* file = XFOPEN(fileName, "rb");
EncryptedInfo info;
buffer converted;
CYASSL_ENTER("CyaSSL_PemCertToDer");
converted.buffer = 0;
if (!file) return SSL_BAD_FILE;
XFSEEK(file, 0, XSEEK_END);
sz = XFTELL(file);
XREWIND(file);
if (sz > (long)sizeof(staticBuffer)) {
fileBuf = (byte*) XMALLOC(sz, 0, DYNAMIC_TYPE_FILE);
if (fileBuf == NULL) {
XFCLOSE(file);
return SSL_BAD_FILE;
}
dynamic = 1;
}
if ( (ret = XFREAD(fileBuf, sz, 1, file)) < 0)
ret = SSL_BAD_FILE;
else
ret = PemToDer(fileBuf, sz, CA_TYPE, &converted, 0, &info, &ecc);
if (ret == 0) {
if (converted.length < (word32)derSz) {
XMEMCPY(derBuf, converted.buffer, converted.length);
ret = converted.length;
}
else
ret = BUFFER_E;
}
XFREE(converted.buffer, 0, DYNAMIC_TYPE_CA);
if (dynamic)
XFREE(fileBuf, 0, DYNAMIC_TYPE_FILE);
XFCLOSE(file);
return ret;
}
#endif /* CYASSL_CERT_GEN */
int CyaSSL_CTX_use_certificate_file(CYASSL_CTX* ctx, const char* file,
int format)
{
CYASSL_ENTER("CyaSSL_CTX_use_certificate_file");
if (ProcessFile(ctx, file, format, CERT_TYPE, NULL, 0, NULL) == SSL_SUCCESS)
return SSL_SUCCESS;
return SSL_FAILURE;
}
int CyaSSL_CTX_use_PrivateKey_file(CYASSL_CTX* ctx, const char* file,int format)
{
CYASSL_ENTER("CyaSSL_CTX_use_PrivateKey_file");
if (ProcessFile(ctx, file, format, PRIVATEKEY_TYPE, NULL, 0, NULL)
== SSL_SUCCESS)
return SSL_SUCCESS;
return SSL_FAILURE;
}
int CyaSSL_CTX_use_certificate_chain_file(CYASSL_CTX* ctx, const char* file)
{
/* procces up to MAX_CHAIN_DEPTH plus subject cert */
CYASSL_ENTER("CyaSSL_CTX_use_certificate_chain_file");
if (ProcessFile(ctx, file, SSL_FILETYPE_PEM,CERT_TYPE,NULL,1, NULL)
== SSL_SUCCESS)
return SSL_SUCCESS;
return SSL_FAILURE;
}
#ifdef OPENSSL_EXTRA
/* put SSL type in extra for now, not very common */
int CyaSSL_use_certificate_file(CYASSL* ssl, const char* file, int format)
{
CYASSL_ENTER("CyaSSL_use_certificate_file");
if (ProcessFile(ssl->ctx, file, format, CERT_TYPE, ssl, 0, NULL)
== SSL_SUCCESS)
return SSL_SUCCESS;
return SSL_FAILURE;
}
int CyaSSL_use_PrivateKey_file(CYASSL* ssl, const char* file, int format)
{
CYASSL_ENTER("CyaSSL_use_PrivateKey_file");
if (ProcessFile(ssl->ctx, file, format, PRIVATEKEY_TYPE, ssl, 0, NULL)
== SSL_SUCCESS)
return SSL_SUCCESS;
return SSL_FAILURE;
}
int CyaSSL_use_certificate_chain_file(CYASSL* ssl, const char* file)
{
/* procces up to MAX_CHAIN_DEPTH plus subject cert */
CYASSL_ENTER("CyaSSL_use_certificate_chain_file");
if (ProcessFile(ssl->ctx, file, SSL_FILETYPE_PEM, CERT_TYPE, ssl, 1, NULL)
== SSL_SUCCESS)
return SSL_SUCCESS;
return SSL_FAILURE;
}
/* server wrapper for ctx or ssl Diffie-Hellman parameters */
static int CyaSSL_SetTmpDH_buffer_wrapper(CYASSL_CTX* ctx, CYASSL* ssl,
const unsigned char* buf, long sz, int format)
{
buffer der;
int ret;
int weOwnDer = 0;
byte p[MAX_DH_SIZE];
byte g[MAX_DH_SIZE];
word32 pSz = sizeof(p);
word32 gSz = sizeof(g);
der.buffer = (byte*)buf;
der.length = sz;
if (format != SSL_FILETYPE_ASN1 && format != SSL_FILETYPE_PEM)
return SSL_BAD_FILETYPE;
if (format == SSL_FILETYPE_PEM) {
der.buffer = NULL;
ret = PemToDer(buf, sz, DH_PARAM_TYPE, &der, ctx->heap, NULL,NULL);
if (ret < 0) {
XFREE(der.buffer, ctx->heap, DYNAMIC_TYPE_KEY);
return ret;
}
weOwnDer = 1;
}
if (DhParamsLoad(der.buffer, der.length, p, &pSz, g, &gSz) < 0)
ret = SSL_BAD_FILETYPE;
else {
if (ssl)
ret = CyaSSL_SetTmpDH(ssl, p, pSz, g, gSz);
else
ret = CyaSSL_CTX_SetTmpDH(ctx, p, pSz, g, gSz);
}
if (weOwnDer)
XFREE(der.buffer, ctx->heap, DYNAMIC_TYPE_KEY);
return ret;
}
/* server Diffie-Hellman parameters */
int CyaSSL_SetTmpDH_buffer(CYASSL* ssl, const unsigned char* buf, long sz,
int format)
{
return CyaSSL_SetTmpDH_buffer_wrapper(ssl->ctx, ssl, buf, sz, format);
}
/* server ctx Diffie-Hellman parameters */
int CyaSSL_CTX_SetTmpDH_buffer(CYASSL_CTX* ctx, const unsigned char* buf,
long sz, int format)
{
return CyaSSL_SetTmpDH_buffer_wrapper(ctx, NULL, buf, sz, format);
}
#ifdef HAVE_ECC
/* Set Temp CTX EC-DHE size in octets, should be 20 - 66 for 160 - 521 bit */
int CyaSSL_CTX_SetTmpEC_DHE_Sz(CYASSL_CTX* ctx, word16 sz)
{
if (ctx == NULL || sz < ECC_MINSIZE || sz > ECC_MAXSIZE)
return BAD_FUNC_ARG;
ctx->eccTempKeySz = sz;
return SSL_SUCCESS;
}
/* Set Temp SSL EC-DHE size in octets, should be 20 - 66 for 160 - 521 bit */
int CyaSSL_SetTmpEC_DHE_Sz(CYASSL* ssl, word16 sz)
{
if (ssl == NULL || sz < ECC_MINSIZE || sz > ECC_MAXSIZE)
return BAD_FUNC_ARG;
ssl->eccTempKeySz = sz;
return SSL_SUCCESS;
}
#endif /* HAVE_ECC */
#if !defined(NO_FILESYSTEM)
/* server Diffie-Hellman parameters */
static int CyaSSL_SetTmpDH_file_wrapper(CYASSL_CTX* ctx, CYASSL* ssl,
const char* fname, int format)
{
byte staticBuffer[FILE_BUFFER_SIZE];
byte* myBuffer = staticBuffer;
int dynamic = 0;
int ret;
long sz = 0;
XFILE* file = XFOPEN(fname, "rb");
if (!file) return SSL_BAD_FILE;
XFSEEK(file, 0, XSEEK_END);
sz = XFTELL(file);
XREWIND(file);
if (sz > (long)sizeof(staticBuffer)) {
CYASSL_MSG("Getting dynamic buffer");
myBuffer = (byte*) XMALLOC(sz, ctx->heap, DYNAMIC_TYPE_FILE);
if (myBuffer == NULL) {
XFCLOSE(file);
return SSL_BAD_FILE;
}
dynamic = 1;
}
if ( (ret = XFREAD(myBuffer, sz, 1, file)) < 0)
ret = SSL_BAD_FILE;
else {
if (ssl)
ret = CyaSSL_SetTmpDH_buffer(ssl, myBuffer, sz, format);
else
ret = CyaSSL_CTX_SetTmpDH_buffer(ctx, myBuffer, sz, format);
}
XFCLOSE(file);
if (dynamic) XFREE(myBuffer, ctx->heap, DYNAMIC_TYPE_FILE);
return ret;
}
/* server Diffie-Hellman parameters */
int CyaSSL_SetTmpDH_file(CYASSL* ssl, const char* fname, int format)
{
return CyaSSL_SetTmpDH_file_wrapper(ssl->ctx, ssl, fname, format);
}
/* server Diffie-Hellman parameters */
int CyaSSL_CTX_SetTmpDH_file(CYASSL_CTX* ctx, const char* fname, int format)
{
return CyaSSL_SetTmpDH_file_wrapper(ctx, NULL, fname, format);
}
#endif /* !NO_FILESYSTEM */
#endif /* OPENSSL_EXTRA */
#ifdef HAVE_NTRU
int CyaSSL_CTX_use_NTRUPrivateKey_file(CYASSL_CTX* ctx, const char* file)
{
CYASSL_ENTER("CyaSSL_CTX_use_NTRUPrivateKey_file");
if (ProcessFile(ctx, file, SSL_FILETYPE_RAW, PRIVATEKEY_TYPE, NULL, 0, NULL)
== SSL_SUCCESS) {
ctx->haveNTRU = 1;
return SSL_SUCCESS;
}
return SSL_FAILURE;
}
#endif /* HAVE_NTRU */
#ifdef OPENSSL_EXTRA
int CyaSSL_CTX_use_RSAPrivateKey_file(CYASSL_CTX* ctx,const char* file,
int format)
{
CYASSL_ENTER("SSL_CTX_use_RSAPrivateKey_file");
if (ProcessFile(ctx, file,format,PRIVATEKEY_TYPE,NULL,0, NULL)
== SSL_SUCCESS)
return SSL_SUCCESS;
return SSL_FAILURE;
}
int CyaSSL_use_RSAPrivateKey_file(CYASSL* ssl, const char* file, int format)
{
CYASSL_ENTER("CyaSSL_use_RSAPrivateKey_file");
if (ProcessFile(ssl->ctx, file, format, PRIVATEKEY_TYPE, ssl, 0, NULL)
== SSL_SUCCESS)
return SSL_SUCCESS;
return SSL_FAILURE;
}
#endif /* OPENSSL_EXTRA */
#endif /* NO_FILESYSTEM */
void CyaSSL_CTX_set_verify(CYASSL_CTX* ctx, int mode, VerifyCallback vc)
{
CYASSL_ENTER("CyaSSL_CTX_set_verify");
if (mode & SSL_VERIFY_PEER) {
ctx->verifyPeer = 1;
ctx->verifyNone = 0; /* in case perviously set */
}
if (mode == SSL_VERIFY_NONE) {
ctx->verifyNone = 1;
ctx->verifyPeer = 0; /* in case previously set */
}
if (mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
ctx->failNoCert = 1;
ctx->verifyCallback = vc;
}
void CyaSSL_set_verify(CYASSL* ssl, int mode, VerifyCallback vc)
{
CYASSL_ENTER("CyaSSL_set_verify");
if (mode & SSL_VERIFY_PEER) {
ssl->options.verifyPeer = 1;
ssl->options.verifyNone = 0; /* in case perviously set */
}
if (mode == SSL_VERIFY_NONE) {
ssl->options.verifyNone = 1;
ssl->options.verifyPeer = 0; /* in case previously set */
}
if (mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
ssl->options.failNoCert = 1;
ssl->verifyCallback = vc;
}
/* store context CA Cache addition callback */
void CyaSSL_CTX_SetCACb(CYASSL_CTX* ctx, CallbackCACache cb)
{
if (ctx && ctx->cm)
ctx->cm->caCacheCallback = cb;
}
#ifndef NO_SESSION_CACHE
CYASSL_SESSION* CyaSSL_get_session(CYASSL* ssl)
{
CYASSL_ENTER("SSL_get_session");
if (ssl)
return GetSession(ssl, 0);
return NULL;
}
int CyaSSL_set_session(CYASSL* ssl, CYASSL_SESSION* session)
{
CYASSL_ENTER("SSL_set_session");
if (session)
return SetSession(ssl, session);
return SSL_FAILURE;
}
#endif /* NO_SESSION_CACHE */
void CyaSSL_load_error_strings(void) /* compatibility only */
{}
int CyaSSL_library_init(void)
{
CYASSL_ENTER("SSL_library_init");
if (CyaSSL_Init() == 0)
return SSL_SUCCESS;
else
return SSL_FATAL_ERROR;
}
#ifndef NO_SESSION_CACHE
/* on by default if built in but allow user to turn off */
long CyaSSL_CTX_set_session_cache_mode(CYASSL_CTX* ctx, long mode)
{
CYASSL_ENTER("SSL_CTX_set_session_cache_mode");
if (mode == SSL_SESS_CACHE_OFF)
ctx->sessionCacheOff = 1;
if (mode == SSL_SESS_CACHE_NO_AUTO_CLEAR)
ctx->sessionCacheFlushOff = 1;
return SSL_SUCCESS;
}
#endif /* NO_SESSION_CACHE */
int CyaSSL_CTX_set_cipher_list(CYASSL_CTX* ctx, const char* list)
{
CYASSL_ENTER("CyaSSL_CTX_set_cipher_list");
if (SetCipherList(&ctx->suites, list))
return SSL_SUCCESS;
else
return SSL_FAILURE;
}
int CyaSSL_set_cipher_list(CYASSL* ssl, const char* list)
{
CYASSL_ENTER("CyaSSL_set_cipher_list");
if (SetCipherList(&ssl->suites, list)) {
byte havePSK = 0;
#ifndef NO_PSK
havePSK = ssl->options.havePSK;
#endif
InitSuites(&ssl->suites, ssl->version, ssl->options.haveDH, havePSK,
ssl->options.haveNTRU, ssl->options.haveECDSAsig,
ssl->options.haveStaticECC, ssl->options.side);
return SSL_SUCCESS;
}
else
return SSL_FAILURE;
}
/* client only parts */
#ifndef NO_CYASSL_CLIENT
CYASSL_METHOD* CyaSSLv3_client_method(void)
{
CYASSL_METHOD* method =
(CYASSL_METHOD*) XMALLOC(sizeof(CYASSL_METHOD), 0,
DYNAMIC_TYPE_METHOD);
CYASSL_ENTER("SSLv3_client_method");
if (method)
InitSSL_Method(method, MakeSSLv3());
return method;
}
#ifdef CYASSL_DTLS
CYASSL_METHOD* CyaDTLSv1_client_method(void)
{
CYASSL_METHOD* method =
(CYASSL_METHOD*) XMALLOC(sizeof(CYASSL_METHOD), 0,
DYNAMIC_TYPE_METHOD);
CYASSL_ENTER("DTLSv1_client_method");
if (method)
InitSSL_Method(method, MakeDTLSv1());
return method;
}
#endif
/* please see note at top of README if you get an error from connect */
int CyaSSL_connect(CYASSL* ssl)
{
int neededState;
CYASSL_ENTER("SSL_connect()");
#ifdef HAVE_ERRNO_H
errno = 0;
#endif
if (ssl->options.side != CLIENT_END) {
CYASSL_ERROR(ssl->error = SIDE_ERROR);
return SSL_FATAL_ERROR;
}
#ifdef CYASSL_DTLS
if (ssl->version.major == DTLS_MAJOR &&
ssl->version.minor == DTLS_MINOR) {
ssl->options.dtls = 1;
ssl->options.tls = 1;
ssl->options.tls1_1 = 1;
}
#endif
if (ssl->buffers.outputBuffer.length > 0) {
if ( (ssl->error = SendBuffered(ssl)) == 0) {
ssl->options.connectState++;
CYASSL_MSG("connect state: Advanced from buffered send");
}
else {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
}
switch (ssl->options.connectState) {
case CONNECT_BEGIN :
/* always send client hello first */
if ( (ssl->error = SendClientHello(ssl)) != 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
ssl->options.connectState = CLIENT_HELLO_SENT;
CYASSL_MSG("connect state: CLIENT_HELLO_SENT");
case CLIENT_HELLO_SENT :
neededState = ssl->options.resuming ? SERVER_FINISHED_COMPLETE :
SERVER_HELLODONE_COMPLETE;
#ifdef CYASSL_DTLS
if (ssl->options.dtls && !ssl->options.resuming)
neededState = SERVER_HELLOVERIFYREQUEST_COMPLETE;
#endif
/* get response */
while (ssl->options.serverState < neededState) {
if ( (ssl->error = ProcessReply(ssl)) < 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
/* if resumption failed, reset needed state */
else if (neededState == SERVER_FINISHED_COMPLETE)
if (!ssl->options.resuming) {
if (!ssl->options.dtls)
neededState = SERVER_HELLODONE_COMPLETE;
else
neededState = SERVER_HELLOVERIFYREQUEST_COMPLETE;
}
}
ssl->options.connectState = HELLO_AGAIN;
CYASSL_MSG("connect state: HELLO_AGAIN");
case HELLO_AGAIN :
if (ssl->options.certOnly)
return SSL_SUCCESS;
#ifdef CYASSL_DTLS
if (ssl->options.dtls && !ssl->options.resuming) {
/* re-init hashes, exclude first hello and verify request */
InitMd5(&ssl->hashMd5);
InitSha(&ssl->hashSha);
#ifndef NO_SHA256
if (IsAtLeastTLSv1_2(ssl))
InitSha256(&ssl->hashSha256);
#endif
if ( (ssl->error = SendClientHello(ssl)) != 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
}
#endif
ssl->options.connectState = HELLO_AGAIN_REPLY;
CYASSL_MSG("connect state: HELLO_AGAIN_REPLY");
case HELLO_AGAIN_REPLY :
#ifdef CYASSL_DTLS
if (ssl->options.dtls) {
neededState = ssl->options.resuming ?
SERVER_FINISHED_COMPLETE : SERVER_HELLODONE_COMPLETE;
/* get response */
while (ssl->options.serverState < neededState) {
if ( (ssl->error = ProcessReply(ssl)) < 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
/* if resumption failed, reset needed state */
else if (neededState == SERVER_FINISHED_COMPLETE)
if (!ssl->options.resuming)
neededState = SERVER_HELLODONE_COMPLETE;
}
}
#endif
ssl->options.connectState = FIRST_REPLY_DONE;
CYASSL_MSG("connect state: FIRST_REPLY_DONE");
case FIRST_REPLY_DONE :
if (ssl->options.sendVerify)
if ( (ssl->error = SendCertificate(ssl)) != 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
ssl->options.connectState = FIRST_REPLY_FIRST;
CYASSL_MSG("connect state: FIRST_REPLY_FIRST");
case FIRST_REPLY_FIRST :
if (!ssl->options.resuming)
if ( (ssl->error = SendClientKeyExchange(ssl)) != 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
ssl->options.connectState = FIRST_REPLY_SECOND;
CYASSL_MSG("connect state: FIRST_REPLY_SECOND");
case FIRST_REPLY_SECOND :
if (ssl->options.sendVerify)
if ( (ssl->error = SendCertificateVerify(ssl)) != 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
ssl->options.connectState = FIRST_REPLY_THIRD;
CYASSL_MSG("connect state: FIRST_REPLY_THIRD");
case FIRST_REPLY_THIRD :
if ( (ssl->error = SendChangeCipher(ssl)) != 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
ssl->options.connectState = FIRST_REPLY_FOURTH;
CYASSL_MSG("connect state: FIRST_REPLY_FOURTH");
case FIRST_REPLY_FOURTH :
if ( (ssl->error = SendFinished(ssl)) != 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
ssl->options.connectState = FINISHED_DONE;
CYASSL_MSG("connect state: FINISHED_DONE");
case FINISHED_DONE :
/* get response */
while (ssl->options.serverState < SERVER_FINISHED_COMPLETE)
if ( (ssl->error = ProcessReply(ssl)) < 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
ssl->options.connectState = SECOND_REPLY_DONE;
CYASSL_MSG("connect state: SECOND_REPLY_DONE");
case SECOND_REPLY_DONE:
if (ssl->buffers.inputBuffer.dynamicFlag)
ShrinkInputBuffer(ssl, NO_FORCED_FREE);
CYASSL_LEAVE("SSL_connect()", SSL_SUCCESS);
return SSL_SUCCESS;
default:
CYASSL_MSG("Unknown connect state ERROR");
return SSL_FATAL_ERROR; /* unknown connect state */
}
}
#endif /* NO_CYASSL_CLIENT */
/* server only parts */
#ifndef NO_CYASSL_SERVER
CYASSL_METHOD* CyaSSLv3_server_method(void)
{
CYASSL_METHOD* method =
(CYASSL_METHOD*) XMALLOC(sizeof(CYASSL_METHOD), 0,
DYNAMIC_TYPE_METHOD);
CYASSL_ENTER("SSLv3_server_method");
if (method) {
InitSSL_Method(method, MakeSSLv3());
method->side = SERVER_END;
}
return method;
}
#ifdef CYASSL_DTLS
CYASSL_METHOD* CyaDTLSv1_server_method(void)
{
CYASSL_METHOD* method =
(CYASSL_METHOD*) XMALLOC(sizeof(CYASSL_METHOD), 0,
DYNAMIC_TYPE_METHOD);
CYASSL_ENTER("DTLSv1_server_method");
if (method) {
InitSSL_Method(method, MakeDTLSv1());
method->side = SERVER_END;
}
return method;
}
#endif
int CyaSSL_accept(CYASSL* ssl)
{
byte havePSK = 0;
CYASSL_ENTER("SSL_accept()");
#ifdef HAVE_ERRNO_H
errno = 0;
#endif
#ifndef NO_PSK
havePSK = ssl->options.havePSK;
#endif
if (ssl->options.side != SERVER_END) {
CYASSL_ERROR(ssl->error = SIDE_ERROR);
return SSL_FATAL_ERROR;
}
/* in case used set_accept_state after init */
if (!havePSK && (ssl->buffers.certificate.buffer == NULL ||
ssl->buffers.key.buffer == NULL)) {
CYASSL_MSG("accept error: don't have server cert and key");
ssl->error = NO_PRIVATE_KEY;
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
#ifdef HAVE_ECC
/* in case used set_accept_state after init */
if (ssl->eccTempKeyPresent == 0) {
if (ecc_make_key(&ssl->rng, ssl->eccTempKeySz,
&ssl->eccTempKey) != 0) {
ssl->error = ECC_MAKEKEY_ERROR;
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
ssl->eccTempKeyPresent = 1;
}
#endif
#ifdef CYASSL_DTLS
if (ssl->version.major == DTLS_MAJOR &&
ssl->version.minor == DTLS_MINOR) {
ssl->options.dtls = 1;
ssl->options.tls = 1;
ssl->options.tls1_1 = 1;
}
#endif
if (ssl->buffers.outputBuffer.length > 0) {
if ( (ssl->error = SendBuffered(ssl)) == 0) {
ssl->options.acceptState++;
CYASSL_MSG("accept state: Advanced from buffered send");
}
else {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
}
switch (ssl->options.acceptState) {
case ACCEPT_BEGIN :
/* get response */
while (ssl->options.clientState < CLIENT_HELLO_COMPLETE)
if ( (ssl->error = ProcessReply(ssl)) < 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
ssl->options.acceptState = ACCEPT_CLIENT_HELLO_DONE;
CYASSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE");
case ACCEPT_CLIENT_HELLO_DONE :
#ifdef CYASSL_DTLS
if (ssl->options.dtls && !ssl->options.resuming)
if ( (ssl->error = SendHelloVerifyRequest(ssl)) != 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
#endif
ssl->options.acceptState = HELLO_VERIFY_SENT;
CYASSL_MSG("accept state HELLO_VERIFY_SENT");
case HELLO_VERIFY_SENT:
#ifdef CYASSL_DTLS
if (ssl->options.dtls && !ssl->options.resuming) {
ssl->options.clientState = NULL_STATE; /* get again */
/* re-init hashes, exclude first hello and verify request */
InitMd5(&ssl->hashMd5);
InitSha(&ssl->hashSha);
#ifndef NO_SHA256
if (IsAtLeastTLSv1_2(ssl))
InitSha256(&ssl->hashSha256);
#endif
while (ssl->options.clientState < CLIENT_HELLO_COMPLETE)
if ( (ssl->error = ProcessReply(ssl)) < 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
}
#endif
ssl->options.acceptState = ACCEPT_FIRST_REPLY_DONE;
CYASSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE");
case ACCEPT_FIRST_REPLY_DONE :
if ( (ssl->error = SendServerHello(ssl)) != 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
ssl->options.acceptState = SERVER_HELLO_SENT;
CYASSL_MSG("accept state SERVER_HELLO_SENT");
case SERVER_HELLO_SENT :
if (!ssl->options.resuming)
if ( (ssl->error = SendCertificate(ssl)) != 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
ssl->options.acceptState = CERT_SENT;
CYASSL_MSG("accept state CERT_SENT");
case CERT_SENT :
if (!ssl->options.resuming)
if ( (ssl->error = SendServerKeyExchange(ssl)) != 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
ssl->options.acceptState = KEY_EXCHANGE_SENT;
CYASSL_MSG("accept state KEY_EXCHANGE_SENT");
case KEY_EXCHANGE_SENT :
if (!ssl->options.resuming)
if (ssl->options.verifyPeer)
if ( (ssl->error = SendCertificateRequest(ssl)) != 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
ssl->options.acceptState = CERT_REQ_SENT;
CYASSL_MSG("accept state CERT_REQ_SENT");
case CERT_REQ_SENT :
if (!ssl->options.resuming)
if ( (ssl->error = SendServerHelloDone(ssl)) != 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
ssl->options.acceptState = SERVER_HELLO_DONE;
CYASSL_MSG("accept state SERVER_HELLO_DONE");
case SERVER_HELLO_DONE :
if (!ssl->options.resuming) {
while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE)
if ( (ssl->error = ProcessReply(ssl)) < 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
}
ssl->options.acceptState = ACCEPT_SECOND_REPLY_DONE;
CYASSL_MSG("accept state ACCEPT_SECOND_REPLY_DONE");
case ACCEPT_SECOND_REPLY_DONE :
if ( (ssl->error = SendChangeCipher(ssl)) != 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
ssl->options.acceptState = CHANGE_CIPHER_SENT;
CYASSL_MSG("accept state CHANGE_CIPHER_SENT");
case CHANGE_CIPHER_SENT :
if ( (ssl->error = SendFinished(ssl)) != 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
ssl->options.acceptState = ACCEPT_FINISHED_DONE;
CYASSL_MSG("accept state ACCEPT_FINISHED_DONE");
case ACCEPT_FINISHED_DONE :
if (ssl->options.resuming)
while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE)
if ( (ssl->error = ProcessReply(ssl)) < 0) {
CYASSL_ERROR(ssl->error);
return SSL_FATAL_ERROR;
}
ssl->options.acceptState = ACCEPT_THIRD_REPLY_DONE;
CYASSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE");
case ACCEPT_THIRD_REPLY_DONE :
if (ssl->buffers.inputBuffer.dynamicFlag)
ShrinkInputBuffer(ssl, NO_FORCED_FREE);
CYASSL_LEAVE("SSL_accept()", SSL_SUCCESS);
return SSL_SUCCESS;
default :
CYASSL_MSG("Unknown accept state ERROR");
return SSL_FATAL_ERROR;
}
}
#endif /* NO_CYASSL_SERVER */
/* prevent multiple mutex initializations */
static volatile int initRefCount = 0;
static CyaSSL_Mutex count_mutex; /* init ref count mutex */
int CyaSSL_Init(void)
{
int ret = 0;
CYASSL_ENTER("CyaSSL_Init");
if (initRefCount == 0) {
#ifndef NO_SESSION_CACHE
if (InitMutex(&session_mutex) != 0)
ret = BAD_MUTEX_ERROR;
#endif
if (InitMutex(&count_mutex) != 0)
ret = BAD_MUTEX_ERROR;
}
if (ret == 0) {
LockMutex(&count_mutex);
initRefCount++;
UnLockMutex(&count_mutex);
}
return ret;
}
int CyaSSL_Cleanup(void)
{
int ret = 0;
int release = 0;
CYASSL_ENTER("CyaSSL_Cleanup");
LockMutex(&count_mutex);
release = initRefCount-- == 1;
if (initRefCount < 0)
initRefCount = 0;
UnLockMutex(&count_mutex);
if (!release)
return ret;
#ifndef NO_SESSION_CACHE
if (FreeMutex(&session_mutex) != 0)
ret = BAD_MUTEX_ERROR;
#endif
if (FreeMutex(&count_mutex) != 0)
ret = BAD_MUTEX_ERROR;
return ret;
}
#ifndef NO_SESSION_CACHE
static INLINE word32 HashSession(const byte* sessionID)
{
/* id is random, just make 32 bit number from first 4 bytes for now */
return (sessionID[0] << 24) | (sessionID[1] << 16) | (sessionID[2] << 8) |
sessionID[3];
}
void CyaSSL_flush_sessions(CYASSL_CTX* ctx, long tm)
{
/* static table now, no flusing needed */
(void)ctx;
(void)tm;
}
/* set ssl session timeout in seconds */
int CyaSSL_set_timeout(CYASSL* ssl, unsigned int to)
{
if (ssl == NULL)
return BAD_FUNC_ARG;
ssl->timeout = to;
return SSL_SUCCESS;
}
/* set ctx session timeout in seconds */
int CyaSSL_CTX_set_timeout(CYASSL_CTX* ctx, unsigned int to)
{
if (ctx == NULL)
return BAD_FUNC_ARG;
ctx->timeout = to;
return SSL_SUCCESS;
}
CYASSL_SESSION* GetSession(CYASSL* ssl, byte* masterSecret)
{
CYASSL_SESSION* ret = 0;
const byte* id = ssl->arrays.sessionID;
word32 row;
int idx;
if (ssl->options.sessionCacheOff)
return NULL;
if (ssl->options.haveSessionId == 0)
return NULL;
row = HashSession(id) % SESSION_ROWS;
if (LockMutex(&session_mutex) != 0)
return 0;
if (SessionCache[row].totalCount >= SESSIONS_PER_ROW)
idx = SESSIONS_PER_ROW - 1;
else
idx = SessionCache[row].nextIdx - 1;
for (; idx >= 0; idx--) {
CYASSL_SESSION* current;
if (idx >= SESSIONS_PER_ROW) /* server could have restarted, idx */
break; /* would be word32(-1) and seg fault */
current = &SessionCache[row].Sessions[idx];
if (XMEMCMP(current->sessionID, id, ID_LEN) == 0) {
if (LowResTimer() < (current->bornOn + current->timeout)) {
ret = current;
if (masterSecret)
XMEMCPY(masterSecret, current->masterSecret, SECRET_LEN);
}
break;
}
}
UnLockMutex(&session_mutex);
return ret;
}
int SetSession(CYASSL* ssl, CYASSL_SESSION* session)
{
if (ssl->options.sessionCacheOff)
return SSL_FAILURE;
if (LowResTimer() < (session->bornOn + session->timeout)) {
ssl->session = *session;
ssl->options.resuming = 1;
#ifdef SESSION_CERTS
ssl->version = session->version;
ssl->options.cipherSuite0 = session->cipherSuite0;
ssl->options.cipherSuite = session->cipherSuite;
#endif
return SSL_SUCCESS;
}
return SSL_FAILURE; /* session timed out */
}
int AddSession(CYASSL* ssl)
{
word32 row, idx;
if (ssl->options.sessionCacheOff)
return 0;
if (ssl->options.haveSessionId == 0)
return 0;
row = HashSession(ssl->arrays.sessionID) % SESSION_ROWS;
if (LockMutex(&session_mutex) != 0)
return BAD_MUTEX_ERROR;
idx = SessionCache[row].nextIdx++;
XMEMCPY(SessionCache[row].Sessions[idx].masterSecret,
ssl->arrays.masterSecret, SECRET_LEN);
XMEMCPY(SessionCache[row].Sessions[idx].sessionID, ssl->arrays.sessionID,
ID_LEN);
SessionCache[row].Sessions[idx].timeout = ssl->timeout;
SessionCache[row].Sessions[idx].bornOn = LowResTimer();
#ifdef SESSION_CERTS
SessionCache[row].Sessions[idx].chain.count = ssl->session.chain.count;
XMEMCPY(SessionCache[row].Sessions[idx].chain.certs,
ssl->session.chain.certs, sizeof(x509_buffer) * MAX_CHAIN_DEPTH);
SessionCache[row].Sessions[idx].version = ssl->version;
SessionCache[row].Sessions[idx].cipherSuite0 = ssl->options.cipherSuite0;
SessionCache[row].Sessions[idx].cipherSuite = ssl->options.cipherSuite;
#endif
SessionCache[row].totalCount++;
if (SessionCache[row].nextIdx == SESSIONS_PER_ROW)
SessionCache[row].nextIdx = 0;
if (UnLockMutex(&session_mutex) != 0)
return BAD_MUTEX_ERROR;
return 0;
}
#ifdef SESSION_STATS
CYASSL_API
void PrintSessionStats(void)
{
word32 totalSessionsSeen = 0;
word32 totalSessionsNow = 0;
word32 rowNow;
int i;
double E; /* expected freq */
double chiSquare = 0;
for (i = 0; i < SESSION_ROWS; i++) {
totalSessionsSeen += SessionCache[i].totalCount;
if (SessionCache[i].totalCount >= SESSIONS_PER_ROW)
rowNow = SESSIONS_PER_ROW;
else if (SessionCache[i].nextIdx == 0)
rowNow = 0;
else
rowNow = SessionCache[i].nextIdx;
totalSessionsNow += rowNow;
}
printf("Total Sessions Seen = %d\n", totalSessionsSeen);
printf("Total Sessions Now = %d\n", totalSessionsNow);
E = (double)totalSessionsSeen / SESSION_ROWS;
for (i = 0; i < SESSION_ROWS; i++) {
double diff = SessionCache[i].totalCount - E;
diff *= diff; /* square */
diff /= E; /* normalize */
chiSquare += diff;
}
printf(" chi-square = %5.1f, d.f. = %d\n", chiSquare,
SESSION_ROWS - 1);
if (SESSION_ROWS == 11)
printf(" .05 p value = 18.3, chi-square should be less\n");
else if (SESSION_ROWS == 211)
printf(".05 p value = 244.8, chi-square should be less\n");
else if (SESSION_ROWS == 5981)
printf(".05 p value = 6161.0, chi-square should be less\n");
else if (SESSION_ROWS == 3)
printf(".05 p value = 6.0, chi-square should be less\n");
else if (SESSION_ROWS == 2861)
printf(".05 p value = 2985.5, chi-square should be less\n");
printf("\n");
}
#endif /* SESSION_STATS */
#else /* NO_SESSION_CACHE */
/* No session cache version */
CYASSL_SESSION* GetSession(CYASSL* ssl, byte* masterSecret)
{
return NULL;
}
#endif /* NO_SESSION_CACHE */
/* call before SSL_connect, if verifying will add name check to
date check and signature check */
int CyaSSL_check_domain_name(CYASSL* ssl, const char* dn)
{
CYASSL_ENTER("CyaSSL_check_domain_name");
if (ssl->buffers.domainName.buffer)
XFREE(ssl->buffers.domainName.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN);
ssl->buffers.domainName.length = (word32)XSTRLEN(dn) + 1;
ssl->buffers.domainName.buffer = (byte*) XMALLOC(
ssl->buffers.domainName.length, ssl->heap, DYNAMIC_TYPE_DOMAIN);
if (ssl->buffers.domainName.buffer) {
XSTRNCPY((char*)ssl->buffers.domainName.buffer, dn,
ssl->buffers.domainName.length);
return SSL_SUCCESS;
}
else {
ssl->error = MEMORY_ERROR;
return SSL_FAILURE;
}
}
/* turn on CyaSSL zlib compression
returns 0 for success, else error (not built in)
*/
int CyaSSL_set_compression(CYASSL* ssl)
{
CYASSL_ENTER("CyaSSL_set_compression");
(void)ssl;
#ifdef HAVE_LIBZ
ssl->options.usingCompression = 1;
return 0;
#else
return NOT_COMPILED_IN;
#endif
}
#ifndef USE_WINDOWS_API
#ifndef NO_WRITEV
/* simulate writev semantics, doesn't actually do block at a time though
because of SSL_write behavior and because front adds may be small */
int CyaSSL_writev(CYASSL* ssl, const struct iovec* iov, int iovcnt)
{
byte tmp[OUTPUT_RECORD_SIZE];
byte* myBuffer = tmp;
int send = 0;
int newBuffer = 0;
int idx = 0;
int i;
int ret;
CYASSL_ENTER("CyaSSL_writev");
for (i = 0; i < iovcnt; i++)
send += iov[i].iov_len;
if (send > (int)sizeof(tmp)) {
byte* tmp2 = (byte*) XMALLOC(send, ssl->heap,
DYNAMIC_TYPE_WRITEV);
if (!tmp2)
return MEMORY_ERROR;
myBuffer = tmp2;
newBuffer = 1;
}
for (i = 0; i < iovcnt; i++) {
XMEMCPY(&myBuffer[idx], iov[i].iov_base, iov[i].iov_len);
idx += iov[i].iov_len;
}
ret = CyaSSL_write(ssl, myBuffer, send);
if (newBuffer) XFREE(myBuffer, ssl->heap, DYNAMIC_TYPE_WRITEV);
return ret;
}
#endif
#endif
#ifdef CYASSL_CALLBACKS
typedef struct itimerval Itimerval;
/* don't keep calling simple functions while setting up timer and singals
if no inlining these are the next best */
#define AddTimes(a, b, c) \
do { \
c.tv_sec = a.tv_sec + b.tv_sec; \
c.tv_usec = a.tv_usec + b.tv_usec; \
if (c.tv_sec >= 1000000) { \
c.tv_sec++; \
c.tv_usec -= 1000000; \
} \
} while (0)
#define SubtractTimes(a, b, c) \
do { \
c.tv_sec = a.tv_sec - b.tv_sec; \
c.tv_usec = a.tv_usec - b.tv_usec; \
if (c.tv_sec < 0) { \
c.tv_sec--; \
c.tv_usec += 1000000; \
} \
} while (0)
#define CmpTimes(a, b, cmp) \
((a.tv_sec == b.tv_sec) ? \
(a.tv_usec cmp b.tv_usec) : \
(a.tv_sec cmp b.tv_sec)) \
/* do nothing handler */
static void myHandler(int signo)
{
return;
}
static int CyaSSL_ex_wrapper(CYASSL* ssl, HandShakeCallBack hsCb,
TimeoutCallBack toCb, Timeval timeout)
{
int ret = SSL_FATAL_ERROR;