Skip to content

Commit

Permalink
net/wireguard - refactor server keypair generation, add a button so t…
Browse files Browse the repository at this point in the history
…he user can easily generate a new pair and copy the public key to the clipboard for reusage. This should also fix a possible race where two instances would try to store /tmp/wireguard.priv at the same time.
  • Loading branch information
AdSchellevis committed Aug 27, 2023
1 parent 33ee537 commit 15a3559
Show file tree
Hide file tree
Showing 6 changed files with 79 additions and 97 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ class ServerController extends ApiMutableModelControllerBase
protected static $internalModelName = 'server';
protected static $internalModelClass = '\OPNsense\Wireguard\Server';

public function keyPairAction()
{
return json_decode((new Backend())->configdRun('wireguard gen_keypair'), true);
}

public function searchServerAction()
{
$search = $this->searchBase(
Expand All @@ -53,24 +58,7 @@ public function getServerAction($uuid = null)

public function addServerAction($uuid = null)
{
if ($this->request->isPost() && $this->request->hasPost("server")) {
if ($uuid != null) {
$node = $this->getModel()->getNodeByReference('servers.server.' . $uuid);
} else {
$node = $this->getModel()->servers->server->Add();
}
$node->setNodes($this->request->getPost("server"));
if (empty((string)$node->pubkey) && empty((string)$node->privkey)) {
// generate new keypair
$backend = new Backend();
$keyspriv = $backend->configdpRun("wireguard genkey", 'private');
$keyspub = $backend->configdpRun("wireguard genkey", 'public');
$node->privkey = trim($keyspriv);
$node->pubkey = trim($keyspub);
}
return $this->validateAndSave($node, 'server');
}
return array("result" => "failed");
return $this->addBase('server', 'servers.server', $uuid);
}

public function delServerAction($uuid)
Expand All @@ -80,24 +68,7 @@ public function delServerAction($uuid)

public function setServerAction($uuid = null)
{
if ($this->request->isPost() && $this->request->hasPost("server")) {
if ($uuid != null) {
$node = $this->getModel()->getNodeByReference('servers.server.' . $uuid);
} else {
$node = $this->getModel()->servers->server->Add();
}
$node->setNodes($this->request->getPost("server"));
if (empty((string)$node->pubkey) && empty((string)$node->privkey)) {
// generate new keypair
$backend = new Backend();
$keyspriv = $backend->configdpRun("wireguard genkey", 'private');
$keyspub = $backend->configdpRun("wireguard genkey", 'public');
$node->privkey = trim($keyspriv);
$node->pubkey = trim($keyspub);
}
return $this->validateAndSave($node, 'server');
}
return array("result" => "failed");
return $this->setBase('server', 'servers.server', $uuid);
}

public function toggleServerAction($uuid)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@
<Required>Y</Required>
</instance>
<pubkey type="TextField">
<Required>N</Required>
<Required>Y</Required>
<ValidationMessage>A public key is required</ValidationMessage>
</pubkey>
<privkey type="TextField">
<Required>N</Required>
<Required>Y</Required>
<ValidationMessage>A private key is required</ValidationMessage>
</privkey>
<port type="PortField">
<Required>N</Required>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,19 @@
}
});

/**
* Move keypair generation button inside the server form and hook api event
*/
$("#control_label_server\\.pubkey").append($("#keygen_div").detach().show());
$("#keygen").click(function(){
ajaxGet("/api/wireguard/server/key_pair", {}, function(data, status){
if (data.status && data.status === 'ok') {
$("#server\\.pubkey").val(data.pubkey);
$("#server\\.privkey").val(data.privkey);
}
});
})

// Put API call into a function, needed for auto-refresh
function update_showconf() {
ajaxCall(url="/api/wireguard/service/showconf", sendData={}, callback=function(data,status) {
Expand Down Expand Up @@ -126,6 +139,11 @@
</table>
</div>
<div id="servers" class="tab-pane fade in">
<span id="keygen_div" style="display:none" class="pull-right">
<button id="keygen" type="button" class="btn btn-secondary" title="{{ lang._('Generate new keypair.') }}" data-toggle="tooltip">
<i class="fa fa-fw fa-gear"></i>
</button>
</span>
<table id="grid-servers" class="table table-responsive" data-editDialog="dialogEditWireguardServer">
<thead>
<tr>
Expand Down
46 changes: 46 additions & 0 deletions net/wireguard/src/opnsense/scripts/Wireguard/gen_keypair.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#!/usr/local/bin/python3

"""
Copyright (c) 2023 Ad Schellevis <[email protected]>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
import subprocess
import ujson


def keypair():
sp = subprocess.run(['/usr/bin/wg', 'genkey'], capture_output=True, text=True)
if sp.returncode == 0:
privkey = sp.stdout.strip()
sp = subprocess.run(['/usr/bin/wg', 'pubkey'], input=privkey, capture_output=True, text=True)
if sp.returncode == 0:
return {'privkey': privkey, 'pubkey': sp.stdout.strip()}
return None

response = keypair()
if not response:
print(ujson.dumps({'status': 'failed'}))
else:
response['status'] = 'ok'
print(ujson.dumps(response))
55 changes: 0 additions & 55 deletions net/wireguard/src/opnsense/scripts/Wireguard/genkey.sh

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@ type:script
message:Renew DNS for WireGuard
description:Renew DNS for WireGuard on stale connections

[genkey]
command:/usr/local/opnsense/scripts/Wireguard/genkey.sh
parameters: %s
[gen_keypair]
command:/usr/local/opnsense/scripts/Wireguard/gen_keypair.py
parameters:
type:script_output
message:Generating WireGuard keys
message:Generating WireGuard keypair

[showconf]
command:/usr/bin/wg show all
Expand Down

0 comments on commit 15a3559

Please sign in to comment.