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
search.rsRust384 lines12.4 KiBraw download
//! The main scan orchestration shared by `search` and `email`.

use std::collections::{HashSet, VecDeque};
use std::sync::Arc;
use std::time::Instant;

use anyhow::{Context, Result, bail};
use tokio::sync::mpsc;

use super::{EXIT_HITS, EXIT_NETWORK, EXIT_NO_HITS, read_targets_file};
use crate::cli::{EmailArgs, ScanArgs};
use crate::db::{self, Selection};
use crate::email;
use crate::engine::http::build_client;
use crate::engine::{Event, Scanner, Target, TargetKind, discovered_handles};
use crate::permute;
use crate::report::{Discovered, EmailIntel, Report, RunInfo, TargetSummary, stem_for};
use crate::settings::Settings;
use crate::ui::{PrintOpts, Printer, stdout_is_tty};
use crate::util;

fn print_opts(settings: &Settings, args: &ScanArgs) -> PrintOpts {
    PrintOpts {
        print_all: args.print_all,
        print_errors: args.print_errors,
        quiet: settings.quiet,
        progress: !args.no_progress && stdout_is_tty(),
        json: args.json,
        show_profile: !args.no_profile,
        animate: settings.animate,
    }
}

/// Build the target list from positionals, input file and permutations.
pub fn collect_targets(
    settings: &Settings,
    args: &ScanArgs,
    positional: &[String],
) -> Result<Vec<String>> {
    let mut targets: Vec<String> = positional
        .iter()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();
    if let Some(p) = &args.input {
        targets.extend(read_targets_file(p)?);
    }
    if args.permute || args.permute_all {
        let max = settings.max_permutations(args);
        let mut expanded = Vec::new();
        for t in &targets {
            for p in permute::permute(t, args.permute_all, max) {
                expanded.push(p);
            }
        }
        targets = expanded;
    }
    let mut seen = HashSet::new();
    targets.retain(|t| seen.insert(t.to_lowercase()));
    Ok(targets)
}

pub struct Prepared {
    pub settings: Settings,
    pub scanner: Arc<Scanner>,
    pub email_scanner: Option<Arc<Scanner>>,
    pub printer: Printer,
    pub sources: Vec<String>,
    pub timeout_secs: f64,
    pub proxy: Option<String>,
}

fn prepare(settings: Settings, args: &ScanArgs, with_email_sites: bool) -> Result<Prepared> {
    let printer = Printer::new(settings.theme, print_opts(&settings, args));
    printer.banner();

    let load = settings.load_options(&args.select)?;
    let dbv = db::load(&load).context("loading site databases")?;
    for r in &dbv.reports {
        tracing::info!(
            "{}: {} sites from {} ({})",
            r.source,
            r.sites,
            r.origin,
            r.format
        );
    }
    if dbv.overlay_disabled > 0 {
        printer.note(format!(
            "{} sites disabled by self-check overlay (--include-disabled to scan them)",
            dbv.overlay_disabled
        ));
    }
    let selection = settings.selection(&args.select, "username")?;
    let sites = dbv.select(&selection);
    if sites.is_empty() && !with_email_sites {
        bail!("no sites match the selection");
    }
    let email_sites = if with_email_sites {
        dbv.select(&Selection {
            id_type: "email".into(),
            ..settings.selection(&args.select, "email")?
        })
    } else {
        Vec::new()
    };

    let client_opts = settings.client_options(&args.net)?;
    let client = build_client(&client_opts)?;
    let scan_opts = settings.scan_options(args)?;
    let sources: Vec<String> = {
        let mut v: Vec<String> = dbv.reports.iter().map(|r| r.source.to_string()).collect();
        v.dedup();
        v
    };
    let scanner = Arc::new(Scanner::new(client.clone(), sites, scan_opts.clone()));
    let email_scanner = if email_sites.is_empty() {
        None
    } else {
        Some(Arc::new(Scanner::new(client, email_sites, scan_opts)))
    };
    let n = scanner.sites().len();
    let mut note = format!(
        "{} sites selected from {}",
        util::group_digits(n),
        util::group_digits(dbv.sites.len())
    );
    if !selection.all_sites
        && dbv
            .sites
            .iter()
            .any(|s| s.source == db::Source::Maigret && s.rank.is_none() && !s.disabled)
    {
        note.push_str(" (--all-sites adds the unranked long tail)");
    }
    printer.note(note);
    if scanner.options().verify {
        printer.note(format!(
            "hits are verified against canary '{}'",
            scanner.canary()
        ));
    }
    Ok(Prepared {
        timeout_secs: client_opts.timeout.as_secs_f64(),
        proxy: client_opts.proxy.clone(),
        settings,
        scanner,
        email_scanner,
        printer,
        sources,
    })
}

/// Run a queue of targets (with optional recursion) and build the report.
async fn run_queue(
    p: &mut Prepared,
    args: &ScanArgs,
    initial: Vec<Target>,
    email_intel: Vec<EmailIntel>,
) -> Result<Report> {
    let started = Instant::now();
    let max_depth = if args.recursive {
        args.max_depth.unwrap_or(1)
    } else {
        0
    };
    let mut report = Report::new();
    report.emails = email_intel;
    report.run = RunInfo {
        sites_selected: p.scanner.sites().len(),
        sources: p.sources.clone(),
        concurrency: p.scanner.options().concurrency,
        timeout_secs: p.timeout_secs,
        verify: p.scanner.options().verify,
        extract: p.scanner.options().extract,
        recursive: args.recursive,
        archive: format!("{:?}", p.scanner.options().archive).to_lowercase(),
        proxy: p.proxy.clone(),
        canary: p.scanner.canary().to_string(),
    };

    let mut queue: VecDeque<Target> = initial.into();
    let mut scanned: HashSet<String> = queue.iter().map(|t| t.value.to_lowercase()).collect();

    while let Some(target) = queue.pop_front() {
        let scanner = if target.kind == TargetKind::Email {
            p.email_scanner.clone()
        } else {
            Some(p.scanner.clone())
        };
        let Some(scanner) = scanner else {
            p.printer.warn(format!(
                "no email-capable sites selected; skipping {}",
                target.value
            ));
            continue;
        };
        let (tx, mut rx) = mpsc::unbounded_channel::<Event>();
        let t2 = target.clone();
        let s2 = scanner.clone();
        let scan_task = tokio::spawn(async move { s2.scan(&t2, Some(&tx)).await });
        let mut stats = None;
        let mut elapsed_ms = 0;
        while let Some(ev) = rx.recv().await {
            if let Event::TargetFinished {
                stats: s,
                elapsed_ms: e,
                ..
            } = &ev
            {
                stats = Some(*s);
                elapsed_ms = *e;
            }
            p.printer.handle(&ev);
        }
        let results = scan_task.await.context("scan task panicked")?;
        let stats = stats.unwrap_or_else(|| crate::engine::Stats::from_results(&results));
        report.targets.push(TargetSummary {
            target: target.value.clone(),
            kind: target.kind,
            depth: target.depth,
            via: target.via.clone(),
            stats,
            elapsed_ms,
        });

        for (handle, via_site) in discovered_handles(&results) {
            let key = handle.to_lowercase();
            let will_scan = target.depth < max_depth && !scanned.contains(&key);
            if !report
                .discovered
                .iter()
                .any(|d| d.handle.eq_ignore_ascii_case(&handle))
            {
                report.discovered.push(Discovered {
                    handle: handle.clone(),
                    via_site: via_site.clone(),
                    parent: target.value.clone(),
                    depth: target.depth + 1,
                    scanned: will_scan,
                });
                p.printer
                    .discovered(&handle, &via_site, &target.value, will_scan);
            }
            if will_scan {
                scanned.insert(key);
                queue.push_back(Target {
                    value: handle,
                    kind: TargetKind::Username,
                    depth: target.depth + 1,
                    via: Some(format!("{via_site} ← {}", target.value)),
                });
            }
        }
        report.results.extend(results);
    }
    report.recompute_summary();
    report.sort_results();
    report.elapsed_secs = started.elapsed().as_secs_f64();
    Ok(report)
}

fn finish(p: &Prepared, args: &ScanArgs, report: &Report, stem: &str) -> Result<i32> {
    let mut paths = Vec::new();
    if let Some(dir) = p.settings.output_dir(args, stem) {
        let formats = p.settings.formats(args)?;
        paths = report.write_all(&dir, &formats, stem)?;
    }
    let failed = p.scanner.archive_failures()
        + p.email_scanner
            .as_ref()
            .map(|s| s.archive_failures())
            .unwrap_or(0);
    if failed > 0 {
        p.printer.warn(format!("{failed} Wayback lookups failed (archive.org rate limits aggressively; retry later or lower --per-host)"));
    }
    p.printer.summary(report, &paths);
    if args.browse {
        for r in report.hits() {
            if let Err(e) = open::that_detached(&r.url) {
                p.printer.warn(format!("cannot open {}: {e}", r.url));
            }
        }
    }
    if args.output.is_none() && report.summary.found > 0 && !args.json && !p.settings.quiet {
        p.printer.note("add -o to write html/json/csv reports");
    }
    let s = &report.summary;
    Ok(if s.found > 0 {
        EXIT_HITS
    } else if s.answered() == 0 && s.total > 0 {
        EXIT_NETWORK
    } else {
        EXIT_NO_HITS
    })
}

/// `percival <username>...` / `percival search`.
pub async fn run_usernames(
    settings: Settings,
    args: &ScanArgs,
    positional: &[String],
) -> Result<i32> {
    let targets = collect_targets(&settings, args, positional)?;
    if targets.is_empty() {
        bail!("no usernames given (pass them as arguments or with --input)");
    }
    let mut p = prepare(settings, args, false)?;
    let initial: Vec<Target> = targets
        .iter()
        .map(|t| Target::username(t.clone()))
        .collect();
    let report = run_queue(&mut p, args, initial, Vec::new()).await?;
    finish(&p, args, &report, &stem_for(&targets))
}

/// `percival email <address>...`.
pub async fn run_emails(settings: Settings, args: &EmailArgs) -> Result<i32> {
    let emails: Vec<String> = args
        .emails
        .iter()
        .map(|e| e.trim().to_lowercase())
        .filter(|e| !e.is_empty())
        .collect();
    for e in &emails {
        if !email::is_email(e) {
            bail!("'{e}' does not look like an email address");
        }
    }
    let mut p = prepare(settings, &args.scan, true)?;
    let hibp_key = args
        .hibp_key
        .clone()
        .or_else(|| p.settings.file.hibp_api_key.clone())
        .filter(|k| !k.trim().is_empty());
    let mut intel = Vec::new();
    let mut initial: Vec<Target> = Vec::new();
    for e in &emails {
        let derived = if args.no_derive {
            Vec::new()
        } else {
            email::derive_handles(e)
        };
        let mut info = EmailIntel {
            email: e.clone(),
            gravatar_hash: util::md5_hex_normalized(e),
            derived_handles: derived.clone(),
            breaches: Vec::new(),
            breach_error: None,
        };
        if let Some(key) = &hibp_key {
            match email::hibp_breaches(p.scanner.client(), key, e).await {
                Ok(b) => info.breaches = b,
                Err(err) => info.breach_error = Some(err.to_string()),
            }
        } else {
            p.printer
                .note("set --hibp-key (or hibp_api_key in config) to include breach data");
        }
        p.printer.note(format!(
            "{e}: gravatar {} · derived handles: {}",
            info.gravatar_hash,
            if derived.is_empty() {
                "none".to_string()
            } else {
                derived.join(", ")
            }
        ));
        intel.push(info);
        initial.push(Target::email(e.clone()));
        for h in derived {
            if !initial.iter().any(|t| t.value.eq_ignore_ascii_case(&h)) {
                initial.push(Target {
                    value: h,
                    kind: TargetKind::Username,
                    depth: 0,
                    via: Some(format!("derived from {e}")),
                });
            }
        }
    }
    let report = run_queue(&mut p, &args.scan, initial, intel).await?;
    finish(&p, &args.scan, &report, &stem_for(&emails))
}