1use crate::audit::{AuditLogger, AuditStorage, GeolocationInfo, RequestMetadata};
8use crate::errors::{AuthError, Result};
9use crate::threat_intelligence::{ThreatFeedManager, ThreatIntelConfig};
10use async_trait::async_trait;
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
13use std::time::{Duration, SystemTime};
14
15#[derive(Clone, Serialize, Deserialize)]
19pub struct Session {
20 pub id: String,
22 pub user_id: String,
24 pub created_at: SystemTime,
26 pub last_accessed: SystemTime,
28 pub expires_at: SystemTime,
30 pub state: SessionState,
32 pub device_info: DeviceInfo,
34 pub security_metadata: SecurityMetadata,
36 pub data: HashMap<String, String>,
38 pub mfa_verified: bool,
40 pub cached_permissions: Option<Vec<String>>,
42 pub last_activity: ActivityInfo,
44}
45
46impl std::fmt::Debug for Session {
47 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48 let mut d = f.debug_struct("Session");
49 d.field("id", &crate::utils::redact::redacted(&self.id));
50 d.field("user_id", &self.user_id);
51 d.field("created_at", &self.created_at);
52 d.field("last_accessed", &self.last_accessed);
53 d.field("expires_at", &self.expires_at);
54 d.field("state", &self.state);
55 d.field("device_info", &self.device_info);
56 d.field("security_metadata", &self.security_metadata);
57 d.field("data", &crate::utils::redact::redacted(&self.data));
58 d.field("mfa_verified", &self.mfa_verified);
59 d.field("cached_permissions", &self.cached_permissions);
60 d.field("last_activity", &self.last_activity);
61 d.finish()
62 }
63}
64
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
67pub enum SessionState {
68 Active,
69 Expired,
70 Revoked,
71 Suspended,
72 RequiresMfa,
73 RequiresReauth,
74}
75
76#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct DeviceInfo {
79 pub fingerprint: String,
81 pub device_type: String,
83 pub operating_system: Option<String>,
85 pub browser: Option<String>,
87 pub screen_resolution: Option<String>,
89 pub timezone: Option<String>,
91 pub language: Option<String>,
93 pub is_trusted: bool,
95 pub device_name: Option<String>,
97}
98
99#[derive(Debug, Clone, Serialize, Deserialize)]
101pub struct SecurityMetadata {
102 pub creation_ip: String,
104 pub current_ip: String,
106 pub creation_location: Option<GeolocationInfo>,
108 pub current_location: Option<GeolocationInfo>,
110 pub security_flags: Vec<SecurityFlag>,
112 pub risk_score: u8,
114 pub location_changed: bool,
116 pub ip_changed: bool,
118 pub failed_auth_attempts: u32,
120}
121
122#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
124pub enum SecurityFlag {
125 SuspiciousActivity,
126 LocationAnomaly,
127 DeviceAnomaly,
128 TimeAnomaly,
129 ConcurrentSessionLimit,
130 BruteForceAttempt,
131 RequiresVerification,
132 ElevatedPrivileges,
133}
134
135#[derive(Debug, Clone, Serialize, Deserialize)]
137pub struct ActivityInfo {
138 pub endpoint: Option<String>,
140 pub action: Option<String>,
142 pub request_metadata: Option<RequestMetadata>,
144 pub timestamp: SystemTime,
146}
147
148#[derive(Debug, Clone)]
150pub struct SessionConfig {
151 pub default_duration: Duration,
153 pub max_duration: Duration,
155 pub idle_timeout: Duration,
157 pub rotate_on_privilege_escalation: bool,
159 pub rotate_periodically: bool,
161 pub rotation_interval: Duration,
163 pub max_concurrent_sessions: Option<u32>,
165 pub track_device_fingerprints: bool,
167 pub enforce_geographic_restrictions: bool,
169 pub allowed_countries: Vec<String>,
171 pub security_policy: SessionSecurityPolicy,
173}
174
175#[derive(Debug, Clone)]
177pub struct SessionSecurityPolicy {
178 pub require_mfa_for_new_devices: bool,
180 pub require_reauth_for_sensitive_ops: bool,
182 pub reauth_timeout: Duration,
184 pub max_risk_score: u8,
186 pub auto_suspend_suspicious: bool,
188 pub verify_location_changes: bool,
190 pub limit_concurrent_sessions: bool,
192}
193
194#[async_trait]
196pub trait SessionStorage: Send + Sync {
197 async fn create_session(&self, session: &Session) -> Result<()>;
199
200 async fn get_session(&self, session_id: &str) -> Result<Option<Session>>;
202
203 async fn update_session(&self, session: &Session) -> Result<()>;
205
206 async fn delete_session(&self, session_id: &str) -> Result<()>;
208
209 async fn get_user_sessions(&self, user_id: &str) -> Result<Vec<Session>>;
211
212 async fn count_active_sessions(&self, user_id: &str) -> Result<u32>;
214
215 async fn cleanup_expired_sessions(&self) -> Result<u32>;
217
218 async fn find_sessions_by_device(&self, device_fingerprint: &str) -> Result<Vec<Session>>;
220
221 async fn find_sessions_by_ip(&self, ip_address: &str) -> Result<Vec<Session>>;
223}
224
225pub struct SessionManager<S: SessionStorage, A: AuditStorage> {
227 storage: S,
228 config: SessionConfig,
229 audit_logger: AuditLogger<A>,
230 fingerprint_generator: DeviceFingerprintGenerator,
231 risk_calculator: RiskCalculator,
232 threat_intel_manager: Option<ThreatFeedManager>,
233}
234
235impl<S: SessionStorage, A: AuditStorage> SessionManager<S, A> {
236 pub fn new(storage: S, config: SessionConfig, audit_logger: AuditLogger<A>) -> Self {
238 let threat_intel_manager = if std::env::var("THREAT_INTEL_ENABLED")
240 .unwrap_or_else(|_| "false".to_string())
241 .to_lowercase()
242 == "true"
243 {
244 match ThreatIntelConfig::from_env_and_config() {
245 Ok(intel_config) => {
246 log::info!(
247 "🟢 Automated threat intelligence enabled - feeds will update automatically"
248 );
249 match ThreatFeedManager::new(intel_config) {
250 Ok(manager) => {
251 if let Err(e) = manager.start_automated_updates() {
253 log::error!("Failed to start automated threat feed updates: {}", e);
254 None
255 } else {
256 log::info!(
257 "✅ Threat intelligence automation started successfully"
258 );
259 Some(manager)
260 }
261 }
262 Err(e) => {
263 log::error!("Failed to initialize threat intelligence manager: {}", e);
264 None
265 }
266 }
267 }
268 Err(e) => {
269 log::error!("Failed to load threat intelligence configuration: {}", e);
270 None
271 }
272 }
273 } else {
274 log::info!("🔴 Automated threat intelligence disabled (THREAT_INTEL_ENABLED=false)");
275 None
276 };
277
278 Self {
279 storage,
280 config,
281 audit_logger,
282 fingerprint_generator: DeviceFingerprintGenerator::new(),
283 risk_calculator: RiskCalculator::new(),
284 threat_intel_manager,
285 }
286 }
287
288 pub async fn create_session(
290 &self,
291 user_id: &str,
292 mut device_info: DeviceInfo,
293 metadata: RequestMetadata,
294 ) -> Result<Session> {
295 if device_info.fingerprint.is_empty() {
297 device_info.fingerprint = self.fingerprint_generator.generate_fingerprint(&metadata);
298 }
299
300 if let Some(max_sessions) = self.config.max_concurrent_sessions {
302 let active_count = self.storage.count_active_sessions(user_id).await?;
303 if active_count >= max_sessions {
304 return Err(AuthError::TooManyConcurrentSessions);
305 }
306 }
307
308 let now = SystemTime::now();
309 let session_id = self.generate_session_id();
310
311 let risk_score = self.risk_calculator.calculate_risk(
313 &device_info,
314 &metadata,
315 &self.get_user_session_history(user_id).await?,
316 self.threat_intel_manager.as_ref(),
317 );
318
319 let mut security_flags = Vec::new();
320 if risk_score > 70 {
321 security_flags.push(SecurityFlag::SuspiciousActivity);
322 }
323
324 let existing_sessions = self
326 .storage
327 .find_sessions_by_device(&device_info.fingerprint)
328 .await?;
329 let is_new_device = existing_sessions.is_empty();
330
331 if is_new_device && self.config.security_policy.require_mfa_for_new_devices {
332 security_flags.push(SecurityFlag::RequiresVerification);
333 }
334
335 let session = Session {
336 id: session_id.clone(),
337 user_id: user_id.to_string(),
338 created_at: now,
339 last_accessed: now,
340 expires_at: now + self.config.default_duration,
341 state: if security_flags.contains(&SecurityFlag::RequiresVerification) {
342 SessionState::RequiresMfa
343 } else {
344 SessionState::Active
345 },
346 device_info: device_info.clone(),
347 security_metadata: SecurityMetadata {
348 creation_ip: metadata.ip_address.clone().unwrap_or_default(),
349 current_ip: metadata.ip_address.clone().unwrap_or_default(),
350 creation_location: metadata.geolocation.clone(),
351 current_location: metadata.geolocation.clone(),
352 security_flags,
353 risk_score,
354 location_changed: false,
355 ip_changed: false,
356 failed_auth_attempts: 0,
357 },
358 data: HashMap::new(),
359 mfa_verified: false,
360 cached_permissions: None,
361 last_activity: ActivityInfo {
362 endpoint: metadata.endpoint.clone(),
363 action: Some("session_created".to_string()),
364 request_metadata: Some(metadata.clone()),
365 timestamp: now,
366 },
367 };
368
369 self.storage.create_session(&session).await?;
370
371 self.audit_logger
373 .log_event(crate::audit::AuditEvent {
374 id: String::new(),
375 event_type: crate::audit::AuditEventType::LoginSuccess,
376 timestamp: now,
377 user_id: Some(user_id.to_string()),
378 session_id: Some(session_id),
379 outcome: crate::audit::EventOutcome::Success,
380 risk_level: if risk_score > 70 {
381 crate::audit::RiskLevel::High
382 } else {
383 crate::audit::RiskLevel::Low
384 },
385 description: "Session created".to_string(),
386 details: HashMap::new(),
387 request_metadata: metadata,
388 resource: None,
389 actor: crate::audit::ActorInfo {
390 actor_type: "user".to_string(),
391 actor_id: user_id.to_string(),
392 actor_name: None,
393 roles: vec![],
394 },
395 correlation_id: None,
396 })
397 .await?;
398
399 Ok(session)
400 }
401
402 pub async fn validate_session(
404 &self,
405 session_id: &str,
406 metadata: RequestMetadata,
407 ) -> Result<Option<Session>> {
408 let mut session = match self.storage.get_session(session_id).await? {
409 Some(session) => session,
410 None => return Ok(None),
411 };
412
413 let now = SystemTime::now();
414
415 if session.expires_at <= now {
417 session.state = SessionState::Expired;
418 self.storage.update_session(&session).await?;
419 return Ok(None);
420 }
421
422 let current_fingerprint = self.fingerprint_generator.generate_fingerprint(&metadata);
424 if current_fingerprint != session.device_info.fingerprint {
425 session.state = SessionState::RequiresMfa;
427 self.storage.update_session(&session).await?;
428
429 self.audit_logger
431 .log_suspicious_activity(
432 Some(&session.user_id),
433 "device_fingerprint_mismatch",
434 &format!(
435 "Session ID: {}, Expected: {}, Got: {}",
436 crate::utils::redact::fingerprint(session_id),
437 session.device_info.fingerprint,
438 current_fingerprint
439 ),
440 metadata.clone(),
441 )
442 .await?;
443 }
444
445 let idle_duration = now
447 .duration_since(session.last_accessed)
448 .unwrap_or_default();
449 if idle_duration > self.config.idle_timeout {
450 session.state = SessionState::Expired;
451 self.storage.update_session(&session).await?;
452 return Ok(None);
453 }
454
455 match session.state {
457 SessionState::Expired | SessionState::Revoked | SessionState::Suspended => {
458 return Ok(None);
459 }
460 SessionState::RequiresMfa | SessionState::RequiresReauth => {
461 return Ok(Some(session));
463 }
464 SessionState::Active => {}
465 }
466
467 let current_ip = metadata.ip_address.clone().unwrap_or_default();
469 let ip_changed = current_ip != session.security_metadata.current_ip;
470
471 if ip_changed {
472 session.security_metadata.ip_changed = true;
473 session.security_metadata.current_ip = current_ip;
474
475 if self.config.security_policy.verify_location_changes {
477 session
478 .security_metadata
479 .security_flags
480 .push(SecurityFlag::LocationAnomaly);
481 session.state = SessionState::RequiresReauth;
482 }
483 }
484
485 session.last_accessed = now;
487 session.last_activity = ActivityInfo {
488 endpoint: metadata.endpoint.clone(),
489 action: Some("session_validated".to_string()),
490 request_metadata: Some(metadata),
491 timestamp: now,
492 };
493
494 let should_rotate = self.should_rotate_session(&session);
496 if should_rotate {
497 let new_session_id = self.generate_session_id();
498 let old_session_id = session.id.clone();
499 session.id = new_session_id;
500
501 self.storage.delete_session(&old_session_id).await?;
503 self.storage.create_session(&session).await?;
504 } else {
505 self.storage.update_session(&session).await?;
506 }
507
508 Ok(Some(session))
509 }
510
511 pub async fn revoke_session(&self, session_id: &str) -> Result<()> {
513 if let Some(mut session) = self.storage.get_session(session_id).await? {
514 session.state = SessionState::Revoked;
515 self.storage.update_session(&session).await?;
516
517 self.audit_logger
519 .log_event(crate::audit::AuditEvent {
520 id: String::new(),
521 event_type: crate::audit::AuditEventType::Logout,
522 timestamp: SystemTime::now(),
523 user_id: Some(session.user_id),
524 session_id: Some(session_id.to_string()),
525 outcome: crate::audit::EventOutcome::Success,
526 risk_level: crate::audit::RiskLevel::Low,
527 description: "Session revoked".to_string(),
528 details: HashMap::new(),
529 request_metadata: crate::audit::RequestMetadata::default(),
530 resource: None,
531 actor: crate::audit::ActorInfo {
532 actor_type: "system".to_string(),
533 actor_id: "session_manager".to_string(),
534 actor_name: None,
535 roles: vec![],
536 },
537 correlation_id: None,
538 })
539 .await?;
540 }
541 Ok(())
542 }
543
544 pub async fn revoke_all_user_sessions(&self, user_id: &str) -> Result<u32> {
546 let sessions = self.storage.get_user_sessions(user_id).await?;
547 let mut revoked_count = 0;
548
549 for mut session in sessions {
550 if session.state == SessionState::Active {
551 session.state = SessionState::Revoked;
552 self.storage.update_session(&session).await?;
553 revoked_count += 1;
554 }
555 }
556
557 Ok(revoked_count)
558 }
559
560 pub async fn get_user_sessions(
562 &self,
563 user_id: &str,
564 include_inactive: bool,
565 ) -> Result<Vec<Session>> {
566 let mut sessions = self.storage.get_user_sessions(user_id).await?;
567
568 if !include_inactive {
569 sessions.retain(|s| s.state == SessionState::Active);
570 }
571
572 Ok(sessions)
573 }
574
575 pub async fn cleanup_expired_sessions(&self) -> Result<u32> {
577 self.storage.cleanup_expired_sessions().await
578 }
579
580 pub fn generate_device_fingerprint(&self, metadata: &RequestMetadata) -> String {
582 self.fingerprint_generator.generate_fingerprint(metadata)
583 }
584
585 pub fn validate_device_fingerprint(
587 &self,
588 session: &Session,
589 metadata: &RequestMetadata,
590 ) -> bool {
591 let current_fingerprint = self.fingerprint_generator.generate_fingerprint(metadata);
592 current_fingerprint == session.device_info.fingerprint
593 }
594
595 pub async fn suspend_session(&self, session_id: &str, reason: &str) -> Result<()> {
597 if let Some(mut session) = self.storage.get_session(session_id).await? {
598 session.state = SessionState::Suspended;
599 session
600 .security_metadata
601 .security_flags
602 .push(SecurityFlag::SuspiciousActivity);
603
604 self.storage.update_session(&session).await?;
605
606 let mut details = HashMap::new();
608 details.insert("suspension_reason".to_string(), reason.to_string());
609
610 self.audit_logger
611 .log_event(crate::audit::AuditEvent {
612 id: String::new(),
613 event_type: crate::audit::AuditEventType::AccountLocked,
614 timestamp: SystemTime::now(),
615 user_id: Some(session.user_id),
616 session_id: Some(session_id.to_string()),
617 outcome: crate::audit::EventOutcome::Success,
618 risk_level: crate::audit::RiskLevel::High,
619 description: format!("Session suspended: {}", reason),
620 details,
621 request_metadata: crate::audit::RequestMetadata::default(),
622 resource: None,
623 actor: crate::audit::ActorInfo {
624 actor_type: "system".to_string(),
625 actor_id: "security_monitor".to_string(),
626 actor_name: None,
627 roles: vec![],
628 },
629 correlation_id: None,
630 })
631 .await?;
632 }
633 Ok(())
634 }
635
636 pub async fn update_session_data(
638 &self,
639 session_id: &str,
640 key: &str,
641 value: &str,
642 ) -> Result<()> {
643 if let Some(mut session) = self.storage.get_session(session_id).await? {
644 session.data.insert(key.to_string(), value.to_string());
645 session.last_accessed = SystemTime::now();
646 self.storage.update_session(&session).await?;
647 }
648 Ok(())
649 }
650
651 fn generate_session_id(&self) -> String {
653 format!("sess_{}", uuid::Uuid::new_v4())
654 }
655
656 fn should_rotate_session(&self, session: &Session) -> bool {
658 if !self.config.rotate_periodically {
659 return false;
660 }
661
662 let session_age = SystemTime::now()
663 .duration_since(session.created_at)
664 .unwrap_or_default();
665
666 session_age > self.config.rotation_interval
667 }
668
669 async fn get_user_session_history(&self, user_id: &str) -> Result<Vec<Session>> {
671 self.storage.get_user_sessions(user_id).await
674 }
675}
676
677pub struct DeviceFingerprintGenerator;
679
680impl Default for DeviceFingerprintGenerator {
681 fn default() -> Self {
682 Self::new()
683 }
684}
685
686impl DeviceFingerprintGenerator {
687 pub fn new() -> Self {
688 Self
689 }
690
691 pub fn generate_fingerprint(&self, metadata: &RequestMetadata) -> String {
693 let mut fingerprint_data = Vec::new();
694
695 if let Some(ua) = &metadata.user_agent {
696 fingerprint_data.push(ua.clone());
697 }
698
699 self.add_advanced_fingerprinting_data(&mut fingerprint_data, metadata);
701
702 let fingerprint_string = fingerprint_data.join("|");
703 format!("fp_{:x}", crc32fast::hash(fingerprint_string.as_bytes()))
704 }
705
706 fn add_advanced_fingerprinting_data(
708 &self,
709 fingerprint_data: &mut Vec<String>,
710 metadata: &RequestMetadata,
711 ) {
712 if let Some(ref ip) = metadata.ip_address {
714 fingerprint_data.push(format!("geo:{}", self.get_ip_geolocation(ip)));
716 }
717
718 fingerprint_data.push(format!("lang:{}", self.get_system_language()));
720 fingerprint_data.push(format!("tz:{}", self.get_timezone_offset()));
721 fingerprint_data.push(format!("hw:{}", self.get_hardware_concurrency()));
722
723 fingerprint_data.push(format!("conn:{}", self.get_connection_info()));
725
726 fingerprint_data.push(format!("caps:{}", self.get_client_capabilities()));
728 }
729
730 fn get_ip_geolocation(&self, ip: &str) -> String {
732 use std::net::IpAddr;
733 use std::str::FromStr;
734
735 if let Ok(ip_addr) = IpAddr::from_str(ip) {
737 match ip_addr {
738 IpAddr::V4(ipv4) => {
739 let octets = ipv4.octets();
740
741 if (octets[0] == 10)
743 || (octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31)
744 || (octets[0] == 192 && octets[1] == 168)
745 {
746 return "private_rfc1918".to_string();
747 }
748
749 if octets[0] == 127 {
751 return "loopback".to_string();
752 }
753
754 if octets[0] == 169 && octets[1] == 254 {
756 return "link_local".to_string();
757 }
758
759 if octets[0] >= 224 && octets[0] <= 239 {
761 return "multicast".to_string();
762 }
763
764 match (octets[0], octets[1], octets[2], octets[3]) {
766 (8, 8, 8, 8) | (8, 8, 4, 4) => "google_dns".to_string(),
767 (1, 1, 1, 1) | (1, 0, 0, 1) => "cloudflare_dns".to_string(),
768 (208, 67, 222, 222) | (208, 67, 220, 220) => "opendns".to_string(),
769 _ => {
770 self.lookup_maxmind_geolocation(&ipv4).unwrap_or_else(|| {
772 match octets[0] {
774 1..=23 => "apnic_region".to_string(), 24..=49 => "arin_region".to_string(), 50..=99 => "ripe_region".to_string(), 100..=127 => "mixed_region".to_string(), 128..=191 => "arin_region".to_string(), 192..=223 => "ripe_apnic_region".to_string(), _ => format!("public_class_{}", octets[0] / 64),
781 }
782 })
783 }
784 }
785 }
786 IpAddr::V6(ipv6) => {
787 let segments = ipv6.segments();
788
789 if ipv6.is_loopback() {
791 return "ipv6_loopback".to_string();
792 }
793
794 if segments[0] & 0xffc0 == 0xfe80 {
796 return "ipv6_link_local".to_string();
797 }
798
799 if segments[0] & 0xfe00 == 0xfc00 {
801 return "ipv6_unique_local".to_string();
802 }
803
804 if segments[0] & 0xff00 == 0xff00 {
806 return "ipv6_multicast".to_string();
807 }
808
809 format!("ipv6_global_{:x}", segments[0] / 0x1000)
811 }
812 }
813 } else {
814 "invalid_ip".to_string()
815 }
816 }
817
818 fn get_system_language(&self) -> String {
820 "en-US".to_string()
822 }
823
824 fn get_timezone_offset(&self) -> String {
826 "-05:00".to_string() }
829
830 fn get_hardware_concurrency(&self) -> String {
832 "4".to_string()
834 }
835
836 fn get_connection_info(&self) -> String {
838 "wifi".to_string()
840 }
841
842 fn get_client_capabilities(&self) -> String {
844 "webgl2_canvas_audio".to_string()
846 }
847
848 fn lookup_maxmind_geolocation(&self, ip: &std::net::Ipv4Addr) -> Option<String> {
850 use std::path::Path;
851
852 let db_path =
854 std::env::var("MAXMIND_DB_PATH").unwrap_or_else(|_| "GeoLite2-City.mmdb".to_string());
855
856 if !Path::new(&db_path).exists() {
857 log::warn!(
858 "MaxMind database not found at {}, falling back to basic geolocation",
859 db_path
860 );
861 return None;
862 }
863
864 match maxminddb::Reader::open_readfile(&db_path) {
865 Ok(reader) => {
866 match reader.lookup((*ip).into()) {
867 Ok(result) => match result.decode::<maxminddb::geoip2::City>() {
868 Ok(Some(city)) => {
869 let mut location_parts = Vec::new();
870
871 if let Some(name) = city.country.names.english {
873 location_parts.push(format!("country:{}", name));
874 }
875
876 if let Some(subdivision) = city.subdivisions.first()
877 && let Some(name) = subdivision.names.english
878 {
879 location_parts.push(format!("region:{}", name));
880 }
881
882 if let Some(name) = city.city.names.english {
883 location_parts.push(format!("city:{}", name));
884 }
885
886 let location = &city.location;
887 if let (Some(lat), Some(lon)) = (location.latitude, location.longitude)
888 {
889 location_parts.push(format!("coords:{:.4},{:.4}", lat, lon));
890 }
891
892 if city.traits.is_anycast == Some(true) {
895 location_parts.push("threats:anycast".to_string());
896 }
897
898 Some(location_parts.join("|"))
899 }
900 Ok(None) => {
901 log::debug!("MaxMind lookup returned no data for {}", ip);
902 None
903 }
904 Err(e) => {
905 log::debug!("MaxMind decode failed for {}: {}", ip, e);
906 None
907 }
908 },
909 Err(e) => {
910 log::debug!("MaxMind lookup failed for {}: {}", ip, e);
911 None
912 }
913 }
914 }
915 Err(e) => {
916 log::warn!("Failed to open MaxMind database: {}", e);
917 None
918 }
919 }
920 }
921}
922
923pub struct RiskCalculator;
925
926impl Default for RiskCalculator {
927 fn default() -> Self {
928 Self::new()
929 }
930}
931
932impl RiskCalculator {
933 pub fn new() -> Self {
934 Self
935 }
936
937 pub fn calculate_risk(
939 &self,
940 device_info: &DeviceInfo,
941 metadata: &RequestMetadata,
942 _session_history: &[Session],
943 threat_intel_manager: Option<&ThreatFeedManager>,
944 ) -> u8 {
945 let mut risk_score = 0u8;
946
947 if !device_info.is_trusted {
949 risk_score += 20;
950 }
951
952 if let Some(ip) = &metadata.ip_address
954 && self.is_suspicious_ip(ip, threat_intel_manager)
955 {
956 risk_score += 30;
957 }
958
959 if let Some(location) = &metadata.geolocation {
961 let mut geo_risk = 0;
962
963 if let Some(country) = &location.country {
965 let country_lower = country.to_lowercase();
966
967 let high_risk_countries =
969 ["tor", "anonymous", "vpn", "proxy", "hosting", "datacenter"];
970
971 for indicator in &high_risk_countries {
972 if country_lower.contains(indicator) {
973 geo_risk += 30;
974 break;
975 }
976 }
977
978 geo_risk += self.assess_country_threat_level(&country_lower) as u8;
980
981 let elevated_risk_patterns = ["cloud", "aws", "azure", "gcp"];
983 for pattern in &elevated_risk_patterns {
984 if country_lower.contains(pattern) {
985 geo_risk += 20;
986 break;
987 }
988 }
989 }
990
991 if let (Some(lat), Some(lon)) = (location.latitude, location.longitude) {
993 if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {
995 geo_risk += 25; }
997
998 if (lat * 100.0).fract().abs() < 0.01 && (lon * 100.0).fract().abs() < 0.01 {
1000 geo_risk += 15; }
1002 }
1003
1004 if let Some(region) = &location.region {
1006 let region_lower = region.to_lowercase();
1007 if region_lower.contains("hosting") || region_lower.contains("datacenter") {
1008 geo_risk += 20;
1009 }
1010 }
1011
1012 if let Some(city) = &location.city {
1014 let city_lower = city.to_lowercase();
1015 if city_lower.contains("server") || city_lower.contains("datacenter") {
1016 geo_risk += 15;
1017 }
1018 }
1019
1020 risk_score += geo_risk;
1021 }
1022
1023 risk_score.min(100)
1029 }
1030
1031 fn is_suspicious_ip(&self, ip: &str, threat_intel_manager: Option<&ThreatFeedManager>) -> bool {
1033 use std::net::IpAddr;
1034 use std::str::FromStr;
1035
1036 if let Ok(ip_addr) = IpAddr::from_str(ip) {
1038 match ip_addr {
1039 IpAddr::V4(ipv4) => {
1040 let octets = ipv4.octets();
1041
1042 if self.check_malicious_ip_feeds(&ipv4, threat_intel_manager) {
1044 return true;
1045 }
1046
1047 let suspicious_ranges = [
1049 (5, 0, 0, 0, 8), (31, 0, 0, 0, 8), (37, 0, 0, 0, 8), (46, 0, 0, 0, 8), (95, 0, 0, 0, 8), (185, 0, 0, 0, 8), ];
1057
1058 for (net, _, _, _, _) in &suspicious_ranges {
1059 if octets[0] == *net {
1060 return true;
1061 }
1062 }
1063
1064 if octets[0] == 0 || (octets[0] == 100 && octets[1] >= 64 && octets[1] <= 127) || (octets[0] == 169 && octets[1] == 254) || (octets[0] >= 224 && octets[0] <= 239) || (octets[0] >= 240)
1070 {
1071 return true;
1073 }
1074
1075 if octets[3] == 0 || octets[3] == 255 {
1077 return true;
1078 }
1079
1080 if self.check_proxy_vpn_databases(&ipv4) {
1082 return true;
1083 }
1084
1085 let proxy_ports_in_ip = [
1087 80, 443, 8080, 3128, 1080, 8000, 8888, 9050, ];
1089
1090 for &port in &proxy_ports_in_ip {
1091 if octets[2] == (port / 256) as u8 && octets[3] == (port % 256) as u8 {
1092 return true;
1093 }
1094 }
1095
1096 false
1097 }
1098 IpAddr::V6(ipv6) => {
1099 let segments = ipv6.segments();
1100
1101 if self.check_tor_exit_nodes(&ipv6) {
1103 return true;
1104 }
1105
1106 if segments[0] == 0x2001 && segments[1] == 0x67c {
1108 return true;
1110 }
1111
1112 let mut sequential_count = 0;
1114 for i in 1..segments.len() {
1115 if segments[i] == segments[i - 1] + 1 {
1116 sequential_count += 1;
1117 }
1118 }
1119 if sequential_count >= 4 {
1120 return true;
1122 }
1123
1124 if segments[0] == 0x2001 && segments[1] == 0x470 {
1126 return true;
1128 }
1129
1130 false
1131 }
1132 }
1133 } else {
1134 true }
1136 }
1137
1138 fn assess_country_threat_level(&self, country: &str) -> u32 {
1140 use std::path::Path;
1141
1142 let threat_db_path = std::env::var("COUNTRY_THREAT_DB_PATH")
1144 .unwrap_or_else(|_| "country-threats.csv".to_string());
1145
1146 if Path::new(&threat_db_path).exists() {
1147 if let Ok(contents) = std::fs::read_to_string(&threat_db_path) {
1149 let mut csv_reader = csv::Reader::from_reader(contents.as_bytes());
1150
1151 for result in csv_reader.records() {
1152 if let Ok(record) = result
1153 && record.len() >= 2
1154 {
1155 let threat_country = record[0].to_lowercase();
1156 if let Ok(risk_score) = record[1].parse::<u32>()
1157 && country.contains(&threat_country)
1158 {
1159 log::debug!("Country threat match: {} -> risk {}", country, risk_score);
1160 return risk_score;
1161 }
1162 }
1163 }
1164 }
1165 }
1166
1167 let high_risk_indicators = [
1169 ("botnet", 40),
1170 ("malware", 35),
1171 ("ransomware", 45),
1172 ("cybercrime", 30),
1173 ("hacking", 25),
1174 ("fraud", 20),
1175 ];
1176
1177 for (indicator, risk) in &high_risk_indicators {
1178 if country.contains(indicator) {
1179 return *risk;
1180 }
1181 }
1182
1183 let hosting_risk_patterns = [
1185 ("hosting", 15),
1186 ("datacenter", 15),
1187 ("cloud", 10),
1188 ("server", 12),
1189 ("vps", 18),
1190 ("dedicated", 10),
1191 ];
1192
1193 for (pattern, risk) in &hosting_risk_patterns {
1194 if country.contains(pattern) {
1195 return *risk;
1196 }
1197 }
1198
1199 0 }
1201
1202 fn check_malicious_ip_feeds(
1204 &self,
1205 ip: &std::net::Ipv4Addr,
1206 threat_intel_manager: Option<&ThreatFeedManager>,
1207 ) -> bool {
1208 if let Some(threat_manager) = threat_intel_manager {
1210 return threat_manager.is_malicious_ip(&std::net::IpAddr::V4(*ip));
1211 }
1212
1213 use std::path::Path;
1215
1216 let feed_paths = [
1218 std::env::var("MALICIOUS_IPS_DB_PATH")
1219 .unwrap_or_else(|_| "malicious-ips.txt".to_string()),
1220 std::env::var("BOTNET_IPS_DB_PATH").unwrap_or_else(|_| "botnet-ips.txt".to_string()),
1221 std::env::var("TOR_EXIT_NODES_DB_PATH").unwrap_or_else(|_| "tor-exits.txt".to_string()),
1222 ];
1223
1224 for feed_path in &feed_paths {
1225 if Path::new(feed_path).exists()
1226 && let Ok(contents) = std::fs::read_to_string(feed_path)
1227 {
1228 for line in contents.lines() {
1229 let line = line.trim();
1230 if line.is_empty() || line.starts_with('#') {
1231 continue;
1232 }
1233
1234 if line == ip.to_string() {
1236 log::warn!("Malicious IP detected: {} (source: {})", ip, feed_path);
1237 return true;
1238 }
1239
1240 if line.contains('/')
1242 && let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
1243 && network.contains(*ip)
1244 {
1245 log::warn!(
1246 "Malicious network detected: {} in {} (source: {})",
1247 ip,
1248 network,
1249 feed_path
1250 );
1251 return true;
1252 }
1253 }
1254 }
1255 }
1256
1257 false
1258 }
1259
1260 fn check_proxy_vpn_databases(&self, ip: &std::net::Ipv4Addr) -> bool {
1262 use std::path::Path;
1263
1264 let db_sources = [
1266 ("VPN_DATABASE_PATH", "vpn-ranges.txt"),
1267 ("PROXY_DATABASE_PATH", "proxy-ips.txt"),
1268 ("DATACENTER_DATABASE_PATH", "datacenter-ranges.txt"),
1269 ("HOSTING_DATABASE_PATH", "hosting-providers.txt"),
1270 ];
1271
1272 for (env_var, default_file) in &db_sources {
1273 let db_path = std::env::var(env_var).unwrap_or_else(|_| default_file.to_string());
1274
1275 if Path::new(&db_path).exists()
1276 && let Ok(contents) = std::fs::read_to_string(&db_path)
1277 {
1278 for line in contents.lines() {
1279 let line = line.trim();
1280 if line.is_empty() || line.starts_with('#') {
1281 continue;
1282 }
1283
1284 if line.contains('/') {
1286 if let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
1288 && network.contains(*ip)
1289 {
1290 log::info!(
1291 "Proxy/VPN detected: {} in {} (source: {})",
1292 ip,
1293 network,
1294 db_path
1295 );
1296 return true;
1297 }
1298 } else if line.contains('-') {
1299 let parts: Vec<&str> = line.split('-').collect();
1301 if parts.len() == 2
1302 && let (Ok(start_ip), Ok(end_ip)) = (
1303 parts[0].trim().parse::<std::net::Ipv4Addr>(),
1304 parts[1].trim().parse::<std::net::Ipv4Addr>(),
1305 )
1306 {
1307 let ip_u32 = u32::from(*ip);
1308 let start_u32 = u32::from(start_ip);
1309 let end_u32 = u32::from(end_ip);
1310
1311 if ip_u32 >= start_u32 && ip_u32 <= end_u32 {
1312 log::info!(
1313 "Proxy/VPN range detected: {} in {}-{} (source: {})",
1314 ip,
1315 start_ip,
1316 end_ip,
1317 db_path
1318 );
1319 return true;
1320 }
1321 }
1322 } else if line == ip.to_string() {
1323 log::info!("Proxy/VPN exact match: {} (source: {})", ip, db_path);
1325 return true;
1326 }
1327 }
1328 }
1329 }
1330
1331 false
1332 }
1333
1334 fn check_tor_exit_nodes(&self, ip: &std::net::Ipv6Addr) -> bool {
1336 use std::path::Path;
1337
1338 let tor_db_path = std::env::var("TOR_EXIT_NODES_IPV6_PATH")
1340 .unwrap_or_else(|_| "tor-exits-ipv6.txt".to_string());
1341
1342 if Path::new(&tor_db_path).exists()
1343 && let Ok(contents) = std::fs::read_to_string(&tor_db_path)
1344 {
1345 for line in contents.lines() {
1346 let line = line.trim();
1347 if line.is_empty() || line.starts_with('#') {
1348 continue;
1349 }
1350
1351 if let Ok(tor_ip) = line.parse::<std::net::Ipv6Addr>()
1353 && tor_ip == *ip
1354 {
1355 log::warn!("Tor exit node detected: {}", ip);
1356 return true;
1357 }
1358
1359 if line.contains('/')
1361 && let Ok(network) = line.parse::<ipnetwork::Ipv6Network>()
1362 && network.contains(*ip)
1363 {
1364 log::warn!("Tor exit network detected: {} in {}", ip, network);
1365 return true;
1366 }
1367 }
1368 }
1369
1370 if let Some(ipv4) = ip.to_ipv4() {
1372 let tor_v4_path = std::env::var("TOR_EXIT_NODES_IPV4_PATH")
1373 .unwrap_or_else(|_| "tor-exits-ipv4.txt".to_string());
1374
1375 if Path::new(&tor_v4_path).exists()
1376 && let Ok(contents) = std::fs::read_to_string(&tor_v4_path)
1377 {
1378 for line in contents.lines() {
1379 let line = line.trim();
1380 if line == ipv4.to_string() {
1381 log::warn!("Tor exit node detected (IPv4-mapped): {}", ip);
1382 return true;
1383 }
1384 }
1385 }
1386 }
1387
1388 false
1389 }
1390}
1391
1392impl Default for SessionConfig {
1393 fn default() -> Self {
1394 Self {
1395 default_duration: Duration::from_secs(3600), max_duration: Duration::from_secs(86400), idle_timeout: Duration::from_secs(1800), rotate_on_privilege_escalation: true,
1399 rotate_periodically: true,
1400 rotation_interval: Duration::from_secs(1800), max_concurrent_sessions: Some(5),
1402 track_device_fingerprints: true,
1403 enforce_geographic_restrictions: false,
1404 allowed_countries: vec![],
1405 security_policy: SessionSecurityPolicy::default(),
1406 }
1407 }
1408}
1409
1410impl Default for SessionSecurityPolicy {
1411 fn default() -> Self {
1412 Self {
1413 require_mfa_for_new_devices: true,
1414 require_reauth_for_sensitive_ops: true,
1415 reauth_timeout: Duration::from_secs(300), max_risk_score: 70,
1417 auto_suspend_suspicious: true,
1418 verify_location_changes: true,
1419 limit_concurrent_sessions: true,
1420 }
1421 }
1422}
1423
1424#[cfg(test)]
1425mod tests {
1426 use super::*;
1427
1428 #[test]
1429 fn test_device_fingerprint_generation() {
1430 let generator = DeviceFingerprintGenerator::new();
1431 let metadata = RequestMetadata {
1432 user_agent: Some("Mozilla/5.0".to_string()),
1433 ..Default::default()
1434 };
1435
1436 let fp1 = generator.generate_fingerprint(&metadata);
1437 let fp2 = generator.generate_fingerprint(&metadata);
1438
1439 assert_eq!(fp1, fp2);
1440 assert!(fp1.starts_with("fp_"));
1441 }
1442
1443 #[test]
1444 fn test_risk_calculation() {
1445 let calculator = RiskCalculator::new();
1446 let device_info = DeviceInfo {
1447 fingerprint: "test".to_string(),
1448 device_type: "desktop".to_string(),
1449 operating_system: None,
1450 browser: None,
1451 screen_resolution: None,
1452 timezone: None,
1453 language: None,
1454 is_trusted: false,
1455 device_name: None,
1456 };
1457
1458 let metadata = RequestMetadata::default();
1459 let history = vec![];
1460
1461 let risk = calculator.calculate_risk(&device_info, &metadata, &history, None);
1462 assert!(risk >= 20); }
1464}