Skip to main content

rusthound_ce/modules/sessions/
mod.rs

1//! Session-collection module for RustHound-CE  (issue #46 - HasSession)
2//! <https://bloodhound.specterops.io/resources/edges/has-session#hassession>
3//! <https://github.com/g0h4n/HasSession-rs>
4//!
5//! Runs AFTER the LDAP phase, from `modules::run_modules`, and only when the
6//! collection method actually contacts machines (i.e. NOT `DCOnly`).
7//!
8//! Three native RPC paths (all provided by the `dcerpc` crate), mapped to the
9//! BloodHound CE computer schema:
10//!
11//!   SRVSVC / NetrSessionEnum   -> Computer.Sessions            (HasSession)
12//!   WKSSVC / NetrWkstaUserEnum -> Computer.PrivilegedSessions  (LoggedOn)
13//!   WINREG / HKEY_USERS        -> Computer.RegistrySessions    (LoggedOn)
14//!
15//! SharpHound-style behaviour baked in:
16//!   * reachability pre-check on 445 with a hard timeout (skip dead hosts);
17//!   * "active computer" filter based on pwdLastSet age (ComputerExpiryDays);
18//!   * DCOnly never reaches this module;
19//!   * bounded concurrency (throttle) instead of a serial loop;
20//!   * names resolved to SIDs using the already-collected LDAP data.
21//!
22//! Authentication reuses the SMB transport: password, pass the hash, or a
23//! Kerberos ticket (pass the ticket) when --kerberos is set. Kerberos material
24//! is built per host, since the AP-REQ targets that host's cifs/<host> SPN.
25//!
26//! The target host is the computer FQDN (properties.name, from dNSHostName).
27//! We do NOT use the fqdn->ip map: connections go to the FQDN and rely on DNS.
28
29use std::collections::HashMap;
30use std::error::Error;
31use std::sync::Arc;
32
33use futures::stream::{self, StreamExt};
34use log::{debug, info, trace, warn};
35use tokio::net::TcpStream;
36use tokio::sync::Semaphore;
37use tokio::time::{timeout, Duration};
38
39use dcerpc::rrp::{RegistryClient, RegistrySession};
40use dcerpc::srvsvc::SrvsvcClient;
41use dcerpc::wkssvc::{WkstaUser, WkstaUserClient};
42use smb2_client::SmbClient;
43use crate::transport::smb::{connect_ipc, open_rpc_pipe, smb_user, SmbAuth};
44
45use crate::args::{CollectionMethod, Options};
46use crate::objects::common::UserComputerSession;
47use crate::objects::computer::Computer;
48use crate::objects::user::User;
49
50const DEFAULT_CONCURRENCY: usize = 10;      // ~ SharpHound --Throttle
51const DEFAULT_PORT_TIMEOUT_MS: u64 = 1_500; // 445 pre-check budget
52const DEFAULT_HOST_TIMEOUT_MS: u64 = 8_000; // whole per-host RPC budget
53const DEFAULT_EXPIRY_DAYS: i64 = 60;        // ~ SharpHound --ComputerExpiryDays
54
55// ----
56// Raw per-host findings (kept close to HasSession-rs)
57// ----
58
59struct SmbSession { user: String, _client: String }
60
61struct HostFindings {
62    computer_sid: String,
63    smb_sessions: Vec<SmbSession>,      // SRVSVC
64    logged_on:    Vec<WkstaUser>,       // WKSSVC
65    registry:     Vec<RegistrySession>, // WINREG
66    errors:       Vec<String>,
67}
68
69// Entry point called by run_modules
70pub async fn run(
71    args:      &Options,
72    users:     &[User],           // needed to resolve RPC principal names -> SIDs
73    computers: &mut Vec<Computer>,
74) -> Result<(), Box<dyn Error>> {
75    // Hard guard: DCOnly must never touch a machine.
76    if !args.collection_method.does_sessions() {
77        debug!("[sessions] collection method does not contact hosts - skipping");
78        return Ok(());
79    }
80
81    // 1) Build the name -> SID resolution table from the LDAP data collected upstream.
82    let sid_index = build_sid_index(users);
83
84    // 2) Select ACTIVE targets only (enabled + pwdLastSet within the expiry window).
85    //    The host is the computer FQDN (properties.name); no fqdn->ip lookup.
86    let expiry_days = DEFAULT_EXPIRY_DAYS;
87    let targets: Vec<(String, String)> = computers
88        .iter()
89        .filter(|c| is_active(c, expiry_days))
90        .map(|c| (c.properties().name().clone(), c.object_identifier().clone()))
91        .collect();
92
93    info!("[sessions] {} active target(s) after expiry/enabled filter", targets.len());
94
95    // 3) Enumerate with bounded concurrency (throttle) instead of a serial loop.
96    let sem = Arc::new(Semaphore::new(DEFAULT_CONCURRENCY));
97    let domain = args.domain.clone();
98    let user = smb_user(args.username.as_deref().unwrap_or_default());
99    let password = args.password.clone().unwrap_or_default();
100    let nt_hash = parse_hash(args.hashes.as_deref()); // "LM:NT" | ":NT" | "NT" -> [u8;16]
101    let method = args.collection_method.clone();
102
103    // Kerberos: ccache path from KRB5CCNAME when --kerberos is set (computed once).
104    let kerberos_ccache: Option<String> = if args.kerberos {
105        std::env::var("KRB5CCNAME").ok()
106    } else {
107        None
108    };
109    // KDC (the DC) to request cifs/<host> service tickets from: FQDN, else IP, else domain.
110    let kdc: String = args
111        .ldapfqdn
112        .clone()
113        .filter(|s| !s.is_empty())
114        .or_else(|| args.ip.clone())
115        .unwrap_or_else(|| args.domain.clone());
116
117    let findings: Vec<HostFindings> = stream::iter(targets)
118        .map(|(host, computer_sid)| {
119            let (sem, domain, user, password, method) =
120                (sem.clone(), domain.clone(), user.clone(), password.clone(), method.clone());
121            let nt_hash = nt_hash;
122            let kerberos_ccache = kerberos_ccache.clone();
123            let kdc = kdc.clone();
124            async move {
125                let _permit = sem.acquire().await.unwrap();
126                enumerate_host(
127                    &host, computer_sid, &domain, &user, &password,
128                    nt_hash.as_ref(), kerberos_ccache.as_deref(), &kdc, &method,
129                ).await
130            }
131        })
132        .buffer_unordered(DEFAULT_CONCURRENCY)
133        .collect()
134        .await;
135
136    // 4) Fold findings back into the matching Computer objects (resolving names -> SIDs).
137    let mut total_sessions = 0usize;
138    for hf in &findings {
139        total_sessions += apply_findings(computers, hf, &sid_index, &args.domain);
140        for e in &hf.errors { warn!("{e}"); }
141    }
142    info!("[sessions] {total_sessions} session(s) enumerated in total across {} host(s)",
143          findings.len());
144
145    Ok(())
146}
147
148// Per-host enumeration (adapted from HasSession-rs enumerate_host)
149#[allow(clippy::too_many_arguments)]
150async fn enumerate_host(
151    host: &str, computer_sid: String,
152    domain: &str, user: &str, password: &str,
153    nt_hash: Option<&[u8; 16]>,
154    kerberos_ccache: Option<&str>,
155    kdc: &str,
156    method: &CollectionMethod,
157) -> HostFindings {
158    // SharpHound-style reachability pre-check: 445 open within budget
159    if !is_reachable(host, DEFAULT_PORT_TIMEOUT_MS).await {
160        trace!("[{host}] 445/tcp unreachable - skip");
161        return HostFindings {
162            computer_sid,
163            smb_sessions: Vec::new(), logged_on: Vec::new(), registry: Vec::new(),
164            errors: vec![format!("{host}: 445/tcp unreachable")],
165        };
166    }
167
168    // The RPC body accumulates into its OWN locals and returns them, so it never
169    // aliases the outer findings the timeout wrapper also needs (avoids E0499).
170    let work = async {
171        let mut smb_sessions = Vec::new();
172        let mut logged_on    = Vec::new();
173        let mut registry     = Vec::new();
174        let mut errors       = Vec::new();
175
176        // Inner block uses `?` for the fatal connect/auth/tree steps; the error
177        // is folded into `errors` instead of bubbling out of `work`.
178        let fatal: Result<(), String> = async {
179            // connect + SESSION_SETUP: Kerberos ticket, or password / pass the hash.
180            let mut smb = if let Some(ccache) = kerberos_ccache {
181                // Kerberos: build a cifs/<host> ticket for THIS host.
182                let spn = format!("cifs/{host}");
183                let (gss_blob, session_key) =
184                    crate::transport::kerberos::kerberos_material_for(ccache, &spn, kdc)
185                        .await
186                        .map_err(|e| format!("{host} krb: {e}"))?;
187                let auth = SmbAuth::Kerberos { gss_blob: &gss_blob, session_key: &session_key };
188                connect_ipc(host, domain, user, auth).await.map_err(|e| format!("{host}: {e}"))?
189            } else {
190                let auth = match nt_hash {
191                    Some(h) => SmbAuth::Hash(h),
192                    None    => SmbAuth::Password(password),
193                };
194                connect_ipc(host, domain, user, auth).await.map_err(|e| format!("{host}: {e}"))?
195            };
196
197            if method.srvsvc() {
198                match srvsvc_sessions(&mut smb, host).await {
199                    Ok((_, 5)) => errors.push(format!("[{host}] SRVSVC rc=5 ACCESS_DENIED (hardened / non-admin)")),
200                    Ok((s, _)) => smb_sessions = s,
201                    Err(e)     => errors.push(format!("{host} SRVSVC: {e}")),
202                }
203            }
204            if method.wkssvc() {
205                match enum_wksta(&mut smb, host).await {
206                    Ok((_, 5)) => errors.push(format!("[{host}] WKSSVC rc=5 (local admin required)")),
207                    Ok((u, _)) => logged_on = dedup_wksta(u),
208                    Err(e)     => errors.push(format!("{host} WKSSVC: {e}")),
209                }
210            }
211            if method.registry() {
212                match enum_registry(&mut smb, domain, user, password, nt_hash, host).await {
213                    Ok(sids) => registry = sids,
214                    Err(e)   => errors.push(format!("{host} WINREG: {e} (RemoteRegistry stopped?)")),
215                }
216            }
217            Ok(())
218        }.await;
219
220        if let Err(e) = fatal { errors.push(e); }
221        (smb_sessions, logged_on, registry, errors)
222    };
223
224    // whole-host budget so a slow-but-open host can't stall a worker
225    match timeout(Duration::from_millis(DEFAULT_HOST_TIMEOUT_MS), work).await {
226        Ok((smb_sessions, logged_on, registry, errors)) => HostFindings {
227            computer_sid, smb_sessions, logged_on, registry, errors,
228        },
229        Err(_elapsed) => HostFindings {
230            computer_sid,
231            smb_sessions: Vec::new(), logged_on: Vec::new(), registry: Vec::new(),
232            errors: vec![format!("{host}: per-host timeout")],
233        },
234    }
235}
236
237// Reachability + activity helpers
238async fn is_reachable(host: &str, port_timeout_ms: u64) -> bool {
239    matches!(
240        timeout(Duration::from_millis(port_timeout_ms),
241                TcpStream::connect(format!("{host}:445"))).await,
242        Ok(Ok(_))
243    )
244}
245
246/// enabled + pwdLastSet within the expiry window (~ SharpHound ComputerExpiryDays).
247fn is_active(c: &Computer, expiry_days: i64) -> bool {
248    if !*c.properties().enabled() { return false; }
249    let pls = c.properties().pwdlastset();
250    if pls <= 0 { return false; }
251    let now = chrono::Utc::now().timestamp();
252    now - pls < expiry_days * 86_400
253}
254
255// Isolated RPC calls (unchanged from HasSession-rs)
256async fn srvsvc_sessions(smb: &mut SmbClient, host: &str) -> anyhow::Result<(Vec<SmbSession>, u32)> {
257    let pipe = open_rpc_pipe(smb, host, "srvsvc").await?;
258    let mut srv = SrvsvcClient::bind(smb, pipe).await?;
259    let (sessions, rc) = srv.enum_sessions().await?;
260    Ok((sessions.into_iter()
261        .map(|s| SmbSession { user: s.user, _client: s.client }).collect(), rc))
262}
263
264async fn enum_wksta(smb: &mut SmbClient, host: &str) -> anyhow::Result<(Vec<WkstaUser>, u32)> {
265    let pipe = open_rpc_pipe(smb, host, "wkssvc").await?;
266    let mut wk = WkstaUserClient::bind(smb, pipe).await?;
267    Ok(wk.enum_users().await?)
268}
269
270async fn enum_registry(smb: &mut SmbClient, domain: &str, user: &str,
271                       password: &str, nt_hash: Option<&[u8; 16]>, host: &str)
272    -> anyhow::Result<Vec<RegistrySession>>
273{
274    let mut reg = match nt_hash {
275        Some(h) => RegistryClient::connect_hash(smb, domain, user, h, host).await
276                       .map_err(|e| anyhow::anyhow!("{e}"))?,
277        None    => RegistryClient::connect(smb, domain, user, password, host).await
278                       .map_err(|e| anyhow::anyhow!("{e}"))?,
279    };
280    reg.logged_on_sids().await.map_err(|e| anyhow::anyhow!("{e}"))
281}
282
283/// Build the principal -> SID lookup from the users collected during LDAP.
284///
285/// `User::properties().name()` is already "SAMACCOUNTNAME@DOMAIN.FQDN" (UPPER),
286/// which we key directly. We also index the bare SAMAccountName as a fallback,
287/// because SRVSVC/WKSSVC hand back a bare username (no realm). Bare-SAM keys can
288/// collide across trusted domains; the fully-qualified key is always tried first.
289fn build_sid_index(users: &[User]) -> HashMap<String, String> {
290    let mut idx = HashMap::with_capacity(users.len() * 2);
291    for u in users {
292        let sid = u.object_identifier().clone();
293        if sid.is_empty() { continue; }
294        let upn = u.properties().name().to_uppercase(); // SAM@DOMAIN.FQDN
295        if let Some(sam) = upn.split('@').next() {
296            idx.entry(sam.to_string()).or_insert_with(|| sid.clone());
297        }
298        idx.insert(upn, sid);
299    }
300    idx
301}
302
303/// Resolve a principal string coming from an RPC call to a domain SID.
304///
305/// Handles "DOMAIN\\user", "DOMAIN/user" and bare "user"; drops empty / "?" /
306/// machine ("$") principals. Tries the fully-qualified key first, then bare SAM.
307fn resolve(raw: &str, idx: &HashMap<String, String>, domain: &str) -> Option<String> {
308    let bare = raw.rsplit(['\\', '/']).next().unwrap_or(raw).trim();
309    if bare.is_empty() || bare == "?" || bare.ends_with('$') {
310        return None;
311    }
312    let sam = bare.to_uppercase();
313    let upn = format!("{sam}@{}", domain.to_uppercase());
314    idx.get(&upn).or_else(|| idx.get(&sam)).cloned()
315}
316
317/// Construct a { UserSID, ComputerSID } link (fields are private -> use mutators).
318fn mk_link(user_sid: String, computer_sid: String) -> UserComputerSession {
319    let mut ucs = UserComputerSession::new();
320    *ucs.user_sid_mut() = user_sid;
321    *ucs.computer_sid_mut() = computer_sid;
322    ucs
323}
324
325/// De-duplicate WKSSVC logon sessions and drop machine accounts (noise on DCs).
326fn dedup_wksta(users: Vec<WkstaUser>) -> Vec<WkstaUser> {
327    use std::collections::BTreeSet;
328    let mut seen = BTreeSet::new();
329    users.into_iter()
330        .filter(|u| !u.username.ends_with('$'))
331        .filter(|u| seen.insert((u.logon_domain.clone(), u.username.clone())))
332        .collect()
333}
334
335/// Write one host's findings into the matching Computer object, and return the
336/// number of session links written for that host.
337///
338/// SRVSVC   -> Sessions            (resolve username -> UserSID)
339/// WKSSVC   -> PrivilegedSessions  (resolve username -> UserSID)
340/// WINREG   -> RegistrySessions    (r.sid is already a SID, no resolution)
341///
342/// Each block sets Collected = true; unresolved principals are logged at warn!
343/// rather than silently dropped, matching SharpHound's behaviour.
344fn apply_findings(
345    computers: &mut [Computer],
346    hf: &HostFindings,
347    sid_index: &HashMap<String, String>,
348    domain: &str,
349) -> usize {
350    let computer = match computers
351        .iter_mut()
352        .find(|c| c.object_identifier() == &hf.computer_sid)
353    {
354        Some(c) => c,
355        None => {
356            warn!("[sessions] no computer object for SID {}", hf.computer_sid);
357            return 0;
358        }
359    };
360    let comp_sid = hf.computer_sid.clone();
361    let fqdn = computer.properties().name().clone(); // clone before the mutable borrows
362    let mut count = 0usize;
363
364    // SRVSVC -> Sessions
365    {
366        let s = computer.sessions_mut();
367        for sess in &hf.smb_sessions {
368            match resolve(&sess.user, sid_index, domain) {
369                Some(user_sid) => {
370                    trace!("[SRVSVC] {} has session on {fqdn}", sess.user);
371                    s.results_mut().push(mk_link(user_sid, comp_sid.clone()));
372                    count += 1;
373                }
374                None => warn!("[{comp_sid}] unresolved SRVSVC principal '{}'", sess.user),
375            }
376        }
377        *s.collected_mut() = true;
378    }
379
380    // WKSSVC -> PrivilegedSessions
381    {
382        let p = computer.privileged_sessions_mut();
383        for u in &hf.logged_on {
384            match resolve(&u.username, sid_index, domain) {
385                Some(user_sid) => {
386                    trace!("[WKSSVC] {}\\{} has session on {fqdn}", u.logon_domain, u.username);
387                    p.results_mut().push(mk_link(user_sid, comp_sid.clone()));
388                    count += 1;
389                }
390                None => warn!("[{comp_sid}] unresolved WKSSVC principal '{}\\{}'",
391                               u.logon_domain, u.username),
392            }
393        }
394        *p.collected_mut() = true;
395    }
396
397    // WINREG -> RegistrySessions (SIDs already; no resolution needed)
398    {
399        let r = computer.registry_sessions_mut();
400        for reg in &hf.registry {
401            if reg.sid.is_empty() { continue; }
402            trace!("[WINREG] {} has session on {fqdn}", reg.sid);
403            r.results_mut().push(mk_link(reg.sid.clone(), comp_sid.clone()));
404            count += 1;
405        }
406        *r.collected_mut() = true;
407    }
408
409    debug!("[sessions] Total {count} session(s) on {fqdn}");
410    count
411}
412
413/// Parse a hash string into the 16-byte NT hash for pass-the-hash.
414///
415/// Accepts "LMHASH:NTHASH", ":NTHASH" or a bare 32-hex "NTHASH". Returns None
416/// when absent or malformed (caller then falls back to password auth).
417fn parse_hash(h: Option<&str>) -> Option<[u8; 16]> {
418    let raw = h?.trim();
419    let nt = raw.rsplit(':').next().unwrap_or(raw).trim();
420    if nt.len() != 32 || !nt.bytes().all(|b| b.is_ascii_hexdigit()) {
421        return None;
422    }
423    let mut out = [0u8; 16];
424    for (i, byte) in out.iter_mut().enumerate() {
425        *byte = u8::from_str_radix(&nt[i * 2..i * 2 + 2], 16).ok()?;
426    }
427    Some(out)
428}