rinzler-core 0.1.11-alpha

Core library for Rinzler - API scanner data models and database
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
// Report generation from database

use crate::data::Database;
use rusqlite::Result;
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::Write;
use std::path::Path;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ReportFormat {
    Text,
    Json,
    Csv,
    Html,
    Markdown,
}

impl ReportFormat {
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "text" => Some(ReportFormat::Text),
            "json" => Some(ReportFormat::Json),
            "csv" => Some(ReportFormat::Csv),
            "html" => Some(ReportFormat::Html),
            "markdown" | "md" => Some(ReportFormat::Markdown),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReportData {
    pub session_id: String,
    pub total_nodes: usize,
    pub findings: Vec<FindingData>,
    pub severity_counts: SeverityCounts,
    pub scan_info: ScanInfo,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sitemap_nodes: Option<Vec<SitemapNode>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SitemapNode {
    pub url: String,
    pub status_code: u16,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FindingData {
    pub id: i64,
    pub severity: String,
    pub title: String,
    pub description: String,
    pub url: String,
    pub finding_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cwe_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub owasp_category: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub impact: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remediation: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SeverityCounts {
    pub critical: i64,
    pub high: i64,
    pub medium: i64,
    pub low: i64,
    pub info: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScanInfo {
    pub start_time: i64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<i64>,
    pub status: String,
    pub seed_urls: String,
}

pub fn gather_report_data(
    db: &Database,
    session_id: &str,
    include_sitemap: bool,
) -> Result<ReportData> {
    // Get session info
    let scan_info = {
        let conn = db.get_connection();
        let mut stmt = conn.prepare(
            "SELECT start_time, end_time, status, seed_urls FROM crawl_sessions WHERE id = ?1",
        )?;

        stmt.query_row([session_id], |row| {
            Ok(ScanInfo {
                start_time: row.get(0)?,
                end_time: row.get(1)?,
                status: row.get(2)?,
                seed_urls: row.get(3)?,
            })
        })?
    };

    // Get node count
    let nodes = db.get_nodes_by_session(session_id)?;
    let total_nodes = nodes.len();

    // Get severity counts
    let severity_counts_raw = db.get_findings_count_by_severity(session_id)?;
    let mut severity_counts = SeverityCounts {
        critical: 0,
        high: 0,
        medium: 0,
        low: 0,
        info: 0,
    };

    for (severity, count) in severity_counts_raw {
        match severity.as_str() {
            "critical" => severity_counts.critical = count,
            "high" => severity_counts.high = count,
            "medium" => severity_counts.medium = count,
            "low" => severity_counts.low = count,
            "info" => severity_counts.info = count,
            _ => {}
        }
    }

    // Get detailed findings
    let conn = db.get_connection();
    let mut stmt = conn.prepare(
        "SELECT f.id, f.severity, f.title, f.description, n.url, f.finding_type,
                f.cwe_id, f.owasp_category, f.impact, f.remediation
         FROM findings f
         JOIN nodes n ON f.node_id = n.id
         WHERE f.session_id = ?1 AND f.false_positive = 0
         ORDER BY CASE f.severity
             WHEN 'critical' THEN 1
             WHEN 'high' THEN 2
             WHEN 'medium' THEN 3
             WHEN 'low' THEN 4
             WHEN 'info' THEN 5
         END, f.id",
    )?;

    let findings = stmt
        .query_map([session_id], |row| {
            Ok(FindingData {
                id: row.get(0)?,
                severity: row.get(1)?,
                title: row.get(2)?,
                description: row.get(3)?,
                url: row.get(4)?,
                finding_type: row.get(5)?,
                cwe_id: row.get(6)?,
                owasp_category: row.get(7)?,
                impact: row.get(8)?,
                remediation: row.get(9)?,
            })
        })?
        .collect::<Result<Vec<_>>>()?;

    // Optionally gather sitemap data
    let sitemap_nodes = if include_sitemap {
        let conn = db.get_connection();
        let mut stmt = conn.prepare(
            "SELECT n.url, n.response_code, n.content_type
             FROM nodes n
             JOIN maps m ON n.map_id = m.id
             WHERE m.session_id = ?1
             ORDER BY n.url",
        )?;

        let nodes = stmt
            .query_map([session_id], |row| {
                Ok(SitemapNode {
                    url: row.get(0)?,
                    status_code: row.get::<_, Option<u16>>(1)?.unwrap_or(0),
                    content_type: row.get(2)?,
                })
            })?
            .collect::<Result<Vec<_>>>()?;

        Some(nodes)
    } else {
        None
    };

    Ok(ReportData {
        session_id: session_id.to_string(),
        total_nodes,
        findings,
        severity_counts,
        scan_info,
        sitemap_nodes,
    })
}

pub fn generate_text_report(data: &ReportData) -> String {
    let mut report = String::new();

    // Header
    report.push_str(
        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n",
    );
    report.push_str("                        RINZLER SECURITY SCAN REPORT\n");
    report.push_str(
        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n",
    );

    // Session info
    report.push_str(&format!("Session ID:   {}\n", data.session_id));
    report.push_str(&format!("Status:       {}\n", data.status_to_string()));
    report.push_str(&format!(
        "Scan Date:    {}\n",
        data.format_timestamp(data.scan_info.start_time)
    ));

    if let Some(end_time) = data.scan_info.end_time {
        let duration = end_time - data.scan_info.start_time;
        report.push_str(&format!("Duration:     {} seconds\n", duration));
    }

    report.push_str(&format!("Targets:      {}\n", data.format_targets()));
    report.push_str(&format!("Pages Found:  {}\n", data.total_nodes));
    report.push('\n');

    // Include sitemap if present
    if let Some(ref sitemap_nodes) = data.sitemap_nodes {
        report.push_str(
            "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n",
        );
        report.push_str("SITE MAP\n");
        report.push_str(
            "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n",
        );
        report.push_str(&generate_sitemap_tree(sitemap_nodes));
        report.push('\n');
    }

    // Executive Summary
    report.push_str(
        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n",
    );
    report.push_str("EXECUTIVE SUMMARY\n");
    report.push_str(
        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n",
    );

    let total_findings = data.severity_counts.critical
        + data.severity_counts.high
        + data.severity_counts.medium
        + data.severity_counts.low
        + data.severity_counts.info;

    report.push_str(&format!("Total Findings: {}\n\n", total_findings));

    if data.severity_counts.critical > 0 {
        report.push_str(&format!(
            "  [CRITICAL] {}  (Immediate action required)\n",
            data.severity_counts.critical
        ));
    }
    if data.severity_counts.high > 0 {
        report.push_str(&format!(
            "  [HIGH]     {}  (High priority)\n",
            data.severity_counts.high
        ));
    }
    if data.severity_counts.medium > 0 {
        report.push_str(&format!(
            "  [MEDIUM]   {}  (Should be addressed)\n",
            data.severity_counts.medium
        ));
    }
    if data.severity_counts.low > 0 {
        report.push_str(&format!(
            "  [LOW]      {}  (Minor issues)\n",
            data.severity_counts.low
        ));
    }
    if data.severity_counts.info > 0 {
        report.push_str(&format!(
            "  [INFO]     {}  (Informational)\n",
            data.severity_counts.info
        ));
    }
    report.push('\n');

    // Detailed findings
    if !data.findings.is_empty() {
        report.push_str(
            "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n",
        );
        report.push_str("DETAILED FINDINGS\n");
        report.push_str(
            "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n",
        );

        for (idx, finding) in data.findings.iter().enumerate() {
            report.push_str(&format!("[{}] {}\n", idx + 1, finding.title));
            report.push_str(&format!(
                "Severity:     {}\n",
                finding.severity.to_uppercase()
            ));
            report.push_str(&format!(
                "Type:         {}\n",
                format_finding_type(&finding.finding_type)
            ));
            report.push_str(&format!("URL:          {}\n", finding.url));

            if let Some(ref cwe) = finding.cwe_id {
                report.push_str(&format!("CWE:          {}\n", cwe));
            }
            if let Some(ref owasp) = finding.owasp_category {
                report.push_str(&format!("OWASP:        {}\n", owasp));
            }

            report.push_str("\nDescription:\n");
            report.push_str(&wrap_text(&finding.description, 80, "  "));
            report.push_str("\n\n");

            if let Some(ref impact) = finding.impact {
                report.push_str("Impact:\n");
                report.push_str(&wrap_text(impact, 80, "  "));
                report.push_str("\n\n");
            }

            if let Some(ref remediation) = finding.remediation {
                report.push_str("Remediation:\n");
                report.push_str(&wrap_text(remediation, 80, "  "));
                report.push_str("\n\n");
            }

            report.push_str("────────────────────────────────────────────────────────────────────────────────\n\n");
        }
    }

    // Footer
    report.push_str(
        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n",
    );
    report.push_str("                          End of Report\n");
    report.push_str(
        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n",
    );
    report.push_str("\nGenerated by Rinzler - A somewhat intelligent Web API scanner\n");
    report.push_str("For authorized security testing only.\n\n");

    report
}

pub fn generate_json_report(data: &ReportData) -> Result<String, serde_json::Error> {
    // Create a structured JSON report with enhanced metadata
    let json_report = serde_json::json!({
        "report": {
            "metadata": {
                "generator": "Rinzler",
                "version": env!("CARGO_PKG_VERSION"),
                "generated_at": chrono::Utc::now().to_rfc3339(),
                "format": "json",
                "disclaimer": "For authorized security testing only"
            },
            "session": {
                "id": data.session_id,
                "status": data.scan_info.status,
                "start_time": format_iso8601_timestamp(data.scan_info.start_time),
                "end_time": data.scan_info.end_time.map(format_iso8601_timestamp),
                "duration_seconds": data.scan_info.end_time.map(|end| end - data.scan_info.start_time),
                "targets": parse_targets(&data.scan_info.seed_urls)
            },
            "summary": {
                "total_pages": data.total_nodes,
                "total_findings": data.severity_counts.critical
                    + data.severity_counts.high
                    + data.severity_counts.medium
                    + data.severity_counts.low
                    + data.severity_counts.info,
                "severity_breakdown": {
                    "critical": data.severity_counts.critical,
                    "high": data.severity_counts.high,
                    "medium": data.severity_counts.medium,
                    "low": data.severity_counts.low,
                    "info": data.severity_counts.info
                }
            },
            "findings": data.findings,
            "sitemap": data.sitemap_nodes.as_ref().map(|nodes| {
                serde_json::json!({
                    "total_nodes": nodes.len(),
                    "nodes": nodes
                })
            })
        }
    });

    serde_json::to_string_pretty(&json_report)
}

pub fn save_report(content: &str, path: &Path) -> std::io::Result<()> {
    let mut file = File::create(path)?;
    file.write_all(content.as_bytes())?;
    Ok(())
}

// Helper functions
impl ReportData {
    fn status_to_string(&self) -> &str {
        match self.scan_info.status.as_str() {
            "completed" => "Completed",
            "failed" => "Failed",
            "running" => "Running",
            "cancelled" => "Cancelled",
            _ => "Unknown",
        }
    }

    fn format_timestamp(&self, timestamp: i64) -> String {
        use chrono::{DateTime, Utc};
        let datetime = DateTime::<Utc>::from_timestamp(timestamp, 0).unwrap_or_else(Utc::now);
        datetime.format("%Y-%m-%d %H:%M:%S UTC").to_string()
    }

    fn format_targets(&self) -> String {
        // Parse JSON seed_urls
        if let Ok(urls) = serde_json::from_str::<Vec<String>>(&self.scan_info.seed_urls) {
            if urls.len() == 1 {
                urls[0].clone()
            } else {
                format!("{} URLs", urls.len())
            }
        } else {
            "Unknown".to_string()
        }
    }
}

fn format_finding_type(finding_type: &str) -> String {
    finding_type
        .replace('_', " ")
        .split_whitespace()
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

fn wrap_text(text: &str, width: usize, indent: &str) -> String {
    let mut result = String::new();
    let mut current_line = String::new();

    for word in text.split_whitespace() {
        if current_line.len() + word.len() + 1 > width - indent.len() && !current_line.is_empty() {
            result.push_str(indent);
            result.push_str(&current_line);
            result.push('\n');
            current_line.clear();
        }

        if !current_line.is_empty() {
            current_line.push(' ');
        }
        current_line.push_str(word);
    }

    if !current_line.is_empty() {
        result.push_str(indent);
        result.push_str(&current_line);
        result.push('\n');
    }

    result
}

fn generate_sitemap_tree(nodes: &[SitemapNode]) -> String {
    use std::collections::HashMap;

    if nodes.is_empty() {
        return "  (empty)\n".to_string();
    }

    // Build a tree structure from URLs
    let mut tree: HashMap<String, Vec<(String, &SitemapNode)>> = HashMap::new();

    for node in nodes {
        if let Ok(parsed) = url::Url::parse(&node.url) {
            let domain = parsed.host_str().unwrap_or("unknown").to_string();
            let path = parsed.path().to_string();

            // Split path into segments
            let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();

            // Build hierarchical path
            let mut current_path = domain.clone();
            tree.entry(current_path.clone()).or_default();

            for (i, segment) in segments.iter().enumerate() {
                let parent_path = current_path.clone();
                current_path = format!("{}/{}", current_path, segment);

                // Only add the leaf node with metadata
                if i == segments.len() - 1 {
                    tree.entry(parent_path)
                        .or_default()
                        .push((current_path.clone(), node));
                } else {
                    tree.entry(parent_path)
                        .or_default()
                        .push((current_path.clone(), node));
                    tree.entry(current_path.clone()).or_default();
                }
            }

            // If root path, add it directly to domain
            if segments.is_empty() {
                tree.entry(domain.clone())
                    .or_default()
                    .push((domain.clone(), node));
            }
        }
    }

    // Simple flat list representation for now (tree structure is complex)
    let mut result = String::new();

    for (i, node) in nodes.iter().enumerate() {
        let is_last = i == nodes.len() - 1;
        let prefix = if is_last { "└── " } else { "├── " };

        // Extract path from URL
        let display_url = if let Ok(parsed) = url::Url::parse(&node.url) {
            let host = parsed.host_str().unwrap_or("unknown");
            let path = parsed.path();
            if i == 0 {
                format!("{}{}", host, path)
            } else {
                // Check if same host as previous
                let prev_host = url::Url::parse(&nodes[i - 1].url)
                    .ok()
                    .and_then(|u| u.host_str().map(String::from));
                if prev_host.as_deref() == Some(host) {
                    format!("    {}", path)
                } else {
                    format!("{}{}", host, path)
                }
            }
        } else {
            node.url.clone()
        };

        // Format status code with color indicator
        let status_indicator = match node.status_code {
            200..=299 => "✓",
            300..=399 => "→",
            400..=499 => "⚠",
            500..=599 => "✗",
            _ => "?",
        };

        let content_type_short = node
            .content_type
            .as_ref()
            .and_then(|ct| ct.split(';').next())
            .and_then(|ct| ct.split('/').nth(1))
            .unwrap_or("?");

        result.push_str(&format!(
            "{}{}  [{} {}] {}\n",
            prefix, display_url, status_indicator, node.status_code, content_type_short
        ));
    }

    result
}

fn format_iso8601_timestamp(timestamp: i64) -> String {
    use chrono::{DateTime, Utc};
    let datetime = DateTime::<Utc>::from_timestamp(timestamp, 0).unwrap_or_else(Utc::now);
    datetime.to_rfc3339()
}

fn parse_targets(seed_urls_json: &str) -> serde_json::Value {
    serde_json::from_str::<Vec<String>>(seed_urls_json)
        .map(|urls| serde_json::json!(urls))
        .unwrap_or_else(|_| serde_json::json!([]))
}