rprobe 0.9.0

A simple tool to probe a remote host http or https connection
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
// File: phpbasic.rs
// SPDX-License-Identifier: MIT OR Apache-2.0
//
// Copyright (c) 2023-2025
// - Volker Schwaberow <volker@schwaberow.de>

use crate::httpinner::HttpInner;
use crate::plugins::pattern_matcher::OptimizedPatternMatcher;
use crate::plugins::{Plugin, PluginCategory, PluginError, PluginMetadata, PluginResult};
use log::{debug, info};
use once_cell::sync::Lazy;
use regex::Regex;

pub struct PHPBasicPlugin;

static PHP_VERSION_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"PHP\s*/?(\d+\.\d+(?:\.\d+)?)").expect("Failed to compile PHP version regex")
});

static BODY_PATTERNS: Lazy<OptimizedPatternMatcher> = Lazy::new(|| {
    OptimizedPatternMatcher::new(
        &[
            ("<?php", "PHPCode"),
            ("PHP Warning", "PHPWarning"),
            ("PHP Parse error", "PHPParseError"),
            ("Fatal error: Uncaught Error", "PHPFatalError"),
            ("Notice: Undefined variable", "PHPNotice"),
            ("Deprecated:", "PHPDeprecated"),
        ],
        &[],
    )
});

static PATTERN_CONFIDENCE: Lazy<std::collections::HashMap<&'static str, u8>> = Lazy::new(|| {
    [
        ("PHPCode", 4u8),
        ("PHPWarning", 3u8),
        ("PHPParseError", 3u8),
        ("PHPFatalError", 3u8),
        ("PHPNotice", 2u8),
        ("PHPDeprecated", 2u8),
    ]
    .iter()
    .cloned()
    .collect()
});

impl Plugin for PHPBasicPlugin {
    fn metadata(&self) -> PluginMetadata {
        PluginMetadata {
            name: "PHP Basic",
            version: "1.2.0",
            description: "PHP scripting language detection through headers, cookies, error messages, and source code patterns",
            category: PluginCategory::ApplicationFramework,
            author: "rprobe team",
            priority: 4,
            enabled: true,
        }
    }

    fn should_run(&self, http_inner: &HttpInner) -> bool {
        if !http_inner.success() {
            let status = http_inner.status();
            if (500..600).contains(&status) {
                return true;
            }
            return false;
        }

        let headers = http_inner.headers();

        if let Some(powered_by) = headers.get("x-powered-by") {
            if let Ok(powered_str) = powered_by.to_str() {
                if powered_str.to_lowercase().contains("php") {
                    return true;
                }
            }
        }

        if let Some(server) = headers.get("server") {
            if let Ok(server_str) = server.to_str() {
                if server_str.to_lowercase().contains("php") {
                    return true;
                }
            }
        }

        for val in headers.get_all("set-cookie").iter() {
            if let Ok(cookie_str) = val.to_str() {
                if cookie_str.contains("PHPSESSID") {
                    return true;
                }
            }
        }

        true
    }

    fn run(&self, http_inner: &HttpInner) -> Result<Option<PluginResult>, PluginError> {
        debug!("Starting PHP Basic detection for URL: {}", http_inner.url());

        let mut detections: Vec<String> = Vec::new();
        let mut confidence_score = 0u8;
        let headers = http_inner.headers();

        if let Some(x_powered_by) = headers.get("x-powered-by") {
            let header_value = x_powered_by.to_str().unwrap_or("");
            if let Some(captures) = PHP_VERSION_REGEX.captures(header_value) {
                let version = captures.get(1).map_or("", |m| m.as_str());
                debug!("PHP detected: X-Powered-By Header with version {}", version);
                detections.push(format!("XPoweredBy[PHP/{}]", version));
                confidence_score = confidence_score.saturating_add(5);
            } else if header_value.to_lowercase().contains("php") {
                debug!("PHP detected: X-Powered-By Header contains PHP");
                detections.push("XPoweredBy[PHP]".to_string());
                confidence_score = confidence_score.saturating_add(4);
            }
        }

        if let Some(server_header) = headers.get("server") {
            let server_value = server_header.to_str().unwrap_or("");
            if let Some(captures) = PHP_VERSION_REGEX.captures(server_value) {
                let version = captures.get(1).map_or("", |m| m.as_str());
                debug!("PHP detected: Server Header with version {}", version);
                detections.push(format!("HTTPServer[PHP/{}]", version));
                confidence_score = confidence_score.saturating_add(4);
            } else if server_value.to_lowercase().contains("php") {
                debug!("PHP detected: Server Header contains PHP");
                detections.push("HTTPServer[PHP]".to_string());
                confidence_score = confidence_score.saturating_add(3);
            }
        }

        for val in headers.get_all("set-cookie").iter() {
            let cookie_str = val.to_str().unwrap_or("");
            if cookie_str.contains("PHPSESSID") {
                debug!("PHP detected: PHPSESSID Cookie found");
                detections.push("Cookie[PHPSESSID]".to_string());
                confidence_score = confidence_score.saturating_add(4);
            }
        }

        let body = http_inner.body();
        if !body.is_empty() && body.len() < 100000 {
            let body_matches = BODY_PATTERNS.find_matches(body);
            for description in body_matches {
                debug!("PHP detected: Body pattern {} found", description);
                detections.push(description.to_string());
                let pattern_confidence = PATTERN_CONFIDENCE.get(description).copied().unwrap_or(1);
                confidence_score = confidence_score.saturating_add(pattern_confidence);
            }
        }

        if detections.is_empty() || confidence_score < 2 {
            debug!("No confident PHP detection for URL: {}", http_inner.url());
            return Ok(None);
        }

        let order = vec![
            "XPoweredBy[PHP/".to_string(),
            "HTTPServer[PHP/".to_string(),
            "XPoweredBy[PHP]".to_string(),
            "HTTPServer[PHP]".to_string(),
            "Cookie[PHPSESSID]".to_string(),
            "PHPCode".to_string(),
            "PHPWarning".to_string(),
            "PHPParseError".to_string(),
            "PHPFatalError".to_string(),
            "PHPNotice".to_string(),
            "PHPDeprecated".to_string(),
        ];

        detections.sort_by_key(|det| {
            order
                .iter()
                .position(|o| {
                    if o.ends_with('/') {
                        det.starts_with(o)
                    } else {
                        det == o
                    }
                })
                .unwrap_or(order.len())
        });

        detections.dedup();

        let final_confidence = std::cmp::min(confidence_score, 8);
        let detection_info = format!("PHP Scripting Language ({})", detections.join(", "));

        info!(
            "PHP detected: {} (confidence: {}/10)",
            detection_info, final_confidence
        );

        Ok(Some(PluginResult {
            plugin_name: self.metadata().name.to_string(),
            detection_info,
            confidence: final_confidence,
            execution_time_ms: 0,
            category: PluginCategory::ApplicationFramework,
        }))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
    use std::str::FromStr;

    fn create_test_http_inner(body: &str, headers: Vec<(&str, &str)>) -> HttpInner {
        let mut header_map = HeaderMap::new();
        for (key, value) in headers {
            header_map.insert(
                HeaderName::from_str(key).unwrap(),
                HeaderValue::from_str(value).unwrap(),
            );
        }

        HttpInner::new_with_all(
            header_map,
            body.to_string(),
            200,
            "https://example.com".to_string(),
            true,
        )
    }

    #[test]
    fn test_metadata() {
        let plugin = PHPBasicPlugin;
        let metadata = plugin.metadata();

        assert_eq!(metadata.name, "PHP Basic");
        assert_eq!(metadata.version, "1.2.0");
        assert_eq!(metadata.category, PluginCategory::ApplicationFramework);
        assert_eq!(metadata.author, "rprobe team");
        assert_eq!(metadata.priority, 4);
        assert!(metadata.enabled);
        assert!(metadata.description.contains("PHP"));
    }

    #[test]
    fn test_x_powered_by_php_version() {
        let plugin = PHPBasicPlugin;
        let http_inner = create_test_http_inner("", vec![("x-powered-by", "PHP/8.0.0")]);

        let result = plugin.run(&http_inner).unwrap();
        assert!(result.is_some());

        let plugin_result = result.unwrap();
        assert!(plugin_result
            .detection_info
            .contains("XPoweredBy[PHP/8.0.0]"));
        assert!(plugin_result.confidence >= 5);
    }

    #[test]
    fn test_x_powered_by_php_generic() {
        let plugin = PHPBasicPlugin;
        let http_inner = create_test_http_inner("", vec![("x-powered-by", "PHP")]);

        let result = plugin.run(&http_inner).unwrap();
        assert!(result.is_some());

        let plugin_result = result.unwrap();
        assert!(plugin_result.detection_info.contains("XPoweredBy[PHP]"));
        assert!(plugin_result.confidence >= 4);
    }

    #[test]
    fn test_server_header_php_version() {
        let plugin = PHPBasicPlugin;
        let http_inner =
            create_test_http_inner("", vec![("server", "Apache/2.4.41 (Ubuntu) PHP/7.4.3")]);

        let result = plugin.run(&http_inner).unwrap();
        assert!(result.is_some());

        let plugin_result = result.unwrap();
        assert!(plugin_result
            .detection_info
            .contains("HTTPServer[PHP/7.4.3]"));
        assert!(plugin_result.confidence >= 4);
    }

    #[test]
    fn test_phpsessid_cookie() {
        let plugin = PHPBasicPlugin;
        let http_inner = create_test_http_inner(
            "",
            vec![("set-cookie", "PHPSESSID=abc123def456; path=/; HttpOnly")],
        );

        let result = plugin.run(&http_inner).unwrap();
        assert!(result.is_some());

        let plugin_result = result.unwrap();
        assert!(plugin_result.detection_info.contains("Cookie[PHPSESSID]"));
        assert!(plugin_result.confidence >= 4);
    }

    #[test]
    fn test_php_code_in_body() {
        let plugin = PHPBasicPlugin;
        let http_inner = create_test_http_inner("<?php echo 'Hello World'; ?>", vec![]);

        let result = plugin.run(&http_inner).unwrap();
        assert!(result.is_some());

        let plugin_result = result.unwrap();
        assert!(plugin_result.detection_info.contains("PHPCode"));
        assert!(plugin_result.confidence >= 4);
    }

    #[test]
    fn test_php_warning_in_body() {
        let plugin = PHPBasicPlugin;
        let http_inner = create_test_http_inner("PHP Warning: Division by zero", vec![]);

        let result = plugin.run(&http_inner).unwrap();
        assert!(result.is_some());

        let plugin_result = result.unwrap();
        assert!(plugin_result.detection_info.contains("PHPWarning"));
        assert!(plugin_result.confidence >= 3);
    }

    #[test]
    fn test_php_parse_error() {
        let plugin = PHPBasicPlugin;
        let http_inner =
            create_test_http_inner("PHP Parse error: syntax error, unexpected token", vec![]);

        let result = plugin.run(&http_inner).unwrap();
        assert!(result.is_some());

        let plugin_result = result.unwrap();
        assert!(plugin_result.detection_info.contains("PHPParseError"));
        assert!(plugin_result.confidence >= 3);
    }

    #[test]
    fn test_php_fatal_error() {
        let plugin = PHPBasicPlugin;
        let http_inner = create_test_http_inner(
            "Fatal error: Uncaught Error: Call to undefined function",
            vec![],
        );

        let result = plugin.run(&http_inner).unwrap();
        assert!(result.is_some());

        let plugin_result = result.unwrap();
        assert!(plugin_result.detection_info.contains("PHPFatalError"));
        assert!(plugin_result.confidence >= 3);
    }

    #[test]
    fn test_php_notice() {
        let plugin = PHPBasicPlugin;
        let http_inner = create_test_http_inner("Notice: Undefined variable: test", vec![]);

        let result = plugin.run(&http_inner).unwrap();
        assert!(result.is_some());

        let plugin_result = result.unwrap();
        assert!(plugin_result.detection_info.contains("PHPNotice"));
        assert!(plugin_result.confidence >= 2);
    }

    #[test]
    fn test_php_deprecated() {
        let plugin = PHPBasicPlugin;
        let http_inner = create_test_http_inner(
            "Deprecated: Function create_function() is deprecated",
            vec![],
        );

        let result = plugin.run(&http_inner).unwrap();
        assert!(result.is_some());

        let plugin_result = result.unwrap();
        assert!(plugin_result.detection_info.contains("PHPDeprecated"));
        assert!(plugin_result.confidence >= 2);
    }

    #[test]
    fn test_multiple_detections() {
        let plugin = PHPBasicPlugin;
        let http_inner = create_test_http_inner(
            "<?php echo 'Hello'; ?>\nPHP Warning: Notice",
            vec![
                ("x-powered-by", "PHP/8.0.0"),
                ("set-cookie", "PHPSESSID=abc123; path=/"),
            ],
        );

        let result = plugin.run(&http_inner).unwrap();
        assert!(result.is_some());

        let plugin_result = result.unwrap();
        assert!(plugin_result
            .detection_info
            .contains("XPoweredBy[PHP/8.0.0]"));
        assert!(plugin_result.detection_info.contains("Cookie[PHPSESSID]"));
        assert!(plugin_result.detection_info.contains("PHPCode"));
        assert!(plugin_result.detection_info.contains("PHPWarning"));
        assert_eq!(plugin_result.confidence, 8);
    }

    #[test]
    fn test_no_detection() {
        let plugin = PHPBasicPlugin;
        let http_inner = create_test_http_inner("", vec![]);

        let result = plugin.run(&http_inner).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_should_run_failed_request() {
        let plugin = PHPBasicPlugin;
        let mut http_inner = create_test_http_inner("", vec![]);
        http_inner.set_success(false);
        http_inner.set_status(404);

        assert!(!plugin.should_run(&http_inner));
    }

    #[test]
    fn test_should_run_server_error() {
        let plugin = PHPBasicPlugin;
        let mut http_inner = create_test_http_inner("", vec![]);
        http_inner.set_success(false);
        http_inner.set_status(500);

        assert!(plugin.should_run(&http_inner));
    }

    #[test]
    fn test_should_run_with_php_header() {
        let plugin = PHPBasicPlugin;
        let http_inner = create_test_http_inner("", vec![("x-powered-by", "PHP/7.4")]);

        assert!(plugin.should_run(&http_inner));
    }

    #[test]
    fn test_should_run_with_phpsessid() {
        let plugin = PHPBasicPlugin;
        let http_inner = create_test_http_inner("", vec![("set-cookie", "PHPSESSID=test")]);

        assert!(plugin.should_run(&http_inner));
    }

    #[test]
    fn test_large_body_skipped() {
        let plugin = PHPBasicPlugin;
        let large_content = "<?php ".repeat(20000);
        let http_inner = create_test_http_inner(&large_content, vec![]);

        let result = plugin.run(&http_inner).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_confidence_scoring() {
        let plugin = PHPBasicPlugin;

        let test_cases = vec![
            (("", vec![("x-powered-by", "PHP/8.0.0")]), 5),
            (("", vec![("x-powered-by", "PHP")]), 4),
            (("", vec![("set-cookie", "PHPSESSID=test")]), 4),
            (("<?php echo 'test'; ?>", vec![]), 4),
            (("PHP Warning: test", vec![]), 3),
            (("Notice: Undefined variable", vec![]), 2),
        ];

        for ((body, headers), expected_min_confidence) in test_cases {
            let http_inner = create_test_http_inner(body, headers);
            let result = plugin.run(&http_inner).unwrap();

            assert!(result.is_some());
            let plugin_result = result.unwrap();
            assert!(plugin_result.confidence >= expected_min_confidence);
        }
    }

    #[test]
    fn test_plugin_name_consistency() {
        let plugin = PHPBasicPlugin;
        let http_inner = create_test_http_inner("", vec![("x-powered-by", "PHP/7.4")]);

        let result = plugin.run(&http_inner).unwrap();
        assert!(result.is_some());

        let plugin_result = result.unwrap();
        assert_eq!(plugin_result.plugin_name, "PHP Basic");
        assert_eq!(plugin_result.category, PluginCategory::ApplicationFramework);
    }

    #[test]
    fn test_version_regex() {
        let plugin = PHPBasicPlugin;

        let test_cases = vec![
            ("PHP/8.0.0", "8.0.0"),
            ("PHP/7.4.3", "7.4.3"),
            ("PHP 5.6", "5.6"),
            ("Apache/2.4.41 PHP/7.2.24", "7.2.24"),
        ];

        for (input, expected_version) in test_cases {
            let http_inner = create_test_http_inner("", vec![("x-powered-by", input)]);
            let result = plugin.run(&http_inner).unwrap();

            assert!(result.is_some());
            let plugin_result = result.unwrap();
            assert!(plugin_result
                .detection_info
                .contains(&format!("PHP/{}", expected_version)));
        }
    }

    #[test]
    fn test_deduplication() {
        let plugin = PHPBasicPlugin;
        let http_inner = create_test_http_inner(
            "<?php echo 'test'; ?> <?php echo 'again'; ?>",
            vec![("x-powered-by", "PHP/7.4")],
        );

        let result = plugin.run(&http_inner).unwrap();
        assert!(result.is_some());

        let plugin_result = result.unwrap();
        let detection_info = &plugin_result.detection_info;

        let php_code_count = detection_info.matches("PHPCode").count();
        assert_eq!(php_code_count, 1);
    }
}