ssl3con.c
上传用户:lyxiangda
上传日期:2007-01-12
资源大小:3042k
文件大小:233k
- * Don't consider failure to find a matching SID an error.
- */
- sid_match = (PRBool)(sidBytes.len > 0 &&
- sidBytes.len == sid->u.ssl3.sessionIDLength &&
- !PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len));
- if (sid_match &&
- sid->version == ss->version &&
- sid->u.ssl3.cipherSuite == ss->ssl3->hs.cipher_suite) do {
- PK11SlotInfo *slot;
- PK11SymKey * wrapKey; /* wrapping key */
- SECItem wrappedMS; /* wrapped master secret. */
- CK_FLAGS keyFlags = 0;
- slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
- sid->u.ssl3.masterSlotID);
- if (slot == NULL) {
- break; /* not considered an error. */
- }
- if (!PK11_IsPresent(slot)) {
- PK11_FreeSlot(slot);
- break; /* not considered an error. */
- }
- wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex,
- sid->u.ssl3.masterWrapMech,
- sid->u.ssl3.masterWrapSeries,
- ss->pkcs11PinArg);
- PK11_FreeSlot(slot);
- if (wrapKey == NULL) {
- break; /* not considered an error. */
- }
- if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
- keyFlags = CKF_SIGN | CKF_VERIFY;
- }
- wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
- wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
- ss->ssl3->pwSpec->master_secret =
- PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
- NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
- CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags);
- errCode = PORT_GetError();
- PK11_FreeSymKey(wrapKey);
- if (ss->ssl3->pwSpec->master_secret == NULL) {
- break; /* errorCode set just after call to UnwrapSymKey. */
- }
- /* Got a Match */
- ++ssl3_hsh_sid_cache_hits;
- ss->ssl3->hs.ws = wait_change_cipher;
- ss->ssl3->hs.isResuming = PR_TRUE;
- /* copy the peer cert from the SID */
- if (sid->peerCert != NULL) {
- ss->sec->peerCert = CERT_DupCertificate(sid->peerCert);
- }
- /* reload the FORTEZZA key material. These keys aren't generated
- * by the master secret, but by the key exchange. We restart by
- * reusing these keys. */
- if (sid->u.ssl3.hasFortezza) {
- ss->ssl3->fortezza.tek = PK11_ReferenceSymKey(sid->u.ssl3.tek);
- }
- if (ss->ssl3->hs.suite_def->bulk_cipher_alg == cipher_fortezza) {
- ss->ssl3->pwSpec->client.write_key =
- PK11_ReferenceSymKey(sid->u.ssl3.clientWriteKey);
- ss->ssl3->pwSpec->server.write_key =
- PK11_ReferenceSymKey(sid->u.ssl3.serverWriteKey);
- /* add the tek later for pre-encrypted files */
- PORT_Memcpy(ss->ssl3->pwSpec->client.write_iv,
- sid->u.ssl3.keys.client_write_iv,
- sizeof sid->u.ssl3.keys.client_write_iv);
- PORT_Memcpy(ss->ssl3->pwSpec->server.write_iv,
- sid->u.ssl3.keys.server_write_iv,
- sizeof sid->u.ssl3.keys.server_write_iv);
- }
- /* NULL value for PMS signifies re-use of the old MS */
- rv = ssl3_InitPendingCipherSpec(ss, NULL);
- if (rv != SECSuccess) {
- goto alert_loser; /* err code was set by ssl3_InitPendingCipherSpec */
- }
- if (ss->ssl3->hs.suite_def->bulk_cipher_alg == cipher_fortezza) {
- rv = PK11_RestoreContext(
- (PK11Context *)ss->ssl3->pwSpec->encodeContext,
- sid->u.ssl3.clientWriteSave,
- sid->u.ssl3.clientWriteSaveLen);
- if (rv != SECSuccess) {
- goto alert_loser; /* err is set. */
- }
- }
- SECITEM_ZfreeItem(&sidBytes, PR_FALSE);
- return SECSuccess;
- } while (0);
- if (sid_match)
- ++ssl3_hsh_sid_cache_not_ok;
- else
- ++ssl3_hsh_sid_cache_misses;
- /* throw the old one away */
- sid->u.ssl3.resumable = PR_FALSE;
- (*ss->sec->uncache)(sid);
- ssl_FreeSID(sid);
- /* get a new sid */
- ss->sec->ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
- if (sid == NULL) {
- goto alert_loser; /* memory error is set. */
- }
- sid->version = ss->version;
- sid->u.ssl3.sessionIDLength = sidBytes.len;
- PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len);
- SECITEM_ZfreeItem(&sidBytes, PR_FALSE);
- ss->ssl3->hs.isResuming = PR_FALSE;
- ss->ssl3->hs.ws = wait_server_cert;
- return SECSuccess;
- alert_loser:
- (void)SSL3_SendAlert(ss, alert_fatal, desc);
- loser:
- if (sidBytes.data != NULL)
- SECITEM_ZfreeItem(&sidBytes, PR_FALSE);
- errCode = ssl_MapLowLevelError(errCode);
- return SECFailure;
- }
- /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
- * ssl3 ServerKeyExchange message.
- * Caller must hold Handshake and RecvBuf locks.
- */
- static SECStatus
- ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
- {
- PRArenaPool * arena;
- SECKEYPublicKey *peerKey;
- PRBool isTLS;
- SECStatus rv;
- int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH;
- SSL3AlertDescription desc = illegal_parameter;
- SECItem modulus = {siBuffer, NULL, 0};
- SECItem exponent = {siBuffer, NULL, 0};
- SECItem signature = {siBuffer, NULL, 0};
- SSL3Hashes hashes;
- SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",
- SSL_GETPID(), ss->fd));
- PORT_Assert( ssl_HaveRecvBufLock(ss) );
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss) );
- if (ss->ssl3->hs.ws != wait_server_key &&
- ss->ssl3->hs.ws != wait_server_cert) {
- errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
- desc = unexpected_message;
- goto alert_loser;
- }
- if (ss->sec->peerCert == NULL) {
- errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
- desc = unexpected_message;
- goto alert_loser;
- }
- isTLS = (PRBool)(ss->ssl3->prSpec->version > SSL_LIBRARY_VERSION_3_0);
- switch (ss->ssl3->hs.kea_def->exchKeyType) {
- case kt_rsa:
- rv = ssl3_ConsumeHandshakeVariable(ss, &modulus, 2, &b, &length);
- if (rv != SECSuccess) {
- goto loser; /* malformed. */
- }
- rv = ssl3_ConsumeHandshakeVariable(ss, &exponent, 2, &b, &length);
- if (rv != SECSuccess) {
- goto loser; /* malformed. */
- }
- rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
- if (rv != SECSuccess) {
- goto loser; /* malformed. */
- }
- if (length != 0) {
- if (isTLS)
- desc = decode_error;
- goto alert_loser; /* malformed. */
- }
- /* failures after this point are not malformed handshakes. */
- /* TLS: send decrypt_error if signature failed. */
- desc = isTLS ? decrypt_error : handshake_failure;
- /*
- * check to make sure the hash is signed by right guy
- */
- rv = ssl3_ComputeExportRSAKeyHash(modulus, exponent,
- &ss->ssl3->hs.client_random,
- &ss->ssl3->hs.server_random, &hashes);
- if (rv != SECSuccess) {
- errCode =
- ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
- goto alert_loser;
- }
- rv = ssl3_VerifySignedHashes(&hashes, ss->sec->peerCert, &signature,
- isTLS, ss->pkcs11PinArg);
- if (rv != SECSuccess) {
- errCode =
- ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
- goto alert_loser;
- }
- /*
- * we really need to build a new key here because we can no longer
- * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
- * pkcs11 slots and ID's.
- */
- arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
- if (arena == NULL) {
- goto no_memory;
- }
- ss->sec->peerKey = peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
- if (peerKey == NULL) {
- goto no_memory;
- }
- peerKey->arena = arena;
- peerKey->keyType = rsaKey;
- peerKey->pkcs11Slot = NULL;
- peerKey->pkcs11ID = CK_INVALID_KEY;
- peerKey->u.rsa.modulus.data =
- (unsigned char*)PORT_ArenaAlloc(arena, modulus.len);
- if (peerKey->u.rsa.modulus.data == NULL)
- goto no_memory;
- PORT_Memcpy(peerKey->u.rsa.modulus.data, modulus.data, modulus.len);
- peerKey->u.rsa.modulus.len = modulus.len;
- peerKey->u.rsa.publicExponent.data =
- (unsigned char*)PORT_ArenaAlloc(arena, exponent.len);
- if (peerKey->u.rsa.publicExponent.data == NULL)
- goto no_memory;
- PORT_Memcpy(peerKey->u.rsa.publicExponent.data,
- exponent.data, exponent.len);
- peerKey->u.rsa.publicExponent.len = exponent.len;
- PORT_Free(modulus.data);
- PORT_Free(exponent.data);
- PORT_Free(signature.data);
- ss->ssl3->hs.ws = wait_cert_request;
- return SECSuccess;
- case kt_fortezza:
- /* Fortezza needs *BOTH* a server cert message
- * and a server key exchange message.
- */
- if (ss->ssl3->hs.ws == wait_server_cert) {
- errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
- desc = unexpected_message;
- goto alert_loser;
- }
- /* Get the server's "random" public key. */
- rv = ssl3_ConsumeHandshake(ss, ss->ssl3->fortezza.R_s,
- sizeof ss->ssl3->fortezza.R_s, &b, &length);
- if (rv != SECSuccess) {
- goto loser; /* malformed */
- }
- ss->ssl3->hs.ws = wait_cert_request;
- return SECSuccess;
- default:
- desc = handshake_failure;
- errCode = SEC_ERROR_UNSUPPORTED_KEYALG;
- break; /* goto alert_loser; */
- }
- alert_loser:
- (void)SSL3_SendAlert(ss, alert_fatal, desc);
- loser:
- if (modulus.data != NULL) SECITEM_FreeItem(&modulus, PR_FALSE);
- if (exponent.data != NULL) SECITEM_FreeItem(&exponent, PR_FALSE);
- if (signature.data != NULL) SECITEM_FreeItem(&signature, PR_FALSE);
- PORT_SetError( errCode );
- return SECFailure;
- no_memory: /* no-memory error has already been set. */
- if (modulus.data != NULL) SECITEM_FreeItem(&modulus, PR_FALSE);
- if (exponent.data != NULL) SECITEM_FreeItem(&exponent, PR_FALSE);
- if (signature.data != NULL) SECITEM_FreeItem(&signature, PR_FALSE);
- ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
- return SECFailure;
- }
- typedef struct dnameNode {
- struct dnameNode *next;
- SECItem name;
- } dnameNode;
- /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
- * ssl3 Certificate Request message.
- * Caller must hold Handshake and RecvBuf locks.
- */
- static SECStatus
- ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
- {
- ssl3State * ssl3 = ss->ssl3;
- PRArenaPool * arena = NULL;
- dnameNode * node;
- unsigned char * data;
- PRInt32 remaining;
- PRInt32 len;
- PRBool isTLS = PR_FALSE;
- int i;
- int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST;
- int nnames = 0;
- SECStatus rv;
- SSL3AlertDescription desc = illegal_parameter;
- SECItem cert_types = {siBuffer, NULL, 0};
- CERTDistNames ca_list;
- SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",
- SSL_GETPID(), ss->fd));
- PORT_Assert( ssl_HaveRecvBufLock(ss) );
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss) );
- if (ssl3->hs.ws != wait_cert_request &&
- ssl3->hs.ws != wait_server_key) {
- desc = unexpected_message;
- errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST;
- goto alert_loser;
- }
- isTLS = (PRBool)(ssl3->prSpec->version > SSL_LIBRARY_VERSION_3_0);
- rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length);
- if (rv != SECSuccess)
- goto loser; /* malformed, alert has been sent */
- arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
- if (arena == NULL)
- goto no_mem;
- remaining = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
- if (remaining < 0)
- goto loser; /* malformed, alert has been sent */
- ca_list.head = node = PORT_ArenaZNew(arena, dnameNode);
- if (node == NULL)
- goto no_mem;
- while (remaining != 0) {
- if (remaining < 2)
- goto alert_loser; /* malformed */
- node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
- if (len < 0)
- goto loser; /* malformed, alert has been sent */
- remaining -= 2;
- if (remaining < len)
- goto alert_loser; /* malformed */
- data = node->name.data = (unsigned char*)PORT_ArenaAlloc(arena, len);
- if (data == NULL)
- goto no_mem;
- rv = ssl3_ConsumeHandshake(ss, data, len, &b, &length);
- if (rv != SECSuccess)
- goto loser; /* malformed, alert has been sent */
- remaining -= len;
- nnames++;
- if (remaining == 0)
- break; /* success */
- node->next = PORT_ArenaZNew(arena, dnameNode);
- node = node->next;
- if (node == NULL)
- goto no_mem;
- }
- ca_list.nnames = nnames;
- ca_list.names = (SECItem*)PORT_ArenaAlloc(arena, nnames * sizeof(SECItem));
- if (ca_list.names == NULL)
- goto no_mem;
- for(i = 0, node = (dnameNode*)ca_list.head;
- i < nnames;
- i++, node = node->next) {
- ca_list.names[i] = node->name;
- }
- if (length != 0)
- goto alert_loser; /* malformed */
- desc = no_certificate;
- ssl3->hs.ws = wait_hello_done;
- if (ss->getClientAuthData == NULL) {
- rv = SECFailure; /* force it to send a no_certificate alert */
- } else {
- /* XXX Should pass cert_types in this call!! */
- rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg,
- ss->fd, &ca_list,
- &ssl3->clientCertificate,
- &ssl3->clientPrivateKey);
- }
- switch (rv) {
- case SECWouldBlock: /* getClientAuthData has put up a dialog box. */
- ssl_SetAlwaysBlock(ss);
- break; /* not an error */
- case SECSuccess:
- /* Setting ssl3->clientCertChain non-NULL will cause
- * ssl3_HandleServerHelloDone to call SendCertificate.
- */
- ssl3->clientCertChain = CERT_CertChainFromCert(ssl3->clientCertificate,
- certUsageSSLClient, PR_FALSE);
- if (ssl3->clientCertChain == NULL) {
- if (ssl3->clientCertificate != NULL) {
- CERT_DestroyCertificate(ssl3->clientCertificate);
- ssl3->clientCertificate = NULL;
- }
- if (ssl3->clientPrivateKey != NULL) {
- SECKEY_DestroyPrivateKey(ssl3->clientPrivateKey);
- ssl3->clientPrivateKey = NULL;
- }
- goto send_no_certificate;
- }
- break; /* not an error */
- case SECFailure:
- default:
- send_no_certificate:
- if (isTLS) {
- ssl3->sendEmptyCert = PR_TRUE;
- } else {
- (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
- }
- rv = SECSuccess;
- break;
- }
- goto done;
- no_mem:
- rv = SECFailure;
- PORT_SetError(SEC_ERROR_NO_MEMORY);
- goto done;
- alert_loser:
- if (isTLS && desc == illegal_parameter)
- desc = decode_error;
- (void)SSL3_SendAlert(ss, alert_fatal, desc);
- loser:
- PORT_SetError(errCode);
- rv = SECFailure;
- done:
- if (arena != NULL)
- PORT_FreeArena(arena, PR_FALSE);
- if (cert_types.data != NULL)
- SECITEM_FreeItem(&cert_types, PR_FALSE);
- return rv;
- }
- /*
- * attempt to restart the handshake after asynchronously handling
- * a request for the client's certificate.
- *
- * inputs:
- * cert Client cert chosen by application.
- * Note: ssl takes this reference, and does not bump the
- * reference count. The caller should drop its reference
- * without calling CERT_DestroyCert after calling this function.
- *
- * key Private key associated with cert. This function makes a
- * copy of the private key, so the caller remains responsible
- * for destroying its copy after this function returns.
- *
- * certChain Chain of signers for cert.
- * Note: ssl takes this reference, and does not copy the chain.
- * The caller should drop its reference without destroying the
- * chain. SSL will free the chain when it is done with it.
- *
- * Return value: XXX
- *
- * XXX This code only works on the initial handshake on a connection, XXX
- * It does not work on a subsequent handshake (redo).
- *
- * Caller holds 1stHandshakeLock.
- */
- SECStatus
- ssl3_RestartHandshakeAfterCertReq(sslSocket * ss,
- CERTCertificate * cert,
- SECKEYPrivateKey * key,
- CERTCertificateList *certChain)
- {
- SECStatus rv = SECSuccess;
- if (MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0)) {
- /* XXX This code only works on the initial handshake on a connection,
- ** XXX It does not work on a subsequent handshake (redo).
- */
- if (ss->handshake != 0) {
- ss->handshake = ssl_GatherRecord1stHandshake;
- ss->ssl3->clientCertificate = cert;
- ss->ssl3->clientCertChain = certChain;
- if (key == NULL) {
- (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
- ss->ssl3->clientPrivateKey = NULL;
- } else {
- ss->ssl3->clientPrivateKey = SECKEY_CopyPrivateKey(key);
- }
- ssl_GetRecvBufLock(ss);
- if (ss->ssl3->hs.msgState.buf != NULL) {
- rv = ssl3_HandleRecord(ss, NULL, &ss->gather->buf);
- }
- ssl_ReleaseRecvBufLock(ss);
- }
- }
- return rv;
- }
- /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
- * ssl3 Server Hello Done message.
- * Caller must hold Handshake and RecvBuf locks.
- */
- static SECStatus
- ssl3_HandleServerHelloDone(sslSocket *ss)
- {
- SECStatus rv;
- SSL3WaitState ws = ss->ssl3->hs.ws;
- PRBool send_verify = PR_FALSE;
- SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",
- SSL_GETPID(), ss->fd));
- PORT_Assert( ssl_HaveRecvBufLock(ss) );
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss) );
- if (ws != wait_hello_done &&
- ws != wait_server_cert &&
- ws != wait_server_key &&
- ws != wait_cert_request) {
- SSL3_SendAlert(ss, alert_fatal, unexpected_message);
- PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
- return SECFailure;
- }
- ssl_GetXmitBufLock(ss); /*******************************/
- if (ss->ssl3->sendEmptyCert) {
- ss->ssl3->sendEmptyCert = PR_FALSE;
- rv = ssl3_SendEmptyCertificate(ss);
- /* Don't send verify */
- if (rv != SECSuccess) {
- goto loser; /* error code is set. */
- }
- } else
- if (ss->ssl3->clientCertChain != NULL &&
- ss->ssl3->clientPrivateKey != NULL) {
- send_verify = PR_TRUE;
- rv = ssl3_SendCertificate(ss);
- if (rv != SECSuccess) {
- goto loser; /* error code is set. */
- }
- }
- rv = ssl3_SendClientKeyExchange(ss);
- if (rv != SECSuccess) {
- goto loser; /* err is set. */
- }
- if (send_verify) {
- rv = ssl3_SendCertificateVerify(ss);
- if (rv != SECSuccess) {
- goto loser; /* err is set. */
- }
- }
- rv = ssl3_SendChangeCipherSpecs(ss);
- if (rv != SECSuccess) {
- goto loser; /* err code was set. */
- }
- rv = ssl3_SendFinished(ss, 0);
- if (rv != SECSuccess) {
- goto loser; /* err code was set. */
- }
- ssl_ReleaseXmitBufLock(ss); /*******************************/
- ss->ssl3->hs.ws = wait_change_cipher;
- return SECSuccess;
- loser:
- ssl_ReleaseXmitBufLock(ss);
- return rv;
- }
- /*
- * Routines used by servers
- */
- static SECStatus
- ssl3_SendHelloRequest(sslSocket *ss)
- {
- SECStatus rv;
- SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),
- ss->fd));
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss) );
- PORT_Assert( ssl_HaveXmitBufLock(ss) );
- rv = ssl3_AppendHandshakeHeader(ss, hello_request, 0);
- if (rv != SECSuccess) {
- return rv; /* err set by AppendHandshake */
- }
- rv = ssl3_FlushHandshake(ss, 0);
- if (rv != SECSuccess) {
- return rv; /* error code set by ssl3_FlushHandshake */
- }
- ss->ssl3->hs.ws = wait_client_hello;
- return SECSuccess;
- }
- /* Sets memory error when returning NULL.
- * Called from:
- * ssl3_SendClientHello()
- * ssl3_HandleServerHello()
- * ssl3_HandleClientHello()
- * ssl3_HandleV2ClientHello()
- */
- static sslSessionID *
- ssl3_NewSessionID(sslSocket *ss, PRBool is_server)
- {
- sslSessionID *sid;
- sid = PORT_ZNew(sslSessionID);
- if (sid == NULL)
- return sid;
- sid->peerID = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID);
- sid->urlSvrName = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url);
- sid->addr = ss->sec->ci.peer;
- sid->port = ss->sec->ci.port;
- sid->references = 1;
- sid->cached = never_cached;
- sid->version = ss->version;
- sid->u.ssl3.resumable = PR_TRUE;
- sid->u.ssl3.policy = SSL_ALLOWED;
- sid->u.ssl3.hasFortezza = PR_FALSE;
- sid->u.ssl3.clientWriteKey = NULL;
- sid->u.ssl3.serverWriteKey = NULL;
- sid->u.ssl3.tek = NULL;
- if (is_server) {
- SECStatus rv;
- int pid = SSL_GETPID();
- sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
- sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff;
- sid->u.ssl3.sessionID[1] = pid & 0xff;
- rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2,
- SSL3_SESSIONID_BYTES -2);
- if (rv != SECSuccess) {
- ssl_FreeSID(sid);
- ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
- return NULL;
- }
- }
- return sid;
- }
- /* Called from: ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
- static SECStatus
- ssl3_SendServerHelloSequence(sslSocket *ss)
- {
- const ssl3KEADef *kea_def;
- SECStatus rv;
- SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",
- SSL_GETPID(), ss->fd));
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss) );
- PORT_Assert( ssl_HaveXmitBufLock(ss) );
- rv = ssl3_SendServerHello(ss);
- if (rv != SECSuccess) {
- return rv; /* err code is set. */
- }
- rv = ssl3_SendCertificate(ss);
- if (rv != SECSuccess) {
- return rv; /* error code is set. */
- }
- /* We have to do this after the call to ssl3_SendServerHello,
- * because kea_def is set up by ssl3_SendServerHello().
- */
- kea_def = ss->ssl3->hs.kea_def;
- ss->ssl3->hs.usedStepDownKey = PR_FALSE;
- if (kea_def->kea == kea_fortezza) {
- rv = ssl3_SendServerKeyExchange(ss);
- if (rv != SECSuccess) {
- return rv; /* err code was set. */
- }
- } else if (kea_def->is_limited && kea_def->exchKeyType == kt_rsa) {
- /* see if we can legally use the key in the cert. */
- int keyLen; /* bytes */
- keyLen = PK11_GetPrivateModulusLen(
- ss->serverKey[kea_def->exchKeyType]);
- if (keyLen > 0 &&
- keyLen * BPB <= kea_def->key_size_limit ) {
- /* XXX AND cert is not signing only!! */
- /* just fall through and use it. */
- } else if (ss->stepDownKeyPair != NULL) {
- ss->ssl3->hs.usedStepDownKey = PR_TRUE;
- rv = ssl3_SendServerKeyExchange(ss);
- if (rv != SECSuccess) {
- return rv; /* err code was set. */
- }
- } else {
- #ifndef HACKED_EXPORT_SERVER
- PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
- return rv;
- #endif
- }
- }
- if (ss->requestCertificate) {
- rv = ssl3_SendCertificateRequest(ss);
- if (rv != SECSuccess) {
- return rv; /* err code is set. */
- }
- }
- rv = ssl3_SendServerHelloDone(ss);
- if (rv != SECSuccess) {
- return rv; /* err code is set. */
- }
- ss->ssl3->hs.ws = (ss->requestCertificate) ? wait_client_cert
- : wait_client_key;
- return SECSuccess;
- }
- /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
- * ssl3 Client Hello message.
- * Caller must hold Handshake and RecvBuf locks.
- */
- static SECStatus
- ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
- {
- sslSessionID * sid = NULL;
- ssl3State * ssl3;
- sslConnectInfo * ci;
- PRInt32 tmp;
- unsigned int i;
- int j;
- SECStatus rv;
- int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
- SSL3AlertDescription desc = illegal_parameter;
- SSL3ProtocolVersion version;
- SECItem sidBytes = {siBuffer, NULL, 0};
- SECItem suites = {siBuffer, NULL, 0};
- SECItem comps = {siBuffer, NULL, 0};
- PRBool haveSpecWriteLock = PR_FALSE;
- PRBool haveXmitBufLock = PR_FALSE;
- SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",
- SSL_GETPID(), ss->fd));
- PORT_Assert( ssl_HaveRecvBufLock(ss) );
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss));
- /* Get peer name of client */
- rv = ssl_GetPeerInfo(ss);
- if (rv != SECSuccess) {
- return rv; /* error code is set. */
- }
- rv = ssl3_InitState(ss);
- if (rv != SECSuccess) {
- return rv; /* ssl3_InitState has set the error code. */
- }
- ssl3 = ss->ssl3;
- if ((ssl3->hs.ws != wait_client_hello) &&
- (ssl3->hs.ws != idle_handshake)) {
- desc = unexpected_message;
- errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
- goto alert_loser;
- }
- ci = &ss->sec->ci;
- tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
- if (tmp < 0)
- goto loser; /* malformed, alert already sent */
- ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp;
- rv = ssl3_NegotiateVersion(ss, version);
- if (rv != SECSuccess) {
- /* We can't do the usual isTLS test here, because the negotiated
- ** version is definitely not 3.1. So the question is, are we
- ** willing/able to do TLS here on our side?
- */
- desc = ss->enableTLS ? protocol_version : handshake_failure;
- errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
- goto alert_loser;
- }
- /* grab the client random data. */
- rv = ssl3_ConsumeHandshake(
- ss, &ssl3->hs.client_random, SSL3_RANDOM_LENGTH, &b, &length);
- if (rv != SECSuccess) {
- goto loser; /* malformed */
- }
- /* grab the client's SID, if present. */
- rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
- if (rv != SECSuccess) {
- goto loser; /* malformed */
- }
- if (sidBytes.len > 0) {
- SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
- SSL_GETPID(), ss->fd, ci->peer.pr_s6_addr32[0],
- ci->peer.pr_s6_addr32[1], ci->peer.pr_s6_addr32[2],
- ci->peer.pr_s6_addr32[3]));
- sid = (*ssl_sid_lookup)(&ci->peer, sidBytes.data, sidBytes.len,
- ss->dbHandle);
- }
- SECITEM_FreeItem(&sidBytes, PR_FALSE);
- /* grab the list of cipher suites. */
- rv = ssl3_ConsumeHandshakeVariable(ss, &suites, 2, &b, &length);
- if (rv != SECSuccess) {
- goto loser; /* malformed */
- }
- /* grab the list of compression methods. */
- rv = ssl3_ConsumeHandshakeVariable(ss, &comps, 1, &b, &length);
- if (rv != SECSuccess) {
- goto loser; /* malformed */
- }
- /* It's OK for length to be non-zero here.
- * Non-zero length means that some new protocol revision has extended
- * the client hello message.
- */
- desc = handshake_failure;
- if (sid != NULL) {
- /* We've found a session cache entry for this client.
- * Now, if we're going to require a client-auth cert,
- * and we don't already have this client's cert in the session cache,
- * and this is the first handshake on this connection (not a redo),
- * then drop this old cache entry and start a new session.
- */
- if ((sid->peerCert == NULL) && ss->requestCertificate &&
- ((ss->requireCertificate == 1) ||
- ((ss->requireCertificate == 2) && !ss->connected))) {
- ++ssl3_hch_sid_cache_not_ok;
- ss->sec->uncache(sid);
- ssl_FreeSID(sid);
- sid = NULL;
- }
- }
- /* Look for a matching cipher suite. */
- j = ssl3_config_match_init(ss);
- if (j <= 0) { /* no ciphers are working/supported by PK11 */
- errCode = PORT_GetError(); /* error code is already set. */
- goto alert_loser;
- }
- /* If we already have a session for this client, be sure to pick the
- ** same cipher suite we picked before.
- ** This is not a loop, despite appearances.
- */
- if (sid) do {
- ssl3CipherSuiteCfg *suite = ss->cipherSuites;
- for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) {
- if (suite->cipher_suite == sid->u.ssl3.cipherSuite)
- break;
- }
- if (!j)
- break;
- if (!config_match(suite, ssl3->policy, PR_TRUE))
- break;
- for (i = 0; i < suites.len; i += 2) {
- if ((suites.data[i] == MSB(suite->cipher_suite)) &&
- (suites.data[i + 1] == LSB(suite->cipher_suite))) {
- ssl3->hs.cipher_suite = suite->cipher_suite;
- ssl3->hs.suite_def =
- ssl_LookupCipherSuiteDef(ssl3->hs.cipher_suite);
- goto suite_found;
- }
- }
- } while (0);
- /* Select a cipher suite.
- ** NOTE: This suite selection algorithm should be the same as the one in
- ** ssl3_HandleV2ClientHello().
- */
- for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
- ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
- if (!config_match(suite, ssl3->policy, PR_TRUE))
- continue;
- for (i = 0; i < suites.len; i += 2) {
- if ((suites.data[i] == MSB(suite->cipher_suite)) &&
- (suites.data[i + 1] == LSB(suite->cipher_suite))) {
- ssl3->hs.cipher_suite = suite->cipher_suite;
- ssl3->hs.suite_def =
- ssl_LookupCipherSuiteDef(ssl3->hs.cipher_suite);
- goto suite_found;
- }
- }
- }
- errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
- goto alert_loser;
- suite_found:
- /* Look for a matching compression algorithm. */
- for (i = 0; i < comps.len; i++) {
- for (j = 0; j < compressionMethodsCount; j++) {
- if (comps.data[i] == compressions[j]) {
- ssl3->hs.compression = (SSL3CompressionMethod)compressions[j];
- goto compression_found;
- }
- }
- }
- errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
- /* null compression must be supported */
- goto alert_loser;
- compression_found:
- PORT_Free(suites.data);
- suites.data = NULL;
- PORT_Free(comps.data);
- comps.data = NULL;
- ss->sec->send = ssl3_SendApplicationData;
- /* If there are any failures while processing the old sid,
- * we don't consider them to be errors. Instead, We just behave
- * as if the client had sent us no sid to begin with, and make a new one.
- */
- if (sid != NULL) do {
- PK11SlotInfo * slot;
- PK11SymKey * wrapKey; /* wrapping key */
- SECItem wrappedKey; /* wrapped key */
- ssl3CipherSpec *pwSpec;
- CK_FLAGS keyFlags = 0;
- if (sid->version != ss->version ||
- sid->u.ssl3.cipherSuite != ssl3->hs.cipher_suite) {
- break; /* not an error */
- }
- if (ci->sid) {
- ss->sec->uncache(ci->sid);
- PORT_Assert(ci->sid != sid); /* should be impossible, but ... */
- if (ci->sid != sid) {
- ssl_FreeSID(ci->sid);
- }
- ci->sid = NULL;
- }
- /* we need to resurrect the master secret.... */
- ssl_GetSpecWriteLock(ss); haveSpecWriteLock = PR_TRUE;
- pwSpec = ssl3->pwSpec;
- wrapKey = getWrappingKey(ss, NULL, sid->u.ssl3.exchKeyType,
- sid->u.ssl3.masterWrapMech, ss->pkcs11PinArg);
- if (!wrapKey) {
- /* we have a SID cache entry, but no wrapping key for it??? */
- break;
- }
- if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
- keyFlags = CKF_SIGN | CKF_VERIFY;
- }
- wrappedKey.data = sid->u.ssl3.keys.wrapped_master_secret;
- wrappedKey.len = sid->u.ssl3.keys.wrapped_master_secret_len;
- /* unwrap the master secret. */
- pwSpec->master_secret =
- PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
- NULL, &wrappedKey, CKM_SSL3_MASTER_KEY_DERIVE,
- CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags);
- PK11_FreeSymKey(wrapKey);
- if (pwSpec->master_secret == NULL) {
- break; /* not an error */
- }
- ci->sid = sid;
- if (sid->peerCert != NULL) {
- ss->sec->peerCert = CERT_DupCertificate(sid->peerCert);
- }
- /*
- * Old SID passed all tests, so resume this old session.
- *
- * XXX make sure compression still matches
- */
- ++ssl3_hch_sid_cache_hits;
- ssl3->hs.isResuming = PR_TRUE;
- ssl_GetXmitBufLock(ss); haveXmitBufLock = PR_TRUE;
- rv = ssl3_SendServerHello(ss);
- if (rv != SECSuccess) {
- errCode = PORT_GetError();
- goto loser;
- }
- /* reload the FORTEZZA key material.
- * On Fortezza, the following keys & IVs are generated by the KEA,
- * not from the PMS. Since we're not going to redo the KEA, we
- * have to save & restore them for Fortezza.
- * use kea because we haven't call InitCipher Specs yet...?
- */
- if (ssl3->hs.suite_def->bulk_cipher_alg == cipher_fortezza) {
- PK11SymKey * Ks;
- SECItem item;
- PORT_Memcpy(pwSpec->client.write_iv,
- sid->u.ssl3.keys.client_write_iv,
- sizeof sid->u.ssl3.keys.client_write_iv);
- PORT_Memcpy(pwSpec->server.write_iv,
- sid->u.ssl3.keys.server_write_iv,
- sizeof sid->u.ssl3.keys.server_write_iv);
- /* Now, unwrap the client and server write keys with Ks */
- /* get the slot that the fortezza server private key is in. */
- slot = PK11_GetSlotFromPrivateKey(ss->serverKey[kt_fortezza]);
- if (slot == NULL) {
- ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
- goto loser;
- }
- /* Look up the Token Fixed Key */
- Ks = PK11_FindFixedKey(slot, CKM_SKIPJACK_WRAP, NULL,
- ss->pkcs11PinArg);
- PK11_FreeSlot(slot);
- if (Ks == NULL) {
- ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
- goto loser;
- }
- /* unwrap client write key with the local Ks */
- item.data = sid->u.ssl3.keys.wrapped_client_write_key;
- item.len = sizeof sid->u.ssl3.keys.wrapped_client_write_key;
- pwSpec->client.write_key =
- PK11_UnwrapSymKey(Ks, CKM_SKIPJACK_WRAP, NULL, &item,
- CKM_SKIPJACK_CBC64, CKA_DECRYPT, 0);
- if (pwSpec->client.write_key == NULL) {
- SEND_ALERT
- ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_UNWRAP_FAILURE);
- goto loser;
- }
- /* unwrap server write key with the local Ks */
- item.data = sid->u.ssl3.keys.wrapped_server_write_key;
- item.len = sizeof sid->u.ssl3.keys.wrapped_server_write_key;
- pwSpec->server.write_key =
- PK11_UnwrapSymKey(Ks, CKM_SKIPJACK_WRAP, NULL, &item,
- CKM_SKIPJACK_CBC64, CKA_ENCRYPT, 0);
- if (pwSpec->server.write_key == NULL) {
- PK11_FreeSymKey(pwSpec->client.write_key);
- pwSpec->client.write_key = NULL;
- SEND_ALERT
- ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_UNWRAP_FAILURE);
- goto loser;
- }
- /* Set flag that says "generate 8 byte random prefix plaintext." */
- PK11_SetFortezzaHack(pwSpec->server.write_key); /* can't fail */
- }
- if (haveSpecWriteLock) {
- ssl_ReleaseSpecWriteLock(ss);
- haveSpecWriteLock = PR_FALSE;
- }
- /* NULL value for PMS signifies re-use of the old MS */
- rv = ssl3_InitPendingCipherSpec(ss, NULL);
- if (rv != SECSuccess) {
- errCode = PORT_GetError();
- goto loser;
- }
- rv = ssl3_SendChangeCipherSpecs(ss);
- if (rv != SECSuccess) {
- errCode = PORT_GetError();
- goto loser;
- }
- rv = ssl3_SendFinished(ss, 0);
- ssl3->hs.ws = wait_change_cipher;
- if (rv != SECSuccess) {
- errCode = PORT_GetError();
- goto loser;
- }
- if (haveXmitBufLock) {
- ssl_ReleaseXmitBufLock(ss);
- haveXmitBufLock = PR_FALSE;
- }
- return SECSuccess;
- } while (0);
- if (haveSpecWriteLock) {
- ssl_ReleaseSpecWriteLock(ss);
- haveSpecWriteLock = PR_FALSE;
- }
- if (sid) { /* we had a sid, but it's no longer valid, free it */
- ++ssl3_hch_sid_cache_not_ok;
- ss->sec->uncache(sid);
- ssl_FreeSID(sid);
- sid = NULL;
- }
- ++ssl3_hch_sid_cache_misses;
- sid = ssl3_NewSessionID(ss, PR_TRUE);
- if (sid == NULL) {
- errCode = PORT_GetError();
- goto loser; /* memory error is set. */
- }
- ci->sid = sid;
- ssl3->hs.isResuming = PR_FALSE;
- ssl_GetXmitBufLock(ss);
- rv = ssl3_SendServerHelloSequence(ss);
- ssl_ReleaseXmitBufLock(ss);
- if (rv != SECSuccess) {
- errCode = PORT_GetError();
- goto loser;
- }
- if (haveXmitBufLock) {
- ssl_ReleaseXmitBufLock(ss);
- haveXmitBufLock = PR_FALSE;
- }
- return SECSuccess;
- alert_loser:
- if (haveSpecWriteLock) {
- ssl_ReleaseSpecWriteLock(ss);
- haveSpecWriteLock = PR_FALSE;
- }
- (void)SSL3_SendAlert(ss, alert_fatal, desc);
- /* FALLTHRU */
- loser:
- if (haveSpecWriteLock) {
- ssl_ReleaseSpecWriteLock(ss);
- haveSpecWriteLock = PR_FALSE;
- }
- if (sidBytes.data != NULL) SECITEM_FreeItem(&sidBytes, PR_FALSE);
- if (suites.data != NULL) SECITEM_FreeItem(&suites, PR_FALSE);
- if (comps.data != NULL) SECITEM_FreeItem(&comps, PR_FALSE);
- if (haveXmitBufLock) {
- ssl_ReleaseXmitBufLock(ss);
- haveXmitBufLock = PR_FALSE;
- }
- PORT_SetError(errCode);
- return SECFailure;
- }
- /*
- * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
- * in asking to use the V3 handshake.
- * Called from ssl2_HandleClientHelloMessage() in sslcon.c
- */
- SECStatus
- ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length)
- {
- sslSessionID * sid = NULL;
- unsigned char * suites;
- unsigned char * random;
- SSL3ProtocolVersion version;
- SECStatus rv;
- int i;
- int j;
- int sid_length;
- int suite_length;
- int rand_length;
- int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
- SSL3AlertDescription desc = handshake_failure;
- SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd));
- PORT_Assert( ssl_HaveRecvBufLock(ss) );
- ssl_GetSSL3HandshakeLock(ss);
- rv = ssl3_InitState(ss);
- if (rv != SECSuccess) {
- ssl_ReleaseSSL3HandshakeLock(ss);
- return rv; /* ssl3_InitState has set the error code. */
- }
- if (ss->ssl3->hs.ws != wait_client_hello) {
- desc = unexpected_message;
- errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
- goto loser; /* alert_loser */
- }
- version = (buffer[1] << 8) | buffer[2];
- suite_length = (buffer[3] << 8) | buffer[4];
- sid_length = (buffer[5] << 8) | buffer[6];
- rand_length = (buffer[7] << 8) | buffer[8];
- ss->clientHelloVersion = version;
- rv = ssl3_NegotiateVersion(ss, version);
- if (rv != SECSuccess) {
- desc = ss->enableTLS ? protocol_version : handshake_failure;
- errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
- /* It's not appropriate to send back SSL3/TLS alert records in
- ** response to an SSL2 client hello, unless the version is
- ** succesfully negotiated to 3.0 or greater, so just goto loser. */
- goto loser; /* alert_loser */
- }
- /* if we get a non-zero SID, just ignore it. */
- if (length !=
- SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + rand_length) {
- SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",
- SSL_GETPID(), ss->fd, length,
- SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length +
- rand_length));
- goto loser; /* malformed */ /* alert_loser */
- }
- suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES;
- random = suites + suite_length + sid_length;
- if (rand_length < SSL_MIN_CHALLENGE_BYTES ||
- rand_length > SSL_MAX_CHALLENGE_BYTES) {
- goto loser; /* malformed */ /* alert_loser */
- }
- PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH);
- PORT_Memset(&ss->ssl3->hs.client_random, 0, SSL3_RANDOM_LENGTH);
- PORT_Memcpy(
- &ss->ssl3->hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length],
- random, rand_length);
- PRINT_BUF(60, (ss, "client random:", &ss->ssl3->hs.client_random.rand[0],
- SSL3_RANDOM_LENGTH));
- i = ssl3_config_match_init(ss);
- if (i <= 0) {
- errCode = PORT_GetError(); /* error code is already set. */
- goto alert_loser;
- }
- /* Select a cipher suite.
- ** NOTE: This suite selection algorithm should be the same as the one in
- ** ssl3_HandleClientHello().
- */
- for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
- ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
- if (!config_match(suite, ss->ssl3->policy, PR_TRUE))
- continue;
- for (i = 0; i < suite_length; i += 3) {
- if ((suites[i] == 0) &&
- (suites[i+1] == MSB(suite->cipher_suite)) &&
- (suites[i+2] == LSB(suite->cipher_suite))) {
- ss->ssl3->hs.cipher_suite = suite->cipher_suite;
- ss->ssl3->hs.suite_def =
- ssl_LookupCipherSuiteDef(ss->ssl3->hs.cipher_suite);
- goto suite_found;
- }
- }
- }
- errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
- goto alert_loser;
- suite_found:
- ss->ssl3->hs.compression = compression_null;
- ss->sec->send = ssl3_SendApplicationData;
- /* we don't even search for a cache hit here. It's just a miss. */
- ++ssl3_hch_sid_cache_misses;
- sid = ssl3_NewSessionID(ss, PR_TRUE);
- if (sid == NULL) {
- errCode = PORT_GetError();
- goto loser; /* memory error is set. */
- }
- ss->sec->ci.sid = sid;
- /* do not worry about memory leak of sid since it now belongs to ci */
- /* We have to update the handshake hashes before we can send stuff */
- rv = ssl3_UpdateHandshakeHashes(ss, buffer, length);
- if (rv != SECSuccess) {
- errCode = PORT_GetError();
- goto loser;
- }
- ssl_GetXmitBufLock(ss);
- rv = ssl3_SendServerHelloSequence(ss);
- ssl_ReleaseXmitBufLock(ss);
- if (rv != SECSuccess) {
- errCode = PORT_GetError();
- goto loser;
- }
- /* XXX_1 The call stack to here is:
- * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here.
- * ssl2_HandleClientHelloMessage returns whatever we return here.
- * ssl_Do1stHandshake will continue looping if it gets back either
- * SECSuccess or SECWouldBlock.
- * SECSuccess is preferable here. See XXX_1 in sslgathr.c.
- */
- ssl_ReleaseSSL3HandshakeLock(ss);
- return SECSuccess;
- alert_loser:
- SSL3_SendAlert(ss, alert_fatal, desc);
- loser:
- ssl_ReleaseSSL3HandshakeLock(ss);
- PORT_SetError(errCode);
- return SECFailure;
- }
- /* The negotiated version number has been already placed in ss->version.
- **
- ** Called from: ssl3_HandleClientHello (resuming session),
- ** ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session),
- ** ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
- */
- static SECStatus
- ssl3_SendServerHello(sslSocket *ss)
- {
- sslSessionID *sid;
- SECStatus rv;
- PRUint32 length;
- SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
- ss->fd));
- PORT_Assert(ss->sec);
- PORT_Assert( ssl_HaveXmitBufLock(ss));
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss));
- PORT_Assert( MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0));
- if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
- PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
- return SECFailure;
- }
- sid = ss->sec->ci.sid;
- length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + 1 +
- ((sid == NULL) ? 0: SSL3_SESSIONID_BYTES) +
- sizeof(ssl3CipherSuite) + 1;
- rv = ssl3_AppendHandshakeHeader(ss, server_hello, length);
- if (rv != SECSuccess) {
- return rv; /* err set by AppendHandshake. */
- }
- rv = ssl3_AppendHandshakeNumber(ss, ss->version, 2);
- if (rv != SECSuccess) {
- return rv; /* err set by AppendHandshake. */
- }
- rv = ssl3_GetNewRandom(&ss->ssl3->hs.server_random);
- if (rv != SECSuccess) {
- ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
- return rv;
- }
- rv = ssl3_AppendHandshake(
- ss, &ss->ssl3->hs.server_random, SSL3_RANDOM_LENGTH);
- if (rv != SECSuccess) {
- return rv; /* err set by AppendHandshake. */
- }
- if (sid)
- rv = ssl3_AppendHandshakeVariable(
- ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
- else
- rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
- if (rv != SECSuccess) {
- return rv; /* err set by AppendHandshake. */
- }
- rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3->hs.cipher_suite, 2);
- if (rv != SECSuccess) {
- return rv; /* err set by AppendHandshake. */
- }
- rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3->hs.compression, 1);
- if (rv != SECSuccess) {
- return rv; /* err set by AppendHandshake. */
- }
- rv = ssl3_SetupPendingCipherSpec(ss, ss->ssl3);
- if (rv != SECSuccess) {
- return rv; /* err set by ssl3_SetupPendingCipherSpec */
- }
- return SECSuccess;
- }
- static SECStatus
- ssl3_SendServerKeyExchange(sslSocket *ss)
- {
- const ssl3KEADef * kea_def = ss->ssl3->hs.kea_def;
- SECStatus rv = SECFailure;
- int length;
- PRBool isTLS;
- SECItem signed_hash = {siBuffer, NULL, 0};
- SSL3Hashes hashes;
- SECKEYPublicKey * sdPub; /* public key for step-down */
- SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
- SSL_GETPID(), ss->fd));
- PORT_Assert( ssl_HaveXmitBufLock(ss));
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss));
- switch (kea_def->exchKeyType) {
- case kt_rsa:
- /* Perform SSL Step-Down here. */
- sdPub = ss->stepDownKeyPair->pubKey;
- PORT_Assert(sdPub != NULL);
- if (!sdPub) {
- PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
- return SECFailure;
- }
- rv = ssl3_ComputeExportRSAKeyHash(sdPub->u.rsa.modulus,
- sdPub->u.rsa.publicExponent,
- &ss->ssl3->hs.client_random,
- &ss->ssl3->hs.server_random,
- &hashes);
- if (rv != SECSuccess) {
- ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
- return rv;
- }
- isTLS = (PRBool)(ss->ssl3->pwSpec->version > SSL_LIBRARY_VERSION_3_0);
- rv = ssl3_SignHashes(&hashes, ss->serverKey[kt_rsa], &signed_hash,
- isTLS);
- if (rv != SECSuccess) {
- goto loser; /* ssl3_SignHashes has set err. */
- }
- if (signed_hash.data == NULL) {
- /* how can this happen and rv == SECSuccess ?? */
- PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
- goto loser;
- }
- length = 2 + sdPub->u.rsa.modulus.len +
- 2 + sdPub->u.rsa.publicExponent.len +
- 2 + signed_hash.len;
- rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length);
- if (rv != SECSuccess) {
- goto loser; /* err set by AppendHandshake. */
- }
- rv = ssl3_AppendHandshakeVariable(ss, sdPub->u.rsa.modulus.data,
- sdPub->u.rsa.modulus.len, 2);
- if (rv != SECSuccess) {
- goto loser; /* err set by AppendHandshake. */
- }
- rv = ssl3_AppendHandshakeVariable(
- ss, sdPub->u.rsa.publicExponent.data,
- sdPub->u.rsa.publicExponent.len, 2);
- if (rv != SECSuccess) {
- goto loser; /* err set by AppendHandshake. */
- }
- rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
- signed_hash.len, 2);
- if (rv != SECSuccess) {
- goto loser; /* err set by AppendHandshake. */
- }
- PORT_Free(signed_hash.data);
- return SECSuccess;
- case kt_fortezza:
- /* Set server's "random" public key R_s to the email value == 1 */
- PORT_Memset(ss->ssl3->fortezza.R_s, 0, sizeof(ss->ssl3->fortezza.R_s));
- ss->ssl3->fortezza.R_s[127] = 1;
- /* don't waste time signing the random number */
- length = sizeof (ss->ssl3->fortezza.R_s) /*+ 2 + signed_hash.len*/;
- rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length);
- if (rv != SECSuccess) {
- goto loser; /* err set by AppendHandshake. */
- }
- rv = ssl3_AppendHandshake( ss, &ss->ssl3->fortezza.R_s,
- sizeof(ss->ssl3->fortezza.R_s));
- if (rv != SECSuccess) {
- goto loser; /* err set by AppendHandshake. */
- }
- return SECSuccess;
- case kt_dh:
- case kt_null:
- default:
- PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
- break;
- }
- loser:
- if (signed_hash.data != NULL)
- PORT_Free(signed_hash.data);
- return SECFailure;
- }
- static SECStatus
- ssl3_SendCertificateRequest(sslSocket *ss)
- {
- SECItem * name;
- CERTDistNames *ca_list;
- const uint8 * certTypes;
- SECItem * names = NULL;
- SECStatus rv;
- int length;
- int i;
- int calen = 0;
- int nnames = 0;
- int certTypesLength;
- SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
- SSL_GETPID(), ss->fd));
- PORT_Assert( ssl_HaveXmitBufLock(ss));
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss));
- /* ssl3->ca_list is initialized to NULL, and never changed. */
- ca_list = ss->ssl3->ca_list;
- if (!ca_list) {
- ca_list = ssl3_server_ca_list;
- }
- if (ca_list != NULL) {
- names = ca_list->names;
- nnames = ca_list->nnames;
- }
- if (!nnames) {
- PORT_SetError(SSL_ERROR_NO_TRUSTED_SSL_CLIENT_CA);
- return SECFailure;
- }
- for (i = 0, name = names; i < nnames; i++, name++) {
- calen += 2 + name->len;
- }
- if (ss->ssl3->hs.kea_def->exchKeyType == kt_fortezza) {
- certTypes = fortezza_certificate_types;
- certTypesLength = sizeof fortezza_certificate_types;
- } else {
- certTypes = certificate_types;
- certTypesLength = sizeof certificate_types;
- }
- length = 1 + certTypesLength + 2 + calen;
- rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length);
- if (rv != SECSuccess) {
- return rv; /* err set by AppendHandshake. */
- }
- rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1);
- if (rv != SECSuccess) {
- return rv; /* err set by AppendHandshake. */
- }
- rv = ssl3_AppendHandshakeNumber(ss, calen, 2);
- if (rv != SECSuccess) {
- return rv; /* err set by AppendHandshake. */
- }
- for (i = 0, name = names; i < nnames; i++, name++) {
- rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2);
- if (rv != SECSuccess) {
- return rv; /* err set by AppendHandshake. */
- }
- }
- return SECSuccess;
- }
- static SECStatus
- ssl3_SendServerHelloDone(sslSocket *ss)
- {
- SECStatus rv;
- SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
- SSL_GETPID(), ss->fd));
- PORT_Assert( ssl_HaveXmitBufLock(ss));
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss));
- rv = ssl3_AppendHandshakeHeader(ss, server_hello_done, 0);
- if (rv != SECSuccess) {
- return rv; /* err set by AppendHandshake. */
- }
- rv = ssl3_FlushHandshake(ss, 0);
- if (rv != SECSuccess) {
- return rv; /* error code set by ssl3_FlushHandshake */
- }
- return SECSuccess;
- }
- /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
- * ssl3 Certificate Verify message
- * Caller must hold Handshake and RecvBuf locks.
- */
- static SECStatus
- ssl3_HandleCertificateVerify(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
- SSL3Hashes *hashes)
- {
- SECItem signed_hash = {siBuffer, NULL, 0};
- SECStatus rv;
- int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY;
- SSL3AlertDescription desc = handshake_failure;
- PRBool isTLS;
- SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
- SSL_GETPID(), ss->fd));
- PORT_Assert( ssl_HaveRecvBufLock(ss) );
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss) );
- if (ss->ssl3->hs.ws != wait_cert_verify || ss->sec->peerCert == NULL) {
- desc = unexpected_message;
- errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY;
- goto alert_loser;
- }
- rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
- if (rv != SECSuccess) {
- goto loser; /* malformed. */
- }
- isTLS = (PRBool)(ss->ssl3->prSpec->version > SSL_LIBRARY_VERSION_3_0);
- /* XXX verify that the key & kea match */
- rv = ssl3_VerifySignedHashes(hashes, ss->sec->peerCert, &signed_hash,
- isTLS, ss->pkcs11PinArg);
- if (rv != SECSuccess) {
- errCode = PORT_GetError();
- desc = isTLS ? decrypt_error : handshake_failure;
- goto alert_loser;
- }
- PORT_Free(signed_hash.data);
- signed_hash.data = NULL;
- if (length != 0) {
- desc = isTLS ? decode_error : illegal_parameter;
- goto alert_loser; /* malformed */
- }
- ss->ssl3->hs.ws = wait_change_cipher;
- return SECSuccess;
- alert_loser:
- SSL3_SendAlert(ss, alert_fatal, desc);
- loser:
- if (signed_hash.data != NULL) SECITEM_FreeItem(&signed_hash, PR_FALSE);
- PORT_SetError(errCode);
- return SECFailure;
- }
- /*
- ** Called from ssl3_HandleClientKeyExchange()
- */
- static SECStatus
- ssl3_HandleFortezzaClientKeyExchange(sslSocket *ss, SSL3Opaque *b,
- PRUint32 length,
- SECKEYPrivateKey *serverKey)
- {
- SECKEYPublicKey * pubKey = NULL;
- PK11SymKey * tek = NULL;
- PK11SymKey * pms;
- PK11SymKey * Ks = NULL;
- sslSessionID * sid = ss->sec->ci.sid;
- ssl3CipherSpec * pwSpec = ss->ssl3->pwSpec;
- void * pwArg = ss->pkcs11PinArg;
- SECStatus rv;
- SECItem raItem;
- SECItem rbItem;
- SECItem param;
- SECItem item;
- SECItem enc_pms;
- SSL3FortezzaKeys fortezza_CKE;
- PORT_Assert( ssl_HaveRecvBufLock(ss) );
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss) );
- fortezza_CKE.y_c.data = NULL;
- rv = ssl3_ConsumeHandshakeVariable(ss, &fortezza_CKE.y_c, 1, &b, &length);
- if (rv != SECSuccess) {
- PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_KEY_EXCH);
- goto fortezza_loser;
- }
- rv = ssl3_ConsumeHandshake(ss, &fortezza_CKE.r_c,
- sizeof fortezza_CKE - sizeof fortezza_CKE.y_c,
- &b, &length);
- if (rv != SECSuccess) {
- PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_KEY_EXCH);
- goto fortezza_loser;
- }
- /* Build a Token Encryption key (tek). TEK's can never be unloaded
- * from the card, but given these parameters, and *OUR* fortezza
- * card, we can always regenerate the same one on the fly.
- */
- if (ss->sec->peerCert != NULL) {
- /* client-auth case */
- pubKey = CERT_ExtractPublicKey(ss->sec->peerCert);
- if (pubKey == NULL) {
- SEND_ALERT
- PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
- rv = SECFailure;
- goto fortezza_loser;
- }
- if (pubKey->keyType != fortezzaKey) {
- /* handle V3 client-auth case */
- SECItem sigItem;
- SECItem hashItem;
- unsigned char hash[SHA1_LENGTH];
- rv = ssl3_ComputeFortezzaPublicKeyHash(fortezza_CKE.y_c, hash);
- if (rv != SECSuccess) {
- SEND_ALERT
- ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
- goto fortezza_loser;
- }
- sigItem.data = fortezza_CKE.y_signature;
- sigItem.len = sizeof fortezza_CKE.y_signature;
- hashItem.data = hash;
- hashItem.len = sizeof hash;
- rv = PK11_Verify(pubKey, &sigItem, &hashItem, pwArg);
- if (rv != SECSuccess) {
- SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
- ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
- goto fortezza_loser;
- }
- SECKEY_DestroyPublicKey(pubKey); pubKey = NULL;
- }
- }
- rv = SECFailure;
- /* Make the public key if necessary */
- if (fortezza_CKE.y_c.len != 0) {
- if (pubKey != NULL) {
- /* The client is not allowed to send the public key
- * if it can be extracted from the certificate. */
- SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
- PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
- goto fortezza_loser;
- }
- pubKey = PK11_MakeKEAPubKey(fortezza_CKE.y_c.data,
- fortezza_CKE.y_c.len);
- }
- if (pubKey == NULL) {
- /* no public Key in either the cert or the protocol message*/
- SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
- PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
- goto fortezza_loser;
- }
- /* Now we derive the TEK. r_c is the client's "random" public key. */
- raItem.data = fortezza_CKE.r_c;
- raItem.len = sizeof(fortezza_CKE.r_c);
- /* R_s == server's "random" public key, sent in the Server Key Exchange */
- rbItem.data = ss->ssl3->fortezza.R_s;
- rbItem.len = sizeof ss->ssl3->fortezza.R_s;
- tek = PK11_PubDerive(serverKey, pubKey, PR_FALSE, /* don't gen r_c */
- &raItem, &rbItem, CKM_KEA_KEY_DERIVE,
- CKM_SKIPJACK_WRAP, CKA_WRAP, 0, pwArg);
- SECKEY_DestroyPublicKey(pubKey); pubKey = NULL;
- if (tek == NULL) {
- SEND_ALERT
- ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
- goto fortezza_loser;
- }
- ss->ssl3->fortezza.tek = PK11_ReferenceSymKey(tek);
- if (pwSpec->cipher_def->calg == calg_fortezza) {
- item.data = fortezza_CKE.wrapped_client_write_key;
- item.len = sizeof fortezza_CKE.wrapped_client_write_key;
- pwSpec->client.write_key =
- PK11_UnwrapSymKey(tek, CKM_SKIPJACK_WRAP, NULL, &item,
- CKM_SKIPJACK_CBC64, CKA_DECRYPT, 0);
- if (pwSpec->client.write_key == NULL) {
- SEND_ALERT
- ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_UNWRAP_FAILURE);
- goto fortezza_loser;
- }
- item.data = fortezza_CKE.wrapped_server_write_key;
- item.len = sizeof fortezza_CKE.wrapped_server_write_key;
- pwSpec->server.write_key =
- PK11_UnwrapSymKey(tek, CKM_SKIPJACK_WRAP, NULL, &item,
- CKM_SKIPJACK_CBC64, CKA_ENCRYPT, 0);
- if (pwSpec->server.write_key == NULL) {
- PK11_FreeSymKey(pwSpec->client.write_key);
- pwSpec->client.write_key = NULL;
- SEND_ALERT
- ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_UNWRAP_FAILURE);
- goto fortezza_loser;
- }
- /* Set a flag that says "generate 8 byte random prefix plaintext." */
- PK11_SetFortezzaHack(pwSpec->server.write_key); /* can't fail */
- PORT_Memcpy(pwSpec->client.write_iv, fortezza_CKE.client_write_iv,
- sizeof fortezza_CKE.client_write_iv);
- PORT_Memcpy(pwSpec->server.write_iv, fortezza_CKE.server_write_iv,
- sizeof fortezza_CKE.server_write_iv);
- }
- /* decrypt the pms with the TEK */
- enc_pms.data = fortezza_CKE.encrypted_preMasterSecret;
- enc_pms.len = sizeof fortezza_CKE.encrypted_preMasterSecret;
- param.data = fortezza_CKE.master_secret_iv;
- param.len = sizeof fortezza_CKE.master_secret_iv;
- pms = PK11_UnwrapSymKey(tek, CKM_SKIPJACK_CBC64, ¶m, &enc_pms,
- CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0);
- if (pms == NULL) {
- SEND_ALERT
- ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_UNWRAP_FAILURE);
- goto fortezza_loser;
- }
- rv = ssl3_InitPendingCipherSpec(ss, pms);
- PK11_FreeSymKey(pms);
- if (rv != SECSuccess) {
- SEND_ALERT
- goto fortezza_loser; /* err code is set. */
- }
- if (pwSpec->cipher_def->calg == calg_fortezza) {
- PK11SlotInfo * slot;
- sid->u.ssl3.clientWriteKey =
- PK11_ReferenceSymKey(pwSpec->client.write_key);
- sid->u.ssl3.serverWriteKey =
- PK11_ReferenceSymKey(pwSpec->server.write_key);
- PORT_Memcpy(sid->u.ssl3.keys.client_write_iv, pwSpec->client.write_iv,
- sizeof sid->u.ssl3.keys.client_write_iv);
- PORT_Memcpy(sid->u.ssl3.keys.server_write_iv, pwSpec->server.write_iv,
- sizeof sid->u.ssl3.keys.server_write_iv);
- /* Now, wrap the client and server write keys in Ks for storage
- * in the on-disk sid.
- */
- slot = PK11_GetSlotFromKey(tek); /* get ref to the slot */
- if (slot == NULL) {
- ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
- goto fortezza_loser;
- }
- /* Look up the Token Fixed Key */
- Ks = PK11_FindFixedKey(slot, CKM_SKIPJACK_WRAP, NULL, ss->pkcs11PinArg);
- PK11_FreeSlot(slot);
- if (Ks == NULL) {
- ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
- goto fortezza_loser;
- }
- /* rewrap server write key with the local Ks */
- item.data = sid->u.ssl3.keys.wrapped_server_write_key;
- item.len = sizeof sid->u.ssl3.keys.wrapped_server_write_key;
- rv = PK11_WrapSymKey(CKM_SKIPJACK_WRAP, NULL, Ks,
- pwSpec->server.write_key, &item);
- if (rv != SECSuccess) {
- ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
- goto fortezza_loser;
- }
- /* rewrap client write key with the local Ks */
- item.data = sid->u.ssl3.keys.wrapped_client_write_key;
- item.len = sizeof sid->u.ssl3.keys.wrapped_client_write_key;
- rv = PK11_WrapSymKey(CKM_SKIPJACK_WRAP, NULL, Ks,
- pwSpec->client.write_key, &item);
- if (rv != SECSuccess) {
- ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
- goto fortezza_loser;
- }
- /* wrap the master secret later, when we handle the client's
- * finished message.
- */
- }
- sid->u.ssl3.hasFortezza = PR_TRUE;
- sid->u.ssl3.tek = tek; tek = NULL;
- rv = SECSuccess;
- fortezza_loser:
- if (Ks) PK11_FreeSymKey(Ks);
- if (tek) PK11_FreeSymKey(tek);
- if (pubKey) SECKEY_DestroyPublicKey(pubKey);
- if (fortezza_CKE.y_c.data != NULL)
- SECITEM_FreeItem(&fortezza_CKE.y_c, PR_FALSE);
- return rv;
- }
- /* find a slot that is able to generate a PMS and wrap it with RSA.
- * Then generate and return the PMS.
- * If the serverKeySlot parameter is non-null, this function will use
- * that slot to do the job, otherwise it will find a slot.
- *
- * Called from ssl3_GenerateSessionKeys() (above)
- * sendRSAClientKeyExchange() (above)
- * ssl3_HandleRSAClientKeyExchange() (below)
- * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
- */
- static PK11SymKey *
- ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
- PK11SlotInfo * serverKeySlot)
- {
- PK11SymKey * pms = NULL;
- PK11SlotInfo * slot = serverKeySlot;
- void * pwArg = ss->pkcs11PinArg;
- SECItem param;
- CK_VERSION version;
- CK_MECHANISM_TYPE mechanism_array[3];
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss) );
- if (slot == NULL) {
- /* The specReadLock would suffice here, but we cannot assert on
- ** read locks. Also, all the callers who call with a non-null
- ** slot already hold the SpecWriteLock.
- */
- PORT_Assert( ssl_HaveSpecWriteLock(ss));
- PORT_Assert(ss->ssl3->prSpec == ss->ssl3->pwSpec);
- /* First get an appropriate slot. */
- mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
- mechanism_array[1] = CKM_RSA_PKCS;
- mechanism_array[2] = (CK_MECHANISM_TYPE) spec->cipher_def->calg;
- slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg);
- if (slot == NULL) {
- /* can't find a slot with all three, find a slot with the minimum */
- slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
- if (slot == NULL) {
- PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
- return pms; /* which is NULL */
- }
- }
- }
- /* Generate the pre-master secret ... */
- version.major = MSB(ss->clientHelloVersion);
- version.minor = LSB(ss->clientHelloVersion);
- param.data = (unsigned char *)&version;
- param.len = sizeof version;
- pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, ¶m, 0, pwArg);
- if (!serverKeySlot)
- PK11_FreeSlot(slot);
- if (pms == NULL) {
- ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
- }
- return pms;
- }
- /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
- * return any indication of failure of the Client Key Exchange message,
- * where that failure is caused by the content of the client's message.
- * This function must not return SECFailure for any reason that is directly
- * or indirectly caused by the content of the client's encrypted PMS.
- * We must not send an alert and also not drop the connection.
- * Instead, we generate a random PMS. This will cause a failure
- * in the processing the finished message, which is exactly where
- * the failure must occur.
- *
- * Called from ssl3_HandleClientKeyExchange
- */
- static SECStatus
- ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
- SSL3Opaque *b,
- PRUint32 length,
- SECKEYPrivateKey *serverKey)
- {
- PK11SymKey * pms;
- SECStatus rv;
- SECItem enc_pms;
- PORT_Assert( ssl_HaveRecvBufLock(ss) );
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss) );
- enc_pms.data = b;
- enc_pms.len = length;
- if (ss->ssl3->prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
- PRInt32 kLen;
- kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len);
- if (kLen < 0) {
- PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
- return SECFailure;
- }
- if ((unsigned)kLen < enc_pms.len) {
- enc_pms.len = kLen;
- }
- }
- /*
- * decrypt pms out of the incoming buffer
- * Note: CKM_SSL3_PRE_MASTER_KEY_GEN is NOT the mechanism used to do
- * the unwrap. Rather, it is the mechanism with which the unwrapped
- * pms will be used.
- */
- pms = PK11_PubUnwrapSymKey(serverKey, &enc_pms,
- CKM_SSL3_PRE_MASTER_KEY_GEN, CKA_DERIVE, 0);
- if (pms != NULL) {
- PRINT_BUF(60, (ss, "decrypted premaster secret:",
- PK11_GetKeyData(pms)->data,
- PK11_GetKeyData(pms)->len));
- } else {
- /* unwrap failed. Generate a bogus pre-master secret and carry on. */
- PK11SlotInfo * slot = PK11_GetSlotFromPrivateKey(serverKey);
- ssl_GetSpecWriteLock(ss);
- pms = ssl3_GenerateRSAPMS(ss, ss->ssl3->prSpec, slot);
- ssl_ReleaseSpecWriteLock(ss);
- PK11_FreeSlot(slot);
- }
- if (pms == NULL) {
- /* last gasp. */
- ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
- return SECFailure;
- }
- rv = ssl3_InitPendingCipherSpec(ss, pms);
- PK11_FreeSymKey(pms);
- if (rv != SECSuccess) {
- SEND_ALERT
- return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
- }
- return SECSuccess;
- }
- /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
- * ssl3 ClientKeyExchange message from the remote client
- * Caller must hold Handshake and RecvBuf locks.
- */
- static SECStatus
- ssl3_HandleClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
- {
- SECKEYPrivateKey *serverKey = NULL;
- SECStatus rv;
- const ssl3KEADef * kea_def;
- SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
- SSL_GETPID(), ss->fd));
- PORT_Assert( ssl_HaveRecvBufLock(ss) );
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss) );
- if (ss->ssl3->hs.ws != wait_client_key) {
- SSL3_SendAlert(ss, alert_fatal, unexpected_message);
- PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
- return SECFailure;
- }
- kea_def = ss->ssl3->hs.kea_def;
- serverKey = (ss->ssl3->hs.usedStepDownKey
- #ifdef DEBUG
- && kea_def->is_limited /* XXX OR cert is signing only */
- && kea_def->exchKeyType == kt_rsa
- && ss->stepDownKeyPair != NULL
- #endif
- ) ? ss->stepDownKeyPair->privKey
- : ss->serverKey[kea_def->exchKeyType];
- if (serverKey == NULL) {
- SEND_ALERT
- PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG);
- return SECFailure;
- }
- switch (kea_def->exchKeyType) {
- case kt_rsa:
- rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey);
- if (rv != SECSuccess) {
- SEND_ALERT
- return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
- }
- break;
- case kt_fortezza:
- rv = ssl3_HandleFortezzaClientKeyExchange(ss, b, length, serverKey);
- if (rv != SECSuccess) {
- return SECFailure; /* error code set */
- }
- break;
- default:
- (void) ssl3_HandshakeFailure(ss);
- PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
- return SECFailure;
- }
- ss->ssl3->hs.ws = ss->sec->peerCert ? wait_cert_verify : wait_change_cipher;
- return SECSuccess;
- }
- /* This is TLS's equivalent of sending a no_certificate alert. */
- static SECStatus
- ssl3_SendEmptyCertificate(sslSocket *ss)
- {
- SECStatus rv;
- rv = ssl3_AppendHandshakeHeader(ss, certificate, 3);
- if (rv == SECSuccess) {
- rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
- }
- return rv; /* error, if any, set by functions called above. */
- }
- /*
- * Used by both client and server.
- * Called from HandleServerHelloDone and from SendServerHelloSequence.
- */
- static SECStatus
- ssl3_SendCertificate(sslSocket *ss)
- {
- SECStatus rv;
- CERTCertificateList *certChain;
- int len = 0;
- int i;
- SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
- SSL_GETPID(), ss->fd));
- PORT_Assert( ssl_HaveXmitBufLock(ss));
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss));
- certChain = (ss->sec->isServer)
- ? ss->serverCertChain[ss->ssl3->hs.kea_def->exchKeyType]
- : ss->ssl3->clientCertChain;
- if (certChain) {
- for (i = 0; i < certChain->len; i++) {
- len += certChain->certs[i].len + 3;
- }
- }
- rv = ssl3_AppendHandshakeHeader(ss, certificate, len + 3);
- if (rv != SECSuccess) {
- return rv; /* err set by AppendHandshake. */
- }
- rv = ssl3_AppendHandshakeNumber(ss, len, 3);
- if (rv != SECSuccess) {
- return rv; /* err set by AppendHandshake. */
- }
- for (i = 0; i < certChain->len; i++) {
- rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
- certChain->certs[i].len, 3);
- if (rv != SECSuccess) {
- return rv; /* err set by AppendHandshake. */
- }
- }
- return SECSuccess;
- }
- /* This is used to delete the CA certificates in the peer certificate chain
- * from the cert database after they've been validated.
- */
- static void
- ssl3_CleanupPeerCerts(ssl3State *ssl3)
- {
- PRArenaPool * arena = ssl3->peerCertArena;
- ssl3CertNode *certs = (ssl3CertNode *)ssl3->peerCertChain;
- for (; certs; certs = certs->next) {
- CERT_DestroyCertificate(certs->cert);
- }
- if (arena) PORT_FreeArena(arena, PR_FALSE);
- ssl3->peerCertArena = NULL;
- ssl3->peerCertChain = NULL;
- }
- /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
- * ssl3 Certificate message.
- * Caller must hold Handshake and RecvBuf locks.
- */
- static SECStatus
- ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
- {
- ssl3CertNode * c;
- ssl3CertNode * certs = NULL;
- PRArenaPool * arena = NULL;
- ssl3State * ssl3 = ss->ssl3;
- sslSecurityInfo *sec = ss->sec;
- CERTCertificate *cert;
- PRInt32 remaining;
- PRInt32 size;
- SECStatus rv;
- PRBool isServer = (PRBool)(!!sec->isServer);
- PRBool trusted = PR_FALSE;
- PRBool isTLS;
- SSL3AlertDescription desc = bad_certificate;
- int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
- SECItem certItem;
- SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
- SSL_GETPID(), ss->fd));
- PORT_Assert( ssl_HaveRecvBufLock(ss) );
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss) );
- if ((ssl3->hs.ws != wait_server_cert) &&
- (ssl3->hs.ws != wait_client_cert)) {
- desc = unexpected_message;
- errCode = SSL_ERROR_RX_UNEXPECTED_CERTIFICATE;
- goto alert_loser;
- }
- PORT_Assert(ssl3->peerCertArena == NULL);
- if (sec->peerCert != NULL) {
- if (sec->peerKey) {
- SECKEY_DestroyPublicKey(sec->peerKey);
- sec->peerKey = NULL;
- }
- CERT_DestroyCertificate(sec->peerCert);
- sec->peerCert = NULL;
- }
- remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
- if (remaining < 0)
- goto loser; /* fatal alert already sent by ConsumeHandshake. */
- isTLS = (PRBool)(ssl3->prSpec->version > SSL_LIBRARY_VERSION_3_0);
- if (!remaining && isTLS && isServer) {
- /* This is TLS's version of a no_certificate alert. */
- /* I'm a server. I've requested a client cert. He hasn't got one. */
- rv = ssl3_HandleNoCertificate(ss);
- goto cert_block;
- }
- ssl3->peerCertArena = arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
- if ( arena == NULL ) {
- goto loser; /* don't send alerts on memory errors */
- }
- /* First get the peer cert. */
- remaining -= 3;
- if (remaining < 0)
- goto decode_loser;
- size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
- if (size < 0)
- goto loser; /* fatal alert already sent by ConsumeHandshake. */
- remaining -= size;
- if (remaining < 0)
- goto decode_loser;
- certItem.data = (unsigned char*)PORT_ArenaAlloc(arena, size);
- if (certItem.data == NULL) {
- goto loser; /* don't send alerts on memory errors */
- }
- certItem.len = size;
- rv = ssl3_ConsumeHandshake(ss, certItem.data, certItem.len, &b, &length);
- if (rv != SECSuccess)
- goto loser; /* fatal alert already sent by ConsumeHandshake. */
- sec->peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
- PR_FALSE, PR_TRUE);
- if (sec->peerCert == NULL) {
- /* We should report an alert if the cert was bad, but not if the
- * problem was just some local problem, like memory error.
- */
- goto ambiguous_err;
- }
- /* Now get all of the CA certs. */
- while (remaining != 0) {
- remaining -= 3;
- if (remaining < 0)
- goto decode_loser;
- size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
- if (size < 0)
- goto loser; /* fatal alert already sent by ConsumeHandshake. */
- remaining -= size;
- if (remaining < 0)
- goto decode_loser;
- certItem.data = (unsigned char*)PORT_ArenaAlloc(arena, size);
- if (certItem.data == NULL) {
- goto loser; /* don't send alerts on memory errors */
- }
- certItem.len = size;
- rv = ssl3_ConsumeHandshake(ss, certItem.data, certItem.len,
- &b, &length);
- if (rv != SECSuccess)
- goto loser; /* fatal alert already sent by ConsumeHandshake. */
- c = PORT_ArenaNew(arena, ssl3CertNode);
- if (c == NULL) {
- goto loser; /* don't send alerts on memory errors */
- }
- c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
- PR_FALSE, PR_TRUE);
- if (c->cert == NULL) {
- goto ambiguous_err;
- }
- if (c->cert->trust)
- trusted = PR_TRUE;
- c->next = certs;
- certs = c;
- }
- if (remaining != 0)
- goto decode_loser;
- SECKEY_UpdateCertPQG(sec->peerCert);
- /*
- * We're making a fortezza connection, and the card hasn't unloaded it's
- * certs, try to unload those certs now.
- */
- if (!trusted) {
- CERTCertificate *ccert;
- ccert = PK11_FindBestKEAMatch(sec->peerCert, ss->pkcs11PinArg);
- if (ccert)
- CERT_DestroyCertificate(ccert);
- }
- rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd,
- PR_TRUE, isServer);
- if (rv) {
- errCode = PORT_GetError();
- if (!ss->handleBadCert) {
- goto bad_cert;
- }
- rv = (SECStatus)(*ss->handleBadCert)(ss->badCertArg, ss->fd);
- if ( rv ) {
- if ( rv == SECWouldBlock ) {
- /* someone will handle this connection asynchronously*/
- SSL_DBG(("%d: SSL3[%d]: go to async cert handler",
- SSL_GETPID(), ss->fd));
- ssl3->peerCertChain = certs;
- certs = NULL;
- ssl_SetAlwaysBlock(ss);
- goto cert_block;
- }
- /* cert is bad */
- goto bad_cert;
- }
- /* cert is good */
- }
- /* start SSL Step Up, if appropriate */
- cert = sec->peerCert;
- if (!isServer &&
- ssl3_global_policy_some_restricted &&
- ssl3->policy == SSL_ALLOWED &&
- anyRestrictedEnabled(ss) &&
- SECSuccess == CERT_VerifyCertNow(cert->dbhandle, cert,
- PR_FALSE, /* checkSig */
- certUsageSSLServerWithStepUp,
- /*XXX*/ ss->authCertificateArg) ) {
- ssl3->policy = SSL_RESTRICTED;
- ssl3->hs.rehandshake = PR_TRUE;
- }
- sec->ci.sid->peerCert = CERT_DupCertificate(sec->peerCert);
- /* We don't need the CA certs now that we've authenticated the peer cert. */
- ssl3->peerCertChain = certs; certs = NULL; arena = NULL;
- ssl3_CleanupPeerCerts(ssl3);
- cert_block:
- if (sec->isServer) {
- ssl3->hs.ws = wait_client_key;
- } else {
- ssl3->hs.ws = wait_cert_request; /* disallow server_key_exchange */
- if (ssl3->hs.kea_def->is_limited ||
- /* XXX OR server cert is signing only. */
- ssl3->hs.kea_def->kea == kea_fortezza) {
- ssl3->hs.ws = wait_server_key; /* allow server_key_exchange */
- }
- }
- /* rv must normally be equal to SECSuccess here. If we called
- * handleBadCert, it can also be SECWouldBlock.
- */
- return rv;
- ambiguous_err:
- errCode = PORT_GetError();
- switch (errCode) {
- case PR_OUT_OF_MEMORY_ERROR:
- case SEC_ERROR_BAD_DATABASE:
- case SEC_ERROR_NO_MEMORY:
- if (isTLS) {
- desc = internal_error;
- goto alert_loser;
- }
- goto loser;
- }
- /* fall through to bad_cert. */
- bad_cert: /* caller has set errCode. */
- switch (errCode) {
- case SEC_ERROR_LIBRARY_FAILURE: desc = unsupported_certificate; break;
- case SEC_ERROR_EXPIRED_CERTIFICATE: desc = certificate_expired; break;
- case SEC_ERROR_REVOKED_CERTIFICATE: desc = certificate_revoked; break;
- case SEC_ERROR_INADEQUATE_KEY_USAGE:
- case SEC_ERROR_INADEQUATE_CERT_TYPE:
- desc = certificate_unknown; break;
- case SEC_ERROR_UNTRUSTED_CERT:
- desc = isTLS ? access_denied : certificate_unknown; break;
- case SEC_ERROR_UNKNOWN_ISSUER:
- case SEC_ERROR_UNTRUSTED_ISSUER:
- desc = isTLS ? unknown_ca : certificate_unknown; break;
- case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
- desc = isTLS ? unknown_ca : certificate_expired; break;
- case SEC_ERROR_CERT_NOT_IN_NAME_SPACE:
- case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID:
- case SEC_ERROR_CA_CERT_INVALID:
- case SEC_ERROR_BAD_SIGNATURE:
- default: desc = bad_certificate; break;
- }
- SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",
- SSL_GETPID(), ss->fd, errCode));
- goto alert_loser;
- decode_loser:
- desc = isTLS ? decode_error : bad_certificate;
- alert_loser:
- (void)SSL3_SendAlert(ss, alert_fatal, desc);
- loser:
- ssl3->peerCertChain = certs; certs = NULL; arena = NULL;
- ssl3_CleanupPeerCerts(ssl3);
- if (sec->peerCert != NULL) {
- CERT_DestroyCertificate(sec->peerCert);
- sec->peerCert = NULL;
- }
- (void)ssl_MapLowLevelError(errCode);
- return SECFailure;
- }
- /* restart an SSL connection that we stopped to run certificate dialogs
- ** XXX Need to document here how an application marks a cert to show that
- ** the application has accepted it (overridden CERT_VerifyCert).
- *
- * XXX This code only works on the initial handshake on a connection, XXX
- * It does not work on a subsequent handshake (redo).
- *
- * Return value: XXX
- *
- * Caller holds 1stHandshakeLock.
- */
- int
- ssl3_RestartHandshakeAfterServerCert(sslSocket *ss)
- {
- CERTCertificate * cert;
- ssl3State * ssl3 = ss->ssl3;
- int rv = SECSuccess;
- if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
- SET_ERROR_CODE
- return SECFailure;
- }
- if (!ss->sec || !ss->ssl3) {
- SET_ERROR_CODE
- return SECFailure;
- }
- cert = ss->sec->peerCert;
- /* Permit step up if user decided to accept the cert */
- if (!ss->sec->isServer &&
- ssl3_global_policy_some_restricted &&
- ssl3->policy == SSL_ALLOWED &&
- anyRestrictedEnabled(ss) &&
- (SECSuccess == CERT_VerifyCertNow(cert->dbhandle, cert,
- PR_FALSE, /* checksig */
- certUsageSSLServerWithStepUp,
- /*XXX*/ ss->authCertificateArg) )) {
- ssl3->policy = SSL_RESTRICTED;
- ssl3->hs.rehandshake = PR_TRUE;
- }
- if (ss->handshake != NULL) {
- ss->handshake = ssl_GatherRecord1stHandshake;
- ssl3_CleanupPeerCerts(ssl3);
- ss->sec->ci.sid->peerCert = CERT_DupCertificate(ss->sec->peerCert);
- ssl_GetRecvBufLock(ss);
- if (ssl3->hs.msgState.buf != NULL) {
- rv = ssl3_HandleRecord(ss, NULL, &ss->gather->buf);
- }
- ssl_ReleaseRecvBufLock(ss);
- }
- return rv;
- }
- static SECStatus
- ssl3_ComputeTLSFinished(ssl3CipherSpec *spec,
- PRBool isServer,
- const SSL3Finished * hashes,
- TLSFinished * tlsFinished)
- {
- PK11Context *prf_context;
- const char * label;
- unsigned int len;
- SECStatus rv;
- SECItem param = {siBuffer, NULL, 0};
- label = isServer ? "server finished" : "client finished";
- len = 15;
- prf_context =
- PK11_CreateContextBySymKey(CKM_TLS_PRF_GENERAL, CKA_SIGN,
- spec->master_secret, ¶m);
- if (!prf_context)
- return SECFailure;
- rv = PK11_DigestBegin(prf_context);
- rv |= PK11_DigestOp(prf_context, (const unsigned char *) label, len);
- rv |= PK11_DigestOp(prf_context, hashes->md5, sizeof *hashes);
- rv |= PK11_DigestFinal(prf_context, tlsFinished->verify_data,
- &len, sizeof *tlsFinished);
- PORT_Assert(rv != SECSuccess || len == sizeof *tlsFinished);
- PK11_DestroyContext(prf_context, PR_TRUE);
- return rv;
- }
- /* called from ssl3_HandleServerHelloDone
- * ssl3_HandleClientHello
- * ssl3_HandleFinished
- */
- static SECStatus
- ssl3_SendFinished(sslSocket *ss, PRInt32 flags)
- {
- ssl3CipherSpec *cwSpec;
- PRBool isTLS;
- PRBool isServer = ss->sec->isServer;
- SECStatus rv;
- SSL3Sender sender = isServer ? sender_server : sender_client;
- SSL3Finished hashes;
- TLSFinished tlsFinished;
- SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd));
- PORT_Assert( ssl_HaveXmitBufLock(ss));
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss));
- ssl_GetSpecReadLock(ss);
- cwSpec = ss->ssl3->cwSpec;
- isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0);
- rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender);
- if (isTLS && rv == SECSuccess) {
- rv = ssl3_ComputeTLSFinished(cwSpec, isServer, &hashes, &tlsFinished);
- }
- ssl_ReleaseSpecReadLock(ss);
- if (rv != SECSuccess) {
- goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */
- }
- if (isTLS) {
- rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof tlsFinished);
- if (rv != SECSuccess)
- goto fail; /* err set by AppendHandshake. */
- rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished);
- if (rv != SECSuccess)
- goto fail; /* err set by AppendHandshake. */
- } else {
- rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof hashes);
- if (rv != SECSuccess)
- goto fail; /* err set by AppendHandshake. */
- rv = ssl3_AppendHandshake(ss, &hashes, sizeof hashes);
- if (rv != SECSuccess)
- goto fail; /* err set by AppendHandshake. */
- }
- rv = ssl3_FlushHandshake(ss, flags);
- if (rv != SECSuccess) {
- goto fail; /* error code set by ssl3_FlushHandshake */
- }
- return SECSuccess;
- fail:
- return rv;
- }
- /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
- * ssl3 Finished message from the peer.
- * Caller must hold Handshake and RecvBuf locks.
- */
- static SECStatus
- ssl3_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
- const SSL3Hashes *hashes)
- {
- sslSecurityInfo * sec = ss->sec;
- ssl3State * ssl3 = ss->ssl3;
- sslSessionID * sid = sec->ci.sid;
- PK11SymKey * wrappingKey = NULL;
- PK11SlotInfo * symKeySlot;
- void * pwArg = ss->pkcs11PinArg;
- SECStatus rv;
- PRBool isServer = sec->isServer;
- PRBool isTLS;
- PRBool doStepUp;
- CK_MECHANISM_TYPE mechanism;
- PORT_Assert( ssl_HaveRecvBufLock(ss) );
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss) );
- SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
- SSL_GETPID(), ss->fd));
- if (ssl3->hs.ws != wait_finished) {
- SSL3_SendAlert(ss, alert_fatal, unexpected_message);
- PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
- return SECFailure;
- }
- isTLS = (PRBool)(ssl3->crSpec->version > SSL_LIBRARY_VERSION_3_0);
- if (isTLS) {
- TLSFinished tlsFinished;
- if (length != sizeof tlsFinished) {
- (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
- PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
- return SECFailure;
- }
- rv = ssl3_ComputeTLSFinished(ssl3->crSpec, !isServer,
- hashes, &tlsFinished);
- if (rv != SECSuccess ||
- 0 != PORT_Memcmp(&tlsFinished, b, length)) {
- (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
- PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
- return SECFailure;
- }
- } else {
- if (length != sizeof(SSL3Hashes)) {
- (void)ssl3_IllegalParameter(ss);
- PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
- return SECFailure;
- }
- if (0 != PORT_Memcmp(hashes, b, length)) {
- (void)ssl3_HandshakeFailure(ss);
- PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
- return SECFailure;
- }
- }
- doStepUp = (PRBool)(!isServer && ssl3->hs.rehandshake);
- ssl_GetXmitBufLock(ss); /*************************************/
- if ((isServer && !ssl3->hs.isResuming) ||
- (!isServer && ssl3->hs.isResuming)) {
- rv = ssl3_SendChangeCipherSpecs(ss);
- if (rv != SECSuccess) {
- goto xmit_loser; /* err is set. */
- }
- /* XXX Right here, if we knew, somehow, that this thread was in
- ** SSL_SecureSend (trying to write some data) and we weren't going
- ** to step up, then we could set the ssl_SEND_FLAG_FORCE_INTO_BUFFER
- ** flag, so that the last two handshake messages
- ** (e.g. change cipher spec and finished) would get
- ** sent out in the same send/write call as the application data.
- */
- rv = ssl3_SendFinished(ss, 0);
- if (rv != SECSuccess) {
- goto xmit_loser; /* err is set. */
- }
- }
- /* Optimization: don't cache this connection if we're going to step up. */
- if (doStepUp) {
- ssl_FreeSID(sid);
- ss->sec->ci.sid = sid = NULL;
- ssl3->hs.rehandshake = PR_FALSE;
- rv = ssl3_SendClientHello(ss);
- xmit_loser:
- ssl_ReleaseXmitBufLock(ss);
- return rv; /* err code is set if appropriate. */
- }
- ssl_ReleaseXmitBufLock(ss); /*************************************/
- /* we're connected now. */
- ss->handshake = NULL;
- ss->connected = PR_TRUE;
- ss->gather->writeOffset = 0;
- ss->gather->readOffset = 0;
- if (sid->cached == never_cached) {
- /* fill in the sid */
- sid->u.ssl3.cipherSuite = ssl3->hs.cipher_suite;
- sid->u.ssl3.compression = ssl3->hs.compression;
- sid->u.ssl3.policy = ssl3->policy;
- sid->u.ssl3.exchKeyType = ssl3->hs.kea_def->exchKeyType;
- sid->version = ss->version;
- ssl_GetSpecReadLock(ss); /*************************************/
- symKeySlot = PK11_GetSlotFromKey(ssl3->crSpec->master_secret);
- if (!isServer) {
- int wrapKeyIndex;
- int incarnation;
- /* these next few functions are mere accessors and don't fail. */
- sid->u.ssl3.masterWrapIndex = wrapKeyIndex =
- PK11_GetCurrentWrapIndex(symKeySlot);
- PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */
- sid->u.ssl3.masterWrapSeries = incarnation =
- PK11_GetSlotSeries(symKeySlot);
- sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot);
- sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot);
- sid->u.ssl3.masterValid = PR_TRUE;
- /* Get the default wrapping key, for wrapping the master secret before
- * placing it in the SID cache entry. */
- wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
- CKM_INVALID_MECHANISM, incarnation,
- pwArg);
- if (wrappingKey) {
- mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
- } else {
- int keyLength;
- /* if the wrappingKey doesn't exist, attempt to create it.
- * Note: we intentionally ignore errors here. If we cannot
- * generate a wrapping key, it is not fatal to this SSL connection,
- * but we will not be able to restart this session.
- */
- mechanism = PK11_GetBestWrapMechanism(symKeySlot);
- keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism);
- /* Zero length means fixed key length algorithm, or error.
- * It's ambiguous.
- */
- wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL,
- keyLength, pwArg);
- if (wrappingKey) {
- PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
- }
- }
- } else {
- /* server. */
- mechanism = PK11_GetBestWrapMechanism(symKeySlot);
- if (mechanism != CKM_INVALID_MECHANISM) {
- wrappingKey =
- getWrappingKey(ss, symKeySlot, ssl3->hs.kea_def->exchKeyType,
- mechanism, pwArg);
- if (wrappingKey) {
- mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
- }
- }
- }
- sid->u.ssl3.masterWrapMech = mechanism;
- PK11_FreeSlot(symKeySlot);
- rv = SECFailure;
- if (wrappingKey) {
- SECItem msItem;
- msItem.data = sid->u.ssl3.keys.wrapped_master_secret;
- msItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret;
- rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey,
- ssl3->crSpec->master_secret, &msItem);
- /* rv is examined below. */
- sid->u.ssl3.keys.wrapped_master_secret_len = msItem.len;
- PK11_FreeSymKey(wrappingKey);
- }
- ssl_ReleaseSpecReadLock(ss); /*************************************/
- /* If the wrap failed, we don't cache the sid.
- * The connection continues normally however.
- */
- if (!ss->noCache && rv == SECSuccess) {
- (*sec->cache)(sid);
- }
- }
- ss->ssl3->hs.ws = idle_handshake;
- /* Do the handshake callback for sslv3 here. */
- if (ss->handshakeCallback != NULL) {
- (ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData);
- }
- return SECSuccess;
- }
- /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
- * hanshake message.
- * Caller must hold Handshake and RecvBuf locks.
- */
- static SECStatus
- ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
- {
- SECStatus rv = SECSuccess;
- SSL3HandshakeType type = ss->ssl3->hs.msg_type;
- SSL3Hashes hashes; /* computed hashes are put here. */
- PRUint8 hdr[4];
- PORT_Assert( ssl_HaveRecvBufLock(ss) );
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss) );
- /*
- * We have to compute the hashes before we update them with the
- * current message.
- */
- ssl_GetSpecReadLock(ss); /************************************/
- if((type == finished) || (type == certificate_verify)) {
- SSL3Sender sender = (SSL3Sender)0;
- ssl3CipherSpec *rSpec = ss->ssl3->prSpec;
- if (type == finished) {
- sender = ss->sec->isServer ? sender_client : sender_server;
- rSpec = ss->ssl3->crSpec;
- }
- rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender);
- }
- ssl_ReleaseSpecReadLock(ss); /************************************/
- if (rv != SECSuccess) {
- return rv; /* error code was set by ssl3_ComputeHandshakeHashes*/
- }
- SSL_TRC(30,("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
- ss->fd, ssl3_DecodeHandshakeType(ss->ssl3->hs.msg_type)));
- PRINT_BUF(60, (ss, "MD5 handshake hash:",
- (unsigned char*)ss->ssl3->hs.md5, MD5_LENGTH));
- PRINT_BUF(95, (ss, "SHA handshake hash:",
- (unsigned char*)ss->ssl3->hs.sha, SHA1_LENGTH));
- hdr[0] = (PRUint8)ss->ssl3->hs.msg_type;
- hdr[1] = (PRUint8)(length >> 16);
- hdr[2] = (PRUint8)(length >> 8);
- hdr[3] = (PRUint8)(length );
- /* Start new handshake hashes when we start a new handshake */
- if (ss->ssl3->hs.msg_type == client_hello) {
- SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes",
- SSL_GETPID(), ss->fd ));
- rv = PK11_DigestBegin(ss->ssl3->hs.md5);
- if (rv != SECSuccess) {
- ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
- return rv;
- }
- rv = PK11_DigestBegin(ss->ssl3->hs.sha);
- if (rv != SECSuccess) {
- ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
- return rv;
- }
- }
- /* We should not include hello_request messages in the handshake hashes */
- if (ss->ssl3->hs.msg_type != hello_request) {
- rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) hdr, 4);
- if (rv != SECSuccess) return rv; /* err code already set. */
- rv = ssl3_UpdateHandshakeHashes(ss, b, length);
- if (rv != SECSuccess) return rv; /* err code already set. */
- }
- PORT_SetError(0); /* each message starts with no error. */
- switch (ss->ssl3->hs.msg_type) {
- case hello_request:
- if (length != 0) {
- (void)ssl3_DecodeError(ss);
- PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST);
- return SECFailure;
- }
- if (ss->sec->isServer) {
- (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
- PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
- return SECFailure;
- }
- rv = ssl3_HandleHelloRequest(ss);
- break;
- case client_hello:
- if (!ss->sec->isServer) {
- (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
- PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO);
- return SECFailure;
- }
- rv = ssl3_HandleClientHello(ss, b, length);
- break;
- case server_hello:
- if (ss->sec->isServer) {
- (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
- PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
- return SECFailure;
- }
- rv = ssl3_HandleServerHello(ss, b, length);
- break;
- case certificate:
- rv = ssl3_HandleCertificate(ss, b, length);
- break;
- case server_key_exchange:
- if (ss->sec->isServer) {
- (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
- PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
- return SECFailure;
- }
- rv = ssl3_HandleServerKeyExchange(ss, b, length);
- break;
- case certificate_request:
- if (ss->sec->isServer) {
- (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
- PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
- return SECFailure;
- }
- rv = ssl3_HandleCertificateRequest(ss, b, length);
- break;
- case server_hello_done:
- if (length != 0) {
- (void)ssl3_DecodeError(ss);
- PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
- return SECFailure;
- }
- if (ss->sec->isServer) {
- (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
- PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
- return SECFailure;
- }
- rv = ssl3_HandleServerHelloDone(ss);
- break;
- case certificate_verify:
- if (!ss->sec->isServer) {
- (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
- PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
- return SECFailure;
- }
- rv = ssl3_HandleCertificateVerify(ss, b, length, &hashes);
- break;
- case client_key_exchange:
- if (!ss->sec->isServer) {
- (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
- PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
- return SECFailure;
- }
- rv = ssl3_HandleClientKeyExchange(ss, b, length);
- break;
- case finished:
- rv = ssl3_HandleFinished(ss, b, length, &hashes);
- break;
- default:
- (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
- PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
- rv = SECFailure;
- }
- return rv;
- }
- /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
- * origBuf is the decrypted ssl record content.
- * Caller must hold the handshake and RecvBuf locks.
- */
- static SECStatus
- ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
- {
- /*
- * There may be a partial handshake message already in the handshake
- * state. The incoming buffer may contain another portion, or a
- * complete message or several messages followed by another portion.
- *
- * Each message is made contiguous before being passed to the actual
- * message parser.
- */
- ssl3State *ssl3 = ss->ssl3;
- sslBuffer *buf = &ssl3->hs.msgState; /* do not lose the original buffer pointer */
- SECStatus rv;
- PORT_Assert( ssl_HaveRecvBufLock(ss) );
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss) );
- if (buf->buf == NULL) {
- *buf = *origBuf;
- }
- while (buf->len > 0) {
- while (ssl3->hs.header_bytes < 4) {
- uint8 t;
- t = *(buf->buf++);
- buf->len--;
- if (ssl3->hs.header_bytes++ == 0)
- ssl3->hs.msg_type = (SSL3HandshakeType)t;
- else
- ssl3->hs.msg_len = (ssl3->hs.msg_len << 8) + t;
- #define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
- if (ssl3->hs.header_bytes == 4) {
- if (ssl3->hs.msg_len > MAX_HANDSHAKE_MSG_LEN) {
- (void)ssl3_DecodeError(ss);
- PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
- return SECFailure;
- }
- }
- #undef MAX_HANDSHAKE_MSG_LEN
- if (buf->len == 0 && ssl3->hs.msg_len > 0) {
- buf->buf = NULL;
- return SECSuccess;
- }
- }
- /*
- * Header has been gathered and there is at least one byte of new
- * data available for this message. If it can be done right out
- * of the original buffer, then use it from there.
- */
- if (ssl3->hs.msg_body.len == 0 && buf->len >= ssl3->hs.msg_len) {
- /* handle it from input buffer */
- rv = ssl3_HandleHandshakeMessage(ss, buf->buf, ssl3->hs.msg_len);
- if (rv == SECFailure) {
- /* This test wants to fall through on either
- * SECSuccess or SECWouldBlock.
- * ssl3_HandleHandshakeMessage MUST set the error code.
- */
- return rv;
- }
- buf->buf += ssl3->hs.msg_len;
- buf->len -= ssl3->hs.msg_len;
- ssl3->hs.msg_len = 0;
- ssl3->hs.header_bytes = 0;
- if (rv != SECSuccess) { /* return if SECWouldBlock. */
- return rv;
- }
- } else {
- /* must be copied to msg_body and dealt with from there */
- unsigned int bytes;
- bytes = PR_MIN(buf->len, ssl3->hs.msg_len);
- /* Grow the buffer if needed */
- if (bytes > ssl3->hs.msg_body.space - ssl3->hs.msg_body.len) {
- rv = sslBuffer_Grow(&ssl3->hs.msg_body,
- ssl3->hs.msg_body.len + bytes);
- if (rv != SECSuccess) {
- /* sslBuffer_Grow has set a memory error code. */
- return SECFailure;
- }
- }
- PORT_Memcpy(ssl3->hs.msg_body.buf + ssl3->hs.msg_body.len,
- buf->buf, buf->len);
- buf->buf += bytes;
- buf->len -= bytes;
- /* should not be more than one message in msg_body */
- PORT_Assert(ssl3->hs.msg_body.len <= ssl3->hs.msg_len);
- /* if we have a whole message, do it */
- if (ssl3->hs.msg_body.len == ssl3->hs.msg_len) {
- rv = ssl3_HandleHandshakeMessage(
- ss, ssl3->hs.msg_body.buf, ssl3->hs.msg_len);
- /*
- * XXX This appears to be wrong. This error handling
- * should clean up after a SECWouldBlock return, like the
- * error handling used 40 lines before/above this one,
- */
- if (rv != SECSuccess) {
- /* ssl3_HandleHandshakeMessage MUST set error code. */
- return rv;
- }
- ssl3->hs.msg_body.len = 0;
- ssl3->hs.msg_len = 0;
- ssl3->hs.header_bytes = 0;
- } else {
- PORT_Assert(buf->len == 0);
- break;
- }
- }
- } /* end loop */
- origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
- buf->buf = NULL; /* not a leak. */
- return SECSuccess;
- }
- /* if cText is non-null, then decipher, check MAC, and decompress the
- * SSL record from cText->buf (typically gs->inbuf)
- * into databuf (typically gs->buf), and any previous contents of databuf
- * is lost. Then handle databuf according to its SSL record type,
- * unless it's an application record.
- *
- * If cText is NULL, then the ciphertext has previously been deciphered and
- * checked, and is already sitting in databuf. It is processed as an SSL
- * Handshake message.
- *
- * DOES NOT process the decrypted/decompressed application data.
- * On return, databuf contains the decrypted/decompressed record.
- *
- * Called from ssl3_GatherCompleteHandshake
- * ssl3_RestartHandshakeAfterCertReq
- * ssl3_RestartHandshakeAfterServerCert
- *
- * Caller must hold the RecvBufLock.
- *
- * This function aquires and releases the SSL3Handshake Lock, holding the
- * lock around any calls to functions that handle records other than
- * Application Data records.
- */
- SECStatus
- ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf)
- {
- const ssl3BulkCipherDef *cipher_def;
- ssl3State * ssl3 = ss->ssl3;
- ssl3CipherSpec * crSpec;
- SECStatus rv;
- unsigned int hashBytes;
- unsigned int padding_length;
- PRBool isTLS;
- SSL3ContentType rType;
- SSL3Opaque hash[MAX_MAC_LENGTH];
- PORT_Assert( ssl_HaveRecvBufLock(ss) );
- if (ssl3 == NULL) {
- ssl_GetSSL3HandshakeLock(ss);
- rv = ssl3_InitState(ss);
- ssl_ReleaseSSL3HandshakeLock(ss);
- if (rv != SECSuccess) {
- return rv; /* ssl3_InitState has set the error code. */
- }
- }
- ssl3 = ss->ssl3;
- /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX().
- * This implies that databuf holds a previously deciphered SSL Handshake
- * message.
- */
- if (cText == NULL) {
- SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake",
- SSL_GETPID(), ss->fd));
- rType = content_handshake;
- goto process_it;
- }
- databuf->len = 0; /* filled in by decode call below. */
- if (databuf->space < MAX_FRAGMENT_LENGTH) {
- rv = sslBuffer_Grow(databuf, MAX_FRAGMENT_LENGTH + 2048);
- if (rv != SECSuccess) {
- SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
- SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048));
- /* sslBuffer_Grow has set a memory error code. */
- return SECFailure;
- }
- }
- PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf, cText->buf->len));
- ssl_GetSpecReadLock(ss); /******************************************/
- crSpec = ssl3->crSpec;
- cipher_def = crSpec->cipher_def;
- isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0);
- if (isTLS && cText->buf->len > (MAX_FRAGMENT_LENGTH + 2048)) {
- ssl_ReleaseSpecReadLock(ss);
- SSL3_SendAlert(ss, alert_fatal, record_overflow);
- PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
- return SECFailure;
- }
- /* decrypt from cText buf to databuf. */
- rv = crSpec->decode(
- crSpec->decodeContext, databuf->buf, (int *)&databuf->len,
- databuf->space, cText->buf->buf, cText->buf->len);
- PRINT_BUF(80, (ss, "cleartext:", databuf->buf, databuf->len));
- if (rv != SECSuccess) {
- ssl_ReleaseSpecReadLock(ss);
- ssl_MapLowLevelError(SSL_ERROR_DECRYPTION_FAILURE);
- if (isTLS)
- (void)SSL3_SendAlert(ss, alert_fatal, decryption_failed);
- ssl_MapLowLevelError(SSL_ERROR_DECRYPTION_FAILURE);
- return SECFailure;
- }
- /* If it's a block cipher, check and strip the padding. */
- if (cipher_def->type == type_block) {
- padding_length = *(databuf->buf + databuf->len - 1);
- /* TLS permits padding to exceed the block size, up to 255 bytes. */
- if (padding_length + crSpec->mac_size >= databuf->len)
- goto bad_pad;
- /* if TLS, check value of first padding byte. */
- if (padding_length && isTLS && padding_length !=
- *(databuf->buf + databuf->len - 1 - padding_length))
- goto bad_pad;
- databuf->len -= padding_length + 1;
- if (databuf->len <= 0) {
- bad_pad:
- /* must not hold spec lock when calling SSL3_SendAlert. */
- ssl_ReleaseSpecReadLock(ss);
- /* SSL3 doesn't have an alert for bad padding, so use bad mac. */
- SSL3_SendAlert(ss, alert_fatal,
- isTLS ? decryption_failed : bad_record_mac);
- PORT_SetError(SSL_ERROR_BAD_BLOCK_PADDING);
- return SECFailure;
- }
- }
- /* Check the MAC. */
- if (databuf->len < crSpec->mac_size) {
- /* record is too short to have a valid mac. */
- goto bad_mac;
- }
- databuf->len -= crSpec->mac_size;
- rType = cText->type;
- rv = ssl3_ComputeRecordMAC(
- crSpec, (ss->sec->isServer) ? crSpec->client.write_mac_context
- : crSpec->server.write_mac_context,
- rType, cText->version, crSpec->read_seq_num,
- databuf->buf, databuf->len, hash, &hashBytes);
- if (rv != SECSuccess) {
- ssl_ReleaseSpecReadLock(ss);
- ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
- return rv;
- }
- if (hashBytes != (unsigned)crSpec->mac_size ||
- PORT_Memcmp(databuf->buf + databuf->len, hash, crSpec->mac_size) != 0) {
- bad_mac:
- /* must not hold spec lock when calling SSL3_SendAlert. */
- ssl_ReleaseSpecReadLock(ss);
- SSL3_SendAlert(ss, alert_fatal, bad_record_mac);
- PORT_SetError(SSL_ERROR_BAD_MAC_READ);
- SSL_DBG(("%d: SSL3[%d]: mac check failed", SSL_GETPID(), ss->fd));
- return SECFailure;
- }
- ssl3_BumpSequenceNumber(&crSpec->read_seq_num);
- ssl_ReleaseSpecReadLock(ss); /*****************************************/
- /*
- * The decrypted data is now in databuf.
- *
- * the null decompression routine is right here
- */
- /*
- ** Having completed the decompression, check the length again.
- */
- if (isTLS && databuf->len > (MAX_FRAGMENT_LENGTH + 1024)) {
- SSL3_SendAlert(ss, alert_fatal, record_overflow);
- PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
- return SECFailure;
- }
- /* Application data records are processed by the caller of this
- ** function, not by this function.
- */
- if (rType == content_application_data) {
- return SECSuccess;
- }
- /* It's a record that must be handled by ssl itself, not the application.
- */
- process_it:
- /* XXX Get the xmit lock here. Odds are very high that we'll be xmiting
- * data ang getting the xmit lock here prevents deadlocks.
- */
- ssl_GetSSL3HandshakeLock(ss);
- /* All the functions called in this switch MUST set error code if
- ** they return SECFailure or SECWouldBlock.
- */
- switch (rType) {
- case content_change_cipher_spec:
- rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
- break;
- case content_alert:
- rv = ssl3_HandleAlert(ss, databuf);
- break;
- case content_handshake:
- rv = ssl3_HandleHandshake(ss, databuf);
- break;
- case content_application_data:
- rv = SECSuccess;
- break;
- default:
- SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
- SSL_GETPID(), ss->fd, cText->type));
- /* XXX Send an alert ??? */
- PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
- rv = SECFailure;
- break;
- }
- ssl_ReleaseSSL3HandshakeLock(ss);
- return rv;
- }
- /*
- * Initialization functions
- */
- /* Called from ssl3_InitState, immediately below. */
- /* Caller must hold the SpecWriteLock. */
- static void
- ssl3_InitCipherSpec(sslSocket *ss, ssl3CipherSpec *spec)
- {
- spec->cipher_def = &bulk_cipher_defs[cipher_null];
- PORT_Assert(spec->cipher_def->cipher == cipher_null);
- spec->mac_def = &mac_defs[mac_null];
- PORT_Assert(spec->mac_def->mac == mac_null);
- spec->encode = Null_Cipher;
- spec->decode = Null_Cipher;
- spec->destroy = NULL;
- spec->mac_size = 0;
- spec->master_secret = NULL;
- spec->client.write_key = NULL;
- spec->client.write_mac_key = NULL;
- spec->client.write_mac_context = NULL;
- spec->server.write_key = NULL;
- spec->server.write_mac_key = NULL;
- spec->server.write_mac_context = NULL;
- spec->write_seq_num.high = 0;
- spec->write_seq_num.low = 0;
- spec->read_seq_num.high = 0;
- spec->read_seq_num.low = 0;
- spec->version = ss->enableTLS
- ? SSL_LIBRARY_VERSION_3_1_TLS
- : SSL_LIBRARY_VERSION_3_0;
- }
- /* Called from: ssl3_SendRecord
- ** ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake()
- ** ssl3_SendClientHello()
- ** ssl3_HandleServerHello()
- ** ssl3_HandleClientHello()
- ** ssl3_HandleV2ClientHello()
- ** ssl3_HandleRecord()
- **
- ** This function should perhaps acquire and release the SpecWriteLock.
- **
- **
- */
- static SECStatus
- ssl3_InitState(sslSocket *ss)
- {
- ssl3State * ssl3 = NULL;
- PK11Context *md5 = NULL;
- PK11Context *sha = NULL;
- SECStatus rv;
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss));
- /* reinitialization for renegotiated sessions XXX */
- if (ss->ssl3 != NULL)
- return SECSuccess;
- ssl3 = PORT_ZNew(ssl3State); /* zero on purpose */
- if (ssl3 == NULL)
- return SECFailure; /* PORT_ZAlloc has set memory error code. */
- /* note that entire HandshakeState is zero, including the buffer */
- ssl3->policy = SSL_ALLOWED;
- ssl_GetSpecWriteLock(ss);
- ssl3->crSpec = ssl3->cwSpec = &ssl3->specs[0];
- ssl3->prSpec = ssl3->pwSpec = &ssl3->specs[1];
- ssl3->hs.rehandshake = PR_FALSE;
- ssl3_InitCipherSpec(ss, ssl3->crSpec);
- ssl3_InitCipherSpec(ss, ssl3->prSpec);
- ssl3->fortezza.tek = NULL;
- ssl3->hs.ws = (ss->sec->isServer) ? wait_client_hello : wait_server_hello;
- ssl_ReleaseSpecWriteLock(ss);
- /*
- * note: We should probably lookup an SSL3 slot for these
- * handshake hashes in hopes that we wind up with the same slots
- * that the master secret will wind up in ...
- */
- SSL_TRC(30,("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd));
- ssl3->hs.md5 = md5 = PK11_CreateDigestContext(SEC_OID_MD5);
- if (md5 == NULL) {
- ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
- goto loser;
- }
- rv = PK11_DigestBegin(ssl3->hs.md5);
- if (rv != SECSuccess) {
- ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
- goto loser;
- }
- sha = ssl3->hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1);
- if (sha == NULL) {
- ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
- goto loser;
- }
- rv = PK11_DigestBegin(ssl3->hs.sha);
- if (rv != SECSuccess) {
- ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
- goto loser;
- }
- /* Don't hide this from the rest of the world any more. */
- ss->ssl3 = ssl3;
- return SECSuccess;
- loser:
- if (md5 != NULL) PK11_DestroyContext(md5, PR_TRUE);
- if (sha != NULL) PK11_DestroyContext(sha, PR_TRUE);
- if (ssl3 != NULL) PORT_Free(ssl3);
- return SECFailure;
- }
- /* Returns a reference counted object that contains a key pair.
- * Or NULL on failure. Initial ref count is 1.
- * Uses the keys in the pair as input.
- */
- ssl3KeyPair *
- ssl3_NewKeyPair( SECKEYPrivateKey * privKey, SECKEYPublicKey * pubKey)
- {
- ssl3KeyPair * pair;
- if (!privKey || !pubKey) {
- PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
- return NULL;
- }
- pair = PORT_ZNew(ssl3KeyPair);
- if (!pair)
- return NULL; /* error code is set. */
- pair->refCount = 1;
- pair->privKey = privKey;
- pair->pubKey = pubKey;
- return pair; /* success */
- }
- ssl3KeyPair *
- ssl3_GetKeyPairRef(ssl3KeyPair * keyPair)
- {
- PR_AtomicIncrement(&keyPair->refCount);
- return keyPair;
- }
- void
- ssl3_FreeKeyPair(ssl3KeyPair * keyPair)
- {
- PRInt32 newCount = PR_AtomicDecrement(&keyPair->refCount);
- if (!newCount) {
- SECKEY_DestroyPrivateKey(keyPair->privKey);
- SECKEY_DestroyPublicKey( keyPair->pubKey);
- PORT_Free(keyPair);
- }
- }
- #define EXPORT_RSA_KEY_LENGTH 64 /* bytes */
- /*
- * Creates the public and private RSA keys for SSL Step down.
- * Called from SSL_ConfigSecureServer in sslsecur.c
- */
- SECStatus
- ssl3_CreateRSAStepDownKeys(sslSocket *ss)
- {
- SECStatus rv = SECSuccess;
- SECKEYPrivateKey * privKey; /* RSA step down key */
- SECKEYPublicKey * pubKey; /* RSA step down key */
- if (ss->stepDownKeyPair)
- ssl3_FreeKeyPair(ss->stepDownKeyPair);
- ss->stepDownKeyPair = NULL;
- #ifndef HACKED_EXPORT_SERVER
- /* Sigh, should have a get key strength call for private keys */
- if (PK11_GetPrivateModulusLen(ss->serverKey[kt_rsa]) >
- EXPORT_RSA_KEY_LENGTH) {
- /* need to ask for the key size in bits */
- privKey = SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH * BPB,
- &pubKey, NULL);
- if (!privKey || !pubKey ||
- !(ss->stepDownKeyPair = ssl3_NewKeyPair(privKey, pubKey))) {
- ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
- rv = SECFailure;
- }
- }
- #endif
- return rv;
- }
- /* record the export policy for this cipher suite */
- SECStatus
- ssl3_SetPolicy(ssl3CipherSuite which, int policy)
- {
- ssl3CipherSuiteCfg *suite;
- suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
- if (suite == NULL) {
- return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
- }
- suite->policy = policy;
- if (policy == SSL_RESTRICTED) {
- ssl3_global_policy_some_restricted = PR_TRUE;
- }
- return SECSuccess;
- }
- SECStatus
- ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy)
- {
- ssl3CipherSuiteCfg *suite;
- PRInt32 policy;
- SECStatus rv;
- suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
- if (suite) {
- policy = suite->policy;
- rv = SECSuccess;
- } else {
- policy = SSL_NOT_ALLOWED;
- rv = SECFailure; /* err code was set by Lookup. */
- }
- *oPolicy = policy;
- return rv;
- }
- /* record the user preference for this suite */
- SECStatus
- ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled)
- {
- ssl3CipherSuiteCfg *suite;
- suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
- if (suite == NULL) {
- return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
- }
- suite->enabled = enabled;
- return SECSuccess;
- }
- /* return the user preference for this suite */
- SECStatus
- ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled)
- {
- ssl3CipherSuiteCfg *suite;
- PRBool pref;
- SECStatus rv;
- suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
- if (suite) {
- pref = suite->enabled;
- rv = SECSuccess;
- } else {
- pref = SSL_NOT_ALLOWED;
- rv = SECFailure; /* err code was set by Lookup. */
- }
- *enabled = pref;
- return rv;
- }
- SECStatus
- ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled)
- {
- ssl3CipherSuiteCfg *suite;
- suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
- if (suite == NULL) {
- return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
- }
- suite->enabled = enabled;
- return SECSuccess;
- }
- SECStatus
- ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *enabled)
- {
- ssl3CipherSuiteCfg *suite;
- PRBool pref;
- SECStatus rv;
- suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
- if (suite) {
- pref = suite->enabled;
- rv = SECSuccess;
- } else {
- pref = SSL_NOT_ALLOWED;
- rv = SECFailure; /* err code was set by Lookup. */
- }
- *enabled = pref;
- return rv;
- }
- /* copy global default policy into socket. */
- void
- ssl3_InitSocketPolicy(sslSocket *ss)
- {
- PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof cipherSuites);
- }
- /* ssl3_config_match_init must have already been called by
- * the caller of this function.
- */
- SECStatus
- ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size)
- {
- int i, count = 0;
- PORT_Assert(ss != 0);
- if (!ss) {
- PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
- return SECFailure;
- }
- if (!ss->enableSSL3 && !ss->enableTLS) {
- *size = 0;
- return SECSuccess;
- }
- if (cs == NULL) {
- *size = count_cipher_suites(ss, SSL_ALLOWED, PR_TRUE);
- return SECSuccess;
- }
- /* ssl3_config_match_init was called by the caller of this function. */
- for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
- ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
- if (config_match(suite, SSL_ALLOWED, PR_TRUE)) {
- if (cs != NULL) {
- *cs++ = 0x00;
- *cs++ = (suite->cipher_suite >> 8) & 0xFF;
- *cs++ = suite->cipher_suite & 0xFF;
- }
- count++;
- }
- }
- *size = count;
- return SECSuccess;
- }
- /*
- ** If ssl3 socket is connected and in idle state, then start a new handshake.
- ** If flushCache is true, the SID cache will be flushed first, forcing a
- ** "Full" handshake (not a session restart handshake), to be done.
- **
- ** called from SSL_RedoHandshake(), which already holds the handshake locks.
- */
- SECStatus
- ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache)
- {
- sslSecurityInfo *sec = ss->sec;
- sslSessionID * sid = ss->sec->ci.sid;
- SECStatus rv;
- PORT_Assert( ssl_HaveSSL3HandshakeLock(ss) );
- if (!ss->connected ||
- ((ss->version >= SSL_LIBRARY_VERSION_3_0) &&
- ss->ssl3 && (ss->ssl3->hs.ws != idle_handshake))) {
- PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
- return SECFailure;
- }
- if (sid && flushCache) {
- sec->uncache(sid); /* remove it from whichever cache it's in. */
- ssl_FreeSID(sid); /* dec ref count and free if zero. */
- ss->sec->ci.sid = NULL;
- }
- ssl_GetXmitBufLock(ss); /**************************************/
- /* start off a new handshake. */
- rv = (sec->isServer) ? ssl3_SendHelloRequest(ss)
- : ssl3_SendClientHello(ss);
- ssl_ReleaseXmitBufLock(ss); /**************************************/
- return rv;
- }
- /* Called from ssl_FreeSocket() in sslsock.c */
- void
- ssl3_DestroySSL3Info(ssl3State *ssl3)
- {
- if (ssl3 == NULL)
- return; /* success the easy way. */
- if (ssl3->clientCertificate != NULL)
- CERT_DestroyCertificate(ssl3->clientCertificate);
- if (ssl3->clientPrivateKey != NULL)
- SECKEY_DestroyPrivateKey(ssl3->clientPrivateKey);
- if (ssl3->peerCertArena != NULL)
- ssl3_CleanupPeerCerts(ssl3);
- /* clean up handshake */
- if (ssl3->hs.md5) {
- PK11_DestroyContext(ssl3->hs.md5,PR_TRUE);
- }
- if (ssl3->hs.sha) {
- PK11_DestroyContext(ssl3->hs.sha,PR_TRUE);
- }
- if (ssl3->fortezza.tek != NULL) {
- PK11_FreeSymKey(ssl3->fortezza.tek);
- }
- /* free the SSL3Buffer (msg_body) */
- PORT_Free(ssl3->hs.msg_body.buf);
- /* free up the CipherSpecs */
- ssl3_DestroyCipherSpec(&ssl3->specs[0]);
- ssl3_DestroyCipherSpec(&ssl3->specs[1]);
- PORT_Free(ssl3);
- }
- /* End of ssl3con.c */