plinth/*: Rename plinth/ folder to freedombox/

Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org>
Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
Sunil Mohan Adapa authored and James Valleroy committed 2026-08-28 07:35:01 -04:00
1 parent dd0161a7e5
commit 23b6aff290
1264 files changed

No files matched your search

+124
View File
@@ -0,0 +1,124 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""FreedomBox app for OpenSSH server."""
import logging
import pathlib
import re
import subprocess
from django.utils.translation import gettext_lazy as _
from plinth import app as app_module
from plinth import menu
from plinth.config import DropinConfigs
from plinth.daemon import Daemon
from plinth.modules.backups.components import BackupRestore
from plinth.modules.firewall.components import Firewall
from plinth.modules.users.components import UsersAndGroups
from plinth.package import Packages
from . import manifest, privileged
logger = logging.getLogger(__name__)
_description = [
_('A Secure Shell server uses the secure shell protocol to accept '
'connections from remote computers. An authorized remote computer '
'can perform administration tasks, copy files or run other services '
'using such connections.')
]
class SSHApp(app_module.App):
"""FreedomBox app for SSH."""
app_id = 'ssh'
_version = 4
def __init__(self) -> None:
"""Create components for the app."""
super().__init__()
info = app_module.Info(app_id=self.app_id, version=self._version,
is_essential=True,
name=_('Secure Shell Server'),
icon='fa-terminal', description=_description,
manual_page='SecureShell', tags=manifest.tags)
self.add(info)
menu_item = menu.Menu('menu-ssh', info.name, info.icon, info.tags,
'ssh:index',
parent_url_name='system:administration',
order=10)
self.add(menu_item)
packages = Packages('packages-ssh', ['openssh-server'])
self.add(packages)
dropin_configs = DropinConfigs('dropin-configs-ssh', [
'/etc/fail2ban/jail.d/ssh-freedombox.conf',
])
self.add(dropin_configs)
dropin_configs = DropinConfigs('dropin-config-ssh-avahi', [
'/etc/avahi/services/sftp-ssh.service',
'/etc/avahi/services/ssh.service',
], copy_only=True)
self.add(dropin_configs)
firewall = Firewall('firewall-ssh', info.name, ports=['ssh'],
is_external=True)
self.add(firewall)
daemon = Daemon('daemon-ssh', 'ssh')
self.add(daemon)
groups = {
'freedombox-ssh': _('Remotely login using Secure Shell (SSH)')
}
users_and_groups = UsersAndGroups('users-and-groups-ssh',
groups=groups)
self.add(users_and_groups)
backup_restore = BackupRestore('backup-restore-ssh', **manifest.backup)
self.add(backup_restore)
def setup(self, old_version):
"""Install and configure the app."""
super().setup(old_version)
privileged.setup()
if not old_version:
self.enable()
elif old_version == 2 and privileged.are_users_restricted():
privileged.restrict_users(True)
elif old_version == 1:
privileged.restrict_users(True)
def get_host_keys():
"""Return Host keys of the system."""
etc_ssh = pathlib.Path('/etc/ssh/')
host_keys = []
pattern = re.compile(r'^(?P<bit_size>\d+) (?P<fingerprint>[\S]+) '
r'.+ \((?P<algorithm>\w+)\)$')
for public_key in etc_ssh.glob('*.pub'):
try:
process = subprocess.run(
['ssh-keygen', '-l', '-f',
str(public_key)], stdout=subprocess.PIPE,
stderr=subprocess.PIPE, check=True)
output = process.stdout.decode().strip()
if output:
match = re.match(pattern, output)
if match:
host_keys.append(match.groupdict())
except subprocess.CalledProcessError as exception:
logger.warning(
'Unable to read SSH host public key file: %s, '
'returncode=%s, stdout=%s, stderr=%s', public_key,
exception.returncode, exception.stdout.decode(),
exception.stderr.decode())
return host_keys
@@ -0,0 +1,3 @@
[Unit]
# The service depends on users and groups defined in LDAP
After=nslcd.service
@@ -0,0 +1,12 @@
<?xml version="1.0" standalone='no'?><!--*-nxml-*-->
<!DOCTYPE service-group SYSTEM "avahi-service.dtd">
<service-group>
<name replace-wildcards="yes">%h SFTP server</name>
<service>
<type>_sftp-ssh._tcp</type>
<port>22</port>
</service>
</service-group>
@@ -0,0 +1,12 @@
<?xml version="1.0" standalone='no'?><!--*-nxml-*-->
<!DOCTYPE service-group SYSTEM "avahi-service.dtd">
<service-group>
<name replace-wildcards="yes">%h</name>
<service>
<type>_ssh._tcp</type>
<port>22</port>
</service>
</service-group>
@@ -0,0 +1,2 @@
[sshd]
enabled = true
@@ -0,0 +1 @@
plinth.modules.ssh
+26
View File
@@ -0,0 +1,26 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
FreedomBox configuration form for OpenSSH server.
"""
from django import forms
from django.utils.translation import gettext_lazy as _
class SSHServerForm(forms.Form):
"""SSH server configuration form."""
password_auth_disabled = forms.BooleanField(
label=_('Disable password authentication'),
help_text=_('Improves security by preventing password guessing. '
'Ensure that you have setup SSH keys in your '
'administrator user account before enabling this option.'),
required=False,
)
allow_all = forms.BooleanField(
label=_('Allow all users to login remotely'),
help_text=_('Allow all users who have a valid account to login '
'remotely via SSH. When disabled, only users of groups '
'root, admin and freedombox-ssh can login via SSH.'),
required=False,
)
+22
View File
@@ -0,0 +1,22 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Application manifest for ssh.
"""
from django.utils.translation import gettext_lazy as _
backup = {
'config': {
'files': ['/etc/ssh/sshd_config.d/freedombox.conf']
},
'secrets': {
'files': [
'/etc/ssh/ssh_host_ecdsa_key', '/etc/ssh/ssh_host_ecdsa_key.pub',
'/etc/ssh/ssh_host_ed25519_key',
'/etc/ssh/ssh_host_ed25519_key.pub', '/etc/ssh/ssh_host_rsa_key',
'/etc/ssh/ssh_host_rsa_key.pub'
]
}
}
tags = [_('SSH'), _('Remote terminal'), _('Fingerprints')]
+142
View File
@@ -0,0 +1,142 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Configuration helper for SSH server."""
import grp
import os
import pathlib
import pwd
import shutil
import stat
import augeas
from plinth import action_utils, utils
from plinth.actions import privileged, secret_str
config_file = pathlib.Path('/etc/ssh/sshd_config.d/freedombox.conf')
def _validate_user(username, password, must_be_admin=True):
"""Validate a user."""
if must_be_admin:
try:
admins = grp.getgrnam('admin').gr_mem
except KeyError:
admins = []
if username not in admins:
msg = f'"{username}" is not authorized to perform this action'
raise PermissionError(msg)
if not utils.is_authenticated_user(username, password):
raise PermissionError('Invalid credentials')
def _managed_user(username):
"""Raise an error if the user is root."""
if pwd.getpwnam(username).pw_gid == 0:
raise ValueError(f'User {username} is not managed by FreedomBox')
return username
@privileged
def setup():
"""Setup Open SSH server.
Regenerates deleted SSH keys. This is necessary when FreedomBox image is
being used. During the image building process the SSH keys are removed and
start OpenSSH server fails without the keys.
If the keys already exist, do nothing. This is necessary when a user
installs FreedomBox using an apt package. SSH keys exist and running
reconfigure on the openssh-server package does not regenerate them.
"""
action_utils.dpkg_reconfigure('openssh-server', {})
@privileged
def restrict_users(should_restrict: bool):
"""Restrict SSH logins to groups root, sudo, admin and freedombox-ssh."""
if not should_restrict:
config_file.unlink(missing_ok=True)
else:
config_file.write_text('AllowGroups root sudo admin freedombox-ssh\n',
encoding='utf-8')
action_utils.service_reload('sshd')
def are_users_restricted() -> bool:
"""Return whether only restricted groups of users are allowed."""
return config_file.exists()
def get_user_homedir(username):
"""Return the home dir of a user by looking up in password database."""
try:
return pwd.getpwnam(username).pw_dir
except KeyError:
raise ValueError('Username not found')
@privileged
def get_keys(user: str) -> str:
"""Get SSH authorized keys."""
path = os.path.join(get_user_homedir(user), '.ssh', 'authorized_keys')
try:
with open(path, 'r', encoding='utf-8') as file_handle:
return file_handle.read()
except FileNotFoundError:
return ''
@privileged
def set_keys(user: str, keys: str, auth_user: str, auth_password: secret_str):
"""Set SSH authorized keys."""
must_be_admin = user != auth_user
_validate_user(auth_user, auth_password, must_be_admin=must_be_admin)
ssh_folder = os.path.join(get_user_homedir(user), '.ssh')
key_file_path = os.path.join(ssh_folder, 'authorized_keys')
action_utils.run(['mkhomedir_helper', user], check=True)
if not os.path.exists(ssh_folder):
os.makedirs(ssh_folder)
shutil.chown(ssh_folder, user, 'users')
with open(key_file_path, 'w', encoding='utf-8') as file_handle:
file_handle.write(keys)
shutil.chown(key_file_path, user, 'users')
os.chmod(key_file_path, stat.S_IRUSR | stat.S_IWUSR)
def _load_augeas():
"""Initialize augeas for this app's configuration file."""
aug = augeas.Augeas(flags=augeas.Augeas.NO_LOAD +
augeas.Augeas.NO_MODL_AUTOLOAD)
aug.set('/augeas/load/Sshd/lens', 'Sshd.lns')
aug.set('/augeas/load/Sshd/incl[last() + 1]', '/etc/ssh/sshd_config')
aug.load()
return aug
@privileged
def is_password_authentication_enabled() -> bool:
"""Retrieve value of password authentication from sshd configuration."""
aug = _load_augeas()
field_path = '/files/etc/ssh/sshd_config/PasswordAuthentication'
get_value = aug.get(field_path)
return (get_value or 'yes') == 'yes'
@privileged
def set_password_authentication(enable: bool):
"""Set value of password authentication in sshd configuration."""
value = 'yes' if enable else 'no'
aug = _load_augeas()
aug.set('/files/etc/ssh/sshd_config/PasswordAuthentication', value)
aug.save()
+38
View File
@@ -0,0 +1,38 @@
{% extends "app.html" %}
{% comment %}
# SPDX-License-Identifier: AGPL-3.0-or-later
{% endcomment %}
{% load bootstrap %}
{% load i18n %}
{% block status %}
{{ block.super }}
<h3>{% trans "Server Fingerprints" %}</h3>
<p>
{% blocktrans trimmed %}
When connecting to the server, ensure that the fingerprint shown by the
SSH client matches one of these fingerprints.
{% endblocktrans %}
</p>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>{% trans "Algorithm" %}</th>
<th>{% trans "Fingerprint" %}</th>
</tr>
</thead>
<tbody>
{% for host_key in host_keys %}
<tr>
<td>{{ host_key.algorithm }}</td>
<td><samp>{{ host_key.fingerprint }}</samp></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
Whitespace-only changes.
@@ -0,0 +1,28 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Functional, browser based tests for ssh app.
"""
import pytest
from plinth.tests.functional import BaseAppTests
pytestmark = [pytest.mark.system, pytest.mark.ssh]
class TestSshApp(BaseAppTests):
app_name = 'ssh'
has_service = True
has_web = False
disable_after_tests = False
# TODO: Improve test_backup_restore to actually check that earlier
# ssh certificate has been restored.
def test_enable_disable(self, session_browser):
"""Skip test for enabling and disabling the app."""
pytest.skip('Avoid restarting SSH server')
def test_backup_restore(self, session_browser):
"""Skip test for backup and restore operations."""
pytest.skip('Avoid restarting SSH server')
+12
View File
@@ -0,0 +1,12 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
URLs for the Secure Shell Server module.
"""
from django.urls import re_path
from plinth.modules.ssh.views import SshAppView
urlpatterns = [
re_path(r'^sys/ssh/$', SshAppView.as_view(), name='index'),
]
+64
View File
@@ -0,0 +1,64 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Views for the SSH app."""
from django.contrib import messages
from django.utils.translation import gettext_lazy as _
from plinth.modules import ssh
from plinth.privileged import service as service_privileged
from plinth.views import AppView
from . import privileged
from .forms import SSHServerForm
class SshAppView(AppView):
"""Show ssh app main page."""
app_id = 'ssh'
template_name = 'ssh.html'
form_class = SSHServerForm
def get_context_data(self, *args, **kwargs):
"""Return additional context for rendering the template."""
context = super().get_context_data(**kwargs)
context['host_keys'] = ssh.get_host_keys()
return context
def get_initial(self):
"""Return initial values of the form."""
initial = super().get_initial()
initial.update({
'password_auth_disabled':
not privileged.is_password_authentication_enabled(),
'allow_all':
not privileged.are_users_restricted()
})
return initial
def form_valid(self, form):
"""Apply changes from the form."""
old_config = self.get_initial()
new_config = form.cleaned_data
updated = False
def is_field_changed(field):
return old_config[field] != new_config[field]
passwd_auth_changed = is_field_changed('password_auth_disabled')
if passwd_auth_changed:
privileged.set_password_authentication(
not new_config['password_auth_disabled'])
service_privileged.reload('ssh')
updated = True
if is_field_changed('allow_all'):
privileged.restrict_users(not new_config['allow_all'])
updated = True
if updated:
messages.success(self.request, _('Configuration updated'))
return super().form_valid(form)