All Products
Search
Document Center

How to prohibit IP addresses or network segments from accessing services in Linux

Last Updated: Apr 21, 2022

Disclaimer: This topic may contain information about third-party products. The information is for reference only. Alibaba Cloud does not make a guarantee in any form of the performance and reliability of the third-party products, and potential impacts of operations on these products.

Overview

This topic describes how to prohibit IP addresses or CIDR blocks from accessing services in Linux.

Description

Take note of the following items:

  • Before you perform high-risk operations such as modifying the specifications or data of an Alibaba Cloud instance, we recommend that you check the disaster recovery and fault tolerance capabilities of the instance to ensure data security.
  • Before you modify the specifications or data of an Alibaba Cloud instance, such as an Elastic Compute Service (ECS) instance or an ApsaraDB RDS instance, we recommend that you create snapshots or enable backups for the instance. For example, you can enable log backups for an ApsaraDB RDS instance.
  • If you have granted specific users the permissions on sensitive information, such as usernames and passwords, or submitted sensitive information in the Alibaba Cloud Management Console, we recommend that you modify the sensitive information at the earliest opportunity.

This topic describes the following methods to prevent IP addresses or CIDR blocks from accessing services. The relevant IP addresses or network segments in this article are purely fictitious, and users need to set them according to their own needs.

Method 1

  1. Log on to the instance, edit the /etc/hosts.deny file, add the following content, and then save and exit.
    sshd:203.XXX.XXX. 189
    # 203.XXX.XXX. 189 SSH access to
    the server sshd:203.XXX.XXX.0/255.XXX.XXX. 0
    # 203.XXX.XXX. 0~255.XXX.XXX. 0 Access to server SSH
  2. Run the following command to restart the service for the configuration to take effect:
    service xinetd restart

Method 2

  1. Log on to the instance, edit the /etc/rc.local file, add the following content, and then save and exit.
    iptables -I INPUT -s 61.XXX.XXX.1 -j DROP
    # 61.XXX.XXX. All packets of 1 are shielded
    iptables -I INPUT -s 61.XXX.XXX.0/24 -j DROP
    #61.XXX.XXX. 1 to 61.XXX.XXX. 255 access all blocked
    iptables -I INPUT -s 192.XXX.XXX.202 -p tcp --dport 80 -j DROP
    # 192.XXX.XXX. All access to port 80 of the 202 is blocked
    iptables -I INPUT -s 192.XXX.XXX.0/24 -p tcp --dport 80 -j DROP
    #192.XXX.XXX. 1~192.XXX.XXX. All access to port 80 of the 1255 is blocked
    Note: After the IP address is added, users may not be able to access the remote connection. Proceed with caution. If you make a mistake, see Connect to a Linux instance by using a management terminal.
  2. You can restart the server.

Applicable scope

  • Elastic Compute Service (ECS)