Ignore:
Timestamp:
Jun 22, 2021, 9:00:19 PM (3 years ago)
Author:
coas-nagasima
Message:

WolfSSLとAzure IoT SDKを更新

Location:
azure_iot_hub_f767zi/trunk/wolfssl-4.7.0
Files:
1 edited
1 moved

Legend:

Unmodified
Added
Removed
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/src/sniffer.c

    r457 r464  
    2626
    2727#include <wolfssl/wolfcrypt/settings.h>
    28 
    29 #ifndef WOLFCRYPT_ONLY
     28#include <wolfssl/wolfcrypt/wc_port.h>
     29
     30/* xctime */
     31#ifndef XCTIME
     32   #define XCTIME ctime
     33#endif
     34
     35/* only in this file, to avoid confusing future ports leave
     36 * these defines here. Do not move to wc_port.h */
     37#ifdef USER_CUSTOM_SNIFFX
     38    /* To be implemented in user_settings.h */
     39#elif defined(FUSION_RTOS)
     40    #include <fcl_network.h>
     41    #define XINET_NTOA FNS_INET_NTOA
     42    #define XINET_ATON FNS_INET_ATON
     43    #define XINET_PTON(a,b,c,d) FNS_INET_PTON((a),(b),(c),(d),NULL)
     44    #define XINET_NTOP(a,b,c,d) FNS_INET_NTOP((a),(b),(c),(d),NULL)
     45    #define XINET_ADDR FNS_INET_ADDR
     46    #define XHTONS FNS_HTONS
     47    #define XNTOHS FNS_NTOHS
     48    #define XHTONL FNS_HTONL
     49    #define XNTOHL FNS_NTOHL
     50    #define XINADDR_NONE FNS_INADDR_NONE
     51#else
     52    /* default */
     53    #define XINET_NTOA inet_ntoa
     54    #define XINET_ATON inet_aton
     55    #define XINET_PTON(a,b,c) inet_pton((a),(b),(c))
     56    #define XINET_NTOP inet_ntop
     57    #define XINET_ADDR inet_addr
     58    #define XHTONS htons
     59    #define XNTOHS ntohs
     60    #define XHTONL htonl
     61    #define XNTOHL ntohl
     62    #define XINADDR_NONE INADDR_NONE
     63#endif
     64
     65#if !defined(WOLFCRYPT_ONLY) && !defined(NO_FILESYSTEM)
    3066#ifdef WOLFSSL_SNIFFER
    3167
     
    3369#include <time.h>
    3470
    35 #ifndef _WIN32
    36   #include <arpa/inet.h>
     71#ifdef FUSION_RTOS
     72    #include <fns_inet.h>
     73    #ifdef TCP_PROTOCOL
     74        #undef TCP_PROTOCOL
     75    #endif
    3776#else
    38   #include <WS2tcpip.h>
     77    #ifndef _WIN32
     78        #include <arpa/inet.h>
     79    #else
     80        #include <WS2tcpip.h>
     81    #endif
    3982#endif
    4083
     
    4588#endif
    4689
    47 #include <wolfssl/openssl/ssl.h>
    4890#include <wolfssl/internal.h>
    4991#include <wolfssl/error-ssl.h>
     
    91133    HASH_SIZE          = 499, /* Session Hash Table Rows */
    92134    PSEUDO_HDR_SZ      = 12,  /* TCP Pseudo Header size in bytes */
    93     FATAL_ERROR_STATE  =  1,  /* SnifferSession fatal error state */
     135    FATAL_ERROR_STATE  = 1,   /* SnifferSession fatal error state */
    94136    TICKET_HINT_LEN    = 4,   /* Session Ticket Hint length */
    95     EXT_TYPE_SZ        = 2,   /* Extension length */
     137    TICKET_HINT_AGE_LEN= 4,   /* Session Ticket Age add length */       
     138    EXT_TYPE_SZ        = 2,   /* Extension type length */
    96139    MAX_INPUT_SZ       = MAX_RECORD_SIZE + COMP_EXTRA + MAX_MSG_EXTRA +
    97140                         MTU_EXTRA,  /* Max input sz of reassembly */
    98     EXT_MASTER_SECRET  = 0x17, /* Extended Master Secret Extension ID */
    99     TICKET_EXT_ID      = 0x23 /* Session Ticket Extension ID */
     141
     142    /* TLS Extensions */
     143    EXT_SERVER_NAME                = 0x0000, /* a.k.a. SNI  */
     144    EXT_MAX_FRAGMENT_LENGTH        = 0x0001,
     145    EXT_TRUSTED_CA_KEYS            = 0x0003,
     146    EXT_TRUNCATED_HMAC             = 0x0004,
     147    EXT_STATUS_REQUEST             = 0x0005, /* a.k.a. OCSP stapling   */
     148    EXT_SUPPORTED_GROUPS           = 0x000a, /* a.k.a. Supported Curves */
     149    EXT_EC_POINT_FORMATS           = 0x000b,
     150    EXT_SIGNATURE_ALGORITHMS       = 0x000d,
     151    EXT_APPLICATION_LAYER_PROTOCOL = 0x0010, /* a.k.a. ALPN */
     152    EXT_STATUS_REQUEST_V2          = 0x0011, /* a.k.a. OCSP stapling v2 */
     153    EXT_ENCRYPT_THEN_MAC           = 0x0016, /* RFC 7366 */
     154    EXT_MASTER_SECRET              = 0x0017, /* Extended Master Secret Extension ID */
     155    EXT_TICKET_ID                  = 0x0023, /* Session Ticket Extension ID */
     156    EXT_PRE_SHARED_KEY             = 0x0029,
     157    EXT_EARLY_DATA                 = 0x002a,
     158    EXT_SUPPORTED_VERSIONS         = 0x002b,
     159    EXT_COOKIE                     = 0x002c,
     160    EXT_PSK_KEY_EXCHANGE_MODES     = 0x002d,
     161    EXT_POST_HANDSHAKE_AUTH        = 0x0031,
     162    EXT_SIGNATURE_ALGORITHMS_CERT  = 0x0032,
     163    EXT_KEY_SHARE                  = 0x0033,
     164    EXT_RENEGOTIATION_INFO         = 0xff01
    100165};
    101166
     
    139204
    140205static WOLFSSL_GLOBAL int TraceOn = 0;         /* Trace is off by default */
    141 static WOLFSSL_GLOBAL FILE* TraceFile = 0;
     206static WOLFSSL_GLOBAL XFILE TraceFile = 0;
    142207
    143208
     
    276341    "No data destination Error",
    277342    "Store data callback failed",
    278     "Loading chain input"
     343    "Loading chain input",
     344    "Got encrypted extension",
     345    "Got Hello Retry Request",
    279346};
    280347
     
    319386    byte*            key;                        /* DER private key */
    320387    word32           keySz;                      /* size of DER private key */
     388    int              isEphemeralKey;
    321389    struct NamedKey* next;                       /* for list */
    322390} NamedKey;
     
    336404/* Sniffer Server holds info for each server/port monitored */
    337405typedef struct SnifferServer {
    338     SSL_CTX*       ctx;                          /* SSL context */
     406    WOLFSSL_CTX*   ctx;                          /* SSL context */
    339407    char           address[MAX_SERVER_ADDRESS];  /* passed in server address */
    340408    IpAddrInfo     server;                       /* network order address */
     
    365433    byte           expectEms;       /* expect extended master secret */
    366434#endif
     435    byte           gotFinished;     /* processed finished */
    367436} Flags;
    368437
    369438
    370439/* Out of Order FIN capture */
    371 typedef struct FinCaputre {
     440typedef struct FinCapture {
    372441    word32 cliFinSeq;               /* client relative sequence FIN  0 is no */
    373442    word32 srvFinSeq;               /* server relative sequence FIN, 0 is no */
    374443    byte   cliCounted;              /* did we count yet, detects duplicates */
    375444    byte   srvCounted;              /* did we count yet, detects duplicates */
    376 } FinCaputre;
     445} FinCapture;
    377446
    378447
     
    385454    wc_Md5 hashMd5;
    386455#endif
    387 #endif
     456#endif /* !NO_OLD_TLS */
    388457#ifndef NO_SHA256
    389458    wc_Sha256 hashSha256;
     
    393462#endif
    394463} HsHashes;
     464
     465typedef struct KeyShareInfo {
     466    word16      named_group;
     467    int         key_len;
     468    const byte* key;
     469
     470    /* additional info */
     471    int         dh_key_bits;
     472    int         curve_id;
     473} KeyShareInfo;
    395474
    396475
     
    398477typedef struct SnifferSession {
    399478    SnifferServer* context;         /* server context */
    400     SSL*           sslServer;       /* SSL server side decode */
    401     SSL*           sslClient;       /* SSL client side decode */
     479    WOLFSSL*       sslServer;       /* SSL server side decode */
     480    WOLFSSL*       sslClient;       /* SSL client side decode */
    402481    IpAddrInfo     server;          /* server address in network byte order */
    403482    IpAddrInfo     client;          /* client address in network byte order */
     
    408487    word32         cliExpected;     /* client expected sequence (relative) */
    409488    word32         srvExpected;     /* server expected sequence (relative) */
    410     FinCaputre     finCaputre;      /* retain out of order FIN s */
     489    FinCapture     finCapture;      /* retain out of order FIN s */
    411490    Flags          flags;           /* session flags */
    412     time_t         lastUsed;          /* last used ticks */
     491    time_t         lastUsed;        /* last used ticks */
    413492    word32         keySz;           /* size of the private key */
    414493    PacketBuffer*  cliReassemblyList; /* client out of order packets */
     
    416495    word32         cliReassemblyMemory; /* client packet memory used */
    417496    word32         srvReassemblyMemory; /* server packet memory used */
    418     struct SnifferSession* next;      /* for hash table list */
    419     byte*          ticketID;          /* mac ID of session ticket */
     497    struct SnifferSession* next;    /* for hash table list */
     498    byte*          ticketID;        /* mac ID of session ticket */
     499#ifdef HAVE_MAX_FRAGMENT
     500    byte*          tlsFragBuf;
     501    word32         tlsFragOffset;
     502    word32         tlsFragSize;
     503#endif
    420504#ifdef HAVE_SNI
    421505    const char*    sni;             /* server name indication */
    422506#endif
    423507#ifdef HAVE_EXTENDED_MASTER
    424     HsHashes*       hash;
     508    HsHashes*      hash;
     509#endif
     510#ifdef WOLFSSL_TLS13
     511    byte*          cliKeyShare;
     512    word32         cliKeyShareSz;
     513    KeyShareInfo   srvKs;
     514    KeyShareInfo   cliKs;
    425515#endif
    426516} SnifferSession;
     
    559649        wc_FreeMutex(&srv->namedKeysMutex);
    560650#endif
    561         SSL_CTX_free(srv->ctx);
     651        wolfSSL_CTX_free(srv->ctx);
    562652    }
    563653    XFREE(srv, NULL, DYNAMIC_TYPE_SNIFFER_SERVER);
     
    595685{
    596686    if (session) {
    597         SSL_free(session->sslClient);
    598         SSL_free(session->sslServer);
     687        wolfSSL_free(session->sslClient);
     688        wolfSSL_free(session->sslServer);
    599689
    600690        FreePacketList(session->cliReassemblyList);
     
    604694#ifdef HAVE_EXTENDED_MASTER
    605695        XFREE(session->hash, NULL, DYNAMIC_TYPE_HASHES);
     696#endif
     697#ifdef WOLFSSL_TLS13
     698        if (session->cliKeyShare)
     699            XFREE(session->cliKeyShare, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     700#endif
     701#ifdef HAVE_MAX_FRAGMENT
     702        if (session->tlsFragBuf) {
     703            XFREE(session->tlsFragBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     704            session->tlsFragBuf = NULL;
     705        }
    606706#endif
    607707    }
     
    622722    wc_LockMutex(&SessionMutex);
    623723
    624     srv = ServerList;
    625     while (srv) {
    626         removeServer = srv;
    627         srv = srv->next;
    628         FreeSnifferServer(removeServer);
    629     }
    630 
     724    /* Free sessions (wolfSSL objects) first */
    631725    for (i = 0; i < HASH_SIZE; i++) {
    632726        session = SessionTable[i];
     
    637731        }
    638732    }
     733    SessionCount = 0;
     734
     735    /* Then server (wolfSSL_CTX) */
     736    srv = ServerList;
     737    while (srv) {
     738        removeServer = srv;
     739        srv = srv->next;
     740        FreeSnifferServer(removeServer);
     741    }
     742    ServerList = NULL;   
    639743
    640744    wc_UnLockMutex(&SessionMutex);
     
    656760    if (TraceFile) {
    657761        TraceOn = 0;
    658         fclose(TraceFile);
     762        XFCLOSE(TraceFile);
    659763        TraceFile = NULL;
    660764    }
     
    678782#endif
    679783#ifndef NO_MD5
    680     if (ret == 0) {
     784    if (ret == 0)
    681785        ret = wc_InitMd5(&hash->hashMd5);
    682     }
    683 #endif
    684 #endif
     786#endif
     787#endif /* !NO_OLD_TLS */
    685788#ifndef NO_SHA256
    686789    if (ret == 0)
     
    694797    return ret;
    695798}
    696 
    697799
    698800static int HashUpdate(HsHashes* hash, const byte* input, int sz)
     
    709811#endif
    710812#ifndef NO_MD5
    711     if (ret == 0) {
     813    if (ret == 0)
    712814        ret = wc_Md5Update(&hash->hashMd5, input, sz);
    713     }
    714 #endif
    715 #endif
     815#endif
     816#endif /* !NO_OLD_TLS */
    716817#ifndef NO_SHA256
    717818    if (ret == 0)
     
    726827}
    727828
    728 
    729829static int HashCopy(HS_Hashes* d, HsHashes* s)
    730830{
    731831#ifndef NO_OLD_TLS
    732832#ifndef NO_SHA
    733         XMEMCPY(&d->hashSha, &s->hashSha, sizeof(wc_Sha));
     833    XMEMCPY(&d->hashSha, &s->hashSha, sizeof(wc_Sha));
    734834#endif
    735835#ifndef NO_MD5
    736         XMEMCPY(&d->hashMd5, &s->hashMd5, sizeof(wc_Md5));
    737 #endif
    738 #endif
    739 
     836    XMEMCPY(&d->hashMd5, &s->hashMd5, sizeof(wc_Md5));
     837#endif
     838#endif /* !NO_OLD_TLS */
    740839#ifndef NO_SHA256
    741         XMEMCPY(&d->hashSha256, &s->hashSha256, sizeof(wc_Sha256));
     840    XMEMCPY(&d->hashSha256, &s->hashSha256, sizeof(wc_Sha256));
    742841#endif
    743842#ifdef WOLFSSL_SHA384
    744         XMEMCPY(&d->hashSha384, &s->hashSha384, sizeof(wc_Sha384));
     843    XMEMCPY(&d->hashSha384, &s->hashSha384, sizeof(wc_Sha384));
    745844#endif
    746845
     
    766865
    767866/* Initialize FIN Capture */
    768 static void InitFinCapture(FinCaputre* cap)
    769 {
    770     XMEMSET(cap, 0, sizeof(FinCaputre));
     867static void InitFinCapture(FinCapture* cap)
     868{
     869    XMEMSET(cap, 0, sizeof(FinCapture));
    771870}
    772871
     
    777876    XMEMSET(session, 0, sizeof(SnifferSession));
    778877    InitFlags(&session->flags);
    779     InitFinCapture(&session->finCaputre);
     878    InitFinCapture(&session->finCapture);
    780879}
    781880
     
    900999        char myBuffer[MAX_ERROR_LEN];
    9011000        GetError(idx, myBuffer);
    902         fprintf(TraceFile, "\t%s\n", myBuffer);
     1001        XFPRINTF(TraceFile, "\t%s\n", myBuffer);
    9031002#ifdef DEBUG_SNIFFER
    904         fprintf(stderr,    "\t%s\n", myBuffer);
     1003        XFPRINTF(stderr,    "\t%s\n", myBuffer);
    9051004#endif
    9061005    }
     
    9121011{
    9131012    if (TraceOn) {
    914         time_t ticks = time(NULL);
    915         fprintf(TraceFile, "\n%s", ctime(&ticks));
     1013        time_t ticks = XTIME(NULL);
     1014        XFPRINTF(TraceFile, "\n%s", XCTIME(&ticks));
    9161015    }
    9171016}
     
    9221021{
    9231022    if (TraceOn) {
    924         fprintf(TraceFile, "\tTrying to install a new Sniffer Server with\n");
    925         fprintf(TraceFile, "\tserver: %s, port: %d, keyFile: %s\n", srv, port,
     1023        XFPRINTF(TraceFile, "\tTrying to install a new Sniffer Server with\n");
     1024        XFPRINTF(TraceFile, "\tserver: %s, port: %d, keyFile: %s\n", srv, port,
    9261025                                                                    keyFile);
    9271026    }
     
    9361035{
    9371036    if (TraceOn) {
    938         fprintf(TraceFile, "\tTrying to install a new Sniffer Server with\n");
    939         fprintf(TraceFile, "\tname: %s, server: %s, port: %d, keyFile: %s\n",
    940                                                       name, srv, port, keyFile);
     1037        XFPRINTF(TraceFile, "\tTrying to install a new Sniffer Server with\n");
     1038        XFPRINTF(TraceFile, "\tname: %s, server: %s, port: %d, keyFile: %s\n",
     1039                name ? name : "",
     1040                srv ? srv : "",
     1041                port,
     1042                keyFile ? keyFile : "");
    9411043    }
    9421044}
     
    9501052    if (TraceOn) {
    9511053        static word32 packetNumber = 0;
    952         fprintf(TraceFile, "\tGot a Packet to decode, packet %u\n",
     1054        XFPRINTF(TraceFile, "\tGot a Packet to decode, packet %u\n",
    9531055                ++packetNumber);
    9541056    }
     
    9591061static const char* IpToS(int version, void* src, char* dst)
    9601062{
    961     return inet_ntop(version, src, dst, TRACE_MSG_SZ);
     1063    return XINET_NTOP(version, src, dst, TRACE_MSG_SZ);
    9621064}
    9631065
     
    9691071        char src[TRACE_MSG_SZ];
    9701072        char dst[TRACE_MSG_SZ];
    971         fprintf(TraceFile, "\tdst:%s src:%s\n",
     1073        XFPRINTF(TraceFile, "\tdst:%s src:%s\n",
    9721074                IpToS(AF_INET, &iphdr->dst, dst),
    9731075                IpToS(AF_INET, &iphdr->src, src));
     
    9821084        char src[TRACE_MSG_SZ];
    9831085        char dst[TRACE_MSG_SZ];
    984         fprintf(TraceFile, "\tdst: %s src: %s\n",
     1086        XFPRINTF(TraceFile, "\tdst: %s src: %s\n",
    9851087                IpToS(AF_INET6, iphdr->dst, dst),
    9861088                IpToS(AF_INET6, iphdr->src, src));
     
    9931095{
    9941096    if (TraceOn) {
    995         fprintf(TraceFile, "\tdstPort:%u srcPort:%u\n", ntohs(tcphdr->dstPort),
    996                 ntohs(tcphdr->srcPort));
     1097        XFPRINTF(TraceFile, "\tdstPort:%u srcPort:%u\n", XNTOHS(tcphdr->dstPort),
     1098                XNTOHS(tcphdr->srcPort));
    9971099    }
    9981100}
     
    10031105{
    10041106    if (TraceOn) {
    1005         fprintf(TraceFile, "\tSequence:%u, payload length:%d\n", seq, len);
     1107        XFPRINTF(TraceFile, "\tSequence:%u, payload length:%d\n", seq, len);
    10061108    }
    10071109}
     
    10121114{
    10131115    if (TraceOn) {
    1014         fprintf(TraceFile, "\tAck:%u Expected:%u\n", ack, expected);
     1116        XFPRINTF(TraceFile, "\tAck:%u Expected:%u\n", ack, expected);
    10151117    }
    10161118}
     
    10211123{
    10221124    if (TraceOn) {
    1023         fprintf(TraceFile, "\tExpected sequence:%u, received sequence:%u\n",
     1125        XFPRINTF(TraceFile, "\tExpected sequence:%u, received sequence:%u\n",
    10241126                expected, got);
    10251127    }
     
    10311133{
    10321134    if (TraceOn) {
    1033         fprintf(TraceFile, "\tServer SYN, Sequence Start:%u\n", seq);
     1135        XFPRINTF(TraceFile, "\tServer SYN, Sequence Start:%u\n", seq);
    10341136    }
    10351137}
     
    10401142{
    10411143    if (TraceOn) {
    1042         fprintf(TraceFile, "\tClient SYN, Sequence Start:%u\n", seq);
     1144        XFPRINTF(TraceFile, "\tClient SYN, Sequence Start:%u\n", seq);
    10431145    }
    10441146}
     
    10491151{
    10501152    if (TraceOn) {
    1051         fprintf(TraceFile, "\tClient FIN capture:%u, current SEQ:%u\n",
     1153        XFPRINTF(TraceFile, "\tClient FIN capture:%u, current SEQ:%u\n",
    10521154                finSeq, relSeq);
    10531155    }
     
    10591161{
    10601162    if (TraceOn) {
    1061         fprintf(TraceFile, "\tServer FIN capture:%u, current SEQ:%u\n",
     1163        XFPRINTF(TraceFile, "\tServer FIN capture:%u, current SEQ:%u\n",
    10621164                finSeq, relSeq);
    10631165    }
     
    10691171{
    10701172    if (TraceOn) {
    1071         fprintf(TraceFile, "\t%d bytes of SSL App data processed\n", bytes);
     1173        XFPRINTF(TraceFile, "\t%d bytes of SSL App data processed\n", bytes);
    10721174    }
    10731175}
     
    10781180{
    10791181    if (TraceOn) {
    1080         fprintf(TraceFile,
     1182        XFPRINTF(TraceFile,
    10811183                "\t%d bytes added to %d existing bytes in User Buffer\n",
    10821184                newBytes, existingBytes);
     
    10891191{
    10901192    if (TraceOn) {
    1091         fprintf(TraceFile, "\tFound a stale session\n");
     1193        XFPRINTF(TraceFile, "\tFound a stale session\n");
    10921194    }
    10931195}
     
    10981200{
    10991201    if (TraceOn) {
    1100         fprintf(TraceFile, "\tTrying to find Stale Sessions\n");
     1202        XFPRINTF(TraceFile, "\tTrying to find Stale Sessions\n");
    11011203    }
    11021204}
     
    11071209{
    11081210    if (TraceOn) {
    1109         fprintf(TraceFile, "\tRemoved it\n");
     1211        XFPRINTF(TraceFile, "\tRemoved it\n");
    11101212    }
    11111213}
     
    11171219    if (TraceOn) {
    11181220        if (sslInfo != NULL && sslInfo->isValid) {
    1119             fprintf(TraceFile,
     1221            XFPRINTF(TraceFile,
    11201222                    "\tver:(%u %u) suiteId:(%02x %02x) suiteName:(%s) "
    11211223                    #ifdef HAVE_SNI
     
    11431245{
    11441246    if (TraceOn) {
    1145         fprintf(TraceFile, "\tAdding %d to %s\n", add, name);
     1247        XFPRINTF(TraceFile, "\tAdding %d to %s\n", add, name);
    11461248    }
    11471249}
     
    13101412{
    13111413    SnifferSession* session;
    1312     time_t          currTime = time(NULL);
     1414    time_t          currTime = XTIME(NULL);
    13131415    word32          row = SessionHash(ipInfo, tcpInfo);
    13141416
     
    13581460
    13591461static int LoadKeyFile(byte** keyBuf, word32* keyBufSz,
    1360                 const char* keyFile, int typeKey,
     1462                const char* keyFile, int keySz, int typeKey,
    13611463                const char* password)
    13621464{
     
    13641466    long fileSz = 0;
    13651467    XFILE file;
    1366     int ret;
     1468    int ret = -1;
    13671469
    13681470    if (keyBuf == NULL || keyBufSz == NULL || keyFile == NULL) {
     
    13701472    }
    13711473
    1372     file = XFOPEN(keyFile, "rb");
    1373     if (file == XBADFILE) return -1;
    1374     if(XFSEEK(file, 0, XSEEK_END) != 0) {
     1474    if (keySz == 0) {
     1475        /* load from file */
     1476        file = XFOPEN(keyFile, "rb");
     1477        if (file == XBADFILE) return -1;
     1478        if(XFSEEK(file, 0, XSEEK_END) != 0) {
     1479            XFCLOSE(file);
     1480            return -1;
     1481        }
     1482        fileSz = XFTELL(file);
     1483        if (fileSz > MAX_WOLFSSL_FILE_SIZE || fileSz < 0) {
     1484            XFCLOSE(file);
     1485            return -1;
     1486        }
     1487        XREWIND(file);
     1488
     1489        loadBuf = (byte*)XMALLOC(fileSz, NULL, DYNAMIC_TYPE_FILE);
     1490        if (loadBuf == NULL) {
     1491            XFCLOSE(file);
     1492            return -1;
     1493        }
     1494
     1495        ret = (int)XFREAD(loadBuf, 1, fileSz, file);
    13751496        XFCLOSE(file);
    1376         return -1;
    1377     }
    1378     fileSz = XFTELL(file);
    1379     if (fileSz > MAX_WOLFSSL_FILE_SIZE || fileSz < 0) {
    1380         XFCLOSE(file);
    1381         return -1;
    1382     }
    1383     XREWIND(file);
    1384 
    1385     loadBuf = (byte*)XMALLOC(fileSz, NULL, DYNAMIC_TYPE_FILE);
    1386     if (loadBuf == NULL) {
    1387         XFCLOSE(file);
    1388         return -1;
    1389     }
    1390 
    1391     ret = (int)XFREAD(loadBuf, 1, fileSz, file);
    1392     XFCLOSE(file);
    1393 
    1394     if (ret != fileSz) {
    1395         XFREE(loadBuf, NULL, DYNAMIC_TYPE_FILE);
    1396         return -1;
     1497
     1498        if (ret != fileSz) {
     1499            XFREE(loadBuf, NULL, DYNAMIC_TYPE_FILE);
     1500            return -1;
     1501        }
     1502    }
     1503    else {
     1504        /* use buffer directly */
     1505        loadBuf = (byte*)XMALLOC(keySz, NULL, DYNAMIC_TYPE_FILE);
     1506        if (loadBuf == NULL) {
     1507            return -1;
     1508        }
     1509        fileSz = keySz;
     1510        XMEMCPY(loadBuf, keyFile, fileSz);       
    13971511    }
    13981512
     
    14501564    }
    14511565    InitSnifferServer(sniffer);
    1452     sniffer->ctx = SSL_CTX_new(TLSv1_2_client_method());
     1566    sniffer->ctx = wolfSSL_CTX_new(SSLv23_client_method());
    14531567    if (!sniffer->ctx) {
    14541568        SetError(MEMORY_STR, error, NULL, 0);
     
    14691583
    14701584static int SetNamedPrivateKey(const char* name, const char* address, int port,
    1471             const char* keyFile, int typeKey, const char* password, char* error)
     1585    const char* keyFile, int keySz, int typeKey, const char* password,
     1586    char* error, int isEphemeralKey)
    14721587{
    14731588    SnifferServer* sniffer;
     
    14981613        XSTRNCPY(namedKey->name, name, namedKey->nameSz);
    14991614        namedKey->name[MAX_SERVER_NAME-1] = '\0';
    1500 
     1615        namedKey->isEphemeralKey = isEphemeralKey;
    15011616        ret = LoadKeyFile(&namedKey->key, &namedKey->keySz,
    1502                           keyFile, type, password);
     1617                          keyFile, keySz, type, password);
    15031618        if (ret < 0) {
    15041619            SetError(KEY_FILE_STR, error, NULL, 0);
     
    15101625
    15111626    serverIp.version = IPV4;
    1512     serverIp.ip4 = inet_addr(address);
    1513     if (serverIp.ip4 == INADDR_NONE) {
    1514         if (inet_pton(AF_INET6, address, serverIp.ip6) == 1) {
     1627    serverIp.ip4 = XINET_ADDR(address);
     1628    if (serverIp.ip4 == XINADDR_NONE) {
     1629    #ifdef FUSION_RTOS
     1630        if (XINET_PTON(AF_INET6, address, serverIp.ip6,
     1631                       sizeof(serverIp.ip4)) == 1) {
     1632    #else
     1633        if (XINET_PTON(AF_INET6, address, serverIp.ip6) == 1) {
     1634    #endif
    15151635            serverIp.version = IPV6;
    15161636        }
     
    15401660        sniffer->port = port;
    15411661
    1542         sniffer->ctx = SSL_CTX_new(TLSv1_2_client_method());
     1662        sniffer->ctx = wolfSSL_CTX_new(SSLv23_client_method());
    15431663        if (!sniffer->ctx) {
    15441664            SetError(MEMORY_STR, error, NULL, 0);
     
    15541674        if (password) {
    15551675    #ifdef WOLFSSL_ENCRYPTED_KEYS
    1556             SSL_CTX_set_default_passwd_cb(sniffer->ctx, SetPassword);
    1557             SSL_CTX_set_default_passwd_cb_userdata(
     1676            wolfSSL_CTX_set_default_passwd_cb(sniffer->ctx, SetPassword);
     1677            wolfSSL_CTX_set_default_passwd_cb_userdata(
    15581678                                                 sniffer->ctx, (void*)password);
    15591679    #endif
    15601680        }
    1561         ret = SSL_CTX_use_PrivateKey_file(sniffer->ctx, keyFile, type);
     1681
     1682    #ifdef WOLFSSL_STATIC_EPHEMERAL
     1683        if (isEphemeralKey) {
     1684            /* auto detect key type with WC_PK_TYPE_NONE */
     1685            /* keySz == 0 mean load file */
     1686            ret = wolfSSL_CTX_set_ephemeral_key(sniffer->ctx, WC_PK_TYPE_NONE,
     1687                keyFile, 0, type);
     1688            if (ret == 0)
     1689                ret = WOLFSSL_SUCCESS;
     1690        }
     1691        else
     1692    #endif
     1693        {
     1694            if (keySz == 0) {
     1695                ret = wolfSSL_CTX_use_PrivateKey_file(sniffer->ctx, keyFile, type);
     1696            }
     1697            else {
     1698                ret = wolfSSL_CTX_use_PrivateKey_buffer(sniffer->ctx,
     1699                                            (const byte*)keyFile, keySz, type);
     1700            }
     1701        }
    15621702        if (ret != WOLFSSL_SUCCESS) {
    15631703            SetError(KEY_FILE_STR, error, NULL, 0);
     
    15891729
    15901730#ifdef HAVE_SNI
    1591 
    15921731/* Sets the private key for a specific name, server and port  */
    15931732/* returns 0 on success, -1 on error */
     
    16031742
    16041743    wc_LockMutex(&ServerListMutex);
    1605     ret = SetNamedPrivateKey(name, address, port, keyFile,
    1606                              typeKey, password, error);
     1744    ret = SetNamedPrivateKey(name, address, port, keyFile, 0,
     1745                             typeKey, password, error, 0);
    16071746    wc_UnLockMutex(&ServerListMutex);
    16081747
     
    16131752}
    16141753
    1615 #endif
    1616 
     1754int ssl_SetNamedPrivateKeyBuffer(const char* name,
     1755                                 const char* address, int port,
     1756                                 const char* keyBuf, int keySz, int typeKey,
     1757                                 const char* password, char* error)
     1758{
     1759    int ret;
     1760
     1761    TraceHeader();
     1762    TraceSetNamedServer(name, address, port, NULL);
     1763
     1764    wc_LockMutex(&ServerListMutex);
     1765    ret = SetNamedPrivateKey(name, address, port, keyBuf, keySz,
     1766                             typeKey, password, error, 0);
     1767    wc_UnLockMutex(&ServerListMutex);
     1768
     1769    if (ret == 0)
     1770        Trace(NEW_SERVER_STR);
     1771
     1772    return ret;
     1773}
     1774#endif /* HAVE_SNI */
    16171775
    16181776/* Sets the private key for a specific server and port  */
    16191777/* returns 0 on success, -1 on error */
    1620 int ssl_SetPrivateKey(const char* address, int port, const char* keyFile,
    1621                       int typeKey, const char* password, char* error)
     1778int ssl_SetPrivateKey(const char* address, int port,
     1779                      const char* keyFile, int typeKey,
     1780                      const char* password, char* error)
    16221781{
    16231782    int ret;
     
    16271786
    16281787    wc_LockMutex(&ServerListMutex);
    1629     ret = SetNamedPrivateKey(NULL, address, port, keyFile,
    1630                              typeKey, password, error);
     1788    ret = SetNamedPrivateKey(NULL, address, port, keyFile, 0,
     1789                             typeKey, password, error, 0);
    16311790    wc_UnLockMutex(&ServerListMutex);
    16321791
     
    16371796}
    16381797
     1798int ssl_SetPrivateKeyBuffer(const char* address, int port,
     1799                            const char* keyBuf, int keySz, int typeKey,
     1800                            const char* password, char* error)
     1801{
     1802    int ret;
     1803
     1804    TraceHeader();
     1805    TraceSetServer(address, port, "from buffer");
     1806
     1807    wc_LockMutex(&ServerListMutex);
     1808    ret = SetNamedPrivateKey(NULL, address, port, keyBuf, keySz,
     1809                             typeKey, password, error, 0);
     1810    wc_UnLockMutex(&ServerListMutex);
     1811
     1812    if (ret == 0)
     1813        Trace(NEW_SERVER_STR);
     1814
     1815    return ret;
     1816}
     1817
     1818#ifdef WOLFSSL_STATIC_EPHEMERAL
     1819#ifdef HAVE_SNI
     1820/* Sets the ephemeral key for a specific name, server and port  */
     1821/* returns 0 on success, -1 on error */
     1822int ssl_SetNamedEphemeralKey(const char* name,
     1823                             const char* address, int port,
     1824                             const char* keyFile, int typeKey,
     1825                             const char* password, char* error)
     1826{
     1827    int ret;
     1828   
     1829    TraceHeader();
     1830    TraceSetNamedServer(name, address, port, keyFile);
     1831   
     1832    wc_LockMutex(&ServerListMutex);
     1833    ret = SetNamedPrivateKey(name, address, port, keyFile, 0,
     1834                             typeKey, password, error, 1);
     1835    wc_UnLockMutex(&ServerListMutex);
     1836   
     1837    if (ret == 0)
     1838        Trace(NEW_SERVER_STR);
     1839   
     1840    return ret;
     1841}
     1842
     1843int ssl_SetNamedEphemeralKeyBuffer(const char* name,
     1844                                   const char* address, int port,
     1845                                   const char* keyBuf, int keySz, int typeKey,
     1846                                   const char* password, char* error)
     1847{
     1848    int ret;
     1849   
     1850    TraceHeader();
     1851    TraceSetNamedServer(name, address, port, NULL);
     1852   
     1853    wc_LockMutex(&ServerListMutex);
     1854    ret = SetNamedPrivateKey(name, address, port, keyBuf, keySz,
     1855                             typeKey, password, error, 1);
     1856    wc_UnLockMutex(&ServerListMutex);
     1857   
     1858    if (ret == 0)
     1859        Trace(NEW_SERVER_STR);
     1860   
     1861    return ret;
     1862}
     1863#endif /* HAVE_SNI */
     1864
     1865/* Sets the ephemeral key for a specific server and port  */
     1866/* returns 0 on success, -1 on error */
     1867int ssl_SetEphemeralKey(const char* address, int port,
     1868                        const char* keyFile, int typeKey,
     1869                        const char* password, char* error)
     1870{
     1871    int ret;
     1872   
     1873    TraceHeader();
     1874    TraceSetServer(address, port, keyFile);
     1875   
     1876    wc_LockMutex(&ServerListMutex);
     1877    ret = SetNamedPrivateKey(NULL, address, port, keyFile, 0,
     1878                             typeKey, password, error, 1);
     1879    wc_UnLockMutex(&ServerListMutex);
     1880   
     1881    if (ret == 0)
     1882        Trace(NEW_SERVER_STR);
     1883   
     1884    return ret;
     1885}
     1886
     1887int ssl_SetEphemeralKeyBuffer(const char* address, int port,
     1888                              const char* keyBuf, int keySz, int typeKey,
     1889                              const char* password, char* error)
     1890{
     1891    int ret;
     1892   
     1893    TraceHeader();
     1894    TraceSetServer(address, port, "from buffer");
     1895   
     1896    wc_LockMutex(&ServerListMutex);
     1897    ret = SetNamedPrivateKey(NULL, address, port, keyBuf, keySz,
     1898                             typeKey, password, error, 1);
     1899    wc_UnLockMutex(&ServerListMutex);
     1900   
     1901    if (ret == 0)
     1902        Trace(NEW_SERVER_STR);
     1903   
     1904    return ret;
     1905}
     1906#endif /* WOLFSSL_STATIC_EPHEMERAL */
    16391907
    16401908/* Check IP Header for IPV6, TCP, and a registered server address */
     
    16771945
    16781946    info->length = exthdrsz;
    1679     info->total = ntohs(iphdr->length) + info->length;
    1680         /* IPv6 doesn't include its own header size in the length like v4. */
     1947    info->total = XNTOHS(iphdr->length) + info->length;
     1948    /* IPv6 doesn't include its own header size in the length like v4. */
    16811949    info->src.version = IPV6;
    16821950    XMEMCPY(info->src.ip6, iphdr->src, sizeof(info->src.ip6));
     
    16931961static int CheckIpHdr(IpHdr* iphdr, IpInfo* info, int length, char* error)
    16941962{
    1695     int    version = IP_V(iphdr);
     1963    int version = IP_V(iphdr);
    16961964
    16971965    if (version == IPV6)
     
    17191987
    17201988    info->length  = IP_HL(iphdr);
    1721     info->total   = ntohs(iphdr->length);
     1989    info->total   = XNTOHS(iphdr->length);
    17221990    info->src.version = IPV4;
    17231991    info->src.ip4 = iphdr->src;
     
    17382006    TraceTcp(tcphdr);
    17392007    Trace(TCP_CHECK_STR);
    1740     info->srcPort   = ntohs(tcphdr->srcPort);
    1741     info->dstPort   = ntohs(tcphdr->dstPort);
     2008    info->srcPort   = XNTOHS(tcphdr->srcPort);
     2009    info->dstPort   = XNTOHS(tcphdr->dstPort);
    17422010    info->length    = TCP_LEN(tcphdr);
    1743     info->sequence  = ntohl(tcphdr->sequence);
     2011    info->sequence  = XNTOHL(tcphdr->sequence);
    17442012    info->fin       = tcphdr->flags & TCP_FIN;
    17452013    info->rst       = tcphdr->flags & TCP_RST;
     
    17472015    info->ack       = tcphdr->flags & TCP_ACK;
    17482016    if (info->ack)
    1749         info->ackNumber = ntohl(tcphdr->ack);
     2017        info->ackNumber = XNTOHL(tcphdr->ack);
    17502018
    17512019#ifndef WOLFSSL_SNIFFER_WATCH
     
    18022070            }
    18032071            sslInfo->keySize = session->keySz;
    1804             #ifdef HAVE_SNI
     2072        #ifdef HAVE_SNI
    18052073            if (NULL != session->sni) {
    18062074                XSTRNCPY((char*)sslInfo->serverNameIndication,
     
    18092077                         [sizeof(sslInfo->serverNameIndication) - 1] = '\0';
    18102078            }
    1811             #endif
     2079        #endif
    18122080            TraceSessionInfo(sslInfo);
    18132081        }
     
    18262094}
    18272095
    1828 
    1829 /* Process Client Key Exchange, RSA or static ECDH */
    1830 static int ProcessClientKeyExchange(const byte* input, int* sslBytes,
    1831                                     SnifferSession* session, char* error)
     2096#ifdef SHOW_SECRETS
     2097static void PrintSecret(const char* desc, const byte* buf, int sz)
     2098{
     2099    int i;
     2100    printf("%s: ", desc);
     2101    for (i = 0; i < sz; i++) {
     2102        printf("%02x", buf[i]);
     2103    }
     2104    printf("\n");
     2105}
     2106
     2107static void ShowTlsSecrets(SnifferSession* session)
     2108{
     2109    PrintSecret("server master secret", session->sslServer->arrays->masterSecret, SECRET_LEN);
     2110    PrintSecret("client master secret", session->sslClient->arrays->masterSecret, SECRET_LEN);
     2111    printf("server suite = %d\n", session->sslServer->options.cipherSuite);
     2112    printf("client suite = %d\n", session->sslClient->options.cipherSuite);
     2113}
     2114#endif /* SHOW_SECRETS */
     2115
     2116
     2117/* Process Keys */
     2118
     2119/* contains static ephemeral keys */
     2120typedef struct {
     2121#ifndef NO_DH
     2122    DerBuffer* dhKey;
     2123#endif
     2124#ifdef HAVE_ECC
     2125    DerBuffer* ecKey;
     2126#endif
     2127#if !defined(NO_RSA) && defined(WOLFSSL_STATIC_RSA)
     2128    DerBuffer* rsaKey;
     2129#endif
     2130} KeyBuffers_t;
     2131
     2132static int SetupKeys(const byte* input, int* sslBytes, SnifferSession* session,
     2133    char* error, KeyShareInfo* ksInfo, KeyBuffers_t* keys)
    18322134{
    18332135    word32 idx = 0;
    1834     int tryEcc = 0;
    18352136    int ret;
    1836 
    1837     if (session->sslServer->buffers.key == NULL ||
    1838         session->sslServer->buffers.key->buffer == NULL ||
    1839         session->sslServer->buffers.key->length == 0) {
    1840 
    1841         SetError(RSA_KEY_MISSING_STR, error, session, FATAL_ERROR_STATE);
    1842         return -1;
    1843     }
    1844 
    1845     {
     2137    DerBuffer* keyBuf;
     2138#ifdef HAVE_ECC
     2139    int useEccCurveId = ECC_CURVE_DEF;
     2140    if (ksInfo && ksInfo->curve_id != 0)
     2141        useEccCurveId = ksInfo->curve_id;
     2142#endif
     2143
     2144#ifndef NO_RSA
     2145    /* Static RSA */
     2146    if (ksInfo == NULL && keys->rsaKey) {
    18462147        RsaKey key;
    18472148        int length;
    18482149
     2150        keyBuf = keys->rsaKey;
     2151
    18492152        ret = wc_InitRsaKey(&key, 0);
    18502153        if (ret == 0) {
    1851             ret = wc_RsaPrivateKeyDecode(
    1852                     session->sslServer->buffers.key->buffer,
    1853                     &idx, &key, session->sslServer->buffers.key->length);
     2154            ret = wc_RsaPrivateKeyDecode(keyBuf->buffer, &idx, &key, keyBuf->length);
    18542155            if (ret != 0) {
    1855                 tryEcc = 1;
    1856                 #ifndef HAVE_ECC
    1857                     SetError(RSA_DECODE_STR, error, session, FATAL_ERROR_STATE);
    1858                 #else
    1859                     /* If we can do ECC, this isn't fatal. Not loading an ECC
    1860                      * key will be fatal, though. */
    1861                     SetError(RSA_DECODE_STR, error, session, 0);
    1862                 #endif
    1863             }
     2156            #ifndef HAVE_ECC
     2157                SetError(RSA_DECODE_STR, error, session, FATAL_ERROR_STATE);
     2158            #else
     2159                /* If we can do ECC, this isn't fatal. Not loading an ECC
     2160                    * key will be fatal, though. */
     2161                SetError(RSA_DECODE_STR, error, session, 0);
     2162                if (keys->ecKey == NULL)
     2163                    keys->ecKey = session->sslServer->buffers.key; /* try ECC */
     2164            #endif
     2165            }
     2166        #ifdef HAVE_ECC
     2167            else {
     2168                useEccCurveId = -1; /* don't try loading ECC */
     2169            }
     2170        #endif
    18642171        }
    18652172
     
    19092216        wc_FreeRsaKey(&key);
    19102217    }
    1911 
    1912     if (tryEcc) {
     2218#endif /* !NO_RSA */
     2219
     2220#if !defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)
     2221    /* Static DH Key */
     2222    if (ksInfo && ksInfo->dh_key_bits != 0 && keys->dhKey) {
     2223        DhKey dhKey;
     2224        const DhParams* params;
     2225        word32 privKeySz;
     2226        byte privKey[52]; /* max for TLS */
     2227       
     2228        keyBuf = keys->dhKey;
     2229
     2230        /* get DH params */
     2231        switch (ksInfo->named_group) {
     2232        #ifdef HAVE_FFDHE_2048
     2233            case WOLFSSL_FFDHE_2048:
     2234                params = wc_Dh_ffdhe2048_Get();
     2235                privKeySz = 29;
     2236                break;
     2237        #endif
     2238        #ifdef HAVE_FFDHE_3072
     2239            case WOLFSSL_FFDHE_3072:
     2240                params = wc_Dh_ffdhe3072_Get();
     2241                privKeySz = 34;
     2242                break;
     2243        #endif
     2244        #ifdef HAVE_FFDHE_4096
     2245            case WOLFSSL_FFDHE_4096:
     2246                params = wc_Dh_ffdhe4096_Get();
     2247                privKeySz = 39;
     2248                break;
     2249        #endif
     2250        #ifdef HAVE_FFDHE_6144
     2251            case WOLFSSL_FFDHE_6144:
     2252                params = wc_Dh_ffdhe6144_Get();
     2253                privKeySz = 46;
     2254                break;
     2255        #endif
     2256        #ifdef HAVE_FFDHE_8192
     2257            case WOLFSSL_FFDHE_8192:
     2258                params = wc_Dh_ffdhe8192_Get();
     2259                privKeySz = 52;
     2260                break;
     2261        #endif
     2262            default:
     2263                return BAD_FUNC_ARG;
     2264        }
     2265
     2266        ret = wc_InitDhKey(&dhKey);
     2267        if (ret == 0) {
     2268            ret = wc_DhSetKey(&dhKey,
     2269                (byte*)params->p, params->p_len,
     2270                (byte*)params->g, params->g_len);
     2271            if (ret == 0) {
     2272                ret = wc_DhKeyDecode(keyBuf->buffer, &idx, &dhKey,
     2273                    keyBuf->length);
     2274            }
     2275            if (ret == 0) {
     2276                ret = wc_DhExportKeyPair(&dhKey, privKey, &privKeySz, NULL,
     2277                    NULL);
     2278            }
     2279
     2280            /* Derive secret from private key and peer's public key */
     2281            do {
     2282            #ifdef WOLFSSL_ASYNC_CRYPT
     2283                ret = wc_AsyncWait(ret, &dhPriv.asyncDev,
     2284                        WC_ASYNC_FLAG_CALL_AGAIN);
     2285            #endif
     2286                if (ret >= 0) {
     2287                    ret = wc_DhAgree(&dhKey,
     2288                        session->sslServer->arrays->preMasterSecret,
     2289                        &session->sslServer->arrays->preMasterSz,
     2290                        privKey, privKeySz,
     2291                        input, *sslBytes);
     2292                }
     2293            } while (ret == WC_PENDING_E);
     2294
     2295            wc_FreeDhKey(&dhKey);
     2296       
     2297            /* left-padded with zeros up to the size of the prime */
     2298            if (params->p_len > session->sslServer->arrays->preMasterSz) {
     2299                word32 diff = params->p_len - session->sslServer->arrays->preMasterSz;
     2300                XMEMMOVE(session->sslServer->arrays->preMasterSecret + diff,
     2301                        session->sslServer->arrays->preMasterSecret,
     2302                        session->sslServer->arrays->preMasterSz);
     2303                XMEMSET(session->sslServer->arrays->preMasterSecret, 0, diff);
     2304                session->sslServer->arrays->preMasterSz = params->p_len;
     2305            }
     2306        }
     2307    }
     2308#endif /* !NO_DH && WOLFSSL_DH_EXTRA */
     2309
    19132310#ifdef HAVE_ECC
     2311    /* Static ECC Key */
     2312    if (useEccCurveId >= ECC_CURVE_DEF && keys->ecKey) {
    19142313        ecc_key key;
    19152314        ecc_key pubKey;
    19162315        int length, keyInit = 0, pubKeyInit = 0;
    19172316
     2317        keyBuf = keys->ecKey;
    19182318        idx = 0;
    19192319        ret = wc_ecc_init(&key);
     
    19222322            ret = wc_ecc_init(&pubKey);
    19232323        }
     2324
     2325    #if defined(ECC_TIMING_RESISTANT) && (!defined(HAVE_FIPS) || \
     2326        (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION != 2))) && \
     2327        !defined(HAVE_SELFTEST)
     2328        if (ret == 0) {
     2329            ret = wc_ecc_set_rng(&key, session->sslServer->rng);
     2330        }
     2331    #endif
     2332
    19242333        if (ret == 0) {
    19252334            pubKeyInit = 1;
    1926             ret = wc_EccPrivateKeyDecode(
    1927                     session->sslServer->buffers.key->buffer,
    1928                     &idx, &key, session->sslServer->buffers.key->length);
     2335            ret = wc_EccPrivateKeyDecode(keyBuf->buffer, &idx, &key, keyBuf->length);
    19292336            if (ret != 0) {
    19302337                SetError(ECC_DECODE_STR, error, session, FATAL_ERROR_STATE);
     
    19362343            /* The length should be 2 times the key size (x and y), plus 1
    19372344             * for the type byte. */
    1938             if (IsTLS(session->sslServer)) {
     2345            if (!IsAtLeastTLSv1_3(session->sslServer->version)) {
    19392346                input += 1; /* Don't include the TLS length for the key. */
    19402347            }
    19412348
    1942             if (length + 1 > *sslBytes) {
    1943                 SetError(PARTIAL_INPUT_STR,
    1944                         error, session, FATAL_ERROR_STATE);
     2349            if (length > *sslBytes) {
     2350                SetError(PARTIAL_INPUT_STR, error, session, FATAL_ERROR_STATE);
    19452351                ret = -1;
    19462352            }
     2353
     2354            /* if curve not provided in key share data, then use private key curve */
     2355            if (useEccCurveId == ECC_CURVE_DEF && key.dp) {
     2356                useEccCurveId = key.dp->id;
     2357            }
    19472358        }
    19482359
    19492360        if (ret == 0) {
    1950             ret = wc_ecc_import_x963_ex(input, length, &pubKey, ECC_CURVE_DEF);
     2361            ret = wc_ecc_import_x963_ex(input, length, &pubKey, useEccCurveId);
    19512362            if (ret != 0) {
    19522363                SetError(ECC_PUB_DECODE_STR, error, session, FATAL_ERROR_STATE);
     
    19832394        if (pubKeyInit)
    19842395            wc_ecc_free(&pubKey);
    1985 #endif
    1986     }
     2396    }
     2397#endif /* HAVE_ECC */
    19872398
    19882399    /* store for client side as well */
     
    19932404        session->sslServer->arrays->preMasterSz;
    19942405
    1995     #ifdef SHOW_SECRETS
    1996     {
    1997         word32 i;
    1998         printf("pre master secret: ");
    1999         for (i = 0; i < session->sslServer->arrays->preMasterSz; i++)
    2000             printf("%02x", session->sslServer->arrays->preMasterSecret[i]);
    2001         printf("\n");
    2002     }
    2003     #endif
     2406#ifdef SHOW_SECRETS
     2407    PrintSecret("pre master secret",
     2408                session->sslServer->arrays->preMasterSecret,
     2409                session->sslServer->arrays->preMasterSz);
     2410#endif
    20042411
    20052412    if (SetCipherSpecs(session->sslServer) != 0) {
     
    20132420    }
    20142421
    2015     ret  = MakeMasterSecret(session->sslServer);
    2016     ret += MakeMasterSecret(session->sslClient);
    2017     ret += SetKeysSide(session->sslServer, ENCRYPT_AND_DECRYPT_SIDE);
    2018     ret += SetKeysSide(session->sslClient, ENCRYPT_AND_DECRYPT_SIDE);
    2019 
     2422#ifdef WOLFSSL_TLS13
     2423    /* TLS v1.3 derive handshake key */
     2424    if (IsAtLeastTLSv1_3(session->sslServer->version)) {
     2425        ret  = DeriveEarlySecret(session->sslServer);
     2426        ret += DeriveEarlySecret(session->sslClient);
     2427        ret += DeriveHandshakeSecret(session->sslServer);
     2428        ret += DeriveHandshakeSecret(session->sslClient);
     2429        ret += DeriveTls13Keys(session->sslServer, handshake_key, ENCRYPT_AND_DECRYPT_SIDE, 1);
     2430        ret += DeriveTls13Keys(session->sslClient, handshake_key, ENCRYPT_AND_DECRYPT_SIDE, 1);
     2431    #ifdef WOLFSSL_EARLY_DATA
     2432        ret += SetKeysSide(session->sslServer, DECRYPT_SIDE_ONLY);
     2433        ret += SetKeysSide(session->sslClient, DECRYPT_SIDE_ONLY);
     2434    #else
     2435        ret += SetKeysSide(session->sslServer, ENCRYPT_AND_DECRYPT_SIDE);
     2436        ret += SetKeysSide(session->sslClient, ENCRYPT_AND_DECRYPT_SIDE);
     2437    #endif
     2438    }
     2439    else
     2440#endif
     2441    {
     2442        ret  = MakeMasterSecret(session->sslServer);
     2443        ret += MakeMasterSecret(session->sslClient);
     2444        ret += SetKeysSide(session->sslServer, ENCRYPT_AND_DECRYPT_SIDE);
     2445        ret += SetKeysSide(session->sslClient, ENCRYPT_AND_DECRYPT_SIDE);
     2446    }
    20202447    if (ret != 0) {
    20212448        SetError(BAD_DERIVE_STR, error, session, FATAL_ERROR_STATE);
     
    20242451
    20252452#ifdef SHOW_SECRETS
    2026     {
    2027         int i;
    2028         printf("server master secret: ");
    2029         for (i = 0; i < SECRET_LEN; i++)
    2030             printf("%02x", session->sslServer->arrays->masterSecret[i]);
    2031         printf("\n");
    2032 
    2033         printf("client master secret: ");
    2034         for (i = 0; i < SECRET_LEN; i++)
    2035             printf("%02x", session->sslClient->arrays->masterSecret[i]);
    2036         printf("\n");
    2037 
    2038         printf("server suite = %d\n", session->sslServer->options.cipherSuite);
    2039         printf("client suite = %d\n", session->sslClient->options.cipherSuite);
    2040     }
     2453    #ifdef WOLFSSL_TLS13
     2454    if (!IsAtLeastTLSv1_3(session->sslServer->version))
     2455    #endif
     2456        ShowTlsSecrets(session);
    20412457#endif
    20422458
     
    20462462}
    20472463
     2464/* Process Client Key Exchange, static RSA  */
     2465static int ProcessClientKeyExchange(const byte* input, int* sslBytes,
     2466                            SnifferSession* session, char* error)
     2467{
     2468    KeyBuffers_t keys;
     2469
     2470    if (session->sslServer->buffers.key == NULL ||
     2471        session->sslServer->buffers.key->buffer == NULL ||
     2472        session->sslServer->buffers.key->length == 0) {
     2473
     2474        SetError(RSA_KEY_MISSING_STR, error, session, FATAL_ERROR_STATE);
     2475        return -1;
     2476    }
     2477
     2478    XMEMSET(&keys, 0, sizeof(keys));
     2479#ifdef WOLFSSL_STATIC_EPHEMERAL
     2480    #ifndef NO_DH
     2481    keys.dhKey = session->sslServer->staticKE.dhKey;
     2482    #endif
     2483    #ifdef HAVE_ECC
     2484    keys.ecKey = session->sslServer->staticKE.ecKey;
     2485    #endif
     2486#endif
     2487    keys.rsaKey = session->sslServer->buffers.key;
     2488    return SetupKeys(input, sslBytes, session, error, NULL, &keys);
     2489}
     2490
     2491#ifdef WOLFSSL_TLS13
     2492static int ProcessKeyShare(KeyShareInfo* info, const byte* input, int len,
     2493    word16 filter_group)
     2494{
     2495    int index = 0;
     2496    while (index < len) {
     2497        /* clear info (reset dh_key_bits and curve_id) */
     2498        XMEMSET(info, 0, sizeof(KeyShareInfo));
     2499
     2500        /* Named group and public key */
     2501        info->named_group = (word16)((input[index] << 8) | input[index+1]);
     2502        index += OPAQUE16_LEN;
     2503        info->key_len = 0;
     2504        info->key = NULL;
     2505        /* If key was provided... (a hello_retry_request will not send a key) */
     2506        if (index + 2 <= len) {
     2507            info->key_len = (word16)((input[index] << 8) | input[index+1]);
     2508            index += OPAQUE16_LEN;
     2509            if (info->key_len == 0 || info->key_len > len - index) {
     2510                return -1;
     2511            }
     2512            info->key = &input[index];
     2513            index += info->key_len;
     2514        }
     2515
     2516        switch (info->named_group) {
     2517    #ifndef NO_DH
     2518        #ifdef HAVE_FFDHE_2048
     2519            case WOLFSSL_FFDHE_2048:
     2520                info->dh_key_bits = 2048;
     2521                break;
     2522        #endif
     2523        #ifdef HAVE_FFDHE_3072
     2524            case WOLFSSL_FFDHE_3072:
     2525                info->dh_key_bits = 3072;
     2526                break;
     2527        #endif
     2528        #ifdef HAVE_FFDHE_4096
     2529            case WOLFSSL_FFDHE_4096:
     2530                info->dh_key_bits = 4096;
     2531                break;
     2532        #endif
     2533        #ifdef HAVE_FFDHE_6144
     2534            case WOLFSSL_FFDHE_6144:
     2535                info->dh_key_bits = 6144;
     2536                break;
     2537        #endif
     2538        #ifdef HAVE_FFDHE_8192
     2539            case WOLFSSL_FFDHE_8192:
     2540                info->dh_key_bits = 8192;
     2541                break;
     2542        #endif
     2543    #endif /* !NO_DH */
     2544    #ifdef HAVE_ECC
     2545        #if !defined(NO_ECC256)  || defined(HAVE_ALL_CURVES)
     2546            #ifndef NO_ECC_SECP
     2547            case WOLFSSL_ECC_SECP256R1:
     2548                info->curve_id = ECC_SECP256R1;
     2549                break;
     2550            #endif /* !NO_ECC_SECP */
     2551        #endif
     2552        #if defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)
     2553            #ifndef NO_ECC_SECP
     2554            case WOLFSSL_ECC_SECP384R1:
     2555                info->curve_id = ECC_SECP384R1;
     2556                break;
     2557            #endif /* !NO_ECC_SECP */
     2558        #endif
     2559        #if defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)
     2560            #ifndef NO_ECC_SECP
     2561            case WOLFSSL_ECC_SECP521R1:
     2562                info->curve_id = ECC_SECP521R1;
     2563                break;
     2564            #endif /* !NO_ECC_SECP */
     2565        #endif
     2566    #endif /* HAVE_ECC */
     2567        #ifdef HAVE_CURVE25519
     2568            case WOLFSSL_ECC_X25519:
     2569                info->curve_id = ECC_X25519;
     2570                break;
     2571        #endif
     2572        #ifdef HAVE_X448
     2573            case WOLFSSL_ECC_X448:
     2574                info->curve_id = ECC_X448;
     2575                break;
     2576        #endif
     2577            default:
     2578                /* do not throw error here, keep iterating the client key share */
     2579                break;
     2580        }
     2581
     2582        if (filter_group == 0 || filter_group == info->named_group) {
     2583            return 0;
     2584        }
     2585    }
     2586    return NO_PEER_KEY; /* unsupported key type */
     2587}
     2588
     2589static int ProcessServerKeyShare(SnifferSession* session, const byte* input, int len,
     2590    char* error)
     2591{
     2592    int ret;
     2593
     2594    if (session->cliKeyShare == NULL || session->cliKeyShareSz == 0) {
     2595        /* session->cliKeyShareSz could not be provided yet if the client_hello
     2596            did not send a key share to force a hello_retry_request */
     2597        return 0;
     2598    }
     2599
     2600    /* Get server_hello key share (and key) */
     2601    ret = ProcessKeyShare(&session->srvKs, input, len, 0);
     2602    if (ret == 0 && session->srvKs.key_len > 0) {
     2603        /* Get client_hello key share */
     2604        ret = ProcessKeyShare(&session->cliKs, session->cliKeyShare,
     2605            session->cliKeyShareSz, session->srvKs.named_group);
     2606    }
     2607    if (ret != 0) {
     2608        SetError(SERVER_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
     2609        return -1;
     2610    }
     2611
     2612    return ret;
     2613}
     2614#endif /* WOLFSSL_TLS13 */
    20482615
    20492616/* Process Session Ticket */
     
    20532620    word16 len;
    20542621
    2055     /* make sure can read through hint and len */
    2056     if (TICKET_HINT_LEN + LENGTH_SZ > *sslBytes) {
     2622#ifdef WOLFSSL_TLS13
     2623    WOLFSSL* ssl;
     2624
     2625    if (session->flags.side == WOLFSSL_SERVER_END)
     2626        ssl = session->sslServer;
     2627    else
     2628        ssl = session->sslClient;
     2629#endif
     2630
     2631    /* make sure can read through hint len */
     2632    if (TICKET_HINT_LEN > *sslBytes) {
    20572633        SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE);
    20582634        return -1;
    20592635    }
    2060 
    2061     input     += TICKET_HINT_LEN;  /* skip over hint */
     2636    input     += TICKET_HINT_LEN; /* skip over hint len */
    20622637    *sslBytes -= TICKET_HINT_LEN;
    20632638
    2064     len = (word16)((input[0] << 8) | input[1]);
    2065     input     += LENGTH_SZ;
    2066     *sslBytes -= LENGTH_SZ;
    2067 
    2068     /* make sure can read through ticket */
    2069     if (len > *sslBytes || len < ID_LEN) {
     2639#ifdef WOLFSSL_TLS13
     2640    /* TLS v1.3 has hint age and nonce */
     2641    if (IsAtLeastTLSv1_3(ssl->version)) {
     2642        /* make sure can read through hint age and nonce len */
     2643        if (TICKET_HINT_AGE_LEN + 1 > *sslBytes) {
     2644            SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE);
     2645            return -1;
     2646        }
     2647        input     += TICKET_HINT_AGE_LEN; /* skip over hint age */
     2648        *sslBytes -= TICKET_HINT_AGE_LEN;
     2649
     2650        /* ticket nonce */
     2651        len = input[0];
     2652        if (len > MAX_TICKET_NONCE_SZ) {
     2653            SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE);
     2654            return -1;
     2655        }
     2656        input += OPAQUE8_LEN;
     2657        *sslBytes -= OPAQUE8_LEN;
     2658    #ifdef HAVE_SESSION_TICKET
     2659        /* store nonce in server for DeriveResumptionPSK */
     2660        session->sslServer->session.ticketNonce.len = len;
     2661        if (len > 0)
     2662            XMEMCPY(&session->sslServer->session.ticketNonce.data, input, len);
     2663    #endif
     2664        input += len;
     2665        *sslBytes -= len;
     2666    }
     2667#endif
     2668
     2669    /* make sure can read through len */
     2670    if (OPAQUE16_LEN > *sslBytes) {
    20702671        SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE);
    20712672        return -1;
    20722673    }
    20732674
    2074     /* store session with macID as sessionID */
    2075     session->sslServer->options.haveSessionId = 1;
    2076     XMEMCPY(session->sslServer->arrays->sessionID, input + len - ID_LEN,ID_LEN);
     2675    len = (word16)((input[0] << 8) | input[1]);
     2676    input     += OPAQUE16_LEN;
     2677    *sslBytes -= OPAQUE16_LEN;
     2678
     2679    /* make sure can read through ticket */
     2680    if (len > *sslBytes) {
     2681        SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE);
     2682        return -1;
     2683    }
     2684
     2685#ifdef WOLFSSL_TLS13
     2686    /* TLS v1.3 has hint age and nonce */
     2687    if (IsAtLeastTLSv1_3(ssl->version)) {
     2688    #ifdef HAVE_SESSION_TICKET
     2689        if (SetTicket(ssl, input, len) != 0) {
     2690            SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE);
     2691            return -1;
     2692        }
     2693        /* set haveSessionId to use the wolfSession cache */
     2694        ssl->options.haveSessionId = 1;
     2695
     2696        /* Use the wolf Session cache to retain resumption secret */
     2697        if (session->flags.cached == 0) {
     2698            WOLFSSL_SESSION* sess = GetSession(ssl, NULL, 0);
     2699            if (sess == NULL) {
     2700                AddSession(ssl); /* don't re add */
     2701            #ifdef WOLFSSL_SNIFFER_STATS
     2702                INC_STAT(SnifferStats.sslResumptionInserts);
     2703            #endif
     2704            }
     2705            session->flags.cached = 1;
     2706        }
     2707    #endif /* HAVE_SESSION_TICKET */
     2708    }
     2709    else
     2710#endif /* WOLFSSL_TLS13 */
     2711    {
     2712        /* capture last part of sessionID as macID (32 bytes) */
     2713        if (len < ID_LEN) {
     2714            SetError(BAD_INPUT_STR, error, session, FATAL_ERROR_STATE);
     2715            return -1;
     2716        }
     2717        /* store session with macID as sessionID */
     2718        session->sslServer->options.haveSessionId = 1;
     2719        XMEMCPY(session->sslServer->arrays->sessionID,
     2720            input + len - ID_LEN, ID_LEN);
     2721    }
    20772722
    20782723    return 0;
    20792724}
    20802725
     2726static int DoResume(SnifferSession* session, char* error)
     2727{
     2728    int ret = 0;
     2729    WOLFSSL_SESSION* resume;
     2730
     2731#ifdef WOLFSSL_TLS13
     2732    if (IsAtLeastTLSv1_3(session->sslServer->version)) {
     2733        resume = GetSession(session->sslServer,
     2734                            session->sslServer->session.masterSecret, 0);
     2735    }
     2736    else
     2737#endif
     2738    {
     2739        resume = GetSession(session->sslServer,
     2740                            session->sslServer->arrays->masterSecret, 0);
     2741    }
     2742    if (resume == NULL) {
     2743        /* a session id without resume is okay with hello_retry_request */
     2744    #ifdef WOLFSSL_SNIFFER_STATS
     2745        INC_STAT(SnifferStats.sslStandardConns);
     2746    #endif
     2747        return 0;
     2748    }
     2749
     2750    /* make sure client has master secret too */
     2751#ifdef WOLFSSL_TLS13
     2752    if (IsAtLeastTLSv1_3(session->sslServer->version)) {
     2753        XMEMCPY(session->sslClient->session.masterSecret,
     2754                session->sslServer->session.masterSecret, SECRET_LEN);
     2755    }
     2756    else
     2757#endif
     2758    {
     2759        XMEMCPY(session->sslClient->arrays->masterSecret,
     2760                session->sslServer->arrays->masterSecret, SECRET_LEN);
     2761    }
     2762    session->flags.resuming = 1;
     2763
     2764    Trace(SERVER_DID_RESUMPTION_STR);
     2765#ifdef WOLFSSL_SNIFFER_STATS
     2766    INC_STAT(SnifferStats.sslResumedConns);
     2767    INC_STAT(SnifferStats.sslResumptionValid);
     2768#endif
     2769    if (SetCipherSpecs(session->sslServer) != 0) {
     2770        SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE);
     2771        return -1;
     2772    }
     2773
     2774    if (SetCipherSpecs(session->sslClient) != 0) {
     2775        SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE);
     2776        return -1;
     2777    }
     2778
     2779#ifdef WOLFSSL_TLS13
     2780    if (IsAtLeastTLSv1_3(session->sslServer->version)) {
     2781    #ifdef HAVE_SESSION_TICKET
     2782        /* Resumption PSK is resumption master secret. */
     2783        session->sslServer->arrays->psk_keySz = session->sslServer->specs.hash_size;
     2784        session->sslClient->arrays->psk_keySz = session->sslClient->specs.hash_size;
     2785        ret  = DeriveResumptionPSK(session->sslServer, session->sslServer->session.ticketNonce.data,
     2786            session->sslServer->session.ticketNonce.len, session->sslServer->arrays->psk_key);
     2787        /* Copy resumption PSK to client */
     2788        XMEMCPY(session->sslClient->arrays->psk_key,
     2789            session->sslServer->arrays->psk_key,
     2790            session->sslServer->arrays->psk_keySz);
     2791    #endif
     2792        /* handshake key setup below and traffic keys done in SetupKeys */
     2793    }
     2794    else
     2795#endif
     2796    {
     2797        if (IsTLS(session->sslServer)) {
     2798            ret =  DeriveTlsKeys(session->sslServer);
     2799            ret += DeriveTlsKeys(session->sslClient);
     2800        }
     2801        else {
     2802#ifndef NO_OLD_TLS
     2803            ret =  DeriveKeys(session->sslServer);
     2804            ret += DeriveKeys(session->sslClient);
     2805#endif
     2806        }
     2807        ret += SetKeysSide(session->sslServer, ENCRYPT_AND_DECRYPT_SIDE);
     2808        ret += SetKeysSide(session->sslClient, ENCRYPT_AND_DECRYPT_SIDE);
     2809    }
     2810
     2811    if (ret != 0) {
     2812        SetError(BAD_DERIVE_STR, error, session, FATAL_ERROR_STATE);
     2813        return -1;
     2814    }
     2815
     2816    return ret;
     2817}
    20812818
    20822819/* Process Server Hello */
     
    20842821                              SnifferSession* session, char* error)
    20852822{
     2823    int             ret = 0;
    20862824    ProtocolVersion pv;
    20872825    byte            b, b0;
    20882826    int             toRead = VERSION_SZ + RAN_LEN + ENUM_LEN;
    2089     int             doResume     = 0;
     2827    int             doResume = 0;
     2828    const byte*     inputHello = input;
    20902829    int             initialBytes = *sslBytes;
    20912830
    20922831    (void)msgSz;
    2093     (void)initialBytes;
    20942832
    20952833    /* make sure we didn't miss ClientHello */
    2096     if (session->flags.clientHello == 0) {
    2097         SetError(MISSED_CLIENT_HELLO_STR, error, session, FATAL_ERROR_STATE);
    2098         return -1;
     2834    if (session->flags.clientHello == 0 || session->sslClient->arrays == NULL) {
     2835        SetError(MISSED_CLIENT_HELLO_STR, error, session, 0);
     2836        return 0; /* do not throw error, just ignore packet */
    20992837    }
    21002838
     
    21112849    session->sslServer->version = pv;
    21122850    session->sslClient->version = pv;
     2851    if (pv.minor >= TLSv1_MINOR) {
     2852        session->sslServer->options.tls = 1;
     2853        session->sslClient->options.tls = 1;
     2854    }
    21132855
    21142856    XMEMCPY(session->sslServer->arrays->serverRandom, input, RAN_LEN);
    21152857    XMEMCPY(session->sslClient->arrays->serverRandom, input, RAN_LEN);
    2116     input    += RAN_LEN;
     2858    input     += RAN_LEN;
    21172859    *sslBytes -= RAN_LEN;
    21182860
     
    21262868    }
    21272869    if (b) {
     2870    #ifdef WOLFSSL_TLS13
     2871        XMEMCPY(session->sslServer->session.sessionID, input, ID_LEN);
     2872    #endif
    21282873        XMEMCPY(session->sslServer->arrays->sessionID, input, ID_LEN);
    21292874        session->sslServer->options.haveSessionId = 1;
     
    21692914    }
    21702915
    2171 #ifdef HAVE_EXTENDED_MASTER
    21722916    /* extensions */
    21732917    if ((initialBytes - *sslBytes) < msgSz) {
     
    21902934
    21912935        while (len >= EXT_TYPE_SZ + LENGTH_SZ) {
    2192             byte   extType[EXT_TYPE_SZ];
     2936            word16 extType;
    21932937            word16 extLen;
    21942938
    2195             extType[0] = input[0];
    2196             extType[1] = input[1];
     2939            extType    = (word16)((input[0] << 8) | input[1]);
    21972940            input     += EXT_TYPE_SZ;
    21982941            *sslBytes -= EXT_TYPE_SZ;
    21992942
    2200             extLen = (word16)((input[0] << 8) | input[1]);
     2943            extLen     = (word16)((input[0] << 8) | input[1]);
    22012944            input     += LENGTH_SZ;
    22022945            *sslBytes -= LENGTH_SZ;
     
    22092952            }
    22102953
    2211             if (extType[0] == 0x00 && extType[1] == EXT_MASTER_SECRET) {
     2954            switch (extType) {
     2955        #ifdef WOLFSSL_TLS13
     2956            case EXT_KEY_SHARE:
     2957                ret = ProcessServerKeyShare(session, input, extLen, error);
     2958                if (ret != 0) {
     2959                    SetError(SERVER_HELLO_INPUT_STR, error, session,
     2960                        FATAL_ERROR_STATE);
     2961                    return -1;
     2962                }
     2963                break;
     2964        #endif
     2965        #ifdef HAVE_SESSION_TICKET
     2966            case EXT_PRE_SHARED_KEY:
     2967                /* indicates we want to use resumption */
     2968                session->sslServer->options.resuming = 1;
     2969                session->sslClient->options.resuming = 1;
     2970            #ifdef WOLFSSL_TLS13
     2971                /* default nonce to len = 1, data = 0 */
     2972                session->sslServer->session.ticketNonce.len = 1;
     2973                session->sslServer->session.ticketNonce.data[0] = 0;
     2974                session->sslClient->session.ticketNonce.len = 1;
     2975                session->sslClient->session.ticketNonce.data[0] = 0;
     2976            #endif
     2977                break;
     2978        #endif
     2979        #ifdef HAVE_MAX_FRAGMENT
     2980            case EXT_MAX_FRAGMENT_LENGTH:
     2981            {
     2982                word16 max_fragment = MAX_RECORD_SIZE;
     2983                switch (input[0]) {
     2984                    case WOLFSSL_MFL_2_8 : max_fragment =  256; break;
     2985                    case WOLFSSL_MFL_2_9 : max_fragment =  512; break;
     2986                    case WOLFSSL_MFL_2_10: max_fragment = 1024; break;
     2987                    case WOLFSSL_MFL_2_11: max_fragment = 2048; break;
     2988                    case WOLFSSL_MFL_2_12: max_fragment = 4096; break;
     2989                    case WOLFSSL_MFL_2_13: max_fragment = 8192; break;
     2990                    default: break;
     2991                }
     2992                session->sslServer->max_fragment = max_fragment;
     2993                session->sslClient->max_fragment = max_fragment;
     2994                break;
     2995            }
     2996        #endif
     2997            case EXT_SUPPORTED_VERSIONS:
     2998                session->sslServer->version.major = input[0];
     2999                session->sslServer->version.minor = input[1];
     3000                session->sslClient->version.major = input[0];
     3001                session->sslClient->version.minor = input[1];
     3002                if (IsAtLeastTLSv1_3(session->sslServer->version)) {
     3003                    /* The server side handshake encryption is on for future packets */
     3004                    session->flags.serverCipherOn = 1;
     3005                }
     3006                break;
     3007            case EXT_MASTER_SECRET:
     3008            #ifdef HAVE_EXTENDED_MASTER
    22123009                session->flags.expectEms = 1;
     3010            #endif
     3011                break;
    22133012            }
    22143013
     
    22193018    }
    22203019
     3020#ifdef HAVE_EXTENDED_MASTER
    22213021    if (!session->flags.expectEms) {
    22223022        XFREE(session->hash, NULL, DYNAMIC_TYPE_HASHES);
     
    22273027    if (session->sslServer->options.haveSessionId) {
    22283028        if (XMEMCMP(session->sslServer->arrays->sessionID,
    2229                     session->sslClient->arrays->sessionID, ID_LEN) == 0)
     3029                session->sslClient->arrays->sessionID, ID_LEN) == 0) {
    22303030            doResume = 1;
    2231     }
     3031        }   
     3032    }       
    22323033    else if (session->sslClient->options.haveSessionId == 0 &&
    22333034             session->sslServer->options.haveSessionId == 0 &&
    2234              session->ticketID)
     3035             session->ticketID) {
    22353036        doResume = 1;
     3037    }
    22363038
    22373039    if (session->ticketID && doResume) {
     
    22423044    }
    22433045
    2244     if (doResume ) {
    2245         int ret = 0;
    2246         SSL_SESSION* resume = GetSession(session->sslServer,
    2247                                   session->sslServer->arrays->masterSecret, 0);
    2248         if (resume == NULL) {
    2249 #ifdef WOLFSSL_SNIFFER_STATS
    2250             INC_STAT(SnifferStats.sslResumeMisses);
    2251 #endif
    2252             SetError(BAD_SESSION_RESUME_STR, error, session, FATAL_ERROR_STATE);
    2253             return -1;
    2254         }
    2255         /* make sure client has master secret too */
    2256         XMEMCPY(session->sslClient->arrays->masterSecret,
    2257                session->sslServer->arrays->masterSecret, SECRET_LEN);
    2258         session->flags.resuming = 1;
    2259 
    2260         Trace(SERVER_DID_RESUMPTION_STR);
    2261 #ifdef WOLFSSL_SNIFFER_STATS
    2262         INC_STAT(SnifferStats.sslResumedConns);
    2263         INC_STAT(SnifferStats.sslResumptionValid);
    2264 #endif
    2265         if (SetCipherSpecs(session->sslServer) != 0) {
    2266             SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE);
    2267             return -1;
    2268         }
    2269 
    2270         if (SetCipherSpecs(session->sslClient) != 0) {
    2271             SetError(BAD_CIPHER_SPEC_STR, error, session, FATAL_ERROR_STATE);
    2272             return -1;
    2273         }
    2274 
    2275         if (session->sslServer->options.tls) {
    2276             ret =  DeriveTlsKeys(session->sslServer);
    2277             ret += DeriveTlsKeys(session->sslClient);
    2278         }
    2279         else {
    2280             ret =  DeriveKeys(session->sslServer);
    2281             ret += DeriveKeys(session->sslClient);
    2282         }
    2283         ret += SetKeysSide(session->sslServer, ENCRYPT_AND_DECRYPT_SIDE);
    2284         ret += SetKeysSide(session->sslClient, ENCRYPT_AND_DECRYPT_SIDE);
    2285 
     3046#ifdef WOLFSSL_TLS13
     3047    /* Is TLS v1.3 hello_retry_request? */
     3048    if (IsAtLeastTLSv1_3(session->sslServer->version) && session->srvKs.key_len == 0) {
     3049        Trace(GOT_HELLO_RETRY_REQ_STR);
     3050
     3051        /* do not compute keys yet */
     3052        session->flags.serverCipherOn = 0;
     3053
     3054        /* make sure the mac and digest size are set */
     3055        SetCipherSpecs(session->sslServer);
     3056        SetCipherSpecs(session->sslClient);
     3057
     3058        /* reset hashes */
     3059        RestartHandshakeHash(session->sslServer);
     3060        RestartHandshakeHash(session->sslClient);
     3061
     3062        doResume = 0;
     3063    }
     3064#endif
     3065
     3066    /* hash server_hello */
     3067    HashRaw(session->sslServer, inputHello - HANDSHAKE_HEADER_SZ,
     3068        initialBytes + HANDSHAKE_HEADER_SZ);
     3069    HashRaw(session->sslClient, inputHello - HANDSHAKE_HEADER_SZ,
     3070        initialBytes + HANDSHAKE_HEADER_SZ);
     3071
     3072    if (doResume) {
     3073        ret = DoResume(session, error);
    22863074        if (ret != 0) {
    2287             SetError(BAD_DERIVE_STR, error, session, FATAL_ERROR_STATE);
    2288             return -1;
     3075            return ret;
    22893076        }
    22903077    }
     
    22943081#endif
    22953082    }
     3083
    22963084#ifdef SHOW_SECRETS
    2297     {
    2298         int i;
    2299         printf("cipher suite = 0x%02x\n",
    2300                session->sslServer->options.cipherSuite);
    2301         printf("server random: ");
    2302         for (i = 0; i < RAN_LEN; i++)
    2303             printf("%02x", session->sslServer->arrays->serverRandom[i]);
    2304         printf("\n");
    2305     }
    2306 #endif
     3085    printf("cipher suite = 0x%02x\n", session->sslServer->options.cipherSuite);
     3086    PrintSecret("server random", session->sslServer->arrays->serverRandom, RAN_LEN);
     3087#endif
     3088
     3089#ifdef WOLFSSL_TLS13
     3090    /* Setup handshake keys */
     3091    if (IsAtLeastTLSv1_3(session->sslServer->version) && session->srvKs.key_len > 0) {
     3092        KeyBuffers_t keys;
     3093        XMEMSET(&keys, 0, sizeof(keys));
     3094        keys.rsaKey = session->sslServer->buffers.key;
     3095    #ifdef WOLFSSL_STATIC_EPHEMERAL
     3096        #ifndef NO_DH
     3097        keys.dhKey = session->sslServer->staticKE.dhKey;
     3098        #endif
     3099        #ifdef HAVE_ECC
     3100        keys.ecKey = session->sslServer->staticKE.ecKey;
     3101        #endif
     3102    #endif
     3103        ret = SetupKeys(session->cliKs.key, &session->cliKs.key_len,
     3104            session, error, &session->cliKs, &keys);
     3105        if (ret != 0) {
     3106            SetError(SERVER_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
     3107            return ret;
     3108        }
     3109
     3110        if (session->flags.side == WOLFSSL_SERVER_END)
     3111            session->flags.serverCipherOn = 1;
     3112        else
     3113            session->flags.clientCipherOn = 1;
     3114    }
     3115#endif
     3116
    23073117    return 0;
    23083118}
     
    23133123                              SnifferSession* session, char* error)
    23143124{
     3125    int ret = 0;
    23153126    byte   bLen;
    23163127    word16 len;
    23173128    int    toRead = VERSION_SZ + RAN_LEN + ENUM_LEN;
     3129    const byte* inputHello = input;
     3130    int inputHelloSz = *sslBytes;
     3131    WOLFSSL* ssl = session->sslServer;
     3132    int didHash = 0;
    23183133
    23193134#ifdef HAVE_SNI
     
    23213136        byte name[MAX_SERVER_NAME];
    23223137        word32 nameSz = sizeof(name);
    2323         int ret;
    23243138
    23253139        ret = wolfSSL_SNI_GetFromBuffer(
     
    23393153                if (nameSz == namedKey->nameSz &&
    23403154                           XSTRNCMP((char*)name, namedKey->name, nameSz) == 0) {
    2341                     if (wolfSSL_use_PrivateKey_buffer(session->sslServer,
    2342                                             namedKey->key, namedKey->keySz,
    2343                                             WOLFSSL_FILETYPE_ASN1) != WOLFSSL_SUCCESS) {
     3155                #ifdef WOLFSSL_STATIC_EPHEMERAL
     3156                    if (namedKey->isEphemeralKey) {
     3157                        /* auto detect key type with WC_PK_TYPE_NONE */
     3158                        ret = wolfSSL_set_ephemeral_key(ssl,
     3159                            WC_PK_TYPE_NONE, (const char*)namedKey->key,
     3160                            namedKey->keySz, WOLFSSL_FILETYPE_ASN1);
     3161                        if (ret == 0)
     3162                            ret = WOLFSSL_SUCCESS;
     3163                    }
     3164                    else
     3165                #endif
     3166                    {
     3167                        ret = wolfSSL_use_PrivateKey_buffer(ssl,
     3168                            namedKey->key, namedKey->keySz,
     3169                            WOLFSSL_FILETYPE_ASN1);
     3170                    }
     3171                    if (ret != WOLFSSL_SUCCESS) {
    23443172                        wc_UnLockMutex(&session->context->namedKeysMutex);
    23453173                        SetError(CLIENT_HELLO_LATE_KEY_STR, error, session,
     
    23553183            wc_UnLockMutex(&session->context->namedKeysMutex);
    23563184        }
     3185        /* SSLv3 does not support the SNI TLS Extension and may return SNI_UNSUPPORTED */
     3186        if (ret > 0 || ret == SNI_UNSUPPORTED) {
     3187            /* make sure WOLFSSL_SUCCESS is converted to zero error code */
     3188            ret = 0;
     3189        }
    23573190    }
    23583191#endif
     
    23853218        }
    23863219        Trace(CLIENT_RESUME_TRY_STR);
     3220#ifdef WOLFSSL_TLS13
     3221        XMEMCPY(session->sslClient->session.sessionID, input, ID_LEN);
     3222#endif
    23873223        XMEMCPY(session->sslClient->arrays->sessionID, input, ID_LEN);
    23883224        session->sslClient->options.haveSessionId = 1;
    23893225    }
     3226
    23903227#ifdef SHOW_SECRETS
    2391     {
    2392         int i;
    2393         printf("client random: ");
    2394         for (i = 0; i < RAN_LEN; i++)
    2395             printf("%02x", session->sslServer->arrays->clientRandom[i]);
    2396         printf("\n");
    2397     }
     3228    PrintSecret("client random", ssl->arrays->clientRandom, RAN_LEN);
    23983229#endif
    23993230
     
    24503281
    24513282    while (len >= EXT_TYPE_SZ + LENGTH_SZ) {
    2452         byte   extType[EXT_TYPE_SZ];
     3283        word16 extType;
    24533284        word16 extLen;
    24543285
    2455         extType[0] = input[0];
    2456         extType[1] = input[1];
     3286        extType    = (word16)((input[0] << 8) | input[1]);
    24573287        input     += EXT_TYPE_SZ;
    24583288        *sslBytes -= EXT_TYPE_SZ;
    24593289
    2460         extLen = (word16)((input[0] << 8) | input[1]);
     3290        extLen     = (word16)((input[0] << 8) | input[1]);
    24613291        input     += LENGTH_SZ;
    24623292        *sslBytes -= LENGTH_SZ;
     
    24683298        }
    24693299
    2470         if (extType[0] == 0x00 && extType[1] == TICKET_EXT_ID) {
    2471 
     3300        switch (extType) {
     3301    #ifdef WOLFSSL_TLS13
     3302        case EXT_KEY_SHARE:
     3303        {
     3304            word16 ksLen = (word16)((input[0] << 8) | input[1]);
     3305            if (ksLen + OPAQUE16_LEN > extLen) {
     3306                SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
     3307                return -1;
     3308            }
     3309            /* cache key share data till server_hello */
     3310            session->cliKeyShareSz = ksLen;
     3311            session->cliKeyShare = (byte*)XMALLOC(ksLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     3312            if (session->cliKeyShare == NULL) {
     3313                SetError(MEMORY_STR, error, session, FATAL_ERROR_STATE);
     3314                break;
     3315            }
     3316            XMEMCPY(session->cliKeyShare, &input[2], ksLen);
     3317            break;
     3318        }
     3319        #ifdef HAVE_SESSION_TICKET
     3320        case EXT_PRE_SHARED_KEY:
     3321        {
     3322            word16 idsLen, idLen, bindersLen, idx = 0;
     3323            word32 ticketAge;
     3324            const byte *identity, *binders;
     3325
     3326            idsLen = (word16)((input[idx] << 8) | input[idx+1]);
     3327            if (idsLen + OPAQUE16_LEN + idx > extLen) {
     3328                SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
     3329                return -1;
     3330            }
     3331            idx += OPAQUE16_LEN;
     3332
     3333            /* PSK identity */
     3334            idLen = (word16)((input[idx] << 8) | input[idx+1]);
     3335            if (idLen + OPAQUE16_LEN + idx > extLen) {
     3336                SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
     3337                return -1;
     3338            }
     3339            idx += OPAQUE16_LEN;
     3340            identity = &input[idx];
     3341            idx += idLen;
     3342
     3343            /* Obfuscated Ticket Age 32-bits */
     3344            ticketAge = (word32)((input[idx] << 24) | (input[idx+1] << 16) |
     3345                                 (input[idx+2] << 8) | input[idx+3]);
     3346            (void)ticketAge; /* not used */
     3347            idx += OPAQUE32_LEN;
     3348
     3349            /* binders - all binders */
     3350            bindersLen = (word16)((input[idx] << 8) | input[idx+1]);
     3351            if (bindersLen + OPAQUE16_LEN + idx > extLen) {
     3352                SetError(CLIENT_HELLO_INPUT_STR, error, session, FATAL_ERROR_STATE);
     3353                return -1;
     3354            }
     3355            idx += OPAQUE16_LEN;
     3356            binders = &input[idx];
     3357            bindersLen += OPAQUE16_LEN; /* includes 2 bytes for total len */
     3358            (void)binders; /* not used */
     3359
     3360            /* Hash data up to binders for deriving binders in PSK extension. */
     3361            HashRaw(session->sslServer, inputHello - HANDSHAKE_HEADER_SZ,
     3362                inputHelloSz - bindersLen + HANDSHAKE_HEADER_SZ);
     3363            HashRaw(session->sslClient, inputHello - HANDSHAKE_HEADER_SZ,
     3364                inputHelloSz - bindersLen + HANDSHAKE_HEADER_SZ);
     3365
     3366            /* call to decrypt session ticket */
     3367            if (DoClientTicket(ssl, identity, idLen) != 0) {
     3368                /* we aren't decrypting the resumption, since we know the master secret */
     3369                /* ignore errors */
     3370            }
     3371            ssl->options.resuming  = 1;
     3372
     3373            /* Hash the rest of the ClientHello. */
     3374            HashRaw(session->sslServer, inputHello + inputHelloSz - bindersLen, bindersLen);
     3375            HashRaw(session->sslClient, inputHello + inputHelloSz - bindersLen, bindersLen);
     3376            didHash = 1;
     3377            break;
     3378        }
     3379        #endif /* HAVE_SESSION_TICKET */
     3380    #endif /* WOLFSSL_TLS13 */
     3381        case EXT_SUPPORTED_VERSIONS:
     3382            break;
     3383        case EXT_TICKET_ID:
    24723384            /* make sure can read through ticket if there is a non blank one */
    24733385            if (extLen && extLen < ID_LEN) {
     
    24763388                return -1;
    24773389            }
    2478 
    24793390            if (extLen) {
    2480                 if (session->ticketID == 0) {
     3391                if (session->ticketID == NULL) {
    24813392                    session->ticketID = (byte*)XMALLOC(ID_LEN,
    24823393                            NULL, DYNAMIC_TYPE_SNIFFER_TICKET_ID);
     
    24893400                XMEMCPY(session->ticketID, input + extLen - ID_LEN, ID_LEN);
    24903401            }
     3402            break;
    24913403        }
    24923404
     
    24963408    }
    24973409
    2498     return 0;
     3410    if (!didHash) {
     3411        HashRaw(session->sslServer, inputHello - HANDSHAKE_HEADER_SZ,
     3412            inputHelloSz + HANDSHAKE_HEADER_SZ);
     3413        HashRaw(session->sslClient, inputHello - HANDSHAKE_HEADER_SZ,
     3414            inputHelloSz + HANDSHAKE_HEADER_SZ);
     3415    }
     3416
     3417    (void)ssl;
     3418
     3419    return ret;
    24993420}
    25003421
    25013422
    25023423#ifdef WOLFSSL_SNIFFER_WATCH
     3424
     3425static int KeyWatchCall(SnifferSession* session, const byte* data, int dataSz,
     3426    char* error)
     3427{
     3428    int ret;
     3429    Sha256 sha;
     3430    byte digest[SHA256_DIGEST_SIZE];
     3431
     3432    if (WatchCb == NULL) {
     3433        SetError(WATCH_CB_MISSING_STR, error, session, FATAL_ERROR_STATE);
     3434        return -1;
     3435    }
     3436
     3437    ret = wc_InitSha256(&sha);
     3438    if (ret == 0)
     3439        ret = wc_Sha256Update(&sha, data, dataSz);
     3440    if (ret == 0)
     3441        ret = wc_Sha256Final(&sha, digest);
     3442    if (ret != 0) {
     3443        SetError(WATCH_HASH_STR, error, session, FATAL_ERROR_STATE);
     3444        return -1;
     3445    }
     3446
     3447    ret = WatchCb((void*)session, digest, sizeof(digest),
     3448            data, dataSz, WatchCbCtx, error);
     3449    if (ret != 0) {
     3450#ifdef WOLFSSL_SNIFFER_STATS
     3451        INC_STAT(SnifferStats.sslKeysUnmatched);
     3452#endif
     3453        SetError(WATCH_FAIL_STR, error, session, FATAL_ERROR_STATE);
     3454        ret = -1;
     3455    }
     3456    else {
     3457#ifdef WOLFSSL_SNIFFER_STATS
     3458        INC_STAT(SnifferStats.sslKeyMatches);
     3459#endif
     3460    }
     3461    return ret;
     3462}
    25033463
    25043464/* Process Certificate */
     
    25063466        SnifferSession* session, char* error)
    25073467{
    2508     Sha256 sha;
    2509     const byte* certChain;
    25103468    word32 certChainSz;
    25113469    word32 certSz;
    2512     int ret;
    2513     byte digest[SHA256_DIGEST_SIZE];
    25143470
    25153471    /* If the receiver is the server, this is the client certificate message,
     
    25183474        return 0;
    25193475
    2520     if (WatchCb == NULL) {
    2521         SetError(WATCH_CB_MISSING_STR, error, session, FATAL_ERROR_STATE);
    2522         return -1;
    2523     }
    2524 
    25253476    if (*sslBytes < CERT_HEADER_SZ) {
    25263477        SetError(BAD_CERT_MSG_STR, error, session, FATAL_ERROR_STATE);
    25273478        return -1;
    25283479    }
     3480
     3481#ifdef WOLFSSL_TLS13
     3482    if (IsAtLeastTLSv1_3(session->sslServer->version)) {
     3483        /* skip 1 byte (Request context len) */
     3484        input += OPAQUE8_LEN;
     3485        *sslBytes -= OPAQUE8_LEN;
     3486    }
     3487#endif
     3488
    25293489    ato24(input, &certChainSz);
    25303490    *sslBytes -= CERT_HEADER_SZ;
     
    25353495        return -1;
    25363496    }
    2537     certChain = input;
    25383497
    25393498    ato24(input, &certSz);
     
    25463505    *sslBytes -= certChainSz;
    25473506
    2548     ret = wc_InitSha256(&sha);
    2549     if (ret == 0)
    2550         ret = wc_Sha256Update(&sha, input, certSz);
    2551     if (ret == 0)
    2552         ret = wc_Sha256Final(&sha, digest);
    2553     if (ret != 0) {
    2554         SetError(WATCH_HASH_STR, error, session, FATAL_ERROR_STATE);
    2555         return -1;
    2556     }
    2557 
    2558     ret = WatchCb((void*)session, digest, sizeof(digest),
    2559             certChain, certChainSz, WatchCbCtx, error);
    2560     if (ret != 0) {
    2561 #ifdef WOLFSSL_SNIFFER_STATS
    2562         INC_STAT(SnifferStats.sslKeysUnmatched);
    2563 #endif
    2564         SetError(WATCH_FAIL_STR, error, session, FATAL_ERROR_STATE);
    2565         return -1;
    2566     }
    2567     else {
    2568 #ifdef WOLFSSL_SNIFFER_STATS
    2569         INC_STAT(SnifferStats.sslKeyMatches);
    2570 #endif
    2571     }
    2572 
    2573     return 0;
     3507    return KeyWatchCall(session, input, certSz, error);
    25743508}
    25753509
     
    25813515                           SnifferSession* session, char* error)
    25823516{
    2583     SSL*  ssl;
     3517    WOLFSSL* ssl;
    25843518    word32 inOutIdx = 0;
    25853519    int    ret;
     
    25903524        ssl = session->sslClient;
    25913525
    2592     ret = DoFinished(ssl, input, &inOutIdx, (word32) size, (word32) *sslBytes,
    2593                                                                          SNIFF);
     3526#ifdef WOLFSSL_TLS13
     3527    if (IsAtLeastTLSv1_3(ssl->version)) {
     3528        ret = DoTls13Finished(ssl, input, &inOutIdx, (word32)size,
     3529            (word32)*sslBytes, SNIFF);
     3530
     3531        ssl->options.handShakeState = HANDSHAKE_DONE;
     3532        ssl->options.handShakeDone  = 1;
     3533    }
     3534    else
     3535#endif
     3536    {
     3537        ret = DoFinished(ssl, input, &inOutIdx, (word32)size,
     3538            (word32)*sslBytes, SNIFF);
     3539    }
    25943540    *sslBytes -= (int)inOutIdx;
    25953541
     
    26123558    }
    26133559
     3560#ifdef WOLFSSL_TLS13
     3561    /* Derive TLS v1.3 traffic keys */
     3562    if (IsAtLeastTLSv1_3(ssl->version)) {
     3563        if (!session->flags.gotFinished) {
     3564            /* When either side gets "finished" derive master secret and keys */
     3565            ret  = DeriveMasterSecret(session->sslServer);
     3566            ret += DeriveMasterSecret(session->sslClient);
     3567        #ifdef WOLFSSL_EARLY_DATA
     3568            ret += DeriveTls13Keys(session->sslServer, traffic_key, ENCRYPT_AND_DECRYPT_SIDE, ssl->earlyData == no_early_data);
     3569            ret += DeriveTls13Keys(session->sslClient, traffic_key, ENCRYPT_AND_DECRYPT_SIDE, ssl->earlyData == no_early_data);
     3570        #else
     3571            ret += DeriveTls13Keys(session->sslServer, traffic_key, ENCRYPT_AND_DECRYPT_SIDE, 1);
     3572            ret += DeriveTls13Keys(session->sslClient, traffic_key, ENCRYPT_AND_DECRYPT_SIDE, 1);
     3573        #endif
     3574
     3575            if (ret != 0) {
     3576                SetError(BAD_FINISHED_MSG, error, session, FATAL_ERROR_STATE);
     3577                return -1;
     3578            }
     3579
     3580            session->flags.gotFinished = 1;
     3581        #ifdef SHOW_SECRETS
     3582            ShowTlsSecrets(session);   
     3583        #endif
     3584        }
     3585
     3586        if (session->flags.side == WOLFSSL_SERVER_END) {
     3587            /* finished from client to server */
     3588            ret  = SetKeysSide(session->sslServer, DECRYPT_SIDE_ONLY);
     3589            ret += SetKeysSide(session->sslClient, ENCRYPT_SIDE_ONLY);
     3590
     3591        #ifdef HAVE_SESSION_TICKET
     3592            /* derive resumption secret for next session - on finished (from client) */
     3593            ret += DeriveResumptionSecret(session->sslClient, session->sslClient->session.masterSecret);
     3594
     3595            /* copy resumption secret to server */
     3596            XMEMCPY(session->sslServer->session.masterSecret,
     3597                session->sslClient->session.masterSecret, SECRET_LEN);
     3598            #ifdef SHOW_SECRETS
     3599            PrintSecret("resumption secret", session->sslClient->session.masterSecret, SECRET_LEN);
     3600            #endif
     3601        #endif
     3602        }
     3603        else {
     3604            /* finished from server to client */
     3605            ret  = SetKeysSide(session->sslServer, ENCRYPT_SIDE_ONLY);
     3606            ret += SetKeysSide(session->sslClient, DECRYPT_SIDE_ONLY);
     3607        }
     3608
     3609        if (ret != 0) {
     3610            SetError(BAD_FINISHED_MSG, error, session, FATAL_ERROR_STATE);
     3611            return -1;
     3612        }
     3613    }
     3614#endif
     3615
    26143616    /* If receiving a finished message from one side, free the resources
    26153617     * from the other side's tracker. */
     
    26253627/* Process HandShake input */
    26263628static int DoHandShake(const byte* input, int* sslBytes,
    2627                        SnifferSession* session, char* error)
     3629                       SnifferSession* session, char* error, word16 rhSize)
    26283630{
    26293631    byte type;
    26303632    int  size;
    26313633    int  ret = 0;
    2632     int  startBytes;
     3634    WOLFSSL* ssl;
     3635    int startBytes;
     3636
     3637    (void)rhSize;
     3638
     3639#ifdef HAVE_MAX_FRAGMENT
     3640    if (session->tlsFragBuf) {
     3641        XMEMCPY(session->tlsFragBuf + session->tlsFragOffset, input, rhSize);
     3642        session->tlsFragOffset += rhSize;
     3643        *sslBytes -= rhSize;
     3644
     3645        if (session->tlsFragOffset < session->tlsFragSize) {
     3646            return 0;
     3647        }
     3648
     3649        /* reassembled complete fragment */
     3650        input = session->tlsFragBuf;
     3651        *sslBytes = session->tlsFragSize;
     3652        rhSize = session->tlsFragSize;
     3653    }
     3654#endif
    26333655
    26343656    if (*sslBytes < HANDSHAKE_HEADER_SZ) {
     
    26493671    }
    26503672
    2651     /* A session's arrays are released when the handshake is completed. */
    2652     if (session->sslServer->arrays == NULL &&
    2653         session->sslClient->arrays == NULL) {
    2654 
    2655         SetError(NO_SECURE_RENEGOTIATION, error, session, FATAL_ERROR_STATE);
    2656         return -1;
    2657     }
    2658 
     3673    if (session->flags.side == WOLFSSL_SERVER_END)
     3674        ssl = session->sslServer;
     3675    else
     3676        ssl = session->sslClient;
     3677
     3678#ifdef HAVE_SECURE_RENEGOTIATION
     3679    if (!IsAtLeastTLSv1_3(ssl->version)) {
     3680        /* A session's arrays are released when the handshake is completed. */
     3681        if (session->sslServer->arrays == NULL &&
     3682            session->sslClient->arrays == NULL) {
     3683
     3684            SetError(NO_SECURE_RENEGOTIATION, error, session, FATAL_ERROR_STATE);
     3685            return -1;
     3686        }
     3687    }
     3688#endif
     3689
     3690#ifdef HAVE_MAX_FRAGMENT
     3691    if (rhSize < size) {
     3692        /* partial fragment, let's reassemble */
     3693        if (session->tlsFragBuf == NULL) {
     3694            session->tlsFragOffset = 0;
     3695            session->tlsFragSize = size + HANDSHAKE_HEADER_SZ;
     3696            session->tlsFragBuf = (byte*)XMALLOC(session->tlsFragSize, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     3697            if (session->tlsFragBuf == NULL) {
     3698                SetError(MEMORY_STR, error, NULL, 0);
     3699                return 0;
     3700            }
     3701
     3702            /* include the handshake header */
     3703            input -= HANDSHAKE_HEADER_SZ;
     3704            *sslBytes += HANDSHAKE_HEADER_SZ;
     3705        }
     3706
     3707        XMEMCPY(session->tlsFragBuf + session->tlsFragOffset, input, rhSize);
     3708        session->tlsFragOffset += rhSize;
     3709        *sslBytes -= rhSize;
     3710        return 0;
     3711    }
     3712#endif
     3713
     3714#ifdef WOLFSSL_TLS13
     3715    if (type != client_hello && type != server_hello) {
     3716        /* For resumption the hash is before / after client_hello PSK binder */
     3717        /* hash the packet including header */
     3718        /* TLS v1.3 requires the hash for the handshake and transfer key derivation */
     3719        /* we hash even for non TLS v1.3, since we don't know if its actually
     3720            TLS v1.3 till later at EXT_SUPPORTED_VERSIONS in server_hello */
     3721        /* hello retry request restarts hash prior to server_hello hash calc */
     3722        HashRaw(session->sslServer, input - HANDSHAKE_HEADER_SZ, size + HANDSHAKE_HEADER_SZ);
     3723        HashRaw(session->sslClient, input - HANDSHAKE_HEADER_SZ, size + HANDSHAKE_HEADER_SZ);
     3724    }
     3725#endif
    26593726#ifdef HAVE_EXTENDED_MASTER
    26603727    if (session->hash) {
     
    26623729            SetError(EXTENDED_MASTER_HASH_STR, error,
    26633730                     session, FATAL_ERROR_STATE);
    2664             return -1;
     3731            ret = -1;
     3732            goto exit;
    26653733        }
    26663734    }
     
    26943762            ret = -1;
    26953763            break;
     3764        case encrypted_extensions:
     3765            Trace(GOT_ENC_EXT_STR);
     3766            ssl->msgsReceived.got_encrypted_extensions = 1;
     3767            break;
    26963768        case certificate:
    26973769            Trace(GOT_CERT_STR);
     
    27533825        default:
    27543826            SetError(GOT_UNKNOWN_HANDSHAKE_STR, error, session, 0);
    2755             return -1;
    2756     }
     3827            ret = -1;
     3828            break;
     3829    }
     3830
     3831#ifdef HAVE_EXTENDED_MASTER
     3832exit:
     3833#endif
     3834#ifdef HAVE_MAX_FRAGMENT
     3835    if (session->tlsFragBuf) {
     3836        XFREE(session->tlsFragBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     3837        session->tlsFragBuf = NULL;
     3838    }
     3839#endif
    27573840
    27583841    *sslBytes = startBytes - size;  /* actual bytes of full process */
     
    27633846
    27643847/* Decrypt input into plain output, 0 on success */
    2765 static int Decrypt(SSL* ssl, byte* output, const byte* input, word32 sz)
     3848static int Decrypt(WOLFSSL* ssl, byte* output, const byte* input, word32 sz)
    27663849{
    27673850    int ret = 0;
     
    28143897        #endif
    28153898
    2816         #ifdef HAVE_AESGCM
     3899        #if defined(HAVE_AESGCM) || defined(HAVE_AESCCM)
    28173900        case wolfssl_aes_gcm:
    2818             if (sz >= (word32)(AESGCM_EXP_IV_SZ + ssl->specs.aead_mac_size))
    2819             {
    2820                 /* scratch buffer, sniffer ignores auth tag*/
     3901        case wolfssl_aes_ccm: /* GCM AEAD macros use same size as CCM */
     3902            if (sz >= (word32)(AESGCM_EXP_IV_SZ + ssl->specs.aead_mac_size)) {
     3903                /* scratch buffer, sniffer ignores auth tag */
     3904                wc_AesAuthEncryptFunc aes_auth_fn;
    28213905                byte authTag[WOLFSSL_MIN_AUTH_TAG_SZ];
    2822 
    28233906                byte nonce[AESGCM_NONCE_SZ];
    28243907                XMEMCPY(nonce, ssl->keys.aead_dec_imp_IV, AESGCM_IMP_IV_SZ);
    28253908                XMEMCPY(nonce + AESGCM_IMP_IV_SZ, input, AESGCM_EXP_IV_SZ);
    28263909
    2827                 if (wc_AesGcmEncrypt(ssl->decrypt.aes,
     3910                /* use encrypt because we don't care about authtag */
     3911            #if defined(BUILD_AESGCM) && defined(HAVE_AESCCM)
     3912                aes_auth_fn = (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm)
     3913                                ? wc_AesGcmEncrypt : wc_AesCcmEncrypt;
     3914            #elif defined(BUILD_AESGCM)
     3915                aes_auth_fn = wc_AesGcmEncrypt;
     3916            #else
     3917                aes_auth_fn = wc_AesCcmEncrypt;
     3918            #endif
     3919                if (aes_auth_fn(ssl->decrypt.aes,
    28283920                            output,
    28293921                            input + AESGCM_EXP_IV_SZ,
     
    28423934            }
    28433935            break;
    2844          #endif
     3936        #endif
    28453937
    28463938        #ifdef HAVE_NULL_CIPHER
     
    28613953
    28623954/* Decrypt input message into output, adjust output steam if needed */
    2863 static const byte* DecryptMessage(SSL* ssl, const byte* input, word32 sz,
    2864                                   byte* output, int* error, int* advance)
     3955static const byte* DecryptMessage(WOLFSSL* ssl, const byte* input, word32 sz,
     3956                byte* output, int* error, int* advance, RecordLayerHeader* rh)
    28653957{
    28663958    int ivExtra = 0;
    2867 
    2868     int ret = Decrypt(ssl, output, input, sz);
     3959    int ret;
     3960   
     3961#ifdef WOLFSSL_TLS13
     3962    if (IsAtLeastTLSv1_3(ssl->version)) {
     3963        ret = DecryptTls13(ssl, output, input, sz, (byte*)rh, RECORD_HEADER_SZ);
     3964    }
     3965    else
     3966#endif
     3967    {
     3968        ret = Decrypt(ssl, output, input, sz);
     3969    }
    28693970    if (ret != 0) {
    28703971        *error = ret;
     
    28733974    ssl->keys.encryptSz = sz;
    28743975    if (ssl->options.tls1_1 && ssl->specs.cipher_type == block) {
    2875         output += ssl->specs.block_size;     /* go past TLSv1.1 IV */
     3976        output += ssl->specs.block_size; /* go past TLSv1.1 IV */
    28763977        ivExtra = ssl->specs.block_size;
    28773978        *advance = ssl->specs.block_size;
     
    28873988    if (ssl->specs.cipher_type == block)
    28883989        ssl->keys.padSz += *(output + sz - ivExtra - 1) + 1;
     3990
     3991#ifdef WOLFSSL_TLS13
     3992    if (IsAtLeastTLSv1_3(ssl->version)) {
     3993        word16 i = (word16)(sz - ssl->keys.padSz);
     3994        /* Remove padding from end of plain text. */
     3995        for (--i; i > 0; i--) {
     3996            if (output[i] != 0)
     3997                break;
     3998        }
     3999        /* Get the real content type from the end of the data. */
     4000        rh->type = output[i];
     4001        ssl->keys.padSz = sz - i;
     4002    }
     4003#endif
     4004    (void)rh;
    28894005
    28904006    return output;
     
    29434059        while (session) {
    29444060            SnifferSession* next = session->next;
    2945             if (time(NULL) >= session->lastUsed + WOLFSSL_SNIFFER_TIMEOUT) {
     4061            if (XTIME(NULL) >= session->lastUsed + WOLFSSL_SNIFFER_TIMEOUT) {
    29464062                TraceStaleSession();
    29474063                RemoveSession(session, NULL, NULL, i);
     
    29924108    session->cliSeqStart = tcpInfo->sequence;
    29934109    session->cliExpected = 1;  /* relative */
    2994     session->lastUsed= time(NULL);
     4110    session->lastUsed= XTIME(NULL);
    29954111    session->keySz = 0;
    29964112#ifdef HAVE_SNI
     
    30054121    }
    30064122
    3007     session->sslServer = SSL_new(session->context->ctx);
     4123    session->sslServer = wolfSSL_new(session->context->ctx);
    30084124    if (session->sslServer == NULL) {
    30094125        SetError(BAD_NEW_SSL_STR, error, session, FATAL_ERROR_STATE);
     
    30114127        return 0;
    30124128    }
    3013     session->sslClient = SSL_new(session->context->ctx);
     4129    session->sslClient = wolfSSL_new(session->context->ctx);
    30144130    if (session->sslClient == NULL) {
    3015         SSL_free(session->sslServer);
     4131        wolfSSL_free(session->sslServer);
    30164132        session->sslServer = 0;
    30174133
     
    31524268                  int length, const byte** sslFrame, int* sslBytes, char* error)
    31534269{
     4270    IpHdr* iphdr = (IpHdr*)packet;
     4271    int version;
     4272
    31544273    TraceHeader();
    31554274    TracePacket();
     
    31604279        return -1;
    31614280    }
     4281
     4282    version = IP_V(iphdr);
     4283    if (version != IPV6 && version != IPV4) {
     4284        /* Is this VLAN IEEE 802.1Q Frame? TPID = 0x8100 */
     4285        if (packet[2] == 0x81 && packet[3] == 0x00) {
     4286            /* trim VLAN header and try again */
     4287            packet += 8;
     4288            length -= 8;
     4289        }
     4290    }
     4291
    31624292    if (CheckIpHdr((IpHdr*)packet, ipInfo, length, error) != 0)
    31634293        return -1;
     
    31774307        return -1;
    31784308    }
     4309   
    31794310    /* We only care about the data in the TCP/IP record. There may be extra
    31804311     * data after the IP record for the FCS for Ethernet. */
     
    33724503{
    33734504    if (session->flags.side == WOLFSSL_SERVER_END) {
    3374         if (session->finCaputre.cliCounted == 0)
    3375             session->finCaputre.cliFinSeq = sequence;
     4505        if (session->finCapture.cliCounted == 0)
     4506            session->finCapture.cliFinSeq = sequence;
    33764507    }
    33774508    else {
    3378         if (session->finCaputre.srvCounted == 0)
    3379             session->finCaputre.srvFinSeq = sequence;
     4509        if (session->finCapture.srvCounted == 0)
     4510            session->finCapture.srvFinSeq = sequence;
    33804511    }
    33814512    return 1;
     
    35134644                                    &session->cliReassemblyMemory :
    35144645                                    &session->srvReassemblyMemory;
    3515     SSL*                 ssl = (session->flags.side == WOLFSSL_SERVER_END) ?
     4646    WOLFSSL*             ssl = (session->flags.side == WOLFSSL_SERVER_END) ?
    35164647                                    session->sslServer :
    35174648                                    session->sslClient;
     
    35894720    word32*   expected = (session->flags.side == WOLFSSL_SERVER_END) ?
    35904721                                &session->srvExpected : &session->cliExpected;
     4722    word32    seqStart = (session->flags.side == WOLFSSL_SERVER_END) ?
     4723                                session->srvSeqStart : session->cliSeqStart;
    35914724    PacketBuffer* list = (session->flags.side == WOLFSSL_SERVER_END) ?
    35924725                                session->srvReassemblyList :
     
    35964729                                &session->flags.cliSkipPartial;
    35974730
     4731    if (tcpInfo->ackNumber < seqStart) {
     4732        return -1; /* do not fix sequence - could be ack on unseen seq */
     4733    }
    35984734    *skipPartial = 1;
     4735   
    35994736    if (list != NULL)
    36004737        *expected = list->begin;
    3601     else {
    3602         word32 seqStart = (session->flags.side == WOLFSSL_SERVER_END) ?
    3603                                 session->srvSeqStart : session->cliSeqStart;
    3604         word32     real = tcpInfo->ackNumber - seqStart;
    3605 
    3606         *expected = real;
    3607     }
     4738    else
     4739        *expected = tcpInfo->ackNumber - seqStart;
     4740
    36084741
    36094742    return 1;
     
    36464779                        &session->flags.srvAckFault;
    36474780
    3648     /* init SEQ from server to client */
    3649     if (tcpInfo->syn && tcpInfo->ack) {
     4781    /* init SEQ from server to client - if not ack fault */
     4782    if (tcpInfo->syn && tcpInfo->ack && !*ackFault) {
    36504783        session->srvSeqStart = tcpInfo->sequence;
    36514784        session->srvExpected = 1;
     
    36944827{
    36954828    word32 length;
    3696     SSL* ssl = ((*session)->flags.side == WOLFSSL_SERVER_END) ?
     4829    WOLFSSL* ssl = ((*session)->flags.side == WOLFSSL_SERVER_END) ?
    36974830                                  (*session)->sslServer : (*session)->sslClient;
    36984831    byte  skipPartial = ((*session)->flags.side == WOLFSSL_SERVER_END) ?
     
    37584891
    37594892        Trace(CHAIN_INPUT_STR);
    3760         headerSz = (word32)*sslFrame - (word32)chain[0].iov_base;
     4893        headerSz = (word32)((const byte*)*sslFrame - (const byte*)chain[0].iov_base);
    37614894        remainder = *sslBytes;
    37624895
     
    38334966                                  &session->cliExpected : &session->srvExpected;
    38344967    /* buffer is on receiving end */
    3835     word32*        length = (session->flags.side == WOLFSSL_SERVER_END) ?
     4968    word32*          length = (session->flags.side == WOLFSSL_SERVER_END) ?
    38364969                               &session->sslServer->buffers.inputBuffer.length :
    38374970                               &session->sslClient->buffers.inputBuffer.length;
     
    38394972                               &session->sslServer->buffers.inputBuffer.buffer :
    38404973                               &session->sslClient->buffers.inputBuffer.buffer;
    3841     word32*       bufferSize = (session->flags.side == WOLFSSL_SERVER_END) ?
     4974    word32*      bufferSize = (session->flags.side == WOLFSSL_SERVER_END) ?
    38424975                           &session->sslServer->buffers.inputBuffer.bufferSize :
    38434976                           &session->sslClient->buffers.inputBuffer.bufferSize;
    3844     SSL*               ssl  = (session->flags.side == WOLFSSL_SERVER_END) ?
     4977    WOLFSSL*           ssl  = (session->flags.side == WOLFSSL_SERVER_END) ?
    38454978                            session->sslServer : session->sslClient;
    38464979    word32*     reassemblyMemory = (session->flags.side == WOLFSSL_SERVER_END) ?
     
    39045037    int               notEnough;        /* notEnough bytes yet flag */
    39055038    int               decrypted = 0;    /* was current msg decrypted */
    3906     SSL*              ssl = (session->flags.side == WOLFSSL_SERVER_END) ?
    3907                                         session->sslServer : session->sslClient;
     5039    WOLFSSL*          ssl = (session->flags.side == WOLFSSL_SERVER_END) ?
     5040                            session->sslServer : session->sslClient;
    39085041doMessage:
    39095042    notEnough = 0;
     
    39515084                                               session->flags.clientCipherOn)) {
    39525085        int ivAdvance = 0;  /* TLSv1.1 advance amount */
     5086
     5087        /* change_cipher_spec is not encrypted */
     5088        if (rh.type == change_cipher_spec) {
     5089            goto doPart;
     5090        }
    39535091        if (ssl->decrypt.setup != 1) {
    39545092            SetError(DECRYPT_KEYS_NOT_SETUP, error, session, FATAL_ERROR_STATE);
     
    39595097            return -1;
    39605098        }
     5099
    39615100        sslFrame = DecryptMessage(ssl, sslFrame, rhSize,
    39625101                                  ssl->buffers.outputBuffer.buffer, &errCode,
    3963                                   &ivAdvance);
     5102                                  &ivAdvance, &rh);
    39645103        recordEnd = sslFrame - ivAdvance + rhSize;  /* sslFrame moved so
    39655104                                                       should recordEnd */
     
    39925131
    39935132                Trace(GOT_HANDSHAKE_STR);
    3994                 ret = DoHandShake(sslFrame, &sslBytes, session, error);
    3995                 if (ret != 0) {
     5133                ret = DoHandShake(sslFrame, &sslBytes, session, error, rhSize);
     5134                if (ret != 0 || sslBytes > startIdx) {
    39965135                    if (session->flags.fatalError == 0)
    39975136                        SetError(BAD_HANDSHAKE_STR, error, session,
     
    40085147            break;
    40095148        case change_cipher_spec:
    4010             if (session->flags.side == WOLFSSL_SERVER_END)
    4011                 session->flags.serverCipherOn = 1;
     5149            if (session->flags.side == WOLFSSL_SERVER_END) {
     5150            #ifdef WOLFSSL_TLS13
     5151                if (IsAtLeastTLSv1_3(session->sslServer->version) && session->srvKs.key_len == 0) {
     5152                    session->flags.serverCipherOn = 0;
     5153                }
     5154                else
     5155            #endif
     5156                {
     5157                    session->flags.serverCipherOn = 1;
     5158                }
     5159            }
    40125160            else
    40135161                session->flags.clientCipherOn = 1;
     
    41465294{
    41475295    int ret = 0;
    4148     if (session->finCaputre.cliFinSeq && session->finCaputre.cliFinSeq <=
     5296    if (session->finCapture.cliFinSeq && session->finCapture.cliFinSeq <=
    41495297                                         session->cliExpected) {
    4150         if (session->finCaputre.cliCounted == 0) {
     5298        if (session->finCapture.cliCounted == 0) {
    41515299            session->flags.finCount += 1;
    4152             session->finCaputre.cliCounted = 1;
    4153             TraceClientFin(session->finCaputre.cliFinSeq, session->cliExpected);
    4154         }
    4155     }
    4156 
    4157     if (session->finCaputre.srvFinSeq && session->finCaputre.srvFinSeq <=
     5300            session->finCapture.cliCounted = 1;
     5301            TraceClientFin(session->finCapture.cliFinSeq, session->cliExpected);
     5302        }
     5303    }
     5304
     5305    if (session->finCapture.srvFinSeq && session->finCapture.srvFinSeq <=
    41585306                                         session->srvExpected) {
    4159         if (session->finCaputre.srvCounted == 0) {
     5307        if (session->finCapture.srvCounted == 0) {
    41605308            session->flags.finCount += 1;
    4161             session->finCaputre.srvCounted = 1;
    4162             TraceServerFin(session->finCaputre.srvFinSeq, session->srvExpected);
     5309            session->finCapture.srvCounted = 1;
     5310            TraceServerFin(session->finCapture.srvFinSeq, session->srvExpected);
    41635311        }
    41645312    }
     
    45815729                                          WOLFSSL_FILETYPE_ASN1;
    45825730
    4583     ret = LoadKeyFile(&keyBuf, &keyBufSz, keyFile, keyType, password);
     5731    ret = LoadKeyFile(&keyBuf, &keyBufSz, keyFile, 0, keyType, password);
    45845732    if (ret < 0) {
    45855733        SetError(KEY_FILE_STR, error, NULL, 0);
Note: See TracChangeset for help on using the changeset viewer.