-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathmain.go
More file actions
149 lines (125 loc) · 4.21 KB
/
Copy pathmain.go
File metadata and controls
149 lines (125 loc) · 4.21 KB
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
package main
import (
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/peterbourgon/ff/v3"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/bvantagelimited/freeradius_exporter/client"
"github.com/bvantagelimited/freeradius_exporter/collector"
)
var version, commit, date string
func main() {
fs := flag.NewFlagSet("freeradius_exporter", flag.ContinueOnError)
appHelp := fs.Bool("help", false, "Display help")
appVersion := fs.Bool("version", false, "Display version information")
_ = fs.String("config", "", "Config file (optional)")
listenAddr := fs.String("web.listen-address", ":9812", "Address to listen on for web interface and telemetry.")
metricsPath := fs.String("web.telemetry-path", "/metrics", "A path under which to expose metrics.")
metricsAuthToken := fs.String("web.auth-token", "", "Auth token required in X-Auth-Token header to access /metrics (optional).")
metricsAllowedIPs := fs.String("web.allowed-ips", "", "Comma-separated list of IPs or CIDR ranges allowed to access /metrics (optional).")
radiusTimeout := fs.Int("radius.timeout", 5000, "Timeout, in milliseconds [RADIUS_TIMEOUT].")
radiusAddr := fs.String("radius.address", "127.0.0.1:18121", "Address of FreeRADIUS status server [RADIUS_ADDRESS].")
homeServers := fs.String("radius.homeservers", "", "List of FreeRADIUS home servers to check, e.g. '172.28.1.2:1812:auth,172.28.1.3:1813:acct' [RADIUS_HOMESERVERS].")
radiusSecret := fs.String("radius.secret", "adminsecret", "FreeRADIUS client secret [RADIUS_SECRET].")
err := ff.Parse(fs, os.Args[1:], ff.WithEnvVarNoPrefix(), ff.WithConfigFileFlag("config"), ff.WithConfigFileParser(ff.JSONParser))
if err != nil {
println(err.Error())
os.Exit(1)
}
if *appHelp {
fs.PrintDefaults()
os.Exit(0)
}
if *appVersion {
println(filepath.Base(os.Args[0]), version, commit, date)
os.Exit(0)
}
allowedCIDRs, err := parseAllowedIPs(*metricsAllowedIPs)
if err != nil {
println(err)
os.Exit(1)
}
registry := prometheus.NewRegistry()
hs := strings.Split(*homeServers, ",")
radiusClient, err := client.NewFreeRADIUSClient(*radiusAddr, hs, *radiusSecret, *radiusTimeout)
if err != nil {
log.Fatal(err)
}
registry.MustRegister(collector.NewFreeRADIUSCollector(radiusClient))
metricsHandler := promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
http.Handle(*metricsPath, withTokenOrIP(*metricsAuthToken, allowedCIDRs, metricsHandler))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>FreeRADIUS Exporter</title></head>
<body>
<h1>FreeRADIUS Exporter</h1>
<p><a href='` + *metricsPath + `'>Metrics</a></p>
</body>
</html>`))
})
srv := &http.Server{}
listener, err := net.Listen("tcp4", *listenAddr)
if err != nil {
log.Fatal(err)
}
log.Printf("Providing metrics at %s%s", *listenAddr, *metricsPath)
log.Fatal(srv.Serve(listener))
}
func parseAllowedIPs(input string) ([]*net.IPNet, error) {
if input == "" {
return nil, nil
}
entries := strings.Split(input, ",")
var result []*net.IPNet
for _, entry := range entries {
entry = strings.TrimSpace(entry)
if ip := net.ParseIP(entry); ip != nil {
result = append(result, &net.IPNet{
IP: ip,
Mask: net.CIDRMask(32, 32),
})
continue
}
if _, cidr, err := net.ParseCIDR(entry); err == nil {
result = append(result, cidr)
continue
}
return nil, fmt.Errorf("Invalid IP or CIDR : %s", entry)
}
return result, nil
}
func withTokenOrIP(token string, allowed []*net.IPNet, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// no filters defined → PASS
if token == "" && len(allowed) == 0 {
next.ServeHTTP(w, r)
return
}
// token valid → PASS
if token != "" && r.Header.Get("X-Auth-Token") == token {
next.ServeHTTP(w, r)
return
}
// valid CIDR or IP → PASS
if len(allowed) > 0 {
ipStr, _, err := net.SplitHostPort(r.RemoteAddr)
if err == nil {
ip := net.ParseIP(ipStr)
for _, ipNet := range allowed {
if ipNet.Contains(ip) {
next.ServeHTTP(w, r)
return
}
}
}
}
http.Error(w, "Forbidden", http.StatusForbidden)
})
}