cert-x-gen 1.9.2

Advanced Multi-Language Security Scanning Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
//! YAML template engine implementation with full matcher support

use crate::error::{Error, Result};
use crate::flows::{Flow, FlowContext, FlowExecutor};
use crate::matcher::{HttpResponse, MatchCondition, Matcher, MatcherType};
use crate::network::NetworkClient;
use crate::template::{Template, TemplateEngine};
use crate::types::{Context, Evidence, Finding, Protocol, Target, TemplateMetadata};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;

/// YAML template engine
#[derive(Debug)]
pub struct YamlTemplateEngine {
    network_client: Option<Arc<NetworkClient>>,
    flow_executor: Option<Arc<FlowExecutor>>,
}

impl YamlTemplateEngine {
    /// Create a new YAML template engine
    pub fn new() -> Self {
        Self {
            network_client: None,
            flow_executor: None,
        }
    }

    /// Set network client
    pub fn with_network_client(mut self, client: Arc<NetworkClient>) -> Self {
        self.network_client = Some(client.clone());
        self.flow_executor = Some(Arc::new(FlowExecutor::new(client)));
        self
    }
}

impl Default for YamlTemplateEngine {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl TemplateEngine for YamlTemplateEngine {
    async fn load_template(&self, path: &Path) -> Result<Box<dyn Template>> {
        let content = std::fs::read_to_string(path).map_err(|e| {
            Error::template(
                path.display().to_string(),
                format!("Failed to read template: {}", e),
            )
        })?;

        let mut template_data = parse_template_data(&content)?;
        template_data.metadata.file_path = path.to_path_buf();

        Ok(Box::new(YamlTemplateImpl {
            data: template_data,
            network_client: self.network_client.clone(),
            flow_executor: self.flow_executor.clone(),
        }))
    }

    async fn validate_template(&self, template: &dyn Template) -> Result<()> {
        template.validate()
    }

    async fn execute_template(
        &self,
        template: &dyn Template,
        target: &Target,
        context: &Context,
    ) -> Result<Vec<Finding>> {
        template.execute(target, context).await
    }

    fn supported_protocols(&self) -> Vec<Protocol> {
        // Return all protocols that YAML templates CAN support
        // Individual templates will report their specific protocols via detect_protocols()
        vec![
            Protocol::Http,
            Protocol::Https,
            Protocol::Tcp,
            Protocol::Udp,
            Protocol::Dns,
            Protocol::Ssh,
            Protocol::Ftp,
            Protocol::Smtp,
            Protocol::Smb,
            Protocol::Rdp,
            // Custom protocols are handled dynamically
        ]
    }

    fn name(&self) -> &str {
        "yaml"
    }

    fn supports_file(&self, path: &Path) -> bool {
        path.extension()
            .and_then(|s| s.to_str())
            .map(|ext| ext == "yaml" || ext == "yml")
            .unwrap_or(false)
    }
}

/// YAML template data structure
#[derive(Debug, Clone, Deserialize, Serialize)]
struct YamlTemplateData {
    /// Template metadata
    #[serde(flatten)]
    metadata: TemplateMetadata,

    /// HTTP requests
    http: Option<Vec<HttpRequestSpec>>,

    /// Network/TCP requests
    network: Option<Vec<NetworkRequestSpec>>,

    /// Matchers
    matchers: Option<Vec<MatcherType>>,

    /// Matcher condition (and/or)
    #[serde(rename = "matchers-condition")]
    matchers_condition: Option<MatchCondition>,

    /// Flows (multi-step execution)
    flows: Option<Vec<Flow>>,
}

impl YamlTemplateData {
    fn validate(&self) -> Result<()> {
        let operations = self.http.as_ref().map_or(0, Vec::len)
            + self.network.as_ref().map_or(0, Vec::len)
            + self.flows.as_ref().map_or(0, Vec::len);
        if operations == 0 {
            return Err(Error::TemplateValidation {
                template: self.metadata.id.clone(),
                reason: "Template must have either 'http', 'network', or 'flows' defined"
                    .to_string(),
            });
        }
        let sample = Target::new("example.test", Protocol::Http);
        for request in self.http.iter().flatten() {
            request
                .method
                .to_uppercase()
                .parse::<reqwest::Method>()
                .map_err(|e| Error::Execution(format!("Invalid HTTP method: {e}")))?;
            let paths = request.path.as_deref().unwrap_or(&[]);
            if request.path.is_some() && paths.is_empty() {
                return Err(Error::Execution("HTTP path list must not be empty".into()));
            }
            for path in paths {
                resolve_http_url(path, &sample, None)?;
            }
            for (name, value) in &request.headers {
                reqwest::header::HeaderName::from_bytes(name.as_bytes())
                    .map_err(|e| Error::Execution(format!("Invalid HTTP header name: {e}")))?;
                let (value, dynamic) = render_http_text(value, &sample, None)?;
                if !dynamic {
                    reqwest::header::HeaderValue::from_str(&value)
                        .map_err(|e| Error::Execution(format!("Invalid HTTP header value: {e}")))?;
                }
            }
            if let Some(body) = &request.body {
                render_http_text(body, &sample, None)?;
            }
        }
        for request in self.network.iter().flatten() {
            if !request.protocol.eq_ignore_ascii_case("tcp") {
                return Err(Error::Execution(format!(
                    "Unsupported network protocol: {} (only tcp is implemented)",
                    request.protocol
                )));
            }
            if request.port == 0 || request.payloads.is_empty() {
                return Err(Error::Execution(
                    "Network requests require a non-zero port and at least one payload".into(),
                ));
            }
        }
        Ok(())
    }
}

fn parse_template_data(content: &str) -> Result<YamlTemplateData> {
    let data: YamlTemplateData = serde_yaml::from_str(content)?;
    data.validate()?;
    Ok(data)
}

/// Validate using the exact schema and execution-block parser used by loading.
pub fn validate_template_content(content: &str) -> Result<()> {
    parse_template_data(content).map(|_| ())
}

/// HTTP request specification
#[derive(Debug, Clone, Deserialize, Serialize)]
struct HttpRequestSpec {
    /// HTTP method
    #[serde(default = "default_method")]
    method: String,

    /// Request paths
    path: Option<Vec<String>>,

    /// Headers
    #[serde(default)]
    headers: HashMap<String, String>,

    /// Request body
    body: Option<String>,

    /// Matchers for this request
    matchers: Option<Vec<MatcherType>>,

    /// Matcher condition
    #[serde(rename = "matchers-condition")]
    matchers_condition: Option<MatchCondition>,
}

fn default_method() -> String {
    "GET".to_string()
}

/// Expand the native HTTP vocabulary and runtime context. During validation,
/// unknown context values remain dynamic: their values are checked at execution.
fn render_http_text(
    input: &str,
    target: &Target,
    context: Option<&Context>,
) -> Result<(String, bool)> {
    let mut output = String::new();
    let mut remaining = input;
    let mut dynamic = false;
    while let Some((prefix, tail)) = remaining.split_once("{{") {
        if prefix.contains("}}") {
            return Err(Error::Execution(
                "Unbalanced HTTP template placeholder".into(),
            ));
        }
        let (name, rest) = tail
            .split_once("}}")
            .ok_or_else(|| Error::Execution("Unclosed HTTP template placeholder".into()))?;
        let name = name.trim();
        if name.is_empty()
            || !name
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-'))
        {
            return Err(Error::Execution(format!(
                "Unsupported HTTP template placeholder: {name}"
            )));
        }
        let value = match name {
            "BaseURL" | "RootURL" => target.url(),
            "Hostname" | "Host" => target.address.clone(),
            "Port" => target
                .port
                .unwrap_or(if target.protocol == Protocol::Https {
                    443
                } else {
                    80
                })
                .to_string(),
            "Scheme" => target.protocol.to_string(),
            "Path" => "/".into(),
            _ => match context {
                Some(context) => context.variables.get(name).cloned().ok_or_else(|| {
                    Error::Execution(format!("Missing HTTP template context variable: {name}"))
                })?,
                None => {
                    dynamic = true;
                    "cxg".into()
                }
            },
        };
        output.push_str(prefix);
        output.push_str(&value);
        remaining = rest;
    }
    if remaining.contains("}}") {
        return Err(Error::Execution(
            "Unbalanced HTTP template placeholder".into(),
        ));
    }
    output.push_str(remaining);
    Ok((output, dynamic))
}

fn resolve_http_url(path: &str, target: &Target, context: Option<&Context>) -> Result<String> {
    let (path, dynamic) = render_http_text(path, target, context)?;
    let url = if path.contains("://") {
        path
    } else {
        format!(
            "{}{}{}",
            target.url(),
            if path.starts_with('/') || path.starts_with('?') {
                ""
            } else {
                "/"
            },
            path
        )
    };
    if !dynamic {
        let parsed = url::Url::parse(&url)
            .map_err(|e| Error::Execution(format!("Invalid HTTP request URL: {e}")))?;
        if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {
            return Err(Error::Execution(
                "HTTP requests require an http or https URL with a host".into(),
            ));
        }
    }
    Ok(url)
}

/// Network/TCP request specification
#[derive(Debug, Clone, Deserialize, Serialize)]
struct NetworkRequestSpec {
    /// Protocol (tcp/udp)
    #[serde(default = "default_protocol")]
    protocol: String,

    /// Port number
    port: u16,

    /// Payloads to send
    #[serde(default)]
    payloads: Vec<String>,

    /// Matchers for this request
    matchers: Option<Vec<MatcherType>>,

    /// Matcher condition
    #[serde(rename = "matchers-condition")]
    matchers_condition: Option<MatchCondition>,
}

fn default_protocol() -> String {
    "tcp".to_string()
}

/// YAML template implementation
struct YamlTemplateImpl {
    data: YamlTemplateData,
    network_client: Option<Arc<NetworkClient>>,
    flow_executor: Option<Arc<FlowExecutor>>,
}

impl YamlTemplateImpl {
    /// Dynamically detect supported protocols from template content
    fn detect_protocols(&self) -> Vec<Protocol> {
        let mut protocols = Vec::new();

        // Check for HTTP requests - supports both HTTP and HTTPS
        if self.data.http.is_some() {
            protocols.push(Protocol::Http);
            protocols.push(Protocol::Https);
        }

        // Check for network requests and parse their protocols
        if let Some(ref network_requests) = self.data.network {
            for request in network_requests {
                let protocol = match request.protocol.to_lowercase().as_str() {
                    "tcp" => Protocol::Tcp,
                    "udp" => Protocol::Udp,
                    "dns" => Protocol::Dns,
                    "ssh" => Protocol::Ssh,
                    "ftp" => Protocol::Ftp,
                    "smtp" => Protocol::Smtp,
                    "smb" => Protocol::Smb,
                    "rdp" => Protocol::Rdp,
                    other => Protocol::Custom(other.to_string()),
                };

                if !protocols.contains(&protocol) {
                    protocols.push(protocol);
                }
            }
        }

        // Check flows for protocol hints
        if let Some(ref flows) = self.data.flows {
            for flow in flows {
                for step in &flow.steps {
                    use crate::flows::FlowStep;
                    match step {
                        FlowStep::HttpRequest { .. } => {
                            if !protocols.contains(&Protocol::Http) {
                                protocols.push(Protocol::Http);
                                protocols.push(Protocol::Https);
                            }
                        }
                        _ => {
                            // Other flow steps don't indicate specific protocols
                        }
                    }
                }
            }
        }

        // If no protocols detected, default to HTTP/HTTPS for backward compatibility
        if protocols.is_empty() {
            tracing::warn!(
                "Template {} has no protocol indicators, defaulting to HTTP/HTTPS",
                self.data.metadata.id
            );
            protocols.push(Protocol::Http);
            protocols.push(Protocol::Https);
        }

        protocols
    }
}

#[async_trait]
impl Template for YamlTemplateImpl {
    fn measures_network_requests(&self) -> bool {
        true
    }
    fn metadata(&self) -> &TemplateMetadata {
        &self.data.metadata
    }

    async fn execute(&self, target: &Target, context: &Context) -> Result<Vec<Finding>> {
        if self.network_client.is_none()
            || (self.data.flows.is_some() && self.flow_executor.is_none())
        {
            return Err(Error::Execution(
                "YAML template has no configured network transport".into(),
            ));
        }
        tracing::debug!(
            "Executing YAML template {} against {}",
            self.id(),
            target.address
        );

        let mut findings = Vec::new();

        // Execute flows if present
        if let Some(ref flows) = self.data.flows {
            if let (Some(ref flow_executor), Some(ref network_client)) =
                (&self.flow_executor, &self.network_client)
            {
                let mut flow_context = FlowContext::new(
                    target.clone(),
                    network_client.session_manager().clone(),
                    context.clone(),
                );

                let flow_findings = flow_executor
                    .execute_flows(flows, &mut flow_context)
                    .await?;
                findings.extend(flow_findings);
            }
        }

        // Execute network/TCP requests if present
        if let Some(ref network_requests) = self.data.network {
            if let Some(ref network_client) = self.network_client {
                for request_spec in network_requests {
                    let request_findings = self
                        .execute_network_request(request_spec, target, network_client, context)
                        .await?;
                    findings.extend(request_findings);
                }
            }
        }

        // Execute HTTP requests if present
        if let Some(ref http_requests) = self.data.http {
            if let Some(ref network_client) = self.network_client {
                for request_spec in http_requests {
                    let request_findings = self
                        .execute_http_request(request_spec, target, network_client, context)
                        .await?;
                    findings.extend(request_findings);
                }
            }
        }

        Ok(findings)
    }

    fn validate(&self) -> Result<()> {
        self.data.validate()
    }

    /// Get supported protocols (dynamically detected from template content)
    fn supported_protocols(&self) -> Vec<Protocol> {
        self.detect_protocols()
    }
}

impl YamlTemplateImpl {
    /// Execute a single HTTP request specification
    /// Supports both HTTP and HTTPS automatically
    async fn execute_http_request(
        &self,
        spec: &HttpRequestSpec,
        target: &Target,
        network_client: &NetworkClient,
        context: &Context,
    ) -> Result<Vec<Finding>> {
        let mut findings = Vec::new();

        // For HTTP templates, try both HTTP and HTTPS schemes
        let target_variants = if matches!(target.protocol, Protocol::Http | Protocol::Https) {
            // Try inferred scheme first, then the other
            let inferred = target.infer_scheme();
            if inferred == Protocol::Https {
                vec![
                    Target {
                        protocol: Protocol::Https,
                        ..target.clone()
                    },
                    Target {
                        protocol: Protocol::Http,
                        ..target.clone()
                    },
                ]
            } else {
                vec![
                    Target {
                        protocol: Protocol::Http,
                        ..target.clone()
                    },
                    Target {
                        protocol: Protocol::Https,
                        ..target.clone()
                    },
                ]
            }
        } else {
            vec![target.clone()]
        };

        // Try each scheme variant - smart fallback logic
        // If first scheme connects successfully, skip the other (even without findings)
        // Only try fallback scheme if connection/timeout error occurs
        let mut last_error = None;
        for target_variant in target_variants {
            match self
                .execute_http_request_single(&target_variant, spec, network_client, context)
                .await
            {
                Ok(mut variant_findings) => {
                    // SUCCESS: Connection worked - this is the right protocol
                    findings.append(&mut variant_findings);
                    if !findings.is_empty() {
                        tracing::debug!(
                            "Found {} findings with {} scheme, skipping fallback",
                            findings.len(),
                            target_variant.protocol
                        );
                    } else {
                        tracing::debug!(
                            "No findings but {} scheme connected successfully, skipping fallback",
                            target_variant.protocol
                        );
                    }
                    // Always break on successful connection - no need to try other scheme
                    last_error = None;
                    break;
                }
                Err(e) => {
                    let error_str = e.to_string().to_lowercase();
                    // Check if this is a connection/protocol error that warrants trying another scheme
                    let is_connection_error = matches!(&e, Error::HttpRequest(error) if error.is_connect() || error.is_timeout())
                        || error_str.contains("connection refused")
                        || error_str.contains("connection reset")
                        || error_str.contains("ssl")
                        || error_str.contains("tls")
                        || error_str.contains("certificate")
                        || error_str.contains("handshake")
                        || error_str.contains("protocol")
                        || error_str.contains("timeout")
                        || error_str.contains("record overflow")  // TLS record layer error
                        || error_str.contains("overflow")         // Generic overflow errors
                        || error_str.contains("invalid data")     // Protocol mismatch
                        || error_str.contains("unexpected eof")   // Connection dropped
                        || error_str.contains("eof"); // Unexpected end of connection

                    if is_connection_error {
                        tracing::debug!(
                            "{} scheme failed for {} ({}), trying fallback scheme",
                            target_variant.protocol,
                            target_variant.url(),
                            e
                        );
                        // Continue to try next scheme variant, retaining the
                        // failure if neither transport can execute the check.
                        last_error = Some(e);
                    } else {
                        // Non-connection error (e.g., HTTP 4xx/5xx) means the protocol worked
                        // but the request itself had issues - no point trying other scheme
                        tracing::debug!(
                            "{} scheme connected but request failed: {}",
                            target_variant.protocol,
                            e
                        );
                        return Err(e);
                    }
                }
            }
        }

        if let Some(error) = last_error {
            return Err(error);
        }
        Ok(findings)
    }

    /// Execute HTTP request against a single target variant
    async fn execute_http_request_single(
        &self,
        target: &Target,
        spec: &HttpRequestSpec,
        network_client: &NetworkClient,
        context: &Context,
    ) -> Result<Vec<Finding>> {
        let mut findings = Vec::new();

        // NOTE: We intentionally do NOT filter by port number here.
        // If a template explicitly defines an `http:` section, we trust that the
        // template author knows the target service speaks HTTP on that port.
        // Many services run HTTP APIs on non-standard ports (e.g., Ollama on 11434,
        // Elasticsearch on 9200, custom APIs on arbitrary ports).
        // The connection will simply fail if the port doesn't speak HTTP.

        // Get paths to test
        let paths = spec.path.clone().unwrap_or_else(|| vec!["/".to_string()]);

        for path in paths {
            let url = resolve_http_url(&path, target, Some(context))?;
            tracing::debug!("{} {}", spec.method, url);

            // Build headers: merge template headers + context headers + cookies
            let mut request_headers = HashMap::new();
            for (key, value) in &spec.headers {
                request_headers.insert(
                    key.clone(),
                    render_http_text(value, target, Some(context))?.0,
                );
            }
            let request_body = spec
                .body
                .as_ref()
                .map(|body| {
                    render_http_text(body, target, Some(context)).map(|rendered| rendered.0)
                })
                .transpose()?;

            // Add context headers
            for (key, value) in &context.headers {
                request_headers.insert(key.clone(), value.clone());
            }

            // Add cookies from context as Cookie header
            if !context.cookies.is_empty() {
                let cookie_str = context
                    .cookies
                    .iter()
                    .map(|(k, v)| format!("{}={}", k, v))
                    .collect::<Vec<_>>()
                    .join("; ");
                request_headers.insert("Cookie".to_string(), cookie_str);
                tracing::debug!("Added {} cookies to request", context.cookies.len());
            }

            // Execute HTTP request
            let start = std::time::Instant::now();
            let response = match spec.method.to_uppercase().as_str() {
                "GET" => {
                    network_client
                        .get_with_headers(&url, request_headers.clone())
                        .await?
                }
                "POST" => {
                    network_client
                        .post_with_headers(
                            &url,
                            request_body.clone().unwrap_or_default(),
                            request_headers.clone(),
                        )
                        .await?
                }
                method => {
                    let method = method
                        .parse::<reqwest::Method>()
                        .map_err(|e| Error::Execution(format!("Invalid HTTP method: {e}")))?;
                    let mut builder = network_client.client().request(method, &url);
                    for (key, value) in &request_headers {
                        builder = builder.header(key, value);
                    }
                    if let Some(body) = &request_body {
                        builder = builder.body(body.clone());
                    }
                    network_client.request(builder).await?
                }
            };
            let response_time = start.elapsed();

            // Convert to HttpResponse for matching
            let status = response.status().as_u16();
            let headers: Vec<(String, String)> = response
                .headers()
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
                .collect();

            let body = response
                .bytes()
                .await
                .map_err(|e| Error::Network(format!("Failed to read response: {}", e)))?
                .to_vec();

            let http_response = HttpResponse {
                status,
                headers,
                body,
                response_time,
            };

            // Get matchers (either from request spec or template level)
            let matchers = spec.matchers.as_ref().or(self.data.matchers.as_ref());

            let condition = spec
                .matchers_condition
                .or(self.data.matchers_condition)
                .unwrap_or(MatchCondition::Or);

            // Evaluate matchers
            if let Some(matcher_types) = matchers {
                let matchers: Vec<Matcher> = matcher_types
                    .iter()
                    .map(|mt| Matcher::new(mt.clone()))
                    .collect();

                if crate::matcher::match_all(&matchers, &http_response, condition)? {
                    // Create evidence with request and response data
                    let mut evidence = Evidence::new();

                    // Capture the request
                    let request_str = format!(
                        "{} {}\n{}",
                        spec.method.to_uppercase(),
                        url,
                        request_body.clone().unwrap_or_default()
                    );
                    evidence.request = Some(request_str);

                    // Capture the response
                    evidence.response = Some(http_response.body_string());

                    // Capture matched patterns from matchers
                    for matcher in &matchers {
                        if matcher.matches(&http_response)? {
                            let matcher_type = matcher.matcher_type();
                            match matcher_type {
                                MatcherType::Word { words, .. } => {
                                    let response_str = http_response.body_string();
                                    for word in words {
                                        if response_str.contains(word) {
                                            evidence.matched_patterns.push(word.clone());
                                        }
                                    }
                                }
                                MatcherType::Regex { regex, .. } => {
                                    for pattern in regex {
                                        evidence.matched_patterns.push(pattern.clone());
                                    }
                                }
                                MatcherType::Status {
                                    status: statuses, ..
                                } => {
                                    for s in statuses {
                                        if *s == status {
                                            evidence.matched_patterns.push(format!("status:{}", s));
                                        }
                                    }
                                }
                                _ => {}
                            }
                        }
                    }

                    // Add metadata
                    evidence.add_data("status_code", serde_json::json!(status));
                    evidence.add_data(
                        "response_time_ms",
                        serde_json::json!(response_time.as_millis()),
                    );
                    evidence.add_data("method", serde_json::json!(spec.method.to_uppercase()));
                    evidence.add_data("url", serde_json::json!(url));

                    let finding = Finding::new(
                        target.url(),
                        self.id().to_string(),
                        self.metadata().severity,
                        self.metadata().name.clone(),
                        self.metadata().description.clone(),
                    )
                    .with_confidence(self.metadata().confidence.unwrap_or(90))
                    .with_evidence(evidence);

                    findings.push(finding);

                    tracing::info!(
                        "Template {} matched for target {}",
                        self.id(),
                        target.address
                    );
                }
            }
        }

        Ok(findings)
    }

    /// Execute a single network/TCP request specification
    /// Supports multiple ports from --add-ports or uses template's default port
    async fn execute_network_request(
        &self,
        spec: &NetworkRequestSpec,
        target: &Target,
        _network_client: &NetworkClient,
        _context: &Context,
    ) -> Result<Vec<Finding>> {
        let mut findings = Vec::new();

        // Determine ports to test:
        // 1. If target has port (from --add-ports or target:port) → use it
        // 2. Otherwise, use template's default port
        let port = target.port.unwrap_or(spec.port);

        // Execute the network request on the determined port
        let port_findings = self
            .execute_network_request_on_port(spec, target, port)
            .await?;
        findings.extend(port_findings);

        Ok(findings)
    }

    /// Execute network request on a specific port
    async fn execute_network_request_on_port(
        &self,
        spec: &NetworkRequestSpec,
        target: &Target,
        port: u16,
    ) -> Result<Vec<Finding>> {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        use tokio::net::TcpStream;
        use tokio::time::timeout;

        let mut findings = Vec::new();

        let addr = format!("{}:{}", target.address, port);
        tracing::debug!("{} {}", spec.protocol.to_uppercase(), addr);

        // Connect to the target
        let timeout_duration = std::time::Duration::from_secs(10);
        let stream = match timeout(timeout_duration, TcpStream::connect(&addr)).await {
            Ok(Ok(stream)) => stream,
            Ok(Err(e)) => {
                return Err(Error::Network(format!("Failed to connect to {addr}: {e}")));
            }
            Err(_) => {
                return Err(Error::Timeout {
                    duration: format!("TCP connect to {addr}: 10s"),
                });
            }
        };

        let (mut reader, mut writer) = stream.into_split();
        let mut response_data = Vec::new();

        // Send payloads and collect responses
        for payload in &spec.payloads {
            // Parse escape sequences in payload
            let payload_bytes = payload
                .replace("\\r\\n", "\r\n")
                .replace("\\n", "\n")
                .replace("\\r", "\r")
                .replace("\\t", "\t")
                .into_bytes();

            // Send payload
            crate::network::record_request();
            if let Err(e) = writer.write_all(&payload_bytes).await {
                return Err(Error::Network(format!(
                    "Failed to send payload to {addr}: {e}"
                )));
            }

            // Read response with timeout
            let mut buffer = vec![0u8; 8192];
            match timeout(std::time::Duration::from_secs(5), reader.read(&mut buffer)).await {
                Ok(Ok(n)) if n > 0 => {
                    response_data.extend_from_slice(&buffer[..n]);
                }
                Ok(Ok(_)) => {
                    tracing::debug!("Connection closed by {}", addr);
                    break;
                }
                Ok(Err(e)) => {
                    return Err(Error::Network(format!(
                        "Failed to read response from {addr}: {e}"
                    )));
                }
                Err(_) => {
                    return Err(Error::Timeout {
                        duration: format!("TCP read from {addr}: 5s"),
                    });
                }
            }
        }

        // Convert response to string (lossy for binary data)
        let response_str = String::from_utf8_lossy(&response_data).to_string();

        tracing::debug!(
            "Received {} bytes from {}:{}: {:?}",
            response_data.len(),
            target.address,
            port,
            &response_str[..response_str.len().min(200)]
        );

        // Create a pseudo HTTP response for matcher compatibility
        let network_response = HttpResponse {
            status: 200, // Dummy status for network responses
            headers: vec![],
            body: response_data.clone(),
            response_time: std::time::Duration::from_secs(0),
        };

        // Get matchers (either from request spec or template level)
        let matchers = spec.matchers.as_ref().or(self.data.matchers.as_ref());

        let condition = spec
            .matchers_condition
            .or(self.data.matchers_condition)
            .unwrap_or(MatchCondition::Or);

        tracing::debug!(
            "Evaluating {} matchers with condition {:?}",
            matchers.as_ref().map(|m| m.len()).unwrap_or(0),
            condition
        );

        // Evaluate matchers
        if let Some(matcher_types) = matchers {
            let matchers: Vec<Matcher> = matcher_types
                .iter()
                .map(|mt| Matcher::new(mt.clone()))
                .collect();

            if crate::matcher::match_all(&matchers, &network_response, condition)? {
                // Create evidence with request and response data
                let mut evidence = Evidence::new();

                // Capture the request (payloads sent)
                let request_str = spec.payloads.join("\n");
                evidence.request = Some(request_str);

                // Capture the response
                evidence.response = Some(response_str.clone());

                // Capture matched patterns from matchers
                for matcher in &matchers {
                    if matcher.matches(&network_response)? {
                        let matcher_type = matcher.matcher_type();
                        match matcher_type {
                            MatcherType::Word { words, .. } => {
                                for word in words {
                                    if response_str.contains(word) {
                                        evidence.matched_patterns.push(word.clone());
                                    }
                                }
                            }
                            MatcherType::Regex { regex, .. } => {
                                for pattern in regex {
                                    evidence.matched_patterns.push(pattern.clone());
                                }
                            }
                            MatcherType::Status { .. } => {
                                evidence.matched_patterns.push("status_match".to_string());
                            }
                            _ => {}
                        }
                    }
                }

                // Add metadata
                evidence.add_data("protocol", serde_json::json!(spec.protocol));
                evidence.add_data("port", serde_json::json!(port));
                evidence.add_data("response_length", serde_json::json!(response_data.len()));

                // Create finding with evidence
                let finding = Finding::new(
                    format!("{}:{}", target.address, port),
                    self.id().to_string(),
                    self.metadata().severity,
                    self.metadata().name.clone(),
                    self.metadata().description.clone(),
                )
                .with_confidence(self.metadata().confidence.unwrap_or(90))
                .with_evidence(evidence);

                findings.push(finding);

                tracing::info!(
                    "Template {} matched for target {}:{}",
                    self.id(),
                    target.address,
                    port
                );
            }
        }

        Ok(findings)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_yaml_engine_supports_file() {
        let engine = YamlTemplateEngine::new();
        assert!(engine.supports_file(Path::new("test.yaml")));
        assert!(engine.supports_file(Path::new("test.yml")));
        assert!(!engine.supports_file(Path::new("test.py")));
    }
}