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(Debug, 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 Session {
47 pub fn new(user_id: impl Into<String>, lifetime: Duration) -> Self {
63 let now = SystemTime::now();
64 Self {
65 id: uuid::Uuid::new_v4().to_string(),
66 user_id: user_id.into(),
67 created_at: now,
68 last_accessed: now,
69 expires_at: now + lifetime,
70 state: SessionState::Active,
71 device_info: DeviceInfo::unknown(),
72 security_metadata: SecurityMetadata::default(),
73 data: HashMap::new(),
74 mfa_verified: false,
75 cached_permissions: None,
76 last_activity: ActivityInfo {
77 endpoint: None,
78 action: None,
79 request_metadata: None,
80 timestamp: now,
81 },
82 }
83 }
84}
85
86#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
88pub enum SessionState {
89 Active,
90 Expired,
91 Revoked,
92 Suspended,
93 RequiresMfa,
94 RequiresReauth,
95 RequiresRotation,
97 HighRisk,
99}
100
101#[derive(Debug, Clone, Serialize, Deserialize)]
103pub struct DeviceInfo {
104 pub fingerprint: String,
106 pub device_type: String,
108 pub operating_system: Option<String>,
110 pub browser: Option<String>,
112 pub screen_resolution: Option<String>,
114 pub timezone: Option<String>,
116 pub language: Option<String>,
118 pub is_trusted: bool,
120 pub device_name: Option<String>,
122 pub is_mobile: bool,
124 pub ip_address: Option<String>,
126}
127
128impl DeviceInfo {
129 pub fn unknown() -> Self {
131 Self {
132 fingerprint: String::new(),
133 device_type: "unknown".into(),
134 operating_system: None,
135 browser: None,
136 screen_resolution: None,
137 timezone: None,
138 language: None,
139 is_trusted: false,
140 device_name: None,
141 is_mobile: false,
142 ip_address: None,
143 }
144 }
145}
146
147#[derive(Debug, Clone, Serialize, Deserialize, Default)]
149pub struct SecurityMetadata {
150 pub creation_ip: String,
152 pub current_ip: String,
154 pub creation_location: Option<GeolocationInfo>,
156 pub current_location: Option<GeolocationInfo>,
158 pub security_flags: Vec<SecurityFlag>,
160 pub risk_score: u8,
162 pub location_changed: bool,
164 pub ip_changed: bool,
166 pub failed_auth_attempts: u32,
168}
169
170#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
172pub enum SecurityFlag {
173 SuspiciousActivity,
174 LocationAnomaly,
175 DeviceAnomaly,
176 TimeAnomaly,
177 ConcurrentSessionLimit,
178 BruteForceAttempt,
179 RequiresVerification,
180 ElevatedPrivileges,
181}
182
183#[derive(Debug, Clone, Serialize, Deserialize)]
185pub struct ActivityInfo {
186 pub endpoint: Option<String>,
188 pub action: Option<String>,
190 pub request_metadata: Option<RequestMetadata>,
192 pub timestamp: SystemTime,
194}
195
196#[derive(Debug, Clone)]
198pub struct SessionConfig {
199 pub default_duration: Duration,
201 pub max_duration: Duration,
203 pub idle_timeout: Duration,
205 pub rotate_on_privilege_escalation: bool,
207 pub rotate_periodically: bool,
209 pub rotation_interval: Duration,
211 pub max_concurrent_sessions: Option<u32>,
213 pub track_device_fingerprints: bool,
215 pub enforce_geographic_restrictions: bool,
217 pub allowed_countries: Vec<String>,
219 pub security_policy: SessionSecurityPolicy,
221}
222
223impl SessionConfig {
225 pub fn builder() -> SessionConfigBuilder {
227 SessionConfigBuilder::default()
228 }
229}
230
231#[derive(Default)]
233pub struct SessionConfigBuilder {
234 config: SessionConfig,
235}
236
237impl SessionConfigBuilder {
238 pub fn default_duration(mut self, duration: std::time::Duration) -> Self {
248 self.config.default_duration = duration;
249 self
250 }
251
252 pub fn max_duration(mut self, duration: std::time::Duration) -> Self {
261 self.config.max_duration = duration;
262 self
263 }
264
265 pub fn idle_timeout(mut self, timeout: std::time::Duration) -> Self {
274 self.config.idle_timeout = timeout;
275 self
276 }
277
278 pub fn rotate_on_privilege_escalation(mut self, rotate: bool) -> Self {
287 self.config.rotate_on_privilege_escalation = rotate;
288 self
289 }
290
291 pub fn rotate_periodically(mut self, rotate: bool) -> Self {
301 self.config.rotate_periodically = rotate;
302 self
303 }
304
305 pub fn rotation_interval(mut self, interval: std::time::Duration) -> Self {
315 self.config.rotation_interval = interval;
316 self
317 }
318
319 pub fn max_concurrent_sessions(mut self, max: u32) -> Self {
328 self.config.max_concurrent_sessions = Some(max);
329 self
330 }
331
332 pub fn allowed_countries(mut self, countries: Vec<String>) -> Self {
337 self.config.allowed_countries = countries;
338 self
339 }
340
341 pub fn for_web_app() -> Self {
350 Self {
351 config: SessionConfig {
352 default_duration: Duration::from_secs(3600), max_duration: Duration::from_secs(86400), idle_timeout: Duration::from_secs(1800), rotate_on_privilege_escalation: true,
356 rotate_periodically: true,
357 rotation_interval: Duration::from_secs(1800), max_concurrent_sessions: Some(5),
359 track_device_fingerprints: true,
360 enforce_geographic_restrictions: false,
361 allowed_countries: vec![],
362 security_policy: SessionSecurityPolicy::default(),
363 },
364 }
365 }
366
367 pub fn for_api_service() -> Self {
378 Self {
379 config: SessionConfig {
380 default_duration: Duration::from_secs(900), max_duration: Duration::from_secs(3600), idle_timeout: Duration::from_secs(600), rotate_on_privilege_escalation: true,
384 rotate_periodically: false,
385 rotation_interval: Duration::from_secs(3600),
386 max_concurrent_sessions: None, track_device_fingerprints: false,
388 enforce_geographic_restrictions: false,
389 allowed_countries: vec![],
390 security_policy: SessionSecurityPolicy {
391 require_mfa_for_new_devices: false,
392 require_reauth_for_sensitive_ops: false,
393 reauth_timeout: Duration::from_secs(300),
394 max_risk_score: 90,
395 auto_suspend_suspicious: false,
396 verify_location_changes: false,
397 limit_concurrent_sessions: false,
398 },
399 },
400 }
401 }
402
403 pub fn for_high_security() -> Self {
413 Self {
414 config: SessionConfig {
415 default_duration: Duration::from_secs(1800), max_duration: Duration::from_secs(7200), idle_timeout: Duration::from_secs(300), rotate_on_privilege_escalation: true,
419 rotate_periodically: true,
420 rotation_interval: Duration::from_secs(900), max_concurrent_sessions: Some(1),
422 track_device_fingerprints: true,
423 enforce_geographic_restrictions: true,
424 allowed_countries: vec![], security_policy: SessionSecurityPolicy {
426 require_mfa_for_new_devices: true,
427 require_reauth_for_sensitive_ops: true,
428 reauth_timeout: Duration::from_secs(120), max_risk_score: 40,
430 auto_suspend_suspicious: true,
431 verify_location_changes: true,
432 limit_concurrent_sessions: true,
433 },
434 },
435 }
436 }
437
438 pub fn build(self) -> SessionConfig {
448 self.config
449 }
450}
451
452#[derive(Debug, Clone)]
453pub struct SessionSecurityPolicy {
454 pub require_mfa_for_new_devices: bool,
456 pub require_reauth_for_sensitive_ops: bool,
458 pub reauth_timeout: Duration,
460 pub max_risk_score: u8,
462 pub auto_suspend_suspicious: bool,
464 pub verify_location_changes: bool,
466 pub limit_concurrent_sessions: bool,
468}
469
470#[async_trait]
472pub trait SessionStorage: Send + Sync {
473 async fn create_session(&self, session: &Session) -> Result<()>;
475
476 async fn get_session(&self, session_id: &str) -> Result<Option<Session>>;
478
479 async fn update_session(&self, session: &Session) -> Result<()>;
481
482 async fn delete_session(&self, session_id: &str) -> Result<()>;
484
485 async fn get_user_sessions(&self, user_id: &str) -> Result<Vec<Session>>;
487
488 async fn count_active_sessions(&self, user_id: &str) -> Result<u32>;
490
491 async fn cleanup_expired_sessions(&self) -> Result<u32>;
493
494 async fn find_sessions_by_device(&self, device_fingerprint: &str) -> Result<Vec<Session>>;
496
497 async fn find_sessions_by_ip(&self, ip_address: &str) -> Result<Vec<Session>>;
499}
500
501pub struct SessionManager<S: SessionStorage, A: AuditStorage> {
503 storage: S,
504 config: SessionConfig,
505 audit_logger: AuditLogger<A>,
506 fingerprint_generator: DeviceFingerprintGenerator,
507 risk_calculator: RiskCalculator,
508 threat_intel_manager: Option<ThreatFeedManager>,
509}
510
511impl<S: SessionStorage, A: AuditStorage> SessionManager<S, A> {
512 pub fn new(storage: S, config: SessionConfig, audit_logger: AuditLogger<A>) -> Self {
517 let threat_intel_manager = if std::env::var("THREAT_INTEL_ENABLED")
519 .unwrap_or_else(|_| "false".to_string())
520 .to_lowercase()
521 == "true"
522 {
523 match ThreatIntelConfig::from_env_and_config() {
524 Ok(intel_config) => {
525 tracing::info!(
526 "🟢 Automated threat intelligence enabled - feeds will update automatically"
527 );
528 match ThreatFeedManager::new(intel_config) {
529 Ok(manager) => {
530 if let Err(e) = manager.start_automated_updates() {
532 tracing::error!(
533 "Failed to start automated threat feed updates: {}",
534 e
535 );
536 None
537 } else {
538 tracing::info!(
539 "✅ Threat intelligence automation started successfully"
540 );
541 Some(manager)
542 }
543 }
544 Err(e) => {
545 tracing::error!(
546 "Failed to initialize threat intelligence manager: {}",
547 e
548 );
549 None
550 }
551 }
552 }
553 Err(e) => {
554 tracing::error!("Failed to load threat intelligence configuration: {}", e);
555 None
556 }
557 }
558 } else {
559 tracing::info!(
560 "🔴 Automated threat intelligence disabled (THREAT_INTEL_ENABLED=false)"
561 );
562 None
563 };
564
565 Self {
566 storage,
567 config,
568 audit_logger,
569 fingerprint_generator: DeviceFingerprintGenerator::new(),
570 risk_calculator: RiskCalculator::new(),
571 threat_intel_manager,
572 }
573 }
574
575 pub async fn create_session(
577 &self,
578 user_id: &str,
579 mut device_info: DeviceInfo,
580 metadata: RequestMetadata,
581 ) -> Result<Session> {
582 if device_info.fingerprint.is_empty() {
584 device_info.fingerprint = self.fingerprint_generator.generate_fingerprint(&metadata);
585 }
586
587 if let Some(max_sessions) = self.config.max_concurrent_sessions {
589 let active_count = self.storage.count_active_sessions(user_id).await?;
590 if active_count >= max_sessions {
591 return Err(AuthError::TooManyConcurrentSessions);
592 }
593 }
594
595 let now = SystemTime::now();
596 let session_id = self.generate_session_id();
597
598 let risk_score = self.risk_calculator.calculate_risk(
600 &device_info,
601 &metadata,
602 &self.get_user_session_history(user_id).await?,
603 self.threat_intel_manager.as_ref(),
604 );
605
606 let mut security_flags = Vec::new();
607 if risk_score > 70 {
608 security_flags.push(SecurityFlag::SuspiciousActivity);
609 }
610
611 let existing_sessions = self
613 .storage
614 .find_sessions_by_device(&device_info.fingerprint)
615 .await?;
616 let is_new_device = existing_sessions.is_empty();
617
618 if is_new_device && self.config.security_policy.require_mfa_for_new_devices {
619 security_flags.push(SecurityFlag::RequiresVerification);
620 }
621
622 let session = Session {
623 id: session_id.clone(),
624 user_id: user_id.to_string(),
625 created_at: now,
626 last_accessed: now,
627 expires_at: now + self.config.default_duration,
628 state: if security_flags.contains(&SecurityFlag::RequiresVerification) {
629 SessionState::RequiresMfa
630 } else {
631 SessionState::Active
632 },
633 device_info: device_info.clone(),
634 security_metadata: SecurityMetadata {
635 creation_ip: metadata.ip_address.clone().unwrap_or_default(),
636 current_ip: metadata.ip_address.clone().unwrap_or_default(),
637 creation_location: metadata.geolocation.clone(),
638 current_location: metadata.geolocation.clone(),
639 security_flags,
640 risk_score,
641 location_changed: false,
642 ip_changed: false,
643 failed_auth_attempts: 0,
644 },
645 data: HashMap::new(),
646 mfa_verified: false,
647 cached_permissions: None,
648 last_activity: ActivityInfo {
649 endpoint: metadata.endpoint.clone(),
650 action: Some("session_created".to_string()),
651 request_metadata: Some(metadata.clone()),
652 timestamp: now,
653 },
654 };
655
656 self.storage.create_session(&session).await?;
657
658 self.audit_logger
660 .log_event({
661 let mut ev = crate::audit::AuditEvent::builder(
662 crate::audit::AuditEventType::LoginSuccess,
663 "Session created",
664 )
665 .user_id(user_id)
666 .outcome(crate::audit::EventOutcome::Success)
667 .risk_level(if risk_score > 70 {
668 crate::audit::RiskLevel::High
669 } else {
670 crate::audit::RiskLevel::Low
671 })
672 .request_metadata(metadata)
673 .with_actor("user", user_id)
674 .build();
675 ev.session_id = Some(session_id);
676 ev.timestamp = now;
677 ev
678 })
679 .await?;
680
681 Ok(session)
682 }
683
684 pub async fn validate_session(
686 &self,
687 session_id: &str,
688 metadata: RequestMetadata,
689 ) -> Result<Option<Session>> {
690 let mut session = match self.storage.get_session(session_id).await? {
691 Some(session) => session,
692 None => return Ok(None),
693 };
694
695 let now = SystemTime::now();
696
697 if let Ok(age) = now.duration_since(session.created_at)
699 && age > self.config.max_duration
700 {
701 session.state = SessionState::Expired;
702 self.storage.update_session(&session).await?;
703 return Ok(None);
704 }
705
706 if session.expires_at <= now {
708 session.state = SessionState::Expired;
709 self.storage.update_session(&session).await?;
710 return Ok(None);
711 }
712
713 let current_fingerprint = self.fingerprint_generator.generate_fingerprint(&metadata);
715 if current_fingerprint != session.device_info.fingerprint {
716 session.state = SessionState::RequiresMfa;
718 self.storage.update_session(&session).await?;
719
720 self.audit_logger
722 .log_suspicious_activity(
723 Some(&session.user_id),
724 "device_fingerprint_mismatch",
725 &format!(
726 "Session ID: {}, Expected: {}, Got: {}",
727 session_id, session.device_info.fingerprint, current_fingerprint
728 ),
729 metadata.clone(),
730 )
731 .await?;
732 }
733
734 let idle_duration = now
736 .duration_since(session.last_accessed)
737 .unwrap_or_default();
738 if idle_duration > self.config.idle_timeout {
739 session.state = SessionState::Expired;
740 self.storage.update_session(&session).await?;
741 return Ok(None);
742 }
743
744 match session.state {
746 SessionState::Expired | SessionState::Revoked | SessionState::Suspended => {
747 return Ok(None);
748 }
749 SessionState::RequiresMfa | SessionState::RequiresReauth => {
750 return Ok(Some(session));
752 }
753 SessionState::Active | SessionState::RequiresRotation | SessionState::HighRisk => {}
754 }
755
756 let current_ip = metadata.ip_address.clone().unwrap_or_default();
758 let ip_changed = current_ip != session.security_metadata.current_ip;
759
760 if ip_changed {
761 session.security_metadata.ip_changed = true;
762 session.security_metadata.current_ip = current_ip;
763
764 if self.config.security_policy.verify_location_changes {
766 session
767 .security_metadata
768 .security_flags
769 .push(SecurityFlag::LocationAnomaly);
770 session.state = SessionState::RequiresReauth;
771 }
772 }
773
774 session.last_accessed = now;
776 session.last_activity = ActivityInfo {
777 endpoint: metadata.endpoint.clone(),
778 action: Some("session_validated".to_string()),
779 request_metadata: Some(metadata),
780 timestamp: now,
781 };
782
783 let should_rotate = self.should_rotate_session(&session);
785 if should_rotate {
786 let new_session_id = self.generate_session_id();
787 let old_session_id = session.id.clone();
788 session.id = new_session_id;
789
790 self.storage.delete_session(&old_session_id).await?;
792 self.storage.create_session(&session).await?;
793 } else {
794 self.storage.update_session(&session).await?;
795 }
796
797 Ok(Some(session))
798 }
799
800 pub async fn revoke_session(&self, session_id: &str) -> Result<()> {
802 if let Some(mut session) = self.storage.get_session(session_id).await? {
803 session.state = SessionState::Revoked;
804 self.storage.update_session(&session).await?;
805
806 self.audit_logger
808 .log_event(
809 crate::audit::AuditEvent::builder(
810 crate::audit::AuditEventType::Logout,
811 "Session revoked",
812 )
813 .user_id(session.user_id)
814 .session_id(session_id)
815 .outcome(crate::audit::EventOutcome::Success)
816 .with_actor("system", "session_manager")
817 .build(),
818 )
819 .await?;
820 }
821 Ok(())
822 }
823
824 pub async fn revoke_all_user_sessions(&self, user_id: &str) -> Result<u32> {
826 let sessions = self.storage.get_user_sessions(user_id).await?;
827 let mut revoked_count = 0;
828
829 for mut session in sessions {
830 if session.state == SessionState::Active {
831 session.state = SessionState::Revoked;
832 self.storage.update_session(&session).await?;
833 revoked_count += 1;
834 }
835 }
836
837 Ok(revoked_count)
838 }
839
840 pub async fn get_user_sessions(
849 &self,
850 user_id: &str,
851 include_inactive: bool,
852 ) -> Result<Vec<Session>> {
853 let mut sessions = self.storage.get_user_sessions(user_id).await?;
854
855 if !include_inactive {
856 sessions.retain(|s| s.state == SessionState::Active);
857 }
858
859 Ok(sessions)
860 }
861
862 pub async fn list_user_sessions(
870 &self,
871 user_id: &str,
872 filter: crate::auth_operations::SessionFilter,
873 ) -> Result<Vec<Session>> {
874 self.get_user_sessions(user_id, filter.include_inactive())
875 .await
876 }
877
878 pub async fn cleanup_expired_sessions(&self) -> Result<u32> {
880 self.storage.cleanup_expired_sessions().await
881 }
882
883 pub fn generate_device_fingerprint(&self, metadata: &RequestMetadata) -> String {
885 self.fingerprint_generator.generate_fingerprint(metadata)
886 }
887
888 pub fn validate_device_fingerprint(
890 &self,
891 session: &Session,
892 metadata: &RequestMetadata,
893 ) -> bool {
894 let current_fingerprint = self.fingerprint_generator.generate_fingerprint(metadata);
895 current_fingerprint == session.device_info.fingerprint
896 }
897
898 pub async fn suspend_session(&self, session_id: &str, reason: &str) -> Result<()> {
900 if let Some(mut session) = self.storage.get_session(session_id).await? {
901 session.state = SessionState::Suspended;
902 session
903 .security_metadata
904 .security_flags
905 .push(SecurityFlag::SuspiciousActivity);
906
907 self.storage.update_session(&session).await?;
908
909 let mut details = HashMap::new();
911 details.insert("suspension_reason".to_string(), reason.to_string());
912
913 self.audit_logger
914 .log_event(
915 crate::audit::AuditEvent::builder(
916 crate::audit::AuditEventType::AccountLocked,
917 format!("Session suspended: {}", reason),
918 )
919 .user_id(session.user_id)
920 .session_id(session_id)
921 .outcome(crate::audit::EventOutcome::Success)
922 .risk_level(crate::audit::RiskLevel::High)
923 .details(details)
924 .with_actor("system", "security_monitor")
925 .build(),
926 )
927 .await?;
928 }
929 Ok(())
930 }
931
932 pub async fn update_session_data(
934 &self,
935 session_id: &str,
936 key: &str,
937 value: &str,
938 ) -> Result<()> {
939 if let Some(mut session) = self.storage.get_session(session_id).await? {
940 session.data.insert(key.to_string(), value.to_string());
941 session.last_accessed = SystemTime::now();
942 self.storage.update_session(&session).await?;
943 }
944 Ok(())
945 }
946
947 fn generate_session_id(&self) -> String {
949 format!("sess_{}", uuid::Uuid::new_v4())
950 }
951
952 fn should_rotate_session(&self, session: &Session) -> bool {
954 if !self.config.rotate_periodically {
955 return false;
956 }
957
958 let session_age = SystemTime::now()
959 .duration_since(session.created_at)
960 .unwrap_or_default();
961
962 session_age > self.config.rotation_interval
963 }
964
965 async fn get_user_session_history(&self, user_id: &str) -> Result<Vec<Session>> {
967 self.storage.get_user_sessions(user_id).await
970 }
971}
972
973pub struct DeviceFingerprintGenerator;
978
979impl Default for DeviceFingerprintGenerator {
980 fn default() -> Self {
981 Self::new()
982 }
983}
984
985impl DeviceFingerprintGenerator {
986 pub fn new() -> Self {
987 Self
988 }
989
990 pub fn generate_fingerprint(&self, metadata: &RequestMetadata) -> String {
992 let mut fingerprint_data = Vec::new();
993
994 if let Some(ua) = &metadata.user_agent {
995 fingerprint_data.push(ua.clone());
996 }
997
998 self.add_advanced_fingerprinting_data(&mut fingerprint_data, metadata);
1000
1001 let fingerprint_string = fingerprint_data.join("|");
1002 format!("fp_{:x}", crc32fast::hash(fingerprint_string.as_bytes()))
1003 }
1004
1005 fn add_advanced_fingerprinting_data(
1007 &self,
1008 fingerprint_data: &mut Vec<String>,
1009 metadata: &RequestMetadata,
1010 ) {
1011 if let Some(ref ip) = metadata.ip_address {
1013 fingerprint_data.push(format!("geo:{}", self.get_ip_geolocation(ip)));
1015 }
1016
1017 fingerprint_data.push(format!("lang:{}", self.get_system_language()));
1019 fingerprint_data.push(format!("tz:{}", self.get_timezone_offset()));
1020 fingerprint_data.push(format!("hw:{}", self.get_hardware_concurrency()));
1021
1022 fingerprint_data.push(format!("conn:{}", self.get_connection_info()));
1024
1025 fingerprint_data.push(format!("caps:{}", self.get_client_capabilities()));
1027 }
1028
1029 fn get_ip_geolocation(&self, ip: &str) -> String {
1031 use std::net::IpAddr;
1032 use std::str::FromStr;
1033
1034 if let Ok(ip_addr) = IpAddr::from_str(ip) {
1036 match ip_addr {
1037 IpAddr::V4(ipv4) => {
1038 let octets = ipv4.octets();
1039
1040 if (octets[0] == 10)
1042 || (octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31)
1043 || (octets[0] == 192 && octets[1] == 168)
1044 {
1045 return "private_rfc1918".to_string();
1046 }
1047
1048 if octets[0] == 127 {
1050 return "loopback".to_string();
1051 }
1052
1053 if octets[0] == 169 && octets[1] == 254 {
1055 return "link_local".to_string();
1056 }
1057
1058 if octets[0] >= 224 && octets[0] <= 239 {
1060 return "multicast".to_string();
1061 }
1062
1063 match (octets[0], octets[1], octets[2], octets[3]) {
1065 (8, 8, 8, 8) | (8, 8, 4, 4) => "google_dns".to_string(),
1066 (1, 1, 1, 1) | (1, 0, 0, 1) => "cloudflare_dns".to_string(),
1067 (208, 67, 222, 222) | (208, 67, 220, 220) => "opendns".to_string(),
1068 _ => {
1069 self.lookup_maxmind_geolocation(&ipv4).unwrap_or_else(|| {
1071 match octets[0] {
1073 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),
1080 }
1081 })
1082 }
1083 }
1084 }
1085 IpAddr::V6(ipv6) => {
1086 let segments = ipv6.segments();
1087
1088 if ipv6.is_loopback() {
1090 return "ipv6_loopback".to_string();
1091 }
1092
1093 if segments[0] & 0xffc0 == 0xfe80 {
1095 return "ipv6_link_local".to_string();
1096 }
1097
1098 if segments[0] & 0xfe00 == 0xfc00 {
1100 return "ipv6_unique_local".to_string();
1101 }
1102
1103 if segments[0] & 0xff00 == 0xff00 {
1105 return "ipv6_multicast".to_string();
1106 }
1107
1108 format!("ipv6_global_{:x}", segments[0] / 0x1000)
1110 }
1111 }
1112 } else {
1113 "invalid_ip".to_string()
1114 }
1115 }
1116
1117 fn get_system_language(&self) -> String {
1119 "en-US".to_string()
1121 }
1122
1123 fn get_timezone_offset(&self) -> String {
1125 "-05:00".to_string() }
1128
1129 fn get_hardware_concurrency(&self) -> String {
1131 "4".to_string()
1133 }
1134
1135 fn get_connection_info(&self) -> String {
1137 "wifi".to_string()
1139 }
1140
1141 fn get_client_capabilities(&self) -> String {
1143 "webgl2_canvas_audio".to_string()
1145 }
1146
1147 fn lookup_maxmind_geolocation(&self, ip: &std::net::Ipv4Addr) -> Option<String> {
1149 let db_path =
1151 std::env::var("MAXMIND_DB_PATH").unwrap_or_else(|_| "GeoLite2-City.mmdb".to_string());
1152 self.lookup_maxmind_geolocation_at(&db_path, ip)
1153 }
1154
1155 fn lookup_maxmind_geolocation_at(
1157 &self,
1158 db_path: &str,
1159 ip: &std::net::Ipv4Addr,
1160 ) -> Option<String> {
1161 use std::path::Path;
1162
1163 if !Path::new(&db_path).exists() {
1164 tracing::warn!(
1165 "MaxMind database not found at {}, falling back to basic geolocation",
1166 db_path
1167 );
1168 return None;
1169 }
1170
1171 match maxminddb::Reader::open_readfile(db_path) {
1172 Ok(reader) => {
1173 match reader.lookup((*ip).into()) {
1174 Ok(result) => match result.decode::<maxminddb::geoip2::City>() {
1175 Ok(Some(city)) => {
1176 let mut location_parts = Vec::new();
1177
1178 let location = &city.location;
1180 if let (Some(lat), Some(lon)) = (location.latitude, location.longitude)
1181 {
1182 location_parts.push(format!("coords:{:.4},{:.4}", lat, lon));
1183 }
1184
1185 if location_parts.is_empty() {
1188 None
1189 } else {
1190 Some(location_parts.join("|"))
1191 }
1192 }
1193 Ok(None) => {
1194 tracing::debug!("MaxMind lookup returned no data for {}", ip);
1195 None
1196 }
1197 Err(e) => {
1198 tracing::debug!("MaxMind decode failed for {}: {}", ip, e);
1199 None
1200 }
1201 },
1202 Err(e) => {
1203 tracing::debug!("MaxMind lookup failed for {}: {}", ip, e);
1204 None
1205 }
1206 }
1207 }
1208 Err(e) => {
1209 tracing::warn!("Failed to open MaxMind database: {}", e);
1210 None
1211 }
1212 }
1213 }
1214}
1215
1216pub struct RiskCalculator;
1222
1223impl Default for RiskCalculator {
1224 fn default() -> Self {
1225 Self::new()
1226 }
1227}
1228
1229impl RiskCalculator {
1230 pub fn new() -> Self {
1231 Self
1232 }
1233
1234 pub fn calculate_risk(
1236 &self,
1237 device_info: &DeviceInfo,
1238 metadata: &RequestMetadata,
1239 _session_history: &[Session],
1240 threat_intel_manager: Option<&ThreatFeedManager>,
1241 ) -> u8 {
1242 let mut risk_score = 0u8;
1243
1244 if !device_info.is_trusted {
1246 risk_score += 20;
1247 }
1248
1249 if let Some(ip) = &metadata.ip_address
1251 && self.is_suspicious_ip(ip, threat_intel_manager)
1252 {
1253 risk_score += 30;
1254 }
1255
1256 if let Some(location) = &metadata.geolocation {
1258 let mut geo_risk = 0;
1259
1260 if let Some(country) = &location.country {
1262 let country_lower = country.to_lowercase();
1263
1264 let high_risk_countries =
1266 ["tor", "anonymous", "vpn", "proxy", "hosting", "datacenter"];
1267
1268 for indicator in &high_risk_countries {
1269 if country_lower.contains(indicator) {
1270 geo_risk += 30;
1271 break;
1272 }
1273 }
1274
1275 geo_risk += self.assess_country_threat_level(&country_lower) as u8;
1277
1278 let elevated_risk_patterns = ["cloud", "aws", "azure", "gcp"];
1280 for pattern in &elevated_risk_patterns {
1281 if country_lower.contains(pattern) {
1282 geo_risk += 20;
1283 break;
1284 }
1285 }
1286 }
1287
1288 if let (Some(lat), Some(lon)) = (location.latitude, location.longitude) {
1290 if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {
1292 geo_risk += 25; }
1294
1295 if (lat * 100.0).fract().abs() < 0.01 && (lon * 100.0).fract().abs() < 0.01 {
1297 geo_risk += 15; }
1299 }
1300
1301 if let Some(region) = &location.region {
1303 let region_lower = region.to_lowercase();
1304 if region_lower.contains("hosting") || region_lower.contains("datacenter") {
1305 geo_risk += 20;
1306 }
1307 }
1308
1309 if let Some(city) = &location.city {
1311 let city_lower = city.to_lowercase();
1312 if city_lower.contains("server") || city_lower.contains("datacenter") {
1313 geo_risk += 15;
1314 }
1315 }
1316
1317 risk_score += geo_risk;
1318 }
1319
1320 risk_score.min(100)
1326 }
1327
1328 fn is_suspicious_ip(&self, ip: &str, threat_intel_manager: Option<&ThreatFeedManager>) -> bool {
1330 use std::net::IpAddr;
1331 use std::str::FromStr;
1332
1333 if let Ok(ip_addr) = IpAddr::from_str(ip) {
1335 match ip_addr {
1336 IpAddr::V4(ipv4) => {
1337 let octets = ipv4.octets();
1338
1339 if self.check_malicious_ip_feeds(&ipv4, threat_intel_manager) {
1341 return true;
1342 }
1343
1344 let suspicious_ranges = [
1346 (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), ];
1354
1355 for (net, _, _, _, _) in &suspicious_ranges {
1356 if octets[0] == *net {
1357 return true;
1358 }
1359 }
1360
1361 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)
1367 {
1368 return true;
1370 }
1371
1372 if octets[3] == 0 || octets[3] == 255 {
1374 return true;
1375 }
1376
1377 if self.check_proxy_vpn_databases(&ipv4) {
1379 return true;
1380 }
1381
1382 let proxy_ports_in_ip = [
1384 80, 443, 8080, 3128, 1080, 8000, 8888, 9050, ];
1386
1387 for &port in &proxy_ports_in_ip {
1388 if octets[2] == (port / 256) as u8 && octets[3] == (port % 256) as u8 {
1389 return true;
1390 }
1391 }
1392
1393 false
1394 }
1395 IpAddr::V6(ipv6) => {
1396 let segments = ipv6.segments();
1397
1398 if self.check_tor_exit_nodes(&ipv6) {
1400 return true;
1401 }
1402
1403 if segments[0] == 0x2001 && segments[1] == 0x67c {
1405 return true;
1407 }
1408
1409 let mut sequential_count = 0;
1411 for i in 1..segments.len() {
1412 if segments[i] == segments[i - 1] + 1 {
1413 sequential_count += 1;
1414 }
1415 }
1416 if sequential_count >= 4 {
1417 return true;
1419 }
1420
1421 if segments[0] == 0x2001 && segments[1] == 0x470 {
1423 return true;
1425 }
1426
1427 false
1428 }
1429 }
1430 } else {
1431 true }
1433 }
1434
1435 fn assess_country_threat_level(&self, country: &str) -> u32 {
1437 use std::path::Path;
1438
1439 let threat_db_path = std::env::var("COUNTRY_THREAT_DB_PATH")
1441 .unwrap_or_else(|_| "country-threats.csv".to_string());
1442
1443 if Path::new(&threat_db_path).exists() {
1444 if let Ok(contents) = std::fs::read_to_string(&threat_db_path) {
1446 let mut csv_reader = csv::Reader::from_reader(contents.as_bytes());
1447
1448 for result in csv_reader.records() {
1449 if let Ok(record) = result
1450 && record.len() >= 2
1451 {
1452 let threat_country = record[0].to_lowercase();
1453 if let Ok(risk_score) = record[1].parse::<u32>()
1454 && country.contains(&threat_country)
1455 {
1456 tracing::debug!(
1457 "Country threat match: {} -> risk {}",
1458 country,
1459 risk_score
1460 );
1461 return risk_score;
1462 }
1463 }
1464 }
1465 }
1466 }
1467
1468 0 }
1471
1472 fn check_malicious_ip_feeds(
1474 &self,
1475 ip: &std::net::Ipv4Addr,
1476 threat_intel_manager: Option<&ThreatFeedManager>,
1477 ) -> bool {
1478 if let Some(threat_manager) = threat_intel_manager {
1480 return threat_manager.is_malicious_ip(&std::net::IpAddr::V4(*ip));
1481 }
1482
1483 use std::path::Path;
1485
1486 let feed_paths = [
1488 std::env::var("MALICIOUS_IPS_DB_PATH")
1489 .unwrap_or_else(|_| "malicious-ips.txt".to_string()),
1490 std::env::var("BOTNET_IPS_DB_PATH").unwrap_or_else(|_| "botnet-ips.txt".to_string()),
1491 std::env::var("TOR_EXIT_NODES_DB_PATH").unwrap_or_else(|_| "tor-exits.txt".to_string()),
1492 ];
1493
1494 for feed_path in &feed_paths {
1495 if Path::new(feed_path).exists()
1496 && let Ok(contents) = std::fs::read_to_string(feed_path)
1497 {
1498 for line in contents.lines() {
1499 let line = line.trim();
1500 if line.is_empty() || line.starts_with('#') {
1501 continue;
1502 }
1503
1504 if line == ip.to_string() {
1506 tracing::warn!("Malicious IP detected: {} (source: {})", ip, feed_path);
1507 return true;
1508 }
1509
1510 if line.contains('/')
1512 && let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
1513 && network.contains(*ip)
1514 {
1515 tracing::warn!(
1516 "Malicious network detected: {} in {} (source: {})",
1517 ip,
1518 network,
1519 feed_path
1520 );
1521 return true;
1522 }
1523 }
1524 }
1525 }
1526
1527 false
1528 }
1529
1530 fn check_proxy_vpn_databases(&self, ip: &std::net::Ipv4Addr) -> bool {
1532 use std::path::Path;
1533
1534 let db_sources = [
1536 ("VPN_DATABASE_PATH", "vpn-ranges.txt"),
1537 ("PROXY_DATABASE_PATH", "proxy-ips.txt"),
1538 ("DATACENTER_DATABASE_PATH", "datacenter-ranges.txt"),
1539 ("HOSTING_DATABASE_PATH", "hosting-providers.txt"),
1540 ];
1541
1542 for (env_var, default_file) in &db_sources {
1543 let db_path = std::env::var(env_var).unwrap_or_else(|_| default_file.to_string());
1544
1545 if Path::new(&db_path).exists()
1546 && let Ok(contents) = std::fs::read_to_string(&db_path)
1547 {
1548 for line in contents.lines() {
1549 let line = line.trim();
1550 if line.is_empty() || line.starts_with('#') {
1551 continue;
1552 }
1553
1554 if line.contains('/') {
1556 if let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
1558 && network.contains(*ip)
1559 {
1560 tracing::info!(
1561 "Proxy/VPN detected: {} in {} (source: {})",
1562 ip,
1563 network,
1564 db_path
1565 );
1566 return true;
1567 }
1568 } else if line.contains('-') {
1569 let parts: Vec<&str> = line.split('-').collect();
1571 if parts.len() == 2
1572 && let (Ok(start_ip), Ok(end_ip)) = (
1573 parts[0].trim().parse::<std::net::Ipv4Addr>(),
1574 parts[1].trim().parse::<std::net::Ipv4Addr>(),
1575 )
1576 {
1577 let ip_u32 = u32::from(*ip);
1578 let start_u32 = u32::from(start_ip);
1579 let end_u32 = u32::from(end_ip);
1580
1581 if ip_u32 >= start_u32 && ip_u32 <= end_u32 {
1582 tracing::info!(
1583 "Proxy/VPN range detected: {} in {}-{} (source: {})",
1584 ip,
1585 start_ip,
1586 end_ip,
1587 db_path
1588 );
1589 return true;
1590 }
1591 }
1592 } else if line == ip.to_string() {
1593 tracing::info!("Proxy/VPN exact match: {} (source: {})", ip, db_path);
1595 return true;
1596 }
1597 }
1598 }
1599 }
1600
1601 false
1602 }
1603
1604 fn check_tor_exit_nodes(&self, ip: &std::net::Ipv6Addr) -> bool {
1606 use std::path::Path;
1607
1608 let tor_db_path = std::env::var("TOR_EXIT_NODES_IPV6_PATH")
1610 .unwrap_or_else(|_| "tor-exits-ipv6.txt".to_string());
1611
1612 if Path::new(&tor_db_path).exists()
1613 && let Ok(contents) = std::fs::read_to_string(&tor_db_path)
1614 {
1615 for line in contents.lines() {
1616 let line = line.trim();
1617 if line.is_empty() || line.starts_with('#') {
1618 continue;
1619 }
1620
1621 if let Ok(tor_ip) = line.parse::<std::net::Ipv6Addr>()
1623 && tor_ip == *ip
1624 {
1625 tracing::warn!("Tor exit node detected: {}", ip);
1626 return true;
1627 }
1628
1629 if line.contains('/')
1631 && let Ok(network) = line.parse::<ipnetwork::Ipv6Network>()
1632 && network.contains(*ip)
1633 {
1634 tracing::warn!("Tor exit network detected: {} in {}", ip, network);
1635 return true;
1636 }
1637 }
1638 }
1639
1640 if let Some(ipv4) = ip.to_ipv4() {
1642 let tor_v4_path = std::env::var("TOR_EXIT_NODES_IPV4_PATH")
1643 .unwrap_or_else(|_| "tor-exits-ipv4.txt".to_string());
1644
1645 if Path::new(&tor_v4_path).exists()
1646 && let Ok(contents) = std::fs::read_to_string(&tor_v4_path)
1647 {
1648 for line in contents.lines() {
1649 let line = line.trim();
1650 if line == ipv4.to_string() {
1651 tracing::warn!("Tor exit node detected (IPv4-mapped): {}", ip);
1652 return true;
1653 }
1654 }
1655 }
1656 }
1657
1658 false
1659 }
1660}
1661
1662impl Default for SessionConfig {
1663 fn default() -> Self {
1664 Self {
1665 default_duration: Duration::from_secs(3600), max_duration: Duration::from_secs(86400), idle_timeout: Duration::from_secs(1800), rotate_on_privilege_escalation: true,
1669 rotate_periodically: true,
1670 rotation_interval: Duration::from_secs(1800), max_concurrent_sessions: Some(5),
1672 track_device_fingerprints: true,
1673 enforce_geographic_restrictions: false,
1674 allowed_countries: vec![],
1675 security_policy: SessionSecurityPolicy::default(),
1676 }
1677 }
1678}
1679
1680impl Default for SessionSecurityPolicy {
1681 fn default() -> Self {
1682 Self {
1683 require_mfa_for_new_devices: true,
1684 require_reauth_for_sensitive_ops: true,
1685 reauth_timeout: Duration::from_secs(300), max_risk_score: 70,
1687 auto_suspend_suspicious: true,
1688 verify_location_changes: true,
1689 limit_concurrent_sessions: true,
1690 }
1691 }
1692}
1693
1694#[cfg(test)]
1695mod tests {
1696 use super::*;
1697
1698 #[test]
1699 fn test_device_fingerprint_generation() {
1700 let generator = DeviceFingerprintGenerator::new();
1701 let metadata = RequestMetadata {
1702 user_agent: Some("Mozilla/5.0".to_string()),
1703 ..Default::default()
1704 };
1705
1706 let fp1 = generator.generate_fingerprint(&metadata);
1707 let fp2 = generator.generate_fingerprint(&metadata);
1708
1709 assert_eq!(fp1, fp2);
1710 assert!(fp1.starts_with("fp_"));
1711 }
1712
1713 #[test]
1714 fn test_risk_calculation() {
1715 let calculator = RiskCalculator::new();
1716 let device_info = DeviceInfo {
1717 fingerprint: "test".to_string(),
1718 device_type: "desktop".to_string(),
1719 operating_system: None,
1720 browser: None,
1721 screen_resolution: None,
1722 timezone: None,
1723 language: None,
1724 is_trusted: false,
1725 device_name: None,
1726 is_mobile: false,
1727 ip_address: None,
1728 };
1729
1730 let metadata = RequestMetadata::default();
1731 let history = vec![];
1732
1733 let risk = calculator.calculate_risk(&device_info, &metadata, &history, None);
1734 assert!(risk >= 20); }
1736
1737 #[test]
1738 fn test_session_config_builder_for_web_app() {
1739 let config = SessionConfigBuilder::for_web_app().build();
1740 assert_eq!(config.default_duration, Duration::from_secs(3600));
1741 assert_eq!(config.max_duration, Duration::from_secs(86400));
1742 assert_eq!(config.max_concurrent_sessions, Some(5));
1743 assert!(config.track_device_fingerprints);
1744 }
1745
1746 #[test]
1747 fn test_session_config_builder_for_api_service() {
1748 let config = SessionConfigBuilder::for_api_service().build();
1749 assert_eq!(config.default_duration, Duration::from_secs(900));
1750 assert!(config.max_concurrent_sessions.is_none());
1751 assert!(!config.track_device_fingerprints);
1752 assert!(!config.rotate_periodically);
1753 }
1754
1755 #[test]
1756 fn test_session_config_builder_for_high_security() {
1757 let config = SessionConfigBuilder::for_high_security()
1758 .allowed_countries(vec!["US".into()])
1759 .build();
1760 assert_eq!(config.default_duration, Duration::from_secs(1800));
1761 assert_eq!(config.max_concurrent_sessions, Some(1));
1762 assert!(config.enforce_geographic_restrictions);
1763 assert_eq!(config.allowed_countries, vec!["US".to_string()]);
1764 assert!(config.security_policy.require_mfa_for_new_devices);
1765 }
1766
1767 #[test]
1771 fn maxmind_geolocation_none_for_missing_or_garbage_database() {
1772 let generator = DeviceFingerprintGenerator::new();
1773 let ip = std::net::Ipv4Addr::new(8, 8, 8, 8);
1774 let dir = tempfile::tempdir().unwrap();
1775
1776 let missing = dir.path().join("missing.mmdb");
1777 assert_eq!(
1778 generator.lookup_maxmind_geolocation_at(missing.to_str().unwrap(), &ip),
1779 None
1780 );
1781
1782 let garbage_inputs: [(&str, &[u8]); 3] = [
1783 ("empty.mmdb", b""),
1784 ("garbage.mmdb", b"this is not a MaxMind database at all"),
1785 ("truncated.mmdb", b"\xAB\xCD\xEFMaxMind.com\x00"),
1786 ];
1787 for (name, bytes) in garbage_inputs {
1788 let path = dir.path().join(name);
1789 std::fs::write(&path, bytes).unwrap();
1790 assert!(
1792 maxminddb::Reader::open_readfile(&path).is_err(),
1793 "{name}: maxminddb accepted garbage bytes"
1794 );
1795 assert_eq!(
1796 generator.lookup_maxmind_geolocation_at(path.to_str().unwrap(), &ip),
1797 None,
1798 "{name}"
1799 );
1800 }
1801 }
1802}