File size: 19,718 Bytes
a21c316 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 | //! Security Database Module
//! 安全监控相关的数据库操作
use rusqlite::{params, Connection};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
/// IP 访问日志
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IpAccessLog {
pub id: String,
pub client_ip: String,
pub timestamp: i64,
pub method: Option<String>,
pub path: Option<String>,
pub user_agent: Option<String>,
pub status: Option<i32>,
pub duration: Option<i64>,
pub api_key_hash: Option<String>,
pub blocked: bool,
pub block_reason: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub username: Option<String>,
}
/// IP 黑名单条目
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IpBlacklistEntry {
pub id: String,
pub ip_pattern: String,
pub reason: Option<String>,
pub created_at: i64,
pub expires_at: Option<i64>,
pub created_by: String,
pub hit_count: i64,
}
/// IP 白名单条目
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IpWhitelistEntry {
pub id: String,
pub ip_pattern: String,
pub description: Option<String>,
pub created_at: i64,
}
/// IP 统计概览
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IpStats {
pub total_requests: u64,
pub unique_ips: u64,
pub blocked_count: u64,
pub today_requests: u64,
pub blacklist_count: u64,
pub whitelist_count: u64,
}
/// IP 访问排行
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IpRanking {
pub client_ip: String,
pub request_count: u64,
pub last_seen: i64,
pub is_blocked: bool,
}
/// 获取安全数据库路径
pub fn get_security_db_path() -> Result<PathBuf, String> {
let data_dir = crate::modules::account::get_data_dir()?;
Ok(data_dir.join("security.db"))
}
/// 连接数据库
fn connect_db() -> Result<Connection, String> {
let db_path = get_security_db_path()?;
let conn = Connection::open(db_path).map_err(|e| e.to_string())?;
// Enable WAL mode for better concurrency
conn.pragma_update(None, "journal_mode", "WAL")
.map_err(|e| e.to_string())?;
// Set busy timeout
conn.pragma_update(None, "busy_timeout", 5000)
.map_err(|e| e.to_string())?;
conn.pragma_update(None, "synchronous", "NORMAL")
.map_err(|e| e.to_string())?;
Ok(conn)
}
/// 初始化安全数据库
pub fn init_db() -> Result<(), String> {
let conn = connect_db()?;
// IP 访问日志表
conn.execute(
"CREATE TABLE IF NOT EXISTS ip_access_logs (
id TEXT PRIMARY KEY,
client_ip TEXT NOT NULL,
timestamp INTEGER NOT NULL,
method TEXT,
path TEXT,
user_agent TEXT,
status INTEGER,
duration INTEGER,
api_key_hash TEXT,
blocked INTEGER DEFAULT 0,
block_reason TEXT
)",
[],
)
.map_err(|e| e.to_string())?;
// IP 黑名单表
conn.execute(
"CREATE TABLE IF NOT EXISTS ip_blacklist (
id TEXT PRIMARY KEY,
ip_pattern TEXT NOT NULL UNIQUE,
reason TEXT,
created_at INTEGER NOT NULL,
expires_at INTEGER,
created_by TEXT DEFAULT 'manual',
hit_count INTEGER DEFAULT 0
)",
[],
)
.map_err(|e| e.to_string())?;
// IP 白名单表
conn.execute(
"CREATE TABLE IF NOT EXISTS ip_whitelist (
id TEXT PRIMARY KEY,
ip_pattern TEXT NOT NULL UNIQUE,
description TEXT,
created_at INTEGER NOT NULL
)",
[],
)
.map_err(|e| e.to_string())?;
// 创建索引
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_ip_access_ip ON ip_access_logs (client_ip)",
[],
)
.map_err(|e| e.to_string())?;
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_ip_access_timestamp ON ip_access_logs (timestamp DESC)",
[],
)
.map_err(|e| e.to_string())?;
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_ip_access_blocked ON ip_access_logs (blocked)",
[],
)
.map_err(|e| e.to_string())?;
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_blacklist_pattern ON ip_blacklist (ip_pattern)",
[],
)
.map_err(|e| e.to_string())?;
// Migration: Add username column to ip_access_logs
let _ = conn.execute("ALTER TABLE ip_access_logs ADD COLUMN username TEXT", []);
Ok(())
}
// ============================================================================
// IP 访问日志操作
// ============================================================================
/// 保存 IP 访问日志
pub fn save_ip_access_log(log: &IpAccessLog) -> Result<(), String> {
let conn = connect_db()?;
conn.execute(
"INSERT INTO ip_access_logs (id, client_ip, timestamp, method, path, user_agent, status, duration, api_key_hash, blocked, block_reason, username)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
params![
log.id,
log.client_ip,
log.timestamp,
log.method,
log.path,
log.user_agent,
log.status,
log.duration,
log.api_key_hash,
log.blocked,
log.block_reason,
log.username,
],
)
.map_err(|e| e.to_string())?;
Ok(())
}
/// 获取 IP 访问日志 (分页)
pub fn get_ip_access_logs(
limit: usize,
offset: usize,
ip_filter: Option<&str>,
blocked_only: bool,
) -> Result<Vec<IpAccessLog>, String> {
let conn = connect_db()?;
let sql = if blocked_only {
if let Some(ip) = ip_filter {
format!(
"SELECT id, client_ip, timestamp, method, path, user_agent, status, duration, api_key_hash, blocked, block_reason, username
FROM ip_access_logs
WHERE blocked = 1 AND client_ip LIKE '%{}%'
ORDER BY timestamp DESC
LIMIT {} OFFSET {}",
ip, limit, offset
)
} else {
format!(
"SELECT id, client_ip, timestamp, method, path, user_agent, status, duration, api_key_hash, blocked, block_reason, username
FROM ip_access_logs
WHERE blocked = 1
ORDER BY timestamp DESC
LIMIT {} OFFSET {}",
limit, offset
)
}
} else if let Some(ip) = ip_filter {
format!(
"SELECT id, client_ip, timestamp, method, path, user_agent, status, duration, api_key_hash, blocked, block_reason, username
FROM ip_access_logs
WHERE client_ip LIKE '%{}%'
ORDER BY timestamp DESC
LIMIT {} OFFSET {}",
ip, limit, offset
)
} else {
format!(
"SELECT id, client_ip, timestamp, method, path, user_agent, status, duration, api_key_hash, blocked, block_reason, username
FROM ip_access_logs
ORDER BY timestamp DESC
LIMIT {} OFFSET {}",
limit, offset
)
};
let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
let logs_iter = stmt
.query_map([], |row| {
Ok(IpAccessLog {
id: row.get(0)?,
client_ip: row.get(1)?,
timestamp: row.get(2)?,
method: row.get(3)?,
path: row.get(4)?,
user_agent: row.get(5)?,
status: row.get(6)?,
duration: row.get(7)?,
api_key_hash: row.get(8)?,
blocked: row.get::<_, i32>(9)? != 0,
block_reason: row.get(10)?,
username: row.get(11).unwrap_or(None),
})
})
.map_err(|e| e.to_string())?;
let mut logs = Vec::new();
for log in logs_iter {
logs.push(log.map_err(|e| e.to_string())?);
}
Ok(logs)
}
/// 获取 IP 统计概览
pub fn get_ip_stats() -> Result<IpStats, String> {
let conn = connect_db()?;
let today_start = chrono::Utc::now()
.date_naive()
.and_hms_opt(0, 0, 0)
.unwrap()
.and_utc()
.timestamp();
let (total_requests, unique_ips, blocked_count, today_requests): (u64, u64, u64, u64) = conn
.query_row(
"SELECT
COUNT(*) as total,
COUNT(DISTINCT client_ip) as unique_ips,
SUM(CASE WHEN blocked = 1 THEN 1 ELSE 0 END) as blocked,
SUM(CASE WHEN timestamp >= ?1 THEN 1 ELSE 0 END) as today
FROM ip_access_logs",
[today_start],
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
)
.map_err(|e| e.to_string())?;
let blacklist_count: u64 = conn
.query_row("SELECT COUNT(*) FROM ip_blacklist", [], |row| row.get(0))
.map_err(|e| e.to_string())?;
let whitelist_count: u64 = conn
.query_row("SELECT COUNT(*) FROM ip_whitelist", [], |row| row.get(0))
.map_err(|e| e.to_string())?;
Ok(IpStats {
total_requests,
unique_ips,
blocked_count,
today_requests,
blacklist_count,
whitelist_count,
})
}
/// 获取 TOP N IP 访问排行
pub fn get_top_ips(limit: usize, hours: i64) -> Result<Vec<IpRanking>, String> {
let conn = connect_db()?;
let since = chrono::Utc::now().timestamp() - (hours * 3600);
let mut stmt = conn
.prepare(
"SELECT client_ip, COUNT(*) as cnt, MAX(timestamp) as last_seen
FROM ip_access_logs
WHERE timestamp >= ?1
GROUP BY client_ip
ORDER BY cnt DESC
LIMIT ?2",
)
.map_err(|e| e.to_string())?;
let rankings_iter = stmt
.query_map([since, limit as i64], |row| {
Ok(IpRanking {
client_ip: row.get(0)?,
request_count: row.get(1)?,
last_seen: row.get(2)?,
is_blocked: false, // 稍后填充
})
})
.map_err(|e| e.to_string())?;
let mut rankings = Vec::new();
for r in rankings_iter {
let mut ranking = r.map_err(|e| e.to_string())?;
// 检查是否在黑名单中
ranking.is_blocked = is_ip_in_blacklist(&ranking.client_ip)?;
rankings.push(ranking);
}
Ok(rankings)
}
/// 清理旧的 IP 访问日志
pub fn cleanup_old_ip_logs(days: i64) -> Result<usize, String> {
let conn = connect_db()?;
let cutoff_timestamp = chrono::Utc::now().timestamp() - (days * 24 * 3600);
let deleted = conn
.execute(
"DELETE FROM ip_access_logs WHERE timestamp < ?1",
[cutoff_timestamp],
)
.map_err(|e| e.to_string())?;
// VACUUM to reclaim space
conn.execute("VACUUM", []).map_err(|e| e.to_string())?;
Ok(deleted)
}
// ============================================================================
// 黑名单操作
// ============================================================================
/// 添加 IP 到黑名单
pub fn add_to_blacklist(
ip_pattern: &str,
reason: Option<&str>,
expires_at: Option<i64>,
created_by: &str,
) -> Result<IpBlacklistEntry, String> {
let conn = connect_db()?;
let id = uuid::Uuid::new_v4().to_string();
let now = chrono::Utc::now().timestamp();
conn.execute(
"INSERT INTO ip_blacklist (id, ip_pattern, reason, created_at, expires_at, created_by, hit_count)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0)",
params![id, ip_pattern, reason, now, expires_at, created_by],
)
.map_err(|e| e.to_string())?;
Ok(IpBlacklistEntry {
id,
ip_pattern: ip_pattern.to_string(),
reason: reason.map(|s| s.to_string()),
created_at: now,
expires_at,
created_by: created_by.to_string(),
hit_count: 0,
})
}
/// 从黑名单移除
pub fn remove_from_blacklist(id: &str) -> Result<(), String> {
let conn = connect_db()?;
conn.execute("DELETE FROM ip_blacklist WHERE id = ?1", [id])
.map_err(|e| e.to_string())?;
Ok(())
}
/// 获取黑名单列表
pub fn get_blacklist() -> Result<Vec<IpBlacklistEntry>, String> {
let conn = connect_db()?;
let mut stmt = conn
.prepare(
"SELECT id, ip_pattern, reason, created_at, expires_at, created_by, hit_count
FROM ip_blacklist
ORDER BY created_at DESC",
)
.map_err(|e| e.to_string())?;
let entries_iter = stmt
.query_map([], |row| {
Ok(IpBlacklistEntry {
id: row.get(0)?,
ip_pattern: row.get(1)?,
reason: row.get(2)?,
created_at: row.get(3)?,
expires_at: row.get(4)?,
created_by: row.get(5)?,
hit_count: row.get(6)?,
})
})
.map_err(|e| e.to_string())?;
let mut entries = Vec::new();
for e in entries_iter {
entries.push(e.map_err(|e| e.to_string())?);
}
Ok(entries)
}
/// 检查 IP 是否在黑名单中
pub fn is_ip_in_blacklist(ip: &str) -> Result<bool, String> {
get_blacklist_entry_for_ip(ip).map(|entry| entry.is_some())
}
/// 获取 IP 对应的黑名单条目(如果存在)
pub fn get_blacklist_entry_for_ip(ip: &str) -> Result<Option<IpBlacklistEntry>, String> {
let conn = connect_db()?;
let now = chrono::Utc::now().timestamp();
// 清理过期的黑名单条目
let _ = conn.execute(
"DELETE FROM ip_blacklist WHERE expires_at IS NOT NULL AND expires_at < ?1",
[now],
);
// 精确匹配
let entry_result = conn.query_row(
"SELECT id, ip_pattern, reason, created_at, expires_at, created_by, hit_count
FROM ip_blacklist WHERE ip_pattern = ?1",
[ip],
|row| {
Ok(IpBlacklistEntry {
id: row.get(0)?,
ip_pattern: row.get(1)?,
reason: row.get(2)?,
created_at: row.get(3)?,
expires_at: row.get(4)?,
created_by: row.get(5)?,
hit_count: row.get(6)?,
})
},
);
if let Ok(entry) = entry_result {
// 增加命中计数
let _ = conn.execute(
"UPDATE ip_blacklist SET hit_count = hit_count + 1 WHERE ip_pattern = ?1",
[ip],
);
return Ok(Some(entry));
}
// CIDR 匹配
let entries = get_blacklist()?;
for entry in entries {
if entry.ip_pattern.contains('/') {
if cidr_match(ip, &entry.ip_pattern) {
// 增加命中计数
let _ = conn.execute(
"UPDATE ip_blacklist SET hit_count = hit_count + 1 WHERE id = ?1",
[&entry.id],
);
return Ok(Some(entry));
}
}
}
Ok(None)
}
/// 简单的 CIDR 匹配
fn cidr_match(ip: &str, cidr: &str) -> bool {
let parts: Vec<&str> = cidr.split('/').collect();
if parts.len() != 2 {
return false;
}
let network = parts[0];
let prefix_len: u8 = match parts[1].parse() {
Ok(p) => p,
Err(_) => return false,
};
let ip_parts: Vec<u8> = ip
.split('.')
.filter_map(|s| s.parse().ok())
.collect();
let net_parts: Vec<u8> = network
.split('.')
.filter_map(|s| s.parse().ok())
.collect();
if ip_parts.len() != 4 || net_parts.len() != 4 {
return false;
}
let ip_u32 = u32::from_be_bytes([ip_parts[0], ip_parts[1], ip_parts[2], ip_parts[3]]);
let net_u32 = u32::from_be_bytes([net_parts[0], net_parts[1], net_parts[2], net_parts[3]]);
let mask = if prefix_len == 0 {
0
} else {
!0u32 << (32 - prefix_len)
};
(ip_u32 & mask) == (net_u32 & mask)
}
// ============================================================================
// 白名单操作
// ============================================================================
/// 添加 IP 到白名单
pub fn add_to_whitelist(ip_pattern: &str, description: Option<&str>) -> Result<IpWhitelistEntry, String> {
let conn = connect_db()?;
let id = uuid::Uuid::new_v4().to_string();
let now = chrono::Utc::now().timestamp();
conn.execute(
"INSERT INTO ip_whitelist (id, ip_pattern, description, created_at)
VALUES (?1, ?2, ?3, ?4)",
params![id, ip_pattern, description, now],
)
.map_err(|e| e.to_string())?;
Ok(IpWhitelistEntry {
id,
ip_pattern: ip_pattern.to_string(),
description: description.map(|s| s.to_string()),
created_at: now,
})
}
/// 从白名单移除
pub fn remove_from_whitelist(id: &str) -> Result<(), String> {
let conn = connect_db()?;
conn.execute("DELETE FROM ip_whitelist WHERE id = ?1", [id])
.map_err(|e| e.to_string())?;
Ok(())
}
/// 获取白名单列表
pub fn get_whitelist() -> Result<Vec<IpWhitelistEntry>, String> {
let conn = connect_db()?;
let mut stmt = conn
.prepare(
"SELECT id, ip_pattern, description, created_at
FROM ip_whitelist
ORDER BY created_at DESC",
)
.map_err(|e| e.to_string())?;
let entries_iter = stmt
.query_map([], |row| {
Ok(IpWhitelistEntry {
id: row.get(0)?,
ip_pattern: row.get(1)?,
description: row.get(2)?,
created_at: row.get(3)?,
})
})
.map_err(|e| e.to_string())?;
let mut entries = Vec::new();
for e in entries_iter {
entries.push(e.map_err(|e| e.to_string())?);
}
Ok(entries)
}
/// 检查 IP 是否在白名单中
pub fn is_ip_in_whitelist(ip: &str) -> Result<bool, String> {
let conn = connect_db()?;
// 精确匹配
let count: i64 = conn
.query_row(
"SELECT COUNT(*) FROM ip_whitelist WHERE ip_pattern = ?1",
[ip],
|row| row.get(0),
)
.map_err(|e| e.to_string())?;
if count > 0 {
return Ok(true);
}
// CIDR 匹配
let entries = get_whitelist()?;
for entry in entries {
if entry.ip_pattern.contains('/') {
if cidr_match(ip, &entry.ip_pattern) {
return Ok(true);
}
}
}
Ok(false)
}
/// 清空所有 IP 访问日志
pub fn clear_ip_access_logs() -> Result<(), String> {
let conn = connect_db()?;
conn.execute("DELETE FROM ip_access_logs", [])
.map_err(|e| e.to_string())?;
Ok(())
}
/// 获取 IP 访问日志总数
pub fn get_ip_access_logs_count(ip_filter: Option<&str>, blocked_only: bool) -> Result<u64, String> {
let conn = connect_db()?;
let sql = if blocked_only {
if let Some(ip) = ip_filter {
format!(
"SELECT COUNT(*) FROM ip_access_logs WHERE blocked = 1 AND client_ip LIKE '%{}%'",
ip
)
} else {
"SELECT COUNT(*) FROM ip_access_logs WHERE blocked = 1".to_string()
}
} else if let Some(ip) = ip_filter {
format!(
"SELECT COUNT(*) FROM ip_access_logs WHERE client_ip LIKE '%{}%'",
ip
)
} else {
"SELECT COUNT(*) FROM ip_access_logs".to_string()
};
let count: u64 = conn
.query_row(&sql, [], |row| row.get(0))
.map_err(|e| e.to_string())?;
Ok(count)
}
|