Network Security Basics: Connecting Safely
Welcome to the fifth installment in our TTY series! In previous posts, we've covered how to navigate the Linux file system, keep your software updated, control file permissions, and manage processes. In this post, we'll explore network security basics, like how your Linux system connects to the outside world and how to protect those connections.
Network connectivity is essential for most systems today, but it’s also one of the primary attack vectors. Understanding how your Linux system communicates over a network and implementing a few basic security measures can significantly reduce your vulnerability to external threats.
Understanding Your Network Interfaces
Let's start by identifying how your system connects to the network. Network interfaces are the connection points between your computer and the outside world.
To view your network interfaces, you can use the `ip` utility with the `address` object and `show` command:
$ ip a show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether 00:16:3e:5e:6c:00 brd ff:ff:ff:ff:ff:ff
inet 192.168.1.100/24 brd 192.168.1.255 scope global dynamic eth0
valid_lft 86389sec preferred_lft 86389sec
inet6 fe80::216:3eff:fe5e:6c00/64 scope link
valid_lft forever preferred_lft forever
NOTE: You can abbreviate `address` as `addr` or `a`
In this example, we see two interfaces:
- `lo`: The loopback interface (127.0.0.1), used for internal communications within your system.
- `eth0`: An ethernet interface with the IP address 192.168.1.100. This is your connection to the local network!
You might also see interfaces like:
- `wlan0`: Wireless network connection
- `tun0` or `vpn0`: VPN connections
- `docker0`: Docker container network bridge
- `ens33`: A different naming convention for `eth0`
For older systems, you might use the `ifconfig` command instead:
$ ifconfig
If this command isn't found, you can install it with:
$ sudo apt install net-tools# For Debian/Ubuntu
Checking Network Connectivity
To test basic network connectivity, use the `ping` command:
$ ping -c 4 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=53 time=11.6 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=53 time=12.1 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=53 time=11.9 ms
64 bytes from 8.8.8.8: icmp_seq=4 ttl=53 time=12.0 ms
--- 8.8.8.8 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3006ms
rtt min/avg/max/mdev = 11.637/11.909/12.084/0.173 ms
The `-c 4` option limits the test to 4 packets. If we don't specify a count, ping just keeps going until you hit CTRL+C. This example shows a successful connection to Google's DNS server (8.8.8.8).
To test DNS resolution (converting hostnames to IP addresses):
$ host example.com
example.com has address 93.184.216.34
example.com has IPv6 address 2606:2800:220:1:248:1893:25c8:1946
Or use the `dig` command for more detailed DNS information:
$ dig example.com
; <<>> DiG 9.16.1-Ubuntu <<>> example.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 40555
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 65494
;; QUESTION SECTION:
;example.com. IN A
;; ANSWER SECTION:
example.com. 86400 IN A 93.184.216.34
;; Query time: 52 msec
;; SERVER: 127.0.0.53#53(127.0.0.53)
;; WHEN: Sat Mar 05 10:45:30 UTC 2023
;; MSG SIZE rcvd: 56
If `dig` isn't installed, you can add it. Not sure how to do that? Review the second installment of our TTY post, System Updates and Package Management: Keeping Your System Safe.
Understanding Network Ports and Services
Services on your computer listen on specific network ports. These numbered endpoints help identify a particular service. For example:
- Port 22: SSH (Secure Shell)
- Port 80: HTTP (web traffic)
- Port 443: HTTPS (secure web traffic)
To see which ports are open and listening on your system:
$ sudo ss -tulpn
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
udp UNCONN 0 0 127.0.0.53%lo:53 0.0.0.0:* users:(("systemd-resolve",pid=571,fd=12))
udp UNCONN 0 0 0.0.0.0:68 0.0.0.0:* users:(("dhclient",pid=600,fd=6))
tcp LISTEN 0 128 127.0.0.53%lo:53 0.0.0.0:* users:(("systemd-resolve",pid=571,fd=13))
tcp LISTEN 0 128 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=950,fd=3))
tcp LISTEN 0 128 127.0.0.1:631 0.0.0.0:* users:(("cupsd",pid=696,fd=7))
tcp LISTEN 0 128 [::]:22 [::]:* users:(("sshd",pid=950,fd=4))
tcp LISTEN 0 128 [::1]:631 [::]:* users:(("cupsd",pid=696,fd=6))
The options mean:
- `t`: Show TCP ports
- `u`: Show UDP ports
- `l`: Show only listening ports
- `p`: Show the process using the port
- `n`: Show numerical addresses and ports
From a security perspective, every listening port is a potential entry point to your system. The fewer ports you have open, the smaller your attack surface.
For a more comprehensive port scan, you can use the `nmap` tool:
$ sudo apt install nmap# Install if needed
$ sudo nmap -sT -O localhost
Starting Nmap 7.80 ( https://nmap.org ) at 2023-03-05 10:50 UTC
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000097s latency).
Not shown: 998 closed ports
PORT STATE SERVICE
22/tcp open ssh
631/tcp open ipp
Device type: general purpose
Running: Linux 4.X|5.X
OS CPE: cpe:/o:linux:linux_kernel:4 cpe:/o:linux:linux_kernel:5
OS details: Linux 4.15 - 5.6
Network Distance: 0 hops
OS detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 1.73 seconds
This shows open ports and attempts to identify the operating system.
Use this tool responsibly: only on systems you own or have permission to scan.
Implementing a Basic Firewall
A firewall is your first line of defense against network-based attacks. Linux includes a powerful firewall called `iptables`, but for beginners, the `ufw` (Uncomplicated Firewall) makes configuration much easier.
First, install `ufw` if it's not already available:
$ sudo apt install ufw
Check the status:
$ sudo ufw status
Status: inactive
Before enabling the firewall, let's set up some basic rules to ensure we don't lock ourselves out:
$ sudo ufw allow ssh
$ sudo ufw allow 2222/tcp
$ sudo ufw allow http
$ sudo ufw allow https
Now enable the ufw firewall:
$ sudo ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup
Check the status again to see your rules:
$ sudo ufw status
Status: active
To Action From
-- ------ ----
22/tcp ALLOW Anywhere
80/tcp ALLOW Anywhere
443/tcp ALLOW Anywhere
22/tcp (v6) ALLOW Anywhere (v6)
80/tcp (v6) ALLOW Anywhere (v6)
443/tcp (v6) ALLOW Anywhere (v6)
By default, `ufw` blocks all incoming connections and allows all outgoing connections. This is a good starting point for most users.
To deny a specific port:
$ sudo ufw deny 23
To remove a rule:
$ sudo ufw delete allow 80/tcp
For more complex rules, you can specify IP addresses or ranges:
$ sudo ufw allow from 192.168.1.5 to any port 22
$ sudo ufw allow from 192.168.1.0/24 to any port 3306
Securing SSH: Your Remote Access Connection
Secure Shell (SSH) is commonly used for remote access to Linux systems. Since it provides powerful access, securing it properly is essential:
1. Edit the SSH configuration file:
$ sudo nano /etc/ssh/sshd_config
2. Make these security-enhancing changes:
PermitRootLogin no
Protocol 2
AllowUsers sec406 lab
PasswordAuthentication no
ClientAliveInterval 300
ClientAliveCountMax 3
Port 2222
3. After making changes, restart the SSH service:
$ sudo systemctl restart ssh
4. If you changed the port, update your firewall:
$ sudo ufw allow 2222/tcp
$ sudo ufw delete allow 22/tcp
#### Setting Up SSH Key Authentication
Key-based authentication is much more secure than password only authentication. Here's how to set it up:
1. On your local machine, generate an SSH key pair:
$ ssh-keygen -t ed25519 -C "sec406@sans.org.local"
Follow the prompts and set a passphrase for additional security.
2. Copy the public key to your SSH server:
$ ssh-copy-id sec406@ssh-server
3. Now you can log in without a password. If you are prompted for a password, it is most likely the password placed on the SSH key itself and not password authentication to the target SSH server.
$ ssh sec406@ssh-server
4. Disable password authentication in the SSH config only AFTER key-based authentication is working, as shown above.
Monitoring Network Activity
Monitoring your network activity helps identify unusual behavior that might indicate a security issue.
#### Network Connection Monitoring
We've already seen `ss` for listing open ports. To monitor active connections:
$ ss -tanp
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=950,fd=3))
LISTEN 0 128 127.0.0.1:631 0.0.0.0:* users:(("cupsd",pid=696,fd=7))
ESTAB 0 0 192.168.1.100:22 192.168.1.5:49232 users:(("sshd",pid=2490,fd=4))
This shows established connections (ESTAB), their local and remote addresses, and the processes using them.
#### Using tcpdump for Packet Capture
For more detailed network monitoring, `tcpdump` allows you to perform full network packet captures and analyze network traffic:
$ sudo apt install tcpdump# Install if needed
$ sudo tcpdump -i eth0 -n tcp port 80
This captures TCP port 80 HTTP traffic on the eth0 interface. The `-n` option prevents DNS resolution, which speeds up the display.
For a more user-friendly view, try `wireshark`, a graphical packet analysis tool:
$ sudo apt install wireshark
$ sudo wireshark
#### Network Bandwidth Monitoring
To monitor real-time bandwidth usage by connection, try `iftop`. Press 'h' for help or 'q' to quit.
$ sudo apt install iftop
$ sudo iftop -i eth0
To show bandwidth usage grouped by process:
$ sudo apt install nethogs
$ sudo nethogs
Securing Network Services
Beyond SSH, you might run other network services that need protection.
#### Web Servers (Apache/Nginx)
If you're running a web server:
1. Keep it updated:
$ sudo apt update && sudo apt upgrade
2. Remove unnecessary modules from Apache with the `a2dismod` tool. For example:
$ sudo a2dismod status autoindex
$ sudo systemctl restart apache2
3. Use HTTPS with a free Let's Encrypt certificate:
$ sudo apt install certbot python3-certbot-apache
$ sudo certbot --apache
4. Set secure headers in your configuration.
#### Database Servers
For database servers like MySQL/MariaDB:
1. Ensure they only listen on localhost if external access is not necessary:
bind-address = 127.0.0.1
2. Use strong passwords and limit database user privileges:
$ sudo mysql_secure_installation
$ sudo mariadb-secure-installation
3. Consider using a firewall to restrict access to database ports (3306 for MySQL):
$ sudo ufw allow from 192.168.1.5 to any port 3306
Network Threat Detection
Simple tools can help detect potential network-based threats.
#### Using fail2ban to Block Brute Force Attacks
`fail2ban` monitors log files and temporarily bans IP addresses showing malicious activity:
$ sudo apt install fail2ban
Create a basic configuration file:
$ sudo nano /etc/fail2ban/jail.local
Add this content for SSH protection:
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 5
bantime = 3600
Restart the service:
$ sudo systemctl restart fail2ban
Now, any IP address that fails SSH authentication five times within the monitoring period will be banned for an hour. This is called a speed bump lockout and is a great protection to slow down automated attacker tools.
################## REPLACE WITH LYNIS? #########################
#### Using rkhunter for Rootkit Detection
Rootkits often establish network connections to command and control (C2) servers:
$ sudo apt install rkhunter
$ sudo rkhunter --update
$ sudo rkhunter --check
Review the results for suspicious network activity.
Securing DNS Settings
Domain Name System (DNS) translates domain names to IP addresses. Secure DNS settings can prevent various attacks:
1. Check your current DNS settings:
$ cat /etc/resolv.conf
2. Consider using secure DNS providers like Quad9 (9.9.9.9) or Cloudflare (1.1.1.1):
$ sudo nano /etc/resolv.conf
Add these lines:
nameserver 1.1.1.1
nameserver 1.0.0.1
For a more permanent solution, configure your network manager or DHCP client.
3. To verify DNS is working and secure:
$ dig +short @ns1-1.akamaitech.net whoami.akamai.net
This should return your public IP address.
Network Encryption with VPNs
A Virtual Private Network (VPN) encrypts your internet connection for better privacy and security, especially on public networks.
#### Using OpenVPN
1. Install the free OpenVPN client:
$ sudo apt install openvpn
2. Connect using a configuration file from your VPN provider:
$ sudo openvpn --config ~/openvpn-configuration-file.ovpn
#### Using WireGuard (a newer, simpler VPN)
1. Install WireGuard:
$ sudo apt install wireguard
2. Create a basic configuration:
$ sudo nano /etc/wireguard/wg0.conf
Add configuration details provided by your Wireguard VPN service.
3. Start the connection:
$ sudo wg-quick up wg0
4. Make it start automatically at boot:
$ sudo systemctl enable wg-quick@wg0
Network Hardening Checklist
Here's a checklist to secure your Linux system's network connections:
1. Know your network interfaces and open ports:
$ ip addr show
$ sudo ss -tulpn
2. Set up a basic firewall:
$ sudo ufw allow ssh
$ sudo ufw enable
3. Secure SSH:
- - Disable root login
- - Use key-based authentication
- - Change default port (optional)
4. Keep all network services updated:
$ sudo apt update && sudo apt upgrade
5. Disable or secure unnecessary services:
$ sudo systemctl disable <service_name> --now
$ sudo systemctl mask <service_name>
6. Monitor network traffic for unusual activity:
$ sudo tcpdump -i eth0 -n
7. Implement fail2ban to prevent brute force attacks:
$ sudo apt install fail2ban
8. Use secure DNS providers:
nameserver 1.1.1.1
nameserver 9.9.9.9
9. Consider using a VPN on public networks:
$ sudo apt install openvpn
10. Regularly check for unauthorized users logged in over the network:
$ last
$ who
Practical Exercise: Basic Network Security Setup
Let's combine what we've learned into a practical exercise to secure your system's network:
1. Check your current network status:
$ ip addr show
$ sudo ss -tulpn
2. Install and configure a basic firewall:
$ sudo apt install ufw
$ sudo ufw allow ssh
$ sudo ufw enable
$ sudo ufw status
3. Secure SSH (if you're using it):
$ sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
$ sudo nano /etc/ssh/sshd_config
Make these changes:
PermitRootLogin no
PasswordAuthentication no # Only if you've set up key authentication
Restart SSH:
$ sudo systemctl restart ssh
4. Install and set up fail2ban:
$ sudo apt install fail2ban
$ sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
$ sudo nano /etc/fail2ban/jail.local
Enable the SSH jail and restart:
$ sudo systemctl restart fail2ban
5. Check for unnecessary network services:
$ sudo systemctl list-units --type=service --state=running
Disable any services you don't need:
$ sudo systemctl disable --now <service_name>
6. Verify your DNS settings:
$ cat /etc/resolv.conf
Set secure DNS providers if needed.
7. Test your security:
$ sudo apt install nmap
$ sudo nmap -sT -O localhost
Check that only the necessary ports are open.
Understanding Wireless Network Security
If your Linux system uses wireless networking, additional security measures are needed:
1. Check your wireless interface:
$ iwconfig
2. Scan for available networks:
$ sudo iwlist wlan0 scan | grep ESSID
3. Connect to WPA2/WPA3 networks only (avoid WEP):
$ sudo nano /etc/netplan/01-network-manager-all.yaml
Configure with strong credentials.
4. Disable wireless when not needed:
$ sudo ip link set wlan0 down
Network Access Control with iptables
While `ufw` is simpler, understanding basic `iptables` commands gives you more control:
$ sudo iptables -L
$ sudo iptables -A INPUT -s 192.168.1.10 -j DROP
$ sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
$ sudo iptables-save > /etc/iptables/rules.v4
For more complex scenarios, consider learning more about `iptables` or its newer replacement, `nftables`.
Conclusion: Building Your Network Defense
Network security is a critical aspect of overall Linux security. By understanding your network connections, implementing a firewall, securing services, and monitoring for unusual activity, you've significantly improved your system's defense against network-based attacks.
Remember that network security is an ongoing process, not a one-time setup. Regular monitoring and updates are essential to maintaining your security posture.
Practice Questions
To reinforce your learning, try answering these questions:
1. What command shows which network ports are listening?
2. How do you allow SSH connections from 192.168.1.5 only?
3. Why is HHS key-based authentication more secure than password authentication?
4. What tool helps block IP addresses that show suspicious behavior, like multiple failed login attempts?
5. What protects your data on public Wi-Fi?
Want to know more? Check out the course preview of SEC406: Linux Security for InfoSec Professionals for a free hour of course content. Ready to take your Linux skills to the next level? For a limited time, take the SEC406 course for just $5,250!