diff --git a/src/ikev2/crypto.rs b/src/ikev2/crypto.rs index a252e06..5f7b1e7 100644 --- a/src/ikev2/crypto.rs +++ b/src/ikev2/crypto.rs @@ -35,24 +35,19 @@ pub struct TransformParameters { dh: Option, esn: Option, protocol_id: message::IPSecProtocolID, - spi: message::SPI, + spi: message::Spi, } impl TransformParameters { pub fn create_dh(&self) -> Result { - DHTransformType::init( - self.dh - .as_ref() - .ok_or_else(|| "DH not configured")? - .transform_type, - ) + DHTransformType::init(self.dh.as_ref().ok_or("DH not configured")?.transform_type) } pub fn create_prf(&self, key: &[u8]) -> Result { PseudorandomTransform::init( self.prf .as_ref() - .ok_or_else(|| "PRF not configured")? + .ok_or("PRF not configured")? .transform_type, key, ) @@ -62,7 +57,7 @@ impl TransformParameters { self.protocol_id } - pub fn spi(&self) -> message::SPI { + pub fn spi(&self) -> message::Spi { self.spi } @@ -147,8 +142,8 @@ impl<'a> Iterator for TransformParametersIter<'a> { } } -pub fn choose_sa_parameters<'a>( - sa: &'a message::PayloadSecurityAssociation, +pub fn choose_sa_parameters( + sa: &message::PayloadSecurityAssociation, ) -> Option<(TransformParameters, u8)> { sa.iter_proposals() .flat_map(|prop| { @@ -553,7 +548,7 @@ impl PseudorandomTransform { } // Following T-chunks. next_data[0..hash.len()].copy_from_slice(&hash); - next_data[hash.len()..hash.len() + data.len()].copy_from_slice(&data); + next_data[hash.len()..hash.len() + data.len()].copy_from_slice(data); next_data[hash.len() + data.len()] = t + 1; let mut signer = new_hmac_sha256(key).map_err(|err| { debug!("Failed to init SHA256 HMAC signer: {}", err); @@ -785,7 +780,7 @@ impl CryptoStack { let enc = params .enc .as_ref() - .ok_or_else(|| "Undefined encryption parameters")?; + .ok_or("Undefined encryption parameters")?; let auth = params .auth .as_ref() @@ -793,7 +788,7 @@ impl CryptoStack { let prf = params .prf .as_ref() - .ok_or_else(|| "Undefined pseudorandom transform parameters")? + .ok_or("Undefined pseudorandom transform parameters")? .transform_type; Ok(CryptoStack { derive_key, @@ -817,9 +812,9 @@ impl CryptoStack { + self.auth_responder.signature_length() } - pub fn encrypt_data<'a>( + pub fn encrypt_data( &self, - data: &'a mut [u8], + data: &mut [u8], msg_len: usize, associated_data: &[u8], ) -> Result<(), CryptoError> { @@ -841,7 +836,7 @@ impl CryptoStack { let decrypted_slice = if decrypted_slice.len() >= padding_length { &decrypted_slice[..decrypted_slice.len() - padding_length] } else { - &decrypted_slice + decrypted_slice }; Ok(decrypted_slice) } @@ -864,9 +859,9 @@ impl CryptoStack { } pub trait Encryption { - fn encrypt<'a>( + fn encrypt( &self, - data: &'a mut [u8], + data: &mut [u8], msg_len: usize, associated_data: &[u8], ) -> Result<(), CryptoError>; @@ -918,9 +913,9 @@ impl EncryptionType { } } - fn encrypt<'a>( + fn encrypt( &self, - data: &'a mut [u8], + data: &mut [u8], msg_len: usize, associated_data: &[u8], ) -> Result<(), CryptoError> { @@ -948,7 +943,7 @@ pub struct EncryptionAesCbc256 { } impl Encryption for EncryptionAesCbc256 { - fn encrypt<'a>(&self, data: &'a mut [u8], msg_len: usize, _: &[u8]) -> Result<(), CryptoError> { + fn encrypt(&self, data: &mut [u8], msg_len: usize, _: &[u8]) -> Result<(), CryptoError> { let aes_cbc_cipher = cipher::Cipher::aes_256_cbc(); let mut ctx = cipher_ctx::CipherCtx::new().map_err(|err| { debug!("Failed to init cipher context: {}", err); @@ -968,7 +963,7 @@ impl Encryption for EncryptionAesCbc256 { debug!("Failed to generate IV for AES CBC 256: {}", err); "Failed to generate IV for AES CBC 256" })?; - ctx.encrypt_init(Some(&aes_cbc_cipher), Some(&self.cipher_key), Some(iv)) + ctx.encrypt_init(Some(aes_cbc_cipher), Some(&self.cipher_key), Some(iv)) .map_err(|err| { debug!("Failed to init AES CBC 256 encryptor: {}", err); "Failed to init AES CBC 256 encryptor" @@ -1006,7 +1001,7 @@ impl Encryption for EncryptionAesCbc256 { return Err("Message length is too short".into()); } let iv = &data[..iv_size]; - ctx.decrypt_init(Some(&aes_cbc_cipher), Some(&self.cipher_key), Some(iv)) + ctx.decrypt_init(Some(aes_cbc_cipher), Some(&self.cipher_key), Some(iv)) .map_err(|err| { debug!("Failed to init AES CBC 256 decryptor: {}", err); "Failed to init AES CBC 256 decryptor" @@ -1044,9 +1039,9 @@ pub struct EncryptionAesGcm256 { } impl Encryption for EncryptionAesGcm256 { - fn encrypt<'a>( + fn encrypt( &self, - data: &'a mut [u8], + data: &mut [u8], msg_len: usize, associated_data: &[u8], ) -> Result<(), CryptoError> { @@ -1072,7 +1067,7 @@ impl Encryption for EncryptionAesGcm256 { debug!("Failed to init cipher context: {}", err); "Failed to init cipher context" })?; - match ctx.encrypt_init(Some(&aes_gcm_cipher), Some(&self.cipher_key), Some(&nonce)) { + match ctx.encrypt_init(Some(aes_gcm_cipher), Some(&self.cipher_key), Some(&nonce)) { Ok(dec) => dec, Err(err) => { debug!("Failed to init AES GCM 16 256: {}", err); @@ -1122,7 +1117,7 @@ impl Encryption for EncryptionAesGcm256 { debug!("Failed to init cipher context: {}", err); "Failed to init cipher context" })?; - ctx.decrypt_init(Some(&aes_gcm_cipher), Some(&self.cipher_key), Some(&nonce)) + ctx.decrypt_init(Some(aes_gcm_cipher), Some(&self.cipher_key), Some(&nonce)) .map_err(|err| { debug!("Failed to init AES GCM 16 256: {}", err); "Failed to init AES GCM 16 256" @@ -1164,7 +1159,7 @@ impl Encryption for EncryptionAesGcm256 { fn new_hmac_sha256( key: &pkey::PKey, ) -> Result { - sign::Signer::new(hash::MessageDigest::sha256(), &key) + sign::Signer::new(hash::MessageDigest::sha256(), key) } pub fn hash_sha1(data: &[u8]) -> Result<[u8; 160 / 8], CryptoError> { diff --git a/src/ikev2/message.rs b/src/ikev2/message.rs index a918858..a0ba91e 100644 --- a/src/ikev2/message.rs +++ b/src/ikev2/message.rs @@ -77,14 +77,14 @@ impl fmt::Display for Flags { } #[derive(Clone, Copy, PartialEq, Eq)] -pub enum SPI { +pub enum Spi { None, U32(u32), U64(u64), } -impl SPI { - fn from_slice(spi: &[u8]) -> Result { +impl Spi { + fn from_slice(spi: &[u8]) -> Result { if spi.len() == 4 { let mut value = [0u8; 4]; value.copy_from_slice(spi); @@ -120,7 +120,7 @@ impl SPI { } } -impl fmt::Display for SPI { +impl fmt::Display for Spi { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { Self::None => Ok(()), @@ -130,7 +130,7 @@ impl fmt::Display for SPI { } } -impl fmt::Debug for SPI { +impl fmt::Debug for Spi { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(self, f) } @@ -277,7 +277,7 @@ impl InputMessage<'_> { } pub fn raw_data(&self) -> &[u8] { - &self.data + self.data } } @@ -656,7 +656,7 @@ impl<'a> Iterator for PayloadIter<'a> { } let current_payload = self.next_payload; let start_offset = self.start_offset; - let data = &self.data[..]; + let data = self.data; let next_payload = self.data[0]; self.next_payload = next_payload; let payload_flags = self.data[1]; @@ -838,7 +838,7 @@ impl<'a> Iterator for SecurityAssociationIter<'a> { debug!("Proposal overflow"); return None; } - let data = &self.data[..]; + let data = self.data; self.data = &self.data[proposal_length..]; let proposal_num = data[4]; if proposal_num != self.next_proposal_num { @@ -863,7 +863,7 @@ impl<'a> Iterator for SecurityAssociationIter<'a> { return None; } let spi = &data[8..8 + spi_size]; - let spi = match SPI::from_slice(spi) { + let spi = match Spi::from_slice(spi) { Ok(spi) => spi, Err(_) => { return Some(Err("Unsupported SPI format".into())); @@ -884,7 +884,7 @@ pub struct SecurityAssociationProposal<'a> { proposal_num: u8, protocol_id: IPSecProtocolID, num_transforms: usize, - spi: SPI, + spi: Spi, data: &'a [u8], } @@ -904,7 +904,7 @@ impl<'a> SecurityAssociationProposal<'a> { self.protocol_id } - pub fn spi(&self) -> SPI { + pub fn spi(&self) -> Spi { self.spi } } @@ -1087,7 +1087,7 @@ impl<'a> Iterator for SecurityAssociationTransformIter<'a> { debug!("Transform overflow"); return None; } - let data = &self.data[..]; + let data = self.data; self.data = &self.data[transform_length..]; if self.num_transforms == 0 && !self.data.is_empty() { debug!("Packet has unaccounted transforms"); @@ -1302,7 +1302,7 @@ impl<'a> PayloadIdentification<'a> { } pub fn raw_value(&self) -> &[u8] { - &self.data + self.data } pub fn read_value(&self) -> &[u8] { @@ -1360,7 +1360,7 @@ pub struct PayloadCertificate<'a> { impl<'a> PayloadCertificate<'a> { fn from_payload(data: &'a [u8]) -> Result, FormatError> { - if data.len() < 1 { + if data.is_empty() { debug!("Not enough data in certificate payload"); return Err("Not enough data in certificate payload".into()); } @@ -1378,7 +1378,7 @@ impl<'a> PayloadCertificate<'a> { } pub fn read_value(&self) -> &[u8] { - &self.data + self.data } } @@ -1388,7 +1388,7 @@ pub struct PayloadCertificateRequest<'a> { impl<'a> PayloadCertificateRequest<'a> { fn from_payload(data: &'a [u8]) -> Result, FormatError> { - if data.len() < 1 { + if data.is_empty() { debug!("Not enough data in certificate request payload"); Err("Not enough data in certificate request payload".into()) } else { @@ -1436,7 +1436,7 @@ pub struct PayloadAuthentication<'a> { impl<'a> PayloadAuthentication<'a> { fn from_payload(data: &'a [u8]) -> Result, FormatError> { - if data.len() < 1 { + if data.is_empty() { debug!("Not enough data in authentication payload"); return Err("Not enough data in certificate payload".into()); } @@ -1757,7 +1757,7 @@ impl<'a> Iterator for TrafficSelectorIter<'a> { return None; } - let data = &self.data[..]; + let data = self.data; self.data = &self.data[selector_length..]; self.num_selectors = self.num_selectors.saturating_sub(1); let ts_type = match TrafficSelectorType::from_u8(data[0]) { @@ -1921,7 +1921,7 @@ impl<'a> Iterator for ConfigurationAttributesIter<'a> { debug!("Attribute overflow"); return None; } - let data = &self.data[..]; + let data = self.data; self.data = &self.data[4 + attribute_length..]; let mut attribute_type = [0u8; 2]; diff --git a/src/ikev2/mod.rs b/src/ikev2/mod.rs index f460ae1..10fead6 100644 --- a/src/ikev2/mod.rs +++ b/src/ikev2/mod.rs @@ -46,8 +46,8 @@ pub struct Server { impl Server { pub fn new(config: Config) -> Result { let pki_processing = pki::PkiProcessing::new( - config.hostname.as_ref().map(|hostname| hostname.as_str()), - config.root_ca.as_ref().map(|root_ca| root_ca.as_str()), + config.hostname.as_deref(), + config.root_ca.as_deref(), config .server_cert .as_ref() @@ -173,8 +173,8 @@ impl Sockets { send_to: &SocketAddr, data: &[u8], ) -> Result<(), IKEv2Error> { - match self.sockets.get(&send_from) { - Some(ref socket) => { + match self.sockets.get(send_from) { + Some(socket) => { socket.send_to(data, send_to).await?; Ok(()) } @@ -499,7 +499,7 @@ impl IKEv2Session { response.write_header( session_id.remote_spi, session_id.local_spi, - exchange_type.clone(), + exchange_type, false, request.read_message_id(), )?; @@ -553,7 +553,7 @@ impl IKEv2Session { } else { return Err("Crypto parameters not initialized".into()); }; - let validate_slice = request.signature_data(&encrypted_payload, signature_length.is_some()); + let validate_slice = request.signature_data(encrypted_payload, signature_length.is_some()); let valid_signature = crypto_stack.validate_signature(validate_slice); if !valid_signature { return Err("Packet has invalid signature".into()); @@ -606,9 +606,9 @@ impl IKEv2Session { let (associated_data, encrypt_data) = raw_data.split_at_mut(full_message_len - full_encrypted_length); let associated_data = if !add_signature { - associated_data.as_ref() + associated_data } else { - &[] + &mut [0u8; 0] }; crypto_stack @@ -715,7 +715,7 @@ impl IKEv2Session { .copy_from_slice(nonce_remote); prf_key_cursor += nonce_remote.len(); prf_key[prf_key_cursor..prf_key_cursor + nonce_local.len()] - .copy_from_slice(&nonce_local); + .copy_from_slice(nonce_local); prf_key_cursor += nonce_local.len(); prf_key[prf_key_cursor..prf_key_cursor + 8] .copy_from_slice(&session_id.remote_spi.to_be_bytes()); @@ -763,7 +763,7 @@ impl IKEv2Session { continue; } }; - match prf_transform.create_crypto_stack(¶ms, &prf_key) { + match prf_transform.create_crypto_stack(params, &prf_key) { Ok(crypto_stack) => self.crypto_stack = Some(crypto_stack), Err(err) => { debug!("Failed to set up cryptography stack {}", err); @@ -773,7 +773,7 @@ impl IKEv2Session { }; let dest = response .next_payload_slice(message::PayloadType::NONCE, nonce_local.len())?; - dest.copy_from_slice(&nonce_local); + dest.copy_from_slice(nonce_local); } _ => {} } @@ -877,19 +877,15 @@ impl IKEv2Session { // TODO: return INVALID_SYNTAX notification. continue; }; - match payload.payload_type() { - message::PayloadType::ENCRYPTED_AND_AUTHENTICATED => { - let encrypted_payload = payload.encrypted_data()?; - // TODO: return AUTHENTICATION_FAILED notification on error. - let decrypted_slice = self.process_encrypted_payload( - request, - &encrypted_payload, - &mut decrypted_request, - )?; - decrypted_iter = - Some(encrypted_payload.iter_decrypted_message(decrypted_slice)); - } - _ => {} + if payload.payload_type() == message::PayloadType::ENCRYPTED_AND_AUTHENTICATED { + let encrypted_payload = payload.encrypted_data()?; + // TODO: return AUTHENTICATION_FAILED notification on error. + let decrypted_slice = self.process_encrypted_payload( + request, + &encrypted_payload, + &mut decrypted_request, + )?; + decrypted_iter = Some(encrypted_payload.iter_decrypted_message(decrypted_slice)); } } @@ -1045,7 +1041,7 @@ impl IKEv2Session { { let write_slice = response .next_payload_slice(message::PayloadType::ID_RESPONDER, id_responder.len())?; - write_slice.copy_from_slice(&id_responder); + write_slice.copy_from_slice(id_responder); } } @@ -1063,7 +1059,7 @@ impl IKEv2Session { responder_signed[ctx.message_responder.len() ..ctx.message_responder.len() + ctx.nonce_initiator.len()] .copy_from_slice(&ctx.nonce_initiator); - match crypto_stack.authenticate_id_responder(&id_responder) { + match crypto_stack.authenticate_id_responder(id_responder) { Ok(signature) => responder_signed [ctx.message_responder.len() + ctx.nonce_initiator.len()..responder_signed_len] .copy_from_slice(&signature), @@ -1119,18 +1115,14 @@ impl IKEv2Session { // TODO: return INVALID_SYNTAX notification. continue; }; - match payload.payload_type() { - message::PayloadType::ENCRYPTED_AND_AUTHENTICATED => { - let encrypted_payload = payload.encrypted_data()?; - let decrypted_slice = self.process_encrypted_payload( - request, - &encrypted_payload, - &mut decrypted_data, - )?; - decrypted_iter = - Some(encrypted_payload.iter_decrypted_message(decrypted_slice)); - } - _ => {} + if payload.payload_type() == message::PayloadType::ENCRYPTED_AND_AUTHENTICATED { + let encrypted_payload = payload.encrypted_data()?; + let decrypted_slice = self.process_encrypted_payload( + request, + &encrypted_payload, + &mut decrypted_data, + )?; + decrypted_iter = Some(encrypted_payload.iter_decrypted_message(decrypted_slice)); } } @@ -1173,7 +1165,7 @@ fn nat_detection_ip(initiator_spi: u64, responder_spi: u64, addr: IpAddr, port: src_data[16 + addr_len..16 + addr_len + 2].copy_from_slice(&port.to_be_bytes()); let src_data = &src_data[..16 + addr_len + 2]; - crypto::hash_sha1(&src_data).unwrap_or([0u8; 20]) + crypto::hash_sha1(src_data).unwrap_or([0u8; 20]) } #[derive(Debug)] diff --git a/src/ikev2/pki.rs b/src/ikev2/pki.rs index fd57f72..e0d4209 100644 --- a/src/ikev2/pki.rs +++ b/src/ikev2/pki.rs @@ -19,12 +19,12 @@ impl PkiProcessing { server_cert: Option<(&str, &str)>, ) -> Result { let client_validation = if let Some(root_ca) = root_ca { - Some(ClientValidation::new(&root_ca)?) + Some(ClientValidation::new(root_ca)?) } else { None }; let server_identity = if let Some((public_cert, private_key)) = server_cert { - Some(ServerIdentity::new(&public_cert, &private_key)?) + Some(ServerIdentity::new(public_cert, private_key)?) } else { None }; @@ -76,9 +76,7 @@ impl PkiProcessing { } pub fn server_id(&self) -> Option<&[u8]> { - self.server_id - .as_ref() - .map(|server_id| server_id.as_slice()) + self.server_id.as_deref() } pub fn verify_client_cert( @@ -159,7 +157,7 @@ pub struct ClientCertificate { impl ClientCertificate { pub fn subject(&self) -> Option<&str> { - self.subject.as_ref().map(|subject| subject.as_str()) + self.subject.as_deref() } pub fn verify_signature(&self, msg: &[u8], signature: &[u8]) -> Result<(), CertError> { diff --git a/src/main.rs b/src/main.rs index 93fe565..e4ddcf9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -29,7 +29,7 @@ Options:\ impl Args { fn parse() -> Args { - let fail_with_error = |name: &str, value: &str, err: fmt::Arguments| -> () { + let fail_with_error = |name: &str, value: &str, err: fmt::Arguments| { eprintln!( "Argument {} has an unsupported value {}: {}", name, value, err