Organizations are increasing their use of various solutions to address communication needs across their infrastructure. As file systems are an integral part of collaboration, this article will dive into one of the most widely used protocols necessary for many systems. We will learn more about the SMB protocol, Port 139, Port 445, how it works, the risks associated with it, and remediation steps to provide a more secure communication channel.
What is SMB Port?
The SMB (Server Message Block) port is a network port primarily utilized for file and resource sharing across a computer network. SMB operates over TCP port 445 and enables shared access to files, printers, and serial ports among devices on a network.
Moreover, its core function of resource sharing, enables SMB to be utilized for following use cases:
- Involving mail slots (inter-process communication mechanisms)
- Named pipes (a method for processes to communicate either on the same machine or over a network).
What are Port 139 and Port 445?
For the SMB protocol to function correctly, network ports are required to communicate with other systems. SMB requires either port 139 or port 445 to be an open port.
Port 139
Originally, SMB ran on port 139 as an application layer protocol for Windows computers to communicate with each other on the same network. It was run on NetBIOS over TCP/IP and is being passed over by port 445 in modern environments.
Port 445
Port 445 port is used by newer versions of SMB as Windows 2000 adopted it for use for direct TCP/IP communication. Generally favored over port 139, it also allows for communication across different networks for things like internet-based file sharing.
How does SMB Protocol work?
Client-Server Communication
SMB is known as a response-request protocol. It uses the approach of a client-server relationship, where the client makes any specific request, and the server responds as requested. Some examples of practical use today are situations where file resources are requested or printers need to be shared. SMB is also used for other uses, such as mail slots and named pipe situations.
Historical Development
Historically, SMB originated with IBM and was designed in 1983 for DOS file access over networks. It wasn’t until 1990 that Microsoft merged the SMB protocol with its LAN Manager product. From there, continual maturation of the SMB protocol appeared in instances such as the introduction of CIFS, as well as milestone improvements in efficiency, performance, and security, as described through the aforementioned upgrades of SMB 2 and SMB 3.
SMB Protocol Dialects
With an increasing presence of SMB implementations across the industry, network requirements evolved to have different demands of SMB. This led to the emergence of different SMB protocol dialects to cater to different environments. Depending on the need and use, different dialects could be implemented for a variety of purposes.
SMB Dialect Variations
Here’s a list of popular SMB dialects along with their uses:
- CIFS (Common Internet File System): was a Microsoft developed dialect debuting in Windows 95 that was designed for network connections over remote servers. This dialect (CIFS Port) enabled clients to connect to remote file and printer shares as if they were accessed locally.
- Samba: Samba is an open source dialect (Samba port) that enables Linux/Unix machines to communicate with Windows devices.
- NQ: was developed by Visuality Systems that brings the SMB protocol to non-Windows platforms. Especially prevalent in devices such as printers and home network devices.
- Tuxera SMB and MoSMB: Dialects were also created as proprietary methods using the SMB protocol for specific features, such as enterprise file sharing and advanced authentication.
Security Risks Associated with Open SMB Ports
Ports like the ones used with the SMB protocol are necessary to communicate from within and across different networks. While their use isn’t itself dangerous, open ports can be used and exploited for malicious purposes.
Having over exposed ports can lead to the following vulnerabilities, such as:
- A Wormable port
- Man-In-The-Middle attacks,
- NetBIOS spoofing,
Case Study: WannaCry Ransomware:
Once recent occurrence was the WannaCry ransomware attack that targeted Windows clients running an outdated version of SMB. A worm infection was installed on a target machine, encrypting the user’s files in exchange for ransom. In addition to that, the infected system would also start searching for other machines via the SMB v1 protocol, and if other systems were using those open ports, they would be susceptible to the ransomware self-install on that machine and continue its spread.
While WannaCry created havoc and pain for many companies and networks, its disastrous results could have been much less impactful had systems been patched with up-to-date security measures.
Best Practices to Secure SMB Ports 139 and 445
Since SMB ports can be targeted, here are some best practices to implement to protect against various attacks:
Enable Firewall and Endpoint Protection
Enabling these network security devices can protect these ports from threats as well provide blacklisting services against known malicious IP addresses.
Utilize VPNs
By utilizing VPNs, network traffic can be encrypted and protected against malicious actors.
Create VLANs
Creating Virtual LANs can be utilized to isolate internal traffic to limit attack surface.
Implement MAC Address Filtering:
These filters can keep unknown systems from accessing and infiltrating your internal network.
Implement System Configuration Changes
Following changes can be made to harden your security against SMB attacks:
Disable NetBIOS over TCP/IP
- Select Start, point to Settings, and then select Network and Dial-up Connection.
- Right-click Local Area Connection, and then select Properties.
- Select Internet Protocol (TCP/IP), and then select Properties.
- Select Advanced.
- Select the WINS tab, and then select Disable NetBIOS over TCP/IP.
Commands to monitor port status
To determine if NetBIOS is enabled on a Windows computer, run a net config redirector or net config server command to see if if any ‘NetBT_Tcpip’ device is bound to the network adapter.
Conclusion
The SMB protocol has proved to be a valuable and vital method of accessing different network resources. While it has enabled things like file sharing and connectivity, security measures should be taken to ensure authorized access within the network. Securing ports and keeping up to date with protocols are a couple of examples of how to heighten your security profile in modern-day networking.
In conjunction with network security, Netwrix can fulfill your security plan at the data layer. With Netwrix solutions, we can help your organization see who has access to your data and the activity that surrounds it. Monitoring is a critical part of detecting attacks and protecting against breaches.
Mark has over 20 years in the IT industry and has consulted in a wide array of industries including the automotive, insurance, medical, legal, and financial sectors. With his IT background, he joins Netwrix with his ability to empathize with the problems IT teams face today. In his role as Solutions Engineer, Mark will understand the needs your organization faces and provide solutions to help overcome those challenges.
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
SMB (сокр. от англ. Server Message Block) — сетевой протокол прикладного уровня для удалённого доступа к файлам, принтерам и другим сетевым ресурсам, а также для межпроцессного взаимодействия. Первая версия протокола, также известная как Common Internet File System (CIFS) (Единая файловая система Интернета), была разработана компаниями IBM, Microsoft, Intel и 3Com в 1980-х годах; вторая (SMB 2.0) была создана Microsoft и появилась в Windows Vista. В настоящее время SMB связан главным образом с операционными системами Microsoft Windows, где используется для реализации «Сети Microsoft Windows» (англ. Microsoft Windows Network) и «Совместного использования файлов и принтеров» (англ. File and Printer Sharing).
Первая версия протокола была разработана сотрудником IBM Бэрри Файгенбаумом (англ. Barry Feigenbaum) в 1983 году[1][2]. Изначально SMB был реализован через NetBIOS (поверх NBF, IPX/SPX или NetBIOS over TCP/IP) и использовался в сетях MS-NET и LAN Manager для DOS, а также в Windows for Workgroups. Microsoft регулярно дополняла протокол новыми возможностями; так, вторая версия Microsoft Networks SMB File Sharing Protocol Extensions появилась в 1988 году, 3-я версия — в 1989 году, версия 3.4 — в 1992[3].
В 1992 году появилась Samba — свободная реализация протокола SMB для UNIX-подобных операционных систем (изначально для SunOS). Поскольку Microsoft не опубликовала документацию значительной части своих дополнений к SMB, разработчикам Samba пришлось провести обратную разработку протокола.
В 1996 году Microsoft стала использовать новое название для дополненной версии протокола, которая использовалась в Windows NT 4.0 — CIFS (англ. Common Internet File System); новое имя прижилось, SMB и CIFS фактически стали синонимами[2]. Microsoft некоторое время пыталась превратить CIFS в международный стандарт через IETF, но после 2000 года прекратила работу по стандартизации.
В Windows 2000 впервые появился SMB непосредственно поверх TCP (без NetBIOS); для этого используется порт 445 (SMB через NBT использовал порт 139).
В Windows Vista появилась новая версия протокола — SMB 2.0. Протокол был значительно упрощён (в SMB было более 100 команд, а в SMB 2 — всего 19); при этом была повышена производительность (благодаря механизму кэширования возможно совмещать несколько команд SMB 2 в одном сетевом запросе и увеличенным буферам чтения и записи), особенно в сетях с высокой латентностью, улучшена масштабируемость и добавлена возможность автоматического продолжения сеанса в случае временного отсоединения от сервера[4]. SMB 2 использует тот же порт (445) как и SMB, но другой заголовок пакетов (0xFF 'S' 'M' 'B'
в SMB, 0xFE 'S' 'M' 'B'
в SMB 2)[5].
В Windows 8 появилась новая версия протокола — SMB 3.0. Новые возможности изложены на сайте разработчиков.
В 2008 году под давлением Еврокомиссии Microsoft опубликовала описание своих частных протоколов, в том числе и SMB, на сайте MSDN[6].
SMB — это протокол, основанный на технологии клиент-сервер, который предоставляет клиентским приложениям простой способ для чтения и записи файлов, а также запроса служб у серверных программ в различных типах сетевого окружения. Серверы предоставляют файловые системы и другие ресурсы (принтеры, почтовые сегменты, именованные каналы и т. д.) для общего доступа в сети. Клиентские компьютеры могут иметь у себя свои носители информации, но также имеют доступ к ресурсам, предоставленным сервером для общего пользования.
Клиенты соединяются с сервером, используя протоколы TCP/IP (а, точнее, NetBIOS через TCP/IP), NetBEUI или IPX/SPX. После того, как соединение установлено, клиенты могут посылать команды серверу (эти команды называются SMB-команды или SMBs), который даёт им доступ к ресурсам, позволяет открывать, читать файлы, писать в файлы и вообще выполнять весь перечень действий, которые можно выполнять с файловой системой. Однако в случае использования SMB эти действия совершаются через сеть.
Как было сказано выше, SMB работает, используя различные протоколы. В сетевой модели OSI протокол SMB используется как протокол Application/Presentation уровня и зависит от низкоуровневых транспортных протоколов. SMB может использоваться через TCP/IP, NetBEUI и IPX/SPX. Если TCP/IP или NetBEUI будут заняты, то будет использоваться NetBIOS API. SMB также может посылаться через протокол DECnet. Digital (ныне Compaq) сделала это специально для своего продукта PATHWORKS. NetBIOS в случае использования через TCP/IP имеет различные названия. Microsoft называет его в некоторых случаях NBT, а в некоторых NetBT. Также встречается название RFCNB.
С начала существования SMB было разработано множество различных вариантов протокола для обработки всё возрастающей сложности компьютерной среды, в которой он использовался. Договорились, что реальный вариант протокола, который будет использоваться клиентом и сервером, будет определяться командой negprot (negotiate protocol). Этот SMB обязан посылаться первым до установления соединения. Первым вариантом протокола был Core Protocol, известный как SMB-реализация PC NETWORK PROGRAM 1.0. Он должным образом поддерживает весь набор основных операций, который включает в себя:
- присоединение к файловым и принтерным ресурсам и отсоединение от них;
- открытие и закрытие файлов;
- открытие и закрытие принтерных файлов;
- чтение и запись файлов;
- создание и удаление файлов и каталогов;
- поиск каталогов;
- получение и установление атрибутов файла;
- блокировка и разблокировка файлов.
8 | 16 | 24 | 32 bits |
IDF | |||
---|---|---|---|
Command | RCLS | Reserved | ERR |
ERR (cont) | REB/FLG | Reserved | |
Reserved | |||
Reserved | |||
Reserved | |||
Tree ID | Process ID | ||
User ID | Multiplex ID | ||
WCT | VWV | ||
BCC | BUF | ||
SMB header structure |
Основные элементы структуры заголовка SMB:
• IDF (Identifier) — Идентификатор протокола: 0xff, 0x53(‘S’), 0x4d(‘M’), 0x42(‘B’).
• Command — команда протокола.
• RCLS — код класса ошибки.
• ERR — код ошибки.
• Tree ID (TID) — идентификатор соединения с сетевым ресурсом.
• Process ID (PID) — идентификатор клиентского процесса фактического соединения.
• User ID (UID) — идентификатор пользователя; используется сервером для проверки прав доступа пользователя.
• Multiplex ID (MID) — идентификатор группы пользователя; используется сервером для проверки прав доступа группы пользователя.
• WCT — количество параметров, следующих за заголовком.
• BCC — количество байт данных, следующих за параметрами.
Аутентификация Microsoft SMB Protocol
править
Модель механизма защиты, которая используется в Microsoft SMB Protocol, в основном идентична модели любого другого варианта SMB-протокола. Она состоит из двух уровней защиты: user-level (пользовательский уровень) и share-level (уровень совместно используемого ресурса). Под share (опубликованный ресурс) понимается файл, каталог, принтер, любая услуга, которая может быть доступна клиентам по сети.
Аутентификация на уровне user-level означает, что клиент, который пытается получить доступ к ресурсу на сервере, должен иметь username (имя пользователя) и password (пароль). Если данная аутентификация прошла успешно, клиент имеет доступ ко всем доступным ресурсам сервера, кроме тех, что с share-level-защитой. Этот уровень защиты даёт возможность системным администраторам конкретно указывать, какие пользователи и группы пользователей имеют доступ к определённым данным. Он используется в Windows NT, Windows 2000, Windows XP.
Аутентификация на уровне share-level означает, что доступ к ресурсу контролируется паролем, установленным конкретно на этот ресурс. В отличие от user-level, этот уровень защиты не требует имя пользователя для аутентификации и не устанавливается никакая уникальность текущего пользователя. Этот уровень используется в Windows NT, Windows 2000 и Windows XP для обеспечения дополнительного уровня контроля защиты сверх user-level. Операционные системы Windows 95, Windows 98 и Windows ME реализуют защиту только этого уровня.
В обоих этих уровнях защиты используется шифрование. Пароль зашифровывается, прежде чем отправляется на сервер. Типы шифрования NTLM, NTLMv2 и старые версии LAN Manager (LM) поддерживаются протоколом. Оба метода шифрования используют аутентификацию типа отклик-отзыв, в которой сервер посылает клиенту случайную сгенерированную строку, а клиент возвращает в качестве отзыва обработанную строку, которая доказывает, что клиент имеет достаточный мандат для доступа к данным.
На протяжении всего срока эксплуатации эталонной реализации протокола от Microsoft специалистами по информационной безопасности выявлялись уязвимости, позволяющие успешно провести сетевую атаку на удалённый узел.[7][8][9] Организация атаки на незащищённые серверы SMB является одной из наиболее привлекательных среди злоумышленников[10]. Так, например, с помощью использования уязвимостей протокола SMB были осуществлены взлом серверов Sony Pictures Entertainment[11] и распространение вредоносного ПО DoublePulsar, WannaCry[12] (уязвимость EternalBlue) и Petya[13].
- Samba
- NetBIOS
- Network File System
- Badlock
- EternalBlue
- ↑ Christopher R. Hertel. SMB Filesharing URL Scheme (англ.) (8 января 2003). Дата обращения: 21 октября 2009. Архивировано из оригинала 3 июня 2012 года.
- ↑ 1 2 Andrew Tridgell. Myths About Samba (англ.). Дата обращения: 2 июня 2011. Архивировано из оригинала 3 июня 2012 года.
- ↑ Dan Shearer. History of SMB (англ.) (16 ноября 1996). Дата обращения: 21 октября 2009. Архивировано из оригинала 3 июня 2012 года.
- ↑ Joseph Barreto. SMB2, a complete redesign of the main remote file protocol for Windows (англ.) (9 декабря 2008). Дата обращения: 22 октября 2009. Архивировано из оригинала 3 июня 2012 года.
- ↑ SMB2. Wireshark. Дата обращения: 22 октября 2009. Архивировано из оригинала 3 июня 2012 года.
- ↑ [MS-CIFS]: Common Internet File System (CIFS) Protocol (англ.). Дата обращения: 11 августа 2015. Архивировано 5 ноября 2015 года.
- ↑ MS02-070: Flaw in SMB Signing May Permit Group Policy to Be Modified. Microsoft (1 декабря 2007). Дата обращения: 1 ноября 2009. Архивировано 25 июля 2017 года.
- ↑ MS09-001: Vulnerabilities in SMB could allow remote code execution. Microsoft (13 января 2009). Дата обращения: 1 ноября 2009. Архивировано 5 октября 2009 года.
- ↑ Microsoft Security Bulletin MS17-010 – Critical. technet.microsoft.com. Дата обращения: 13 мая 2017. Архивировано 21 мая 2017 года.
- ↑ Alert (TA14-353A) Targeted Destructive Malware. US-CERT. Дата обращения: 16 мая 2017. Архивировано 20 декабря 2014 года.
- ↑ Sony Hackers Used Server Message Block (SMB) Worm Tool. Дата обращения: 16 мая 2017. Архивировано 20 декабря 2014 года.
- ↑ WannaCry Ransomware Attack Hits Victims With Microsoft SMB Exploit. eWeek. Дата обращения: 13 мая 2017.
- ↑ Petya ransomware virus is back amid cyber attack: Swiss agency. Reuters. Tue Jun 27 14:50:10 UTC 2017. Архивировано 2017-06-27. Дата обращения: 2017-06-27.
- A Common Internet File System (CIFS/1.0) Protocol — Preliminary Draft (англ.)
- [MS-SMB]: Server Message Block (SMB) Protocol (англ.)
- [MS-SMB2]: Server Message Block (SMB) Protocol Versions 2 and 3 (англ.)
- Just what is SMB? (англ.)
- IBM Protocols: SMB (англ.)
- IBM SMB: Server Message Block protocol (англ.)
The server message block (SMB) protocol provides “client-server communication,” which allows programs and services on networked computers to communicate with one another. SMB enables network functions like file, print and device sharing, among others.
SMB Ports Explained
SMB ports are used for file sharing, enabling programs and services on networked computers to communicate with each other. The SMB protocol sends and receives request-response communication between clients and servers to make dealing with networked computers easier.
What Is an SMB Port?
A server message block (SMB) port is a network port that allows devices within the same network to communicate with each other, so they can exchange files and share data, printers and other resources. In the case of files, users on different devices can perform various actions like opening, editing and moving files. While SMB ports have relied on different protocols through the years, they currently use port 445 (more on this to come).
How Does SMB Work?
The SMB protocol sends and receives request-response messages to establish communication between clients and servers. This arrangement sets up a file-sharing system as if a user were accessing data on their hard drive. It makes dealing with networked systems all over the world a lot easier.
Other operating systems, such as Unix, Linux and OS/2, use Samba to connect and provide file-sharing services within a network by speaking the same language as SMB.
SMB History and Evolution
During the mid-1990s, Microsoft incorporated SMB in their LAN Manager product, which IBM initially built. SMB 1.0 was renamed common internet file system (CIFS) , and Microsoft published draft standards to the Internet Engineering Task Force (IETF), though these have now expired.
SMB and early CIFS implementation had a number of flaws that limited its applicability to managing small files for end-users. The protocol was “chatty,” which resulted in poor performance over long distances or when there was a lag between client and server. Around this time, the Samba project was born, with the goal of reverse-engineering the SMB/CIFS protocol and developing an SMB server that would allow MS-DOS clients to access files on Unix machines.
SMB has gone through a few evolutions since then.
SMB 2.0
Microsoft released SMB2 with Windows Vista in 2006. SMB2.0 had a significant number of improvements over SMB 1.0, particularly reducing the “chattiness” of the protocol by reducing the number of commands and subcommands from hundreds to 19.
The term CIFS becomes redundant, as it only applied to SMB version 1.0.
SMB2 supported many other improvements like TCP window scaling and WAN acceleration, opportunistic locking and a feature known as “pipelining” to enable multiple requests to be queued at the same time.
Performance improvements included allowing larger block sizes, which improved large file transfers. Microsoft introduced “durable file handles” that allowed the connection to an SMB server to survive brief network failures frequently seen in wireless networks. They did this by allowing clients to transparently reconnect to servers.
SMB 2.1
SMB 2.1 was released alongside Windows 7 and Windows Server 2008, and included minor upgrades.
SMB 3.0
With Windows 8 and Windows Server 2012, SMB 3.0 (also known as SMB 2.2) was released. SMB3 included significant protocol modifications such as the SMB Direct Protocol (SMB over remote direct memory access (RDMA) and SMB Multichannel (many connections per SMB session), which are meant to improve SMB2 performance, particularly in virtualized data centers.
SMB 3.1.1
SMB 3.1.1 was introduced alongside Windows Server 2016 and Windows 10. The protocol comes with additional security measures, including advanced encryption, expanded caching options and pre-authentication features to address man-in-the-middle attacks.
SMB Protocol Ports
To provide file and print-sharing services within a network, SMB uses a number of ports. The following are all known SMB v2/v3 ports:
- TCP 445 — SMB over transmission control protocol (TCP) without the need for a network basic input/output system (NetBIOS).
- UDP 137 — SMB over user datagram protocol (UDP or Name Services).
- UDP 138 — SMB over UDP (datagram).
- TCP 139 — SMB over TCP (session service).
More on CybersecurityWhat Is Smishing
SMB Ports 139 and 445 Explained
There are two common ports you will see in SMBs — Port 139 and Port 445. Here’s what they do.
Port 139
Port 139 is used by the NetBIOS session service. Prior to Windows 2000, most operating systems used TCP 139, with SMB running on top of NetBIOS. NetBIOS is a service on the Open Systems Interconnection (OSI) model’s session layer that allows applications to communicate with one another within a local area network (LAN). This might be anyone on the internet, but because of security concerns, it’s not a recommended alternative.
Port 445
Windows uses port 445 for file sharing across the network. From Windows 2000 onward, Microsoft changed SMB to use port 445. Microsoft directory services, often known as Microsoft-DS, use port 445.
TCP and UDP protocols both use port 445 for numerous Microsoft services. For file replication, user and computer authentication, group policy and trusts, Microsoft Active Directory and Domain Services use this port. SMB, CIFS, SMB2, DFSN, LSARPC, NbtSS, NetLogonR, SamR and SrvSvc protocols and services are most likely to be found on these ports.
Is SMB Secure?
While different versions of SMB provide varying levels of security and protection, SMBv1 was discovered to have a vulnerability that hackers may exploit to execute their code without the user’s knowledge. When a device becomes infected, it attacks other devices that are linked to it. The National Security Agency (NSA) uncovered the flaw in 2017.
The exploit was called EternalBlue, and it was taken from the NSA and posted online by the Shadow Brokers hacker group. Microsoft did issue a patch to address the vulnerability, but the WannaCry ransomware attack hit the world just a month later.
More recently, LemonDuck malware has taken advantage of EternalBlue and launched brute-force attacks on SMB services to gain network access. Meanwhile, hackers used DarkGate malware to spread their malware via Samba file shares in a brief campaign. SMB security has improved over the years, but the protocol isn’t immune to attacks — especially as malicious players invent new methods for infiltrating SMB services.
More on Cybersecurity: What Is a Phishing Attack? (With 18 Examples)
How to Prevent SMB Vulnerabilities
To keep your SMB services secure, combine the following tools and best practices for shoring up your defenses against SMB attacks.
Patch All Devices
Attackers will be unable to access a patched machine, but a huge number of Windows computers have yet to be patched. The March 2017 update from Microsoft can assist in patching the server message block vulnerabilities. If you use a Windows 10 or later system, the fixes are already built in. This is why most SMB assaults target Windows 7 and earlier. Furthermore, the WannaCry patch can prevent EternalBlue exploits and similar flaws.
Practice Healthy SMB Habits
It’s better to have layers of security when it comes to protecting yourself from cyberattacks, as it is with other things. Apart from the WannaCry and ransomware patches, you can further safeguard your systems by restricting SMB access from the internet, blocking SMB in offsite computers when in public areas and removing SMB if it’s not needed.
Establish Firewall and Endpoint Protection Measures
Firewalls are excellent tools for regulating network traffic, ensuring only authorized users can access network information. For any devices that fall outside firewalls, endpoint protection methods like antivirus software can shield laptops, phones and other devices from the initial attempts of cyber attackers.
Invest in Detection Tools and Services
Finally, vulnerability scanning and managed detection and response services can help your system avoid and identify SMB attacks and other cyberattacks.
Introduction to SMB (Server Message Block)
Server Message Block (SMB) is a widely used network protocol that allows shared access to files, printers, and serial ports between nodes on a network. It’s heavily used in Windows environments but also supported on Linux and macOS.Understanding which port SMB uses is crucial for configuring firewalls, enhancing security, and enabling successful network file sharing.
What is the Default Port for SMB?
The default port used by SMB is TCP 445. This enables direct communication without relying on older NetBIOS services. Previously, SMB also ran over TCP 139 through NetBIOS, but this method is now mostly deprecated.
Port 445: SMB over TCP
Port 445 supports SMB directly over TCP/IP and is used by modern operating systems. It eliminates the dependency on NetBIOS, simplifying configuration and increasing security.
Port 139: NetBIOS Session Service
Port 139 is associated with older SMB implementations using NetBIOS over TCP/IP. Although some legacy systems may still use it, it’s considered less secure and should be disabled if possible.
Why Does SMB Use Port 445?
Modern SMB versions (SMBv2 and SMBv3) require port 445 to establish secure and efficient communication. Port 445 supports authentication, encryption, and direct connection between devices without relying on name resolution services.
TCP vs UDP for SMB Communication
SMB primarily uses TCP for data transfer. However, NetBIOS services historically required UDP for name resolution and datagram services.
Does SMB Use Both Ports 445 and 139?
Most modern environments use only port 445, but older systems may still use both ports 445 and 139. Ensuring your infrastructure is up-to-date helps simplify this and boosts security.
Disable SMBv1 using PowerShell:
Set-SmbServerConfiguration -EnableSMB1Protocol $false
SMB Ports and Security: Why Blocking Port 445 Matters
The WannaCry and NotPetya ransomware attacks exploited vulnerabilities in SMBv1 over port 445. Blocking or monitoring this port can protect your infrastructure from similar attacks.
Key Tips:
Block port 445 at the perimeter firewall
Disable SMBv1 on all devices
Use Endpoint Detection & Response (EDR) for monitoring SMB usage.
Best Practices: Firewall Rules for SMB
Windows
New-NetFirewallRule -DisplayName "Block SMB 445" -Direction Inbound -LocalPort 445 -Protocol TCP -Action Block
Linux (UFW)
sudo ufw deny 445/tcpsudo ufw deny 139/tcp
How to Open SMB Ports on Windows and Linux
To enable SMB for internal file sharing:On Windows:
Go to Windows Firewall > Advanced Settings. Create a new inbound rule for TCP 445.
Allow access from trusted IP ranges only.
On Linux:
sudo ufw allow from 192.168.0.0/16 to any port 445 proto tcp
Alternatives to SMB fo
SFTP (SSH File Transfer Protocol)
NFS (Network File System)
WebDAVCloud-based sharing (e.g., OneDrive, Google Drive)
These options offer encryption, centralized access control, and better protection for remote sharing.
Conclusion: Proactive SMB Port Security
Understanding the role of ports 445 and 139 is essential for secure SMB implementation. Modern networks should rely exclusively on TCP port 445, with legacy ports disabled. Firewalls must be configured to restrict external access and reduce risk from exploits.