diff --git a/rust/src/nasl/builtin/cryptographic/aes_cbc.rs b/rust/src/nasl/builtin/cryptographic/aes_cbc.rs index 4da1c2374..610dc08fe 100644 --- a/rust/src/nasl/builtin/cryptographic/aes_cbc.rs +++ b/rust/src/nasl/builtin/cryptographic/aes_cbc.rs @@ -17,7 +17,7 @@ use crate::nasl::prelude::*; use super::{get_data, get_iv, get_key, get_len, Crypt}; /// Base function for en- and decrypting Cipher Block Chaining (CBC) mode -fn cbc(register: &Register, crypt: Crypt) -> Result +fn cbc(register: &Register, crypt: Crypt) -> Result where D: BlockCipher + BlockEncrypt + BlockDecrypt + KeyInit, { @@ -71,7 +71,7 @@ where /// Currently the data is filled with zeroes. Therefore the length of the encrypted data must be /// known for decryption. If no length is given, the last block is decrypted as a whole. /// - The iv must have a length of 16 bytes -fn aes128_cbc_encrypt(register: &Register, _: &Context) -> Result { +fn aes128_cbc_encrypt(register: &Register, _: &Context) -> Result { cbc::(register, Crypt::Encrypt) } @@ -83,7 +83,7 @@ fn aes128_cbc_encrypt(register: &Register, _: &Context) -> Result Result { +fn aes128_cbc_decrypt(register: &Register, _: &Context) -> Result { cbc::(register, Crypt::Decrypt) } @@ -94,7 +94,7 @@ fn aes128_cbc_decrypt(register: &Register, _: &Context) -> Result Result { +fn aes192_cbc_encrypt(register: &Register, _: &Context) -> Result { cbc::(register, Crypt::Encrypt) } @@ -106,7 +106,7 @@ fn aes192_cbc_encrypt(register: &Register, _: &Context) -> Result Result { +fn aes192_cbc_decrypt(register: &Register, _: &Context) -> Result { cbc::(register, Crypt::Decrypt) } @@ -117,7 +117,7 @@ fn aes192_cbc_decrypt(register: &Register, _: &Context) -> Result Result { +fn aes256_cbc_encrypt(register: &Register, _: &Context) -> Result { cbc::(register, Crypt::Encrypt) } @@ -129,7 +129,7 @@ fn aes256_cbc_encrypt(register: &Register, _: &Context) -> Result Result { +fn aes256_cbc_decrypt(register: &Register, _: &Context) -> Result { cbc::(register, Crypt::Decrypt) } diff --git a/rust/src/nasl/builtin/cryptographic/aes_ccm.rs b/rust/src/nasl/builtin/cryptographic/aes_ccm.rs index 846899ffd..9785ba1ed 100644 --- a/rust/src/nasl/builtin/cryptographic/aes_ccm.rs +++ b/rust/src/nasl/builtin/cryptographic/aes_ccm.rs @@ -2,7 +2,7 @@ // // SPDX-License-Identifier: GPL-2.0-or-later WITH x11vnc-openssl-exception -use crate::nasl::utils::error::NaslError; +use crate::nasl::utils::error::FunctionErrorKind; use aes::cipher::{BlockCipher, BlockDecrypt, BlockEncrypt, BlockSizeUser}; use aes::{Aes128, Aes192, Aes256}; use ccm::{ @@ -41,7 +41,7 @@ where } /// Base function for ccm en- and decryption. Sets the tag length to 16. -fn ccm(register: &Register, crypt: Crypt, auth: bool) -> Result +fn ccm(register: &Register, crypt: Crypt, auth: bool) -> Result where D: BlockCipher + BlockSizeUser + BlockEncrypt + BlockDecrypt + KeyInit, { @@ -71,7 +71,7 @@ where /// - The length of the key should be 16 bytes long /// - The iv must have a length of 7-13 bytes /// - The tag_size default is 16, it can be set to either 4, 6, 8, 10, 12, 14 or 16 -fn aes128_ccm_encrypt(register: &Register, _: &Context) -> Result { +fn aes128_ccm_encrypt(register: &Register, _: &Context) -> Result { ccm::(register, Crypt::Encrypt, false) } @@ -82,7 +82,10 @@ fn aes128_ccm_encrypt(register: &Register, _: &Context) -> Result Result { +fn aes128_ccm_encrypt_auth( + register: &Register, + _: &Context, +) -> Result { ccm::(register, Crypt::Encrypt, true) } @@ -93,7 +96,7 @@ fn aes128_ccm_encrypt_auth(register: &Register, _: &Context) -> Result Result { +fn aes128_ccm_decrypt(register: &Register, _: &Context) -> Result { ccm::(register, Crypt::Decrypt, false) } @@ -104,7 +107,10 @@ fn aes128_ccm_decrypt(register: &Register, _: &Context) -> Result Result { +fn aes128_ccm_decrypt_auth( + register: &Register, + _: &Context, +) -> Result { ccm::(register, Crypt::Decrypt, true) } @@ -115,7 +121,7 @@ fn aes128_ccm_decrypt_auth(register: &Register, _: &Context) -> Result Result { +fn aes192_ccm_encrypt(register: &Register, _: &Context) -> Result { ccm::(register, Crypt::Encrypt, false) } @@ -126,7 +132,10 @@ fn aes192_ccm_encrypt(register: &Register, _: &Context) -> Result Result { +fn aes192_ccm_encrypt_auth( + register: &Register, + _: &Context, +) -> Result { ccm::(register, Crypt::Encrypt, true) } @@ -137,7 +146,7 @@ fn aes192_ccm_encrypt_auth(register: &Register, _: &Context) -> Result Result { +fn aes192_ccm_decrypt(register: &Register, _: &Context) -> Result { ccm::(register, Crypt::Decrypt, false) } @@ -148,7 +157,10 @@ fn aes192_ccm_decrypt(register: &Register, _: &Context) -> Result Result { +fn aes192_ccm_decrypt_auth( + register: &Register, + _: &Context, +) -> Result { ccm::(register, Crypt::Decrypt, true) } @@ -159,7 +171,7 @@ fn aes192_ccm_decrypt_auth(register: &Register, _: &Context) -> Result Result { +fn aes256_ccm_encrypt(register: &Register, _: &Context) -> Result { ccm::(register, Crypt::Encrypt, false) } @@ -170,7 +182,10 @@ fn aes256_ccm_encrypt(register: &Register, _: &Context) -> Result Result { +fn aes256_ccm_encrypt_auth( + register: &Register, + _: &Context, +) -> Result { ccm::(register, Crypt::Encrypt, true) } @@ -181,7 +196,7 @@ fn aes256_ccm_encrypt_auth(register: &Register, _: &Context) -> Result Result { +fn aes256_ccm_decrypt(register: &Register, _: &Context) -> Result { ccm::(register, Crypt::Decrypt, false) } @@ -192,13 +207,16 @@ fn aes256_ccm_decrypt(register: &Register, _: &Context) -> Result Result { +fn aes256_ccm_decrypt_auth( + register: &Register, + _: &Context, +) -> Result { ccm::(register, Crypt::Decrypt, true) } macro_rules! ccm_call_typed { ($(($t1s: expr, $t1: ty) => $(($t2s: expr, $t2: ty)),*);*) => { - fn ccm_typed(tag_size: usize, iv_size: usize, crypt: Crypt, key: &[u8], nonce: &[u8], data: &[u8], aad: &[u8]) -> Result, aError>, NaslError> + fn ccm_typed(tag_size: usize, iv_size: usize, crypt: Crypt, key: &[u8], nonce: &[u8], data: &[u8], aad: &[u8]) -> Result, aError>, FunctionErrorKind> where D: BlockCipher + BlockSizeUser + BlockEncrypt + BlockDecrypt + KeyInit { match tag_size { @@ -210,11 +228,11 @@ macro_rules! ccm_call_typed { Ok(ccm_crypt::(crypt, key, nonce, data, aad)) } ),* - other => Err(NaslError::wrong_unnamed_argument("iv must be between 7 and 13", other.to_string().as_str())) + other => Err(FunctionErrorKind::wrong_unnamed_argument("iv must be between 7 and 13", other.to_string().as_str())) } } ),* - other => Err(NaslError::wrong_unnamed_argument("tag_size must be 4, 6, 8, 10, 12, 14 or 16", other.to_string().as_str())) + other => Err(FunctionErrorKind::wrong_unnamed_argument("tag_size must be 4, 6, 8, 10, 12, 14 or 16", other.to_string().as_str())) } } } diff --git a/rust/src/nasl/builtin/cryptographic/aes_cmac.rs b/rust/src/nasl/builtin/cryptographic/aes_cmac.rs index 987c8b5bf..9e01cd544 100644 --- a/rust/src/nasl/builtin/cryptographic/aes_cmac.rs +++ b/rust/src/nasl/builtin/cryptographic/aes_cmac.rs @@ -3,7 +3,7 @@ // SPDX-License-Identifier: GPL-2.0-or-later WITH x11vnc-openssl-exception use crate::nasl::syntax::NaslValue; -use crate::nasl::utils::{Context, NaslError, Register}; +use crate::nasl::utils::{Context, FunctionErrorKind, Register}; use aes::Aes128; use cmac::{Cmac, Mac}; @@ -16,7 +16,7 @@ use super::{get_data, get_key, CryptographicError}; /// This function expects 2 named arguments key and data either in a string or data type. /// It is important to notice, that internally the CMAC algorithm is used and not, as the name /// suggests, CBC-MAC. -fn aes_cmac(register: &Register, _: &Context) -> Result { +fn aes_cmac(register: &Register, _: &Context) -> Result { let key = get_key(register)?; let data = get_data(register)?; diff --git a/rust/src/nasl/builtin/cryptographic/aes_ctr.rs b/rust/src/nasl/builtin/cryptographic/aes_ctr.rs index ff8b335f7..7d46c7495 100644 --- a/rust/src/nasl/builtin/cryptographic/aes_ctr.rs +++ b/rust/src/nasl/builtin/cryptographic/aes_ctr.rs @@ -15,7 +15,7 @@ use crate::nasl::prelude::*; use super::{get_data, get_iv, get_key, get_len, Crypt}; -fn ctr(register: &Register, crypt: Crypt) -> Result +fn ctr(register: &Register, crypt: Crypt) -> Result where D: BlockSizeUser + aes::cipher::KeyInit @@ -56,7 +56,7 @@ where /// Currently the data is filled with zeroes. Therefore the length of the encrypted data must be /// known for decryption. If no length is given, the last block is decrypted as a whole. /// - The iv must have a length of 16 bytes. It is used as the initial counter. -fn aes128_ctr_encrypt(register: &Register, _: &Context) -> Result { +fn aes128_ctr_encrypt(register: &Register, _: &Context) -> Result { ctr::(register, Crypt::Encrypt) } @@ -68,7 +68,7 @@ fn aes128_ctr_encrypt(register: &Register, _: &Context) -> Result Result { +fn aes128_ctr_decrypt(register: &Register, _: &Context) -> Result { ctr::(register, Crypt::Decrypt) } @@ -79,7 +79,7 @@ fn aes128_ctr_decrypt(register: &Register, _: &Context) -> Result Result { +fn aes192_ctr_encrypt(register: &Register, _: &Context) -> Result { ctr::(register, Crypt::Encrypt) } @@ -91,7 +91,7 @@ fn aes192_ctr_encrypt(register: &Register, _: &Context) -> Result Result { +fn aes192_ctr_decrypt(register: &Register, _: &Context) -> Result { ctr::(register, Crypt::Decrypt) } @@ -102,7 +102,7 @@ fn aes192_ctr_decrypt(register: &Register, _: &Context) -> Result Result { +fn aes256_ctr_encrypt(register: &Register, _: &Context) -> Result { ctr::(register, Crypt::Encrypt) } @@ -114,7 +114,7 @@ fn aes256_ctr_encrypt(register: &Register, _: &Context) -> Result Result { +fn aes256_ctr_decrypt(register: &Register, _: &Context) -> Result { ctr::(register, Crypt::Decrypt) } diff --git a/rust/src/nasl/builtin/cryptographic/aes_gcm.rs b/rust/src/nasl/builtin/cryptographic/aes_gcm.rs index af2b1682e..9d8fbf436 100644 --- a/rust/src/nasl/builtin/cryptographic/aes_gcm.rs +++ b/rust/src/nasl/builtin/cryptographic/aes_gcm.rs @@ -2,7 +2,7 @@ // // SPDX-License-Identifier: GPL-2.0-or-later WITH x11vnc-openssl-exception -// NaslError::GeneralError +// FunctionErrorKind::GeneralError use crate::nasl::prelude::*; use aes::{ cipher::{BlockCipher, BlockDecrypt, BlockEncrypt, BlockSizeUser, KeyInit}, @@ -16,7 +16,7 @@ use digest::typenum::{U12, U16}; use super::{get_aad, get_data, get_iv, get_key, get_len, Crypt, CryptographicError}; -fn gcm(register: &Register, crypt: Crypt, auth: bool) -> Result +fn gcm(register: &Register, crypt: Crypt, auth: bool) -> Result where D: BlockSizeUser + aes::cipher::KeyInit @@ -76,7 +76,7 @@ where /// - The iv must have a length of 16 bytes. It is used as the initial counter. /// - The result contains the ciphertext and the calculated tag in a single data type. /// - The tag has a size of 16 Bytes. -fn aes128_gcm_encrypt(register: &Register, _: &Context) -> Result { +fn aes128_gcm_encrypt(register: &Register, _: &Context) -> Result { gcm::(register, Crypt::Encrypt, false) } @@ -89,7 +89,10 @@ fn aes128_gcm_encrypt(register: &Register, _: &Context) -> Result Result { +fn aes128_gcm_encrypt_auth( + register: &Register, + _: &Context, +) -> Result { gcm::(register, Crypt::Encrypt, true) } @@ -102,7 +105,7 @@ fn aes128_gcm_encrypt_auth(register: &Register, _: &Context) -> Result Result { +fn aes128_gcm_decrypt(register: &Register, _: &Context) -> Result { gcm::(register, Crypt::Decrypt, false) } @@ -115,7 +118,10 @@ fn aes128_gcm_decrypt(register: &Register, _: &Context) -> Result Result { +fn aes128_gcm_decrypt_auth( + register: &Register, + _: &Context, +) -> Result { gcm::(register, Crypt::Decrypt, true) } @@ -128,7 +134,7 @@ fn aes128_gcm_decrypt_auth(register: &Register, _: &Context) -> Result Result { +fn aes192_gcm_encrypt(register: &Register, _: &Context) -> Result { gcm::(register, Crypt::Encrypt, false) } @@ -141,7 +147,10 @@ fn aes192_gcm_encrypt(register: &Register, _: &Context) -> Result Result { +fn aes192_gcm_encrypt_auth( + register: &Register, + _: &Context, +) -> Result { gcm::(register, Crypt::Encrypt, true) } @@ -154,7 +163,7 @@ fn aes192_gcm_encrypt_auth(register: &Register, _: &Context) -> Result Result { +fn aes192_gcm_decrypt(register: &Register, _: &Context) -> Result { gcm::(register, Crypt::Decrypt, false) } @@ -167,7 +176,10 @@ fn aes192_gcm_decrypt(register: &Register, _: &Context) -> Result Result { +fn aes192_gcm_decrypt_auth( + register: &Register, + _: &Context, +) -> Result { gcm::(register, Crypt::Decrypt, true) } @@ -180,7 +192,7 @@ fn aes192_gcm_decrypt_auth(register: &Register, _: &Context) -> Result Result { +fn aes256_gcm_encrypt(register: &Register, _: &Context) -> Result { gcm::(register, Crypt::Encrypt, false) } @@ -193,7 +205,10 @@ fn aes256_gcm_encrypt(register: &Register, _: &Context) -> Result Result { +fn aes256_gcm_encrypt_auth( + register: &Register, + _: &Context, +) -> Result { gcm::(register, Crypt::Encrypt, true) } @@ -206,7 +221,7 @@ fn aes256_gcm_encrypt_auth(register: &Register, _: &Context) -> Result Result { +fn aes256_gcm_decrypt(register: &Register, _: &Context) -> Result { gcm::(register, Crypt::Decrypt, false) } @@ -219,7 +234,10 @@ fn aes256_gcm_decrypt(register: &Register, _: &Context) -> Result Result { +fn aes256_gcm_decrypt_auth( + register: &Register, + _: &Context, +) -> Result { gcm::(register, Crypt::Decrypt, true) } diff --git a/rust/src/nasl/builtin/cryptographic/aes_gmac.rs b/rust/src/nasl/builtin/cryptographic/aes_gmac.rs index 5d9a9a39c..03147c1f8 100644 --- a/rust/src/nasl/builtin/cryptographic/aes_gmac.rs +++ b/rust/src/nasl/builtin/cryptographic/aes_gmac.rs @@ -10,7 +10,7 @@ use crate::nasl::prelude::*; /// /// This function expects 3 named arguments key, data and iv either in a string or data type. #[cfg(feature = "nasl-c-lib")] -fn aes_gmac(register: &Register, _: &Context) -> Result { +fn aes_gmac(register: &Register, _: &Context) -> Result { use super::{get_data, get_iv, get_key, CryptographicError}; use nasl_c_lib::cryptographic::mac::aes_gmac; diff --git a/rust/src/nasl/builtin/cryptographic/des.rs b/rust/src/nasl/builtin/cryptographic/des.rs index 20944a225..7e1f26020 100644 --- a/rust/src/nasl/builtin/cryptographic/des.rs +++ b/rust/src/nasl/builtin/cryptographic/des.rs @@ -7,7 +7,7 @@ use aes::cipher::BlockEncrypt; use ccm::KeyInit; use des::cipher::generic_array::GenericArray; -fn encrypt_des(register: &Register, _: &Context) -> Result { +fn encrypt_des(register: &Register, _: &Context) -> Result { let positional = register.positional(); if positional.len() != 2 { return Err(ArgumentError::MissingPositionals { diff --git a/rust/src/nasl/builtin/cryptographic/hash.rs b/rust/src/nasl/builtin/cryptographic/hash.rs index 4d9d59340..5289e0033 100644 --- a/rust/src/nasl/builtin/cryptographic/hash.rs +++ b/rust/src/nasl/builtin/cryptographic/hash.rs @@ -3,7 +3,7 @@ // SPDX-License-Identifier: GPL-2.0-or-later WITH x11vnc-openssl-exception use crate::function_set; -use crate::nasl::utils::error::NaslError; +use crate::nasl::utils::error::FunctionErrorKind; use digest::Digest; use md2::Md2; use md4::Md4; @@ -15,7 +15,7 @@ use sha2::{Sha256, Sha512}; use crate::nasl::syntax::NaslValue; use crate::nasl::utils::{Context, Register}; -fn nasl_hash(register: &Register) -> Result +fn nasl_hash(register: &Register) -> Result where D::OutputSize: std::ops::Add, ::Output: digest::generic_array::ArrayLength, @@ -37,37 +37,37 @@ where } /// NASL function to get MD2 hash -pub fn hash_md2(register: &Register, _: &Context) -> Result { +pub fn hash_md2(register: &Register, _: &Context) -> Result { nasl_hash::(register) } /// NASL function to get MD4 hash -pub fn hash_md4(register: &Register, _: &Context) -> Result { +pub fn hash_md4(register: &Register, _: &Context) -> Result { nasl_hash::(register) } /// NASL function to get MD5 hash -pub fn hash_md5(register: &Register, _: &Context) -> Result { +pub fn hash_md5(register: &Register, _: &Context) -> Result { nasl_hash::(register) } /// NASL function to get SHA1 hash -pub fn hash_sha1(register: &Register, _: &Context) -> Result { +pub fn hash_sha1(register: &Register, _: &Context) -> Result { nasl_hash::(register) } /// NASL function to get SHA256 hash -pub fn hash_sha256(register: &Register, _: &Context) -> Result { +pub fn hash_sha256(register: &Register, _: &Context) -> Result { nasl_hash::(register) } /// NASL function to get SHA512 hash -pub fn hash_sha512(register: &Register, _: &Context) -> Result { +pub fn hash_sha512(register: &Register, _: &Context) -> Result { nasl_hash::(register) } /// NASL function to get RIPemd160 hash -pub fn hash_ripemd160(register: &Register, _: &Context) -> Result { +pub fn hash_ripemd160(register: &Register, _: &Context) -> Result { nasl_hash::(register) } diff --git a/rust/src/nasl/builtin/cryptographic/hmac.rs b/rust/src/nasl/builtin/cryptographic/hmac.rs index 95d3a973f..4aa78f744 100644 --- a/rust/src/nasl/builtin/cryptographic/hmac.rs +++ b/rust/src/nasl/builtin/cryptographic/hmac.rs @@ -19,7 +19,7 @@ use sha2::{Sha256, Sha384, Sha512}; use crate::nasl::prelude::*; -fn hmac(register: &Register) -> Result +fn hmac(register: &Register) -> Result where D: CoreProxy, D::Core: HashMarker @@ -44,7 +44,7 @@ where let mut hmac = match Hmac::::new_from_slice(key.as_bytes()) { Ok(x) => x, Err(InvalidLength) => { - return Err(NaslError::wrong_unnamed_argument( + return Err(FunctionErrorKind::wrong_unnamed_argument( "valid size key", "invalid size key", )) @@ -57,37 +57,37 @@ where } /// NASL function to get HMAC MD2 string -pub fn hmac_md2(register: &Register, _: &Context) -> Result { +pub fn hmac_md2(register: &Register, _: &Context) -> Result { hmac::(register) } /// NASL function to get HMAC MD5 string -pub fn hmac_md5(register: &Register, _: &Context) -> Result { +pub fn hmac_md5(register: &Register, _: &Context) -> Result { hmac::(register) } /// NASL function to get HMAC RIPEMD160 string -pub fn hmac_ripemd160(register: &Register, _: &Context) -> Result { +pub fn hmac_ripemd160(register: &Register, _: &Context) -> Result { hmac::(register) } /// NASL function to get HMAC SHA1 string -pub fn hmac_sha1(register: &Register, _: &Context) -> Result { +pub fn hmac_sha1(register: &Register, _: &Context) -> Result { hmac::(register) } /// NASL function to get HMAC SHA256 string -pub fn hmac_sha256(register: &Register, _: &Context) -> Result { +pub fn hmac_sha256(register: &Register, _: &Context) -> Result { hmac::(register) } /// NASL function to get HMAC SHA384 string -pub fn hmac_sha384(register: &Register, _: &Context) -> Result { +pub fn hmac_sha384(register: &Register, _: &Context) -> Result { hmac::(register) } /// NASL function to get HMAC SHA512 string -pub fn hmac_sha512(register: &Register, _: &Context) -> Result { +pub fn hmac_sha512(register: &Register, _: &Context) -> Result { hmac::(register) } diff --git a/rust/src/nasl/builtin/cryptographic/tests/aes_gcm.rs b/rust/src/nasl/builtin/cryptographic/tests/aes_gcm.rs index f928923e7..28b663ef8 100644 --- a/rust/src/nasl/builtin/cryptographic/tests/aes_gcm.rs +++ b/rust/src/nasl/builtin/cryptographic/tests/aes_gcm.rs @@ -2,7 +2,7 @@ // // SPDX-License-Identifier: GPL-2.0-or-later WITH x11vnc-openssl-exception -// NaslError::GeneralError +// FunctionErrorKind::GeneralError use super::helper::decode_hex; use crate::nasl::test_prelude::*; diff --git a/rust/src/nasl/builtin/description/mod.rs b/rust/src/nasl/builtin/description/mod.rs index 4a6066d7e..f797089af 100644 --- a/rust/src/nasl/builtin/description/mod.rs +++ b/rust/src/nasl/builtin/description/mod.rs @@ -25,7 +25,7 @@ use crate::nasl::utils::get_named_parameter; ///} /// ```` /// The first parameter is the name of the function as well as the &str lookup key. -/// Afterwards a method that transform `&[&NaslValue]` to `Result` must be defined. +/// Afterwards a method that transform `&[&NaslValue]` to `Result` must be defined. /// /// Parameter are separated from the definition by a `=>`. /// @@ -59,7 +59,7 @@ macro_rules! make_storage_function { pub fn $name( registrat: &Register, ctxconfigs: &Context, - ) -> Result { + ) -> Result { let mut variables = vec![]; $( let positional = registrat.positional(); @@ -106,7 +106,7 @@ macro_rules! make_storage_function { }; } -type Transform = Result, NaslError>; +type Transform = Result, FunctionErrorKind>; fn as_timeout_field(_: &ContextKey, arguments: &[&NaslValue]) -> Transform { Ok(vec![NVTField::Preference(NvtPreference { diff --git a/rust/src/nasl/builtin/error.rs b/rust/src/nasl/builtin/error.rs index a95936984..00bfa8484 100644 --- a/rust/src/nasl/builtin/error.rs +++ b/rust/src/nasl/builtin/error.rs @@ -1,6 +1,6 @@ use thiserror::Error; -use super::super::prelude::NaslError; +use super::super::prelude::FunctionErrorKind; use super::cryptographic::CryptographicError; use super::regex::RegexError; use super::{misc::MiscError, network::socket::SocketError, ssh::SshError, string::StringError}; @@ -32,18 +32,18 @@ macro_rules! builtin_error_variant ( } } - impl From<$err> for NaslError { + impl From<$err> for FunctionErrorKind { fn from(value: $err) -> Self { - NaslError::Builtin(BuiltinError::$variant(value)) + FunctionErrorKind::Builtin(BuiltinError::$variant(value)) } } - impl TryFrom for $err { + impl TryFrom for $err { type Error = (); - fn try_from(value: NaslError) -> Result { + fn try_from(value: FunctionErrorKind) -> Result { match value { - NaslError::Builtin(BuiltinError::$variant(e)) => Ok(e), + FunctionErrorKind::Builtin(BuiltinError::$variant(e)) => Ok(e), _ => Err(()), } } diff --git a/rust/src/nasl/builtin/host/mod.rs b/rust/src/nasl/builtin/host/mod.rs index f61a77a8b..8a941ea79 100644 --- a/rust/src/nasl/builtin/host/mod.rs +++ b/rust/src/nasl/builtin/host/mod.rs @@ -8,7 +8,7 @@ mod tests; use std::{net::IpAddr, str::FromStr}; use crate::function_set; -use crate::nasl::utils::{error::NaslError, lookup_keys::TARGET}; +use crate::nasl::utils::{error::FunctionErrorKind, lookup_keys::TARGET}; use crate::nasl::syntax::NaslValue; use crate::nasl::utils::{Context, ContextType, Register}; @@ -17,7 +17,7 @@ use crate::nasl::utils::{Context, ContextType, Register}; /// /// It does lookup TARGET and when not found falls back to 127.0.0.1 to resolve. /// If the TARGET is not a IP address than we assume that it already is a fqdn or a hostname and will return that instead. -fn resolve_hostname(register: &Register) -> Result { +fn resolve_hostname(register: &Register) -> Result { use std::net::ToSocketAddrs; let default_ip = "127.0.0.1"; @@ -41,7 +41,7 @@ fn resolve_hostname(register: &Register) -> Result { /// /// As of now (2023-01-20) there is no vhost handling. /// Therefore this function does load the registered TARGET and if it is an IP Address resolves it via DNS instead. -fn get_host_names(register: &Register, _: &Context) -> Result { +fn get_host_names(register: &Register, _: &Context) -> Result { resolve_hostname(register).map(|x| NaslValue::Array(vec![NaslValue::String(x)])) } @@ -49,12 +49,12 @@ fn get_host_names(register: &Register, _: &Context) -> Result Result { +fn get_host_name(register: &Register, _: &Context) -> Result { resolve_hostname(register).map(NaslValue::String) } /// Return the target's IP address as IpAddr. -pub fn get_host_ip(context: &Context) -> Result { +pub fn get_host_ip(context: &Context) -> Result { let default_ip = "127.0.0.1"; let r_sock_addr = match context.target() { x if !x.is_empty() => IpAddr::from_str(x), @@ -63,7 +63,7 @@ pub fn get_host_ip(context: &Context) -> Result { match r_sock_addr { Ok(x) => Ok(x), - Err(e) => Err(NaslError::wrong_unnamed_argument( + Err(e) => Err(FunctionErrorKind::wrong_unnamed_argument( "IP address", e.to_string().as_str(), )), @@ -71,7 +71,10 @@ pub fn get_host_ip(context: &Context) -> Result { } /// Return the target's IP address or 127.0.0.1 if not set. -fn nasl_get_host_ip(_register: &Register, context: &Context) -> Result { +fn nasl_get_host_ip( + _register: &Register, + context: &Context, +) -> Result { let ip = get_host_ip(context)?; Ok(NaslValue::String(ip.to_string())) } diff --git a/rust/src/nasl/builtin/http/mod.rs b/rust/src/nasl/builtin/http/mod.rs index 585c06ee6..98b59d758 100644 --- a/rust/src/nasl/builtin/http/mod.rs +++ b/rust/src/nasl/builtin/http/mod.rs @@ -35,9 +35,9 @@ pub struct NaslHttp { async fn lock_handles( handles: &Arc>>, -) -> Result>, NaslError> { +) -> Result>, FunctionErrorKind> { // we actually need to panic as a lock error is fatal - // alternatively we need to add a poison error on NaslError + // alternatively we need to add a poison error on FunctionErrorKind Ok(Arc::as_ref(handles).lock().await) } @@ -131,7 +131,7 @@ impl NaslHttp { data: String, method: Method, handle: &mut Handle, - ) -> Result<(Parts, String), NaslError> { + ) -> Result<(Parts, String), FunctionErrorKind> { // Establish TCP connection to the server. let mut config = ClientConfig::builder() @@ -148,20 +148,31 @@ impl NaslHttp { let stream = match TcpStream::connect(format!("{}:{}", ip_str, port)).await { Ok(a) => a, Err(e) => { - return Err(NaslError::Diagnostic(e.to_string(), Some(NaslValue::Null))); + return Err(FunctionErrorKind::Diagnostic( + e.to_string(), + Some(NaslValue::Null), + )); } }; let stream = match connector.connect(server_name, stream).await { Ok(a) => a, Err(e) => { - return Err(NaslError::Diagnostic(e.to_string(), Some(NaslValue::Null))); + return Err(FunctionErrorKind::Diagnostic( + e.to_string(), + Some(NaslValue::Null), + )); } }; let (h2, connection) = match client::handshake(stream).await { Ok((x, y)) => (x, y), - Err(e) => return Err(NaslError::Diagnostic(e.to_string(), Some(NaslValue::Null))), + Err(e) => { + return Err(FunctionErrorKind::Diagnostic( + e.to_string(), + Some(NaslValue::Null), + )) + } }; tokio::spawn(async move { @@ -170,7 +181,12 @@ impl NaslHttp { let mut h2 = match h2.ready().await { Ok(x) => x, - Err(e) => return Err(NaslError::Diagnostic(e.to_string(), Some(NaslValue::Null))), + Err(e) => { + return Err(FunctionErrorKind::Diagnostic( + e.to_string(), + Some(NaslValue::Null), + )) + } }; // Prepare the HTTP request to send to the server. @@ -200,7 +216,12 @@ impl NaslHttp { while let Some(chunk) = body.data().await { let chunk = match chunk { Ok(byte_chunk) => byte_chunk, - Err(e) => return Err(NaslError::Diagnostic(e.to_string(), Some(NaslValue::Null))), + Err(e) => { + return Err(FunctionErrorKind::Diagnostic( + e.to_string(), + Some(NaslValue::Null), + )) + } }; resp.push_str(&String::from_utf8_lossy(&chunk)); @@ -217,7 +238,7 @@ impl NaslHttp { register: &Register, ctx: &Context<'a>, method: Method, - ) -> Result { + ) -> Result { let handle_id = match register.named("handle") { Some(ContextType::Value(NaslValue::Number(x))) => *x as i32, _ => { @@ -233,7 +254,7 @@ impl NaslHttp { { Some((_i, handle)) => handle, _ => { - return Err(NaslError::Diagnostic( + return Err(FunctionErrorKind::Diagnostic( format!("Handle ID {} not found", handle_id), Some(NaslValue::Null), )) @@ -243,7 +264,7 @@ impl NaslHttp { let item: String = match register.named("item") { Some(x) => x.to_string(), _ => { - return Err(NaslError::Diagnostic( + return Err(FunctionErrorKind::Diagnostic( "Missing item".to_string(), Some(NaslValue::Null), )) @@ -311,7 +332,7 @@ impl NaslHttp { &self, register: &Register, ctx: &Context<'a>, - ) -> Result { + ) -> Result { self.http2_req(register, ctx, Method::GET).await } @@ -320,7 +341,7 @@ impl NaslHttp { &self, register: &Register, ctx: &Context<'a>, - ) -> Result { + ) -> Result { self.http2_req(register, ctx, Method::POST).await } @@ -329,7 +350,7 @@ impl NaslHttp { &self, register: &Register, ctx: &Context<'a>, - ) -> Result { + ) -> Result { self.http2_req(register, ctx, Method::PUT).await } @@ -338,7 +359,7 @@ impl NaslHttp { &self, register: &Register, ctx: &Context<'a>, - ) -> Result { + ) -> Result { self.http2_req(register, ctx, Method::HEAD).await } @@ -347,7 +368,7 @@ impl NaslHttp { &self, register: &Register, ctx: &Context<'a>, - ) -> Result { + ) -> Result { self.http2_req(register, ctx, Method::DELETE).await } @@ -358,7 +379,7 @@ impl NaslHttp { /// On success the function returns a and integer with the handle /// identifier. Null on error. #[nasl_function] - async fn handle(&self) -> Result { + async fn handle(&self) -> Result { let mut handles = lock_handles(&self.handles).await?; let handle_id = next_handle_id(&handles); let h = Handle { @@ -378,7 +399,7 @@ impl NaslHttp { /// The function returns an integer. /// O on success, -1 on error. #[nasl_function(named(handle))] - async fn close_handle(&self, handle: i32) -> Result { + async fn close_handle(&self, handle: i32) -> Result { let mut handles = lock_handles(&self.handles).await?; match handles .iter_mut() @@ -389,7 +410,7 @@ impl NaslHttp { handles.remove(i); Ok(NaslValue::Number(0)) } - _ => Err(NaslError::Diagnostic( + _ => Err(FunctionErrorKind::Diagnostic( format!("Handle ID {} not found", handle), Some(NaslValue::Number(-1)), )), @@ -406,7 +427,7 @@ impl NaslHttp { &self, register: &Register, _: &Context<'_>, - ) -> Result { + ) -> Result { let handle_id = match register.named("handle") { Some(ContextType::Value(NaslValue::Number(x))) => *x as i32, _ => { @@ -421,7 +442,7 @@ impl NaslHttp { .find(|(_i, h)| h.handle_id == handle_id) { Some((_i, handle)) => Ok(NaslValue::Number(handle.http_code as i64)), - _ => Err(NaslError::Diagnostic( + _ => Err(FunctionErrorKind::Diagnostic( format!("Handle ID {} not found", handle_id), Some(NaslValue::Null), )), @@ -438,10 +459,10 @@ impl NaslHttp { &self, register: &Register, _: &Context<'_>, - ) -> Result { + ) -> Result { let header_item = match register.named("header_item") { Some(ContextType::Value(NaslValue::String(x))) => x, - _ => return Err(NaslError::missing_argument("No command passed")), + _ => return Err(FunctionErrorKind::missing_argument("No command passed")), }; let (key, val) = header_item.split_once(": ").expect("Missing header_item"); @@ -463,7 +484,7 @@ impl NaslHttp { h.header_items.push((key.to_string(), val.to_string())); Ok(NaslValue::Number(0)) } - _ => Err(NaslError::Diagnostic( + _ => Err(FunctionErrorKind::Diagnostic( format!("Handle ID {} not found", handle_id), Some(NaslValue::Null), )), diff --git a/rust/src/nasl/builtin/isotime/mod.rs b/rust/src/nasl/builtin/isotime/mod.rs index a5e75ebbc..5f9543fd0 100644 --- a/rust/src/nasl/builtin/isotime/mod.rs +++ b/rust/src/nasl/builtin/isotime/mod.rs @@ -41,14 +41,14 @@ fn parse_readable_time(time: &str) -> Option { None } -fn parse_time(time: &str) -> Result { +fn parse_time(time: &str) -> Result { if let Some(time) = parse_isotime(time) { return Ok(time); } if let Some(time) = parse_readable_time(time) { return Ok(time); } - Err(NaslError::Diagnostic( + Err(FunctionErrorKind::Diagnostic( format!( "The given time is not in the correct isotime ({}) or readable time format ({}): {}", ISOFORMAT, READABLEFORMAT, time @@ -63,7 +63,7 @@ fn isotime_add( years: Option, days: Option, seconds: Option, -) -> Result { +) -> Result { let mut time = parse_time(time)?; if let Some(years) = years { @@ -83,7 +83,7 @@ fn isotime_add( } if time.year() < 0 || time.year() > 9999 { - return Err(NaslError::Diagnostic( + return Err(FunctionErrorKind::Diagnostic( format!( "The resulting year is out of range (0000-9999): {}.", time.year() @@ -106,12 +106,12 @@ fn isotime_now() -> String { } #[nasl_function] -fn isotime_print(time: &str) -> Result { +fn isotime_print(time: &str) -> Result { Ok(parse_time(time)?.format("%Y-%m-%d %H:%M:%S").to_string()) } #[nasl_function] -fn isotime_scan(time: &str) -> Result { +fn isotime_scan(time: &str) -> Result { let time = parse_time(time)?; Ok(time.format("%Y%m%dT%H%M%S").to_string()) diff --git a/rust/src/nasl/builtin/isotime/tests.rs b/rust/src/nasl/builtin/isotime/tests.rs index cc5fc21f6..eaf6d86a3 100644 --- a/rust/src/nasl/builtin/isotime/tests.rs +++ b/rust/src/nasl/builtin/isotime/tests.rs @@ -21,22 +21,22 @@ mod tests { #[test] fn isotime_scan() { - check_err_matches!("isotime_scan(\"\");", NaslError::Diagnostic { .. }); + check_err_matches!("isotime_scan(\"\");", FunctionErrorKind::Diagnostic { .. }); check_err_matches!( "isotime_scan(\"a8691002T123456\");", - NaslError::Diagnostic { .. } + FunctionErrorKind::Diagnostic { .. } ); check_err_matches!( "isotime_scan(\"18691002T1234\");", - NaslError::Diagnostic { .. } + FunctionErrorKind::Diagnostic { .. } ); check_err_matches!( "isotime_scan(\"18691002T1234512\");", - NaslError::Diagnostic { .. } + FunctionErrorKind::Diagnostic { .. } ); check_err_matches!( "isotime_scan(\"1869-10-02T12:34:56\");", - NaslError::Diagnostic { .. } + FunctionErrorKind::Diagnostic { .. } ); check_code_result("isotime_scan(\"18691002T123456\");", "18691002T123456"); @@ -47,18 +47,18 @@ mod tests { #[test] fn isotime_print() { - check_err_matches!("isotime_print(\"\");", NaslError::Diagnostic { .. }); + check_err_matches!("isotime_print(\"\");", FunctionErrorKind::Diagnostic { .. }); check_err_matches!( "isotime_print(\"a8691002T123456\");", - NaslError::Diagnostic { .. } + FunctionErrorKind::Diagnostic { .. } ); check_err_matches!( "isotime_print(\"18691002T1234\");", - NaslError::Diagnostic { .. } + FunctionErrorKind::Diagnostic { .. } ); check_err_matches!( "isotime_print(\"1869-10-02T12:34:56\");", - NaslError::Diagnostic { .. } + FunctionErrorKind::Diagnostic { .. } ); check_code_result("isotime_print(\"18691002T123456\");", "1869-10-02 12:34:56"); @@ -76,14 +76,17 @@ mod tests { #[test] fn isotime_add() { - check_err_matches!("isotime_add(\"\", years: 0);", NaslError::Diagnostic { .. }); + check_err_matches!( + "isotime_add(\"\", years: 0);", + FunctionErrorKind::Diagnostic { .. } + ); check_err_matches!( "isotime_add(\"50001002T120000\", years: 5000);", - NaslError::Diagnostic { .. } + FunctionErrorKind::Diagnostic { .. } ); check_err_matches!( "isotime_add(\"50001002T120000\", years: -5001);", - NaslError::Diagnostic { .. } + FunctionErrorKind::Diagnostic { .. } ); check_code_result( diff --git a/rust/src/nasl/builtin/knowledge_base/mod.rs b/rust/src/nasl/builtin/knowledge_base/mod.rs index 7ab8c66d2..296fd6a83 100644 --- a/rust/src/nasl/builtin/knowledge_base/mod.rs +++ b/rust/src/nasl/builtin/knowledge_base/mod.rs @@ -9,7 +9,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; use crate::function_set; use crate::nasl::syntax::NaslValue; -use crate::nasl::utils::error::NaslError; +use crate::nasl::utils::error::FunctionErrorKind; use crate::nasl::utils::Context; use crate::storage::{Field, Kb, Retrieve}; use nasl_function_proc_macro::nasl_function; @@ -22,13 +22,13 @@ fn set_kb_item( name: NaslValue, value: NaslValue, expires: Option, -) -> Result { +) -> Result { let expires = match expires { Some(NaslValue::Number(x)) => Some(x), Some(NaslValue::Exit(0)) => None, None => None, Some(x) => { - return Err(NaslError::Diagnostic( + return Err(FunctionErrorKind::Diagnostic( format!("expected expires to be a number but is {x}."), None, )) @@ -56,7 +56,7 @@ fn set_kb_item( /// NASL function to get a knowledge base #[nasl_function] -fn get_kb_item(c: &Context, key: &str) -> Result { +fn get_kb_item(c: &Context, key: &str) -> Result { c.retriever() .retrieve(c.key(), Retrieve::KB(key.to_string())) .map(|r| { @@ -73,7 +73,11 @@ fn get_kb_item(c: &Context, key: &str) -> Result { /// NASL function to replace a kb list #[nasl_function(named(name, value))] -fn replace_kb_item(c: &Context, name: NaslValue, value: NaslValue) -> Result { +fn replace_kb_item( + c: &Context, + name: NaslValue, + value: NaslValue, +) -> Result { c.dispatcher() .dispatch_replace( c.key(), @@ -89,7 +93,7 @@ fn replace_kb_item(c: &Context, name: NaslValue, value: NaslValue) -> Result Result { +fn get_kb_list(c: &Context, key: NaslValue) -> Result { c.retriever() .retrieve(c.key(), Retrieve::KB(key.to_string())) .map(|r| { diff --git a/rust/src/nasl/builtin/network/mod.rs b/rust/src/nasl/builtin/network/mod.rs index eeaedebcc..3a09e6e42 100644 --- a/rust/src/nasl/builtin/network/mod.rs +++ b/rust/src/nasl/builtin/network/mod.rs @@ -74,7 +74,7 @@ impl Display for OpenvasEncaps { } } -pub fn get_kb_item(context: &Context, name: &str) -> Result, NaslError> { +pub fn get_kb_item(context: &Context, name: &str) -> Result, FunctionErrorKind> { context .retriever() .retrieve(context.key(), Retrieve::KB(name.to_string())) diff --git a/rust/src/nasl/builtin/network/network.rs b/rust/src/nasl/builtin/network/network.rs index 003692176..33f3915bf 100644 --- a/rust/src/nasl/builtin/network/network.rs +++ b/rust/src/nasl/builtin/network/network.rs @@ -11,7 +11,7 @@ use super::{ verify_port, DEFAULT_PORT, }; use crate::function_set; -use crate::nasl::utils::{Context, NaslError}; +use crate::nasl::utils::{Context, FunctionErrorKind}; use crate::storage::{types::Primitive, Field, Kb}; use nasl_function_proc_macro::nasl_function; @@ -132,7 +132,11 @@ fn islocalnet(context: &Context) -> Result { /// Declares an open port on the target host #[nasl_function(named(port, proto))] -fn scanner_add_port(context: &Context, port: i64, proto: Option<&str>) -> Result<(), NaslError> { +fn scanner_add_port( + context: &Context, + port: i64, + proto: Option<&str>, +) -> Result<(), FunctionErrorKind> { let port = verify_port(port)?; let protocol = proto.unwrap_or("tcp"); diff --git a/rust/src/nasl/builtin/network/socket.rs b/rust/src/nasl/builtin/network/socket.rs index 8e22ec7c8..cf81a770c 100644 --- a/rust/src/nasl/builtin/network/socket.rs +++ b/rust/src/nasl/builtin/network/socket.rs @@ -297,7 +297,7 @@ impl NaslSockets { data: &[u8], flags: Option, len: Option, - ) -> Result { + ) -> Result { let len = if let Some(len) = len { if len < 1 || len > data.len() { data.len() @@ -381,7 +381,7 @@ impl NaslSockets { len: usize, min: Option, timeout: Option, - ) -> Result { + ) -> Result { let min = min .map(|min| if min < 0 { len } else { min as usize }) .unwrap_or(len); @@ -473,7 +473,7 @@ impl NaslSockets { /// - Secret/kdc_port /// - Secret/kdc_use_tcp #[nasl_function] - fn open_sock_kdc(&self, context: &Context) -> Result { + fn open_sock_kdc(&self, context: &Context) -> Result { let hostname = match get_kb_item(context, "Secret/kdc_hostname")? { Some(x) => Ok(x.to_string()), None => Err(SocketError::Diagnostic( @@ -556,7 +556,7 @@ impl NaslSockets { bufsz: Option, // TODO: Extract information from custom priority string // priority: Option<&str>, - ) -> Result { + ) -> Result { // Get port let port = verify_port(port)?; let transport = transport.unwrap_or(-1); @@ -657,7 +657,7 @@ impl NaslSockets { bufsz: Option, timeout: Duration, tls_config: Option, - ) -> Result { + ) -> Result { let addr = ipstr2ipaddr(addr)?; let mut retry = super::get_kb_item(context, "timeout_retry")? .map(|val| match val { @@ -717,7 +717,7 @@ impl NaslSockets { bufsz: Option, timeout: Duration, hostname: &str, - ) -> Result { + ) -> Result { let cert_path = get_kb_item(context, "SSL/cert")? .ok_or(SocketError::Diagnostic( "unable to open TLS connection: kes 'SSL/cert' is missing".to_string(), @@ -796,7 +796,7 @@ impl NaslSockets { /// Open a UDP socket to the target host #[nasl_function] - fn open_sock_udp(&self, context: &Context, port: i64) -> Result { + fn open_sock_udp(&self, context: &Context, port: i64) -> Result { let port = verify_port(port)?; let addr = ipstr2ipaddr(context.target())?; diff --git a/rust/src/nasl/builtin/raw_ip/frame_forgery.rs b/rust/src/nasl/builtin/raw_ip/frame_forgery.rs index 6656cec9f..2724ea750 100644 --- a/rust/src/nasl/builtin/raw_ip/frame_forgery.rs +++ b/rust/src/nasl/builtin/raw_ip/frame_forgery.rs @@ -105,11 +105,11 @@ impl From<&Frame> for Vec { } impl TryFrom<&[u8]> for Frame { - type Error = NaslError; + type Error = FunctionErrorKind; fn try_from(f: &[u8]) -> Result { if f.len() < 14 { - Err(NaslError::missing_argument("valid ip address")) + Err(FunctionErrorKind::missing_argument("valid ip address")) } else { let mut frame = Frame::new(); frame.set_dsthaddr(MacAddr(f[0], f[1], f[2], f[3], f[4], f[5])); @@ -272,13 +272,15 @@ fn convert_vec_into_mac_address(v: &[u8]) -> Option { } } -fn validate_mac_address(v: Option<&ContextType>) -> Result { +fn validate_mac_address(v: Option<&ContextType>) -> Result { let mac_addr = match v { Some(ContextType::Value(NaslValue::String(x))) => MacAddr::from_str(x).ok(), Some(ContextType::Value(NaslValue::Data(x))) => convert_vec_into_mac_address(x), _ => None, }; - mac_addr.ok_or_else(|| NaslError::wrong_unnamed_argument("mac address", "invalid mac address")) + mac_addr.ok_or_else(|| { + FunctionErrorKind::wrong_unnamed_argument("mac address", "invalid mac address") + }) } /// Return the MAC address, given the interface name @@ -291,7 +293,7 @@ fn get_local_mac_address(name: &str) -> Option { /// Return a frame given a capture device and a filter. It returns an empty frame in case /// there was no response or anything was filtered. -fn recv_frame(cap: &mut Capture, filter: &str) -> Result { +fn recv_frame(cap: &mut Capture, filter: &str) -> Result { let f = Frame::new(); let p = match cap.filter(filter, true) { @@ -311,7 +313,7 @@ fn send_frame( pcap_active: &bool, filter: Option<&String>, timeout: i32, -) -> Result, NaslError> { +) -> Result, FunctionErrorKind> { let mut capture_dev = match Capture::from_device(iface.clone()) { Ok(c) => match c.promisc(true).timeout(timeout).open() { Ok(mut capture) => match capture.sendpacket(frame) { @@ -344,12 +346,15 @@ fn send_frame( /// /// It takes the following argument: /// - cap_timeout: time to wait for answer in seconds, 5 by default -fn nasl_send_arp_request(register: &Register, context: &Context) -> Result { +fn nasl_send_arp_request( + register: &Register, + context: &Context, +) -> Result { let timeout = match register.named("pcap_timeout") { Some(ContextType::Value(NaslValue::Number(x))) => *x as i32 * 1000i32, // to milliseconds None => DEFAULT_TIMEOUT, _ => { - return Err(NaslError::wrong_unnamed_argument( + return Err(FunctionErrorKind::wrong_unnamed_argument( "Integer", "Invalid timeout value", )) @@ -359,7 +364,7 @@ fn nasl_send_arp_request(register: &Register, context: &Context) -> Result Result x, _ => { - return Err(NaslError::missing_argument( + return Err(FunctionErrorKind::missing_argument( "Not possible to get a src mac address.", )) } @@ -378,7 +383,7 @@ fn nasl_send_arp_request(register: &Register, context: &Context) -> Result x, Err(_) => { - return Err(NaslError::missing_argument( + return Err(FunctionErrorKind::missing_argument( "Not possible to parse the src IP address.", )) } @@ -387,7 +392,7 @@ fn nasl_send_arp_request(register: &Register, context: &Context) -> Result x, Err(_) => { - return Err(NaslError::missing_argument( + return Err(FunctionErrorKind::missing_argument( "Not possible to parse the dst IP address.", )) } @@ -407,7 +412,7 @@ fn nasl_send_arp_request(register: &Register, context: &Context) -> Result Result { +) -> Result { let positional = register.positional(); if positional.is_empty() { return Err(ArgumentError::MissingPositionals { @@ -423,7 +428,7 @@ fn nasl_get_local_mac_address_from_ip( let iface = get_interface_by_local_ip(ip)?; match get_local_mac_address(&iface.name) { Some(mac) => Ok(NaslValue::String(mac.to_string())), - _ => Err(NaslError::Diagnostic( + _ => Err(FunctionErrorKind::Diagnostic( "Not possible to get the local mac address".to_string(), Some(NaslValue::Null), )), @@ -442,7 +447,7 @@ fn nasl_get_local_mac_address_from_ip( /// - ether_proto: is an int containing the ethernet type (normally given as hexadecimal). /// It is optional and its default value is 0x0800. A list of Types can be e.g. looked up here. /// - payload: is any data, which is then attached as payload to the frame. -fn nasl_forge_frame(register: &Register, _: &Context) -> Result { +fn nasl_forge_frame(register: &Register, _: &Context) -> Result { let src_haddr = validate_mac_address(register.named("src_haddr"))?; let dst_haddr = validate_mac_address(register.named("dst_haddr"))?; let ether_proto = match register.named("ether_proto") { @@ -470,11 +475,11 @@ fn nasl_forge_frame(register: &Register, _: &Context) -> Result Result { +fn nasl_send_frame(register: &Register, context: &Context) -> Result { let frame = match register.named("frame") { Some(ContextType::Value(NaslValue::Data(x))) => x, _ => { - return Err(NaslError::wrong_unnamed_argument( + return Err(FunctionErrorKind::wrong_unnamed_argument( "Data", "Invalid data type", )) @@ -485,7 +490,7 @@ fn nasl_send_frame(register: &Register, context: &Context) -> Result x, None => &true, _ => { - return Err(NaslError::wrong_unnamed_argument( + return Err(FunctionErrorKind::wrong_unnamed_argument( "Boolean", "Invalid pcap_active value", )) @@ -496,7 +501,7 @@ fn nasl_send_frame(register: &Register, context: &Context) -> Result Some(x), None => None, _ => { - return Err(NaslError::wrong_unnamed_argument( + return Err(FunctionErrorKind::wrong_unnamed_argument( "String", "Invalid pcap_filter value", )) @@ -507,7 +512,7 @@ fn nasl_send_frame(register: &Register, context: &Context) -> Result *x as i32 * 1000i32, // to milliseconds None => DEFAULT_TIMEOUT, _ => { - return Err(NaslError::wrong_unnamed_argument( + return Err(FunctionErrorKind::wrong_unnamed_argument( "Integer", "Invalid timeout value", )) @@ -529,11 +534,11 @@ fn nasl_send_frame(register: &Register, context: &Context) -> Result Result { +fn nasl_dump_frame(register: &Register, _: &Context) -> Result { let frame: Frame = match register.named("frame") { Some(ContextType::Value(NaslValue::Data(x))) => (x as &[u8]).try_into()?, _ => { - return Err(NaslError::wrong_unnamed_argument( + return Err(FunctionErrorKind::wrong_unnamed_argument( "Data", "Invalid data type", )) diff --git a/rust/src/nasl/builtin/raw_ip/packet_forgery.rs b/rust/src/nasl/builtin/raw_ip/packet_forgery.rs index f9efeba2d..601363fdb 100644 --- a/rust/src/nasl/builtin/raw_ip/packet_forgery.rs +++ b/rust/src/nasl/builtin/raw_ip/packet_forgery.rs @@ -41,13 +41,13 @@ pub enum PacketForgeryError { Custom(String), } -fn error(s: String) -> NaslError { +fn error(s: String) -> FunctionErrorKind { PacketForgeryError::Custom(s).into() } macro_rules! custom_error { ($a:expr, $b:expr) => { - Err(NaslError::Diagnostic( + Err(FunctionErrorKind::Diagnostic( format!($a, $b), Some(NaslValue::Null), )) @@ -99,7 +99,7 @@ fn safe_copy_from_slice( o_buf: &[u8], o_init: usize, o_fin: usize, -) -> Result<(), NaslError> { +) -> Result<(), FunctionErrorKind> { let o_range = o_fin - o_init; let d_range = d_fin - d_init; if d_buf.len() < d_range @@ -132,7 +132,7 @@ fn safe_copy_from_slice( /// - ip_v is: the IP version. 4 by default. /// /// Returns the IP datagram or NULL on error. -fn forge_ip_packet(register: &Register, configs: &Context) -> Result { +fn forge_ip_packet(register: &Register, configs: &Context) -> Result { let dst_addr = get_host_ip(configs)?; if dst_addr.is_ipv6() { @@ -153,7 +153,7 @@ fn forge_ip_packet(register: &Register, configs: &Context) -> Result Result Result { +fn set_ip_elements( + register: &Register, + _configs: &Context, +) -> Result { let mut buf = match register.named("ip") { Some(ContextType::Value(NaslValue::Data(d))) => d.clone(), _ => { - return Err(NaslError::missing_argument("ip")); + return Err(FunctionErrorKind::missing_argument("ip")); } }; let mut pkt = packet::ipv4::MutableIpv4Packet::new(&mut buf).ok_or_else(|| { - NaslError::Diagnostic( + FunctionErrorKind::Diagnostic( "No possible to create a packet from buffer".to_string(), None, ) @@ -368,11 +371,11 @@ fn set_ip_elements(register: &Register, _configs: &Context) -> Result Result { +fn get_ip_element(register: &Register, _configs: &Context) -> Result { let buf = match register.named("ip") { Some(ContextType::Value(NaslValue::Data(d))) => d.clone(), _ => { - return Err(NaslError::missing_argument("ip")); + return Err(FunctionErrorKind::missing_argument("ip")); } }; @@ -394,12 +397,12 @@ fn get_ip_element(register: &Register, _configs: &Context) -> Result Ok(NaslValue::String(pkt.get_destination().to_string())), _ => Err(ArgumentError::WrongArgument("Invalid element".to_string()).into()), }, - _ => Err(NaslError::missing_argument("element")), + _ => Err(FunctionErrorKind::missing_argument("element")), } } /// Receive a list of IP packets and print them in a readable format in the screen. -fn dump_ip_packet(register: &Register, _: &Context) -> Result { +fn dump_ip_packet(register: &Register, _: &Context) -> Result { let positional = register.positional(); if positional.is_empty() { return Err(ArgumentError::MissingPositionals { @@ -455,31 +458,34 @@ fn dump_protocol(pkt: &Ipv4Packet) -> String { /// - code: is the identifier of the option to add /// - length: is the length of the option data /// - value: is the option data -fn insert_ip_options(register: &Register, _configs: &Context) -> Result { +fn insert_ip_options( + register: &Register, + _configs: &Context, +) -> Result { let buf = match register.named("ip") { Some(ContextType::Value(NaslValue::Data(d))) => d.clone(), _ => { - return Err(NaslError::missing_argument("ip")); + return Err(FunctionErrorKind::missing_argument("ip")); } }; let code = match register.named("code") { Some(ContextType::Value(NaslValue::Number(x))) => *x, _ => { - return Err(NaslError::missing_argument("code")); + return Err(FunctionErrorKind::missing_argument("code")); } }; let length = match register.named("length") { Some(ContextType::Value(NaslValue::Number(x))) => *x as usize, _ => { - return Err(NaslError::missing_argument("length")); + return Err(FunctionErrorKind::missing_argument("length")); } }; let value = match register.named("value") { Some(ContextType::Value(NaslValue::String(x))) => x.as_bytes(), Some(ContextType::Value(NaslValue::Data(x))) => x, _ => { - return Err(NaslError::missing_argument("value")); + return Err(FunctionErrorKind::missing_argument("value")); } }; @@ -548,12 +554,15 @@ fn insert_ip_options(register: &Register, _configs: &Context) -> Result Result { +fn forge_tcp_packet( + register: &Register, + _configs: &Context, +) -> Result { let mut ip_buf = match register.named("ip") { Some(ContextType::Value(NaslValue::Data(d))) => d.clone(), _ => { // Missingarguments - return Err(NaslError::missing_argument("ip")); + return Err(FunctionErrorKind::missing_argument("ip")); } }; let original_ip_len = ip_buf.len(); @@ -663,11 +672,14 @@ fn forge_tcp_packet(register: &Register, _configs: &Context) -> Result Result { +fn get_tcp_element( + register: &Register, + _configs: &Context, +) -> Result { let buf = match register.named("tcp") { Some(ContextType::Value(NaslValue::Data(d))) => d.clone(), _ => { - return Err(NaslError::missing_argument("tcp")); + return Err(FunctionErrorKind::missing_argument("tcp")); } }; @@ -691,7 +703,7 @@ fn get_tcp_element(register: &Register, _configs: &Context) -> Result Ok(NaslValue::Data(tcp.payload().to_vec())), _ => Err(ArgumentError::WrongArgument("element".to_string()).into()), }, - _ => Err(NaslError::missing_argument("element")), + _ => Err(FunctionErrorKind::missing_argument("element")), } } @@ -706,11 +718,11 @@ fn get_tcp_element(register: &Register, _configs: &Context) -> Result Result { +fn get_tcp_option(register: &Register, _configs: &Context) -> Result { let buf = match register.named("tcp") { Some(ContextType::Value(NaslValue::Data(d))) => d.clone(), _ => { - return Err(NaslError::missing_argument("tcp")); + return Err(FunctionErrorKind::missing_argument("tcp")); } }; @@ -761,7 +773,7 @@ fn get_tcp_option(register: &Register, _configs: &Context) -> Result Ok(NaslValue::Array(timestamps)), _ => Err(ArgumentError::WrongArgument("Invalid option".to_string()).into()), }, - _ => Err(NaslError::missing_argument("option")), + _ => Err(FunctionErrorKind::missing_argument("option")), } } @@ -780,11 +792,14 @@ fn get_tcp_option(register: &Register, _configs: &Context) -> Result Result { +fn set_tcp_elements( + register: &Register, + _configs: &Context, +) -> Result { let buf = match register.named("tcp") { Some(ContextType::Value(NaslValue::Data(d))) => d.clone(), _ => { - return Err(NaslError::missing_argument("tcp")); + return Err(FunctionErrorKind::missing_argument("tcp")); } }; @@ -916,7 +931,10 @@ fn set_tcp_elements(register: &Register, _configs: &Context) -> Result Result { +fn insert_tcp_options( + register: &Register, + _configs: &Context, +) -> Result { let buf = match register.named("tcp") { Some(ContextType::Value(NaslValue::Data(d))) => d.clone(), _ => { @@ -1095,7 +1113,7 @@ fn insert_tcp_options(register: &Register, _configs: &Context) -> Result Result { +fn dump_tcp_packet(register: &Register, _: &Context) -> Result { let positional = register.positional(); if positional.is_empty() { return Err(error( @@ -1197,10 +1215,13 @@ fn format_flags(pkt: &TcpPacket) -> String { /// - update_ip_len: is a flag (TRUE by default). If set, NASL will recompute the size field of the IP datagram. /// /// Returns the modified IP datagram or NULL on error. -fn forge_udp_packet(register: &Register, _configs: &Context) -> Result { +fn forge_udp_packet( + register: &Register, + _configs: &Context, +) -> Result { let mut ip_buf = match register.named("ip") { Some(ContextType::Value(NaslValue::Data(d))) => d.clone(), - _ => return Err(NaslError::missing_argument("ip")), + _ => return Err(FunctionErrorKind::missing_argument("ip")), }; let original_ip_len = ip_buf.len(); @@ -1275,11 +1296,14 @@ fn forge_udp_packet(register: &Register, _configs: &Context) -> Result Result { +fn set_udp_elements( + register: &Register, + _configs: &Context, +) -> Result { let buf = match register.named("udp") { Some(ContextType::Value(NaslValue::Data(d))) => d.clone(), _ => { - return Err(NaslError::missing_argument("udp")); + return Err(FunctionErrorKind::missing_argument("udp")); } }; @@ -1376,7 +1400,7 @@ fn set_udp_elements(register: &Register, _configs: &Context) -> Result Result { +fn dump_udp_packet(register: &Register, _: &Context) -> Result { let positional = register.positional(); if positional.is_empty() { return Err(error( @@ -1428,11 +1452,14 @@ fn dump_udp_packet(register: &Register, _: &Context) -> Result Result { +fn get_udp_element( + register: &Register, + _configs: &Context, +) -> Result { let buf = match register.named("udp") { Some(ContextType::Value(NaslValue::Data(d))) => d.clone(), _ => { - return Err(NaslError::missing_argument("udp")); + return Err(FunctionErrorKind::missing_argument("udp")); } }; @@ -1463,11 +1490,14 @@ fn get_udp_element(register: &Register, _configs: &Context) -> Result Result { +fn forge_icmp_packet( + register: &Register, + _configs: &Context, +) -> Result { let mut ip_buf = match register.named("ip") { Some(ContextType::Value(NaslValue::Data(d))) => d.clone(), _ => { - return Err(NaslError::missing_argument("icmp")); + return Err(FunctionErrorKind::missing_argument("icmp")); } }; let original_ip_len = ip_buf.len(); @@ -1554,11 +1584,14 @@ fn forge_icmp_packet(register: &Register, _configs: &Context) -> Result Result { +fn get_icmp_element( + register: &Register, + _configs: &Context, +) -> Result { let buf = match register.named("icmp") { Some(ContextType::Value(NaslValue::Data(d))) => d.clone(), _ => { - return Err(NaslError::missing_argument("icmp")); + return Err(FunctionErrorKind::missing_argument("icmp")); } }; @@ -1605,15 +1638,15 @@ fn get_icmp_element(register: &Register, _configs: &Context) -> Result Ok(NaslValue::Null), }, - _ => Err(NaslError::missing_argument("element")), + _ => Err(FunctionErrorKind::missing_argument("element")), } } /// Receive a list of IPv4 ICMP packets and print them in a readable format in the screen. -fn dump_icmp_packet(register: &Register, _: &Context) -> Result { +fn dump_icmp_packet(register: &Register, _: &Context) -> Result { let positional = register.positional(); if positional.is_empty() { - return Err(NaslError::missing_argument("icmp")); + return Err(FunctionErrorKind::missing_argument("icmp")); } for icmp_pkt in positional.iter() { @@ -1736,11 +1769,14 @@ pub mod igmp { /// - group: IGMP group /// - type: IGMP type. 0 by default. /// - update_ip_len: If this flag is set, NASL will recompute the size field of the IP datagram. Default: True. -fn forge_igmp_packet(register: &Register, _configs: &Context) -> Result { +fn forge_igmp_packet( + register: &Register, + _configs: &Context, +) -> Result { let mut ip_buf = match register.named("ip") { Some(ContextType::Value(NaslValue::Data(d))) => d.clone(), _ => { - return Err(NaslError::missing_argument("igmp")); + return Err(FunctionErrorKind::missing_argument("igmp")); } }; let original_ip_len = ip_buf.len(); @@ -1799,7 +1835,7 @@ fn forge_igmp_packet(register: &Register, _configs: &Context) -> Result Result Result { +fn new_raw_socket() -> Result { match Socket::new_raw( Domain::IPV4, socket2::Type::RAW, @@ -1832,7 +1868,7 @@ fn new_raw_socket() -> Result { /// /// Its argument is: /// - port: port for the ping -fn nasl_tcp_ping(register: &Register, configs: &Context) -> Result { +fn nasl_tcp_ping(register: &Register, configs: &Context) -> Result { let rnd_tcp_port = || -> u16 { (random_impl().unwrap_or(0) % 65535 + 1024) as u16 }; let sports_ori: Vec = vec![ @@ -1866,7 +1902,7 @@ fn nasl_tcp_ping(register: &Register, configs: &Context) -> Result *x, None => 0, //TODO: implement plug_get_host_open_port() _ => { - return Err(NaslError::wrong_unnamed_argument( + return Err(FunctionErrorKind::wrong_unnamed_argument( "Number", "Invalid length value", )) @@ -1968,12 +2004,15 @@ fn nasl_tcp_ping(register: &Register, configs: &Context) -> Result Result { +fn nasl_send_packet( + register: &Register, + configs: &Context, +) -> Result { let use_pcap = match register.named("pcap_active") { Some(ContextType::Value(NaslValue::Boolean(x))) => *x, None => true, _ => { - return Err(NaslError::wrong_unnamed_argument( + return Err(FunctionErrorKind::wrong_unnamed_argument( "Boolean", "Invalid pcap_active value", )) @@ -1984,7 +2023,7 @@ fn nasl_send_packet(register: &Register, configs: &Context) -> Result x.to_string(), None => String::new(), _ => { - return Err(NaslError::wrong_unnamed_argument( + return Err(FunctionErrorKind::wrong_unnamed_argument( "String", "Invalid pcap_filter value", )) @@ -1995,7 +2034,7 @@ fn nasl_send_packet(register: &Register, configs: &Context) -> Result *x as i32 * 1000i32, // to milliseconds None => DEFAULT_TIMEOUT, _ => { - return Err(NaslError::wrong_unnamed_argument( + return Err(FunctionErrorKind::wrong_unnamed_argument( "Integer", "Invalid timeout value", )) @@ -2006,7 +2045,7 @@ fn nasl_send_packet(register: &Register, configs: &Context) -> Result *x, None => false, _ => { - return Err(NaslError::wrong_unnamed_argument( + return Err(FunctionErrorKind::wrong_unnamed_argument( "Boolean", "Invalid allow_broadcast value", )) @@ -2028,7 +2067,7 @@ fn nasl_send_packet(register: &Register, configs: &Context) -> Result *x, None => 0, _ => { - return Err(NaslError::wrong_unnamed_argument( + return Err(FunctionErrorKind::wrong_unnamed_argument( "Number", "Invalid length value", )) @@ -2051,7 +2090,12 @@ fn nasl_send_packet(register: &Register, configs: &Context) -> Result data as &[u8], - _ => return Err(NaslError::wrong_unnamed_argument("Data", "Invalid packet")), + _ => { + return Err(FunctionErrorKind::wrong_unnamed_argument( + "Data", + "Invalid packet", + )) + } }; let packet = packet::ipv4::Ipv4Packet::new(packet_raw) .ok_or_else(|| error("No possible to create a packet from buffer".to_string()))?; @@ -2077,7 +2121,7 @@ fn nasl_send_packet(register: &Register, configs: &Context) -> Result socket2::SockAddr::from(addr), Err(e) => { - return Err(NaslError::Diagnostic( + return Err(FunctionErrorKind::Diagnostic( format!("send_packet: {}", e), Some(NaslValue::Null), )); @@ -2089,7 +2133,7 @@ fn nasl_send_packet(register: &Register, configs: &Context) -> Result { - return Err(NaslError::Diagnostic( + return Err(FunctionErrorKind::Diagnostic( format!("send_packet: {}", e), Some(NaslValue::Null), )); @@ -2116,7 +2160,7 @@ fn nasl_send_packet(register: &Register, configs: &Context) -> Result Result { +fn nasl_pcap_next(register: &Register, configs: &Context) -> Result { nasl_send_capture(register, configs) } @@ -2125,12 +2169,15 @@ fn nasl_pcap_next(register: &Register, configs: &Context) -> Result Result { +fn nasl_send_capture( + register: &Register, + configs: &Context, +) -> Result { let interface = match register.named("interface") { Some(ContextType::Value(NaslValue::String(x))) => x.to_string(), None => String::new(), _ => { - return Err(NaslError::wrong_unnamed_argument( + return Err(FunctionErrorKind::wrong_unnamed_argument( "String", "Invalid interface value", )) @@ -2141,7 +2188,7 @@ fn nasl_send_capture(register: &Register, configs: &Context) -> Result x.to_string(), None => String::new(), _ => { - return Err(NaslError::wrong_unnamed_argument( + return Err(FunctionErrorKind::wrong_unnamed_argument( "String", "Invalid pcap_filter value", )) @@ -2152,7 +2199,7 @@ fn nasl_send_capture(register: &Register, configs: &Context) -> Result *x as i32 * 1000i32, // to milliseconds None => DEFAULT_TIMEOUT, _ => { - return Err(NaslError::wrong_unnamed_argument( + return Err(FunctionErrorKind::wrong_unnamed_argument( "Integer", "Invalid timeout value", )) diff --git a/rust/src/nasl/builtin/raw_ip/raw_ip_utils.rs b/rust/src/nasl/builtin/raw_ip/raw_ip_utils.rs index c59ef6fa1..ae1794023 100644 --- a/rust/src/nasl/builtin/raw_ip/raw_ip_utils.rs +++ b/rust/src/nasl/builtin/raw_ip/raw_ip_utils.rs @@ -8,14 +8,14 @@ use std::{ }; use crate::nasl::syntax::NaslValue; -use crate::nasl::utils::NaslError; +use crate::nasl::utils::FunctionErrorKind; use pcap::{Address, Device}; /// Convert a string in a IpAddr -pub fn ipstr2ipaddr(ip_addr: &str) -> Result { +pub fn ipstr2ipaddr(ip_addr: &str) -> Result { match IpAddr::from_str(ip_addr) { Ok(ip) => Ok(ip), - Err(_) => Err(NaslError::Diagnostic( + Err(_) => Err(FunctionErrorKind::Diagnostic( "Invalid IP address".to_string(), Some(NaslValue::Null), )), @@ -39,7 +39,7 @@ pub fn islocalhost(addr: IpAddr) -> bool { } /// Get the interface from the local ip -pub fn get_interface_by_local_ip(local_address: IpAddr) -> Result { +pub fn get_interface_by_local_ip(local_address: IpAddr) -> Result { // This fake IP is used for matching (and return false) // during the search of the interface in case an interface // doesn't have an associated address. @@ -70,15 +70,18 @@ pub fn get_interface_by_local_ip(local_address: IpAddr) -> Result Ok(dev), - _ => Err(NaslError::Diagnostic( + _ => Err(FunctionErrorKind::Diagnostic( "Invalid ip address".to_string(), None, )), } } -pub fn bind_local_socket(dst: &SocketAddr) -> Result { - let fe = Err(NaslError::Diagnostic("Error binding".to_string(), None)); +pub fn bind_local_socket(dst: &SocketAddr) -> Result { + let fe = Err(FunctionErrorKind::Diagnostic( + "Error binding".to_string(), + None, + )); match dst { SocketAddr::V4(_) => UdpSocket::bind("0.0.0.0:0").or(fe), SocketAddr::V6(_) => UdpSocket::bind(" 0:0:0:0:0:0:0:0:0").or(fe), @@ -86,7 +89,7 @@ pub fn bind_local_socket(dst: &SocketAddr) -> Result { } /// Return the source IP address given the destination IP address -pub fn get_source_ip(dst: IpAddr, port: u16) -> Result { +pub fn get_source_ip(dst: IpAddr, port: u16) -> Result { let socket = SocketAddr::new(dst, port); let sd = format!("{}:{}", dst, port); let local_socket = bind_local_socket(&socket)?; @@ -94,17 +97,17 @@ pub fn get_source_ip(dst: IpAddr, port: u16) -> Result { Ok(_) => match local_socket.local_addr() { Ok(l_addr) => match IpAddr::from_str(&l_addr.ip().to_string()) { Ok(x) => Ok(x), - Err(_) => Err(NaslError::Diagnostic( + Err(_) => Err(FunctionErrorKind::Diagnostic( "No route to destination".to_string(), None, )), }, - Err(_) => Err(NaslError::Diagnostic( + Err(_) => Err(FunctionErrorKind::Diagnostic( "No route to destination".to_string(), None, )), }, - Err(_) => Err(NaslError::Diagnostic( + Err(_) => Err(FunctionErrorKind::Diagnostic( "No route to destination".to_string(), None, )), diff --git a/rust/src/nasl/builtin/raw_ip/tests/packet_forgery.rs b/rust/src/nasl/builtin/raw_ip/tests/packet_forgery.rs index 0d9a10fcb..fb446c261 100644 --- a/rust/src/nasl/builtin/raw_ip/tests/packet_forgery.rs +++ b/rust/src/nasl/builtin/raw_ip/tests/packet_forgery.rs @@ -8,7 +8,7 @@ mod tests { use nasl_builtin_raw_ip::RawIp; use nasl_builtin_std::ContextFactory; - use crate::nasl::utils::{error::NaslError, Executor}; + use crate::nasl::utils::{error::FunctionErrorKind, Executor}; use crate::nasl::interpreter::test_utils::TestBuilder; use crate::nasl::syntax::NaslValue; @@ -20,7 +20,7 @@ mod tests { o_buf: &[u8], o_init: usize, o_fin: usize, - ) -> Result<(), NaslError> { + ) -> Result<(), FunctionErrorKind> { let o_range = o_fin - o_init; let d_range = d_fin - d_init; if d_buf.len() < d_range @@ -29,7 +29,7 @@ mod tests { || d_buf.len() < d_fin || o_buf.len() < o_fin { - return Err(NaslError::Diagnostic( + return Err(FunctionErrorKind::Diagnostic( "Error copying from slice. Index out of range".to_string(), Some(NaslValue::Null), )); @@ -270,7 +270,7 @@ mod tests { // different range size between origin and destination assert_eq!( safe_copy_from_slice(&mut a, 0, 2, &b, 0, b.len()), - Err(NaslError::Diagnostic( + Err(FunctionErrorKind::Diagnostic( "Error copying from slice. Index out of range".to_string(), Some(NaslValue::Null) )) @@ -279,7 +279,7 @@ mod tests { // different range size between origin and destination assert_eq!( safe_copy_from_slice(&mut a, 0, alen, &b, 0, 2), - Err(NaslError::Diagnostic( + Err(FunctionErrorKind::Diagnostic( "Error copying from slice. Index out of range".to_string(), Some(NaslValue::Null) )) @@ -288,7 +288,7 @@ mod tests { // out of index in the destination range assert_eq!( safe_copy_from_slice(&mut a, 1, alen + 1, &b, 0, b.len()), - Err(NaslError::Diagnostic( + Err(FunctionErrorKind::Diagnostic( "Error copying from slice. Index out of range".to_string(), Some(NaslValue::Null) )) diff --git a/rust/src/nasl/builtin/regex/mod.rs b/rust/src/nasl/builtin/regex/mod.rs index 9cb3d5d52..adb2e8af7 100644 --- a/rust/src/nasl/builtin/regex/mod.rs +++ b/rust/src/nasl/builtin/regex/mod.rs @@ -52,7 +52,7 @@ fn ereg( icase: Option, rnul: Option, multiline: Option, -) -> Result { +) -> Result { let icase = icase.unwrap_or(false); let rnul = rnul.unwrap_or(true); let multiline = multiline.unwrap_or(false); @@ -79,7 +79,7 @@ fn ereg_replace( replace: NaslValue, icase: Option, rnul: Option, -) -> Result { +) -> Result { let icase = icase.unwrap_or(false); let rnul = rnul.unwrap_or(true); @@ -107,7 +107,7 @@ fn egrep( pattern: NaslValue, icase: Option, rnul: Option, -) -> Result { +) -> Result { let icase = icase.unwrap_or(false); let rnul = rnul.unwrap_or(true); @@ -141,7 +141,7 @@ fn eregmatch( find_all: Option, icase: Option, rnul: Option, -) -> Result { +) -> Result { let icase = icase.unwrap_or(false); let rnul = rnul.unwrap_or(true); let find_all = find_all.unwrap_or(false); diff --git a/rust/src/nasl/builtin/report_functions/mod.rs b/rust/src/nasl/builtin/report_functions/mod.rs index dc7ccae92..652d1fcd9 100644 --- a/rust/src/nasl/builtin/report_functions/mod.rs +++ b/rust/src/nasl/builtin/report_functions/mod.rs @@ -26,7 +26,7 @@ impl Reporting { typus: ResultType, register: &Register, context: &Context, - ) -> Result { + ) -> Result { let data = register.named("data").map(|x| x.to_string()); let port = register .named("port") @@ -70,7 +70,11 @@ impl Reporting { /// - port, optional TCP or UDP port number of the service /// - proto is the protocol ("tcp" by default; "udp" is the other value). /// - uri specifies the location of a found product - fn log_message(&self, register: &Register, context: &Context) -> Result { + fn log_message( + &self, + register: &Register, + context: &Context, + ) -> Result { self.store_result(ResultType::Log, register, context) } @@ -85,7 +89,7 @@ impl Reporting { &self, register: &Register, context: &Context, - ) -> Result { + ) -> Result { self.store_result(ResultType::Alarm, register, context) } @@ -100,7 +104,7 @@ impl Reporting { &self, register: &Register, context: &Context, - ) -> Result { + ) -> Result { self.store_result(ResultType::Error, register, context) } } diff --git a/rust/src/nasl/builtin/ssh/mod.rs b/rust/src/nasl/builtin/ssh/mod.rs index 19140eec6..3d2815ed1 100644 --- a/rust/src/nasl/builtin/ssh/mod.rs +++ b/rust/src/nasl/builtin/ssh/mod.rs @@ -42,7 +42,7 @@ mod libssh_uses { #[cfg(feature = "nasl-builtin-libssh")] pub use libssh_uses::*; -type Result = std::result::Result; +type Result = std::result::Result; const DEFAULT_SSH_PORT: u16 = 22; @@ -519,7 +519,7 @@ impl Ssh { } AuthStatus::Success => break, status => { - return Err(NaslError::Diagnostic( + return Err(FunctionErrorKind::Diagnostic( format!( "Unexpected authentication status for session_id {}: {:?}", session_id, status diff --git a/rust/src/nasl/builtin/ssh/utils.rs b/rust/src/nasl/builtin/ssh/utils.rs index 744ca3b38..3a0a89d4d 100644 --- a/rust/src/nasl/builtin/ssh/utils.rs +++ b/rust/src/nasl/builtin/ssh/utils.rs @@ -12,7 +12,7 @@ impl<'a, T> FromNaslValue<'a> for CommaSeparated where T: for<'b> FromNaslValue<'b>, { - fn from_nasl_value(value: &'a NaslValue) -> Result { + fn from_nasl_value(value: &'a NaslValue) -> Result { let s = StringOrData::from_nasl_value(value)?; Ok(Self( s.0.split(",") @@ -21,13 +21,13 @@ where let nasl_val = NaslValue::String(substr.to_string()); T::from_nasl_value(&nasl_val) }) - .collect::, NaslError>>()?, + .collect::, FunctionErrorKind>>()?, )) } } impl<'a> FromNaslValue<'a> for key::Name { - fn from_nasl_value(value: &'a NaslValue) -> Result { + fn from_nasl_value(value: &'a NaslValue) -> Result { let s = String::from_nasl_value(value)?; key::Name::try_from(&*s).map_err(|_| { ArgumentError::WrongArgument(format!("Expected a valid SSH key type, found '{}'", s)) @@ -37,7 +37,7 @@ impl<'a> FromNaslValue<'a> for key::Name { } impl<'a> FromNaslValue<'a> for cipher::Name { - fn from_nasl_value(value: &'a NaslValue) -> Result { + fn from_nasl_value(value: &'a NaslValue) -> Result { let s = String::from_nasl_value(value)?; cipher::Name::try_from(&*s).map_err(|_| { ArgumentError::WrongArgument(format!("Expected a valid SSH cipher type, found '{}'", s)) diff --git a/rust/src/nasl/builtin/string/mod.rs b/rust/src/nasl/builtin/string/mod.rs index 41828d5be..64b822030 100644 --- a/rust/src/nasl/builtin/string/mod.rs +++ b/rust/src/nasl/builtin/string/mod.rs @@ -10,7 +10,7 @@ mod tests; use crate::nasl::{ utils::{ function::{bytes_to_str, CheckedPositionals, Maybe, StringOrData}, - NaslError, + FunctionErrorKind, }, ArgumentError, }; @@ -290,7 +290,7 @@ fn stridx(haystack: NaslValue, needle: NaslValue, offset: Option) -> i64 /// NASL function to display any number of NASL values /// /// Internally the string function is used to concatenate the given parameters -fn display(register: &Register, configs: &Context) -> Result { +fn display(register: &Register, configs: &Context) -> Result { println!("{}", &string(register, configs)?); Ok(NaslValue::Null) } @@ -368,7 +368,11 @@ fn insstr( /// `pattern` contains the pattern to search for. /// The optional argument `icase` toggles case sensitivity. Default: false (case sensitive). If true, search is case insensitive. #[nasl_function(named(string, pattern, icase))] -fn match_(string: NaslValue, pattern: NaslValue, icase: Option) -> Result { +fn match_( + string: NaslValue, + pattern: NaslValue, + icase: Option, +) -> Result { let options = MatchOptions { case_sensitive: !icase.unwrap_or(false), require_literal_separator: false, diff --git a/rust/src/nasl/interpreter/error.rs b/rust/src/nasl/interpreter/error.rs index 1da72d046..d108f0475 100644 --- a/rust/src/nasl/interpreter/error.rs +++ b/rust/src/nasl/interpreter/error.rs @@ -6,7 +6,7 @@ use std::io; use crate::nasl::syntax::LoadError; use crate::nasl::syntax::{Statement, SyntaxError, TokenCategory}; -use crate::nasl::utils::error::NaslError; +use crate::nasl::utils::error::FunctionErrorKind; use crate::nasl::InternalError; use crate::storage::StorageError; use thiserror::Error; @@ -19,12 +19,12 @@ pub struct FunctionError { pub function: String, /// Kind of error #[source] - pub kind: NaslError, + pub kind: FunctionErrorKind, } impl FunctionError { /// Creates a new FunctionError - pub fn new(function: &str, kind: NaslError) -> Self { + pub fn new(function: &str, kind: FunctionErrorKind) -> Self { Self { function: function.to_owned(), kind, @@ -231,7 +231,7 @@ impl From for InterpretError { impl From for InterpretError { fn from(fe: FunctionError) -> Self { match fe.kind { - NaslError::Internal(InternalError::Storage(e)) => { + FunctionErrorKind::Internal(InternalError::Storage(e)) => { Self::new(InterpretErrorKind::StorageError(e), None) } _ => Self::new(InterpretErrorKind::FunctionCallError(fe), None), diff --git a/rust/src/nasl/mod.rs b/rust/src/nasl/mod.rs index 701611cb4..8581544c3 100644 --- a/rust/src/nasl/mod.rs +++ b/rust/src/nasl/mod.rs @@ -20,8 +20,8 @@ pub mod prelude { pub use super::utils::ArgumentError; pub use super::utils::Context; pub use super::utils::ContextType; + pub use super::utils::FunctionErrorKind; pub use super::utils::InternalError; - pub use super::utils::NaslError; pub use super::utils::NaslResult; pub use super::utils::Register; pub use crate::function_set; diff --git a/rust/src/nasl/test_utils.rs b/rust/src/nasl/test_utils.rs index 400cf81ab..69736ed46 100644 --- a/rust/src/nasl/test_utils.rs +++ b/rust/src/nasl/test_utils.rs @@ -290,7 +290,7 @@ where fn check_result( &self, - result: &Result, + result: &Result, reference: &TracedTestResult, line_count: usize, ) { @@ -301,7 +301,7 @@ where "Mismatch at {}.\nIn code \"{}\":\nExpected: {:?}\nFound: {:?}", reference.location, self.lines[line_count], - Ok::<_, NaslError>(reference_result), + Ok::<_, FunctionErrorKind>(reference_result), result, ); } @@ -322,7 +322,7 @@ where fn compare_result( &self, - result: &Result, + result: &Result, reference: &TestResult, ) -> bool { match reference { @@ -395,11 +395,11 @@ macro_rules! check_err_matches { |e| { if let Err(e) = e { // Convert with try_into to allow using - // the variants of `NaslError` directly without + // the variants of `FunctionErrorKind` directly without // having to wrap them in the outer enum. let converted = e.try_into(); // This is only irrefutable for the - // NaslError -> NaslError conversion but not for others. + // FunctionErrorKind -> FunctionErrorKind conversion but not for others. #[allow(irrefutable_let_patterns)] if let Ok(e) = converted { matches!(e, $pat) diff --git a/rust/src/nasl/utils/error.rs b/rust/src/nasl/utils/error.rs index d52802e64..bdf5d80fb 100644 --- a/rust/src/nasl/utils/error.rs +++ b/rust/src/nasl/utils/error.rs @@ -14,7 +14,7 @@ use super::ContextType; #[derive(Debug, Clone, Error)] /// Descriptive kind of error that can occur while calling a function -pub enum NaslError { +pub enum FunctionErrorKind { /// Diagnostic string is informational and the second arg is the return value for the user #[error("{0}")] Diagnostic(String, Option), @@ -46,40 +46,40 @@ pub enum InternalError { Storage(#[from] StorageError), } -impl From for NaslError { +impl From for FunctionErrorKind { fn from(value: StorageError) -> Self { - NaslError::Internal(InternalError::Storage(value)) + FunctionErrorKind::Internal(InternalError::Storage(value)) } } -impl TryFrom for ArgumentError { +impl TryFrom for ArgumentError { type Error = (); - fn try_from(value: NaslError) -> Result { + fn try_from(value: FunctionErrorKind) -> Result { match value { - NaslError::Argument(e) => Ok(e), + FunctionErrorKind::Argument(e) => Ok(e), _ => Err(()), } } } -impl TryFrom for InternalError { +impl TryFrom for InternalError { type Error = (); - fn try_from(value: NaslError) -> Result { + fn try_from(value: FunctionErrorKind) -> Result { match value { - NaslError::Internal(e) => Ok(e), + FunctionErrorKind::Internal(e) => Ok(e), _ => Err(()), } } } -impl TryFrom for BuiltinError { +impl TryFrom for BuiltinError { type Error = (); - fn try_from(value: NaslError) -> Result { + fn try_from(value: FunctionErrorKind) -> Result { match value { - NaslError::Builtin(e) => Ok(e), + FunctionErrorKind::Builtin(e) => Ok(e), _ => Err(()), } } @@ -94,7 +94,7 @@ impl ArgumentError { } } -impl NaslError { +impl FunctionErrorKind { /// Helper function to quickly construct a `WrongArgument` variant /// containing the name of the argument, the expected value and /// the actual value. @@ -111,7 +111,7 @@ impl NaslError { } } -impl From<(&str, &str, &NaslValue)> for NaslError { +impl From<(&str, &str, &NaslValue)> for FunctionErrorKind { fn from(value: (&str, &str, &NaslValue)) -> Self { let (key, expected, got) = value; let got: &str = &got.to_string(); @@ -119,7 +119,7 @@ impl From<(&str, &str, &NaslValue)> for NaslError { } } -impl From<(&str, &str, Option<&NaslValue>)> for NaslError { +impl From<(&str, &str, Option<&NaslValue>)> for FunctionErrorKind { fn from(value: (&str, &str, Option<&NaslValue>)) -> Self { match value { (key, expected, Some(x)) => (key, expected, x).into(), @@ -128,7 +128,7 @@ impl From<(&str, &str, Option<&NaslValue>)> for NaslError { } } -impl From<(&str, &str, Option<&ContextType>)> for NaslError { +impl From<(&str, &str, Option<&ContextType>)> for FunctionErrorKind { fn from(value: (&str, &str, Option<&ContextType>)) -> Self { match value { (key, expected, Some(ContextType::Value(x))) => (key, expected, x).into(), @@ -140,10 +140,10 @@ impl From<(&str, &str, Option<&ContextType>)> for NaslError { } } -impl From<(&str, &NaslValue)> for NaslError { +impl From<(&str, &NaslValue)> for FunctionErrorKind { fn from(value: (&str, &NaslValue)) -> Self { let (expected, got) = value; let got: &str = &got.to_string(); - NaslError::wrong_unnamed_argument(expected, got) + FunctionErrorKind::wrong_unnamed_argument(expected, got) } } diff --git a/rust/src/nasl/utils/function/from_nasl_value.rs b/rust/src/nasl/utils/function/from_nasl_value.rs index 106d89742..eecf9b68c 100644 --- a/rust/src/nasl/utils/function/from_nasl_value.rs +++ b/rust/src/nasl/utils/function/from_nasl_value.rs @@ -6,23 +6,23 @@ use crate::nasl::prelude::*; /// The conversion may fail. pub trait FromNaslValue<'a>: Sized { /// Perform the conversion - fn from_nasl_value(value: &'a NaslValue) -> Result; + fn from_nasl_value(value: &'a NaslValue) -> Result; } impl<'a> FromNaslValue<'a> for NaslValue { - fn from_nasl_value(value: &'a NaslValue) -> Result { + fn from_nasl_value(value: &'a NaslValue) -> Result { Ok(value.clone()) } } impl<'a> FromNaslValue<'a> for &'a NaslValue { - fn from_nasl_value(value: &'a NaslValue) -> Result { + fn from_nasl_value(value: &'a NaslValue) -> Result { Ok(value) } } impl<'a> FromNaslValue<'a> for String { - fn from_nasl_value(value: &NaslValue) -> Result { + fn from_nasl_value(value: &NaslValue) -> Result { match value { NaslValue::String(string) => Ok(string.to_string()), _ => Err(ArgumentError::WrongArgument("Expected string.".to_string()).into()), @@ -31,7 +31,7 @@ impl<'a> FromNaslValue<'a> for String { } impl<'a> FromNaslValue<'a> for &'a str { - fn from_nasl_value(value: &'a NaslValue) -> Result { + fn from_nasl_value(value: &'a NaslValue) -> Result { match value { NaslValue::String(string) => Ok(string), _ => Err(ArgumentError::WrongArgument("Expected string.".to_string()).into()), @@ -40,7 +40,7 @@ impl<'a> FromNaslValue<'a> for &'a str { } impl<'a> FromNaslValue<'a> for &'a [u8] { - fn from_nasl_value(value: &'a NaslValue) -> Result { + fn from_nasl_value(value: &'a NaslValue) -> Result { match value { NaslValue::Data(bytes) => Ok(bytes), _ => Err(ArgumentError::WrongArgument("Expected byte data.".to_string()).into()), @@ -49,19 +49,19 @@ impl<'a> FromNaslValue<'a> for &'a [u8] { } impl<'a, T: FromNaslValue<'a>> FromNaslValue<'a> for Vec { - fn from_nasl_value(value: &'a NaslValue) -> Result { + fn from_nasl_value(value: &'a NaslValue) -> Result { match value { NaslValue::Array(vals) => Ok(vals .iter() .map(T::from_nasl_value) - .collect::, NaslError>>()?), + .collect::, FunctionErrorKind>>()?), _ => Err(ArgumentError::WrongArgument("Expected an array..".to_string()).into()), } } } impl<'a, T: FromNaslValue<'a>> FromNaslValue<'a> for HashMap { - fn from_nasl_value(value: &'a NaslValue) -> Result { + fn from_nasl_value(value: &'a NaslValue) -> Result { match value { NaslValue::Dict(map) => Ok(map .iter() @@ -73,7 +73,7 @@ impl<'a, T: FromNaslValue<'a>> FromNaslValue<'a> for HashMap { } impl<'a> FromNaslValue<'a> for bool { - fn from_nasl_value(value: &'a NaslValue) -> Result { + fn from_nasl_value(value: &'a NaslValue) -> Result { match value { NaslValue::Boolean(b) => Ok(*b), NaslValue::Number(n) => Ok(*n != 0), @@ -85,7 +85,7 @@ impl<'a> FromNaslValue<'a> for bool { macro_rules! impl_from_nasl_value_for_numeric_type { ($ty: ty) => { impl<'a> FromNaslValue<'a> for $ty { - fn from_nasl_value(value: &NaslValue) -> Result { + fn from_nasl_value(value: &NaslValue) -> Result { match value { NaslValue::Number(num) => Ok(<$ty>::try_from(*num).map_err(|_| { ArgumentError::WrongArgument("Expected positive number.".into()) diff --git a/rust/src/nasl/utils/function/maybe.rs b/rust/src/nasl/utils/function/maybe.rs index 04a8cc049..28085e718 100644 --- a/rust/src/nasl/utils/function/maybe.rs +++ b/rust/src/nasl/utils/function/maybe.rs @@ -1,6 +1,6 @@ use crate::nasl::syntax::NaslValue; -use crate::nasl::NaslError; +use crate::nasl::FunctionErrorKind; use super::FromNaslValue; @@ -12,7 +12,7 @@ use super::FromNaslValue; pub struct Maybe(Option); impl<'a, T: FromNaslValue<'a>> FromNaslValue<'a> for Maybe { - fn from_nasl_value(value: &'a NaslValue) -> Result { + fn from_nasl_value(value: &'a NaslValue) -> Result { Ok(Self(T::from_nasl_value(value).ok())) } } diff --git a/rust/src/nasl/utils/function/positionals.rs b/rust/src/nasl/utils/function/positionals.rs index fc26a3128..bd29d26f5 100644 --- a/rust/src/nasl/utils/function/positionals.rs +++ b/rust/src/nasl/utils/function/positionals.rs @@ -1,6 +1,6 @@ use std::{marker::PhantomData, ops::Index}; -use crate::nasl::{NaslError, Register}; +use crate::nasl::{FunctionErrorKind, Register}; use super::FromNaslValue; @@ -22,9 +22,9 @@ impl<'a, T: FromNaslValue<'a>> Positionals<'a, T> { } /// Returns an iterator over the positional arguments. - /// The item type is Result, since + /// The item type is Result, since /// the conversion to T can still fail. - pub fn iter(&self) -> impl Iterator> + 'a { + pub fn iter(&self) -> impl Iterator> + 'a { self.register .positional() .iter() @@ -45,12 +45,12 @@ pub struct CheckedPositionals { impl<'a, T: FromNaslValue<'a>> CheckedPositionals { /// Create a new `CheckedPositionals` from the register. - pub fn new(register: &'a Register) -> Result { + pub fn new(register: &'a Register) -> Result { let data = register .positional() .iter() .map(T::from_nasl_value) - .collect::, NaslError>>()?; + .collect::, FunctionErrorKind>>()?; Ok(Self { data, _marker: PhantomData, diff --git a/rust/src/nasl/utils/function/to_nasl_result.rs b/rust/src/nasl/utils/function/to_nasl_result.rs index 5afff332a..ab48aa7eb 100644 --- a/rust/src/nasl/utils/function/to_nasl_result.rs +++ b/rust/src/nasl/utils/function/to_nasl_result.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use crate::nasl::syntax::NaslValue; -use crate::nasl::{NaslError, NaslResult}; +use crate::nasl::{FunctionErrorKind, NaslResult}; /// A type that can be converted to a NaslResult. /// The conversion is fallible to make it possible to convert from other Result @@ -26,7 +26,7 @@ impl ToNaslResult for Option { } } -impl> ToNaslResult for Result { +impl> ToNaslResult for Result { fn to_nasl_result(self) -> NaslResult { self.map_err(|e| e.into()).and_then(|x| x.to_nasl_result()) } @@ -67,7 +67,7 @@ impl ToNaslResult for Vec<&str> { Ok(NaslValue::Array( self.into_iter() .map(|s| s.to_nasl_result()) - .collect::, NaslError>>()?, + .collect::, FunctionErrorKind>>()?, )) } } @@ -77,7 +77,7 @@ impl ToNaslResult for Vec { Ok(NaslValue::Array( self.into_iter() .map(|s| s.to_nasl_result()) - .collect::, NaslError>>()?, + .collect::, FunctionErrorKind>>()?, )) } } @@ -93,7 +93,7 @@ impl ToNaslResult for HashMap { Ok(NaslValue::Dict( self.into_iter() .map(|(key, s)| s.to_nasl_result().map(|res| (key, res))) - .collect::, NaslError>>()?, + .collect::, FunctionErrorKind>>()?, )) } } @@ -116,7 +116,7 @@ macro_rules! impl_to_nasl_result_for_numeric_type { impl_to_nasl_result_for_numeric_type!($ty, skip_vec_impl); impl ToNaslResult for Vec<$ty> { fn to_nasl_result(self) -> NaslResult { - let collected: Result, NaslError> = + let collected: Result, FunctionErrorKind> = self.into_iter().map(|x| x.to_nasl_result()).collect(); Ok(NaslValue::Array(collected?)) } diff --git a/rust/src/nasl/utils/function/types.rs b/rust/src/nasl/utils/function/types.rs index ff1920f45..38179334d 100644 --- a/rust/src/nasl/utils/function/types.rs +++ b/rust/src/nasl/utils/function/types.rs @@ -5,7 +5,7 @@ use crate::nasl::prelude::*; pub struct StringOrData(pub String); impl<'a> FromNaslValue<'a> for StringOrData { - fn from_nasl_value(value: &'a NaslValue) -> Result { + fn from_nasl_value(value: &'a NaslValue) -> Result { match value { NaslValue::String(string) => Ok(Self(string.clone())), NaslValue::Data(buffer) => Ok(Self(bytes_to_str(buffer))), diff --git a/rust/src/nasl/utils/function/utils.rs b/rust/src/nasl/utils/function/utils.rs index b3d33f3a6..14990eccc 100644 --- a/rust/src/nasl/utils/function/utils.rs +++ b/rust/src/nasl/utils/function/utils.rs @@ -9,7 +9,7 @@ use crate::nasl::prelude::*; pub fn get_optional_positional_arg<'a, T: FromNaslValue<'a>>( register: &'a Register, position: usize, -) -> Result, NaslError> { +) -> Result, FunctionErrorKind> { register .positional() .get(position) @@ -23,7 +23,7 @@ pub fn get_positional_arg<'a, T: FromNaslValue<'a>>( register: &'a Register, position: usize, num_required_positional_args: usize, -) -> Result { +) -> Result { let positional = register.positional(); let arg = positional.get(position).ok_or_else(|| { let num_given = positional.len(); @@ -53,7 +53,7 @@ fn context_type_as_nasl_value<'a>( pub fn get_optional_named_arg<'a, T: FromNaslValue<'a>>( register: &'a Register, name: &'a str, -) -> Result, NaslError> { +) -> Result, FunctionErrorKind> { register .named(name) .map(|arg| context_type_as_nasl_value(arg, name)) @@ -67,7 +67,7 @@ pub fn get_optional_named_arg<'a, T: FromNaslValue<'a>>( pub fn get_named_arg<'a, T: FromNaslValue<'a>>( register: &'a Register, name: &'a str, -) -> Result { +) -> Result { let arg = register .named(name) .ok_or_else(|| ArgumentError::MissingNamed(vec![name.to_string()]))?; @@ -80,7 +80,7 @@ pub fn get_optional_maybe_named_arg<'a, T: FromNaslValue<'a>>( register: &'a Register, name: &'a str, position: usize, -) -> Result, NaslError> { +) -> Result, FunctionErrorKind> { let via_position = get_optional_positional_arg::(register, position)?; if let Some(via_position) = via_position { Ok(Some(via_position)) @@ -95,7 +95,7 @@ pub fn get_maybe_named_arg<'a, T: FromNaslValue<'a>>( register: &'a Register, name: &'a str, position: usize, -) -> Result { +) -> Result { let via_position = get_optional_positional_arg(register, position)?; if let Some(via_position) = via_position { Ok(via_position) @@ -114,7 +114,7 @@ fn check_named_args( _nasl_fn_name: &str, named: &[&str], maybe_named: &[&str], -) -> Result { +) -> Result { let mut num_maybe_named = 0; for arg_name in register.iter_named_args().unwrap() { if arg_name == FC_ANON_ARGS || named.contains(&arg_name) { @@ -142,7 +142,7 @@ pub fn check_args( named: &[&str], maybe_named: &[&str], max_num_expected_positional: Option, -) -> Result<(), NaslError> { +) -> Result<(), FunctionErrorKind> { let num_maybe_named_given = check_named_args(register, _nasl_fn_name, named, maybe_named)?; let num_positional_given = register.positional().len(); if let Some(max_num_expected_positional) = max_num_expected_positional { diff --git a/rust/src/nasl/utils/mod.rs b/rust/src/nasl/utils/mod.rs index 6b0333122..cf8699b9e 100644 --- a/rust/src/nasl/utils/mod.rs +++ b/rust/src/nasl/utils/mod.rs @@ -13,13 +13,13 @@ use std::collections::HashMap; pub use context::{Context, ContextType, Register}; pub use error::ArgumentError; +pub use error::FunctionErrorKind; pub use error::InternalError; -pub use error::NaslError; pub use executor::{Executor, IntoFunctionSet, StoredFunctionSet}; /// The result of a function call. -pub type NaslResult = Result; +pub type NaslResult = Result; /// Resolves positional arguments from the register. pub fn resolve_positional_arguments(register: &Register) -> Vec { diff --git a/rust/src/scannerctl/interpret/mod.rs b/rust/src/scannerctl/interpret/mod.rs index 771d5affc..89caa58b3 100644 --- a/rust/src/scannerctl/interpret/mod.rs +++ b/rust/src/scannerctl/interpret/mod.rs @@ -141,7 +141,7 @@ where Err(e) => match &e.kind { InterpretErrorKind::FunctionCallError(FunctionError { function: _, - kind: NaslError::Diagnostic(_, x), + kind: FunctionErrorKind::Diagnostic(_, x), }) => { tracing::warn!(error=?e, "function call error"); x.clone().unwrap_or_default()