Initial commit
🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
176
lib/wireguard/peers.dart
Normal file
176
lib/wireguard/peers.dart
Normal file
@@ -0,0 +1,176 @@
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:waylume_server/utils.dart';
|
||||
import 'package:waylume_server/wireguard/utils.dart';
|
||||
|
||||
class WireGuardPeer {
|
||||
final String privateKey;
|
||||
final String publicKey;
|
||||
final String ip;
|
||||
|
||||
WireGuardPeer({
|
||||
required this.privateKey,
|
||||
required this.publicKey,
|
||||
required this.ip,
|
||||
});
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'privateKey': privateKey,
|
||||
'publicKey': publicKey,
|
||||
'ip': ip,
|
||||
};
|
||||
|
||||
factory WireGuardPeer.fromJson(Map<String, dynamic> json) => WireGuardPeer(
|
||||
privateKey: json['privateKey'],
|
||||
publicKey: json['publicKey'],
|
||||
ip: json['ip'],
|
||||
);
|
||||
|
||||
String generateClientConfig({
|
||||
required String serverPublicKey,
|
||||
required String serverEndpoint,
|
||||
String dns = '1.1.1.1, 8.8.8.8', // Cloudflare and Google DNS
|
||||
String allowedIPs = '0.0.0.0/0',
|
||||
}) {
|
||||
return '''
|
||||
[Interface]
|
||||
PrivateKey = $privateKey
|
||||
Address = $ip/32
|
||||
DNS = $dns
|
||||
|
||||
[Peer]
|
||||
PublicKey = $serverPublicKey
|
||||
Endpoint = $serverEndpoint
|
||||
AllowedIPs = $allowedIPs
|
||||
PersistentKeepalive = 25
|
||||
''';
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> generateClientConfig(WireGuardPeer peer) async {
|
||||
|
||||
String server_endpoint = '${await getWanIp()}:51820'; // Assuming default WireGuard port
|
||||
String serverPublicKey = await getServerPublicKey();
|
||||
|
||||
return peer.generateClientConfig(
|
||||
serverPublicKey: serverPublicKey,
|
||||
serverEndpoint: server_endpoint,
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
/// Creates a new WireGuard peer and returns the peer info
|
||||
Future<WireGuardPeer> createPeer() async {
|
||||
// Generate private key
|
||||
final privateKeyResult = await Process.run('wg', ['genkey']);
|
||||
final privateKey = privateKeyResult.stdout.toString().trim();
|
||||
|
||||
// Generate public key from private key
|
||||
final pubProcess = await Process.start('wg', ['pubkey']);
|
||||
pubProcess.stdin.writeln(privateKey);
|
||||
await pubProcess.stdin.close();
|
||||
final publicKey = await pubProcess.stdout.transform(utf8.decoder).join();
|
||||
|
||||
// Get next available IP
|
||||
final ip = await _getNextIP();
|
||||
|
||||
// Add peer to WireGuard
|
||||
await Process.run('wg', ['set', 'wg0', 'peer', publicKey.trim(), 'allowed-ips', '$ip/32']);
|
||||
|
||||
return WireGuardPeer(
|
||||
privateKey: privateKey,
|
||||
publicKey: publicKey.trim(),
|
||||
ip: ip,
|
||||
);
|
||||
}
|
||||
|
||||
Future<bool> deletePeer(String publicKey) async {
|
||||
// Remove peer from WireGuard
|
||||
final result = await Process.run('wg', ['set', 'wg0', 'peer', publicKey, 'remove']);
|
||||
if (result.exitCode != 0) {
|
||||
print('Error removing peer: ${result.stderr}');
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<void> setSpeedLimit(String publicKey, int speedKbps) async {
|
||||
final peerIP = await _getPeerIP(publicKey);
|
||||
if (peerIP == null) throw Exception('Peer not found');
|
||||
|
||||
final mark = _getMarkForIP(peerIP);
|
||||
|
||||
await Process.run('iptables', ['-I', 'FORWARD', '-s', peerIP, '-j', 'MARK', '--set-mark', mark.toString()]);
|
||||
await Process.run('iptables', ['-I', 'FORWARD', '-d', peerIP, '-j', 'MARK', '--set-mark', mark.toString()]);
|
||||
await Process.run('tc', ['class', 'add', 'dev', 'wg0', 'parent', '1:1', 'classid', '1:$mark', 'htb', 'rate', '${speedKbps}kbit', 'ceil', '${speedKbps}kbit']);
|
||||
await Process.run('tc', ['filter', 'add', 'dev', 'wg0', 'protocol', 'ip', 'parent', '1:', 'prio', '1', 'handle', mark.toString(), 'fw', 'flowid', '1:$mark']);
|
||||
}
|
||||
|
||||
Future<void> setDataCap(String publicKey, int dataCapMB) async {
|
||||
final peerIP = await _getPeerIP(publicKey);
|
||||
if (peerIP == null) throw Exception('Peer not found');
|
||||
|
||||
final quotaBytes = dataCapMB * 1024 * 1024;
|
||||
await Process.run('iptables', ['-I', 'FORWARD', '-s', peerIP, '-m', 'quota', '--quota', quotaBytes.toString(), '-j', 'ACCEPT']);
|
||||
await Process.run('iptables', ['-I', 'FORWARD', '-d', peerIP, '-m', 'quota', '--quota', quotaBytes.toString(), '-j', 'ACCEPT']);
|
||||
await Process.run('iptables', ['-A', 'FORWARD', '-s', peerIP, '-j', 'DROP']);
|
||||
await Process.run('iptables', ['-A', 'FORWARD', '-d', peerIP, '-j', 'DROP']);
|
||||
}
|
||||
|
||||
Future<String?> _getPeerIP(String publicKey) async {
|
||||
final result = await Process.run('wg', ['show', 'wg0', 'allowed-ips']);
|
||||
if (result.exitCode != 0) return null;
|
||||
|
||||
final lines = result.stdout.toString().split('\n');
|
||||
for (final line in lines) {
|
||||
if (line.contains(publicKey)) {
|
||||
final match = RegExp(r'(\d+\.\d+\.\d+\.\d+)').firstMatch(line);
|
||||
return match?.group(1);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
int _getMarkForIP(String ip) {
|
||||
return ip.split('.').last.hashCode % 65535 + 1;
|
||||
}
|
||||
|
||||
Future<String> _getNextIP() async {
|
||||
final result = await Process.run('wg', ['show', 'wg0', 'allowed-ips']);
|
||||
final usedIPs = RegExp(r'10\.(\d+)\.(\d+)\.(\d+)')
|
||||
.allMatches(result.stdout.toString())
|
||||
.map((m) => '${m.group(1)}.${m.group(2)}.${m.group(3)}')
|
||||
.toSet();
|
||||
|
||||
// Start from 10.0.0.2 (skip .1 for server)
|
||||
for (int a = 0; a <= 255; a++) {
|
||||
for (int b = 0; b <= 255; b++) {
|
||||
for (int c = (a == 0 && b == 0 ? 2 : 1); c <= 254; c++) {
|
||||
final ip = '10.$a.$b.$c';
|
||||
if (!usedIPs.contains('$a.$b.$c')) return ip;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw Exception('No available IPs');
|
||||
}
|
||||
|
||||
void main() async {
|
||||
try {
|
||||
final peer = await createPeer();
|
||||
print('New WireGuard Peer Created:');
|
||||
print('Private Key: ${peer.privateKey}');
|
||||
print('Public Key: ${peer.publicKey}');
|
||||
print('IP Address: ${peer.ip}');
|
||||
|
||||
// Example usage of generating client config
|
||||
final clientConfig = peer.generateClientConfig(
|
||||
serverPublicKey: 'your_server_public_key',
|
||||
serverEndpoint: 'your_server_endpoint:51820',
|
||||
);
|
||||
print('Client Config:\n$clientConfig');
|
||||
} catch (e) {
|
||||
print('Error creating WireGuard peer: $e');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user