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
mod.rsRust531 lines16.9 KiBraw download
//! The scanner: concurrent site checks with per-host limits, retries, canary
//! verification, profile extraction and archive lookups.

pub mod detect;
pub mod http;
pub mod result;
pub mod waf;

use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use futures::{StreamExt, stream};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc};

pub use detect::Verdict;
pub use result::*;

use crate::archive;
use crate::db::{Site, render_body};
use crate::extract;
use crate::util;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ArchiveMode {
    Off,
    Found,
    All,
}

#[derive(Clone, Debug)]
pub struct ScanOptions {
    pub concurrency: usize,
    pub per_host: usize,
    pub retries: u32,
    pub verify: bool,
    pub extract: bool,
    pub archive: ArchiveMode,
    pub dump_dir: Option<PathBuf>,
    pub max_body: usize,
    pub random_ua: bool,
    pub extra_headers: Vec<(String, String)>,
    pub cookie: Option<String>,
    /// Consult alternate probes even when the primary says "not found".
    pub thorough: bool,
}

impl Default for ScanOptions {
    fn default() -> Self {
        ScanOptions {
            concurrency: 60,
            per_host: 4,
            retries: 1,
            verify: true,
            extract: true,
            archive: ArchiveMode::Off,
            dump_dir: None,
            max_body: 3 * 1024 * 1024,
            random_ua: false,
            extra_headers: Vec::new(),
            cookie: None,
            thorough: false,
        }
    }
}

#[derive(Clone, Debug)]
pub struct Target {
    pub value: String,
    pub kind: TargetKind,
    pub depth: u8,
    pub via: Option<String>,
}

impl Target {
    pub fn username(s: impl Into<String>) -> Self {
        Target {
            value: s.into(),
            kind: TargetKind::Username,
            depth: 0,
            via: None,
        }
    }
    pub fn email(s: impl Into<String>) -> Self {
        Target {
            value: s.into(),
            kind: TargetKind::Email,
            depth: 0,
            via: None,
        }
    }
}

#[derive(Debug)]
pub enum Event {
    TargetStarted {
        target: Target,
        sites: usize,
    },
    Result(Box<ScanResult>),
    TargetFinished {
        target: Target,
        stats: Stats,
        elapsed_ms: u64,
    },
}

/// Per-host concurrency limiter so no single site is hammered.
pub struct HostLimiter {
    per_host: usize,
    map: Mutex<HashMap<String, Arc<Semaphore>>>,
}

impl HostLimiter {
    pub fn new(per_host: usize) -> Self {
        HostLimiter {
            per_host: per_host.max(1),
            map: Mutex::new(HashMap::new()),
        }
    }

    pub async fn acquire(&self, host: &str) -> OwnedSemaphorePermit {
        let sem = {
            let mut map = self.map.lock().expect("limiter poisoned");
            map.entry(host.to_string())
                .or_insert_with(|| Arc::new(Semaphore::new(self.per_host)))
                .clone()
        };
        sem.acquire_owned().await.expect("semaphore closed")
    }
}

/// What the canary account produced on a site: the verdict plus the links and
/// handles its page carried (site chrome, never profile data).
#[derive(Clone, Debug, Default)]
pub struct CanaryInfo {
    pub verdict: Option<bool>,
    pub links: HashSet<String>,
    pub handles: HashSet<String>,
}

/// Outcome of a single request+evaluation.
#[derive(Clone, Debug)]
pub struct CheckOutcome {
    pub verdict: Verdict,
    pub exchange: Option<http::Exchange>,
    pub error: Option<String>,
    pub elapsed_ms: u64,
    pub attempts: u32,
}

pub struct Scanner {
    client: Client,
    sites: Arc<Vec<Site>>,
    opts: ScanOptions,
    limiter: HostLimiter,
    canary: String,
    canary_cache: Mutex<HashMap<String, CanaryInfo>>,
    archive_failures: AtomicUsize,
}

impl Scanner {
    pub fn new(client: Client, sites: Vec<Site>, opts: ScanOptions) -> Self {
        let limiter = HostLimiter::new(opts.per_host);
        Scanner {
            client,
            sites: Arc::new(sites),
            opts,
            limiter,
            canary: util::random_handle(14),
            canary_cache: Mutex::new(HashMap::new()),
            archive_failures: AtomicUsize::new(0),
        }
    }

    pub fn sites(&self) -> &[Site] {
        &self.sites
    }

    pub fn canary(&self) -> &str {
        &self.canary
    }

    pub fn client(&self) -> &Client {
        &self.client
    }

    pub fn options(&self) -> &ScanOptions {
        &self.opts
    }

    /// Number of Wayback lookups that failed (usually archive.org rate limiting).
    pub fn archive_failures(&self) -> usize {
        self.archive_failures.load(Ordering::Relaxed)
    }

    /// Render the request for a site/account pair.
    pub fn prepare(&self, site: &Site, account: &str) -> http::Prepared {
        let mut headers = self.opts.extra_headers.clone();
        for (k, v) in &site.headers {
            headers.retain(|(hk, _)| !hk.eq_ignore_ascii_case(k));
            headers.push((k.clone(), v.clone()));
        }
        if let Some(c) = &self.opts.cookie {
            if !headers
                .iter()
                .any(|(k, _)| k.eq_ignore_ascii_case("cookie"))
            {
                headers.push(("Cookie".to_string(), c.clone()));
            }
        }
        let body = site
            .body
            .as_deref()
            .map(|b| render_body(b, account, site.content_type()));
        http::Prepared {
            method: site.method,
            url: site.probe_url(account),
            headers,
            body,
            follow_redirects: site.follow_redirects,
            encoding: site.encoding.clone(),
        }
    }

    /// Check one account against one site (with retries and host limiting).
    pub async fn check(&self, site: &Site, raw_account: &str) -> CheckOutcome {
        let start = Instant::now();
        let account = site.prepare_account(raw_account);
        if account.trim().is_empty() {
            return CheckOutcome {
                verdict: Verdict::new(
                    Status::Illegal,
                    Confidence::High,
                    "account is empty after stripping disallowed characters",
                ),
                exchange: None,
                error: None,
                elapsed_ms: 0,
                attempts: 0,
            };
        }
        if !site.accepts(&account) {
            return CheckOutcome {
                verdict: Verdict::new(
                    Status::Illegal,
                    Confidence::High,
                    "does not match the site's username rules",
                ),
                exchange: None,
                error: None,
                elapsed_ms: 0,
                attempts: 0,
            };
        }
        let req = self.prepare(site, &account);
        let _permit = self.limiter.acquire(&site.limiter_key()).await;
        let ua = if self.opts.random_ua {
            Some(http::random_user_agent())
        } else {
            None
        };
        let mut attempt: u32 = 0;
        let err: http::FetchError = loop {
            attempt += 1;
            match http::fetch(&self.client, &req, self.opts.max_body, ua).await {
                Ok(ex) => {
                    let verdict = detect::evaluate(site, &ex, &account);
                    return CheckOutcome {
                        verdict,
                        exchange: Some(ex),
                        error: None,
                        elapsed_ms: start.elapsed().as_millis() as u64,
                        attempts: attempt,
                    };
                }
                Err(e) => {
                    if attempt > self.opts.retries || !e.is_transient() {
                        break e;
                    }
                    let backoff = Duration::from_millis(250 * (1u64 << (attempt.min(4) - 1)));
                    tokio::time::sleep(backoff).await;
                }
            }
        };
        CheckOutcome {
            verdict: Verdict::new(Status::Error, Confidence::High, err.short()),
            exchange: None,
            error: Some(err.short()),
            elapsed_ms: start.elapsed().as_millis() as u64,
            attempts: attempt,
        }
    }

    /// Run the canary account through a site. `Some(true)` = detector behaves,
    /// `Some(false)` = the canary was "found" too, `None` = inconclusive.
    pub async fn verify(&self, site: &Site) -> Option<bool> {
        self.canary_info(site).await.verdict
    }

    /// Cached canary result for a site, including the links its page carried.
    pub async fn canary_info(&self, site: &Site) -> CanaryInfo {
        let key = site.probe_key();
        if let Some(v) = self.canary_cache.lock().expect("cache poisoned").get(&key) {
            return v.clone();
        }
        let account = site.prepare_account(&self.canary);
        let mut info = CanaryInfo::default();
        if site.accepts(&account) {
            let out = self.check(site, &self.canary).await;
            info.verdict = match out.verdict.status {
                Status::Found => Some(false),
                Status::NotFound => Some(true),
                _ => None,
            };
            if let Some(ex) = &out.exchange {
                if let Some(p) = extract::extract(site, ex, &self.canary) {
                    info.links = p.links.iter().map(|l| l.to_ascii_lowercase()).collect();
                    info.handles = p.handles.iter().map(|h| h.to_ascii_lowercase()).collect();
                }
            }
        }
        self.canary_cache
            .lock()
            .expect("cache poisoned")
            .insert(key, info.clone());
        info
    }

    /// Check the primary probe, falling back to other databases' probes for the
    /// same site when the primary is blocked, errors, or cannot decide.
    pub async fn check_with_alternates<'a>(
        &self,
        site: &'a Site,
        account: &str,
    ) -> (CheckOutcome, &'a Site) {
        let out = self.check(site, account).await;
        let retry = match out.verdict.status {
            Status::Blocked | Status::Unknown | Status::Error => true,
            Status::NotFound => self.opts.thorough,
            _ => false,
        };
        if !retry || site.alternates.is_empty() {
            return (out, site);
        }
        for alt in site.alternates.iter().take(2) {
            let mut o2 = self.check(alt, account).await;
            if matches!(o2.verdict.status, Status::Found | Status::NotFound) {
                o2.verdict.reason = format!("{} (via {} probe)", o2.verdict.reason, alt.source);
                return (o2, alt);
            }
        }
        (out, site)
    }

    async fn check_full(&self, primary: &Site, target: &Target) -> ScanResult {
        let (out, site) = self.check_with_alternates(primary, &target.value).await;
        let mut r = ScanResult {
            target: target.value.clone(),
            kind: target.kind,
            depth: target.depth,
            via: target.via.clone(),
            site: primary.name.clone(),
            category: primary.category.clone(),
            tags: primary.tags.clone(),
            source: site.source,
            url: primary.display_url(&primary.prepare_account(&target.value)),
            probe_url: site.probe_url(&site.prepare_account(&target.value)),
            status: out.verdict.status,
            confidence: out.verdict.confidence,
            verified: None,
            reason: out.verdict.reason.clone(),
            http_status: out.exchange.as_ref().map(|e| e.final_status),
            elapsed_ms: out.elapsed_ms,
            profile: None,
            archive: None,
            error: out.error.clone(),
        };
        let mut canary: Option<CanaryInfo> = None;
        if r.status == Status::Found && self.opts.verify {
            let info = self.canary_info(site).await;
            match info.verdict {
                Some(true) => r.verified = Some(true),
                Some(false) => {
                    r.verified = Some(false);
                    r.confidence = Confidence::Low;
                    r.reason = format!(
                        "{}; canary '{}' was also reported as found",
                        r.reason, self.canary
                    );
                }
                None => {}
            }
            canary = Some(info);
        }
        if r.status == Status::Found && self.opts.extract {
            if let Some(ex) = &out.exchange {
                r.profile = extract::extract(site, ex, &target.value);
            }
            if let (Some(p), Some(info)) = (r.profile.as_mut(), canary.as_ref()) {
                // Anything the canary's page also linked to is site chrome, not profile data.
                p.links
                    .retain(|l| !info.links.contains(&l.to_ascii_lowercase()));
                p.handles
                    .retain(|h| !info.handles.contains(&h.to_ascii_lowercase()));
                if p.is_empty() {
                    r.profile = None;
                }
            }
        }
        let want_archive = match self.opts.archive {
            ArchiveMode::Off => false,
            ArchiveMode::Found => r.status == Status::Found,
            ArchiveMode::All => matches!(
                r.status,
                Status::Found | Status::NotFound | Status::Unknown | Status::Blocked
            ),
        };
        if want_archive {
            let _permit = self.limiter.acquire("archive.org").await;
            let mut outcome = archive::lookup(&self.client, &r.url).await;
            if matches!(&outcome, Err(e) if e.to_string().contains("429")) {
                tokio::time::sleep(Duration::from_secs(3)).await;
                outcome = archive::lookup(&self.client, &r.url).await;
            }
            match outcome {
                Ok(hit) => r.archive = hit,
                Err(e) => {
                    self.archive_failures.fetch_add(1, Ordering::Relaxed);
                    tracing::debug!("wayback lookup failed for {}: {e}", r.url);
                }
            }
        }
        if let Some(dir) = &self.opts.dump_dir {
            if let Some(ex) = &out.exchange {
                if let Err(e) = dump_exchange(dir, target, primary, ex) {
                    tracing::warn!("dump failed for {}: {e}", site.name);
                }
            }
        }
        r
    }

    /// Scan a target against every site, streaming results as events.
    pub async fn scan(
        &self,
        target: &Target,
        tx: Option<&mpsc::UnboundedSender<Event>>,
    ) -> Vec<ScanResult> {
        let started = Instant::now();
        if let Some(tx) = tx {
            let _ = tx.send(Event::TargetStarted {
                target: target.clone(),
                sites: self.sites.len(),
            });
        }
        let results: Vec<ScanResult> = stream::iter(0..self.sites.len())
            .map(|i| async move {
                let r = self.check_full(&self.sites[i], target).await;
                if let Some(tx) = tx {
                    let _ = tx.send(Event::Result(Box::new(r.clone())));
                }
                r
            })
            .buffer_unordered(self.opts.concurrency.max(1))
            .collect()
            .await;
        let stats = Stats::from_results(&results);
        if let Some(tx) = tx {
            let _ = tx.send(Event::TargetFinished {
                target: target.clone(),
                stats,
                elapsed_ms: started.elapsed().as_millis() as u64,
            });
        }
        results
    }
}

fn dump_exchange(
    dir: &std::path::Path,
    target: &Target,
    site: &Site,
    ex: &http::Exchange,
) -> std::io::Result<()> {
    use std::io::Write;
    let sub = dir.join(util::sanitize_filename(&target.value));
    std::fs::create_dir_all(&sub)?;
    let ext = match ex.content_type.as_deref() {
        Some(ct) if ct.contains("json") => "json",
        Some(ct) if ct.contains("html") => "html",
        _ => "txt",
    };
    let path = sub.join(format!("{}.{ext}", util::sanitize_filename(&site.name)));
    let mut f = std::fs::File::create(path)?;
    writeln!(
        f,
        "<!-- {} {} → HTTP {} (first {}) final {} -->",
        site.method.as_str(),
        ex.url,
        ex.final_status,
        ex.first_status,
        ex.final_url
    )?;
    for (k, v) in &ex.headers {
        writeln!(f, "<!-- {k}: {v} -->")?;
    }
    writeln!(f)?;
    f.write_all(ex.body.as_bytes())?;
    Ok(())
}

/// Collect pivot handles discovered in a batch of results.
pub fn discovered_handles(results: &[ScanResult]) -> Vec<(String, String)> {
    let mut out: Vec<(String, String)> = Vec::new();
    for r in results.iter().filter(|r| r.is_hit()) {
        if let Some(p) = &r.profile {
            for h in &p.handles {
                if !out.iter().any(|(x, _)| x.eq_ignore_ascii_case(h)) {
                    out.push((h.clone(), r.site.clone()));
                }
            }
        }
    }
    out
}