From 241dd6f9fbc7fb424ce0e6bb3185cd55892826ea Mon Sep 17 00:00:00 2001 From: ShareVB Date: Thu, 21 Aug 2025 15:25:44 +0200 Subject: [PATCH] feat(new tool): Wireguard Config Generator Fix #1536 --- package.json | 3 + pnpm-lock.yaml | 25 ++ src/tools/wireguard-config-generator/index.ts | 13 + .../lib/WgConfig.ts | 137 +++++++++ .../lib/types/WgConfigObject.ts | 142 ++++++++++ .../lib/utils/configParser.ts | 259 ++++++++++++++++++ .../lib/utils/createPeerPairs.ts | 36 +++ .../lib/utils/generateKeyPair.ts | 209 ++++++++++++++ .../wireguard-config-generator.vue | 259 ++++++++++++++++++ 9 files changed, 1083 insertions(+) create mode 100644 src/tools/wireguard-config-generator/index.ts create mode 100644 src/tools/wireguard-config-generator/lib/WgConfig.ts create mode 100644 src/tools/wireguard-config-generator/lib/types/WgConfigObject.ts create mode 100644 src/tools/wireguard-config-generator/lib/utils/configParser.ts create mode 100644 src/tools/wireguard-config-generator/lib/utils/createPeerPairs.ts create mode 100644 src/tools/wireguard-config-generator/lib/utils/generateKeyPair.ts create mode 100644 src/tools/wireguard-config-generator/wireguard-config-generator.vue diff --git a/package.json b/package.json index 4dae6358..da8249a9 100644 --- a/package.json +++ b/package.json @@ -204,6 +204,7 @@ "lodash.defaultsdeep": "^4.6.1", "lodash.flattendeep": "^4.4.0", "lodash.last": "^3.0.0", + "lodash.mergewith": "^4.6.2", "long": "^5.3.1", "lorem-ipsum-japanese": "^1.0.1", "luhn-js": "^1.1.2", @@ -256,6 +257,7 @@ "qrcode": "^1.5.4", "qrcode-parser": "^2.1.3", "qrcode-terminal-nooctal": "^0.12.1", + "qrcode-vue3": "^1.7.1", "quicktype-core": "^23.1.3", "randexp": "^0.5.3", "regex": "^4.4.0", @@ -342,6 +344,7 @@ "@types/lodash.defaultsdeep": "^4.6.9", "@types/lodash.flattendeep": "^4.4.9", "@types/lodash.last": "^3.0.9", + "@types/lodash.mergewith": "^4.6.9", "@types/luxon": "^3.4.2", "@types/markdown-it": "^13.0.9", "@types/memorystream": "^0.3.4", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 23f441f3..db651491 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -500,6 +500,9 @@ dependencies: lodash.last: specifier: ^3.0.0 version: 3.0.0 + lodash.mergewith: + specifier: ^4.6.2 + version: 4.6.2 long: specifier: ^5.3.1 version: 5.3.1 @@ -656,6 +659,9 @@ dependencies: qrcode-terminal-nooctal: specifier: ^0.12.1 version: 0.12.1 + qrcode-vue3: + specifier: ^1.7.1 + version: 1.7.1 quicktype-core: specifier: ^23.1.3 version: 23.1.3 @@ -910,6 +916,9 @@ devDependencies: '@types/lodash.last': specifier: ^3.0.9 version: 3.0.9 + '@types/lodash.mergewith': + specifier: ^4.6.9 + version: 4.6.9 '@types/luxon': specifier: ^3.4.2 version: 3.4.2 @@ -6647,6 +6656,12 @@ packages: '@types/lodash': 4.17.20 dev: true + /@types/lodash.mergewith@4.6.9: + resolution: {integrity: sha512-fgkoCAOF47K7sxrQ7Mlud2TH023itugZs2bUg8h/KzT+BnZNrR2jAOmaokbLunHNnobXVWOezAeNn/lZqwxkcw==} + dependencies: + '@types/lodash': 4.17.20 + dev: true + /@types/lodash@4.17.20: resolution: {integrity: sha512-H3MHACvFUEiujabxhaI/ImO6gUrd8oOurg7LQtS7mbwIXA/cUqWrvBsaeJ23aZEPk1TAYkurjfMbSELfoCXlGA==} @@ -13676,6 +13691,10 @@ packages: resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==} dev: true + /lodash.mergewith@4.6.2: + resolution: {integrity: sha512-GK3g5RPZWTRSeLSpgP8Xhra+pnjBC56q9FZYe1d5RN3TJ35dbkGy3YqBSMbyCrlbi+CM9Z3Jk5yTL7RCsqboyQ==} + dev: false + /lodash.sortby@4.7.0: resolution: {integrity: sha512-HDWXG8isMntAyRF5vZ7xKuEvOhT4AhlRt/3czTSjvGUxjYCBVRQY48ViDHyfYz9VIoBkW4TMGQNapx+l3RUwdA==} dev: true @@ -15769,6 +15788,12 @@ packages: hasBin: true dev: false + /qrcode-vue3@1.7.1: + resolution: {integrity: sha512-Xa82NslFJUqsnQbLtc1qO+xPEOeFaTRxktg3ugRd2Pk116kta1X+7GLSEPQj9gor8jWVyfmLmhYZHuANnRZoLQ==} + dependencies: + qrcode-generator: 1.4.4 + dev: false + /qrcode@1.5.4: resolution: {integrity: sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==} engines: {node: '>=10.13.0'} diff --git a/src/tools/wireguard-config-generator/index.ts b/src/tools/wireguard-config-generator/index.ts new file mode 100644 index 00000000..207c777f --- /dev/null +++ b/src/tools/wireguard-config-generator/index.ts @@ -0,0 +1,13 @@ +import { Link } from '@vicons/tabler'; +import { defineTool } from '../tool'; + +export const tool = defineTool({ + name: 'Wireguard Config Generator', + path: '/wireguard-config-generator', + description: 'Generate Wireguard Server and Clients configuration files', + keywords: ['wireguard', 'config', 'generator'], + component: () => import('./wireguard-config-generator.vue'), + icon: Link, + createdAt: new Date('2025-08-15'), + category: 'Network', +}); diff --git a/src/tools/wireguard-config-generator/lib/WgConfig.ts b/src/tools/wireguard-config-generator/lib/WgConfig.ts new file mode 100644 index 00000000..35b5fd7a --- /dev/null +++ b/src/tools/wireguard-config-generator/lib/WgConfig.ts @@ -0,0 +1,137 @@ +import mergeWith from 'lodash.mergewith'; +import { generateConfigString, parseConfigString } from './utils/configParser'; +import type { WgConfigObject, WgConfigPeer } from './types/WgConfigObject'; +import { generateKeyPair } from './utils/generateKeyPair'; + +interface GenerateKeysOptions { + /** Also create a preshared key */ + preSharedKey?: boolean + /** + * Overwrite this object's private key if it already exists + * + * If this is not set to true, a new public key will be generated from the existing private key if + * the private key exists. + */ + overwrite?: boolean +} + +/** A Javascript object representation of a WireGuard config file with some extras */ +export class WgConfig implements WgConfigObject { + /** Defines the VPN settings for the local node. */ + wgInterface: WgConfigObject['wgInterface'] = {}; + /** An array of VPN settings for remote peers */ + peers: WgConfigObject['peers']; + /** A place to keep the public key for this node (it's not saved in the WireGuard config) */ + publicKey: WgConfigObject['publicKey']; + /** A place to keep the pre-shared key for this node (it's not saved in the WireGuard config) */ + preSharedKey: WgConfigObject['preSharedKey']; + /** A place to keep the endpoint for this node (it's not saved in the WireGuard config) */ + endpoint: WgConfigObject['endpoint']; + /** A place to keep the client AllowedIPs for this node (it's not saved in the WireGuard config) */ + clientsAllowedIps: WgConfigObject['clientsAllowedIps']; + + /** creates a new WgConfig */ + constructor(init: Partial) { + if (init?.wgInterface) { + this.wgInterface = init.wgInterface; + } + this.peers = init?.peers || []; + this.preSharedKey = init?.preSharedKey; + this.publicKey = init?.publicKey; + } + + /** Return a string akin to a WireGuard config file from this WgConfig object */ + toString() { + return generateConfigString(this); + } + + /** JSON.stringify this WgConfig object */ + toJson() { + return JSON.stringify(this); + } + + /** Parse a WireGuard config file in the form of a string into this WgConfig object */ + parse(configAsString: string) { + const parsedObj = parseConfigString(configAsString); + Object.assign(this, parsedObj); + } + + /** Generate a public/private key pair for this WgConfig object */ + generateKeys(opts?: GenerateKeysOptions) { + const overwrite = opts?.overwrite; + const privateKey = overwrite ? undefined : this.wgInterface?.privateKey; + const keys = generateKeyPair({ privateKey, preSharedKey: opts?.preSharedKey ?? false }); + this.publicKey = keys.publicKey; + this.wgInterface.privateKey = keys.privateKey; + this.preSharedKey = keys.preSharedKey; + return keys; + } + + /** + * Add a peer to the peers for this WgConfig. + * + * If the peer already exists (found by public key) then it will be updated by merging the + * existing with the new. The allowedIps will be replaced by the new peer's allowedIps unless + * { mergeAllowedIps: true } is passed in as settings + */ + addPeer(peer: WgConfigPeer, settings?: { mergeAllowedIps?: boolean }) { + const mergeAllowedIps = settings?.mergeAllowedIps; + if (!this.peers) { + this.peers = []; + } + // check if peer exists by public key + const i = this.peers.map(x => x.publicKey).indexOf(peer.publicKey); + if (i === -1) { + this.peers.push(peer); + } + else { + mergeWith(this.peers[i], peer, (objValue: any, srcValue: any, key: string) => { + if (key === 'allowedIps' && Array.isArray(objValue) && Array.isArray(srcValue)) { + return mergeAllowedIps ? [...new Set([...objValue, ...srcValue])] : srcValue; + } + }); + } + } + + /** + * Remove a peer if it exists in the peer array by its public key + */ + removePeer(publicKey: string) { + if (!this.peers) { + this.peers = []; + } + const i = this.peers.map(x => x.publicKey).indexOf(publicKey); + if (i !== -1) { + this.peers.splice(i, 1); + } + } + + /** Creates a WfgConfigPeer object from this WgCongig object */ + createPeer(settings: WgConfigPeer) { + const keys = generateKeyPair({ privateKey: undefined, preSharedKey: !!this.preSharedKey }); + const peer: WgConfigPeer = { + privateKey: keys.privateKey, + publicKey: keys.publicKey, + preSharedKey: this.preSharedKey, + endpoint: this.endpoint, + allowedIps: this.clientsAllowedIps, + ...settings, + }; + return peer; + } + + /** Get a peer from the peer array by it's public key */ + getPeer(publicKey: string) { + if (!publicKey) { + return undefined; + } + if (!this.peers || !this.peers.length) { + return undefined; + } + return this.peers.find(x => x.publicKey === publicKey); + } + + clearPeers() { + this.peers = []; + } +} diff --git a/src/tools/wireguard-config-generator/lib/types/WgConfigObject.ts b/src/tools/wireguard-config-generator/lib/types/WgConfigObject.ts new file mode 100644 index 00000000..e7569e08 --- /dev/null +++ b/src/tools/wireguard-config-generator/lib/types/WgConfigObject.ts @@ -0,0 +1,142 @@ +/** Defines the VPN settings for the local node. */ +export interface WgConfigInterface { + /** + * This is just a standard comment in INI syntax used to help keep track of which config section belongs to which node, + * it's completely ignored by WireGuard and has no effect on VPN behavior. + */ + name?: string + /** + * Defines what address range the local node should route traffic for. + * Depending on whether the node is a simple client joining the VPN subnet, or a bounce server that's relaying traffic + * between multiple clients, this can be set to a single IP of the node itself (specified with CIDR notation), + * e.g. 192.0.2.3/32), or a range of IPv4/IPv6 subnets that the node can route traffic for. + */ + address?: string[] + /** + * When the node is acting as a public bounce server, it should hardcode a port to listen for incoming VPN connections + * from the public internet. Clients not acting as relays should not set this value. + */ + listenPort?: number + /** + * This is the private key for the local node, never shared with other servers. + * All nodes must have a private key set, regardless of whether they are public bounce servers relaying traffic, + * or simple clients joining the VPN. + */ + privateKey?: string + /** + * The DNS server(s) to announce to VPN clients via DHCP, most clients will use this server for DNS requests over the VPN, + * but clients can also override this value locally on their nodes + */ + dns?: string[] + /** + * Optionally defines which routing table to use for the WireGuard routes, not necessary to configure for most setups. + * There are two special values: + * -**‘off’**: disables the creation of routes altogether, and + * -**‘auto’**: (the default if omitted) adds routes to the default table and enables special handling of default routes. + */ + table?: string + /** + * Optionally defines the maximum transmission unit (MTU, aka packet/frame size) to use when connecting to the peer, + * not necessary to configure for most setups. The MTU is automatically determined from the endpoint addresses or + * the system default route, which is usually a sane choice. + */ + mtu?: number + /** + * Optionally run bash commands before the interface is brought up. + * These will be added to the config file in order and executed in order. Position 0 in array will be run first. + */ + preUp?: string[] + /** + * Optionally run bash commands after the interface is brought up. + * These will be added to the config file in order and executed in order. Position 0 in array will be run first. + */ + postUp?: string[] + /** + * Optionally run bash commands before the interface is brought down. + * These will be added to the config file in order and executed in order. Position 0 in array will be run first. + */ + preDown?: string[] + /** + * Optionally run bash commands after the interface is brought down. + * These will be added to the config file in order and executed in order. Position 0 in array will be run first. + */ + postDown?: string[] +} + +/** + * Defines the VPN settings for a remote peer capable of routing traffic for one or more addresses (itself and/or other peers). + * Peers can be either a public bounce server that relays traffic to other peers, or a directly accessible client via + * LAN/internet that is not behind a NAT and only routes traffic for itself. + */ +export interface WgConfigPeer { + /** + * This is just a standard comment in INI syntax used to help keep track of which config section belongs to which node, + * it's completely ignored by WireGuard and has no effect on VPN behavior. + */ + name?: string + /** + * Defines the publicly accessible address for a remote peer. + * This should be left out for peers behind a NAT or peers that don't have a stable publicly accessible IP:PORT pair. + * Typically, this only needs to be defined on the main bounce server, but it can also be defined on other public nodes with stable IPs. + */ + endpoint?: string + /** + * This defines the IP ranges for which a peer will route traffic. + * On simple clients, this is usually a single address (the VPN address of the simple client itself). + * For bounce servers this will be a range of the IPs or subnets that the relay server is capable of routing traffic for. + */ + allowedIps?: string[] + /** + * This is the public key for the remote node, shareable with all peers. All nodes must have a + * public key set, regardless of whether they are public bounce servers relaying traffic, or simple clients joining the VPN. + */ + publicKey?: string + /** + * The number of seconds between each keep-alive ping. + * If the connection is going from a NAT-ed peer to a public peer, the node behind the NAT must regularly send an outgoing + * ping in order to keep the bidirectional connection alive in the NAT router's connection table. + */ + persistentKeepalive?: number + /** + * A pre-shared key generated on the remote node to improve security. + */ + preSharedKey?: string + /** + * Client Assigned IP + */ + clientAssignedIP?: string + /** + * Client Private Key + */ + privateKey?: string +} + +/** Defines the WireGuard config for this node */ +export interface WgConfigObject { + /** Defines the VPN settings for the local node. */ + wgInterface: WgConfigInterface + /** An array of VPN settings for remote peers */ + peers?: WgConfigPeer[] + /** + * A place to keep the public key for this node + * Usefull when saving this config somewhere where you can't generate the public key + * + * Note: the private key for this node should be kept in `interface.privateKey` + */ + publicKey?: string + /** + * A place to keep the preSharedKey key for this node + * Usefull when saving this config somewhere where you need to generate peers in future + */ + preSharedKey?: string + /** + * A place to keep the endpoint key for this node + * Usefull when saving this config somewhere where you need to generate peers in future + */ + endpoint?: string + /** + * A place to keep the client AllowedIPs key for this node + * Usefull when saving this config somewhere where you need to generate peers in future + */ + clientsAllowedIps?: string[] +} diff --git a/src/tools/wireguard-config-generator/lib/utils/configParser.ts b/src/tools/wireguard-config-generator/lib/utils/configParser.ts new file mode 100644 index 00000000..851fa2d6 --- /dev/null +++ b/src/tools/wireguard-config-generator/lib/utils/configParser.ts @@ -0,0 +1,259 @@ +import type { WgConfigInterface, WgConfigObject, WgConfigPeer } from '../types/WgConfigObject'; + +interface FindPartInStringOptions { + string: string + part: string +} + +/** + * Find a part in the string based on left hand side of '=' + * eg: + * string === 'PrivateKey = 123456' + * part === 'PrivateKey' + * return value = ['123456'] + * OR + * string === 'PrivateKey = 123456' + * part === 'SomethingElse' + * return value = undefined + */ +function findPartInString({ string, part }: FindPartInStringOptions) { + const parts = string.split('\n'); + const wantedParts = parts.filter(x => x.includes(part)); + + if (!wantedParts.length) { + return undefined; + } + const values = wantedParts + .map(x => x.match(/((?<==).)(.+$)/gm)?.[0]?.trim()) + .filter(x => x !== undefined) as string[]; + + if (!values.length) { + return undefined; + } + return values as [string, ...string[]]; +} + +/** Generate a string version of the WgConfig suitable for saving to a Wireguard Config file (wg0.conf) */ +export function generateConfigString(conf: WgConfigObject): { + server: string + peers: { name: string; config: string }[] +} { + const s: string[] = []; + const { wgInterface, peers, publicKey } = conf; + const { address, privateKey, listenPort, name, dns, mtu, table, preUp, postUp, preDown, postDown } = wgInterface; + + // add interface + s.push('[Interface]'); + if (name !== undefined) { + s.push(`# Name = ${name}`); + } + if (address !== undefined && address.length) { + s.push(`Address = ${address.join(',')}`); + } + if (privateKey) { + s.push(`PrivateKey = ${privateKey}`); + } + if (publicKey) { + s.push(`PublicKey = ${publicKey}`); + } + if (listenPort) { + s.push(`ListenPort = ${listenPort}`); + } + if (dns && dns.length) { + s.push(`DNS = ${dns.join(',')}`); + } + if (mtu) { + s.push(`MTU = ${mtu}`); + } + if (table) { + s.push(`Table = ${table}`); + } + if (preUp && preUp.length) { + s.push(preUp.map(x => `PreUp = ${x}`).join('\n')); + } + if (postUp && postUp.length) { + s.push(postUp.map(x => `PostUp = ${x}`).join('\n')); + } + if (preDown && preDown.length) { + s.push(preDown.map(x => `PreDown = ${x}`).join('\n')); + } + if (postDown && postDown.length) { + s.push(postDown.map(x => `PostDown = ${x}`).join('\n')); + } + + const peersConfig: Array<{ name: string; config: string }> = []; + // add peers + if (peers?.length) { + peers.forEach((peer) => { + s.push(''); + s.push('[Peer]'); + if (peer.name) { + s.push(`# Name = ${peer.name}`); + } + if (peer.publicKey) { + s.push(`PublicKey = ${peer.publicKey}`); + } + if (peer.privateKey) { + s.push(`# PrivateKey = ${peer.privateKey}`); + } + if (peer.clientAssignedIP) { + s.push(`AllowedIPs = ${peer.clientAssignedIP}/32`); + } + if (peer.endpoint) { + s.push(`Endpoint = ${peer.endpoint}`); + } + if (peer.preSharedKey) { + s.push(`PresharedKey = ${peer.preSharedKey}`); + } + if (peer.persistentKeepalive) { + s.push(`PersistentKeepalive = ${peer.persistentKeepalive}`); + } + }); + + peers.forEach((peer) => { + const peerConfig: Array = []; + peerConfig.push('[Interface]'); + if (peer.name) { + peerConfig.push(`# Name = ${peer.name}`); + } + if (peer.clientAssignedIP) { + peerConfig.push(`Address = ${peer.clientAssignedIP}/${(address || ['/24'])[0].split('/')[1]}`); + } + if (peer.privateKey) { + peerConfig.push(`PrivateKey = ${peer.privateKey}`); + } + peerConfig.push(''); + peerConfig.push(''); + peerConfig.push('[Peer]'); + if (publicKey) { + peerConfig.push(`PublicKey = ${publicKey}`); + } + if (peer.preSharedKey) { + peerConfig.push(`PresharedKey = ${peer.preSharedKey}`); + } + if (peer.allowedIps && peer.allowedIps.length) { + peerConfig.push(`AllowedIPs = ${peer.allowedIps.join(',')}`); + } + if (peer.endpoint) { + peerConfig.push(`Endpoint = ${peer.endpoint}`); + } + peersConfig.push({ name: peer.name || '', config: peerConfig.join('\n') }); + }); + } + return { + server: s.join('\n'), + peers: peersConfig, + }; +} + +/** + * Parse a WireGuard config file (wg0.conf) into a WgConfig object for use in Javascript-land + * If no valid interface is found in the config, it will throw an error + * If a peer in the peers array is invalid, it will throw an error + */ +export function parseConfigString(configString: string) { + const interFaceReg = /\[Interface\][^\[]*/gm; + const peerReg = /\[Peer\][^\[]*/gm; + + const interfaces = configString.match(interFaceReg); + const interfaceString = interfaces?.[0]; + if (!interfaceString) { + throw new Error(`No interface found in config:\n${configString}`); + } + + const maybeAddress = findPartInString({ string: interfaceString, part: 'Address' })?.[0]?.split(','); + const address = maybeAddress ? maybeAddress.filter(x => x !== undefined) as [string, ...string[]] : undefined; + if (!address || !address.length) { + throw new Error(`No address found in config:\n${configString}`); + } + + const privateKey = findPartInString({ string: interfaceString, part: 'PrivateKey' })?.[0]; + if (!privateKey) { + throw new Error(`No privateKey found in config:\n${configString}`); + } + + const maybeListenPort = findPartInString({ string: interfaceString, part: 'ListenPort' })?.[0]; + const listenPort = maybeListenPort ? Number.parseInt(maybeListenPort) : undefined; + + const maybeMTU = findPartInString({ string: interfaceString, part: 'MTU' })?.[0]; + const mtu = maybeMTU ? Number.parseInt(maybeMTU) : undefined; + + const maybeDns = findPartInString({ string: interfaceString, part: 'DNS' })?.[0]?.split(',').filter(x => x !== undefined); + const dns = maybeDns?.length ? maybeDns : undefined; + + const wgInterface: WgConfigInterface = { + // required keys + address, + privateKey, + // optional keys + dns, + listenPort, + mtu, + name: findPartInString({ string: interfaceString, part: 'Name' })?.[0], + table: findPartInString({ string: interfaceString, part: 'Table' })?.[0], + preUp: findPartInString({ string: interfaceString, part: 'PreUp' }), + postUp: findPartInString({ string: interfaceString, part: 'PostUp' }), + preDown: findPartInString({ string: interfaceString, part: 'PreDown' }), + postDown: findPartInString({ string: interfaceString, part: 'PostDown' }), + }; + + // remove any undefined keys + let key: keyof WgConfigInterface; + for (key in wgInterface) { + if (wgInterface[key] === undefined) { + delete wgInterface[key]; + } + } + + const peerStrings = configString.match(peerReg); + + const peers = !peerStrings + ? [] + : peerStrings.map((x) => { + if (!x) { + return undefined; + } + + const maybeAllowedIps = findPartInString({ string: x, part: 'AllowedIPs' })?.[0]?.split(','); + const allowedIps = maybeAllowedIps ? maybeAllowedIps.filter(y => y !== undefined) as [string, ...string[]] : undefined; + if (!allowedIps || !allowedIps.length) { + throw new Error(`No allowedIps found in peer:\n${x}`); + } + + const publicKey = findPartInString({ string: x, part: 'PublicKey' })?.[0]; + if (!publicKey) { + throw new Error(`No publicKey found in peer:\n${x}`); + } + + const maybePersistentKeepAlive = findPartInString({ string: interfaceString, part: 'PersistentKeepalive' })?.[0]; + const persistentKeepalive = maybePersistentKeepAlive ? Number.parseInt(maybePersistentKeepAlive) : undefined; + + const peer: WgConfigPeer = { + // required keys + allowedIps, + publicKey, + // optional keys + persistentKeepalive, + name: findPartInString({ string: x, part: 'Name' })?.[0], + endpoint: findPartInString({ string: x, part: 'Endpoint' })?.[0], + preSharedKey: findPartInString({ string: x, part: 'PresharedKey' })?.[0], + }; + + // remove undefined keys + let peerKey: keyof WgConfigPeer; + for (peerKey in peer) { + if (peer[peerKey] === undefined) { + delete peer[peerKey]; + } + } + + return peer; + }).filter(x => x !== undefined) as WgConfigPeer[]; + + const returnVal: Pick = { + wgInterface, + peers, + }; + + return returnVal; +} diff --git a/src/tools/wireguard-config-generator/lib/utils/createPeerPairs.ts b/src/tools/wireguard-config-generator/lib/utils/createPeerPairs.ts new file mode 100644 index 00000000..a1b5b2d8 --- /dev/null +++ b/src/tools/wireguard-config-generator/lib/utils/createPeerPairs.ts @@ -0,0 +1,36 @@ +import type { WgConfigPeer } from '../types/WgConfigObject'; +import type { WgConfig } from '../WgConfig'; + +interface CreatePeerPairsOptions { + /** The config to derive public key from for the peer */ + config: WgConfig + /** The peer settings to apply when adding this config as a peer */ + peerSettings: Omit | ((args: { thisConfig: WgConfig; peerConfig: WgConfig }) => Omit) +} + +/** + * Create peer pairs from more than one WgConfig object. + * + * Will add wgConfigs[0] as a peer in wgConfigs[1] and wgConfigs[1] as a peer in wgConfigs[0] etc. + * Will fail and error if + */ +export function createPeerPairs(pairs: CreatePeerPairsOptions[]) { + for (let i = 0; i < pairs.length; i++) { + const thisConfig = pairs[i]; + for (let subI = 0; subI < pairs.length; subI++) { + const peerConfig = pairs[subI]; + if (thisConfig.config.publicKey === peerConfig.config.publicKey) { + continue; + } + const peerSettings = typeof peerConfig.peerSettings === 'function' + ? peerConfig.peerSettings({ thisConfig: thisConfig.config, peerConfig: peerConfig.config }) + : peerConfig.peerSettings; + const thisConfigPreSharedKey = thisConfig.config.preSharedKey; + if (thisConfigPreSharedKey) { + peerSettings.preSharedKey = thisConfigPreSharedKey; + } + const peer = peerConfig.config.createPeer(peerSettings); + thisConfig.config.addPeer(peer, { mergeAllowedIps: false }); + } + } +} diff --git a/src/tools/wireguard-config-generator/lib/utils/generateKeyPair.ts b/src/tools/wireguard-config-generator/lib/utils/generateKeyPair.ts new file mode 100644 index 00000000..6e2fff47 --- /dev/null +++ b/src/tools/wireguard-config-generator/lib/utils/generateKeyPair.ts @@ -0,0 +1,209 @@ +/*! SPDX-License-Identifier: GPL-2.0 + * + * Copyright (C) 2015-2020 Jason A. Donenfeld . All Rights Reserved. + */ +import { Base64 } from 'js-base64'; + +function gf(init?: Array) { + const r = new Float64Array(16); + if (init) { + for (let i = 0; i < init.length; ++i) { + r[i] = init[i]; + } + } + return r; +} + +function pack(o: Uint8Array, n: Float64Array) { + let b; + const m = gf(); + const t = gf(); + for (let i = 0; i < 16; ++i) { + t[i] = n[i]; + } + carry(t); + carry(t); + carry(t); + for (let j = 0; j < 2; ++j) { + m[0] = t[0] - 0xFFED; + for (let i = 1; i < 15; ++i) { + m[i] = t[i] - 0xFFFF - ((m[i - 1] >> 16) & 1); + m[i - 1] &= 0xFFFF; + } + m[15] = t[15] - 0x7FFF - ((m[14] >> 16) & 1); + b = (m[15] >> 16) & 1; + m[14] &= 0xFFFF; + cswap(t, m, 1 - b); + } + for (let i = 0; i < 16; ++i) { + o[2 * i] = t[i] & 0xFF; + o[2 * i + 1] = t[i] >> 8; + } +} + +function carry(o: Float64Array) { + // let c; + for (let i = 0; i < 16; ++i) { + o[(i + 1) % 16] += (i < 15 ? 1 : 38) * Math.floor(o[i] / 65536); + o[i] &= 0xFFFF; + } +} + +function cswap(p: Float64Array, q: Float64Array, b: number) { + let t; + const c = ~(b - 1); + for (let i = 0; i < 16; ++i) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } +} + +function add(o: Float64Array, a: Float64Array, b: Float64Array) { + for (let i = 0; i < 16; ++i) { + o[i] = (a[i] + b[i]) | 0; + } +} + +function subtract(o: Float64Array, a: Float64Array, b: Float64Array) { + for (let i = 0; i < 16; ++i) { + o[i] = (a[i] - b[i]) | 0; + } +} + +function multmod(o: Float64Array, a: Float64Array, b: Float64Array) { + const t = new Float64Array(31); + for (let i = 0; i < 16; ++i) { + for (let j = 0; j < 16; ++j) { + t[i + j] += a[i] * b[j]; + } + } + for (let i = 0; i < 15; ++i) { + t[i] += 38 * t[i + 16]; + } + for (let i = 0; i < 16; ++i) { + o[i] = t[i]; + } + carry(o); + carry(o); +} + +function invert(o: Float64Array, i: Float64Array) { + const c = gf(); + for (let a = 0; a < 16; ++a) { + c[a] = i[a]; + } + for (let a = 253; a >= 0; --a) { + multmod(c, c, c); + if (a !== 2 && a !== 4) { + multmod(c, c, i); + } + } + for (let a = 0; a < 16; ++a) { + o[a] = c[a]; + } +} + +function clamp(z: Uint8Array) { + z[31] = (z[31] & 127) | 64; + z[0] &= 248; +} + +function generatePublicKey(privateKey: Uint8Array) { + let r; + const z = new Uint8Array(32); + const a = gf([1]); + const b = gf([9]); + const c = gf(); + const d = gf([1]); + const e = gf(); + const f = gf(); + const _121665 = gf([0xDB41, 1]); + const _9 = gf([9]); + for (let i = 0; i < 32; ++i) { + z[i] = privateKey[i]; + } + clamp(z); + for (let i = 254; i >= 0; --i) { + r = (z[i >>> 3] >>> (i & 7)) & 1; + cswap(a, b, r); + cswap(c, d, r); + add(e, a, c); + subtract(a, a, c); + add(c, b, d); + subtract(b, b, d); + multmod(d, e, e); + multmod(f, a, a); + multmod(a, c, a); + multmod(c, b, e); + add(e, a, c); + subtract(a, a, c); + multmod(b, a, a); + subtract(c, d, f); + multmod(a, c, _121665); + add(a, a, d); + multmod(c, c, a); + multmod(a, d, f); + multmod(d, b, _9); + multmod(b, e, e); + cswap(a, b, r); + cswap(c, d, r); + } + invert(c, c); + multmod(a, a, c); + pack(z, a); + return z; +} + +function generatePresharedKey() { + const preSharedKey = new Uint8Array(32); + window.crypto.getRandomValues(preSharedKey); + return preSharedKey; +} + +function generatePrivateKey() { + const privateKey = generatePresharedKey(); + clamp(privateKey); + return privateKey; +} + +// function encodeBase64(dest: Uint8Array, src: Uint8Array) { +// const input = Uint8Array.from([(src[0] >> 2) & 63, ((src[0] << 4) | (src[1] >> 4)) & 63, ((src[1] << 2) | (src[2] >> 6)) & 63, src[2] & 63]); +// for (let i = 0; i < 4; ++i) { +// dest[i] = input[i] + 65 +// + (((25 - input[i]) >> 8) & 6) +// - (((51 - input[i]) >> 8) & 75) +// - (((61 - input[i]) >> 8) & 15) +// + (((62 - input[i]) >> 8) & 3); +// } +// } + +// function keyToBase64(key: Uint8Array) { +// let i; +// const base64 = new Uint8Array(44); +// for (i = 0; i < 32 / 3; ++i) { +// encodeBase64(base64.subarray(i * 4), key.subarray(i * 3)); +// } +// encodeBase64(base64.subarray(i * 4), Uint8Array.from([key[i * 3 + 0], key[i * 3 + 1], 0])); +// base64[43] = 61; +// return String.fromCharCode.apply(null, [...base64]); +// } + +export function generateKeyPair({ + privateKey = undefined, + preSharedKey = false, +}: { + privateKey: Uint8Array | string | undefined + preSharedKey: boolean +}) { + if (!privateKey) { + privateKey = generatePrivateKey(); + } + const privateKeyUint8Array = typeof privateKey === 'string' ? Base64.toUint8Array(privateKey) : privateKey; + const publicKey = generatePublicKey(privateKeyUint8Array); + return { + publicKey: Base64.fromUint8Array(publicKey), + privateKey: Base64.fromUint8Array(privateKeyUint8Array), + preSharedKey: preSharedKey ? Base64.fromUint8Array(generatePresharedKey()) : undefined, + }; +} diff --git a/src/tools/wireguard-config-generator/wireguard-config-generator.vue b/src/tools/wireguard-config-generator/wireguard-config-generator.vue new file mode 100644 index 00000000..aa406ade --- /dev/null +++ b/src/tools/wireguard-config-generator/wireguard-config-generator.vue @@ -0,0 +1,259 @@ + + +