samba: private shares

- new share types - group and home shares
- users: when creating, deleting or changing user password, update also Samba
  tdbsam backend database
- users: new managed packages - samba-common-bin, tdb-tools
- module page: show current samba users who are in freedombox-share group
- module page: show users who should re-enter their password in the password change page
- fix: use os.path.ismount() from Python standard library to validate a mount point
- fix: samba share permissions, fixes #1729
- fix: delete a share - do not raise an exception if the share doesn't exist
- storage: show samba share type in the directory selection form

Closes #1727

Signed-off-by: Veiko Aasa <veiko17@disroot.org>
Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
Veiko Aasa authored and James Valleroy committed 2019-12-20 21:01:12 -05:00
1 parent 851d1c7c28
commit 83cb305026
10 files changed
+360 -172

No files matched your search

+53 -10
View File
@@ -18,7 +18,10 @@
FreedomBox app to configure samba.
"""
import grp
import json
import os
import pwd
import socket
from django.urls import reverse_lazy
@@ -34,7 +37,7 @@ from plinth.utils import format_lazy
from .manifest import backup, clients # noqa, pylint: disable=unused-import
version = 1
version = 2
managed_services = ['smbd', 'nmbd']
@@ -51,12 +54,18 @@ description = [
'other computers in your local network.'),
format_lazy(
_('After installation, you can choose which disks to use for sharing. '
'Enabled {hostname} shares are open to everyone in your local '
'network and are accessible under Network section in the file '
'manager on your computer.'), hostname=socket.gethostname().upper())
'Enabled shares are accessbile in the file manager on your computer '
'at location \\\\{hostname} (on Windows) or smb://{hostname}.local '
'(on Linux and Mac). There are three types of shares '
'you can choose from: '), hostname=socket.gethostname()),
_('Open share - accessible to everyone in your local network.'),
_('Group share - accessible only to FreedomBox users who are in the '
'freedombox-share group.'),
_('Home share - every user in the freedombox-share group can have their '
'own private space.'),
]
group = ('freedombox-share', _('Access shared folders from inside the server'))
group = ('freedombox-share', _('Access to the private shares'))
clients = clients
@@ -124,18 +133,43 @@ def diagnose():
return results
def add_share(mount_point, filesystem):
def add_share(mount_point, share_type, filesystem):
"""Add a share."""
command = ['add-share', '--mount-point', mount_point]
command = [
'add-share', '--mount-point', mount_point, '--share-type', share_type
]
if filesystem in ['ntfs', 'vfat']:
command = command + ['--windows-filesystem']
actions.superuser_run('samba', command)
def delete_share(mount_point):
def delete_share(mount_point, share_type):
"""Delete a share."""
command = ['delete-share', '--mount-point', mount_point]
actions.superuser_run('samba', command)
actions.superuser_run('samba', [
'delete-share', '--mount-point', mount_point, '--share-type',
share_type
])
def get_users():
"""Get non-system users who are in the freedombox-share or admin group."""
output = actions.superuser_run('samba', ['get-users'])
samba_users = json.loads(output)['users']
group_users = grp.getgrnam('freedombox-share').gr_mem + grp.getgrnam(
'admin').gr_mem
allowed_users = []
for group_user in group_users:
uid = pwd.getpwnam(group_user).pw_uid
if uid > 1000:
allowed_users.append(group_user)
return {
'access_ok':
sorted(set(allowed_users) & set(samba_users)),
'password_re_enter_needed':
sorted(set(allowed_users) - set(samba_users))
}
def get_shares():
@@ -145,6 +179,15 @@ def get_shares():
return json.loads(output)
def disk_name(mount_point):
"""Get a disk name."""
share_name = os.path.basename(mount_point)
if not share_name:
share_name = 'disk'
return share_name
def backup_pre(packet):
"""Save registry share configuration."""
actions.superuser_run('samba', ['dump-shares'])
-33
View File
@@ -1,33 +0,0 @@
/**
* @licstart The following is the entire license notice for the JavaScript
* code in this page.
*
* This file is part of FreedomBox.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @licend The above is the entire license notice for the JavaScript code
* in this page.
*/
$(document).on('turbolinks:load', function() {
const share_checkbox = $(".shareform > input[type='checkbox']");
share_checkbox.change(function(event) {
this.disabled=true;
this.style.cursor='wait';
this.form.submit();
});
});
+65 -52
View File
@@ -20,6 +20,7 @@
{% load bootstrap %}
{% load i18n %}
{% load plinth_extras %}
{% load static %}
{% block page_head %}
@@ -35,79 +36,91 @@
{{ block.super }}
{% if is_enabled %}
<h3>{% trans "Select disks for sharing" %}</h3>
<h3>{% trans "Shares" %}</h3>
<p>
{% blocktrans trimmed %}
Note: only specially created directory will be shared on selected disks,
Note: only specially created directories will be shared on selected disks,
not the whole disk.
{% endblocktrans %}
</p>
<table class="table table-bordered table-condensed table-striped">
<table class="table table-bordered table-condensed table-striped">
<thead>
<tr>
<th></th>
<th>{% trans "Device" %}</th>
<th>{% trans "Label" %}</th>
<th>{% trans "Mount Point" %}</th>
<th>{% trans "Type" %}</th>
<th>{% trans "Disk Name" %}</th>
<th>{% trans "Shares" %}</th>
<th>{% trans "Used" %}</th>
</tr>
</thead>
<tbody>
{% for disk in disks %}
{% for disk in disks %}
<tr>
<td>{{ disk.name|default_if_none:"" }}</td>
<td>
{% if disk.mount_point in shared_mounts %}
<form class="form shareform" method="post"
action="{% url 'samba:unshare' disk.mount_point|urlencode:'' %}">
{% csrf_token %}
<input type="checkbox" value="{{ disk.mount_point }}"
name="mount_point" autocomplete="off" checked/>
</form>
{% else %}
<form class="form shareform" method="post"
action="{% url 'samba:share' disk.mount_point|urlencode:'' %}">
{% csrf_token %}
<input type="hidden" value="{{ disk.filesystem_type }}"
name="filesystem_type">
<input type="checkbox" value="{{ disk.mount_point }}"
name="mount_point" autocomplete="off"
{% if disk.filesystem_type == 'vfat' %}
title='{% trans "vfat partitions are not supported" %}' disabled
{% endif %}/>
</form>
{% endif %}
<form class="form shareform" method="post"
action="{% url 'samba:share' disk.mount_point|urlencode:'' %}">
{% csrf_token %}
<input type="hidden" name="filesystem_type" value="{{ disk.filesystem_type }}">
{% for share_type in share_types %}
<button type="submit"
{% if share_type.0 in shared_mounts|lookup:disk.mount_point %}
class="btn btn-success" name="{{ share_type.0 }}_share" value="disable"
{% else %}
class="btn btn-default" name="{{ share_type.0 }}_share" value="enable"
{% endif %}
{% if disk.filesystem_type == 'vfat' %}
title='{% trans "vfat partitions are not supported" %}' disabled
{% endif %}>{{ share_type.1 }}
</button>
{% endfor %}
</form>
</td>
<td>{{ disk.device }}</td>
<td>{{ disk.label|default_if_none:"" }}</td>
<td>{{ disk.mount_point }}</td>
<td>{{ disk.filesystem_type }}</td>
<td>
<td >
<div class="progress">
{% if disk.percent_used < 75 %}
<div class="progress-bar progress-bar-striped progress-bar-success"
{% elif disk.percent_used < 90 %}
<div class="progress-bar progress-bar-striped progress-bar-warning"
<div class="progress-bar progress-bar-striped progress-bar-warning"
{% else %}
<div class="progress-bar progress-bar-striped progress-bar-danger"
<div class="progress-bar progress-bar-striped progress-bar-danger"
{% endif %}
role="progressbar" aria-valuenow="disk.percent_used"
aria-valuemin="0" aria-valuemax="100"
style="width: {{ disk.percent_used }}%;">
{{ disk.percent_used }}%
</div>
</div>
<div>{{ disk.used_str }} / {{ disk.size_str }}</div>
role="progressbar" aria-valuenow="{{ disk.percent_used }}"
aria-valuemin="0" aria-valuemax="100"
style="width: {{ disk.percent_used }}%;">
{{ disk.percent_used }}%
</div>
</div>
<div>{{ disk.used_str }} / {{ disk.size_str }}</div>
</td>
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>
</table>
<p>
{% url 'storage:index' as storage_url %}
{% url 'users:index' as users_url %}
{% blocktrans trimmed %}
You can find additional information about disks on the
<a href="{{ storage_url }}">storage</a> module page and configure
access to the shares on the <a href="{{ users_url }}">users</a> module page.
{% endblocktrans %}</p>
<p>{% trans "Users who can currently access group and home shares" %}:
{{ users.access_ok|join:", " }}</p>
{% if users.password_re_enter_needed %}
<p>{% trans "Users who need to re-enter their password on the password change page to access group and home shares" %}:
<strong>{{ users.password_re_enter_needed|join:", " }}</strong>.</p>
{% endif %}
{% if unavailable_shares %}
<h3>{% trans "Shares configured but the disk is not available" %}</h3>
<h3>{% trans "Unavailable Shares" %}</h3>
<p>
{% trans "If the disk is plugged back in, sharing will be automatically enabled." %}
{% blocktrans trimmed %}
Shares that are configured but the disk is not available. If the disk
is plugged back in, sharing will be automatically enabled.
{% endblocktrans %}
</p>
<table class="table table-bordered table-condensed table-striped">
<thead>
@@ -122,9 +135,12 @@
<td>{{ share.name }}</td>
<td>
<form class="form" method="post"
action="{% url 'samba:unshare' share.mount_point|urlencode:'' %}">
action="{% url 'samba:share' share.mount_point|urlencode:'' %}">
{% csrf_token %}
<input type="submit" class="btn btn-danger" value="Delete">
<button type="submit" class="btn btn-danger"
name="{{ share.share_type }}_share"
value="disable">{% trans "Delete" %}
</button>
</form>
</td>
</tr>
@@ -135,6 +151,3 @@
{% endif %}
{% endblock %}
{% block page_js %}
<script type="text/javascript" src="{% static 'samba/samba.js' %}"></script>
{% endblock %}
+1 -3
View File
@@ -25,7 +25,5 @@ from . import views
urlpatterns = [
url(r'^apps/samba/$', views.SambaAppView.as_view(), name='index'),
url(r'^apps/samba/share/(?P<mount_point>[A-Za-z0-9%_.\-~]+)/$',
views.share, name='share'),
url(r'^apps/samba/unshare/(?P<mount_point>[A-Za-z0-9%_.\-~]+)/$',
views.unshare, name='unshare'),
views.share, name='share')
]
+43 -32
View File
@@ -20,13 +20,16 @@ Views for samba module.
import logging
import urllib.parse
from collections import defaultdict
from django.contrib import messages
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.translation import ugettext as _
from django.views.decorators.http import require_POST
from plinth import views
from plinth.errors import ActionError
from plinth.modules import samba, storage
logger = logging.getLogger(__name__)
@@ -45,9 +48,20 @@ class SambaAppView(views.AppView):
"""Return template context data."""
context = super().get_context_data(*args, **kwargs)
disks = storage.get_disks()
context['disks'] = disks
shares = samba.get_shares()
context['shared_mounts'] = [share['mount_point'] for share in shares]
for disk in disks:
disk['name'] = samba.disk_name(disk['mount_point'])
context['disks'] = disks
shared_mounts = defaultdict(list)
for share in shares:
shared_mounts[share['mount_point']].append(share['share_type'])
context['shared_mounts'] = shared_mounts
context['share_types'] = [('open', _('Open Share')),
('group', _('Group Share')),
('home', _('Home Share'))]
unavailable_shares = []
for share in shares:
@@ -58,6 +72,8 @@ class SambaAppView(views.AppView):
unavailable_shares.append(share)
context['unavailable_shares'] = unavailable_shares
context['users'] = samba.get_users()
return context
@@ -70,35 +86,30 @@ def share(request, mount_point):
"""
mount_point = urllib.parse.unquote(mount_point)
filesystem = request.POST.get('filesystem_type', '')
try:
samba.add_share(mount_point, filesystem)
messages.success(request, _('Share enabled.'))
except Exception as exception:
logger.exception('Error enabling share')
messages.error(
request,
_('Error enabling share: {error_message}').format(
error_message=exception))
return redirect(reverse('samba:index'))
@require_POST
def unshare(request, mount_point):
"""Disable sharing, given its name.
mount_point is urlquoted.
"""
mount_point = urllib.parse.unquote(mount_point)
try:
samba.delete_share(mount_point)
messages.success(request, _('Share disabled.'))
except Exception as exception:
logger.exception('Error disabling share')
messages.error(
request,
_('Error disabling share: {error_message}').format(
error_message=exception))
share_types = ['open', 'group', 'home']
for share_type in share_types:
action = request.POST.get(share_type + '_share', '')
if action == 'enable':
try:
samba.add_share(mount_point, share_type, filesystem)
messages.success(request, _('Share enabled.'))
except ActionError as exception:
logger.exception('Error enabling share')
messages.error(
request,
_('Error enabling share: {error_message}').format(
error_message=exception))
elif action == 'disable':
try:
samba.delete_share(mount_point, share_type)
messages.success(request, _('Share disabled.'))
except ActionError as exception:
logger.exception('Error disabling share')
messages.error(
request,
_('Error disabling share: {error_message}').format(
error_message=exception))
return redirect(reverse('samba:index'))
+9 -2
View File
@@ -150,8 +150,15 @@ class DirectorySelectForm(AppForm):
_('Default'), self.default))]
available_shares = get_available_samba_shares()
for share in available_shares:
choices = choices + [(share['path'], '{0} ({1}): {2}'.format(
_('Samba share'), share['name'], share['path']))]
if share['share_type'] != 'home':
share_type = _('Share')
if share['share_type'] == 'group':
share_type = _('Group Share')
elif share['share_type'] == 'open':
share_type = _('Open Share')
selection_text = 'Samba {0} ({1}): {2}'.format(
share_type, share['name'], share['path'])
choices = choices + [(share['path'], selection_text)]
choices = choices + [('/', _('Other directory (specify below)'))]
initial_value, subdir = self.get_initial(choices)
+1 -1
View File
@@ -34,7 +34,7 @@ is_essential = True
managed_packages = [
'ldapscripts', 'ldap-utils', 'libnss-ldapd', 'libpam-ldapd', 'nscd',
'nslcd', 'slapd'
'nslcd', 'samba-common-bin', 'slapd', 'tdb-tools'
]
first_boot_steps = [
+16 -2
View File
@@ -17,6 +17,7 @@
import subprocess
import plinth.forms
from django import forms
from django.contrib import auth, messages
from django.contrib.auth.forms import SetPasswordForm, UserCreationForm
@@ -24,8 +25,6 @@ from django.contrib.auth.models import Group, User
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_lazy
import plinth.forms
from plinth import actions, module_loader
from plinth.errors import ActionError
from plinth.modules import first_boot, users
@@ -262,6 +261,21 @@ class UserUpdateForm(ValidNewUsernameCheckMixin,
except ActionError:
messages.error(self.request, _('Unable to set SSH keys.'))
is_active = self.cleaned_data['is_active']
if self.initial['is_active'] != is_active:
if is_active:
status = 'active'
else:
status = 'inactive'
try:
actions.superuser_run(
'users',
['set-user-status',
user.get_username(), status])
except ActionError:
messages.error(self.request,
_('Failed to change user status.'))
return user
def validate_last_admin_user(self, groups):