-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwireguard.py
More file actions
220 lines (192 loc) · 6.51 KB
/
Copy pathwireguard.py
File metadata and controls
220 lines (192 loc) · 6.51 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
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
"""Monitor WireGuard connectivity and expose its status to Prometheus."""
import json
import logging
import subprocess
import time
import click
from prometheus_client import Gauge, start_http_server
from config_manager import new_config
from hard_stop import stop_fastd, stop_wg
from inform_admin import send_mail
WIREGUARD_INTERFACE = "exit"
FASTD_SERVICE = "ffsh"
CURL_RETRIES = 3
CURL_RETRY_DELAY = 2
wireguard_up = Gauge(
"wireguard_up", "Whether the WireGuard connection is up", ["interface"]
)
def is_service_running(service_name):
"""Return whether the configured FastD service is running."""
result = subprocess.run(
[
"sudo",
"systemctl",
"show",
"-p",
"SubState",
f"fastd@{service_name}.service",
],
capture_output=True,
text=True,
check=False,
)
return result.stdout.strip() == "SubState=running"
def test_interface(interface_name):
"""Returns True if interface is ok, returns False if interface is not ok."""
curl_cmd = [
"curl",
"--connect-timeout",
"15",
"--interface",
interface_name,
"https://am.i.mullvad.net/json",
]
data = None
for attempt in range(1, CURL_RETRIES + 1):
try:
result = subprocess.run(
curl_cmd, capture_output=True, text=True, check=True
)
data = json.loads(result.stdout)
break
except subprocess.CalledProcessError as e:
logging.error(
"Curl could not connect to Mullvad (attempt %d/%d), "
"returncode=%s, stderr=%s",
attempt,
CURL_RETRIES,
e.returncode,
e.stderr,
)
except json.JSONDecodeError as e:
logging.error(
"Curl returned invalid json (attempt %d/%d): %s, stdout=%s",
attempt,
CURL_RETRIES,
e,
result.stdout,
)
if attempt < CURL_RETRIES:
time.sleep(CURL_RETRY_DELAY)
if data is None:
logging.error(
"Curl could not connect to Mullvad or json was not valid after %d attempts",
CURL_RETRIES,
)
return False
try:
connected = data["mullvad_exit_ip"] is True
except KeyError:
# something went wrong the json did not contain mullvad_exit_ip
logging.error("mullvad_exit_ip was not in the json")
return False
if connected:
logging.info("Everything ok.")
return True
logging.error("Mullvad says we are not connected to Mullvad")
return False
def verify(interface_name, fastd_name, mail_config):
"""Check the connection and attempt recovery once if it is down."""
result = test_interface(interface_name)
if result is False:
# connection not ok
logging.warning("Connection via vpn not ok, generating new config")
new_config(interface_name)
result = test_interface(interface_name)
if result is False:
logging.error("New config did not help, stop fastd")
stop_fastd(fastd_name)
stop_wg(interface_name)
send_mail(
mail_config,
"VPN connection did not work, new VPN config did not help.\n"
"Fastd and wireguard stopped.",
)
return result
def run_check(
mail_config, interface_name=WIREGUARD_INTERFACE, fastd_name=FASTD_SERVICE
):
"""Run one health cycle and return the resulting up/down state."""
if is_service_running(service_name=fastd_name):
return verify(
interface_name=interface_name,
fastd_name=fastd_name,
mail_config=mail_config,
)
logging.info("Fastd service is down, not checking connection")
return False
def configure_logging(log, loglevel=logging.INFO):
"""Create the log file if needed and configure application logging."""
try:
with open(log, "x", encoding="utf-8"):
pass
except FileExistsError:
pass
logging.basicConfig(
format="%(asctime)s %(levelname)-8s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
filename=log,
encoding="utf-8",
level=loglevel,
)
def build_mail_config(user, password):
"""Build the mail settings used by the recovery alert."""
return {
"target": "noc@freifunk-suedholstein.de",
"host": "mail.freifunk-suedholstein.de",
"port": "465",
"user": user,
"password": password,
}
@click.group()
def cli():
"""WireGuard monitoring commands."""
@cli.command()
@click.option("--user", help="Mail address", required=True)
@click.option("--password", help="Password for Mail Address", required=True)
@click.option("--log", help="Path to log file", required=True)
@click.option(
"--loglevel",
type=click.Choice(["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]),
default="INFO",
show_default=True,
)
def check(user, password, log, loglevel):
"""Check the status of the WireGuard interface once."""
configure_logging(log, getattr(logging, loglevel))
run_check(build_mail_config(user, password))
@cli.command()
@click.option("--user", help="Mail address", required=True)
@click.option("--password", help="Password for Mail Address", required=True)
@click.option("--log", help="Path to log file", required=True)
@click.option(
"--loglevel",
type=click.Choice(["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]),
default="INFO",
show_default=True,
)
@click.option("--interval", type=float, default=60.0, show_default=True)
@click.option("--host", default="127.0.0.1", show_default=True)
@click.option("--port", type=int, default=8000, show_default=True)
def serve(**kwargs):
"""Run checks and expose the latest WireGuard status as Prometheus metrics."""
user = kwargs["user"]
password = kwargs["password"]
log = kwargs["log"]
loglevel = kwargs["loglevel"]
interval = kwargs["interval"]
host = kwargs["host"]
port = kwargs["port"]
configure_logging(log, getattr(logging, loglevel))
start_http_server(port, addr=host)
config = build_mail_config(user, password)
try:
while True:
wireguard_up.labels(interface=WIREGUARD_INTERFACE).set(
1 if run_check(config) else 0
)
time.sleep(interval)
except KeyboardInterrupt:
logging.info("Stopping WireGuard metrics server")
if __name__ == "__main__":
cli()