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 use std::path::Path;
1150
1151 let db_path =
1153 std::env::var("MAXMIND_DB_PATH").unwrap_or_else(|_| "GeoLite2-City.mmdb".to_string());
1154
1155 if !Path::new(&db_path).exists() {
1156 tracing::warn!(
1157 "MaxMind database not found at {}, falling back to basic geolocation",
1158 db_path
1159 );
1160 return None;
1161 }
1162
1163 match maxminddb::Reader::open_readfile(&db_path) {
1164 Ok(reader) => {
1165 match reader.lookup((*ip).into()) {
1166 Ok(result) => match result.decode::<maxminddb::geoip2::City>() {
1167 Ok(Some(city)) => {
1168 let mut location_parts = Vec::new();
1169
1170 let location = &city.location;
1172 if let (Some(lat), Some(lon)) = (location.latitude, location.longitude)
1173 {
1174 location_parts.push(format!("coords:{:.4},{:.4}", lat, lon));
1175 }
1176
1177 if location_parts.is_empty() {
1180 None
1181 } else {
1182 Some(location_parts.join("|"))
1183 }
1184 }
1185 Ok(None) => {
1186 tracing::debug!("MaxMind lookup returned no data for {}", ip);
1187 None
1188 }
1189 Err(e) => {
1190 tracing::debug!("MaxMind decode failed for {}: {}", ip, e);
1191 None
1192 }
1193 },
1194 Err(e) => {
1195 tracing::debug!("MaxMind lookup failed for {}: {}", ip, e);
1196 None
1197 }
1198 }
1199 }
1200 Err(e) => {
1201 tracing::warn!("Failed to open MaxMind database: {}", e);
1202 None
1203 }
1204 }
1205 }
1206}
1207
1208pub struct RiskCalculator;
1214
1215impl Default for RiskCalculator {
1216 fn default() -> Self {
1217 Self::new()
1218 }
1219}
1220
1221impl RiskCalculator {
1222 pub fn new() -> Self {
1223 Self
1224 }
1225
1226 pub fn calculate_risk(
1228 &self,
1229 device_info: &DeviceInfo,
1230 metadata: &RequestMetadata,
1231 _session_history: &[Session],
1232 threat_intel_manager: Option<&ThreatFeedManager>,
1233 ) -> u8 {
1234 let mut risk_score = 0u8;
1235
1236 if !device_info.is_trusted {
1238 risk_score += 20;
1239 }
1240
1241 if let Some(ip) = &metadata.ip_address
1243 && self.is_suspicious_ip(ip, threat_intel_manager)
1244 {
1245 risk_score += 30;
1246 }
1247
1248 if let Some(location) = &metadata.geolocation {
1250 let mut geo_risk = 0;
1251
1252 if let Some(country) = &location.country {
1254 let country_lower = country.to_lowercase();
1255
1256 let high_risk_countries =
1258 ["tor", "anonymous", "vpn", "proxy", "hosting", "datacenter"];
1259
1260 for indicator in &high_risk_countries {
1261 if country_lower.contains(indicator) {
1262 geo_risk += 30;
1263 break;
1264 }
1265 }
1266
1267 geo_risk += self.assess_country_threat_level(&country_lower) as u8;
1269
1270 let elevated_risk_patterns = ["cloud", "aws", "azure", "gcp"];
1272 for pattern in &elevated_risk_patterns {
1273 if country_lower.contains(pattern) {
1274 geo_risk += 20;
1275 break;
1276 }
1277 }
1278 }
1279
1280 if let (Some(lat), Some(lon)) = (location.latitude, location.longitude) {
1282 if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {
1284 geo_risk += 25; }
1286
1287 if (lat * 100.0).fract().abs() < 0.01 && (lon * 100.0).fract().abs() < 0.01 {
1289 geo_risk += 15; }
1291 }
1292
1293 if let Some(region) = &location.region {
1295 let region_lower = region.to_lowercase();
1296 if region_lower.contains("hosting") || region_lower.contains("datacenter") {
1297 geo_risk += 20;
1298 }
1299 }
1300
1301 if let Some(city) = &location.city {
1303 let city_lower = city.to_lowercase();
1304 if city_lower.contains("server") || city_lower.contains("datacenter") {
1305 geo_risk += 15;
1306 }
1307 }
1308
1309 risk_score += geo_risk;
1310 }
1311
1312 risk_score.min(100)
1318 }
1319
1320 fn is_suspicious_ip(&self, ip: &str, threat_intel_manager: Option<&ThreatFeedManager>) -> bool {
1322 use std::net::IpAddr;
1323 use std::str::FromStr;
1324
1325 if let Ok(ip_addr) = IpAddr::from_str(ip) {
1327 match ip_addr {
1328 IpAddr::V4(ipv4) => {
1329 let octets = ipv4.octets();
1330
1331 if self.check_malicious_ip_feeds(&ipv4, threat_intel_manager) {
1333 return true;
1334 }
1335
1336 let suspicious_ranges = [
1338 (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), ];
1346
1347 for (net, _, _, _, _) in &suspicious_ranges {
1348 if octets[0] == *net {
1349 return true;
1350 }
1351 }
1352
1353 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)
1359 {
1360 return true;
1362 }
1363
1364 if octets[3] == 0 || octets[3] == 255 {
1366 return true;
1367 }
1368
1369 if self.check_proxy_vpn_databases(&ipv4) {
1371 return true;
1372 }
1373
1374 let proxy_ports_in_ip = [
1376 80, 443, 8080, 3128, 1080, 8000, 8888, 9050, ];
1378
1379 for &port in &proxy_ports_in_ip {
1380 if octets[2] == (port / 256) as u8 && octets[3] == (port % 256) as u8 {
1381 return true;
1382 }
1383 }
1384
1385 false
1386 }
1387 IpAddr::V6(ipv6) => {
1388 let segments = ipv6.segments();
1389
1390 if self.check_tor_exit_nodes(&ipv6) {
1392 return true;
1393 }
1394
1395 if segments[0] == 0x2001 && segments[1] == 0x67c {
1397 return true;
1399 }
1400
1401 let mut sequential_count = 0;
1403 for i in 1..segments.len() {
1404 if segments[i] == segments[i - 1] + 1 {
1405 sequential_count += 1;
1406 }
1407 }
1408 if sequential_count >= 4 {
1409 return true;
1411 }
1412
1413 if segments[0] == 0x2001 && segments[1] == 0x470 {
1415 return true;
1417 }
1418
1419 false
1420 }
1421 }
1422 } else {
1423 true }
1425 }
1426
1427 fn assess_country_threat_level(&self, country: &str) -> u32 {
1429 use std::path::Path;
1430
1431 let threat_db_path = std::env::var("COUNTRY_THREAT_DB_PATH")
1433 .unwrap_or_else(|_| "country-threats.csv".to_string());
1434
1435 if Path::new(&threat_db_path).exists() {
1436 if let Ok(contents) = std::fs::read_to_string(&threat_db_path) {
1438 let mut csv_reader = csv::Reader::from_reader(contents.as_bytes());
1439
1440 for result in csv_reader.records() {
1441 if let Ok(record) = result
1442 && record.len() >= 2
1443 {
1444 let threat_country = record[0].to_lowercase();
1445 if let Ok(risk_score) = record[1].parse::<u32>()
1446 && country.contains(&threat_country)
1447 {
1448 tracing::debug!(
1449 "Country threat match: {} -> risk {}",
1450 country,
1451 risk_score
1452 );
1453 return risk_score;
1454 }
1455 }
1456 }
1457 }
1458 }
1459
1460 0 }
1463
1464 fn check_malicious_ip_feeds(
1466 &self,
1467 ip: &std::net::Ipv4Addr,
1468 threat_intel_manager: Option<&ThreatFeedManager>,
1469 ) -> bool {
1470 if let Some(threat_manager) = threat_intel_manager {
1472 return threat_manager.is_malicious_ip(&std::net::IpAddr::V4(*ip));
1473 }
1474
1475 use std::path::Path;
1477
1478 let feed_paths = [
1480 std::env::var("MALICIOUS_IPS_DB_PATH")
1481 .unwrap_or_else(|_| "malicious-ips.txt".to_string()),
1482 std::env::var("BOTNET_IPS_DB_PATH").unwrap_or_else(|_| "botnet-ips.txt".to_string()),
1483 std::env::var("TOR_EXIT_NODES_DB_PATH").unwrap_or_else(|_| "tor-exits.txt".to_string()),
1484 ];
1485
1486 for feed_path in &feed_paths {
1487 if Path::new(feed_path).exists()
1488 && let Ok(contents) = std::fs::read_to_string(feed_path)
1489 {
1490 for line in contents.lines() {
1491 let line = line.trim();
1492 if line.is_empty() || line.starts_with('#') {
1493 continue;
1494 }
1495
1496 if line == ip.to_string() {
1498 tracing::warn!("Malicious IP detected: {} (source: {})", ip, feed_path);
1499 return true;
1500 }
1501
1502 if line.contains('/')
1504 && let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
1505 && network.contains(*ip)
1506 {
1507 tracing::warn!(
1508 "Malicious network detected: {} in {} (source: {})",
1509 ip,
1510 network,
1511 feed_path
1512 );
1513 return true;
1514 }
1515 }
1516 }
1517 }
1518
1519 false
1520 }
1521
1522 fn check_proxy_vpn_databases(&self, ip: &std::net::Ipv4Addr) -> bool {
1524 use std::path::Path;
1525
1526 let db_sources = [
1528 ("VPN_DATABASE_PATH", "vpn-ranges.txt"),
1529 ("PROXY_DATABASE_PATH", "proxy-ips.txt"),
1530 ("DATACENTER_DATABASE_PATH", "datacenter-ranges.txt"),
1531 ("HOSTING_DATABASE_PATH", "hosting-providers.txt"),
1532 ];
1533
1534 for (env_var, default_file) in &db_sources {
1535 let db_path = std::env::var(env_var).unwrap_or_else(|_| default_file.to_string());
1536
1537 if Path::new(&db_path).exists()
1538 && let Ok(contents) = std::fs::read_to_string(&db_path)
1539 {
1540 for line in contents.lines() {
1541 let line = line.trim();
1542 if line.is_empty() || line.starts_with('#') {
1543 continue;
1544 }
1545
1546 if line.contains('/') {
1548 if let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
1550 && network.contains(*ip)
1551 {
1552 tracing::info!(
1553 "Proxy/VPN detected: {} in {} (source: {})",
1554 ip,
1555 network,
1556 db_path
1557 );
1558 return true;
1559 }
1560 } else if line.contains('-') {
1561 let parts: Vec<&str> = line.split('-').collect();
1563 if parts.len() == 2
1564 && let (Ok(start_ip), Ok(end_ip)) = (
1565 parts[0].trim().parse::<std::net::Ipv4Addr>(),
1566 parts[1].trim().parse::<std::net::Ipv4Addr>(),
1567 )
1568 {
1569 let ip_u32 = u32::from(*ip);
1570 let start_u32 = u32::from(start_ip);
1571 let end_u32 = u32::from(end_ip);
1572
1573 if ip_u32 >= start_u32 && ip_u32 <= end_u32 {
1574 tracing::info!(
1575 "Proxy/VPN range detected: {} in {}-{} (source: {})",
1576 ip,
1577 start_ip,
1578 end_ip,
1579 db_path
1580 );
1581 return true;
1582 }
1583 }
1584 } else if line == ip.to_string() {
1585 tracing::info!("Proxy/VPN exact match: {} (source: {})", ip, db_path);
1587 return true;
1588 }
1589 }
1590 }
1591 }
1592
1593 false
1594 }
1595
1596 fn check_tor_exit_nodes(&self, ip: &std::net::Ipv6Addr) -> bool {
1598 use std::path::Path;
1599
1600 let tor_db_path = std::env::var("TOR_EXIT_NODES_IPV6_PATH")
1602 .unwrap_or_else(|_| "tor-exits-ipv6.txt".to_string());
1603
1604 if Path::new(&tor_db_path).exists()
1605 && let Ok(contents) = std::fs::read_to_string(&tor_db_path)
1606 {
1607 for line in contents.lines() {
1608 let line = line.trim();
1609 if line.is_empty() || line.starts_with('#') {
1610 continue;
1611 }
1612
1613 if let Ok(tor_ip) = line.parse::<std::net::Ipv6Addr>()
1615 && tor_ip == *ip
1616 {
1617 tracing::warn!("Tor exit node detected: {}", ip);
1618 return true;
1619 }
1620
1621 if line.contains('/')
1623 && let Ok(network) = line.parse::<ipnetwork::Ipv6Network>()
1624 && network.contains(*ip)
1625 {
1626 tracing::warn!("Tor exit network detected: {} in {}", ip, network);
1627 return true;
1628 }
1629 }
1630 }
1631
1632 if let Some(ipv4) = ip.to_ipv4() {
1634 let tor_v4_path = std::env::var("TOR_EXIT_NODES_IPV4_PATH")
1635 .unwrap_or_else(|_| "tor-exits-ipv4.txt".to_string());
1636
1637 if Path::new(&tor_v4_path).exists()
1638 && let Ok(contents) = std::fs::read_to_string(&tor_v4_path)
1639 {
1640 for line in contents.lines() {
1641 let line = line.trim();
1642 if line == ipv4.to_string() {
1643 tracing::warn!("Tor exit node detected (IPv4-mapped): {}", ip);
1644 return true;
1645 }
1646 }
1647 }
1648 }
1649
1650 false
1651 }
1652}
1653
1654impl Default for SessionConfig {
1655 fn default() -> Self {
1656 Self {
1657 default_duration: Duration::from_secs(3600), max_duration: Duration::from_secs(86400), idle_timeout: Duration::from_secs(1800), rotate_on_privilege_escalation: true,
1661 rotate_periodically: true,
1662 rotation_interval: Duration::from_secs(1800), max_concurrent_sessions: Some(5),
1664 track_device_fingerprints: true,
1665 enforce_geographic_restrictions: false,
1666 allowed_countries: vec![],
1667 security_policy: SessionSecurityPolicy::default(),
1668 }
1669 }
1670}
1671
1672impl Default for SessionSecurityPolicy {
1673 fn default() -> Self {
1674 Self {
1675 require_mfa_for_new_devices: true,
1676 require_reauth_for_sensitive_ops: true,
1677 reauth_timeout: Duration::from_secs(300), max_risk_score: 70,
1679 auto_suspend_suspicious: true,
1680 verify_location_changes: true,
1681 limit_concurrent_sessions: true,
1682 }
1683 }
1684}
1685
1686#[cfg(test)]
1687mod tests {
1688 use super::*;
1689
1690 #[test]
1691 fn test_device_fingerprint_generation() {
1692 let generator = DeviceFingerprintGenerator::new();
1693 let metadata = RequestMetadata {
1694 user_agent: Some("Mozilla/5.0".to_string()),
1695 ..Default::default()
1696 };
1697
1698 let fp1 = generator.generate_fingerprint(&metadata);
1699 let fp2 = generator.generate_fingerprint(&metadata);
1700
1701 assert_eq!(fp1, fp2);
1702 assert!(fp1.starts_with("fp_"));
1703 }
1704
1705 #[test]
1706 fn test_risk_calculation() {
1707 let calculator = RiskCalculator::new();
1708 let device_info = DeviceInfo {
1709 fingerprint: "test".to_string(),
1710 device_type: "desktop".to_string(),
1711 operating_system: None,
1712 browser: None,
1713 screen_resolution: None,
1714 timezone: None,
1715 language: None,
1716 is_trusted: false,
1717 device_name: None,
1718 is_mobile: false,
1719 ip_address: None,
1720 };
1721
1722 let metadata = RequestMetadata::default();
1723 let history = vec![];
1724
1725 let risk = calculator.calculate_risk(&device_info, &metadata, &history, None);
1726 assert!(risk >= 20); }
1728
1729 #[test]
1730 fn test_session_config_builder_for_web_app() {
1731 let config = SessionConfigBuilder::for_web_app().build();
1732 assert_eq!(config.default_duration, Duration::from_secs(3600));
1733 assert_eq!(config.max_duration, Duration::from_secs(86400));
1734 assert_eq!(config.max_concurrent_sessions, Some(5));
1735 assert!(config.track_device_fingerprints);
1736 }
1737
1738 #[test]
1739 fn test_session_config_builder_for_api_service() {
1740 let config = SessionConfigBuilder::for_api_service().build();
1741 assert_eq!(config.default_duration, Duration::from_secs(900));
1742 assert!(config.max_concurrent_sessions.is_none());
1743 assert!(!config.track_device_fingerprints);
1744 assert!(!config.rotate_periodically);
1745 }
1746
1747 #[test]
1748 fn test_session_config_builder_for_high_security() {
1749 let config = SessionConfigBuilder::for_high_security()
1750 .allowed_countries(vec!["US".into()])
1751 .build();
1752 assert_eq!(config.default_duration, Duration::from_secs(1800));
1753 assert_eq!(config.max_concurrent_sessions, Some(1));
1754 assert!(config.enforce_geographic_restrictions);
1755 assert_eq!(config.allowed_countries, vec!["US".to_string()]);
1756 assert!(config.security_policy.require_mfa_for_new_devices);
1757 }
1758}