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
email.rsRust143 lines4.7 KiBraw download
//! Email targets: derive candidate handles and query passive breach data.

use anyhow::{Context, Result, bail};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::permute;

pub fn is_email(s: &str) -> bool {
    let s = s.trim();
    let Some((local, domain)) = s.split_once('@') else {
        return false;
    };
    !local.is_empty()
        && domain.contains('.')
        && !domain.starts_with('.')
        && !domain.ends_with('.')
        && !s.contains(char::is_whitespace)
}

/// Usernames worth searching for a given email address.
pub fn derive_handles(email: &str) -> Vec<String> {
    let Some((local, _)) = email.trim().split_once('@') else {
        return Vec::new();
    };
    let local = local.trim().to_string();
    if local.is_empty() {
        return Vec::new();
    }
    let mut out: Vec<String> = Vec::new();
    let mut push = |s: String| {
        if s.len() >= 3 && !out.iter().any(|x| x.eq_ignore_ascii_case(&s)) {
            out.push(s);
        }
    };
    // Strip Gmail-style plus tags.
    let base = local.split('+').next().unwrap_or(&local).to_string();
    push(base.clone());
    push(base.replace('.', ""));
    push(base.replace('.', "_"));
    push(base.replace('.', "-"));
    let stripped: String = base
        .trim_end_matches(|c: char| c.is_ascii_digit())
        .to_string();
    push(stripped);
    for p in permute::permute(&base, false, 12) {
        push(p);
    }
    out
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Breach {
    pub name: String,
    pub domain: String,
    pub date: String,
    pub pwn_count: u64,
    pub data_classes: Vec<String>,
}

/// Query Have I Been Pwned (requires an API key).
pub async fn hibp_breaches(client: &Client, api_key: &str, email: &str) -> Result<Vec<Breach>> {
    let url = format!(
        "https://haveibeenpwned.com/api/v3/breachedaccount/{}?truncateResponse=false",
        percent_encoding::utf8_percent_encode(email.trim(), percent_encoding::NON_ALPHANUMERIC)
    );
    let resp = client
        .get(&url)
        .header("hibp-api-key", api_key)
        .header("user-agent", format!("{}/{}", crate::NAME, crate::VERSION))
        .send()
        .await
        .context("HIBP request")?;
    match resp.status().as_u16() {
        200 => {}
        404 => return Ok(Vec::new()),
        401 => bail!("HIBP rejected the API key"),
        429 => bail!("HIBP rate limit hit"),
        other => bail!("HIBP returned HTTP {other}"),
    }
    let text = resp.text().await?;
    let v: Value = serde_json::from_str(&text).context("HIBP JSON")?;
    Ok(parse_hibp(&v))
}

pub fn parse_hibp(v: &Value) -> Vec<Breach> {
    v.as_array()
        .map(|a| {
            a.iter()
                .filter_map(|b| {
                    Some(Breach {
                        name: b.get("Name")?.as_str()?.to_string(),
                        domain: b
                            .get("Domain")
                            .and_then(Value::as_str)
                            .unwrap_or("")
                            .to_string(),
                        date: b
                            .get("BreachDate")
                            .and_then(Value::as_str)
                            .unwrap_or("")
                            .to_string(),
                        pwn_count: b.get("PwnCount").and_then(Value::as_u64).unwrap_or(0),
                        data_classes: b
                            .get("DataClasses")
                            .and_then(Value::as_array)
                            .map(|d| {
                                d.iter()
                                    .filter_map(Value::as_str)
                                    .map(String::from)
                                    .collect()
                            })
                            .unwrap_or_default(),
                    })
                })
                .collect()
        })
        .unwrap_or_default()
}

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

    #[test]
    fn validates_and_derives() {
        assert!(is_email("john.doe@example.com"));
        assert!(!is_email("john.doe"));
        assert!(!is_email("a@b"));
        let h = derive_handles("john.doe+news@example.com");
        assert_eq!(h[0], "john.doe");
        assert!(h.contains(&"johndoe".to_string()));
        assert!(h.contains(&"john_doe".to_string()));
        assert!(h.contains(&"jdoe".to_string()));
        assert!(!h.iter().any(|x| x.contains('+')));
        let v: Value = serde_json::from_str(r#"[{"Name":"Adobe","Domain":"adobe.com","BreachDate":"2013-10-04","PwnCount":152445165,"DataClasses":["Email addresses","Passwords"]}]"#).unwrap();
        let b = parse_hibp(&v);
        assert_eq!(b.len(), 1);
        assert_eq!(b[0].name, "Adobe");
        assert_eq!(b[0].data_classes.len(), 2);
    }
}