File Coverage

inc/matrixssl-3-9-3-open/matrixssl/hsDecode.c
Criterion Covered Total %
statement 370 1101 33.6
branch 205 690 29.7
condition n/a
subroutine n/a
pod n/a
total 575 1791 32.1


line stmt bran cond sub pod time code
1             /**
2             * @file hsDecode.c
3             * @version 950bba4 (HEAD -> master)
4             *
5             * SSL/TLS handshake message parsing
6             */
7             /*
8             * Copyright (c) 2013-2017 INSIDE Secure Corporation
9             * Copyright (c) PeerSec Networks, 2002-2011
10             * All Rights Reserved
11             *
12             * The latest version of this code is available at http://www.matrixssl.org
13             *
14             * This software is open source; you can redistribute it and/or modify
15             * it under the terms of the GNU General Public License as published by
16             * the Free Software Foundation; either version 2 of the License, or
17             * (at your option) any later version.
18             *
19             * This General Public License does NOT permit incorporating this software
20             * into proprietary programs. If you are unable to comply with the GPL, a
21             * commercial license for this software may be purchased from INSIDE at
22             * http://www.insidesecure.com/
23             *
24             * This program is distributed in WITHOUT ANY WARRANTY; without even the
25             * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
26             * See the GNU General Public License for more details.
27             *
28             * You should have received a copy of the GNU General Public License
29             * along with this program; if not, write to the Free Software
30             * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
31             * http://www.gnu.org/copyleft/gpl.html
32             */
33             /******************************************************************************/
34              
35             #include "matrixsslImpl.h"
36              
37             #ifdef USE_ECC
38             # define USE_ECC_EPHEMERAL_KEY_CACHE
39             #endif
40              
41             #define COMPRESSION_METHOD_NULL 0x0
42             #define COMPRESSION_METHOD_DEFLATE 0x1
43              
44             /* Errors from these routines must either be MATRIXSSL_ERROR or PS_MEM_FAIL */
45              
46             /******************************************************************************/
47              
48             #ifdef USE_SERVER_SIDE_SSL
49 1149           int32 parseClientHello(ssl_t *ssl, unsigned char **cp, unsigned char *end)
50             {
51             unsigned char *suiteStart, *suiteEnd;
52             unsigned char compareMin, compareMaj, compLen, serverHighestMinor;
53             uint32 suiteLen;
54 1149           uint32 resumptionOnTrack, cipher = 0;
55             int32 rc, i;
56             unsigned char *c;
57              
58             # ifdef USE_ECC_CIPHER_SUITE
59             const psEccCurve_t *curve;
60             # endif
61             # if defined(USE_ECC) || defined(REQUIRE_DH_PARAMS)
62 1149           void *pkiData = ssl->userPtr;
63             # endif
64              
65 1149           c = *cp;
66              
67             /* First two bytes are the highest supported major and minor SSL versions */
68             psTraceHs(">>> Server parsing CLIENT_HELLO\n");
69              
70             # ifdef USE_MATRIXSSL_STATS
71             matrixsslUpdateStat(ssl, CH_RECV_STAT, 1);
72             # endif
73 1149 50         if (end - c < 2)
74             {
75 0           ssl->err = SSL_ALERT_DECODE_ERROR;
76             psTraceInfo("Invalid ssl header version length\n");
77 0           return MATRIXSSL_ERROR;
78             }
79              
80 1149           ssl->reqMajVer = *c; c++;
81 1149           ssl->reqMinVer = *c; c++;
82              
83             # ifndef USE_SSL_PROTOCOL_VERSIONS_OTHER_THAN_3
84             /* RFC 5246 Suggests to accept all RSA minor versions, but only
85             major version 0x03 (SSLv3, TLS 1.0, TLS 1.1, TLS 1.2, TLS 1.3 etc) */
86 1149 50         if (ssl->reqMajVer != 0x03
87             # ifdef USE_DTLS
88             && ssl->reqMajVer != DTLS_MAJ_VER
89             # endif /* USE_DTLS */
90             )
91             {
92             /* Consider invalid major version protocol version error. */
93 0           ssl->err = SSL_ALERT_PROTOCOL_VERSION;
94             psTraceInfo("Won't support client's SSL major version\n");
95 0           return MATRIXSSL_ERROR;
96             }
97             # endif /* USE_SSL_PROTOCOL_VERSIONS_OTHER_THAN_3 */
98              
99             /* Client should always be sending highest supported protocol. Server
100             will reply with a match or a lower version if enabled (or forced). */
101 1149 100         if (ssl->majVer != 0)
102             {
103             /* If our forced server version is a later protocol than their
104             request, we have to exit */
105 7 50         if (ssl->reqMinVer < ssl->minVer)
106             {
107 0           ssl->err = SSL_ALERT_PROTOCOL_VERSION;
108             psTraceInfo("Won't support client's SSL version\n");
109 0           return MATRIXSSL_ERROR;
110             }
111             # ifdef USE_DTLS
112             if (ssl->flags & SSL_FLAGS_DTLS)
113             {
114             /* DTLS specfication somehow assigned minimum version of DTLS 1.0
115             as 255 so there was nowhere to go but down in DTLS 1.1 so
116             that is 253 and requires the opposite test from above */
117             if (ssl->reqMinVer > ssl->minVer)
118             {
119             ssl->err = SSL_ALERT_PROTOCOL_VERSION;
120             psTraceInfo("Won't support client's DTLS version\n");
121             return MATRIXSSL_ERROR;
122             }
123             }
124             # endif
125             /* Otherwise we just set our forced version to act like it was
126             what the client wanted in order to move through the standard
127             negotiation. */
128 7           compareMin = ssl->minVer;
129 7           compareMaj = ssl->majVer;
130             /* Set the highest version to the version explicitly set */
131 7           serverHighestMinor = ssl->minVer;
132             }
133             else
134             {
135 1142           compareMin = ssl->reqMinVer;
136 1142           compareMaj = ssl->reqMajVer;
137             /* If no explicit version was set for the server, use the highest supported */
138 1142           serverHighestMinor = TLS_HIGHEST_MINOR;
139             }
140              
141 1149 50         if (compareMaj >= SSL3_MAJ_VER)
142             {
143 1149           ssl->majVer = compareMaj;
144             # ifdef USE_TLS
145 1149 50         if (compareMin >= TLS_MIN_VER)
146             {
147             # ifndef DISABLE_TLS_1_0
148 1149           ssl->minVer = TLS_MIN_VER;
149 1149           ssl->flags |= SSL_FLAGS_TLS;
150             # endif
151             # ifdef USE_TLS_1_1 /* TLS_1_1 */
152 1149 50         if (compareMin >= TLS_1_1_MIN_VER)
153             {
154             # ifndef DISABLE_TLS_1_1
155 1149           ssl->minVer = TLS_1_1_MIN_VER;
156 1149           ssl->flags |= SSL_FLAGS_TLS_1_1 | SSL_FLAGS_TLS;
157             # endif
158             }
159             # ifdef USE_TLS_1_2
160 1149 50         if (compareMin == TLS_1_2_MIN_VER)
161             {
162 1149           ssl->minVer = TLS_1_2_MIN_VER;
163 1149           ssl->flags |= SSL_FLAGS_TLS_1_2 | SSL_FLAGS_TLS_1_1 | SSL_FLAGS_TLS;
164             }
165             # ifdef USE_DTLS
166             if (ssl->flags & SSL_FLAGS_DTLS)
167             {
168             if (compareMin == DTLS_1_2_MIN_VER)
169             {
170             ssl->minVer = DTLS_1_2_MIN_VER;
171             }
172             }
173             # endif
174             # endif /* USE_TLS_1_2 */
175             # endif /* USE_TLS_1_1 */
176 1149 50         if (ssl->minVer == 0)
177             {
178             /* TLS versions are disabled. Go SSLv3 if available. */
179             # ifdef DISABLE_SSLV3
180 0           ssl->err = SSL_ALERT_PROTOCOL_VERSION;
181             psTraceInfo("Can't support client's SSL version\n");
182 0           return MATRIXSSL_ERROR;
183             # else
184             ssl->minVer = SSL3_MIN_VER;
185             # endif
186             }
187             }
188 0 0         else if (compareMin == 0)
189             {
190             # ifdef DISABLE_SSLV3
191 0           ssl->err = SSL_ALERT_PROTOCOL_VERSION;
192             psTraceInfo("Client wanted to talk SSLv3 but it's disabled\n");
193 0           return MATRIXSSL_ERROR;
194             # else
195             ssl->minVer = SSL3_MIN_VER;
196             # endif /* DISABLE_SSLV3 */
197             }
198             # ifdef USE_DTLS
199             if (ssl->flags & SSL_FLAGS_DTLS)
200             {
201             if (compareMin < DTLS_1_2_MIN_VER)
202             {
203             ssl->err = SSL_ALERT_PROTOCOL_VERSION;
204             psTraceInfo("Error: incorrect DTLS required version\n");
205             return MATRIXSSL_ERROR;
206             }
207             ssl->minVer = DTLS_MIN_VER;
208             # ifdef USE_TLS_1_2
209             if (compareMin == DTLS_1_2_MIN_VER)
210             {
211             ssl->flags |= SSL_FLAGS_TLS_1_2 | SSL_FLAGS_TLS_1_1 | SSL_FLAGS_TLS;
212             ssl->minVer = DTLS_1_2_MIN_VER;
213             }
214             # ifdef USE_DTLS
215             if (ssl->flags & SSL_FLAGS_DTLS)
216             {
217             if (compareMin == DTLS_1_2_MIN_VER)
218             {
219             ssl->minVer = DTLS_1_2_MIN_VER;
220             }
221             }
222             # endif /* USE_DTLS */
223             # endif /* USE_TLS_1_2 */
224              
225             }
226             # endif /* USE_DTLS */
227             # else
228             ssl->minVer = SSL3_MIN_VER;
229              
230             # endif /* USE_TLS */
231              
232             }
233             else
234             {
235 0           ssl->err = SSL_ALERT_PROTOCOL_VERSION;
236             psTraceIntInfo("Unsupported ssl version: %d\n", compareMaj);
237 0           return MATRIXSSL_ERROR;
238             }
239              
240 1149 50         if (ssl->rec.majVer > SSL2_MAJ_VER)
241             {
242             /* Next is a 32 bytes of random data for key generation
243             and a single byte with the session ID length */
244 1149 50         if (end - c < SSL_HS_RANDOM_SIZE + 1)
245             {
246 0           ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
247             psTraceIntInfo("Invalid length of random data %d\n",
248             (int32) (end - c));
249 0           return MATRIXSSL_ERROR;
250             }
251 1149           memcpy(ssl->sec.clientRandom, c, SSL_HS_RANDOM_SIZE);
252 1149           c += SSL_HS_RANDOM_SIZE;
253 1149           ssl->sessionIdLen = *c; c++; /* length verified with + 1 above */
254             /* If a session length was specified, the client is asking to
255             resume a previously established session to speed up the handshake */
256 1149 100         if (ssl->sessionIdLen > 0)
257             {
258 2 50         if (ssl->sessionIdLen > SSL_MAX_SESSION_ID_SIZE ||
    50          
259 2           end - c < ssl->sessionIdLen)
260             {
261 0           ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
262             # ifdef USE_MATRIXSSL_STATS
263             matrixsslUpdateStat(ssl, FAILED_RESUMPTIONS_STAT, 1);
264             # endif
265 0           return MATRIXSSL_ERROR;
266             }
267 2           memcpy(ssl->sessionId, c, ssl->sessionIdLen);
268 2           c += ssl->sessionIdLen;
269             }
270             else
271             {
272             /* Always clear the RESUMED flag if no client session id
273             It may be re-enabled if a client session ticket extension is recvd */
274 1147           ssl->flags &= ~SSL_FLAGS_RESUMED;
275             }
276             # ifdef USE_DTLS
277             /* If DTLS is enabled, make sure we received a valid cookie in the
278             CLIENT_HELLO message. */
279             if (ssl->flags & SSL_FLAGS_DTLS)
280             {
281             psSize_t cookie_len;
282             /* Next field is the cookie length */
283             if (end - c < 1)
284             {
285             ssl->err = SSL_ALERT_DECODE_ERROR;
286             psTraceInfo("Cookie length not provided\n");
287             return MATRIXSSL_ERROR;
288             }
289             /** Calculate what we expect the cookie should be by hashing the
290             client_hello data up to this point:
291              
292             2 byte version + 1 byte session_id_len +
293             session_id + client_random
294              
295             @future The creation of the cookie should ideally take some
296             IP Tuple information about the client into account.
297             @impl MatrixSSL sends a zero length cookie on re-handshake, but
298             other implementations may not, so this allows either
299             to be supported.
300             */
301             cookie_len = 3 + ssl->sessionIdLen + SSL_HS_RANDOM_SIZE;
302             if (dtlsComputeCookie(ssl, c - cookie_len, cookie_len) < 0)
303             {
304             ssl->err = SSL_ALERT_INTERNAL_ERROR;
305             psTraceInfo("Invalid cookie length\n");
306             return MATRIXSSL_ERROR;
307             }
308             cookie_len = *c++;
309             if (cookie_len > 0)
310             {
311             if (end - c < cookie_len || cookie_len != DTLS_COOKIE_SIZE)
312             {
313             ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
314             psTraceInfo("Invalid cookie length\n");
315             return MATRIXSSL_ERROR;
316             }
317             if (memcmpct(c, ssl->srvCookie, DTLS_COOKIE_SIZE) != 0)
318             {
319             /* Cookie mismatch. Error to avoid possible DOS */
320             ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
321             psTraceInfo("Cookie mismatch\n");
322             return MATRIXSSL_ERROR;
323             }
324             c += DTLS_COOKIE_SIZE;
325             }
326             else
327             {
328             /* If client sent an empty cookie, and we're not secure
329             yet, set the hsState to encode a HELLO_VERIFY message to
330             the client, which will provide a new cookie. */
331             if (!(ssl->flags & SSL_FLAGS_READ_SECURE))
332             {
333             ssl->hsState = SSL_HS_CLIENT_HELLO;
334             c = end;
335             *cp = c;
336             /* Clear session so it will be found again when the cookie
337             clientHello message comes in next */
338             if (ssl->flags & SSL_FLAGS_RESUMED)
339             {
340             matrixClearSession(ssl, 0);
341             }
342             /* Will cause HELLO_VERIFY to be encoded */
343             return SSL_PROCESS_DATA;
344             }
345             /** No cookie provided on already secure connection.
346             @impl This is a re-handshake case. MatrixSSL lets it slide
347             since we're already authenticated. */
348             }
349             }
350             # endif /* USE_DTLS */
351             /* Next is the two byte cipher suite list length, network byte order.
352             It must not be zero, and must be a multiple of two. */
353 1149 50         if (end - c < 2)
354             {
355 0           ssl->err = SSL_ALERT_DECODE_ERROR;
356             psTraceInfo("Invalid cipher suite list length\n");
357 0           return MATRIXSSL_ERROR;
358             }
359 1149           suiteLen = *c << 8; c++;
360 1149           suiteLen += *c; c++;
361             /* Save aside. We're going to come back after extensions are
362             parsed and choose a cipher suite */
363 1149           suiteStart = c;
364              
365 1149 50         if (suiteLen <= 0 || suiteLen & 1)
    50          
366             {
367 0           ssl->err = SSL_ALERT_DECODE_ERROR;
368             psTraceIntInfo("Unable to parse cipher suite list: %d\n",
369             suiteLen);
370 0           return MATRIXSSL_ERROR;
371             }
372             /* Now is 'suiteLen' bytes of the supported cipher suite list,
373             listed in order of preference. */
374 1149 50         if (end - c < suiteLen)
375             {
376 0           ssl->err = SSL_ALERT_DECODE_ERROR;
377             psTraceInfo("Malformed clientHello message\n");
378 0           return MATRIXSSL_ERROR;
379             }
380             /* We do not choose a ciphersuite yet, as the cipher we choose
381             may depend on an extension sent by the client. For example,
382             ALPN for HTTP/2 limits which suites we can negotiate, and
383             ELLIPTIC_CURVE/ELLIPTIC_POINT extensions may not match with
384             what we have available and we would have to fall back to a
385             non-ECC cipher.
386             Still, make one entire pass of the cipher suites now
387             to search for SCSV if secure rehandshakes are on. This is
388             the exception because SCSV is not a true ciphersuite, but
389             more like an extension that can be "hidden" for pre-TLS1.0
390             implementations. */
391 1149           suiteEnd = c + suiteLen;
392 20660 100         while (c < suiteEnd)
393             {
394 19511           cipher = *c << 8; c++;
395 19511           cipher += *c; c++;
396             # ifdef ENABLE_SECURE_REHANDSHAKES
397 19511 100         if (ssl->myVerifyDataLen == 0)
398             {
399 19414 100         if (cipher == TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
400             {
401 1142           ssl->secureRenegotiationFlag = PS_TRUE;
402             }
403             }
404             # endif
405             /** If TLS_FALLBACK_SCSV appears in ClientHello.cipher_suites and the
406             highest protocol version supported by the server is higher than
407             the version indicated in ClientHello.client_version, the server
408             MUST respond with a fatal inappropriate_fallback alert.
409             @see https://tools.ietf.org/html/rfc7507#section-3 */
410 19511 50         if (cipher == TLS_FALLBACK_SCSV)
411             {
412 0 0         if (ssl->reqMinVer < serverHighestMinor)
413             {
414 0           ssl->err = SSL_ALERT_INAPPROPRIATE_FALLBACK;
415             psTraceInfo("Inappropriate version fallback\n");
416 0           return MATRIXSSL_ERROR;
417             }
418             }
419             }
420              
421             /* Compression parameters */
422 1149 50         if (end - c < 1)
423             {
424 0           ssl->err = SSL_ALERT_DECODE_ERROR;
425             psTraceInfo("Invalid compression header length\n");
426 0           return MATRIXSSL_ERROR;
427             }
428 1149           compLen = *c++;
429 1149 50         if ((uint32) (end - c) < compLen)
430             {
431 0           ssl->err = SSL_ALERT_DECODE_ERROR;
432             psTraceInfo("Invalid compression header length\n");
433 0           return MATRIXSSL_ERROR;
434             }
435             /* Per TLS RFCs proposing null compression is MUST. Check the other end
436             has proposed null compression (amongst possible other choices). */
437 1149 50         for (i = 0; i < compLen; i++)
438             {
439 1149 50         if (c[i] == COMPRESSION_METHOD_NULL)
440             {
441 1149           break;
442             }
443             }
444 1149 50         if (i == compLen)
445             {
446             /* Note, also catches compLen == 0 */
447 0           ssl->err = SSL_ALERT_DECODE_ERROR;
448             psTraceInfo("No compression.null proposed\n");
449 0           return MATRIXSSL_ERROR;
450             }
451             # ifdef USE_ZLIB_COMPRESSION
452             while (compLen > 0)
453             {
454             /* Client wants it and we have it. Enable if we're not already
455             in a compression state. FUTURE: Could be re-handshake */
456             if (ssl->compression == 0)
457             {
458             if (*c++ == 0x01)
459             {
460             ssl->inflate.zalloc = NULL;
461             ssl->inflate.zfree = NULL;
462             ssl->inflate.opaque = NULL;
463             ssl->inflate.avail_in = 0;
464             ssl->inflate.next_in = NULL;
465             if (inflateInit(&ssl->inflate) != Z_OK)
466             {
467             psTraceInfo("inflateInit fail. No compression\n");
468             }
469             else
470             {
471             ssl->deflate.zalloc = Z_NULL;
472             ssl->deflate.zfree = Z_NULL;
473             ssl->deflate.opaque = Z_NULL;
474             if (deflateInit(&ssl->deflate,
475             Z_DEFAULT_COMPRESSION) != Z_OK)
476             {
477             psTraceInfo("deflateInit fail. No compression\n");
478             inflateEnd(&ssl->inflate);
479             }
480             else
481             {
482             /* Init good. Let's enable it */
483             ssl->compression = 1;
484             }
485             }
486             }
487             compLen--;
488             }
489             else
490             {
491             c++;
492             compLen--;
493             }
494             }
495             # else
496 1149           c += compLen;
497             # endif
498 1149           rc = parseClientHelloExtensions(ssl, &c, end - c);
499 1149 50         if (rc < 0)
500             {
501             /* Alerts are set by the extension parse */
502 0           return rc;
503             }
504             }
505             else
506             {
507 0           ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
508             psTraceInfo("SSLV2 CLIENT_HELLO not supported.\n");
509 0           return MATRIXSSL_ERROR;
510             }
511              
512             /* ClientHello should be the only one in the record. */
513 1149 50         if (c != end)
514             {
515 0           ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
516             psTraceInfo("Invalid final client hello length\n");
517 0           return MATRIXSSL_ERROR;
518             }
519              
520             /* Look up the session id for ssl session resumption. If found, we
521             load the pre-negotiated masterSecret and cipher.
522             A resumed request must meet the following restrictions:
523             The id must be present in the lookup table
524             The requested version must match the original version
525             The cipher suite list must contain the original cipher suite
526             */
527 1149 100         if (ssl->sessionIdLen > 0)
528             {
529             /* Check if we are resuming on a session ticket first. It is
530             legal for a client to send both a session ID and a ticket. If
531             the ticket is used, the session ID should not be used at all */
532             # ifdef USE_STATELESS_SESSION_TICKETS
533 2 50         if ((ssl->flags & SSL_FLAGS_RESUMED) && (ssl->sid) &&
    0          
    0          
534 0           (ssl->sid->sessionTicketState == SESS_TICKET_STATE_USING_TICKET))
535             {
536 0           goto SKIP_STANDARD_RESUMPTION;
537             }
538             # endif
539              
540 2 50         if (matrixResumeSession(ssl) >= 0)
541             {
542 2           ssl->flags &= ~SSL_FLAGS_CLIENT_AUTH;
543 2           ssl->flags |= SSL_FLAGS_RESUMED;
544             # ifdef USE_MATRIXSSL_STATS
545             matrixsslUpdateStat(ssl, RESUMPTIONS_STAT, 1);
546             # endif
547             }
548             else
549             {
550 0           ssl->flags &= ~SSL_FLAGS_RESUMED;
551             # ifdef USE_STATELESS_SESSION_TICKETS
552             /* Client MAY generate and include a Session ID in the
553             TLS ClientHello. If the server accepts the ticket
554             and the Session ID is not empty, then it MUST respond
555             with the same Session ID present in the ClientHello. Check
556             if client is even using the mechanism though */
557 0 0         if (ssl->sid)
558             {
559 0 0         if (ssl->sid->sessionTicketState == SESS_TICKET_STATE_INIT)
560             {
561 0           memset(ssl->sessionId, 0, SSL_MAX_SESSION_ID_SIZE);
562 0           ssl->sessionIdLen = 0;
563             }
564             else
565             {
566             /* This flag means we received a session we can't resume
567             but we have to send it back if we also get a ticket
568             later that we like */
569 0           ssl->extFlags.session_id = 1;
570             }
571             }
572             else
573             {
574 0           memset(ssl->sessionId, 0, SSL_MAX_SESSION_ID_SIZE);
575 0           ssl->sessionIdLen = 0;
576             }
577             # else
578             memset(ssl->sessionId, 0, SSL_MAX_SESSION_ID_SIZE);
579             ssl->sessionIdLen = 0;
580             # ifdef USE_MATRIXSSL_STATS
581             matrixsslUpdateStat(ssl, FAILED_RESUMPTIONS_STAT, 1);
582             # endif
583             # endif
584             }
585             }
586              
587             # ifdef USE_STATELESS_SESSION_TICKETS
588             SKIP_STANDARD_RESUMPTION:
589             # endif
590              
591             /* If resumed, confirm the cipher suite was sent. Otherwise, choose
592             the cipher suite based on what the user has loaded or what the user
593             sends in the pubkey callback */
594 1149 100         if (ssl->flags & SSL_FLAGS_RESUMED)
595             {
596             /* Have to rewalk ciphers and see if they sent the cipher. Can
597             move suiteStart safely since we'll be the last to use it */
598 2           suiteEnd = suiteStart + suiteLen;
599 2           resumptionOnTrack = 0;
600 34 100         while (suiteStart < suiteEnd)
601             {
602 32 50         if (ssl->rec.majVer > SSL2_MAJ_VER)
603             {
604 32           cipher = *suiteStart << 8; suiteStart++;
605 32           cipher += *suiteStart; suiteStart++;
606             }
607             else
608             {
609 0           ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
610             psTraceInfo("SSLV2 not supported.\n");
611 0           return MATRIXSSL_ERROR;
612             }
613 32 100         if (cipher == ssl->cipher->ident)
614             {
615 2           resumptionOnTrack = 1;
616             }
617             }
618 2 50         if (resumptionOnTrack == 0)
619             {
620             /* Previous cipher suite wasn't sent for resumption. This is an
621             error according to the specs */
622             psTraceIntInfo("Client didn't send cipher %d for resumption\n",
623             ssl->cipher->ident);
624 0           ssl->cipher = sslGetCipherSpec(ssl, SSL_NULL_WITH_NULL_NULL);
625 0           ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
626 0           return MATRIXSSL_ERROR;
627             }
628             }
629             else
630             {
631             /* User helps pick the cipher based on the key material. Successful
632             end result will be assignment of ssl->cipher */
633 1147 50         if (chooseCipherSuite(ssl, suiteStart, suiteLen) < 0)
634             {
635             psTraceInfo("Server could not support any client cipher suites\n");
636 0           ssl->cipher = sslGetCipherSpec(ssl, SSL_NULL_WITH_NULL_NULL);
637 0 0         if (ssl->err != SSL_ALERT_UNRECOGNIZED_NAME)
638             {
639 0           ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
640             }
641 0           return MATRIXSSL_ERROR;
642             }
643 1147 50         if (ssl->cipher->ident == 0)
644             {
645             psTraceInfo("Client attempting SSL_NULL_WITH_NULL_NULL conn\n");
646 0           ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
647 0           return MATRIXSSL_ERROR;
648             }
649             }
650              
651 1149           matrixSslSetKexFlags(ssl);
652              
653             /* If we're resuming a handshake, then the next handshake message we
654             expect is the finished message. Otherwise we do the full handshake */
655 1149 100         if (ssl->flags & SSL_FLAGS_RESUMED)
656             {
657 2           ssl->hsState = SSL_HS_FINISHED;
658             }
659             else
660             {
661             # ifdef USE_DHE_CIPHER_SUITE
662             /* If we are DH key exchange we need to generate some keys. The
663             FLAGS_DHE_KEY_EXCH will eventually drive the state matchine to
664             the ServerKeyExchange path, but ECDH_ suites need the key gen now */
665 1147 100         if (ssl->flags & SSL_FLAGS_DHE_KEY_EXCH)
666             {
667              
668             # ifdef USE_ECC_CIPHER_SUITE
669 1146 50         if (ssl->flags & SSL_FLAGS_ECC_CIPHER)
670             {
671             /* If ecCurveId is zero and we received the extension, then
672             we really couldn't match and can't continue. */
673 1146 50         if (ssl->ecInfo.ecCurveId == 0 &&
    0          
674 0           (ssl->ecInfo.ecFlags & IS_RECVD_EXT))
675             {
676             psTraceInfo("Did not share any EC curves with client\n");
677             /* Don't see any particular alert for this case */
678 0           ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
679 0           return MATRIXSSL_ERROR;
680             }
681             /* A ecCurveId of zero (with no extension) will return a
682             default which is fine according to spec */
683 1146 50         if (getEccParamById(ssl->ecInfo.ecCurveId, &curve) < 0)
684             {
685 0           return MATRIXSSL_ERROR;
686             }
687 1146 50         if (psEccNewKey(ssl->hsPool, &ssl->sec.eccKeyPriv, curve) < 0)
688             {
689 0           return PS_MEM_FAIL;
690             }
691             # ifdef USE_ECC_EPHEMERAL_KEY_CACHE
692 1146 50         if ((rc = matrixSslGenEphemeralEcKey(ssl->keys,
693             ssl->sec.eccKeyPriv, curve, pkiData)) < 0)
694             {
695             # else
696             if ((rc = psEccGenKey(ssl->hsPool, ssl->sec.eccKeyPriv,
697             curve, pkiData)) < 0)
698             {
699              
700             # endif
701 0           psEccDeleteKey(&ssl->sec.eccKeyPriv);
702             psTraceInfo("GenEphemeralEcc failed\n");
703 0           ssl->err = SSL_ALERT_INTERNAL_ERROR;
704 0           return rc;
705             }
706             }
707             else
708             {
709             # endif /* USE_ECC_CIPHER_SUITE */
710             # ifdef REQUIRE_DH_PARAMS
711             /* Servers using DH suites know DH key sizes when handshake
712             pool is created so that has been accounted for here */
713 0 0         if ((ssl->sec.dhKeyPriv = psMalloc(ssl->hsPool,
714             sizeof(psDhKey_t))) == NULL)
715             {
716 0           return MATRIXSSL_ERROR;
717             }
718 0 0         if ((rc = psDhGenKeyInts(ssl->hsPool, ssl->keys->dhParams.size,
719 0           &ssl->keys->dhParams.p, &ssl->keys->dhParams.g,
720             ssl->sec.dhKeyPriv, pkiData)) < 0)
721             {
722 0           psFree(ssl->sec.dhKeyPriv, ssl->hsPool);
723 0           ssl->sec.dhKeyPriv = NULL;
724             psTraceInfo("Error generating DH keys\n");
725 0           ssl->err = SSL_ALERT_INTERNAL_ERROR;
726 0           return MATRIXSSL_ERROR;
727             }
728             # endif
729             # ifdef USE_ECC_CIPHER_SUITE
730             }
731             # endif /* USE_ECC_CIPHER_SUITE */
732             }
733             # endif /* USE_DHE_CIPHER_SUITE */
734              
735 1147           ssl->hsState = SSL_HS_CLIENT_KEY_EXCHANGE;
736             # ifdef USE_CLIENT_AUTH
737             /* Next state in client authentication case is to receive the cert */
738 1147 50         if (ssl->flags & SSL_FLAGS_CLIENT_AUTH)
739             {
740             # ifdef USE_ANON_DH_CIPHER_SUITE
741             /* However, what if the server has called for client auth and
742             the client is requesting an 'anon' cipher suite?
743              
744             SECURITY: Options are to default to what the
745             client wants, what the server wants, or error out. The
746             current implementation does what the client wants. */
747 0 0         if (ssl->flags & SSL_FLAGS_ANON_CIPHER)
748             {
749             psTraceIntInfo(
750             "Anon cipher %d negotiated. Disabling client auth\n",
751             ssl->cipher->ident);
752 0           ssl->flags &= ~SSL_FLAGS_CLIENT_AUTH;
753             }
754             else
755             {
756             # endif /* USE_ANON_DH_CIPHER_SUITE */
757 0           ssl->hsState = SSL_HS_CERTIFICATE;
758             # ifdef USE_ANON_DH_CIPHER_SUITE
759             }
760             # endif /* USE_ANON_DH_CIPHER_SUITE */
761             }
762             # endif /* USE_CLIENT_AUTH */
763             }
764             /* Now that we've parsed the ClientHello, we need to tell the caller that
765             we have a handshake response to write out.
766             The caller should call sslWrite upon receiving this return code. */
767 1149           *cp = c;
768 1149           ssl->decState = SSL_HS_CLIENT_HELLO;
769 1149           return SSL_PROCESS_DATA;
770             }
771              
772             /******************************************************************************/
773              
774 1057           int32 parseClientKeyExchange(ssl_t *ssl, int32 hsLen, unsigned char **cp,
775             unsigned char *end)
776             {
777             int32 rc, pubKeyLen;
778             unsigned char *c;
779              
780             # ifdef USE_RSA_CIPHER_SUITE
781             unsigned char R[SSL_HS_RSA_PREMASTER_SIZE - 2];
782 1057           psPool_t *ckepkiPool = NULL;
783             # endif
784             # ifdef USE_PSK_CIPHER_SUITE
785             uint8_t pskLen;
786 1057           unsigned char *pskKey = NULL;
787             # endif
788 1057           void *pkiData = ssl->userPtr;
789              
790 1057           c = *cp;
791              
792             /* RSA: This message contains the premaster secret encrypted with the
793             server's public key (from the Certificate). The premaster
794             secret is 48 bytes of random data, but the message will be longer
795             than that because the 48 bytes are padded before encryption
796             according to PKCS#1v1.5. After encryption, we should have the
797             correct length. */
798             psTraceHs(">>> Server parsing CLIENT_KEY_EXCHANGE\n");
799 1057 50         if ((int32) (end - c) < hsLen)
800             {
801 0           ssl->err = SSL_ALERT_DECODE_ERROR;
802             psTraceInfo("Invalid ClientKeyExchange length 1\n");
803 0           return MATRIXSSL_ERROR;
804             }
805              
806 1057           pubKeyLen = hsLen;
807             # ifdef USE_TLS
808             /* TLS - Two byte length is explicit. */
809 1057 50         if (ssl->majVer >= TLS_MAJ_VER && ssl->minVer >= TLS_MIN_VER)
    50          
810             {
811 1057 50         if (end - c < 2)
812             {
813 0           ssl->err = SSL_ALERT_DECODE_ERROR;
814             psTraceInfo("Invalid ClientKeyExchange length 2\n");
815 0           return MATRIXSSL_ERROR;
816             }
817             # ifdef USE_ECC_CIPHER_SUITE
818 1057 100         if (ssl->flags & SSL_FLAGS_ECC_CIPHER)
819             {
820 1056           pubKeyLen = *c; c++;
821             }
822             else
823             {
824             # endif /* USE_ECC_CIPHER_SUITE */
825 1           pubKeyLen = *c << 8; c++;
826 1           pubKeyLen += *c; c++;
827             # ifdef USE_ECC_CIPHER_SUITE
828             }
829             # endif /* USE_ECC_CIPHER_SUITE */
830 1057 50         if ((int32) (end - c) < pubKeyLen)
831             {
832 0           ssl->err = SSL_ALERT_DECODE_ERROR;
833             psTraceInfo("Invalid ClientKeyExchange length 3\n");
834 0           return MATRIXSSL_ERROR;
835             }
836             }
837             # endif /* USE_TLS */
838              
839             # ifdef USE_DHE_CIPHER_SUITE
840 1057 100         if (ssl->flags & SSL_FLAGS_DHE_KEY_EXCH)
841             {
842 1056 50         if (ssl->majVer == SSL3_MAJ_VER && ssl->minVer == SSL3_MIN_VER)
    50          
843             {
844             # ifdef USE_ECC_CIPHER_SUITE
845             /* Support ECC ciphers in SSLv3. This isn't really a desirable
846             combination and it's a fuzzy area in the specs but it works */
847 0 0         if (!(ssl->flags & SSL_FLAGS_ECC_CIPHER))
848             {
849             # endif
850             /* DH cipher suites use the ClientDiffieHellmanPublic format
851             which always includes the explicit key length regardless
852             of protocol. If TLS, we already stripped it out above. */
853 0 0         if (end - c < 2)
854             {
855 0           ssl->err = SSL_ALERT_DECODE_ERROR;
856             psTraceInfo("Invalid ClientKeyExchange length 4\n");
857 0           return MATRIXSSL_ERROR;
858             }
859 0           pubKeyLen = *c << 8; c++;
860 0           pubKeyLen += *c; c++;
861 0 0         if ((int32) (end - c) < pubKeyLen)
862             {
863 0           ssl->err = SSL_ALERT_DECODE_ERROR;
864             psTraceInfo("Invalid ClientKeyExchange length 5\n");
865 0           return MATRIXSSL_ERROR;
866             }
867             # ifdef USE_ECC_CIPHER_SUITE
868             }
869             else
870             {
871 0           pubKeyLen = *c; c++;
872             }
873             # endif
874             }
875             # ifdef USE_PSK_CIPHER_SUITE
876 1056 50         if (ssl->flags & SSL_FLAGS_PSK_CIPHER)
877             {
878             /* That initial pubKeyLen we read off the top was actually the
879             length of the PSK id that we need to find a key for */
880 0 0         if ((uint32) (end - c) < pubKeyLen)
881             {
882 0           ssl->err = SSL_ALERT_DECODE_ERROR;
883             psTraceInfo("Invalid ClientKeyExchange PSK length\n");
884 0           return MATRIXSSL_ERROR;
885             }
886              
887             /* If there are PSKs loaded, look at those. Otherwise see if
888             there is a callback. */
889 0 0         if (ssl->keys && ssl->keys->pskKeys)
    0          
890             {
891 0           matrixSslPskGetKey(ssl, c, pubKeyLen, &pskKey, &pskLen);
892             }
893 0 0         else if (ssl->sec.pskCb)
894             {
895 0           (ssl->sec.pskCb)(ssl, c, pubKeyLen, &pskKey, &pskLen);
896             }
897 0 0         if (pskKey == NULL)
898             {
899             psTraceInfo("Server doesn't not have matching pre-shared key\n");
900 0           ssl->err = SSL_ALERT_UNKNOWN_PSK_IDENTITY;
901 0           return MATRIXSSL_ERROR;
902             }
903 0           c += pubKeyLen;
904             /* This is the DH pub key now */
905 0           pubKeyLen = *c << 8; c++;
906 0           pubKeyLen += *c; c++;
907 0 0         if ((uint32) (end - c) < pubKeyLen)
908             {
909 0           ssl->err = SSL_ALERT_DECODE_ERROR;
910             psTraceInfo("Invalid ClientKeyExchange length\n");
911 0           return MATRIXSSL_ERROR;
912             }
913             }
914             # endif /* USE_PSK_CIPHER_SUITE */
915              
916             # ifdef USE_ECC_CIPHER_SUITE
917 1056 50         if (ssl->flags & SSL_FLAGS_ECC_CIPHER)
918             {
919 1056 50         if (psEccNewKey(ssl->hsPool, &ssl->sec.eccKeyPub,
920 1056           ssl->sec.eccKeyPriv->curve) < 0)
921             {
922 0           return SSL_MEM_ERROR;
923             }
924 1056 50         if (psEccX963ImportKey(ssl->hsPool, c, pubKeyLen,
925 1056           ssl->sec.eccKeyPub, ssl->sec.eccKeyPriv->curve) < 0)
926             {
927 0           ssl->err = SSL_ALERT_DECODE_ERROR;
928 0           return MATRIXSSL_ERROR;
929             }
930             /* BUG FIX after 3.8.1a release. This increment is done later
931             in the function. So in cases where multiple handshake messages
932             were put in a single record, we are moving pubKeyLen farther
933             than we want which could still be in the valid buffer.
934             The error would be an "unexpected handshake message" when
935             the next message parse was attempted */
936             /* c += pubKeyLen; */
937              
938 1056           ssl->sec.premasterSize = ssl->sec.eccKeyPriv->curve->size;
939 1056           ssl->sec.premaster = psMalloc(ssl->hsPool,
940             ssl->sec.premasterSize);
941 1056 50         if (ssl->sec.premaster == NULL)
942             {
943 0           return SSL_MEM_ERROR;
944             }
945 1056 50         if ((rc = psEccGenSharedSecret(ssl->hsPool, ssl->sec.eccKeyPriv,
946 1056           ssl->sec.eccKeyPub, ssl->sec.premaster,
947             &ssl->sec.premasterSize, pkiData)) < 0)
948             {
949 0           ssl->err = SSL_ALERT_INTERNAL_ERROR;
950 0           psFree(ssl->sec.premaster, ssl->hsPool);
951 0           ssl->sec.premaster = NULL;
952 0           return MATRIXSSL_ERROR;
953             }
954 1056           psEccDeleteKey(&ssl->sec.eccKeyPub);
955 1056           psEccDeleteKey(&ssl->sec.eccKeyPriv);
956             }
957             else
958             {
959             # endif /* USE_ECC_CIPHER_SUITE */
960             # ifdef REQUIRE_DH_PARAMS
961 0 0         if ((ssl->sec.dhKeyPub = psMalloc(ssl->hsPool, sizeof(psDhKey_t))) == NULL)
962             {
963 0           return MATRIXSSL_ERROR;
964             }
965 0 0         if (psDhImportPubKey(ssl->hsPool, c, pubKeyLen,
966             ssl->sec.dhKeyPub) < 0)
967             {
968 0           psFree(ssl->sec.dhKeyPub, ssl->hsPool);
969 0           ssl->sec.dhKeyPub = NULL;
970 0           return MATRIXSSL_ERROR;
971             }
972             /*
973             Now know the premaster details. Create it.
974              
975             A Diffie-Hellman shared secret has, at maximum, the same number of
976             bytes as the prime. Use this number as our max buffer size that
977             will be into psDhGenSecret.
978             */
979 0           ssl->sec.premasterSize = ssl->sec.dhPLen;
980              
981             # ifdef USE_PSK_CIPHER_SUITE
982 0 0         if (ssl->flags & SSL_FLAGS_PSK_CIPHER)
983             {
984             /*
985             Premaster is appended with the PSK. Account for that length
986             here to avoid a realloc after the standard DH premaster is
987             created below.
988             */
989 0           ssl->sec.premasterSize += pskLen + 4; /* psSize_t len heads */
990             }
991             # endif /* USE_PSK_CIPHER_SUITE */
992              
993 0           ssl->sec.premaster = psMalloc(ssl->hsPool, ssl->sec.premasterSize);
994 0 0         if (ssl->sec.premaster == NULL)
995             {
996 0           return SSL_MEM_ERROR;
997             }
998 0 0         if ((rc = psDhGenSharedSecret(ssl->hsPool, ssl->sec.dhKeyPriv,
999 0           ssl->sec.dhKeyPub, ssl->sec.dhP, ssl->sec.dhPLen,
1000             ssl->sec.premaster,
1001             &ssl->sec.premasterSize, pkiData)) < 0)
1002             {
1003 0           return MATRIXSSL_ERROR;
1004             }
1005 0           psFree(ssl->sec.dhP, ssl->hsPool);
1006 0           ssl->sec.dhP = NULL; ssl->sec.dhPLen = 0;
1007 0           psFree(ssl->sec.dhG, ssl->hsPool);
1008 0           ssl->sec.dhG = NULL; ssl->sec.dhGLen = 0;
1009 0           psDhClearKey(ssl->sec.dhKeyPub);
1010 0           psFree(ssl->sec.dhKeyPub, ssl->hsPool);
1011 0           ssl->sec.dhKeyPub = NULL;
1012 0           psDhClearKey(ssl->sec.dhKeyPriv);
1013 0           psFree(ssl->sec.dhKeyPriv, ssl->hsPool);
1014 0           ssl->sec.dhKeyPriv = NULL;
1015             # ifdef USE_PSK_CIPHER_SUITE
1016 0 0         if (ssl->flags & SSL_FLAGS_PSK_CIPHER)
1017             {
1018             /*
1019             Need to prepend a psSize_t length to the premaster key.
1020             */
1021 0           memmove(&ssl->sec.premaster[2], ssl->sec.premaster,
1022 0           ssl->sec.premasterSize);
1023 0           ssl->sec.premaster[0] = (ssl->sec.premasterSize & 0xFF00) >> 8;
1024 0           ssl->sec.premaster[1] = (ssl->sec.premasterSize & 0xFF);
1025             /*
1026             Next, uint8_t length of PSK and key itself
1027             */
1028 0           ssl->sec.premaster[ssl->sec.premasterSize + 2] = 0;
1029 0           ssl->sec.premaster[ssl->sec.premasterSize + 3] = (pskLen & 0xFF);
1030 0           memcpy(&ssl->sec.premaster[ssl->sec.premasterSize + 4], pskKey,
1031             pskLen);
1032             /*
1033             Lastly, adjust the premasterSize
1034             */
1035 1056           ssl->sec.premasterSize += pskLen + 4;
1036             }
1037             # endif /* USE_PSK_CIPHER_SUITE */
1038             # endif /* REQUIRE_DH_PARAMS */
1039             # ifdef USE_ECC_CIPHER_SUITE
1040             }
1041             # endif /* USE_ECC_CIPHER_SUITE */
1042             }
1043             else
1044             {
1045             # endif /* USE_DHE_CIPHER_SUITE */
1046             # ifdef USE_PSK_CIPHER_SUITE
1047 1 50         if (ssl->flags & SSL_FLAGS_PSK_CIPHER)
1048             {
1049              
1050 0 0         if (ssl->majVer == SSL3_MAJ_VER && ssl->minVer == SSL3_MIN_VER)
    0          
1051             {
1052             /* SSLv3 for basic PSK suites will not have read off
1053             pubKeyLen at this point */
1054 0           pubKeyLen = *c << 8; c++;
1055 0           pubKeyLen += *c; c++;
1056             }
1057             /* If there are PSKs loaded, look at those. Otherwise see if
1058             there is a callback. */
1059 0 0         if (ssl->keys && ssl->keys->pskKeys)
    0          
1060             {
1061 0           matrixSslPskGetKey(ssl, c, pubKeyLen, &pskKey,
1062             &pskLen);
1063             }
1064 0 0         else if (ssl->sec.pskCb)
1065             {
1066 0 0         if ((ssl->sec.pskCb)(ssl, c, pubKeyLen, &pskKey, &pskLen)
1067             < 0)
1068             {
1069             psTraceInfo("User couldn't find pre-shared key\n");
1070 0           ssl->err = SSL_ALERT_UNKNOWN_PSK_IDENTITY;
1071 0           return MATRIXSSL_ERROR;
1072             }
1073             }
1074 0 0         if (pskKey == NULL)
1075             {
1076             psTraceInfo("Server doesn't have matching pre-shared key\n");
1077 0           ssl->err = SSL_ALERT_UNKNOWN_PSK_IDENTITY;
1078 0           return MATRIXSSL_ERROR;
1079             }
1080 0           ssl->sec.premasterSize = (pskLen * 2) + 4;
1081 0           ssl->sec.premaster = psMalloc(ssl->hsPool,
1082             ssl->sec.premasterSize);
1083 0 0         if (ssl->sec.premaster == NULL)
1084             {
1085 0           return SSL_MEM_ERROR;
1086             }
1087 0           memset(ssl->sec.premaster, 0, ssl->sec.premasterSize);
1088 0           ssl->sec.premaster[0] = 0;
1089 0           ssl->sec.premaster[1] = (pskLen & 0xFF);
1090             /* memset to 0 handled middle portion */
1091 0           ssl->sec.premaster[2 + pskLen] = 0;
1092 0           ssl->sec.premaster[3 + pskLen] = (pskLen & 0xFF);
1093 0           memcpy(&ssl->sec.premaster[4 + pskLen], pskKey, pskLen);
1094             }
1095             else
1096             {
1097             # endif
1098             # ifdef USE_ECC_CIPHER_SUITE
1099 1 50         if (ssl->cipher->type == CS_ECDH_ECDSA ||
    50          
1100 1           ssl->cipher->type == CS_ECDH_RSA)
1101             {
1102 0 0         if (ssl->majVer == SSL3_MAJ_VER &&
    0          
1103 0           ssl->minVer == SSL3_MIN_VER)
1104             {
1105             /* Support ECC ciphers in SSLv3. This isn't really a
1106             desirable combination and it's a fuzzy area in the
1107             specs but it works */
1108 0           pubKeyLen = *c; c++;
1109             }
1110 0 0         if (ssl->keys == NULL)
1111             {
1112 0           ssl->err = SSL_ALERT_INTERNAL_ERROR;
1113 0           return MATRIXSSL_ERROR;
1114             }
1115 0 0         if (psEccNewKey(ssl->hsPool, &ssl->sec.eccKeyPub,
1116 0           ssl->keys->privKey.key.ecc.curve) < 0)
1117             {
1118 0           return SSL_MEM_ERROR;
1119             }
1120 0 0         if (psEccX963ImportKey(ssl->hsPool, c, pubKeyLen,
1121 0           ssl->sec.eccKeyPub, ssl->keys->privKey.key.ecc.curve)
1122             < 0)
1123             {
1124 0           ssl->err = SSL_ALERT_DECODE_ERROR;
1125 0           return MATRIXSSL_ERROR;
1126             }
1127             /* BUG FIX after 3.8.1a release. This increment is done
1128             later in the function. So in cases where multiple
1129             handshake messages were put in a single record, we are
1130             moving pubKeyLen farther than we want which could still
1131             be in the valid buffer. The error would be an
1132             "unexpected handshake message" when the next message
1133             parse was attempted */
1134             /* c += pubKeyLen; */
1135              
1136 0           ssl->sec.premasterSize =
1137 0           ssl->keys->privKey.key.ecc.curve->size;
1138 0           ssl->sec.premaster = psMalloc(ssl->hsPool,
1139             ssl->sec.premasterSize);
1140 0 0         if (ssl->sec.premaster == NULL)
1141             {
1142 0           return SSL_MEM_ERROR;
1143             }
1144 0 0         if ((rc = psEccGenSharedSecret(ssl->hsPool,
1145 0           &ssl->keys->privKey.key.ecc, ssl->sec.eccKeyPub,
1146             ssl->sec.premaster, &ssl->sec.premasterSize,
1147             pkiData)) < 0)
1148             {
1149 0           ssl->err = SSL_ALERT_INTERNAL_ERROR;
1150 0           psFree(ssl->sec.premaster, ssl->hsPool);
1151 0           ssl->sec.premaster = NULL;
1152 0           return MATRIXSSL_ERROR;
1153             }
1154 0           psEccDeleteKey(&ssl->sec.eccKeyPub);
1155             }
1156             else
1157             {
1158             # endif /* USE_ECC_CIPHER_SUITE */
1159              
1160             # ifdef USE_RSA_CIPHER_SUITE
1161 1 50         if (ssl->keys == NULL)
1162             {
1163 0           ssl->err = SSL_ALERT_INTERNAL_ERROR;
1164 0           return MATRIXSSL_ERROR;
1165             }
1166             /* Standard RSA suite. Now have a handshake pool to allocate
1167             the premaster storage */
1168 1           ssl->sec.premasterSize = SSL_HS_RSA_PREMASTER_SIZE;
1169 1           ssl->sec.premaster = psMalloc(ssl->hsPool,
1170             SSL_HS_RSA_PREMASTER_SIZE);
1171 1 50         if (ssl->sec.premaster == NULL)
1172             {
1173 0           return SSL_MEM_ERROR;
1174             }
1175              
1176             /**
1177             @security Caution - the results of an RSA private key
1178             decryption should never have any bearing on timing or response,
1179             otherwise we can be vulnerable to a side channel attack.
1180             @see http://web-in-security.blogspot.co.at/2014/08/old-attacks-on-new-tls-implementations.html
1181             @see https://tools.ietf.org/html/rfc5246#section-7.4.7.1
1182             "In any case, a TLS server MUST NOT generate an alert if processing an
1183             RSA-encrypted premaster secret message fails, or the version number
1184             is not as expected. Instead, it MUST continue the handshake with a
1185             randomly generated premaster secret. It may be useful to log the
1186             real cause of failure for troubleshooting purposes; however, care
1187             must be taken to avoid leaking the information to an attacker
1188             (through, e.g., timing, log files, or other channels.)"
1189             */
1190 1           rc = psRsaDecryptPriv(ckepkiPool, &ssl->keys->privKey.key.rsa, c,
1191 1           pubKeyLen, ssl->sec.premaster, ssl->sec.premasterSize,
1192             pkiData);
1193             /* Step 1 of Bleichenbacher attack mitigation. We do it here
1194             after the RSA op, but regardless of the result of the op. */
1195 1 50         if (psGetPrngLocked(R, sizeof(R), ssl->userPtr) < 0)
1196             {
1197 0           ssl->err = SSL_ALERT_INTERNAL_ERROR;
1198 0           return MATRIXSSL_ERROR;
1199             }
1200              
1201             /* Step 3
1202             If the PKCS#1 padding is not correct, or the length of message
1203             M is not exactly 48 bytes:
1204             pre_master_secret = ClientHello.client_version || R
1205             else
1206             pre_master_secret = ClientHello.client_version || M[2..47]
1207              
1208             Note that explicitly constructing the pre_master_secret with the
1209             ClientHello.client_version produces an invalid master_secret if the
1210             client has sent the wrong version in the original pre_master_secret.
1211              
1212             Note: The version number in the PreMasterSecret is the version
1213             offered by the client in the ClientHello.client_version, not the
1214             version negotiated for the connection. This feature is designed to
1215             prevent rollback attacks. Unfortunately, some old implementations
1216             use the negotiated version instead, and therefore checking the
1217             version number may lead to failure to interoperate with such
1218             incorrect client implementations. This is known in OpenSSL as the
1219             SSL_OP_TLS_ROLLBACK_BUG. MatrixSSL doesn't support these
1220             incorrect implementations.
1221             */
1222 1           ssl->sec.premaster[0] = ssl->reqMajVer;
1223 1           ssl->sec.premaster[1] = ssl->reqMinVer;
1224 1 50         if (rc < 0)
1225             {
1226 0           memcpy(ssl->sec.premaster + 2, R, sizeof(R));
1227             }
1228             else
1229             {
1230             /* Not necessary, but keep timing similar */
1231 1           memcpy(R, ssl->sec.premaster + 2, sizeof(R));
1232             }
1233              
1234             /* R may contain sensitive data, eg. premaster */
1235 1           memzero_s(R, sizeof(R));
1236              
1237             # else /* RSA is the 'default' so if that didn't get hit there is a problem */
1238             psTraceInfo("There is no handler for ClientKeyExchange parse. ERROR\n");
1239             return MATRIXSSL_ERROR;
1240             # endif /* USE_RSA_CIPHER_SUITE */
1241             # ifdef USE_ECC_CIPHER_SUITE
1242             }
1243             # endif /* USE_ECC_CIPHER_SUITE */
1244             # ifdef USE_PSK_CIPHER_SUITE
1245             }
1246             # endif /* USE_PSK_CIPHER_SUITE */
1247             # ifdef USE_DHE_CIPHER_SUITE
1248             }
1249             # endif /* USE_DHE_CIPHER_SUITE */
1250              
1251             /* Now that we've got the premaster secret, derive the various
1252             symmetric keys using it and the client and server random values.
1253             Update the cached session (if found) with the masterSecret and
1254             negotiated cipher. */
1255 1057 50         if (ssl->extFlags.extended_master_secret == 1)
1256             {
1257 1057 50         if (tlsExtendedDeriveKeys(ssl) < 0)
1258             {
1259 0           return MATRIXSSL_ERROR;
1260             }
1261             }
1262             else
1263             {
1264 0 0         if (sslCreateKeys(ssl) < 0)
1265             {
1266 0           ssl->err = SSL_ALERT_INTERNAL_ERROR;
1267 0           return MATRIXSSL_ERROR;
1268             }
1269             }
1270 1057           matrixUpdateSession(ssl);
1271              
1272 1057           c += pubKeyLen;
1273 1057           ssl->hsState = SSL_HS_FINISHED;
1274              
1275             # ifdef USE_DTLS
1276             /* The freeing of premaster and cert were not done at the normal time
1277             because of the retransmit scenarios. This is server side */
1278             if (ssl->sec.premaster)
1279             {
1280             psFree(ssl->sec.premaster, ssl->hsPool); ssl->sec.premaster = NULL;
1281             ssl->sec.premasterSize = 0;
1282             }
1283             # endif /* USE_DTLS */
1284              
1285             # ifdef USE_CLIENT_AUTH
1286             /* In the non client auth case, we are done with the handshake pool */
1287 1057 50         if (!(ssl->flags & SSL_FLAGS_CLIENT_AUTH))
1288             {
1289             # ifdef USE_DTLS
1290             # ifndef USE_ONLY_PSK_CIPHER_SUITE
1291             if (ssl->sec.cert)
1292             {
1293             psFree(ssl->sec.cert, NULL); ssl->sec.cert = NULL;
1294             }
1295             # endif
1296             if (ssl->ckeMsg != NULL)
1297             {
1298             psFree(ssl->ckeMsg, ssl->hsPool); ssl->ckeMsg = NULL;
1299             }
1300             # endif /* USE_DTLS */
1301 1057           ssl->hsPool = NULL;
1302             }
1303             # else /* CLIENT_AUTH */
1304             # ifdef USE_DTLS
1305             if (ssl->ckeMsg != NULL)
1306             {
1307             psFree(ssl->ckeMsg, ssl->hsPool); ssl->ckeMsg = NULL;
1308             }
1309             # endif /* USE_DTLS */
1310             ssl->hsPool = NULL;
1311             # endif
1312              
1313              
1314             # ifdef USE_CLIENT_AUTH
1315             /* Tweak the state here for client authentication case */
1316 1057 50         if (ssl->flags & SSL_FLAGS_CLIENT_AUTH)
1317             {
1318 0           ssl->hsState = SSL_HS_CERTIFICATE_VERIFY;
1319             }
1320             # endif /* USE_CLIENT_AUTH */
1321              
1322 1057           *cp = c;
1323 1057           ssl->decState = SSL_HS_CLIENT_KEY_EXCHANGE;
1324 1057           return PS_SUCCESS;
1325             }
1326              
1327             /******************************************************************************/
1328              
1329             # ifndef USE_ONLY_PSK_CIPHER_SUITE
1330             # ifdef USE_CLIENT_AUTH
1331 0           int32 parseCertificateVerify(ssl_t *ssl,
1332             unsigned char hsMsgHash[SHA512_HASH_SIZE],
1333             unsigned char **cp, unsigned char *end)
1334             {
1335             uint32 certVerifyLen, pubKeyLen;
1336             int32 rc, i;
1337              
1338             # ifdef USE_RSA
1339             unsigned char certVerify[SHA512_HASH_SIZE];
1340             # endif /* USE_RSA */
1341             unsigned char *c;
1342 0           psPool_t *cvpkiPool = NULL;
1343 0           void *pkiData = ssl->userPtr;
1344              
1345 0           c = *cp;
1346 0           rc = 0;
1347             PS_VARIABLE_SET_BUT_UNUSED(rc); /* Note: Only used ifdef USE_ECC. */
1348             psTraceHs(">>> Server parsing CERTIFICATE_VERIFY message\n");
1349              
1350             # ifdef USE_TLS_1_2
1351 0 0         if (ssl->flags & SSL_FLAGS_TLS_1_2)
1352             {
1353             uint32_t hashSigAlg;
1354              
1355 0 0         if ((uint32) (end - c) < 2)
1356             {
1357 0           ssl->err = SSL_ALERT_DECODE_ERROR;
1358             psTraceInfo("Invalid Certificate Verify message\n");
1359 0           return MATRIXSSL_ERROR;
1360             }
1361 0           hashSigAlg = HASH_SIG_MASK(c[0], c[1]);
1362              
1363             /* The server-sent algorithms has to be one of the ones we sent in
1364             our ClientHello extension */
1365 0 0         if (!(ssl->hashSigAlg & hashSigAlg))
1366             {
1367 0           ssl->err = SSL_ALERT_DECODE_ERROR;
1368             psTraceInfo("Invalid SigHash\n");
1369 0           return MATRIXSSL_ERROR;
1370             }
1371              
1372 0           switch (c[0])
1373             {
1374              
1375             case HASH_SIG_SHA256:
1376 0           certVerifyLen = SHA256_HASH_SIZE;
1377 0           break;
1378              
1379             # ifdef USE_SHA384
1380             case HASH_SIG_SHA384:
1381             /* The one-off grab of SHA-384 handshake hash */
1382 0           sslSha384RetrieveHSHash(ssl, hsMsgHash);
1383 0           certVerifyLen = SHA384_HASH_SIZE;
1384 0           break;
1385             # endif
1386              
1387             # ifdef USE_SHA512
1388             case HASH_SIG_SHA512:
1389             /* The one-off grab of SHA-512 handshake hash */
1390 0           sslSha512RetrieveHSHash(ssl, hsMsgHash);
1391 0           certVerifyLen = SHA512_HASH_SIZE;
1392 0           break;
1393             # endif
1394              
1395             # ifdef USE_SHA1
1396             case HASH_SIG_SHA1:
1397             /* The one-off grab of SHA-1 handshake hash */
1398 0           sslSha1RetrieveHSHash(ssl, hsMsgHash);
1399 0           certVerifyLen = SHA1_HASH_SIZE;
1400 0           break;
1401             # endif
1402             default:
1403 0           ssl->err = SSL_ALERT_DECODE_ERROR;
1404             psTraceInfo("Invalid Certificate Verify message\n");
1405 0           return MATRIXSSL_ERROR;
1406             }
1407 0           c += 2;
1408             }
1409             else
1410             {
1411 0           certVerifyLen = MD5_HASH_SIZE + SHA1_HASH_SIZE;
1412             }
1413             # else
1414             certVerifyLen = MD5_HASH_SIZE + SHA1_HASH_SIZE;
1415             # endif /* USE_TLS_1_2 */
1416              
1417 0 0         if ((uint32) (end - c) < 2)
1418             {
1419 0           ssl->err = SSL_ALERT_DECODE_ERROR;
1420             psTraceInfo("Invalid Certificate Verify message\n");
1421 0           return MATRIXSSL_ERROR;
1422             }
1423 0           pubKeyLen = *c << 8; c++;
1424 0           pubKeyLen |= *c; c++;
1425 0 0         if ((uint32) (end - c) < pubKeyLen)
1426             {
1427 0           ssl->err = SSL_ALERT_DECODE_ERROR;
1428             psTraceInfo("Invalid Certificate Verify message\n");
1429 0           return MATRIXSSL_ERROR;
1430             }
1431             /* The server side verification of client identity. If we can match
1432             the signature we know the client has possesion of the private key. */
1433             # ifdef USE_ECC
1434             /* Need to read sig algorithm type out of cert itself */
1435 0 0         if (ssl->sec.cert->pubKeyAlgorithm == OID_ECDSA_KEY_ALG)
1436             {
1437 0           rc = 0;
1438              
1439             # ifdef USE_TLS_1_2
1440 0 0         if (ssl->flags & SSL_FLAGS_TLS_1_2)
1441             {
1442 0 0         if ((i = psEccDsaVerify(cvpkiPool,
1443 0           &ssl->sec.cert->publicKey.key.ecc,
1444             hsMsgHash, certVerifyLen,
1445             c, pubKeyLen, &rc, pkiData)) != 0)
1446             {
1447             psTraceInfo("ECDSA signature validation failed\n");
1448 0           ssl->err = SSL_ALERT_BAD_CERTIFICATE;
1449 0           return MATRIXSSL_ERROR;
1450             }
1451             }
1452             else
1453             {
1454 0           certVerifyLen = SHA1_HASH_SIZE; /* per spec */
1455 0 0         if ((i = psEccDsaVerify(cvpkiPool,
1456 0           &ssl->sec.cert->publicKey.key.ecc,
1457             hsMsgHash + MD5_HASH_SIZE, certVerifyLen,
1458             c, pubKeyLen,
1459             &rc, pkiData)) != 0)
1460             {
1461             psTraceInfo("ECDSA signature validation failed\n");
1462 0           ssl->err = SSL_ALERT_BAD_CERTIFICATE;
1463 0           return MATRIXSSL_ERROR;
1464             }
1465             }
1466             # else
1467             certVerifyLen = SHA1_HASH_SIZE; /* per spec */
1468             if ((i = psEccDsaVerify(cvpkiPool,
1469             &ssl->sec.cert->publicKey.key.ecc,
1470             hsMsgHash + MD5_HASH_SIZE, certVerifyLen,
1471             c, pubKeyLen,
1472             &rc, pkiData)) != 0)
1473             {
1474             psTraceInfo("ECDSA signature validation failed\n");
1475             ssl->err = SSL_ALERT_BAD_CERTIFICATE;
1476             return MATRIXSSL_ERROR;
1477             }
1478             # endif
1479 0 0         if (rc != 1)
1480             {
1481             psTraceInfo("Can't verify certVerify sig\n");
1482 0           ssl->err = SSL_ALERT_BAD_CERTIFICATE;
1483 0           return MATRIXSSL_ERROR;
1484             }
1485 0           rc = MATRIXSSL_SUCCESS; /* done using rc as a temp */
1486             }
1487             else
1488             {
1489             # endif /* USE_ECC */
1490             # ifdef USE_RSA
1491              
1492             # ifdef USE_TLS_1_2
1493 0 0         if (ssl->flags & SSL_FLAGS_TLS_1_2)
1494             {
1495 0 0         if ((i = pubRsaDecryptSignedElement(cvpkiPool,
1496 0           &ssl->sec.cert->publicKey.key.rsa, c, pubKeyLen, certVerify,
1497             certVerifyLen, pkiData)) < 0)
1498             {
1499             psTraceInfo("Unable to decrypt CertVerify digital element\n");
1500 0           return MATRIXSSL_ERROR;
1501             }
1502             }
1503             else
1504             {
1505 0 0         if ((i = psRsaDecryptPub(cvpkiPool, &ssl->sec.cert->publicKey.key.rsa, c,
1506             pubKeyLen, certVerify, certVerifyLen, pkiData)) < 0)
1507             {
1508             psTraceInfo("Unable to publicly decrypt Certificate Verify message\n");
1509 0           return MATRIXSSL_ERROR;
1510             }
1511             }
1512             # else /* !USE_TLS_1_2 */
1513             if ((i = psRsaDecryptPub(cvpkiPool, &ssl->sec.cert->publicKey.key.rsa, c,
1514             pubKeyLen, certVerify, certVerifyLen, pkiData)) < 0)
1515             {
1516             psTraceInfo("Unable to publicly decrypt Certificate Verify message\n");
1517             return MATRIXSSL_ERROR;
1518             }
1519             # endif /* USE_TLS_1_2 */
1520              
1521 0 0         if (memcmpct(certVerify, hsMsgHash, certVerifyLen) != 0)
1522             {
1523             psTraceInfo("Unable to verify client certificate signature\n");
1524 0           return MATRIXSSL_ERROR;
1525             }
1526             # else /* RSA is 'default' so if that didn't get hit there is a problem */
1527             psTraceInfo("There is no handler for CertificateVerify parse. ERROR\n");
1528             return MATRIXSSL_ERROR;
1529             # endif /* USE_RSA */
1530             # ifdef USE_ECC
1531             }
1532             # endif /* USE_ECC*/
1533              
1534 0           c += pubKeyLen;
1535 0           ssl->hsState = SSL_HS_FINISHED;
1536              
1537 0           *cp = c;
1538 0           ssl->decState = SSL_HS_CERTIFICATE_VERIFY;
1539 0           return PS_SUCCESS;
1540             }
1541             # endif /* !USE_ONLY_PSK_CIPHER_SUITE */
1542             # endif /* USE_ONLY_PSK_CIPHER_SUITE */
1543             #endif /* USE_SERVER_SIDE_SSL */
1544              
1545             /******************************************************************************/
1546              
1547             #ifdef USE_CLIENT_SIDE_SSL
1548 1150           int32 parseServerHello(ssl_t *ssl, int32 hsLen, unsigned char **cp,
1549             unsigned char *end)
1550             {
1551 1150           uint32 sessionIdLen, cipher = 0;
1552             int32 rc;
1553             unsigned char *extData;
1554             unsigned char *c;
1555              
1556 1150           c = *cp;
1557              
1558             psTraceHs(">>> Client parsing SERVER_HELLO message\n");
1559             # ifdef USE_MATRIXSSL_STATS
1560             matrixsslUpdateStat(ssl, SH_RECV_STAT, 1);
1561             # endif
1562             /* Need to track hsLen because there is no explict way to tell if
1563             hello extensions are appended so it isn't clear if the record data
1564             after the compression parameters are a new message or extension data */
1565 1150           extData = c;
1566              
1567             # ifdef USE_DTLS
1568             /* Know now that the allocated members that were helping with the
1569             HELLO_VERIFY_REQUEST exchange have finished serving their purpose */
1570             if (ssl->cookie)
1571             {
1572             psFree(ssl->cookie, ssl->hsPool); ssl->cookie = NULL;
1573             ssl->cookieLen = 0; ssl->haveCookie = 0;
1574             }
1575             if (ssl->helloExt)
1576             {
1577             psFree(ssl->helloExt, ssl->hsPool); ssl->helloExt = NULL;
1578             ssl->helloExtLen = 0;
1579             }
1580             # endif /* USE_DTLS */
1581              
1582             /* First two bytes are the negotiated SSL version */
1583 1150 50         if (end - c < 2)
1584             {
1585 0           ssl->err = SSL_ALERT_DECODE_ERROR;
1586             psTraceInfo("Invalid ssl header version length\n");
1587 0           return MATRIXSSL_ERROR;
1588             }
1589 1150           ssl->reqMajVer = *c; c++;
1590 1150           ssl->reqMinVer = *c; c++;
1591 1150 50         if (ssl->reqMajVer != ssl->majVer)
1592             {
1593 0           ssl->err = SSL_ALERT_PROTOCOL_VERSION;
1594             psTraceIntInfo("Unsupported ssl version: %d\n", ssl->reqMajVer);
1595 0           return MATRIXSSL_ERROR;
1596             }
1597              
1598             # ifdef USE_TLS
1599             /* See if the protocol is being downgraded */
1600 1150 50         if (ssl->reqMinVer != ssl->minVer)
1601             {
1602 0 0         if (ssl->clientRejectVersionDowngrade)
1603             {
1604 0           ssl->err = SSL_ALERT_PROTOCOL_VERSION;
1605             psTraceInfo("Error: version downgrade attempt by server ");
1606             psTraceInfo(" rejected: ServerHello.server_version <");
1607             psTraceInfo(" ClientHello.client_version\n");
1608 0           return MATRIXSSL_ERROR;
1609             }
1610              
1611 0 0         if (ssl->reqMinVer == SSL3_MIN_VER && ssl->minVer >= TLS_MIN_VER)
    0          
1612             {
1613             # ifdef DISABLE_SSLV3
1614 0           ssl->err = SSL_ALERT_PROTOCOL_VERSION;
1615             psTraceInfo("Server wants to talk SSLv3 but it's disabled\n");
1616 0           return MATRIXSSL_ERROR;
1617             # else
1618             /* Server minVer now becomes OUR initial requested version.
1619             This is used during the creation of the premaster where
1620             this initial requested version is part of the calculation.
1621             The RFC actually says to use the original requested version
1622             but no implemenations seem to follow that and just use the
1623             agreed upon one. */
1624             ssl->reqMinVer = ssl->minVer;
1625             ssl->minVer = SSL3_MIN_VER;
1626             ssl->flags &= ~SSL_FLAGS_TLS;
1627             # ifdef USE_TLS_1_1
1628             ssl->flags &= ~SSL_FLAGS_TLS_1_1;
1629             # endif /* USE_TLS_1_1 */
1630             # ifdef USE_TLS_1_2
1631             ssl->flags &= ~SSL_FLAGS_TLS_1_2;
1632             # endif /* USE_TLS_1_2 */
1633             # endif /* DISABLE_SSLV3 */
1634             }
1635             else
1636             {
1637             # ifdef USE_TLS_1_1
1638             # ifdef USE_TLS_1_2
1639             /* Step down one at a time */
1640 0 0         if (ssl->reqMinVer < TLS_1_2_MIN_VER &&
    0          
1641 0           (ssl->flags & SSL_FLAGS_TLS_1_2))
1642             {
1643 0           ssl->flags &= ~SSL_FLAGS_TLS_1_2;
1644 0 0         if (ssl->reqMinVer == TLS_1_1_MIN_VER)
1645             {
1646             # ifdef DISABLE_TLS_1_1
1647             ssl->err = SSL_ALERT_PROTOCOL_VERSION;
1648             psTraceInfo("Server wants to talk TLS1.1 but it's disabled\n");
1649             return MATRIXSSL_ERROR;
1650             # else
1651 0           ssl->reqMinVer = ssl->minVer;
1652 0           ssl->minVer = TLS_1_1_MIN_VER;
1653 0           goto PROTOCOL_DETERMINED;
1654             # endif
1655             }
1656             }
1657             # endif /* USE_TLS_1_2 */
1658 0 0         if (ssl->reqMinVer == TLS_MIN_VER &&
    0          
1659 0           ssl->minVer <= TLS_1_2_MIN_VER)
1660             {
1661             # ifdef DISABLE_TLS_1_0
1662             ssl->err = SSL_ALERT_PROTOCOL_VERSION;
1663             psTraceInfo("Server wants to talk TLS1.0 but it's disabled\n");
1664             return MATRIXSSL_ERROR;
1665             # else
1666 0           ssl->reqMinVer = ssl->minVer;
1667 0           ssl->minVer = TLS_MIN_VER;
1668 0           ssl->flags &= ~SSL_FLAGS_TLS_1_1;
1669             # endif
1670             }
1671             else
1672             {
1673             # endif /* USE_TLS_1_1 */
1674             # ifdef USE_DTLS
1675             /* Tests for DTLS downgrades */
1676             if (ssl->flags & SSL_FLAGS_DTLS)
1677             {
1678             if (ssl->reqMinVer == DTLS_MIN_VER &&
1679             ssl->minVer == DTLS_1_2_MIN_VER)
1680             {
1681             ssl->reqMinVer = ssl->minVer;
1682             ssl->minVer = DTLS_MIN_VER;
1683             ssl->flags &= ~SSL_FLAGS_TLS_1_2;
1684             goto PROTOCOL_DETERMINED;
1685             }
1686             }
1687             # endif
1688             /* Wasn't able to settle on a common protocol */
1689 0           ssl->err = SSL_ALERT_PROTOCOL_VERSION;
1690             psTraceIntInfo("Unsupported ssl version: %d\n",
1691             ssl->reqMajVer);
1692 0           return MATRIXSSL_ERROR;
1693             # ifdef USE_TLS_1_1
1694             }
1695             # endif /* USE_TLS_1_1 */
1696             }
1697             }
1698             # endif /* USE_TLS */
1699              
1700             # if (defined (USE_TLS_1_2) && !defined(DISABLE_TLS_1_1)) || defined (USE_DTLS)
1701             PROTOCOL_DETERMINED:
1702             # endif /* (USE_TLS_1_2 && !DISABLE_TLS_1_1) || USE_DTLS */
1703              
1704             /* Next is a 32 bytes of random data for key generation
1705             and a single byte with the session ID length */
1706 1150 50         if (end - c < SSL_HS_RANDOM_SIZE + 1)
1707             {
1708 0           ssl->err = SSL_ALERT_DECODE_ERROR;
1709             psTraceInfo("Invalid length of random data\n");
1710 0           return MATRIXSSL_ERROR;
1711             }
1712 1150           memcpy(ssl->sec.serverRandom, c, SSL_HS_RANDOM_SIZE);
1713 1150           c += SSL_HS_RANDOM_SIZE;
1714 1150           sessionIdLen = *c; c++;
1715 1150 50         if (sessionIdLen > SSL_MAX_SESSION_ID_SIZE ||
    50          
1716 1150           (uint32) (end - c) < sessionIdLen)
1717             {
1718 0           ssl->err = SSL_ALERT_DECODE_ERROR;
1719 0           return MATRIXSSL_ERROR;
1720             }
1721             /* If a session length was specified, the server has sent us a
1722             session Id. We may have requested a specific session, and the
1723             server may or may not agree to use that session. */
1724 1150 50         if (sessionIdLen > 0)
1725             {
1726 1150 100         if (ssl->sessionIdLen > 0)
1727             {
1728 2 50         if (memcmp(ssl->sessionId, c, sessionIdLen) == 0)
1729             {
1730 2           ssl->flags |= SSL_FLAGS_RESUMED;
1731             }
1732             else
1733             {
1734 0           ssl->cipher = sslGetCipherSpec(ssl, SSL_NULL_WITH_NULL_NULL);
1735 0           memset(ssl->sec.masterSecret, 0x0, SSL_HS_MASTER_SIZE);
1736 0           ssl->sessionIdLen = (unsigned char) sessionIdLen;
1737 0           memcpy(ssl->sessionId, c, sessionIdLen);
1738 2           ssl->flags &= ~SSL_FLAGS_RESUMED;
1739             # ifdef USE_MATRIXSSL_STATS
1740             matrixsslUpdateStat(ssl, FAILED_RESUMPTIONS_STAT, 1);
1741             # endif
1742             }
1743             # ifdef USE_EAP_FAST /* TODO Could also do this for any TICKET */
1744             if (ssl->sid->sessionTicketState == SESS_TICKET_STATE_SENT_TICKET)
1745             {
1746             if (ssl->flags & SSL_FLAGS_RESUMED)
1747             {
1748             /* The server has accepted our session ticket, and indicated that
1749             by echoing the random session id we sent. */
1750             ssl->extFlags.eap_fast_master_secret = 1;
1751             /* TODO could derive eap keys here */
1752             }
1753             else
1754             {
1755             /* The server isn't going to use our ticket. But may still
1756             send a ticket extension and (possibly blank) ticket message */
1757             ssl->extFlags.eap_fast_master_secret = 0;
1758             }
1759             }
1760             # endif
1761             }
1762             else
1763             {
1764 1148           ssl->sessionIdLen = (unsigned char) sessionIdLen;
1765 1148           memcpy(ssl->sessionId, c, sessionIdLen);
1766             }
1767 1150           c += sessionIdLen;
1768             }
1769             else
1770             {
1771 0 0         if (ssl->sessionIdLen > 0)
1772             {
1773 0           ssl->cipher = sslGetCipherSpec(ssl, SSL_NULL_WITH_NULL_NULL);
1774 0           memset(ssl->sec.masterSecret, 0x0, SSL_HS_MASTER_SIZE);
1775 0           ssl->sessionIdLen = 0;
1776 0           memset(ssl->sessionId, 0x0, SSL_MAX_SESSION_ID_SIZE);
1777 0           ssl->flags &= ~SSL_FLAGS_RESUMED;
1778             # ifdef USE_MATRIXSSL_STATS
1779             matrixsslUpdateStat(ssl, FAILED_RESUMPTIONS_STAT, 1);
1780             # endif
1781             }
1782             }
1783             /* Next is the two byte cipher suite */
1784 1150 50         if (end - c < 2)
1785             {
1786 0           ssl->err = SSL_ALERT_DECODE_ERROR;
1787             psTraceInfo("Invalid cipher suite length\n");
1788 0           return MATRIXSSL_ERROR;
1789             }
1790 1150           cipher = *c << 8; c++;
1791 1150           cipher += *c; c++;
1792              
1793             /* A resumed session can only match the cipher originally
1794             negotiated. Otherwise, match the first cipher that we support */
1795 1150 100         if (ssl->flags & SSL_FLAGS_RESUMED)
1796             {
1797 2 50         psAssert(ssl->cipher != NULL);
1798 2 50         if (ssl->cipher->ident != cipher)
1799             {
1800 0           ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
1801             psTraceInfo("Can't support resumed cipher\n");
1802 0           return MATRIXSSL_ERROR;
1803             }
1804             }
1805             else
1806             {
1807 1148 50         if ((ssl->cipher = sslGetCipherSpec(ssl, cipher)) == NULL)
1808             {
1809 0           ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
1810             psTraceIntInfo("Can't support requested cipher: %d\n", cipher);
1811 0           return MATRIXSSL_ERROR;
1812             }
1813             }
1814 1150           matrixSslSetKexFlags(ssl);
1815              
1816             /* Decode the compression parameter byte. */
1817             # define COMPRESSION_METHOD_NULL 0x0
1818             # define COMPRESSION_METHOD_DEFLATE 0x1
1819 1150 50         if (end - c < 1)
1820             {
1821 0           ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
1822             psTraceInfo("Expected compression value\n");
1823 0           return MATRIXSSL_ERROR;
1824             }
1825 1150 50         switch (*c)
1826             {
1827             case COMPRESSION_METHOD_NULL:
1828             /* No compression */
1829 1150           break;
1830             # ifdef USE_ZLIB_COMPRESSION
1831             case COMPRESSION_METHOD_DEFLATE:
1832             ssl->inflate.zalloc = NULL;
1833             ssl->inflate.zfree = NULL;
1834             ssl->inflate.opaque = NULL;
1835             ssl->inflate.avail_in = 0;
1836             ssl->inflate.next_in = NULL;
1837             if (inflateInit(&ssl->inflate) != Z_OK)
1838             {
1839             psTraceInfo("inflateInit fail. No compression\n");
1840             }
1841             else
1842             {
1843             ssl->deflate.zalloc = Z_NULL;
1844             ssl->deflate.zfree = Z_NULL;
1845             ssl->deflate.opaque = Z_NULL;
1846             if (deflateInit(&ssl->deflate, Z_DEFAULT_COMPRESSION) != Z_OK)
1847             {
1848             psTraceInfo("deflateInit fail. No compression\n");
1849             inflateEnd(&ssl->inflate);
1850             }
1851             else
1852             {
1853             ssl->compression = 1; /* Both contexts initialized */
1854             }
1855             }
1856             break;
1857             # endif /* USE_ZLIB_COMPRESSION */
1858             default:
1859 0           ssl->err = SSL_ALERT_DECODE_ERROR;
1860             psTraceInfo("zlib compression not enabled.\n");
1861 0           return MATRIXSSL_ERROR;
1862             }
1863             /* At this point, if we're resumed, we have all the required info
1864             to derive keys. The next handshake message we expect is
1865             the Finished message.
1866             After incrementing c below, we will either be pointing at 'end'
1867             with no more data in the message, or at the first byte of an optional
1868             extension. */
1869 1150           c++;
1870              
1871             /* If our sent ClientHello had an extension there could be extension data
1872             to parse here: http://www.faqs.org/rfcs/rfc3546.html
1873              
1874             The explict test on hsLen is necessary for TLS 1.0 and 1.1 because
1875             there is no good way to tell if the remaining record data is the
1876             next handshake message or if it is extension data */
1877 1150 50         if (c != end && ((int32) hsLen > (c - extData)))
    50          
1878             {
1879 1150           rc = parseServerHelloExtensions(ssl, hsLen, extData, &c, c - end);
1880 1150 50         if (rc < 0)
1881             {
1882             /* Alerts will already have been set inside */
1883 0           return rc;
1884             }
1885             }
1886              
1887             # ifdef USE_OCSP_MUST_STAPLE
1888             /* Will catch cases where a server does not send any extensions at all */
1889 1150 50         if (ssl->extFlags.req_status_request == 1)
1890             {
1891 0 0         if (ssl->extFlags.status_request == 0)
1892             {
1893             psTraceInfo("Server doesn't support OCSP stapling\n");
1894 0           ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
1895 0           return MATRIXSSL_ERROR;
1896             }
1897             }
1898             # endif
1899              
1900 1150 50         if (ssl->maxPtFrag & 0x10000 || ssl->extFlags.req_max_fragment_len)
    50          
1901             {
1902             /* Server didn't respond to our MAX_FRAG request. Reset default */
1903             psTraceInfo("Server ignored max fragment length ext request\n");
1904 0           ssl->maxPtFrag = SSL_MAX_PLAINTEXT_LEN;
1905             }
1906              
1907 1150           if (ssl->extFlags.req_sni)
1908             {
1909             psTraceInfo("Server ignored SNI ext request\n");
1910             }
1911              
1912             # ifdef USE_STATELESS_SESSION_TICKETS
1913 1150 100         if (ssl->sid &&
    50          
1914 510           ssl->sid->sessionTicketState == SESS_TICKET_STATE_SENT_TICKET)
1915             {
1916             /*
1917             Server did not send an extension reply to our populated ticket.
1918              
1919             From the updated RFC 5077:
1920              
1921             "It is also permissible to have an exchange using the
1922             abbreviated handshake defined in Figure 2 of RFC 4346, where
1923             the client uses the SessionTicket extension to resume the
1924             session, but the server does not wish to issue a new ticket,
1925             and therefore does not send a SessionTicket extension."
1926              
1927             Lame. We don't get an indication that the server accepted or
1928             rejected our ticket until we see the next handshake message.
1929             If they accepted it we'll see a ChangeCipherSpec message and
1930             if they rejected it we'll see a Certificate message. Let's
1931             flag this case of a non-response and handle it in the CCS parse.
1932              
1933             TODO - could also send a sessionId and see if it is returned here.
1934             Spec requires the same sessionId to be returned if ticket is accepted.
1935             */
1936 0           ssl->sid->sessionTicketState = SESS_TICKET_STATE_IN_LIMBO;
1937             }
1938             # endif /* USE_STATELESS_SESSION_TICKETS */
1939              
1940              
1941             # if 0 /* TODO moved to extDecode:parseServerHelloExtensions */
1942             # ifdef ENABLE_SECURE_REHANDSHAKES
1943             if (renegotiationExt == 0)
1944             {
1945             # ifdef REQUIRE_SECURE_REHANDSHAKES
1946             ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
1947             psTraceInfo("Srv doesn't support renegotiationInfo\n");
1948             return MATRIXSSL_ERROR;
1949             # else
1950             if (ssl->secureRenegotiationFlag == PS_TRUE)
1951             {
1952             ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
1953             psTraceInfo("Srv didn't send renegotiationInfo on re-hndshk\n");
1954             return MATRIXSSL_ERROR;
1955             }
1956             # ifndef ENABLE_INSECURE_REHANDSHAKES
1957             /* This case can only be hit if ENABLE_SECURE is on because otherwise
1958             we wouldn't even have got this far because both would be off. */
1959             if (ssl->secureRenegotiationFlag == PS_FALSE &&
1960             ssl->myVerifyDataLen > 0)
1961             {
1962             ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
1963             psTraceInfo("Srv attempting insecure renegotiation\n");
1964             return MATRIXSSL_ERROR;
1965             }
1966             # endif /* !ENABLE_SECURE_REHANDSHAKES */
1967             # endif /* REQUIRE_SECURE_REHANDSHAKES */
1968             }
1969             # endif /* ENABLE_SECURE_REHANDSHAKES */
1970             # endif
1971              
1972 1150 100         if (ssl->flags & SSL_FLAGS_RESUMED)
1973             {
1974 2 50         if (sslCreateKeys(ssl) < 0)
1975             {
1976 0           ssl->err = SSL_ALERT_INTERNAL_ERROR;
1977 0           return MATRIXSSL_ERROR;
1978             }
1979 2           ssl->hsState = SSL_HS_FINISHED;
1980             }
1981             else
1982             {
1983 1148           ssl->hsState = SSL_HS_CERTIFICATE;
1984             # ifdef USE_ANON_DH_CIPHER_SUITE
1985             /* Anonymous DH uses SERVER_KEY_EXCHANGE message to send key params */
1986 1148 50         if (ssl->flags & SSL_FLAGS_ANON_CIPHER)
1987             {
1988 0           ssl->hsState = SSL_HS_SERVER_KEY_EXCHANGE;
1989             }
1990             # endif /* USE_ANON_DH_CIPHER_SUITE */
1991             # ifdef USE_PSK_CIPHER_SUITE
1992             /* PSK ciphers never send a CERTIFICATE message. */
1993 1148 50         if (ssl->flags & SSL_FLAGS_PSK_CIPHER)
1994             {
1995 0           ssl->hsState = SSL_HS_SERVER_KEY_EXCHANGE;
1996             }
1997             # endif /* USE_PSK_CIPHER_SUITE */
1998             }
1999              
2000 1150           *cp = c;
2001 1150           ssl->decState = SSL_HS_SERVER_HELLO;
2002 1150           return PS_SUCCESS;
2003             }
2004              
2005             /******************************************************************************/
2006              
2007 1057           int32 parseServerKeyExchange(ssl_t *ssl,
2008             unsigned char hsMsgHash[SHA512_HASH_SIZE],
2009             unsigned char **cp, unsigned char *end)
2010             {
2011             unsigned char *c;
2012              
2013             # ifdef USE_DHE_CIPHER_SUITE
2014             int32 i;
2015             uint32 pubDhLen, hashSize;
2016 1057           psPool_t *skepkiPool = NULL;
2017             # ifndef USE_ONLY_PSK_CIPHER_SUITE
2018             psDigestContext_t digestCtx;
2019 1057           unsigned char *sigStart = NULL, *sigStop = NULL;
2020             # endif /* USE_ONLY_PSK_CIPHER_SUITE */
2021             # ifdef USE_TLS_1_2
2022             uint32 skeHashSigAlg;
2023             # endif
2024             # ifdef USE_RSA_CIPHER_SUITE
2025             unsigned char sigOut[MAX_HASH_SIZE];
2026             # endif
2027             # ifdef USE_ECC_CIPHER_SUITE
2028             uint32 res;
2029             const psEccCurve_t *curve;
2030             # endif
2031 1057           void *pkiData = ssl->userPtr;
2032              
2033             # endif /* USE_DHE_CIPHER_SUITE */
2034              
2035 1057           c = *cp;
2036              
2037             psTraceHs(">>> Client parsing SERVER_KEY_EXCHANGE message\n");
2038             # ifdef USE_DHE_CIPHER_SUITE
2039             /* Check the DH status. Could also be a PSK_DHE suite */
2040 1057 50         if (ssl->flags & SSL_FLAGS_DHE_KEY_EXCH)
2041             {
2042              
2043             # ifdef USE_PSK_CIPHER_SUITE
2044 1057 50         if (ssl->flags & SSL_FLAGS_PSK_CIPHER)
2045             {
2046             /* Using the value of MAX_HINT_SIZE to know if the user is
2047             expecting a hint. The PSK specification ONLY allows these
2048             hints if the "application profile specification" says to
2049             include them.
2050              
2051             Contact Support if you require assistance here */
2052             if (SSL_PSK_MAX_HINT_SIZE > 0)
2053             {
2054 0 0         if ((end - c) < 2)
2055             {
2056 0           ssl->err = SSL_ALERT_DECODE_ERROR;
2057             psTraceInfo("Invalid PSK Hint Len\n");
2058 0           return MATRIXSSL_ERROR;
2059             }
2060 0           ssl->sec.hintLen = *c << 8; c++;
2061 0           ssl->sec.hintLen |= *c; c++;
2062 0 0         if (ssl->sec.hintLen > 0)
2063             {
2064 0 0         if ((unsigned short) (end - c) < ssl->sec.hintLen)
2065             {
2066 0           ssl->err = SSL_ALERT_DECODE_ERROR;
2067             psTraceInfo("Invalid PSK Hint\n");
2068 0           return MATRIXSSL_ERROR;
2069             }
2070 0           ssl->sec.hint = psMalloc(ssl->hsPool, ssl->sec.hintLen);
2071 0 0         if (ssl->sec.hint == NULL)
2072             {
2073 0           return SSL_MEM_ERROR;
2074             }
2075 0           memcpy(ssl->sec.hint, c, ssl->sec.hintLen);
2076 0           c += ssl->sec.hintLen;
2077             }
2078             }
2079             }
2080             # endif /* USE_PSK_CIPHER_SUITE */
2081             # ifdef USE_ECC_CIPHER_SUITE
2082 1057 50         if (ssl->flags & SSL_FLAGS_ECC_CIPHER)
2083             {
2084             /* Entry point for ECDHE SKE parsing */
2085 1057           sigStart = c;
2086 1057 50         if ((end - c) < 4) /* ECCurveType, NamedCurve, ECPoint len */
2087             {
2088 0           ssl->err = SSL_ALERT_DECODE_ERROR;
2089             psTraceInfo("Invalid ServerKeyExchange message\n");
2090 0           return MATRIXSSL_ERROR;
2091             }
2092             /*
2093             Only named curves are currently supported
2094              
2095             enum { explicit_prime (1), explicit_char2 (2),
2096             named_curve (3), reserved(248..255) } ECCurveType;
2097             */
2098 1057 50         if ((int32) * c != 3)
2099             {
2100 0           ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
2101             psTraceIntInfo("Unsupported ECCurveType message %d\n",
2102             (int32) * c);
2103 0           return MATRIXSSL_ERROR;
2104             }
2105 1057           c++;
2106              
2107             /* Next is curveId */
2108 1057           i = *c << 8; c++;
2109 1057           i |= *c; c++;
2110              
2111             /* Return -1 if this isn't a curve we specified in client hello */
2112 1057 50         if (getEccParamById(i, &curve) < 0)
2113             {
2114 0           ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
2115             psTraceIntInfo("Error: Could not match EC curve: %d\n", i);
2116 0           return MATRIXSSL_ERROR;
2117             }
2118             /*
2119             struct {
2120             opaque point <1..2^8-1>;
2121             } ECPoint;
2122              
2123             RFC4492
2124             This is the byte string representation of an elliptic curve
2125             point following the conversion routine in Section 4.3.6 of ANSI
2126             X9.62. This byte string may represent an elliptic curve point
2127             in uncompressed or compressed format; it MUST conform to what
2128             client has requested through a Supported Point Formats Extension
2129             if this extension was used.
2130             */
2131 1057           i = *c; c++;
2132 1057 50         if ((end - c) < i)
2133             {
2134 0           ssl->err = SSL_ALERT_DECODE_ERROR;
2135             psTraceInfo("Invalid ServerKeyExchange message\n");
2136 0           return MATRIXSSL_ERROR;
2137             }
2138 1057 50         if (psEccNewKey(ssl->hsPool, &ssl->sec.eccKeyPub, curve) < 0)
2139             {
2140 0           return SSL_MEM_ERROR;
2141             }
2142 1057 50         if (psEccX963ImportKey(ssl->hsPool, c, i,
2143             ssl->sec.eccKeyPub, curve) < 0)
2144             {
2145 0           ssl->err = SSL_ALERT_DECODE_ERROR;
2146 0           return MATRIXSSL_ERROR;
2147             }
2148 1057           c += i;
2149 1057           sigStop = c;
2150              
2151             }
2152             else
2153             {
2154             # endif /* USE_ECC_CIPHER_SUITE */
2155             # ifdef REQUIRE_DH_PARAMS
2156             /* Entry point for standard DH SKE parsing */
2157 0 0         if ((end - c) < 2)
2158             {
2159 0           ssl->err = SSL_ALERT_DECODE_ERROR;
2160             psTraceInfo("Invalid ServerKeyExchange message\n");
2161 0           return MATRIXSSL_ERROR;
2162             }
2163             # ifndef USE_ONLY_PSK_CIPHER_SUITE
2164 0           sigStart = c;
2165             # endif
2166 0           ssl->sec.dhPLen = *c << 8; c++;
2167 0           ssl->sec.dhPLen |= *c; c++;
2168 0 0         if ((uint32) (end - c) < ssl->sec.dhPLen)
2169             {
2170 0           ssl->err = SSL_ALERT_DECODE_ERROR;
2171             psTraceInfo("Invalid ServerKeyExchange message\n");
2172 0           return MATRIXSSL_ERROR;
2173             }
2174 0           ssl->sec.dhP = psMalloc(ssl->hsPool, ssl->sec.dhPLen);
2175 0 0         if (ssl->sec.dhP == NULL)
2176             {
2177 0           return SSL_MEM_ERROR;
2178             }
2179 0           memcpy(ssl->sec.dhP, c, ssl->sec.dhPLen);
2180 0           c += ssl->sec.dhPLen;
2181              
2182 0           ssl->sec.dhGLen = *c << 8; c++;
2183 0           ssl->sec.dhGLen |= *c; c++;
2184 0 0         if ((uint32) (end - c) < ssl->sec.dhGLen)
2185             {
2186 0           ssl->err = SSL_ALERT_DECODE_ERROR;
2187             psTraceInfo("Invalid ServerKeyExchange message\n");
2188 0           return MATRIXSSL_ERROR;
2189             }
2190 0           ssl->sec.dhG = psMalloc(ssl->hsPool, ssl->sec.dhGLen);
2191 0 0         if (ssl->sec.dhG == NULL)
2192             {
2193 0           return SSL_MEM_ERROR;
2194             }
2195 0           memcpy(ssl->sec.dhG, c, ssl->sec.dhGLen);
2196 0           c += ssl->sec.dhGLen;
2197              
2198 0           pubDhLen = *c << 8; c++;
2199 0           pubDhLen |= *c; c++;
2200              
2201 0 0         if ((uint32) (end - c) < pubDhLen)
2202             {
2203 0           ssl->err = SSL_ALERT_DECODE_ERROR;
2204             psTraceInfo("Invalid ServerKeyExchange message\n");
2205 0           return MATRIXSSL_ERROR;
2206             }
2207             /*
2208             The next bit on the wire is the public key. Assign to
2209             the session in structure format
2210             */
2211 0 0         if ((ssl->sec.dhKeyPub = psMalloc(ssl->hsPool, sizeof(psDhKey_t))) == NULL)
2212             {
2213 0           return MATRIXSSL_ERROR;
2214             }
2215 0 0         if (psDhImportPubKey(ssl->hsPool, c, pubDhLen,
2216             ssl->sec.dhKeyPub) < 0)
2217             {
2218 0           psFree(ssl->sec.dhKeyPub, ssl->hsPool);
2219 0           ssl->sec.dhKeyPub = NULL;
2220 0           return MATRIXSSL_ERROR;
2221             }
2222 0           c += pubDhLen;
2223             # ifndef USE_ONLY_PSK_CIPHER_SUITE
2224 0           sigStop = c;
2225             # endif
2226             /*
2227             Key size is now known for premaster storage. The extra byte
2228             is to account for the cases where the pubkey length ends
2229             up being a byte less than the premaster. The premaster size
2230             is adjusted accordingly when the actual secret is generated.
2231             */
2232 0           ssl->sec.premasterSize = ssl->sec.dhPLen;
2233             # ifdef USE_PSK_CIPHER_SUITE
2234 0 0         if (ssl->flags & SSL_FLAGS_PSK_CIPHER)
2235             {
2236             /*
2237             In the PSK case, the true premaster size is still unknown
2238             but didn't want to change the allocation logic so just
2239             make sure the size is large enough for the additional
2240             PSK and length bytes
2241             */
2242 0           ssl->sec.premasterSize += SSL_PSK_MAX_KEY_SIZE + 4;
2243             }
2244             # endif /* USE_PSK_CIPHER_SUITE */
2245 0           ssl->sec.premaster = psMalloc(ssl->hsPool, ssl->sec.premasterSize);
2246 0 0         if (ssl->sec.premaster == NULL)
2247             {
2248 0           return SSL_MEM_ERROR;
2249             }
2250             # ifdef USE_ANON_DH_CIPHER_SUITE
2251 0 0         if (ssl->flags & SSL_FLAGS_ANON_CIPHER)
2252             {
2253             /*
2254             In the anonymous case, there is no signature to follow
2255             */
2256 0           ssl->hsState = SSL_HS_SERVER_HELLO_DONE;
2257 0           *cp = c;
2258 0           ssl->decState = SSL_HS_SERVER_KEY_EXCHANGE;
2259 0           return PS_SUCCESS;
2260             }
2261             # endif /* USE_ANON_DH_CIPHER_SUITE */
2262             # endif /* REQUIRE_DH_PARAMS */
2263             # ifdef USE_ECC_CIPHER_SUITE
2264             }
2265             # endif /* USE_ECC_CIPHER_SUITE */
2266             /*
2267             This layer of authentation is at the key exchange level.
2268             The server has sent a signature of the key material that
2269             the client can validate here.
2270             */
2271 1057 50         if ((end - c) < 2)
2272             {
2273 0           ssl->err = SSL_ALERT_DECODE_ERROR;
2274             psTraceInfo("Invalid ServerKeyExchange message\n");
2275 0           return MATRIXSSL_ERROR;
2276             }
2277              
2278             # ifdef USE_TLS_1_2
2279 1057           hashSize = 0;
2280 1057 50         if (ssl->flags & SSL_FLAGS_TLS_1_2)
2281             {
2282 1057           skeHashSigAlg = *c << 8; c++;
2283 1057           skeHashSigAlg += *c; c++;
2284 1057 50         if ((skeHashSigAlg >> 8) == 0x4)
2285             {
2286 1057           hashSize = SHA256_HASH_SIZE;
2287             }
2288 0 0         else if ((skeHashSigAlg >> 8) == 0x5)
2289             {
2290 0           hashSize = SHA384_HASH_SIZE;
2291             }
2292 0 0         else if ((skeHashSigAlg >> 8) == 0x6)
2293             {
2294 0           hashSize = SHA512_HASH_SIZE;
2295             }
2296 0 0         else if ((skeHashSigAlg >> 8) == 0x2)
2297             {
2298 0           hashSize = SHA1_HASH_SIZE;
2299             }
2300             else
2301             {
2302             psTraceIntInfo("Unsupported hashAlg SKE parse: %d\n",
2303             skeHashSigAlg);
2304 0           return MATRIXSSL_ERROR;
2305             }
2306             }
2307             # endif /* USE_TLS_1_2 */
2308 1057           pubDhLen = *c << 8; c++; /* Reusing variable */
2309 1057           pubDhLen |= *c; c++;
2310              
2311 1057 50         if ((uint32) (end - c) < pubDhLen)
2312             {
2313 0           ssl->err = SSL_ALERT_DECODE_ERROR;
2314             psTraceInfo("Invalid ServerKeyExchange message\n");
2315 0           return MATRIXSSL_ERROR;
2316             }
2317              
2318             # ifdef USE_RSA_CIPHER_SUITE
2319 1057 50         if (ssl->flags & SSL_FLAGS_DHE_WITH_RSA)
2320             {
2321             /*
2322             We are using the public key provided by the server during the
2323             CERTIFICATE message. That cert has already been authenticated
2324             by this point so this signature is to ensure that entity is also
2325             the one negotiating keys with us.
2326             */
2327             # ifdef USE_TLS_1_2
2328             /* TLS 1.2 uses single hashes everywhere */
2329 1057 50         if (ssl->flags & SSL_FLAGS_TLS_1_2)
2330             {
2331 1057 50         if (hashSize == SHA256_HASH_SIZE)
2332             {
2333 1057           psSha256PreInit(&digestCtx.sha256);
2334 1057           psSha256Init(&digestCtx.sha256);
2335 1057           psSha256Update(&digestCtx.sha256, ssl->sec.clientRandom,
2336             SSL_HS_RANDOM_SIZE);
2337 1057           psSha256Update(&digestCtx.sha256, ssl->sec.serverRandom,
2338             SSL_HS_RANDOM_SIZE);
2339 1057           psSha256Update(&digestCtx.sha256, sigStart,
2340 1057           (uint32) (sigStop - sigStart));
2341 1057           psSha256Final(&digestCtx.sha256, hsMsgHash);
2342             # ifdef USE_SHA384
2343             }
2344 0 0         else if (hashSize == SHA384_HASH_SIZE)
2345             {
2346 0           psSha384PreInit(&digestCtx.sha384);
2347 0           psSha384Init(&digestCtx.sha384);
2348 0           psSha384Update(&digestCtx.sha384, ssl->sec.clientRandom,
2349             SSL_HS_RANDOM_SIZE);
2350 0           psSha384Update(&digestCtx.sha384, ssl->sec.serverRandom,
2351             SSL_HS_RANDOM_SIZE);
2352 0           psSha384Update(&digestCtx.sha384, sigStart,
2353 0           (uint32) (sigStop - sigStart));
2354 0           psSha384Final(&digestCtx.sha384, hsMsgHash);
2355             # endif /* USE_SHA384 */
2356             # ifdef USE_SHA512
2357             }
2358 0 0         else if (hashSize == SHA512_HASH_SIZE)
2359             {
2360 0           psSha512PreInit(&digestCtx.sha512);
2361 0           psSha512Init(&digestCtx.sha512);
2362 0           psSha512Update(&digestCtx.sha512, ssl->sec.clientRandom,
2363             SSL_HS_RANDOM_SIZE);
2364 0           psSha512Update(&digestCtx.sha512, ssl->sec.serverRandom,
2365             SSL_HS_RANDOM_SIZE);
2366 0           psSha512Update(&digestCtx.sha512, sigStart,
2367 0           (uint32) (sigStop - sigStart));
2368 0           psSha512Final(&digestCtx.sha512, hsMsgHash);
2369             # endif /* USE_SHA512 */
2370             # ifdef USE_SHA1
2371             }
2372 0 0         else if (hashSize == SHA1_HASH_SIZE)
2373             {
2374 0           psSha1PreInit(&digestCtx.sha1);
2375 0           psSha1Init(&digestCtx.sha1);
2376 0           psSha1Update(&digestCtx.sha1, ssl->sec.clientRandom,
2377             SSL_HS_RANDOM_SIZE);
2378 0           psSha1Update(&digestCtx.sha1, ssl->sec.serverRandom,
2379             SSL_HS_RANDOM_SIZE);
2380 0           psSha1Update(&digestCtx.sha1, sigStart,
2381 0           (uint32) (sigStop - sigStart));
2382 0           psSha1Final(&digestCtx.sha1, hsMsgHash);
2383             # endif
2384             }
2385             else
2386             {
2387 0           return MATRIXSSL_ERROR;
2388             }
2389              
2390             }
2391             else
2392             {
2393             # ifdef USE_MD5SHA1
2394 0           psMd5Sha1PreInit(&digestCtx.md5sha1);
2395 0           psMd5Sha1Init(&digestCtx.md5sha1);
2396 0           psMd5Sha1Update(&digestCtx.md5sha1, ssl->sec.clientRandom,
2397             SSL_HS_RANDOM_SIZE);
2398 0           psMd5Sha1Update(&digestCtx.md5sha1, ssl->sec.serverRandom,
2399             SSL_HS_RANDOM_SIZE);
2400 0           psMd5Sha1Update(&digestCtx.md5sha1, sigStart,
2401 0           (uint32) (sigStop - sigStart));
2402 0           psMd5Sha1Final(&digestCtx.md5sha1, hsMsgHash);
2403             # else /* USE_MD5SHA1 */
2404             psTraceInfo("USE_MD5SHA1 required\n");
2405             return MATRIXSSL_ERROR;
2406             # endif /* USE_MD5SHA1 */
2407             }
2408             # else /* USE_TLS_1_2 */
2409             /*
2410             The signature portion is an MD5 and SHA1 concat of the randoms
2411             and the contents of this server key exchange message.
2412             */
2413             # ifdef USE_MD5SHA1
2414             psMd5Sha1PreInit(&digestCtx.md5sha1);
2415             psMd5Sha1Init(&digestCtx.md5sha1);
2416             psMd5Sha1Update(&digestCtx.md5sha1, ssl->sec.clientRandom,
2417             SSL_HS_RANDOM_SIZE);
2418             psMd5Sha1Update(&digestCtx.md5sha1, ssl->sec.serverRandom,
2419             SSL_HS_RANDOM_SIZE);
2420             psMd5Sha1Update(&digestCtx.md5sha1, sigStart,
2421             (uint32) (c - sigStart));
2422             psMd5Sha1Final(&digestCtx.md5sha1, hsMsgHash);
2423             # else
2424             psTraceInfo("USE_MD5SHA1 required\n");
2425             return MATRIXSSL_ERROR;
2426             # endif /* USE_MD5SHA1 */
2427             # endif /* USE_TLS_1_2 */
2428              
2429              
2430             # ifdef USE_TLS_1_2
2431 1057 50         if (ssl->flags & SSL_FLAGS_TLS_1_2)
2432             {
2433             /* TLS 1.2 doesn't just sign the straight hash so we can't
2434             pass it through the normal public decryption becuase
2435             that expects an output length of a known size. These
2436             signatures are done on elements with some ASN.1
2437             wrapping so a special decryption with parse is needed */
2438 1057 50         if ((i = pubRsaDecryptSignedElement(skepkiPool,
2439 1057           &ssl->sec.cert->publicKey.key.rsa, c, pubDhLen, sigOut,
2440             hashSize, pkiData)) < 0)
2441             {
2442              
2443             psTraceInfo("Can't decrypt serverKeyExchange sig\n");
2444 0           ssl->err = SSL_ALERT_BAD_CERTIFICATE;
2445 0           return MATRIXSSL_ERROR;
2446             }
2447              
2448             }
2449             else
2450             {
2451 0           hashSize = MD5_HASH_SIZE + SHA1_HASH_SIZE;
2452              
2453 0 0         if ((i = psRsaDecryptPub(skepkiPool,
2454 0           &ssl->sec.cert->publicKey.key.rsa, c, pubDhLen, sigOut,
2455             hashSize, pkiData)) < 0)
2456             {
2457             psTraceInfo("Can't decrypt server key exchange sig\n");
2458 0           ssl->err = SSL_ALERT_BAD_CERTIFICATE;
2459 0           return MATRIXSSL_ERROR;
2460             }
2461             }
2462             # else /* ! USE_TLS_1_2 */
2463             hashSize = MD5_HASH_SIZE + SHA1_HASH_SIZE;
2464             if ((i = psRsaDecryptPub(skepkiPool, &ssl->sec.cert->publicKey.key.rsa,
2465             c, pubDhLen, sigOut, hashSize, pkiData)) < 0)
2466             {
2467             psTraceInfo("Unable to decrypt server key exchange sig\n");
2468             ssl->err = SSL_ALERT_BAD_CERTIFICATE;
2469             return MATRIXSSL_ERROR;
2470             }
2471             # endif /* USE_TLS_1_2 */
2472              
2473             /* Now have hash from the server. Create ours and check match */
2474 1057           c += pubDhLen;
2475              
2476 1057 50         if (memcmpct(sigOut, hsMsgHash, hashSize) != 0)
2477             {
2478             psTraceInfo("Fail to verify serverKeyExchange sig\n");
2479 0           ssl->err = SSL_ALERT_BAD_CERTIFICATE;
2480 0           return MATRIXSSL_ERROR;
2481             }
2482             }
2483             # endif /* USE_RSA_CIPHER_SUITE */
2484             # ifdef USE_ECC_CIPHER_SUITE
2485 1057 50         if (ssl->flags & SSL_FLAGS_DHE_WITH_DSA)
2486             {
2487             /*
2488             RFC4492: The default hash function is SHA-1, and sha_size is 20.
2489             */
2490             # ifdef USE_TLS_1_2
2491 0 0         if (ssl->flags & SSL_FLAGS_TLS_1_2 &&
    0          
2492             (hashSize == SHA256_HASH_SIZE))
2493             {
2494 0           psSha256PreInit(&digestCtx.sha256);
2495 0           psSha256Init(&digestCtx.sha256);
2496 0           psSha256Update(&digestCtx.sha256, ssl->sec.clientRandom,
2497             SSL_HS_RANDOM_SIZE);
2498 0           psSha256Update(&digestCtx.sha256, ssl->sec.serverRandom,
2499             SSL_HS_RANDOM_SIZE);
2500 0           psSha256Update(&digestCtx.sha256, sigStart,
2501 0           (int32) (sigStop - sigStart));
2502 0           psSha256Final(&digestCtx.sha256, hsMsgHash);
2503             # ifdef USE_SHA384
2504             }
2505 0 0         else if (ssl->flags & SSL_FLAGS_TLS_1_2 &&
    0          
2506             (hashSize == SHA384_HASH_SIZE))
2507             {
2508 0           psSha384PreInit(&digestCtx.sha384);
2509 0           psSha384Init(&digestCtx.sha384);
2510 0           psSha384Update(&digestCtx.sha384, ssl->sec.clientRandom,
2511             SSL_HS_RANDOM_SIZE);
2512 0           psSha384Update(&digestCtx.sha384, ssl->sec.serverRandom,
2513             SSL_HS_RANDOM_SIZE);
2514 0           psSha384Update(&digestCtx.sha384, sigStart,
2515 0           (int32) (sigStop - sigStart));
2516 0           psSha384Final(&digestCtx.sha384, hsMsgHash);
2517             # endif
2518             # ifdef USE_SHA512
2519             }
2520 0 0         else if (hashSize == SHA512_HASH_SIZE)
2521             {
2522 0           psSha512PreInit(&digestCtx.sha512);
2523 0           psSha512Init(&digestCtx.sha512);
2524 0           psSha512Update(&digestCtx.sha512, ssl->sec.clientRandom,
2525             SSL_HS_RANDOM_SIZE);
2526 0           psSha512Update(&digestCtx.sha512, ssl->sec.serverRandom,
2527             SSL_HS_RANDOM_SIZE);
2528 0           psSha512Update(&digestCtx.sha512, sigStart,
2529 0           (uint32) (sigStop - sigStart));
2530 0           psSha512Final(&digestCtx.sha512, hsMsgHash);
2531             # endif /* USE_SHA512 */
2532             # ifdef USE_SHA1
2533             }
2534 0 0         else if (ssl->minVer < TLS_1_2_MIN_VER ||
    0          
2535             # ifdef USE_DTLS
2536             ssl->minVer == DTLS_MIN_VER ||
2537             # endif
2538 0 0         ((ssl->flags & SSL_FLAGS_TLS_1_2) &&
2539             (hashSize == SHA1_HASH_SIZE)))
2540             {
2541 0           hashSize = SHA1_HASH_SIZE;
2542 0           psSha1PreInit(&digestCtx.sha1);
2543 0           psSha1Init(&digestCtx.sha1);
2544 0           psSha1Update(&digestCtx.sha1, ssl->sec.clientRandom,
2545             SSL_HS_RANDOM_SIZE);
2546 0           psSha1Update(&digestCtx.sha1, ssl->sec.serverRandom,
2547             SSL_HS_RANDOM_SIZE);
2548 0           psSha1Update(&digestCtx.sha1, sigStart,
2549 0           (int32) (sigStop - sigStart));
2550 0           psSha1Final(&digestCtx.sha1, hsMsgHash);
2551             # endif
2552             }
2553             else
2554             {
2555 0           return MATRIXSSL_ERROR;
2556             }
2557             # else /* USE_TLS_1_2 */
2558             hashSize = SHA1_HASH_SIZE;
2559             psSha1Init(&digestCtx.sha1);
2560             psSha1Update(&digestCtx.sha1, ssl->sec.clientRandom,
2561             SSL_HS_RANDOM_SIZE);
2562             psSha1Update(&digestCtx.sha1, ssl->sec.serverRandom,
2563             SSL_HS_RANDOM_SIZE);
2564             psSha1Update(&digestCtx.sha1, sigStart,
2565             (int32) (sigStop - sigStart));
2566             psSha1Final(&digestCtx.sha1, hsMsgHash);
2567             # endif /* USE_TLS_1_2 */
2568              
2569 0           i = 0;
2570              
2571 0 0         if ((res = psEccDsaVerify(skepkiPool,
2572 0           &ssl->sec.cert->publicKey.key.ecc,
2573             hsMsgHash, hashSize,
2574             c, pubDhLen,
2575             &i, pkiData)) != 0)
2576             {
2577             psTraceInfo("ECDSA signature validation failed\n");
2578 0           ssl->err = SSL_ALERT_BAD_CERTIFICATE;
2579 0           return MATRIXSSL_ERROR;
2580             }
2581 0           c += pubDhLen;
2582             /*
2583             The validation code comes out of the final parameter
2584             */
2585 0 0         if (i != 1)
2586             {
2587             psTraceInfo("Can't verify serverKeyExchange sig\n");
2588 0           ssl->err = SSL_ALERT_BAD_CERTIFICATE;
2589 0           return MATRIXSSL_ERROR;
2590              
2591             }
2592             }
2593             # endif /* USE_ECC_CIPHER_SUITE */
2594              
2595 1057           ssl->hsState = SSL_HS_SERVER_HELLO_DONE;
2596              
2597             }
2598             # endif /* USE_DHE_CIPHER_SUITE */
2599             # ifdef USE_PSK_CIPHER_SUITE
2600             /*
2601             Entry point for basic PSK ciphers (not DHE or RSA) parsing SKE message
2602             */
2603 1057 50         if (ssl->flags & SSL_FLAGS_PSK_CIPHER)
2604             {
2605 0 0         if ((end - c) < 2)
2606             {
2607 0           ssl->err = SSL_ALERT_DECODE_ERROR;
2608             psTraceInfo("Invalid ServerKeyExchange message\n");
2609 0           return MATRIXSSL_ERROR;
2610             }
2611 0           ssl->sec.hintLen = *c << 8; c++;
2612 0           ssl->sec.hintLen |= *c; c++;
2613 0 0         if ((uint32) (end - c) < ssl->sec.hintLen)
2614             {
2615 0           ssl->err = SSL_ALERT_DECODE_ERROR;
2616             psTraceInfo("Invalid ServerKeyExchange message\n");
2617 0           return MATRIXSSL_ERROR;
2618             }
2619 0 0         if (ssl->sec.hintLen > 0)
2620             {
2621 0           ssl->sec.hint = psMalloc(ssl->hsPool, ssl->sec.hintLen);
2622 0 0         if (ssl->sec.hint == NULL)
2623             {
2624 0           return SSL_MEM_ERROR;
2625             }
2626 0           memcpy(ssl->sec.hint, c, ssl->sec.hintLen);
2627 0           c += ssl->sec.hintLen;
2628             }
2629 0           ssl->hsState = SSL_HS_SERVER_HELLO_DONE;
2630             }
2631             # endif /* USE_PSK_CIPHER_SUITE */
2632              
2633 1057           *cp = c;
2634 1057           ssl->decState = SSL_HS_SERVER_KEY_EXCHANGE;
2635 1057           return PS_SUCCESS;
2636             }
2637              
2638             # ifdef USE_OCSP
2639 0           int32 parseCertificateStatus(ssl_t *ssl, int32 hsLen, unsigned char **cp,
2640             unsigned char *end)
2641             {
2642             unsigned char *c;
2643             int32_t responseLen, rc;
2644             psOcspResponse_t response;
2645              
2646             /*
2647             struct {
2648             CertificateStatusType status_type;
2649             select (status_type) {
2650             case ocsp: OCSPResponse;
2651             } response;
2652             } CertificateStatus;
2653              
2654             enum { ocsp(1), (255) } CertificateStatusType;
2655             opaque OCSPResponse<1..2^24-1>;
2656              
2657             An "ocsp_response" contains a complete, DER-encoded OCSP response
2658             (using the ASN.1 type OCSPResponse defined in [RFC6960]). Only one
2659             OCSP response may be sent.
2660             */
2661 0           c = *cp;
2662 0 0         if ((end - c) < 4)
2663             {
2664 0           ssl->err = SSL_ALERT_DECODE_ERROR;
2665             psTraceInfo("Invalid CertificateStatus length\n");
2666 0           return MATRIXSSL_ERROR;
2667             }
2668              
2669 0 0         if (*c != 0x1)
2670             {
2671 0           ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
2672             psTraceInfo("Invalid status_type in certificateStatus message\n");
2673 0           return MATRIXSSL_ERROR;
2674             }
2675 0           c++;
2676              
2677 0           responseLen = *c << 16; c++;
2678 0           responseLen |= *c << 8; c++;
2679 0           responseLen |= *c; c++;
2680              
2681 0 0         if (responseLen > (end - c))
2682             {
2683 0           ssl->err = SSL_ALERT_DECODE_ERROR;
2684             psTraceInfo("Malformed CertificateStatus message\n");
2685 0           return MATRIXSSL_ERROR;
2686             }
2687 0           memset(&response, 0x0, sizeof(psOcspResponse_t));
2688 0 0         if ((rc = psOcspParseResponse(ssl->hsPool, responseLen, &c, end, &response))
2689             < 0)
2690             {
2691             /* Couldn't parse or no good responses in stream */
2692 0           psX509FreeCert(response.OCSPResponseCert);
2693 0           ssl->err = SSL_ALERT_BAD_CERTIFICATE_STATUS_RESPONSE;
2694             psTraceInfo("Unable to parse OCSPResponse\n");
2695 0           return MATRIXSSL_ERROR;
2696             }
2697 0           *cp = c;
2698              
2699             /* Authenticate the parsed response based on the registered CA files
2700             AND passing through the server chain as well because some real
2701             world examples we have seen use the intermediate cert as the
2702             OCSP responder */
2703 0 0         if ((rc = psOcspResponseValidateOld(ssl->hsPool, ssl->keys->CAcerts,
2704             ssl->sec.cert, &response)) < 0)
2705             {
2706             /* Couldn't validate */
2707 0           psX509FreeCert(response.OCSPResponseCert);
2708 0           ssl->err = SSL_ALERT_BAD_CERTIFICATE_STATUS_RESPONSE;
2709             psTraceInfo("Unable to validate OCSPResponse\n");
2710 0           return MATRIXSSL_ERROR;
2711             }
2712 0           psX509FreeCert(response.OCSPResponseCert);
2713              
2714             /* Same logic to determine next state as in end of SSL_HS_CERTIFICATE */
2715 0           ssl->hsState = SSL_HS_SERVER_HELLO_DONE;
2716             # ifdef USE_DHE_CIPHER_SUITE
2717 0 0         if (ssl->flags & SSL_FLAGS_DHE_KEY_EXCH)
2718             {
2719 0           ssl->hsState = SSL_HS_SERVER_KEY_EXCHANGE;
2720             }
2721             # endif /* USE_DHE_CIPHER_SUITE */
2722 0           ssl->decState = SSL_HS_CERTIFICATE_STATUS;
2723 0           return PS_SUCCESS;
2724             }
2725             # endif /* USE_OCSP */
2726              
2727             /******************************************************************************/
2728              
2729 1058           int32 parseServerHelloDone(ssl_t *ssl, int32 hsLen, unsigned char **cp,
2730             unsigned char *end)
2731             {
2732             unsigned char *c;
2733              
2734             # if defined(USE_DHE_CIPHER_SUITE) || defined(REQUIRE_DH_PARAMS)
2735             int32 rc;
2736 1058           void *pkiData = ssl->userPtr;
2737              
2738             # endif /* DH */
2739              
2740 1058           c = *cp;
2741              
2742             psTraceHs(">>> Client parsing SERVER_HELLO_DONE message\n");
2743 1058 50         if (hsLen != 0)
2744             {
2745 0           ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
2746             psTraceInfo("Invalid ServerHelloDone message\n");
2747 0           return MATRIXSSL_ERROR;
2748             }
2749              
2750             # ifdef USE_DHE_CIPHER_SUITE
2751 1058 100         if (ssl->flags & SSL_FLAGS_DHE_KEY_EXCH)
2752             {
2753             # ifdef USE_ECC_CIPHER_SUITE
2754              
2755 1057 50         if (ssl->flags & SSL_FLAGS_ECC_CIPHER)
2756             {
2757             /* Set up our private side of the ECC key based on the agreed
2758             upon curve */
2759 1057 50         if (psEccNewKey(ssl->sec.eccDhKeyPool, &ssl->sec.eccKeyPriv,
2760 1057           ssl->sec.eccKeyPub->curve) < 0)
2761             {
2762 0           return PS_MEM_FAIL;
2763             }
2764 1057 50         if ((rc = matrixSslGenEphemeralEcKey(ssl->keys,
2765 1057           ssl->sec.eccKeyPriv, ssl->sec.eccKeyPub->curve,
2766             pkiData)) < 0)
2767             {
2768 0           psEccDeleteKey(&ssl->sec.eccKeyPriv);
2769             psTraceInfo("GenEphemeralEcc failed\n");
2770 0           ssl->err = SSL_ALERT_INTERNAL_ERROR;
2771 0           return MATRIXSSL_ERROR;
2772             }
2773             }
2774             else
2775             {
2776             # endif
2777             # ifdef REQUIRE_DH_PARAMS
2778             /* Can safely set up our ssl->sec.dhKeyPriv with DH keys
2779             based on the parameters passed over from the server.
2780             Storing these in a client specific DH pool because at
2781             handshake pool creation, the size for PKI was not known */
2782 0 0         if ((ssl->sec.dhKeyPriv = psMalloc(ssl->sec.dhKeyPool,
2783             sizeof(psDhKey_t))) == NULL)
2784             {
2785 0           return MATRIXSSL_ERROR;
2786             }
2787 0 0         if ((rc = psDhGenKey(ssl->sec.dhKeyPool, ssl->sec.dhPLen,
2788 0           ssl->sec.dhP, ssl->sec.dhPLen, ssl->sec.dhG,
2789 0           ssl->sec.dhGLen, ssl->sec.dhKeyPriv, pkiData)) < 0)
2790             {
2791 0           psFree(ssl->sec.dhKeyPriv, ssl->sec.dhKeyPool);
2792 0           ssl->sec.dhKeyPriv = NULL;
2793 0           return MATRIXSSL_ERROR;
2794             }
2795             /* Freeing as we go. No more need for G */
2796 0           psFree(ssl->sec.dhG, ssl->hsPool); ssl->sec.dhG = NULL;
2797             # endif /* REQUIRE_DH_PARAMS */
2798             # ifdef USE_ECC_CIPHER_SUITE
2799             }
2800             # endif /* USE_ECC_CIPHER_SUITE */
2801             }
2802             # endif /* USE_DHE_CIPHER_SUITE */
2803              
2804 1058           ssl->hsState = SSL_HS_FINISHED;
2805              
2806 1058           *cp = c;
2807 1058           ssl->decState = SSL_HS_SERVER_HELLO_DONE;
2808 1058           return SSL_PROCESS_DATA;
2809             }
2810              
2811             /******************************************************************************/
2812              
2813             # ifndef USE_ONLY_PSK_CIPHER_SUITE
2814 0           int32 parseCertificateRequest(ssl_t *ssl, int32 hsLen, unsigned char **cp,
2815             unsigned char *end)
2816             {
2817             # ifdef USE_CLIENT_AUTH
2818             psX509Cert_t *cert;
2819             int32 i;
2820             # endif
2821             int32 certTypeLen, certChainLen;
2822             uint32 certLen;
2823             # ifdef USE_TLS_1_2
2824             uint32 sigAlgMatch;
2825             # ifdef USE_CLIENT_AUTH
2826             uint32 hashSigAlg;
2827             # endif
2828             # endif
2829             unsigned char *c;
2830              
2831 0           c = *cp;
2832              
2833             psTraceHs(">>> Client parsing CERTIFICATE_REQUEST message\n");
2834 0 0         if (hsLen < 4)
2835             {
2836 0           ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
2837             psTraceInfo("Invalid Certificate Request message\n");
2838 0           return MATRIXSSL_ERROR;
2839             }
2840             /* Currently ignoring the authentication type request because it was
2841             underspecified up to TLS 1.1 and TLS 1.2 is now taking care of this
2842             with the supported_signature_algorithms handling */
2843 0           certTypeLen = *c++;
2844 0 0         if (end - c < certTypeLen)
2845             {
2846 0           ssl->err = SSL_ALERT_DECODE_ERROR;
2847             psTraceInfo("Invalid Certificate Request message\n");
2848 0           return MATRIXSSL_ERROR;
2849             }
2850 0           c += certTypeLen; /* Skipping (RSA_SIGN etc.) */
2851             # ifdef USE_TLS_1_2
2852 0           sigAlgMatch = 0;
2853 0 0         if (ssl->flags & SSL_FLAGS_TLS_1_2)
2854             {
2855             /* supported_signature_algorithms field
2856             enum {none(0), md5(1), sha1(2), sha224(3), sha256(4), sha384(5),
2857             sha512(6), (255) } HashAlgorithm;
2858              
2859             enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) } SigAlg */
2860 0 0         if (end - c < 2)
2861             {
2862 0           ssl->err = SSL_ALERT_DECODE_ERROR;
2863             psTraceInfo("Invalid SigHash in Certificate Request message\n");
2864 0           return MATRIXSSL_ERROR;
2865             }
2866 0           certChainLen = *c << 8; c++; /* just borrowing this variable */
2867 0           certChainLen |= *c; c++;
2868 0 0         if (end - c < certChainLen)
2869             {
2870 0           ssl->err = SSL_ALERT_DECODE_ERROR;
2871             psTraceInfo("Invalid SigHash in Certificate Request message\n");
2872 0           return MATRIXSSL_ERROR;
2873             }
2874             # ifdef USE_CLIENT_AUTH
2875             /* Going to adhere to this supported_signature_algorithm to
2876             be compliant with the spec. This is now the first line
2877             of testing about what certificates the server will accept.
2878             If any of our certs do not use a signature algorithm
2879             that the server supports we will flag that here which will
2880             ultimately result in an empty CERTIFICATE message and
2881             no CERTIFICATE_VERIFY message. We're going to convert
2882             MD5 to use SHA1 instead though.
2883              
2884             Start by building a bitmap of supported algs */
2885 0           hashSigAlg = 0;
2886 0 0         while (certChainLen >= 2)
2887             {
2888 0           i = HASH_SIG_MASK(c[0], c[1]);
2889             /* Our own ssl->hashSigAlg is the list we support. So choose
2890             from those only */
2891 0 0         if (ssl->hashSigAlg & i)
2892             {
2893 0           hashSigAlg |= i;
2894             }
2895 0           c += 2;
2896 0           certChainLen -= 2;
2897             }
2898             /* RFC: The end-entity certificate provided by the client MUST
2899             contain a key that is compatible with certificate_types.
2900             If the key is a signature key, it MUST be usable with some
2901             hash/signature algorithm pair in supported_signature_algorithms.
2902              
2903             So not only do we have to check the signature algorithm, we
2904             have to check the pub key type as well. */
2905 0           sigAlgMatch = 1; /* de-flag if we hit unsupported one */
2906 0 0         if (ssl->keys == NULL || ssl->keys->cert == NULL)
    0          
2907             {
2908 0           sigAlgMatch = 0;
2909             }
2910             else
2911             {
2912 0           cert = ssl->keys->cert;
2913 0 0         while (cert)
2914             {
2915 0 0         if (cert->pubKeyAlgorithm == OID_RSA_KEY_ALG)
2916             {
2917 0 0         if (!(hashSigAlg & HASH_SIG_SHA1_RSA_MASK) &&
    0          
2918             # ifdef USE_SHA384
2919 0 0         !(hashSigAlg & HASH_SIG_SHA384_RSA_MASK) &&
2920             # endif
2921 0 0         !(hashSigAlg & HASH_SIG_SHA256_RSA_MASK) &&
2922 0           !(hashSigAlg & HASH_SIG_MD5_RSA_MASK))
2923             {
2924 0           sigAlgMatch = 0;
2925             }
2926             }
2927 0 0         if (cert->sigAlgorithm == OID_SHA1_RSA_SIG ||
    0          
2928 0           cert->sigAlgorithm == OID_MD5_RSA_SIG)
2929             {
2930 0 0         if (!(hashSigAlg & HASH_SIG_SHA1_RSA_MASK))
2931             {
2932 0           sigAlgMatch = 0;
2933             }
2934             }
2935 0 0         if (cert->sigAlgorithm == OID_SHA256_RSA_SIG)
2936             {
2937 0 0         if (!(hashSigAlg & HASH_SIG_SHA256_RSA_MASK))
2938             {
2939 0           sigAlgMatch = 0;
2940             }
2941             }
2942             # ifdef USE_SHA384
2943 0 0         if (cert->sigAlgorithm == OID_SHA384_RSA_SIG)
2944             {
2945 0 0         if (!(hashSigAlg & HASH_SIG_SHA384_RSA_MASK))
2946             {
2947 0           sigAlgMatch = 0;
2948             }
2949             }
2950             # endif
2951             # ifdef USE_SHA512
2952 0 0         if (cert->sigAlgorithm == OID_SHA512_RSA_SIG)
2953             {
2954 0 0         if (!(hashSigAlg & HASH_SIG_SHA512_RSA_MASK))
2955             {
2956 0           sigAlgMatch = 0;
2957             }
2958             }
2959             # endif
2960             # ifdef USE_ECC
2961 0 0         if (cert->pubKeyAlgorithm == OID_ECDSA_KEY_ALG)
2962             {
2963 0 0         if (!(hashSigAlg & HASH_SIG_SHA1_ECDSA_MASK) &&
    0          
2964             # ifdef USE_SHA384
2965 0 0         !(hashSigAlg & HASH_SIG_SHA384_ECDSA_MASK) &&
2966             # endif
2967             # ifdef USE_SHA512
2968 0 0         !(hashSigAlg & HASH_SIG_SHA512_ECDSA_MASK) &&
2969             # endif
2970 0 0         !(hashSigAlg & HASH_SIG_SHA256_ECDSA_MASK) &&
2971 0           !(hashSigAlg & HASH_SIG_SHA1_ECDSA_MASK))
2972             {
2973 0           sigAlgMatch = 0;
2974             }
2975             }
2976 0 0         if (cert->sigAlgorithm == OID_SHA1_ECDSA_SIG)
2977             {
2978 0 0         if (!(hashSigAlg & HASH_SIG_SHA1_ECDSA_MASK))
2979             {
2980 0           sigAlgMatch = 0;
2981             }
2982             }
2983 0 0         if (cert->sigAlgorithm == OID_SHA256_ECDSA_SIG)
2984             {
2985 0 0         if (!(hashSigAlg & HASH_SIG_SHA256_ECDSA_MASK))
2986             {
2987 0           sigAlgMatch = 0;
2988             }
2989             }
2990             # ifdef USE_SHA384
2991 0 0         if (cert->sigAlgorithm == OID_SHA384_ECDSA_SIG)
2992             {
2993 0 0         if (!(hashSigAlg & HASH_SIG_SHA384_ECDSA_MASK))
2994             {
2995 0           sigAlgMatch = 0;
2996             }
2997             }
2998             # endif
2999             # ifdef USE_SHA512
3000 0 0         if (cert->sigAlgorithm == OID_SHA512_ECDSA_SIG)
3001             {
3002 0 0         if (!(hashSigAlg & HASH_SIG_SHA512_ECDSA_MASK))
3003             {
3004 0           sigAlgMatch = 0;
3005             }
3006             }
3007             # endif
3008             # endif /* USE_ECC */
3009 0           cert = cert->next;
3010             }
3011             }
3012             # endif /* USE_CLIENT_AUTH */
3013 0           c += certChainLen;
3014             }
3015             # endif /* TLS_1_2 */
3016              
3017 0           certChainLen = 0;
3018 0 0         if (end - c >= 2)
3019             {
3020 0           certChainLen = *c << 8; c++;
3021 0           certChainLen |= *c; c++;
3022 0 0         if (end - c < certChainLen)
3023             {
3024 0           ssl->err = SSL_ALERT_DECODE_ERROR;
3025             psTraceInfo("Invalid Certificate Request message\n");
3026 0           return MATRIXSSL_ERROR;
3027             }
3028             }
3029             /* Check the passed in DNs against our cert issuer to see if they match.
3030             Only supporting a single cert on the client side. */
3031 0           ssl->sec.certMatch = 0;
3032              
3033             # ifdef USE_CLIENT_AUTH
3034             /* If the user has actually gone to the trouble to load a certificate
3035             to reply with, we flag that here so there is some flexibility as
3036             to whether we want to reply with something (even if it doesn't match)
3037             just in case the server is willing to do a custom test of the cert */
3038 0 0         if (ssl->keys != NULL && ssl->keys->cert)
    0          
3039             {
3040 0           ssl->sec.certMatch = SSL_ALLOW_ANON_CONNECTION;
3041             }
3042             # endif /* USE_CLIENT_AUTH */
3043 0 0         while (certChainLen > 2)
3044             {
3045 0           certLen = *c << 8; c++;
3046 0           certLen |= *c; c++;
3047 0 0         if ((uint32) (end - c) < certLen || certLen <= 0 ||
    0          
    0          
3048 0           (int32) certLen > certChainLen)
3049             {
3050 0           ssl->err = SSL_ALERT_DECODE_ERROR;
3051             psTraceInfo("Invalid CertificateRequest message\n");
3052 0           return MATRIXSSL_ERROR;
3053             }
3054 0           certChainLen -= 2;
3055             # ifdef USE_CLIENT_AUTH
3056             /* Can parse the message, but will not look for a match. The
3057             setting of certMatch to 1 will trigger the correct response
3058             in sslEncode */
3059 0 0         if (ssl->keys != NULL && ssl->keys->cert)
    0          
3060             {
3061             /* Flag a match if the hash of the DN issuer is identical */
3062 0 0         if (ssl->keys->cert->issuer.dnencLen == certLen)
3063             {
3064 0 0         if (memcmp(ssl->keys->cert->issuer.dnenc, c, certLen) == 0)
3065             {
3066 0           ssl->sec.certMatch = 1;
3067             }
3068             }
3069             }
3070             # endif /* USE_CLIENT_AUTH */
3071 0           c += certLen;
3072 0           certChainLen -= certLen;
3073             }
3074             # ifdef USE_TLS_1_2
3075 0 0         if (ssl->flags & SSL_FLAGS_TLS_1_2)
3076             {
3077             /* We let the DN parse complete but if we didn't get a sigAlgMatch
3078             from the previous test we're going to adhere to that for spec
3079             compliance. So here goes */
3080 0 0         if (sigAlgMatch == 0)
3081             {
3082 0           ssl->sec.certMatch = 0;
3083             }
3084             }
3085             # endif
3086 0           ssl->hsState = SSL_HS_SERVER_HELLO_DONE;
3087              
3088 0           *cp = c;
3089 0           ssl->decState = SSL_HS_CERTIFICATE_REQUEST;
3090 0           return PS_SUCCESS;
3091             }
3092             # endif /* USE_ONLY_PSK_CIPHER_SUITE */
3093             #endif /* USE_CLIENT_SIDE_SSL */
3094              
3095             /******************************************************************************/
3096              
3097 2119           int32 parseFinished(ssl_t *ssl, int32 hsLen,
3098             unsigned char hsMsgHash[SHA384_HASH_SIZE],
3099             unsigned char **cp,
3100             unsigned char *end)
3101             {
3102             int32 rc;
3103             unsigned char *c;
3104              
3105 2119           rc = PS_SUCCESS;
3106 2119           c = *cp;
3107              
3108 2119 50         psAssert(hsLen <= SHA384_HASH_SIZE);
3109              
3110             /* Before the finished handshake message, we should have seen the
3111             CHANGE_CIPHER_SPEC message come through in the record layer, which
3112             would have activated the read cipher, and set the READ_SECURE flag.
3113             This is the first handshake message that was sent securely. */
3114             psTraceStrHs(">>> %s parsing FINISHED message\n",
3115             (ssl->flags & SSL_FLAGS_SERVER) ? "Server" : "Client");
3116 2119 50         if (!(ssl->flags & SSL_FLAGS_READ_SECURE))
3117             {
3118 0           ssl->err = SSL_ALERT_UNEXPECTED_MESSAGE;
3119             psTraceInfo("Finished before ChangeCipherSpec\n");
3120 0           return MATRIXSSL_ERROR;
3121             }
3122             /* The contents of the finished message is a 16 byte MD5 hash followed
3123             by a 20 byte sha1 hash of all the handshake messages so far, to verify
3124             that nothing has been tampered with while we were still insecure.
3125             Compare the message to the value we calculated at the beginning of
3126             this function. */
3127             #ifdef USE_TLS
3128 2119 50         if (ssl->flags & SSL_FLAGS_TLS)
3129             {
3130 2119 50         if (hsLen != TLS_HS_FINISHED_SIZE)
3131             {
3132 0           ssl->err = SSL_ALERT_DECODE_ERROR;
3133             psTraceInfo("Invalid Finished length\n");
3134 0           return MATRIXSSL_ERROR;
3135             }
3136             }
3137             else
3138             {
3139             #endif /* USE_TLS */
3140 0 0         if (hsLen != MD5_HASH_SIZE + SHA1_HASH_SIZE)
3141             {
3142 0           ssl->err = SSL_ALERT_DECODE_ERROR;
3143             psTraceInfo("Invalid Finished length\n");
3144 0           return MATRIXSSL_ERROR;
3145             }
3146             #ifdef USE_TLS
3147             }
3148             #endif /* USE_TLS */
3149 2119 50         if ((int32) (end - c) < hsLen)
3150             {
3151 0           ssl->err = SSL_ALERT_DECODE_ERROR;
3152             psTraceInfo("Invalid Finished length\n");
3153 0           return MATRIXSSL_ERROR;
3154             }
3155 2119 50         if (memcmpct(c, hsMsgHash, hsLen) != 0)
3156             {
3157 0           ssl->err = SSL_ALERT_DECRYPT_ERROR;
3158             psTraceInfo("Invalid handshake msg hash\n");
3159 0           return MATRIXSSL_ERROR;
3160             }
3161             #ifdef ENABLE_SECURE_REHANDSHAKES
3162             /* Got the peer verify_data for secure renegotiations */
3163 2119           memcpy(ssl->peerVerifyData, c, hsLen);
3164 2119           ssl->peerVerifyDataLen = hsLen;
3165             #endif /* ENABLE_SECURE_REHANDSHAKES */
3166 2119           c += hsLen;
3167 2119           ssl->hsState = SSL_HS_DONE;
3168             /* Now that we've parsed the Finished message, if we're a resumed
3169             connection, we're done with handshaking, otherwise, we return
3170             SSL_PROCESS_DATA to get our own cipher spec and finished messages
3171             sent out by the caller. */
3172 2119 100         if (ssl->flags & SSL_FLAGS_SERVER)
3173             {
3174 1059 100         if (!(ssl->flags & SSL_FLAGS_RESUMED))
3175             {
3176 1057           rc = SSL_PROCESS_DATA;
3177             }
3178             else
3179             {
3180             #ifdef USE_SSL_INFORMATIONAL_TRACE
3181             /* Server side resumed completion */
3182             matrixSslPrintHSDetails(ssl);
3183             #endif
3184             }
3185             }
3186             else
3187             {
3188             #ifdef USE_STATELESS_SESSION_TICKETS
3189             /* Now that FINISHED is verified, we can mark the ticket as
3190             valid to conform to section 3.3 of the 5077 RFC */
3191 1060 100         if (ssl->sid && ssl->sid->sessionTicketLen > 0)
    50          
3192             {
3193 0           ssl->sid->sessionTicketState = SESS_TICKET_STATE_USING_TICKET;
3194             }
3195             #endif
3196 1060 100         if (ssl->flags & SSL_FLAGS_RESUMED)
3197             {
3198 2           rc = SSL_PROCESS_DATA;
3199             }
3200             else
3201             {
3202             #ifdef USE_SSL_INFORMATIONAL_TRACE
3203             /* Client side standard completion */
3204             matrixSslPrintHSDetails(ssl);
3205             #endif
3206             }
3207             }
3208             #ifndef USE_ONLY_PSK_CIPHER_SUITE
3209             # if defined(USE_CLIENT_SIDE_SSL) || defined(USE_CLIENT_AUTH)
3210             /* There is also an attempt to free the cert during
3211             the sending of the finished message to deal with client
3212             and server and differing handshake types. Both cases are
3213             attempted keep the lifespan of this allocation as short as possible. */
3214 2119 50         if (!(ssl->bFlags & BFLAG_KEEP_PEER_CERTS))
3215             {
3216 2119 50         if (ssl->sec.cert)
3217             {
3218 0           psX509FreeCert(ssl->sec.cert);
3219 0           ssl->sec.cert = NULL;
3220             }
3221             }
3222             # endif /* USE_CLIENT_SIDE_SSL || USE_CLIENT_AUTH */
3223             #endif /* !USE_ONLY_PSK_CIPHER_SUITE */
3224              
3225             #ifdef USE_DTLS
3226             if (ssl->flags & SSL_FLAGS_DTLS)
3227             {
3228             /* A successful parse of the FINISHED message means the record sequence
3229             numbers have been reset so we need to clear out our replay detector */
3230             zeroSixByte(ssl->lastRsn);
3231              
3232             /* This will just be set between CCS parse and FINISHED parse */
3233             ssl->parsedCCS = 1;
3234              
3235             /* Look at the comment in the fragment parsing code to see the
3236             justification of placing this free here. Bascially, this
3237             is the best place to do it because we know there can be no
3238             further fragmented messages. More importantly, the
3239             hanshake pool is being freed here! */
3240             if (ssl->fragMessage != NULL)
3241             {
3242             psFree(ssl->fragMessage, ssl->hsPool);
3243             ssl->fragMessage = NULL;
3244             }
3245             }
3246             /* Premaster was not freed at the usual spot becasue of retransmit cases */
3247             if (ssl->sec.premaster)
3248             {
3249             psFree(ssl->sec.premaster, ssl->hsPool); ssl->sec.premaster = NULL;
3250             }
3251             if (ssl->ckeMsg)
3252             {
3253             psFree(ssl->ckeMsg, ssl->hsPool); ssl->ckeMsg = NULL;
3254             }
3255             if (ssl->certVerifyMsg)
3256             {
3257             psFree(ssl->certVerifyMsg, ssl->hsPool); ssl->certVerifyMsg = NULL;
3258             }
3259             # if defined(USE_PSK_CIPHER_SUITE) && defined(USE_CLIENT_SIDE_SSL)
3260             if (ssl->sec.hint)
3261             {
3262             psFree(ssl->sec.hint, ssl->hsPool); ssl->sec.hint = NULL;
3263             }
3264             # endif
3265             #endif /* USE_DTLS */
3266 2119           ssl->hsPool = NULL;
3267              
3268 2119           *cp = c;
3269 2119           ssl->decState = SSL_HS_FINISHED;
3270 2119           return rc;
3271             }
3272              
3273             /******************************************************************************/
3274              
3275             #ifndef USE_ONLY_PSK_CIPHER_SUITE
3276             # if defined(USE_CLIENT_SIDE_SSL) || defined(USE_CLIENT_AUTH)
3277 1148           int32 parseCertificate(ssl_t *ssl, unsigned char **cp, unsigned char *end)
3278             {
3279             psX509Cert_t *currentCert, *cert, *foundIssuer;
3280             unsigned char *c;
3281             uint32 certLen;
3282 1148           int32 rc, i, certChainLen, parseLen = 0;
3283 1148           void *pkiData = ssl->userPtr;
3284             int32 pathLen;
3285              
3286             psTraceStrHs(">>> %s parsing CERTIFICATE message\n",
3287             (ssl->flags & SSL_FLAGS_SERVER) ? "Server" : "Client");
3288              
3289 1148           c = *cp;
3290              
3291             # ifdef USE_CERT_CHAIN_PARSING
3292             if (ssl->rec.partial)
3293             {
3294             /* The test for a first pass is against the record header length */
3295             if (ssl->rec.hsBytesParsed == ssl->recordHeadLen)
3296             {
3297             /* Account for the one-time header portion parsed above
3298             and the 3 byte cert chain length about to be parsed below.
3299             The minimum length tests have already been performed. */
3300             ssl->rec.hsBytesParsed += ssl->hshakeHeadLen + 3;
3301             }
3302             else
3303             {
3304             goto SKIP_CERT_CHAIN_INIT;
3305             }
3306             }
3307             # endif
3308 1148 50         if (end - c < 3)
3309             {
3310 0           ssl->err = SSL_ALERT_DECODE_ERROR;
3311             psTraceInfo("Invalid Certificate message\n");
3312 0           return MATRIXSSL_ERROR;
3313             }
3314 1148           certChainLen = *c << 16; c++;
3315 1148           certChainLen |= *c << 8; c++;
3316 1148           certChainLen |= *c; c++;
3317 1148 50         if (certChainLen == 0)
3318             {
3319             # ifdef SERVER_WILL_ACCEPT_EMPTY_CLIENT_CERT_MSG
3320 0 0         if (ssl->flags & SSL_FLAGS_SERVER)
3321             {
3322 0           ssl->err = SSL_ALERT_BAD_CERTIFICATE;
3323 0           ssl->flags &= ~SSL_FLAGS_CLIENT_AUTH;
3324 0           goto STRAIGHT_TO_USER_CALLBACK;
3325             }
3326             # endif
3327 0 0         if (ssl->majVer == SSL3_MAJ_VER && ssl->minVer == SSL3_MIN_VER)
    0          
3328             {
3329 0           ssl->err = SSL_ALERT_NO_CERTIFICATE;
3330             }
3331             else
3332             {
3333 0           ssl->err = SSL_ALERT_BAD_CERTIFICATE;
3334             }
3335             psTraceInfo("No certificate sent to verify\n");
3336 0           return MATRIXSSL_ERROR;
3337             }
3338 1148 50         if (end - c < 3)
3339             {
3340 0           ssl->err = SSL_ALERT_DECODE_ERROR;
3341             psTraceInfo("Invalid Certificate message\n");
3342 0           return MATRIXSSL_ERROR;
3343             }
3344              
3345             # ifdef USE_CERT_CHAIN_PARSING
3346             SKIP_CERT_CHAIN_INIT:
3347             if (ssl->rec.partial)
3348             {
3349             /* It is possible to activate the CERT_STREAM_PARSE feature and not
3350             receive a cert chain in multiple buffers. If we are not flagged
3351             for 'partial' parsing, we can drop into the standard parse case */
3352             while (end - c > 0)
3353             {
3354             certLen = *c << 16; c++;
3355             certLen |= *c << 8; c++;
3356             certLen |= *c; c++;
3357             if ((parseLen = parseSingleCert(ssl, c, end, certLen)) < 0 )
3358             {
3359             return parseLen;
3360             }
3361             ssl->rec.hsBytesParsed += parseLen + 3; /* 3 for certLen */
3362             c += parseLen;
3363             }
3364             if (ssl->rec.hsBytesParsed < ssl->rec.trueLen)
3365             {
3366             *cp = c;
3367             return MATRIXSSL_SUCCESS;
3368             }
3369              
3370             psAssert(ssl->rec.hsBytesParsed == ssl->rec.trueLen);
3371             /* Got it all. Disable the stream mechanism. */
3372             ssl->rec.partial = 0x0;
3373             ssl->rec.hsBytesParsed = 0;
3374             ssl->rec.hsBytesHashed = 0;
3375             }
3376             else
3377             {
3378             psAssert(certChainLen > 0);
3379             # endif /* USE_CERT_CHAIN_PARSING */
3380 1148           i = 0;
3381 1148           currentCert = NULL;
3382              
3383             # if defined(USE_HARDWARE_CRYPTO_PKA) || defined(USE_EXT_CERTIFICATE_VERIFY_SIGNING)
3384             /* Skip re-parsing the certs if pending. The above few bytes are fine */
3385             if (ssl->hwflags & SSL_HWFLAGS_PENDING_PKA_R)
3386             {
3387             c += certChainLen;
3388             ssl->hwflags &= ~SSL_HWFLAGS_PENDING_PKA_R;
3389             goto RESUME_VALIDATE_CERTS;
3390             }
3391             # endif /* USE_HARDWARE_CRYPTO_PKA || USE_EXT_CERTIFICATE_VERIFY_SIGNING */
3392             /* Chain must be at least 3 b certLen */
3393 2297 100         while (certChainLen >= 3)
3394             {
3395 1149           int32 certFlags = 0;
3396              
3397 1149           certLen = *c << 16; c++;
3398 1149           certLen |= *c << 8; c++;
3399 1149           certLen |= *c; c++;
3400 1149           certChainLen -= 3;
3401              
3402 1149 50         if ((uint32) (end - c) < certLen || (int32) certLen > certChainLen)
    50          
3403             {
3404 0           ssl->err = SSL_ALERT_DECODE_ERROR;
3405             psTraceInfo("Invalid certificate length\n");
3406 0           return MATRIXSSL_ERROR;
3407             }
3408 1149 50         if (ssl->bFlags & BFLAG_KEEP_PEER_CERT_DER)
3409             {
3410 0           certFlags |= CERT_STORE_UNPARSED_BUFFER;
3411             }
3412             /*
3413             Extract the binary cert message into the cert structure
3414             */
3415 1149 50         if ((parseLen = psX509ParseCert(ssl->hsPool, c, certLen, &cert, certFlags))
3416             < 0)
3417             {
3418             psTraceInfo("Parsing of the peer certificate failed\n");
3419 0           psX509FreeCert(cert);
3420 0 0         if (parseLen == PS_MEM_FAIL)
3421             {
3422 0           ssl->err = SSL_ALERT_INTERNAL_ERROR;
3423             }
3424             else
3425             {
3426 0           ssl->err = SSL_ALERT_BAD_CERTIFICATE;
3427             }
3428 0           return MATRIXSSL_ERROR;
3429             }
3430             # ifdef ALLOW_VERSION_1_ROOT_CERT_PARSE
3431             /* When ALLOW_VERSION_1_ROOT_CERT_PARSE is defined,
3432             psX509ParseCert lets version 1 certificates through, in
3433             order to support loading of locally trusted v1 root
3434             certs. This means that we need to explicitly reject v1
3435             certificates sent to us by the peer. They cannot be
3436             trusted due to missing Basic Constraints, etc. */
3437             if (cert->version != 2)
3438             {
3439             psTraceInfo("Version 1 peer certificates not allowed\n");
3440             ssl->err = SSL_ALERT_BAD_CERTIFICATE;
3441             }
3442             # endif /* ALLOW_VERSION_1_ROOT_CERT_PARSE */
3443 1149           c += parseLen;
3444              
3445 1149 100         if (i++ == 0)
3446             {
3447 1148           ssl->sec.cert = cert;
3448 1148           currentCert = ssl->sec.cert;
3449             }
3450             else
3451             {
3452 1           currentCert->next = cert;
3453 1           currentCert = currentCert->next;
3454             }
3455 1149           certChainLen -= certLen;
3456             }
3457             # ifdef USE_CERT_CHAIN_PARSING
3458             }
3459             # endif /* USE_CERT_CHAIN_PARSING */
3460              
3461             # ifdef USE_CLIENT_SIDE_SSL
3462             /* Now want to test to see if supplied child-most cert is the appropriate
3463             pubkey algorithm for the chosen cipher suite. Have seen test
3464             cases with OpenSSL where an RSA cert will be sent for an ECDHE_ECDSA
3465             suite, for example. Just testing on the client side because client
3466             auth is a bit more flexible on the algorithm choices. */
3467 1148 50         if (!(ssl->flags & SSL_FLAGS_SERVER))
3468             {
3469 1148 50         if (csCheckCertAgainstCipherSuite(ssl->sec.cert->publicKey.type,
3470 1148           ssl->cipher->type) == 0)
3471             {
3472             psTraceIntInfo("Server sent bad pubkey type for cipher suite %d\n",
3473             ssl->cipher->type);
3474 0           ssl->err = SSL_ALERT_UNSUPPORTED_CERTIFICATE;
3475 0           return MATRIXSSL_ERROR;
3476             }
3477             }
3478             # endif
3479              
3480             /* Time to authenticate the supplied cert against our CAs */
3481             # if defined(USE_HARDWARE_CRYPTO_PKA) || defined(USE_EXT_CERTIFICATE_VERIFY_SIGNING)
3482             RESUME_VALIDATE_CERTS:
3483             # endif /* USE_HARDWARE_CRYPTO_PKA || USE_EXT_CERTIFICATE_VERIFY_SIGNING */
3484              
3485 1148 50         rc = matrixValidateCertsExt(ssl->hsPool, ssl->sec.cert,
3486 2296           ssl->keys == NULL ? NULL : ssl->keys->CAcerts, ssl->expectedName,
3487 1148           &foundIssuer, pkiData, ssl->memAllocPtr, &ssl->validateCertsOpts);
3488              
3489 1148 50         if (rc == PS_MEM_FAIL)
3490             {
3491 0           ssl->err = SSL_ALERT_INTERNAL_ERROR;
3492 0           return MATRIXSSL_ERROR;
3493             }
3494             /* Now walk the subject certs and convert any parse or authentication error
3495             into an SSL alert. The alerts SHOULD be read by the user callback
3496             to determine whether they are fatal or not. If no user callback,
3497             the first alert will be considered fatal. */
3498 1148           cert = ssl->sec.cert;
3499 1148           pathLen = 0;
3500 2297 100         while (cert)
3501             {
3502 1149           ++pathLen;
3503 1149 50         if (ssl->validateCertsOpts.max_verify_depth > 0)
3504             {
3505 0           int exceeded = 0;
3506             psTraceIntInfo("max_verify_depth: %d\n", ssl->validateCertsOpts.max_verify_depth);
3507             /*
3508             A maximum verification depth has been specified in session opts.
3509             */
3510 0 0         if (pathLen > (ssl->validateCertsOpts.max_verify_depth))
3511             {
3512 0           exceeded = 1;
3513             }
3514 0 0         else if (pathLen == (ssl->validateCertsOpts.max_verify_depth))
3515             {
3516             /*
3517             We don't have the root in cert->next. So do the
3518             following: If the cert is _not_ self-signed, it must
3519             have a valid root cert as the issuer, since this
3520             is checked in matrixValidateCerts. Now take that root
3521             into account when checking the path length.
3522             */
3523 0 0         if (memcmpct(&cert->subject, &cert->issuer,
3524             sizeof(cert->subject)))
3525             {
3526             /* Root cert causes depth to be exceeded. */
3527 0           exceeded = 1;
3528             }
3529             }
3530 0 0         if (exceeded)
3531             {
3532             /* Max depth exceeded. */
3533             psTraceInfo("Error: max_verify_depth exceeded\n");
3534 0           ssl->err = SSL_ALERT_UNKNOWN_CA;
3535 0           cert->authStatus |= PS_CERT_AUTH_FAIL_PATH_LEN;
3536 0           cert->authFailFlags |= PS_CERT_AUTH_FAIL_VERIFY_DEPTH_FLAG;
3537             }
3538             }
3539 1149 50         if (ssl->err != SSL_ALERT_NONE)
3540             {
3541 0           break; /* The first alert is the logical one to send */
3542             }
3543 1149           switch (cert->authStatus)
3544             {
3545             case PS_CERT_AUTH_FAIL_SIG:
3546 0           ssl->err = SSL_ALERT_BAD_CERTIFICATE;
3547 0           break;
3548             case PS_CERT_AUTH_FAIL_REVOKED:
3549 0           ssl->err = SSL_ALERT_CERTIFICATE_REVOKED;
3550 0           break;
3551             case PS_CERT_AUTH_FAIL_AUTHKEY:
3552             case PS_CERT_AUTH_FAIL_PATH_LEN:
3553 0           ssl->err = SSL_ALERT_BAD_CERTIFICATE;
3554 0           break;
3555             case PS_CERT_AUTH_FAIL_EXTENSION:
3556             /* The math and basic constraints matched. This case is
3557             for X.509 extension mayhem */
3558 1146 50         if (cert->authFailFlags & PS_CERT_AUTH_FAIL_DATE_FLAG)
3559             {
3560 0           ssl->err = SSL_ALERT_CERTIFICATE_EXPIRED;
3561             }
3562 1146 50         else if (cert->authFailFlags & PS_CERT_AUTH_FAIL_SUBJECT_FLAG)
3563             {
3564             /* expectedName was giving to NewSession but couldn't
3565             match what the peer gave us */
3566 0           ssl->err = SSL_ALERT_CERTIFICATE_UNKNOWN;
3567             }
3568 1146 50         else if (cert->next != NULL)
3569             {
3570             /* This is an extension problem in the chain.
3571             Even if it's minor, we are shutting it down */
3572 0           ssl->err = SSL_ALERT_BAD_CERTIFICATE;
3573             }
3574             else
3575             {
3576             /* This is the case where we did successfully find the
3577             correct CA to validate the cert and the math passed
3578             but the extensions had a problem. Give app a
3579             different message in this case */
3580 1146           ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
3581             }
3582 1146           break;
3583             case PS_CERT_AUTH_FAIL_BC:
3584             case PS_CERT_AUTH_FAIL_DN:
3585             /* These two are pre-math tests. If this was a problem in the
3586             middle of the chain it means the chain couldn't even
3587             validate itself. If it is at the end it means a matching
3588             CA could not be found */
3589 1 50         if (cert->next != NULL)
3590             {
3591 0           ssl->err = SSL_ALERT_BAD_CERTIFICATE;
3592             }
3593             else
3594             {
3595 1           ssl->err = SSL_ALERT_UNKNOWN_CA;
3596             }
3597 1           break;
3598              
3599             default:
3600 2           break;
3601             }
3602 1149           cert = cert->next;
3603             }
3604              
3605             /* The last thing we want to check before passing the certificates to
3606             the user callback is the case in which we don't have any
3607             CA files loaded but we were passed a valid chain that was
3608             terminated with a self-signed cert. The fact that a CA on this
3609             peer has not validated the chain should result in an UNKNOWN_CA alert
3610              
3611             NOTE: This case should only ever get hit if VALIDATE_KEY_MATERIAL
3612             has been disabled in matrixssllib.h */
3613              
3614 1148 100         if (ssl->err == SSL_ALERT_NONE &&
    50          
3615 1 50         (ssl->keys == NULL || ssl->keys->CAcerts == NULL))
3616             {
3617 0           ssl->err = SSL_ALERT_UNKNOWN_CA;
3618             psTraceInfo("WARNING: Valid self-signed cert or cert chain but no local authentication\n");
3619 0           rc = -1; /* Force the check on existence of user callback */
3620             }
3621              
3622 1148 100         if (rc < 0)
3623             {
3624             psTraceInfo("WARNING: cert did not pass internal validation test\n");
3625             /* Cert auth failed. If there is no user callback issue fatal alert
3626             because there will be no intervention to give it a second look. */
3627 1 50         if (ssl->sec.validateCert == NULL)
3628             {
3629             /* ssl->err should have been set correctly above but catch
3630             any missed cases with the generic BAD_CERTIFICATE alert */
3631 0 0         if (ssl->err == SSL_ALERT_NONE)
3632             {
3633 0           ssl->err = SSL_ALERT_BAD_CERTIFICATE;
3634             }
3635 0           return MATRIXSSL_ERROR;
3636             }
3637             }
3638              
3639             # ifdef SERVER_WILL_ACCEPT_EMPTY_CLIENT_CERT_MSG
3640             STRAIGHT_TO_USER_CALLBACK:
3641             # endif
3642              
3643             /* Return from user validation space with knowledge that there is a fatal
3644             alert or that this is an ANONYMOUS connection. */
3645 1148           rc = matrixUserCertValidator(ssl, ssl->err, ssl->sec.cert,
3646             ssl->sec.validateCert);
3647             /* Test what the user callback returned. */
3648 1148           ssl->sec.anon = 0;
3649 1148 100         if (rc == SSL_ALLOW_ANON_CONNECTION)
3650             {
3651 11           ssl->sec.anon = 1;
3652             }
3653 1137 100         else if (rc > 0)
3654             {
3655             /* User returned an alert. May or may not be the alert that was
3656             determined above */
3657             psTraceIntInfo("Certificate authentication alert %d\n", rc);
3658 70           ssl->err = rc;
3659 70           return MATRIXSSL_ERROR;
3660             }
3661 1067 100         else if (rc < 0)
3662             {
3663             psTraceIntInfo("User certificate callback had an internal error\n", rc);
3664 20           ssl->err = SSL_ALERT_INTERNAL_ERROR;
3665 20           return MATRIXSSL_ERROR;
3666             }
3667              
3668             /* User callback returned 0 (continue on). Did they determine the alert
3669             was not fatal after all? */
3670 1058 100         if (ssl->err != SSL_ALERT_NONE)
3671             {
3672             psTraceIntInfo("User certificate callback determined alert %d was NOT fatal\n",
3673             ssl->err);
3674 1057           ssl->err = SSL_ALERT_NONE;
3675             }
3676              
3677             /* Either a client or server could have been processing the cert as part of
3678             the authentication process. If server, we move to the client key
3679             exchange state. */
3680 1058 50         if (ssl->flags & SSL_FLAGS_SERVER)
3681             {
3682 0           ssl->hsState = SSL_HS_CLIENT_KEY_EXCHANGE;
3683             }
3684             else
3685             {
3686 1058           ssl->hsState = SSL_HS_SERVER_HELLO_DONE;
3687             # ifdef USE_DHE_CIPHER_SUITE
3688 1058 100         if (ssl->flags & SSL_FLAGS_DHE_KEY_EXCH)
3689             {
3690 1057           ssl->hsState = SSL_HS_SERVER_KEY_EXCHANGE;
3691             }
3692             # endif /* USE_DHE_CIPHER_SUITE */
3693             # ifdef USE_OCSP
3694             /* State management for OCSP use. Testing if we received a
3695             status_request from the server to set next expected state */
3696 1058 50         if (ssl->extFlags.status_request || ssl->extFlags.status_request_v2)
    50          
3697             {
3698             /* Why do they allow an ambiguous state here?! From RFC 6066:
3699              
3700             Note that a server MAY also choose not to send a
3701             "CertificateStatus" message, even if has received a
3702             "status_request" extension in the client hello message and has
3703             sent a "status_request" extension in the server hello message */
3704 0           ssl->hsState = SSL_HS_CERTIFICATE_STATUS;
3705             }
3706             # endif
3707             }
3708 1058           *cp = c;
3709 1058           ssl->decState = SSL_HS_CERTIFICATE;
3710 1148           return MATRIXSSL_SUCCESS;
3711             }
3712             # endif /* USE_CLIENT_SIDE_SSL || USE_CLIENT_AUTH */
3713             #endif /* !USE_ONLY_PSK_CIPHER_SUITE */
3714              
3715             /******************************************************************************/
3716