-
Notifications
You must be signed in to change notification settings - Fork 0
/
sfcli.py
executable file
·1453 lines (1242 loc) · 44.8 KB
/
sfcli.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 -*-
# -------------------------------------------------------------------------------
# Name: sfcli
# Purpose: Command Line Interface for SpiderFoot.
#
# Author: Steve Micallef <steve@binarypool.com>
#
# Created: 03/05/2017
# Copyright: (c) Steve Micallef 2017
# Licence: MIT
# -------------------------------------------------------------------------------
import argparse
import cmd
import codecs
import io
import json
import os
import re
import shlex
import sys
import time
from os.path import expanduser
import requests
ASCII_LOGO = r"""
_________ .__ .___ ___________ __
/ _____/_____ |__| __| _/__________\_ _____/___ _____/ |_
\_____ \\____ \| |/ __ |/ __ \_ __ \ __)/ _ \ / _ \ __\
/ \ |_> > / /_/ \ ___/| | \/ \( <_> | <_> ) |
/_______ / __/|__\____ |\___ >__| \___ / \____/ \____/|__|
\/|__| \/ \/ \/
Open Source Intelligence Automation."""
COPYRIGHT_INFO = " by Steve Micallef | @spiderfoot\n"
try:
import readline
except ImportError:
import pyreadline as readline
# Colors to make things purty
class bcolors:
GREYBLUE = '\x1b[38;5;25m'
GREY = '\x1b[38;5;243m'
DARKRED = '\x1b[38;5;124m'
DARKGREEN = '\x1b[38;5;30m'
BOLD = '\033[1m'
ENDC = '\033[0m'
GREYBLUE_DARK = '\x1b[38;5;24m'
class SpiderFootCli(cmd.Cmd):
version = "4.0.0"
pipecmd = None
output = None
modules = []
types = []
correlationrules = []
prompt = "sf> "
nohelp = "[!] Unknown command '%s'."
knownscans = []
ownopts = {
"cli.debug": False,
"cli.silent": False,
"cli.color": True,
"cli.output": "pretty",
"cli.history": True,
"cli.history_file": "",
"cli.spool": False,
"cli.spool_file": "",
"cli.ssl_verify": True,
"cli.username": "",
"cli.password": "",
"cli.server_baseurl": "http://127.0.0.1:5001"
}
def default(self, line):
if line.startswith('#'):
return
self.edprint("Unknown command")
# Auto-complete for these commands
def complete_start(self, text, line, startidx, endidx):
return self.complete_default(text, line, startidx, endidx)
def complete_find(self, text, line, startidx, endidx):
return self.complete_default(text, line, startidx, endidx)
def complete_data(self, text, line, startidx, endidx):
return self.complete_default(text, line, startidx, endidx)
# Command completion for arguments
def complete_default(self, text, line, startidx, endidx):
ret = list()
if not isinstance(text, str):
return ret
if not isinstance(line, str):
return ret
if "-m" in line and line.find("-m") > line.find("-t"):
for m in self.modules:
if m.startswith(text):
ret.append(m)
if "-t" in line and line.find("-t") > line.find("-m"):
for t in self.types:
if t.startswith(text):
ret.append(t)
return ret
def dprint(self, msg, err=False, deb=False, plain=False, color=None):
cout = ""
sout = ""
pfx = ""
col = ""
if err:
pfx = "[!]"
if self.ownopts['cli.color']:
col = bcolors.DARKRED
else:
pfx = "[*]"
if self.ownopts['cli.color']:
col = bcolors.DARKGREEN
if deb:
if not self.ownopts["cli.debug"]:
return
pfx = "[+]"
if self.ownopts['cli.color']:
col = bcolors.GREY
if color:
pfx = ""
col = color
if err or not self.ownopts["cli.silent"]:
if not plain or color:
cout = col + bcolors.BOLD + pfx + " " + bcolors.ENDC + col + msg + bcolors.ENDC
# Never include color in the spool
sout = pfx + " " + msg
else:
cout = msg
sout = msg
print(cout)
if self.ownopts['cli.spool']:
f = codecs.open(self.ownopts['cli.spool_file'], "a", encoding="utf-8")
f.write(sout)
f.write('\n')
f.close()
# Shortcut commands
def do_debug(self, line):
"""debug
Short-cut command for set cli.debug = 1"""
if self.ownopts['cli.debug']:
val = "0"
else:
val = "1"
return self.do_set("cli.debug = " + val)
def do_spool(self, line):
"""spool
Short-cut command for set cli.spool = 1/0"""
if self.ownopts['cli.spool']:
val = "0"
else:
val = "1"
if self.ownopts['cli.spool_file']:
return self.do_set("cli.spool = " + val)
self.edprint("You haven't set cli.spool_file. Set that before enabling spooling.")
return None
def do_history(self, line):
"""history [-l]
Short-cut command for set cli.history = 1/0.
Add -l to just list the history."""
c = self.myparseline(line)
if '-l' in c[0]:
i = 0
while i < readline.get_current_history_length():
self.dprint(readline.get_history_item(i), plain=True)
i += 1
return None
if self.ownopts['cli.history']:
val = "0"
else:
val = "1"
return self.do_set("cli.history = " + val)
# Run before all commands to handle history and spooling
def precmd(self, line):
if self.ownopts['cli.history'] and line != "EOF":
f = codecs.open(self.ownopts["cli.history_file"], "a", encoding="utf-8")
f.write(line)
f.write('\n')
f.close()
if self.ownopts['cli.spool']:
f = codecs.open(self.ownopts["cli.spool_file"], "a", encoding="utf-8")
f.write(self.prompt + line)
f.write('\n')
f.close()
return line
# Debug print
def ddprint(self, msg):
self.dprint(msg, deb=True)
# Error print
def edprint(self, msg):
self.dprint(msg, err=True)
# Print nice tables.
def pretty(self, data, titlemap=None):
if not data:
return ""
out = list()
# Get the column titles
maxsize = dict()
if type(data[0]) == dict:
cols = list(data[0].keys())
else:
# for lists, use the index numbers as titles
cols = list(map(str, list(range(0, len(data[0])))))
# Strip out columns that don't have titles
if titlemap:
nc = list()
for c in cols:
if c in titlemap:
nc.append(c)
cols = nc
spaces = 2
# Find the maximum column sizes
for r in data:
for i, c in enumerate(r):
if type(r) == list:
# we have list index
cn = str(i)
if type(c) == int:
v = str(c)
if type(c) == str:
v = c
else:
# we have a dict key
cn = c
v = str(r[c])
# print(str(cn) + ", " + str(c) + ", " + str(v))
if len(v) > maxsize.get(cn, 0):
maxsize[cn] = len(v)
# Adjust for long titles
if titlemap:
for c in maxsize:
if len(titlemap.get(c, c)) > maxsize[c]:
maxsize[c] = len(titlemap.get(c, c))
# Display the column titles
for i, c in enumerate(cols):
if titlemap:
t = titlemap.get(c, c)
else:
t = c
# out += t
out.append(t)
sdiff = maxsize[c] - len(t) + 1
# out += " " * spaces
out.append(" " * spaces)
if sdiff > 0 and i < len(cols) - 1:
# out += " " * sdiff
out.append(" " * sdiff)
# out += "\n"
out.append('\n')
# Then the separator
for i, c in enumerate(cols):
# out += "-" * ((maxsize[c]+spaces))
out.append("-" * ((maxsize[c] + spaces)))
if i < len(cols) - 1:
# out += "+"
out.append("+")
# out += "\n"
out.append("\n")
# Then the actual data
# ts = time.time()
for r in data:
i = 0
di = 0
tr = type(r)
for c in r:
if tr == list:
# we have list index
cn = str(i)
tc = type(c)
if tc == int:
v = str(c)
if tc == str:
v = c
else:
# we have a dict key
cn = c
v = str(r[c])
if cn not in cols:
i += 1
continue
out.append(v)
lv = len(v)
# there is a preceeding space if this is after the
# first column
# sdiff = number of spaces between end of word and |
if di == 0:
sdiff = (maxsize[cn] - lv) + spaces
else:
sdiff = (maxsize[cn] - lv) + spaces - 1
if di < len(cols) - 1:
# out += " " * sdiff
out.append(" " * sdiff)
if di < len(cols) - 1:
# out += "| "
out.append("| ")
di += 1
i += 1
# out += "\n"
out.append("\n")
# print("time: " + str(time.time() - ts))
return ''.join(out)
# Make a request to the SpiderFoot server
def request(self, url, post=None):
if not url:
self.edprint("Invalid request URL")
return None
if not isinstance(url, str):
self.edprint(f"Invalid request URL: {url}")
return None
# logging.basicConfig()
# logging.getLogger().setLevel(logging.DEBUG)
# requests_log = logging.getLogger("requests.packages.urllib3")
# requests_log.setLevel(logging.DEBUG)
# requests_log.propagate = True
headers = {
"User-agent": "SpiderFoot-CLI/" + self.version,
"Accept": "application/json"
}
try:
self.ddprint(f"Fetching: {url}")
if not post:
r = requests.get(
url,
headers=headers,
verify=self.ownopts['cli.ssl_verify'],
auth=requests.auth.HTTPDigestAuth(
self.ownopts['cli.username'],
self.ownopts['cli.password']
)
)
else:
self.ddprint(f"Posting: {post}")
r = requests.post(
url,
headers=headers,
verify=self.ownopts['cli.ssl_verify'],
auth=requests.auth.HTTPDigestAuth(
self.ownopts['cli.username'],
self.ownopts['cli.password']
),
data=post
)
self.ddprint(f"Response: {r}")
if r.status_code == requests.codes.ok: # pylint: disable=no-member
return r.text
r.raise_for_status()
except BaseException as e:
self.edprint(f"Failed communicating with server: {e}")
return None
def emptyline(self):
return
def completedefault(self, text, line, begidx, endidx):
return []
# Parse the command line, returns a list of lists:
# sf> scans "blahblah test" | top 10 | grep foo ->
# [[ 'blahblah test' ], [[ 'top', '10' ], [ 'grep', 'foo']]]
def myparseline(self, cmdline, replace=True):
ret = [list(), list()]
if not cmdline:
return ret
try:
s = shlex.split(cmdline)
except Exception as e:
self.edprint(f"Error parsing command: {e}")
return ret
for c in s:
if c == '|':
break
if replace and c.startswith("$") and c in self.ownopts:
ret[0].append(self.ownopts[c])
else:
ret[0].append(c)
if s.count('|') == 0:
return ret
# Handle any pipe commands at the end
ret[1] = list()
i = 0
ret[1].append(list())
for t in s[(s.index('|') + 1):]:
if t == '|':
i += 1
ret[1].append(list())
# Replace variables
elif t.startswith("$") and t in self.ownopts:
ret[1][i].append(self.ownopts[t])
else:
ret[1][i].append(t)
return ret
# Send the command output to the user, processing the pipes
# that may have been used.
def send_output(self, data, cmd, titles=None, total=True, raw=False):
out = None
try:
if raw:
j = data
totalrec = 0
else:
j = json.loads(data)
totalrec = len(j)
except BaseException as e:
self.edprint(f"Unable to parse data from server: {e}")
return
if raw:
out = data
else:
if self.ownopts['cli.output'] == "json":
out = json.dumps(j, indent=4, separators=(',', ': '))
if self.ownopts['cli.output'] == "pretty":
out = self.pretty(j, titlemap=titles)
if not out:
self.edprint(f"Unknown output format '{self.ownopts['cli.output']}'.")
return
c = self.myparseline(cmd)
# If no pipes, just disply the output
if len(c[1]) == 0:
self.dprint(out, plain=True)
if total:
self.dprint(f"Total records: {totalrec}")
return
for pc in c[1]:
newout = ""
if len(pc) == 0:
self.edprint("Invalid syntax.")
return
pipecmd = pc[0]
pipeargs = " ".join(pc[1:])
if pipecmd not in ["str", "regex", "file", "grep", "top", "last"]:
self.edprint("Unrecognised pipe command.")
return
if pipecmd == "regex":
p = re.compile(pipeargs, re.IGNORECASE)
for r in out.split("\n"):
if re.match(p, r.strip()):
newout += r + "\n"
if pipecmd in ['str', 'grep']:
for r in out.split("\n"):
if pipeargs.lower() in r.strip().lower():
newout += r + "\n"
if pipecmd == "top":
if not pipeargs.isdigit():
self.edprint("Invalid syntax.")
return
newout = "\n".join(out.split("\n")[0:int(pipeargs)])
if pipecmd == "last":
if not pipeargs.isdigit():
self.edprint("Invalid syntax.")
return
tot = len(out.split("\n"))
i = tot - int(pipeargs)
newout = "\n".join(out.split("\n")[i:])
if pipecmd == "file":
try:
f = codecs.open(pipeargs, "w", encoding="utf-8")
f.write(out)
f.close()
except BaseException as e:
self.edprint(f"Unable to write to file: {e}")
return
self.dprint(f"Successfully wrote to file '{pipeargs}'.")
return
out = newout
self.dprint(newout, plain=True)
# Run SQL against the DB.
def do_query(self, line):
"""query <SQL query>
Run an <SQL query> against the database."""
c = self.myparseline(line)
if len(c[0]) < 1:
self.edprint("Invalid syntax.")
return
query = ' '.join(c[0])
d = self.request(self.ownopts['cli.server_baseurl'] + "/query",
post={"query": query})
if not d:
return
j = json.loads(d)
if j[0] == "ERROR":
self.edprint(f"Error running your query: {j[1]}")
return
self.send_output(d, line)
# Ping the server.
def do_ping(self, line):
"""ping
Ping the SpiderFoot server to ensure it's responding."""
d = self.request(self.ownopts['cli.server_baseurl'] + "/ping")
if not d:
return
s = json.loads(d)
if s[0] == "SUCCESS":
self.dprint(f"Server {self.ownopts['cli.server_baseurl']} responding.")
self.do_modules("", cacheonly=True)
self.do_types("", cacheonly=True)
else:
self.dprint(f"Something odd happened: {d}")
if s[1] != self.version:
self.edprint(f"Server and CLI version are not the same ({s[1]} / {self.version}). This could lead to unpredictable results!")
# List all SpiderFoot modules.
def do_modules(self, line, cacheonly=False):
"""modules
List all available modules and their descriptions."""
d = self.request(self.ownopts['cli.server_baseurl'] + "/modules")
if not d:
return
if cacheonly:
j = json.loads(d)
for m in j:
self.modules.append(m['name'])
return
self.send_output(d, line, titles={"name": "Module name",
"descr": "Description"})
# List all SpiderFoot correlation rules
def do_correlationrules(self, line, cacheonly=False):
"""correlations
List all available correlation rules and their descriptions."""
d = self.request(self.ownopts['cli.server_baseurl'] + "/correlationrules")
if not d:
return
if cacheonly:
j = json.loads(d)
for m in j:
self.correlationrules.append(m['name'])
return
self.send_output(d, line, titles={"id": "Correlation rule ID",
"name": "Name",
"risk": "Risk"})
# List all SpiderFoot data element types.
def do_types(self, line, cacheonly=False):
"""types
List all available element types and their descriptions."""
d = self.request(self.ownopts['cli.server_baseurl'] + "/eventtypes")
if not d:
return
if cacheonly:
j = json.loads(d)
for t in j:
self.types.append(t[0])
return
self.send_output(
d,
line,
titles={
"1": "Element description",
"0": "Element name"
}
)
# Load commands from a file.
def do_load(self, line):
"""load <file>
Execute SpiderFoot CLI commands found in <file>."""
pass
# Get scan info and config.
def do_scaninfo(self, line):
"""scaninfo <sid> [-c]
Get status information for scan ID <sid>, optionally also its
configuration if -c is supplied."""
c = self.myparseline(line)
if len(c[0]) < 1:
self.edprint("Invalid syntax.")
return
sid = c[0][0]
d = self.request(self.ownopts['cli.server_baseurl'] + f"/scanopts?id={sid}")
if not d:
return
j = json.loads(d)
if len(j) == 0:
self.dprint("No such scan exists.")
return
out = list()
out.append(f"Name: {j['meta'][0]}")
out.append(f"ID: {sid}")
out.append(f"Target: {j['meta'][1]}")
out.append(f"Started: {j['meta'][3]}")
out.append(f"Completed: {j['meta'][4]}")
out.append(f"Status: {j['meta'][5]}")
if "-c" in c[0]:
out.append("Configuration:")
for k in sorted(j['config']):
out.append(f" {k} = {j['config'][k]}")
self.send_output("\n".join(out), line, total=False, raw=True)
# List scans.
def do_scans(self, line):
"""scans [-x]
List all scans, past and present. -x for extended view."""
d = self.request(self.ownopts['cli.server_baseurl'] + "/scanlist")
if not d:
return
j = json.loads(d)
if len(j) == 0:
self.dprint("No scans exist.")
return
c = self.myparseline(line)
titles = dict()
if "-x" in c[0]:
titles = {
"0": "ID",
"1": "Name",
"2": "Target",
"4": "Started",
"5": "Finished",
"6": "Status",
"7": "Total Elements"
}
else:
titles = {
"0": "ID",
"2": "Target",
"6": "Status",
"7": "Total Elements"
}
self.send_output(d, line, titles=titles)
# Show the correlation results from a scan.
def do_correlations(self, line):
"""correlations <sid> [-c correlation_id]
Get the correlation results for scan ID <sid> and optionally the
events associated with a correlation result [correlation_id] to
get the results for a particular correlation."""
c = self.myparseline(line)
if len(c[0]) < 1:
self.edprint("Invalid syntax.")
return
post = {"id": c[0][0]}
if "-c" in c[0]:
post['correlationId'] = c[0][c[0].index("-c") + 1]
url = self.ownopts['cli.server_baseurl'] + "/scaneventresults"
titles = {
"10": "Type",
"1": "Data"
}
else:
url = self.ownopts['cli.server_baseurl'] + "/scancorrelations"
titles = {
"0": "ID",
"1": "Title",
"3": "Risk",
"7": "Data Elements"
}
d = self.request(url, post=post)
if not d:
return
j = json.loads(d)
if len(j) < 1:
self.dprint("No results.")
return
self.send_output(d, line, titles=titles)
# Show the data from a scan.
def do_data(self, line):
"""data <sid> [-t type] [-x] [-u]
Get the scan data for scan ID <sid> and optionally the element
type [type] (e.g. EMAILADDR), [type]. Use -x for extended format.
Use -u for a unique set of results."""
c = self.myparseline(line)
if len(c[0]) < 1:
self.edprint("Invalid syntax.")
return
post = {"id": c[0][0]}
if "-t" in c[0]:
post["eventType"] = c[0][c[0].index("-t") + 1]
else:
post["eventType"] = "ALL"
if "-u" in c[0]:
url = self.ownopts['cli.server_baseurl'] + "/scaneventresultsunique"
titles = {
"0": "Data"
}
else:
url = self.ownopts['cli.server_baseurl'] + "/scaneventresults"
titles = {
"10": "Type",
"1": "Data"
}
d = self.request(url, post=post)
if not d:
return
j = json.loads(d)
if len(j) < 1:
self.dprint("No results.")
return
if "-x" in c[0]:
titles["0"] = "Last Seen"
titles["3"] = "Module"
titles["2"] = "Source Data"
d = d.replace("</SFURL>", "").replace("<SFURL>", "")
self.send_output(d, line, titles=titles)
# Export data from a scan.
def do_export(self, line):
"""export <sid> [-t type] [-f file]
Export the scan data for scan ID <sid> as type [type] to file [file].
Valid types: csv, json, gexf (default: json)."""
c = self.myparseline(line)
if len(c[0]) < 1:
self.edprint("Invalid syntax.")
return
export_format = 'json'
if '-t' in c[0]:
export_format = c[0][c[0].index("-t") + 1]
file = None
if '-f' in c[0]:
file = c[0][c[0].index("-f") + 1]
base_url = self.ownopts['cli.server_baseurl']
post = {"ids": c[0][0]}
if export_format not in ['json', 'csv', 'gexf']:
self.edprint(f"Invalid export format: {export_format}")
return
data = None
if export_format == 'json':
res = self.request(base_url + '/scanexportjsonmulti', post=post)
if not res:
self.dprint("No results.")
return
j = json.loads(res)
if len(j) < 1:
self.dprint("No results.")
return
data = json.dumps(j)
elif export_format == 'csv':
data = self.request(base_url + '/scaneventresultexportmulti', post=post)
elif export_format == 'gexf':
data = self.request(base_url + '/scanvizmulti', post=post)
if not data:
self.dprint("No results.")
return
self.send_output(data, line, titles=None, total=False, raw=True)
if file:
try:
with io.open(file, "w", encoding="utf-8", errors="ignore") as fp:
fp.write(data)
self.dprint(f"Wrote scan {c[0][0]} data to {file}")
except Exception as e:
self.edprint(f"Could not write scan {c[0][0]} data to file '{file}': {e}")
# Show logs.
def do_logs(self, line):
"""logs <sid> [-l count] [-w]
Show the most recent [count] logs for a given scan ID, <sid>.
If no count is supplied, all logs are given.
If -w is supplied, logs will be streamed to the console until
Ctrl-C is entered."""
c = self.myparseline(line)
if len(c[0]) < 1:
self.edprint("Invalid syntax.")
return
sid = c[0][0]
limit = None
if "-l" in c[0]:
limit = c[0][c[0].index("-l") + 1]
if not limit.isdigit():
self.edprint(f"Invalid result count: {limit}")
return
limit = int(limit)
if "-w" not in c[0]:
d = self.request(
self.ownopts['cli.server_baseurl'] + "/scanlog",
post={'id': sid, 'limit': limit}
)
if not d:
return
j = json.loads(d)
if len(j) < 1:
self.dprint("No results.")
return
self.send_output(
d,
line,
titles={
"0": "Generated",
"1": "Type",
"2": "Source",
"3": "Message"
}
)
return
# Get the rowid of the latest log message
d = self.request(
self.ownopts['cli.server_baseurl'] + "/scanlog",
post={'id': sid, 'limit': '1'}
)
if not d:
return
j = json.loads(d)
if len(j) < 1:
self.dprint("No logs (yet?).")
return
rowid = j[0][4]
if not limit:
limit = 10
d = self.request(
self.ownopts['cli.server_baseurl'] + "/scanlog",
post={'id': sid, 'reverse': '1', 'rowId': rowid - limit}
)
if not d:
return
j = json.loads(d)
for r in j:
# self.send_output(str(r), line, total=False, raw=True)
if r[2] == "ERROR":
self.edprint(f"{r[1]}: {r[3]}")
else:
self.dprint(f"{r[1]}: {r[3]}")
try:
while True:
d = self.request(
self.ownopts['cli.server_baseurl'] + "/scanlog",
post={'id': sid, 'reverse': '1', 'rowId': rowid}
)
if not d:
return
j = json.loads(d)
for r in j:
if r[2] == "ERROR":
self.edprint(f"{r[1]}: {r[3]}")
else:
self.dprint(f"{r[1]}: {r[3]}")
rowid = str(r[4])
time.sleep(0.5)
except KeyboardInterrupt:
return
# Start a new scan.
def do_start(self, line):
"""start <target> (-m m1,... | -t t1,... | -u case) [-n name] [-w]
Start a scan against <target> using modules m1,... OR looking
for types t1,...
OR by use case ("all", "investigate", "passive" and "footprint").
Scan be be optionally named [name], without a name the target
will be used.
Use -w to watch the logs from the scan. Ctrl-C to abort the
logging (but will not abort the scan).
"""
c = self.myparseline(line)
if len(c[0]) < 3:
self.edprint("Invalid syntax.")
return None
mods = ""
types = ""
usecase = ""
if "-m" in c[0]:
mods = c[0][c[0].index("-m") + 1]
if "-t" in c[0]:
# Scan by type
types = c[0][c[0].index("-t") + 1]
if "-u" in c[0]:
# Scan by use case
usecase = c[0][c[0].index("-u") + 1]
if not mods and not types and not usecase:
self.edprint("Invalid syntax.")
return None
target = c[0][0]
if "-n" in c[0]:
title = c[0][c[0].index("-n") + 1]
else:
title = target
post = {
"scanname": title,
"scantarget": target,
"modulelist": mods,
"typelist": types,
"usecase": usecase