forked from tsenart/vegeta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathattack.go
209 lines (186 loc) · 5.2 KB
/
attack.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package main
import (
"bytes"
"crypto/x509"
"encoding/gob"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"os/signal"
"strings"
"time"
vegeta "github.com/tsenart/vegeta/lib"
)
func attackCmd() command {
fs := flag.NewFlagSet("vegeta attack", flag.ExitOnError)
opts := &attackOpts{
headers: headers{http.Header{}},
laddr: localAddr{&vegeta.DefaultLocalAddr},
}
fs.StringVar(&opts.targetsf, "targets", "stdin", "Targets file")
fs.StringVar(&opts.outputf, "output", "stdout", "Output file")
fs.StringVar(&opts.bodyf, "body", "", "Requests body file")
fs.StringVar(&opts.certf, "cert", "", "x509 Certificate file")
fs.BoolVar(&opts.lazy, "lazy", false, "Read targets lazily")
fs.DurationVar(&opts.duration, "duration", 10*time.Second, "Duration of the test")
fs.DurationVar(&opts.timeout, "timeout", vegeta.DefaultTimeout, "Requests timeout")
fs.Uint64Var(&opts.rate, "rate", 50, "Requests per second")
fs.Uint64Var(&opts.workers, "workers", 0, "Number of workers")
fs.IntVar(&opts.redirects, "redirects", vegeta.DefaultRedirects, "Number of redirects to follow")
fs.Var(&opts.headers, "header", "Request header")
fs.Var(&opts.laddr, "laddr", "Local IP address")
fs.BoolVar(&opts.keepalive, "keepalive", true, "Use persistent connections")
fs.StringVar(&opts.proxy, "proxy", "none", "Set HTTP proxy (need to specify scheme. e.g. http://127.0.0.1:8888)")
return command{fs, func(args []string) error {
fs.Parse(args)
return attack(opts)
}}
}
var (
errZeroDuration = errors.New("duration must be bigger than zero")
errZeroRate = errors.New("rate must be bigger than zero")
errBadCert = errors.New("bad certificate")
)
// attackOpts aggregates the attack function command options
type attackOpts struct {
targetsf string
outputf string
bodyf string
certf string
lazy bool
duration time.Duration
timeout time.Duration
rate uint64
workers uint64
redirects int
headers headers
laddr localAddr
keepalive bool
proxy string
}
// attack validates the attack arguments, sets up the
// required resources, launches the attack and writes the results
func attack(opts *attackOpts) (err error) {
if opts.rate == 0 {
return errZeroRate
}
if opts.duration == 0 {
return errZeroDuration
}
files := map[string]io.Reader{}
for _, filename := range []string{opts.targetsf, opts.bodyf, opts.certf} {
if filename == "" {
continue
}
f, err := file(filename, false)
if err != nil {
return fmt.Errorf("error opening %s: %s", filename, err)
}
defer f.Close()
files[filename] = f
}
var body []byte
if bodyf, ok := files[opts.bodyf]; ok {
if body, err = ioutil.ReadAll(bodyf); err != nil {
return fmt.Errorf("error reading %s: %s", opts.bodyf, err)
}
}
var (
tr vegeta.Targeter
src = files[opts.targetsf]
hdr = opts.headers.Header
)
if opts.lazy {
tr = vegeta.NewLazyTargeter(src, body, hdr)
} else if tr, err = vegeta.NewEagerTargeter(src, body, hdr); err != nil {
return err
}
out, err := file(opts.outputf, true)
if err != nil {
return fmt.Errorf("error opening %s: %s", opts.outputf, err)
}
defer out.Close()
var cert []byte
if certf, ok := files[opts.certf]; ok {
if cert, err = ioutil.ReadAll(certf); err != nil {
return fmt.Errorf("error reading %s: %s", opts.certf, err)
}
}
tlsc := *vegeta.DefaultTLSConfig
if opts.certf != "" {
if tlsc.RootCAs, err = certPool(cert); err != nil {
return err
}
}
atk := vegeta.NewAttacker(
vegeta.Redirects(opts.redirects),
vegeta.Timeout(opts.timeout),
vegeta.LocalAddr(*opts.laddr.IPAddr),
vegeta.TLSConfig(&tlsc),
vegeta.Workers(opts.workers),
vegeta.KeepAlive(opts.keepalive),
vegeta.SetProxy(opts.proxy),
)
res := atk.Attack(tr, opts.rate, opts.duration)
enc := gob.NewEncoder(out)
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
for {
select {
case <-sig:
atk.Stop()
return nil
case r, ok := <-res:
if !ok {
return nil
}
if err = enc.Encode(r); err != nil {
return err
}
}
}
}
// headers is the http.Header used in each target request
// it is defined here to implement the flag.Value interface
// in order to support multiple identical flags for request header
// specification
type headers struct{ http.Header }
func (h headers) String() string {
buf := &bytes.Buffer{}
if err := h.Write(buf); err != nil {
return ""
}
return buf.String()
}
func (h headers) Set(value string) error {
parts := strings.SplitN(value, ":", 2)
if len(parts) != 2 {
return fmt.Errorf("header '%s' has a wrong format", value)
}
key, val := strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])
if key == "" || val == "" {
return fmt.Errorf("header '%s' has a wrong format", value)
}
h.Add(key, val)
return nil
}
// localAddr implements the Flag interface for parsing net.IPAddr
type localAddr struct{ *net.IPAddr }
func (ip *localAddr) Set(value string) (err error) {
ip.IPAddr, err = net.ResolveIPAddr("ip", value)
return
}
// certPool returns a new *x509.CertPool with the passed cert included.
// An error is returned if the cert is invalid.
func certPool(cert []byte) (*x509.CertPool, error) {
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(cert) {
return nil, errBadCert
}
return pool, nil
}