mirror of https://github.com/wg-easy/wg-easy
Browse Source
Implement server-side firewall rules to restrict client network access, allowing administrators to enforce security policies that cannot be bypassed by clients modifying their local configuration. This feature addresses the limitation where "Allowed IPs" only controls client-side routing but doesn't prevent clients from accessing networks they shouldn't reach. The firewall rules are enforced on the server using iptables/ip6tables and provide true access control. Features: - Opt-in via "Enable Per-Client Firewall" toggle in admin interface - Per-client "Firewall Allowed IPs" field for granular control - Support for IPs, CIDRs, and port-based filtering - Protocol specification: TCP, UDP, or both (default) - IPv4 and IPv6 dual-stack support - Falls back to client's allowedIps when firewallIps is empty - Clean separation of routing (allowedIps) from security (firewallIps) Supported formats: - 10.10.0.3 (single IP) - 10.10.0.0/24 (CIDR range) - 192.168.1.5:443 (IP with port, both TCP+UDP) - 192.168.1.5:443/tcp (IP with specific protocol) - [2001:db8::1]:443 (IPv6 with port) Implementation: - New database columns: firewall_enabled (interfaces), firewall_ips (clients) - Migration 0003_add_firewall_filtering for schema updates - firewall.ts utility for iptables chain management (WG_CLIENTS chain) - Integration into WireGuard.ts for automatic rule application - UI components with conditional rendering based on firewall toggle Technical details: - Uses custom WG_CLIENTS iptables chain for isolation - Rebuild strategy: flush and recreate all rules on config save - Mutex protection via rebuildInProgress/rebuildQueued flags - Graceful cleanup when firewall is disabled - No new dependencies (uses existing is-ip, is-cidr packages)pull/2418/head
11 changed files with 361 additions and 31 deletions
@ -0,0 +1,252 @@ |
|||
import debug from 'debug'; |
|||
import { isIPv6 } from 'is-ip'; |
|||
|
|||
import { exec } from './cmd'; |
|||
import type { ClientType } from '#db/repositories/client/types'; |
|||
import type { InterfaceType } from '#db/repositories/interface/types'; |
|||
import type { UserConfigType } from '#db/repositories/userConfig/types'; |
|||
|
|||
const FW_DEBUG = debug('Firewall'); |
|||
const CHAIN_NAME = 'WG_CLIENTS'; |
|||
|
|||
// Mutex to prevent concurrent rule rebuilds
|
|||
let rebuildInProgress = false; |
|||
let rebuildQueued = false; |
|||
|
|||
type ParsedEntry = { |
|||
ip: string; |
|||
port?: number; |
|||
proto?: 'tcp' | 'udp' | 'both'; |
|||
}; |
|||
|
|||
/** |
|||
* Parse a firewall entry string into its components. |
|||
* Supports formats: |
|||
* - IP: "10.0.0.1" or "2001:db8::1" |
|||
* - CIDR: "10.0.0.0/24" or "2001:db8::/32" |
|||
* - IP:port: "10.0.0.1:443" or "[2001:db8::1]:443" |
|||
* - IP:port/proto: "10.0.0.1:443/tcp" or "10.0.0.1:53/udp" |
|||
*/ |
|||
function parseFirewallEntry(entry: string): ParsedEntry { |
|||
// Extract protocol suffix first: /tcp or /udp
|
|||
let proto: 'tcp' | 'udp' | 'both' | undefined; |
|||
let remaining = entry; |
|||
|
|||
if (entry.endsWith('/tcp')) { |
|||
proto = 'tcp'; |
|||
remaining = entry.slice(0, -4); |
|||
} else if (entry.endsWith('/udp')) { |
|||
proto = 'udp'; |
|||
remaining = entry.slice(0, -4); |
|||
} |
|||
|
|||
// Handle IPv6 with port: [2001:db8::1]:443
|
|||
if (remaining.startsWith('[')) { |
|||
const match = remaining.match(/^\[(.+)\]:(\d+)$/); |
|||
if (match) { |
|||
return { ip: match[1], port: parseInt(match[2], 10), proto: proto ?? 'both' }; |
|||
} |
|||
// Just bracketed IPv6 without port
|
|||
const ipMatch = remaining.match(/^\[(.+)\]$/); |
|||
if (ipMatch) { |
|||
return { ip: ipMatch[1] }; |
|||
} |
|||
return { ip: remaining }; |
|||
} |
|||
|
|||
// Handle IPv4 with port or CIDR with port
|
|||
// Count colons to distinguish IPv6 from IPv4:port
|
|||
const colonCount = (remaining.match(/:/g) || []).length; |
|||
|
|||
if (colonCount === 1) { |
|||
// Could be IPv4:port or CIDR:port
|
|||
const lastColon = remaining.lastIndexOf(':'); |
|||
const possiblePort = remaining.slice(lastColon + 1); |
|||
if (/^\d+$/.test(possiblePort)) { |
|||
return { |
|||
ip: remaining.slice(0, lastColon), |
|||
port: parseInt(possiblePort, 10), |
|||
proto: proto ?? 'both', |
|||
}; |
|||
} |
|||
} |
|||
|
|||
// Plain IP or CIDR (IPv4 or IPv6)
|
|||
return { ip: remaining }; |
|||
} |
|||
|
|||
/** |
|||
* Generate iptables rule arguments for a single firewall entry |
|||
*/ |
|||
function generateRuleArgs( |
|||
clientIp: string, |
|||
entry: ParsedEntry, |
|||
action: 'A' | 'D' = 'A' |
|||
): string[] { |
|||
const rules: string[] = []; |
|||
const baseArgs = `-${action} ${CHAIN_NAME} -s ${clientIp} -d ${entry.ip}`; |
|||
|
|||
if (entry.port) { |
|||
// Port-specific rules
|
|||
if (entry.proto === 'tcp' || entry.proto === 'both') { |
|||
rules.push(`${baseArgs} -p tcp --dport ${entry.port} -j ACCEPT`); |
|||
} |
|||
if (entry.proto === 'udp' || entry.proto === 'both') { |
|||
rules.push(`${baseArgs} -p udp --dport ${entry.port} -j ACCEPT`); |
|||
} |
|||
} else { |
|||
// No port - allow all traffic to destination
|
|||
rules.push(`${baseArgs} -j ACCEPT`); |
|||
} |
|||
|
|||
return rules; |
|||
} |
|||
|
|||
export const firewall = { |
|||
/** |
|||
* Initialize the custom chain if it doesn't exist |
|||
*/ |
|||
async initChain(interfaceName: string): Promise<void> { |
|||
FW_DEBUG(`Initializing firewall chain ${CHAIN_NAME} for interface ${interfaceName}`); |
|||
|
|||
// Create chain if not exists (iptables returns error if exists, so we ignore)
|
|||
await exec(`iptables -N ${CHAIN_NAME} 2>/dev/null || true`); |
|||
await exec(`ip6tables -N ${CHAIN_NAME} 2>/dev/null || true`); |
|||
|
|||
// Ensure chain is referenced from FORWARD (if not already)
|
|||
// Insert at position 1 to process before generic ACCEPT rules
|
|||
await exec( |
|||
`iptables -C FORWARD -i ${interfaceName} -j ${CHAIN_NAME} 2>/dev/null || iptables -I FORWARD 1 -i ${interfaceName} -j ${CHAIN_NAME}` |
|||
); |
|||
await exec( |
|||
`ip6tables -C FORWARD -i ${interfaceName} -j ${CHAIN_NAME} 2>/dev/null || ip6tables -I FORWARD 1 -i ${interfaceName} -j ${CHAIN_NAME}` |
|||
); |
|||
}, |
|||
|
|||
/** |
|||
* Flush all rules in the custom chain |
|||
*/ |
|||
async flushChain(): Promise<void> { |
|||
FW_DEBUG(`Flushing firewall chain ${CHAIN_NAME}`); |
|||
await exec(`iptables -F ${CHAIN_NAME} 2>/dev/null || true`); |
|||
await exec(`ip6tables -F ${CHAIN_NAME} 2>/dev/null || true`); |
|||
}, |
|||
|
|||
/** |
|||
* Apply firewall rules for a single client |
|||
*/ |
|||
async applyClientRules( |
|||
client: ClientType, |
|||
defaultAllowedIps: string[], |
|||
enableIpv6: boolean |
|||
): Promise<void> { |
|||
// Determine which IPs to use for firewall rules
|
|||
// Priority: firewallIps > allowedIps > defaultAllowedIps
|
|||
const effectiveIps = |
|||
client.firewallIps && client.firewallIps.length > 0 |
|||
? client.firewallIps |
|||
: client.allowedIps ?? defaultAllowedIps; |
|||
|
|||
FW_DEBUG( |
|||
`Applying firewall rules for client ${client.name} (${client.id}): ${effectiveIps.join(', ')}` |
|||
); |
|||
|
|||
for (const ipEntry of effectiveIps) { |
|||
const parsed = parseFirewallEntry(ipEntry); |
|||
const destIsIpv6 = isIPv6(parsed.ip.split('/')[0]); // Handle CIDR by checking base IP
|
|||
|
|||
if (destIsIpv6) { |
|||
if (enableIpv6) { |
|||
const rules = generateRuleArgs(client.ipv6Address, parsed); |
|||
for (const rule of rules) { |
|||
await exec(`ip6tables ${rule}`); |
|||
} |
|||
} |
|||
} else { |
|||
const rules = generateRuleArgs(client.ipv4Address, parsed); |
|||
for (const rule of rules) { |
|||
await exec(`iptables ${rule}`); |
|||
} |
|||
} |
|||
} |
|||
}, |
|||
|
|||
/** |
|||
* Full rebuild of firewall rules from database state |
|||
*/ |
|||
async rebuildRules( |
|||
wgInterface: InterfaceType, |
|||
clients: ClientType[], |
|||
userConfig: UserConfigType, |
|||
enableIpv6: boolean |
|||
): Promise<void> { |
|||
if (!wgInterface.firewallEnabled) { |
|||
FW_DEBUG('Firewall filtering disabled, removing any existing rules'); |
|||
await this.removeFiltering(wgInterface.name); |
|||
return; |
|||
} |
|||
|
|||
// Handle concurrent rebuilds with queue
|
|||
if (rebuildInProgress) { |
|||
FW_DEBUG('Rebuild already in progress, queuing'); |
|||
rebuildQueued = true; |
|||
return; |
|||
} |
|||
|
|||
rebuildInProgress = true; |
|||
|
|||
try { |
|||
FW_DEBUG('Rebuilding firewall rules...'); |
|||
|
|||
// Initialize chain structure
|
|||
await this.initChain(wgInterface.name); |
|||
|
|||
// Flush existing rules
|
|||
await this.flushChain(); |
|||
|
|||
// Apply rules for each enabled client
|
|||
for (const client of clients) { |
|||
if (!client.enabled) continue; |
|||
await this.applyClientRules(client, userConfig.defaultAllowedIps, enableIpv6); |
|||
} |
|||
|
|||
// Add final DROP for any traffic not explicitly allowed
|
|||
await exec(`iptables -A ${CHAIN_NAME} -j DROP`); |
|||
if (enableIpv6) { |
|||
await exec(`ip6tables -A ${CHAIN_NAME} -j DROP`); |
|||
} |
|||
|
|||
FW_DEBUG('Firewall rules rebuilt successfully'); |
|||
} finally { |
|||
rebuildInProgress = false; |
|||
|
|||
// If another rebuild was queued, run it now
|
|||
if (rebuildQueued) { |
|||
rebuildQueued = false; |
|||
FW_DEBUG('Processing queued rebuild'); |
|||
await this.rebuildRules(wgInterface, clients, userConfig, enableIpv6); |
|||
} |
|||
} |
|||
}, |
|||
|
|||
/** |
|||
* Remove all firewall filtering (when feature is disabled) |
|||
*/ |
|||
async removeFiltering(interfaceName: string): Promise<void> { |
|||
FW_DEBUG(`Removing firewall filtering for interface ${interfaceName}`); |
|||
|
|||
// Remove jump rules from FORWARD chain
|
|||
await exec( |
|||
`iptables -D FORWARD -i ${interfaceName} -j ${CHAIN_NAME} 2>/dev/null || true` |
|||
); |
|||
await exec( |
|||
`ip6tables -D FORWARD -i ${interfaceName} -j ${CHAIN_NAME} 2>/dev/null || true` |
|||
); |
|||
|
|||
// Flush and delete the chain
|
|||
await exec(`iptables -F ${CHAIN_NAME} 2>/dev/null || true`); |
|||
await exec(`ip6tables -F ${CHAIN_NAME} 2>/dev/null || true`); |
|||
await exec(`iptables -X ${CHAIN_NAME} 2>/dev/null || true`); |
|||
await exec(`ip6tables -X ${CHAIN_NAME} 2>/dev/null || true`); |
|||
}, |
|||
}; |
|||
Loading…
Reference in new issue