repositories

percival

Follow the trail a handle leaves across the web: username search across 5,700+ sites, in Rust

clonegit clone https://git.daemon-sec.xyz/percival.git
selfcheck.rsRust185 lines5.9 KiBraw download
//! Site self-check: does each detector still recognise a known account and
//! reject a canary? Results can be written as an overlay that disables
//! broken sites for future scans.

use std::collections::BTreeMap;
use std::path::Path;

use anyhow::{Context, Result};
use futures::{StreamExt, stream};
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;

use crate::db::{DisabledEntry, DisabledOverlay, Site, Source, overlay_path};
use crate::engine::{Scanner, Status};
use crate::util;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Health {
    Ok,
    FalsePositive,
    FalseNegative,
    Blocked,
    Error,
    Unknown,
    NoKnownAccount,
}

impl Health {
    pub fn label(self) -> &'static str {
        match self {
            Health::Ok => "ok",
            Health::FalsePositive => "false positive",
            Health::FalseNegative => "false negative",
            Health::Blocked => "blocked",
            Health::Error => "error",
            Health::Unknown => "unknown",
            Health::NoKnownAccount => "canary only",
        }
    }

    /// Whether the overlay should disable this site.
    pub fn is_broken(self) -> bool {
        matches!(self, Health::FalsePositive | Health::FalseNegative)
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SiteHealth {
    pub site: String,
    pub source: Source,
    pub known: Option<String>,
    pub known_status: Option<Status>,
    pub known_reason: Option<String>,
    pub canary_status: Option<Status>,
    pub canary_reason: Option<String>,
    pub health: Health,
    pub elapsed_ms: u64,
}

pub async fn check_site(scanner: &Scanner, site: &Site) -> SiteHealth {
    let start = std::time::Instant::now();
    let known = site.known.iter().find(|k| !k.trim().is_empty()).cloned();
    let canary = scanner.check(site, scanner.canary()).await;
    let (known_status, known_reason) = match &known {
        Some(k) => {
            let out = scanner.check(site, k).await;
            (Some(out.verdict.status), Some(out.verdict.reason))
        }
        None => (None, None),
    };
    let health = match (known_status, canary.verdict.status) {
        (_, Status::Found) => Health::FalsePositive,
        (Some(Status::Found), Status::NotFound) => Health::Ok,
        (Some(Status::NotFound), Status::NotFound) => Health::FalseNegative,
        (Some(Status::Blocked), _) | (_, Status::Blocked) => Health::Blocked,
        (Some(Status::Error), _) | (_, Status::Error) => Health::Error,
        (None, Status::NotFound) => Health::NoKnownAccount,
        (Some(Status::Illegal), _) | (_, Status::Illegal) => Health::Unknown,
        _ => Health::Unknown,
    };
    SiteHealth {
        site: site.name.clone(),
        source: site.source,
        known,
        known_status,
        known_reason,
        canary_status: Some(canary.verdict.status),
        canary_reason: Some(canary.verdict.reason),
        health,
        elapsed_ms: start.elapsed().as_millis() as u64,
    }
}

/// Check every site the scanner holds, streaming results through `tx`.
pub async fn run(
    scanner: &Scanner,
    tx: Option<mpsc::UnboundedSender<SiteHealth>>,
) -> Vec<SiteHealth> {
    let concurrency = scanner.options().concurrency.max(1);
    let sites = scanner.sites();
    stream::iter(0..sites.len())
        .map(|i| {
            let tx = tx.clone();
            async move {
                let h = check_site(scanner, &sites[i]).await;
                if let Some(tx) = tx {
                    let _ = tx.send(h.clone());
                }
                h
            }
        })
        .buffer_unordered(concurrency)
        .collect()
        .await
}

pub fn counts(results: &[SiteHealth]) -> BTreeMap<Health, usize> {
    let mut m = BTreeMap::new();
    for r in results {
        *m.entry(r.health).or_insert(0) += 1;
    }
    m
}

impl PartialOrd for Health {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Health {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        (*self as u8).cmp(&(*other as u8))
    }
}

/// Merge broken sites into the overlay file (keeping earlier entries for sites
/// not covered by this run) and drop entries for sites that now pass.
pub fn write_overlay(data_dir: &Path, results: &[SiteHealth]) -> Result<(usize, usize)> {
    let path = overlay_path(data_dir);
    let mut overlay: DisabledOverlay = match std::fs::read_to_string(&path) {
        Ok(text) => serde_json::from_str(&text).unwrap_or_default(),
        Err(_) => DisabledOverlay::default(),
    };
    let now = util::iso_now();
    let mut added = 0;
    let mut removed = 0;
    for r in results {
        if r.health.is_broken() {
            let reason = match r.health {
                Health::FalsePositive => format!(
                    "canary '{}' reported as found",
                    r.canary_reason.as_deref().unwrap_or("?")
                ),
                _ => format!(
                    "known account '{}' not found ({})",
                    r.known.as_deref().unwrap_or("?"),
                    r.known_reason.as_deref().unwrap_or("?")
                ),
            };
            if overlay
                .sites
                .insert(
                    r.site.clone(),
                    DisabledEntry {
                        reason,
                        checked: now.clone(),
                    },
                )
                .is_none()
            {
                added += 1;
            }
        } else if r.health == Health::Ok && overlay.sites.remove(&r.site).is_some() {
            removed += 1;
        }
    }
    overlay.generated = now;
    std::fs::create_dir_all(data_dir)
        .with_context(|| format!("creating {}", data_dir.display()))?;
    std::fs::write(&path, serde_json::to_string_pretty(&overlay)?)
        .with_context(|| format!("writing {}", path.display()))?;
    Ok((added, removed))
}