bashadvanced83 snippets

Linux Networking: The Hacker Guide

Feel like Mr. Robot. Network commands to discover IPs, open ports and diagnose connections like a CyberSec professional.

Sections6
1

🔍 Basic Diagnostics

15 snippets

Fundamental commands for diagnosing connectivity issues, checking network interface configurations, and resolving DNS-related questions. Essential for quick identification of network infrastructure failures.

Test Connectivity with Ping

Tests network connectivity and the accessibility of a specific host by sending ICMP ECHO_REQUEST packets. The `-c 4` flag limits sending to 4 packets, providing a quick test without overloading the network.

bash
ping -c 4 google.com

Fast Ping with Reduced Interval

Performs a connectivity test with a reduced interval between packets. The `-i 0.5` flag sets an interval of 0.5 seconds between each ping, useful for quick latency tests and to check real-time response.

bash
ping -i 0.5 192.168.1.1

Trace Route to Destination (Traceroute)

Displays the route that IP packets take to reach a destination, showing each router (hop) along the path. Helps identify bottlenecks, excessive latency, or failures at specific points in the network route.

bash
traceroute google.com

Continuous Traceroute (MTR)

Combines the functionalities of `ping` and `traceroute` into a continuous tool. It displays latency and packet loss statistics for each hop in real-time, ideal for prolonged monitoring and identifying intermittent issues.

bash
mtr google.com

Display ARP Table

Displays the system's ARP (Address Resolution Protocol) table, which maps IP addresses to MAC (physical) addresses on the local network. The `-a` flag shows all entries, useful for debugging layer 2 address resolution issues.

bash
arp -a

Display Interfaces and IP Addresses

Displays detailed information about all network interfaces configured on the system, including IP addresses, subnet masks, interface state (UP/DOWN), and scope. It is the modern tool to replace `ifconfig`.

bash
ip addr show

Activate Network Interface

Activates the `eth0` network interface. Replace `eth0` with the desired interface name (e.g., `enp0s3`, `wlan0`). Use `ip link set eth0 down` to deactivate it. Requires root privileges.

bash
ip link set eth0 up

Interface Details with Ethtool

Displays and allows configuration of low-level parameters for the `eth0` network interface, such as speed, duplex mode, auto-negotiation, and hardware statistics. Useful for checking the physical connection state.

bash
ethtool eth0

Network Interface Statistics

Shows concise traffic statistics (bytes sent/received, errors, dropped packets) for the `eth0` network interface. The `-s` flag displays a summary of packet and error statistics.

bash
ip -s link show eth0

List Open Ports (Sockets)

Displays information about open network sockets on the system. The flags `-t` (TCP), `-u` (UDP), `-l` (listening sockets), and `-n` (numeric, no name resolution) are commonly used to list ports awaiting connections.

bash
ss -tuln

DNS Query with Nslookup

Queries DNS servers for domain name information, such as IP addresses (A records) and other record types. It's an older tool but still useful for basic and quick DNS queries.

bash
nslookup google.com

Complete DNS Query with Dig

A more powerful and flexible tool for DNS queries. `ANY` requests all available DNS record types for the specified domain, including A, MX, NS, SOA, etc. Ideal for advanced DNS debugging.

bash
dig google.com ANY

Trace DNS Resolution Path

Traces the DNS resolution path for a domain, showing the root, TLD, and authoritative DNS servers queried at each step. Useful for understanding how a name is resolved globally and identifying delegation issues.

bash
dig +trace google.com

Query MX Records with Host

Queries DNS servers for information about a domain. The `-t mx` flag specifically requests MX (Mail Exchanger) records, which indicate the email servers responsible for receiving messages for the domain.

bash
host -t mx google.com

Systemd-Resolved DNS Status

Displays the current status of the system's DNS resolver managed by `systemd-resolved`, including configured DNS servers, interfaces, and search domains. Relevant on systems using `systemd` for network management.

bash
systemd-resolve --status
2

📊 Traffic Analysis

16 snippets

Commands for capturing, filtering, and analyzing network packets, plus real-time traffic monitoring to identify patterns, anomalies, and performance issues.

Capturar Tráfego na Interface (tcpdump)

Captura e exibe o tráfego de rede passando pela interface `eth0` em tempo real. Requer privilégios de root. Use `Ctrl+C` para parar a captura. É uma ferramenta fundamental para inspeção de pacotes.

bash
sudo tcpdump -i eth0

Capture Traffic without DNS Resolution

Captures traffic on the `eth0` interface without resolving IP addresses to hostnames or port numbers to service names. The `-n` flag speeds up display and is useful in environments without DNS access or to focus only on IPs.

bash
sudo tcpdump -i eth0 -n

Filter Traffic by Port

Filters traffic on the `eth0` interface to show only packets using port 80 (usually HTTP). The filter can be applied to source or destination ports, facilitating the analysis of specific services.

bash
sudo tcpdump -i eth0 port 80

Filter Traffic by Specific Host

Captures only traffic originating from or destined for the IP address `192.168.1.100` on the `eth0` interface. Essential for isolating traffic from a single device or server.

bash
sudo tcpdump -i eth0 host 192.168.1.100

Save Capture to PCAP File

Captures traffic from the `eth0` interface and saves the raw packets to a file named `capture.pcap`. This file can later be analyzed with `tcpdump` or graphical tools like `Wireshark`.

bash
sudo tcpdump -i eth0 -w capture.pcap

Read PCAP File with ASCII Content

Reads and displays the content of a previously saved capture file (`.pcap`). The `-A` flag attempts to print each packet (excluding the link-layer header) in ASCII, useful for inspecting text data within packets.

bash
sudo tcpdump -r capture.pcap -A

Real-time Capture with Tshark

Starts real-time packet capture on the `eth0` interface using `tshark`, the command-line version of Wireshark. Offers more advanced filtering and analysis capabilities than `tcpdump`.

bash
tshark -i eth0

Analyze PCAP File with Tshark

Reads and displays the content of a capture file (`.pcap`) using `tshark`. Allows applying display filters and performing detailed analysis of recorded packets.

bash
tshark -r capture.pcap

Filter HTTP Requests in PCAP

Analyzes a `.pcap` file and displays only packets matching the Wireshark display filter `http.request`, showing captured HTTP requests in detail.

bash
tshark -r capture.pcap -Y "http.request"

Extract Source/Destination IPs from PCAP

Extracts and displays specific packet fields from a `.pcap` file. `-T fields` specifies the output format as fields, and `-e` lists the fields to be extracted (in this case, source and destination IP addresses).

bash
tshark -r capture.pcap -T fields -e ip.src -e ip.dst

IP Conversation Statistics with Tshark

Analyzes a `.pcap` file and generates IP conversation statistics. `-q` suppresses packet output, and `-z conv,ip` enables the IP conversation statistician, showing data and packet volume between IP pairs.

bash
tshark -r capture.pcap -q -z conv,ip

Monitor Real-time Traffic (iftop)

Displays real-time bandwidth usage for the `eth0` interface, showing connections consuming the most bandwidth, ordered by volume. Requires `sudo` and `iftop` installation.

bash
iftop -i eth0

Monitor Traffic by Process (nethogs)

Shows bandwidth consumption per process on the `eth0` interface. Useful for identifying which applications are generating the most network traffic in real-time. Requires `sudo` and `nethogs` installation.

bash
nethogs eth0

Graphical Bandwidth Monitor (bmon)

A bandwidth and network statistics monitor that offers a graphical and detailed view of traffic on all interfaces. Provides an interactive interface for visualizing network metrics. Requires `bmon` installation.

bash
bmon

Detailed Network Statistics (iptraf-ng)

An interactive network monitoring tool that collects and displays a variety of statistics, including IP, TCP, UDP, ICMP, Ethernet information, and more. Useful for in-depth traffic analysis. Requires `iptraf-ng` installation.

bash
iptraf-ng

Network Statistics with Sar

Collects, reports, or saves system activity information. `-n DEV` specifies the network statistics report per device, `1` is the interval in seconds, and `5` is the number of samples to collect. Part of the `sysstat` package.

bash
sar -n DEV 1 5
3

🔒 Firewall and Security

15 snippets

Commands for configuring and managing firewalls (UFW, iptables) and protecting the system against attacks with tools like Fail2Ban.

Enable UFW Firewall

Enables the UFW (Uncomplicated Firewall) firewall. Make sure to have SSH access rules configured before enabling it on remote servers to avoid blocking access. Requires root privileges.

bash
sudo ufw enable

Detailed UFW Status

Displays the current UFW status, showing if it's active, configured rules, default profile, and rule log. The `verbose` flag provides more details about rules and traffic.

bash
sudo ufw status verbose

Allow SSH Connection (UFW)

Creates a rule to allow TCP connections on port 22 (SSH). It is crucial to allow SSH before enabling the firewall on remote servers to maintain administrative access.

bash
sudo ufw allow 22/tcp

Block Specific IP (UFW)

Creates a rule to block all incoming connections from the IP address `192.168.1.100`. Useful for mitigating attacks or blocking unwanted access from a known IP.

bash
sudo ufw deny from 192.168.1.100

Remove UFW Rule

Removes an existing rule that allows traffic on port 80. To remove a specific rule, you can use `ufw status numbered` to see the rules with numbers and then `ufw delete <number>`.

bash
sudo ufw delete allow 80

Reload UFW Rules

Reloads UFW rules after modifications, applying the new configurations without the need to restart the service. This ensures that changes take effect immediately.

bash
sudo ufw reload

List Iptables Rules

Lists all `iptables` firewall rules. `-L` lists the rules, `-n` displays addresses and ports numerically (without DNS resolution for faster speed), and `-v` shows details like packet/byte counters.

bash
sudo iptables -L -n -v

Allow Specific Port (Iptables)

Adds (`-A`) a rule to the `INPUT` chain to allow (`-j ACCEPT`) TCP connections (`-p tcp`) destined for port 22 (`--dport 22`). This rule allows incoming SSH traffic.

bash
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

Block Subnet (Iptables)

Adds a rule to the `INPUT` chain to drop (`-j DROP`) all packets originating from the `192.168.1.0/24` subnet. Useful for isolating or blocking traffic from a specific network.

bash
sudo iptables -A INPUT -s 192.168.1.0/24 -j DROP

Clear All Iptables Rules

Clears (`-F`, flush) all rules from all `iptables` chains. Use with extreme caution, as this can open your system to all traffic and compromise security.

bash
sudo iptables -F

Save Iptables Rules

Saves the current `iptables` rules to a file. In many systems, this file is used to restore rules on system startup, ensuring firewall configuration persistence.

bash
sudo iptables-save > /etc/iptables/rules.v4

Fail2Ban General Status

Displays the general status of the Fail2Ban service, including which "jails" (monitored services, such as SSH, Apache) are active and the total number of banned IPs.

bash
sudo fail2ban-client status

Specific SSHd Jail Status (Fail2Ban)

Shows the specific status of the `sshd` "jail", including how many IPs have been banned and which IPs are currently banned for the SSH service. Useful for monitoring brute-force attempts.

bash
sudo fail2ban-client status sshd

Unban IP with Fail2Ban

Manually unbans an IP address (`192.168.1.100`) from the `sshd` "jail". Useful if a legitimate IP was accidentally blocked or if access needs to be quickly restored.

bash
sudo fail2ban-client set sshd unbanip 192.168.1.100

Reload Fail2Ban Configuration

Reloads the Fail2Ban configuration, applying any changes made to configuration files (e.g., `jail.local`) without needing to restart the full service.

bash
sudo fail2ban-client reload
4

⚖️ Load Balancing

12 snippets

Commands for managing and monitoring load balancing solutions like HAProxy, Nginx, and IPVS, ensuring efficient traffic distribution and high availability.

Validate HAProxy Configuration

Validates the syntax of the HAProxy configuration file (`/etc/haproxy/haproxy.cfg`) without starting or restarting the service. Essential to prevent errors before applying changes in production.

bash
haproxy -f /etc/haproxy/haproxy.cfg -c

Restart HAProxy Service

Restarts the HAProxy service. This applies new configurations and may cause a brief service interruption, depending on the high availability configuration.

bash
sudo systemctl restart haproxy

HAProxy Information via Socket

Displays general information about the HAProxy runtime state, such as version, uptime, number of processes, and session statistics. Requires `socat` and access to the HAProxy control socket.

bash
echo "show info" | socat stdio /var/run/haproxy.sock

HAProxy Statistics via Socket

Displays detailed statistics about frontends, backends, and servers, including active connections, sessions, request rates, and errors. Useful for performance and server health monitoring.

bash
echo "show stat" | socat stdio /var/run/haproxy.sock

Test Nginx Configuration

Tests the syntax of the Nginx configuration file. It is crucial to run this command before reloading or restarting Nginx to ensure there are no configuration errors that could bring down the service.

bash
nginx -t

Reload Nginx Configuration

Reloads the Nginx configuration without dropping existing connections. It is the preferred way to apply configuration changes to a production Nginx server, ensuring zero downtime.

bash
sudo nginx -s reload

Nginx Load Balancer Status

Makes an HTTP HEAD request to the Nginx status URL (if configured), displaying metrics such as active connections, accepted connections, and handled connections. Requires the `ngx_http_stub_status_module` module.

bash
curl -I http://localhost/nginx_status

Monitor Nginx Access Logs

Monitors the Nginx access log file in real-time, showing HTTP requests as they arrive at the server. Useful for debugging, traffic observation, and identifying access patterns.

bash
tail -f /var/log/nginx/access.log

List IPVS Rules (Linux Virtual Server)

Lists all virtual service and real server rules configured in IPVS (Linux Virtual Server). `-n` prevents name resolution for IPs and ports, making the output faster and more concise.

bash
sudo ipvsadm -L -n

Add IPVS Virtual Service

Adds (`-A`) a TCP virtual service (`-t`) at address `192.168.1.100` on port 80, using the `rr` (round-robin) scheduling algorithm to distribute the load among real servers.

bash
sudo ipvsadm -A -t 192.168.1.100:80 -s rr

Add Real Server to IPVS

Adds (`-a`) a real server (`-r`) with IP `192.168.1.101` and port 80 to the virtual service `192.168.1.100:80`, using the `masquerading` (`-m`) routing method.

bash
sudo ipvsadm -a -t 192.168.1.100:80 -r 192.168.1.101:80 -m

IPVS Connection Rate

Lists IPVS rules, including connection and traffic rates for each virtual service and real server, providing real-time performance and usage metrics.

bash
sudo ipvsadm -L --rate
5

🔐 VPN

12 snippets

Commands for configuring, managing, and monitoring VPN connections using OpenVPN, WireGuard, and IPSec (strongSwan) for secure communications.

OpenVPN Service Status

Checks the status of the OpenVPN service. On `systemd`-based systems, it shows whether the OpenVPN server or client is running, its uptime, and recent activity. Useful for debugging.

bash
sudo systemctl status openvpn

Connect OpenVPN Client

Initiates an OpenVPN connection as a client, using the `client.ovpn` configuration file. This command is executed on the client side to establish the secure VPN tunnel.

bash
openvpn --config client.ovpn

Start OpenVPN Server in Daemon

Starts the OpenVPN server in the background (`--daemon`), using the `server.conf` configuration file. Requires root privileges. The server listens for client connections.

bash
sudo openvpn --config server.conf --daemon

Monitor OpenVPN Logs

Monitors the OpenVPN log file in real-time, which records connection events, authentication, errors, and disconnections. Essential for VPN debugging and auditing.

bash
tail -f /var/log/openvpn.log

Generate WireGuard Keys

Generates a pair of cryptographic keys (private and public) for WireGuard. The private key is saved to `private.key` and the public key to `public.key`. Essential for peer configuration.

bash
wg genkey | tee private.key | wg pubkey > public.key

Activate WireGuard Interface

Activates the WireGuard interface `wg0` (or the configured name), establishing the VPN connection according to the configuration in `/etc/wireguard/wg0.conf`. Requires root privileges.

bash
sudo wg-quick up wg0

WireGuard VPN Status

Displays the current status of all active WireGuard interfaces, including public keys, connected peers, IP addresses, and data traffic. Useful for checking connectivity and configuration.

bash
sudo wg show

Deactivate WireGuard Interface

Deactivates the WireGuard interface `wg0`, terminating the VPN connection and removing associated network configurations. Requires root privileges.

bash
sudo wg-quick down wg0

IPSec Status (strongSwan)

Displays the general status of the strongSwan IPSec service, including information about configured connections, established tunnels, peers, and traffic statistics. Useful for monitoring and debugging.

bash
sudo ipsec status

Start IPSec Connection

Starts a specific IPSec connection, identified by `connection-name`, as configured in strongSwan files (e.g., `ipsec.conf`). Establishes the VPN tunnel.

bash
sudo ipsec up connection-name

Terminate IPSec Connection

Terminates a specific IPSec connection, releasing associated resources and the VPN tunnel. Disconnects the client or server from the VPN.

bash
sudo ipsec down connection-name

Reload IPSec Configuration

Reloads the strongSwan configuration without restarting the daemon, applying any changes made to the IPSec configuration files. Ensures new rules take effect.

bash
sudo ipsec reload
6

⚡ Performance and Optimization

13 snippets

Commands for tuning kernel network parameters, configuring Quality of Service (QoS), and running performance tests to optimize throughput and latency.

Display Maximum Receive Buffer

Displays the maximum socket receive buffer value in bytes for all connections. Adjusting this value can improve performance on high-bandwidth and high-latency networks, allowing the system to store more data before processing it.

bash
sysctl net.core.rmem_max

Display Maximum Send Buffer

Displays the maximum socket send buffer value in bytes for all connections. Similar to `rmem_max`, its adjustment can optimize send throughput, especially in high-demand scenarios.

bash
sysctl net.core.wmem_max

TCP Congestion Control Algorithm

Displays the TCP congestion control algorithm currently in use (e.g., `cubic`, `bbr`). The choice of algorithm can significantly impact network performance, especially on links with packet loss or high latency.

bash
sysctl net.ipv4.tcp_congestion_control

TCP Listen Queue Size

Displays the maximum listen queue size for TCP sockets. A low value can lead to refused connections (connection refused) on servers with high request volumes, as new connections cannot be queued.

bash
sysctl net.core.somaxconn

Display Traffic Queue (Qdisc)

Displays the queueing disciplines (qdisc) configured for the `eth0` network interface. Qdiscs are used to manage how packets are queued and transmitted, forming the basis of QoS.

bash
tc qdisc show dev eth0

Create HTB Qdisc for QoS

Creates a Hierarchical Token Bucket (HTB) queueing discipline as `root` on the `eth0` interface, with handle `1:` and default class `30`. HTB is used for hierarchical bandwidth control, allowing prioritization and limitation.

bash
sudo tc qdisc add dev eth0 root handle 1: htb default 30

Limit Bandwidth with HTB Class

Adds an HTB class (`classid 1:1`) under the parent qdisc `1:` on the `eth0` interface, limiting the egress rate to 1 Megabit per second (`rate 1mbit`). This allows controlling the available bandwidth for specific traffic.

bash
sudo tc class add dev eth0 parent 1: classid 1:1 htb rate 1mbit

Filter Traffic by Port for QoS

Adds a filter to direct destination IP traffic on port 80 (`dport 80`) to class `1:10` (which must be previously defined with a rate or priority). `u32` is a powerful classifier for complex filtering rules.

bash
sudo tc filter add dev eth0 protocol ip parent 1:0 prio 1 u32 match ip dport 80 0xffff flowid 1:10

Remove QoS Configuration

Removes the root queuing discipline (`root`) from the `eth0` interface, disabling all QoS rules configured for that interface. This restores the default queuing behavior.

bash
sudo tc qdisc del dev eth0 root

Start Iperf3 Server

Starts the `iperf3` server, which awaits client connections to perform network throughput tests. The server listens on the default port 5201. Essential for measuring bandwidth between two points.

bash
iperf3 -s

Throughput Test with Iperf3

Starts a throughput test as an `iperf3` client, connecting to `server_ip` and running the test for 30 seconds (`-t 30`). Displays the average bandwidth achieved during the period.

bash
iperf3 -c server_ip -t 30

Latency Test with Ping (Summary)

Performs 100 pings with a 0.1-second interval to `server_ip` and displays only the last line of output, which contains the latency statistics summary (min/avg/max/mdev). Useful for quick latency tests.

bash
ping -c 100 -i 0.1 server_ip | tail -1

Testar Porta Aberta com Netcat

Testa se uma porta específica (neste caso, 80) está aberta e acessível em um `server_ip`. A flag `-z` faz um scan sem enviar dados, e `-v` fornece saída verbosa, indicando sucesso ou falha na conexão.

bash
netcat -z -v server_ip 80

Get the latest articles delivered to your inbox.

Follow Us: