1pub mod registry;
14
15use std::fmt;
16use std::path::{Path, PathBuf};
17
18use crate::limits::NseExecutionLimits;
19use crate::profile::{NseModulePolicy, NseScriptPolicy};
20
21#[derive(Debug, Clone, PartialEq, Eq, Hash)]
28pub struct NseModuleName(String);
29
30impl NseModuleName {
31 pub fn as_str(&self) -> &str {
33 &self.0
34 }
35
36 pub fn into_inner(self) -> String {
38 self.0
39 }
40}
41
42impl fmt::Display for NseModuleName {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 write!(f, "{}", self.0)
45 }
46}
47
48const MAX_MODULE_NAME_LEN: usize = 256;
50
51pub fn validate_nse_module_name(name: &str) -> Result<NseModuleName, NseLoadError> {
62 if name.is_empty() {
63 return Err(NseLoadError::InvalidModuleName {
64 name: name.to_string(),
65 reason: "module name is empty".to_string(),
66 });
67 }
68
69 if name.len() > MAX_MODULE_NAME_LEN {
70 return Err(NseLoadError::InvalidModuleName {
71 name: name.to_string(),
72 reason: format!(
73 "module name exceeds maximum length ({} > {})",
74 name.len(),
75 MAX_MODULE_NAME_LEN
76 ),
77 });
78 }
79
80 if name.starts_with('.') {
81 return Err(NseLoadError::InvalidModuleName {
82 name: name.to_string(),
83 reason: "module name must not start with '.'".to_string(),
84 });
85 }
86
87 if name.contains("..") {
89 return Err(NseLoadError::InvalidModuleName {
90 name: name.to_string(),
91 reason: "module name must not contain '..'".to_string(),
92 });
93 }
94
95 for ch in name.chars() {
97 if !ch.is_ascii_alphanumeric() && ch != '_' && ch != '-' && ch != '.' {
98 return Err(NseLoadError::InvalidModuleName {
99 name: name.to_string(),
100 reason: format!("module name contains forbidden character '{}'", ch),
101 });
102 }
103 }
104
105 Ok(NseModuleName(name.to_string()))
106}
107
108#[derive(Debug, Clone)]
114pub enum NseScriptSource {
115 Builtin { name: String },
117 TrustedRegistry { name: String },
119 File { path: PathBuf },
121 InlineManual { label: String, content: String },
123}
124
125impl fmt::Display for NseScriptSource {
126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127 match self {
128 Self::Builtin { name } => write!(f, "builtin:{}", name),
129 Self::TrustedRegistry { name } => write!(f, "registry:{}", name),
130 Self::File { path } => write!(f, "file:{}", path.display()),
131 Self::InlineManual { label, .. } => write!(f, "inline:{}", label),
132 }
133 }
134}
135
136#[derive(Debug, Clone)]
142pub enum NseLoadError {
143 NotFound { source: NseScriptSource },
145 BlockedByPolicy {
147 source: NseScriptSource,
148 reason: String,
149 },
150 OutsideRoot {
152 path: PathBuf,
153 approved_roots: Vec<PathBuf>,
154 },
155 SymlinkEscape { path: PathBuf, resolved: PathBuf },
157 InvalidExtension { path: PathBuf, extension: String },
159 Oversized {
161 source: NseScriptSource,
162 size: usize,
163 limit: usize,
164 },
165 InvalidModuleName { name: String, reason: String },
167 IoError { path: PathBuf, error: String },
169 EvalError {
171 source: NseScriptSource,
172 error: String,
173 },
174}
175
176impl fmt::Display for NseLoadError {
177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178 match self {
179 Self::NotFound { source } => write!(f, "not found: {}", source),
180 Self::BlockedByPolicy { source, reason } => {
181 write!(f, "blocked by policy: {} ({})", source, reason)
182 }
183 Self::OutsideRoot {
184 path,
185 approved_roots,
186 } => write!(
187 f,
188 "path outside approved roots: {} (roots: {:?})",
189 path.display(),
190 approved_roots
191 ),
192 Self::SymlinkEscape { path, resolved } => write!(
193 f,
194 "symlink escapes approved roots: {} -> {}",
195 path.display(),
196 resolved.display()
197 ),
198 Self::InvalidExtension { path, extension } => {
199 write!(f, "invalid extension '{}': {}", extension, path.display())
200 }
201 Self::Oversized {
202 source,
203 size,
204 limit,
205 } => write!(
206 f,
207 "oversized content from {}: {} bytes (limit: {})",
208 source, size, limit
209 ),
210 Self::InvalidModuleName { name, reason } => {
211 write!(f, "invalid module name '{}': {}", name, reason)
212 }
213 Self::IoError { path, error } => {
214 write!(f, "I/O error reading {}: {}", path.display(), error)
215 }
216 Self::EvalError { source, error } => {
217 write!(f, "eval error for {}: {}", source, error)
218 }
219 }
220 }
221}
222
223impl std::error::Error for NseLoadError {}
224
225#[cfg(feature = "nse")]
226impl From<NseLoadError> for mlua::Error {
227 fn from(e: NseLoadError) -> Self {
228 mlua::Error::RuntimeError(e.to_string())
229 }
230}
231
232#[derive(Debug, Clone)]
238pub enum NseLoadDiagnostic {
239 Resolved {
241 source: NseScriptSource,
242 bytes: usize,
243 },
244 Blocked {
246 source: NseScriptSource,
247 reason: String,
248 },
249 OutsideRoot { path: PathBuf, root: PathBuf },
251 SymlinkRejected { path: PathBuf, resolved: PathBuf },
253 ModuleNameRejected { name: String, reason: String },
255 OversizedRejected {
257 source: NseScriptSource,
258 size: usize,
259 limit: usize,
260 },
261 ModuleLoadFailed {
263 name: String,
264 path: PathBuf,
265 error: String,
266 },
267}
268
269#[derive(Debug, Clone)]
275pub struct ResolvedNseScript {
276 pub source: NseScriptSource,
278 pub content: String,
280 pub size: usize,
282}
283
284#[derive(Debug, Clone)]
286pub struct ResolvedNseModule {
287 pub name: NseModuleName,
289 pub content: String,
291 pub size: usize,
293 pub path: Option<PathBuf>,
295}
296
297const ALLOWED_SCRIPT_EXTENSIONS: &[&str] = &["lua", "nse"];
303const ALLOWED_MODULE_EXTENSIONS: &[&str] = &["lua", "nse"];
304
305fn has_allowed_extension(path: &Path, allowed: &[&str]) -> bool {
306 path.extension()
307 .and_then(|e| e.to_str())
308 .map(|ext| allowed.contains(&ext))
309 .unwrap_or(false)
310}
311
312fn try_canonicalize(path: &Path) -> Option<PathBuf> {
319 path.canonicalize().ok()
320}
321
322fn canonicalize_root(path: &Path) -> Option<PathBuf> {
326 path.canonicalize().ok()
327}
328
329fn is_under_root(canonical_path: &Path, canonical_root: &Path) -> bool {
332 canonical_path.strip_prefix(canonical_root).is_ok()
333}
334
335fn validate_existing_path_under_roots(
349 path: &Path,
350 approved_roots: &[PathBuf],
351) -> Result<PathBuf, NseLoadError> {
352 let canonical = try_canonicalize(path).ok_or_else(|| NseLoadError::IoError {
353 path: path.to_path_buf(),
354 error: "path does not exist or cannot be canonicalized".to_string(),
355 })?;
356
357 for root in approved_roots {
358 if let Some(canonical_root) = canonicalize_root(root) {
359 if is_under_root(&canonical, &canonical_root) {
360 return Ok(canonical);
361 }
362 }
363 }
364
365 Err(NseLoadError::OutsideRoot {
366 path: path.to_path_buf(),
367 approved_roots: approved_roots.to_vec(),
368 })
369}
370
371#[allow(dead_code)]
380fn validate_parent_under_roots(
381 path: &Path,
382 approved_roots: &[PathBuf],
383) -> Result<PathBuf, NseLoadError> {
384 let parent = path.parent().ok_or_else(|| NseLoadError::OutsideRoot {
385 path: path.to_path_buf(),
386 approved_roots: approved_roots.to_vec(),
387 })?;
388
389 let canonical_parent = try_canonicalize(parent).ok_or_else(|| NseLoadError::OutsideRoot {
390 path: path.to_path_buf(),
391 approved_roots: approved_roots.to_vec(),
392 })?;
393
394 for root in approved_roots {
395 if let Some(canonical_root) = canonicalize_root(root) {
396 if is_under_root(&canonical_parent, &canonical_root) {
397 return Ok(canonical_parent.join(path.file_name().unwrap_or_default()));
398 }
399 }
400 }
401
402 Err(NseLoadError::OutsideRoot {
403 path: path.to_path_buf(),
404 approved_roots: approved_roots.to_vec(),
405 })
406}
407
408fn validate_symlink_containment(
410 path: &Path,
411 approved_roots: &[PathBuf],
412) -> Result<PathBuf, NseLoadError> {
413 let canonical = path.canonicalize().map_err(|e| NseLoadError::IoError {
414 path: path.to_path_buf(),
415 error: e.to_string(),
416 })?;
417
418 for root in approved_roots {
419 if let Some(canonical_root) = canonicalize_root(root) {
420 if is_under_root(&canonical, &canonical_root) {
421 return Ok(canonical);
422 }
423 }
424 }
425
426 Err(NseLoadError::SymlinkEscape {
427 path: path.to_path_buf(),
428 resolved: canonical,
429 })
430}
431
432const BUILTIN_SCRIPT_NAMES: &[&str] = &[
438 "default",
439 "discovery",
440 "banner",
441 "http-headers",
442 "dns-check",
443 "ssl-cert",
444];
445
446pub fn is_builtin_script(name: &str) -> bool {
448 BUILTIN_SCRIPT_NAMES.contains(&name)
449}
450
451pub struct ScriptResolver {
460 script_policy: NseScriptPolicy,
461 module_policy: NseModulePolicy,
462 limits: NseExecutionLimits,
463 diagnostics: Vec<NseLoadDiagnostic>,
464}
465
466impl ScriptResolver {
467 pub fn new(
469 script_policy: NseScriptPolicy,
470 module_policy: NseModulePolicy,
471 limits: NseExecutionLimits,
472 ) -> Self {
473 Self {
474 script_policy,
475 module_policy,
476 limits,
477 diagnostics: Vec::new(),
478 }
479 }
480
481 pub fn diagnostics(&self) -> &[NseLoadDiagnostic] {
483 &self.diagnostics
484 }
485
486 pub fn take_diagnostics(&mut self) -> Vec<NseLoadDiagnostic> {
488 std::mem::take(&mut self.diagnostics)
489 }
490
491 pub fn clear_diagnostics(&mut self) {
493 self.diagnostics.clear();
494 }
495
496 pub fn resolve_script(
502 &mut self,
503 source: NseScriptSource,
504 ) -> Result<ResolvedNseScript, NseLoadError> {
505 match &source {
506 NseScriptSource::Builtin { name } => self.resolve_builtin(name.clone()),
507 NseScriptSource::TrustedRegistry { name: _ } => {
508 Err(NseLoadError::NotFound {
510 source: source.clone(),
511 })
512 }
513 NseScriptSource::File { path } => self.resolve_script_file(path.clone(), source),
514 NseScriptSource::InlineManual { label, content } => {
515 self.resolve_inline(label.clone(), content.clone(), source)
516 }
517 }
518 }
519
520 fn resolve_builtin(&mut self, name: String) -> Result<ResolvedNseScript, NseLoadError> {
521 if !self.script_policy.allow_builtin_scripts {
522 return Err(NseLoadError::BlockedByPolicy {
523 source: NseScriptSource::Builtin { name: name.clone() },
524 reason: "builtin scripts not allowed by profile".to_string(),
525 });
526 }
527
528 let source = NseScriptSource::Builtin { name };
532 let content = String::new(); let size = 0;
534
535 self.diagnostics.push(NseLoadDiagnostic::Resolved {
536 source: source.clone(),
537 bytes: size,
538 });
539
540 Ok(ResolvedNseScript {
541 source,
542 content,
543 size,
544 })
545 }
546
547 fn resolve_script_file(
548 &mut self,
549 path: PathBuf,
550 source: NseScriptSource,
551 ) -> Result<ResolvedNseScript, NseLoadError> {
552 if !self.script_policy.allow_script_files {
554 self.diagnostics.push(NseLoadDiagnostic::Blocked {
555 source: source.clone(),
556 reason: "script files not allowed by profile".to_string(),
557 });
558 return Err(NseLoadError::BlockedByPolicy {
559 source: source.clone(),
560 reason: "script files not allowed by profile".to_string(),
561 });
562 }
563
564 if !path.exists() {
566 return Err(NseLoadError::NotFound {
567 source: source.clone(),
568 });
569 }
570
571 if !has_allowed_extension(&path, ALLOWED_SCRIPT_EXTENSIONS) {
573 let ext = path
574 .extension()
575 .and_then(|e| e.to_str())
576 .unwrap_or("")
577 .to_string();
578 return Err(NseLoadError::InvalidExtension {
579 path: path.clone(),
580 extension: ext,
581 });
582 }
583
584 if !self.script_policy.allowed_script_roots.is_empty() {
591 validate_existing_path_under_roots(&path, &self.script_policy.allowed_script_roots)?;
592 }
593
594 let canonical = if self.script_policy.allowed_script_roots.is_empty() {
598 path.canonicalize().map_err(|e| NseLoadError::IoError {
600 path: path.clone(),
601 error: e.to_string(),
602 })?
603 } else {
604 validate_symlink_containment(&path, &self.script_policy.allowed_script_roots)?
605 };
606
607 let content = std::fs::read_to_string(&canonical).map_err(|e| NseLoadError::IoError {
609 path: canonical.clone(),
610 error: e.to_string(),
611 })?;
612
613 let size = content.len();
615 if let Some(max) = self.limits.max_script_bytes {
616 if size > max {
617 self.diagnostics.push(NseLoadDiagnostic::OversizedRejected {
618 source: source.clone(),
619 size,
620 limit: max,
621 });
622 return Err(NseLoadError::Oversized {
623 source: source.clone(),
624 size,
625 limit: max,
626 });
627 }
628 }
629 if let Some(max) = self.script_policy.max_script_bytes {
630 if size > max {
631 self.diagnostics.push(NseLoadDiagnostic::OversizedRejected {
632 source: source.clone(),
633 size,
634 limit: max,
635 });
636 return Err(NseLoadError::Oversized {
637 source: source.clone(),
638 size,
639 limit: max,
640 });
641 }
642 }
643
644 self.diagnostics.push(NseLoadDiagnostic::Resolved {
645 source: source.clone(),
646 bytes: size,
647 });
648
649 Ok(ResolvedNseScript {
650 source,
651 content,
652 size,
653 })
654 }
655
656 fn resolve_inline(
657 &mut self,
658 _label: String,
659 content: String,
660 source: NseScriptSource,
661 ) -> Result<ResolvedNseScript, NseLoadError> {
662 let size = content.len();
663
664 if let Some(max) = self.limits.max_script_bytes {
666 if size > max {
667 self.diagnostics.push(NseLoadDiagnostic::OversizedRejected {
668 source: source.clone(),
669 size,
670 limit: max,
671 });
672 return Err(NseLoadError::Oversized {
673 source: source.clone(),
674 size,
675 limit: max,
676 });
677 }
678 }
679 if let Some(max) = self.script_policy.max_script_bytes {
680 if size > max {
681 self.diagnostics.push(NseLoadDiagnostic::OversizedRejected {
682 source: source.clone(),
683 size,
684 limit: max,
685 });
686 return Err(NseLoadError::Oversized {
687 source: source.clone(),
688 size,
689 limit: max,
690 });
691 }
692 }
693
694 self.diagnostics.push(NseLoadDiagnostic::Resolved {
695 source: source.clone(),
696 bytes: size,
697 });
698
699 Ok(ResolvedNseScript {
700 source,
701 content,
702 size,
703 })
704 }
705
706 pub fn resolve_module(
713 &mut self,
714 name: &str,
715 ) -> Result<Option<ResolvedNseModule>, NseLoadError> {
716 let validated_name = validate_nse_module_name(name).inspect_err(|e| {
718 self.diagnostics
719 .push(NseLoadDiagnostic::ModuleNameRejected {
720 name: name.to_string(),
721 reason: e.to_string(),
722 });
723 })?;
724
725 if !self.module_policy.allow_filesystem_modules {
727 return Ok(None);
728 }
729
730 if self.module_policy.allowed_module_roots.is_empty() {
732 return Ok(None);
733 }
734
735 for root in &self.module_policy.allowed_module_roots {
737 let Some(canonical_root) = canonicalize_root(root) else {
738 continue;
740 };
741
742 for ext in ALLOWED_MODULE_EXTENSIONS {
743 let candidate = canonical_root.join(format!("{}.{}", validated_name.as_str(), ext));
744
745 if !candidate.exists() {
746 continue;
747 }
748
749 match validate_existing_path_under_roots(
751 &candidate,
752 &self.module_policy.allowed_module_roots,
753 ) {
754 Ok(canonical_path) => {
755 match validate_symlink_containment(
757 &canonical_path,
758 &self.module_policy.allowed_module_roots,
759 ) {
760 Ok(safe_path) => {
761 match std::fs::read_to_string(&safe_path) {
763 Ok(content) => {
764 let size = content.len();
765
766 if let Some(max) = self.limits.max_required_module_bytes {
768 if size > max {
769 self.diagnostics.push(
770 NseLoadDiagnostic::OversizedRejected {
771 source: NseScriptSource::File {
772 path: safe_path.clone(),
773 },
774 size,
775 limit: max,
776 },
777 );
778 return Err(NseLoadError::Oversized {
779 source: NseScriptSource::File {
780 path: safe_path.clone(),
781 },
782 size,
783 limit: max,
784 });
785 }
786 }
787 if let Some(max) = self.module_policy.max_module_bytes {
788 if size > max {
789 self.diagnostics.push(
790 NseLoadDiagnostic::OversizedRejected {
791 source: NseScriptSource::File {
792 path: safe_path.clone(),
793 },
794 size,
795 limit: max,
796 },
797 );
798 return Err(NseLoadError::Oversized {
799 source: NseScriptSource::File {
800 path: safe_path.clone(),
801 },
802 size,
803 limit: max,
804 });
805 }
806 }
807
808 self.diagnostics.push(NseLoadDiagnostic::Resolved {
809 source: NseScriptSource::File {
810 path: safe_path.clone(),
811 },
812 bytes: size,
813 });
814
815 return Ok(Some(ResolvedNseModule {
816 name: validated_name,
817 content,
818 size,
819 path: Some(safe_path),
820 }));
821 }
822 Err(e) => {
823 self.diagnostics.push(
824 NseLoadDiagnostic::ModuleLoadFailed {
825 name: name.to_string(),
826 path: safe_path,
827 error: e.to_string(),
828 },
829 );
830 }
832 }
833 }
834 Err(NseLoadError::SymlinkEscape { path, resolved }) => {
835 self.diagnostics
836 .push(NseLoadDiagnostic::SymlinkRejected { path, resolved });
837 }
839 Err(e) => return Err(e),
840 }
841 }
842 Err(NseLoadError::OutsideRoot {
843 path,
844 approved_roots,
845 }) => {
846 self.diagnostics.push(NseLoadDiagnostic::OutsideRoot {
847 path,
848 root: approved_roots.first().cloned().unwrap_or_default(),
849 });
850 }
852 Err(e) => return Err(e),
853 }
854 }
855 }
856
857 Ok(None)
859 }
860}
861
862#[cfg(test)]
863mod tests {
864 use super::*;
865
866 #[test]
867 fn test_validate_module_name_valid() {
868 assert!(validate_nse_module_name("stdnse").is_ok());
869 assert!(validate_nse_module_name("http").is_ok());
870 assert!(validate_nse_module_name("my-module").is_ok());
871 assert!(validate_nse_module_name("my_module").is_ok());
872 assert!(validate_nse_module_name("module.v2").is_ok());
873 assert!(validate_nse_module_name("a1b2c3").is_ok());
874 }
875
876 #[test]
877 fn test_validate_module_name_empty() {
878 assert!(matches!(
879 validate_nse_module_name(""),
880 Err(NseLoadError::InvalidModuleName { .. })
881 ));
882 }
883
884 #[test]
885 fn test_validate_module_name_starts_with_dot() {
886 assert!(matches!(
887 validate_nse_module_name(".hidden"),
888 Err(NseLoadError::InvalidModuleName { .. })
889 ));
890 }
891
892 #[test]
893 fn test_validate_module_name_traversal() {
894 assert!(matches!(
895 validate_nse_module_name("..etc/passwd"),
896 Err(NseLoadError::InvalidModuleName { .. })
897 ));
898 assert!(matches!(
899 validate_nse_module_name("foo/../bar"),
900 Err(NseLoadError::InvalidModuleName { .. })
901 ));
902 }
903
904 #[test]
905 fn test_validate_module_name_forbidden_chars() {
906 assert!(validate_nse_module_name("foo/bar").is_err());
907 assert!(validate_nse_module_name("foo\\bar").is_err());
908 assert!(validate_nse_module_name("foo:bar").is_err());
909 assert!(validate_nse_module_name("foo~bar").is_err());
910 assert!(validate_nse_module_name("foo\0bar").is_err());
911 assert!(validate_nse_module_name("foo bar").is_err());
912 assert!(validate_nse_module_name("foo*bar").is_err());
913 assert!(validate_nse_module_name("foo?bar").is_err());
914 assert!(validate_nse_module_name("foo{bar").is_err());
915 }
916
917 #[test]
918 fn test_validate_module_name_too_long() {
919 let long_name = "a".repeat(257);
920 assert!(matches!(
921 validate_nse_module_name(&long_name),
922 Err(NseLoadError::InvalidModuleName { .. })
923 ));
924 }
925
926 #[test]
927 fn test_validate_module_name_max_length() {
928 let max_name = "a".repeat(256);
929 assert!(validate_nse_module_name(&max_name).is_ok());
930 }
931
932 #[test]
933 fn test_script_source_display() {
934 assert_eq!(
935 NseScriptSource::Builtin {
936 name: "default".to_string()
937 }
938 .to_string(),
939 "builtin:default"
940 );
941 assert_eq!(
942 NseScriptSource::File {
943 path: PathBuf::from("/tmp/test.lua")
944 }
945 .to_string(),
946 "file:/tmp/test.lua"
947 );
948 assert_eq!(
949 NseLoadError::NotFound {
950 source: NseScriptSource::Builtin {
951 name: "x".to_string()
952 }
953 }
954 .to_string(),
955 "not found: builtin:x"
956 );
957 }
958
959 #[test]
960 fn test_is_builtin_script() {
961 assert!(is_builtin_script("default"));
962 assert!(is_builtin_script("discovery"));
963 assert!(is_builtin_script("banner"));
964 assert!(is_builtin_script("http-headers"));
965 assert!(is_builtin_script("dns-check"));
966 assert!(is_builtin_script("ssl-cert"));
967 assert!(!is_builtin_script("custom"));
968 assert!(!is_builtin_script(""));
969 }
970
971 #[test]
972 fn test_has_allowed_extension() {
973 assert!(has_allowed_extension(
974 Path::new("test.lua"),
975 ALLOWED_SCRIPT_EXTENSIONS
976 ));
977 assert!(has_allowed_extension(
978 Path::new("test.nse"),
979 ALLOWED_SCRIPT_EXTENSIONS
980 ));
981 assert!(!has_allowed_extension(
982 Path::new("test.txt"),
983 ALLOWED_SCRIPT_EXTENSIONS
984 ));
985 assert!(!has_allowed_extension(
986 Path::new("test"),
987 ALLOWED_SCRIPT_EXTENSIONS
988 ));
989 }
990
991 #[test]
992 fn test_resolver_rejects_script_file_when_policy_blocks() {
993 let profile = crate::profile::ResolvedNseExecutionProfile::agent_safe("10.0.0.1", &[]);
994 let mut resolver =
995 ScriptResolver::new(profile.script_policy, profile.module_policy, profile.limits);
996
997 let result = resolver.resolve_script(NseScriptSource::File {
998 path: PathBuf::from("/tmp/test.lua"),
999 });
1000
1001 assert!(result.is_err());
1002 match result.unwrap_err() {
1003 NseLoadError::BlockedByPolicy { reason, .. } => {
1004 assert!(reason.contains("not allowed"));
1005 }
1006 other => panic!("Expected BlockedByPolicy, got {:?}", other),
1007 }
1008 }
1009
1010 #[test]
1011 fn test_resolver_rejects_oversized_inline_script() {
1012 let profile = crate::profile::ResolvedNseExecutionProfile::agent_safe("10.0.0.1", &[]);
1013 let mut resolver =
1014 ScriptResolver::new(profile.script_policy, profile.module_policy, profile.limits);
1015
1016 let large_content = "x".repeat(1024 * 1024 + 1);
1018 let result = resolver.resolve_script(NseScriptSource::InlineManual {
1019 label: "test".to_string(),
1020 content: large_content,
1021 });
1022
1023 assert!(result.is_err());
1024 match result.unwrap_err() {
1025 NseLoadError::Oversized { size, limit, .. } => {
1026 assert!(size > limit);
1027 }
1028 other => panic!("Expected Oversized, got {:?}", other),
1029 }
1030 }
1031
1032 #[test]
1033 fn test_resolver_allows_inline_script_within_limits() {
1034 let profile = crate::profile::ResolvedNseExecutionProfile::manual_permissive(None);
1035 let mut resolver =
1036 ScriptResolver::new(profile.script_policy, profile.module_policy, profile.limits);
1037
1038 let result = resolver.resolve_script(NseScriptSource::InlineManual {
1039 label: "test".to_string(),
1040 content: "return 1".to_string(),
1041 });
1042
1043 assert!(result.is_ok());
1044 let resolved = result.unwrap();
1045 assert_eq!(resolved.content, "return 1");
1046 }
1047
1048 #[test]
1049 fn test_resolver_rejects_module_name_traversal() {
1050 let profile = crate::profile::ResolvedNseExecutionProfile::agent_safe("10.0.0.1", &[]);
1051 let mut resolver =
1052 ScriptResolver::new(profile.script_policy, profile.module_policy, profile.limits);
1053
1054 let result = resolver.resolve_module("../../etc/passwd");
1055 assert!(result.is_err());
1056 }
1057
1058 #[test]
1059 fn test_resolver_rejects_module_name_slash() {
1060 let profile = crate::profile::ResolvedNseExecutionProfile::agent_safe("10.0.0.1", &[]);
1061 let mut resolver =
1062 ScriptResolver::new(profile.script_policy, profile.module_policy, profile.limits);
1063
1064 let result = resolver.resolve_module("foo/bar");
1065 assert!(result.is_err());
1066 }
1067
1068 #[test]
1069 fn test_resolver_returns_none_for_module_when_filesystem_disallowed() {
1070 let profile = crate::profile::ResolvedNseExecutionProfile::agent_safe("10.0.0.1", &[]);
1071 let mut resolver =
1072 ScriptResolver::new(profile.script_policy, profile.module_policy, profile.limits);
1073
1074 let result = resolver.resolve_module("stdnse").unwrap();
1075 assert!(result.is_none());
1076 }
1077
1078 #[test]
1079 fn test_resolver_allows_builtin_script() {
1080 let profile = crate::profile::ResolvedNseExecutionProfile::manual_permissive(None);
1081 let mut resolver =
1082 ScriptResolver::new(profile.script_policy, profile.module_policy, profile.limits);
1083
1084 let result = resolver.resolve_script(NseScriptSource::Builtin {
1085 name: "default".to_string(),
1086 });
1087 assert!(result.is_ok());
1088 }
1089
1090 #[test]
1091 fn test_resolver_rejects_builtin_when_policy_blocks() {
1092 let mut script_policy = crate::profile::NseScriptPolicy {
1093 allow_builtin_scripts: false,
1094 allow_script_files: false,
1095 allowed_script_roots: Vec::new(),
1096 allow_conventional_nmap_paths: false,
1097 max_script_bytes: None,
1098 };
1099 let mut resolver = ScriptResolver::new(
1100 script_policy,
1101 crate::profile::NseModulePolicy {
1102 allow_builtin_modules: true,
1103 allow_filesystem_modules: false,
1104 allowed_module_roots: Vec::new(),
1105 max_module_bytes: None,
1106 },
1107 NseExecutionLimits::default(),
1108 );
1109
1110 let result = resolver.resolve_script(NseScriptSource::Builtin {
1111 name: "default".to_string(),
1112 });
1113 assert!(result.is_err());
1114 }
1115
1116 #[test]
1117 fn test_diagnostics_accumulate() {
1118 let profile = crate::profile::ResolvedNseExecutionProfile::agent_safe("10.0.0.1", &[]);
1119 let mut resolver =
1120 ScriptResolver::new(profile.script_policy, profile.module_policy, profile.limits);
1121
1122 let _ = resolver.resolve_script(NseScriptSource::File {
1124 path: PathBuf::from("/tmp/test.lua"),
1125 });
1126
1127 let diags = resolver.take_diagnostics();
1128 assert!(!diags.is_empty());
1129 }
1130
1131 #[test]
1136 fn test_is_under_root_component_semantics() {
1137 let root = PathBuf::from("/tmp/root");
1139 let child = PathBuf::from("/tmp/root2/file.nse");
1140 assert!(!is_under_root(&child, &root));
1141
1142 let child = PathBuf::from("/tmp/root/file.nse");
1144 assert!(is_under_root(&child, &root));
1145
1146 let child = PathBuf::from("/tmp/root/sub/file.nse");
1148 assert!(is_under_root(&child, &root));
1149 }
1150
1151 #[test]
1152 fn test_validate_existing_path_under_roots_rejects_sibling_prefix() {
1153 let roots = vec![PathBuf::from("/tmp/root")];
1154 let result = validate_existing_path_under_roots(Path::new("/tmp/root2/file.nse"), &roots);
1159 assert!(matches!(result, Err(NseLoadError::IoError { .. })));
1160 }
1161
1162 #[test]
1163 fn test_validate_existing_path_under_roots_rejects_sibling_prefix_existing_file() {
1164 let tmp = std::env::temp_dir().join("eggsec-nse-sibling-prefix-test");
1167 let root = tmp.join("root");
1168 let evil = tmp.join("root2");
1169 let _ = std::fs::create_dir_all(&root);
1170 let _ = std::fs::create_dir_all(&evil);
1171 std::fs::write(evil.join("real.nse"), "-- content").unwrap();
1172
1173 let result = validate_existing_path_under_roots(&evil.join("real.nse"), &[root.clone()]);
1174 assert!(matches!(result, Err(NseLoadError::OutsideRoot { .. })));
1175
1176 let _ = std::fs::remove_dir_all(&tmp);
1177 }
1178
1179 #[test]
1180 fn test_validate_existing_path_under_roots_rejects_nonexistent_path_outside_root() {
1181 let roots = vec![PathBuf::from("/tmp/root")];
1182 let result =
1185 validate_existing_path_under_roots(Path::new("/tmp/outside/secret.lua"), &roots);
1186 assert!(matches!(result, Err(NseLoadError::IoError { .. })));
1187 }
1188
1189 #[test]
1190 fn test_validate_existing_path_under_roots_rejects_nonexistent_path_inside_root() {
1191 let tmp = std::env::temp_dir().join("eggsec-nse-read-nonexistent-test");
1195 let _ = std::fs::create_dir_all(&tmp);
1196 let roots = vec![tmp.clone()];
1197
1198 let missing = tmp.join("does-not-exist.nse");
1199 let result = validate_existing_path_under_roots(&missing, &roots);
1200 assert!(
1201 matches!(result, Err(NseLoadError::IoError { .. })),
1202 "Expected IoError for non-existent file, got: {:?}",
1203 result
1204 );
1205
1206 let _ = std::fs::remove_dir_all(&tmp);
1207 }
1208
1209 #[test]
1210 fn test_validate_existing_path_under_roots_accepts_existing_inside_root() {
1211 let tmp = std::env::temp_dir().join("eggsec-nse-read-existing-test");
1212 let _ = std::fs::create_dir_all(&tmp);
1213 let file = tmp.join("real.nse");
1214 std::fs::write(&file, "-- script").unwrap();
1215
1216 let roots = vec![tmp.clone()];
1217 let result = validate_existing_path_under_roots(&file, &roots);
1218 assert!(result.is_ok());
1219 assert_eq!(result.unwrap(), file.canonicalize().unwrap());
1220
1221 let _ = std::fs::remove_dir_all(&tmp);
1222 }
1223
1224 #[test]
1225 fn test_validate_existing_path_under_roots_rejects_existing_outside_root() {
1226 let tmp = std::env::temp_dir().join("eggsec-nse-read-outside-test");
1229 let root = tmp.join("root");
1230 let evil = tmp.join("root_evil");
1231 let _ = std::fs::create_dir_all(&root);
1232 let _ = std::fs::create_dir_all(&evil);
1233 let file = evil.join("real.nse");
1234 std::fs::write(&file, "-- script").unwrap();
1235
1236 let roots = vec![root.clone()];
1237 let result = validate_existing_path_under_roots(&file, &roots);
1238 assert!(matches!(result, Err(NseLoadError::OutsideRoot { .. })));
1239
1240 let _ = std::fs::remove_dir_all(&tmp);
1241 }
1242
1243 #[test]
1244 fn test_validate_symlink_containment_rejects_escape() {
1245 let tmp = std::env::temp_dir().join("eggsec-nse-symlink-test");
1247 let allowed = tmp.join("allowed");
1248 let outside = tmp.join("outside");
1249 let _ = std::fs::create_dir_all(&allowed);
1250 let _ = std::fs::create_dir_all(&outside);
1251
1252 std::fs::write(outside.join("secret.txt"), "secret").unwrap();
1254
1255 let link = allowed.join("escape.txt");
1257 #[cfg(unix)]
1258 std::os::unix::fs::symlink(outside.join("secret.txt"), &link).unwrap();
1259
1260 let result = validate_symlink_containment(&link, &[allowed.clone()]);
1262 assert!(result.is_err());
1263 match result.unwrap_err() {
1264 NseLoadError::SymlinkEscape { path, resolved } => {
1265 assert_eq!(path, link);
1266 assert!(resolved.starts_with(&outside));
1267 }
1268 other => panic!("Expected SymlinkEscape, got {:?}", other),
1269 }
1270
1271 let _ = std::fs::remove_dir_all(&tmp);
1273 }
1274
1275 #[test]
1276 fn test_validate_symlink_containment_allows_internal_symlink() {
1277 let tmp = std::env::temp_dir().join("eggsec-nse-symlink-ok-test");
1279 let allowed = tmp.join("allowed");
1280 let _ = std::fs::create_dir_all(allowed.join("sub"));
1281
1282 std::fs::write(allowed.join("real.txt"), "content").unwrap();
1284
1285 let link = allowed.join("sub").join("link.txt");
1287 #[cfg(unix)]
1288 std::os::unix::fs::symlink(allowed.join("real.txt"), &link).unwrap();
1289
1290 let result = validate_symlink_containment(&link, &[allowed.clone()]);
1292 assert!(result.is_ok());
1293
1294 let _ = std::fs::remove_dir_all(&tmp);
1296 }
1297
1298 #[test]
1299 fn test_validate_existing_path_under_roots_rejects_absolute_traversal() {
1300 let roots = vec![PathBuf::from("/tmp/root")];
1301 let result = validate_existing_path_under_roots(Path::new("/etc/passwd"), &roots);
1305 assert!(result.is_err());
1306 }
1307
1308 #[test]
1309 fn test_canonicalize_root_rejects_nonexistent() {
1310 let result = canonicalize_root(Path::new("/tmp/nonexistent-root-eggsec-nse"));
1312 assert!(result.is_none());
1313 }
1314
1315 #[test]
1316 fn test_canonicalize_root_accepts_existing() {
1317 let tmp = std::env::temp_dir().join("eggsec-nse-root-test");
1319 let _ = std::fs::create_dir_all(&tmp);
1320 let result = canonicalize_root(&tmp);
1321 assert!(result.is_some());
1322 let _ = std::fs::remove_dir_all(&tmp);
1323 }
1324}