forked from idaholab/Malcolm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
install.py
executable file
·4625 lines (4312 loc) · 209 KB
/
install.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 python3
# -*- coding: utf-8 -*-
# Copyright (c) 2024 Battelle Energy Alliance, LLC. All rights reserved.
import sys
sys.dont_write_bytecode = True
import argparse
import datetime
import errno
import fileinput
import getpass
import glob
import json
import os
import pathlib
import platform
import pprint
import math
import re
import shutil
import tarfile
import tempfile
import time
try:
from pwd import getpwuid
except ImportError:
getpwuid = None
from collections import defaultdict, namedtuple
from enum import IntEnum
from malcolm_common import (
AskForString,
BoundPathReplacer,
ChooseMultiple,
ChooseOne,
DetermineYamlFileFormat,
DialogInit,
DialogBackException,
DialogCanceledException,
DisplayMessage,
DOCKER_COMPOSE_INSTALL_URLS,
DOCKER_INSTALL_URLS,
DotEnvDynamic,
DownloadToFile,
DumpYaml,
HOMEBREW_INSTALL_URLS,
KubernetesDynamic,
LoadYaml,
MalcolmCfgRunOnceFile,
MalcolmPath,
OrchestrationFramework,
OrchestrationFrameworksSupported,
PLATFORM_LINUX,
PLATFORM_LINUX_CENTOS,
PLATFORM_LINUX_DEBIAN,
PLATFORM_LINUX_FEDORA,
PLATFORM_LINUX_UBUNTU,
PLATFORM_MAC,
PLATFORM_WINDOWS,
PROFILE_MALCOLM,
PROFILE_HEDGEHOG,
PROFILE_KEY,
RequestsDynamic,
ScriptPath,
UserInputDefaultsBehavior,
UserInterfaceMode,
YAMLDynamic,
YesOrNo,
)
from malcolm_utils import (
ChownRecursive,
CountUntilException,
DatabaseMode,
DATABASE_MODE_LABELS,
DATABASE_MODE_ENUMS,
MALCOLM_DB_DIR,
MALCOLM_PCAP_DIR,
MALCOLM_LOGS_DIR,
deep_get,
deep_set,
eprint,
flatten,
LoadFileIfJson,
remove_prefix,
remove_suffix,
run_process,
same_file_or_dir,
str2bool,
touch,
which,
)
###################################################################################################
DOCKER_COMPOSE_INSTALL_VERSION = "2.23.0"
DEB_GPG_KEY_FINGERPRINT = '0EBFCD88' # used to verify GPG key for Docker Debian repository
MAC_BREW_DOCKER_PACKAGE = 'docker'
MAC_BREW_DOCKER_COMPOSE_PACKAGE = 'docker-compose'
MAC_BREW_DOCKER_SETTINGS = '/Users/{}/Library/Group Containers/group.com.docker/settings.json'
BACK_LABEL = 'Back'
LOGSTASH_JAVA_OPTS_DEFAULT = '-server -Xmx2500m -Xms2500m -Xss1536k -XX:-HeapDumpOnOutOfMemoryError -Djava.security.egd=file:/dev/./urandom -Dlog4j.formatMsgNoLookups=true'
OPENSEARCH_JAVA_OPTS_DEFAULT = '-server -Xmx10g -Xms10g -Xss256k -XX:-HeapDumpOnOutOfMemoryError -Djava.security.egd=file:/dev/./urandom -Dlog4j.formatMsgNoLookups=true'
###################################################################################################
ScriptName = os.path.basename(__file__)
origPath = os.getcwd()
###################################################################################################
args = None
requests_imported = None
yaml_imported = None
kube_imported = None
dotenv_imported = None
###################################################################################################
TrueOrFalseQuote = lambda x: "'true'" if x else "'false'"
TrueOrFalseNoQuote = lambda x: 'true' if x else 'false'
MaxAskForValueCount = 100
str2percent = lambda val: max(min(100, int(remove_suffix(val, '%'))), 0) if val else 0
class ConfigOptions(IntEnum):
Preconfig = 0
UidGuid = 1
NodeName = 2
RunProfile = 3
DatabaseMode = 4
LogstashRemote = 5
ContainerResources = 6
RestartMode = 7
RequireHTTPS = 8
DockerNetworking = 9
AuthMethod = 10
StorageLocations = 11
ILMISM = 12
StorageManagement = 13
AutoArkime = 14
AutoSuricata = 15
SuricataRuleUpdate = 16
AutoZeek = 17
ICS = 18
Enrichment = 19
OpenPorts = 20
FileCarving = 21
NetBox = 22
Capture = 23
DarkMode = 24
PostConfig = 25
###################################################################################################
# get interactive user response to Y/N question
def InstallerYesOrNo(
question,
default=None,
forceInteraction=False,
defaultBehavior=UserInputDefaultsBehavior.DefaultsPrompt | UserInputDefaultsBehavior.DefaultsAccept,
uiMode=UserInterfaceMode.InteractionInput | UserInterfaceMode.InteractionDialog,
yesLabel='Yes',
noLabel='No',
extraLabel=None,
):
global args
defBehavior = defaultBehavior
if args.acceptDefaultsNonInteractive and not forceInteraction:
defBehavior = defBehavior + UserInputDefaultsBehavior.DefaultsNonInteractive
return YesOrNo(
question,
default=default,
defaultBehavior=defBehavior,
uiMode=uiMode,
yesLabel=yesLabel,
noLabel=noLabel,
extraLabel=extraLabel,
)
###################################################################################################
# get interactive user response string
def InstallerAskForString(
question,
default=None,
forceInteraction=False,
defaultBehavior=UserInputDefaultsBehavior.DefaultsPrompt | UserInputDefaultsBehavior.DefaultsAccept,
uiMode=UserInterfaceMode.InteractionInput | UserInterfaceMode.InteractionDialog,
extraLabel=None,
):
global args
defBehavior = defaultBehavior
if args.acceptDefaultsNonInteractive and not forceInteraction:
defBehavior = defBehavior + UserInputDefaultsBehavior.DefaultsNonInteractive
return AskForString(
question,
default=default,
defaultBehavior=defBehavior,
uiMode=uiMode,
extraLabel=extraLabel,
)
###################################################################################################
# choose one from a list
def InstallerChooseOne(
prompt,
choices=[],
forceInteraction=False,
defaultBehavior=UserInputDefaultsBehavior.DefaultsPrompt | UserInputDefaultsBehavior.DefaultsAccept,
uiMode=UserInterfaceMode.InteractionInput | UserInterfaceMode.InteractionDialog,
extraLabel=None,
):
global args
defBehavior = defaultBehavior
if args.acceptDefaultsNonInteractive and not forceInteraction:
defBehavior = defBehavior + UserInputDefaultsBehavior.DefaultsNonInteractive
return ChooseOne(
prompt,
choices=choices,
defaultBehavior=defBehavior,
uiMode=uiMode,
extraLabel=extraLabel,
)
###################################################################################################
# choose multiple from a list
def InstallerChooseMultiple(
prompt,
choices=[],
forceInteraction=False,
defaultBehavior=UserInputDefaultsBehavior.DefaultsPrompt | UserInputDefaultsBehavior.DefaultsAccept,
uiMode=UserInterfaceMode.InteractionInput | UserInterfaceMode.InteractionDialog,
extraLabel=None,
):
global args
defBehavior = defaultBehavior
if args.acceptDefaultsNonInteractive and not forceInteraction:
defBehavior = defBehavior + UserInputDefaultsBehavior.DefaultsNonInteractive
return ChooseMultiple(
prompt,
choices=choices,
defaultBehavior=defBehavior,
uiMode=uiMode,
extraLabel=extraLabel,
)
###################################################################################################
# display a message to the user without feedback
def InstallerDisplayMessage(
message,
forceInteraction=False,
defaultBehavior=UserInputDefaultsBehavior.DefaultsPrompt | UserInputDefaultsBehavior.DefaultsAccept,
uiMode=UserInterfaceMode.InteractionInput | UserInterfaceMode.InteractionDialog,
extraLabel=None,
):
global args
defBehavior = defaultBehavior
if args.acceptDefaultsNonInteractive and not forceInteraction:
defBehavior = defBehavior + UserInputDefaultsBehavior.DefaultsNonInteractive
return DisplayMessage(
message,
defaultBehavior=defBehavior,
uiMode=uiMode,
extraLabel=extraLabel,
)
def DetermineUid(
scriptUser,
scriptPlatform,
referencePath,
):
defaultUid = '1000'
defaultGid = '1000'
if ((scriptPlatform == PLATFORM_LINUX) or (scriptPlatform == PLATFORM_MAC)) and (scriptUser == "root"):
if pathUid := os.stat(referencePath).st_uid:
defaultUid = str(pathUid)
if pathGid := os.stat(referencePath).st_gid:
defaultGid = str(pathGid)
uid = defaultUid
gid = defaultGid
try:
if scriptPlatform == PLATFORM_LINUX:
uid = str(os.getuid())
gid = str(os.getgid())
if (uid == '0') or (gid == '0'):
raise Exception('it is preferrable not to run Malcolm as root, prompting for UID/GID instead')
except Exception:
uid = defaultUid
gid = defaultGid
return uid, gid
###################################################################################################
class Installer(object):
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def __init__(self, orchMode, debug=False, configOnly=False):
self.orchMode = orchMode
self.debug = debug
self.configOnly = configOnly
self.platform = platform.system()
self.scriptUser = getpass.getuser()
self.checkPackageCmds = []
self.installPackageCmds = []
self.requiredPackages = []
self.dockerComposeCmd = None
self.pipCmd = 'pip3'
if not which(self.pipCmd, debug=self.debug):
self.pipCmd = 'pip'
self.tempDirName = tempfile.mkdtemp()
self.totalMemoryGigs = 0.0
self.totalCores = 0
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def __del__(self):
shutil.rmtree(self.tempDirName, ignore_errors=True)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def run_process(self, command, stdout=True, stderr=True, stdin=None, privileged=False, retry=0, retrySleepSec=5):
# if privileged, put the sudo command at the beginning of the command
if privileged and (len(self.sudoCmd) > 0):
command = self.sudoCmd + command
return run_process(
command,
stdout=stdout,
stderr=stderr,
stdin=stdin,
retry=retry,
retrySleepSec=retrySleepSec,
debug=self.debug,
)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def package_is_installed(self, package):
result = False
for cmd in self.checkPackageCmds:
ecode, out = self.run_process(cmd + [package])
if ecode == 0:
result = True
break
return result
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def install_package(self, packages):
result = False
pkgs = []
for package in packages:
if not self.package_is_installed(package):
pkgs.append(package)
if len(pkgs) > 0:
for cmd in self.installPackageCmds:
ecode, out = self.run_process(cmd + pkgs, privileged=True)
if ecode == 0:
result = True
break
else:
result = True
return result
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def install_required_packages(self):
if len(self.requiredPackages) > 0:
eprint(f"Installing required packages: {self.requiredPackages}")
return self.install_package(self.requiredPackages)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def install_docker_images(self, docker_image_file, malcolm_install_path):
result = False
composeFile = os.path.join(malcolm_install_path, 'docker-compose.yml')
if self.orchMode is OrchestrationFramework.DOCKER_COMPOSE:
if (
docker_image_file
and os.path.isfile(docker_image_file)
and InstallerYesOrNo(
f'Load Malcolm Docker images from {docker_image_file}?', default=True, forceInteraction=True
)
):
ecode, out = self.run_process(['docker', 'load', '-q', '-i', docker_image_file], privileged=True)
if ecode == 0:
result = True
else:
eprint(f"Loading Malcolm Docker images failed: {out}")
elif (
os.path.isfile(composeFile)
and self.dockerComposeCmd
and InstallerYesOrNo(f'Pull Malcolm Docker images?', default=False, forceInteraction=False)
):
for priv in (False, True):
ecode, out = self.run_process(
[
self.dockerComposeCmd,
'-f',
composeFile,
'--profile=malcolm',
'pull',
'--quiet',
],
privileged=priv,
)
if ecode == 0:
break
if ecode == 0:
result = True
else:
eprint(f"Pulling Malcolm Docker images failed: {out}")
return result
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def install_malcolm_files(self, malcolm_install_file, default_config_dir):
global args
result = False
installPath = None
if (
malcolm_install_file
and os.path.isfile(malcolm_install_file)
and InstallerYesOrNo(
f'Extract Malcolm runtime files from {malcolm_install_file}?', default=True, forceInteraction=True
)
):
# determine and create destination path for installation
loopBreaker = CountUntilException(MaxAskForValueCount, 'Invalid installation path')
while loopBreaker.increment():
defaultPath = os.path.join(origPath, 'malcolm')
installPath = InstallerAskForString(
f'Enter installation path for Malcolm [{defaultPath}]', default=defaultPath, forceInteraction=True
)
if len(installPath) == 0:
installPath = defaultPath
if os.path.isdir(installPath):
eprint(f"{installPath} already exists, please specify a different installation path")
else:
try:
os.makedirs(installPath)
except Exception:
pass
if os.path.isdir(installPath):
break
else:
eprint(f"Failed to create {installPath}, please specify a different installation path")
# extract runtime files
if installPath and os.path.isdir(installPath):
MalcolmPath = installPath
if self.debug:
eprint(f"Created {installPath} for Malcolm runtime files")
# extract the .tar.gz and chown the results
extUid, extGid = DetermineUid(self.scriptUser, self.platform, malcolm_install_file)
tar = tarfile.open(malcolm_install_file)
try:
tar.extractall(path=installPath, numeric_owner=True)
finally:
tar.close()
ChownRecursive(installPath, extUid, extGid)
# .tar.gz normally will contain an intermediate subdirectory. if so, move files back one level
childDir = glob.glob(f'{installPath}/*/')
if (len(childDir) == 1) and os.path.isdir(childDir[0]):
if self.debug:
eprint(f"{installPath} only contains {childDir[0]}")
for f in os.listdir(childDir[0]):
shutil.move(os.path.join(childDir[0], f), installPath)
shutil.rmtree(childDir[0], ignore_errors=True)
# create the config directory for the .env files
if default_config_dir:
args.configDir = os.path.join(installPath, 'config')
try:
os.makedirs(args.configDir)
except OSError as exc:
if (exc.errno == errno.EEXIST) and os.path.isdir(args.configDir):
pass
else:
raise
if self.debug:
eprint(f"Created {args.configDir} for Malcolm configuration files")
# verify the installation worked
if os.path.isfile(os.path.join(installPath, "docker-compose.yml")):
eprint(f"Malcolm runtime files extracted to {installPath}")
result = True
else:
eprint(f"Malcolm install file extracted to {installPath}, but missing runtime files?")
return result, installPath
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def tweak_malcolm_runtime(self, malcolm_install_path):
global args
global dotenv_imported
configFiles = []
if self.orchMode is OrchestrationFramework.DOCKER_COMPOSE:
# determine docker-compose files
if not args.configFile:
# get a list of all of the docker-compose files
configFiles = glob.glob(os.path.join(malcolm_install_path, 'docker-compose*.yml'))
elif os.path.isfile(args.configFile):
# single docker-compose file explicitly specified
configFiles = [os.path.realpath(args.configFile)]
malcolm_install_path = os.path.dirname(configFiles[0])
elif self.orchMode is OrchestrationFramework.KUBERNETES:
if args.configFile and os.path.isfile(args.configFile):
configFiles = [os.path.realpath(args.configFile)]
malcolm_install_path = os.path.realpath(os.path.join(ScriptPath, ".."))
else:
raise Exception(f"{self.orchMode} requires specifying kubeconfig file via -f/--config-file")
if (not args.configDir) or (not os.path.isdir(args.configDir)):
raise Exception("Could not determine configuration directory containing Malcolm's .env files")
if self.orchMode is OrchestrationFramework.DOCKER_COMPOSE:
# guestimate how much memory we should use based on total system memory
if self.debug:
eprint(
f'{malcolm_install_path} with "{configFiles}" and "{args.configDir}", system memory is {self.totalMemoryGigs} GiB'
)
if self.totalMemoryGigs >= 63.0:
osMemory = '24g'
lsMemory = '3g'
elif self.totalMemoryGigs >= 31.0:
osMemory = '16g'
lsMemory = '2500m'
elif self.totalMemoryGigs >= 15.0:
osMemory = '10g'
lsMemory = '2500m'
elif self.totalMemoryGigs >= 11.0:
osMemory = '6g'
lsMemory = '2g'
elif self.totalMemoryGigs >= 7.0:
eprint(f"Detected only {self.totalMemoryGigs} GiB of memory; performance will be suboptimal")
osMemory = '4g'
lsMemory = '2g'
elif self.totalMemoryGigs > 0.0:
eprint(f"Detected only {self.totalMemoryGigs} GiB of memory; performance will be suboptimal")
osMemory = '3500m'
lsMemory = '2g'
else:
eprint("Failed to determine system memory size, using defaults; performance may be suboptimal")
osMemory = '8g'
lsMemory = '3g'
else:
osMemory = '16g'
lsMemory = '3g'
# see Tuning and Profiling Logstash Performance
# - https://www.elastic.co/guide/en/logstash/current/tuning-logstash.html
# - https://www.elastic.co/guide/en/logstash/current/logstash-settings-file.html
# - https://www.elastic.co/guide/en/logstash/current/multiple-pipelines.html
# we don't want it too high, as in Malcolm Logstash also competes with OpenSearch, etc. for resources
if self.orchMode is OrchestrationFramework.DOCKER_COMPOSE:
if self.totalCores > 16:
lsWorkers = 6
elif self.totalCores >= 12:
lsWorkers = 4
else:
lsWorkers = 3
else:
lsWorkers = 6
if args.osMemory:
osMemory = args.osMemory
if args.lsMemory:
lsMemory = args.lsMemory
if args.lsWorkers:
lsWorkers = args.lsWorkers
if args.opensearchPrimaryMode not in DATABASE_MODE_ENUMS.keys():
raise Exception(f'"{args.opensearchPrimaryMode}" is not valid for --opensearch')
if args.opensearchSecondaryMode and (args.opensearchSecondaryMode not in DATABASE_MODE_ENUMS.keys()):
raise Exception(f'"{args.opensearchSecondaryMode}" is not valid for --opensearch-secondary')
opensearchPrimaryMode = DatabaseMode.OpenSearchLocal
opensearchPrimaryUrl = 'http://opensearch:9200'
opensearchPrimarySslVerify = False
opensearchPrimaryLabel = 'local OpenSearch'
opensearchSecondaryMode = DatabaseMode.DatabaseUnset
opensearchSecondaryUrl = ''
opensearchSecondarySslVerify = False
opensearchSecondaryLabel = 'remote OpenSearch'
dashboardsUrl = 'http://dashboards:5601/dashboards'
logstashHost = 'logstash:5044'
indexSnapshotCompressed = False
behindReverseProxy = False
dockerNetworkExternalName = ""
prevStep = None
currentStep = ConfigOptions.Preconfig
while True:
prevStep = currentStep
currentStep = ConfigOptions(int(currentStep) + 1)
try:
###################################################################################
if currentStep == ConfigOptions.Preconfig:
pass
###################################################################################
elif currentStep == ConfigOptions.UidGuid:
# figure out what UID/GID to run non-root processes under docker as
puid, pgid = DetermineUid(self.scriptUser, self.platform, malcolm_install_path)
defaultUid, defaultGid = puid, pgid
loopBreaker = CountUntilException(MaxAskForValueCount, 'Invalid UID/GID')
while (
(not puid.isdigit())
or (not pgid.isdigit())
or (
not InstallerYesOrNo(
f'Malcolm processes will run as UID {puid} and GID {pgid}. Is this OK?',
default=True,
)
)
) and loopBreaker.increment():
puid = InstallerAskForString(
'Enter user ID (UID) for running non-root Malcolm processes', default=defaultUid
)
pgid = InstallerAskForString(
'Enter group ID (GID) for running non-root Malcolm processes', default=defaultGid
)
###################################################################################
elif currentStep == ConfigOptions.NodeName:
pcapNodeName = InstallerAskForString(
f'Enter the node name to associate with network traffic metadata',
default=args.pcapNodeName,
extraLabel=BACK_LABEL,
)
###################################################################################
elif currentStep == ConfigOptions.RunProfile:
malcolmProfile = (
PROFILE_MALCOLM
if InstallerYesOrNo(
'Run with Malcolm (all containers) or Hedgehog (capture only) profile?',
default=args.malcolmProfile,
yesLabel='Malcolm',
noLabel='Hedgehog',
extraLabel=BACK_LABEL,
)
else PROFILE_HEDGEHOG
)
###################################################################################
elif currentStep == ConfigOptions.DatabaseMode:
if (malcolmProfile == PROFILE_MALCOLM) and InstallerYesOrNo(
'Should Malcolm use and maintain its own OpenSearch instance?',
default=DATABASE_MODE_ENUMS[args.opensearchPrimaryMode] == DatabaseMode.OpenSearchLocal,
extraLabel=BACK_LABEL,
):
opensearchPrimaryMode = DatabaseMode.OpenSearchLocal
else:
databaseModeChoice = ''
allowedDatabaseModes = {
DATABASE_MODE_LABELS[DatabaseMode.OpenSearchLocal]: [
DatabaseMode.OpenSearchLocal,
'local OpenSearch',
],
DATABASE_MODE_LABELS[DatabaseMode.OpenSearchRemote]: [
DatabaseMode.OpenSearchRemote,
'remote OpenSearch',
],
DATABASE_MODE_LABELS[DatabaseMode.ElasticsearchRemote]: [
DatabaseMode.ElasticsearchRemote,
'remote Elasticsearch',
],
}
if malcolmProfile != PROFILE_MALCOLM:
del allowedDatabaseModes[DATABASE_MODE_LABELS[DatabaseMode.OpenSearchLocal]]
loopBreaker = CountUntilException(MaxAskForValueCount, 'Invalid primary document store mode')
while databaseModeChoice not in list(allowedDatabaseModes.keys()) and loopBreaker.increment():
databaseModeChoice = InstallerChooseOne(
'Select primary Malcolm document store',
choices=[
(x, allowedDatabaseModes[x][1], x == args.opensearchPrimaryMode)
for x in list(allowedDatabaseModes.keys())
],
extraLabel=BACK_LABEL,
)
opensearchPrimaryMode = allowedDatabaseModes[databaseModeChoice][0]
opensearchPrimaryLabel = allowedDatabaseModes[databaseModeChoice][1]
if opensearchPrimaryMode in (DatabaseMode.OpenSearchRemote, DatabaseMode.ElasticsearchRemote):
loopBreaker = CountUntilException(MaxAskForValueCount, f'Invalid {opensearchPrimaryLabel} URL')
opensearchPrimaryUrl = ''
while (len(opensearchPrimaryUrl) <= 1) and loopBreaker.increment():
opensearchPrimaryUrl = InstallerAskForString(
f'Enter primary {opensearchPrimaryLabel} connection URL (e.g., https://192.168.1.123:9200)',
default=args.opensearchPrimaryUrl,
extraLabel=BACK_LABEL,
)
opensearchPrimarySslVerify = opensearchPrimaryUrl.lower().startswith(
'https'
) and InstallerYesOrNo(
f'Require SSL certificate validation for communication with {opensearchPrimaryLabel} instance?',
default=args.opensearchPrimarySslVerify,
extraLabel=BACK_LABEL,
)
else:
indexSnapshotCompressed = InstallerYesOrNo(
f'Compress {opensearchPrimaryLabel} index snapshots?',
default=args.indexSnapshotCompressed,
extraLabel=BACK_LABEL,
)
if opensearchPrimaryMode == DatabaseMode.ElasticsearchRemote:
loopBreaker = CountUntilException(MaxAskForValueCount, f'Invalid Kibana connection URL')
dashboardsUrl = ''
while (len(dashboardsUrl) <= 1) and loopBreaker.increment():
dashboardsUrl = InstallerAskForString(
f'Enter Kibana connection URL (e.g., https://192.168.1.123:5601)',
default=args.dashboardsUrl,
extraLabel=BACK_LABEL,
)
###################################################################################
elif currentStep == ConfigOptions.LogstashRemote:
if malcolmProfile != PROFILE_MALCOLM:
loopBreaker = CountUntilException(MaxAskForValueCount, f'Invalid Logstash host and port')
logstashHost = ''
while (len(logstashHost) <= 1) and loopBreaker.increment():
logstashHost = InstallerAskForString(
f'Enter Logstash host and port (e.g., 192.168.1.123:5044)',
default=args.logstashHost,
extraLabel=BACK_LABEL,
)
if (malcolmProfile == PROFILE_MALCOLM) and InstallerYesOrNo(
'Forward Logstash logs to a secondary remote document store?',
default=(
DATABASE_MODE_ENUMS[args.opensearchSecondaryMode]
in (DatabaseMode.OpenSearchRemote, DatabaseMode.ElasticsearchRemote)
),
extraLabel=BACK_LABEL,
):
databaseModeChoice = ''
allowedDatabaseModes = {
DATABASE_MODE_LABELS[DatabaseMode.OpenSearchRemote]: [
DatabaseMode.OpenSearchRemote,
'remote OpenSearch',
],
DATABASE_MODE_LABELS[DatabaseMode.ElasticsearchRemote]: [
DatabaseMode.ElasticsearchRemote,
'remote Elasticsearch',
],
}
loopBreaker = CountUntilException(MaxAskForValueCount, 'Invalid secondary document store mode')
while databaseModeChoice not in list(allowedDatabaseModes.keys()) and loopBreaker.increment():
databaseModeChoice = InstallerChooseOne(
'Select secondary Malcolm document store',
choices=[
(x, allowedDatabaseModes[x][1], x == args.opensearchSecondaryMode)
for x in list(allowedDatabaseModes.keys())
],
extraLabel=BACK_LABEL,
)
opensearchSecondaryMode = allowedDatabaseModes[databaseModeChoice][0]
opensearchSecondaryLabel = allowedDatabaseModes[databaseModeChoice][1]
if opensearchSecondaryMode in (DatabaseMode.OpenSearchRemote, DatabaseMode.ElasticsearchRemote):
loopBreaker = CountUntilException(
MaxAskForValueCount, f'Invalid {opensearchSecondaryLabel} URL'
)
opensearchSecondaryUrl = ''
while (len(opensearchSecondaryUrl) <= 1) and loopBreaker.increment():
opensearchSecondaryUrl = InstallerAskForString(
f'Enter secondary {opensearchSecondaryLabel} connection URL (e.g., https://192.168.1.123:9200)',
default=args.opensearchSecondaryUrl,
extraLabel=BACK_LABEL,
)
opensearchSecondarySslVerify = opensearchSecondaryUrl.lower().startswith(
'https'
) and InstallerYesOrNo(
f'Require SSL certificate validation for communication with secondary {opensearchSecondaryLabel} instance?',
default=args.opensearchSecondarySslVerify,
extraLabel=BACK_LABEL,
)
if (opensearchPrimaryMode in (DatabaseMode.OpenSearchRemote, DatabaseMode.ElasticsearchRemote)) or (
opensearchSecondaryMode in (DatabaseMode.OpenSearchRemote, DatabaseMode.ElasticsearchRemote)
):
InstallerDisplayMessage(
f'You must run auth_setup after {ScriptName} to store data store connection credentials.',
)
###################################################################################
elif currentStep == ConfigOptions.ContainerResources:
if malcolmProfile == PROFILE_MALCOLM:
loopBreaker = CountUntilException(
MaxAskForValueCount,
f'Invalid {"OpenSearch/" if opensearchPrimaryMode == DatabaseMode.OpenSearchLocal else ""}Logstash memory setting(s)',
)
while (
not InstallerYesOrNo(
(
f'Setting {osMemory} for OpenSearch and {lsMemory} for Logstash. Is this OK?'
if opensearchPrimaryMode == DatabaseMode.OpenSearchLocal
else f'Setting {lsMemory} for Logstash. Is this OK?'
),
default=True,
extraLabel=BACK_LABEL,
)
and loopBreaker.increment()
):
if opensearchPrimaryMode == DatabaseMode.OpenSearchLocal:
osMemory = InstallerAskForString(
'Enter memory for OpenSearch (e.g., 16g, 9500m, etc.)',
extraLabel=BACK_LABEL,
)
lsMemory = InstallerAskForString(
'Enter memory for Logstash (e.g., 4g, 2500m, etc.)',
extraLabel=BACK_LABEL,
)
loopBreaker = CountUntilException(MaxAskForValueCount, 'Invalid Logstash worker setting(s)')
while (
(not str(lsWorkers).isdigit())
or (
not InstallerYesOrNo(
f'Setting {lsWorkers} workers for Logstash pipelines. Is this OK?',
default=True,
extraLabel=BACK_LABEL,
)
)
) and loopBreaker.increment():
lsWorkers = InstallerAskForString(
'Enter number of Logstash workers (e.g., 4, 8, etc.)',
extraLabel=BACK_LABEL,
)
###################################################################################
elif currentStep == ConfigOptions.RestartMode:
restartMode = None
allowedRestartModes = ('no', 'on-failure', 'always', 'unless-stopped')
if (self.orchMode is OrchestrationFramework.DOCKER_COMPOSE) and InstallerYesOrNo(
'Restart Malcolm upon system or Docker daemon restart?',
default=args.malcolmAutoRestart,
extraLabel=BACK_LABEL,
):
loopBreaker = CountUntilException(MaxAskForValueCount, 'Invalid restart mode')
while restartMode not in allowedRestartModes and loopBreaker.increment():
restartMode = InstallerChooseOne(
'Select Malcolm restart behavior',
choices=[(x, '', x == 'unless-stopped') for x in allowedRestartModes],
extraLabel=BACK_LABEL,
)
else:
restartMode = 'no'
###################################################################################
elif currentStep == ConfigOptions.RequireHTTPS:
if malcolmProfile == PROFILE_MALCOLM:
nginxSSL = InstallerYesOrNo(
'Require encrypted HTTPS connections?',
default=args.nginxSSL,
extraLabel=BACK_LABEL,
)
if (not nginxSSL) and (not args.acceptDefaultsNonInteractive):
nginxSSL = not InstallerYesOrNo(
'Unencrypted connections are NOT recommended. Are you sure?',
default=False,
extraLabel=BACK_LABEL,
)
else:
nginxSSL = True
###################################################################################
elif currentStep == ConfigOptions.DockerNetworking:
behindReverseProxy = (self.orchMode is OrchestrationFramework.KUBERNETES) or (
(malcolmProfile == PROFILE_MALCOLM)
and InstallerYesOrNo(
'Will Malcolm be running behind another reverse proxy (Traefik, Caddy, etc.)?',
default=args.behindReverseProxy or (not nginxSSL),
extraLabel=BACK_LABEL,
)
)
traefikLabels = False
traefikHost = ""
traefikOpenSearchHost = ""
traefikEntrypoint = ""
traefikResolver = ""
if self.orchMode is OrchestrationFramework.DOCKER_COMPOSE:
if behindReverseProxy:
traefikLabels = InstallerYesOrNo(
'Configure labels for Traefik?',
default=bool(args.traefikHost),
extraLabel=BACK_LABEL,
)
if traefikLabels:
loopBreaker = CountUntilException(MaxAskForValueCount, 'Invalid Traefik request domain')
while (len(traefikHost) <= 1) and loopBreaker.increment():
traefikHost = InstallerAskForString(
'Enter request domain (host header value) for Malcolm interface Traefik router (e.g., malcolm.example.org)',
default=args.traefikHost,
extraLabel=BACK_LABEL,
)
if opensearchPrimaryMode == DatabaseMode.OpenSearchLocal:
loopBreaker = CountUntilException(
MaxAskForValueCount, 'Invalid Traefik OpenSearch request domain'
)
while (
(len(traefikOpenSearchHost) <= 1) or (traefikOpenSearchHost == traefikHost)
) and loopBreaker.increment():
traefikOpenSearchHost = InstallerAskForString(
f'Enter request domain (host header value) for OpenSearch Traefik router (e.g., opensearch.{traefikHost})',
default=args.traefikOpenSearchHost,
extraLabel=BACK_LABEL,
)
loopBreaker = CountUntilException(
MaxAskForValueCount, 'Invalid Traefik router entrypoint'
)
while (len(traefikEntrypoint) <= 1) and loopBreaker.increment():
traefikEntrypoint = InstallerAskForString(
'Enter Traefik router entrypoint (e.g., websecure)',
default=args.traefikEntrypoint,
extraLabel=BACK_LABEL,
)
loopBreaker = CountUntilException(
MaxAskForValueCount, 'Invalid Traefik router resolver'
)
while (len(traefikResolver) <= 1) and loopBreaker.increment():
traefikResolver = InstallerAskForString(
'Enter Traefik router resolver (e.g., myresolver)',
default=args.traefikResolver,
extraLabel=BACK_LABEL,
)
dockerNetworkExternalName = InstallerAskForString(
'Specify external Docker network name (or leave blank for default networking)',
default=args.dockerNetworkName,
extraLabel=BACK_LABEL,
)
###################################################################################
elif currentStep == ConfigOptions.AuthMethod:
allowedAuthModes = {
'Basic': 'true',
'Lightweight Directory Access Protocol (LDAP)': 'false',
'None': 'no_authentication',
}
authMode = None if (malcolmProfile == PROFILE_MALCOLM) else 'Basic'
loopBreaker = CountUntilException(MaxAskForValueCount, 'Invalid authentication method')
while authMode not in list(allowedAuthModes.keys()) and loopBreaker.increment():
authMode = InstallerChooseOne(
'Select authentication method',
choices=[
(
x,
'',
x
== (
'Lightweight Directory Access Protocol (LDAP)' if args.authModeLDAP else 'Basic'
),
)
for x in list(allowedAuthModes.keys())
],
extraLabel=BACK_LABEL,
)
ldapStartTLS = False
ldapServerTypeDefault = args.ldapServerType if args.ldapServerType else 'winldap'
ldapServerType = ldapServerTypeDefault
if 'ldap' in authMode.lower():
allowedLdapModes = ('winldap', 'openldap')