Skip to content

Commit

Permalink
parser.go: ipv6 address without network mask support
Browse files Browse the repository at this point in the history
Before we would always add a `/32` to ip addresses without a `/`. This
would be wrong for ipv6 addresses. They have 128 network masks.

Signed-off-by: leonnicolas <[email protected]>
  • Loading branch information
leonnicolas committed Apr 1, 2024
1 parent a2ed1b3 commit 8d80d70
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
11 changes: 9 additions & 2 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"io"
"net"
"net/netip"

Check failure on line 8 in parser.go

View workflow job for this annotation

GitHub Actions / test

package net/netip is not in GOROOT (/opt/hostedtoolcache/go/1.16.15/x64/src/net/netip)
"reflect"
"regexp"
"strconv"
Expand Down Expand Up @@ -123,7 +124,7 @@ func (r Rule) String() (s string) {

// Spec returns the rule specifications of the rule.
// The rulespec does not contain the chain name.
// Different rule specs can descibe the same rule, so
// Different rule specs can describe the same rule, so
// don't use the rulespec to compare rules.
// The rule spec can be used to append, insert or delete
// rules with coreos' go-iptables module.
Expand Down Expand Up @@ -216,7 +217,13 @@ func (d *DNSOrIP) Set(s string) error {
sn := s
// TODO: this can probably be done in a nicer way.
if !strings.Contains(sn, "/") {
sn = sn + "/32"
if addr, err := netip.ParseAddr(sn); err == nil {
if addr.Is4() {
sn = sn + "/32"
} else {
sn = sn + "/128"
}
}
}
if _, ipnet, err := net.ParseCIDR(sn); err == nil {
d.iP = *ipnet
Expand Down
34 changes: 34 additions & 0 deletions parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package iptables_parser

import (
"errors"
"fmt"
"io"
"net"
"reflect"
Expand Down Expand Up @@ -87,6 +88,39 @@ func TestStringPair_Spec(t *testing.T) {
}
}

func TestDNSOrIP_Set(t *testing.T) {
for i, tc := range []struct {
in string
out []string
}{
{
in: "10.10.0.0/16",
out: []string{"-s", "10.10.0.0/16"},
},
{
in: "10.10.0.1",
out: []string{"-s", "10.10.0.1/32"},
},
{
in: "10::/64",
out: []string{"-s", "10::/64"},
},
{
in: "10::10",
out: []string{"-s", "10::10/128"},
},
} {
t.Run(fmt.Sprintf("test %d", i), func(t *testing.T) {
dnsOrIpPair := &DNSOrIPPair{}

dnsOrIpPair.Value.Set(tc.in)
if res := dnsOrIpPair.Spec("-s"); !reflect.DeepEqual(res, tc.out) {
t.Errorf("test %d:\n\texp=%q\n\tgot=%q\n", i, tc.out, res)
}
})
}
}

func TestFlag_String(t *testing.T) {
for i, tc := range []struct {
p Flag
Expand Down

0 comments on commit 8d80d70

Please sign in to comment.