Это старая версия документа.


Защита серверов Samba

Режимы безопасности Samba

Доступны два уровня безопасности для сетевого протокола CIFS (разделяемая файловая система интернета): уровень пользователя (user-level) и уровень ресурса (share-level). Реализация режима безопасности Samba обеспечивает большую гибкость, предоставляя четыре способа реализации уровня пользователя и один вариант реализации уровня разделяемого ресурса:

  1. security = user: требует от клиента предоставить имя пользователя и пароль для подключения к ресурсу. Учетные записи пользователей Samba отделены от системных учетных записей, но пакет libpam-smbpass синхронизирует системных пользователей и пароли с пользовательской базой Samba.

  2. security = domain: этот режим позволяет серверу Samba представляться клиентам Windows первичным доменным контроллером (PDC), резервным доменным контроллером (BDC) или сервером-членом домена (DMS). Смотрите раздел Samba как контроллер домена для дополнительной информации.

  3. security = ADS: позволяет серверу Samba присоединиться к домену Active Directory как родному. Смотрите раздел Интеграция Samba с Active Directory для уточнения деталей.

  4. security = server: этот режим оставлен с тех времен, когда Samba не мог становиться членом домена и по ряду причин, связанных с безопасностью, не может использоваться. Смотрите раздел Server Security руководства по Samba для уточнения деталей.

  5. security = share: позволяет клиентам подключаться к разделяемому ресурсу без предоставления имени пользователя и пароля.

Режим безопасности, который вы выберете, будет зависеть от вашего окружения и того что вы хотите получить от сервера Samba.

Security = User

В этой секции рассматривается как перенастроить сервера файлов и печати Samba, настроенные в разделах Файловый сервер Samba и Сервер печати Samba, чтобы они требовали аутентификацию.

Сначала установим пакет libpam-smbpass, который будет синхронизировать системных пользователей с базой пользователей Samba:

sudo apt-get install libpam-smbpass
Если вы выбирали задачу Samba сервер в процессе установки сервера, то libpam-smbpass уже установлен.

Отредактируйте /etc/samba/smb.conf, и измените в секции [share]:

guest ok = no

Наконец перезагрузите Samba, чтобы воспринялась новая конфигурация:

sudo restart smbd
sudo restart nmbd

Теперь при подсоединении к разделяемым каталогам или принтерам у вас будет запрашиваться имя пользователя и пароль.

Если вы выбираете подсоединение к разделяемому сетевому носителю, то можете установить флажок "Переподключение при входе" ("Reconnect at Logon"), который позволит вам вводить имя и пароль один раз, по крайней мере до смены пароля.

Безопасность разделяемого ресурса

Существует несколько опций для усиления безопасности по каждому конкретному разделяемому каталогу. На примере [share], эта секция рассматривает наиболее распространенные опции.

Группы

Группы определяют коллекции компьютеров или пользователей, которые имеют общий уровень доступа к определенным сетевым ресурсам, и обеспечивают уровень модульности при управлении доступом к этим ресурсам. Например, если определены группа qa, которая содержит пользователей freda, danika и rob, и другая группа support, которая содержит пользователей danika, jeremy и vincent, то некоторый сетевой ресурс, настроенный на доступ группы qa, будет соответственно предоставлять доступ для freda, danika и rob, но не jeremy или vincent. Поскольку пользователь danika относится к обеим группам qa и support, она будет иметь доступ к ресурсам, настроенным на доступ для любой из этих групп, в то время как все остальные - только к ресурсам, настроенным на определенные группы, которым они принадлежат.

По умолчанию Samba ищет локальные системные группы, объявленные в /etc/group для определения какие пользователи им принадлежат. Для дополнительной информации по добавлению и удалению пользователей в группах смотрите раздел Добавление и удаление пользователей.

When defining groups in the Samba configuration file, /etc/samba/smb.conf, the recognized syntax is to preface the group name with an «@» symbol. For example, if you wished to define a group named sysadmin in a certain section of the /etc/samba/smb.conf, you would do so by entering the group name as @sysadmin.

Права доступа к файлам

File Permissions define the explicit rights a computer or user has to a particular directory, file, or set of files. Such permissions may be defined by editing the /etc/samba/smb.conf file and specifying the explicit permissions of a defined file share.

For example, if you have defined a Samba share called share and wish to give read-only permissions to the group of users known as qa, but wanted to allow writing to the share by the group called sysadmin and the user named vincent, then you could edit the /etc/samba/smb.conf file, and add the following entries under the [share] entry:

  read list = @qa
  write list = @sysadmin, vincent

Another possible Samba permission is to declare administrative permissions to a particular shared resource. Users having administrative permissions may read, write, or modify any information contained in the resource the user has been given explicit administrative permissions to.

For example, if you wanted to give the user melissa administrative permissions to the share example, you would edit the /etc/samba/smb.conf file, and add the following line under the [share] entry:

  admin users = melissa

After editing /etc/samba/smb.conf, restart Samba for the changes to take effect:

sudo restart smbd sudo restart nmbd

For the read list and write list to work the Samba security mode must not be set to security = share

Now that Samba has been configured to limit which groups have access to the shared directory, the filesystem permissions need to be updated.

Traditional Linux file permissions do not map well to Windows NT Access Control Lists (ACLs). Fortunately POSIX ACLs are available on Ubuntu servers providing more fine grained control. For example, to enable ACLs on /srv an EXT3 filesystem, edit /etc/fstab adding the acl option:

UUID=66bcdd2e-8861-4fb0-b7e4-e61c569fe17d /srv ext3 noatime,relatime,acl 0 1

Then remount the partition:

sudo mount -v -o remount /srv

The above example assumes /srv on a separate partition. If /srv, or wherever you have configured your share path, is part of the / partition a reboot may be required.

To match the Samba configuration above the sysadmin group will be given read, write, and execute permissions to /srv/samba/share, the qa group will be given read and execute permissions, and the files will be owned by the username melissa. Enter the following in a terminal:

sudo chown -R melissa /srv/samba/share/ sudo chgrp -R sysadmin /srv/samba/share/ sudo setfacl -R -m g:qa:rx /srv/samba/share/

The setfacl command above gives execute permissions to all files in the /srv/samba/share directory, which you may or may not want.

Now from a Windows client you should notice the new file permissions are implemented. See the acl and setfacl man pages for more information on POSIX ACLs.

Профиль AppArmor для Samba

Ubuntu comes with the AppArmor security module, which provides mandatory access controls. The default AppArmor profile for Samba will need to be adapted to your configuration. For more details on using AppArmor see AppArmor.

There are default AppArmor profiles for /usr/sbin/smbd and /usr/sbin/nmbd, the Samba daemon binaries, as part of the apparmor-profiles packages. To install the package, from a terminal prompt enter:

sudo apt-get install apparmor-profiles apparmor-utils

This package contains profiles for several other binaries.

By default the profiles for smbd and nmbd are in complain mode allowing Samba to work without modifying the profile, and only logging errors. To place the smbd profile into enforce mode, and have Samba work as expected, the profile will need to be modified to reflect any directories that are shared.

Edit /etc/apparmor.d/usr.sbin.smbd adding information for [share] from the file server example:

/srv/samba/share/ r,
/srv/samba/share/** rwkix,

Now place the profile into enforce and reload it:

sudo aa-enforce /usr/sbin/smbd cat /etc/apparmor.d/usr.sbin.smbd | sudo apparmor_parser -r

You should now be able to read, write, and execute files in the shared directory as normal, and the smbd binary will have access to only the configured files and directories. Be sure to add entries for each directory you configure Samba to share. Also, any errors will be logged to /var/log/syslog.

Ссылки

  For in depth Samba configurations see the Samba HOWTO Collection
  The guide is also available in printed format.
  O'Reilly's Using Samba is also a good reference.
  Chapter 18 of the Samba HOWTO Collection is devoted to security.
  For more information on Samba and ACLs see the Samba ACLs page .
  The Ubuntu Wiki Samba page.