summaryrefslogtreecommitdiff
path: root/src/validators/ipv4-range-mask
blob: 7bb4539af46e9d38352f141ba2c4f42a10087eb2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/bin/bash

# snippet from https://stackoverflow.com/questions/10768160/ip-address-converter
ip2dec () {
    local a b c d ip=$@
    IFS=. read -r a b c d <<< "$ip"
    printf '%d\n' "$((a * 256 ** 3 + b * 256 ** 2 + c * 256 + d))"
}

error_exit() {
  echo "Error: $1 is not a valid IPv4 address range or these IPs are not under /$2"
  exit 1
}

# Check if address range is under the same netmask
# -m - mask
# -r - IP range in format x.x.x.x-y.y.y.y
while getopts m:r: flag
do
    case "${flag}" in
        m) mask=${OPTARG};;
        r) range=${OPTARG}
    esac
done
if [[ "${range}" =~ "-" ]]&&[[ ! -z ${mask} ]]; then
  # This only works with real bash (<<<) - split IP addresses into array with
  # hyphen as delimiter
  readarray -d - -t strarr <<< ${range}

  ipaddrcheck --is-ipv4-single ${strarr[0]}
  if [ $? -gt 0 ]; then
    error_exit ${range} ${mask}
  fi

  ipaddrcheck --is-ipv4-single ${strarr[1]}
  if [ $? -gt 0 ]; then
    error_exit ${range} ${mask}
  fi

  ${vyos_validators_dir}/numeric --range 0-32 ${mask} > /dev/null
   if [ $? -ne 0 ]; then
     error_exit ${range} ${mask}
   fi

  is_in_24=$( grepcidr ${strarr[0]}"/"${mask} <(echo ${strarr[1]}) )
  if [ -z $is_in_24 ]; then
    error_exit ${range} ${mask}
  fi

  start=$(ip2dec ${strarr[0]})
  stop=$(ip2dec ${strarr[1]})
  if [ $start -ge $stop ]; then
    error_exit ${range} ${mask}
  fi

  exit 0
fi

error_exit ${range} ${mask}