Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add: nasl built regex library, regex nasl functions and tests. #1704

Merged
merged 6 commits into from
Sep 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ members = [
"nasl-builtin-network",
"nasl-builtin-description",
"nasl-builtin-utils",
"nasl-builtin-regex",
"nasl-builtin-std",
"nasl-syntax",
"nasl-interpreter",
Expand Down
17 changes: 17 additions & 0 deletions rust/nasl-builtin-regex/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[package]
name = "nasl-builtin-regex"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
nasl-builtin-utils = {path = "../nasl-builtin-utils"}
nasl-syntax = { path = "../nasl-syntax" }
nasl-function-proc-macro = {path = "../nasl-function-proc-macro"}
storage = {path = "../storage"}
regex = "1.10.6"

[dev-dependencies]
nasl-interpreter = { path = "../nasl-interpreter" }
nasl-builtin-std = {path = "../nasl-builtin-std"}
6 changes: 6 additions & 0 deletions rust/nasl-builtin-regex/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
## Implements
- ereg
- ereg_replace
- egrep
- eregmatch

189 changes: 189 additions & 0 deletions rust/nasl-builtin-regex/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
// SPDX-FileCopyrightText: 2024 Greenbone AG
//
// SPDX-License-Identifier: GPL-2.0-or-later

use nasl_builtin_utils::{error::FunctionErrorKind, NaslFunction};
use nasl_builtin_utils::{Context, Register};
use nasl_function_proc_macro::nasl_function;
use nasl_syntax::NaslValue;
use regex::{Regex, RegexBuilder};

fn parse_search_string(mut s: &str, rnul: bool, multiline: bool) -> &str {
if !rnul {
s = s.split('\0').next().unwrap();
}
if !multiline {
s = s.split('\n').next().unwrap();
}

s
}

fn make_regex(pattern: &str, icase: bool, multiline: bool) -> Result<Regex, FunctionErrorKind> {
match RegexBuilder::new(pattern.to_string().as_str())
.case_insensitive(icase)
.multi_line(multiline)
.build()
{
Ok(re) => Ok(re),
Err(e) => Err(FunctionErrorKind::Dirty(format!(
" Error building regular expression pattern: {}",
e
))),
}
}

/// Matches a string against a regular expression.
/// - string String to search the pattern in
/// - pattern the pattern that should be matched
/// - icase case insensitive flag
/// - rnul replace the null char in the string. Default TRUE.
/// - multiline Is FALSE by default (string is truncated at the first
/// “end of line”), and can be set to TRUE for multiline search.
/// Return true if matches, false otherwise
#[nasl_function(named(string, pattern, icase, rnul, multiline))]
fn ereg(
string: NaslValue,
pattern: NaslValue,
jjnicola marked this conversation as resolved.
Show resolved Hide resolved
icase: Option<bool>,
rnul: Option<bool>,
multiline: Option<bool>,
) -> Result<bool, FunctionErrorKind> {
let icase = icase.unwrap_or(false);
let rnul = rnul.unwrap_or(true);
let multiline = multiline.unwrap_or(false);

let string = string.to_string();
let string = parse_search_string(&string, rnul, multiline);

let re = make_regex(&pattern.to_string(), icase, multiline)?;
Ok(re.is_match(string))
}

/// Search for a pattern in a string and replace it.
/// - string String to search the pattern in
/// - pattern pattern to search in the string for
/// - replace string to replace the pattern with
/// - icase case insensitive flag
/// - rnul replace the null char in the string. Default TRUE.
///
/// Return the new string with the pattern replaced with replace.
#[nasl_function(named(string, pattern, replace, icase, rnul))]
fn ereg_replace(
string: NaslValue,
pattern: NaslValue,
replace: NaslValue,
icase: Option<bool>,
rnul: Option<bool>,
) -> Result<String, FunctionErrorKind> {
let icase = icase.unwrap_or(false);
let rnul = rnul.unwrap_or(true);

let string = string.to_string();
let string = parse_search_string(&string, rnul, true);
let re = make_regex(&pattern.to_string(), icase, false)?;

let out = re
.replace_all(string, replace.to_string().as_str())
.to_string();
Ok(out)
}

/// Looks for a pattern in a string, line by line.
///
/// - string String to search the pattern in
/// - pattern the pattern that should be matched
/// - icase case insensitive flag
/// - rnul replace the null char in the string. Default TRUE.
///
/// Returns the concatenation of all lines that match. Null otherwise.
#[nasl_function(named(string, pattern, replace, icase, rnul))]
fn egrep(
string: NaslValue,
pattern: NaslValue,
icase: Option<bool>,
rnul: Option<bool>,
) -> Result<String, FunctionErrorKind> {
let icase = icase.unwrap_or(false);
let rnul = rnul.unwrap_or(true);

let string = string.to_string();
let string = parse_search_string(&string, rnul, true);
let re = make_regex(&pattern.to_string(), icase, true)?;

let lines: Vec<&str> = string
.split_inclusive('\n')
.filter(|l| re.is_match(l))
.collect();

Ok(lines.concat())
}

/// Does extended regular expression pattern matching.
///
/// - pattern An regex pattern
/// - string A string
/// - icase Boolean, for case sensitive
/// - find_all Boolean, to find all matches
/// - rnul replace the null char in the string. Default TRUE.
///
/// Return an array with the first match (find_all: False)
/// or an array with all matches (find_all: TRUE).
/// NULL or empty if no match was found.
#[nasl_function(named(string, pattern, find_all, icase, rnul))]
fn eregmatch(
string: NaslValue,
pattern: NaslValue,
find_all: Option<bool>,
icase: Option<bool>,
rnul: Option<bool>,
) -> Result<NaslValue, FunctionErrorKind> {
let icase = icase.unwrap_or(false);
let rnul = rnul.unwrap_or(true);
let find_all = find_all.unwrap_or(false);

let string = string.to_string();
let string = parse_search_string(&string, rnul, true);
let re = make_regex(&pattern.to_string(), icase, true)?;

let matches = match find_all {
true => re
.find_iter(string)
.map(|m| NaslValue::String(m.as_str().to_string()))
.collect(),
false => match re.find(string) {
Some(s) => vec![NaslValue::String(s.as_str().to_string())],
None => vec![],
},
};

Ok(NaslValue::Array(matches))
}

/// Returns found function for key or None when not found
pub fn lookup(key: &str) -> Option<NaslFunction> {
match key {
"ereg" => Some(ereg),
"egrep" => Some(egrep),
"ereg_replace" => Some(ereg_replace),
"eregmatch" => Some(eregmatch),
_ => None,
}
}

pub struct RegularExpressions;

impl nasl_builtin_utils::NaslFunctionExecuter for RegularExpressions {
fn nasl_fn_execute(
&self,
name: &str,
register: &Register,
context: &Context,
) -> Option<nasl_builtin_utils::NaslResult> {
lookup(name).map(|x| x(register, context))
}

fn nasl_fn_defined(&self, name: &str) -> bool {
lookup(name).is_some()
}
}
Loading
Loading