feat(network): add configurable VM egress firewall policies and WireGuard-based host routing

This commit is contained in:
2026-05-01 18:32:08 +00:00
parent 69e66cba00
commit 8c8b692fc1
7 changed files with 998 additions and 57 deletions
+1 -1
View File
@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartvm',
version: '1.3.1',
version: '1.4.0',
description: 'A TypeScript module wrapping Amazon Firecracker VMM for managing lightweight microVMs'
}
+667 -50
View File
@@ -1,5 +1,13 @@
import * as plugins from './plugins.js';
import type { INetworkManagerOptions, ITapDevice } from './interfaces/index.js';
import type {
IFirewallConfig,
IFirewallRule,
INetworkManagerOptions,
ITapDevice,
TFirewallAction,
TFirewallProtocol,
TWireGuardConfig,
} from './interfaces/index.js';
import { SmartVMError } from './interfaces/index.js';
type TShellExecResult = Awaited<ReturnType<InstanceType<typeof plugins.smartshell.Smartshell>['execSpawn']>>;
@@ -11,6 +19,17 @@ interface IParsedSubnet {
subnetMask: string;
}
interface IParsedWireGuardConfig {
setConfig: string;
addresses: string[];
mtu?: number;
}
const FIREWALL_ACTION_TO_IPTABLES_TARGET: Record<TFirewallAction, 'ACCEPT' | 'DROP'> = {
allow: 'ACCEPT',
deny: 'DROP',
};
/**
* Manages host networking for Firecracker VMs.
* Creates TAP devices, Linux bridges, and configures NAT for VM internet access.
@@ -26,6 +45,19 @@ export class NetworkManager {
private activeTaps: Map<string, ITapDevice> = new Map();
private bridgeCreated: boolean = false;
private defaultRouteInterface: string | null = null;
private firewall?: IFirewallConfig;
private firewallChainName: string;
private firewallConfigured: boolean = false;
private wireguard?: TWireGuardConfig;
private wireGuardInterface: string | null = null;
private wireGuardManaged: boolean = false;
private wireGuardRouteConfigured: boolean = false;
private wireGuardRouteAdded: boolean = false;
private wireGuardIpRuleAdded: boolean = false;
private wireGuardRouteTable: number | null = null;
private natInterface: string | null = null;
private natConfigured: boolean = false;
private natRuleAdded: boolean = false;
private shell: InstanceType<typeof plugins.smartshell.Smartshell>;
constructor(options: INetworkManagerOptions = {}) {
@@ -40,6 +72,11 @@ export class NetworkManager {
this.gatewayIp = this.intToIp(parsedSubnet.networkAddress + 1);
this.nextIpAddress = parsedSubnet.networkAddress + 2;
this.lastUsableIpAddress = parsedSubnet.broadcastAddress - 1;
this.firewall = options.firewall;
this.wireguard = options.wireguard;
this.firewallChainName = this.buildFirewallChainName(this.bridgeName, this.subnetBase, this.subnetCidr);
this.validateFirewallConfig(this.firewall);
this.validateWireGuardConfig(this.wireguard);
this.shell = new plugins.smartshell.Smartshell({ executor: 'bash' });
}
@@ -114,7 +151,7 @@ export class NetworkManager {
}
private validateInterfaceName(name: string, fieldName: string): void {
if (!/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,14}$/.test(name)) {
if (typeof name !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,14}$/.test(name)) {
throw new SmartVMError(
`${fieldName} '${name}' is not a valid Linux interface name`,
'INVALID_INTERFACE_NAME',
@@ -122,6 +159,297 @@ export class NetworkManager {
}
}
private buildFirewallChainName(bridgeName: string, subnetBase: string, subnetCidr: number): string {
const hash = plugins.crypto
.createHash('sha256')
.update(`${bridgeName}:${subnetBase}/${subnetCidr}`)
.digest('hex')
.slice(0, 10);
return `SVMEG-${hash}`;
}
private getSubnetCidr(): string {
return `${this.subnetBase}/${this.subnetCidr}`;
}
private validateIpv4Cidr(value: string, fieldName: string, errorCode = 'INVALID_FIREWALL_CONFIG'): void {
const [ip, cidrText, extra] = value.split('/');
const cidr = cidrText === undefined || cidrText === '' ? 32 : Number(cidrText);
if (!ip || extra !== undefined || !Number.isInteger(cidr) || cidr < 0 || cidr > 32) {
throw new SmartVMError(
`${fieldName} '${value}' must be an IPv4 address or CIDR with prefix length 0-32`,
errorCode,
);
}
try {
this.ipToInt(ip);
} catch (err) {
if (err instanceof SmartVMError) {
throw new SmartVMError(
`${fieldName} '${value}' must be an IPv4 address or CIDR with prefix length 0-32`,
errorCode,
);
}
throw err;
}
}
private normalizeCidr(value: string): string {
return value.includes('/') ? value : `${value}/32`;
}
private validateFirewallConfig(firewall?: IFirewallConfig): void {
if (!firewall || firewall.egress === undefined) {
return;
}
const egress = firewall.egress;
if (!egress || typeof egress !== 'object') {
throw new SmartVMError('Firewall egress config must be an object', 'INVALID_FIREWALL_CONFIG');
}
if (
egress.defaultAction !== undefined &&
egress.defaultAction !== 'allow' &&
egress.defaultAction !== 'deny'
) {
throw new SmartVMError(
`Invalid firewall egress defaultAction '${egress.defaultAction}'`,
'INVALID_FIREWALL_CONFIG',
);
}
if (egress.rules !== undefined && !Array.isArray(egress.rules)) {
throw new SmartVMError('Firewall egress rules must be an array', 'INVALID_FIREWALL_CONFIG');
}
for (const rule of egress.rules || []) {
this.validateFirewallRule(rule);
}
}
private validateFirewallRule(rule: IFirewallRule): void {
if (!rule || typeof rule !== 'object') {
throw new SmartVMError('Firewall rule must be an object', 'INVALID_FIREWALL_CONFIG');
}
if (rule.action !== 'allow' && rule.action !== 'deny') {
throw new SmartVMError(
`Invalid firewall rule action '${rule.action}'`,
'INVALID_FIREWALL_CONFIG',
);
}
const protocol = rule.protocol || 'all';
if (!['all', 'tcp', 'udp', 'icmp'].includes(protocol)) {
throw new SmartVMError(
`Invalid firewall rule protocol '${protocol}'`,
'INVALID_FIREWALL_CONFIG',
);
}
if (rule.to !== undefined) {
if (typeof rule.to !== 'string') {
throw new SmartVMError('Firewall rule destination must be a string', 'INVALID_FIREWALL_CONFIG');
}
this.validateIpv4Cidr(rule.to, 'firewall rule destination');
}
if (rule.comment !== undefined && typeof rule.comment !== 'string') {
throw new SmartVMError('Firewall rule comment must be a string', 'INVALID_FIREWALL_CONFIG');
}
const ports = this.normalizePorts(rule.ports);
if (ports.length > 0 && protocol !== 'tcp' && protocol !== 'udp') {
throw new SmartVMError(
'Firewall rule ports require protocol tcp or udp',
'INVALID_FIREWALL_CONFIG',
);
}
}
private normalizePorts(ports?: number | number[]): number[] {
if (ports === undefined) {
return [];
}
const portList = Array.isArray(ports) ? ports : [ports];
if (portList.length === 0) {
throw new SmartVMError('Firewall rule ports must not be empty', 'INVALID_FIREWALL_CONFIG');
}
for (const port of portList) {
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new SmartVMError(
`Firewall rule port '${port}' must be an integer between 1 and 65535`,
'INVALID_FIREWALL_CONFIG',
);
}
}
return portList;
}
private validateWireGuardConfig(wireguard?: TWireGuardConfig): void {
if (!wireguard) {
return;
}
const routeTable = wireguard.routeTable === undefined ? 51820 : wireguard.routeTable;
if (!Number.isInteger(routeTable) || routeTable < 1 || routeTable > 4294967295) {
throw new SmartVMError(
`WireGuard routeTable '${routeTable}' must be an integer between 1 and 4294967295`,
'INVALID_WIREGUARD_CONFIG',
);
}
const wireguardOptions = wireguard as unknown as Record<string, unknown>;
const hasExistingInterface = Object.prototype.hasOwnProperty.call(wireguardOptions, 'existingInterface');
const hasManagedConfig = Object.prototype.hasOwnProperty.call(wireguardOptions, 'config');
if (hasExistingInterface && hasManagedConfig) {
throw new SmartVMError(
'WireGuard config must use either existingInterface or managed config, not both',
'INVALID_WIREGUARD_CONFIG',
);
}
if (hasExistingInterface) {
this.validateInterfaceName(wireguardOptions.existingInterface as string, 'wireguard.existingInterface');
return;
}
if (typeof wireguardOptions.config !== 'string') {
throw new SmartVMError('WireGuard managed config requires config text', 'INVALID_WIREGUARD_CONFIG');
}
const interfaceName = wireguardOptions.interfaceName === undefined
? 'svwg0'
: wireguardOptions.interfaceName;
this.validateInterfaceName(interfaceName as string, 'wireguard.interfaceName');
this.parseWireGuardConfig(wireguardOptions.config);
}
private parseWireGuardConfig(config: string): IParsedWireGuardConfig {
if (!config || !config.trim()) {
throw new SmartVMError('WireGuard config must not be empty', 'INVALID_WIREGUARD_CONFIG');
}
const unsafeFields = new Set(['preup', 'postup', 'predown', 'postdown', 'saveconfig']);
const ignoredFields = new Set(['address', 'dns', 'mtu', 'table']);
const wireGuardInterfaceFields = new Set(['privatekey', 'listenport', 'fwmark']);
const wireGuardPeerFields = new Set([
'publickey',
'presharedkey',
'allowedips',
'endpoint',
'persistentkeepalive',
]);
const setConfigLines: string[] = [];
const addresses: string[] = [];
let mtu: number | undefined;
let currentSection: 'Interface' | 'Peer' | null = null;
let sawPrivateKey = false;
for (const rawLine of config.split(/\r?\n/)) {
const trimmedLine = rawLine.trim();
if (!trimmedLine || trimmedLine.startsWith('#') || trimmedLine.startsWith(';')) {
continue;
}
const lineWithoutComment = trimmedLine.replace(/\s+[;#].*$/, '').trim();
if (!lineWithoutComment) {
continue;
}
const sectionMatch = lineWithoutComment.match(/^\[(Interface|Peer)\]$/i);
if (sectionMatch) {
currentSection = sectionMatch[1].toLowerCase() === 'interface' ? 'Interface' : 'Peer';
setConfigLines.push(`[${currentSection}]`);
continue;
}
const keyValueMatch = lineWithoutComment.match(/^([^=]+?)\s*=\s*(.+)$/);
if (!keyValueMatch || !currentSection) {
throw new SmartVMError(
`Invalid WireGuard config line '${rawLine.trim()}'`,
'INVALID_WIREGUARD_CONFIG',
);
}
const key = keyValueMatch[1].trim();
const normalizedKey = key.toLowerCase();
const value = keyValueMatch[2].trim();
if (unsafeFields.has(normalizedKey)) {
throw new SmartVMError(
`WireGuard config field '${key}' is not allowed because it can execute commands or mutate host state`,
'INVALID_WIREGUARD_CONFIG',
);
}
if (currentSection === 'Interface' && normalizedKey === 'address') {
for (const address of value.split(',').map((item) => item.trim()).filter(Boolean)) {
this.validateIpv4Cidr(address, 'WireGuard Address', 'INVALID_WIREGUARD_CONFIG');
addresses.push(this.normalizeCidr(address));
}
continue;
}
if (currentSection === 'Interface' && normalizedKey === 'mtu') {
const parsedMtu = Number(value);
if (!Number.isInteger(parsedMtu) || parsedMtu < 576 || parsedMtu > 9000) {
throw new SmartVMError(
`WireGuard MTU '${value}' must be an integer between 576 and 9000`,
'INVALID_WIREGUARD_CONFIG',
);
}
mtu = parsedMtu;
continue;
}
if (currentSection === 'Peer' && normalizedKey === 'allowedips') {
const allowedIps = value.split(',').map((item) => item.trim()).filter(Boolean);
if (allowedIps.length === 0) {
throw new SmartVMError('WireGuard Peer.AllowedIPs must not be empty', 'INVALID_WIREGUARD_CONFIG');
}
for (const allowedIp of allowedIps) {
this.validateIpv4Cidr(allowedIp, 'WireGuard AllowedIPs', 'INVALID_WIREGUARD_CONFIG');
}
setConfigLines.push(`${key} = ${allowedIps.join(', ')}`);
continue;
}
if (ignoredFields.has(normalizedKey)) {
continue;
}
const allowedFields = currentSection === 'Interface'
? wireGuardInterfaceFields
: wireGuardPeerFields;
if (!allowedFields.has(normalizedKey)) {
throw new SmartVMError(
`Unsupported WireGuard ${currentSection} field '${key}'`,
'INVALID_WIREGUARD_CONFIG',
);
}
if (currentSection === 'Interface' && normalizedKey === 'privatekey') {
sawPrivateKey = true;
}
setConfigLines.push(`${key} = ${value}`);
}
if (!sawPrivateKey) {
throw new SmartVMError('WireGuard config requires Interface.PrivateKey', 'INVALID_WIREGUARD_CONFIG');
}
if (addresses.length === 0) {
throw new SmartVMError('WireGuard config requires at least one IPv4 Interface.Address', 'INVALID_WIREGUARD_CONFIG');
}
return {
setConfig: `${setConfigLines.join('\n')}\n`,
addresses,
mtu,
};
}
/**
* Allocate the next available IP address in the subnet.
*/
@@ -209,18 +537,263 @@ export class NetworkManager {
return iface;
}
private getSharedMemoryTempDir(): string {
try {
if (plugins.fs.existsSync('/dev/shm') && plugins.fs.statSync('/dev/shm').isDirectory()) {
return '/dev/shm';
}
} catch {
// Fall through to os.tmpdir().
}
return plugins.os.tmpdir();
}
private async configureWireGuardEgress(): Promise<string> {
if (!this.wireguard || this.wireguard.routeAllVmTraffic === false) {
return this.getDefaultRouteInterface();
}
try {
const iface = await this.ensureWireGuardInterface();
const routeTable = this.wireguard.routeTable === undefined ? 51820 : this.wireguard.routeTable;
this.wireGuardInterface = iface;
this.wireGuardRouteTable = routeTable;
this.wireGuardRouteAdded = false;
this.wireGuardIpRuleAdded = false;
const routeResult = await this.run('ip', ['route', 'show', 'table', String(routeTable), 'default']);
const existingDefaultRoutes = routeResult.stdout
.split('\n')
.map((line) => line.trim())
.filter(Boolean);
if (existingDefaultRoutes.some((line) => !line.includes(` dev ${iface} `) && !line.endsWith(` dev ${iface}`))) {
throw new SmartVMError(
`WireGuard route table ${routeTable} already has a default route not using ${iface}`,
'WIREGUARD_SETUP_FAILED',
);
}
if (existingDefaultRoutes.length === 0) {
await this.runChecked('ip', [
'route',
'add',
'default',
'dev',
iface,
'table',
String(routeTable),
]);
this.wireGuardRouteAdded = true;
}
this.wireGuardRouteConfigured = true;
if (!await this.hasWireGuardIpRule(routeTable)) {
await this.runChecked('ip', [
'rule',
'add',
'from',
this.getSubnetCidr(),
'table',
String(routeTable),
]);
this.wireGuardIpRuleAdded = true;
}
return iface;
} catch (err) {
if (err instanceof SmartVMError) {
throw err;
}
const message = err instanceof Error ? err.message : String(err);
throw new SmartVMError(`Failed to configure WireGuard egress: ${message}`, 'WIREGUARD_SETUP_FAILED');
}
}
private async hasWireGuardIpRule(routeTable: number): Promise<boolean> {
const result = await this.run('ip', ['rule', 'show']);
return result.stdout
.split('\n')
.some((line) => line.includes(`from ${this.getSubnetCidr()}`) && line.includes(`lookup ${routeTable}`));
}
private async ensureWireGuardInterface(): Promise<string> {
if (!this.wireguard) {
throw new Error('WireGuard is not configured');
}
if ('existingInterface' in this.wireguard) {
await this.runChecked('ip', ['link', 'show', this.wireguard.existingInterface]);
this.wireGuardManaged = false;
return this.wireguard.existingInterface;
}
const iface = this.wireguard.interfaceName || 'svwg0';
const existingInterface = await this.run('ip', ['link', 'show', iface]);
if (existingInterface.exitCode === 0) {
throw new SmartVMError(
`Managed WireGuard interface '${iface}' already exists; use existingInterface to route through it`,
'WIREGUARD_SETUP_FAILED',
);
}
const parsedConfig = this.parseWireGuardConfig(this.wireguard.config);
await this.runChecked('ip', ['link', 'add', 'dev', iface, 'type', 'wireguard']);
this.wireGuardManaged = true;
this.wireGuardInterface = iface;
const tempDir = await plugins.fs.promises.mkdtemp(
plugins.path.join(this.getSharedMemoryTempDir(), `smartvm-wg-${iface}-`),
);
const tempConfigPath = plugins.path.join(tempDir, 'wg.conf');
try {
await plugins.fs.promises.writeFile(tempConfigPath, parsedConfig.setConfig, { mode: 0o600 });
await this.runChecked('wg', ['setconf', iface, tempConfigPath]);
} finally {
await plugins.fs.promises.rm(tempDir, { recursive: true, force: true });
}
for (const address of parsedConfig.addresses) {
await this.runChecked('ip', ['addr', 'add', address, 'dev', iface]);
}
if (parsedConfig.mtu !== undefined) {
await this.runChecked('ip', ['link', 'set', 'mtu', String(parsedConfig.mtu), 'dev', iface]);
}
await this.runChecked('ip', ['link', 'set', iface, 'up']);
return iface;
}
private shouldApplyFailClosed(): boolean {
return Boolean(
this.wireguard &&
this.wireguard.routeAllVmTraffic !== false &&
this.wireguard.failClosed !== false &&
this.wireGuardInterface,
);
}
private async setupNat(egressInterface: string): Promise<void> {
this.natRuleAdded = false;
const ruleArgs = [
'-s',
this.getSubnetCidr(),
'-o',
egressInterface,
'-j',
'MASQUERADE',
];
const checkResult = await this.run('iptables', ['-t', 'nat', '-C', 'POSTROUTING', ...ruleArgs]);
if (checkResult.exitCode !== 0) {
await this.runChecked('iptables', ['-t', 'nat', '-A', 'POSTROUTING', ...ruleArgs]);
this.natRuleAdded = true;
}
this.natInterface = egressInterface;
this.natConfigured = true;
}
private async setupEgressFirewall(egressInterface: string): Promise<void> {
const egress = this.firewall?.egress;
const shouldSetupFirewall = Boolean(egress || this.shouldApplyFailClosed());
if (!shouldSetupFirewall) {
return;
}
await this.ensureIptablesChain('filter', this.firewallChainName);
this.firewallConfigured = true;
await this.runChecked('iptables', ['-t', 'filter', '-F', this.firewallChainName]);
await this.ensureIptablesRule('filter', 'FORWARD', ['-s', this.getSubnetCidr(), '-j', this.firewallChainName]);
await this.runChecked('iptables', [
'-t',
'filter',
'-A',
this.firewallChainName,
'-m',
'conntrack',
'--ctstate',
'ESTABLISHED,RELATED',
'-j',
'ACCEPT',
]);
if (this.shouldApplyFailClosed()) {
await this.runChecked('iptables', [
'-t',
'filter',
'-A',
this.firewallChainName,
'!',
'-o',
egressInterface,
'-j',
'DROP',
]);
}
for (const rule of egress?.rules || []) {
for (const ruleArgs of this.buildFirewallRuleArgs(rule)) {
await this.runChecked('iptables', ['-t', 'filter', '-A', this.firewallChainName, ...ruleArgs]);
}
}
const defaultAction = egress?.defaultAction || 'allow';
await this.runChecked('iptables', [
'-t',
'filter',
'-A',
this.firewallChainName,
'-j',
FIREWALL_ACTION_TO_IPTABLES_TARGET[defaultAction],
]);
}
private buildFirewallRuleArgs(rule: IFirewallRule): string[][] {
const baseArgs: string[] = [];
const protocol = rule.protocol || 'all';
if (rule.to !== undefined) {
baseArgs.push('-d', this.normalizeCidr(rule.to));
}
if (protocol !== 'all') {
baseArgs.push('-p', protocol);
}
if (rule.comment) {
baseArgs.push('-m', 'comment', '--comment', rule.comment.slice(0, 240));
}
const target = FIREWALL_ACTION_TO_IPTABLES_TARGET[rule.action];
const ports = this.normalizePorts(rule.ports);
if (ports.length === 0) {
return [[...baseArgs, '-j', target]];
}
return ports.map((port) => [...baseArgs, '--dport', String(port), '-j', target]);
}
private async ensureIptablesChain(table: string, chain: string): Promise<void> {
const checkResult = await this.run('iptables', ['-t', table, '-S', chain]);
if (checkResult.exitCode !== 0) {
await this.runChecked('iptables', ['-t', table, '-N', chain]);
}
}
private async ensureIptablesRule(table: string, chain: string, ruleArgs: string[]): Promise<void> {
const checkResult = await this.run('iptables', ['-t', table, '-C', chain, ...ruleArgs]);
if (checkResult.exitCode !== 0) {
await this.runChecked('iptables', ['-t', table, '-A', chain, ...ruleArgs]);
}
}
private async deleteIptablesRule(table: string, chain: string, ruleArgs: string[]): Promise<void> {
await this.run('iptables', ['-t', table, '-D', chain, ...ruleArgs]);
}
/**
* Ensure the Linux bridge is created and configured.
*/
public async ensureBridge(): Promise<void> {
if (this.bridgeCreated) return;
let createdBridge = false;
try {
// Check if bridge already exists
const result = await this.run('ip', ['link', 'show', this.bridgeName]);
if (result.exitCode !== 0) {
// Create bridge
await this.runChecked('ip', ['link', 'add', this.bridgeName, 'type', 'bridge']);
createdBridge = true;
await this.runChecked('ip', ['addr', 'add', `${this.gatewayIp}/${this.subnetCidr}`, 'dev', this.bridgeName]);
await this.runChecked('ip', ['link', 'set', this.bridgeName, 'up']);
}
@@ -228,38 +801,26 @@ export class NetworkManager {
// Enable IP forwarding
await this.runChecked('sysctl', ['-w', 'net.ipv4.ip_forward=1']);
// Set up NAT masquerade (idempotent with -C check)
const defaultIface = await this.getDefaultRouteInterface();
const natArgs = [
'-t',
'nat',
'-C',
'POSTROUTING',
'-s',
`${this.subnetBase}/${this.subnetCidr}`,
'-o',
defaultIface,
'-j',
'MASQUERADE',
];
const checkResult = await this.run('iptables', natArgs);
if (checkResult.exitCode !== 0) {
await this.runChecked('iptables', [
'-t',
'nat',
'-A',
'POSTROUTING',
'-s',
`${this.subnetBase}/${this.subnetCidr}`,
'-o',
defaultIface,
'-j',
'MASQUERADE',
]);
}
const egressInterface = await this.configureWireGuardEgress();
await this.setupEgressFirewall(egressInterface);
await this.setupNat(egressInterface);
this.bridgeCreated = true;
} catch (err) {
try {
await this.cleanupEgressFirewall();
await this.cleanupNat();
await this.cleanupWireGuardEgress();
if (createdBridge) {
await this.run('ip', ['link', 'set', this.bridgeName, 'down']);
await this.run('ip', ['link', 'del', this.bridgeName]);
}
} catch {
// Preserve the original setup error.
}
if (err instanceof SmartVMError) {
throw err;
}
const message = err instanceof Error ? err.message : String(err);
throw new SmartVMError(
`Failed to set up network bridge: ${message}`,
@@ -349,6 +910,10 @@ export class NetworkManager {
await this.removeTapDevice(tapName);
}
await this.cleanupEgressFirewall();
await this.cleanupNat();
await this.cleanupWireGuardEgress();
// Remove bridge if we created it
if (this.bridgeCreated) {
try {
@@ -358,26 +923,78 @@ export class NetworkManager {
// Bridge may already be gone
}
// Remove NAT rule
try {
const defaultIface = this.defaultRouteInterface || await this.getDefaultRouteInterface();
await this.run('iptables', [
'-t',
'nat',
'-D',
'POSTROUTING',
'-s',
`${this.subnetBase}/${this.subnetCidr}`,
'-o',
defaultIface,
'-j',
'MASQUERADE',
]);
} catch {
// Rule may not exist
}
this.bridgeCreated = false;
}
}
private async cleanupEgressFirewall(): Promise<void> {
if (!this.firewallConfigured) {
return;
}
await this.deleteIptablesRule('filter', 'FORWARD', [
'-s',
this.getSubnetCidr(),
'-j',
this.firewallChainName,
]);
await this.run('iptables', ['-t', 'filter', '-F', this.firewallChainName]);
await this.run('iptables', ['-t', 'filter', '-X', this.firewallChainName]);
this.firewallConfigured = false;
}
private async cleanupNat(): Promise<void> {
if (!this.natConfigured || !this.natInterface) {
return;
}
if (this.natRuleAdded) {
await this.deleteIptablesRule('nat', 'POSTROUTING', [
'-s',
this.getSubnetCidr(),
'-o',
this.natInterface,
'-j',
'MASQUERADE',
]);
}
this.natInterface = null;
this.natConfigured = false;
this.natRuleAdded = false;
}
private async cleanupWireGuardEgress(): Promise<void> {
if (this.wireGuardRouteConfigured && this.wireGuardRouteTable !== null) {
if (this.wireGuardIpRuleAdded) {
await this.run('ip', [
'rule',
'del',
'from',
this.getSubnetCidr(),
'table',
String(this.wireGuardRouteTable),
]);
}
if (this.wireGuardRouteAdded && this.wireGuardInterface) {
await this.run('ip', [
'route',
'del',
'default',
'dev',
this.wireGuardInterface,
'table',
String(this.wireGuardRouteTable),
]);
}
}
if (this.wireGuardManaged && this.wireGuardInterface) {
await this.run('ip', ['link', 'del', this.wireGuardInterface]);
}
this.wireGuardRouteConfigured = false;
this.wireGuardRouteAdded = false;
this.wireGuardIpRuleAdded = false;
this.wireGuardRouteTable = null;
this.wireGuardManaged = false;
this.wireGuardInterface = null;
}
}
+2
View File
@@ -45,6 +45,8 @@ export class SmartVM {
this.networkManager = new NetworkManager({
bridgeName: this.options.bridgeName,
subnet: this.options.subnet,
firewall: this.options.firewall,
wireguard: this.options.wireguard,
});
// If a custom binary path is provided, use it directly
+69
View File
@@ -20,6 +20,10 @@ export interface ISmartVMOptions {
bridgeName?: string;
/** Network subnet in CIDR notation. Defaults to '172.30.0.0/24'. */
subnet?: string;
/** VM egress firewall configuration. */
firewall?: IFirewallConfig;
/** Host-side WireGuard egress routing configuration for VM traffic. */
wireguard?: TWireGuardConfig;
/** Directory for cached base images. Defaults to /tmp/.smartvm/base-images. */
baseImageCacheDir?: string;
/** Maximum number of cached base image bundles. Defaults to 2. */
@@ -153,6 +157,67 @@ export interface IMicroVMRuntimeOptions {
ephemeralWritableDrives?: boolean;
}
/** Firewall action for VM egress traffic. */
export type TFirewallAction = 'allow' | 'deny';
/** Firewall protocol selector for VM egress traffic. */
export type TFirewallProtocol = 'all' | 'tcp' | 'udp' | 'icmp';
/** One ordered VM egress firewall rule. */
export interface IFirewallRule {
/** Rule action. */
action: TFirewallAction;
/** Destination IPv4 address or CIDR. Omit to match all destinations. */
to?: string;
/** Protocol to match. Defaults to all. */
protocol?: TFirewallProtocol;
/** Destination port or ports for tcp/udp rules. */
ports?: number | number[];
/** Optional human-readable rule label. */
comment?: string;
}
/** VM egress firewall policy. */
export interface IFirewallEgressConfig {
/** Final action when no rule matches. Defaults to allow. */
defaultAction?: TFirewallAction;
/** Ordered rules; first match wins. */
rules?: IFirewallRule[];
}
/** Firewall configuration. */
export interface IFirewallConfig {
/** Egress firewall for traffic leaving the VM subnet. */
egress?: IFirewallEgressConfig;
}
/** Common WireGuard routing options. */
export interface IWireGuardBaseConfig {
/** Route all VM subnet traffic through this WireGuard interface. Defaults to true. */
routeAllVmTraffic?: boolean;
/** Drop VM traffic that would leave through a non-WireGuard interface. Defaults to true. */
failClosed?: boolean;
/** Linux routing table number for VM WireGuard egress. Defaults to 51820. */
routeTable?: number;
}
/** Managed WireGuard interface created and removed by smartvm. */
export interface IWireGuardManagedConfig extends IWireGuardBaseConfig {
/** wg-quick-style WireGuard config text. Hook fields are rejected. */
config: string;
/** Interface name to create. Defaults to svwg0. */
interfaceName?: string;
}
/** Existing WireGuard interface owned outside smartvm. */
export interface IWireGuardExistingInterfaceConfig extends IWireGuardBaseConfig {
/** Existing WireGuard interface to route VM traffic through. */
existingInterface: string;
}
/** WireGuard egress configuration. */
export type TWireGuardConfig = IWireGuardManagedConfig | IWireGuardExistingInterfaceConfig;
/**
* Firecracker boot source configuration.
*/
@@ -353,6 +418,10 @@ export interface INetworkManagerOptions {
bridgeName?: string;
/** Subnet in CIDR notation. Defaults to '172.30.0.0/24'. */
subnet?: string;
/** VM egress firewall configuration. */
firewall?: IFirewallConfig;
/** Host-side WireGuard egress routing configuration for VM traffic. */
wireguard?: TWireGuardConfig;
}
/**