Skip to content

Commit 79a5c92

Browse files
committed
* dhcpd: check if subnet mask is correct
1 parent 0fb42e5 commit 79a5c92

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

dhcpd/dhcpd.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ func (s *Server) setConfig(config ServerConfig) error {
127127
}
128128

129129
subnet, err := parseIPv4(config.SubnetMask)
130-
if err != nil {
130+
if err != nil || !isValidSubnetMask(subnet) {
131131
return wrapErrPrint(err, "Failed to parse subnet mask %s", config.SubnetMask)
132132
}
133133

dhcpd/dhcpd_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,3 +197,15 @@ func TestDB(t *testing.T) {
197197

198198
os.Remove("leases.db")
199199
}
200+
201+
func TestIsValidSubnetMask(t *testing.T) {
202+
if !isValidSubnetMask([]byte{255, 255, 255, 0}) {
203+
t.Fatalf("isValidSubnetMask([]byte{255,255,255,0})")
204+
}
205+
if isValidSubnetMask([]byte{255, 255, 253, 0}) {
206+
t.Fatalf("isValidSubnetMask([]byte{255,255,253,0})")
207+
}
208+
if isValidSubnetMask([]byte{0, 255, 255, 255}) {
209+
t.Fatalf("isValidSubnetMask([]byte{255,255,253,0})")
210+
}
211+
}

dhcpd/helpers.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package dhcpd
22

33
import (
4+
"encoding/binary"
45
"fmt"
56
"net"
67

@@ -65,3 +66,19 @@ func parseIPv4(text string) (net.IP, error) {
6566
}
6667
return result.To4(), nil
6768
}
69+
70+
// Return TRUE if subnet mask is correct (e.g. 255.255.255.0)
71+
func isValidSubnetMask(mask net.IP) bool {
72+
var n uint32
73+
n = binary.BigEndian.Uint32(mask)
74+
for i := 0; i != 32; i++ {
75+
if n == 0 {
76+
break
77+
}
78+
if (n & 0x80000000) == 0 {
79+
return false
80+
}
81+
n <<= 1
82+
}
83+
return true
84+
}

0 commit comments

Comments
 (0)