-
Notifications
You must be signed in to change notification settings - Fork 339
/
Copy pathcontrol.py
executable file
·1452 lines (1290 loc) · 60.6 KB
/
control.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) 2023 Battelle Energy Alliance, LLC. All rights reserved.
import argparse
import errno
import fileinput
import getpass
import glob
import json
import os
import platform
import re
import secrets
import shutil
import stat
import string
import sys
from malcolm_common import *
from base64 import b64encode
from collections import defaultdict, namedtuple
from subprocess import PIPE, STDOUT, Popen, check_call, CalledProcessError
from urllib.parse import urlparse
try:
from contextlib import nullcontext
except ImportError:
class nullcontext(object):
def __init__(self, enter_result=None):
self.enter_result = enter_result
def __enter__(self):
return self.enter_result
def __exit__(self, *args):
pass
###################################################################################################
ScriptName = os.path.basename(__file__)
pyPlatform = platform.system()
args = None
dockerBin = None
dockerComposeBin = None
opensslBin = None
yamlImported = None
dockerComposeYaml = None
###################################################################################################
try:
from colorama import init as ColoramaInit, Fore, Back, Style
ColoramaInit()
coloramaImported = True
except:
coloramaImported = False
###################################################################################################
# perform a service-keystore operation in a Docker container
#
# service - the service in the docker-compose YML file
# keystore_args - arguments to pass to the service-keystore binary in the container
# run_process_kwargs - keyword arguments to pass to run_process
#
# returns True (success) or False (failure)
#
def keystore_op(service, dropPriv=False, *keystore_args, **run_process_kwargs):
global args
global dockerBin
global dockerComposeBin
err = -1
results = []
# the opensearch containers all follow the same naming pattern for these executables
keystoreBinProc = f"/usr/share/{service}/bin/{service}-keystore"
# if we're using docker-uid-gid-setup.sh to drop privileges as we spin up a container
dockerUidGuidSetup = "/usr/local/bin/docker-uid-gid-setup.sh"
# docker-compose use local temporary path
osEnv = os.environ.copy()
osEnv['TMPDIR'] = MalcolmTmpPath
# open up the docker-compose file and "grep" for the line where the keystore file
# is bind-mounted into the service container (once and only once). the bind
# mount needs to exist in the YML file and the local directory containing the
# keystore file needs to exist (although the file itself might not yet).
# also get PUID and PGID variables from the docker-compose file.
localKeystore = None
localKeystoreDir = None
localKeystorePreExists = False
volumeKeystore = None
volumeKeystoreDir = None
uidGidDict = defaultdict(str)
try:
composeFileLines = list()
uidGidDict['PUID'] = f'{os.getuid()}' if (pyPlatform != PLATFORM_WINDOWS) else '1000'
uidGidDict['PGID'] = f'{os.getgid()}' if (pyPlatform != PLATFORM_WINDOWS) else '1000'
with open(args.composeFile, 'r') as f:
allLines = f.readlines()
composeFileLines = [x for x in allLines if re.search(fr'-.*?{service}.keystore\s*:.*{service}.keystore', x)]
uidGidDict.update(
dict(
x.split(':')
for x in [''.join(x.split()) for x in allLines if re.search(fr'^\s*P[UG]ID\s*:\s*\d+\s*$', x)]
)
)
if (len(composeFileLines) == 1) and (len(composeFileLines[0]) > 0):
matches = re.search(
fr'-\s*(?P<localKeystore>.*?{service}.keystore)\s*:\s*(?P<volumeKeystore>.*?{service}.keystore)',
composeFileLines[0],
)
if matches:
localKeystore = os.path.realpath(matches.group('localKeystore'))
localKeystoreDir = os.path.dirname(localKeystore)
volumeKeystore = matches.group('volumeKeystore')
volumeKeystoreDir = os.path.dirname(volumeKeystore)
if (localKeystore is not None) and (volumeKeystore is not None) and os.path.isdir(localKeystoreDir):
localKeystorePreExists = os.path.isfile(localKeystore)
dockerCmd = None
# determine if Malcolm is running; if so, we'll use docker-compose exec, other wise we'll use docker run
err, out = run_process(
[dockerComposeBin, '-f', args.composeFile, 'ps', '-q', service], env=osEnv, debug=args.debug
)
out[:] = [x for x in out if x]
if (err == 0) and (len(out) > 0):
# Malcolm is running, we can use an existing container
# assemble the service-keystore command
dockerCmd = [
dockerComposeBin,
'exec',
# if using stdin, indicate the container is "interactive", else noop (duplicate --rm)
'-T' if ('stdin' in run_process_kwargs and run_process_kwargs['stdin']) else '',
# execute as UID:GID in docker-compose.yml file
'-u',
f'{uidGidDict["PUID"]}:{uidGidDict["PGID"]}',
# the work directory in the container is the directory to contain the keystore file
'-w',
volumeKeystoreDir,
# the service name
service,
# the executable filespec
keystoreBinProc,
]
else:
# Malcolm isn't running, do 'docker run' to spin up a temporary container to run the ocmmand
# "grep" the docker image out of the service's image: value from the docker-compose YML file
serviceImage = None
composeFileLines = list()
with open(args.composeFile, 'r') as f:
composeFileLines = [x for x in f.readlines() if f'image: malcolmnetsec/{service}' in x]
if (len(composeFileLines) > 0) and (len(composeFileLines[0]) > 0):
imageLineValues = composeFileLines[0].split()
if len(imageLineValues) > 1:
serviceImage = imageLineValues[1]
if serviceImage is not None:
# assemble the service-keystore command
dockerCmd = [
dockerBin,
'run',
# remove the container when complete
'--rm',
# if using stdin, indicate the container is "interactive", else noop
'-i' if ('stdin' in run_process_kwargs and run_process_kwargs['stdin']) else '',
# if dropPriv, dockerUidGuidSetup will take care of dropping privileges for the correct UID/GID
# if NOT dropPriv, enter with the keystore executable directly
'--entrypoint',
dockerUidGuidSetup if dropPriv else keystoreBinProc,
'--env',
f'DEFAULT_UID={uidGidDict["PUID"]}',
'--env',
f'DEFAULT_GID={uidGidDict["PGID"]}',
'--env',
f'PUSER_CHOWN={volumeKeystoreDir}',
# rw bind mount the local directory to contain the keystore file to the container directory
'-v',
f'{localKeystoreDir}:{volumeKeystoreDir}:rw',
# the work directory in the container is the directory to contain the keystore file
'-w',
volumeKeystoreDir,
# if dropPriv, execute as root, as docker-uid-gid-setup.sh will drop privileges for us
# if NOT dropPriv, execute as UID:GID in docker-compose.yml file
'-u',
'root' if dropPriv else f'{uidGidDict["PUID"]}:{uidGidDict["PGID"]}',
# the service image name grepped from the YML file
serviceImage,
]
if dropPriv:
# the keystore executable filespec (as we used dockerUidGuidSetup as the entrypoint)
dockerCmd.append(keystoreBinProc)
else:
raise Exception(f'Unable to identify docker image for {service} in {args.composeFile}')
if dockerCmd is not None:
# append whatever other arguments to pass to the executable filespec
if keystore_args:
dockerCmd.extend(list(keystore_args))
dockerCmd[:] = [x for x in dockerCmd if x]
# execute the command, passing through run_process_kwargs to run_process as expanded keyword arguments
err, results = run_process(dockerCmd, env=osEnv, debug=args.debug, **run_process_kwargs)
if (err != 0) or (not os.path.isfile(localKeystore)):
raise Exception(f'Error processing command {service} keystore: {results}')
else:
raise Exception(f'Unable formulate keystore command for {service} in {args.composeFile}')
else:
raise Exception(f'Unable to identify a unique keystore file bind mount for {service} in {args.composeFile}')
except Exception as e:
if err == 0:
err = -1
# don't be so whiny if the "create" failed just because it already existed or a 'remove' failed on a nonexistant item
if (
(not args.debug)
and list(keystore_args)
and (len(list(keystore_args)) > 0)
and (list(keystore_args)[0].lower() in ('create', 'remove'))
and localKeystorePreExists
):
pass
else:
eprint(e)
# success = (error == 0)
return (err == 0), results
###################################################################################################
def status():
global args
global dockerComposeBin
# docker-compose use local temporary path
osEnv = os.environ.copy()
osEnv['TMPDIR'] = MalcolmTmpPath
err, out = run_process(
[dockerComposeBin, '-f', args.composeFile, 'ps', args.service][: 5 if args.service is not None else -1],
env=osEnv,
debug=args.debug,
)
if err == 0:
print("\n".join(out))
else:
eprint("Failed to display Malcolm status\n")
eprint("\n".join(out))
exit(err)
###################################################################################################
def logs():
global args
global dockerBin
global dockerComposeBin
urlUserPassRegEx = re.compile(r'(\w+://[^/]+?:)[^/]+?(@[^/]+)')
# noisy logs (a lot of it is NGINX logs from health checks)
ignoreRegEx = re.compile(
r"""
.+(
deprecated
| "GET\s+/\s+HTTP/1\.\d+"\s+200\s+-
| \bGET.+\b302\s+30\b
| (async|output)\.go.+(reset\s+by\s+peer|Connecting\s+to\s+backoff|backoff.+established$)
| /(opensearch-dashboards|dashboards|kibana)/(api/ui_metric/report|internal/search/(es|opensearch))
| (Error\s+during\s+file\s+comparison|File\s+was\s+renamed):\s+/zeek/live/logs/
| /_ns_/nstest\.html
| /usr/share/logstash/x-pack/lib/filters/geoip/database_manager
| \b(d|es)?stats\.json
| \b1.+GET\s+/\s+.+401.+curl
| _cat/indices
| branding.*config\s+is\s+not\s+found\s+or\s+invalid
| but\s+there\s+are\s+no\s+living\s+connections
| Connecting\s+to\s+backoff
| curl.+localhost.+GET\s+/api/status\s+200
| DEPRECATION
| descheduling\s+job\s*id
| eshealth
| esindices/list
| executing\s+attempt_(transition|set_replica_count)\s+for
| GET\s+/(netbox/api|_cat/health|api/status|sessions2-|arkime_\w+).+HTTP/[\d\.].+\b200\b
| loaded\s+config\s+'/etc/netbox/config/
| "netbox"\s+application\s+started
| \[notice\].+app\s+process\s+\d+\s+exited\s+with\s+code\s+0\b
| POST\s+/(arkime_\w+)(/\w+)?/_(d?stat|doc|search).+HTTP/[\d\.].+\b20[01]\b
| POST\s+/_bulk\s+HTTP/[\d\.].+\b20[01]\b
| POST\s+/server/php/\s+HTTP/\d+\.\d+"\s+\d+\s+\d+.*:8443/
| POST\s+HTTP/[\d\.].+\b200\b
| reaped\s+unknown\s+pid
| remov(ed|ing)\s+(old\s+file|dead\s+symlink|empty\s+directory)
| retry\.go.+(send\s+unwait|done$)
| running\s+full\s+sweep
| saved_objects
| scheduling\s+job\s*id.+opendistro-ism
| SSL/TLS\s+verifications\s+disabled
| Successfully\s+handled\s+GET\s+request\s+for\s+'/'
| Test\s+run\s+complete.*:failed=>0,\s*:errored=>0\b
| throttling\s+index
| update_mapping
| updating\s+number_of_replicas
| use_field_mapping
| Using\s+geoip\s+database
)
""",
re.VERBOSE | re.IGNORECASE,
)
# logs we don't want to eliminate, but we don't want to repeat ad-nauseum
# TODO: not implemented yet
dupeRegEx = re.compile(
r"""
.+(
Maybe the destination pipeline is down or stopping
)
""",
re.VERBOSE | re.IGNORECASE,
)
serviceRegEx = re.compile(r'^(?P<service>.+?\|)\s*(?P<message>.*)$')
iso8601TimeRegEx = re.compile(
r'^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\.[0-9]+)?(Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$'
)
# increase COMPOSE_HTTP_TIMEOUT to be ridiculously large so docker-compose never times out the TTY doing debug output
osEnv = os.environ.copy()
osEnv['COMPOSE_HTTP_TIMEOUT'] = '100000000'
# docker-compose use local temporary path
osEnv['TMPDIR'] = MalcolmTmpPath
err, out = run_process(
[dockerComposeBin, '-f', args.composeFile, 'ps', args.service][: 5 if args.service is not None else -1],
env=osEnv,
debug=args.debug,
)
print("\n".join(out))
process = Popen(
[dockerComposeBin, '-f', args.composeFile, 'logs', '-f', args.service][: 6 if args.service is not None else -1],
env=osEnv,
stdout=PIPE,
)
while True:
output = process.stdout.readline()
if (len(output) == 0) and (process.poll() is not None):
break
if output:
outputStr = urlUserPassRegEx.sub(r"\1xxxxxxxx\2", output.decode().strip())
outputStrEscaped = EscapeAnsi(outputStr)
if ignoreRegEx.match(outputStrEscaped):
pass ### print(f'!!!!!!!: {outputStr}')
else:
serviceMatch = serviceRegEx.search(outputStrEscaped)
serviceMatchFmt = serviceRegEx.search(outputStr) if coloramaImported else serviceMatch
serviceStr = serviceMatchFmt.group('service') if (serviceMatchFmt is not None) else ''
messageStr = serviceMatch.group('message') if (serviceMatch is not None) else ''
messageStrSplit = messageStr.split(' ')
messageTimeMatch = iso8601TimeRegEx.match(messageStrSplit[0])
if (messageTimeMatch is None) or (len(messageStrSplit) <= 1):
messageStrToTestJson = messageStr
else:
messageStrToTestJson = messageStrSplit[1:].join(' ')
outputJson = LoadStrIfJson(messageStrToTestJson)
if isinstance(outputJson, dict):
# if there's a timestamp, move it outside of the JSON to the beginning of the log string
timeKey = None
if 'time' in outputJson:
timeKey = 'time'
elif 'timestamp' in outputJson:
timeKey = 'timestamp'
elif '@timestamp' in outputJson:
timeKey = '@timestamp'
timeStr = ''
if timeKey is not None:
timeStr = f"{outputJson[timeKey]} "
outputJson.pop(timeKey, None)
elif messageTimeMatch is not None:
timeStr = f"{messageTimeMatch[0]} "
if (
('job.schedule' in outputJson)
and ('job.position' in outputJson)
and ('job.command' in outputJson)
):
# this is a status output line from supercronic, let's format and clean it up so it fits in better with the rest of the logs
# remove some clutter for the display
for noisyKey in ['level', 'channel', 'iteration', 'job.position', 'job.schedule']:
outputJson.pop(noisyKey, None)
# if it's just command and message, format those NOT as JSON
jobCmd = outputJson['job.command']
jobStatus = outputJson['msg']
if (len(outputJson.keys()) == 2) and ('job.command' in outputJson) and ('msg' in outputJson):
# if it's the most common status (starting or job succeeded) then don't print unless debug mode
if args.debug or ((jobStatus != 'starting') and (jobStatus != 'job succeeded')):
print(
f"{serviceStr}{Style.RESET_ALL if coloramaImported else ''} {timeStr} {jobCmd}: {jobStatus}"
)
else:
pass
else:
# standardize and print the JSON output
print(
f"{serviceStr}{Style.RESET_ALL if coloramaImported else ''} {timeStr}{json.dumps(outputJson)}"
)
elif 'dashboards' in serviceStr:
# this is an output line from dashboards, let's clean it up a bit: remove some clutter for the display
for noisyKey in ['type', 'tags', 'pid', 'method', 'prevState', 'prevMsg']:
outputJson.pop(noisyKey, None)
# standardize and print the JSON output
print(
f"{serviceStr}{Style.RESET_ALL if coloramaImported else ''} {timeStr}{json.dumps(outputJson)}"
)
elif 'filebeat' in serviceStr:
# this is an output line from filebeat, let's clean it up a bit: remove some clutter for the display
for noisyKey in [
'ecs.version',
'harvester_id',
'input_id',
'log.level',
'log.logger',
'log.origin',
'os_id',
'service.name',
'state_id',
]:
outputJson.pop(noisyKey, None)
# we'll fancify a couple of common things from filebeat
if (
(len(outputJson.keys()) == 3)
and ('message' in outputJson)
and ('source_file' in outputJson)
and ('finished' in outputJson)
):
print(
f"{serviceStr}{Style.RESET_ALL if coloramaImported else ''} {timeStr}{outputJson['message'].rstrip('.')}: {outputJson['source_file']}"
)
elif len(outputJson.keys()) == 1:
outputKey = next(iter(outputJson))
print(
f"{serviceStr}{Style.RESET_ALL if coloramaImported else ''} {timeStr}{outputKey + ': ' if outputKey != 'message' else ''}{outputJson[outputKey]}"
)
else:
# standardize and print the JSON output
print(
f"{serviceStr}{Style.RESET_ALL if coloramaImported else ''} {timeStr}{json.dumps(outputJson)}"
)
else:
# standardize and print the JSON output
print(
f"{serviceStr}{Style.RESET_ALL if coloramaImported else ''} {timeStr}{json.dumps(outputJson)}"
)
else:
# just a regular non-JSON string, print as-is
print(outputStr if coloramaImported else outputStrEscaped)
else:
time.sleep(0.5)
process.poll()
###################################################################################################
def stop(wipe=False):
global args
global dockerBin
global dockerComposeBin
global dockerComposeYaml
# docker-compose use local temporary path
osEnv = os.environ.copy()
osEnv['TMPDIR'] = MalcolmTmpPath
# if stop.sh is being called with wipe.sh (after the docker-compose file)
# then also remove named and anonymous volumes (not external volumes, of course)
err, out = run_process(
[dockerComposeBin, '-f', args.composeFile, 'down', '--volumes'][: 5 if wipe else -1],
env=osEnv,
debug=args.debug,
)
if err == 0:
eprint("Stopped Malcolm\n")
else:
eprint("Malcolm failed to stop\n")
eprint("\n".join(out))
exit(err)
if wipe:
# there is some overlap here among some of these containers, but it doesn't matter
boundPathsToWipe = (
BoundPath("arkime", "/opt/arkime/logs", True, None, None),
BoundPath("arkime", "/opt/arkime/raw", True, None, None),
BoundPath("filebeat", "/zeek", True, None, None),
BoundPath("file-monitor", "/zeek/logs", True, None, None),
BoundPath("netbox", "/opt/netbox/netbox/media", True, None, ["."]),
BoundPath("netbox-postgres", "/var/lib/postgresql/data", True, None, ["."]),
BoundPath("netbox-redis", "/data", True, None, ["."]),
BoundPath("opensearch", "/usr/share/opensearch/data", True, ["nodes"], None),
BoundPath("pcap-monitor", "/pcap", True, ["processed", "upload"], None),
BoundPath("suricata", "/var/log/suricata", True, None, ["."]),
BoundPath("upload", "/var/www/upload/server/php/chroot/files", True, None, None),
BoundPath("zeek", "/zeek/extract_files", True, None, None),
BoundPath("zeek", "/zeek/upload", True, None, None),
BoundPath("zeek-live", "/zeek/live", True, ["spool"], None),
BoundPath(
"filebeat",
"/zeek",
False,
["processed", "current", "live"],
["processed", "current", "live"],
),
)
for boundPath in boundPathsToWipe:
localPath = LocalPathForContainerBindMount(
boundPath.service,
dockerComposeYaml,
boundPath.container_dir,
MalcolmPath,
)
if localPath and os.path.isdir(localPath):
# delete files
if boundPath.files:
if args.debug:
eprint(f'Walking "{localPath}" for file deletion')
for root, dirnames, filenames in os.walk(localPath, topdown=True, onerror=None):
for file in filenames:
fileSpec = os.path.join(root, file)
if (os.path.isfile(fileSpec) or os.path.islink(fileSpec)) and (not file.startswith('.git')):
try:
os.remove(fileSpec)
except:
pass
# delete whole directories
if boundPath.relative_dirs:
for relDir in GetIterable(boundPath.relative_dirs):
tmpPath = os.path.join(localPath, relDir)
if os.path.isdir(tmpPath):
if args.debug:
eprint(f'Performing rmtree on "{tmpPath}"')
shutil.rmtree(tmpPath, ignore_errors=True)
# cleanup empty directories
if boundPath.clean_empty_dirs:
for cleanDir in GetIterable(boundPath.clean_empty_dirs):
tmpPath = os.path.join(localPath, cleanDir)
if os.path.isdir(tmpPath):
if args.debug:
eprint(f'Performing RemoveEmptyFolders on "{tmpPath}"')
RemoveEmptyFolders(tmpPath, removeRoot=False)
eprint("Malcolm has been stopped and its data cleared\n")
###################################################################################################
def start():
global args
global dockerBin
global dockerComposeBin
# make sure the auth files exist. if we are in an interactive shell and we're
# missing any of the auth files, prompt to create them now
if sys.__stdin__.isatty() and (not MalcolmAuthFilesExist()):
authSetup()
# still missing? sorry charlie
if not MalcolmAuthFilesExist():
raise Exception(
'Malcolm administrator account authentication files are missing, please run ./scripts/auth_setup to generate them'
)
# touch the htadmin metadata file and .opensearch.*.curlrc files
open(os.path.join(MalcolmPath, os.path.join('htadmin', 'metadata')), 'a').close()
open(os.path.join(MalcolmPath, '.opensearch.primary.curlrc'), 'a').close()
open(os.path.join(MalcolmPath, '.opensearch.secondary.curlrc'), 'a').close()
# if the OpenSearch keystore doesn't exist exist, create empty ones
if not os.path.isfile(os.path.join(MalcolmPath, os.path.join('opensearch', 'opensearch.keystore'))):
keystore_op('opensearch', True, 'create')
# make sure permissions are set correctly for the worker processes
for authFile in [
os.path.join(MalcolmPath, os.path.join('nginx', 'htpasswd')),
os.path.join(MalcolmPath, os.path.join('htadmin', 'config.ini')),
os.path.join(MalcolmPath, os.path.join('htadmin', 'metadata')),
]:
# chmod 644 authFile
os.chmod(authFile, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
for authFile in [
os.path.join(MalcolmPath, os.path.join('nginx', 'nginx_ldap.conf')),
os.path.join(MalcolmPath, '.opensearch.primary.curlrc'),
os.path.join(MalcolmPath, '.opensearch.secondary.curlrc'),
os.path.join(MalcolmPath, os.path.join('netbox', os.path.join('env', 'netbox.env'))),
os.path.join(MalcolmPath, os.path.join('netbox', os.path.join('env', 'postgres.env'))),
os.path.join(MalcolmPath, os.path.join('netbox', os.path.join('env', 'redis-cache.env'))),
os.path.join(MalcolmPath, os.path.join('netbox', os.path.join('env', 'redis.env'))),
]:
# chmod 600 authFile
os.chmod(authFile, stat.S_IRUSR | stat.S_IWUSR)
# make sure some directories exist before we start
boundPathsToCreate = (
BoundPath("arkime", "/opt/arkime/logs", False, None, None),
BoundPath("arkime", "/opt/arkime/raw", False, None, None),
BoundPath("file-monitor", "/zeek/logs", False, None, None),
BoundPath("nginx-proxy", "/var/local/ca-trust", False, None, None),
BoundPath("netbox", "/opt/netbox/netbox/media", False, None, None),
BoundPath("netbox-postgres", "/var/lib/postgresql/data", False, None, None),
BoundPath("netbox-redis", "/data", False, None, None),
BoundPath("opensearch", "/usr/share/opensearch/data", False, ["nodes"], None),
BoundPath("opensearch", "/opt/opensearch/backup", False, None, None),
BoundPath("pcap-monitor", "/pcap", False, ["processed", "upload"], None),
BoundPath("suricata", "/var/log/suricata", False, ["live"], None),
BoundPath("upload", "/var/www/upload/server/php/chroot/files", False, None, None),
BoundPath("zeek", "/zeek/extract_files", False, None, None),
BoundPath("zeek", "/zeek/upload", False, None, None),
BoundPath("zeek", "/opt/zeek/share/zeek/site/intel", False, ["MISP", "STIX"], None),
BoundPath("zeek-live", "/zeek/live", False, ["spool"], None),
BoundPath("filebeat", "/zeek", False, ["processed", "current", "live", "extract_files", "upload"], None),
)
for boundPath in boundPathsToCreate:
localPath = LocalPathForContainerBindMount(
boundPath.service,
dockerComposeYaml,
boundPath.container_dir,
MalcolmPath,
)
if localPath:
try:
if args.debug:
eprint(f'Ensuring "{localPath}" exists')
os.makedirs(localPath)
except OSError as exc:
if (exc.errno == errno.EEXIST) and os.path.isdir(localPath):
pass
else:
raise
if boundPath.relative_dirs:
for relDir in GetIterable(boundPath.relative_dirs):
tmpPath = os.path.join(localPath, relDir)
try:
if args.debug:
eprint(f'Ensuring "{tmpPath}" exists')
os.makedirs(tmpPath)
except OSError as exc:
if (exc.errno == errno.EEXIST) and os.path.isdir(tmpPath):
pass
else:
raise
# touch the zeek intel file
open(os.path.join(MalcolmPath, os.path.join('zeek', os.path.join('intel', '__load__.zeek'))), 'a').close()
# clean up any leftover intel update locks
shutil.rmtree(os.path.join(MalcolmPath, os.path.join('zeek', os.path.join('intel', 'lock'))), ignore_errors=True)
# increase COMPOSE_HTTP_TIMEOUT to be ridiculously large so docker-compose never times out the TTY doing debug output
osEnv = os.environ.copy()
osEnv['COMPOSE_HTTP_TIMEOUT'] = '100000000'
# docker-compose use local temporary path
osEnv['TMPDIR'] = MalcolmTmpPath
# start docker
err, out = run_process([dockerComposeBin, '-f', args.composeFile, 'up', '--detach'], env=osEnv, debug=args.debug)
if err == 0:
eprint("Started Malcolm\n\n")
eprint("In a few minutes, Malcolm services will be accessible via the following URLs:")
eprint("------------------------------------------------------------------------------")
eprint(" - Arkime: https://localhost/")
eprint(" - OpenSearch Dashboards: https://localhost/dashboards/")
eprint(" - PCAP upload (web): https://localhost/upload/")
eprint(" - PCAP upload (sftp): sftp://[email protected]:8022/files/")
eprint(" - Host and subnet name mapping editor: https://localhost/name-map-ui/")
eprint(" - NetBox: https://localhost/netbox/\n")
eprint(" - Account management: https://localhost:488/\n")
eprint(" - Documentation: https://localhost/readme/\n")
else:
eprint("Malcolm failed to start\n")
eprint("\n".join(out))
exit(err)
###################################################################################################
def authSetup(wipe=False):
global args
global dockerBin
global dockerComposeBin
global opensslBin
if YesOrNo('Store administrator username/password for local Malcolm access?', default=True):
# prompt username and password
usernamePrevious = None
password = None
passwordConfirm = None
passwordEncrypted = ''
while True:
username = AskForString("Administrator username")
if len(username) > 0:
break
while True:
password = AskForPassword(f"{username} password: ")
passwordConfirm = AskForPassword(f"{username} password (again): ")
if password == passwordConfirm:
break
eprint("Passwords do not match")
# get previous admin username to remove from htpasswd file if it's changed
authEnvFile = os.path.join(MalcolmPath, 'auth.env')
if os.path.isfile(authEnvFile):
prevAuthInfo = defaultdict(str)
with open(authEnvFile, 'r') as f:
for line in f:
try:
k, v = line.rstrip().split("=")
prevAuthInfo[k] = v.strip('"')
except:
pass
if len(prevAuthInfo['MALCOLM_USERNAME']) > 0:
usernamePrevious = prevAuthInfo['MALCOLM_USERNAME']
# get openssl hash of password
err, out = run_process([opensslBin, 'passwd', '-1', '-stdin'], stdin=password, stderr=False, debug=args.debug)
if (err == 0) and (len(out) > 0) and (len(out[0]) > 0):
passwordEncrypted = out[0]
else:
raise Exception('Unable to generate password hash with openssl')
# write auth.env (used by htadmin and file-upload containers)
with open(authEnvFile, 'w') as f:
f.write(
"# Malcolm Administrator username and encrypted password for nginx reverse proxy (and upload server's SFTP access)\n"
)
f.write(f'MALCOLM_USERNAME={username}\n')
f.write(f'MALCOLM_PASSWORD={b64encode(passwordEncrypted.encode()).decode("ascii")}\n')
os.chmod(authEnvFile, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
# create or update the htpasswd file
htpasswdFile = os.path.join(MalcolmPath, os.path.join('nginx', 'htpasswd'))
htpasswdCmd = ['htpasswd', '-i', '-B', htpasswdFile, username]
if not os.path.isfile(htpasswdFile):
htpasswdCmd.insert(1, '-c')
err, out = run_process(htpasswdCmd, stdin=password, stderr=True, debug=args.debug)
if err != 0:
raise Exception(f'Unable to generate htpasswd file: {out}')
# if the admininstrator username has changed, remove the previous administrator username from htpasswd
if (usernamePrevious is not None) and (usernamePrevious != username):
htpasswdLines = list()
with open(htpasswdFile, 'r') as f:
htpasswdLines = f.readlines()
with open(htpasswdFile, 'w') as f:
for line in htpasswdLines:
if not line.startswith(f"{usernamePrevious}:"):
f.write(line)
# configure default LDAP stuff (they'll have to edit it by hand later)
ldapConfFile = os.path.join(MalcolmPath, os.path.join('nginx', 'nginx_ldap.conf'))
if not os.path.isfile(ldapConfFile):
ldapDefaults = defaultdict(str)
if os.path.isfile(os.path.join(MalcolmPath, '.ldap_config_defaults')):
ldapDefaults = defaultdict(str)
with open(os.path.join(MalcolmPath, '.ldap_config_defaults'), 'r') as f:
for line in f:
try:
k, v = line.rstrip().split("=")
ldapDefaults[k] = v.strip('"').strip("'")
except:
pass
ldapProto = ldapDefaults.get("LDAP_PROTO", "ldap://")
ldapHost = ldapDefaults.get("LDAP_HOST", "ds.example.com")
ldapPort = ldapDefaults.get("LDAP_PORT", "3268")
ldapType = ldapDefaults.get("LDAP_SERVER_TYPE", "winldap")
if ldapType == "openldap":
ldapUri = 'DC=example,DC=com?uid?sub?(objectClass=posixAccount)'
ldapGroupAttr = "memberUid"
ldapGroupAttrIsDN = "off"
else:
ldapUri = 'DC=example,DC=com?sAMAccountName?sub?(objectClass=person)'
ldapGroupAttr = "member"
ldapGroupAttrIsDN = "on"
with open(ldapConfFile, 'w') as f:
f.write('# This is a sample configuration for the ldap_server section of nginx.conf.\n')
f.write('# Yours will vary depending on how your Active Directory/LDAP server is configured.\n')
f.write('# See https://github.com/kvspb/nginx-auth-ldap#available-config-parameters for options.\n\n')
f.write('ldap_server ad_server {\n')
f.write(f' url "{ldapProto}{ldapHost}:{ldapPort}/{ldapUri}";\n\n')
f.write(' binddn "bind_dn";\n')
f.write(' binddn_passwd "bind_dn_password";\n\n')
f.write(f' group_attribute {ldapGroupAttr};\n')
f.write(f' group_attribute_is_dn {ldapGroupAttrIsDN};\n')
f.write(' require group "CN=malcolm,OU=groups,DC=example,DC=com";\n')
f.write(' require valid_user;\n')
f.write(' satisfy all;\n')
f.write('}\n\n')
f.write('auth_ldap_cache_enabled on;\n')
f.write('auth_ldap_cache_expiration_time 10000;\n')
f.write('auth_ldap_cache_size 1000;\n')
os.chmod(ldapConfFile, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
# populate htadmin config file
with open(os.path.join(MalcolmPath, os.path.join('htadmin', 'config.ini')), 'w') as f:
f.write('; HTAdmin config file.\n\n')
f.write('[application]\n')
f.write('; Change this to customize your title:\n')
f.write('app_title = Malcolm User Management\n\n')
f.write('; htpasswd file\n')
f.write('secure_path = ./config/htpasswd\n')
f.write('; metadata file\n')
f.write('metadata_path = ./config/metadata\n\n')
f.write('; administrator user/password (htpasswd -b -c -B ...)\n')
f.write(f'admin_user = {username}\n\n')
f.write('; username field quality checks\n')
f.write(';\n')
f.write('min_username_len = 4\n')
f.write('max_username_len = 12\n\n')
f.write('; Password field quality checks\n')
f.write(';\n')
f.write('min_password_len = 6\n')
f.write('max_password_len = 20\n\n')
# touch the metadata file
open(os.path.join(MalcolmPath, os.path.join('htadmin', 'metadata')), 'a').close()
# generate HTTPS self-signed certificates
if YesOrNo('(Re)generate self-signed certificates for HTTPS access', default=True):
with pushd(os.path.join(MalcolmPath, os.path.join('nginx', 'certs'))):
# remove previous files
for oldfile in glob.glob("*.pem"):
os.remove(oldfile)
# generate dhparam -------------------------------
err, out = run_process(
[opensslBin, 'dhparam', '-out', 'dhparam.pem', '2048'], stderr=True, debug=args.debug
)
if err != 0:
raise Exception(f'Unable to generate dhparam.pem file: {out}')
# generate key/cert -------------------------------
err, out = run_process(
[
opensslBin,
'req',
'-subj',
'/CN=localhost',
'-x509',
'-newkey',
'rsa:4096',
'-nodes',
'-keyout',
'key.pem',
'-out',
'cert.pem',
'-days',
'3650',
],
stderr=True,
debug=args.debug,
)
if err != 0:
raise Exception(f'Unable to generate key.pem/cert.pem file(s): {out}')
# generate beats/logstash self-signed certificates
logstashPath = os.path.join(MalcolmPath, os.path.join('logstash', 'certs'))
filebeatPath = os.path.join(MalcolmPath, os.path.join('filebeat', 'certs'))
if YesOrNo('(Re)generate self-signed certificates for a remote log forwarder', default=True):
with pushd(logstashPath):
# make clean to clean previous files
for pat in ['*.srl', '*.csr', '*.key', '*.crt', '*.pem']:
for oldfile in glob.glob(pat):
os.remove(oldfile)
# -----------------------------------------------
# generate new ca/server/client certificates/keys
# ca -------------------------------
err, out = run_process([opensslBin, 'genrsa', '-out', 'ca.key', '2048'], stderr=True, debug=args.debug)
if err != 0:
raise Exception(f'Unable to generate ca.key: {out}')
err, out = run_process(
[
opensslBin,
'req',
'-x509',
'-new',
'-nodes',
'-key',
'ca.key',
'-sha256',
'-days',
'9999',
'-subj',
'/C=US/ST=ID/O=sensor/OU=ca',
'-out',
'ca.crt',
],
stderr=True,
debug=args.debug,
)
if err != 0:
raise Exception(f'Unable to generate ca.crt: {out}')
# server -------------------------------
err, out = run_process([opensslBin, 'genrsa', '-out', 'server.key', '2048'], stderr=True, debug=args.debug)
if err != 0:
raise Exception(f'Unable to generate server.key: {out}')
err, out = run_process(
[
opensslBin,
'req',
'-sha512',
'-new',
'-key',
'server.key',
'-out',
'server.csr',
'-config',
'server.conf',
],
stderr=True,
debug=args.debug,
)
if err != 0:
raise Exception(f'Unable to generate server.csr: {out}')
err, out = run_process(
[
opensslBin,
'x509',
'-days',
'3650',
'-req',
'-sha512',
'-in',
'server.csr',
'-CAcreateserial',
'-CA',
'ca.crt',
'-CAkey',
'ca.key',
'-out',
'server.crt',
'-extensions',
'v3_req',
'-extfile',
'server.conf',
],
stderr=True,
debug=args.debug,
)
if err != 0:
raise Exception(f'Unable to generate server.crt: {out}')
shutil.move("server.key", "server.key.pem")
err, out = run_process(
[opensslBin, 'pkcs8', '-in', 'server.key.pem', '-topk8', '-nocrypt', '-out', 'server.key'],
stderr=True,
debug=args.debug,
)
if err != 0:
raise Exception(f'Unable to generate server.key: {out}')
# client -------------------------------