How to add a new static route on RHEL/CentOS 4.x/5.x/6.x/7.x Linux

by Vivek Gite

I have two network interfaces connected to two different routers as follows:

[a] eth0 LAN network 10.0.0.0/8 – gateway IP – 10.8.2.65

[b] eth1 ISP assigned network 202.54.22.128/28 – gateway IP – 202.54.22.129

I can only ping to public server but not to another servers inside my LAN? I am not able to route traffic via 10.8.2.65. How do I configure static routing under Red Hat Enterprise Linux 5.x/6.x/7.x or CentOS Linux 5.2/6.x/7.x?

How to add a new static route on a centos rhel linux
Under Red Hat Enterprise Linux or CentOS Linux you need to define static routing using the route command or ip command. The configuration is stored under /etc/sysconfig/network-scripts/route-eth0 for eth0 interface.

Update route using route command

Type the following command:
# route add -net 10.0.0.0 netmask 255.0.0.0 gw 10.8.2.65 eth0
# route -n

OR use the ip command to update/set new routing for you:
# ip route add 10.0.0.0/8 via 10.8.2.65
# ip r

OR
# ip route add 10.0.0.0/8 via 10.8.2.65 dev eth0
# ip r

RHEL 7/CentOS 7.x can use the following syntax to set static routing:
# nmcli connection modify eth0 +ipv4.routes "10.0.0.0/8 via 10.8.2.65"

Create static routing file for CentOS/RHEL version 4.x/5.x/6.x and older only

The drawback of above route command is that, when RHEL/CentOS server reboots it will forget static routes. So store them in a configuration file for eth0 interface:
# echo '10.0.0.0/8 via 10.8.2.65' >> /etc/sysconfig/network-scripts/route-eth0
Restart networking:
# service network restart
Verify new changes:
# route -n
# ip r
# ip a
# ping 10.8.2.65
# ping 10.8.2.10
# ping google.com
# traceroute google.com
# traceroute 10.8.2.10

How to add a new static route on CentOS/RHEL version 7.x and above

To see current ip settings run:
# ip a
# ip r

Create a file named /etc/sysconfig/network-scripts/route-enp6s0 to route traffic for sub/net 10.0.0.0/8 via 10.8.2.65 for enp6s0 interface:
# echo "10.0.0.0/8 via 10.8.2.65 dev enp6s0" >> /etc/sysconfig/network-scripts/route-enp6s0
Finally restart the networking:
# systemctl restart network
# ip r
# ping 10.8.2.65
# ping 10.8.2.10
# ping google.com

Further readings:
  • man pages ip, route command

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Shared via Inoreader

iPhoneから送信

How to add a new static route on RHEL/CentOS 4.x/5.x/6.x/7.x Linux

Iptables List and Show All NAT IPTables Rules Command

by Vivek Gite

I am using /sbin/iptables -L -v -n | more command. However, I am unable to list NAT rules. How do I use the iptables command to view or list NAT rules stored in NAT tables? How do I see all the rules in NAT tables under CentOS / RHEL / Debian / Ubuntu Linux based server?

/sbin/iptables command for IPv4 packet filtering and NAT. Network address translation (NAT) imodifyies IP address information in IP packet headers while in transit across a routing device. To see NAT rules type:
Show/Display Iptables NAT rules

Syntax

The syntax is as follows for iptables command:
iptables -t nat -L
iptables -t nat -L -n -v | grep 'something'
iptables -t nat -L -n -v

Sample outputs:

   Chain PREROUTING (policy ACCEPT 867 packets, 146K bytes)    pkts bytes target     prot opt in     out     source               destination                0     0 DROP       all  --  vlan2  *       0.0.0.0/0            192.168.1.0/24             Chain POSTROUTING (policy ACCEPT 99 packets, 6875 bytes)    pkts bytes target     prot opt in     out     source               destination                0     0 MASQUERADE  all  --  *      vlan2   0.0.0.0/0            0.0.0.0/0                  Chain OUTPUT (policy ACCEPT 99 packets, 6875 bytes)    pkts bytes target     prot opt in     out     source               destination                Chain WANPREROUTING (0 references)    pkts bytes target     prot opt in     out     source               destination            [email protected]:/tmp/home/root#   

Chain PREROUTING (policy ACCEPT 867 packets, 146K bytes) pkts bytes target prot opt in out source destination 0 0 DROP all — vlan2 * 0.0.0.0/0 192.168.1.0/24Chain POSTROUTING (policy ACCEPT 99 packets, 6875 bytes) pkts bytes target prot opt in out source destination 0 0 MASQUERADE all — * vlan2 0.0.0.0/0 0.0.0.0/0Chain OUTPUT (policy ACCEPT 99 packets, 6875 bytes) pkts bytes target prot opt in out source destinationChain WANPREROUTING (0 references) pkts bytes target prot opt in out source destination [email protected]:/tmp/home/root#

Here is another command:
$ sudo iptables -t nat -L -n -v
Sample outputs:

   Chain PREROUTING (policy ACCEPT 294K packets, 17M bytes)    pkts bytes target     prot opt in     out     source               destination             165K 9879K DNAT       tcp  --  *      *       0.0.0.0/0            192.168.203.146      tcp dpt:443 to:10.105.28.42:443    166K 9982K DNAT       tcp  --  *      *       0.0.0.0/0            192.168.203.146      tcp dpt:80 to:10.105.28.42:80       0     0 DNAT       tcp  --  *      *       0.0.0.0/0            192.168.203.146      tcp dpt:443 to:10.105.28.42:443       0     0 DNAT       tcp  --  *      *       0.0.0.0/0            192.168.203.146      tcp dpt:80 to:10.105.28.42:80   22034 1322K DNAT       tcp  --  *      *       0.0.0.0/0            192.168.203.146      tcp dpt:444 to:10.105.28.45:444   22073 1324K DNAT       tcp  --  *      *       0.0.0.0/0            192.168.203.146      tcp dpt:81 to:10.105.28.45:81   31328 1880K DNAT       tcp  --  *      *       0.0.0.0/0            192.168.203.146      tcp dpt:445 to:10.105.28.44:445   19424 1165K DNAT       tcp  --  *      *       0.0.0.0/0            192.168.203.146      tcp dpt:82 to:10.105.28.44:82       Chain INPUT (policy ACCEPT 199K packets, 12M bytes)    pkts bytes target     prot opt in     out     source               destination                Chain OUTPUT (policy ACCEPT 387 packets, 24906 bytes)    pkts bytes target     prot opt in     out     source               destination                Chain POSTROUTING (policy ACCEPT 252K packets, 15M bytes)    pkts bytes target     prot opt in     out     source               destination            93223 5593K MASQUERADE  all  --  *      *       10.105.28.0/24      !10.105.28.0/24       /* generated for LXD network lxdbr0 */   

Chain PREROUTING (policy ACCEPT 294K packets, 17M bytes) pkts bytes target prot opt in out source destination 165K 9879K DNAT tcp — * * 0.0.0.0/0 192.168.203.146 tcp dpt:443 to:10.105.28.42:443 166K 9982K DNAT tcp — * * 0.0.0.0/0 192.168.203.146 tcp dpt:80 to:10.105.28.42:80 0 0 DNAT tcp — * * 0.0.0.0/0 192.168.203.146 tcp dpt:443 to:10.105.28.42:443 0 0 DNAT tcp — * * 0.0.0.0/0 192.168.203.146 tcp dpt:80 to:10.105.28.42:80 22034 1322K DNAT tcp — * * 0.0.0.0/0 192.168.203.146 tcp dpt:444 to:10.105.28.45:444 22073 1324K DNAT tcp — * * 0.0.0.0/0 192.168.203.146 tcp dpt:81 to:10.105.28.45:81 31328 1880K DNAT tcp — * * 0.0.0.0/0 192.168.203.146 tcp dpt:445 to:10.105.28.44:445 19424 1165K DNAT tcp — * * 0.0.0.0/0 192.168.203.146 tcp dpt:82 to:10.105.28.44:82Chain INPUT (policy ACCEPT 199K packets, 12M bytes) pkts bytes target prot opt in out source destinationChain OUTPUT (policy ACCEPT 387 packets, 24906 bytes) pkts bytes target prot opt in out source destinationChain POSTROUTING (policy ACCEPT 252K packets, 15M bytes) pkts bytes target prot opt in out source destination 93223 5593K MASQUERADE all — * * 10.105.28.0/24 !10.105.28.0/24 /* generated for LXD network lxdbr0 */

Say hello netstat-nat

The netstat-nat command display the natted connections on a Linux iptable firewall:
# netstat-nat -n
To display SNAT connections, run:
# netstat-nat -S
To display DNAT connections, type:
# netstat-nat -D

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Shared via Inoreader

iPhoneから送信

Iptables List and Show All NAT IPTables Rules Command

How To Setup a Firewall with UFW on an Ubuntu and Debian Linux

by Vivek Gite

How do I setup a firewall with UFW (uncomplicated firewall) on an Ubuntu Linux 16.04 LTS server to restrict traffic on my personal web-server that hosts my pictures and blogs for my family members?

UFW is an acronym for uncomplicated firewall. It is used for managing a Linux firewall and aims to provide an easy to use interface for the user. In this tutorial you will learn how to use UFW a frontend to iptables for managing firewall on Ubuntu Linux 16.04 LTS server.

Installing UFW

UFW is included with Ubuntu but not with Debian Linux. Type the following apt-get command to install UFW in Debian Linux server:
$ sudo apt-get update
$ sudo apt-get install ufw

Sample outputs:
Fig.01: Installing UFW firewall on Debain or Ubuntu LInuxFig.01: Installing UFW firewall on Debain or Ubuntu LInux

How do I view status of ufw?

By default ufw is inactive status i.e. no firewall rules are configured and all traffic is allowed. To see status, enter:
$ sudo ufw status
Sample outputs:

   Status: inactive   

Setting up default policy

By default when ufw activated it blocks all incoming traffic to the firewall/server. Only outgoing traffic allowed. You can view UFW’s defaults by typing the following command:
$ grep 'DEFAULT_' /etc/default/ufw
Sample outputs:

   DEFAULT_INPUT_POLICY="DROP"   DEFAULT_OUTPUT_POLICY="ACCEPT"   DEFAULT_FORWARD_POLICY="DROP"   DEFAULT_APPLICATION_POLICY="SKIP"   

The default policy works out well for both the servers and laptop/workstation as you only need to open a limited number of incoming ports. It is a good policy as it closes all ports on the server/firewall and you need to only open ports one by one. You can run the following commands to set policy to block all incoming connection and only allow outgoing connections from the server/firewall:
$ sudo ufw default allow outgoing
$ sudo ufw default deny incoming

Writing your first firewall rule to allow connection to ssh (tcp port 22)

Type the following command to allow SSH connections to your server:
$ sudo ufw allow ssh
OR
sudo ufw allow 22/tcp
Say if you are running ssh on port 2020, enter:
$ sudo ufw allow 2020/tcp
The following rules allow access to tcp ssh port 22 only on 10.8.0.1 (i.e. your ssh server is listing on 10.8.0.1 port 22) from anywhere:
$ sudo ufw allow proto tcp from any to 10.8.0.1 port 22

How do I add a comment for the rule?

Use the following syntax
$ sudo ufw rule comment 'my cool comment here'
Open port 53 and write a comment about rule too:
ufw allow 53 comment 'open tcp and udp port 53 for dns'
Another example:
$ sudo ufw allow proto tcp from any to any port 80,443 comment 'my cool web app ports'
OR
$ sudo ufw allow proto tcp from any to 10.8.0.1 port 22 'SSHD port 22 for private lan'

Enable the UFW based firewall

Now you have default policy and ssh port allowed. It is safe to start enable the firewall, enter:
$ sudo ufw enable
Sample outputs:

      

Once enabled, the firewall runs after reboots too.

Disable the UFW based firewall

If you need to stop the firewall and disable on system startup, enter:
$ sudo ufw disable
Sample outputs:

      

How do I check the status of my rules?

Use the status command:
$ sudo ufw status
$ sudo ufw status verbose

Sample outputs:

   Status: active   Logging: on (low)   Default: deny (incoming), allow (outgoing), deny (routed)   New profiles: skip           To                         Action      From   --                         ------      ----   192.168.1.10 443/tcp       ALLOW       Anywhere                     192.168.1.10 22/tcp        ALLOW       Anywhere   

Status: active Logging: on (low) Default: deny (incoming), allow (outgoing), deny (routed) New profiles: skipTo Action From — —— —- 192.168.1.10 443/tcp ALLOW Anywhere 192.168.1.10 22/tcp ALLOW Anywhere

Adding more rules (open ports and allow IPs)

The syntax is as follows to open tcp port 22 and 443:
$ sudo ufw allow 80/tcp
$ sudo ufw allow 443/tcp

Open UDP/1194 (OpenVPN) server:
$ sudo ufw allow 1194/udp
Open port 25 (smtpd/email server):
$ sudo ufw allow 25

Allowing port ranges

You can allow port ranges too say, tcp and udp 3000 to 5000:
$ sudo ufw allow 3000:5000/tcp
$ sudo ufw allow 3000:5000/udp

Make sure you allow connections from an IP address called 1.2.3.4, enter:
$ sudo ufw allow from 1.2.3.4
Make sure you allow connections from an IP address called 1.2.3.4 to our port 22, enter:
$ sudo ufw allow from 1.2.3.4 to any port 22 proto tcp
OR (dest 222.222.222.222 port 22)
$ sudo ufw allow from 1.2.3.4 to 222.222.222.222 port 22 proto tcp

How to allow incoming HTTPS traffic (open port 443)

$ sudo ufw allow https comment 'Allow all to access Nginx server'
## allow only from 139.1.1.1 ##
$ sudo ufw allow from 139.1.1.1 to any port 443
## allow only from 203.11.11.2/29 ##
$ sudo ufw allow from 203.11.11.2/29 to any port 443

How to allow incoming HTTP traffic (open port 80)

$ sudo ufw allow http comment 'Allow all to access Apache server'
## allow only from 139.1.1.1 ##
$ sudo ufw allow from 139.1.1.1 to any port 80
## allow only from 203.11.11.2/29 ##
$ sudo ufw allow from 203.11.11.2/29 to any port 80

How to allow incoming MySQL/MariaDB traffic (open port 3306)

Allow access to MySQL/MariaDB port 3306 from selected subnet only (see MySQL/MariaDB remote access tutorial):
$ sudo ufw allow from 192.168.1.0/24 to any port 3306
Allow access to MySQL/MariaDB port 3306 Apache server only:
$ sudo ufw allow from 202.54.1.1 to any port 3306

How to allow incoming PostgreSQL traffic (open port 5432)

Allow access to PostgreSQL port 5432 from selected subnet only (see PostgreSQL remote access tutorial):
$ sudo ufw allow from 192.168.1.0/24 to any port 5432
Allow access to PostgreSQL port 5432 Apache server only:
$ sudo ufw allow from 202.54.1.1 to any port 5432

How to allow incoming SMTPD/Postfix/Sendmail (mail server) traffic (open port 25)

$ sudo ufw allow 25
$ sudo ufw allow smtp

How to allow incoming IMAP/IMAP
S

$ sudo ufw allow 143
$ sudo ufw allow 993

How to allow incoming POP3/POP3S

$ sudo ufw allow 110
$ sudo ufw allow 995

Denying access to port or connections (close ports and block IPs)

The syntax is as follows to deny access (i.e. simply ignoring access to port 443) to port tcp port 443:
$ sudo ufw deny 443/tcp
Make sure you deny all connections from an IP address called 1.2.3.4, enter:
$ sudo ufw deny from 1.2.3.4
Make sure you deny all connections from an IP/subnet called 123.45.67.89/24, enter:
$ sudo ufw deny from 123.45.67.89/24
Make sure you deny access to 1.2.3.4 (say hackers IP) on port 22:
$ sudo ufw deny from 1.2.3.4 to any port 22 proto tcp

Rejecting access to port or connections (reject and let user know they are blocked by firewall)

The deny syntax simply ignores traffic. If you want let the sender know when traffic is being denied, rather than simply ignoring it, use reject syntax:
$ sudo ufw reject in smtp
$ sudo ufw reject out smtp
$ sudo sudo ufw reject 1194 comment 'No more vpn traffic'
$ sudo ufw reject 23 comment 'Unencrypted port not allowed'

If somebody try to connect to port 23 they will get reject message as follows:

   telnet: Unable to connect to remote host: Connection refused   

Deleting the UFW firewall rules

Now you know how to add, deny, and list the firewall rules. It is time to delete unwanted rules. There are two options to deleting rules. The first syntax is:
$ sudo ufw delete {rule-here}
In this example, delete HTTPS (tcp port 443) traffic rule,
$ sudo ufw delete allow 443
If you no longer wished to allow smptd/email (port 25) traffic, execute:
$ sudo ufw delete allow 25
The second option is to list list all of the current rules in a numbered list format:
$ sudo ufw status numbered
Sample outputs:

   Status: active            To                         Action      From        --                         ------      ----   [ 1] 10.8.0.1 22/tcp            ALLOW IN    Anywhere                     [ 2] Anywhere                   DENY IN     123.45.67.0/24               [ 3] 22/tcp                     DENY IN     1.2.3.4   

Status: activeTo Action From — —— —- [ 1] 10.8.0.1 22/tcp ALLOW IN Anywhere [ 2] Anywhere DENY IN 123.45.67.0/24 [ 3] 22/tcp DENY IN 1.2.3.4

To delete 2nd rule (“ufw deny from 123.45.67.89/24”), you type the command:
$ sudo ufw delete 2
Sample outputs:

   Deleting:    deny from 123.45.67.0/24   Proceed with operation (y|n)? y   Rule deleted   

How do I reset the firewall?

The syntax is as follows to reset ufw rules to their factory default settings and in an inactive mode, run:
$ sudo ufw reset
Sample outputs:

   Resetting all rules to installed defaults. This may disrupt existing ssh   connections. Proceed with operation (y|n)? y   Backing up 'user6.rules' to '/etc/ufw/user6.rules.20160801_121710'   Backing up 'after.rules' to '/etc/ufw/after.rules.20160801_121710'   Backing up 'before.rules' to '/etc/ufw/before.rules.20160801_121710'   Backing up 'after6.rules' to '/etc/ufw/after6.rules.20160801_121710'   Backing up 'user.rules' to '/etc/ufw/user.rules.20160801_121710'   Backing up 'before6.rules' to '/etc/ufw/before6.rules.20160801_121710'   

How do I reload the firewall?

The syntax is as follows to reload firewall:
$ sudo ufw reload
When you edit UFW’ configuration file, you need to run reload command. For example, you can edit /etc/ufw/before.rules, enter:
$ sudo nano /etc/ufw/before.rules
OR
$ sudo vi /etc/ufw/before.rules
To allow all traffic fro eth0 to eth0 (add after line that read as “# End required lines”), enter:

   # allow all on eth0   -A ufw-before-input -i eth0 -j ACCEPT   -A ufw-before-output -o eth0 -j ACCEPT   

Save and close the file. Reload the firwall:
$ sudo ufw reload

How do I see the firewall logs?

By default all UFW entries are logged into /var/log/ufw.log file:
$ sudo more /var/log/ufw.log
$ sudo tail -f /var/log/ufw.log

Sample outputs:

      

You can search log file with grep command:
$ sudo grep something /var/log/ufw.log
$ sudo grep '187.134.225.91' /var/log/ufw.log

How do I see ufw reports?

The added report displays the list of rules as they were added on the command-line:
$ sudo ufw show added
Sample outputs:

   Added user rules (see 'ufw status' for running firewall):   ufw allow 22   ufw reject 23   

The raw report shows the complete firewall, while the others show a subset of what is in the raw report:
$ sudo ufw show raw
$ sudo ufw show raw | more

The listening report will display the ports on the live system in the listening state for tcp and the open state for udp, along with the address of the interface and the executable listening on the port. An ‘*’ is used in place of the address of the interface when the executable is bound to all interfaces on that port. Following this information is a list of rules which may affect connections on this port. The rules are listed in the order they are evaluated by the kernel, and the first match wins. Please note that the default policy is not listed and tcp6 and udp6 are shown only if IPV6 is enabled:
$ sudo ufw show listening
$ sudo ufw show listening | more

   tcp:     22 10.86.115.66 (sshd)      [ 1] allow 22         22 10.8.0.1 (sshd)      [ 1] allow 22         443 75.xxx.yyy.zzz (openvpn)   udp:     123 10.8.0.1 (ntpd)     123 75.xxx.yyy.zzz (ntpd)     123 10.86.115.66 (ntpd)     123 * (ntpd)   udp6:     123 * (ntpd)   

tcp: 22 10.86.115.66 (sshd) [ 1] allow 2222 10.8.0.1 (sshd) [ 1] allow 22443 75.xxx.yyy.zzz (openvpn) udp: 123 10.8.0.1 (ntpd) 123 75.xxx.yyy.zzz (ntpd) 123 10.86.115.66 (ntpd) 123 * (ntpd) udp6: 123 * (ntpd)

Other possible reports are:
$ sudo ufw show builtins
$ sudo ufw show before-rules
$ sudo ufw show user-rules
$ sudo ufw show after-rules
$ sudo ufw show logging-rules

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Shared via Inoreader

iPhoneから送信

How To Setup a Firewall with UFW on an Ubuntu and Debian Linux

40 Linux Server Hardening Security Tips [2017 edition]

by Vivek Gite

linux-logo.png

Securing your Linux server is important to protect your data, intellectual property, and time, from the hands of crackers (hackers). The system administrator is responsible for security of the Linux box. In this first part of a Linux server security series, I will provide 40 hardening tips for default installation of Linux system.

Linux Security Tips

Linux Server Hardening Checklist and Tips

The following instructions assume that you are using CentOS/RHEL or Ubuntu/Debian based Linux distribution.

#1: Encrypt Data Communication

All data transmitted over a network is open to monitoring. Encrypt transmitted data whenever possible with password or using keys / certificates.

  1. Use scp, ssh, rsync, or sftp for file transfer. You can also mount remote server file system or your own home directory using special sshfs and fuse tools.
  2. GnuPG allows to encrypt and sign your data and communication, features a versatile key managment system as well as access modules for all kind of public key directories.
  3. OpenVPN is a cost-effective, lightweight SSL VPN. Another option is to try out tinc that uses tunneling and encryption to create a secure private network between hosts on the Internet or private insecure LAN.
  4. Lighttpd SSL (Secure Server Layer) Https Configuration And Installation
  5. Apache SSL (Secure Server Layer) Https (mod_ssl) Configuration And Installation
  6. How to configure Nginx with free Let’s Encrypt SSL certificate on Debian or Ubuntu Linux

#2: Avoid Using FTP, Telnet, And Rlogin / Rsh Services

Under most network configurations, user names, passwords, FTP / telnet / rsh commands and transferred files can be captured by anyone on the same network using a packet sniffer. The common solution to this problem is to use either OpenSSH , SFTP, or FTPS (FTP over SSL), which adds SSL or TLS encryption to FTP. Type the following yum command to delete NIS, rsh and other outdated service:
# yum erase xinetd ypserv tftp-server telnet-server rsh-server
If you are using a Debian/Ubuntu Linux based server, try apt-get command/apt command to remove insecure services:
$ sudo apt-get --purge remove xinetd nis yp-tools tftpd atftpd tftpd-hpa telnetd rsh-server rsh-redone-server

#3: Minimize Software to Minimize Vulnerability

Do you really need all sort of web services installed? Avoid installing unnecessary software to avoid vulnerabilities in software. Use the RPM package manager such as yum or apt-get and/or dpkg to review all installed set of software packages on a system. Delete all unwanted packages.
# yum list installed
# yum list packageName
# yum remove packageName

OR
# dpkg --list
# dpkg --info packageName
# apt-get remove packageName

#4: One Network Service Per System or VM Instance

Run different network services on separate servers or VM instance. This limits the number of other services that can be compromised. For example, if an attacker able to successfully exploit a software such as Apache flow, he or she will get an access to entire server including other services such as MySQL/MariaDB/PGSql, e-mail server and so on. See how to install Virtualization software for more info:

#5: Keep Linux Kernel and Software Up to Date

Applying security patches is an important part of maintaining Linux server. Linux provides all necessary tools to keep your system updated, and also allows for easy upgrades between versions. All security update should be reviewed and applied as soon as possible. Again, use the RPM package manager such as yum and/or apt-get and/or dpkg to apply all security updates.
# yum update
OR
# apt-get update && apt-get upgrade
You can configure Red hat / CentOS / Fedora Linux to send yum package update notification via email. Another option is to apply all security updates via a cron job. Under Debian / Ubuntu Linux you can use apticron to send security notifications. It is also possible to configure unattended upgrades for your Debian/Ubuntu Linux server using apt-get command/apt command:
$ sudo apt-get install unattended-upgrades apt-listchanges bsd-mailx

#6: Use Linux Security Extensions

Linux comes with various security patches which can be used to guard against misconfigured or compromised programs. If possible use SELinux and other L
inux security
extensions to enforce limitations on network and other programs. For example, SELinux provides a variety of security policies for Linux kernel.

#7: SELinux

I strongly recommend using SELinux which provides a flexible Mandatory Access Control (MAC). Under standard Linux Discretionary Access Control (DAC), an application or process running as a user (UID or SUID) has the user’s permissions to objects such as files, sockets, and other processes. Running a MAC kernel protects the system from malicious or flawed applications that can damage or destroy the system. See the official Redhat documentation which explains SELinux configuration.

#8: User Accounts and Strong Password Policy

Use the useradd / usermod commands to create and maintain user accounts. Make sure you have a good and strong password policy. For example, a good password includes at least 8 characters long and mixture of alphabets, number, special character, upper & lower alphabets etc. Most important pick a password you can remember. Use tools such as “John the ripper” to find out weak users passwords on your server. Configure pam_cracklib.so to enforce the password policy.

#9: Password Aging

The chage command changes the number of days between password changes and the date of the last password change. This information is used by the system to determine when a user must change his/her password. The /etc/login.defs file defines the site-specific configuration for the shadow password suite including password aging configuration. To disable password aging, enter:
# chage -M 99999 userName
To get password expiration information, enter:
# chage -l userName
Finally, you can also edit the /etc/shadow file in the following fields:

   {userName}:{password}:{lastpasswdchanged}:{Minimum_days}:{Maximum_days}:{Warn}:{Inactive}:{Expire}:   

Where,

  1. Minimum_days: The minimum number of days required between password changes i.e. the number of days left before the user is allowed to change his/her password.
  2. Maximum_days: The maximum number of days the password is valid (after that user is forced to change his/her password).
  3. Warn : The number of days before password is to expire that user is warned that his/her password must be changed.
  4. Expire : Days since Jan 1, 1970 that account is disabled i.e. an absolute date specifying when the login may no longer be used.

I recommend chage command instead of editing the /etc/shadow file by hand:
# chage -M 60 -m 7 -W 7 userName
Recommend readings:

#10: Restricting Use of Previous Passwords

You can prevent all users from using or reuse same old passwords under Linux. The pam_unix module parameter remember can be used to configure the number of previous passwords that cannot be reused.

#11: Locking User Accounts After Login Failures

Under Linux you can use the faillog command to display faillog records or to set login failure limits. faillog formats the contents of the failure log from /var/log/faillog database / log file. It also can be used for maintains failure counters and limits.To see failed login attempts, enter:
faillog
To unlock an account after login failures, run:
faillog -r -u userName
Note you can use passwd command to lock and unlock accounts:
# lock account
passwd -l userName
# unlocak account
passwd -u userName

#12: How Do I Verify No Accounts Have Empty Passwords?

Type the following command
# awk -F: '($2 == "") {print}' /etc/shadow
Lock all empty password accounts:
# passwd -l accountName

#13: Make Sure No Non-Root Accounts Have UID Set To 0

Only root account have UID 0 with full permissions to access the system. Type the following command to display all accounts with UID set to 0:
# awk -F: '($3 == "0") {print}' /etc/passwd
You should only see one line as follows:

   root:x:0:0:root:/root:/bin/bash   

If you see other lines, delete them or make sure other accounts are authorized by you to use UID 0.

#14: Disable root Login

Never ever login as root user. You should use sudo to execute root level commands as and when required. sudo does greatly enhances the security of the system without sharing root password with other users and admins. sudo provides simple auditing and tracking features too.

#15: Physical Server Security

You must protect Linux servers physical console access. Configure the BIOS and disable the booting from external devices such as DVDs / CDs / USB pen. Set BIOS and grub boot loader password to protect these settings. All production boxes must be locked in IDCs (Internet Data Center) and all persons must pass some sort of security checks before accessing your server. See also:

#16: Disable Unwanted Services

Disable all unnecessary services and daemons (services that runs in the background). You need to remove all unwanted services from the system start-up. Type the following command to list all services which are started at boot time in run level # 3:
# chkconfig --list | grep '3:on'
To disable service, enter:
# service serviceName stop
# chkconfig serviceName off

#17: Find Listening Network Ports

Use the following command to list all open ports and associated programs:
netstat -tulpn
OR use the ss command as follows:
$ ss -tulpn
OR
nmap -sT -O localhost
nmap -sT -O server.example.com

#18: Delete X Windows

X Windows on server is not required. There is no reason to run X Windows on your dedicated mail and Apache web server. You can disable and remove X Windows to improve server security and performance. Edit /etc/inittab and set run level to 3. Finally, remove X Windows system, enter:
# yum groupremove "X Window System"
On CentOS 7/RHEL 7 server u
se the following commands:
# yum group remove "GNOME Desktop"
# yum group remove "KDE Plasma Workspaces"
# yum group remove "Server with GUI"
# yum group remove "MATE Desktop"

#19: Configure Iptables and TCPWrappers

Iptables is a user space application program that allows you to configure the firewall (Netfilter) provided by the Linux kernel. Use firewall to filter out traffic and allow only necessary traffic. Also use the TCPWrappers a host-based networking ACL system to filter network access to Internet. You can prevent many denial of service attacks with the help of Iptables:

#20: Linux Kernel /etc/sysctl.conf Hardening

/etc/sysctl.conf file is used to configure kernel parameters at runtime. Linux reads and applies settings from /etc/sysctl.conf at boot time. Sample /etc/sysctl.conf:

   # Turn on execshield   kernel.exec-shield=1   kernel.randomize_va_space=1   # Enable IP spoofing protection   net.ipv4.conf.all.rp_filter=1   # Disable IP source routing   net.ipv4.conf.all.accept_source_route=0   # Ignoring broadcasts request   net.ipv4.icmp_echo_ignore_broadcasts=1   net.ipv4.icmp_ignore_bogus_error_messages=1   # Make sure spoofed packets get logged   net.ipv4.conf.all.log_martians = 1   

#21: Separate Disk Partitions

Separation of the operating system files from user files may result into a better and secure system. Make sure the following filesystems are mounted on separate partitions:

  • /usr
  • /home
  • /var and /var/tmp
  • /tmp

Create separate partitions for Apache and FTP server roots. Edit /etc/fstab file and make sure you add the following configuration options:

  1. noexec – Do not set execution of any binaries on this partition (prevents execution of binaries but allows scripts).
  2. nodev – Do not allow character or special devices on this partition (prevents use of device files such as zero, sda etc).
  3. nosuid – Do not set SUID/SGID access on this partition (prevent the setuid bit).

Sample /etc/fstab entry to to limit user access on /dev/sda5 (ftp server root directory):

   /dev/sda5  /ftpdata          ext3    defaults,nosuid,nodev,noexec 1 2   

#22: Disk Quotas

Make sure disk quota is enabled for all users. To implement disk quotas, use the following steps:

  1. Enable quotas per file system by modifying the /etc/fstab file.
  2. Remount the file system(s).
  3. Create the quota database files and generate the disk usage table.
  4. Assign quota policies.
  5. See implementing disk quotas tutorial for further details.

#23: Turn Off IPv6

Internet Protocol version 6 (IPv6) provides a new Internet layer of the TCP/IP protocol suite that replaces Internet Protocol version 4 (IPv4) and provides many benefits. If you are NOT using IPv6 disable it:

#24: Disable Unwanted SUID and SGID Binaries

All SUID/SGID bits enabled file can be misused when the SUID/SGID executable has a security problem or bug. All local or remote user can use such file. It is a good idea to find all such files. Use the find command as follows:
#See all set user id files:
find / -perm +4000
# See all group id files
find / -perm +2000
# Or combine both in a single command
find / ( -perm -4000 -o -perm -2000 ) -print
find / -path -prune -o -type f -perm +6000 -ls

You need to investigate each reported file. See reported file man page for further details.

#25: World-Writable Files

Anyone can modify world-writable file resulting into a security issue. Use the following command to find all world writable and sticky bits set files:
find /dir -xdev -type d ( -perm -0002 -a ! -perm -1000 ) -print
You need to investigate each reported file and either set correct user and group permission or remove it.

#26: Noowner Files

Files not owned by any user or group can pose a security problem. Just find them with the following command which do not belong to a valid user and a valid group
find /dir -xdev ( -nouser -o -nogroup ) -print
You need to investigate each reported file and either assign it to an appropriate user and group or remove it.

#27: Use A Centralized Authentication Service

Without a centralized authentication system, user auth data becomes inconsistent, which may lead into out-of-date credentials and forgotten accounts which should have been deleted in first place. A centralized authentication service allows you maintaining central control over Linux / UNIX account and authentication data. You can keep auth data synchronized between servers. Do not use the NIS service for centralized authentication. Use OpenLDAP for clients and servers.

#28: Kerberos

Kerberos performs authentication as a trusted third party authentication service by using cryptographic shared secret under the assumption that packets traveling along the insecure network can be read, modified, and inserted. Kerberos builds on symmetric-key cryptography and requires a key distribution center. You can make remote login, remote copy, secure inter-system file copying and other high-risk tasks safer and more controllable using Kerberos. So, when users authenticate to network services using Kerberos, unauthorized users attempting to gather passwords by monitoring network traffic are effectively thwarted. See how to setup and use Kerberos.

#29: Logging and Auditing

You need to configure logging and auditing to collect all hacking and cracking attempts. By default syslog stores data in /var/log/ directory. This is also useful to find out software misconfiguration which may open your system to various attacks. See the following logging related articles:

  1. Linux log file locations.
  2. How to send logs to a remote loghost.
  3. How do I rotate log files?.
  4. man pages syslogd, syslog.conf and logrotate.

#30: Monitor Suspicious Log Messages With Logwatch / Logcheck

Read your logs using logwatch command (logcheck). These tools make your log reading life easier. You get detailed reporting on unusual items in syslog via email. A sample syslog report:

    ################### Logwatch 7.3 (03/24/06) ####################           Processing Initiated: Fri Oct 30 04:02:03 2009           Date Range Processed: yesterday                                 ( 2009-Oct-29 )
                          Period is day.         Detail Level of Output: 0                 Type of Output: unformatted              Logfiles for Host: www-52.nixcraft.net.in     ##################################################################       --------------------- Named Begin ------------------------       **Unmatched Entries**       general: info: zone XXXXXX.com/IN: Transfer started.: 3 Time(s)       general: info: zone XXXXXX.com/IN: refresh: retry limit for master ttttttttttttttttttt#53 exceeded (source ::#0): 3 Time(s)       general: info: zone XXXXXX.com/IN: Transfer started.: 4 Time(s)       general: info: zone XXXXXX.com/IN: refresh: retry limit for master ttttttttttttttttttt#53 exceeded (source ::#0): 4 Time(s)       ---------------------- Named End -------------------------        --------------------- iptables firewall Begin ------------------------       Logged 87 packets on interface eth0      From 58.y.xxx.ww - 1 packet to tcp(8080)      From 59.www.zzz.yyy - 1 packet to tcp(22)      From 60.32.nnn.yyy - 2 packets to tcp(45633)      From 222.xxx.ttt.zz - 5 packets to tcp(8000,8080,8800)       ---------------------- iptables firewall End -------------------------       --------------------- SSHD Begin ------------------------       Users logging in through sshd:       root:          123.xxx.ttt.zzz: 6 times       ---------------------- SSHD End -------------------------       --------------------- Disk Space Begin ------------------------       Filesystem            Size  Used Avail Use% Mounted on    /dev/sda3             450G  185G  241G  44% /    /dev/sda1              99M   35M   60M  37% /boot       ---------------------- Disk Space End -------------------------       ###################### Logwatch End #########################   

See Common Linux log files names and usage for more info.

#31: System Accounting with auditd

The auditd is provided for system auditing. It is responsible for writing audit records to the disk. During startup, the rules in /etc/audit.rules are read by this daemon. You can open /etc/audit.rules file and make changes such as setup audit file log location and other option. With auditd you can answers the following questions:

  1. System startup and shutdown events (reboot / halt).
  2. Date and time of the event.
  3. User respoisble for the event (such as trying to access /path/to/topsecret.dat file).
  4. Type of event (edit, access, delete, write, update file & commands).
  5. Success or failure of the event.
  6. Records events that Modify date and time.
  7. Find out who made changes to modify the system’s network settings.
  8. Record events that modify user/group information.
  9. See who made changes to a file etc.

See our quick tutorial which explains enabling and using the auditd service.

#32: Secure OpenSSH Server

The SSH protocol is recommended for remote login and remote file transfer. However, ssh is open to many attacks. See how to secure OpenSSH server:

#33: Install And Use Intrusion Detection System

A network intrusion detection system (NIDS) is an intrusion detection system that tries to detect malicious activity such as denial of service attacks, port scans or even attempts to crack into computers by monitoring network traffic.

It is a good practice to deploy any integrity checking software before system goes online in a production environment. If possible install AIDE software before the system is connected to any network. AIDE is a host-based intrusion detection system (HIDS) it can monitor and analyses the internals of a computing system. I recommended that you install and use rkhunter root kit detection software too.

#34: Disable USB/firewire/thunderbolt devices

Type the following command to disable USB devices on Linux system:
# echo 'install usb-storage /bin/true' >> /etc/modprobe.d/disable-usb-storage.conf
You can use same method to disable firewire and thunderbolt modules:
# echo "blacklist firewire-core" >> /etc/modprobe.d/firewire.conf
# echo "blacklist thunderbolt" >> /etc/modprobe.d/thunderbolt.conf

Once done, users can not quickly copy sensitive data to USB devices or install malware/viruses or backdoor on your Linux based system.

#35: Disable unused services

You can disable unused services using the service command/systemctl command:
$ sudo systemctl stop service
$ sudo systemctl disable service

For example, if you are not going to use Nginx service for some time disable it:
$ sudo systemctl stop nginx
$ sudo systemctl disable nginx

#36: Use fail2ban/denyhost as IDS (Install an Intrusion Detection System)

Fail2ban or denyhost scans the log files for too many failed login attempts and blocks the IP address which is showing malicious signs. See how to install and use denyhost for Linux. One can install fail2ban easily:
$ sudo apt-get install fail2ban
OR
$ sudo yum install fail2ban
Edit the config file as per your needs:
$ sudo vi /etc/fail2ban/jail.conf
Restart the service:
$ sudo systemctl restart fail2ban.service

#37: Secure Apache/PHP/Nginx server

Edit httpd.conf file and add the following:

   ServerTokens Prod   ServerSignature Off   TraceEnable Off   Options all -Indexes   Header always unset X-Powered-By   

Restart the httpd/apache2 server on Linux, run:
$ sudo systemctl restart apache2.service
OR
$ sudo systemctl restart httpd.service
You must install and enable mod_security on RHEL/CentOS server. It is recommended that you edit php.ini and secure it too.

#38: Protecting Files, Directories and Email

Linux offers excellent protections against unauthorized data access. File permissions and MAC prevent unauthorized access from accessing data. However, permissions set by the Linux are irrelevant if an attacker has physical access to a computer and can simply move the computer’s hard drive to another system to copy and analyze the sensitive data. You can easily protect files, and partitons under Linux using the following tools:

#39. Backups

It cannot be stressed enough how important it is to make a backup of your Linux system. A proper offsite backup allows you to recover from cracked server i.e. an intrusion. The traditional UNIX backup programs are dump and restore are also recommended. You must set up encrypted backups to external storage such as NAS server or FreeNAS server or use cloud computing service such as AWS:

#
40. Other Recommendation:

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Shared via Inoreader

iPhoneから送信

40 Linux Server Hardening Security Tips [2017 edition]

How to Set Up a Raspberry Pi in Linux

by Christian Cawley

MakeUseOf / 2017-08-15 03:01

It can be used as a media center Install Kodi to Turn Your Raspberry Pi Into a Home Media Center Install Kodi to Turn Your Raspberry Pi Into a Home Media Center You need a media center solution, and you’ve heard about Kodi. Is it suitable, and can you install it on your Raspberry Pi? And how do you take it beyond the basics? Read More , the brain of a robot, as a web server, even a digital picture frame ShowerThoughts and EarthPorn: Make an Inspiring Raspberry Pi Photo Frame ShowerThoughts and EarthPorn: Make an Inspiring Raspberry Pi Photo Frame Read More . The little Raspberry Pi appears to know very few limits… you can even run old Windows games on it without emulation!

Setting up a Raspberry Pi opens a gateway to an exciting world of compact, portable computing. It seems like almost all of the instructions online are for Windows computers, however, if you’re running Linux, you may not know how to successfully set up your Raspberry Pi.

We’ve already addressed this problem for Apple macOS users Getting Started With Raspberry Pi On The Mac Getting Started With Raspberry Pi On The Mac Apple users can get in on the Raspberry Pi game pretty easily, but there are a few different ways to image a microSD card using your Mac. Read More , so now it’s the turn of Linux. Here’s how to swiftly and easily set up a Raspberry Pi using your Linux computer.

The Easy Way: Use NOOBS

Released in 2013, NOOBS (New Out Of Box Software) is a useful installation interface that gives you the chance to select from multiple Raspberry Pi operating systems. One or more of these can then be installed, depending on how much space you have on your microSD card. Ensure your card is at least 4 GB. Because it will need to be formatted first, before inserting, list any mounted devices with:

sudo fdisk -l  

Now, insert the card and run the command again. The new entry is your microSD card. Typically, the card will be labeled mmcblk0. However, if it has been partitioned, the name will be appended with p1, such as mmcblk0p1.

Next, run fdisk:

sudo fdisk /dev/mmcblk0  

Delete any partitions on that drive with d, inputting the partition number when prompted. When done, follow this with n to create a new partition, then p to confirm the details of the partition.

linux setup raspberry pi

At this stage, the partition type will be set to Linux, but NOOBS requires FAT32. To set FAT32, tap t, select the partition number, and then the partition type (W95 FAT32). Confirm the details again with p. Finally, hit w to write the partition table.

linux raspberry pi setup format

Next, you need to format the partition:

sudo mkfs.vfat /dev/mmcblk0p1  

Ensure you use the name of the partition, rather than the device.

Download NOOBS

You can download NOOBS from www.raspberrypi.org/downloads. Save this to a location on your PC where you can easily find it.

The downloaded ZIP comes in two sizes: a full version for offline installation, and a lite option which requires an internet connection for your Pi. This is achieved via Ethernet cable (Wi-Fi will be available once the operating system is installed).

Included in NOOBS are:

  1. Raspbian
  2. Pidora
  3. RISC OS
  4. Arch Linux
  5. OSMC

At times, additional Linux versions are added to the list.

Copying the NOOBS software to the microSD card will require you to first mount the card, with:

mount | grep -i mmcblk0p1  

When this is done, the internal serial number of the media device should be displayed. Use this to change directory:

cd /media/[serial]  

All you need to do now is, unzip the NOOBS download:

unzip /home/[your_username]/Downloads/RaspberryPi/distros/NOOBS_v1_3_11.zip  

Wait while this command unzips the NOOBS data into the microSD card. Once complete, you’ll need to safely unmount the card to eject it:

cd    sudo umount /dev/mmcblk0p1  

With the card removed, you’re ready to insert it into a powered-down Raspberry Pi. With the power cable connected (along with a mouse and/or keyboard and a HDMI display) you’ll be ready to select your preferred operating system(s), and let NOOBS finish things off.

linux raspberry pi setup noobs

Note that if you opted to install multiple operating systems, when you boot your Raspberry Pi, a menu will be displayed for you to choose which one you want to use.

Install an Operating System Image

Your other option is to download an operating system — typically Raspbian Jessie, but many alternatives are available 7 Operating Systems You Can Run With Raspberry Pi 7 Operating Systems You Can Run With Raspberry Pi Who can argue with a $40 computer? Especially one that also forms a good base for electronics projects! I certainly can’t. But the hardware alone is only one side of the story: you still need… Read More — and write this to the microSD card.

The best way to do this is with a third party application. Several are available for writing disk images, such as Etcher, which you’ll find
in your package manager.

linux raspberry pi setup etcher config

Once you’ve done that, it’s time to choose your Raspberry Pi operating system. As noted, several are available. The preferred option is Raspbian Jessie (also available from www.raspberrypi.org/downloads), but you might just as easily install RecalBox Retro Gaming in Style With RecalBox for the Raspberry Pi Retro Gaming in Style With RecalBox for the Raspberry Pi RecalBox brings together classic emulators with a fantastic unified user interface that makes choosing games and configuring your controllers easy. Read More for retro gaming, Ubuntu MATE How to Get Ubuntu Running on Your Raspberry Pi How to Get Ubuntu Running on Your Raspberry Pi Raspbian Jessie is a great Raspberry Pi operating system. But what if you want a more traditional Linux experience? Well, you could go ahead and install Ubuntu instead. Read More , or any other compatible operating system you can find.

Download the image file (which should have the .IMG suffix) to a memorable place on your Linux computer (the Downloads folder in the Home directory is always good) and if necessary, unpackage any compression. What you should end up with is a file along the lines of raspberrypi_operatingsystem.img.

linux raspberry pi setup etcher

Next, run Etcher, and browse for and select the IMG file in the Select image box. Note that you can hover the mouse over the filename after you’ve done this to check the right file is selected. You can even click the pop-up to read the full file path.

Next, ensure that the correct drive is selected. Mouse over the drive icon to confirm the name, and if you need to amend it, click Change. Any other external storage connected to your computer will be listed here. Make sure the microSD card is selected.

linux raspberry pi setup etcher complete

Click Flash to begin writing the IMG file to the microSD card. Once this is done, your Raspberry Pi operating system will be ready to use. Safely eject the card, and insert it into your switched off Pi. Connect the power to boot up and enjoy!

Set Up Your Raspberry Pi in Linux With Ease!

It really is that easy. If you’re installing a standard operating system IMG file, all you need is an image-to-SD-card writing app such as Image Writer. While using the dd command in the terminal How to Easily Clone and Restore a Linux Disk Image With dd How to Easily Clone and Restore a Linux Disk Image With dd If you want to wipe, backup, or restore data on Linux, there are a number of apps you can pick. But whichever Linux operating system you run, there’s one command that always works — dd. Read More is an option, it’s not suitable for beginners.

If you want a choice of operating systems curated by the Raspberry Pi team that is easy to install, then NOOBS should be your option.

In short, setting up a Raspberry Pi with Linux is just as simple as it is in Windows or macOS!

Which option did you use? Do you use NOOBS on your Raspberry Pi, or do you prefer a single operating system on your microSD card? Did you run into any problems? Let us know in the comments.

Image Credit: Bygetvitamin via Shutterstock.com

0 comments Write a Comment

Shared via Inoreader

iPhoneから送信

How to Set Up a Raspberry Pi in Linux