Debian Codegraph @

examples/python/gi/nm-wg-set

raw
1 #!/usr/bin/env python
2 # SPDX-License-Identifier: GPL-2.0-or-later
3 #
4 # Copyright (C) 2018 - 2019 Red Hat, Inc.
5 #
6
7 # nm-wg-set: modify an existing WireGuard connection profile.
8 #
9 # $ nm-wg-set [id|uuid|interface] ID [wg-args...]
10 #
11 # The arguments to set the parameters are like the set parameters from `man 8 wg`.
12 # For example:
13 #
14 # $ nm-wg-set wg0 peer wN8G5HpphoXOGkiXTgBPyr9BhrRm2z9JEI6BiH6fB0g= preshared-key <(wg genpsk)
15 #
16 # extra, script specific arguments:
17 # - private-key-flags
18 # - preshared-key-flags
19 #
20 # Note that the arguments have some simliarities to `wg set` command. But this
21 # script only modify the connection profile in NetworkManager. They don't (re)activate
22 # the profile and thus the changes only result in the configuration of the kernel interface
23 # after activating the profile. Use `nmcli connection up` for that.
24 #
25 # The example script does not support creating or deleting the WireGuard profile itself. It also
26 # does not support modifying other settings of the connection profile, like the IP address configuration.
27 # For that also use nmcli. For example:
28 #
29 # PROFILE=wg0
30 #
31 # # create the WireGuard profile with nmcli
32 # PRIVKEY_FILE=/tmp/wg.key
33 # (umask 077; rm -f "$PRIVKEY_FILE"; wg genkey > "$PRIVKEY_FILE")
34 # IFNAME=wg0
35 # PUBKEY=$(wg pubkey < "$PRIVKEY_FILE")
36 # IP4ADDR=192.168.99.5/24
37 # IP4GW=192.168.99.1
38 # nmcli connection delete id "$PROFILE"
39 # nmcli connection add \
40 # type wireguard \
41 # con-name "$PROFILE" \
42 # ifname "$IFNAME" \
43 # connection.stable-id "$PROFILE-$PUBKEY" \
44 # ipv4.method manual \
45 # ipv4.addresses "$IP4ADDR" \
46 # ipv4.gateway "$IP4GW" \
47 # ipv4.never-default yes \
48 # ipv6.method link-local \
49 # wireguard.listen-port 0 \
50 # wireguard.fwmark 0 \
51 # wireguard.private-key '' \
52 # wireguard.private-key-flags 0
53 # nmcli connection up \
54 # id "$PROFILE" \
55 # passwd-file <(echo "wireguard.private-key:$(cat "$PRIVKEY_FILE")")
56 #
57 # # modify the WireGuard profile with the script
58 # nm-wg-set id "$PROFILE" $WG_ARGS
59
60 import sys
61 import os
62
63 import gi
64
65 gi.require_version("NM", "1.0")
66 from gi.repository import NM
67
68
69 class MyError(Exception):
70 pass
71
72
73 def pr(v):
74 import pprint
75
76 pprint.pprint(v, indent=4, depth=5, width=60)
77
78
79 ###############################################################################
80
81
82 def connection_is_wireguard(conn):
83 s_con = conn.get_setting(NM.SettingConnection)
84 return (
85 s_con
86 and s_con.get_connection_type() == NM.SETTING_WIREGUARD_SETTING_NAME
87 and conn.get_setting(NM.SettingWireGuard)
88 )
89
90
91 def connection_to_str(conn):
92 if connection_is_wireguard(conn):
93 iface = conn.get_setting(NM.SettingConnection).get_interface_name()
94 if iface:
95 extra = ', interface: "%s"' % (iface)
96 else:
97 extra = ""
98 else:
99 extra = ", type: %s" % (
100 conn.get_setting(NM.SettingConnection).get_connection_type()
101 )
102
103 return '"%s" (%s%s)' % (conn.get_id(), conn.get_uuid(), extra)
104
105
106 def connections_wg(connections):
107 l = list([c for c in connections if connection_is_wireguard(c)])
108 l.sort(key=connection_to_str)
109 return l
110
111
112 def connections_find(connections, con_spec, con_id):
113 connections = list(sorted(connections, key=connection_to_str))
114 l = []
115 if con_spec in [None, "id"]:
116 for c in connections:
117 if con_id == c.get_id():
118 if c not in l:
119 l.append(c)
120 if con_spec in [None, "interface"]:
121 for c in connections:
122 s_con = c.get_setting(NM.SettingConnection)
123 if s_con and con_id == s_con.get_interface_name():
124 if c not in l:
125 l.append(c)
126 if con_spec in [None, "uuid"]:
127 for c in connections:
128 if con_id == c.get_uuid():
129 if c not in l:
130 l.append(c)
131 l.sort(key=connection_to_str)
132 return l
133
134
135 def print_hint(nm_client):
136 print("Maybe you want to create a profile first with")
137 print(" nmcli connection add type wireguard ifname wg0 $MORE_ARGS")
138 connections = connections_wg(nm_client.get_connections())
139 if connections:
140 print("Or edit one of the following WireGuard profiles:")
141 for c in connections:
142 print(" - %s" % (connection_to_str(c)))
143
144
145 ###############################################################################
146
147
148 def argv_get_one(argv, idx, type_ctor=None, topic=None):
149 if topic is not None:
150 try:
151 v = argv_get_one(argv, idx, type_ctor, None)
152 except MyError as e:
153 if isinstance(topic, (int, long)):
154 topic = argv[topic]
155 raise MyError('error for "%s": %s' % (topic, e.message))
156 return v
157
158 v = None
159 try:
160 v = argv[idx]
161 except:
162 raise MyError("missing argument")
163 if type_ctor is not None:
164 try:
165 v = type_ctor(v)
166 except Exception as e:
167 raise MyError('invalid argument "%s" (%s)' % (v, e.message))
168 return v
169
170
171 ###############################################################################
172
173
174 def arg_parse_secret_flags(arg):
175 try:
176 f = arg.strip()
177 n = {
178 "none": NM.SettingSecretFlags.NONE,
179 "not-saved": NM.SettingSecretFlags.NOT_SAVED,
180 "not-required": NM.SettingSecretFlags.NOT_REQUIRED,
181 "agent-owned": NM.SettingSecretFlags.AGENT_OWNED,
182 }.get(f)
183 if n is not None:
184 return n
185 return NM.SettingSecretFlags(int(f))
186 except Exception as e:
187 raise MyError('invalid secret flags "%s"' % (arg))
188
189
190 def _arg_parse_int(arg, vmin, vmax, key, base=0):
191 try:
192 v = int(arg, base)
193 if v >= vmin and vmax <= 0xFFFFFFFF:
194 return v
195 except:
196 raise MyError('invalid %s "%s"' % (key, arg))
197 raise MyError("%s out of range" % (key))
198
199
200 def arg_parse_listen_port(arg):
201 return _arg_parse_int(arg, 0, 0xFFFF, "listen-port")
202
203
204 def arg_parse_fwmark(arg):
205 return _arg_parse_int(arg, 0, 0xFFFFFFFF, "fwmark", base=0)
206
207
208 def arg_parse_persistent_keep_alive(arg):
209 return _arg_parse_int(arg, 0, 0xFFFFFFFF, "persistent-keepalive")
210
211
212 def arg_parse_allowed_ips(arg):
213 l = [s.strip() for s in arg.strip().split(",")]
214 l = [s for s in l if s != ""]
215 l = list(l)
216 # use a peer to parse and validate the allowed-ips.
217 peer = NM.WireGuardPeer()
218 for aip in l:
219 if not peer.append_allowed_ip(aip, False):
220 raise MyError('invalid allowed-ip "%s"' % (aip))
221 return l
222
223
224 ###############################################################################
225
226
227 def secret_flags_to_string(flags):
228 nick = {
229 NM.SettingSecretFlags.NONE: "none",
230 NM.SettingSecretFlags.NOT_SAVED: "not-saved",
231 NM.SettingSecretFlags.NOT_REQUIRED: "not-required",
232 NM.SettingSecretFlags.AGENT_OWNED: "agent-owned",
233 }.get(flags)
234 num = str(int(flags))
235 if nick is None:
236 return num
237 return "%s (%s)" % (num, nick)
238
239
240 def secret_to_string(secret):
241 if os.environ.get("WG_HIDE_KEYS", "") != "never":
242 return "(hidden)"
243 if not secret:
244 return ""
245 return secret
246
247
248 def val_to_str(val):
249 if val == NM.Ternary.DEFAULT:
250 return "default"
251 if val == NM.Ternary.TRUE:
252 return "true"
253 if val == NM.Ternary.FALSE:
254 return "false"
255 return repr(val)
256
257
258 ###############################################################################
259
260
261 def wg_read_private_key(privkey_file):
262 import base64
263
264 try:
265 with open(privkey_file, "r") as f:
266 data = f.read()
267 bdata = base64.decodestring(data)
268 if len(bdata) != 32:
269 raise Exception("not 32 bytes base64 encoded")
270 return base64.encodestring(bdata).strip()
271 except Exception as e:
272 raise MyError('failed to read private key "%s": %s' % (privkey_file, e.message))
273
274
275 def wg_peer_is_valid(peer, msg=None):
276 try:
277 peer.is_valid(True, True)
278 except gi.repository.GLib.Error as e:
279 if msg is None:
280 raise MyError("%s" % (e.message))
281 else:
282 raise MyError("%s" % (msg))
283
284
285 ###############################################################################
286
287
288 def do_get(nm_client, connection):
289 s_con = conn.get_setting(NM.SettingConnection)
290 s_wg = conn.get_setting(NM.SettingWireGuard)
291
292 # Fetching secrets is not implemented. For now show them all as
293 # <hidden>.
294
295 print("interface: %s" % (s_con.get_interface_name()))
296 print("uuid: %s" % (conn.get_uuid()))
297 print("id: %s" % (conn.get_id()))
298 print(
299 "private-key: %s" % (secret_to_string(s_wg.get_private_key()))
300 )
301 print(
302 "private-key-flags: %s"
303 % (secret_flags_to_string(s_wg.get_private_key_flags()))
304 )
305 print("listen-port: %s" % (s_wg.get_listen_port()))
306 print("fwmark: 0x%x" % (s_wg.get_fwmark()))
307 print("peer-routes: %s" % (val_to_str(s_wg.get_peer_routes())))
308 print(
309 "ip4-auto-default-route: %s"
310 % (val_to_str(s_wg.get_ip4_auto_default_route()))
311 )
312 print(
313 "ip6-auto-default-route: %s"
314 % (val_to_str(s_wg.get_ip6_auto_default_route()))
315 )
316 for i in range(s_wg.get_peers_len()):
317 peer = s_wg.get_peer(i)
318 print("peer[%d].public-key: %s" % (i, peer.get_public_key()))
319 print(
320 "peer[%d].preshared-key: %s"
321 % (i, secret_to_string(peer.get_preshared_key()))
322 )
323 print(
324 "peer[%d].preshared-key-flags: %s"
325 % (i, secret_flags_to_string(peer.get_preshared_key_flags()))
326 )
327 print(
328 "peer[%d].endpoint: %s"
329 % (i, peer.get_endpoint() if peer.get_endpoint() else "")
330 )
331 print(
332 "peer[%d].persistent-keepalive: %s" % (i, peer.get_persistent_keepalive())
333 )
334 print(
335 "peer[%d].allowed-ips: %s"
336 % (
337 i,
338 ",".join(
339 [peer.get_allowed_ip(j) for j in range(peer.get_allowed_ips_len())]
340 ),
341 )
342 )
343
344
345 def do_set(nm_client, conn, argv):
346 s_wg = conn.get_setting(NM.SettingWireGuard)
347 peer = None
348 peer_remove = False
349 peer_idx = None
350 peer_secret_flags = None
351
352 try:
353 idx = 0
354 while True:
355 if peer and (idx >= len(argv) or argv[idx] == "peer"):
356 if peer_remove:
357 pp_peer, pp_idx = s_wg.get_peer_by_public_key(peer.get_public_key())
358 if pp_peer:
359 s_wg.remove_peer(pp_idx)
360 else:
361 if peer_secret_flags is not None:
362 peer.set_preshared_key_flags(peer_secret_flags)
363 wg_peer_is_valid(peer)
364 if peer_idx is None:
365 s_wg.append_peer(peer)
366 else:
367 s_wg.set_peer(peer, peer_idx)
368 peer = None
369 peer_remove = False
370 peer_idx = None
371 peer_secret_flags = None
372
373 if idx >= len(argv):
374 break
375
376 if not peer and argv[idx] == "private-key":
377 key = argv_get_one(argv, idx + 1, None, idx)
378 if key == "":
379 s_wg.set_property(NM.SETTING_WIREGUARD_PRIVATE_KEY, None)
380 else:
381 s_wg.set_property(
382 NM.SETTING_WIREGUARD_PRIVATE_KEY, wg_read_private_key(key)
383 )
384 idx += 2
385 continue
386 if not peer and argv[idx] == "private-key-flags":
387 s_wg.set_property(
388 NM.SETTING_WIREGUARD_PRIVATE_KEY_FLAGS,
389 argv_get_one(argv, idx + 1, arg_parse_secret_flags, idx),
390 )
391 idx += 2
392 continue
393 if not peer and argv[idx] == "listen-port":
394 s_wg.set_property(
395 NM.SETTING_WIREGUARD_LISTEN_PORT,
396 argv_get_one(argv, idx + 1, arg_parse_listen_port, idx),
397 )
398 idx += 2
399 continue
400 if not peer and argv[idx] == "fwmark":
401 s_wg.set_property(
402 NM.SETTING_WIREGUARD_FWMARK,
403 argv_get_one(argv, idx + 1, arg_parse_fwmark, idx),
404 )
405 idx += 2
406 continue
407 if argv[idx] == "peer":
408 public_key = argv_get_one(argv, idx + 1, None, idx)
409 peer, peer_idx = s_wg.get_peer_by_public_key(public_key)
410 if peer:
411 peer = peer.new_clone(True)
412 else:
413 peer_idx = None
414 peer = NM.WireGuardPeer()
415 peer.set_public_key(public_key, True)
416 wg_peer_is_valid(peer, 'public key "%s" is invalid' % (public_key))
417 peer_remove = False
418 idx += 2
419 continue
420 if peer and argv[idx] == "remove":
421 peer_remove = True
422 idx += 1
423 continue
424 if peer and argv[idx] == "preshared-key":
425 psk = argv_get_one(argv, idx + 1, None, idx)
426 if psk == "":
427 peer.set_preshared_key(None, True)
428 if peer_secret_flags is not None:
429 peer_secret_flags = NM.SettingSecretFlags.NOT_REQUIRED
430 else:
431 peer.set_preshared_key(wg_read_private_key(psk), True)
432 if peer_secret_flags is not None:
433 peer_secret_flags = NM.SettingSecretFlags.NONE
434 idx += 2
435 continue
436 if peer and argv[idx] == "preshared-key-flags":
437 peer_secret_flags = argv_get_one(
438 argv, idx + 1, arg_parse_secret_flags, idx
439 )
440 idx += 2
441 continue
442 if peer and argv[idx] == "endpoint":
443 peer.set_endpoint(argv_get_one(argv, idx + 1, None, idx), True)
444 idx += 2
445 continue
446 if peer and argv[idx] == "persistent-keepalive":
447 peer.set_persistent_keepalive(
448 argv_get_one(argv, idx + 1, arg_parse_persistent_keep_alive, idx)
449 )
450 idx += 2
451 continue
452 if peer and argv[idx] == "allowed-ips":
453 allowed_ips = list(
454 argv_get_one(argv, idx + 1, arg_parse_allowed_ips, idx)
455 )
456 peer.clear_allowed_ips()
457 for aip in allowed_ips:
458 peer.append_allowed_ip(aip, False)
459 del allowed_ips
460 idx += 2
461 continue
462
463 raise MyError('invalid argument "%s"' % (argv[idx]))
464 except MyError as e:
465 print("Error: %s" % (e.message))
466 sys.exit(1)
467
468 try:
469 conn.commit_changes(True, None)
470 except Exception as e:
471 print("failure to commit connection: %s" % (e))
472 sys.exit(1)
473
474 print("Success")
475 sys.exit(0)
476
477
478 ###############################################################################
479
480 if __name__ == "__main__":
481 nm_client = NM.Client.new(None)
482
483 argv = sys.argv
484 del argv[0]
485
486 con_spec = None
487 if len(argv) >= 1:
488 if argv[0] in ["id", "uuid", "interface"]:
489 con_spec = argv[0]
490 del argv[0]
491
492 if len(argv) < 1:
493 print(
494 "Requires an existing NetworkManager connection profile as first argument"
495 )
496 print(
497 "Select it based on the connection ID, UUID, or interface-name (optionally qualify the selection with [id|uuid|interface])"
498 )
499 print_hint(nm_client)
500 sys.exit(1)
501 con_id = argv[0]
502 del argv[0]
503
504 connections = connections_find(nm_client.get_connections(), con_spec, con_id)
505 if len(connections) == 0:
506 print(
507 'No matching connection %s"%s" found.'
508 % ((con_spec + " " if con_spec else ""), con_id)
509 )
510 print_hint(nm_client)
511 sys.exit(1)
512 if len(connections) > 1:
513 print(
514 'Connection %s"%s" is not unique (%s)'
515 % (
516 (con_spec + " " if con_spec else ""),
517 con_id,
518 ", ".join(["[" + connection_to_str(c) + "]" for c in connections]),
519 )
520 )
521 if not con_spec:
522 print("Maybe qualify the name with [id|uuid|interface]?")
523 sys.exit(1)
524
525 conn = connections[0]
526 if not connection_is_wireguard(conn):
527 print("Connection %s is not a WireGuard profile" % (connection_to_str(conn)))
528 print("See available profiles with `nmcli connection show`")
529 sys.exit(1)
530
531 try:
532 secrets = conn.get_secrets(NM.SETTING_WIREGUARD_SETTING_NAME)
533 if secrets:
534 conn.update_secrets(NM.SETTING_WIREGUARD_SETTING_NAME, secrets)
535 except Exception:
536 pass
537
538 if not argv:
539 do_get(nm_client, conn)
540 else:
541 do_set(nm_client, conn, argv)