Merge pull request #3489 from pi-hole/ip_validation

Improve IP validation function
This commit is contained in:
DL6ER 2020-06-21 21:56:30 +02:00 committed by GitHub
commit bf392d7a60
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 19 deletions

View file

@ -10,18 +10,22 @@
# This file is copyright under the latest version of the EUPL.
# Please see LICENSE file for your rights under this license.
readonly setupVars="/etc/pihole/setupVars.conf"
readonly dnsmasqconfig="/etc/dnsmasq.d/01-pihole.conf"
readonly dhcpconfig="/etc/dnsmasq.d/02-pihole-dhcp.conf"
readonly FTLconf="/etc/pihole/pihole-FTL.conf"
# 03 -> wildcards
readonly dhcpstaticconfig="/etc/dnsmasq.d/04-pihole-static-dhcp.conf"
readonly PI_HOLE_BIN_DIR="/usr/local/bin"
readonly dnscustomfile="/etc/pihole/custom.list"
readonly dnscustomcnamefile="/etc/dnsmasq.d/05-pihole-custom-cname.conf"
readonly gravityDBfile="/etc/pihole/gravity.db"
# Source install script for ${setupVars}, ${PI_HOLE_BIN_DIR} and valid_ip()
readonly PI_HOLE_FILES_DIR="/etc/.pihole"
# shellcheck disable=SC2034 # used in basic-install
PH_TEST="true"
source "${PI_HOLE_FILES_DIR}/automated install/basic-install.sh"
coltable="/opt/pihole/COL_TABLE"
if [[ -f ${coltable} ]]; then
source ${coltable}
@ -227,7 +231,15 @@ SetDNSServers() {
for index in "${!array[@]}"
do
# Replace possible "\#" by "#". This fixes AdminLTE#1427
add_setting "PIHOLE_DNS_$((index+1))" "${array[index]//\\#/#}"
local ip
ip="${array[index]//\\#/#}"
if valid_ip "${ip}" ; then
add_setting "PIHOLE_DNS_$((index+1))" "${ip}"
else
echo -e " ${CROSS} Invalid IP has been passed"
exit 1
fi
done
if [[ "${args[3]}" == "domain-needed" ]]; then

View file

@ -1017,22 +1017,16 @@ valid_ip() {
local ip=${1}
local stat=1
# If the IP matches the format xxx.xxx.xxx.xxx,
if [[ "${ip}" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
# Save the old Internal Field Separator in a variable
OIFS=$IFS
# and set the new one to a dot (period)
IFS='.'
# Put the IP into an array
read -r -a ip <<< "${ip}"
# Restore the IFS to what it was
IFS=${OIFS}
## Evaluate each octet by checking if it's less than or equal to 255 (the max for each octet)
[[ "${ip[0]}" -le 255 && "${ip[1]}" -le 255 \
&& "${ip[2]}" -le 255 && "${ip[3]}" -le 255 ]]
# Save the exit code
stat=$?
fi
# One IPv4 element is 8bit: 0 - 256
local ipv4elem="(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)";
# optional port number starting '#' with range of 1-65536
local portelem="(#([1-9]|[1-8][0-9]|9[0-9]|[1-8][0-9]{2}|9[0-8][0-9]|99[0-9]|[1-8][0-9]{3}|9[0-8][0-9]{2}|99[0-8][0-9]|999[0-9]|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-6]))?"
# build a full regex string from the above parts
local regex="^${ipv4elem}\.${ipv4elem}\.${ipv4elem}\.${ipv4elem}${portelem}$"
[[ $ip =~ ${regex} ]]
stat=$?
# Return the exit code
return "${stat}"
}