Merge: * dhcpd: check if subnet mask is correct

Close #887

* commit '79a5c920a40180b7291d94535e50017d98eb3a63':
  * dhcpd: check if subnet mask is correct
This commit is contained in:
Simon Zolin 2019-07-17 12:45:45 +03:00
commit 1973901802
3 changed files with 30 additions and 1 deletions

View File

@ -127,7 +127,7 @@ func (s *Server) setConfig(config ServerConfig) error {
} }
subnet, err := parseIPv4(config.SubnetMask) subnet, err := parseIPv4(config.SubnetMask)
if err != nil { if err != nil || !isValidSubnetMask(subnet) {
return wrapErrPrint(err, "Failed to parse subnet mask %s", config.SubnetMask) return wrapErrPrint(err, "Failed to parse subnet mask %s", config.SubnetMask)
} }

View File

@ -197,3 +197,15 @@ func TestDB(t *testing.T) {
os.Remove("leases.db") os.Remove("leases.db")
} }
func TestIsValidSubnetMask(t *testing.T) {
if !isValidSubnetMask([]byte{255, 255, 255, 0}) {
t.Fatalf("isValidSubnetMask([]byte{255,255,255,0})")
}
if isValidSubnetMask([]byte{255, 255, 253, 0}) {
t.Fatalf("isValidSubnetMask([]byte{255,255,253,0})")
}
if isValidSubnetMask([]byte{0, 255, 255, 255}) {
t.Fatalf("isValidSubnetMask([]byte{255,255,253,0})")
}
}

View File

@ -1,6 +1,7 @@
package dhcpd package dhcpd
import ( import (
"encoding/binary"
"fmt" "fmt"
"net" "net"
@ -65,3 +66,19 @@ func parseIPv4(text string) (net.IP, error) {
} }
return result.To4(), nil return result.To4(), nil
} }
// Return TRUE if subnet mask is correct (e.g. 255.255.255.0)
func isValidSubnetMask(mask net.IP) bool {
var n uint32
n = binary.BigEndian.Uint32(mask)
for i := 0; i != 32; i++ {
if n == 0 {
break
}
if (n & 0x80000000) == 0 {
return false
}
n <<= 1
}
return true
}