Все о smb ports firewall

Cетевой обмен по протоколу SMB / SAMBA

Применение протоколов SMB / Samba позволяет осуществлять доступ с STB (работает под управлением ОС Linux) к папкам и файлам, расположенным на сетевых компьютерах (работающих под управлением ОС Linux, Windows и др.). Таким образом, пользователи STB получают возможность проигрывать на STB медиа-файлы (видео, аудио, изображения), которые расположены на сетевых компьютерах, работающих под управлением одного из типов ОС, поддерживающей протокол SMB.

Протокол Протокол SMB / Samba использует архитектуру клиент – сервер: в качестве сервера выступает ПК, на котором размещаются определенные сетевые ресурсы (папки) с медиа-файлами, в качестве клиента – STB, с которого медиа-файлы проигрываются.

Сетевые ресурсы (в виде ярлыков) отображаются в STB, в меню , в соответствии со стандартной сетевой LAN-архитектурой ОС Windows: Сеть / Рабочая группа / Компьютер / Папка.

По умолчанию, доступ к ресурсам компьютера закрыт настройками на стороне компьютера. При необходимости получить доступ к определенной сетевой папке, пользователь компьютера открывает доступ к этой папке. Для управления доступом к папкам используется процедура ОС Windows «Общий доступ к файлам».

Предусмотрены два типа сетевого доступа к папкам (тип доступа определяется на стороне сервера):

  • по паролю — для доступа к сетевой папке со стороны STB используется процедура Авторизации (необходимо ввести имя (login) определенного пользователя компьютера и его пароль (password);
  • без пароля — доступ к сетевой папке открыт для всех пользователей, без необходимости вводить пароль.

Обнаружение общих сетевых ресурсов на стороне STB происходит автоматически (если это не запрещено на стороне компьютера или кроме случаев, связанных с некорректной работой сети). Соединение с сетевой папкой устанавливается, когда пользователь STB открывает сетевую папку. Если используется доступ к папке по паролю, пользователю выдается запрос указать login и password.

Также предусмотрена возможность ручного подключения сетевых папок (если они не были обнаружены автоматически). Настройка и доступ к ресурсам сети по протоколу SMB Samba на STB проводится в меню Home media.

Ниже рассмотрен пример, как подключить сетевую папку ПК с ОС Windows 10 для воспроизведения медиа-файлов с STB.

Безопасность

За прошедшие годы в реализации протокола или компонентов Microsoft, на которые она напрямую полагается, обнаружилось множество уязвимостей. Уязвимости системы безопасности других производителей заключаются в основном в отсутствии поддержки новых протоколов аутентификации, таких как NTLMv2 и Kerberos, в пользу таких протоколов, как NTLMv1, LanMan или паролей в виде открытого текста. Отслеживание атак в режиме реального времени показывает, что SMB является одним из основных векторов атак для попыток вторжения, например, атака Sony Pictures в г. и атака вымогателя WannaCry в 2017 г. В 2020 г. были обнаружены две уязвимости SMB высокой степени опасности, названные SMBGhost

Disable SMBv1 Server with Group Policy

This procedure configures the following new item in the registry:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters

  • Registry entry: SMB1
  • REG_DWORD: = Disabled

To configure this by using Group Policy, follow these steps:

  1. Open the Group Policy Management Console. Right-click the Group Policy object (GPO) that should contain the new preference item, and then click Edit.

  2. In the console tree under Computer Configuration, expand the Preferences folder, and then expand the Windows Settings folder.

  3. Right-click the Registry node, point to New, and select Registry Item.

In the New Registry Propertiesdialog box, select the following:

  • Action: Create
  • Hive: HKEY_LOCAL_MACHINE
  • Key Path: SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters
  • Value name: SMB1
  • Value type: REG_DWORD
  • Value data: 0

This disables the SMBv1 Server components. This Group Policy must be applied to all necessary workstations, servers, and domain controllers in the domain.

Note

 WMI filters can also be set to exclude unsupported operating systems or selected exclusions, such as Windows XP.

Important

Be careful when you make these changes on domain controllers on which legacy Windows XP or older Linux and third-party systems (that do not support SMBv2 or SMBv3) require access to SYSVOL or other file shares where SMB v1 is being disabled.

API

var smb2Client = new SMB2 ( options )

The SMB2 class is the constructor of your SMB2 client.

the parameter accepts this list of attributes:

  • (mandatory): the share you want to access
  • (mandatory): the domain of which the user is registred
  • (mandatory): the username of the user that access the share
  • (mandatory): the password
  • (optional): default , the port of the SMB server
  • (optional): default , the number of simulatanous packet when writting / reading data from the share
  • (optional): default , the timeout in milliseconds before to close the SMB2 session and the socket, if setted to the connection will never be closed unless you do it

Example:

// load the library
var SMB2 = require('smb2');

// create an SMB2 instance
var smb2Client = new SMB2({
  share:'\\\\000.000.000.000\\c$'
, domain:'DOMAIN'
, username:'username'
, password:'password!'
});

smb2Client.readdir ( path, callback )

Asynchronous readdir(3). Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding ‘.’ and ‘..’.

Example:

smb2Client.readdir('Windows\\System32', function(err, files){
    if(err) throw err;
    console.log(files);
});

smb2Client.readFile ( filename, , callback )

  • String
  • Object
  • Function

Asynchronously reads the entire contents of a file. Example:

smb2Client.readFile('path\\to\\my\\file.txt', function(err, data){
    if(err) throw err;
    console.log(data);
});

The callback is passed two arguments (err, data), where data is the contents of the file.

If no encoding is specified, then the raw buffer is returned.

smb2Client.writeFile ( filename, data, , callback )

  • String
  • String | Buffer
  • Object
  • Function

Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.

The encoding option is ignored if data is a buffer. It defaults to ‘utf8’.

Example:

smb2Client.writeFile('path\\to\\my\\file.txt', 'Hello Node', function (err) {
    if (err) throw err;
    console.log('It\'s saved!');
});

smb2Client.mkdir ( path, , callback )

Asynchronous mkdir(2). No arguments other than a possible exception are given to the completion callback. mode defaults to 0777.

Example:

smb2Client.mkdir('path\\to\\the\\folder', function (err) {
    if (err) throw err;
    console.log('Folder created!');
});

smb2Client.rmdir ( path, callback )

Asynchronous rmdir(2). No arguments other than a possible exception are given to the completion callback.

Example:

smb2Client.rmdir('path\\to\\the\\folder', function (err) {
    if (err) throw err;
    console.log('Folder deleted!');
});

smb2Client.exists ( path, callback )

Test whether or not the given path exists by checking with the file system. Then call the callback argument with either true or false. Example:

smb2Client.exists('path\\to\\my\\file.txt', function (err, exists) {
    if (err) throw err;
    console.log(exists ? "it's there" : "it's not there!");
});

smb2Client.unlink ( path, callback )

Asynchronous unlink(2). No arguments other than a possible exception are given to the completion callback.

smb2Client.unlink('path\\to\\my\\file.txt', function (err) {
    if (err) throw err;
    console.log("file has been deleted");
});

smb2Client.rename ( oldPath, newPath, callback )

Asynchronous rename(2). No arguments other than a possible exception are given to the completion callback.

smb2Client.rename('path\\to\\my\\file.txt', 'new\\path\\to\\my\\new-file-name.txt', function (err) {
    if (err) throw err;
    console.log("file has been renamed");
});

smb2Client.close ( )

This function will close the open connection if opened, it will be called automatically after ms of no SMB2 call on the server.

Как на Windows 10 включить SMB1

Как уже было сказано выше, по соображениям безопасности в десятке SMB1 попросту отключен. Именно поэтому и появляется ошибка, по которой Windows 10 не видит Samba или NAS. Несмотря на это, существуют способы активировать поддержку технологии самостоятельно. Они то и описаны далее.

Использование настройки компонентов для включения протокола

Самый простой способ справиться с проблемой, когда Windows 10 не видит сетевые папки. Он основан на использовании раздела «Программы и компоненты», который является предустановленным в современных версиях операционных систем виндовс. В десятке он также имеется.

Общая пошаговая инструкция по активации SMB1 выглядит следующим образом:

  1. Переходят в меню «Пуск» и прописывают в поисковой строке «программы и компоненты».
  2. Дожидаются окончания поиска и выбирают соответствующий результат.
  3. После открытия окна с установленными программами переходят по ссылке «Включение и отключение компонентов виндовс», которая находится слева.
  4. Дожидаются открытия диалогового окна «Компоненты системы» и ожидают прогрузки данных в нем. Это может занять около минуты.
  5. Находят пункт «SMB 1.0/CIFS File Sharing Support» и устанавливают галочку напротив него.
  6. Нажимают «Ок» и выполняют перезагрузку компьютера. После этого доступ к файлам и сетевым папкам должен появиться.

Обратите внимание! Попасть в окно «Программы и компоненты» можно и через панель управления. Достаточно найти ее в меню «Пуск» или в окне-утилите «Выполнить» прописать «control» и нажать на клавишу «Ввода»

Там это приложение ищется аналогичным образом.

Активация компонента

Как включить SMB1 через PowerShell

Аналогичное действие можно произвести и с помощью оболочки PowerShell. Включение поддержки компонента осуществляется путем ввода соответствующей команды. В следующей поэтапной инструкции подробно рассказано, как это сделать:

  1. Переходят в меню «Пуск» и выполняют поиск утилиты PowerShell.
  2. Переходят в ее окно и проверяют, отключен ли SMB1Protocol-Client по команде «Get-WindowsOptionalFeature -Online -FeatureName SMB1Protocol-Client».
  3. Если он отключен, то вводят команду «Enable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol-Client».
  4. Выполняют перезагрузку персонального компьютера и проверяют работоспособность принятых изменений.

More Information

To work around this issue, contact the manufacturer of the product that supports only SMBv1, and request a software or firmware update that support SMBv2.02 or a later version. For a current list of known vendors and their SMBv1 requirements, see the following Windows and Windows Server Storage Engineering Team Blog article:

Leasing mode

If SMBv1 is required to provide application compatibility for legacy software behavior, such as a requirement to disable oplocks, Windows provides a new SMB share flag that’s known as Leasing mode. This flag specifies whether a share disables modern SMB semantics such as leases and oplocks.

You can specify a share without using oplocks or leasing to allow a legacy application to work with SMBv2 or a later version. To do this, use the New-SmbShare or Set-SmbShare PowerShell cmdlets together with the -LeasingMode None parameter.

Note

You should use this option only on shares that are required by a third-party application for legacy support if the vendor states that it is required. Do not specify Leasing mode on user data shares or CA shares that are used by Scale-Out File Servers. This is because the removal of oplocks and leases causes instability and data corruption in most applications. Leasing mode works only in Share mode. It can be used by any client operating system.

Explorer Network Browsing

The Computer Browser service relies on the SMBv1 protocol to populate the Windows Explorer Network node (also known as «Network Neighborhood»). This legacy protocol is long deprecated, doesn’t route, and has limited security. Because the service cannot function without SMBv1, it is removed at the same time.

However, if you still have to use the Explorer Network in home and small business workgroup environments to locate Windows-based computers, you can follow these steps on your Windows-based computers that no longer use SMBv1:

  1. Start the «Function Discovery Provider Host» and «Function Discovery Resource Publication» services, and then set them to Automatic (Delayed Start).

  2. When you open Explorer Network, enable network discovery when you are prompted.

All Windows devices within that subnet that have these settings will now appear in Network for browsing. This uses the WS-DISCOVERY protocol. Contact your other vendors and manufacturers if their devices still don’t appear in this browse list after the Windows devices appear. It is possible they have this protocol disabled or that they support only SMBv1.

Note

 We recommend that you map drives and printers instead of enabling this feature, which still requires searching and browsing for their devices. Mapped resources are easier to locate, require less training, and are safer to use. This is especially true if these resources are provided automatically through Group Policy. An administrator can configure printers for location by methods other than the legacy Computer Browser service by using IP addresses, Active Directory Domain Services (AD DS), Bonjour, mDNS, uPnP, and so on.

If you cannot use any of these workarounds, or if the application manufacturer cannot provide supported versions of SMB, you can re-enable SMBv1 manually by following the steps in How to detect, enable and disable SMBv1, SMBv2, and SMBv3 in Windows.

Important

We strongly recommend that you don’t reinstall SMBv1. This is because this older protocol has known security issues regarding ransomware and other malware.

Windows Server best practices analyzer messaging

Windows Server 2012 and later server operation systems contain a best practices analyzer (BPA) for file servers. If you have followed the correct online guidance to uninstall SMB1, running this BPA will return a contradictory warning message:

You should ignore this specific BPA rule’s guidance, it’s deprecated. We repeat: don’t enable SMB 1.0.

Системные файлы, связанные с SMBSMB-related system files

В этом разделе перечислены системные файлы, связанные с SMB.This section lists the SMB-related system files. Чтобы обеспечить обновление системных файлов, убедитесь, что установлен последний накопительный пакет обновления .To keep the system files updated, make sure that the latest update rollup is installed.

Двоичные файлы клиента SMB, перечисленные в разделе % WINDIR% \ \ драйверы system32:SMB Client binaries that are listed under %windir%\system32\Drivers:

  • RDBSS.sysRDBSS.sys

  • MRXSMB.sysMRXSMB.sys

  • MRXSMB10.sysMRXSMB10.sys

  • MRXSMB20.sysMRXSMB20.sys

  • MUP.sysMUP.sys

  • SMBdirect.sysSMBdirect.sys

Двоичные файлы SMB Server, указанные в разделе % WINDIR% \ \ драйверы system32:SMB Server binaries that are listed under %windir%\system32\Drivers:

  • SRVNET.sysSRVNET.sys

  • SRV.sysSRV.sys

  • SRV2.sysSRV2.sys

  • SMBdirect.sysSMBdirect.sys

  • В папке % WINDIR% \ system32Under %windir%\system32

  • srvsvc.dllsrvsvc.dll

Обновление предложенийUpdate suggestions

Перед устранением проблем с SMB рекомендуется обновить следующие компоненты:We recommend that you update the following components before you troubleshoot SMB issues:

  • Файловый сервер требует наличия хранилища файлов.A file server requires file storage. Если в хранилище есть компонент iSCSI, обновите эти компоненты.If your storage has iSCSI component, update those components.

  • Обновите сетевые компоненты.Update the network components.

  • Для повышения производительности и стабильности обновите Windows Core.For better performance and stability, update Windows Core.

Принцип работы

CIFS — это протокол, основанный на технологии клиент-сервер, который предоставляет клиентским приложениям простой способ для чтения и записи файлов, а также запроса служб у серверных программ в различных типах сетевого окружения. Единственное отличие от модели клиент-сервер состоит в том, что, когда клиент посылает в качестве запроса возможные блокировки, то сервер вынужден отпустить уже предоставленную блокировку, так как другой клиент запросил открытие файла в режиме, несовместимом с предоставленной блокировкой. В этом случае сервер посылает клиенту уведомительное сообщение о том, что блокировка была снята. Серверы предоставляют файловые системы и другие ресурсы (принтеры, почтовые сегменты, именованные каналы и т. д.) для общего доступа в сети. Клиентские компьютеры могут иметь у себя свои носители информации, но также имеют доступ к ресурсам, предоставленным сервером для общего пользования.

Клиенты соединяются с сервером, используя протоколы TCP/IP (а, точнее, NetBIOS через TCP/IP), NetBEUI или IPX/SPX. После того, как соединение установлено, клиенты могут посылать команды серверу, который даёт им доступ к ресурсам, позволяет открывать, читать файлы, писать в файлы и вообще выполнять весь перечень действий, которые можно выполнять с файловой системой. Однако в случае использования CIFS эти действия совершаются через сеть.

CIFS определяет серию команд, используемых для передачи информации между сетевыми компьютерами. Запросы на перенаправление отправляют пакеты, предназначенные для удаленных компьютеров в структуре CIFS. CIFS можно отправлять по сети на удаленные устройства. Перенаправитель также использует CIFS для выполнения запросов к стеку протоколов локального компьютера. Сообщения CIFS могут быть в целом классифицированы следующим образом:

  • Сообщения установления соединения, состоящие из команд, которые запускают и завершают соединение перенаправителя с общим ресурсом на сервере.
  • Сообщения о пространстве имен и манипуляциях с файлами, использующиеся перенаправителем для получения доступа к файлам на сервере и для их чтения и записи.
  • Сообщения принтера, использующиеся перенаправителем для отправки данных в очередь печати на сервере и получения информации о состоянии очереди печати.
  • Различные сообщения, использующиеся перенаправителем для записи в mailslots (клиент-серверный интерфейс) и именованные каналы.

CIFS дополняет протокол передачи гипертекста (HTTP), обеспечивая более сложное совместное использование файлов и передачу файлов, чем старые протоколы, такие как FTP.
Компоненты в перенаправителе обеспечивают поддержку CIFS, например:

  • Rdbss.sys Все взаимодействия на уровне ядра инкапсулируются в этом драйвере. Сюда входят все менеджеры кэшей, диспетчеры памяти и запросы для удаленных файловых систем, чтобы указанный протокол мог использовать запрошенный сервер.
  • Mrxsmb.sys Этот мини-перенаправитель для CIFS имеет команды, специфичные для CIFS.
  • Mrxnfs.sys Этот мини-редиректор для сетевой файловой системы (NFS) обеспечивает поддержку NFS. Mrxnfs.sys включен в Службы для Unix.

В Windows NT 4.0 разрешение имен Windows Internet Name (WINS) и Domain Name System (DNS) было выполнено с использованием TCP-порта 134. Расширения для CIFS и NetBT теперь позволяют соединения непосредственно через TCP/IP с использованием TCP-порта 445. Оба способа разрешения все еще доступны в Windows 2000. Можно отключить одну или обе этих службы в реестре.

Disable SMBv1 Client with Group Policy

To disable the SMBv1 client, the services registry key needs to be updated to disable the start of MRxSMB10 and then the dependency on MRxSMB10 needs to be removed from the entry for LanmanWorkstation so that it can start normally without requiring MRxSMB10 to first start.

This will update and replace the default values in the following two items in the registry:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\mrxsmb10

Registry entry: Start REG_DWORD: 4= Disabled

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanWorkstation

Registry entry: DependOnService REG_MULTI_SZ: «Bowser»,»MRxSmb20″,»NSI»

Note

 The default included MRxSMB10 which is now removed as dependency.

To configure this by using Group Policy, follow these steps:

  1. Open the Group Policy Management Console. Right-click the Group Policy object (GPO) that should contain the new preference item, and then click Edit.

  2. In the console tree under Computer Configuration, expand the Preferences folder, and then expand the Windows Settings folder.

  3. Right-click the Registry node, point to New, and select Registry Item.

  4. In the New Registry Properties dialog box, select the following:

    • Action: Update
    • Hive: HKEY_LOCAL_MACHINE
    • Key Path: SYSTEM\CurrentControlSet\services\mrxsmb10
    • Value name: Start
    • Value type: REG_DWORD
    • Value data: 4
  5. Then remove the dependency on the MRxSMB10 that was just disabled.

    In the New Registry Properties dialog box, select the following:

    • Action: Replace
    • Hive: HKEY_LOCAL_MACHINE
    • Key Path: SYSTEM\CurrentControlSet\Services\LanmanWorkstation
    • Value name: DependOnService
    • Value type: REG_MULTI_SZ
    • Value data:
      • Bowser
      • MRxSmb20
      • NSI

    Note

    These three strings will not have bullets (see the following screen shot).

    The default value includes MRxSMB10 in many versions of Windows, so by replacing them with this multi-value string, it is in effect removing MRxSMB10 as a dependency for LanmanServer and going from four default values down to just these three values above.

    Note

    When you use Group Policy Management Console, you don’t have to use quotation marks or commas. Just type the each entry on individual lines.

  6. Restart the targeted systems to finish disabling SMB v1.

Auditing SMBv1 usage

To determine which clients are attempting to connect to an SMB server with SMBv1, you can enable auditing on Windows Server 2016, Windows 10, and Windows Server 2019. You can also audit on Windows 7 and Windows Server 2008 R2 if they installed the May 2018 monthly update and on Windows 8, Windows 8.1, Windows Server 2012, and Windows Server 2012 R2 if they installed the July 2017 monthly update.

  • Enable:

  • Disable:

  • Detect:

When SMBv1 auditing is enabled, event 3000 appears in the «Microsoft-Windows-SMBServer\Audit» event log, identifying each client that attempts to connect with SMBv1.

Summary

If all the settings are in the same Group Policy Object (GPO), Group Policy Management displays the following settings.

Testing and validation

After these are configured, allow the policy to replicate and update. As necessary for testing, run gpupdate /force at a command prompt, and then review the target computers to make sure that the registry settings are applied correctly. Make sure SMB v2 and SMB v3 is functioning for all other systems in the environment.

SPECIAL SECTIONS

The section

Parameters in this section apply to the server as a whole, or are defaults for sections that do not
specifically define certain items. See the notes under PARAMETERS for more information.

The section

If a section called is included in the configuration file, services connecting clients
to their home directories can be created on the fly by the server.

When the connection request is made, the existing sections are scanned. If a match is found, it is
used. If no match is found, the requested section name is treated as a username and looked up in the local
password file. If the name exists and the correct password has been given, a share is created by cloning the
section.

Some modifications are then made to the newly created share:

  • The share name is changed from homes to the located username.

  • If no path was given, the path is set to the user’s home directory.

If you decide to use a path = line in your section, it may be useful
to use the %S macro. For example:

is useful if you have different home directories for your PCs than for UNIX access.

This is a fast and simple way to give a large number of clients access to their home directories with a minimum
of fuss.

A similar process occurs if the requested section name is “homes”, except that the share
name is not changed to that of the requesting user. This method of using the section works well if
different users share a client PC.

The section can specify all the parameters a normal service section can specify, though some make more sense
than others. The following is a typical and suitable section:

An important point is that if guest access is specified in the section, all home directories will be
visible to all clients without a password. In the very unlikely event that this is actually
desirable, it is wise to also specify read only access.

The browseable flag for auto home directories will be inherited from the global browseable
flag, not the browseable flag. This is useful as it means setting browseable = no in
the section will hide the share but make any auto home directories visible.

Оцените статью
Рейтинг автора
5
Материал подготовил
Андрей Измаилов
Наш эксперт
Написано статей
116
Добавить комментарий