Samba port no linux

How to mount a samba share on non-standard port?

The firewall on my network drops all packets on TCP port 139 and 445. So all samba shares don’t work outside the LAN. I tried letting the samba daemon listen on a non-standard port. This method works well for linux, because both smbclient and smbmount has an option to set server port. But on windows I cannot find a similar option. Does Windows support mounting smb shares on non-standard ports? Third-party softwares are also acceptable. Edit: \\hostname:port\share in Windows explorer doesn’t work. Strangely, I can see the connection is established on the server. But Windows keeps telling me that the server couldn’t be reached. It doesn’t work even in LAN with standard port 445, in which case a path without port number will get through.

In your case I would use a port redirector running on my local 127.0.0.1:139 and on 127.0.0.1:445, and I would redirect them to your destination ip. But I think a VPN solution would be more feasible (for example, openvpn).

4 Answers 4

Unfortunately, it is not possible as windows does only support ports 445 and 139

You might be able to use ssh tunneling. Here is a reference using windows and linux: https://www.ocf.berkeley.edu/~xuanluo/sshproxywin.html

Do you have a reference for the claim that Windows only supports 445 and 139? I don’t doubt it, but it would be nice to see something official, if it exists.

For those who are still looking for a way to mount SMB resources on a non-standard port, here is a great article on how to do this. I personally set up stunnel to wrap SMB traffic with SSL, since I access my SMB shares remotely over the Internet. Works like a charm.

This is possible! It’s been a good few years, but combining a loopback interface tutorial I found with portions out of @Mike’s [..link-only] answer (multihost version) I’ve created a script that can do this for you.

You can use this after running Install-Module -Name LoopbackAdapter -MinimumVersion 1.2.0.0 in an admin terminal (dont forget to dot-source the script so you can call this).

Create-Host -Name bob -Ip 10.254.0.1 -Dest ipOfHostname -Port port 

which [upon reboot] will allow you to go to \\bob (fake IP 10.254.0.1) which attaches to your «hostname:port» from your question.
This will persist across boots and you don’t need to re-run it if the source server goes up or down; teardown is as simple as Retire-Host -Name bob .

That easy, one command, programmatic, no gui/windows settings dialogs; but feel free to follow along below manually.

Explanation:

Use netsh portproxy to link a fake IP with your SMB server, this will make the nonstandard port accessible on one Explorer accepts.

#it's important IP's are used here, not hostnames netsh ` interface portproxy ` add v4tov4 ` listenaddress= ` listenport=445 ` connectaddress= ` connectport=

Optionally add the IP to your %windir%\System32\drivers\etc\hosts file so you don’t need to remember this IP (Eg interact with \\bob instead of \\10.254.0.1 ).

Читайте также:  Примонтировать файл в linux

Use DevCon to create a loopback network adapter, this «network» is what will host the IP.

$interface = New-LoopbackAdapter -Name

Disable conflicting/unused services that break various things.

$interface ` | Disable-NetAdapterBinding ` -ComponentID ms_msclient,ms_pacer,ms_server,ms_lltdio,ms_rspndr $interface ` | Set-DnsClient ` -RegisterThisConnectionsAddress $False ` -PassThru ` | Set-NetIPInterface ` -InterfaceMetric '254' ` -WeakHostSend Enabled ` -WeakHostReceive Enabled ` -Dhcp Disabled 

Set the IP your machine will be reachable at on this «network».

$interface ` | New-NetIPAddress ` -IPAddress ` -PrefixLength 32 ` -AddressFamily IPv4 

Done! Upon reboot the forwarding will have hooked up, and you can access it as long as your pc can access the remote port. The setup will not disappear until you manually tear it down.

It’s worth noting I only forward to 445 (and actually from 445 using ssh -L tunnelling to a machine on a network my pc cannot directly see), but it will simply be a change/additional netsh portproxy to swap/add the 139 equivalent if wanted.

To troubleshoot you can check windows is attempting to forward using

netsh interface portproxy show v4tov4 

whether that is successfully listening on the loopback device

and if your remote machine’s server is accepting connections

Test-NetConnection -ComputerName -Port

finally that the whole thing has come together (and maybe it’s some credential issue)

Test-NetConnection -ComputerName -Port 445 

Источник

Samba port no linux

Разрешение доступа клиентам

В этой статье объясняется, как настроить брандмауэр iptables, чтобы разрешить сетевым клиентам доступ к серверу Samba на узле Linux.
Я запускал серверы Samba уже несколько лет, всегда в частных сетях за брандмауэрами, и обычно отключал брандмауэр на внутреннем хосте, чтобы не усложнять настройку или избавиться от неожиданных багов. С годами я стал более сознательным в вопросах безопасности, и теперь я стараюсь всегда настраивать фаервол, чтобы впускать трафик только тот, что мне нужен. Эта краткая статья должна объяснить основы разрешения трафика Samba через iptables. А пока немного о самой Samba.

Порты, протоколы, и службы

В файле /etc/services несколько строк, связанных с Samba:

netbios-ns 137/tcp # NetBIOS Name Service
netbios-ns 137/udp
netbios-dgm 138/tcp # NetBIOS Datagram Service
netbios-dgm 138/udp
netbios-ssn 139/tcp # NetBIOS Session Service
netbios-ssn 139/udp
microsoft-ds 445/tcp # Microsoft Directory Service
microsoft-ds 445/udp

На самом деле количество портов можно сократить к следующему виду:

netbios-ns 137/udp # NetBIOS Name Service
netbios-dgm 138/udp # NetBIOS Datagram Service
netbios-ssn 139/tcp # NetBIOS Session Service
microsoft-ds 445/tcp # Microsoft Directory Service

…потому что это порты, которые слушают службы сервера Samba. Первые три строки представляют порты, используемые сетью windows, так как сеть TCP/IP стала стандартной в операционной системе Windows 95. Оставшийся порт стал использоваться, когда Microsoft представила свою службу каталогов с Windows 2000. Для устранения неполадок или настройки полезно отметить, что протоколы UDP (порты 137 и 138) обслуживаются демоном nmbd, а протоколы TCP (порты 139 и 445) обслуживаются smbd.

Читайте также:  Обмен файлами между windows linux

Вы можете сами проверить, какие порты используются Samba, с помощью этих команд (от root):

# service smb stop
# netstat -ln > netstat-ln-smb.before
# service smb start
# netstat -ln > netstat-ln-smb.after
# diff netstat-ln-smb.*

И Вы увидите, что порты, перечисленные выше, появляются в выходных данных вместе с протоколом (TCP или UDP), которые используются для связи.

Настройка iptables

Разрешим же необходимые порты:

# iptables -A INPUT -p udp -m udp —dport 137 -j ACCEPT
# iptables -A INPUT -p udp -m udp —dport 138 -j ACCEPT
# iptables -A INPUT -m state —state NEW -m tcp -p tcp —dport 139 -j ACCEPT
# iptables -A INPUT -m state —state NEW -m tcp -p tcp —dport 445 -j ACCEPT

Затем перезапустим службу Samba:

В некоторых случаях есть хосты, которые не должны иметь доступа к серверу Samba. Вы можете ограничить диапазон IP-адресов, которые могут успешно подключаться к серверу Samba. Вот пример команд, вместо приведенных выше:

# iptables -A INPUT -p udp -m udp -s 192.168.0.0/24 —dport 137 -j ACCEPT
# iptables -A INPUT -p udp -m udp -s 192.168.0.0/24 —dport 138 -j ACCEPT
# iptables -A INPUT -m state —state NEW -m tcp -p tcp -s 192.168.0.0/24 —dport 139 -j ACCEPT
# iptables -A INPUT -m state —state NEW -m tcp -p tcp -s 192.168.0.0/24 —dport 445 -j ACCEPT

Этот пример позволит только хостам с IP-адресами между 192.168.0.1 и 192.168.0.254 связаться с сервером Samba.

Если требуется ограничить доступ только с одного хоста, используйте эти команды:

# iptables -A INPUT -p udp -m udp -s 192.168.0.1/32 —dport 137 -j ACCEPT
# iptables -A INPUT -p udp -m udp -s 192.168.0.1/32 —dport 138 -j ACCEPT
# iptables -A INPUT -m state —state NEW -m tcp -p tcp -s 192.168.0.1/32 —dport 139 -j ACCEPT
# iptables -A INPUT -m state —state NEW -m tcp -p tcp -s 192.168.0.1/32 —dport 445 -j ACCEPT

Эта конфигурация позволит только хосту с IP-адресом 192.168.0.1 связаться с сервером Samba.

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

Настройка доступа в Samba

С помощью самой же Samba так же можно ограничить доступ. Но это скорее как вспомогательная опция к брэндмауэру.

interfaces -это глобальная опция в файле конфигурации smb.conf, которая может ограничить возможность установления соединений с Samba на одном или нескольких сетевых интерфейсах. В системах с одним сетевым интерфейсом эта опция может быть полезна только для того, чтобы Samba могла работать с интерфейсом loopback или создаваться программным обеспечением вроде VMware. Вот типичный пример использования этой опции:

Читайте также:  How to install pip on linux

interfaces = 192.168.100.1 127.0.0.1

Теперь порты слушаются только на loopback интерфейсе и интерфейсе с адресом 192.168.100.1

И еще два параметра hosts deny и hosts allow. С их помощью запрещаем или разрешаем доступ от источника:

hosts deny = 192.168.0.0/255.255.255.0
hosts allow = 192.168.1.0/255.255.255.0 192.168.3.10 192.168.3.12

Источник

What ports does the Samba client require?

Since an Ubuntu machine needs an smb client to access a smb server, it would have to establish a connection to the server. What ports does the client open to establish the connection? Do those ports continue to listen for incoming connections once the connection to the smb server ends? Note: I am asking about the ports used by a smb client, not a smb server.

To discover what ports a given service uses, you can use firewall-config to get a pretty big list of default configurations.

1 Answer 1

Identify on which ports and interfaces Samba is listening

You can use netstat to identify which ports Samba and related daemons are listening on and on which IPs:

# netstat -tulpn | egrep "samba|smbd|nmbd|winbind" The following is a snippet of an example output: tcp 0 0 127.0.0.1:139 0.0.0.0:* LISTEN 43270/smbd tcp 0 0 10.0.0.1:139 0.0.0.0:* LISTEN 43270/smbd tcp 0 0 10.0.0.1:88 0.0.0.0:* 

LISTEN 43273/samba tcp 0 0 127.0.0.1:88
0.0.0.0:* LISTEN 43273/samba tcp 0 0 127.0.0.1:445 0.0.0.0:*
LISTEN 43270/smbd tcp 0 0 10.0.0.1:445
0.0.0.0:* LISTEN 43270/smbd

The above example shows, that the services are listening on localhost (127.0.0.1) and the interface with IP 10.0.0.1 — each on the listed ports (139, 88, 445. ).

Port usage when Samba runs as an Active Directory Domain Controller

Service Port protocol DNS 53 tcp/udp Kerberos 88 tcp/udp End Point Mapper (DCE/RPC Locator Service) 135 tcp NetBIOS Name Service 137 udp NetBIOS Datagram 138 udp NetBIOS Session 139 tcp LDAP 389 tcp/udp SMB over TCP 445 tcp Kerberos kpasswd 464 tcp/udp LDAPS (only if "tls enabled = yes") 636 tcp Dynamic RPC Ports* 1024-5000 tcp Global Cataloge 3268 tcp Global Cataloge SSL (only if "tls enabled = yes") 3269 tcp Multicast DNS 5353 tcp/udp 
  • Samba, like Windows, supports dynamic RPC services. The range starts at 1024. If something occupies this port for some reason, it will be a different port (literally walked up from 1024). Remember, that there can be other ports too, which are related to your Samba installation but not provided from Samba itself, like if you run a NTP server for time synchronisation as well.
Service Port protocol End Point Mapper (DCE/RPC Locator Service) 135 tcp NetBIOS Name Service 137 udp NetBIOS Datagram 138 udp NetBIOS Session 139 tcp SMB over TCP 445 tcp 

Port usage when Samba runs as a Member Server

Service Port protocol End Point Mapper (DCE/RPC Locator Service) 135 tcp NetBIOS Name Service 137 udp NetBIOS Datagram 138 udp NetBIOS Session 139 tcp SMB over TCP 445 tcp 

Источник

Оцените статью
Adblock
detector