-
Notifications
You must be signed in to change notification settings - Fork 6
/
wirelogd.go
242 lines (215 loc) · 6.42 KB
/
wirelogd.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
// Wirelogd is a logging daemon for WireGuard.
//
// Since WireGuard itself does not log the state of its peers (and since it is
// UDP based so, there no concept of "connection state"), Wirelogd relies on
// the latest handshake to determine if a peer is active or inactive. While
// there is traffic the handshake should be renewed every 2 minutes. If there is
// no traffic, handshake is not renewed. Based on this behavior we assume that
// if there is no new handshake after a while (default Wirelogd timeout value
// is 5 minutes), the client is probably inactive.
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"log/slog"
"log/syslog"
"net"
"os"
"os/signal"
"syscall"
"time"
"golang.zx2c4.com/wireguard/wgctrl"
)
type wirelogdConfig struct {
Debug bool `json:"debug"`
LogDestination string `json:"log_destination"`
LogFormat string `json:"log_format"`
Refresh int `json:"refresh"`
Timeout int64 `json:"timeout"`
}
type wirelogdPeer struct {
Interface string `json:"interface"`
PublicKey string `json:"public_key"`
Endpoint string `json:"endpoint"`
AllowedIPs []string `json:"allowed_ips"`
LatestHandshake int64 `json:"-"`
}
var configFile string
var config wirelogdConfig
var version string
var showVersion bool
func init() {
// Set default values
config = wirelogdConfig{
Debug: false,
LogDestination: "stdout",
LogFormat: "json",
Refresh: 5,
Timeout: 300,
}
// Parse flags
var configFromArgs wirelogdConfig
flag.StringVar(&configFile, "config", "", "path to JSON configuration file")
flag.StringVar(&configFromArgs.LogDestination, "log-destination", "stdout", "logging destination, could be \"stdout\", \"syslog\" or a file path")
flag.StringVar(&configFromArgs.LogFormat, "log-format", "json", "logging format, could be \"json\" or \"text\"")
flag.BoolVar(&configFromArgs.Debug, "debug", false, "enable debug logging")
flag.IntVar(&configFromArgs.Refresh, "refresh", 0, "refresh interval in seconds")
flag.Int64Var(&configFromArgs.Timeout, "timeout", 0, "wireguard handshake timeout in seconds")
flag.BoolVar(&showVersion, "version", false, "show version")
flag.Parse()
// Read config file
if configFile != "" {
if data, errRead := os.ReadFile(configFile); errRead == nil {
if errParse := json.Unmarshal(data, &config); errParse != nil {
panic(fmt.Sprintf("cannot parse configuration file: %s", errParse.Error()))
}
} else {
panic(fmt.Sprintf("cannot read configuration file: %s", errRead.Error()))
}
}
// Apply config from flags
if isFlagPassed("debug") {
config.Debug = configFromArgs.Debug
}
if isFlagPassed("log-destination") {
config.LogDestination = configFromArgs.LogDestination
}
if isFlagPassed("log-format") {
config.LogFormat = configFromArgs.LogFormat
}
if isFlagPassed("refresh") {
config.Refresh = configFromArgs.Refresh
}
if isFlagPassed("timeout") {
config.Timeout = configFromArgs.Timeout
}
// Configure logging level
logHandlerOptions := &slog.HandlerOptions{
Level: slog.LevelInfo,
}
if config.Debug {
logHandlerOptions.Level = slog.LevelDebug
}
// Configure logging destination
var logWriter io.Writer
switch config.LogDestination {
case "stdout":
logWriter = os.Stdout
case "syslog":
syslogPriority := syslog.LOG_INFO
if config.Debug {
syslogPriority = syslog.LOG_DEBUG
}
if syslogWriter, syslogErr := syslog.New(syslogPriority, "wirelogd"); syslogErr == nil {
logWriter = syslogWriter
} else {
panic(syslogErr.Error())
}
default:
if logFile, logFileErr := os.OpenFile(config.LogDestination, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644); logFileErr == nil {
logWriter = logFile
} else {
panic(logFileErr.Error())
}
}
// Configure logging format
var logHandler slog.Handler
switch config.LogFormat {
case "json":
logHandler = slog.NewJSONHandler(logWriter, logHandlerOptions)
case "text":
logHandler = slog.NewTextHandler(logWriter, logHandlerOptions)
default:
panic("unsupported log format")
}
// Configure logger
logger := slog.New(logHandler)
slog.SetDefault(logger)
}
func (p *wirelogdPeer) JSON() []byte {
pJSON, err := json.Marshal(p)
if err != nil {
slog.Error(err.Error())
os.Exit(1)
}
return pJSON
}
func getPeers() []wirelogdPeer {
wg, err := wgctrl.New()
if err != nil {
slog.Error(err.Error())
os.Exit(1)
}
defer wg.Close()
wgDevices, err := wg.Devices()
if err != nil {
slog.Error(err.Error())
os.Exit(1)
}
var wgPeers []wirelogdPeer
for _, wgDevice := range wgDevices {
for _, wgPeer := range wgDevice.Peers {
// replace empty endpoint
var endpoint string
if wgPeer.Endpoint != (*net.UDPAddr)(nil) {
endpoint = fmt.Sprintf("%s:%d", wgPeer.Endpoint.IP.String(), wgPeer.Endpoint.Port)
} else {
endpoint = "(none)"
}
// get list of allowed ip addresses
var allowedIPs []string
for _, allowedIp := range wgPeer.AllowedIPs {
allowedIPs = append(allowedIPs, allowedIp.IP.String())
}
wgPeers = append(wgPeers, wirelogdPeer{
Interface: wgDevice.Name,
PublicKey: wgPeer.PublicKey.String(),
Endpoint: endpoint,
AllowedIPs: allowedIPs,
LatestHandshake: wgPeer.LastHandshakeTime.Unix(),
})
}
}
return wgPeers
}
func main() {
configJSON, _ := json.Marshal(config)
slog.Debug("", slog.String("config", string(configJSON)))
if showVersion {
fmt.Printf("wirelogd version %s\n", version)
os.Exit(0)
}
slog.Info("start wirelogd")
// catch sigterm signal
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
slog.Info("stop wirelogd")
os.Exit(0)
}()
// init activity state
activityState := make(map[string]bool)
for {
wgPeers := getPeers()
peersJSON, _ := json.Marshal(wgPeers)
slog.Debug("", slog.String("peers", string(peersJSON)))
now := time.Now().Unix()
for _, wgPeer := range wgPeers {
wgKey := fmt.Sprintf("%s-%s", wgPeer.Interface, wgPeer.PublicKey)
wasActive := activityState[wgKey]
timedOut := (now - wgPeer.LatestHandshake) > config.Timeout
if wasActive && timedOut {
activityState[wgKey] = false
slog.Info("", slog.String("peer", string(wgPeer.JSON())), slog.String("state", "inactive"))
} else if !wasActive && !timedOut {
activityState[wgKey] = true
slog.Info("", slog.String("peer", string(wgPeer.JSON())), slog.String("state", "active"))
}
}
// wait
time.Sleep(time.Duration(config.Refresh) * time.Second)
}
}