tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

sslsecur.c (40004B)


      1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
      2 /*
      3 * Various SSL functions.
      4 *
      5 * This Source Code Form is subject to the terms of the Mozilla Public
      6 * License, v. 2.0. If a copy of the MPL was not distributed with this
      7 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
      8 #include "cert.h"
      9 #include "secitem.h"
     10 #include "keyhi.h"
     11 #include "ssl.h"
     12 #include "sslimpl.h"
     13 #include "sslproto.h"
     14 #include "secoid.h"   /* for SECOID_GetALgorithmTag */
     15 #include "pk11func.h" /* for PK11_GenerateRandom */
     16 #include "nss.h"      /* for NSS_RegisterShutdown */
     17 #include "prinit.h"   /* for PR_CallOnceWithArg */
     18 #include "tls13ech.h"
     19 #include "tls13psk.h"
     20 
     21 /* Step through the handshake functions.
     22 *
     23 * Called from: SSL_ForceHandshake  (below),
     24 *              ssl_SecureRecv      (below) and
     25 *              ssl_SecureSend      (below)
     26 *    from: WaitForResponse     in sslsocks.c
     27 *          ssl_SocksRecv       in sslsocks.c
     28 *              ssl_SocksSend       in sslsocks.c
     29 *
     30 * Caller must hold the (write) handshakeLock.
     31 */
     32 SECStatus
     33 ssl_Do1stHandshake(sslSocket *ss)
     34 {
     35    SECStatus rv = SECSuccess;
     36 
     37    while (ss->handshake && rv == SECSuccess) {
     38        PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
     39        PORT_Assert(ss->opt.noLocks || !ssl_HaveRecvBufLock(ss));
     40        PORT_Assert(ss->opt.noLocks || !ssl_HaveXmitBufLock(ss));
     41        PORT_Assert(ss->opt.noLocks || !ssl_HaveSSL3HandshakeLock(ss));
     42 
     43        rv = (*ss->handshake)(ss);
     44    };
     45 
     46    PORT_Assert(ss->opt.noLocks || !ssl_HaveRecvBufLock(ss));
     47    PORT_Assert(ss->opt.noLocks || !ssl_HaveXmitBufLock(ss));
     48    PORT_Assert(ss->opt.noLocks || !ssl_HaveSSL3HandshakeLock(ss));
     49 
     50    return rv;
     51 }
     52 
     53 SECStatus
     54 ssl_FinishHandshake(sslSocket *ss)
     55 {
     56    PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
     57    PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
     58    PORT_Assert(ss->ssl3.hs.echAccepted ||
     59                (ss->opt.enableTls13BackendEch &&
     60                 ss->xtnData.ech &&
     61                 ss->xtnData.ech->receivedInnerXtn) ==
     62                    ssl3_ExtensionNegotiated(ss, ssl_tls13_encrypted_client_hello_xtn));
     63 
     64    /* If ECH was OFFERED to (echHpkeCtx is set on the client) DISABLED by the
     65     * server through negotiation of a TLS version < 1.3, an 'ech_required'
     66     * alert MUST be sent to inform the server about the intention / possible
     67     * misconfiguration. */
     68    if (!ss->sec.isServer && ss->ssl3.hs.echHpkeCtx && !ss->ssl3.hs.echAccepted) {
     69        SSL3_SendAlert(ss, alert_fatal, ech_required);
     70        /* "If [one, none] of the retry_configs contains a supported version,
     71         * the client can regard ECH as securely [replaced, disabled] by the
     72         * server." */
     73        if (ss->xtnData.ech && ss->xtnData.ech->retryConfigs.len) {
     74            PORT_SetError(SSL_ERROR_ECH_RETRY_WITH_ECH);
     75            ss->xtnData.ech->retryConfigsValid = PR_TRUE;
     76        } else {
     77            PORT_SetError(SSL_ERROR_ECH_RETRY_WITHOUT_ECH);
     78        }
     79        return SECFailure;
     80    }
     81 
     82    SSL_TRC(3, ("%d: SSL[%d]: handshake is completed", SSL_GETPID(), ss->fd));
     83 
     84    ss->firstHsDone = PR_TRUE;
     85    ss->enoughFirstHsDone = PR_TRUE;
     86    ss->gs.writeOffset = 0;
     87    ss->gs.readOffset = 0;
     88 
     89    if (ss->handshakeCallback) {
     90        PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
     91                    ssl_preinfo_all);
     92        (ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData);
     93    }
     94 
     95    ssl_FreeEphemeralKeyPairs(ss);
     96 
     97    return SECSuccess;
     98 }
     99 
    100 /*
    101 * Handshake function that blocks.  Used to force a
    102 * retry on a connection on the next read/write.
    103 */
    104 static SECStatus
    105 ssl3_AlwaysBlock(sslSocket *ss)
    106 {
    107    PORT_SetError(PR_WOULD_BLOCK_ERROR);
    108    return SECFailure;
    109 }
    110 
    111 /*
    112 * set the initial handshake state machine to block
    113 */
    114 void
    115 ssl3_SetAlwaysBlock(sslSocket *ss)
    116 {
    117    if (!ss->firstHsDone) {
    118        ss->handshake = ssl3_AlwaysBlock;
    119    }
    120 }
    121 
    122 static SECStatus
    123 ssl_SetTimeout(PRFileDesc *fd, PRIntervalTime timeout)
    124 {
    125    sslSocket *ss;
    126 
    127    ss = ssl_FindSocket(fd);
    128    if (!ss) {
    129        SSL_DBG(("%d: SSL[%d]: bad socket in SetTimeout", SSL_GETPID(), fd));
    130        return SECFailure;
    131    }
    132    SSL_LOCK_READER(ss);
    133    ss->rTimeout = timeout;
    134    if (ss->opt.fdx) {
    135        SSL_LOCK_WRITER(ss);
    136    }
    137    ss->wTimeout = timeout;
    138    if (ss->opt.fdx) {
    139        SSL_UNLOCK_WRITER(ss);
    140    }
    141    SSL_UNLOCK_READER(ss);
    142    return SECSuccess;
    143 }
    144 
    145 /* Acquires and releases HandshakeLock.
    146 */
    147 SECStatus
    148 SSL_ResetHandshake(PRFileDesc *s, PRBool asServer)
    149 {
    150    sslSocket *ss;
    151    SECStatus status;
    152    PRNetAddr addr;
    153 
    154    ss = ssl_FindSocket(s);
    155    if (!ss) {
    156        SSL_DBG(("%d: SSL[%d]: bad socket in ResetHandshake", SSL_GETPID(), s));
    157        return SECFailure;
    158    }
    159 
    160    /* Don't waste my time */
    161    if (!ss->opt.useSecurity)
    162        return SECSuccess;
    163 
    164    SSL_LOCK_READER(ss);
    165    SSL_LOCK_WRITER(ss);
    166 
    167    /* Reset handshake state */
    168    ssl_Get1stHandshakeLock(ss);
    169 
    170    ss->firstHsDone = PR_FALSE;
    171    ss->enoughFirstHsDone = PR_FALSE;
    172    if (asServer) {
    173        ss->handshake = ssl_BeginServerHandshake;
    174        ss->handshaking = sslHandshakingAsServer;
    175    } else {
    176        ss->handshake = ssl_BeginClientHandshake;
    177        ss->handshaking = sslHandshakingAsClient;
    178    }
    179 
    180    ssl_GetRecvBufLock(ss);
    181    status = ssl3_InitGather(&ss->gs);
    182    ssl_ReleaseRecvBufLock(ss);
    183    if (status != SECSuccess)
    184        goto loser;
    185 
    186    ssl_GetSSL3HandshakeLock(ss);
    187    ss->ssl3.hs.canFalseStart = PR_FALSE;
    188    ss->ssl3.hs.restartTarget = NULL;
    189 
    190    /*
    191    ** Blow away old security state and get a fresh setup.
    192    */
    193    ssl_GetXmitBufLock(ss);
    194    ssl_ResetSecurityInfo(&ss->sec, PR_TRUE);
    195    status = ssl_CreateSecurityInfo(ss);
    196    ssl_ReleaseXmitBufLock(ss);
    197 
    198    ssl_ReleaseSSL3HandshakeLock(ss);
    199    ssl_Release1stHandshakeLock(ss);
    200 
    201    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
    202    ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.echOuterExtensions);
    203    ssl3_ResetExtensionData(&ss->xtnData, ss);
    204    tls13_ResetHandshakePsks(ss, &ss->ssl3.hs.psks);
    205 
    206    if (ss->ssl3.hs.echHpkeCtx) {
    207        PK11_HPKE_DestroyContext(ss->ssl3.hs.echHpkeCtx, PR_TRUE);
    208        ss->ssl3.hs.echHpkeCtx = NULL;
    209        PORT_Assert(ss->ssl3.hs.echPublicName);
    210        PORT_Free((void *)ss->ssl3.hs.echPublicName); /* CONST */
    211        ss->ssl3.hs.echPublicName = NULL;
    212    }
    213    /* Make sure greaseEchBuf is freed in ECH setups without echHpkeCtx. */
    214    if (ss->ssl3.hs.echHpkeCtx ||
    215        ss->opt.enableTls13BackendEch ||
    216        ss->opt.enableTls13GreaseEch) {
    217        sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf);
    218    }
    219 
    220    tls13_ClientGreaseDestroy(ss);
    221 
    222    tls_ClientHelloExtensionPermutationDestroy(ss);
    223 
    224    if (!ss->TCPconnected)
    225        ss->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ss, &addr));
    226 
    227 loser:
    228    SSL_UNLOCK_WRITER(ss);
    229    SSL_UNLOCK_READER(ss);
    230 
    231    return status;
    232 }
    233 
    234 /* For SSLv2, does nothing but return an error.
    235 ** For SSLv3, flushes SID cache entry (if requested),
    236 ** and then starts new client hello or hello request.
    237 ** Acquires and releases HandshakeLock.
    238 */
    239 SECStatus
    240 SSL_ReHandshake(PRFileDesc *fd, PRBool flushCache)
    241 {
    242    sslSocket *ss;
    243    SECStatus rv;
    244 
    245    ss = ssl_FindSocket(fd);
    246    if (!ss) {
    247        SSL_DBG(("%d: SSL[%d]: bad socket in RedoHandshake", SSL_GETPID(), fd));
    248        return SECFailure;
    249    }
    250 
    251    if (!ss->opt.useSecurity)
    252        return SECSuccess;
    253 
    254    ssl_Get1stHandshakeLock(ss);
    255 
    256    ssl_GetSSL3HandshakeLock(ss);
    257    rv = ssl3_RedoHandshake(ss, flushCache); /* force full handshake. */
    258    ssl_ReleaseSSL3HandshakeLock(ss);
    259 
    260    ssl_Release1stHandshakeLock(ss);
    261 
    262    return rv;
    263 }
    264 
    265 /*
    266 ** Same as above, but with an I/O timeout.
    267 */
    268 SSL_IMPORT SECStatus
    269 SSL_ReHandshakeWithTimeout(PRFileDesc *fd,
    270                           PRBool flushCache,
    271                           PRIntervalTime timeout)
    272 {
    273    if (SECSuccess != ssl_SetTimeout(fd, timeout)) {
    274        return SECFailure;
    275    }
    276    return SSL_ReHandshake(fd, flushCache);
    277 }
    278 
    279 SECStatus
    280 SSL_RedoHandshake(PRFileDesc *fd)
    281 {
    282    return SSL_ReHandshake(fd, PR_TRUE);
    283 }
    284 
    285 /* Register an application callback to be called when SSL handshake completes.
    286 ** Acquires and releases HandshakeLock.
    287 */
    288 SECStatus
    289 SSL_HandshakeCallback(PRFileDesc *fd, SSLHandshakeCallback cb,
    290                      void *client_data)
    291 {
    292    sslSocket *ss;
    293 
    294    ss = ssl_FindSocket(fd);
    295    if (!ss) {
    296        SSL_DBG(("%d: SSL[%d]: bad socket in HandshakeCallback",
    297                 SSL_GETPID(), fd));
    298        return SECFailure;
    299    }
    300 
    301    if (!ss->opt.useSecurity) {
    302        PORT_SetError(SEC_ERROR_INVALID_ARGS);
    303        return SECFailure;
    304    }
    305 
    306    ssl_Get1stHandshakeLock(ss);
    307    ssl_GetSSL3HandshakeLock(ss);
    308 
    309    ss->handshakeCallback = cb;
    310    ss->handshakeCallbackData = client_data;
    311 
    312    ssl_ReleaseSSL3HandshakeLock(ss);
    313    ssl_Release1stHandshakeLock(ss);
    314 
    315    return SECSuccess;
    316 }
    317 
    318 /* Register an application callback to be called when false start may happen.
    319 ** Acquires and releases HandshakeLock.
    320 */
    321 SECStatus
    322 SSL_SetCanFalseStartCallback(PRFileDesc *fd, SSLCanFalseStartCallback cb,
    323                             void *arg)
    324 {
    325    sslSocket *ss;
    326 
    327    ss = ssl_FindSocket(fd);
    328    if (!ss) {
    329        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetCanFalseStartCallback",
    330                 SSL_GETPID(), fd));
    331        return SECFailure;
    332    }
    333 
    334    if (!ss->opt.useSecurity) {
    335        PORT_SetError(SEC_ERROR_INVALID_ARGS);
    336        return SECFailure;
    337    }
    338 
    339    ssl_Get1stHandshakeLock(ss);
    340    ssl_GetSSL3HandshakeLock(ss);
    341 
    342    ss->canFalseStartCallback = cb;
    343    ss->canFalseStartCallbackData = arg;
    344 
    345    ssl_ReleaseSSL3HandshakeLock(ss);
    346    ssl_Release1stHandshakeLock(ss);
    347 
    348    return SECSuccess;
    349 }
    350 
    351 SECStatus
    352 SSL_RecommendedCanFalseStart(PRFileDesc *fd, PRBool *canFalseStart)
    353 {
    354    sslSocket *ss;
    355 
    356    *canFalseStart = PR_FALSE;
    357    ss = ssl_FindSocket(fd);
    358    if (!ss) {
    359        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_RecommendedCanFalseStart",
    360                 SSL_GETPID(), fd));
    361        return SECFailure;
    362    }
    363 
    364    /* Require a forward-secret key exchange. */
    365    *canFalseStart = ss->ssl3.hs.kea_def->kea == kea_dhe_dss ||
    366                     ss->ssl3.hs.kea_def->kea == kea_dhe_rsa ||
    367                     ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa ||
    368                     ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa;
    369 
    370    return SECSuccess;
    371 }
    372 
    373 /* Try to make progress on an SSL handshake by attempting to read the
    374 ** next handshake from the peer, and sending any responses.
    375 ** For non-blocking sockets, returns PR_ERROR_WOULD_BLOCK  if it cannot
    376 ** read the next handshake from the underlying socket.
    377 ** Returns when handshake is complete, or application data has
    378 ** arrived that must be taken by application before handshake can continue,
    379 ** or a fatal error occurs.
    380 ** Application should use handshake completion callback to tell which.
    381 */
    382 SECStatus
    383 SSL_ForceHandshake(PRFileDesc *fd)
    384 {
    385    sslSocket *ss;
    386    SECStatus rv = SECFailure;
    387 
    388    ss = ssl_FindSocket(fd);
    389    if (!ss) {
    390        SSL_DBG(("%d: SSL[%d]: bad socket in ForceHandshake",
    391                 SSL_GETPID(), fd));
    392        return rv;
    393    }
    394 
    395    /* Don't waste my time */
    396    if (!ss->opt.useSecurity)
    397        return SECSuccess;
    398 
    399    if (!ssl_SocketIsBlocking(ss)) {
    400        ssl_GetXmitBufLock(ss);
    401        if (ss->pendingBuf.len != 0) {
    402            int sent = ssl_SendSavedWriteData(ss);
    403            if ((sent < 0) && (PORT_GetError() != PR_WOULD_BLOCK_ERROR)) {
    404                ssl_ReleaseXmitBufLock(ss);
    405                return SECFailure;
    406            }
    407        }
    408        ssl_ReleaseXmitBufLock(ss);
    409    }
    410 
    411    ssl_Get1stHandshakeLock(ss);
    412 
    413    if (ss->version >= SSL_LIBRARY_VERSION_3_0) {
    414        int gatherResult;
    415 
    416        ssl_GetRecvBufLock(ss);
    417        gatherResult = ssl3_GatherCompleteHandshake(ss, 0);
    418        ssl_ReleaseRecvBufLock(ss);
    419        if (gatherResult > 0) {
    420            rv = SECSuccess;
    421        } else {
    422            if (gatherResult == 0) {
    423                PORT_SetError(PR_END_OF_FILE_ERROR);
    424            }
    425            /* We can rely on ssl3_GatherCompleteHandshake to set
    426             * PR_WOULD_BLOCK_ERROR as needed here. */
    427            rv = SECFailure;
    428        }
    429    } else {
    430        PORT_Assert(!ss->firstHsDone);
    431        rv = ssl_Do1stHandshake(ss);
    432    }
    433 
    434    ssl_Release1stHandshakeLock(ss);
    435 
    436    return rv;
    437 }
    438 
    439 /*
    440 ** Same as above, but with an I/O timeout.
    441 */
    442 SSL_IMPORT SECStatus
    443 SSL_ForceHandshakeWithTimeout(PRFileDesc *fd,
    444                              PRIntervalTime timeout)
    445 {
    446    if (SECSuccess != ssl_SetTimeout(fd, timeout)) {
    447        return SECFailure;
    448    }
    449    return SSL_ForceHandshake(fd);
    450 }
    451 
    452 /************************************************************************/
    453 
    454 /*
    455 ** Save away write data that is trying to be written before the security
    456 ** handshake has been completed. When the handshake is completed, we will
    457 ** flush this data out.
    458 ** Caller must hold xmitBufLock
    459 */
    460 SECStatus
    461 ssl_SaveWriteData(sslSocket *ss, const void *data, unsigned int len)
    462 {
    463    SECStatus rv;
    464 
    465    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
    466    rv = sslBuffer_Append(&ss->pendingBuf, data, len);
    467    SSL_TRC(5, ("%d: SSL[%d]: saving %u bytes of data (%u total saved so far)",
    468                SSL_GETPID(), ss->fd, len, ss->pendingBuf.len));
    469    return rv;
    470 }
    471 
    472 /*
    473 ** Send saved write data. This will flush out data sent prior to a
    474 ** complete security handshake. Hopefully there won't be too much of it.
    475 ** Returns count of the bytes sent, NOT a SECStatus.
    476 ** Caller must hold xmitBufLock
    477 */
    478 int
    479 ssl_SendSavedWriteData(sslSocket *ss)
    480 {
    481    int rv = 0;
    482 
    483    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
    484    if (ss->pendingBuf.len != 0) {
    485        SSL_TRC(5, ("%d: SSL[%d]: sending %d bytes of saved data",
    486                    SSL_GETPID(), ss->fd, ss->pendingBuf.len));
    487        rv = ssl_DefSend(ss, ss->pendingBuf.buf, ss->pendingBuf.len, 0);
    488        if (rv < 0) {
    489            return rv;
    490        }
    491        if (rv > ss->pendingBuf.len) {
    492            PORT_Assert(0); /* This shouldn't happen */
    493            ss->pendingBuf.len = 0;
    494        } else {
    495            ss->pendingBuf.len -= rv;
    496        }
    497        if (ss->pendingBuf.len > 0 && rv > 0) {
    498            /* UGH !! This shifts the whole buffer down by copying it */
    499            PORT_Memmove(ss->pendingBuf.buf, ss->pendingBuf.buf + rv,
    500                         ss->pendingBuf.len);
    501        }
    502    }
    503    return rv;
    504 }
    505 
    506 /************************************************************************/
    507 
    508 /*
    509 ** Receive some application data on a socket.  Reads SSL records from the input
    510 ** stream, decrypts them and then copies them to the output buffer.
    511 ** Called from ssl_SecureRecv() below.
    512 **
    513 ** Caller does NOT hold 1stHandshakeLock because that handshake is over.
    514 ** Caller doesn't call this until initial handshake is complete.
    515 ** The call to ssl3_GatherAppDataRecord may encounter handshake
    516 ** messages from a subsequent handshake.
    517 **
    518 ** This code is similar to, and easily confused with,
    519 **   ssl_GatherRecord1stHandshake() in sslcon.c
    520 */
    521 static int
    522 DoRecv(sslSocket *ss, unsigned char *out, int len, int flags)
    523 {
    524    int rv;
    525    int amount;
    526    int available;
    527 
    528    /* ssl3_GatherAppDataRecord may call ssl_FinishHandshake, which needs the
    529     * 1stHandshakeLock. */
    530    ssl_Get1stHandshakeLock(ss);
    531    ssl_GetRecvBufLock(ss);
    532 
    533    available = ss->gs.writeOffset - ss->gs.readOffset;
    534    if (available == 0) {
    535        /* Wait for application data to arrive.  */
    536        rv = ssl3_GatherAppDataRecord(ss, 0);
    537        if (rv <= 0) {
    538            if (rv == 0) {
    539                /* EOF */
    540                SSL_TRC(10, ("%d: SSL[%d]: ssl_recv EOF",
    541                             SSL_GETPID(), ss->fd));
    542                goto done;
    543            }
    544            if (PR_GetError() != PR_WOULD_BLOCK_ERROR) {
    545                /* Some random error */
    546                goto done;
    547            }
    548 
    549            /*
    550            ** Gather record is blocked waiting for more record data to
    551            ** arrive. Try to process what we have already received
    552            */
    553        } else {
    554            /* Gather record has finished getting a complete record */
    555        }
    556 
    557        /* See if any clear data is now available */
    558        available = ss->gs.writeOffset - ss->gs.readOffset;
    559        if (available == 0) {
    560            /*
    561            ** No partial data is available. Force error code to
    562            ** EWOULDBLOCK so that caller will try again later. Note
    563            ** that the error code is probably EWOULDBLOCK already,
    564            ** but if it isn't (for example, if we received a zero
    565            ** length record) then this will force it to be correct.
    566            */
    567            PORT_SetError(PR_WOULD_BLOCK_ERROR);
    568            rv = SECFailure;
    569            goto done;
    570        }
    571        SSL_TRC(30, ("%d: SSL[%d]: partial data ready, available=%d",
    572                     SSL_GETPID(), ss->fd, available));
    573    }
    574 
    575    if (IS_DTLS(ss) && (len < available)) {
    576        /* DTLS does not allow you to do partial reads */
    577        SSL_TRC(30, ("%d: SSL[%d]: DTLS short read. len=%d available=%d",
    578                     SSL_GETPID(), ss->fd, len, available));
    579        ss->gs.readOffset += available;
    580        PORT_SetError(SSL_ERROR_RX_SHORT_DTLS_READ);
    581        rv = SECFailure;
    582        goto done;
    583    }
    584 
    585    /* Dole out clear data to reader */
    586    amount = PR_MIN(len, available);
    587    PORT_Memcpy(out, ss->gs.buf.buf + ss->gs.readOffset, amount);
    588    if (!(flags & PR_MSG_PEEK)) {
    589        ss->gs.readOffset += amount;
    590    }
    591    PORT_Assert(ss->gs.readOffset <= ss->gs.writeOffset);
    592    rv = amount;
    593 
    594 #ifdef DEBUG
    595    /* In Debug builds free and zero gather plaintext buffer after its content
    596     * has been used/copied for advanced ASAN coverage/utilization.
    597     * This frees the buffer after reception of application data,
    598     * non-application data is freed at the end of
    599     * ssl3con.c/ssl3_HandleRecord(). */
    600    if (ss->gs.writeOffset == ss->gs.readOffset) {
    601        sslBuffer_Clear(&ss->gs.buf);
    602    }
    603 #endif
    604 
    605    SSL_TRC(30, ("%d: SSL[%d]: amount=%d available=%d",
    606                 SSL_GETPID(), ss->fd, amount, available));
    607    PRINT_BUF(4, (ss, "DoRecv receiving plaintext:", out, amount));
    608 
    609 done:
    610    ssl_ReleaseRecvBufLock(ss);
    611    ssl_Release1stHandshakeLock(ss);
    612    return rv;
    613 }
    614 
    615 /************************************************************************/
    616 
    617 SECStatus
    618 ssl_CreateSecurityInfo(sslSocket *ss)
    619 {
    620    SECStatus status;
    621 
    622    ssl_GetXmitBufLock(ss);
    623    status = sslBuffer_Grow(&ss->sec.writeBuf, 4096);
    624    ssl_ReleaseXmitBufLock(ss);
    625 
    626    return status;
    627 }
    628 
    629 SECStatus
    630 ssl_CopySecurityInfo(sslSocket *ss, sslSocket *os)
    631 {
    632    ss->sec.isServer = os->sec.isServer;
    633 
    634    ss->sec.peerCert = CERT_DupCertificate(os->sec.peerCert);
    635    if (os->sec.peerCert && !ss->sec.peerCert)
    636        goto loser;
    637 
    638    return SECSuccess;
    639 
    640 loser:
    641    return SECFailure;
    642 }
    643 
    644 /* Reset sec back to its initial state.
    645 ** Caller holds any relevant locks.
    646 */
    647 void
    648 ssl_ResetSecurityInfo(sslSecurityInfo *sec, PRBool doMemset)
    649 {
    650    if (sec->localCert) {
    651        CERT_DestroyCertificate(sec->localCert);
    652        sec->localCert = NULL;
    653    }
    654    if (sec->peerCert) {
    655        CERT_DestroyCertificate(sec->peerCert);
    656        sec->peerCert = NULL;
    657    }
    658    if (sec->peerKey) {
    659        SECKEY_DestroyPublicKey(sec->peerKey);
    660        sec->peerKey = NULL;
    661    }
    662 
    663    /* cleanup the ci */
    664    if (sec->ci.sid != NULL) {
    665        ssl_FreeSID(sec->ci.sid);
    666    }
    667    PORT_ZFree(sec->ci.sendBuf.buf, sec->ci.sendBuf.space);
    668    if (doMemset) {
    669        memset(&sec->ci, 0, sizeof sec->ci);
    670    }
    671 }
    672 
    673 /*
    674 ** Called from SSL_ResetHandshake (above), and
    675 **        from ssl_FreeSocket     in sslsock.c
    676 ** Caller should hold relevant locks (e.g. XmitBufLock)
    677 */
    678 void
    679 ssl_DestroySecurityInfo(sslSecurityInfo *sec)
    680 {
    681    ssl_ResetSecurityInfo(sec, PR_FALSE);
    682 
    683    PORT_ZFree(sec->writeBuf.buf, sec->writeBuf.space);
    684    sec->writeBuf.buf = 0;
    685 
    686    memset(sec, 0, sizeof *sec);
    687 }
    688 
    689 /************************************************************************/
    690 
    691 int
    692 ssl_SecureConnect(sslSocket *ss, const PRNetAddr *sa)
    693 {
    694    PRFileDesc *osfd = ss->fd->lower;
    695    int rv;
    696 
    697    if (ss->opt.handshakeAsServer) {
    698        ss->handshake = ssl_BeginServerHandshake;
    699        ss->handshaking = sslHandshakingAsServer;
    700    } else {
    701        ss->handshake = ssl_BeginClientHandshake;
    702        ss->handshaking = sslHandshakingAsClient;
    703    }
    704 
    705    /* connect to server */
    706    rv = osfd->methods->connect(osfd, sa, ss->cTimeout);
    707    if (rv == PR_SUCCESS) {
    708        ss->TCPconnected = 1;
    709    } else {
    710        int err = PR_GetError();
    711        SSL_DBG(("%d: SSL[%d]: connect failed, errno=%d",
    712                 SSL_GETPID(), ss->fd, err));
    713        if (err == PR_IS_CONNECTED_ERROR) {
    714            ss->TCPconnected = 1;
    715        }
    716    }
    717 
    718    SSL_TRC(5, ("%d: SSL[%d]: secure connect completed, rv == %d",
    719                SSL_GETPID(), ss->fd, rv));
    720    return rv;
    721 }
    722 
    723 /*
    724 * Also, in the unlikely event that the TCP pipe is full and the peer stops
    725 * reading, the SSL3_SendAlert call in ssl_SecureClose and ssl_SecureShutdown
    726 * may block indefinitely in blocking mode, and may fail (without retrying)
    727 * in non-blocking mode.
    728 */
    729 
    730 int
    731 ssl_SecureClose(sslSocket *ss)
    732 {
    733    int rv;
    734 
    735    if (!(ss->shutdownHow & ssl_SHUTDOWN_SEND) &&
    736        ss->firstHsDone) {
    737 
    738        /* We don't want the final alert to be Nagle delayed. */
    739        if (!ss->delayDisabled) {
    740            ssl_EnableNagleDelay(ss, PR_FALSE);
    741            ss->delayDisabled = 1;
    742        }
    743 
    744        (void)SSL3_SendAlert(ss, alert_warning, close_notify);
    745    }
    746    rv = ssl_DefClose(ss);
    747    return rv;
    748 }
    749 
    750 /* Caller handles all locking */
    751 int
    752 ssl_SecureShutdown(sslSocket *ss, int nsprHow)
    753 {
    754    PRFileDesc *osfd = ss->fd->lower;
    755    int rv;
    756    PRIntn sslHow = nsprHow + 1;
    757 
    758    if ((unsigned)nsprHow > PR_SHUTDOWN_BOTH) {
    759        PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
    760        return PR_FAILURE;
    761    }
    762 
    763    if ((sslHow & ssl_SHUTDOWN_SEND) != 0 &&
    764        !(ss->shutdownHow & ssl_SHUTDOWN_SEND) &&
    765        ss->firstHsDone) {
    766 
    767        (void)SSL3_SendAlert(ss, alert_warning, close_notify);
    768    }
    769 
    770    rv = osfd->methods->shutdown(osfd, nsprHow);
    771 
    772    ss->shutdownHow |= sslHow;
    773 
    774    return rv;
    775 }
    776 
    777 /************************************************************************/
    778 
    779 static SECStatus
    780 tls13_CheckKeyUpdate(sslSocket *ss, SSLSecretDirection dir)
    781 {
    782    PRBool keyUpdate;
    783    ssl3CipherSpec *spec;
    784    sslSequenceNumber seqNum;
    785    sslSequenceNumber margin;
    786    tls13KeyUpdateRequest keyUpdateRequest;
    787    SECStatus rv = SECSuccess;
    788 
    789    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
    790        return SECSuccess;
    791    }
    792 
    793    /* If both sides update at the same number, then this will cause two updates
    794     * to happen at once. The problem is that the KeyUpdate itself consumes a
    795     * sequence number, and that will trigger the reading side to request an
    796     * update.
    797     *
    798     * If we have the writing side update first, the writer will be the one that
    799     * drives the update.  An update by the writer doesn't need a response, so
    800     * it is more efficient overall.  The margins here are pretty arbitrary, but
    801     * having the write margin larger reduces the number of times that a
    802     * KeyUpdate is sent by a reader. */
    803    ssl_GetSpecReadLock(ss);
    804    if (dir == ssl_secret_read) {
    805        spec = ss->ssl3.crSpec;
    806        margin = spec->cipherDef->max_records / 8;
    807    } else {
    808        spec = ss->ssl3.cwSpec;
    809        margin = spec->cipherDef->max_records / 4;
    810    }
    811    seqNum = spec->nextSeqNum;
    812    keyUpdate = seqNum > spec->cipherDef->max_records - margin;
    813    ssl_ReleaseSpecReadLock(ss);
    814    if (!keyUpdate) {
    815        return SECSuccess;
    816    }
    817 
    818    SSL_TRC(5, ("%d: SSL[%d]: automatic key update at %llx for %s cipher spec",
    819                SSL_GETPID(), ss->fd, seqNum,
    820                (dir == ssl_secret_read) ? "read" : "write"));
    821    keyUpdateRequest = (dir == ssl_secret_read) ? update_requested : update_not_requested;
    822    ssl_GetSSL3HandshakeLock(ss);
    823    if (ss->ssl3.clientCertRequested) {
    824        ss->ssl3.hs.keyUpdateDeferred = PR_TRUE;
    825        ss->ssl3.hs.deferredKeyUpdateRequest = keyUpdateRequest;
    826    } else {
    827        rv = tls13_SendKeyUpdate(ss, keyUpdateRequest,
    828                                 dir == ssl_secret_write /* buffer */);
    829    }
    830    ssl_ReleaseSSL3HandshakeLock(ss);
    831    return rv;
    832 }
    833 
    834 int
    835 ssl_SecureRecv(sslSocket *ss, unsigned char *buf, int len, int flags)
    836 {
    837    int rv = 0;
    838 
    839    if (ss->shutdownHow & ssl_SHUTDOWN_RCV) {
    840        PORT_SetError(PR_SOCKET_SHUTDOWN_ERROR);
    841        return PR_FAILURE;
    842    }
    843    if (flags & ~PR_MSG_PEEK) {
    844        PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
    845        return PR_FAILURE;
    846    }
    847 
    848    if (!ssl_SocketIsBlocking(ss) && !ss->opt.fdx) {
    849        ssl_GetXmitBufLock(ss);
    850        if (ss->pendingBuf.len != 0) {
    851            rv = ssl_SendSavedWriteData(ss);
    852            if ((rv < 0) && (PORT_GetError() != PR_WOULD_BLOCK_ERROR)) {
    853                ssl_ReleaseXmitBufLock(ss);
    854                return SECFailure;
    855            }
    856        }
    857        ssl_ReleaseXmitBufLock(ss);
    858    }
    859 
    860    rv = 0;
    861    if (!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData)) {
    862        PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
    863        return tls13_Read0RttData(ss, buf, len);
    864    }
    865 
    866    /* If any of these is non-zero, the initial handshake is not done. */
    867    if (!ss->firstHsDone) {
    868        ssl_Get1stHandshakeLock(ss);
    869        if (ss->handshake) {
    870            rv = ssl_Do1stHandshake(ss);
    871        }
    872        ssl_Release1stHandshakeLock(ss);
    873    } else {
    874        if (tls13_CheckKeyUpdate(ss, ssl_secret_read) != SECSuccess) {
    875            rv = PR_FAILURE;
    876        }
    877    }
    878    if (rv < 0) {
    879        if (PORT_GetError() == PR_WOULD_BLOCK_ERROR &&
    880            !PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData)) {
    881            PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
    882            return tls13_Read0RttData(ss, buf, len);
    883        }
    884        return rv;
    885    }
    886 
    887    if (len == 0)
    888        return 0;
    889 
    890    rv = DoRecv(ss, (unsigned char *)buf, len, flags);
    891    SSL_TRC(2, ("%d: SSL[%d]: recving %d bytes securely (errno=%d)",
    892                SSL_GETPID(), ss->fd, rv, PORT_GetError()));
    893    return rv;
    894 }
    895 
    896 int
    897 ssl_SecureRead(sslSocket *ss, unsigned char *buf, int len)
    898 {
    899    return ssl_SecureRecv(ss, buf, len, 0);
    900 }
    901 
    902 /* Caller holds the SSL Socket's write lock. SSL_LOCK_WRITER(ss) */
    903 int
    904 ssl_SecureSend(sslSocket *ss, const unsigned char *buf, int len, int flags)
    905 {
    906    int rv = 0;
    907    PRBool zeroRtt = PR_FALSE;
    908 
    909    SSL_TRC(2, ("%d: SSL[%d]: SecureSend: sending %d bytes",
    910                SSL_GETPID(), ss->fd, len));
    911 
    912    if (ss->shutdownHow & ssl_SHUTDOWN_SEND) {
    913        PORT_SetError(PR_SOCKET_SHUTDOWN_ERROR);
    914        rv = PR_FAILURE;
    915        goto done;
    916    }
    917    if (flags) {
    918        PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
    919        rv = PR_FAILURE;
    920        goto done;
    921    }
    922 
    923    ssl_GetXmitBufLock(ss);
    924    if (ss->pendingBuf.len != 0) {
    925        PORT_Assert(ss->pendingBuf.len > 0);
    926        rv = ssl_SendSavedWriteData(ss);
    927        if (rv >= 0 && ss->pendingBuf.len != 0) {
    928            PORT_Assert(ss->pendingBuf.len > 0);
    929            PORT_SetError(PR_WOULD_BLOCK_ERROR);
    930            rv = SECFailure;
    931        }
    932    }
    933    ssl_ReleaseXmitBufLock(ss);
    934    if (rv < 0) {
    935        goto done;
    936    }
    937 
    938    if (len > 0)
    939        ss->writerThread = PR_GetCurrentThread();
    940 
    941    /* Check to see if we can write even though we're not finished.
    942     *
    943     * Case 1: False start
    944     * Case 2: TLS 1.3 0-RTT
    945     */
    946    if (!ss->firstHsDone) {
    947        PRBool allowEarlySend = PR_FALSE;
    948        PRBool firstClientWrite = PR_FALSE;
    949 
    950        ssl_Get1stHandshakeLock(ss);
    951        /* The client can sometimes send before the handshake is fully
    952         * complete. In TLS 1.2: false start; in TLS 1.3: 0-RTT. */
    953        if (!ss->sec.isServer &&
    954            (ss->opt.enableFalseStart || ss->opt.enable0RttData)) {
    955            ssl_GetSSL3HandshakeLock(ss);
    956            zeroRtt = ss->ssl3.hs.zeroRttState == ssl_0rtt_sent ||
    957                      ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted;
    958            allowEarlySend = ss->ssl3.hs.canFalseStart || zeroRtt;
    959            firstClientWrite = ss->ssl3.hs.ws == idle_handshake;
    960            ssl_ReleaseSSL3HandshakeLock(ss);
    961        }
    962        /* Allow the server to send 0.5 RTT data in TLS 1.3. Requesting a
    963         * certificate implies that the server might condition its sending on
    964         * client authentication, so force servers that do that to wait.
    965         *
    966         * What might not be obvious here is that this allows 0.5 RTT when doing
    967         * PSK-based resumption.  As a result, 0.5 RTT is always enabled when
    968         * early data is accepted.
    969         *
    970         * This check might be more conservative than absolutely necessary.
    971         * It's possible that allowing 0.5 RTT data when the server requests,
    972         * but does not require client authentication is safe because we can
    973         * expect the server to check for a client certificate properly. */
    974        if (ss->sec.isServer &&
    975            ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
    976            !tls13_ShouldRequestClientAuth(ss)) {
    977            ssl_GetSSL3HandshakeLock(ss);
    978            allowEarlySend = TLS13_IN_HS_STATE(ss, wait_finished);
    979            ssl_ReleaseSSL3HandshakeLock(ss);
    980        }
    981        if (!allowEarlySend && ss->handshake) {
    982            rv = ssl_Do1stHandshake(ss);
    983        }
    984        if (firstClientWrite) {
    985            /* Wait until after sending ClientHello and double-check 0-RTT. */
    986            ssl_GetSSL3HandshakeLock(ss);
    987            zeroRtt = ss->ssl3.hs.zeroRttState == ssl_0rtt_sent ||
    988                      ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted;
    989            ssl_ReleaseSSL3HandshakeLock(ss);
    990        }
    991        ssl_Release1stHandshakeLock(ss);
    992    }
    993 
    994    if (rv < 0) {
    995        ss->writerThread = NULL;
    996        goto done;
    997    }
    998 
    999    if (ss->firstHsDone) {
   1000        if (tls13_CheckKeyUpdate(ss, ssl_secret_write) != SECSuccess) {
   1001            rv = PR_FAILURE;
   1002            goto done;
   1003        }
   1004    }
   1005 
   1006    if (zeroRtt) {
   1007        /* There's a limit to the number of early data octets we can send.
   1008         *
   1009         * Note that taking this lock doesn't prevent the cipher specs from
   1010         * being changed out between here and when records are ultimately
   1011         * encrypted.  The only effect of that is to occasionally do an
   1012         * unnecessary short write when data is identified as 0-RTT here but
   1013         * 1-RTT later.
   1014         */
   1015        ssl_GetSpecReadLock(ss);
   1016        len = tls13_LimitEarlyData(ss, ssl_ct_application_data, len);
   1017        ssl_ReleaseSpecReadLock(ss);
   1018    }
   1019 
   1020    /* Check for zero length writes after we do housekeeping so we make forward
   1021     * progress.
   1022     */
   1023    if (len == 0) {
   1024        rv = 0;
   1025        goto done;
   1026    }
   1027    PORT_Assert(buf != NULL);
   1028    if (!buf) {
   1029        PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
   1030        rv = PR_FAILURE;
   1031        goto done;
   1032    }
   1033 
   1034    ssl_GetXmitBufLock(ss);
   1035    rv = ssl3_SendApplicationData(ss, buf, len, flags);
   1036    ssl_ReleaseXmitBufLock(ss);
   1037    ss->writerThread = NULL;
   1038 done:
   1039    if (rv < 0) {
   1040        SSL_TRC(2, ("%d: SSL[%d]: SecureSend: returning %d count, error %d",
   1041                    SSL_GETPID(), ss->fd, rv, PORT_GetError()));
   1042    } else {
   1043        SSL_TRC(2, ("%d: SSL[%d]: SecureSend: returning %d count",
   1044                    SSL_GETPID(), ss->fd, rv));
   1045    }
   1046    return rv;
   1047 }
   1048 
   1049 int
   1050 ssl_SecureWrite(sslSocket *ss, const unsigned char *buf, int len)
   1051 {
   1052    return ssl_SecureSend(ss, buf, len, 0);
   1053 }
   1054 
   1055 SECStatus
   1056 SSLExp_RecordLayerWriteCallback(PRFileDesc *fd, SSLRecordWriteCallback cb,
   1057                                void *arg)
   1058 {
   1059    sslSocket *ss = ssl_FindSocket(fd);
   1060    if (!ss) {
   1061        SSL_DBG(("%d: SSL[%d]: invalid socket for SSL_RecordLayerWriteCallback",
   1062                 SSL_GETPID(), fd));
   1063        return SECFailure;
   1064    }
   1065    if (IS_DTLS(ss)) {
   1066        SSL_DBG(("%d: SSL[%d]: DTLS socket for SSL_RecordLayerWriteCallback",
   1067                 SSL_GETPID(), fd));
   1068        PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1069        return SECFailure;
   1070    }
   1071 
   1072    /* This needs both HS and Xmit locks because this value is checked under
   1073     * both locks. HS to disable reading from the underlying IO layer; Xmit to
   1074     * prevent writing. */
   1075    ssl_GetSSL3HandshakeLock(ss);
   1076    ssl_GetXmitBufLock(ss);
   1077    ss->recordWriteCallback = cb;
   1078    ss->recordWriteCallbackArg = arg;
   1079    ssl_ReleaseXmitBufLock(ss);
   1080    ssl_ReleaseSSL3HandshakeLock(ss);
   1081    return SECSuccess;
   1082 }
   1083 
   1084 SECStatus
   1085 SSL_AlertReceivedCallback(PRFileDesc *fd, SSLAlertCallback cb, void *arg)
   1086 {
   1087    sslSocket *ss;
   1088 
   1089    ss = ssl_FindSocket(fd);
   1090    if (!ss) {
   1091        SSL_DBG(("%d: SSL[%d]: unable to find socket in SSL_AlertReceivedCallback",
   1092                 SSL_GETPID(), fd));
   1093        return SECFailure;
   1094    }
   1095 
   1096    ss->alertReceivedCallback = cb;
   1097    ss->alertReceivedCallbackArg = arg;
   1098 
   1099    return SECSuccess;
   1100 }
   1101 
   1102 SECStatus
   1103 SSL_AlertSentCallback(PRFileDesc *fd, SSLAlertCallback cb, void *arg)
   1104 {
   1105    sslSocket *ss;
   1106 
   1107    ss = ssl_FindSocket(fd);
   1108    if (!ss) {
   1109        SSL_DBG(("%d: SSL[%d]: unable to find socket in SSL_AlertSentCallback",
   1110                 SSL_GETPID(), fd));
   1111        return SECFailure;
   1112    }
   1113 
   1114    ss->alertSentCallback = cb;
   1115    ss->alertSentCallbackArg = arg;
   1116 
   1117    return SECSuccess;
   1118 }
   1119 
   1120 SECStatus
   1121 SSL_BadCertHook(PRFileDesc *fd, SSLBadCertHandler f, void *arg)
   1122 {
   1123    sslSocket *ss;
   1124 
   1125    ss = ssl_FindSocket(fd);
   1126    if (!ss) {
   1127        SSL_DBG(("%d: SSL[%d]: bad socket in SSLBadCertHook",
   1128                 SSL_GETPID(), fd));
   1129        return SECFailure;
   1130    }
   1131 
   1132    ss->handleBadCert = f;
   1133    ss->badCertArg = arg;
   1134 
   1135    return SECSuccess;
   1136 }
   1137 
   1138 /*
   1139 * Allow the application to pass the url or hostname into the SSL library
   1140 * so that we can do some checking on it. It will be used for the value in
   1141 * SNI extension of client hello message.
   1142 */
   1143 SECStatus
   1144 SSL_SetURL(PRFileDesc *fd, const char *url)
   1145 {
   1146    sslSocket *ss = ssl_FindSocket(fd);
   1147    SECStatus rv = SECSuccess;
   1148 
   1149    if (!ss) {
   1150        SSL_DBG(("%d: SSL[%d]: bad socket in SSLSetURL",
   1151                 SSL_GETPID(), fd));
   1152        return SECFailure;
   1153    }
   1154    ssl_Get1stHandshakeLock(ss);
   1155    ssl_GetSSL3HandshakeLock(ss);
   1156 
   1157    if (ss->url) {
   1158        PORT_Free((void *)ss->url); /* CONST */
   1159    }
   1160 
   1161    ss->url = (const char *)PORT_Strdup(url);
   1162    if (ss->url == NULL) {
   1163        rv = SECFailure;
   1164    }
   1165 
   1166    ssl_ReleaseSSL3HandshakeLock(ss);
   1167    ssl_Release1stHandshakeLock(ss);
   1168 
   1169    return rv;
   1170 }
   1171 
   1172 /*
   1173 * Allow the application to pass the set of trust anchors
   1174 */
   1175 SECStatus
   1176 SSL_SetTrustAnchors(PRFileDesc *fd, CERTCertList *certList)
   1177 {
   1178    sslSocket *ss = ssl_FindSocket(fd);
   1179    CERTDistNames *names = NULL;
   1180 
   1181    if (!certList) {
   1182        PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1183        return SECFailure;
   1184    }
   1185    if (!ss) {
   1186        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetTrustAnchors",
   1187                 SSL_GETPID(), fd));
   1188        return SECFailure;
   1189    }
   1190 
   1191    names = CERT_DistNamesFromCertList(certList);
   1192    if (names == NULL) {
   1193        return SECFailure;
   1194    }
   1195    ssl_Get1stHandshakeLock(ss);
   1196    ssl_GetSSL3HandshakeLock(ss);
   1197    if (ss->ssl3.ca_list) {
   1198        CERT_FreeDistNames(ss->ssl3.ca_list);
   1199    }
   1200    ss->ssl3.ca_list = names;
   1201    ssl_ReleaseSSL3HandshakeLock(ss);
   1202    ssl_Release1stHandshakeLock(ss);
   1203 
   1204    return SECSuccess;
   1205 }
   1206 
   1207 /*
   1208 ** Returns Negative number on error, zero or greater on success.
   1209 ** Returns the amount of data immediately available to be read.
   1210 */
   1211 int
   1212 SSL_DataPending(PRFileDesc *fd)
   1213 {
   1214    sslSocket *ss;
   1215    int rv = 0;
   1216 
   1217    ss = ssl_FindSocket(fd);
   1218 
   1219    if (ss && ss->opt.useSecurity) {
   1220        ssl_GetRecvBufLock(ss);
   1221        rv = ss->gs.writeOffset - ss->gs.readOffset;
   1222        ssl_ReleaseRecvBufLock(ss);
   1223    }
   1224 
   1225    return rv;
   1226 }
   1227 
   1228 SECStatus
   1229 SSL_InvalidateSession(PRFileDesc *fd)
   1230 {
   1231    sslSocket *ss = ssl_FindSocket(fd);
   1232    SECStatus rv = SECFailure;
   1233 
   1234    if (ss) {
   1235        ssl_Get1stHandshakeLock(ss);
   1236        ssl_GetSSL3HandshakeLock(ss);
   1237 
   1238        if (ss->sec.ci.sid) {
   1239            ssl_UncacheSessionID(ss);
   1240            rv = SECSuccess;
   1241        }
   1242 
   1243        ssl_ReleaseSSL3HandshakeLock(ss);
   1244        ssl_Release1stHandshakeLock(ss);
   1245    }
   1246    return rv;
   1247 }
   1248 
   1249 SECItem *
   1250 SSL_GetSessionID(PRFileDesc *fd)
   1251 {
   1252    sslSocket *ss;
   1253    SECItem *item = NULL;
   1254 
   1255    ss = ssl_FindSocket(fd);
   1256    if (ss) {
   1257        ssl_Get1stHandshakeLock(ss);
   1258        ssl_GetSSL3HandshakeLock(ss);
   1259 
   1260        if (ss->opt.useSecurity && ss->firstHsDone && ss->sec.ci.sid) {
   1261            item = (SECItem *)PORT_Alloc(sizeof(SECItem));
   1262            if (item) {
   1263                sslSessionID *sid = ss->sec.ci.sid;
   1264                item->len = sid->u.ssl3.sessionIDLength;
   1265                item->data = (unsigned char *)PORT_Alloc(item->len);
   1266                PORT_Memcpy(item->data, sid->u.ssl3.sessionID, item->len);
   1267            }
   1268        }
   1269 
   1270        ssl_ReleaseSSL3HandshakeLock(ss);
   1271        ssl_Release1stHandshakeLock(ss);
   1272    }
   1273    return item;
   1274 }
   1275 
   1276 SECStatus
   1277 SSL_CertDBHandleSet(PRFileDesc *fd, CERTCertDBHandle *dbHandle)
   1278 {
   1279    sslSocket *ss;
   1280 
   1281    ss = ssl_FindSocket(fd);
   1282    if (!ss)
   1283        return SECFailure;
   1284    if (!dbHandle) {
   1285        PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1286        return SECFailure;
   1287    }
   1288    ss->dbHandle = dbHandle;
   1289    return SECSuccess;
   1290 }
   1291 
   1292 /* DO NOT USE. This function was exported in ssl.def with the wrong signature;
   1293 * this implementation exists to maintain link-time compatibility.
   1294 */
   1295 int
   1296 SSL_RestartHandshakeAfterCertReq(sslSocket *ss,
   1297                                 CERTCertificate *cert,
   1298                                 SECKEYPrivateKey *key,
   1299                                 CERTCertificateList *certChain)
   1300 {
   1301    PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
   1302    return -1;
   1303 }
   1304 
   1305 /* DO NOT USE. This function was exported in ssl.def with the wrong signature;
   1306 * this implementation exists to maintain link-time compatibility.
   1307 */
   1308 int
   1309 SSL_RestartHandshakeAfterServerCert(sslSocket *ss)
   1310 {
   1311    PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
   1312    return -1;
   1313 }
   1314 
   1315 /* See documentation in ssl.h */
   1316 SECStatus
   1317 SSL_AuthCertificateComplete(PRFileDesc *fd, PRErrorCode error)
   1318 {
   1319    SECStatus rv;
   1320    sslSocket *ss = ssl_FindSocket(fd);
   1321 
   1322    if (!ss) {
   1323        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_AuthCertificateComplete",
   1324                 SSL_GETPID(), fd));
   1325        return SECFailure;
   1326    }
   1327 
   1328    ssl_Get1stHandshakeLock(ss);
   1329    rv = ssl3_AuthCertificateComplete(ss, error);
   1330    ssl_Release1stHandshakeLock(ss);
   1331 
   1332    return rv;
   1333 }
   1334 
   1335 SECStatus
   1336 SSL_ClientCertCallbackComplete(PRFileDesc *fd, SECStatus outcome, SECKEYPrivateKey *clientPrivateKey,
   1337                               CERTCertificate *clientCertificate)
   1338 {
   1339    SECStatus rv;
   1340    sslSocket *ss = ssl_FindSocket(fd);
   1341 
   1342    if (!ss) {
   1343        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_ClientCertCallbackComplete",
   1344                 SSL_GETPID(), fd));
   1345        return SECFailure;
   1346    }
   1347 
   1348    /* There exists a codepath which exercises each lock.
   1349     * Socket is blocked whilst waiting on this callback anyway. */
   1350    ssl_Get1stHandshakeLock(ss);
   1351    ssl_GetRecvBufLock(ss);
   1352    ssl_GetSSL3HandshakeLock(ss);
   1353 
   1354    if (!ss->ssl3.hs.clientCertificatePending) {
   1355        /* Application invoked callback at wrong time */
   1356        SSL_DBG(("%d: SSL[%d]: socket not waiting for SSL_ClientCertCallbackComplete",
   1357                 SSL_GETPID(), fd));
   1358        PORT_SetError(PR_INVALID_STATE_ERROR);
   1359        rv = SECFailure;
   1360        goto cleanup;
   1361    }
   1362 
   1363    rv = ssl3_ClientCertCallbackComplete(ss, outcome, clientPrivateKey, clientCertificate);
   1364 
   1365 cleanup:
   1366    ssl_ReleaseRecvBufLock(ss);
   1367    ssl_ReleaseSSL3HandshakeLock(ss);
   1368    ssl_Release1stHandshakeLock(ss);
   1369    return rv;
   1370 }
   1371 
   1372 /* For more info see ssl.h */
   1373 SECStatus
   1374 SSL_SNISocketConfigHook(PRFileDesc *fd, SSLSNISocketConfig func,
   1375                        void *arg)
   1376 {
   1377    sslSocket *ss;
   1378 
   1379    ss = ssl_FindSocket(fd);
   1380    if (!ss) {
   1381        SSL_DBG(("%d: SSL[%d]: bad socket in SNISocketConfigHook",
   1382                 SSL_GETPID(), fd));
   1383        return SECFailure;
   1384    }
   1385 
   1386    ss->sniSocketConfig = func;
   1387    ss->sniSocketConfigArg = arg;
   1388    return SECSuccess;
   1389 }