kaccy-core 0.2.0

Core business logic for Kaccy Protocol - batching, fee optimization, and transaction management
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
//! Penetration Testing Framework
//!
//! This module provides security testing utilities for identifying vulnerabilities
//! in the application. It includes tests for common security issues like SQL injection,
//! XSS, authentication bypass, and rate limit bypass.
//!
//! # Features
//!
//! - SQL injection testing
//! - XSS vulnerability scanning
//! - Authentication bypass detection
//! - Rate limit bypass detection
//!
//! # Examples
//!
//! ```
//! use kaccy_core::utils::pentest::{PentestSuite, VulnerabilityScanner};
//!
//! let mut scanner = VulnerabilityScanner::new();
//! let results = scanner.scan_sql_injection("SELECT * FROM users WHERE id = ?", "1 OR 1=1");
//! ```

use serde::{Deserialize, Serialize};
use std::time::Instant;

/// Vulnerability severity level
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Severity {
    /// Low severity
    Low,
    /// Medium severity
    Medium,
    /// High severity
    High,
    /// Critical severity
    Critical,
}

/// Vulnerability type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum VulnerabilityType {
    /// SQL injection
    SqlInjection,
    /// Cross-site scripting
    Xss,
    /// Authentication bypass
    AuthBypass,
    /// Rate limit bypass
    RateLimitBypass,
    /// Command injection
    CommandInjection,
    /// Path traversal
    PathTraversal,
    /// CSRF
    Csrf,
    /// Sensitive data exposure
    SensitiveDataExposure,
}

/// Vulnerability finding
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VulnerabilityFinding {
    /// Vulnerability type
    pub vuln_type: VulnerabilityType,
    /// Severity level
    pub severity: Severity,
    /// Description
    pub description: String,
    /// Affected endpoint/component
    pub affected_component: String,
    /// Proof of concept
    pub poc: Option<String>,
    /// Remediation advice
    pub remediation: String,
}

impl VulnerabilityFinding {
    /// Create a new vulnerability finding
    pub fn new(
        vuln_type: VulnerabilityType,
        severity: Severity,
        description: &str,
        component: &str,
    ) -> Self {
        Self {
            vuln_type,
            severity,
            description: description.to_string(),
            affected_component: component.to_string(),
            poc: None,
            remediation: String::new(),
        }
    }

    /// Add proof of concept
    pub fn with_poc(mut self, poc: &str) -> Self {
        self.poc = Some(poc.to_string());
        self
    }

    /// Add remediation advice
    pub fn with_remediation(mut self, remediation: &str) -> Self {
        self.remediation = remediation.to_string();
        self
    }
}

/// SQL injection test patterns
const SQL_INJECTION_PATTERNS: &[&str] = &[
    "' OR '1'='1",
    "1' OR '1'='1",
    "\" OR \"1\"=\"1",
    "1 OR 1=1",
    "'; DROP TABLE users--",
    "1'; DROP TABLE users--",
    "1 UNION SELECT * FROM users",
    "' UNION SELECT NULL--",
];

/// XSS test patterns
const XSS_PATTERNS: &[&str] = &[
    "<script>alert('XSS')</script>",
    "<img src=x onerror=alert('XSS')>",
    "<svg onload=alert('XSS')>",
    "javascript:alert('XSS')",
    "<iframe src='javascript:alert(\"XSS\")'></iframe>",
    "<body onload=alert('XSS')>",
];

/// Path traversal patterns
const PATH_TRAVERSAL_PATTERNS: &[&str] = &[
    "../../../etc/passwd",
    "..\\..\\..\\windows\\system32\\config\\sam",
    "....//....//....//etc/passwd",
    "%2e%2e%2f%2e%2e%2f%2e%2e%2fetc%2fpasswd",
];

/// Vulnerability scanner
pub struct VulnerabilityScanner {
    /// Findings
    findings: Vec<VulnerabilityFinding>,
    /// Test statistics
    tests_run: usize,
    /// Vulnerabilities found
    vulnerabilities_found: usize,
}

impl VulnerabilityScanner {
    /// Create a new vulnerability scanner
    pub fn new() -> Self {
        Self {
            findings: Vec::new(),
            tests_run: 0,
            vulnerabilities_found: 0,
        }
    }

    /// Scan for SQL injection vulnerabilities
    pub fn scan_sql_injection(&mut self, query: &str, user_input: &str) -> bool {
        self.tests_run += 1;
        let mut vulnerable = false;

        for pattern in SQL_INJECTION_PATTERNS {
            let test_input = format!("{}{}", user_input, pattern);

            // Simple check: does the query contain dangerous patterns?
            if query.contains(&test_input) || self.is_sql_injection_pattern(&test_input) {
                let finding = VulnerabilityFinding::new(
                    VulnerabilityType::SqlInjection,
                    Severity::Critical,
                    "Potential SQL injection vulnerability detected",
                    query,
                )
                .with_poc(pattern)
                .with_remediation("Use parameterized queries or prepared statements");

                self.findings.push(finding);
                self.vulnerabilities_found += 1;
                vulnerable = true;
                break;
            }
        }

        vulnerable
    }

    /// Scan for XSS vulnerabilities
    pub fn scan_xss(&mut self, output: &str, user_input: &str) -> bool {
        self.tests_run += 1;
        let mut vulnerable = false;

        for pattern in XSS_PATTERNS {
            let test_input = format!("{}{}", user_input, pattern);

            // Check if user input is reflected without sanitization
            if output.contains(pattern) || self.is_xss_pattern(&test_input) {
                let finding = VulnerabilityFinding::new(
                    VulnerabilityType::Xss,
                    Severity::High,
                    "Cross-site scripting vulnerability detected",
                    "Output",
                )
                .with_poc(pattern)
                .with_remediation("Sanitize and escape user input before rendering");

                self.findings.push(finding);
                self.vulnerabilities_found += 1;
                vulnerable = true;
                break;
            }
        }

        vulnerable
    }

    /// Test authentication bypass
    pub fn test_auth_bypass(&mut self, endpoint: &str, bypass_attempts: &[(&str, &str)]) -> bool {
        self.tests_run += 1;
        let mut vulnerable = false;

        for (username, password) in bypass_attempts {
            // Common auth bypass patterns
            let bypass_patterns = [
                ("admin' --", ""),
                ("admin'/*", ""),
                ("' OR 1=1--", ""),
                ("admin", "' OR '1'='1"),
            ];

            for (user_pattern, pass_pattern) in &bypass_patterns {
                if username.contains(user_pattern) || password.contains(pass_pattern) {
                    let finding = VulnerabilityFinding::new(
                        VulnerabilityType::AuthBypass,
                        Severity::Critical,
                        "Authentication bypass vulnerability detected",
                        endpoint,
                    )
                    .with_poc(&format!(
                        "username: {}, password: {}",
                        user_pattern, pass_pattern
                    ))
                    .with_remediation("Use parameterized queries and proper password hashing");

                    self.findings.push(finding);
                    self.vulnerabilities_found += 1;
                    vulnerable = true;
                    break;
                }
            }
        }

        vulnerable
    }

    /// Test rate limit bypass
    pub fn test_rate_limit(&mut self, endpoint: &str, requests_per_second: usize) -> bool {
        self.tests_run += 1;
        let mut vulnerable = false;

        // Simulate rapid requests
        let threshold = 100; // Example threshold

        if requests_per_second > threshold {
            let finding = VulnerabilityFinding::new(
                VulnerabilityType::RateLimitBypass,
                Severity::Medium,
                &format!(
                    "Rate limit bypass detected: {} requests/sec exceeds threshold of {}",
                    requests_per_second, threshold
                ),
                endpoint,
            )
            .with_poc(&format!(
                "Sent {} requests in 1 second",
                requests_per_second
            ))
            .with_remediation("Implement stricter rate limiting with token bucket or leaky bucket");

            self.findings.push(finding);
            self.vulnerabilities_found += 1;
            vulnerable = true;
        }

        vulnerable
    }

    /// Test path traversal vulnerability
    pub fn test_path_traversal(&mut self, file_path: &str, user_input: &str) -> bool {
        self.tests_run += 1;
        let mut vulnerable = false;

        for pattern in PATH_TRAVERSAL_PATTERNS {
            let test_path = format!("{}{}", user_input, pattern);

            if file_path.contains("..") || test_path.contains("..") {
                let finding = VulnerabilityFinding::new(
                    VulnerabilityType::PathTraversal,
                    Severity::High,
                    "Path traversal vulnerability detected",
                    file_path,
                )
                .with_poc(pattern)
                .with_remediation("Validate and sanitize file paths, use whitelisting");

                self.findings.push(finding);
                self.vulnerabilities_found += 1;
                vulnerable = true;
                break;
            }
        }

        vulnerable
    }

    /// Get all findings
    pub fn get_findings(&self) -> &[VulnerabilityFinding] {
        &self.findings
    }

    /// Get findings by severity
    pub fn get_findings_by_severity(&self, severity: Severity) -> Vec<&VulnerabilityFinding> {
        self.findings
            .iter()
            .filter(|f| f.severity == severity)
            .collect()
    }

    /// Get summary
    pub fn get_summary(&self) -> ScanSummary {
        let critical = self.get_findings_by_severity(Severity::Critical).len();
        let high = self.get_findings_by_severity(Severity::High).len();
        let medium = self.get_findings_by_severity(Severity::Medium).len();
        let low = self.get_findings_by_severity(Severity::Low).len();

        ScanSummary {
            tests_run: self.tests_run,
            vulnerabilities_found: self.vulnerabilities_found,
            critical_findings: critical,
            high_findings: high,
            medium_findings: medium,
            low_findings: low,
        }
    }

    /// Check if string contains SQL injection pattern
    fn is_sql_injection_pattern(&self, input: &str) -> bool {
        let input_lower = input.to_lowercase();
        input_lower.contains("union")
            || input_lower.contains("drop")
            || input_lower.contains("delete")
            || input_lower.contains("insert")
            || input_lower.contains("update")
            || input_lower.contains("exec")
            || input.contains("--")
            || input.contains("/*")
    }

    /// Check if string contains XSS pattern
    fn is_xss_pattern(&self, input: &str) -> bool {
        let input_lower = input.to_lowercase();
        input_lower.contains("<script")
            || input_lower.contains("javascript:")
            || input_lower.contains("onerror")
            || input_lower.contains("onload")
            || input_lower.contains("<iframe")
    }
}

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

/// Scan summary
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScanSummary {
    /// Number of tests run
    pub tests_run: usize,
    /// Total vulnerabilities found
    pub vulnerabilities_found: usize,
    /// Critical findings
    pub critical_findings: usize,
    /// High severity findings
    pub high_findings: usize,
    /// Medium severity findings
    pub medium_findings: usize,
    /// Low severity findings
    pub low_findings: usize,
}

impl ScanSummary {
    /// Check if scan is clean (no vulnerabilities)
    pub fn is_clean(&self) -> bool {
        self.vulnerabilities_found == 0
    }

    /// Get risk score (0-100, higher is worse)
    pub fn risk_score(&self) -> u32 {
        (self.critical_findings * 25)
            .min(100)
            .saturating_add((self.high_findings * 10).min(100))
            .saturating_add((self.medium_findings * 5).min(100))
            .saturating_add(self.low_findings.min(100))
            .min(100) as u32
    }
}

/// Penetration test suite
pub struct PentestSuite {
    /// Suite name
    pub name: String,
    /// Scanners
    scanners: Vec<VulnerabilityScanner>,
    /// Start time
    start_time: Option<Instant>,
}

impl PentestSuite {
    /// Create a new penetration test suite
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            scanners: Vec::new(),
            start_time: None,
        }
    }

    /// Add a scanner to the suite
    pub fn add_scanner(&mut self, scanner: VulnerabilityScanner) {
        self.scanners.push(scanner);
    }

    /// Run all scanners
    pub fn run_all(&mut self) -> PentestReport {
        self.start_time = Some(Instant::now());

        let mut all_findings = Vec::new();
        let mut total_tests = 0;
        let mut total_vulns = 0;

        for scanner in &self.scanners {
            all_findings.extend(scanner.get_findings().iter().cloned());
            total_tests += scanner.tests_run;
            total_vulns += scanner.vulnerabilities_found;
        }

        let duration_ms = self
            .start_time
            .map(|s| s.elapsed().as_millis() as u64)
            .unwrap_or(0);

        PentestReport {
            suite_name: self.name.clone(),
            total_tests,
            total_vulnerabilities: total_vulns,
            findings: all_findings,
            duration_ms,
        }
    }
}

/// Penetration test report
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PentestReport {
    /// Suite name
    pub suite_name: String,
    /// Total tests run
    pub total_tests: usize,
    /// Total vulnerabilities found
    pub total_vulnerabilities: usize,
    /// All findings
    pub findings: Vec<VulnerabilityFinding>,
    /// Duration in milliseconds
    pub duration_ms: u64,
}

impl PentestReport {
    /// Get summary
    pub fn summary(&self) -> ScanSummary {
        let critical = self
            .findings
            .iter()
            .filter(|f| f.severity == Severity::Critical)
            .count();
        let high = self
            .findings
            .iter()
            .filter(|f| f.severity == Severity::High)
            .count();
        let medium = self
            .findings
            .iter()
            .filter(|f| f.severity == Severity::Medium)
            .count();
        let low = self
            .findings
            .iter()
            .filter(|f| f.severity == Severity::Low)
            .count();

        ScanSummary {
            tests_run: self.total_tests,
            vulnerabilities_found: self.total_vulnerabilities,
            critical_findings: critical,
            high_findings: high,
            medium_findings: medium,
            low_findings: low,
        }
    }
}

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

    #[test]
    fn test_vulnerability_scanner_creation() {
        let scanner = VulnerabilityScanner::new();
        assert_eq!(scanner.tests_run, 0);
        assert_eq!(scanner.vulnerabilities_found, 0);
    }

    #[test]
    fn test_sql_injection_detection() {
        let mut scanner = VulnerabilityScanner::new();
        let query = "SELECT * FROM users WHERE id = ";
        let vulnerable = scanner.scan_sql_injection(query, "1' OR '1'='1");

        assert!(vulnerable);
        assert_eq!(scanner.vulnerabilities_found, 1);
    }

    #[test]
    fn test_xss_detection() {
        let mut scanner = VulnerabilityScanner::new();
        let output = "<div><script>alert('XSS')</script></div>";
        let vulnerable = scanner.scan_xss(output, "");

        assert!(vulnerable);
        assert_eq!(scanner.vulnerabilities_found, 1);
    }

    #[test]
    fn test_auth_bypass_detection() {
        let mut scanner = VulnerabilityScanner::new();
        let attempts = vec![("admin' --", "password")];
        let vulnerable = scanner.test_auth_bypass("/login", &attempts);

        assert!(vulnerable);
        assert_eq!(scanner.vulnerabilities_found, 1);
    }

    #[test]
    fn test_rate_limit_bypass_detection() {
        let mut scanner = VulnerabilityScanner::new();
        let vulnerable = scanner.test_rate_limit("/api/login", 500);

        assert!(vulnerable);
        assert_eq!(scanner.vulnerabilities_found, 1);
    }

    #[test]
    fn test_path_traversal_detection() {
        let mut scanner = VulnerabilityScanner::new();
        let vulnerable = scanner.test_path_traversal("/files/", "../../../etc/passwd");

        assert!(vulnerable);
        assert_eq!(scanner.vulnerabilities_found, 1);
    }

    #[test]
    fn test_get_findings_by_severity() {
        let mut scanner = VulnerabilityScanner::new();
        scanner.scan_sql_injection("SELECT * FROM users WHERE id = ", "1' OR '1'='1");

        let critical_findings = scanner.get_findings_by_severity(Severity::Critical);
        assert_eq!(critical_findings.len(), 1);
    }

    #[test]
    fn test_scan_summary() {
        let mut scanner = VulnerabilityScanner::new();
        scanner.scan_sql_injection("SELECT * FROM users WHERE id = ", "1' OR '1'='1");

        let summary = scanner.get_summary();
        assert_eq!(summary.vulnerabilities_found, 1);
        assert_eq!(summary.critical_findings, 1);
    }

    #[test]
    fn test_risk_score() {
        let summary = ScanSummary {
            tests_run: 10,
            vulnerabilities_found: 2,
            critical_findings: 1,
            high_findings: 1,
            medium_findings: 0,
            low_findings: 0,
        };

        let risk_score = summary.risk_score();
        assert!(risk_score > 0);
    }

    #[test]
    fn test_pentest_suite() {
        let mut suite = PentestSuite::new("Security Test Suite");
        let mut scanner = VulnerabilityScanner::new();
        scanner.scan_sql_injection("SELECT * FROM users WHERE id = ", "1' OR '1'='1");

        suite.add_scanner(scanner);
        let report = suite.run_all();

        assert_eq!(report.total_vulnerabilities, 1);
    }
}