-
Notifications
You must be signed in to change notification settings - Fork 1
/
ziti_router_auto_enroll.py
executable file
·2038 lines (1798 loc) · 77.1 KB
/
ziti_router_auto_enroll.py
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
Ziti Router Automated Enrollment
"""
import sys
import time
from urllib.parse import urlparse
import argparse
import tarfile
import socket
import os
import logging
import json
import subprocess
import platform
import ipaddress
import yaml
import distro
import psutil
from packaging.version import Version
from tqdm import tqdm
import jwt
from colorama import Fore, Style, init
from jinja2 import Template
import requests
import urllib3
CONFIG_TEMPLATE_STRING = ("""v: 3
identity:
cert: {{ identity.cert }}
server_cert: {{ identity.server_cert }}
key: {{ identity.key }}
ca: {{ identity.ca }}
ctrl:
endpoint: {{ ctrl.endpoint }}
{%- if ha %}
ha:
enabled: true
{%- endif %}
{%- if proxy %}
proxy:
type: {{ proxy.proxy_type }}
address: {{ proxy.address }}:{{ proxy.port}}
{%- endif %}
link:
dialers:
{%- for dialer in link_dialers %}
- binding: {{ dialer.binding }}
{%- if dialer.bind is defined %}
bind: {{ dialer.bind }}
{%- endif %}
{%- endfor %}
{%- if link_listeners %}
listeners:
{%- endif %}
{%- for listener in link_listeners %}
- binding: {{ listener.binding }}
bind: {{ listener.bind }}
advertise: {{ listener.advertise }}
{%- if listener.options is defined %}
options:
{%- if listener.options.outqueuesize is defined %}
outQueueSize: {{ listener.options.outqueuesize }}
{%- endif %}
{%- endif %}
{%- endfor %}
{%- if healthChecks is defined %}
healthChecks:
{%- if healthChecks.ctrlPingCheck is defined %}
ctrlPingCheck:
interval: {{ healthChecks.ctrlPingCheck.interval }}
timeout: {{ healthChecks.ctrlPingCheck.timeout }}
initialDelay: {{ healthChecks.ctrlPingCheck.initialDelay }}
{%- endif %}
{%- if healthChecks.linkCheck is defined %}
linkCheck:
minLinks: {{ healthChecks.linkCheck.minLinks }}
interval: {{ healthChecks.linkCheck.interval }}
initialDelay: {{ healthChecks.linkCheck.initialDelay }}
{%- endif %}
{%- endif %}
{%- if metrics is defined %}
metrics:
reportInterval: {{ metrics.reportInterval }}
messageQueueSize: {{ metrics.messageQueueSize }}
{%- endif %}
{%- if edge is defined %}
edge:
{%- if edge.heartbeatIntervalSeconds is defined %}
heartbeatIntervalSeconds: {{ edge.heartbeatIntervalSeconds }}
{%- endif %}
csr:
country: {{ edge.csr.country }}
province: {{ edge.csr.province }}
locality: {{ edge.csr.locality }}
organization: {{ edge.csr.organization }}
organizationalUnit: {{ edge.csr.organizationalUnit }}
sans:
{%- if edge.csr.sans.dns is defined %}
dns:
{%- for dns in edge.csr.sans.dns %}
- {{ dns }}
{%- endfor %}
{%- endif %}
{%- if edge.csr.sans.email is defined %}
email:
{%- for email in edge.csr.sans.email %}
- {{ email }}
{%- endfor %}
{%- endif %}
{%- if edge.csr.sans.ip is defined %}
ip:
{%- for ip in edge.csr.sans.ip %}
- {{ ip }}
{%- endfor %}
{%- endif %}
{%- if edge.csr.sans.uri is defined %}
uri:
{%- for uri in edge.csr.sans.uri %}
- {{ uri }}
{%- endfor %}
{%- endif %}
{%- endif %}
{%- if apiProxy is defined %}
apiProxy:
listener: {{ apiProxy.listener }}
upstream: {{ apiProxy.upstream }}
{%- endif %}
{%- if listeners is defined %}
listeners:
{%- endif %}
{%- for listener in listeners %}
- binding: {{ listener.binding }}
{%- if listener.address is defined %}
address: {{ listener.address }}
{%- endif %}
{%- if listener.service is defined %}
service: {{ listener.service }}
{%- endif %}
{%- if listener.options is defined %}
options:
{%- if listener.options.advertise is defined %}
advertise: {{ listener.options.advertise }}
{%- endif %}
{%- if listener.options.maxQueuedConnects is defined %}
maxQueuedConnects: {{ listener.options.maxQueuedConnects }}
{%- endif %}
{%- if listener.options.maxOutstandingConnects is defined %}
maxOutstandingConnects: {{ listener.options.maxOutstandingConnects }}
{%- endif %}
{%- if listener.options.connectTimeoutMs is defined %}
connectTimeoutMs: {{ listener.options.connectTimeoutMs }}
{%- endif %}
{%- if listener.options.lookupApiSessionTimeout is defined %}
lookupApiSessionTimeout: {{ listener.options.lookupApiSessionTimeout }}
{%- endif %}
{%- if listener.options.mode is defined %}
mode: {{ listener.options.mode }}
{%- endif %}
{%- if listener.options.resolver is defined %}
resolver: {{ listener.options.resolver }}
{%- endif %}
{%- if listener.options.lanIf is defined %}
lanIf: {{ listener.options.lanIf }}
{%- endif %}
{%- if listener.options.dnsSvcIpRange is defined %}
dnsSvcIpRange: {{ listener.options.dnsSvcIpRange }}
{%- endif %}
{%- endif %}
{%- endfor %}
{%- if webs is defined %}
web:
{%- for web in webs %}
- name: {{ web.name }}
bindPoints:
- interface: {{ web.bindpoints.interface }}
address: {{ web.bindpoints.address }}
apis:
- binding: {{ web.apis.binding }}
{%- endfor %}
{%- endif %}""")
SYSTEMD_UNIT_TEMPLATE_STRING =("""
[Unit]
Description=Ziti-Router
After=network.target
[Service]
User=root
WorkingDirectory={{ install_dir }}
ExecStartPre=-/usr/sbin/iptables -F NF-INTERCEPT -t mangle
{% if single_binary -%}
ExecStart={{ install_dir }}/ziti router run {{ install_dir }}/config.yml
{%- else -%}
ExecStart={{ install_dir }}/ziti-router run {{ install_dir }}/config.yml
{%- endif %}
Restart=always
RestartSec=2
LimitNOFILE=65535
AmbientCapabilities=CAP_NET_BIND_SERVICE
SyslogIdentifier=ziti-router
[Install]
WantedBy=multi-user.target
"""
)
def add_general_arguments(parser, version):
"""
Add general arguments to the parser.
:param parser: The argparse.ArgumentParser instance to add the arguments to.
:param version: The version string for the --version argument.
"""
parser.add_argument('enrollment_jwt', nargs='?',
help='Enrollment JWT String')
parser.add_argument('-j','--jwt', type=str,
help='Path to file based jwt')
parser.add_argument('-p', '--printConfig',
action="store_true",
help='Print the generated configuration and exit')
parser.add_argument('-t', '--printTemplate',
action="store_true",
help='Print the jinja template used to create the config and exit')
parser.add_argument('-n', '--noHostname',
action='store_true',
help='Dont use hostnames only IP addresses for auto generated config')
parser.add_argument('-f', '--force',
action="store_false",
help='Forcefully proceed with re-enrollment',
default=True)
parser.add_argument('-l', '--logLevel', type=str,
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
default='INFO', help='Set the logging level - Default: INFO)')
parser.add_argument('-v', '--version',
action='version',
version=version)
def add_install_arguments(parser):
"""
Add install options arguments to the parser.
:param parser: The argparse.ArgumentParser instance to add the arguments to.
"""
install_config = parser.add_argument_group('Install options')
install_config.formatter_class = argparse.ArgumentDefaultsHelpFormatter
install_config.add_argument('--logFile', type=str,
help='Specify the log file -'
'Default {cwd}/{program_name}}.log')
install_config.add_argument('--parametersFile', type=str,
help='File containing all parameters - json or yaml')
install_config.add_argument('--installDir', type=str,
help='Installation directory for Openziti - '
'Default /opt/openziti/ziti-router',
default='/opt/openziti/ziti-router')
install_config.add_argument('--installVersion', type=str,
help='Install specific version - '
'Default is to match Controller')
install_config.add_argument('--downloadUrl', type=str,
help='Bundle download url - '
'Default https://github.com/openziti/ziti/releases/latest/')
install_config.add_argument('--skipSystemd',
action='store_true',
help='Skip systemd installation',
default=False)
def add_router_identity_arguments(parser):
"""
Add identity options arguments to the parser.
:param parser: The argparse.ArgumentParser instance to add the arguments to.
"""
router_identity_config_group = parser.add_argument_group('Router Identity Paths')
router_identity_config_group.add_argument('--identityCert', type=str,
help='Path to certificate - '
'Default {installDir}/certs/cert.pem')
router_identity_config_group.add_argument('--identityServerCert', type=str,
help='Path to server chain - '
'Default {installDir}/certs/server_cert.pem')
router_identity_config_group.add_argument('--identityKey', type=str,
help='Path to key file - '
'Default {installDir}/certs/key.pem')
router_identity_config_group.add_argument('--identityCa', type=str,
help='Path to ca chain - '
'Default {installDir}}/certs/ca.pem')
def add_router_ctrl_arguments(parser):
"""
Add ctrl options arguments to the parser.
:param parser: The argparse.ArgumentParser instance to add the arguments to.
"""
router_ctrl_config_group = parser.add_argument_group('Controller Options')
router_ctrl_config_group.add_argument('--controller',type=str,
help='Hostname or IP of Openziti controller')
router_ctrl_config_group.add_argument('--controllerFabricPort',type=int,
help='Controller Fabric Port'
'Default 80',
default=80)
router_ctrl_config_group.add_argument('--controllerMgmtPort',type=int,
help='Controller Management Port'
'Default 443',
default=443)
def add_router_proxy_arguments(parser):
"""
Add proxy options arguments to the parser.
:param parser: The argparse.ArgumentParser instance to add the arguments to.
"""
router_proxy_config_group = parser.add_argument_group('Proxy Options')
router_proxy_config_group.add_argument('--proxyType',type=str,
help='Proxy type '
'Default http',
default="http")
router_proxy_config_group.add_argument('--proxyAddress',type=str,
help='Proxy Address '
'Default None')
router_proxy_config_group.add_argument('--proxyPort',type=int,
help='Proxy Port'
'Default 3128 ',
default=3128)
def add_router_health_checks_arguments(parser):
"""
Add health checks options arguments to the parser.
:param parser: The argparse.ArgumentParser instance to add the arguments to.
"""
router_health_checks_group = parser.add_argument_group('HealthCheck Options')
router_health_checks_group.add_argument('--disableHealthChecks',
action='store_false',
help='Disable HealthChecks',
default=True)
router_health_checks_group.add_argument('--ctrlPingCheckInterval', type=int, default=30,
help='How often to ping the controller - '
'Default 30')
router_health_checks_group.add_argument('--ctrlPingCheckTimeout', type=int, default=15,
help='Timeout the ping - '
'Default 15')
router_health_checks_group.add_argument('--ctrlPingCheckInitialDelay', type=int, default=15,
help='How long to wait before pinging the controller - '
'Default 15')
router_health_checks_group.add_argument('--linkCheckMinLinks', type=int, default=1,
help='Number of links required for the'
'health check to be passing.'
'Default 1')
router_health_checks_group.add_argument('--linkCheckInterval', type=int, default=5,
help='How often to check the link count'
'Default 5')
router_health_checks_group.add_argument('--linkCheckInitialDelay', type=int, default=5,
help='How long to wait before running the first check'
'Default 5')
def add_router_metrics_arguments(parser):
"""
Add metrics options arguments to the parser.
:param parser: The argparse.ArgumentParser instance to add the arguments to.
"""
router_metrics_group = parser.add_argument_group('Metrics Options')
router_metrics_group.add_argument('--reportInterval',type=int,
help='Reporting Interval - '
'Default 60')
router_metrics_group.add_argument('--messageQueueSize',type=int,
help='Message Queue Size - '
'Default 10')
def add_router_edge_arguments(parser):
"""
Add edge options arguments to the parser.
:param parser: The argparse.ArgumentParser instance to add the arguments to.
"""
router_edge_config_group = parser.add_argument_group('Edge Options')
router_edge_config_group.add_argument('--disableEdge',
action='store_false',
help="Disable the Edge",
default=True)
router_edge_config_group.add_argument('--heartbeatIntervalSeconds',
help='Edge heartbeatInterval in Seconds - '
'Default 60',
default=60,
type=int)
router_edge_config_group.add_argument('--csrCountry',
help='Country in certificate - '
'Default US',
default='US')
router_edge_config_group.add_argument('--csrProvince',
help='Province in certificate - '
'Default NC',
default='NC')
router_edge_config_group.add_argument('--csrLocality',
help='Locality in certificate - '
'Default Charlotte',
default='Charlotte')
router_edge_config_group.add_argument('--csrOrganization',
help='Organization in certificate - '
'Default NetFoundry',
default='NetFoundry')
router_edge_config_group.add_argument('--csrOrganizationalUnit',
help='OrganizationalUnit in certificate -'
'Default Ziti',
default='Ziti')
router_edge_config_group.add_argument('--csrSansEmail',
action='append',
help='SANS Email')
router_edge_config_group.add_argument('--csrSansDns',
action='append',
help='List of SANS DNS names')
router_edge_config_group.add_argument('--csrSansIp',
action='append',
help='List of SANS IP Addresses')
router_edge_config_group.add_argument('--csrSansUri',
action='append',
help='List of SANS URIs')
def add_router_api_proxy_arguments(parser):
"""
Add api proxy options arguments to the parser.
:param parser: The argparse.ArgumentParser instance to add the arguments to.
"""
router_proxy_config = parser.add_argument_group('API Proxy')
router_proxy_config.add_argument('--apiProxyListener', default=[],
help='ProxyListener')
router_proxy_config.add_argument('--apiProxyUpstream', default=[],
help='ProxyUpstream')
def add_router_fabric_link_arguments(parser):
"""
Add fabric link options arguments to the parser.
:param parser: The argparse.ArgumentParser instance to add the arguments to.
"""
router_fabric_link_group = parser.add_argument_group('Link Options')
router_fabric_link_group.add_argument('--linkDialers',
action='append',
nargs='+',
metavar=('BINDING BIND'),
help='Link Dialers - '
'Default \'transport\'')
router_fabric_link_group.add_argument('--linkListeners',
action='append',
nargs='+',
metavar=('BINDING BIND ADVERTISE OUTQUESIZE'),
help='Link Listener - '
'Default None')
def add_router_listener_arguments(parser):
"""
Add listner options arguments to the parser.
:param parser: The argparse.ArgumentParser instance to add the arguments to.
"""
router_listener_group = parser.add_argument_group('Listeners Options')
router_listener_group.add_argument('--disableListeners',
action='store_false',
help='Disable Listeners',
default=True)
router_listener_group.add_argument('--assumePublic',
action='store_true',
help='Attempt to use external '
'lookup to assign default edge listener '
'instead of {default_gw_adapter}')
router_listener_group.add_argument('--edgeListeners',
action='append',
nargs='+',
metavar=('ADDRESS ADVERTISE '
'MAXQUEUEDCONNECTS '
'MAXOUTSTANDINGCONNECTS '
'CONNECTTIMEOUTMS '
'LOOKUPAPISESSIONTIMEOUT'),
help='Edge Binding Listener - '
'Default \'edge\' '
'\'tls:0.0.0.0:443\' '
'\'{default_gw_adapter}:443\'')
router_listener_group.add_argument('--proxyListeners',
action='append',
nargs=2,
metavar=('ADDRESS','SERVICE'),
help='Proxy Binding Listener - '
'Default None')
router_listener_group.add_argument('--tunnelListener',
nargs='+',
metavar=('MODE RESOLVER LANIF DNSSVCIPRANGE'),
help='Tunnel Binding Listener - '
'Default None')
router_listener_group.add_argument('--autoTunnelListener',
action='store_true',
help='Automatically add a local tproxy tunneler '
'with the {default_gw_adapter} as the local resolver '
'and LANIf',
default=False)
router_listener_group.add_argument('--skipDNS',
action='store_true',
help='Skip DNS configuration',
default=False)
def add_router_web_arguments(parser):
"""
Add web options arguments to the parser.
:param parser: The argparse.ArgumentParser instance to add the arguments to.
"""
router_web_group = parser.add_argument_group('Web Options')
router_web_group.formatter_class = argparse.ArgumentDefaultsHelpFormatter
router_web_group.add_argument('--webs',
action='append',
nargs='+',
metavar=('NAME INTERFACE ADDRESS BINDING'),
help=('Web Options - '
'Default \'health-check\' '
'\'0.0.0.0:8081\' '
'\'0.0.0.0:8081\' '
'\'health-checks\''))
def add_create_router_arguments(parser):
"""
Add create options arguments to the parser.
:param parser: The argparse.ArgumentParser instance to add the arguments to.
"""
create_router_group = parser.add_argument_group(
'Router Creation Options: '
'Create new router on the controller before enrollment')
create_router_group.add_argument('--adminUser',type=str,
help="Openziti Admin username")
create_router_group.add_argument('--adminPassword',type=str,
help='Openziti Admin passowrd')
create_router_group.add_argument('--routerName',type=str,
help='Router name created in controller')
def add_router_ha_arguments(parser):
"""
Add ha option argument to the parser.
:param parser: The argparse.ArgumentParser instance to add the arguments to.
"""
router_ha_group = parser.add_argument_group("HA")
router_ha_group.add_argument('--ha',
action='store_true',
help="Enable ha flag")
def check_root_permissions():
"""
Check to see if this is running as root privileges & exit if not.
"""
if os.geteuid() >= 1:
print("\033[0;31mERROR:\033[0m This script must be run with elevated privileges, "
"please use 'sudo -E' or run as root")
sys.exit(1)
def check_env_vars(args, parser):
"""
Sets argparse argument values based on environment variables with matching names.
:args:args (argparse.Namespace): A Namespace object containing the parsed arguments.
"""
for arg in vars(args):
env_name = arg.upper()
env_value = os.environ.get(env_name)
if env_value is not None:
current_argument = getattr(args, arg)
if current_argument == parser.get_default(arg) or current_argument is None:
if ',' in env_value:
value = env_value.split(',')
else:
value = env_value
setattr(args, arg, value)
else:
logging.warning("Overriding Environmental value"
" for %s, with value set via cli", arg)
def check_iptables(args):
"""
Check if the 'iptables' executable is installed on the system by searching
for it in the directories listed in the system's PATH environment variable.
If 'iptables' is not found, print an error message and exit the script with
an exit code of 1.
"""
logging.debug("Checking for iptables")
def is_executable_file(file_path):
return os.path.isfile(file_path) and os.access(file_path, os.X_OK)
iptables_installed = False
system_path = os.environ.get('PATH', '').split(os.pathsep)
for path_dir in system_path:
iptables_path = os.path.join(path_dir, 'iptables')
if is_executable_file(iptables_path):
iptables_installed = True
logging.debug("Found iptables: %s", iptables_path)
break
if not iptables_installed:
if args.printConfig:
logging.warning("Unable to find iptables. "
"This configuration is invalid, tproxy requires iptables")
else:
logging.error("Unable to find iptables. Unable to continue enrollment")
sys.exit(1)
def check_parameters_file(args, parser):
"""
Sets argparse argument values based on values in a YAML or JSON file.
:args:args (argparse.Namespace): A Namespace object containing the parsed arguments.
"""
if not os.path.exists(args.parametersFile):
logging.error("Unable to open file: %s", args.parametersFile)
sys.exit(1)
logging.debug("Attempting to open parameters file: %s", args.parametersFile)
with open(args.parametersFile, encoding='UTF-8') as open_file:
if args.parametersFile.endswith('.json'):
logging.debug("Found json file, trying to open.")
try:
config = json.load(open_file)
except json.JSONDecodeError as error:
logging.error("Unable to decode Json file: %s", error)
sys.exit(1)
elif args.parametersFile.endswith('.yaml') or args.parametersFile.endswith('.yml'):
logging.debug("Found yaml file, trying to open.")
try:
config = yaml.safe_load(open_file)
except yaml.YAMLError as error:
logging.error("Unable to decode Yaml file: %s", error)
sys.exit(1)
else:
logging.error("File format not supported: %s", args.parametersFile)
sys.exit(1)
for arg in vars(args):
if arg in config:
current_argument = getattr(args, arg)
if current_argument == parser.get_default(arg) or current_argument is None:
setattr(args, arg, config[arg])
else:
logging.warning("Overriding parameter file value for %s,"
" with value set via cli", arg)
def cleanup_previous_versions(args):
"""
Removes previous ziti binaries that are present in the system
:args:args (argparse.Namespace): A Namespace object containing the parsed arguments.
"""
files_to_remove = [
"/ziti-router",
"/ziti",
"/endpoints"
]
logging.info("Removing previous binaries")
for file in files_to_remove:
file_to_remove = args.installDir + file
if os.path.isfile(file_to_remove):
try:
logging.debug("Removing file: %s", file_to_remove)
os.remove(file_to_remove)
except OSError:
logging.error("Unable to remove %s", file_to_remove)
sys.exit(1)
def create_file(name, path, content="", permissions=0o644):
"""
Create a file with the given name, path, content, and permissions.
:param:name (str): The name of the file to create.
:param:path (str): The path where the file should be created.
:param:content (str, optional): The content to be written to the file. Defaults to empty string.
:param:permissions (int, optional): The file permissions in octal notation. Defaults to 0o644.
:return:str: The full path of the created file.
:return:None: If there was an error creating the file.
"""
try:
logging.debug("Writing file %s", name)
full_name_path = os.path.join(path, name)
with open(full_name_path, "w", encoding='UTF-8') as file:
file.write(content)
logging.debug("Updating permissions of file: %s", name)
os.chmod(full_name_path, permissions)
except OSError as error:
logging.error("Writing file to disk: %s", error)
sys.exit(1)
return full_name_path
def create_edge_router(session_token, router_name, endpoint, enable_tunneler):
"""
Creates a new edge router using the session token.
:param session_token: The session token.
:param router_name: The name of the new edge router.
:param endpoint: The scheme, hostname or IP and port of the controller.
:return: The created edge router id.
"""
url = f"{endpoint}/edge/management/v1/edge-routers"
headers = {
"Content-Type": "application/json",
"zt-session": session_token
}
payload = {
"name": router_name,
'isTunnelerEnabled': enable_tunneler
}
logging.debug("TunnelerEnabled: %s", enable_tunneler)
urllib3.disable_warnings()
try:
response = requests.post(url, headers=headers,
json=payload,
timeout=15,
verify=False)
except requests.ConnectTimeout:
logging.error("Unable to connect to controller: Connection Timed out")
sys.exit(1)
except requests.ConnectionError:
logging.error("Unable to connect to controller: Connection Error")
if response.status_code == 201:
return response.json()['data']['id']
if "name is must be unique" in response.text:
logging.error("A router by the name: '%s' already exists.", router_name)
else:
logging.error("Unable to create router: %s %s",
response.status_code,
response.text)
sys.exit(1)
def create_parser():
"""
Create argparser Namespace
:return: A Namespace containing arguments
"""
__version__ = '1.0.20'
parser = argparse.ArgumentParser()
add_general_arguments(parser, __version__)
add_install_arguments(parser)
add_router_identity_arguments(parser)
add_router_ctrl_arguments(parser)
add_router_proxy_arguments(parser)
add_router_health_checks_arguments(parser)
add_router_metrics_arguments(parser)
add_router_edge_arguments(parser)
add_router_api_proxy_arguments(parser)
add_router_fabric_link_arguments(parser)
add_router_listener_arguments(parser)
add_router_web_arguments(parser)
add_router_ha_arguments(parser)
add_create_router_arguments(parser)
return parser
def compare_semver(version1, version2):
"""
Compare two semantic version numbers.
:param version1: The first version number as a string.
:param version2: The second version number as a string.
:return: 1 if version1 is greater, -1 if version2 is greater, 0 if equal.
"""
version_one = Version(version1)
version_two = Version(version2)
if version_one > version_two:
return 1
if version_one < version_two:
return -1
return 0
def decode_jwt(jwt_string):
"""
Process a jwt passed in as a string.
Read the JWT & check if it's not expired, and returns the decoded payload
as a dictionary or exit with error if expired.
:param args: An object containing either the enrollment_jwt or jwt_file attribute.
:return: The decoded JWT payload as a dictionary if the JWT is not expired.
"""
try:
jwt_decoded = jwt.decode(jwt_string, options={"verify_signature": False})
except jwt.DecodeError:
logging.error("Unable to decode JWT")
sys.exit(1)
current_time = time.time()
if jwt_decoded['exp'] < current_time:
logging.error("JWT is expired")
sys.exit(1)
return jwt_decoded, jwt_string
def download_file(download_url):
"""
Download a file from the specified URL and save it locally as 'download_{timestamp}.tar.gz'.
:param download_url: The URL of the file to download.
:return: The name of the downloaded file.
"""
try:
logging.info("Downloading file: %s", download_url)
timestamp = int(time.time())
file_name=f"download_{timestamp}.tar.gz"
response = requests.get(download_url, stream=True, timeout=120)
if response.status_code == 200:
total_size = int(response.headers.get("content-length", 0))
block_size = 1024 # 1 Kibibyte
status_bar = tqdm(total=total_size, unit="iB", unit_scale=True, desc="Downloading")
with open(file_name, "wb") as open_file:
for data in response.iter_content(block_size):
status_bar.update(len(data))
open_file.write(data)
status_bar.close()
logging.info("Successfully downloaded file")
elif response.status_code == 404:
logging.error("File not found at the specified URL")
sys.exit(1)
else:
logging.error("Unexpected status code: %s", response.status_code)
sys.exit(1)
except OSError:
logging.error("Unable to download binaries")
sys.exit(1)
return file_name
def enroll_ziti(jwt_string, install_dir):
"""
Register the ziti edge router
This function should be updated once Ziti has fix the exit codes.
"""
logging.info("Starting Router Enrollment")
current_env = os.environ.copy()
# write jwt file
logging.debug("Attempting to write jwt file to disk")
jwt_path = create_file(name="enroll.jwt",
path=install_dir,
content=jwt_string)
if os.path.isfile(f"{install_dir}/ziti-router"):
registration_command = [f"{install_dir}/ziti-router",
'enroll',
f"{install_dir}/config.yml",
'--jwt',
jwt_path]
else:
registration_command = [f"{install_dir}/ziti",
'router',
'enroll',
f"{install_dir}/config.yml",
'--jwt',
jwt_path]
logging.debug("Running command:")
logging.debug(registration_command)
try:
subprocess.run(registration_command,
capture_output=True,
text=True,
check=True,
env=current_env)
except subprocess.CalledProcessError as error:
if "registration complete" in error.stderr:
logging.info("Successfully enrolled Ziti")
create_file(name=".is_registered",
path=install_dir)
else:
logging.error("Failed to register Ziti"
"Command output %s %s", error.stdout, error.stderr)
sys.exit(1)
logging.info("Successfully enrolled Ziti")
create_file(name=".is_registered",
path=install_dir)
def get_default_interface():
"""
Get the name of the network interface associated with the default gateway.
:return:str: The name of the network interface associated with the default gateway.
:return:None: Returns None if no default gateway or associated interface is found.
"""
for _ in range(5):
try:
route_output = subprocess.check_output(["ip",
"route",
"show",
"default"]).decode("utf-8").strip()
default_gateway_interface = route_output.split(" ")[4]
return default_gateway_interface
except (subprocess.CalledProcessError, IndexError):
# If an exception occurred, wait 1 second before trying again
time.sleep(1)
return None
def get_hostname_from_ip(ip_address, args):
"""
Get the hostname associated with an IP address.
:param: ip (str): The IP address to look up.
:param args: Parsed command line arguments.
:return:str: The hostname associated with the IP address.
:return:None: If the IP address is invalid or the hostname cannot be found.
"""
if args.noHostname:
return None
if not is_valid_ip(ip_address):
logging.error("Provided IP is not an ip: %s", ip_address)
return None
try:
hostname, _, _ = socket.gethostbyaddr(ip_address)
return hostname
except socket.herror:
logging.debug("Unable to find the hostname for IP address %s", ip_address)
return None
def get_router_jwt(session_token, router_id, endpoint):
"""
Authenticates with the given token and retrieves a router jwt.
:param session_token: The session token.
:param routerId: The id of the edge router use to retrive the jwt.
:param endpoint: The scheme, hostname or IP and port of the controller.
:return: The session token.
"""
url = f"{endpoint}/edge/management/v1/edge-routers/{router_id}"
headers = {
"Content-Type": "application/json",
"zt-session": session_token
}
logging.debug("Attempting to acces url: %s", url)
urllib3.disable_warnings()
try:
response = requests.get(url, headers=headers, timeout=15, verify=False)
except requests.ConnectTimeout:
logging.error("Unable to connect to controller: Connection Timed out")
sys.exit(1)
except requests.ConnectionError:
logging.error("Unable to connect to controller: Connection Error")
sys.exit(1)
if response.status_code == 200:
logging.debug("Edge Router JWT: %s", response.json()['data']['enrollmentJwt'])
return response.json()['data']['enrollmentJwt']
logging.error("Unable to retrieve jwt from edge router: %s %s",
response.status_code,
response.text)
sys.exit(1)
def get_os_platform():
"""
Determines the OS platform and returns one of the following:
'darwin-amd64', 'linux-arm', 'linux-arm64', 'linux-amd64', 'windows-amd64'
:return: The OS platform string.
"""
os_system = platform.system().lower()
architecture = platform.machine().lower()
if os_system == 'darwin':
return 'darwin-amd64'
if os_system == 'linux':
if architecture == 'arm' or architecture.startswith('armv'):
return 'linux-arm'
if architecture in ('aarch64','arm64'):
return 'linux-arm64'
if architecture == 'x86_64':
return 'linux-amd64'
logging.error("Unsupported Linux architecture: %s", architecture)
sys.exit(1)
if os_system == 'windows':
if architecture in ('amd64','x86_64'):
return 'windows-amd64'
logging.error("Unsupported Linux architecture: %s", architecture)
sys.exit(1)
logging.error("Unsupported OS/architecture: %s %s", os_system, architecture)
sys.exit(1)