-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtraefik-proxy-bouncer.go
95 lines (80 loc) · 1.72 KB
/
traefik-proxy-bouncer.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
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"gopkg.in/yaml.v2"
csbouncer "github.com/crowdsecurity/go-cs-bouncer"
)
type config struct {
Key string `yaml:"crowdsec-key"`
Url string `yaml:"crowdsec-url"`
}
func (c *config) getConfig() bool {
yamlFile, err := ioutil.ReadFile("config.yaml")
ok := true
if err != nil {
log.Printf("yaml error loading file : %v", err)
ok = false
}
err = yaml.Unmarshal(yamlFile, c)
if err != nil {
log.Fatalf("yaml error loading file : %v", err)
ok = false
}
return ok
}
var bouncer csbouncer.LiveBouncer
var conf config
var listenAddress string
func init() {
ok := conf.getConfig()
if !ok {
os.Exit(2)
}
listenAddress = "0.0.0.0:8090"
bouncer = csbouncer.LiveBouncer{
APIKey: conf.Key,
APIUrl: conf.Url,
}
if err := bouncer.Init(); err != nil {
log.Fatalf(err.Error())
}
}
func main() {
log.Println("Started", listenAddress)
http.HandleFunc("/auth", auth)
http.ListenAndServe(listenAddress, nil)
}
func auth(response http.ResponseWriter, request *http.Request) {
var source_ip string
ip_value, prs := request.Header["Cf-Connecting-Ip"]
if !prs {
ip_value, prs = request.Header["X-Forwarded-For"]
if !prs {
ip_value, prs = request.Header["X-Real-Ip"]
if !prs {
ip_value = []string{
strings.Split(request.RemoteAddr, ":")[0]}
}
}
}
source_ip = ip_value[0]
decisions, err := bouncer.Get(source_ip)
if err != nil {
log.Fatalf("unable to get decision for ip '%s' : '%s'", source_ip, err)
}
if len(*decisions) == 0 {
code := 200
response.WriteHeader(code)
fmt.Fprintf(response, "Ok\n")
} else {
code := 403
response.WriteHeader(code)
fmt.Fprintf(response, "Forbiden\n")
}
log.Println(source_ip)
}