-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcommander.py
More file actions
executable file
·942 lines (847 loc) · 37.9 KB
/
commander.py
File metadata and controls
executable file
·942 lines (847 loc) · 37.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
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
#!/usr/bin/env python
"""Cyber Hygiene commander.
Feeds scanners jobs, processes output, and stores results in database.
Usage:
commander [options] <working-dir>
commander (-h | --help)
commander --version
Options:
-b --background Run in background (daemonize).
-d --debug Enable debug logging.
-l --stdout-log Log to standard out.
-s SECTION --section=SECTION Configuration section to use.
"""
# easy-installs
# fabric
# python-daemon
from collections import defaultdict
import logging
import os
import Queue
import random
import shutil
import signal
import sys
import threading
import time
import traceback
from ConfigParser import SafeConfigParser
import daemon
from docopt import docopt
import lockfile
from fabric import operations
from fabric.api import task, run, env
from fabric.network import disconnect_all, normalize
from fabric.state import connections
from fabric.tasks import Task, execute
from cyhy.core import *
from cyhy.core.common import DEFAULT_OWNER, SCAN_TYPE, STAGE
from cyhy.db import CHDatabase, database
from cyhy.util import setup_logging
from job_sink import NmapSink, NessusSink, TryAgainSink, NoOpSink
from job_source import DirectoryJobSource, DatabaseJobSource
# fabric configuration
env.command_timeout = 60
env.keepalive = 30
env.use_ssh_config = True
# remote files
DONE_DIR = "runner/done"
DONE_FILE = ".done"
READY_FILE = ".ready"
RUNNING_DIR = "runner/running"
# local files
CONFIG_FILENAME = "/etc/cyhy/commander.conf"
DEFAULT_LOGGER_LEVEL = logging.INFO
DROP_DIR = "drop"
FAILED_DIR = "failed"
LOCK_FILENAME = "cyhy-commander"
LOG_FILE = "/var/log/cyhy/commander.log"
LOGGER_FORMAT = "%(asctime)-15s %(levelname)s %(name)s - %(message)s"
PUSHED_DIR = "pushed"
STOP_FILE = "stop"
SUCCESS_DIR = "done"
# local job files
me = os.path.realpath(__file__)
myDir = os.path.dirname(me)
jobsDir = os.path.join(myDir, "jobs")
BASESCAN_JOB_FILE = os.path.join(jobsDir, "basescan.sh")
NETSCAN1_JOB_FILE = os.path.join(jobsDir, "netscan1.sh")
NETSCAN2_JOB_FILE = os.path.join(jobsDir, "netscan2.sh")
PORTSCAN_JOB_FILE = os.path.join(jobsDir, "portscan.sh")
SLEEP_JOB_FILE = os.path.join(jobsDir, "rand-sleep.py")
VULNSCAN_JOB_FILE = os.path.join(jobsDir, "vulnscan.py")
# config file
DATABASE_NAME = "database-name"
DATABASE_URI = "database-uri"
DEFAULT = "DEFAULT"
DEFAULT_SCHEDULER = "default-scheduler"
DEFAULT_SECTION = "default-section"
JOB_PROCESSING_THREADS = "job-processing-threads"
JOBS_PER_NESSUS_HOST = "jobs-per-nessus-host"
JOBS_PER_NMAP_HOST = "jobs-per-nmap-host"
KEEP_FAILURES = "keep-failures"
KEEP_SUCCESSES = "keep-successes"
NESSUS_HOSTS = "nessus-hosts"
NEXT_SCAN_LIMIT = "next-scan-limit"
NMAP_HOSTS = "nmap-hosts"
POLL_INTERVAL = "poll-interval"
PRODUCTION_SECTION = "production"
SHUTDOWN_WHEN_IDLE = "shutdown-when-idle"
TEST_MODE = "test-mode"
TESTING_PURGE_SECTION = "testing-purge"
TESTING_SECTION = "testing"
# TODO eventual config options
IPS_PER_BASESCAN_JOB = 32
IPS_PER_NETSCAN1_JOB = 128
IPS_PER_NETSCAN2_JOB = 128 / 2
IPS_PER_PORTSCAN_JOB = 32 / 4
IPS_PER_VULNSCAN_JOB = 4
RANDOMIZE_SOURCES = True
NESSUS_WORKGROUP = "nessus"
NMAP_WORKGROUP = "nmap"
# The number of exceptions to allow before putting a host on "cooldown".
#
# A host on cooldown is removed from any work group lists it is on for the
# duration of its cooldown period. This means that the existing connection is
# closed, and no attempts are made to interact with the host until the below
# cooldown duration has expired. Once it has, the host is restored to the
# list(s) it was removed from and normal operations for that host continue.
NUM_EXCEPTIONS_ALLOWED = 2
# How long should a host remain on cooldown
#
# This value is in seconds, but it is set up to use minutes for granularity. The
# second value should be changed to modify the cooldown duration.
COOLDOWN_DURATION = 60 * 30
class Commander(object):
def __init__(self, config_section=None, debug_logging=False, console_logging=False):
# Set up logging first in order to log any errors as soon as possible.
self.__logger = logging.getLogger(__name__)
self.__setup_logging(debug_logging, console_logging)
self.__all_hosts_idle = False
self.__config_section = config_section
self.__db = None
self.__failed_job_queue = None
self.__failure_sinks = []
self.__host_exceptions = defaultdict(lambda: 0)
self.__hosts_on_cooldown = []
self.__is_processing_jobs = True
self.__is_running = True
self.__job_processing_sleep_duration = 1
self.__keep_failures = False
self.__keep_successes = False
self.__log_output_sleep_duration = 10
self.__nessus_sources = []
self.__next_scan_limit = 2000
self.__nmap_sources = []
self.__queue_monitor_output_lock = threading.Lock()
self.__setup_directories()
self.__shutdown_when_idle = False
self.__success_sinks = []
self.__successful_job_queue = None
self.__test_mode = False
def __setup_logging(self, debug_logging, console_logging):
# get default logging setup
if debug_logging:
level = logging.DEBUG
else:
level = DEFAULT_LOGGER_LEVEL
if console_logging:
setup_logging(level, console=True)
else:
setup_logging(level, filename=LOG_FILE)
# This is only output if debug in enabled. Skipped outwise.
self.__logger.debug("Debug logging enabled")
def __setup_directories(self):
for directory in (SUCCESS_DIR, PUSHED_DIR, FAILED_DIR):
if not os.path.exists(directory):
self.__logger.info('Creating directory "%s".' % (directory))
os.makedirs(directory)
def __setup_db(self, db_name, uri):
self.__db = database.db_from_connection(uri, db_name)
self.__ch_db = CHDatabase(self.__db, next_scan_limit=self.__next_scan_limit)
def __setup_sources(self):
if self.__test_mode:
self.__nmap_sources.append(
DatabaseJobSource(
SLEEP_JOB_FILE,
self.__db,
job_type=STAGE.NETSCAN1,
count=IPS_PER_NETSCAN1_JOB,
)
)
self.__nmap_sources.append(
DatabaseJobSource(
SLEEP_JOB_FILE,
self.__db,
job_type=STAGE.NETSCAN2,
count=IPS_PER_NETSCAN2_JOB,
)
)
self.__nmap_sources.append(
DatabaseJobSource(
SLEEP_JOB_FILE,
self.__db,
job_type=STAGE.PORTSCAN,
count=IPS_PER_PORTSCAN_JOB,
)
)
self.__nessus_sources.append(
DatabaseJobSource(
SLEEP_JOB_FILE,
self.__db,
job_type=STAGE.VULNSCAN,
count=IPS_PER_VULNSCAN_JOB,
)
)
# self.__nmap_sources.append(DatabaseJobSource(SLEEP_JOB_FILE, self.__db, job_type=STAGE.BASESCAN, count=IPS_PER_BASESCAN_JOB))
else:
self.__nessus_sources.append(DirectoryJobSource(DROP_DIR))
self.__nmap_sources.append(
DatabaseJobSource(
NETSCAN1_JOB_FILE,
self.__db,
job_type=STAGE.NETSCAN1,
count=IPS_PER_NETSCAN1_JOB,
)
)
self.__nmap_sources.append(
DatabaseJobSource(
NETSCAN2_JOB_FILE,
self.__db,
job_type=STAGE.NETSCAN2,
count=IPS_PER_NETSCAN2_JOB,
)
)
self.__nmap_sources.append(
DatabaseJobSource(
PORTSCAN_JOB_FILE,
self.__db,
job_type=STAGE.PORTSCAN,
count=IPS_PER_PORTSCAN_JOB,
)
)
self.__nessus_sources.append(
DatabaseJobSource(
VULNSCAN_JOB_FILE,
self.__db,
job_type=STAGE.VULNSCAN,
count=IPS_PER_VULNSCAN_JOB,
)
)
# self.__nmap_sources.append(DatabaseJobSource(BASESCAN_JOB_FILE, self.__db, job_type=STAGE.BASESCAN, count=IPS_PER_BASESCAN_JOB))
def __setup_sinks(self):
if self.__test_mode:
noop_sink = NoOpSink(self.__db)
self.__success_sinks.append(noop_sink)
else:
netscan1_sink = NmapSink(self.__db, STAGE.NETSCAN1)
netscan2_sink = NmapSink(self.__db, STAGE.NETSCAN2)
portscan_sink = NmapSink(self.__db, STAGE.PORTSCAN)
vulnscan_sink = NessusSink(self.__db)
# baseline_sink = NmapSink(self.__db, STAGE.BASESCAN)
self.__success_sinks.extend(
(netscan1_sink, netscan2_sink, portscan_sink, vulnscan_sink)
)
self.__failure_sinks = [TryAgainSink(self.__db)]
@task
def __done_jobs(self):
try:
output = run("ls %s" % DONE_DIR)
if output.failed:
self.__logger.warning(
'Unable to get listing of "%s" on %s' % (DONE_DIR, env.host_string)
)
output = ""
doneJobs = output.split()
for job in doneJobs:
jobPath = os.path.join(DONE_DIR, job)
output = run("ls -a %s" % (jobPath))
jobContents = output.split()
if DONE_FILE in jobContents:
self.__logger.info(
"%s is ready for pickup on %s" % (job, env.host_string)
)
donePath = os.path.join(jobPath, DONE_FILE)
exitCode = run("cat %s" % donePath)
if exitCode == "0":
destDir = SUCCESS_DIR
else:
destDir = FAILED_DIR
self.__logger.warning(
"%s had a non-zero exit code: %s" % (job, exitCode)
)
paths = operations.get(jobPath, destDir)
if len(paths.failed) == 0:
self.__logger.info(
"%s was copied successfully from %s to %s"
% (job, env.host_string, destDir)
)
# remove remote dir
run("rm -rf %s" % jobPath)
self.__logger.info(
"%s was removed from %s" % (job, env.host_string)
)
local_job_path = os.path.join(destDir, job)
if destDir == SUCCESS_DIR:
self.__successful_job_queue.put(local_job_path)
else:
self.__failed_job_queue.put(local_job_path)
else:
self.__logger.warning(
"%s is not ready for pickup on %s" % (job, env.host_string)
)
except Exception as e:
self.__logger.error(
"Exception when retrieving done jobs from %s" % env.host_string
)
self.__logger.error(e)
self.__host_exceptions[env.host_string] += 1
@task
def __running_job_count(self):
try:
output = run("ls %s" % RUNNING_DIR)
if output.failed:
self.__logger.warning(
'Unable to get listing of "%s" on %s'
% (RUNNING_DIR, env.host_string)
)
return None
runningJobs = output.split()
count = len(runningJobs)
return count
except Exception as e:
self.__logger.error(
"Exception when retrieving running job count from %s" % env.host_string
)
self.__logger.error(e)
self.__host_exceptions[env.host_string] += 1
@task
def __push_job(self, job_path):
try:
paths = operations.put(job_path, RUNNING_DIR)
if len(paths.failed) == 0:
self.__logger.info(
"%s was pushed successfully to %s" % (job_path, env.host_string)
)
job_name = os.path.basename(job_path)
run("touch %s" % os.path.join(RUNNING_DIR, job_name, READY_FILE))
self.__move_to_pushed(job_path)
else:
self.__logger.error(
"Error pushing %s to host %s" % (job_path, env.host_string)
)
except Exception as e:
self.__logger.error(
"Exception when pushing %s to host %s" % (job_path, env.host_string)
)
self.__logger.error(e)
self.__host_exceptions[env.host_string] += 1
def __unique_filename(self, path):
if not os.path.exists(path):
return path
new_name = "%s.%d" % (os.path.basename(path), int(time.time() * 1000000))
new_path = os.path.join(os.path.dirname(path), new_name)
return new_path
def __move_to_pushed(self, job_path):
if not self.__test_mode:
shutil.rmtree(job_path)
self.__logger.info("%s deleted" % job_path)
else:
dest = os.path.join(PUSHED_DIR, os.path.basename(job_path))
dest = self.__unique_filename(dest)
shutil.move(job_path, dest)
self.__logger.info("%s moved locally to %s" % (job_path, dest))
def __lowest_host(self, counts):
lowest_count = None
lowest_host = None
for (host, count) in counts.items():
if count != None and (lowest_count == None or count < lowest_count):
lowest_host = host
lowest_count = count
return lowest_host
def __all_idle(self, counts):
for (host, count) in counts.items():
if count > 0:
self.__all_hosts_idle = False
return False
if not self.__all_hosts_idle:
self.__all_hosts_idle = True
self.__logger.info("All hosts are now idle.")
if self.__shutdown_when_idle:
self.__logger.warning("Shutting down since all hosts are idle.")
self.__is_running = False
def __job_from_sources(self, sources):
job = None
if RANDOMIZE_SOURCES:
random.shuffle(sources)
for source in sources:
self.__logger.debug("Checking %s for a job." % source)
job = source.get_job()
if job != None:
self.__logger.info("Acquired a job from %s" % source)
break
self.__logger.debug("No available jobs returned by %s" % source)
return job
def __fill_hosts(self, counts, sources, workgroup_name, jobs_per_host):
while True:
lowest_host = self.__lowest_host(counts)
if counts[lowest_host] >= jobs_per_host:
self.__logger.debug("All %s hosts are full" % workgroup_name)
break # everyone is full
job_path = self.__job_from_sources(sources)
if job_path == None:
self.__logger.debug(
"Not enough work available to fill %s hosts" % workgroup_name
)
break # no more work to do
execute(self.__push_job, self, job_path, hosts=[lowest_host])
counts[lowest_host] += 1
def __monitor_job_queues(self):
# Output the number of jobs that are not done for each queue every
# self.__log_output_sleep_duration seconds while work is on the queues.
while self.__is_processing_jobs:
with self.__queue_monitor_output_lock:
self.__logger.debug(
"%d unfinished jobs in the successful job queue"
% self.__successful_job_queue.unfinished_tasks
)
self.__logger.debug(
"%d unfinished jobs in the failed job queue"
% self.__failed_job_queue.unfinished_tasks
)
time.sleep(self.__log_output_sleep_duration)
def __process_queued_jobs(self):
# define an inner function to process jobs
def process_job_from_queue(target_job_queue, job_processing_function):
"""Helper function to process jobs from a queue.
Args:
target_job_queue (Queue.Queue): The queue to get a job to process.
job_processing_function (callable): The function used to process a job.
Returns:
The job path that was processed or None if the queue was empty.
"""
job_path = None
# check the successful jobs queue
try:
job_path = target_job_queue.get(timeout=1)
except Queue.Empty:
return job_path
try:
job_processing_function(job_path)
except Exception, e:
self.__logger.critical(e)
self.__logger.critical(traceback.format_exc())
# report task completion no matter what so the queue can be joined
target_job_queue.task_done()
# return path of the job that was processed
return job_path
# run as long as the commander is processing jobs
while self.__is_processing_jobs:
# process successful job
job_processing_results = process_job_from_queue(
self.__successful_job_queue, self.__process_successful_job
)
# process failed job if a successful job was not processed
if job_processing_results is None:
job_processing_results = process_job_from_queue(
self.__failed_job_queue, self.__process_failed_job
)
# sleep if both queues are empty
if job_processing_results is None:
time.sleep(self.__job_processing_sleep_duration)
def __process_successful_job(self, job_path):
# Get the name of the current thread
thread_name = threading.current_thread().name
for sink in self.__success_sinks:
if sink.can_handle(job_path):
self.__logger.info(
"[%s] Processing %s with %s" % (thread_name, job_path, sink)
)
sink.handle(job_path)
self.__logger.info("[%s] Processing completed" % thread_name)
if not self.__test_mode and not self.__keep_successes:
shutil.rmtree(job_path)
self.__logger.info("[%s] %s deleted" % (thread_name, job_path))
return
self.__logger.warning(
"[%s] No handler was able to process %s" % (thread_name, job_path)
)
def __process_failed_job(self, job_path):
# Get the name of the current thread
thread_name = threading.current_thread().name
for sink in self.__failure_sinks:
if sink.can_handle(job_path):
self.__logger.warning(
"[%s] Processing %s with %s" % (thread_name, job_path, sink)
)
sink.handle(job_path)
self.__logger.info("[%s] Processing completed" % thread_name)
if not self.__test_mode and not self.__keep_failures:
shutil.rmtree(job_path)
self.__logger.info("[%s] %s deleted" % (thread_name, job_path))
return
self.__logger.warning(
"[%s] No handler was able to process %s" % (thread_name, job_path)
)
def handle_term(self, signal, frame):
self.__logger.warning(
"Received signal %d. Shutting down after this work cycle completes."
% signal
)
self.__is_running = False
def __check_stop_file(self):
if os.path.exists(STOP_FILE):
self.__logger.warning(
"Stop file found. Shutting down after this work cycle completes."
)
os.remove(STOP_FILE)
self.__is_running = False
def __check_database_pause(self):
while self.__ch_db.should_commander_pause() and self.__is_running:
self.__logger.info("Commander is paused due to database request.")
time.sleep(self.__log_output_sleep_duration)
self.__check_stop_file()
def __write_config(self):
config = SafeConfigParser()
config.set(None, DATABASE_URI, "mongodb://localhost:27017/")
config.set(None, JOBS_PER_NMAP_HOST, "8")
config.set(None, JOBS_PER_NESSUS_HOST, "8")
config.set(None, JOB_PROCESSING_THREADS, "4")
config.set(None, POLL_INTERVAL, "30")
config.set(None, NEXT_SCAN_LIMIT, "2000")
config.set(None, DEFAULT_SECTION, TESTING_SECTION)
config.set(None, TEST_MODE, "false")
config.set(None, KEEP_FAILURES, "false")
config.set(None, KEEP_SUCCESSES, "false")
config.set(None, SHUTDOWN_WHEN_IDLE, "false")
config.set(None, DEFAULT_SCHEDULER, "PERSISTENT1")
config.add_section(TESTING_SECTION)
config.set(TESTING_SECTION, NMAP_HOSTS, "comma,separated,list")
config.set(TESTING_SECTION, NESSUS_HOSTS, "comma,separated,list")
config.set(TESTING_SECTION, DATABASE_NAME, "test_database")
config.set(TESTING_SECTION, TEST_MODE, "true")
config.add_section(TESTING_PURGE_SECTION)
config.set(TESTING_PURGE_SECTION, JOBS_PER_NMAP_HOST, "0")
config.set(TESTING_PURGE_SECTION, JOBS_PER_NESSUS_HOST, "0")
config.set(TESTING_PURGE_SECTION, SHUTDOWN_WHEN_IDLE, "true")
config.set(TESTING_PURGE_SECTION, NMAP_HOSTS, "comma,separated,list")
config.set(TESTING_PURGE_SECTION, NESSUS_HOSTS, "comma,separated,list")
config.set(TESTING_PURGE_SECTION, DATABASE_NAME, "test_database")
config.set(TESTING_PURGE_SECTION, TEST_MODE, "true")
config.add_section(PRODUCTION_SECTION)
config.set(PRODUCTION_SECTION, NMAP_HOSTS, "comma,separated,list")
config.set(PRODUCTION_SECTION, NESSUS_HOSTS, "comma,separated,list")
config.set(PRODUCTION_SECTION, DATABASE_NAME, "test_database")
with open(CONFIG_FILENAME, "wb") as config_file:
config.write(config_file)
def __read_config(self):
config = SafeConfigParser()
config.read([CONFIG_FILENAME])
return config
def __setup_default_owner(self, scheduler):
"""Ensures that a RequestDoc exists in the database for the default owner.
This function checks if a RequestDoc for the default owner exists, and
if not, creates one with default values. This function also enables
scanning for the default owner and sets the scheduler as specified.
The default owner owns all "ownerless" HostDocs. The default owner's
RequestDoc does not have a valid list of networks (IP addresses), but it
does have scan windows and concurrency settings. Those "ownerless"
HostDocs are created when a CyHy entity has a hostname that resolves to
IP addresses that are not already owned by a CyHy entity. This is how
we account for cases where an entity owns a hostname, but not
necessarily the IP addresses that it resolves to.
Args:
scheduler (str): The scheduler value to assign to the default
owner's RequestDoc.
Returns:
None
"""
if not self.__db.RequestDoc.get_by_owner(DEFAULT_OWNER):
self.__logger.info(
"%s request document does not exist; creating..." % DEFAULT_OWNER
)
# Create a new request document populated with default values
request = self.__db.RequestDoc()
# Customize request document for the default owner
request["_id"] = DEFAULT_OWNER
request["agency"]["acronym"] = DEFAULT_OWNER
request["agency"]["name"] = "Default CyHy system owner"
# Remove the location field; it is not required here
request["agency"].pop("location")
# Enable scanning for default owner
request["scan_types"] = [SCAN_TYPE.CYHY]
request["scheduler"] = scheduler
request.save()
self.__logger.info("%s request document created" % DEFAULT_OWNER)
def do_work(self):
env.warn_only = True
self.__logger.info("Starting up.")
self.__setup_directories()
# process configuration
if not os.path.exists(CONFIG_FILENAME):
print >>sys.stderr, 'Configuration file not found: "%s"' % CONFIG_FILENAME
self.__write_config()
print >>sys.stderr, "A default configuration file was created in the working directory."
print >>sys.stderr, "Please edit and relaunch."
self.__logger.error("Configuration file not found. Exiting.")
sys.exit(-1)
config = self.__read_config()
if self.__config_section == None:
config_section = config.get(DEFAULT, DEFAULT_SECTION)
else:
config_section = self.__config_section
self.__logger.info('Reading configuration section: "%s"' % config_section)
nmap_hosts = config.get(config_section, NMAP_HOSTS).split(",")
nessus_hosts = config.get(config_section, NESSUS_HOSTS).split(",")
# remove any duplicates
nmap_hosts = list(set(nmap_hosts))
nessus_hosts = list(set(nessus_hosts))
# clean up the host lists and sort them
nmap_hosts = sorted([h.strip() for h in nmap_hosts if h])
nessus_hosts = sorted([h.strip() for h in nessus_hosts if h])
# clean up empty lists from config
if not nmap_hosts:
nmap_hosts = None
if not nessus_hosts:
nessus_hosts = None
self.__logger.info("nmap hosts: %s" % nmap_hosts)
self.__logger.info("nessus hosts: %s" % nessus_hosts)
jobs_per_nmap_host = config.getint(config_section, JOBS_PER_NMAP_HOST)
self.__logger.info("Jobs per nmap host: %d", jobs_per_nmap_host)
jobs_per_nessus_host = config.getint(config_section, JOBS_PER_NESSUS_HOST)
self.__logger.info("Jobs per nessus host: %d", jobs_per_nessus_host)
self.__next_scan_limit = config.getint(config_section, NEXT_SCAN_LIMIT)
self.__logger.info("Next scan fetch limit: %d", self.__next_scan_limit)
self.__poll_interval = config.getint(config_section, POLL_INTERVAL)
self.__logger.info("Poll interval: %d", self.__poll_interval)
db_name = config.get(config_section, DATABASE_NAME)
db_uri = config.get(config_section, DATABASE_URI)
self.__setup_db(db_name, db_uri)
self.__logger.info("Database: %s", self.__db)
self.__test_mode = config.getboolean(config_section, TEST_MODE)
self.__logger.info("Test mode: %s", self.__test_mode)
self.__keep_failures = config.getboolean(config_section, KEEP_FAILURES)
job_processing_thread_count = config.getint(
config_section, JOB_PROCESSING_THREADS
)
self.__logger.info(
"Number of job processing threads: %d", job_processing_thread_count
)
self.__logger.info("Keep failed jobs: %s", self.__keep_failures)
self.__keep_successes = config.getboolean(config_section, KEEP_SUCCESSES)
self.__logger.info("Keep successful jobs: %s", self.__keep_successes)
self.__shutdown_when_idle = config.getboolean(
config_section, SHUTDOWN_WHEN_IDLE
)
self.__logger.info("Idle shutdown: %s", self.__shutdown_when_idle)
self.__logger.info('Default owner: "%s"' % DEFAULT_OWNER)
default_scheduler = config.get(config_section, DEFAULT_SCHEDULER)
self.__logger.info('Default scheduler: "%s"' % default_scheduler)
self.__setup_default_owner(default_scheduler)
self.__setup_sources()
self.__setup_sinks()
self.__successful_job_queue = Queue.Queue()
self.__failed_job_queue = Queue.Queue()
# spin up the thread pool to process retrieved work
job_processing_threads = []
for t in range(job_processing_thread_count):
job_processing_thread = threading.Thread(
name="JobProcessor-%d" % t, target=self.__process_queued_jobs
)
job_processing_threads.append(job_processing_thread)
try:
job_processing_thread.start()
except Exception as e:
self.__logger.error("Unable to start job processing thread #%s", t)
self.__logger.error(e)
# bail out
self.__logger.critical(
"Shutting down due to inability to start job processing threads."
)
self.__is_running = False
# spin up a thread to output queue load information
self.__queue_monitor_output_lock.acquire()
job_queue_monitor_thread = threading.Thread(
name="QueueMonitor", target=self.__monitor_job_queues
)
try:
job_queue_monitor_thread.start()
except Exception as e:
self.__logger.error("Unable to start job queue monitoring thread")
self.__logger.error(e)
# bail out
self.__logger.critical(
"Shutting down due to inability to start queue monitoring thread."
)
self.__is_running = False
# pairs of hosts and job sources
work_groups = (
(NMAP_WORKGROUP, nmap_hosts, self.__nmap_sources, jobs_per_nmap_host),
(
NESSUS_WORKGROUP,
nessus_hosts,
self.__nessus_sources,
jobs_per_nessus_host,
),
)
# main work loop
while self.__is_running:
try:
# record time at start of duty cycle
cycle_start_time = time.time()
next_cycle_start_time = cycle_start_time + self.__poll_interval
# check for hosts that are coming off of cooldown
self.__logger.debug("Checking for hosts to bring off of cooldown")
# we don't want to modify the list while we are iterating, so we
# iterate through a copy and remove from the original
for host_info in self.__hosts_on_cooldown[:]:
cooldown_end = host_info["cooldown_start"] + COOLDOWN_DURATION
if time.time() >= cooldown_end:
try:
# Manually set the appropriate environment value
env.host_string = host_info["host"]
# Manually re-connect to the host
for cache_key in host_info["cache_keys"]:
connections.connect(cache_key)
except Exception as e:
self.__logger.error(
"Unable to reconnect to '%s'" % host_info["host"]
)
self.__logger.error(e)
continue
for group in host_info["work_groups"]:
work_groups[group][1].append(host_info["host"])
work_groups[group][1].sort()
self.__hosts_on_cooldown.remove(host_info)
self.__logger.debug(
"Host '%s' has been put back into rotation"
% host_info["host"]
)
else:
self.__logger.debug(
"Host '%s' is out of rotation until %s"
% (
host_info["host"],
# output an ISO 8601 human readable time
time.strftime(
"%Y-%m-%dT%H:%M:%S", time.localtime(cooldown_end)
),
)
)
# check for hosts that have had multiple exceptions
self.__logger.debug("Checking for hosts with too many exceptions")
for (host, count) in self.__host_exceptions.items():
if count > NUM_EXCEPTIONS_ALLOWED:
groups = []
for (index, group) in enumerate(work_groups):
if host in group[1]:
groups.append(index)
group[1].remove(host)
info_dict = {
"host": host,
"cooldown_start": time.time(),
"work_groups": groups,
}
self.__host_exceptions[host] = 0
cache_keys = []
for cache_key in connections.keys():
cuser, chost, cport = normalize(cache_key)
if chost == host:
connections[cache_key].close()
cache_keys.append(cache_key)
info_dict["cache_keys"] = cache_keys
self.__hosts_on_cooldown.append(info_dict)
self.__logger.debug(
"Host '%s' has been removed from rotation" % host
)
# process anything that has completed
self.__logger.debug(
"Checking remotes for completed jobs to download and process"
)
self.__queue_monitor_output_lock.release()
for (workgroup_name, hosts, sources, jobs_per_host) in work_groups:
if hosts == None:
continue
execute(self.__done_jobs, self, hosts=hosts)
# wait for work to process
self.__logger.debug("Waiting for completed jobs to be processed.")
self.__successful_job_queue.join()
self.__failed_job_queue.join()
self.__queue_monitor_output_lock.acquire()
# check for scheduled hosts
self.__logger.debug(
"Checking for scheduled DONE hosts to mark WAITING."
)
self.__ch_db.check_host_next_scans()
# balance the number of hosts that are ready and running
self.__logger.debug("Balancing READY status of hosts.")
self.__ch_db.balance_ready_hosts()
# push out new work and count
self.__logger.debug("Checking sources for new jobs")
all_workgroup_counts = {} # track counts from each work_group
for (workgroup_name, hosts, sources, jobs_per_host) in work_groups:
if hosts == None:
continue
counts = execute(self.__running_job_count, self, hosts=hosts)
self.__fill_hosts(counts, sources, workgroup_name, jobs_per_host)
all_workgroup_counts.update(counts)
# check to see if all host are idle and log it
self.__all_idle(all_workgroup_counts)
self.__check_stop_file()
if self.__is_running:
now = time.time()
if now < next_cycle_start_time:
sleep_time = next_cycle_start_time - now
self.__logger.debug(
"Sleeping for %1.1f seconds.\n\n\n" % sleep_time
)
time.sleep(sleep_time)
else:
self.__logger.debug(
"No time to sleep. Last cycle took %1.1f seconds.\n\n\n"
% (now - cycle_start_time)
)
self.__check_stop_file()
self.__check_database_pause()
except Exception, e:
self.__logger.critical(e)
self.__logger.critical(traceback.format_exc())
# signal job processing threads to exit once they have finished all
# queued work
self.__is_processing_jobs = False
self.__queue_monitor_output_lock.release()
# wait for the job processing threads to exit
for job_processing_thread in job_processing_threads:
job_processing_thread.join()
# wait for the job queue monitoring thread to exit
job_queue_monitor_thread.join()
self.__logger.info("Shutting down.")
disconnect_all()
def main():
args = docopt(__doc__, version="v1.1.0")
workingDir = os.path.join(os.getcwd(), args["<working-dir>"])
if not os.path.exists(workingDir):
print >>sys.stderr, 'Working directory "%s" does not exist. Attempting to create...' % workingDir
os.mkdir(workingDir)
os.chdir(workingDir)
lock = lockfile.LockFile(os.path.join(workingDir, LOCK_FILENAME), timeout=0)
if lock.is_locked():
print >>sys.stderr, "Cannot start. There is already a cyhy-commander executing in this working directory."
sys.exit(-1)
commander = Commander(args["--section"], args["--debug"], args["--stdout-log"])
if args["--background"]:
context = daemon.DaemonContext(
working_directory=workingDir, umask=0002, pidfile=lock
)
context.signal_map = {
signal.SIGTERM: commander.handle_term,
signal.SIGCHLD: signal.SIG_IGN,
}
with context:
commander.do_work()
else:
signal.signal(signal.SIGTERM, commander.handle_term)
signal.signal(signal.SIGINT, commander.handle_term)
commander.do_work()
if __name__ == "__main__":
main()