Skip to content

Commit

Permalink
vpn: ipsec: Add swanctl.conf download button to settings.volt view (#…
Browse files Browse the repository at this point in the history
…7972)

* vpn: ipsec: Add swanctl.conf download button to settings.volt view. Bootstrap dialogue warns user about sensitive file contents. Error scenarios like missing file or API errors are handled gracefully with error messages.

* Update src/opnsense/mvc/app/views/OPNsense/IPsec/settings.volt

Co-authored-by: Franco Fichtner <franco@lastsummer.de>

* vpn: ipsec: make plist-fix

---------

Co-authored-by: Franco Fichtner <franco@lastsummer.de>
  • Loading branch information
Monviech and fichtner authored Oct 21, 2024
1 parent 786bc2c commit 3a7cd41
Show file tree
Hide file tree
Showing 5 changed files with 151 additions and 2 deletions.
1 change: 1 addition & 0 deletions plist
Original file line number Diff line number Diff line change
Expand Up @@ -1147,6 +1147,7 @@
/usr/local/opnsense/scripts/ipsec/connect.py
/usr/local/opnsense/scripts/ipsec/disconnect.py
/usr/local/opnsense/scripts/ipsec/get_legacy_vti.php
/usr/local/opnsense/scripts/ipsec/get_swanctl.py
/usr/local/opnsense/scripts/ipsec/lib/__init__.py
/usr/local/opnsense/scripts/ipsec/list_leases.py
/usr/local/opnsense/scripts/ipsec/list_sad.py
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?php

/*
* Copyright (C) 2022 Deciso B.V.
* Copyright (C) 2022-2024 Deciso B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
Expand Down Expand Up @@ -30,6 +30,7 @@

use OPNsense\Base\ApiMutableModelControllerBase;
use OPNsense\Core\Config;
use OPNsense\Core\Backend;

/**
* Class ConnectionsController
Expand Down Expand Up @@ -309,4 +310,20 @@ public function toggleAction($enabled = null)
}
return ['status' => 'failed'];
}

/**
* Fetch the contents of swanctl.conf
*/
public function swanctlAction()
{
$backend = new Backend();

$responseArray = json_decode($backend->configdRun('ipsec get swanctl'), true);

if (isset($responseArray['error'])) {
return ["status" => "failed", "message" => $responseArray['message']];
}

return ["status" => "success", "content" => $responseArray['content']];
}
}
84 changes: 83 additions & 1 deletion src/opnsense/mvc/app/views/OPNsense/IPsec/settings.volt
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,96 @@
}
});
});
});

function showDialogAlert(type, title, message) {
BootstrapDialog.show({
type: type,
title: title,
message: message,
buttons: [{
label: '{{ lang._('Close') }}',
action: function(dialogRef) {
dialogRef.close();
}
}]
});
}

function fetchAndDownloadConfig(apiUrl, filename) {
ajaxGet(apiUrl, null, function(response, status) {
if (status === "success" && response.status === "success") {
const content = response.content;
const a_tag = $('<a></a>')
.attr('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(content))
.attr('download', filename)
.appendTo('body');
a_tag[0].click();
a_tag.remove();
} else {
showDialogAlert(BootstrapDialog.TYPE_WARNING, "{{ lang._('Download Error') }}",
response.message || "{{ lang._('Failed to download the configuration file.') }}");
}
}).fail(function(xhr, status, error) {
showDialogAlert(BootstrapDialog.TYPE_DANGER, "{{ lang._('Download Request Failed') }}", error);
});
}

let warningAcknowledged = false;

$("#downloadConfig").click(function() {
const apiUrl = '/api/ipsec/connections/swanctl';
const timestamp = new Date().toISOString().replace(/[-:]/g, '').replace('T', '-').split('.')[0];
const filename = "swanctl.conf_" + timestamp + ".txt";

if (warningAcknowledged) {
fetchAndDownloadConfig(apiUrl, filename);
} else {
BootstrapDialog.show({
type: BootstrapDialog.TYPE_WARNING,
title: "{{ lang._('Warning') }}",
message: "{{ lang._('The file you are about to download may contain sensitive data. Please handle it with care.') }}",
buttons: [{
label: '{{ lang._('Cancel') }}',
action: function(dialogRef) {
dialogRef.close();
}
}, {
label: '{{ lang._('Download') }}',
cssClass: 'btn-primary',
action: function(dialogRef) {
dialogRef.close();
warningAcknowledged = true;
fetchAndDownloadConfig(apiUrl, filename);
}
}]
});
}
});

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
const activeTab = $(e.target).attr('href');

if (activeTab === '#configTab') {
$('#reconfigureAct').hide();
$('#downloadConfig').show();
} else {
$('#reconfigureAct').show();
$('#downloadConfig').hide();
}
});

});
</script>

<ul class="nav nav-tabs" role="tablist" id="maintabs">
{{ partial("layout_partials/base_tabs_header",['formData':formSettings]) }}
<li><a data-toggle="tab" href="#configTab" role="tab">{{ lang._('swanctl.conf') }}</a></li>
</ul>

<form id="mainform">
<div class="content-box tab-content">
{{ partial("layout_partials/base_tabs_content",['formData':formSettings]) }}
<div id="configTab" class="tab-pane fade"/>
</div>
</form>

Expand All @@ -42,6 +121,9 @@
data-error-title="{{ lang._('Error reconfiguring IPsec') }}"
type="button"
></button>
<button class="btn btn-primary" id="downloadConfig" style="display: none;">
{{ lang._('Download') }}
</button>
<br/><br/>
</div>
</div>
43 changes: 43 additions & 0 deletions src/opnsense/scripts/ipsec/get_swanctl.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#!/usr/local/bin/python3

"""
Copyright (c) 2024 Deciso B.V.
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 json
import re

config_path = "/usr/local/etc/swanctl/swanctl.conf"

try:
with open(config_path, "r") as file:
config_data = file.read()

print(json.dumps({"content": config_data}))

except FileNotFoundError:
print(json.dumps({"error": "File not found", "message": "swanctl.conf file not found"}))
except Exception as e:
print(json.dumps({"error": "General Error", "message": str(e)}))
6 changes: 6 additions & 0 deletions src/opnsense/service/conf/actions.d/actions_ipsec.conf
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ parameters:
type:script_output
message:IPsec list legacy VirtualTunnelInterfaces

[get.swanctl]
command:/usr/local/opnsense/scripts/ipsec/get_swanctl.py
parameters:
type:script_output
message:Get swanctl.conf file

[connect]
command:/usr/local/opnsense/scripts/ipsec/connect.py
parameters:%s
Expand Down

0 comments on commit 3a7cd41

Please sign in to comment.