diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 589d696..1a927c9 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -12,18 +12,28 @@ on: # Also on PRs, just be careful not to publish anything pull_request: - jobs: - ci: - runs-on: ubuntu-22.04 + library-ci: + runs-on: ubuntu-latest + strategy: + matrix: + subcmd: [build, clippy, test] + steps: - uses: actions/checkout@v4 - - name: Build - run: cargo check + - name: Run `cargo ${{ matrix.subcmd }}` for library + run: cargo ${{ matrix.subcmd }} + + example-ci: + runs-on: ubuntu-latest + strategy: + matrix: + example: [embassy, blocking, tokio, nrf52] - - name: Test - run: cargo test -- --nocapture + steps: + - uses: actions/checkout@v4 - - name: Build examples - run: for i in embassy blocking tokio nrf52; do pushd examples/$i; cargo build; popd; done; + - name: Run `cargo build` for example ${{ matrix.example }} + working-directory: examples/${{ matrix.example }} + run: cargo build diff --git a/src/alert.rs b/src/alert.rs index 3d477c9..d073b2c 100644 --- a/src/alert.rs +++ b/src/alert.rs @@ -10,6 +10,7 @@ pub enum AlertLevel { } impl AlertLevel { + #[must_use] pub fn of(num: u8) -> Option { match num { 1 => Some(AlertLevel::Warning), @@ -52,6 +53,7 @@ pub enum AlertDescription { } impl AlertDescription { + #[must_use] pub fn of(num: u8) -> Option { match num { 0 => Some(AlertDescription::CloseNotify), @@ -94,6 +96,7 @@ pub struct Alert { } impl Alert { + #[must_use] pub fn new(level: AlertLevel, description: AlertDescription) -> Self { Self { level, description } } diff --git a/src/application_data.rs b/src/application_data.rs index 4ef54b9..24e2551 100644 --- a/src/application_data.rs +++ b/src/application_data.rs @@ -1,4 +1,4 @@ -use crate::buffer::*; +use crate::buffer::CryptoBuffer; use crate::record::RecordHeader; use core::fmt::{Debug, Formatter}; diff --git a/src/asynch.rs b/src/asynch.rs index 87026df..e86b66a 100644 --- a/src/asynch.rs +++ b/src/asynch.rs @@ -1,6 +1,6 @@ use crate::common::decrypted_buffer_info::DecryptedBufferInfo; use crate::common::decrypted_read_handler::DecryptedReadHandler; -use crate::connection::*; +use crate::connection::{decrypt_record, Handshake, State}; use crate::key_schedule::KeySchedule; use crate::key_schedule::{ReadKeySchedule, SharedState, WriteKeySchedule}; use crate::read_buffer::ReadBuffer; diff --git a/src/blocking.rs b/src/blocking.rs index 98c4e4c..40bb8c1 100644 --- a/src/blocking.rs +++ b/src/blocking.rs @@ -1,6 +1,6 @@ use crate::common::decrypted_buffer_info::DecryptedBufferInfo; use crate::common::decrypted_read_handler::DecryptedReadHandler; -use crate::connection::*; +use crate::connection::{decrypt_record, Handshake, State}; use crate::key_schedule::KeySchedule; use crate::key_schedule::{ReadKeySchedule, SharedState, WriteKeySchedule}; use crate::read_buffer::ReadBuffer; diff --git a/src/buffer.rs b/src/buffer.rs index 1d9ec3f..c90a9a8 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -127,7 +127,7 @@ impl<'b> CryptoBuffer<'b> { } pub fn truncate(&mut self, len: usize) { - self.truncate_internal(len) + self.truncate_internal(len); } pub fn len(&self) -> usize { @@ -235,7 +235,7 @@ impl<'b> Buffer for CryptoBuffer<'b> { } fn truncate(&mut self, len: usize) { - self.truncate_internal(len) + self.truncate_internal(len); } } diff --git a/src/change_cipher_spec.rs b/src/change_cipher_spec.rs index 3ebb320..89d39d5 100644 --- a/src/change_cipher_spec.rs +++ b/src/change_cipher_spec.rs @@ -6,6 +6,7 @@ use crate::TlsError; #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct ChangeCipherSpec {} +#[allow(clippy::unnecessary_wraps)] // TODO impl ChangeCipherSpec { pub fn new() -> Self { Self {} @@ -21,8 +22,8 @@ impl ChangeCipherSpec { Ok(Self {}) } - #[allow(dead_code)] - pub(crate) fn encode(&self, buf: &mut CryptoBuffer<'_>) -> Result<(), TlsError> { + #[allow(dead_code, clippy::unused_self)] + pub(crate) fn encode(self, buf: &mut CryptoBuffer<'_>) -> Result<(), TlsError> { buf.push(1).map_err(|_| TlsError::EncodeError)?; Ok(()) } diff --git a/src/common/decrypted_read_handler.rs b/src/common/decrypted_read_handler.rs index a96e9e9..c1303cd 100644 --- a/src/common/decrypted_read_handler.rs +++ b/src/common/decrypted_read_handler.rs @@ -56,7 +56,7 @@ impl DecryptedReadHandler<'_> { // by the user. Ok(()) } - _ => { + ServerRecord::Handshake(_) => { unimplemented!() } } diff --git a/src/config.rs b/src/config.rs index 6261eef..b983a08 100644 --- a/src/config.rs +++ b/src/config.rs @@ -120,6 +120,7 @@ where #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[must_use = "TlsConfig does nothing unless consumed"] pub struct TlsConfig<'a> { pub(crate) server_name: Option<&'a str>, pub(crate) psk: Option<(&'a [u8], Vec<&'a [u8], 4>)>, diff --git a/src/connection.rs b/src/connection.rs index 75ac09a..72c9cd2 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -5,7 +5,7 @@ use crate::record::{ClientRecord, ServerRecord}; use crate::record_reader::RecordReader; use crate::write_buffer::WriteBuffer; use crate::{ - alert::*, + alert::{Alert, AlertDescription, AlertLevel}, handshake::{certificate::CertificateRef, certificate_request::CertificateRequest}, }; use crate::{CertificateVerify, CryptoProvider, TlsError, TlsVerifier}; @@ -551,11 +551,11 @@ where Ok((mut signing_key, signature_scheme)) => { let ctx_str = b"TLS 1.3, client CertificateVerify\x00"; let mut msg: heapless::Vec = heapless::Vec::new(); - msg.resize(64, 0x20).map_err(|_| TlsError::EncodeError)?; + msg.resize(64, 0x20).map_err(|()| TlsError::EncodeError)?; msg.extend_from_slice(ctx_str) - .map_err(|_| TlsError::EncodeError)?; + .map_err(|()| TlsError::EncodeError)?; msg.extend_from_slice(&key_schedule.transcript_hash().clone().finalize()) - .map_err(|_| TlsError::EncodeError)?; + .map_err(|()| TlsError::EncodeError)?; let signature = signing_key.sign(&msg); diff --git a/src/crypto_engine.rs b/src/crypto_engine.rs index 5771705..c3498d4 100644 --- a/src/crypto_engine.rs +++ b/src/crypto_engine.rs @@ -4,6 +4,7 @@ use p256::ecdh::SharedSecret; pub struct CryptoEngine {} +#[allow(clippy::unused_self, clippy::needless_pass_by_value)] // TODO impl CryptoEngine { pub fn new(_group: NamedGroup, _shared: SharedSecret) -> Self { Self {} diff --git a/src/extensions/extension_data/key_share.rs b/src/extensions/extension_data/key_share.rs index b33359b..1a13d69 100644 --- a/src/extensions/extension_data/key_share.rs +++ b/src/extensions/extension_data/key_share.rs @@ -36,7 +36,7 @@ impl<'a, const N: usize> KeyShareClientHello<'a, N> { pub fn encode(&self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { buf.with_u16_length(|buf| { - for client_share in self.client_shares.iter() { + for client_share in &self.client_shares { client_share.encode(buf)?; } Ok(()) diff --git a/src/extensions/extension_data/pre_shared_key.rs b/src/extensions/extension_data/pre_shared_key.rs index 9d16a8d..49e58b6 100644 --- a/src/extensions/extension_data/pre_shared_key.rs +++ b/src/extensions/extension_data/pre_shared_key.rs @@ -19,7 +19,7 @@ impl PreSharedKeyClientHello<'_, N> { pub fn encode(&self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { buf.with_u16_length(|buf| { - for identity in self.identities.iter() { + for identity in &self.identities { buf.with_u16_length(|buf| buf.extend_from_slice(identity)) .map_err(|_| TlsError::EncodeError)?; @@ -56,7 +56,7 @@ impl PreSharedKeyServerHello { }) } - pub fn encode(&self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { + pub fn encode(self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { buf.push_u16(self.selected_identity) .map_err(|_| TlsError::EncodeError) } diff --git a/src/extensions/extension_data/psk_key_exchange_modes.rs b/src/extensions/extension_data/psk_key_exchange_modes.rs index d83224a..419541f 100644 --- a/src/extensions/extension_data/psk_key_exchange_modes.rs +++ b/src/extensions/extension_data/psk_key_exchange_modes.rs @@ -23,8 +23,8 @@ impl PskKeyExchangeMode { } } - fn encode(&self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { - buf.push(*self as u8).map_err(|_| TlsError::EncodeError) + fn encode(self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { + buf.push(self as u8).map_err(|_| TlsError::EncodeError) } } @@ -44,7 +44,7 @@ impl PskKeyExchangeModes { pub fn encode(&self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { buf.with_u8_length(|buf| { - for mode in self.modes.iter() { + for mode in &self.modes { mode.encode(buf)?; } Ok(()) diff --git a/src/extensions/extension_data/server_name.rs b/src/extensions/extension_data/server_name.rs index 9eeea23..b7bc42e 100644 --- a/src/extensions/extension_data/server_name.rs +++ b/src/extensions/extension_data/server_name.rs @@ -24,8 +24,8 @@ impl NameType { } } - pub fn encode(&self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { - buf.push(*self as u8).map_err(|_| TlsError::EncodeError) + pub fn encode(self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { + buf.push(self as u8).map_err(|_| TlsError::EncodeError) } } @@ -97,7 +97,7 @@ impl<'a, const N: usize> ServerNameList<'a, N> { pub fn encode(&self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { buf.with_u16_length(|buf| { - for name in self.names.iter() { + for name in &self.names { name.encode(buf)?; } @@ -118,13 +118,14 @@ pub struct ServerNameResponse; impl ServerNameResponse { pub fn parse(buf: &mut ParseBuffer) -> Result { - if !buf.is_empty() { - Err(ParseError::InvalidData) - } else { + if buf.is_empty() { Ok(Self) + } else { + Err(ParseError::InvalidData) } } + #[allow(clippy::unused_self, clippy::unnecessary_wraps)] pub fn encode(&self, _buf: &mut CryptoBuffer) -> Result<(), TlsError> { Ok(()) } diff --git a/src/extensions/extension_data/signature_algorithms.rs b/src/extensions/extension_data/signature_algorithms.rs index 7cf4a65..bf6cf09 100644 --- a/src/extensions/extension_data/signature_algorithms.rs +++ b/src/extensions/extension_data/signature_algorithms.rs @@ -77,6 +77,7 @@ impl SignatureScheme { } } + #[must_use] pub fn as_u16(self) -> u16 { match self { Self::RsaPkcs1Sha256 => 0x0401, @@ -126,7 +127,7 @@ impl SignatureAlgorithms { pub fn encode(&self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { buf.with_u16_length(|buf| { - for &a in self.supported_signature_algorithms.iter() { + for &a in &self.supported_signature_algorithms { buf.push_u16(a.as_u16()) .map_err(|_| TlsError::EncodeError)?; } diff --git a/src/extensions/extension_data/signature_algorithms_cert.rs b/src/extensions/extension_data/signature_algorithms_cert.rs index d1f5ad7..7a427bf 100644 --- a/src/extensions/extension_data/signature_algorithms_cert.rs +++ b/src/extensions/extension_data/signature_algorithms_cert.rs @@ -24,7 +24,7 @@ impl SignatureAlgorithmsCert { pub fn encode(&self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { buf.with_u16_length(|buf| { - for &a in self.supported_signature_algorithms.iter() { + for &a in &self.supported_signature_algorithms { buf.push_u16(a.as_u16()) .map_err(|_| TlsError::EncodeError)?; } diff --git a/src/extensions/extension_data/supported_groups.rs b/src/extensions/extension_data/supported_groups.rs index 0ef6fb9..a17b1e9 100644 --- a/src/extensions/extension_data/supported_groups.rs +++ b/src/extensions/extension_data/supported_groups.rs @@ -58,7 +58,7 @@ impl NamedGroup { } } - pub fn encode(&self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { + pub fn encode(self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { buf.push_u16(self.as_u16()) .map_err(|_| TlsError::EncodeError) } @@ -81,7 +81,7 @@ impl SupportedGroups { pub fn encode(&self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { buf.with_u16_length(|buf| { - for g in self.supported_groups.iter() { + for g in &self.supported_groups { g.encode(buf)?; } Ok(()) diff --git a/src/extensions/extension_data/supported_versions.rs b/src/extensions/extension_data/supported_versions.rs index fb309de..2f6a53b 100644 --- a/src/extensions/extension_data/supported_versions.rs +++ b/src/extensions/extension_data/supported_versions.rs @@ -10,7 +10,7 @@ use heapless::Vec; pub struct ProtocolVersion(u16); impl ProtocolVersion { - pub fn encode(&self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { + pub fn encode(self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { buf.push_u16(self.0).map_err(|_| TlsError::EncodeError) } @@ -38,7 +38,7 @@ impl SupportedVersionsClientHello { pub fn encode(&self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { buf.with_u8_length(|buf| { - for v in self.versions.iter() { + for v in &self.versions { v.encode(buf)?; } Ok(()) @@ -59,7 +59,7 @@ impl SupportedVersionsServerHello { }) } - pub fn encode(&self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { + pub fn encode(self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { self.selected_version.encode(buf) } } diff --git a/src/extensions/extension_data/unimplemented.rs b/src/extensions/extension_data/unimplemented.rs index 991042b..55a80fc 100644 --- a/src/extensions/extension_data/unimplemented.rs +++ b/src/extensions/extension_data/unimplemented.rs @@ -11,6 +11,7 @@ pub struct Unimplemented<'a> { } impl<'a> Unimplemented<'a> { + #[allow(clippy::unnecessary_wraps)] pub fn parse(buf: &mut ParseBuffer<'a>) -> Result { Ok(Self { data: buf.as_slice(), diff --git a/src/extensions/mod.rs b/src/extensions/mod.rs index 0e932b3..411cba1 100644 --- a/src/extensions/mod.rs +++ b/src/extensions/mod.rs @@ -72,8 +72,7 @@ impl ExtensionType { } } - pub fn encode(&self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { - buf.push_u16(*self as u16) - .map_err(|_| TlsError::EncodeError) + pub fn encode(self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { + buf.push_u16(self as u16).map_err(|_| TlsError::EncodeError) } } diff --git a/src/handshake/binder.rs b/src/handshake/binder.rs index eb4d427..e648e09 100644 --- a/src/handshake/binder.rs +++ b/src/handshake/binder.rs @@ -1,4 +1,4 @@ -use crate::buffer::*; +use crate::buffer::CryptoBuffer; use crate::TlsError; use core::fmt::{Debug, Formatter}; //use digest::generic_array::{ArrayLength, GenericArray}; diff --git a/src/handshake/certificate.rs b/src/handshake/certificate.rs index 83b19ea..ea8b29c 100644 --- a/src/handshake/certificate.rs +++ b/src/handshake/certificate.rs @@ -51,7 +51,7 @@ impl<'a> CertificateRef<'a> { pub(crate) fn encode(&self, buf: &mut CryptoBuffer<'_>) -> Result<(), TlsError> { buf.with_u8_length(|buf| buf.extend_from_slice(self.request_context))?; buf.with_u24_length(|buf| { - for entry in self.entries.iter() { + for entry in &self.entries { entry.encode(buf)?; } Ok(()) @@ -146,11 +146,11 @@ impl<'a, const N: usize> TryFrom> for Certificate { let mut request_context = Vec::new(); request_context .extend_from_slice(cert.request_context) - .map_err(|_| TlsError::OutOfMemory)?; + .map_err(|()| TlsError::OutOfMemory)?; let mut entries_data = Vec::new(); entries_data .extend_from_slice(cert.raw_entries) - .map_err(|_| TlsError::OutOfMemory)?; + .map_err(|()| TlsError::OutOfMemory)?; Ok(Self { request_context, diff --git a/src/handshake/certificate_request.rs b/src/handshake/certificate_request.rs index 6822327..53457ef 100644 --- a/src/handshake/certificate_request.rs +++ b/src/handshake/certificate_request.rs @@ -40,7 +40,7 @@ impl<'a> TryFrom> for CertificateRequest { let mut request_context = Vec::new(); request_context .extend_from_slice(cert.request_context) - .map_err(|_| { + .map_err(|()| { error!("CertificateRequest: InsufficientSpace"); TlsError::InsufficientSpace })?; diff --git a/src/handshake/client_hello.rs b/src/handshake/client_hello.rs index 0c94393..81b4620 100644 --- a/src/handshake/client_hello.rs +++ b/src/handshake/client_hello.rs @@ -21,7 +21,7 @@ use crate::extensions::messages::ClientHelloExtension; use crate::handshake::{Random, LEGACY_VERSION}; use crate::key_schedule::{HashOutputSize, WriteKeySchedule}; use crate::TlsError; -use crate::{buffer::*, CryptoProvider}; +use crate::{buffer::CryptoBuffer, CryptoProvider}; pub struct ClientHello<'config, CipherSuite> where diff --git a/src/handshake/finished.rs b/src/handshake/finished.rs index 0eee90c..e6208a3 100644 --- a/src/handshake/finished.rs +++ b/src/handshake/finished.rs @@ -1,4 +1,4 @@ -use crate::buffer::*; +use crate::buffer::CryptoBuffer; use crate::parse_buffer::ParseBuffer; use crate::TlsError; use core::fmt::{Debug, Formatter}; diff --git a/src/handshake/mod.rs b/src/handshake/mod.rs index e06824e..21fa01c 100644 --- a/src/handshake/mod.rs +++ b/src/handshake/mod.rs @@ -11,7 +11,7 @@ use crate::handshake::server_hello::ServerHello; use crate::key_schedule::HashOutputSize; use crate::parse_buffer::{ParseBuffer, ParseError}; use crate::TlsError; -use crate::{buffer::*, key_schedule::WriteKeySchedule}; +use crate::{buffer::CryptoBuffer, key_schedule::WriteKeySchedule}; use core::fmt::{Debug, Formatter}; use sha2::Digest; @@ -119,15 +119,10 @@ where } } - pub fn finalize_encrypted( - &self, - buf: &mut CryptoBuffer, - transcript: &mut CipherSuite::Hash, - ) -> Result<(), TlsError> { + pub fn finalize_encrypted(buf: &mut CryptoBuffer, transcript: &mut CipherSuite::Hash) { let enc_buf = buf.as_slice(); let end = enc_buf.len(); transcript.update(&enc_buf[0..end]); - Ok(()) } } diff --git a/src/handshake/server_hello.rs b/src/handshake/server_hello.rs index 537a106..71c7175 100644 --- a/src/handshake/server_hello.rs +++ b/src/handshake/server_hello.rs @@ -69,7 +69,7 @@ impl<'a> ServerHello<'a> { Some(secret.diffie_hellman(&server_public_key)) } - pub fn initialize_crypto_engine(&self, secret: EphemeralSecret) -> Option { + pub fn initialize_crypto_engine(&self, secret: &EphemeralSecret) -> Option { let server_key_share = self.key_share()?; let group = server_key_share.group; diff --git a/src/key_schedule.rs b/src/key_schedule.rs index 13da0fa..644327f 100644 --- a/src/key_schedule.rs +++ b/src/key_schedule.rs @@ -52,18 +52,18 @@ where let mut hkdf_label = heapless_typenum::Vec::>::new(); hkdf_label .extend_from_slice(&N::to_u16().to_be_bytes()) - .map_err(|_| TlsError::InternalError)?; + .map_err(|()| TlsError::InternalError)?; let label_len = 6 + label.len() as u8; hkdf_label .extend_from_slice(&label_len.to_be_bytes()) - .map_err(|_| TlsError::InternalError)?; + .map_err(|()| TlsError::InternalError)?; hkdf_label .extend_from_slice(b"tls13 ") - .map_err(|_| TlsError::InternalError)?; + .map_err(|()| TlsError::InternalError)?; hkdf_label .extend_from_slice(label) - .map_err(|_| TlsError::InternalError)?; + .map_err(|()| TlsError::InternalError)?; match context_type { ContextType::None => { @@ -72,10 +72,10 @@ where ContextType::Hash(context) => { hkdf_label .extend_from_slice(&(context.len() as u8).to_be_bytes()) - .map_err(|_| TlsError::InternalError)?; + .map_err(|()| TlsError::InternalError)?; hkdf_label .extend_from_slice(&context) - .map_err(|_| TlsError::InternalError)?; + .map_err(|()| TlsError::InternalError)?; } } @@ -262,8 +262,8 @@ where (self.shared, self.client_state, self.server_state) } - /// Re-creates a KeySchedule from its split parts. Make sure to only pass in - /// parts coming from the same original KeySchedule. + /// Re-creates a `KeySchedule` from its split parts. Make sure to only pass in + /// parts coming from the same original `KeySchedule`. pub fn unsplit( shared: SharedState, write: WriteKeySchedule, @@ -423,7 +423,7 @@ where CipherSuite: TlsCipherSuite, { pub(crate) fn increment_counter(&mut self) { - self.state.increment_counter() + self.state.increment_counter(); } pub(crate) fn get_key(&self) -> Result, TlsError> { @@ -466,7 +466,7 @@ where CipherSuite: TlsCipherSuite, { pub(crate) fn increment_counter(&mut self) { - self.state.increment_counter() + self.state.increment_counter(); } pub(crate) fn transcript_hash(&mut self) -> &mut CipherSuite::Hash { diff --git a/src/lib.rs b/src/lib.rs index ba6d908..ec2c60f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,12 @@ #![cfg_attr(not(any(test, feature = "std")), no_std)] #![doc = include_str!("../README.md")] +#![warn(clippy::pedantic)] +#![allow( + clippy::module_name_repetitions, + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + clippy::missing_errors_doc // TODO +)] /*! # Example @@ -116,12 +123,11 @@ pub enum TlsError { impl embedded_io::Error for TlsError { fn kind(&self) -> embedded_io::ErrorKind { - match self { - Self::Io(k) => *k, - _ => { - error!("TLS error: {:?}", self); - embedded_io::ErrorKind::Other - } + if let Self::Io(k) = self { + *k + } else { + error!("TLS error: {:?}", self); + embedded_io::ErrorKind::Other } } } diff --git a/src/parse_buffer.rs b/src/parse_buffer.rs index bdb581e..368324b 100644 --- a/src/parse_buffer.rs +++ b/src/parse_buffer.rs @@ -133,7 +133,7 @@ impl<'b> ParseBuffer<'b> { Err(ParseError::InsufficientSpace) } else if self.pos + num_bytes <= self.buffer.len() { dest.extend_from_slice(&self.buffer[self.pos..self.pos + num_bytes]) - .map_err(|_| { + .map_err(|()| { error!( "Failed to extend destination buffer. Space: {} required: {}", space, num_bytes diff --git a/src/read_buffer.rs b/src/read_buffer.rs index 1a86fe1..99bfdff 100644 --- a/src/read_buffer.rs +++ b/src/read_buffer.rs @@ -20,11 +20,13 @@ impl<'a> ReadBuffer<'a> { } #[inline] + #[must_use] pub fn len(&self) -> usize { self.data.len() - self.consumed } #[inline] + #[must_use] pub fn is_empty(&self) -> bool { self.len() == 0 } diff --git a/src/record.rs b/src/record.rs index ee00f85..1156c0c 100644 --- a/src/record.rs +++ b/src/record.rs @@ -6,8 +6,11 @@ use crate::handshake::client_hello::ClientHello; use crate::handshake::{ClientHandshake, ServerHandshake}; use crate::key_schedule::WriteKeySchedule; use crate::TlsError; -use crate::{alert::*, parse_buffer::ParseBuffer}; -use crate::{buffer::*, CryptoProvider}; +use crate::{ + alert::{Alert, AlertDescription, AlertLevel}, + parse_buffer::ParseBuffer, +}; +use crate::{buffer::CryptoBuffer, CryptoProvider}; use core::fmt::Debug; pub type Encrypted = bool; @@ -31,26 +34,26 @@ pub enum ClientRecordHeader { } impl ClientRecordHeader { - pub fn is_encrypted(&self) -> bool { + pub fn is_encrypted(self) -> bool { match self { ClientRecordHeader::Handshake(encrypted) | ClientRecordHeader::Alert(encrypted) => { - *encrypted + encrypted } ClientRecordHeader::ApplicationData => true, } } - pub fn header_content_type(&self) -> ContentType { + pub fn header_content_type(self) -> ContentType { match self { Self::Handshake(false) => ContentType::Handshake, Self::Alert(false) => ContentType::ChangeCipherSpec, - Self::Handshake(true) => ContentType::ApplicationData, - Self::Alert(true) => ContentType::ApplicationData, - Self::ApplicationData => ContentType::ApplicationData, + Self::Handshake(true) | Self::Alert(true) | Self::ApplicationData => { + ContentType::ApplicationData + } } } - pub fn trailer_content_type(&self) -> ContentType { + pub fn trailer_content_type(self) -> ContentType { match self { Self::Handshake(_) => ContentType::Handshake, Self::Alert(_) => ContentType::Alert, @@ -58,17 +61,14 @@ impl ClientRecordHeader { } } - pub fn version(&self) -> [u8; 2] { + pub fn version(self) -> [u8; 2] { match self { - Self::Handshake(true) => [0x03, 0x03], - Self::Handshake(false) => [0x03, 0x01], - Self::Alert(true) => [0x03, 0x03], - Self::Alert(false) => [0x03, 0x01], - Self::ApplicationData => [0x03, 0x03], + Self::Handshake(true) | Self::Alert(true) | Self::ApplicationData => [0x03, 0x03], + Self::Handshake(false) | Self::Alert(false) => [0x03, 0x01], } } - pub fn encode(&self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { + pub fn encode(self, buf: &mut CryptoBuffer) -> Result<(), TlsError> { buf.push(self.header_content_type() as u8) .map_err(|_| TlsError::EncodeError)?; buf.extend_from_slice(&self.version()) @@ -131,8 +131,9 @@ where ClientRecord::Handshake(handshake, false) => { handshake.finalize(buf, transcript, write_key_schedule) } - ClientRecord::Handshake(handshake, true) => { - handshake.finalize_encrypted(buf, transcript) + ClientRecord::Handshake(_, true) => { + ClientHandshake::::finalize_encrypted(buf, transcript); + Ok(()) } _ => Ok(()), } diff --git a/src/split.rs b/src/split.rs index 8b95ea4..d1737c8 100644 --- a/src/split.rs +++ b/src/split.rs @@ -52,7 +52,7 @@ pub use stdlib::ManagedSplitState; #[cfg(feature = "std")] mod stdlib { - use super::*; + use super::{SplitConnectionState, SplitState, SplitStateContainer}; use std::sync::Arc; #[derive(Clone)] @@ -77,7 +77,7 @@ mod stdlib { } fn set_open(&self, open: bool) { - self.0.as_ref().set_open(open) + self.0.as_ref().set_open(open); } fn same(&self, other: &Self) -> bool { diff --git a/src/webpki.rs b/src/webpki.rs index e96b62c..4fe3530 100644 --- a/src/webpki.rs +++ b/src/webpki.rs @@ -15,10 +15,11 @@ impl TryInto<&'static webpki::SignatureAlgorithm> for SignatureScheme { type Error = TlsError; fn try_into(self) -> Result<&'static webpki::SignatureAlgorithm, Self::Error> { // TODO: support other schemes via 'alloc' feature + #[allow(clippy::match_same_arms)] // Style match self { - SignatureScheme::RsaPkcs1Sha256 => Err(TlsError::InvalidSignatureScheme), - SignatureScheme::RsaPkcs1Sha384 => Err(TlsError::InvalidSignatureScheme), - SignatureScheme::RsaPkcs1Sha512 => Err(TlsError::InvalidSignatureScheme), + SignatureScheme::RsaPkcs1Sha256 + | SignatureScheme::RsaPkcs1Sha384 + | SignatureScheme::RsaPkcs1Sha512 => Err(TlsError::InvalidSignatureScheme), /* ECDSA algorithms */ SignatureScheme::EcdsaSecp256r1Sha256 => Ok(&webpki::ECDSA_P256_SHA256), @@ -26,26 +27,26 @@ impl TryInto<&'static webpki::SignatureAlgorithm> for SignatureScheme { SignatureScheme::EcdsaSecp521r1Sha512 => Err(TlsError::InvalidSignatureScheme), /* RSASSA-PSS algorithms with public key OID rsaEncryption */ - SignatureScheme::RsaPssRsaeSha256 => Err(TlsError::InvalidSignatureScheme), - SignatureScheme::RsaPssRsaeSha384 => Err(TlsError::InvalidSignatureScheme), - SignatureScheme::RsaPssRsaeSha512 => Err(TlsError::InvalidSignatureScheme), + SignatureScheme::RsaPssRsaeSha256 + | SignatureScheme::RsaPssRsaeSha384 + | SignatureScheme::RsaPssRsaeSha512 => Err(TlsError::InvalidSignatureScheme), /* EdDSA algorithms */ SignatureScheme::Ed25519 => Ok(&webpki::ED25519), - SignatureScheme::Ed448 => Err(TlsError::InvalidSignatureScheme), - - SignatureScheme::Sha224Ecdsa => Err(TlsError::InvalidSignatureScheme), - SignatureScheme::Sha224Rsa => Err(TlsError::InvalidSignatureScheme), - SignatureScheme::Sha224Dsa => Err(TlsError::InvalidSignatureScheme), + SignatureScheme::Ed448 + | SignatureScheme::Sha224Ecdsa + | SignatureScheme::Sha224Rsa + | SignatureScheme::Sha224Dsa => Err(TlsError::InvalidSignatureScheme), /* RSASSA-PSS algorithms with public key OID RSASSA-PSS */ - SignatureScheme::RsaPssPssSha256 => Err(TlsError::InvalidSignatureScheme), - SignatureScheme::RsaPssPssSha384 => Err(TlsError::InvalidSignatureScheme), - SignatureScheme::RsaPssPssSha512 => Err(TlsError::InvalidSignatureScheme), + SignatureScheme::RsaPssPssSha256 + | SignatureScheme::RsaPssPssSha384 + | SignatureScheme::RsaPssPssSha512 => Err(TlsError::InvalidSignatureScheme), /* Legacy algorithms */ - SignatureScheme::RsaPkcs1Sha1 => Err(TlsError::InvalidSignatureScheme), - SignatureScheme::EcdsaSha1 => Err(TlsError::InvalidSignatureScheme), + SignatureScheme::RsaPkcs1Sha1 | SignatureScheme::EcdsaSha1 => { + Err(TlsError::InvalidSignatureScheme) + } } } } @@ -108,11 +109,22 @@ where _clock: PhantomData, } +impl Default for CertVerifier +where + C: TlsClock, + Cs: TlsCipherSuite, +{ + fn default() -> Self { + Self::new() + } +} + impl CertVerifier where Clock: TlsClock, CipherSuite: TlsCipherSuite, { + #[must_use] pub fn new() -> Self { Self { host: None, @@ -131,7 +143,7 @@ where { fn set_hostname_verification(&mut self, hostname: &str) -> Result<(), TlsError> { self.host.replace( - heapless::String::try_from(hostname).map_err(|_| TlsError::InsufficientSpace)?, + heapless::String::try_from(hostname).map_err(|()| TlsError::InsufficientSpace)?, ); Ok(()) } @@ -152,22 +164,22 @@ where let handshake_hash = unwrap!(self.certificate_transcript.take()); let ctx_str = b"TLS 1.3, server CertificateVerify\x00"; let mut msg: Vec = Vec::new(); - msg.resize(64, 0x20).map_err(|_| TlsError::EncodeError)?; + msg.resize(64, 0x20).map_err(|()| TlsError::EncodeError)?; msg.extend_from_slice(ctx_str) - .map_err(|_| TlsError::EncodeError)?; + .map_err(|()| TlsError::EncodeError)?; msg.extend_from_slice(&handshake_hash.finalize()) - .map_err(|_| TlsError::EncodeError)?; + .map_err(|()| TlsError::EncodeError)?; let certificate = unwrap!(self.certificate.as_ref()).try_into()?; - verify_signature(&msg[..], certificate, verify)?; + verify_signature(&msg[..], &certificate, &verify)?; Ok(()) } } fn verify_signature( message: &[u8], - certificate: ServerCertificate, - verify: CertificateVerifyRef, + certificate: &ServerCertificate, + verify: &CertificateVerifyRef, ) -> Result<(), TlsError> { let mut verified = false; if !certificate.entries.is_empty() { @@ -185,7 +197,7 @@ fn verify_signature( info!("Signature: {:x?}", verify.signature); let pkisig = verify.signature_scheme.try_into()?; match cert.verify_signature(pkisig, message, verify.signature) { - Ok(_) => { + Ok(()) => { verified = true; } Err(e) => { @@ -239,7 +251,7 @@ fn verify_certificate( webpki::KeyUsage::server_auth(), &[], ) { - Ok(_) => verified = true, + Ok(()) => verified = true, Err(e) => { warn!("Error verifying certificate: {:?}", e); } @@ -248,7 +260,7 @@ fn verify_certificate( if let Some(server_name) = verify_host { match webpki::SubjectNameRef::try_from_ascii(server_name.as_bytes()) { Ok(subject) => match cert.verify_is_valid_for_subject_name(subject) { - Ok(_) => host_verified = true, + Ok(()) => host_verified = true, Err(e) => { warn!("Error verifying host: {:?}", e); }