Skip to content

Commit

Permalink
Merge pull request #49 from hagbard-01/current
Browse files Browse the repository at this point in the history
T793: wireguard: implement fwmark, pre-shared key
  • Loading branch information
hagbard-01 committed Sep 3, 2018
2 parents c49ec13 + d6679e2 commit d31d16d
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 23 deletions.
13 changes: 11 additions & 2 deletions interface-definitions/wireguard.xml
Expand Up @@ -87,17 +87,26 @@
</constraint>
<constraintErrorMessage>Key is not valid 44-character (32-bytes) base64</constraintErrorMessage>
</properties>
</leafNode>
<leafNode name="preshared-key">
<properties>
<help>base64 encoded preshared key</help>
<constraint>
<regex>^[0-9a-zA-Z\+/]{43}=$</regex>
</constraint>
<constraintErrorMessage>Key is not valid 44-character (32-bytes) base64</constraintErrorMessage>
</properties>
</leafNode>
<leafNode name="allowed-ips">
<properties>
<help>IP addresses allowed to traverse the peer</help>
<multi/>
</properties>
</leafNode>
<!-- check format IP:port -->
<!-- eventually check format IP:port -->
<leafNode name="endpoint">
<properties>
<help>Remote endpoint</help>
<help>Remote endpoint (IP:port)</help>
</properties>
</leafNode>
<leafNode name="persistent-keepalive">
Expand Down
12 changes: 9 additions & 3 deletions op-mode-definitions/wireguard.xml
Expand Up @@ -12,8 +12,14 @@
<properties>
<help>generate a wireguard keypair</help>
</properties>
<command>${vyos_op_scripts_dir}/wireguard_key.py --genkey</command>
<command>${vyos_op_scripts_dir}/wireguard.py --genkey</command>
</leafNode>
<leafNode name="preshared-key">
<properties>
<help>generate a wireguard preshared key</help>
</properties>
<command>${vyos_op_scripts_dir}/wireguard.py --genpsk</command>
</leafNode>
</children>
</node>
</children>
Expand All @@ -26,13 +32,13 @@
<properties>
<help>show wireguard public key</help>
</properties>
<command>${vyos_op_scripts_dir}/wireguard_key.py --showpub</command>
<command>${vyos_op_scripts_dir}/wireguard.py --showpub</command>
</leafNode>
<leafNode name="privkey">
<properties>
<help>show wireguard private key</help>
</properties>
<command>${vyos_op_scripts_dir}/wireguard_key.py --showpriv</command>
<command>${vyos_op_scripts_dir}/wireguard.py --showpriv</command>
</leafNode>
</children>
</node>
Expand Down
37 changes: 25 additions & 12 deletions src/conf_mode/wireguard.py
Expand Up @@ -28,6 +28,7 @@
dir = r'/config/auth/wireguard'
pk = dir + '/private.key'
pub = dir + '/public.key'
psk_file = r'/tmp/psk'

def check_kmod():
if not os.path.exists('/sys/module/wireguard'):
Expand Down Expand Up @@ -117,7 +118,9 @@ def get_config():
config_data['interfaces'][intfc]['peer'][p]['endpoint'] = c.return_value(cnf + ' peer ' + p + ' endpoint')
if c.exists(cnf + ' peer ' + p + ' persistent-keepalive'):
config_data['interfaces'][intfc]['peer'][p]['persistent-keepalive'] = c.return_value(cnf + ' peer ' + p + ' persistent-keepalive')

if c.exists(cnf + ' peer ' + p + ' preshared-key'):
config_data['interfaces'][intfc]['peer'][p]['psk'] = c.return_value(cnf + ' peer ' + p + ' preshared-key')

return config_data

def verify(c):
Expand Down Expand Up @@ -225,24 +228,22 @@ def apply(c):
fh.write(str(cnf_descr))

def configure_interface(c, intf):
wg_config = {
for p in c['interfaces'][intf]['peer']:
## config init for wg call
wg_config = {
'interface' : intf,
'port' : 0,
'private-key' : '/config/auth/wireguard/private.key',
'peer' :
{
'pubkey' : ''
},
'port' : 0,
'private-key' : pk,
'pubkey' : '',
'psk' : '/dev/null',
'allowed-ips' : [],
'fwmark' : 0x00,
'endpoint' : None,
'keepalive' : 0

}

for p in c['interfaces'][intf]['peer']:
## mandatory settings
wg_config['peer']['pubkey'] = c['interfaces'][intf]['peer'][p]['pubkey']
wg_config['pubkey'] = c['interfaces'][intf]['peer'][p]['pubkey']
wg_config['allowed-ips'] = c['interfaces'][intf]['peer'][p]['allowed-ips']

## optional settings
Expand All @@ -258,11 +259,19 @@ def configure_interface(c, intf):
if 'persistent-keepalive' in c['interfaces'][intf]['peer'][p]:
wg_config['keepalive'] = c['interfaces'][intf]['peer'][p]['persistent-keepalive']

## preshared-key - is only read from a file, it's called via sudo redirection doesn't work either
if 'psk' in c['interfaces'][intf]['peer'][p]:
old_umask = os.umask(0o077)
open(psk_file, 'w').write(str(c['interfaces'][intf]['peer'][p]['psk']))
os.umask(old_umask)
wg_config['psk'] = psk_file

### assemble wg command
cmd = "sudo wg set " + intf
cmd += " listen-port " + str(wg_config['port'])
cmd += " private-key " + wg_config['private-key']
cmd += " peer " + wg_config['peer']['pubkey']
cmd += " peer " + wg_config['pubkey']
cmd += " preshared-key " + wg_config['psk']
cmd += " allowed-ips "
for ap in wg_config['allowed-ips']:
if ap != wg_config['allowed-ips'][-1]:
Expand All @@ -279,7 +288,11 @@ def configure_interface(c, intf):
cmd += " persistent-keepalive 0"

sl.syslog(sl.LOG_NOTICE, cmd)
#print (cmd)
subprocess.call([cmd], shell=True)
""" remove psk_file """
if os.path.exists(psk_file):
os.remove(psk_file)

def add_addr(intf, addr):
ret = subprocess.call(['ip a a dev ' + intf + ' ' + addr + ' &>/dev/null'], shell=True)
Expand Down
22 changes: 16 additions & 6 deletions src/op_mode/wireguard_key.py → src/op_mode/wireguard.py
Expand Up @@ -19,44 +19,47 @@
import argparse
import os
import sys
import syslog as sl
import subprocess
import syslog as sl

from vyos import ConfigError

dir = r'/config/auth/wireguard'
pk = dir + '/private.key'
pub = dir + '/public.key'
psk = dir + '/preshared.key'

### check_kmod may be removed in the future,
### once it's loaded automatically
def check_kmod():
""" check if kmod is loaded, if not load it """
if not os.path.exists('/sys/module/wireguard'):
sl.syslog(sl.LOG_NOTICE, "loading wirguard kmod")
if os.system('sudo modprobe wireguard') != 0:
sl.syslog(sl.LOG_ERR, "modprobe wireguard failed")
raise ConfigError("modprobe wireguard failed")

def generate_keypair():
""" generates a keypair which is stored in /config/auth/wireguard """
ret = subprocess.call(['wg genkey | tee ' + pk + '|wg pubkey > ' + pub], shell=True)
if ret != 0:
raise ConfigError("wireguard key-pair generation failed")
else:
sl.syslog(sl.LOG_NOTICE, "new keypair wireguard key generated in " + dir)

def genkey():
### if umask 077 makes trouble, 027 will work
""" helper function to check, regenerate the keypair """
old_umask = os.umask(0o077)
if os.path.exists(pk) and os.path.exists(pub):
choice = input("You have a wireguard key-pair already, do you want to re-generate? [y/n] ")
choice = input("You already have a wireguard key-pair already, do you want to re-generate? [y/n] ")
if choice == 'y' or choice == 'Y':
generate_keypair()
else:
os.mkdir(dir)
if not os.path.exists(dir):
os.mkdir(dir)
generate_keypair()
os.umask(old_umask)

def showkey(key):
""" helper function to show privkey or pubkey """
if key == "pub":
if os.path.exists(pub):
print ( open(pub).read().strip() )
Expand All @@ -69,13 +72,18 @@ def showkey(key):
else:
print("no private key found")

def genpsk():
""" generates a preshared key and shows it on stdout, it's stroed only in the config """
subprocess.call(['wg genpsk'], shell=True)

if __name__ == '__main__':
check_kmod()

parser = argparse.ArgumentParser(description='wireguard key management')
parser.add_argument('--genkey', action="store_true", help='generate key-pair')
parser.add_argument('--showpub', action="store_true", help='shows public key')
parser.add_argument('--showpriv', action="store_true", help='shows private key')
parser.add_argument('--genpsk', action="store_true", help='generates preshared-key')
args = parser.parse_args()

try:
Expand All @@ -85,6 +93,8 @@ def showkey(key):
showkey("pub")
if args.showpriv:
showkey("pk")
if args.genpsk:
genpsk()

except ConfigError as e:
print(e)
Expand Down

0 comments on commit d31d16d

Please sign in to comment.