Skip to content

Commit

Permalink
added ipv4 address octet range validation
Browse files Browse the repository at this point in the history
  • Loading branch information
lekhan05 committed Jun 28, 2021
1 parent 7c6f9b7 commit ddd0b2e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
20 changes: 16 additions & 4 deletions models/bannedips.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package models

import (
"fmt"
"strconv"
"strings"

Expand Down Expand Up @@ -59,11 +60,11 @@ func (t *ipv4AddressTrie) insertIpv4AddressToTrie(ipv4Address string) error {
addressIndex := 0
addressSegments := strings.Split(ipv4Address, ".")
for _, segment := range addressSegments {
octet, err := strconv.Atoi(segment)
curAddressOctet, err := getIpv4AddressOctet(segment)
if err != nil {
return err
}
curAddressOctet := byte(octet)

if cur.children[curAddressOctet] == nil {
addressIndex++
cur.children[curAddressOctet] = &ipv4AddressTrieNode{
Expand Down Expand Up @@ -99,15 +100,26 @@ func (t *ipv4AddressTrie) traverseAllNodesInTheIpv4Address(ipv4Address string) (
cur := t.root
addressSegments := strings.Split(ipv4Address, ".")
for _, segment := range addressSegments {
octet, err := strconv.Atoi(segment)
curAddressOctet, err := getIpv4AddressOctet(segment)
if err != nil {
return nil, err
}
curAddressOctet := byte(octet)

if cur.children[curAddressOctet] == nil {
return nil, nil
}
cur = cur.children[curAddressOctet]
}
return cur, nil
}

func getIpv4AddressOctet(addressSegment string) (byte, error) {
addressOctet, err := strconv.Atoi(addressSegment)
if err != nil {
return 0, err
}
if addressOctet < 0 || addressOctet > 255 {
return 0, fmt.Errorf("error ipv4 address octet %d exceeds expected range ", addressOctet)
}
return byte(addressOctet), nil
}
19 changes: 19 additions & 0 deletions tests/ipfilter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,25 @@ func Test_Trie_Based_IpAddress_Search_For_EmptyIpAddress(t *testing.T) {
}
}

func Test_Trie_Based_IpAddress_Search_For_Invalid_Address_Octet(t *testing.T) {

ipList1 := []string{"192.555.0.1"}
domainId1 := 1
bannedIpsByDomain := map[int][]string{
domainId1: ipList1,
}

bannedIpv4AddressTriesPerDomain, err := models.CreateIpv4BannedAddressTriePerDomain(bannedIpsByDomain)
if err != nil {
t.Logf("Failed to create trie model for banned ipv4 addresses as expected : %s", err.Error())
}

trieToBeSearched := bannedIpv4AddressTriesPerDomain[domainId1]
if trieToBeSearched == nil {
t.Logf("Failed to create trie for the specified domain %d as expected", domainId1)
}
}

func Tes_Trie_Based_IpAddress_Search_For_InvalidInput(t *testing.T) {

ipList1 := []string{"axyz"}
Expand Down

0 comments on commit ddd0b2e

Please sign in to comment.