init network loss attack

Signed-off-by: cwen0 <cwenyin0@gmail.com>
This commit is contained in:
cwen0 2020-11-24 16:03:23 +08:00
parent 670ff91317
commit 1dfedebc77
8 changed files with 127 additions and 179 deletions

View File

@ -29,6 +29,7 @@ func NewNetworkAttackCommand() *cobra.Command {
cmd.AddCommand(
NewNetworkDelayCommand(),
NewNetworkLossCommand(),
)
return cmd
@ -41,13 +42,14 @@ func NewNetworkDelayCommand() *cobra.Command {
Use: "delay [option]",
Short: "delay network",
Run: networkDelayCommandFunc,
Run: networkCommandFunc,
}
cmd.Flags().StringVarP(&nFlag.Latency, "latency", "l", "",
"delay egress time, time units: ns, us (or µs), ms, s, m, h.")
cmd.Flags().StringVarP(&nFlag.Jitter, "jitter", "j", "",
"jitter time, time units: ns, us (or µs), ms, s, m, h.")
cmd.Flags().StringVarP(&nFlag.Correlation, "correlation", "c", "0", "correlation is percentage (10 is 10%)")
cmd.Flags().StringVarP(&nFlag.Device, "device", "d", "", "the network interface to impact")
cmd.Flags().StringVarP(&nFlag.EgressPort, "egress-port", "e", "",
"only impact egress traffic to these destination ports, use a ',' to separate or to indicate the range, such as 80, 8001:8010. It can only be used in conjunction with -p tcp or -p udp")
@ -58,12 +60,37 @@ func NewNetworkDelayCommand() *cobra.Command {
cmd.Flags().StringVarP(&nFlag.IPProtocol, "protocol", "p", "",
"only impact traffic using this IP protocol, supported: tcp, udp, icmp, all")
nFlag.Action = core.NetworkDelayAction
nFlag.SetDefault()
nFlag.SetDefaultForNetworkDelay()
return cmd
}
func networkDelayCommandFunc(cmd *cobra.Command, args []string) {
func NewNetworkLossCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "loss [option]",
Short: "loss network packet",
Run: networkCommandFunc,
}
cmd.Flags().StringVar(&nFlag.Percent, "percent", "1", "percentage of packets to drop (10 is 10%)")
cmd.Flags().StringVarP(&nFlag.Correlation, "correlation", "c", "0", "correlation is percentage (10 is 10%)")
cmd.Flags().StringVarP(&nFlag.Device, "device", "d", "", "the network interface to impact")
cmd.Flags().StringVarP(&nFlag.EgressPort, "egress-port", "e", "",
"only impact egress traffic to these destination ports, use a ',' to separate or to indicate the range, such as 80, 8001:8010. It can only be used in conjunction with -p tcp or -p udp")
cmd.Flags().StringVarP(&nFlag.SourcePort, "source-port", "s", "",
"only impact egress traffic from these source ports, use a ',' to separate or to indicate the range, such as 80, 8001:8010. It can only be used in conjunction with -p tcp or -p udp")
cmd.Flags().StringVarP(&nFlag.IPAddress, "ip", "i", "", "only impact egress traffic to these IP addresses")
cmd.Flags().StringVarP(&nFlag.Hostname, "hostname", "H", "", "only impact traffic to these hostnames")
cmd.Flags().StringVarP(&nFlag.IPProtocol, "protocol", "p", "",
"only impact traffic using this IP protocol, supported: tcp, udp, icmp, all")
nFlag.Action = core.NetworkLossAction
nFlag.SetDefaultForNetworkLoss()
return cmd
}
func networkCommandFunc(cmd *cobra.Command, args []string) {
if err := nFlag.Validate(); err != nil {
ExitWithError(ExitBadArgs, err)
}

3
go.mod
View File

@ -17,7 +17,6 @@ require (
github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c // indirect
github.com/gin-gonic/gin v1.6.3
github.com/go-logr/logr v0.1.0
github.com/go-logr/zapr v0.1.0
github.com/go-ole/go-ole v1.2.1 // indirect
github.com/go-playground/validator/v10 v10.3.0 // indirect
github.com/gogo/googleapis v1.3.2 // indirect
@ -35,7 +34,7 @@ require (
github.com/mattn/go-sqlite3 v2.0.1+incompatible // indirect
github.com/mitchellh/go-ps v0.0.0-20170309133038-4fdf99ab2936
github.com/morikuni/aec v1.0.0 // indirect
github.com/onsi/ginkgo v1.12.0
github.com/onsi/ginkgo v1.12.0 // indirect
github.com/onsi/gomega v1.9.0
github.com/opencontainers/image-spec v1.0.1 // indirect
github.com/opencontainers/runc v1.0.0-rc9 // indirect

View File

@ -39,6 +39,7 @@ files=($(find . -type f -not \( \
-o -path './pkg/uiserver/embedded_assets_handler.go' \
-o -path '*/pb/*' \
-o -path '*/*.deepcopy.go' \
-o -path '*/*pb.go' \
\) | grep -v -F "$ignored_files"
))

View File

@ -31,6 +31,7 @@ type NetworkCommand struct {
Latency string
Jitter string
Correlation string
Percent string
Device string
SourcePort string
EgressPort string
@ -41,17 +42,18 @@ type NetworkCommand struct {
const (
NetworkDelayAction = "delay"
NetworkLossAction = "loss"
)
func (n *NetworkCommand) Validate() error {
switch n.Action {
case NetworkDelayAction:
return n.validNetworkDelay()
case NetworkLossAction:
return n.validNetworkLoss()
default:
return errors.Errorf("network action %s not supported", n.Action)
}
return nil
}
func (n *NetworkCommand) validNetworkDelay() error {
@ -69,6 +71,10 @@ func (n *NetworkCommand) validNetworkDelay() error {
}
}
if !utils.CheckPercent(n.Correlation) {
return errors.Errorf("correlation %s not valid", n.Correlation)
}
if len(n.Device) == 0 {
return errors.New("device is required")
}
@ -80,7 +86,31 @@ func (n *NetworkCommand) validNetworkDelay() error {
return checkProtocolAndPorts(n.IPProtocol, n.SourcePort, n.EgressPort)
}
func (n *NetworkCommand) SetDefault() {
func (n *NetworkCommand) validNetworkLoss() error {
if len(n.Percent) == 0 {
return errors.New("percent is required")
}
if !utils.CheckPercent(n.Percent) {
return errors.Errorf("percent %s not valid", n.Percent)
}
if !utils.CheckPercent(n.Correlation) {
return errors.Errorf("correlation %s not valid", n.Correlation)
}
if len(n.Device) == 0 {
return errors.New("device is required")
}
if !utils.CheckIPs(n.IPAddress) {
return errors.Errorf("ip addressed %s not valid", n.IPAddress)
}
return checkProtocolAndPorts(n.IPProtocol, n.SourcePort, n.EgressPort)
}
func (n *NetworkCommand) SetDefaultForNetworkDelay() {
if len(n.Jitter) == 0 {
n.Jitter = "0ms"
}
@ -90,6 +120,12 @@ func (n *NetworkCommand) SetDefault() {
}
}
func (n *NetworkCommand) SetDefaultForNetworkLoss() {
if len(n.Correlation) == 0 {
n.Correlation = "0"
}
}
func checkProtocolAndPorts(p string, sports string, dports string) error {
if !utils.CheckPorts(sports) {
return errors.Errorf("source ports %s not valid", sports)
@ -120,7 +156,7 @@ func (n *NetworkCommand) String() string {
return string(data)
}
func (n *NetworkCommand) ToNetem() (*pb.Netem, error) {
func (n *NetworkCommand) ToDelayNetem() (*pb.Netem, error) {
delayTime, err := time.ParseDuration(n.Latency)
if err != nil {
return nil, errors.WithStack(err)
@ -146,6 +182,23 @@ func (n *NetworkCommand) ToNetem() (*pb.Netem, error) {
return netem, nil
}
func (n *NetworkCommand) ToLossNetem() (*pb.Netem, error) {
percent, err := strconv.ParseFloat(n.Percent, 32)
if err != nil {
return nil, errors.WithStack(err)
}
corr, err := strconv.ParseFloat(n.Correlation, 32)
if err != nil {
return nil, errors.WithStack(err)
}
return &pb.Netem{
Loss: float32(percent),
LossCorr: float32(corr),
}, nil
}
func (n *NetworkCommand) ToTC(ipset string) (*pb.Tc, error) {
tc := &pb.Tc{
Type: pb.Tc_NETEM,
@ -155,17 +208,25 @@ func (n *NetworkCommand) ToTC(ipset string) (*pb.Tc, error) {
EgressPort: n.EgressPort,
}
var (
netem *pb.Netem
err error
)
switch n.Action {
case NetworkDelayAction:
netem, err := n.ToNetem()
if err != nil {
if netem, err = n.ToDelayNetem(); err != nil {
return nil, errors.WithStack(err)
}
case NetworkLossAction:
if netem, err = n.ToLossNetem(); err != nil {
return nil, errors.WithStack(err)
}
tc.Netem = netem
default:
return nil, errors.Errorf("action %s not supported", n.Action)
}
tc.Netem = netem
return tc, nil
}

View File

@ -1,163 +0,0 @@
// Copyright 2020 Chaos Mesh Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package ptrace
import (
"encoding/binary"
"math/rand"
"os"
"os/exec"
"testing"
"time"
"unsafe"
"github.com/go-logr/zapr"
"go.uber.org/zap"
"github.com/chaos-mesh/chaos-daemon/test/pkg/timer"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"sigs.k8s.io/controller-runtime/pkg/envtest"
)
func TestPTrace(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecsWithDefaultAndCustomReporters(t,
"PTrace Suit",
[]Reporter{envtest.NewlineReporter{}})
}
var _ = BeforeSuite(func(done Done) {
rand.Seed(GinkgoRandomSeed())
By("change working directory")
err := os.Chdir("../../")
Expect(err).NotTo(HaveOccurred())
By("register logger")
zapLog, err := zap.NewDevelopment()
Expect(err).NotTo(HaveOccurred())
log := zapr.NewLogger(zapLog)
RegisterLogger(log)
close(done)
})
// These tests are written in BDD-style using Ginkgo framework. Refer to
// http://onsi.github.io/ginkgo to learn more.
var _ = Describe("PTrace", func() {
var t *timer.Timer
var program *TracedProgram
BeforeEach(func() {
var err error
t, err = timer.StartTimer()
Expect(err).ShouldNot(HaveOccurred(), "error: %+v", err)
time.Sleep(time.Millisecond)
program, err = Trace(t.Pid())
Expect(err).ShouldNot(HaveOccurred(), "error: %+v", err)
})
AfterEach(func() {
err := program.Detach()
Expect(err).ShouldNot(HaveOccurred(), "error: %+v", err)
err = t.Stop()
Expect(err).ShouldNot(HaveOccurred(), "error: %+v", err)
})
It("should mmap slice successfully", func() {
Expect(program.Pid()).Should(Equal(t.Pid()))
helloWorld := []byte("Hello World")
entry, err := program.MmapSlice(helloWorld)
Expect(err).ShouldNot(HaveOccurred(), "error: %+v", err)
readBuf, err := program.ReadSlice(entry.StartAddress, uint64(len(helloWorld)))
Expect(err).ShouldNot(HaveOccurred(), "error: %+v", err)
Expect(*readBuf).Should(Equal(helloWorld))
})
It("double trace should get error", func() {
_, err := Trace(t.Pid())
Expect(err).Should(HaveOccurred())
})
It("should ptrace write slice successfully", func() {
helloWorld := []byte("Hello World")
addr, err := program.Mmap(uint64(len(helloWorld)), 0)
Expect(err).ShouldNot(HaveOccurred(), "error: %+v", err)
err = program.PtraceWriteSlice(addr, helloWorld)
Expect(err).ShouldNot(HaveOccurred(), "error: %+v, addr: %d", err, addr)
readBuf, err := program.ReadSlice(addr, uint64(len(helloWorld)))
Expect(err).ShouldNot(HaveOccurred(), "error: %+v, addr: %d", err, addr)
Expect(*readBuf).Should(Equal(helloWorld))
})
It("should write uint64 successfully", func() {
number := rand.Uint64()
size := uint64(unsafe.Sizeof(number))
expectBuf := make([]byte, size)
binary.LittleEndian.PutUint64(expectBuf, number)
addr, err := program.Mmap(size, 0)
Expect(err).ShouldNot(HaveOccurred(), "error: %+v", err)
err = program.WriteUint64ToAddr(addr, number)
Expect(err).ShouldNot(HaveOccurred(), "error: %+v, addr: %d", err, addr)
readBuf, err := program.ReadSlice(addr, size)
Expect(err).ShouldNot(HaveOccurred(), "error: %+v, addr: %d", err, addr)
Expect(*readBuf).Should(Equal(expectBuf))
})
It("should be able to detach and reattach", func() {
err := program.Detach()
Expect(err).ShouldNot(HaveOccurred(), "error: %+v", err)
program, err = Trace(t.Pid())
Expect(err).ShouldNot(HaveOccurred(), "error: %+v", err)
})
It("should be able to attach and detach multithread program", func() {
p := exec.Command("./bin/test/multithread_tracee")
err := p.Start()
Expect(err).ShouldNot(HaveOccurred(), "error: %+v", err)
time.Sleep(time.Millisecond)
pid := p.Process.Pid
program, err := Trace(pid)
Expect(err).ShouldNot(HaveOccurred(), "error: %+v", err)
err = program.Detach()
Expect(err).ShouldNot(HaveOccurred(), "error: %+v", err)
err = p.Process.Kill()
Expect(err).ShouldNot(HaveOccurred(), "error: %+v", err)
})
})

View File

@ -163,7 +163,12 @@ func (s *Server) applyTC(attack *core.NetworkCommand, ipset string, uid string)
Correlation: attack.Correlation,
Jitter: attack.Jitter,
},
Loss: &core.LossSpec{
Loss: attack.Percent,
Correlation: attack.Correlation,
},
}
tcString, err := json.Marshal(tc)
if err != nil {
return errors.WithStack(err)

View File

@ -104,9 +104,10 @@ func (i *iptablesRuleStore) FindByExperiment(_ context.Context, experiment strin
Where("experiment = ?", experiment).
Find(&rules).
Error; err != nil && !gorm.IsRecordNotFoundError(err) {
return nil, errors.WithStack(err)
}
return nil, nil
return rules, nil
}
func (i *iptablesRuleStore) DeleteByExperiment(_ context.Context, experiment string) error {
@ -150,9 +151,9 @@ func (t *tcRuleStore) FindByExperiment(_ context.Context, experiment string) ([]
Where("experiment = ?", experiment).
Find(&rules).
Error; err != nil && !gorm.IsRecordNotFoundError(err) {
return nil, errors.WithStack(err)
}
return nil, nil
return rules, nil
}
func (t *tcRuleStore) DeleteByExperiment(_ context.Context, experiment string) error {

View File

@ -85,3 +85,20 @@ func CheckIPProtocols(p string) bool {
return false
}
func CheckPercent(p string) bool {
if len(p) == 0 {
return true
}
v, err := strconv.ParseFloat(p, 32)
if err != nil {
return false
}
if v < 0 || v > 100 {
return false
}
return true
}