Skip to content

Commit

Permalink
Merge: * dhcpd: check if subnet mask is correct
Browse files Browse the repository at this point in the history
Close #887

* commit '79a5c920a40180b7291d94535e50017d98eb3a63':
  * dhcpd: check if subnet mask is correct
  • Loading branch information
szolin committed Jul 17, 2019
2 parents 0fb42e5 + 79a5c92 commit 1973901
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
2 changes: 1 addition & 1 deletion dhcpd/dhcpd.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ func (s *Server) setConfig(config ServerConfig) error {
}

subnet, err := parseIPv4(config.SubnetMask)
if err != nil {
if err != nil || !isValidSubnetMask(subnet) {
return wrapErrPrint(err, "Failed to parse subnet mask %s", config.SubnetMask)
}

Expand Down
12 changes: 12 additions & 0 deletions dhcpd/dhcpd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,15 @@ func TestDB(t *testing.T) {

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})")
}
}
17 changes: 17 additions & 0 deletions dhcpd/helpers.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package dhcpd

import (
"encoding/binary"
"fmt"
"net"

Expand Down Expand Up @@ -65,3 +66,19 @@ func parseIPv4(text string) (net.IP, error) {
}
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
}

0 comments on commit 1973901

Please sign in to comment.