feat(firewall): add IP set blocking convenience API with CIDR interval support and optional rule comments
This commit is contained in:
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartnftables',
|
||||
version: '1.1.0',
|
||||
version: '1.2.0',
|
||||
description: 'A TypeScript module for managing nftables rules including NAT, firewall, and rate limiting with a high-level API.'
|
||||
}
|
||||
|
||||
@@ -52,7 +52,9 @@ export type {
|
||||
INftRateLimitRule,
|
||||
INftConnectionRateRule,
|
||||
INftFirewallRule,
|
||||
INftIPSetBlockOptions,
|
||||
INftIPSetConfig,
|
||||
INftCleanupOptions,
|
||||
INftRuleGroup,
|
||||
ISmartNftablesOptions,
|
||||
INftStatus,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { SmartNftables } from './nft.manager.js';
|
||||
import type { INftFirewallRule, INftIPSetConfig } from './nft.types.js';
|
||||
import type { INftFirewallRule, INftIPSetBlockOptions, INftIPSetConfig } from './nft.types.js';
|
||||
import {
|
||||
buildFirewallRule,
|
||||
buildIPSetCreate,
|
||||
@@ -82,6 +82,41 @@ export class FirewallManager {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience: block many IPs or CIDR subnets using one nftables set and
|
||||
* one matching drop rule. This is substantially cheaper than one rule per IP.
|
||||
*/
|
||||
public async blockIPSet(groupId: string, options: INftIPSetBlockOptions): Promise<void> {
|
||||
const ips = [...new Set(options.ips)].filter(Boolean).sort();
|
||||
if (ips.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.parent.ensureFilterChains();
|
||||
|
||||
const setName = options.setName ?? `${groupId.replace(/[^a-zA-Z0-9_]/g, '_')}_set`;
|
||||
const setType = options.type ?? (this.parent.family === 'ip6' ? 'ipv6_addr' : 'ipv4_addr');
|
||||
const needsIntervalSet = ips.some((ip) => ip.includes('/'));
|
||||
const direction = options.direction ?? 'input';
|
||||
const commands = [
|
||||
...buildIPSetCreate(this.parent.tableName, this.parent.family, {
|
||||
name: setName,
|
||||
type: setType,
|
||||
elements: ips,
|
||||
interval: needsIntervalSet,
|
||||
}),
|
||||
...buildIPSetMatchRule(this.parent.tableName, this.parent.family, {
|
||||
setName,
|
||||
direction,
|
||||
matchField: 'saddr',
|
||||
action: 'drop',
|
||||
comment: options.comment,
|
||||
}),
|
||||
];
|
||||
|
||||
await this.parent.applyRuleGroup(`fw:blockset:${groupId}`, commands);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience: allow only specific IPs on a port.
|
||||
* Adds accept rules for each IP, then a drop rule for everything else on that port.
|
||||
|
||||
+4
-4
@@ -3,7 +3,7 @@ import { buildTableSetup, buildFilterChains, buildTableCleanup } from './nft.rul
|
||||
import { NatManager } from './nft.manager.nat.js';
|
||||
import { FirewallManager } from './nft.manager.firewall.js';
|
||||
import { RateLimitManager } from './nft.manager.ratelimit.js';
|
||||
import type { TNftFamily, INftRuleGroup, INftStatus, ISmartNftablesOptions } from './nft.types.js';
|
||||
import type { TNftFamily, INftCleanupOptions, INftRuleGroup, INftStatus, ISmartNftablesOptions } from './nft.types.js';
|
||||
|
||||
/**
|
||||
* SmartNftables — high-level facade for managing nftables rules.
|
||||
@@ -122,8 +122,8 @@ export class SmartNftables {
|
||||
/**
|
||||
* Delete the entire nftables table and clear all tracking.
|
||||
*/
|
||||
public async cleanup(): Promise<void> {
|
||||
if (this.executor.isRoot() && this.initialized) {
|
||||
public async cleanup(options: INftCleanupOptions = {}): Promise<void> {
|
||||
if (this.executor.isRoot() && (this.initialized || options.force)) {
|
||||
const commands = buildTableCleanup(this.tableName, this.family);
|
||||
await this.executor.execBatch(commands, { continueOnError: true });
|
||||
}
|
||||
@@ -138,7 +138,7 @@ export class SmartNftables {
|
||||
* Returns false if not root, not initialized, or the table was removed externally.
|
||||
*/
|
||||
public async tableExists(): Promise<boolean> {
|
||||
if (!this.executor.isRoot() || !this.initialized) {
|
||||
if (!this.executor.isRoot()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
|
||||
@@ -84,10 +84,11 @@ export function buildIPSetCreate(
|
||||
config: INftIPSetConfig,
|
||||
): string[] {
|
||||
const commands: string[] = [];
|
||||
const flags = config.interval ? ' flags interval \\;' : '';
|
||||
|
||||
// Create the set
|
||||
commands.push(
|
||||
`nft add set ${family} ${tableName} ${config.name} { type ${config.type} \\; }`
|
||||
`nft add set ${family} ${tableName} ${config.name} { type ${config.type} \\;${flags} }`
|
||||
);
|
||||
|
||||
// Add initial elements if provided
|
||||
@@ -154,10 +155,12 @@ export function buildIPSetMatchRule(
|
||||
direction: 'input' | 'output' | 'forward';
|
||||
matchField: 'saddr' | 'daddr';
|
||||
action: 'accept' | 'drop' | 'reject';
|
||||
comment?: string;
|
||||
},
|
||||
): string[] {
|
||||
const comment = options.comment ? ` comment "${options.comment}"` : '';
|
||||
return [
|
||||
`nft add rule ${family} ${tableName} ${options.direction} ip ${options.matchField} @${options.setName} ${options.action}`
|
||||
`nft add rule ${family} ${tableName} ${options.direction} ip ${options.matchField} @${options.setName}${comment} ${options.action}`
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -73,9 +73,29 @@ export interface INftIPSetConfig {
|
||||
name: string;
|
||||
type: 'ipv4_addr' | 'ipv6_addr' | 'inet_service';
|
||||
elements?: string[];
|
||||
/** Enable interval sets so CIDR/range elements can be stored. */
|
||||
interval?: boolean;
|
||||
comment?: string;
|
||||
}
|
||||
|
||||
export interface INftIPSetBlockOptions {
|
||||
/** Name of the nftables set to create and match against. */
|
||||
setName?: string;
|
||||
/** IPs or CIDR ranges to add to the set. */
|
||||
ips: string[];
|
||||
/** Chain to apply the block rule to. Default: input. */
|
||||
direction?: 'input' | 'forward';
|
||||
/** Set type. Defaults to ipv4_addr for the default ip family. */
|
||||
type?: 'ipv4_addr' | 'ipv6_addr';
|
||||
/** Optional rule comment. */
|
||||
comment?: string;
|
||||
}
|
||||
|
||||
export interface INftCleanupOptions {
|
||||
/** Delete the table even when this process did not initialize it. */
|
||||
force?: boolean;
|
||||
}
|
||||
|
||||
// ─── Rule Group (tracking unit) ───────────────────────────────────
|
||||
export interface INftRuleGroup {
|
||||
id: string;
|
||||
|
||||
Reference in New Issue
Block a user