ytls-server 0.0.9

yolox sans-io TLS server context
Documentation
//! Encrypted Extensions handler for Server Ctx

use crate::{CtxError, ServerHandshakeCtx, TlsServerCtxConfig};

use ytls_traits::CryptoChaCha20Poly1305Processor;
use ytls_traits::CryptoSha256TranscriptProcessor;

use ytls_traits::CryptoConfig;
use ytls_traits::CryptoRng;
use ytls_traits::Tls13KeyScheduleHandshakeSha256;
use ytls_traits::TlsLeftOut;

use ytls_record::WrappedStaticRecordBuilder;
use ytls_traits::EncryptedExtensionsBuilder;
use ytls_traits::WrappedHandshakeBuilder;

impl<Config, Crypto, Rng> EncryptedExtensionsBuilder for ServerHandshakeCtx<Config, Crypto, Rng>
where
    Config: TlsServerCtxConfig,
    Crypto: CryptoConfig,
    Rng: CryptoRng,
{
    // Empty for nowx
}

impl<Config, Crypto, Rng> ServerHandshakeCtx<Config, Crypto, Rng>
where
    Config: TlsServerCtxConfig,
    Crypto: CryptoConfig,
    Rng: CryptoRng,
{
    #[inline]
    pub(crate) fn do_encrypted_extensions<L: TlsLeftOut, T: CryptoSha256TranscriptProcessor>(
        &mut self,
        left: &mut L,
        transcript: &mut T,
    ) -> Result<(), CtxError> {
        let key: [u8; 32] = match self.handshake_server_key {
            None => return Err(CtxError::MissingHandshakeKey),
            Some(k) => k,
        };

        let nonce: [u8; 12] = match self.handshake_server_iv {
            None => return Err(CtxError::MissingHandshakeIv),
            Some(ref mut n) => match n.use_and_incr() {
                Some(cur) => cur,
                None => return Err(CtxError::ExhaustedIv),
            },
        };

        let cipher = Crypto::aead_chaha20poly1305(&key);

        let mut encrypted_extensions =
            WrappedStaticRecordBuilder::<8192>::encrypted_extensions(self)
                .map_err(CtxError::Builder)?;

        transcript.sha256_update(encrypted_extensions.as_hashing_context_ref());

        let tag = if let Ok([additional_data, encrypt_payload]) =
            encrypted_extensions.as_disjoint_mut_for_aead()
        {
            cipher
                .encrypt_in_place(&nonce, &additional_data, encrypt_payload.as_mut())
                .map_err(|_| CtxError::Bug("Encrypt failure."))?
        } else {
            return Err(CtxError::Bug(
                "Disjoint for AEAD failed at certificate verify.",
            ));
        };

        encrypted_extensions.set_auth_tag(&tag);

        left.send_record_out(encrypted_extensions.as_encoded_bytes());
        Ok(())
    }
}