2021-04-19 09:24:46 -04:00
|
|
|
package firewall
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"errors"
|
|
|
|
|
"fmt"
|
2021-07-16 20:04:17 +00:00
|
|
|
"os/exec"
|
2021-04-19 09:24:46 -04:00
|
|
|
"strings"
|
2021-04-19 14:35:29 -04:00
|
|
|
|
|
|
|
|
"github.com/qdm12/golibs/command"
|
2021-04-19 09:24:46 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var (
|
2021-04-19 14:35:29 -04:00
|
|
|
ErrIP6Tables = errors.New("failed ip6tables command")
|
|
|
|
|
ErrIP6NotSupported = errors.New("ip6tables not supported")
|
2021-04-19 09:24:46 -04:00
|
|
|
)
|
|
|
|
|
|
2021-04-19 14:35:29 -04:00
|
|
|
func ip6tablesSupported(ctx context.Context, commander command.Commander) (supported bool) {
|
2021-07-16 20:04:17 +00:00
|
|
|
cmd := exec.CommandContext(ctx, "ip6tables", "-L")
|
|
|
|
|
if _, err := commander.Run(cmd); err != nil {
|
2021-04-19 14:35:29 -04:00
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
|
2021-07-23 19:12:16 +00:00
|
|
|
func (c *Config) runIP6tablesInstructions(ctx context.Context, instructions []string) error {
|
2021-04-19 09:24:46 -04:00
|
|
|
for _, instruction := range instructions {
|
|
|
|
|
if err := c.runIP6tablesInstruction(ctx, instruction); err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2021-07-23 19:12:16 +00:00
|
|
|
func (c *Config) runIP6tablesInstruction(ctx context.Context, instruction string) error {
|
2021-04-19 14:35:29 -04:00
|
|
|
if !c.ip6Tables {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
2021-04-19 09:24:46 -04:00
|
|
|
c.ip6tablesMutex.Lock() // only one ip6tables command at once
|
|
|
|
|
defer c.ip6tablesMutex.Unlock()
|
2021-07-23 18:20:18 +00:00
|
|
|
|
|
|
|
|
c.logger.Debug("ip6tables " + instruction)
|
|
|
|
|
|
2021-04-19 09:24:46 -04:00
|
|
|
flags := strings.Fields(instruction)
|
2021-07-16 20:04:17 +00:00
|
|
|
cmd := exec.CommandContext(ctx, "ip6tables", flags...)
|
|
|
|
|
if output, err := c.commander.Run(cmd); err != nil {
|
2021-05-30 16:14:08 +00:00
|
|
|
return fmt.Errorf("%w: \"ip6tables %s\": %s: %s", ErrIP6Tables, instruction, output, err)
|
2021-04-19 09:24:46 -04:00
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2021-05-30 16:14:08 +00:00
|
|
|
var errPolicyNotValid = errors.New("policy is not valid")
|
|
|
|
|
|
2021-07-23 19:12:16 +00:00
|
|
|
func (c *Config) setIPv6AllPolicies(ctx context.Context, policy string) error {
|
2021-04-19 09:24:46 -04:00
|
|
|
switch policy {
|
|
|
|
|
case "ACCEPT", "DROP":
|
|
|
|
|
default:
|
2021-05-30 16:14:08 +00:00
|
|
|
return fmt.Errorf("%w: %s", errPolicyNotValid, policy)
|
2021-04-19 09:24:46 -04:00
|
|
|
}
|
|
|
|
|
return c.runIP6tablesInstructions(ctx, []string{
|
|
|
|
|
"--policy INPUT " + policy,
|
|
|
|
|
"--policy OUTPUT " + policy,
|
|
|
|
|
"--policy FORWARD " + policy,
|
|
|
|
|
})
|
|
|
|
|
}
|