harborshield 0.1.0

A Rust port of Whalewall, to automate management of firewall rules for Docker containers
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
pub mod database;
pub mod docker;
pub mod error;
pub mod handlers;
pub mod nftables;
#[cfg(target_os = "linux")]
pub mod security;
pub mod server;

use crate::{
    database::DB,
    docker::DockerClient,
    handlers::cleanup::CleanupTracker,
    nftables::{FILTER_TABLE, NftablesClient},
};
use bon::bon;
pub use error::{Error, Result};
use std::path::Path;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::time::Duration;
use tokio::signal;
use tokio::sync::{Mutex, mpsc};
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, warn};

pub const ENABLED_LABEL: &str = "harborshield.enabled";
pub const RULES_LABEL: &str = "harborshield.rules";

#[derive(Clone)]
pub struct Harborshield {
    docker_client: Arc<DockerClient>,
    nftables_client: Arc<Mutex<NftablesClient>>,
    db: Arc<Mutex<DB>>,
    shutdown_tx: mpsc::Sender<()>,
    shutdown_rx: Arc<Mutex<mpsc::Receiver<()>>>,
    task_handles: Arc<StdMutex<Vec<JoinHandle<()>>>>,
    health_server_handle: Arc<Option<JoinHandle<()>>>,
    start_time: chrono::DateTime<chrono::Utc>,
    cleanup_tracker: Arc<CleanupTracker>,
    cancellation_token: CancellationToken,
}

#[bon]
impl Harborshield {
    #[builder]
    pub async fn new(
        db_path: &Path,
        timeout: Duration,
        health_server_addr: Option<&str>,
    ) -> Result<Self> {
        let docker_client = Arc::new(DockerClient::builder().timeout_duration(timeout).build()?);
        let mut nftables_client = NftablesClient::builder().build();
        // Enable NAT support for localhost mapped port gateway handling
        nftables_client.init_base_chains().await?;
        let nftables_client = Arc::new(Mutex::new(nftables_client));

        let db = Arc::new(Mutex::new(DB::builder().db_path(db_path).build().await?));

        let (shutdown_tx, shutdown_rx) = mpsc::channel(1);
        let shutdown_rx = Arc::new(Mutex::new(shutdown_rx));

        // Setup metrics
        let prometheus_handle = server::setup_metrics()?;

        // Start health server if requested
        let health_server_handle = if let Some(addr) = health_server_addr {
            let health_server =
                server::HealthServer::new(addr, prometheus_handle, crate::VERSION.to_string())
                    .await?;

            let handle = tokio::spawn(async move {
                if let Err(e) = health_server.serve().await {
                    error!("Health server error: {}", e);
                }
            });
            Some(handle)
        } else {
            None
        };

        let cleanup_tracker = Arc::new(CleanupTracker::builder().db(db.clone()).build());

        let cancellation_token = CancellationToken::new();

        let handlers = Self {
            docker_client,
            nftables_client,
            db,
            shutdown_tx,
            shutdown_rx,
            task_handles: Arc::new(StdMutex::new(Vec::new())),
            health_server_handle: Arc::new(health_server_handle),
            start_time: chrono::Utc::now(),
            cleanup_tracker,
            cancellation_token,
        };

        Ok(handlers)
    }

    pub async fn start(self) -> Result<Self> {
        info!("Starting harborshield rule handlers");

        // Clean up orphaned rules from previous runs
        self.cleanup_orphaned_rules().await?;

        // Sync existing containers
        let stopped_container_ids = self
            .sync_containers(self.get_database_containers().await?)
            .await?;

        // Clean up stopped containers
        self.cleanup_stopped_containers(stopped_container_ids)
            .await?;

        let handlers = Arc::new(self.clone());
        // Start event listener
        let event_handle = self.spawn_event_listener(handlers);
        self.task_handles.lock().unwrap().push(event_handle);

        // Update metrics
        self.update_metrics().await;

        Ok(self)
    }

    pub async fn stop(self) {
        info!("Stopping harborshield rule handlers");

        // Cancel all operations
        self.cancellation_token.cancel();

        // Send shutdown signal to all tasks
        let _ = self.shutdown_tx.send(()).await;

        // Clean up any partially created resources
        info!("Performing cleanup of tracked resources");
        if let Err(e) = self.cleanup_tracker.cleanup_all().await {
            error!("Failed to cleanup tracked resources: {}", e);
        }

        // Wait for all background tasks to complete with timeout
        let timeout_duration = Duration::from_secs(30);
        let mut tasks = self.task_handles.lock().unwrap();
        let task_vec = std::mem::take(&mut *tasks);
        drop(tasks); // Release the lock

        let mut all_tasks = task_vec;

        if let Some(health_handle) = Arc::try_unwrap(self.health_server_handle)
            .ok()
            .and_then(|opt| opt)
        {
            all_tasks.push(health_handle);
        }

        for handle in all_tasks {
            let task_result = tokio::time::timeout(timeout_duration, handle).await;
            match task_result {
                Ok(Ok(())) => {
                    debug!("Task completed successfully");
                }
                Ok(Err(e)) => {
                    error!("Task completed with error: {}", e);
                }
                Err(_) => {
                    warn!("Task did not complete within timeout, forcing shutdown");
                }
            }
        }

        // Shutdown cleanup tracker
        let cleanup_tracker = Arc::try_unwrap(self.cleanup_tracker)
            .ok()
            .expect("Cleanup tracker has other references");
        if let Err(e) = cleanup_tracker.shutdown().await {
            error!("Failed to shutdown cleanup tracker: {}", e);
        }

        // Close database connection
        if let Ok(db_mutex) = Arc::try_unwrap(self.db) {
            match db_mutex.into_inner() {
                db => {
                    if let Err(e) = db.close().await {
                        error!("Failed to close database connection: {}", e);
                    }
                }
            }
        }

        info!("Harborshield rule handlers stopped gracefully");
    }

    pub async fn clear(&self) -> Result<()> {
        info!("Clearing all harborshield rules");

        // First, clear all Harborshield container chains from the filter table
        self.clear_all_harborshield_chains().await?;

        // Clear the main harborshield chain
        let mut nftables = self.nftables_client.lock().await;
        nftables.clear_table().await?;
        drop(nftables);

        // Clear database
        let db = self.db.lock().await;
        use crate::database::{DbOp, DbOpResult};

        // Get all containers from database
        let containers = match db.execute(&DbOp::ListContainers).await? {
            DbOpResult::Containers(containers) => containers,
            _ => vec![],
        };

        // Clear all containers from database
        for container in containers {
            db.execute(&DbOp::DeleteContainer(&container.id)).await?;
        }
        drop(db);

        // Clear tracker
        self.docker_client.container_tracker.clear();

        Ok(())
    }

    /// Clear all Harborshield container chains from the filter table
    async fn clear_all_harborshield_chains(&self) -> Result<()> {
        info!("Clearing all Harborshield container chains from filter table");

        // Get a list of all Harborshield chains (hs-* chains)
        let list_output = std::process::Command::new("nft")
            .args(&["-j", "list", "table", "ip", FILTER_TABLE])
            .output()
            .map_err(|e| Error::Config {
                message: format!("Failed to list filter table: {}", e),
                location: "clear_all_harborshield_chains".to_string(),
                suggestion: Some("Check nftables permissions".to_string()),
            })?;

        if !list_output.status.success() {
            warn!(
                "Failed to list filter table: {}",
                String::from_utf8_lossy(&list_output.stderr)
            );
            return Ok(()); // Don't fail cleanup if we can't list
        }

        let output_str = String::from_utf8_lossy(&list_output.stdout);

        // Parse JSON to find all chains starting with "hs-"
        if let Ok(json) = serde_json::from_str::<serde_json::Value>(&output_str) {
            if let Some(nftables) = json.get("nftables").and_then(|n| n.as_array()) {
                let mut chains_to_delete = Vec::new();

                for item in nftables {
                    if let Some(chain) = item.get("chain") {
                        if let Some(name) = chain.get("name").and_then(|n| n.as_str()) {
                            if name.starts_with("hs-") {
                                chains_to_delete.push(name.to_string());
                            }
                        }
                    }
                }

                info!(
                    "Found {} Harborshield container chains to delete",
                    chains_to_delete.len()
                );

                // Delete each container chain
                for chain_name in chains_to_delete {
                    // First flush the chain
                    let flush_result = std::process::Command::new("nft")
                        .args(&["flush", "chain", "ip", FILTER_TABLE, &chain_name])
                        .output();

                    if let Err(e) = flush_result {
                        warn!("Failed to flush chain {}: {}", chain_name, e);
                    }

                    // Then delete the chain
                    let delete_result = std::process::Command::new("nft")
                        .args(&["delete", "chain", "ip", FILTER_TABLE, &chain_name])
                        .output();

                    match delete_result {
                        Ok(output) => {
                            if output.status.success() {
                                debug!("Successfully deleted chain {}", chain_name);
                            } else {
                                warn!(
                                    "Failed to delete chain {}: {}",
                                    chain_name,
                                    String::from_utf8_lossy(&output.stderr)
                                );
                            }
                        }
                        Err(e) => {
                            warn!("Failed to delete chain {}: {}", chain_name, e);
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Clean up orphaned Harborshield rules that don't belong to any running container
    async fn cleanup_orphaned_rules(&self) -> Result<()> {
        info!("Cleaning up orphaned Harborshield rules");

        // Get all running containers
        let running_containers = self.docker_client.get_sorted_containers().await?;
        let mut valid_chain_names = std::collections::HashSet::new();

        // Build set of valid chain names for running containers
        for container in running_containers {
            if let Some(id) = container.id {
                if let Ok(details) = self.docker_client.try_get_container_by_id(&id).await {
                    let chain_name = format!(
                        "hs-{}-{}",
                        details.name.replace(['_', '.', '/'], "-"),
                        &id[..12.min(id.len())]
                    );
                    valid_chain_names.insert(chain_name);
                }
            }
        }

        // Get all chains in the filter table
        let list_output = std::process::Command::new("nft")
            .args(&["-j", "list", "table", "ip", FILTER_TABLE])
            .output()
            .map_err(|e| Error::Config {
                message: format!("Failed to list filter table: {}", e),
                location: "cleanup_orphaned_rules".to_string(),
                suggestion: Some("Check nftables permissions".to_string()),
            })?;

        if !list_output.status.success() {
            warn!(
                "Failed to list filter table: {}",
                String::from_utf8_lossy(&list_output.stderr)
            );
            return Ok(()); // Don't fail startup if we can't list
        }

        let output_str = String::from_utf8_lossy(&list_output.stdout);

        // Parse JSON to find orphaned chains
        if let Ok(json) = serde_json::from_str::<serde_json::Value>(&output_str) {
            if let Some(nftables) = json.get("nftables").and_then(|n| n.as_array()) {
                let mut orphaned_chains = Vec::new();

                for item in nftables {
                    if let Some(chain) = item.get("chain") {
                        if let Some(name) = chain.get("name").and_then(|n| n.as_str()) {
                            if name.starts_with("hs-") && !valid_chain_names.contains(name) {
                                orphaned_chains.push(name.to_string());
                            }
                        }
                    }
                }

                if orphaned_chains.is_empty() {
                    info!("No orphaned Harborshield chains found");
                } else {
                    info!(
                        "Found {} orphaned Harborshield chains to remove",
                        orphaned_chains.len()
                    );

                    // Delete each orphaned chain
                    for chain_name in orphaned_chains {
                        info!("Removing orphaned chain: {}", chain_name);

                        // First flush the chain
                        let flush_result = std::process::Command::new("nft")
                            .args(&["flush", "chain", "ip", FILTER_TABLE, &chain_name])
                            .output();

                        if let Err(e) = flush_result {
                            warn!("Failed to flush orphaned chain {}: {}", chain_name, e);
                        }

                        // Then delete the chain
                        let delete_result = std::process::Command::new("nft")
                            .args(&["delete", "chain", "ip", FILTER_TABLE, &chain_name])
                            .output();

                        match delete_result {
                            Ok(output) => {
                                if output.status.success() {
                                    debug!("Successfully removed orphaned chain {}", chain_name);
                                } else {
                                    warn!(
                                        "Failed to delete orphaned chain {}: {}",
                                        chain_name,
                                        String::from_utf8_lossy(&output.stderr)
                                    );
                                }
                            }
                            Err(e) => {
                                warn!("Failed to delete orphaned chain {}: {}", chain_name, e);
                            }
                        }
                    }
                }
            }
        }

        Ok(())
    }
}

pub const VERSION: &str = env!("CARGO_PKG_VERSION");

pub fn parse_duration(s: &str) -> std::result::Result<Duration, String> {
    let s = s.trim();

    if let Some(stripped) = s.strip_suffix("ms") {
        stripped
            .parse::<u64>()
            .map(Duration::from_millis)
            .map_err(|e| format!("Invalid milliseconds: {}", e))
    } else if let Some(stripped) = s.strip_suffix('s') {
        stripped
            .parse::<u64>()
            .map(Duration::from_secs)
            .map_err(|e| format!("Invalid seconds: {}", e))
    } else if let Some(stripped) = s.strip_suffix('m') {
        stripped
            .parse::<u64>()
            .map(|m| Duration::from_secs(m * 60))
            .map_err(|e| format!("Invalid minutes: {}", e))
    } else {
        // Default to seconds if no suffix
        s.parse::<u64>()
            .map(Duration::from_secs)
            .map_err(|e| format!("Invalid duration: {}", e))
    }
}

pub async fn shutdown_signal() {
    let ctrl_c = async {
        signal::ctrl_c()
            .await
            .expect("Failed to install Ctrl+C handler");
    };

    #[cfg(unix)]
    let terminate = async {
        signal::unix::signal(signal::unix::SignalKind::terminate())
            .expect("Failed to install signal handler")
            .recv()
            .await;
    };

    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    tokio::select! {
        _ = ctrl_c => {},
        _ = terminate => {},
    }
}

pub fn check_kernel_version() {
    use std::process::Command;

    let output = match Command::new("uname").arg("-r").output() {
        Ok(output) => output,
        Err(e) => {
            error!("Failed to check kernel version: {}", e);
            return;
        }
    };

    if !output.status.success() {
        error!("Failed to get kernel version");
        return;
    }

    let version = String::from_utf8_lossy(&output.stdout);
    let version = version.trim();

    // Parse major.minor version
    let parts: Vec<&str> = version.split('.').collect();
    if parts.len() >= 2 {
        if let (Ok(major), Ok(minor)) = (parts[0].parse::<u32>(), parts[1].parse::<u32>()) {
            if major < 5 || (major == 5 && minor < 10) {
                warn!(
                    "Current kernel version {} is unsupported, 5.10 or greater is required; harborshield will probably not work correctly",
                    version
                );
            }
        }
    }
}