Busybox: Upgrade to 1.21.1 (stable). lsof active.
[tomato.git] / release / src / router / matrixssl / src / sslDecode.c
blobccdde5ccc704a907c4e97cd78d9435977ca79469
1 /*
2 * sslDecode.c
3 * Release $Name: MATRIXSSL_1_8_8_OPEN $
5 * Secure Sockets Layer message decoding
6 */
7 /*
8 * Copyright (c) PeerSec Networks, 2002-2009. All Rights Reserved.
9 * The latest version of this code is available at http://www.matrixssl.org
11 * This software is open source; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This General Public License does NOT permit incorporating this software
17 * into proprietary programs. If you are unable to comply with the GPL, a
18 * commercial license for this software may be purchased from PeerSec Networks
19 * at http://www.peersec.com
21 * This program is distributed in WITHOUT ANY WARRANTY; without even the
22 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
23 * See the GNU General Public License for more details.
25 * You should have received a copy of the GNU General Public License
26 * along with this program; if not, write to the Free Software
27 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 * http://www.gnu.org/copyleft/gpl.html
30 /******************************************************************************/
32 #include "matrixInternal.h"
34 /******************************************************************************/
36 #define SSL_MAX_IGNORED_MESSAGE_COUNT 1024
38 static int32 parseSSLHandshake(ssl_t *ssl, char *inbuf, int32 len);
39 static int32 parseSingleCert(ssl_t *ssl, unsigned char *c, unsigned char *end,
40 int32 certLen);
42 /******************************************************************************/
44 Parse incoming data per http://wp.netscape.com/eng/ssl3
46 int32 matrixSslDecode(ssl_t *ssl, sslBuf_t *in, sslBuf_t *out,
47 unsigned char *error, unsigned char *alertLevel,
48 unsigned char *alertDescription)
50 unsigned char *c, *p, *end, *pend, *oend;
51 unsigned char *mac, macError;
52 int32 rc;
53 unsigned char padLen;
55 If we've had a protocol error, don't allow further use of the session
57 *error = SSL_ALERT_NONE;
58 if (ssl->flags & SSL_FLAGS_ERROR || ssl->flags & SSL_FLAGS_CLOSED) {
59 return SSL_ERROR;
62 This flag is set if the previous call to this routine returned an SSL_FULL
63 error from encodeResponse, indicating that there is data to be encoded,
64 but the out buffer was not big enough to handle it. If we fall in this
65 case, the user has increased the out buffer size and is re-calling this
66 routine
68 if (ssl->flags & SSL_FLAGS_NEED_ENCODE) {
69 ssl->flags &= ~SSL_FLAGS_NEED_ENCODE;
70 goto encodeResponse;
73 c = in->start;
74 end = in->end;
75 oend = out->end;
77 Processing the SSL Record header:
78 If the high bit of the first byte is set and this is the first
79 message we've seen, we parse the request as an SSLv2 request
80 http://wp.netscape.com/eng/security/SSL_2.html
81 SSLv2 also supports a 3 byte header when padding is used, but this should
82 not be required for the initial plaintext message, so we don't support it
83 v3 Header:
84 1 byte type
85 1 byte major version
86 1 byte minor version
87 2 bytes length
88 v2 Header
89 2 bytes length (ignore high bit)
91 decodeMore:
92 sslAssert(out->end == oend);
93 if (end - c == 0) {
95 This case could happen if change cipher spec was last
96 message in the buffer
98 return SSL_SUCCESS;
101 if (end - c < SSL2_HEADER_LEN) {
102 return SSL_PARTIAL;
104 if (ssl->majVer != 0 || (*c & 0x80) == 0) {
105 if (end - c < ssl->recordHeadLen) {
106 return SSL_PARTIAL;
108 ssl->rec.type = *c; c++;
109 ssl->rec.majVer = *c; c++;
110 ssl->rec.minVer = *c; c++;
111 ssl->rec.len = *c << 8; c++;
112 ssl->rec.len += *c; c++;
113 } else {
114 ssl->rec.type = SSL_RECORD_TYPE_HANDSHAKE;
115 ssl->rec.majVer = 2;
116 ssl->rec.minVer = 0;
117 ssl->rec.len = (*c & 0x7f) << 8; c++;
118 ssl->rec.len += *c; c++;
121 Validate the various record headers. The type must be valid,
122 the major and minor versions must match the negotiated versions (if we're
123 past ClientHello) and the length must be < 16K and > 0
125 if (ssl->rec.type != SSL_RECORD_TYPE_CHANGE_CIPHER_SPEC &&
126 ssl->rec.type != SSL_RECORD_TYPE_ALERT &&
127 ssl->rec.type != SSL_RECORD_TYPE_HANDSHAKE &&
128 ssl->rec.type != SSL_RECORD_TYPE_APPLICATION_DATA) {
129 ssl->err = SSL_ALERT_UNEXPECTED_MESSAGE;
130 matrixIntDebugMsg("Record header type not valid: %d\n", ssl->rec.type);
131 goto encodeResponse;
135 Verify the record version numbers unless this is the first record we're
136 reading.
138 if (ssl->hsState != SSL_HS_SERVER_HELLO &&
139 ssl->hsState != SSL_HS_CLIENT_HELLO) {
140 if (ssl->rec.majVer != ssl->majVer || ssl->rec.minVer != ssl->minVer) {
141 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
142 matrixStrDebugMsg("Record header version not valid\n", NULL);
143 goto encodeResponse;
147 Verify max and min record lengths
149 if (ssl->rec.len > SSL_MAX_RECORD_LEN || ssl->rec.len == 0) {
150 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
151 matrixIntDebugMsg("Record header length not valid: %d\n", ssl->rec.len);
152 goto encodeResponse;
155 This implementation requires the entire SSL record to be in the 'in' buffer
156 before we parse it. This is because we need to MAC the entire record before
157 allowing it to be used by the caller. The only alternative would be to
158 copy the partial record to an internal buffer, but that would require more
159 memory usage, which we're trying to keep low.
161 if (end - c < ssl->rec.len) {
162 return SSL_PARTIAL;
166 Make sure we have enough room to hold the decoded record
168 if ((out->buf + out->size) - out->end < ssl->rec.len) {
169 return SSL_FULL;
173 Decrypt the entire record contents. The record length should be
174 a multiple of block size, or decrypt will return an error
175 If we're still handshaking and sending plaintext, the decryption
176 callback will point to a null provider that passes the data unchanged
178 if (ssl->decrypt(&ssl->sec.decryptCtx, c, out->end, ssl->rec.len) < 0) {
179 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
180 goto encodeResponse;
182 c += ssl->rec.len;
184 If we're reading a secure message, we need to validate the MAC and
185 padding (if using a block cipher). Insecure messages do not have
186 a trailing MAC or any padding.
188 SECURITY - There are several vulnerabilities in block cipher padding
189 that we handle in the below code. For more information see:
190 http://www.openssl.org/~bodo/tls-cbc.txt
192 if (ssl->flags & SSL_FLAGS_READ_SECURE) {
194 Verify the record is at least as big as the MAC
195 Start tracking MAC errors, rather then immediately catching them to
196 stop timing and alert description attacks that differentiate between
197 a padding error and a MAC error.
199 if (ssl->rec.len < ssl->deMacSize) {
200 ssl->err = SSL_ALERT_BAD_RECORD_MAC;
201 matrixStrDebugMsg("Record length too short for MAC\n", NULL);
202 goto encodeResponse;
204 macError = 0;
206 Decode padding only if blocksize is > 0 (we're using a block cipher),
207 otherwise no padding will be present, and the mac is the last
208 macSize bytes of the record.
210 if (ssl->deBlockSize <= 1) {
211 mac = out->end + ssl->rec.len - ssl->deMacSize;
212 } else {
214 Verify the pad data for block ciphers
215 c points within the cipher text, p points within the plaintext
216 The last byte of the record is the pad length
218 p = out->end + ssl->rec.len;
219 padLen = *(p - 1);
221 SSL3.0 requires the pad length to be less than blockSize
222 TLS can have a pad length up to 255 for obfuscating the data len
224 if (ssl->majVer == SSL3_MAJ_VER && ssl->minVer == SSL3_MIN_VER &&
225 padLen >= ssl->deBlockSize) {
226 macError++;
229 The minimum record length is the size of the mac, plus pad bytes
230 plus one length byte
232 if (ssl->rec.len < ssl->deMacSize + padLen + 1) {
233 macError++;
236 The mac starts macSize bytes before the padding and length byte.
237 If we have a macError, just fake the mac as the last macSize bytes
238 of the record, so we are sure to have enough bytes to verify
239 against, we'll fail anyway, so the actual contents don't matter.
241 if (!macError) {
242 mac = p - padLen - 1 - ssl->deMacSize;
243 } else {
244 mac = out->end + ssl->rec.len - ssl->deMacSize;
248 Verify the MAC of the message by calculating our own MAC of the message
249 and comparing it to the one in the message. We do this step regardless
250 of whether or not we've already set macError to stop timing attacks.
251 Clear the mac in the callers buffer if we're successful
253 if (ssl->verifyMac(ssl, ssl->rec.type, out->end,
254 (int32)(mac - out->end), mac) < 0 || macError) {
255 ssl->err = SSL_ALERT_BAD_RECORD_MAC;
256 matrixStrDebugMsg("Couldn't verify MAC or pad of record data\n",
257 NULL);
258 goto encodeResponse;
260 memset(mac, 0x0, ssl->deMacSize);
262 Record data starts at out->end and ends at mac
264 p = out->end;
265 pend = mac;
266 } else {
268 The record data is the entire record as there is no MAC or padding
270 p = out->end;
271 pend = mac = out->end + ssl->rec.len;
274 Check now for maximum plaintext length of 16kb. No appropriate
275 SSL alert for this
277 if ((int32)(pend - p) > SSL_MAX_PLAINTEXT_LEN) {
278 ssl->err = SSL_ALERT_BAD_RECORD_MAC;
279 matrixStrDebugMsg("Record overflow\n", NULL);
280 goto encodeResponse;
284 Take action based on the actual record type we're dealing with
285 'p' points to the start of the data, and 'pend' points to the end
287 switch (ssl->rec.type) {
288 case SSL_RECORD_TYPE_CHANGE_CIPHER_SPEC:
290 Body is single byte with value 1 to indicate that the next message
291 will be encrypted using the negotiated cipher suite
293 if (pend - p < 1) {
294 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
295 matrixStrDebugMsg("Invalid length for CipherSpec\n", NULL);
296 goto encodeResponse;
298 if (*p == 1) {
299 p++;
300 } else {
301 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
302 matrixStrDebugMsg("Invalid value for CipherSpec\n", NULL);
303 goto encodeResponse;
307 If we're expecting finished, then this is the right place to get
308 this record. It is really part of the handshake but it has its
309 own record type.
310 Activate the read cipher callbacks, so we will decrypt incoming
311 data from now on.
313 if (ssl->hsState == SSL_HS_FINISHED) {
314 sslActivateReadCipher(ssl);
315 } else {
316 ssl->err = SSL_ALERT_UNEXPECTED_MESSAGE;
317 matrixIntDebugMsg("Invalid CipherSpec order: %d\n", ssl->hsState);
318 goto encodeResponse;
320 in->start = c;
321 goto decodeMore;
323 case SSL_RECORD_TYPE_ALERT:
325 1 byte alert level (warning or fatal)
326 1 byte alert description corresponding to SSL_ALERT_*
328 if (pend - p < 2) {
329 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
330 matrixStrDebugMsg("Error in length of alert record\n", NULL);
331 goto encodeResponse;
333 *alertLevel = *p; p++;
334 *alertDescription = *p; p++;
336 If the alert is fatal, or is a close message (usually a warning),
337 flag the session with ERROR so it cannot be used anymore.
338 Caller can decide whether or not to close on other warnings.
340 if (*alertLevel == SSL_ALERT_LEVEL_FATAL) {
341 ssl->flags |= SSL_FLAGS_ERROR;
343 if (*alertDescription == SSL_ALERT_CLOSE_NOTIFY) {
344 ssl->flags |= SSL_FLAGS_CLOSED;
346 return SSL_ALERT;
348 case SSL_RECORD_TYPE_HANDSHAKE:
350 We've got one or more handshake messages in the record data.
351 The handshake parsing function will take care of all messages
352 and return an error if there is any problem.
353 If there is a response to be sent (either a return handshake
354 or an error alert, send it). If the message was parsed, but no
355 response is needed, loop up and try to parse another message
357 rc = parseSSLHandshake(ssl, (char*)p, (int32)(pend - p));
358 switch (rc) {
359 case SSL_SUCCESS:
360 in->start = c;
361 return SSL_SUCCESS;
362 case SSL_PROCESS_DATA:
363 in->start = c;
364 goto encodeResponse;
365 case SSL_ERROR:
366 if (ssl->err == SSL_ALERT_NONE) {
367 ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
369 goto encodeResponse;
371 break;
373 case SSL_RECORD_TYPE_APPLICATION_DATA:
375 Data is in the out buffer, let user handle it
376 Don't allow application data until handshake is complete, and we are
377 secure. It is ok to let application data through on the client
378 if we are in the SERVER_HELLO state because this could mean that
379 the client has sent a CLIENT_HELLO message for a rehandshake
380 and is awaiting reply.
382 if ((ssl->hsState != SSL_HS_DONE && ssl->hsState != SSL_HS_SERVER_HELLO)
383 || !(ssl->flags & SSL_FLAGS_READ_SECURE)) {
384 ssl->err = SSL_ALERT_UNEXPECTED_MESSAGE;
385 matrixIntDebugMsg("Incomplete handshake: %d\n", ssl->hsState);
386 goto encodeResponse;
389 SECURITY - If the mac is at the current out->end, then there is no data
390 in the record. These records are valid, but are usually not sent by
391 the application layer protocol. Rather, they are initiated within the
392 remote SSL protocol implementation to avoid some types of attacks when
393 using block ciphers. For more information see:
394 http://www.openssl.org/~bodo/tls-cbc.txt
396 We eat these records here rather than passing them on to the caller.
397 The rationale behind this is that if the caller's application protocol
398 is depending on zero length SSL messages, it will fail anyway if some of
399 those messages are initiated within the SSL protocol layer. Also
400 this clears up any confusion where the caller might interpret a zero
401 length read as an end of file (EOF) or would block (EWOULDBLOCK) type
402 scenario.
404 SECURITY - Looping back up and ignoring the message has the potential
405 for denial of service, because we are not changing the state of the
406 system in any way when processing these messages. To counteract this,
407 we maintain a counter that we share with other types of ignored messages
409 in->start = c;
410 if (out->end == mac) {
411 if (ssl->ignoredMessageCount++ < SSL_MAX_IGNORED_MESSAGE_COUNT) {
412 goto decodeMore;
414 ssl->err = SSL_ALERT_UNEXPECTED_MESSAGE;
415 matrixIntDebugMsg("Exceeded limit on ignored messages: %d\n",
416 SSL_MAX_IGNORED_MESSAGE_COUNT);
417 goto encodeResponse;
419 if (ssl->ignoredMessageCount > 0) {
420 ssl->ignoredMessageCount--;
422 out->end = mac;
423 return SSL_PROCESS_DATA;
426 Should not get here
428 matrixIntDebugMsg("Invalid record type in matrixSslDecode: %d\n",
429 ssl->rec.type);
430 return SSL_ERROR;
432 encodeResponse:
434 We decoded a record that needs a response, either a handshake response
435 or an alert if we've detected an error.
437 SECURITY - Clear the decoded incoming record from outbuf before encoding
438 the response into outbuf. rec.len could be invalid, clear the minimum
439 of rec.len and remaining outbuf size
441 rc = min (ssl->rec.len, (int32)((out->buf + out->size) - out->end));
442 if (rc > 0) {
443 memset(out->end, 0x0, rc);
445 if (ssl->hsState == SSL_HS_HELLO_REQUEST) {
447 Don't clear the session info. If receiving a HELLO_REQUEST from a
448 MatrixSSL enabled server the determination on whether to reuse the
449 session is made on that side, so always send the current session
451 rc = matrixSslEncodeClientHello(ssl, out, ssl->cipher->id);
452 } else {
453 rc = sslEncodeResponse(ssl, out);
455 if (rc == SSL_SUCCESS) {
456 if (ssl->err != SSL_ALERT_NONE) {
457 *error = (unsigned char)ssl->err;
458 ssl->flags |= SSL_FLAGS_ERROR;
459 return SSL_ERROR;
461 return SSL_SEND_RESPONSE;
463 if (rc == SSL_FULL) {
464 ssl->flags |= SSL_FLAGS_NEED_ENCODE;
465 return SSL_FULL;
467 return SSL_ERROR;
470 /******************************************************************************/
472 The workhorse for parsing handshake messages. Also enforces the state
473 machine for proper ordering of handshake messages.
474 Parameters:
475 ssl - ssl context
476 inbuf - buffer to read handshake message from
477 len - data length for the current ssl record. The ssl record
478 can contain multiple handshake messages, so we may need to parse
479 them all here.
480 Return:
481 SSL_SUCCESS
482 SSL_PROCESS_DATA
483 SSL_ERROR - see ssl->err for details
485 static int32 parseSSLHandshake(ssl_t *ssl, char *inbuf, int32 len)
487 unsigned char *c;
488 unsigned char *end;
489 unsigned char hsType;
490 int32 i, hsLen, rc, parseLen = 0;
491 uint32 cipher = 0;
492 unsigned char hsMsgHash[SSL_MD5_HASH_SIZE + SSL_SHA1_HASH_SIZE];
494 #ifdef USE_SERVER_SIDE_SSL
495 unsigned char *p;
496 int32 suiteLen, challengeLen, pubKeyLen, extLen;
497 #endif /* USE_SERVER_SIDE_SSL */
499 #ifdef USE_CLIENT_SIDE_SSL
500 int32 sessionIdLen, certMatch, certTypeLen;
501 sslCert_t *subjectCert;
502 int32 valid, certLen, certChainLen, anonCheck;
503 sslCert_t *cert, *currentCert;
504 #endif /* USE_CLIENT_SIDE_SSL */
506 rc = SSL_SUCCESS;
507 c = (unsigned char*)inbuf;
508 end = (unsigned char*)(inbuf + len);
511 parseHandshake:
512 if (end - c < 1) {
513 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
514 matrixStrDebugMsg("Invalid length of handshake message\n", NULL);
515 return SSL_ERROR;
517 hsType = *c; c++;
519 #ifndef ALLOW_SERVER_REHANDSHAKES
521 Disables server renegotiation. This is in response to the HTTPS
522 flaws discovered by Marsh Ray in which a man-in-the-middle may take
523 advantage of the "authentication gap" in the SSL renegotiation protocol
525 if (hsType == SSL_HS_CLIENT_HELLO && ssl->hsState == SSL_HS_DONE) {
526 ssl->err = SSL_ALERT_UNEXPECTED_MESSAGE;
527 matrixStrDebugMsg("Server rehandshaking is disabled\n", NULL);
528 return SSL_ERROR;
530 #endif /* ALLOW_SERVER_REHANDSHAKES */
533 hsType is the received handshake type and ssl->hsState is the expected
534 handshake type. If it doesn't match, there are some possible cases
535 that are not errors. These are checked here.
537 if (hsType != ssl->hsState &&
538 (hsType != SSL_HS_CLIENT_HELLO || ssl->hsState != SSL_HS_DONE)) {
541 A mismatch is possible in the client authentication case.
542 The optional CERTIFICATE_REQUEST may be appearing instead of
543 SERVER_HELLO_DONE.
545 if ((hsType == SSL_HS_CERTIFICATE_REQUEST) &&
546 (ssl->hsState == SSL_HS_SERVER_HELLO_DONE)) {
548 This is where the client is first aware of requested client
549 authentication so we set the flag here.
551 ssl->flags |= SSL_FLAGS_CLIENT_AUTH;
552 ssl->hsState = SSL_HS_CERTIFICATE_REQUEST;
553 goto hsStateDetermined;
556 Another possible mismatch allowed is for a HELLO_REQEST message.
557 Indicates a rehandshake initiated from the server.
559 if ((hsType == SSL_HS_HELLO_REQUEST) &&
560 (ssl->hsState == SSL_HS_DONE) &&
561 !(ssl->flags & SSL_FLAGS_SERVER)) {
562 sslResetContext(ssl);
563 ssl->hsState = hsType;
564 goto hsStateDetermined;
569 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
570 matrixIntDebugMsg("Invalid type of handshake message: %d\n", hsType);
571 return SSL_ERROR;
574 hsStateDetermined:
575 if (hsType == SSL_HS_CLIENT_HELLO) {
576 sslInitHSHash(ssl);
577 if (ssl->hsState == SSL_HS_DONE) {
579 Rehandshake. Server receiving client hello on existing connection
581 sslResetContext(ssl);
582 ssl->hsState = hsType;
587 We need to get a copy of the message hashes to compare to those sent
588 in the finished message (which does not include a hash of itself)
589 before we update the handshake hashes
591 if (ssl->hsState == SSL_HS_FINISHED) {
592 sslSnapshotHSHash(ssl, hsMsgHash,
593 (ssl->flags & SSL_FLAGS_SERVER) ? 0 : SSL_FLAGS_SERVER);
597 Process the handshake header and update the ongoing handshake hash
598 SSLv3:
599 1 byte type
600 3 bytes length
601 SSLv2:
602 1 byte type
604 if (ssl->rec.majVer >= SSL3_MAJ_VER) {
605 if (end - c < 3) {
606 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
607 matrixStrDebugMsg("Invalid length of handshake message\n", NULL);
608 return SSL_ERROR;
610 hsLen = *c << 16; c++;
611 hsLen += *c << 8; c++;
612 hsLen += *c; c++;
613 if (end - c < hsLen) {
614 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
615 matrixStrDebugMsg("Invalid handshake length\n", NULL);
616 return SSL_ERROR;
618 sslUpdateHSHash(ssl, c - ssl->hshakeHeadLen,
619 hsLen + ssl->hshakeHeadLen);
621 } else if (ssl->rec.majVer == SSL2_MAJ_VER) {
623 Assume that the handshake len is the same as the incoming ssl record
624 length minus 1 byte (type), this is verified in SSL_HS_CLIENT_HELLO
626 hsLen = len - 1;
627 sslUpdateHSHash(ssl, (unsigned char*)inbuf, len);
628 } else {
629 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
630 matrixIntDebugMsg("Invalid record version: %d\n", ssl->rec.majVer);
631 return SSL_ERROR;
634 Finished with header. Process each type of handshake message.
636 switch(ssl->hsState) {
638 #ifdef USE_SERVER_SIDE_SSL
639 case SSL_HS_CLIENT_HELLO:
641 First two bytes are the highest supported major and minor SSL versions
642 We support only 3.0 (support 3.1 in commercial version)
644 if (end - c < 2) {
645 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
646 matrixStrDebugMsg("Invalid ssl header version length\n", NULL);
647 return SSL_ERROR;
649 ssl->reqMajVer = *c; c++;
650 ssl->reqMinVer = *c; c++;
651 if (ssl->reqMajVer >= SSL3_MAJ_VER) {
652 ssl->majVer = ssl->reqMajVer;
653 ssl->minVer = SSL3_MIN_VER;
655 } else {
656 ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
657 matrixIntDebugMsg("Unsupported ssl version: %d\n", ssl->reqMajVer);
658 return SSL_ERROR;
661 Support SSLv3 and SSLv2 ClientHello messages. Browsers usually send v2
662 messages for compatibility
664 if (ssl->rec.majVer > SSL2_MAJ_VER) {
666 Next is a 32 bytes of random data for key generation
667 and a single byte with the session ID length
669 if (end - c < SSL_HS_RANDOM_SIZE + 1) {
670 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
671 matrixStrDebugMsg("Invalid length of random data\n", NULL);
672 return SSL_ERROR;
674 memcpy(ssl->sec.clientRandom, c, SSL_HS_RANDOM_SIZE);
675 c += SSL_HS_RANDOM_SIZE;
676 ssl->sessionIdLen = *c; c++;
678 If a session length was specified, the client is asking to
679 resume a previously established session to speed up the handshake.
681 if (ssl->sessionIdLen > 0) {
682 if (ssl->sessionIdLen > SSL_MAX_SESSION_ID_SIZE ||
683 end - c < ssl->sessionIdLen) {
684 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
685 return SSL_ERROR;
687 memcpy(ssl->sessionId, c, ssl->sessionIdLen);
688 c += ssl->sessionIdLen;
690 Look up the session id for ssl session resumption. If found, we
691 load the pre-negotiated masterSecret and cipher.
692 A resumed request must meet the following restrictions:
693 The id must be present in the lookup table
694 The requested version must match the original version
695 The cipher suite list must contain the original cipher suite
697 if (matrixResumeSession(ssl) >= 0) {
698 ssl->flags &= ~SSL_FLAGS_CLIENT_AUTH;
699 ssl->flags |= SSL_FLAGS_RESUMED;
700 } else {
701 memset(ssl->sessionId, 0, SSL_MAX_SESSION_ID_SIZE);
702 ssl->sessionIdLen = 0;
704 } else {
706 Always clear the RESUMED flag if no client session id specified
708 ssl->flags &= ~SSL_FLAGS_RESUMED;
711 Next is the two byte cipher suite list length, network byte order.
712 It must not be zero, and must be a multiple of two.
714 if (end - c < 2) {
715 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
716 matrixStrDebugMsg("Invalid cipher suite list length\n", NULL);
717 return SSL_ERROR;
719 suiteLen = *c << 8; c++;
720 suiteLen += *c; c++;
721 if (suiteLen == 0 || suiteLen & 1) {
722 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
723 matrixIntDebugMsg("Unable to parse cipher suite list: %d\n",
724 suiteLen);
725 return SSL_ERROR;
728 Now is 'suiteLen' bytes of the supported cipher suite list,
729 listed in order of preference. Loop through and find the
730 first cipher suite we support.
732 if (end - c < suiteLen) {
733 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
734 return SSL_ERROR;
736 p = c + suiteLen;
737 while (c < p) {
738 cipher = *c << 8; c++;
739 cipher += *c; c++;
741 A resumed session can only match the cipher originally
742 negotiated. Otherwise, match the first cipher that we support
744 if (ssl->flags & SSL_FLAGS_RESUMED) {
745 sslAssert(ssl->cipher);
746 if (ssl->cipher->id == cipher) {
747 c = p;
748 break;
750 } else {
751 if ((ssl->cipher = sslGetCipherSpec(cipher)) != NULL) {
752 c = p;
753 break;
758 If we fell to the default cipher suite, we didn't have
759 any in common with the client, or the client is being bad
760 and requesting the null cipher!
762 if (ssl->cipher == NULL || ssl->cipher->id != cipher ||
763 cipher == SSL_NULL_WITH_NULL_NULL) {
764 matrixStrDebugMsg("Can't support requested cipher\n", NULL);
765 ssl->cipher = sslGetCipherSpec(SSL_NULL_WITH_NULL_NULL);
766 ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
767 return SSL_ERROR;
771 Bypass the compression parameters. Only supporting mandatory NULL
773 if (end - c < 1) {
774 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
775 matrixStrDebugMsg("Invalid compression header length\n", NULL);
776 return SSL_ERROR;
778 extLen = *c++;
779 if (end - c < extLen) {
780 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
781 matrixStrDebugMsg("Invalid compression header length\n", NULL);
782 return SSL_ERROR;
784 c += extLen;
785 } else {
787 Parse a SSLv2 ClientHello message. The same information is
788 conveyed but the order and format is different.
789 First get the cipher suite length, session id length and challenge
790 (client random) length - all two byte values, network byte order.
792 if (end - c < 6) {
793 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
794 matrixStrDebugMsg("Can't parse hello message\n", NULL);
795 return SSL_ERROR;
797 suiteLen = *c << 8; c++;
798 suiteLen += *c; c++;
799 if (suiteLen == 0 || suiteLen % 3 != 0) {
800 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
801 matrixStrDebugMsg("Can't parse hello message\n", NULL);
802 return SSL_ERROR;
804 ssl->sessionIdLen = *c << 8; c++;
805 ssl->sessionIdLen += *c; c++;
807 A resumed session would use a SSLv3 ClientHello, not SSLv2.
809 if (ssl->sessionIdLen != 0) {
810 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
811 matrixStrDebugMsg("Bad resumption request\n", NULL);
812 return SSL_ERROR;
814 challengeLen = *c << 8; c++;
815 challengeLen += *c; c++;
816 if (challengeLen < 16 || challengeLen > 32) {
817 matrixStrDebugMsg("Bad challenge length\n", NULL);
818 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
819 return SSL_ERROR;
822 Validate the three lengths that were just sent to us, don't
823 want any buffer overflows while parsing the remaining data
825 if (end - c != suiteLen + ssl->sessionIdLen + challengeLen) {
826 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
827 return SSL_ERROR;
830 Parse the cipher suite list similar to the SSLv3 method, except
831 each suite is 3 bytes, instead of two bytes. We define the suite
832 as an integer value, so either method works for lookup.
833 We don't support session resumption from V2 handshakes, so don't
834 need to worry about matching resumed cipher suite.
836 p = c + suiteLen;
837 while (c < p) {
838 cipher = *c << 16; c++;
839 cipher += *c << 8; c++;
840 cipher += *c; c++;
841 if ((ssl->cipher = sslGetCipherSpec(cipher)) != NULL) {
842 c = p;
843 break;
846 if (ssl->cipher == NULL ||
847 ssl->cipher->id == SSL_NULL_WITH_NULL_NULL) {
848 ssl->cipher = sslGetCipherSpec(SSL_NULL_WITH_NULL_NULL);
849 ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
850 matrixStrDebugMsg("Can't support requested cipher\n", NULL);
851 return SSL_ERROR;
854 We don't allow session IDs for v2 ClientHellos
856 if (ssl->sessionIdLen > 0) {
857 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
858 matrixStrDebugMsg("SSLv2 sessions not allowed\n", NULL);
859 return SSL_ERROR;
862 The client random (between 16 and 32 bytes) fills the least
863 significant bytes in the (always) 32 byte SSLv3 client random field.
865 memset(ssl->sec.clientRandom, 0x0, SSL_HS_RANDOM_SIZE);
866 memcpy(ssl->sec.clientRandom + (SSL_HS_RANDOM_SIZE - challengeLen),
867 c, challengeLen);
868 c += challengeLen;
871 ClientHello should be the only one in the record.
873 if (c != end) {
874 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
875 matrixStrDebugMsg("Invalid final client hello length\n", NULL);
876 return SSL_ERROR;
881 If we're resuming a handshake, then the next handshake message we
882 expect is the finished message. Otherwise we do the full handshake.
884 if (ssl->flags & SSL_FLAGS_RESUMED) {
885 ssl->hsState = SSL_HS_FINISHED;
886 } else {
887 ssl->hsState = SSL_HS_CLIENT_KEY_EXCHANGE;
890 Now that we've parsed the ClientHello, we need to tell the caller that
891 we have a handshake response to write out.
892 The caller should call sslWrite upon receiving this return code.
894 rc = SSL_PROCESS_DATA;
895 break;
897 case SSL_HS_CLIENT_KEY_EXCHANGE:
899 RSA: This message contains the premaster secret encrypted with the
900 server's public key (from the Certificate). The premaster
901 secret is 48 bytes of random data, but the message may be longer
902 than that because the 48 bytes are padded before encryption
903 according to PKCS#1v1.5. After encryption, we should have the
904 correct length.
906 if (end - c < hsLen) {
907 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
908 matrixStrDebugMsg("Invalid ClientKeyExchange length\n", NULL);
909 return SSL_ERROR;
911 sslActivatePublicCipher(ssl);
913 pubKeyLen = hsLen;
917 Now have a handshake pool to allocate the premaster storage
919 ssl->sec.premasterSize = SSL_HS_RSA_PREMASTER_SIZE;
920 ssl->sec.premaster = psMalloc(ssl->hsPool,
921 SSL_HS_RSA_PREMASTER_SIZE);
923 if (ssl->decryptPriv(ssl->hsPool, ssl->keys->cert.privKey, c,
924 pubKeyLen, ssl->sec.premaster, ssl->sec.premasterSize)
925 != ssl->sec.premasterSize) {
926 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
927 matrixStrDebugMsg("Failed to decrypt premaster\n", NULL);
928 return SSL_ERROR;
932 The first two bytes of the decrypted message should be the
933 client's requested version number (which may not be the same
934 as the final negotiated version). The other 46 bytes -
935 pure random!
937 SECURITY -
938 Some SSL clients (Including Microsoft IE 6.0) incorrectly set
939 the first two bytes to the negotiated version rather than the
940 requested version. This is known in OpenSSL as the
941 SSL_OP_TLS_ROLLBACK_BUG. We allow this to slide only if we
942 don't support TLS, TLS was requested and the negotiated
943 versions match.
945 if (*ssl->sec.premaster != ssl->reqMajVer) {
946 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
947 matrixStrDebugMsg("Incorrect version in ClientKeyExchange\n",
948 NULL);
949 return SSL_ERROR;
951 if (*(ssl->sec.premaster + 1) != ssl->reqMinVer) {
952 if (ssl->reqMinVer < TLS_MIN_VER ||
953 *(ssl->sec.premaster + 1) != ssl->minVer) {
954 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
955 matrixStrDebugMsg("Incorrect version in ClientKeyExchange\n",
956 NULL);
957 return SSL_ERROR;
962 Now that we've got the premaster secret, derive the various
963 symmetric keys using it and the client and server random values.
964 Update the cached session (if found) with the masterSecret and
965 negotiated cipher.
967 sslDeriveKeys(ssl);
969 matrixUpdateSession(ssl);
971 c += pubKeyLen;
972 ssl->hsState = SSL_HS_FINISHED;
975 break;
976 #endif /* USE_SERVER_SIDE_SSL */
978 case SSL_HS_FINISHED:
980 Before the finished handshake message, we should have seen the
981 CHANGE_CIPHER_SPEC message come through in the record layer, which
982 would have activated the read cipher, and set the READ_SECURE flag.
983 This is the first handshake message that was sent securely.
985 if (!(ssl->flags & SSL_FLAGS_READ_SECURE)) {
986 ssl->err = SSL_ALERT_UNEXPECTED_MESSAGE;
987 matrixStrDebugMsg("Finished before ChangeCipherSpec\n", NULL);
988 return SSL_ERROR;
991 The contents of the finished message is a 16 byte MD5 hash followed
992 by a 20 byte sha1 hash of all the handshake messages so far, to verify
993 that nothing has been tampered with while we were still insecure.
994 Compare the message to the value we calculated at the beginning of
995 this function.
997 if (hsLen != SSL_MD5_HASH_SIZE + SSL_SHA1_HASH_SIZE) {
998 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
999 matrixStrDebugMsg("Invalid Finished length\n", NULL);
1000 return SSL_ERROR;
1002 if (end - c < hsLen) {
1003 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
1004 matrixStrDebugMsg("Invalid Finished length\n", NULL);
1005 return SSL_ERROR;
1007 if (memcmp(c, hsMsgHash, hsLen) != 0) {
1008 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
1009 matrixStrDebugMsg("Invalid handshake msg hash\n", NULL);
1010 return SSL_ERROR;
1012 c += hsLen;
1013 ssl->hsState = SSL_HS_DONE;
1015 Now that we've parsed the Finished message, if we're a resumed
1016 connection, we're done with handshaking, otherwise, we return
1017 SSL_PROCESS_DATA to get our own cipher spec and finished messages
1018 sent out by the caller.
1020 if (ssl->flags & SSL_FLAGS_SERVER) {
1021 if (!(ssl->flags & SSL_FLAGS_RESUMED)) {
1022 rc = SSL_PROCESS_DATA;
1024 } else {
1025 if (ssl->flags & SSL_FLAGS_RESUMED) {
1026 rc = SSL_PROCESS_DATA;
1029 #ifdef USE_CLIENT_SIDE_SSL
1031 Free handshake pool, of which the cert is the primary member.
1032 There is also an attempt to free the handshake pool during
1033 the sending of the finished message to deal with client
1034 and server and differing handshake types. Both cases are
1035 attempted keep the lifespan of this pool as short as possible.
1036 This is the default case for the server side.
1038 if (ssl->sec.cert) {
1039 matrixX509FreeCert(ssl->sec.cert);
1040 ssl->sec.cert = NULL;
1042 #endif /* USE_CLIENT_SIDE */
1043 break;
1045 #ifdef USE_CLIENT_SIDE_SSL
1046 case SSL_HS_HELLO_REQUEST:
1048 No body message and the only one in record flight
1050 if (end - c != 0) {
1051 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
1052 matrixStrDebugMsg("Invalid hello request message\n", NULL);
1053 return SSL_ERROR;
1056 Intentionally not changing state here to SERVER_HELLO. The
1057 encodeResponse case this will fall into needs to distinguish
1058 between calling the normal sslEncodeResponse or encodeClientHello.
1059 The HELLO_REQUEST state is used to make that determination and the
1060 writing of CLIENT_HELLO will properly move the state along itself.
1062 rc = SSL_PROCESS_DATA;
1063 break;
1065 case SSL_HS_SERVER_HELLO:
1067 First two bytes are the negotiated SSL version
1068 We support only 3.0 (other options are 2.0 or 3.1)
1070 if (end - c < 2) {
1071 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
1072 matrixStrDebugMsg("Invalid ssl header version length\n", NULL);
1073 return SSL_ERROR;
1075 ssl->reqMajVer = *c; c++;
1076 ssl->reqMinVer = *c; c++;
1077 if (ssl->reqMajVer != ssl->majVer) {
1078 ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
1079 matrixIntDebugMsg("Unsupported ssl version: %d\n", ssl->reqMajVer);
1080 return SSL_ERROR;
1084 Next is a 32 bytes of random data for key generation
1085 and a single byte with the session ID length
1087 if (end - c < SSL_HS_RANDOM_SIZE + 1) {
1088 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
1089 matrixStrDebugMsg("Invalid length of random data\n", NULL);
1090 return SSL_ERROR;
1092 memcpy(ssl->sec.serverRandom, c, SSL_HS_RANDOM_SIZE);
1093 c += SSL_HS_RANDOM_SIZE;
1094 sessionIdLen = *c; c++;
1095 if (sessionIdLen > SSL_MAX_SESSION_ID_SIZE ||
1096 end - c < sessionIdLen) {
1097 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
1098 return SSL_ERROR;
1101 If a session length was specified, the server has sent us a
1102 session Id. We may have requested a specific session, and the
1103 server may or may not agree to use that session.
1105 if (sessionIdLen > 0) {
1106 if (ssl->sessionIdLen > 0) {
1107 if (memcmp(ssl->sessionId, c, sessionIdLen) == 0) {
1108 ssl->flags |= SSL_FLAGS_RESUMED;
1109 } else {
1110 ssl->cipher = sslGetCipherSpec(SSL_NULL_WITH_NULL_NULL);
1111 memset(ssl->sec.masterSecret, 0x0, SSL_HS_MASTER_SIZE);
1112 ssl->sessionIdLen = sessionIdLen;
1113 memcpy(ssl->sessionId, c, sessionIdLen);
1114 ssl->flags &= ~SSL_FLAGS_RESUMED;
1116 } else {
1117 ssl->sessionIdLen = sessionIdLen;
1118 memcpy(ssl->sessionId, c, sessionIdLen);
1120 c += sessionIdLen;
1121 } else {
1122 if (ssl->sessionIdLen > 0) {
1123 ssl->cipher = sslGetCipherSpec(SSL_NULL_WITH_NULL_NULL);
1124 memset(ssl->sec.masterSecret, 0x0, SSL_HS_MASTER_SIZE);
1125 ssl->sessionIdLen = 0;
1126 memset(ssl->sessionId, 0x0, SSL_MAX_SESSION_ID_SIZE);
1127 ssl->flags &= ~SSL_FLAGS_RESUMED;
1131 Next is the two byte cipher suite
1133 if (end - c < 2) {
1134 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
1135 matrixStrDebugMsg("Invalid cipher suite length\n", NULL);
1136 return SSL_ERROR;
1138 cipher = *c << 8; c++;
1139 cipher += *c; c++;
1142 A resumed session can only match the cipher originally
1143 negotiated. Otherwise, match the first cipher that we support
1145 if (ssl->flags & SSL_FLAGS_RESUMED) {
1146 sslAssert(ssl->cipher);
1147 if (ssl->cipher->id != cipher) {
1148 ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
1149 matrixStrDebugMsg("Can't support resumed cipher\n", NULL);
1150 return SSL_ERROR;
1152 } else {
1153 if ((ssl->cipher = sslGetCipherSpec(cipher)) == NULL) {
1154 ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
1155 matrixStrDebugMsg("Can't support requested cipher\n", NULL);
1156 return SSL_ERROR;
1162 Decode the compression parameters. Always zero.
1163 There are no compression schemes defined for SSLv3
1165 if (end - c < 1 || *c != 0) {
1166 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
1167 matrixStrDebugMsg("Invalid compression value\n", NULL);
1168 return SSL_ERROR;
1171 At this point, if we're resumed, we have all the required info
1172 to derive keys. The next handshake message we expect is
1173 the Finished message.
1175 c++;
1177 if (ssl->flags & SSL_FLAGS_RESUMED) {
1178 sslDeriveKeys(ssl);
1179 ssl->hsState = SSL_HS_FINISHED;
1180 } else {
1181 ssl->hsState = SSL_HS_CERTIFICATE;
1183 break;
1185 case SSL_HS_CERTIFICATE:
1186 if (end - c < 3) {
1187 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
1188 matrixStrDebugMsg("Invalid Certificate message\n", NULL);
1189 return SSL_ERROR;
1191 certChainLen = *c << 16; c++;
1192 certChainLen |= *c << 8; c++;
1193 certChainLen |= *c; c++;
1194 if (certChainLen == 0) {
1195 if (ssl->majVer == SSL3_MAJ_VER && ssl->minVer == SSL3_MIN_VER) {
1196 ssl->err = SSL_ALERT_NO_CERTIFICATE;
1197 } else {
1198 ssl->err = SSL_ALERT_BAD_CERTIFICATE;
1200 matrixStrDebugMsg("No certificate sent to verify\n", NULL);
1201 return SSL_ERROR;
1203 if (end - c < 3) {
1204 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
1205 matrixStrDebugMsg("Invalid Certificate message\n", NULL);
1206 return SSL_ERROR;
1209 i = 0;
1210 while (certChainLen > 0) {
1211 certLen = *c << 16; c++;
1212 certLen |= *c << 8; c++;
1213 certLen |= *c; c++;
1215 if (end - c < certLen) {
1216 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
1217 matrixStrDebugMsg("Invalid certificate length\n", NULL);
1218 return SSL_ERROR;
1221 Extract the binary cert message into the cert structure
1223 if ((parseLen = matrixX509ParseCert(ssl->hsPool, c, certLen, &cert)) < 0) {
1224 matrixX509FreeCert(cert);
1225 ssl->err = SSL_ALERT_BAD_CERTIFICATE;
1226 matrixStrDebugMsg("Can't parse certificate\n", NULL);
1227 return SSL_ERROR;
1229 c += parseLen;
1231 if (i++ == 0) {
1232 ssl->sec.cert = cert;
1233 currentCert = ssl->sec.cert;
1234 } else {
1235 currentCert->next = cert;
1236 currentCert = currentCert->next;
1238 certChainLen -= (certLen + 3);
1241 May have received a chain of certs in the message. Spec says they
1242 must be in order so that each subsequent one is the parent of the
1243 previous. Confirm this now.
1245 if (matrixX509ValidateCertChain(ssl->hsPool, ssl->sec.cert,
1246 &subjectCert, &valid) < 0) {
1247 ssl->err = SSL_ALERT_BAD_CERTIFICATE;
1248 matrixStrDebugMsg("Couldn't validate certificate chain\n", NULL);
1249 return SSL_ERROR;
1252 There may not be a caCert set. The validate implemenation will just
1253 take the subject cert and make sure it is a self signed cert.
1255 if (matrixX509ValidateCert(ssl->hsPool, subjectCert,
1256 ssl->keys == NULL ? NULL : ssl->keys->caCerts,
1257 &subjectCert->valid) < 0) {
1258 ssl->err = SSL_ALERT_BAD_CERTIFICATE;
1259 matrixStrDebugMsg("Error validating certificate\n", NULL);
1260 return SSL_ERROR;
1262 if (subjectCert->valid < 0) {
1263 matrixStrDebugMsg(
1264 "Warning: Cert did not pass default validation checks\n", NULL);
1266 If there is no user callback, fail on validation check because there
1267 will be no intervention to give it a second look.
1269 if (ssl->sec.validateCert == NULL) {
1270 ssl->err = SSL_ALERT_BAD_CERTIFICATE;
1271 return SSL_ERROR;
1275 Call the user validation function with the entire cert chain. The user
1276 will proabably want to drill down to the last cert to make sure it
1277 has been properly validated by a CA on this side.
1279 Need to return from user validation space with knowledge
1280 that this is an ANONYMOUS connection.
1282 if ((anonCheck = matrixX509UserValidator(ssl->hsPool, ssl->sec.cert,
1283 ssl->sec.validateCert, ssl->sec.validateCertArg)) < 0) {
1284 ssl->err = SSL_ALERT_BAD_CERTIFICATE;
1285 return SSL_ERROR;
1288 Set the flag that is checked by the matrixSslGetAnonStatus API
1290 if (anonCheck == SSL_ALLOW_ANON_CONNECTION) {
1291 ssl->sec.anon = 1;
1292 } else {
1293 ssl->sec.anon = 0;
1297 Either a client or server could have been processing the cert as part of
1298 the authentication process. If server, we move to the client key
1299 exchange state.
1301 if (ssl->flags & SSL_FLAGS_SERVER) {
1302 ssl->hsState = SSL_HS_CLIENT_KEY_EXCHANGE;
1303 } else {
1304 ssl->hsState = SSL_HS_SERVER_HELLO_DONE;
1306 break;
1308 case SSL_HS_SERVER_HELLO_DONE:
1309 if (hsLen != 0) {
1310 ssl->err = SSL_ALERT_BAD_CERTIFICATE;
1311 matrixStrDebugMsg("Can't validate certificate\n", NULL);
1312 return SSL_ERROR;
1314 ssl->hsState = SSL_HS_FINISHED;
1315 rc = SSL_PROCESS_DATA;
1316 break;
1318 case SSL_HS_CERTIFICATE_REQUEST:
1319 if (hsLen < 4) {
1320 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
1321 matrixStrDebugMsg("Invalid Certificate Request message\n", NULL);
1322 return SSL_ERROR;
1325 We only have RSA_SIGN types. Make sure server can accept them
1327 certMatch = 0;
1328 certTypeLen = *c++;
1329 if (end - c < certTypeLen) {
1330 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
1331 matrixStrDebugMsg("Invalid Certificate Request message\n", NULL);
1332 return SSL_ERROR;
1334 while (certTypeLen-- > 0) {
1335 if (*c++ == RSA_SIGN) {
1336 certMatch = 1;
1339 if (certMatch == 0) {
1340 ssl->err = SSL_ALERT_UNSUPPORTED_CERTIFICATE;
1341 matrixStrDebugMsg("Can only support RSA_SIGN cert authentication\n",
1342 NULL);
1343 return SSL_ERROR;
1345 certChainLen = *c << 8; c++;
1346 certChainLen |= *c; c++;
1347 if (end - c < certChainLen) {
1348 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
1349 matrixStrDebugMsg("Invalid Certificate Request message\n", NULL);
1350 return SSL_ERROR;
1353 Check the passed in DNs against our cert issuer to see if they match.
1354 Only supporting a single cert on the client side.
1356 ssl->sec.certMatch = 0;
1357 while (certChainLen > 0) {
1358 certLen = *c << 8; c++;
1359 certLen |= *c; c++;
1360 if (end - c < certLen) {
1361 ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
1362 matrixStrDebugMsg("Invalid CertificateRequest message\n", NULL);
1363 return SSL_ERROR;
1365 c += certLen;
1366 certChainLen -= (2 + certLen);
1368 ssl->hsState = SSL_HS_SERVER_HELLO_DONE;
1369 break;
1370 #endif /* USE_CLIENT_SIDE_SSL */
1372 case SSL_HS_SERVER_KEY_EXCHANGE:
1373 ssl->err = SSL_ALERT_UNEXPECTED_MESSAGE;
1374 return SSL_ERROR;
1376 default:
1377 ssl->err = SSL_ALERT_UNEXPECTED_MESSAGE;
1378 return SSL_ERROR;
1383 if we've got more data in the record, the sender has packed
1384 multiple handshake messages in one record. Parse the next one.
1386 if (c < end) {
1387 goto parseHandshake;
1389 return rc;
1392 /******************************************************************************/