Problem overview
Unexpected or unauthorized DNS server configurations can expose a network to outages, slow response times, or even security risks. This script tackles that challenge by ensuring each Linux device strictly adheres to a permitted DNS server list, reducing the risk of misconfiguration or malicious updates.
#!/bin/bash
# This resource is provided as a convenience for Level users. We cannot
# guarantee it will work in all environments. Please test before deploying
# to your production environment. We welcome contributions to our community
# library
# Level Library
# https://level.io/library/script-linux-monitor-dns-servers
# Expected DNS servers (comma-separated list)
allowed_dns_servers_string="{{cf_dns}}"
# Convert the comma-separated list into an array
IFS=',' read -r -a allowed_dns_servers <<< "$allowed_dns_servers_string"
# Function to check DNS servers
check_dns_servers() {
# Get current DNS servers from resolv.conf as fallback if nmcli is not installed
if command -v nmcli &> /dev/null; then
readarray -t current_dns_servers < <(nmcli dev show | grep 'IP4.DNS' | awk '{print $2}')
else
readarray -t current_dns_servers < <(grep "^nameserver" /etc/resolv.conf | awk '{print $2}')
fi
echo "Allowed DNS servers: ${allowed_dns_servers[*]}"
echo "Current DNS servers: ${current_dns_servers[*]}"
if [[ ${#current_dns_servers[@]} -eq 0 ]]; then
echo "ALERT: No DNS servers configured"
exit 1
fi
# Compare current DNS servers against allowed list
for dns in "${current_dns_servers[@]}"; do
if [[ ! " ${allowed_dns_servers[*]} " =~ " ${dns} " ]]; then
echo "ALERT: Not all DNS servers are in the allowed list."
exit 1
fi
done
echo "SUCCESS: DNS servers match the allowed list."
}
# Check DNS servers
check_dns_servers
This script checks the Linux system’s current DNS servers and compares them against a custom-defined “allowed” DNS list from Level’s cf_dns field. If any discrepancies are found, it issues an alert indicating that the servers are not compliant with the trusted configuration.
Because it verifies DNS at a system or root permission level, it can accurately monitor and detect any unauthorized changes in real time, providing a reliable safeguard against DNS misconfigurations.
Use cases
- Monitoring critical servers for DNS tampering
- Ensuring consistent DNS policies across diverse Linux environments
- Quickly detecting accidental DNS changes that might cause service disruptions
- Pairing with remediation automations to automatically revert DNS settings
Recommendations
- Test in a staging or test environment before live deployment
- Create a script-based monitor in Level to trigger this script on demand whenever DNS changes are suspected
- Use a custom automation in Level with a scheduled trigger for proactive checks
- Confirm nmcli is installed and functional on each target system