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