/* Construct the initial HELLO message to send to the server and initiate the SSL handshake. Can be used in the re-handshake scenario as well. */ int _ssl_doHandshake(SSL *ssl) { char buf[1024]; int err, rc; /* MatrixSSL doesn't provide buffers for data internally. Define them here to support buffered reading and writing for non-blocking sockets. Although it causes quite a bit more work, we support dynamically growing the buffers as needed. Alternately, we could define 16K buffers here and not worry about growing them. */ short cipherSuite = 0; err = matrixSslEncodeClientHello(ssl->ssl, &(ssl->outsock), cipherSuite); if (err < 0) { socketAssert(err < 0); return -1; } /* Send the hello with a blocking write */ err = _psSocketWrite(ssl->fd, &(ssl->outsock)); if (err < 0) { fprintf(stdout, "Error in socketWrite\n"); return -1; } ssl->outsock.start = ssl->outsock.end = ssl->outsock.buf; /* Call _ssl_read to work through the handshake. Not actually expecting data back, so the finished case is simply when the handshake is complete. */ readMore: rc = _ssl_read(ssl, buf, 1024); /* Reading handshake records should always return 0 bytes, we aren't expecting any data yet. */ if(rc > 0 || (rc == 0 && matrixSslHandshakeIsComplete(ssl->ssl) == 0)) { goto readMore; } if(rc < 0) { return -1; } return 0; }
sslConn_t *sslDoHandshake(sslConn_t *conn, short cipherSuite) { char buf[1024]; int bytes, status, rc; conn->insock.size = 1024; conn->insock.start = conn->insock.end = conn->insock.buf = (unsigned char *)malloc(conn->insock.size); conn->outsock.size = 1024; conn->outsock.start = conn->outsock.end = conn->outsock.buf = (unsigned char *)malloc(conn->outsock.size); conn->inbuf.size = 0; conn->inbuf.start = conn->inbuf.end = conn->inbuf.buf = NULL; bytes = matrixSslEncodeClientHello(conn->ssl, &conn->outsock, cipherSuite); if (bytes < 0) { fprintf(stderr, "error %s:%d\n",__FILE__,__LINE__); socketAssert(bytes < 0); goto error; } if (psSocketWrite(conn->fd, &conn->outsock) < 0) { fprintf(stdout, "Error in socketWrite\n"); goto error; } conn->outsock.start = conn->outsock.end = conn->outsock.buf; readMore: rc = sslRead(conn, buf, sizeof(buf), &status); if (rc == 0) { if (status == SSLSOCKET_EOF || status == SSLSOCKET_CLOSE_NOTIFY) { fprintf(stderr, "error %s:%d\n",__FILE__,__LINE__); goto error; } if (matrixSslHandshakeIsComplete(conn->ssl) == 0) { goto readMore; } } else if (rc > 0) { fprintf(stderr, "sslRead got %d data in sslDoHandshake %s\n", rc, buf); goto readMore; } else { fprintf(stderr, "sslRead error in sslDoHandhake\n"); goto error; } return conn; error: fprintf(stderr, "error %s:%d\n",__FILE__,__LINE__); sslFreeConnection(&conn); return NULL; }
/* Construct the initial HELLO message to send to the server and initiate the SSL handshake. Can be used in the re-handshake scenario as well. */ sslConn_t *sslDoHandshake(sslConn_t *conn, short cipherSuite) { char buf[1024]; int bytes, status, rc; /* MatrixSSL doesn't provide buffers for data internally. Define them here to support buffered reading and writing for non-blocking sockets. Although it causes quite a bit more work, we support dynamically growing the buffers as needed. Alternately, we could define 16K buffers here and not worry about growing them. */ conn->insock.size = 1024; conn->insock.start = conn->insock.end = conn->insock.buf = (unsigned char *)malloc(conn->insock.size); conn->outsock.size = 1024; conn->outsock.start = conn->outsock.end = conn->outsock.buf = (unsigned char *)malloc(conn->outsock.size); conn->inbuf.size = 0; conn->inbuf.start = conn->inbuf.end = conn->inbuf.buf = NULL; bytes = matrixSslEncodeClientHello(conn->ssl, &conn->outsock, cipherSuite); if (bytes < 0) { socketAssert(bytes < 0); goto error; } /* Send the hello with a blocking write */ if (psSocketWrite(conn->fd, &conn->outsock) < 0) { fprintf(stdout, "Error in socketWrite\n"); goto error; } conn->outsock.start = conn->outsock.end = conn->outsock.buf; /* Call sslRead to work through the handshake. Not actually expecting data back, so the finished case is simply when the handshake is complete. */ readMore: rc = sslRead(conn, buf, sizeof(buf), &status); /* Reading handshake records should always return 0 bytes, we aren't expecting any data yet. */ if (rc == 0) { if (status == SSLSOCKET_EOF || status == SSLSOCKET_CLOSE_NOTIFY) { goto error; } if (matrixSslHandshakeIsComplete(conn->ssl) == 0) { goto readMore; } } else if (rc > 0) { fprintf(stderr, "sslRead got %d data in sslDoHandshake %s\n", rc, buf); goto readMore; } else { fprintf(stderr, "sslRead error in sslDoHandhake\n"); goto error; } return conn; error: sslFreeConnection(&conn); return NULL; }
/* Parse incoming data per http://wp.netscape.com/eng/ssl3 */ int32 matrixSslDecode(ssl_t *ssl, sslBuf_t *in, sslBuf_t *out, unsigned char *error, unsigned char *alertLevel, unsigned char *alertDescription) { unsigned char *c, *p, *end, *pend, *oend; unsigned char *mac, macError; int32 rc; unsigned char padLen; /* If we've had a protocol error, don't allow further use of the session */ *error = SSL_ALERT_NONE; if (ssl->flags & SSL_FLAGS_ERROR || ssl->flags & SSL_FLAGS_CLOSED) { return SSL_ERROR; } /* This flag is set if the previous call to this routine returned an SSL_FULL error from encodeResponse, indicating that there is data to be encoded, but the out buffer was not big enough to handle it. If we fall in this case, the user has increased the out buffer size and is re-calling this routine */ if (ssl->flags & SSL_FLAGS_NEED_ENCODE) { ssl->flags &= ~SSL_FLAGS_NEED_ENCODE; goto encodeResponse; } c = in->start; end = in->end; oend = out->end; /* Processing the SSL Record header: If the high bit of the first byte is set and this is the first message we've seen, we parse the request as an SSLv2 request http://wp.netscape.com/eng/security/SSL_2.html SSLv2 also supports a 3 byte header when padding is used, but this should not be required for the initial plaintext message, so we don't support it v3 Header: 1 byte type 1 byte major version 1 byte minor version 2 bytes length v2 Header 2 bytes length (ignore high bit) */ decodeMore: sslAssert(out->end == oend); if (end - c == 0) { /* This case could happen if change cipher spec was last message in the buffer */ return SSL_SUCCESS; } if (end - c < SSL2_HEADER_LEN) { return SSL_PARTIAL; } if (ssl->majVer != 0 || (*c & 0x80) == 0) { if (end - c < ssl->recordHeadLen) { return SSL_PARTIAL; } ssl->rec.type = *c; c++; ssl->rec.majVer = *c; c++; ssl->rec.minVer = *c; c++; ssl->rec.len = *c << 8; c++; ssl->rec.len += *c; c++; } else { ssl->rec.type = SSL_RECORD_TYPE_HANDSHAKE; ssl->rec.majVer = 2; ssl->rec.minVer = 0; ssl->rec.len = (*c & 0x7f) << 8; c++; ssl->rec.len += *c; c++; } /* Validate the various record headers. The type must be valid, the major and minor versions must match the negotiated versions (if we're past ClientHello) and the length must be < 16K and > 0 */ if (ssl->rec.type != SSL_RECORD_TYPE_CHANGE_CIPHER_SPEC && ssl->rec.type != SSL_RECORD_TYPE_ALERT && ssl->rec.type != SSL_RECORD_TYPE_HANDSHAKE && ssl->rec.type != SSL_RECORD_TYPE_APPLICATION_DATA) { ssl->err = SSL_ALERT_UNEXPECTED_MESSAGE; matrixIntDebugMsg("Record header type not valid: %d\n", ssl->rec.type); goto encodeResponse; } /* Verify the record version numbers unless this is the first record we're reading. */ if (ssl->hsState != SSL_HS_SERVER_HELLO && ssl->hsState != SSL_HS_CLIENT_HELLO) { if (ssl->rec.majVer != ssl->majVer || ssl->rec.minVer != ssl->minVer) { ssl->err = SSL_ALERT_ILLEGAL_PARAMETER; matrixStrDebugMsg("Record header version not valid\n", NULL); goto encodeResponse; } } /* Verify max and min record lengths */ if (ssl->rec.len > SSL_MAX_RECORD_LEN || ssl->rec.len == 0) { ssl->err = SSL_ALERT_ILLEGAL_PARAMETER; matrixIntDebugMsg("Record header length not valid: %d\n", ssl->rec.len); goto encodeResponse; } /* This implementation requires the entire SSL record to be in the 'in' buffer before we parse it. This is because we need to MAC the entire record before allowing it to be used by the caller. The only alternative would be to copy the partial record to an internal buffer, but that would require more memory usage, which we're trying to keep low. */ if (end - c < ssl->rec.len) { return SSL_PARTIAL; } /* Make sure we have enough room to hold the decoded record */ if ((out->buf + out->size) - out->end < ssl->rec.len) { return SSL_FULL; } /* Decrypt the entire record contents. The record length should be a multiple of block size, or decrypt will return an error If we're still handshaking and sending plaintext, the decryption callback will point to a null provider that passes the data unchanged */ if (ssl->decrypt(&ssl->sec.decryptCtx, c, out->end, ssl->rec.len) < 0) { ssl->err = SSL_ALERT_ILLEGAL_PARAMETER; goto encodeResponse; } c += ssl->rec.len; /* If we're reading a secure message, we need to validate the MAC and padding (if using a block cipher). Insecure messages do not have a trailing MAC or any padding. SECURITY - There are several vulnerabilities in block cipher padding that we handle in the below code. For more information see: http://www.openssl.org/~bodo/tls-cbc.txt */ if (ssl->flags & SSL_FLAGS_READ_SECURE) { /* Verify the record is at least as big as the MAC Start tracking MAC errors, rather then immediately catching them to stop timing and alert description attacks that differentiate between a padding error and a MAC error. */ if (ssl->rec.len < ssl->deMacSize) { ssl->err = SSL_ALERT_BAD_RECORD_MAC; matrixStrDebugMsg("Record length too short for MAC\n", NULL); goto encodeResponse; } macError = 0; /* Decode padding only if blocksize is > 0 (we're using a block cipher), otherwise no padding will be present, and the mac is the last macSize bytes of the record. */ if (ssl->deBlockSize <= 1) { mac = out->end + ssl->rec.len - ssl->deMacSize; } else { /* Verify the pad data for block ciphers c points within the cipher text, p points within the plaintext The last byte of the record is the pad length */ p = out->end + ssl->rec.len; padLen = *(p - 1); /* SSL3.0 requires the pad length to be less than blockSize TLS can have a pad length up to 255 for obfuscating the data len */ if (ssl->majVer == SSL3_MAJ_VER && ssl->minVer == SSL3_MIN_VER && padLen >= ssl->deBlockSize) { macError++; } /* The minimum record length is the size of the mac, plus pad bytes plus one length byte */ if (ssl->rec.len < ssl->deMacSize + padLen + 1) { macError++; } /* The mac starts macSize bytes before the padding and length byte. If we have a macError, just fake the mac as the last macSize bytes of the record, so we are sure to have enough bytes to verify against, we'll fail anyway, so the actual contents don't matter. */ if (!macError) { mac = p - padLen - 1 - ssl->deMacSize; } else { mac = out->end + ssl->rec.len - ssl->deMacSize; } } /* Verify the MAC of the message by calculating our own MAC of the message and comparing it to the one in the message. We do this step regardless of whether or not we've already set macError to stop timing attacks. Clear the mac in the callers buffer if we're successful */ if (ssl->verifyMac(ssl, ssl->rec.type, out->end, (int32)(mac - out->end), mac) < 0 || macError) { ssl->err = SSL_ALERT_BAD_RECORD_MAC; matrixStrDebugMsg("Couldn't verify MAC or pad of record data\n", NULL); goto encodeResponse; } memset(mac, 0x0, ssl->deMacSize); /* Record data starts at out->end and ends at mac */ p = out->end; pend = mac; } else { /* The record data is the entire record as there is no MAC or padding */ p = out->end; pend = mac = out->end + ssl->rec.len; } /* Check now for maximum plaintext length of 16kb. No appropriate SSL alert for this */ if ((int32)(pend - p) > SSL_MAX_PLAINTEXT_LEN) { ssl->err = SSL_ALERT_BAD_RECORD_MAC; matrixStrDebugMsg("Record overflow\n", NULL); goto encodeResponse; } /* Take action based on the actual record type we're dealing with 'p' points to the start of the data, and 'pend' points to the end */ switch (ssl->rec.type) { case SSL_RECORD_TYPE_CHANGE_CIPHER_SPEC: /* Body is single byte with value 1 to indicate that the next message will be encrypted using the negotiated cipher suite */ if (pend - p < 1) { ssl->err = SSL_ALERT_ILLEGAL_PARAMETER; matrixStrDebugMsg("Invalid length for CipherSpec\n", NULL); goto encodeResponse; } if (*p == 1) { p++; } else { ssl->err = SSL_ALERT_ILLEGAL_PARAMETER; matrixStrDebugMsg("Invalid value for CipherSpec\n", NULL); goto encodeResponse; } /* If we're expecting finished, then this is the right place to get this record. It is really part of the handshake but it has its own record type. Activate the read cipher callbacks, so we will decrypt incoming data from now on. */ if (ssl->hsState == SSL_HS_FINISHED) { sslActivateReadCipher(ssl); } else { ssl->err = SSL_ALERT_UNEXPECTED_MESSAGE; matrixIntDebugMsg("Invalid CipherSpec order: %d\n", ssl->hsState); goto encodeResponse; } in->start = c; goto decodeMore; case SSL_RECORD_TYPE_ALERT: /* 1 byte alert level (warning or fatal) 1 byte alert description corresponding to SSL_ALERT_* */ if (pend - p < 2) { ssl->err = SSL_ALERT_ILLEGAL_PARAMETER; matrixStrDebugMsg("Error in length of alert record\n", NULL); goto encodeResponse; } *alertLevel = *p; p++; *alertDescription = *p; p++; /* If the alert is fatal, or is a close message (usually a warning), flag the session with ERROR so it cannot be used anymore. Caller can decide whether or not to close on other warnings. */ if (*alertLevel == SSL_ALERT_LEVEL_FATAL) { ssl->flags |= SSL_FLAGS_ERROR; } if (*alertDescription == SSL_ALERT_CLOSE_NOTIFY) { ssl->flags |= SSL_FLAGS_CLOSED; } return SSL_ALERT; case SSL_RECORD_TYPE_HANDSHAKE: /* We've got one or more handshake messages in the record data. The handshake parsing function will take care of all messages and return an error if there is any problem. If there is a response to be sent (either a return handshake or an error alert, send it). If the message was parsed, but no response is needed, loop up and try to parse another message */ rc = parseSSLHandshake(ssl, (char*)p, (int32)(pend - p)); switch (rc) { case SSL_SUCCESS: in->start = c; return SSL_SUCCESS; case SSL_PROCESS_DATA: in->start = c; goto encodeResponse; case SSL_ERROR: if (ssl->err == SSL_ALERT_NONE) { ssl->err = SSL_ALERT_HANDSHAKE_FAILURE; } goto encodeResponse; } break; case SSL_RECORD_TYPE_APPLICATION_DATA: /* Data is in the out buffer, let user handle it Don't allow application data until handshake is complete, and we are secure. It is ok to let application data through on the client if we are in the SERVER_HELLO state because this could mean that the client has sent a CLIENT_HELLO message for a rehandshake and is awaiting reply. */ if ((ssl->hsState != SSL_HS_DONE && ssl->hsState != SSL_HS_SERVER_HELLO) || !(ssl->flags & SSL_FLAGS_READ_SECURE)) { ssl->err = SSL_ALERT_UNEXPECTED_MESSAGE; matrixIntDebugMsg("Incomplete handshake: %d\n", ssl->hsState); goto encodeResponse; } /* SECURITY - If the mac is at the current out->end, then there is no data in the record. These records are valid, but are usually not sent by the application layer protocol. Rather, they are initiated within the remote SSL protocol implementation to avoid some types of attacks when using block ciphers. For more information see: http://www.openssl.org/~bodo/tls-cbc.txt We eat these records here rather than passing them on to the caller. The rationale behind this is that if the caller's application protocol is depending on zero length SSL messages, it will fail anyway if some of those messages are initiated within the SSL protocol layer. Also this clears up any confusion where the caller might interpret a zero length read as an end of file (EOF) or would block (EWOULDBLOCK) type scenario. SECURITY - Looping back up and ignoring the message has the potential for denial of service, because we are not changing the state of the system in any way when processing these messages. To counteract this, we maintain a counter that we share with other types of ignored messages */ in->start = c; if (out->end == mac) { if (ssl->ignoredMessageCount++ < SSL_MAX_IGNORED_MESSAGE_COUNT) { goto decodeMore; } ssl->err = SSL_ALERT_UNEXPECTED_MESSAGE; matrixIntDebugMsg("Exceeded limit on ignored messages: %d\n", SSL_MAX_IGNORED_MESSAGE_COUNT); goto encodeResponse; } if (ssl->ignoredMessageCount > 0) { ssl->ignoredMessageCount--; } out->end = mac; return SSL_PROCESS_DATA; } /* Should not get here */ matrixIntDebugMsg("Invalid record type in matrixSslDecode: %d\n", ssl->rec.type); return SSL_ERROR; encodeResponse: /* We decoded a record that needs a response, either a handshake response or an alert if we've detected an error. SECURITY - Clear the decoded incoming record from outbuf before encoding the response into outbuf. rec.len could be invalid, clear the minimum of rec.len and remaining outbuf size */ rc = min (ssl->rec.len, (int32)((out->buf + out->size) - out->end)); if (rc > 0) { memset(out->end, 0x0, rc); } if (ssl->hsState == SSL_HS_HELLO_REQUEST) { /* Don't clear the session info. If receiving a HELLO_REQUEST from a MatrixSSL enabled server the determination on whether to reuse the session is made on that side, so always send the current session */ rc = matrixSslEncodeClientHello(ssl, out, ssl->cipher->id); } else { rc = sslEncodeResponse(ssl, out); } if (rc == SSL_SUCCESS) { if (ssl->err != SSL_ALERT_NONE) { *error = (unsigned char)ssl->err; ssl->flags |= SSL_FLAGS_ERROR; return SSL_ERROR; } return SSL_SEND_RESPONSE; } if (rc == SSL_FULL) { ssl->flags |= SSL_FLAGS_NEED_ENCODE; return SSL_FULL; } return SSL_ERROR; }
int32_t matrixSslNewClientSession(ssl_t **ssl, const sslKeys_t *keys, sslSessionId_t *sid, const uint16_t cipherSpec[], uint8_t cipherSpecLen, sslCertCb_t certCb, const char *expectedName, tlsExtension_t *extensions, sslExtCb_t extCb, sslSessOpts_t *options) { ssl_t *lssl; psBuf_t tmp; uint32 len; int32 rc, i; if (!ssl) { return PS_ARG_FAIL; } if (cipherSpecLen > 0 && (cipherSpec == NULL || cipherSpec[0] == 0)) { return PS_ARG_FAIL; } if (options == NULL) { return PS_ARG_FAIL; } *ssl = NULL; lssl = NULL; /* Give priority to cipher suite if session id is provided and doesn't match */ if (cipherSpec != NULL && cipherSpec[0] != 0 && sid != NULL && sid->cipherId != 0) { rc = 1; for (i = 0; i < cipherSpecLen; i++) { if (cipherSpec[i] == sid->cipherId) { rc = 0; } } if (rc) { psTraceInfo("Explicit cipher suite will override session cache\n"); memset(sid->id, 0, SSL_MAX_SESSION_ID_SIZE); memset(sid->masterSecret, 0, SSL_HS_MASTER_SIZE); sid->cipherId = 0; } } if ((rc = matrixSslNewSession(&lssl, keys, sid, options)) < 0) { return rc; } lssl->userPtr = options->userPtr; #ifndef USE_ONLY_PSK_CIPHER_SUITE if (expectedName) { if (psX509ValidateGeneralName((char*)expectedName) < 0) { matrixSslDeleteSession(lssl); return rc; } rc = strlen(expectedName); lssl->expectedName = psMalloc(lssl->sPool, rc + 1); strcpy(lssl->expectedName, expectedName); } if (certCb) { matrixSslSetCertValidator(lssl, certCb); } #endif if (extCb) { lssl->extCb = extCb; } RETRY_HELLO: tmp.size = lssl->outsize; tmp.buf = tmp.start = tmp.end = lssl->outbuf; if ((rc = matrixSslEncodeClientHello(lssl, &tmp, cipherSpec, cipherSpecLen, &len, extensions, options)) < 0) { if (rc == SSL_FULL) { if ((tmp.buf = psRealloc(lssl->outbuf, len, lssl->bufferPool)) == NULL) { matrixSslDeleteSession(lssl); return PS_MEM_FAIL; } lssl->outbuf = tmp.buf; lssl->outsize = len; goto RETRY_HELLO; } else { matrixSslDeleteSession(lssl); return rc; } } psAssert(tmp.start == tmp.buf); lssl->outlen = tmp.end - tmp.start; *ssl = lssl; return MATRIXSSL_REQUEST_SEND; }
/* Encode a CLIENT_HELLO or HELLO_REQUEST to re-handshake an existing connection. Can't "downgrade" the re-handshake. This means if keys or certCb are NULL we stick with whatever the session already has loaded. keys should be NULL if no change in key material is being made cipherSpec is only used by clients */ int32_t matrixSslEncodeRehandshake(ssl_t *ssl, sslKeys_t *keys, int32 (*certCb)(ssl_t *ssl, psX509Cert_t *cert, int32 alert), uint32 sessionOption, const uint16_t cipherSpec[], uint8_t cipherSpecLen) { sslBuf_t sbuf; int32 rc, i; uint32 reqLen, newLen; unsigned char *p; sslSessOpts_t options; /* Clear extFlags for rehandshakes */ ssl->extFlags.truncated_hmac = 0; ssl->extFlags.sni = 0; if (!ssl) { return PS_ARG_FAIL; } if (cipherSpecLen > 0 && (cipherSpec == NULL || cipherSpec[0] == 0)) { return PS_ARG_FAIL; } if (ssl->bFlags & BFLAG_CLOSE_AFTER_SENT) { return PS_PROTOCOL_FAIL; } psAssert(ssl->outsize > 0 && ssl->outbuf != NULL); #ifdef DISABLE_DTLS_CLIENT_CHANGE_CIPHER_FROM_GCM_TO_GCM #endif /* DISABLE_DTLS_CLIENT_CHANGE_CIPHER_FROM_GCM_TO_GCM */ #ifdef USE_ZLIB_COMPRESSION /* Re-handshakes are not currently supported for compressed sessions. */ if (ssl->compression > 0) { psTraceInfo("Re-handshakes not supported for compressed sessions\n"); return PS_UNSUPPORTED_FAIL; } #endif /* The only explicit option that can be passsed in is SSL_OPTION_FULL_HANDSHAKE to indicate no resumption is allowed */ if (sessionOption == SSL_OPTION_FULL_HANDSHAKE) { matrixSslSetSessionOption(ssl, sessionOption, NULL); } /* If the key material or cert callback are provided we have to assume it was intentional to "upgrade" the re-handshake and we force full handshake No big overhead calling SetSessionOption with FULL_HS multiple times. */ if (keys != NULL) { ssl->keys = keys; matrixSslSetSessionOption(ssl, SSL_OPTION_FULL_HANDSHAKE, NULL); } #ifndef USE_ONLY_PSK_CIPHER_SUITE if (certCb != NULL) { matrixSslSetSessionOption(ssl, SSL_OPTION_FULL_HANDSHAKE, NULL); #if defined(USE_CLIENT_AUTH) || defined(USE_CLIENT_SIDE_SSL) matrixSslSetCertValidator(ssl, certCb); #endif /* USE_CLIENT_AUTH || USE_CLIENT_SIDE_SSL */ #if defined(USE_CLIENT_AUTH) && defined(USE_SERVER_SIDE_SSL) /* If server, a certCb is an explicit flag to set client auth just as it is in matrixSslNewServerSession */ if (ssl->flags & SSL_FLAGS_SERVER) { matrixSslSetSessionOption(ssl, SSL_OPTION_ENABLE_CLIENT_AUTH, NULL); } #endif /* USE_CLIENT_AUTH && USE_SERVER_SIDE_SSL */ } #endif /* !USE_ONLY_PSK_CIPHER_SUITE */ /* If cipher spec is explicitly different from current, force a full handshake */ if (!(ssl->flags & SSL_FLAGS_SERVER)) { rc = 0; if (cipherSpecLen > 0) { rc = 1; for (i = 0; i < cipherSpecLen; i++) { if (cipherSpec[i] == ssl->cipher->ident) { rc = 0; } } } if (rc) { matrixSslSetSessionOption(ssl, SSL_OPTION_FULL_HANDSHAKE, NULL); } } #ifdef USE_DTLS if (ssl->flags & SSL_FLAGS_DTLS) { /* Resend epoch should be brought up-to-date with new epoch */ ssl->resendEpoch[0] = ssl->epoch[0]; ssl->resendEpoch[1] = ssl->epoch[1]; ssl->msn = ssl->resendMsn = 0; } #endif /* USE_DTLS */ /* Options are set. Encode the HELLO message */ newLen = 0; L_REHANDSHAKE: if (ssl->flags & SSL_FLAGS_SERVER) { sbuf.buf = sbuf.start = sbuf.end = ssl->outbuf + ssl->outlen; sbuf.size = ssl->outsize - ssl->outlen; if ((rc = matrixSslEncodeHelloRequest(ssl, &sbuf, &reqLen)) < 0) { if (rc == SSL_FULL && newLen == 0) { newLen = ssl->outlen + reqLen; if (newLen < SSL_MAX_BUF_SIZE) { if ((p = psRealloc(ssl->outbuf, newLen, ssl->bufferPool)) == NULL){ return PS_MEM_FAIL; } ssl->outbuf = p; ssl->outsize = newLen; goto L_REHANDSHAKE; } } return rc; } } else { sbuf.buf = sbuf.start = sbuf.end = ssl->outbuf + ssl->outlen; sbuf.size = ssl->outsize - ssl->outlen; memset(&options, 0x0, sizeof(sslSessOpts_t)); #ifdef USE_ECC_CIPHER_SUITE options.ecFlags = ssl->ecInfo.ecFlags; #endif /* Use extended master secret if original connection used it */ if (ssl->extFlags.extended_master_secret == 1) { options.extendedMasterSecret = 1; ssl->extFlags.extended_master_secret = 0; } else { options.extendedMasterSecret = -1; } if ((rc = matrixSslEncodeClientHello(ssl, &sbuf, cipherSpec, cipherSpecLen, &reqLen, NULL, &options)) < 0) { if (rc == SSL_FULL && newLen == 0) { newLen = ssl->outlen + reqLen; if (newLen < SSL_MAX_BUF_SIZE) { if ((p = psRealloc(ssl->outbuf, newLen, ssl->bufferPool)) == NULL) { return PS_MEM_FAIL; } ssl->outbuf = p; ssl->outsize = newLen; goto L_REHANDSHAKE; } } return rc; } } ssl->outlen += sbuf.end - sbuf.start; return MATRIXSSL_SUCCESS; }
void doio(void) { iopause_fd x[2]; struct taia deadline; struct taia now; struct taia timeout; if (! stralloc_ready(&encinbuf, bufsizein)) die_nomem(); encin.buf =encin.start =encin.end =encinbuf.s; encin.size =bufsizein; if (! stralloc_ready(&decinbuf, bufsizein)) die_nomem(); decin.buf =decin.start =decin.end =decinbuf.s; decin.size =bufsizein; if (! stralloc_ready(&encoubuf, bufsizeou)) die_nomem(); encou.buf =encou.start =encou.end =encoubuf.s; encou.size =bufsizeou; if (! stralloc_ready(&decoubuf, bufsizeou)) die_nomem(); decou.buf =decou.start =decou.end =decoubuf.s; decou.size =bufsizeou; if (client) { rc =matrixSslEncodeClientHello(ssl, &decou, 0); if (rc != 0) fatalx("unable to encode client hello"); if (write(fdstdou, decou.start, decou.end -decou.start) != (decou.end -decou.start)) fatal("unable to send client hello"); if (verbose > 2) info("sending client hello"); if (verbose > 2) infou("write bytes: ", decou.end -decou.start); bytesou +=decou.end -decou.start; decou.start =decou.end =decou.buf; } taia_now(&now); taia_uint(&timeout, handshake_timeout); taia_add(&timeout, &now, &timeout); for (;;) { iopause_fd *xx =x; int l =2; x[0].fd =encpipe[0]; x[0].events =IOPAUSE_READ; x[0].revents =0; x[1].fd =fdstdin; x[1].events =IOPAUSE_READ; x[1].revents =0; if ((x[0].fd == -1) || handshake) { --l; ++xx; } if (x[1].fd == -1) --l; if (! l) return; taia_now(&now); if (handshake) { if (taia_less(&timeout, &now)) { if (verbose) info("ssl handshake timeout, exit."); return; } deadline.sec =timeout.sec; deadline.nano =timeout.nano; deadline.atto =timeout.atto; } else { taia_uint(&deadline, 30); taia_add(&deadline, &now, &deadline); } iopause(xx, l, &deadline, &now); if (x[0].revents) encode(); if (x[1].revents) decode(); } }
/* Encode a CLIENT_HELLO or HELLO_REQUEST to re-handshake an existing connection. Can't "downgrade" the re-handshake. This means if keys or certCb are NULL we stick with whatever the session already has loaded. keys should be NULL if no change in key material is being made cipherSpec is only used by clients */ int32 matrixSslEncodeRehandshake(ssl_t *ssl, sslKeys_t *keys, int32 (*certCb)(ssl_t *ssl, psX509Cert_t *cert, int32 alert), uint32 sessionOption, uint32 cipherSpec[], uint16 cipherSpecLen) { sslBuf_t sbuf; int32 rc, i; uint32 reqLen, newLen; unsigned char *p; if (!ssl) { return PS_ARG_FAIL; } if (cipherSpecLen > 0 && (cipherSpec == NULL || cipherSpec[0] == 0)) { return PS_ARG_FAIL; } if (ssl->bFlags & BFLAG_CLOSE_AFTER_SENT) { return PS_PROTOCOL_FAIL; } psAssert(ssl->outsize > 0 && ssl->outbuf != NULL); #ifdef USE_ZLIB_COMPRESSION /* Re-handshakes are not currently supported for compressed sessions. */ if (ssl->compression > 0) { psTraceInfo("Re-handshakes not supported for compressed sessions\n"); return PS_UNSUPPORTED_FAIL; } #endif /* The only explicit option that can be passsed in is SSL_OPTION_FULL_HANDSHAKE to indicate no resumption is allowed */ if (sessionOption == SSL_OPTION_FULL_HANDSHAKE) { matrixSslSetSessionOption(ssl, sessionOption, NULL); } /* If the key material or cert callback are provided we have to assume it was intentional to "upgrade" the re-handshake and we force full handshake No big overhead calling SetSessionOption with FULL_HS multiple times. */ if (keys != NULL) { ssl->keys = keys; matrixSslSetSessionOption(ssl, SSL_OPTION_FULL_HANDSHAKE, NULL); } #ifndef USE_ONLY_PSK_CIPHER_SUITE if (certCb != NULL) { matrixSslSetSessionOption(ssl, SSL_OPTION_FULL_HANDSHAKE, NULL); #if defined(USE_CLIENT_AUTH) || defined(USE_CLIENT_SIDE_SSL) matrixSslSetCertValidator(ssl, (sslCertCb_t)certCb); #endif /* USE_CLIENT_AUTH || USE_CLIENT_SIDE_SSL */ #if defined(USE_CLIENT_AUTH) && defined(USE_SERVER_SIDE_SSL) /* If server, a certCb is an explicit flag to set client auth just as it is in matrixSslNewServerSession */ if (ssl->flags & SSL_FLAGS_SERVER) { matrixSslSetSessionOption(ssl, SSL_OPTION_ENABLE_CLIENT_AUTH, NULL); } #endif /* USE_CLIENT_AUTH && USE_SERVER_SIDE_SSL */ } #endif /* !USE_ONLY_PSK_CIPHER_SUITE */ /* If cipher spec is explicitly different from current, force a full handshake */ if (!(ssl->flags & SSL_FLAGS_SERVER)) { rc = 0; if (cipherSpecLen > 0) { rc = 1; for (i = 0; i < cipherSpecLen; i++) { if (cipherSpec[i] == ssl->cipher->ident) { rc = 0; } } } if (rc) { matrixSslSetSessionOption(ssl, SSL_OPTION_FULL_HANDSHAKE, NULL); } } /* Options are set. Encode the HELLO message */ newLen = 0; L_REHANDSHAKE: if (ssl->flags & SSL_FLAGS_SERVER) { sbuf.buf = sbuf.start = sbuf.end = ssl->outbuf + ssl->outlen; sbuf.size = ssl->outsize - ssl->outlen; if ((rc = matrixSslEncodeHelloRequest(ssl, &sbuf, &reqLen)) < 0) { if (rc == SSL_FULL && newLen == 0) { newLen = ssl->outlen + reqLen; if (newLen < SSL_MAX_BUF_SIZE) { if ((p = psRealloc(ssl->outbuf, newLen)) == NULL){ return PS_MEM_FAIL; } ssl->outbuf = p; ssl->outsize = newLen; goto L_REHANDSHAKE; } } return rc; } } else { sbuf.buf = sbuf.start = sbuf.end = ssl->outbuf + ssl->outlen; sbuf.size = ssl->outsize - ssl->outlen; if ((rc = matrixSslEncodeClientHello(ssl, &sbuf, cipherSpec, cipherSpecLen, &reqLen, NULL)) < 0) { if (rc == SSL_FULL && newLen == 0) { newLen = ssl->outlen + reqLen; if (newLen < SSL_MAX_BUF_SIZE) { if ((p = psRealloc(ssl->outbuf, newLen)) == NULL) { return PS_MEM_FAIL; } ssl->outbuf = p; ssl->outsize = newLen; goto L_REHANDSHAKE; } } return rc; } } ssl->outlen += sbuf.end - sbuf.start; return MATRIXSSL_SUCCESS; }