|
| 1 | +require 'ipaddress' |
| 2 | +require 'open3' |
| 3 | + |
| 4 | +class WgConfig < ApplicationRecord |
| 5 | + |
| 6 | + belongs_to :user |
| 7 | + |
| 8 | + validates :name, presence: true |
| 9 | + validates :privatekey, presence: true |
| 10 | + validates :publickey, presence: true |
| 11 | + validates :name, uniqueness: { scope: :user_id } |
| 12 | + |
| 13 | + after_initialize :init_keys |
| 14 | + |
| 15 | + def generate_keys! |
| 16 | + self.privatekey = gen_privatekey |
| 17 | + self.publickey = gen_publickey(self.privatekey) |
| 18 | + end |
| 19 | + |
| 20 | + def addresses(as_networks=true) |
| 21 | + raise "Model is not saved" if self.id.nil? |
| 22 | + |
| 23 | + first = IPAddress Setting['wgFirstClientAddress'] |
| 24 | + last = IPAddress Setting['wgLastClientAddress'] |
| 25 | + |
| 26 | + ip = IPAddress(first.to_i + self.id) |
| 27 | + |
| 28 | + raise "Failed to assign IP: out of range" if ip > last |
| 29 | + |
| 30 | + ip.netmask = Setting['wgNetmask'] if as_networks |
| 31 | + |
| 32 | + ip.to_string |
| 33 | + end |
| 34 | + |
| 35 | + def to_s |
| 36 | + lines = [] |
| 37 | + lines << "# WireGuard config #{name}" |
| 38 | + lines << '[Interface]' |
| 39 | + lines << "PrivateKey = #{privatekey}" |
| 40 | + lines << "Address = #{self.addresses}" |
| 41 | + lines << '' |
| 42 | + lines << '[Peer]' |
| 43 | + lines << "PublicKey = #{Setting['wgServerPublicKey']}" |
| 44 | + lines << "Endpoint = #{Setting['wgServerEndpoint']}" |
| 45 | + lines << "AllowedIPs = #{Setting['wgAllowedIPs']}" |
| 46 | + |
| 47 | + lines.join("\n") |
| 48 | + end |
| 49 | + |
| 50 | + def as_peer |
| 51 | + s = [] |
| 52 | + s << "# User #{self.user_id}, config '#{self.name}'" |
| 53 | + s << "[Peer]" |
| 54 | + s << "PublicKey = #{publickey}" |
| 55 | + s << "AllowedIPs = #{addresses(false)}" |
| 56 | + |
| 57 | + s.join("\n") |
| 58 | + end |
| 59 | + |
| 60 | + private |
| 61 | + |
| 62 | + def init_keys |
| 63 | + generate_keys! if self.privatekey.blank? |
| 64 | + end |
| 65 | + |
| 66 | + def gen_privatekey |
| 67 | + key, status = Open3.capture2("wg genkey") |
| 68 | + key.strip |
| 69 | + end |
| 70 | + |
| 71 | + def gen_publickey(private_key) |
| 72 | + stdout_str = '' |
| 73 | + Open3.popen2("wg pubkey") do |stdin, stdout, _wait_thr| |
| 74 | + stdin.print(private_key) |
| 75 | + stdin.close |
| 76 | + stdout_str = stdout.gets |
| 77 | + end |
| 78 | + |
| 79 | + stdout_str.strip |
| 80 | + end |
| 81 | +end |
0 commit comments