123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437 |
- package iptables
- import (
- "bytes"
- "fmt"
- "io"
- "net"
- "os/exec"
- "regexp"
- "strconv"
- "strings"
- "syscall"
- )
- type Error struct {
- exec.ExitError
- cmd exec.Cmd
- msg string
- }
- func (e *Error) ExitStatus() int {
- return e.Sys().(syscall.WaitStatus).ExitStatus()
- }
- func (e *Error) Error() string {
- return fmt.Sprintf("running %v: exit status %v: %v", e.cmd.Args, e.ExitStatus(), e.msg)
- }
- type Protocol byte
- const (
- ProtocolIPv4 Protocol = iota
- ProtocolIPv6
- )
- type IPTables struct {
- path string
- proto Protocol
- hasCheck bool
- hasWait bool
- }
- func New() (*IPTables, error) {
- return NewWithProtocol(ProtocolIPv4)
- }
- func NewWithProtocol(proto Protocol) (*IPTables, error) {
- path, err := exec.LookPath(getIptablesCommand(proto))
- if err != nil {
- return nil, err
- }
- checkPresent, waitPresent, err := getIptablesCommandSupport(path)
- if err != nil {
- return nil, fmt.Errorf("error checking iptables version: %v", err)
- }
- ipt := IPTables{
- path: path,
- proto: proto,
- hasCheck: checkPresent,
- hasWait: waitPresent,
- }
- return &ipt, nil
- }
- func (ipt *IPTables) Proto() Protocol {
- return ipt.proto
- }
- func (ipt *IPTables) Exists(table, chain string, rulespec ...string) (bool, error) {
- if !ipt.hasCheck {
- return ipt.existsForOldIptables(table, chain, rulespec)
- }
- cmd := append([]string{"-t", table, "-C", chain}, rulespec...)
- err := ipt.run(cmd...)
- eerr, eok := err.(*Error)
- switch {
- case err == nil:
- return true, nil
- case eok && eerr.ExitStatus() == 1:
- return false, nil
- default:
- return false, err
- }
- }
- func (ipt *IPTables) Insert(table, chain string, pos int, rulespec ...string) error {
- cmd := append([]string{"-t", table, "-I", chain, strconv.Itoa(pos)}, rulespec...)
- return ipt.run(cmd...)
- }
- func (ipt *IPTables) Append(table, chain string, rulespec ...string) error {
- cmd := append([]string{"-t", table, "-A", chain}, rulespec...)
- return ipt.run(cmd...)
- }
- func (ipt *IPTables) AppendUnique(table, chain string, rulespec ...string) error {
- exists, err := ipt.Exists(table, chain, rulespec...)
- if err != nil {
- return err
- }
- if !exists {
- return ipt.Append(table, chain, rulespec...)
- }
- return nil
- }
- func (ipt *IPTables) Delete(table, chain string, rulespec ...string) error {
- cmd := append([]string{"-t", table, "-D", chain}, rulespec...)
- return ipt.run(cmd...)
- }
- func (ipt *IPTables) List(table, chain string) ([]string, error) {
- args := []string{"-t", table, "-S", chain}
- return ipt.executeList(args)
- }
- func (ipt *IPTables) ListWithCounters(table, chain string) ([]string, error) {
- args := []string{"-t", table, "-v", "-S", chain}
- return ipt.executeList(args)
- }
- func (ipt *IPTables) ListChains(table string) ([]string, error) {
- args := []string{"-t", table, "-S"}
- result, err := ipt.executeList(args)
- if err != nil {
- return nil, err
- }
-
-
-
-
-
- var chains []string
- for _, val := range result {
- if strings.HasPrefix(val, "-P") || strings.HasPrefix(val, "-N") {
- chains = append(chains, strings.Fields(val)[1])
- } else {
- break
- }
- }
- return chains, nil
- }
- func (ipt *IPTables) Stats(table, chain string) ([][]string, error) {
- args := []string{"-t", table, "-L", chain, "-n", "-v", "-x"}
- lines, err := ipt.executeList(args)
- if err != nil {
- return nil, err
- }
- appendSubnet := func(addr string) string {
- if strings.IndexByte(addr, byte('/')) < 0 {
- if strings.IndexByte(addr, '.') < 0 {
- return addr + "/128"
- }
- return addr + "/32"
- }
- return addr
- }
- ipv6 := ipt.proto == ProtocolIPv6
- rows := [][]string{}
- for i, line := range lines {
-
- if i < 2 {
- continue
- }
-
-
- line = strings.TrimSpace(line)
- fields := strings.Fields(line)
-
-
- if ipv6 {
-
- dest := fields[6]
- ip, _, _ := net.ParseCIDR(dest)
- if ip == nil {
- ip = net.ParseIP(dest)
- }
-
- if ip != nil {
- f := []string{}
- f = append(f, fields[:4]...)
- f = append(f, " ")
- f = append(f, fields[4:]...)
- fields = f
- }
- }
-
-
- fields[7] = appendSubnet(fields[7])
- fields[8] = appendSubnet(fields[8])
-
- options := fields[9:]
- fields = fields[:9]
- fields = append(fields, strings.Join(options, " "))
- rows = append(rows, fields)
- }
- return rows, nil
- }
- func (ipt *IPTables) executeList(args []string) ([]string, error) {
- var stdout bytes.Buffer
- if err := ipt.runWithOutput(args, &stdout); err != nil {
- return nil, err
- }
- rules := strings.Split(stdout.String(), "\n")
- if len(rules) > 0 && rules[len(rules)-1] == "" {
- rules = rules[:len(rules)-1]
- }
- return rules, nil
- }
- func (ipt *IPTables) NewChain(table, chain string) error {
- return ipt.run("-t", table, "-N", chain)
- }
- func (ipt *IPTables) ClearChain(table, chain string) error {
- err := ipt.NewChain(table, chain)
- eerr, eok := err.(*Error)
- switch {
- case err == nil:
- return nil
- case eok && eerr.ExitStatus() == 1:
-
- return ipt.run("-t", table, "-F", chain)
- default:
- return err
- }
- }
- func (ipt *IPTables) RenameChain(table, oldChain, newChain string) error {
- return ipt.run("-t", table, "-E", oldChain, newChain)
- }
- func (ipt *IPTables) DeleteChain(table, chain string) error {
- return ipt.run("-t", table, "-X", chain)
- }
- func (ipt *IPTables) run(args ...string) error {
- return ipt.runWithOutput(args, nil)
- }
- func (ipt *IPTables) runWithOutput(args []string, stdout io.Writer) error {
- args = append([]string{ipt.path}, args...)
- if ipt.hasWait {
- args = append(args, "--wait")
- } else {
- fmu, err := newXtablesFileLock()
- if err != nil {
- return err
- }
- ul, err := fmu.tryLock()
- if err != nil {
- return err
- }
- defer ul.Unlock()
- }
- var stderr bytes.Buffer
- cmd := exec.Cmd{
- Path: ipt.path,
- Args: args,
- Stdout: stdout,
- Stderr: &stderr,
- }
- if err := cmd.Run(); err != nil {
- switch e := err.(type) {
- case *exec.ExitError:
- return &Error{*e, cmd, stderr.String()}
- default:
- return err
- }
- }
- return nil
- }
- func getIptablesCommand(proto Protocol) string {
- if proto == ProtocolIPv6 {
- return "ip6tables"
- } else {
- return "iptables"
- }
- }
- func getIptablesCommandSupport(path string) (bool, bool, error) {
- vstring, err := getIptablesVersionString(path)
- if err != nil {
- return false, false, err
- }
- v1, v2, v3, err := extractIptablesVersion(vstring)
- if err != nil {
- return false, false, err
- }
- return iptablesHasCheckCommand(v1, v2, v3), iptablesHasWaitCommand(v1, v2, v3), nil
- }
- func extractIptablesVersion(str string) (int, int, int, error) {
- versionMatcher := regexp.MustCompile("v([0-9]+)\\.([0-9]+)\\.([0-9]+)")
- result := versionMatcher.FindStringSubmatch(str)
- if result == nil {
- return 0, 0, 0, fmt.Errorf("no iptables version found in string: %s", str)
- }
- v1, err := strconv.Atoi(result[1])
- if err != nil {
- return 0, 0, 0, err
- }
- v2, err := strconv.Atoi(result[2])
- if err != nil {
- return 0, 0, 0, err
- }
- v3, err := strconv.Atoi(result[3])
- if err != nil {
- return 0, 0, 0, err
- }
- return v1, v2, v3, nil
- }
- func getIptablesVersionString(path string) (string, error) {
- cmd := exec.Command(path, "--version")
- var out bytes.Buffer
- cmd.Stdout = &out
- err := cmd.Run()
- if err != nil {
- return "", err
- }
- return out.String(), nil
- }
- func iptablesHasCheckCommand(v1 int, v2 int, v3 int) bool {
- if v1 > 1 {
- return true
- }
- if v1 == 1 && v2 > 4 {
- return true
- }
- if v1 == 1 && v2 == 4 && v3 >= 11 {
- return true
- }
- return false
- }
- func iptablesHasWaitCommand(v1 int, v2 int, v3 int) bool {
- if v1 > 1 {
- return true
- }
- if v1 == 1 && v2 > 4 {
- return true
- }
- if v1 == 1 && v2 == 4 && v3 >= 20 {
- return true
- }
- return false
- }
- func (ipt *IPTables) existsForOldIptables(table, chain string, rulespec []string) (bool, error) {
- rs := strings.Join(append([]string{"-A", chain}, rulespec...), " ")
- args := []string{"-t", table, "-S"}
- var stdout bytes.Buffer
- err := ipt.runWithOutput(args, &stdout)
- if err != nil {
- return false, err
- }
- return strings.Contains(stdout.String(), rs), nil
- }
|