- Как закрыть порты в Linux?
- How to Open and Close Ports using IPTables?
- Open a port in IPtables – CentOS 6
- Open a port in IPtables – CentOS 7
- Close a port in IPtables – CentOS 6
- Close a port in IPtables – CentOS 7
- Рабочий метод разрыва конкретного активного соединения из командной строки linux (drop/kill/cut/close ESTABLISHED connection)
- How to Close Unused Open Ports: TCP and UDP Port Scan
- How to identify the processes that are keeping ports open
Как закрыть порты в Linux?
У меня есть какой-то вопрос в закрытии порта, я думаю, что у меня есть некоторые странные вещи.
Когда я использую выполнить
это показывает, что порт 23 / TCP открыт.
Но когда я выполню
это показывает, что порт 23 / tcp закрыт.
Какой из них является правдой? Я хочу закрыть этот порт на всей моей системе, как я могу это сделать?
Nmap — отличный сканер портов, но иногда вам хочется чего-то более авторитетного. Вы можете спросить ядро, какие процессы имеют какие порты открывать, используя netstat утилиту:
Варианты, которые я дал:
- -t Только TCP
- -l Только прослушивающие порты
- -n Не ищите имена сервисов и хостов, просто отображайте номера
- -p Показать информацию о процессе (требуется привилегия root)
В этом случае мы можем видеть, что sshd прослушивает любой 0.0.0.0 порт интерфейса ( ) 22 и cupsd прослушивает 127.0.0.1 порт 631 loopback ( ). Ваш вывод может показать, что telnetd имеет локальный адрес 192.168.1.1:23 , то есть он не будет отвечать на соединения на адаптере обратной связи (например, вы не можете telnet 127.0.0.1 ).
Существуют и другие инструменты, которые отображают аналогичную информацию (например, lsof или /proc ), но netstat является наиболее широко доступным. Это даже работает на Windows ( netstat -anb ). Netstat в BSD немного отличается: вам придется использовать sockstat (1) для получения информации о процессе.
Если у вас есть идентификатор процесса и имя программы, вы можете найти процесс и убить его, если хотите закрыть порт. Для более детального управления вы можете использовать брандмауэр (iptables в Linux), чтобы ограничить доступ только определенными адресами. Возможно, вам придется отключить запуск службы. Если PID в Linux означает «-», это, вероятно, процесс ядра (например, это характерно для NFS), так что удачи в выяснении, что это такое.
Примечание: я сказал «авторитетный», потому что вам не мешают условия сети и брандмауэры. Если вы доверяете своему компьютеру, это здорово. Однако, если вы подозреваете, что вас взломали, вы не сможете доверять инструментам на своем компьютере. Замена стандартных утилит (а иногда даже системных вызовов) на те, которые скрывают определенные процессы или порты (или руткиты), является стандартной практикой для злоумышленников. Лучше всего на этом этапе сделать криминалистическую копию вашего диска и восстановить ее из резервной копии; затем используйте копию, чтобы определить, как они вошли, и закройте ее.
Источник
How to Open and Close Ports using IPTables?
IPtables is the default firewall used on CentOS and RHEL systems. On most of our services like VPS Servers or Dedicated Servers, you will find the firewall is active but all ports are open. We do this to ensure all users can connect to services they may install like cPanel or Plesk. If you want to close some ports on your server or even open some if you have a pre-configured firewall you can use the rules below to open and close ports on your firewall.
List Current Firewall Rules
iptables—L
This command lists all the current firewall rules loaded into IPtables.
Open a port in IPtables – CentOS 6
Open a port in IPtables – CentOS 7
In CentOS 7 you use the –permanent flag to open the port. Like in CentOS 6 just swap the number 80 for your required port and run the –reload command
This command opens the requested port. In our example, it’s port 80. Just swap the 80 for the port number you wish to open. Run the service iptables save command to save the rules to your firewall configuration.
Close a port in IPtables – CentOS 6
This command would close the port 80 on your server and no one would be able to connect via that port. Just swap the 80 for your required port number then run the service iptables save command to save this to your IPtables configuration. You can also use the DROP command instead of REJECT.
Close a port in IPtables – CentOS 7
Just switch the 80 for the port number you wish to close then run the rest of the command to commit that to the firewall configuration.
Buy a domain
Buy a domain — There is no need to waste time looking for a reliable and profitable company to buy a domain. As the Hostimul.com team, we offer you hi..
Best Web Hosting for Small Business (2021)
Best Web Hosting For Small Business Guide — If you are running a business and don’t have a website yet, there is bad news for you. The online existenc..
Website Hosting Price
Website hosting price is a term referred to the overall costs of services offered by hosting providers. Although there are some free hosting practices..
Cheap dedicated Hosting
Cheap Dedicated Hosting — A business with a forward-looking perspective will sooner or later consider to opt for an alternative that provides more res..
Rent VPS Server for your professional web site.
Rent VPS Server for your professional web site. Rent VPS Server — Renting a VPS for running a website is becoming popular by each passing day. Most..
VPS Windows Server make a great effect on your site.
VPS Windows Server — Best Web Server Different business houses need dissimilar servers to conduct their respective business. It is just like a back..
Cheap VPS Europe server is the best for your web site.
Cheap VPS Europe — How Cheap VPS Servers Help Your Organization? Cheap VPS Europe — You can use VPS hosting services if you have a small or medium-..
Buy VPS for your professional web site from Hostimul.com
Buy VPS — Know the Details about VPS There are a number of VPS hosting providers are available in the market. They all have different types of crit..
VPS hosting Europe Makes Your Website Noticeable
VPS hosting Europe in Hostimul.com It is always a good idea for you to switch to a provider for getting VPS hosting services for your website. This..
VPS Server Windows with a high-security and cheaper options.
VPS Server Windows — Quality Servers for Your Web Operation There are different types of business are around the world. They need certain servers t..
Low Cost VPS with cheap prices at Hostimul.com
Low Cost VPS Hostimul.com! Business is dynamic. It needs real-time upgradation to stay ahead of others. If the competitors will knock you out from ..
Buy VPS Server for your professional web site from Hostimul.com
Buy VPS Server — Everything a Website Owner Needs to Know About A VPS hosting service has become the most popular one among all. Virtualization tec..
GMod Dedicated Server
GMod Dedicated Server — Game lovers always want a proper game server that will meet their own exceptions. They prefer to enjoy their without any flaws..
Virtual Dedicated Server Hosting
Virtual Dedicated Server Hosting — The virtual private server which is also known as a dedicated server paves the way to separate on the server with m..
Shared Hosting vs Dedicated Hosting
Shared Hosting vs Dedicated Hosting — People who are planning to own a website; they do search for web hosting companies. They sometimes stay undecide..
Install KVM Windows VPS for Faster Speed
KVM stands for Kernel-based virtual machine. It is one of the full virtualization technology that combines properly with Linux and virtualization tech..
Free Dedicated Server
Free dedicated server are properly leased by dedicated hosting service providers mainly to internet marketers. They also extend their service to such ..
Domain and Hosting
Domain and Hosting — Website owners have to pay for their domain name once a year and if they are paying hosting charges for each month, then, it woul..
Dedicated Server Price
Dedicated server price are known for their speed, reliability, and security. Therefore, almost all the website owners want to have these servers for t..
Dedicated Server Low Cost
Dedicated Server Low Cost — Gone those days when website administrators were experiencing slow and flaw websites. They were not able to handle huge tr..
Dedicated Cloud
Dedicated cloud server is known as the gateway to the internet for the website you want to host. It is true that there is one or a number of websites ..
cPanel Dedicated Server
cPanel Dedicated Server — Website administrators need to research well in order to know the right kinds of servers are available in the market. The ma..
Cheap Web Hosting
Cheap Web Hosting — There are a number of web hosts available in the market. They are different from each other in terms of price and popularity. Most..
Cheap Domain
Cheap Domain — Business websites are now becoming much more valuable compared to other aspects of the business. These are something that will not only..
Buy Website Domain
Buy Website Domain — If you want to own a website, purchasing a domain is the initial stage to go for. However, website domains can be purchased in a ..
ARK Dedicated Server
ARK Dedicated Server — Gamers always prefer to enjoy their game without any kind of flaws. There are a number of cans be listed that are reducing the ..
Affordable Dedicated Server
Affordable Dedicated Server — Website owners who are suffering from their poor speed of the website, they would feel relaxed by opting dedicated serve..
VPS or Cloud Hosting with cheapest prices
VPS or Cloud Hosting ⏪ Modern organizations think about which one can have a better effect on their business VPS or cloud hosting ⏩ VPS or Cloud Hosti..
VPS Cloud RAM according to your needs
VPS Cloud RAM ⏪ VPS cloud RAM according to your needs. We have the option to customize the server if you need a bigger RAM ⏩ VPS cloud RAM ✅ You can a..
SSD Cloud VPS with Best Options
SSD cloud VPS ⏪ By getting the SSD cloud VPS; you can reach out to the outer world through your website with the help of the internet ⏩ SSD cloud VPS ..
Baranova 2869/35, Žižkov,
130 00 Prague 3, Czechia
Источник
Рабочий метод разрыва конкретного активного соединения из командной строки linux (drop/kill/cut/close ESTABLISHED connection)
Иногда бывает необходимо принудительно разорвать активное соединение. Самый распространенный способ:
netstat -na
kill PID
Проблема в том, что один воркер может одновременно обслуживать несколько соединений, поэтому правильнее будет убить соединение а не воркер. Для этого на многих форумах рекомендуют использовать tcpkilll, cutter или awk+hping3. Однако, хоть эти утилиты и находятся в официальных репозиториях, мне не удалось заставить их разрывать соединения.
После продолжительных поисков был обнаружен perl скрипт killcx, разрывающий соединение по удаленному хосту и порту.
killcx 94.133.119.242:4403
[PARENT] checking connection with [94.133.119.242:4403]
[PARENT] found connection with [78.220.184.126:80] (ESTABLISHED)
[PARENT] forking child
[CHILD] interface not defined, will use [eth0]
[CHILD] setting up filter to sniff ACK on [eth0] for 5 seconds
[CHILD] hooked ACK from [77.220.184.126:80]
[CHILD] found AckNum [3091573605] and SeqNum [3105164779]
[CHILD] sending spoofed RST to [78.220.184.126:80] with SeqNum [3091573605]
[CHILD] sending RST to remote host as well with SeqNum [3105164779]
[CHILD] all done, sending USR1 signal to parent [13723] and exiting
[PARENT] received child signal, checking results.
=> success : connection has been closed !
Для его работы требуется целый набор библиотек.
apt-get install \
libpcap0.8 \
libpcap-dev \
libnet-pcap-perl \
libyaml-perl \
libyaml-dev \
libyaml-0-1 \
-y
cpan -i \
Net::RawIP \
NetPacket::Ethernet
Источник
How to Close Unused Open Ports: TCP and UDP Port Scan
One of the checks done in a network scan by
Acunetix Vulnerability Scanner is a TCP and UDP port scan. Any open ports detected during the scan will be reported as shown in the screenshot.
In this particular scan, these ports have been detected as being open on the server: 80, 1027, 135, 1457, 3389, 139, 8443. These are all TCP ports, and UDP ports identified by the
Acunetix network scanner are reported separately.
Although you do require ports to be open for users to connect to your services, you should restrict open ports, and ports exposed on the Internet to these services only.
Open ports allow hackers to:
- Configure the service to distribute content: Unused services tend to be left with default configurations, which are not always secure or may be using default passwords.
- Exploit old versions of unused software: Unused services tend to be forgotten, which means that they not get updated. Old versions of software tend to be full of known vulnerabilities.
- Gain better information on your network: Some services give an attacker easy access to certain information, at the very least, they can have a very good guess on the operating system that the server is running, which is already a good head start.
So now that you are armed with the same information that an attacker would have when probing your server, you should do the following:
- Identify the ports that you want to have running on the server. For example, if you are running a web and an FTP server, you will need ports 80 for web, 20 and 21 for FTP.
- If the host being scanned is a firewall, you will need to review any port address translation rules configured in the firewall/router and consult your firewall documentation.
- Identify the processes listening on the ports that the Acunetix network scan has identified. You will need to close these or block them from being exposed on the Internet.
How to identify the processes that are keeping ports open
Windows OS
For Windows operating systems, you can use netstat, which is included with the OS.
- On the scanned server, open command prompt.
- Run the command: netstat -ano. This will list all the network connections on the machine. The last column shows the process ID of the process for the specific network connection.
- You will probably want to filter this down using the ‘find’ command.
For example, if you only want to list the network connections on port 3306, use:
netstat -ano | find “:3306”
This will list a network connection in LISTENING mode and the id of the process that opened the connection. Use “tasklist /SVC /FI “PID eq xxx” to show the name of the process and service for process id xxx.
For example, if you want to list the information about processed id 7424, use:
tasklist /SVC /FI “PID eq 7424
The screenshot below shows the information for the examples used.
Now that you have identified the process and service that is responding to requests on the specific port, you would need to confirm that the service is not required. You can then proceed to either configuring the application to stop listening or stop the service from Windows Services and marking the service as disabled.
If you are not a command line fan, you can download TCPView from
Sysinternals, which gives pretty much the same information as netstat.
Linux OS
Most Linux distributions include the netstat command, however, the switches are different than the one included in Windows. Proceed as follows:
- On the scanned server, open a terminal session.
- Run the command: netstat -tulpn. This will list all daemons (services) listening for both TCP and UDP network traffic on the machine. The last column shows the process id of the process for the specific network connection. If this information is not being displayed, it is most likely because the user you are using does not have sufficient privileges. You may need to use sudo to get access to this information.
- You will probably want to filter this down using the grep command.
For example, if you only want to list the network connections on port 3306, use:
The screenshot below shows the information for the examples used.
Now that you have identified the process and daemon (service) that is responding to requests on the specific port, you would need to confirm that the service is not required. You can then proceed to either configuring the application to stop listening or stop the daemon.
In order to stop daemons in Debian-flavoured Linux distributions (this would also apply for Ubuntu Server distributions) you can run the command shown in the example below where we are going to be stopping the MySQL daemon. However, you would obviously need to replace the daemon name with the name of the daemon you’d like to stop.
In cases where programs you are trying to kill are not daemons, you may wish to stop them using pkill.
Naturally, similar syntaxes exist for other initscript standards used in distributions that are not based on Debian, therefore, it is advised that you consult your distribution’s documentation first.
Источник