-
Notifications
You must be signed in to change notification settings - Fork 13.8k
/
db.rb
2111 lines (1898 loc) · 63.8 KB
/
db.rb
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
# -*- coding: binary -*-
require 'json'
require 'rexml/document'
require 'metasploit/framework/data_service'
require 'metasploit/framework/data_service/remote/http/core'
module Msf
module Ui
module Console
module CommandDispatcher
class Db
require 'tempfile'
include Msf::Ui::Console::CommandDispatcher
include Msf::Ui::Console::CommandDispatcher::Common
include Msf::Ui::Console::CommandDispatcher::Analyze
DB_CONFIG_PATH = 'framework/database'
#
# The dispatcher's name.
#
def name
"Database Backend"
end
#
# Returns the hash of commands supported by this dispatcher.
#
def commands
base = {
"db_connect" => "Connect to an existing data service",
"db_disconnect" => "Disconnect from the current data service",
"db_status" => "Show the current data service status",
"db_save" => "Save the current data service connection as the default to reconnect on startup",
"db_remove" => "Remove the saved data service entry"
}
more = {
"workspace" => "Switch between database workspaces",
"hosts" => "List all hosts in the database",
"services" => "List all services in the database",
"vulns" => "List all vulnerabilities in the database",
"notes" => "List all notes in the database",
"loot" => "List all loot in the database",
"db_import" => "Import a scan result file (filetype will be auto-detected)",
"db_export" => "Export a file containing the contents of the database",
"db_nmap" => "Executes nmap and records the output automatically",
"db_rebuild_cache" => "Rebuilds the database-stored module cache (deprecated)",
"analyze" => "Analyze database information about a specific address or address range",
}
# Always include commands that only make sense when connected.
# This avoids the problem of them disappearing unexpectedly if the
# database dies or times out. See #1923
base.merge(more)
end
def deprecated_commands
[
"db_autopwn",
"db_driver",
"db_hosts",
"db_notes",
"db_services",
"db_vulns",
]
end
#
# Attempts to connect to the previously configured database, and additionally keeps track of
# the currently loaded data service.
#
def load_config(path = nil)
result = Msf::DbConnector.db_connect_from_config(framework, path)
if result[:error]
print_error(result[:error])
end
if result[:data_service_name]
@current_data_service = result[:data_service_name]
end
end
#
# Returns true if the db is connected, prints an error and returns
# false if not.
#
# All commands that require an active database should call this before
# doing anything.
#
def active?
if not framework.db.active
print_error("Database not connected")
return false
end
true
end
def cmd_workspace_help
print_line "Usage:"
print_line " workspace List workspaces"
print_line " workspace -v List workspaces verbosely"
print_line " workspace [name] Switch workspace"
print_line " workspace -a [name] ... Add workspace(s)"
print_line " workspace -d [name] ... Delete workspace(s)"
print_line " workspace -D Delete all workspaces"
print_line " workspace -r <old> <new> Rename workspace"
print_line " workspace -h Show this help information"
print_line
end
def cmd_workspace(*args)
return unless active?
search_term = nil
while (arg = args.shift)
case arg
when '-h','--help'
cmd_workspace_help
return
when '-a','--add'
adding = true
when '-d','--del'
deleting = true
when '-D','--delete-all'
delete_all = true
when '-r','--rename'
renaming = true
when '-v','--verbose'
verbose = true
when '-S', '--search'
search_term = args.shift
else
names ||= []
names << arg
end
end
if adding and names
# Add workspaces
wspace = nil
names.each do |name|
wspace = framework.db.workspaces(name: name).first
if wspace
print_status("Workspace '#{wspace.name}' already existed, switching to it.")
else
wspace = framework.db.add_workspace(name)
print_status("Added workspace: #{wspace.name}")
end
end
framework.db.workspace = wspace
print_status("Workspace: #{framework.db.workspace.name}")
elsif deleting and names
ws_ids_to_delete = []
starting_ws = framework.db.workspace
names.uniq.each do |n|
ws = framework.db.workspaces(name: n).first
ws_ids_to_delete << ws.id if ws
end
if ws_ids_to_delete.count > 0
deleted = framework.db.delete_workspaces(ids: ws_ids_to_delete)
process_deleted_workspaces(deleted, starting_ws)
else
print_status("No workspaces matching the given name(s) were found.")
end
elsif delete_all
ws_ids_to_delete = []
starting_ws = framework.db.workspace
framework.db.workspaces.each do |ws|
ws_ids_to_delete << ws.id
end
deleted = framework.db.delete_workspaces(ids: ws_ids_to_delete)
process_deleted_workspaces(deleted, starting_ws)
elsif renaming
if names.length != 2
print_error("Wrong number of arguments to rename")
return
end
ws_to_update = framework.db.find_workspace(names.first)
unless ws_to_update
print_error("Workspace '#{names.first}' does not exist")
return
end
opts = {
id: ws_to_update.id,
name: names.last
}
begin
updated_ws = framework.db.update_workspace(opts)
if updated_ws
framework.db.workspace = updated_ws if names.first == framework.db.workspace.name
print_status("Renamed workspace '#{names.first}' to '#{updated_ws.name}'")
else
print_error "There was a problem updating the workspace. Setting to the default workspace."
framework.db.workspace = framework.db.default_workspace
return
end
if names.first == Msf::DBManager::Workspace::DEFAULT_WORKSPACE_NAME
print_status("Recreated default workspace")
end
rescue => e
print_error "Failed to rename workspace: #{e.message}"
end
elsif names
name = names.last
# Switch workspace
workspace = framework.db.find_workspace(name)
if workspace
framework.db.workspace = workspace
print_status("Workspace: #{workspace.name}")
else
print_error("Workspace not found: #{name}")
return
end
else
current_workspace = framework.db.workspace
unless verbose
current = nil
framework.db.workspaces.sort_by {|s| s.name}.each do |s|
if s.name == current_workspace.name
current = s.name
else
print_line(" #{s.name}")
end
end
print_line("%red* #{current}%clr") unless current.nil?
return
end
col_names = %w{current name hosts services vulns creds loots notes}
tbl = Rex::Text::Table.new(
'Header' => 'Workspaces',
'Columns' => col_names,
'SortIndex' => -1,
'SearchTerm' => search_term
)
framework.db.workspaces.each do |ws|
tbl << [
current_workspace.name == ws.name ? '*' : '',
ws.name,
framework.db.hosts(workspace: ws.name).count,
framework.db.services(workspace: ws.name).count,
framework.db.vulns(workspace: ws.name).count,
framework.db.creds(workspace: ws.name).count,
framework.db.loots(workspace: ws.name).count,
framework.db.notes(workspace: ws.name).count
]
end
print_line
print_line(tbl.to_s)
end
end
def process_deleted_workspaces(deleted_workspaces, starting_ws)
deleted_workspaces.each do |ws|
print_status "Deleted workspace: #{ws.name}"
if ws.name == Msf::DBManager::Workspace::DEFAULT_WORKSPACE_NAME
framework.db.workspace = framework.db.default_workspace
print_status 'Recreated the default workspace'
elsif ws == starting_ws
framework.db.workspace = framework.db.default_workspace
print_status "Switched to workspace: #{framework.db.workspace.name}"
end
end
end
def cmd_workspace_tabs(str, words)
return [] unless active?
framework.db.workspaces.map { |s| s.name } if (words & ['-a','--add']).empty?
end
def cmd_hosts_help
# This command does some lookups for the list of appropriate column
# names, so instead of putting all the usage stuff here like other
# help methods, just use it's "-h" so we don't have to recreating
# that list
cmd_hosts("-h")
end
# Changes the specified host data
#
# @param host_ranges - range of hosts to process
# @param host_data - hash of host data to be updated
def change_host_data(host_ranges, host_data)
if !host_data || host_data.length != 1
print_error("A single key-value data hash is required to change the host data")
return
end
attribute = host_data.keys[0]
if host_ranges == [nil]
print_error("In order to change the host #{attribute}, you must provide a range of hosts")
return
end
each_host_range_chunk(host_ranges) do |host_search|
next if host_search && host_search.empty?
framework.db.hosts(address: host_search).each do |host|
framework.db.update_host(host_data.merge(id: host.id))
framework.db.report_note(host: host.address, type: "host.#{attribute}", data: host_data[attribute])
end
end
end
def add_host_tag(rws, tag_name)
if rws == [nil]
print_error("In order to add a tag, you must provide a range of hosts")
return
end
opts = Hash.new()
opts[:workspace] = framework.db.workspace
opts[:tag_name] = tag_name
rws.each do |rw|
rw.each do |ip|
opts[:address] = ip
unless framework.db.add_host_tag(opts)
print_error("Host #{ip} could not be found.")
end
end
end
end
def find_host_tags(workspace, host_id)
opts = Hash.new()
opts[:workspace] = workspace
opts[:id] = host_id
framework.db.get_host_tags(opts)
end
def delete_host_tag(rws, tag_name)
opts = Hash.new()
opts[:workspace] = framework.db.workspace
opts[:tag_name] = tag_name
if rws == [nil]
unless framework.db.delete_host_tag(opts)
print_error("Host #{opts[:address].to_s + " " if opts[:address]}could not be found.")
end
else
rws.each do |rw|
rw.each do |ip|
opts[:address] = ip
unless framework.db.delete_host_tag(opts)
print_error("Host #{ip} could not be found.")
end
end
end
end
end
@@hosts_columns = [ 'address', 'mac', 'name', 'os_name', 'os_flavor', 'os_sp', 'purpose', 'info', 'comments']
def cmd_hosts(*args)
return unless active?
onlyup = false
set_rhosts = false
mode = []
delete_count = 0
rhosts = []
host_ranges = []
search_term = nil
output = nil
default_columns = [
'address',
'arch',
'comm',
'comments',
'created_at',
'cred_count',
'detected_arch',
'exploit_attempt_count',
'host_detail_count',
'info',
'mac',
'name',
'note_count',
'os_family',
'os_flavor',
'os_lang',
'os_name',
'os_sp',
'purpose',
'scope',
'service_count',
'state',
'updated_at',
'virtual_host',
'vuln_count',
'workspace_id']
default_columns << 'tags' # Special case
virtual_columns = [ 'svcs', 'vulns', 'workspace', 'tags' ]
col_search = @@hosts_columns
default_columns.delete_if {|v| (v[-2,2] == "id")}
while (arg = args.shift)
case arg
when '-a','--add'
mode << :add
when '-d','--delete'
mode << :delete
when '-c','-C'
list = args.shift
if(!list)
print_error("Invalid column list")
return
end
col_search = list.strip().split(",")
col_search.each { |c|
if not default_columns.include?(c) and not virtual_columns.include?(c)
all_columns = default_columns + virtual_columns
print_error("Invalid column list. Possible values are (#{all_columns.join("|")})")
return
end
}
if (arg == '-C')
@@hosts_columns = col_search
end
when '-u','--up'
onlyup = true
when '-o'
output = args.shift
when '-O'
if (order_by = args.shift.to_i - 1) < 0
print_error('Please specify a column number starting from 1')
return
end
when '-R', '--rhosts'
set_rhosts = true
when '-S', '--search'
search_term = args.shift
when '-i', '--info'
mode << :new_info
info_data = args.shift
when '-n', '--name'
mode << :new_name
name_data = args.shift
when '-m', '--comment'
mode << :new_comment
comment_data = args.shift
when '-t', '--tag'
mode << :tag
tag_name = args.shift
when '-h','--help'
print_line "Usage: hosts [ options ] [addr1 addr2 ...]"
print_line
print_line "OPTIONS:"
print_line " -a,--add Add the hosts instead of searching"
print_line " -d,--delete Delete the hosts instead of searching"
print_line " -c <col1,col2> Only show the given columns (see list below)"
print_line " -C <col1,col2> Only show the given columns until the next restart (see list below)"
print_line " -h,--help Show this help information"
print_line " -u,--up Only show hosts which are up"
print_line " -o <file> Send output to a file in csv format"
print_line " -O <column> Order rows by specified column number"
print_line " -R,--rhosts Set RHOSTS from the results of the search"
print_line " -S,--search Search string to filter by"
print_line " -i,--info Change the info of a host"
print_line " -n,--name Change the name of a host"
print_line " -m,--comment Change the comment of a host"
print_line " -t,--tag Add or specify a tag to a range of hosts"
print_line
print_line "Available columns: #{default_columns.join(", ")}"
print_line
return
else
# Anything that wasn't an option is a host to search for
unless (arg_host_range(arg, host_ranges))
return
end
end
end
if col_search
col_names = col_search
else
col_names = default_columns + virtual_columns
end
mode << :search if mode.empty?
if mode == [:add]
host_ranges.each do |range|
range.each do |address|
host = framework.db.find_or_create_host(:host => address)
print_status("Time: #{host.created_at} Host: host=#{host.address}")
end
end
return
end
cp_hsh = {}
col_names.map do |col|
cp_hsh[col] = { 'MaxChar' => 52 }
end
# If we got here, we're searching. Delete implies search
tbl = Rex::Text::Table.new(
{
'Header' => "Hosts",
'Columns' => col_names,
'ColProps' => cp_hsh,
'SortIndex' => order_by
})
# Sentinel value meaning all
host_ranges.push(nil) if host_ranges.empty?
case
when mode == [:new_info]
change_host_data(host_ranges, info: info_data)
return
when mode == [:new_name]
change_host_data(host_ranges, name: name_data)
return
when mode == [:new_comment]
change_host_data(host_ranges, comments: comment_data)
return
when mode == [:tag]
begin
add_host_tag(host_ranges, tag_name)
rescue => e
if e.message.include?('Validation failed')
print_error(e.message)
else
raise e
end
end
return
when mode.include?(:tag) && mode.include?(:delete)
delete_host_tag(host_ranges, tag_name)
return
end
matched_host_ids = []
each_host_range_chunk(host_ranges) do |host_search|
next if host_search && host_search.empty?
framework.db.hosts(address: host_search, non_dead: onlyup, search_term: search_term).each do |host|
matched_host_ids << host.id
columns = col_names.map do |n|
# Deal with the special cases
if virtual_columns.include?(n)
case n
when "svcs"; host.service_count
when "vulns"; host.vuln_count
when "workspace"; host.workspace.name
when "tags"
found_tags = find_host_tags(framework.db.workspace, host.id)
tag_names = []
found_tags.each { |t| tag_names << t.name }
found_tags * ", "
end
# Otherwise, it's just an attribute
else
host[n] || ""
end
end
tbl << columns
if set_rhosts
addr = (host.scope ? host.address + '%' + host.scope : host.address)
rhosts << addr
end
end
if mode == [:delete]
result = framework.db.delete_host(ids: matched_host_ids)
delete_count += result.size
end
end
if output
print_status("Wrote hosts to #{output}")
::File.open(output, "wb") { |ofd|
ofd.write(tbl.to_csv)
}
else
print_line
print_line(tbl.to_s)
end
# Finally, handle the case where the user wants the resulting list
# of hosts to go into RHOSTS.
set_rhosts_from_addrs(rhosts.uniq) if set_rhosts
print_status("Deleted #{delete_count} hosts") if delete_count > 0
end
def cmd_services_help
# Like cmd_hosts, use "-h" instead of recreating the column list
# here
cmd_services("-h")
end
def cmd_services(*args)
return unless active?
mode = :search
onlyup = false
output_file = nil
set_rhosts = false
col_search = ['port', 'proto', 'name', 'state', 'info']
default_columns = [
'created_at',
'info',
'name',
'port',
'proto',
'state',
'updated_at']
host_ranges = []
port_ranges = []
rhosts = []
delete_count = 0
search_term = nil
opts = {}
# option parsing
while (arg = args.shift)
case arg
when '-a','--add'
mode = :add
when '-d','--delete'
mode = :delete
when '-U', '--update'
mode = :update
when '-u','--up'
onlyup = true
when '-c'
list = args.shift
if(!list)
print_error("Invalid column list")
return
end
col_search = list.strip().split(",")
col_search.each { |c|
if not default_columns.include? c
print_error("Invalid column list. Possible values are (#{default_columns.join("|")})")
return
end
}
when '-p'
unless (arg_port_range(args.shift, port_ranges, true))
return
end
when '-r'
proto = args.shift
if (!proto)
print_status("Invalid protocol")
return
end
proto = proto.strip
when '-s'
namelist = args.shift
if (!namelist)
print_error("Invalid name list")
return
end
names = namelist.strip().split(",")
when '-o'
output_file = args.shift
if (!output_file)
print_error("Invalid output filename")
return
end
output_file = ::File.expand_path(output_file)
when '-O'
if (order_by = args.shift.to_i - 1) < 0
print_error('Please specify a column number starting from 1')
return
end
when '-R', '--rhosts'
set_rhosts = true
when '-S', '--search'
search_term = args.shift
opts[:search_term] = search_term
when '-h','--help'
print_line
print_line "Usage: services [-h] [-u] [-a] [-r <proto>] [-p <port1,port2>] [-s <name1,name2>] [-o <filename>] [addr1 addr2 ...]"
print_line
print_line " -a,--add Add the services instead of searching"
print_line " -d,--delete Delete the services instead of searching"
print_line " -c <col1,col2> Only show the given columns"
print_line " -h,--help Show this help information"
print_line " -s <name> Name of the service to add"
print_line " -p <port> Search for a list of ports"
print_line " -r <protocol> Protocol type of the service being added [tcp|udp]"
print_line " -u,--up Only show services which are up"
print_line " -o <file> Send output to a file in csv format"
print_line " -O <column> Order rows by specified column number"
print_line " -R,--rhosts Set RHOSTS from the results of the search"
print_line " -S,--search Search string to filter by"
print_line " -U,--update Update data for existing service"
print_line
print_line "Available columns: #{default_columns.join(", ")}"
print_line
return
else
# Anything that wasn't an option is a host to search for
unless (arg_host_range(arg, host_ranges))
return
end
end
end
ports = port_ranges.flatten.uniq
if mode == :add
# Can only deal with one port and one service name at a time
# right now. Them's the breaks.
if ports.length != 1
print_error("Exactly one port required")
return
end
if host_ranges.empty?
print_error("Host address or range required")
return
end
host_ranges.each do |range|
range.each do |addr|
info = {
:host => addr,
:port => ports.first.to_i
}
info[:proto] = proto.downcase if proto
info[:name] = names.first.downcase if names and names.first
svc = framework.db.find_or_create_service(info)
print_status("Time: #{svc.created_at} Service: host=#{svc.host.address} port=#{svc.port} proto=#{svc.proto} name=#{svc.name}")
end
end
return
end
# If we got here, we're searching. Delete implies search
col_names = default_columns
if col_search
col_names = col_search
end
tbl = Rex::Text::Table.new({
'Header' => "Services",
'Columns' => ['host'] + col_names,
'SortIndex' => order_by
})
# Sentinel value meaning all
host_ranges.push(nil) if host_ranges.empty?
ports = nil if ports.empty?
matched_service_ids = []
each_host_range_chunk(host_ranges) do |host_search|
next if host_search && host_search.empty?
opts[:workspace] = framework.db.workspace
opts[:hosts] = {address: host_search} if !host_search.nil?
opts[:port] = ports if ports
framework.db.services(opts).each do |service|
unless service.state == 'open'
next if onlyup
end
host = service.host
matched_service_ids << service.id
if mode == :update
service.name = names.first if names
service.proto = proto if proto
service.port = ports.first if ports
framework.db.update_service(service.as_json.symbolize_keys)
end
columns = [host.address] + col_names.map { |n| service[n].to_s || "" }
tbl << columns
if set_rhosts
addr = (host.scope ? host.address + '%' + host.scope : host.address )
rhosts << addr
end
end
end
if (mode == :delete)
result = framework.db.delete_service(ids: matched_service_ids)
delete_count += result.size
end
if (output_file == nil)
print_line(tbl.to_s)
else
# create the output file
::File.open(output_file, "wb") { |f| f.write(tbl.to_csv) }
print_status("Wrote services to #{output_file}")
end
# Finally, handle the case where the user wants the resulting list
# of hosts to go into RHOSTS.
set_rhosts_from_addrs(rhosts.uniq) if set_rhosts
print_status("Deleted #{delete_count} services") if delete_count > 0
end
def cmd_vulns_help
print_line "Print all vulnerabilities in the database"
print_line
print_line "Usage: vulns [addr range]"
print_line
print_line " -h,--help Show this help information"
print_line " -o <file> Send output to a file in csv format"
print_line " -p,--port <portspec> List vulns matching this port spec"
print_line " -s <svc names> List vulns matching these service names"
print_line " -R,--rhosts Set RHOSTS from the results of the search"
print_line " -S,--search Search string to filter by"
print_line " -i,--info Display vuln information"
print_line
print_line "Examples:"
print_line " vulns -p 1-65536 # only vulns with associated services"
print_line " vulns -p 1-65536 -s http # identified as http on any port"
print_line
end
def cmd_vulns(*args)
return unless active?
default_columns = ['Timestamp', 'Host', 'Name', 'References']
host_ranges = []
port_ranges = []
svcs = []
rhosts = []
search_term = nil
show_info = false
set_rhosts = false
output_file = nil
delete_count = 0
while (arg = args.shift)
case arg
# when '-a', '--add'
# mode = :add
when '-d', '--delete' # TODO: This is currently undocumented because it's not officially supported.
mode = :delete
when '-h', '--help'
cmd_vulns_help
return
when '-o', '--output'
output_file = args.shift
if output_file
output_file = File.expand_path(output_file)
else
print_error("Invalid output filename")
return
end
when '-p', '--port'
unless (arg_port_range(args.shift, port_ranges, true))
return
end
when '-s', '--service'
service = args.shift
if (!service)
print_error("Argument required for -s")
return
end
svcs = service.split(/[\s]*,[\s]*/)
when '-R', '--rhosts'
set_rhosts = true
when '-S', '--search'
search_term = args.shift
when '-i', '--info'
show_info = true
else
# Anything that wasn't an option is a host to search for
unless (arg_host_range(arg, host_ranges))
return
end
end
end
if show_info
default_columns << 'Information'
end
# add sentinel value meaning all if empty
host_ranges.push(nil) if host_ranges.empty?
# normalize
ports = port_ranges.flatten.uniq
svcs.flatten!
tbl = Rex::Text::Table.new(
'Header' => 'Vulnerabilities',
'Columns' => default_columns
)
matched_vuln_ids = []
vulns = []
if host_ranges.compact.empty?
vulns = framework.db.vulns({:search_term => search_term})
else
each_host_range_chunk(host_ranges) do |host_search|
next if host_search && host_search.empty?
vulns.concat(framework.db.vulns({:hosts => { :address => host_search }, :search_term => search_term }))
end
end
vulns.each do |vuln|
reflist = vuln.refs.map {|r| r.name}
if (vuln.service)
# Skip this one if the user specified a port and it
# doesn't match.
next unless ports.empty? or ports.include? vuln.service.port
# Same for service names
next unless svcs.empty? or svcs.include?(vuln.service.name)
else
# This vuln has no service, so it can't match
next unless ports.empty? and svcs.empty?
end
matched_vuln_ids << vuln.id
row = []
row << vuln.created_at
row << vuln.host.address
row << vuln.name
row << reflist.join(',')
if show_info
row << vuln.info
end
tbl << row
if set_rhosts
addr = (vuln.host.scope ? vuln.host.address + '%' + vuln.host.scope : vuln.host.address)
rhosts << addr
end
end
if mode == :delete
result = framework.db.delete_vuln(ids: matched_vuln_ids)
delete_count = result.size
end
if output_file
File.write(output_file, tbl.to_csv)
print_status("Wrote vulnerability information to #{output_file}")
else
print_line
print_line(tbl.to_s)
end
# Finally, handle the case where the user wants the resulting list
# of hosts to go into RHOSTS.
set_rhosts_from_addrs(rhosts.uniq) if set_rhosts
print_status("Deleted #{delete_count} vulnerabilities") if delete_count > 0
end
def cmd_notes_help
print_line "Usage: notes [-h] [-t <type1,type2>] [-n <data string>] [-a] [addr range]"
print_line
print_line " -a,--add Add a note to the list of addresses, instead of listing"
print_line " -d,--delete Delete the hosts instead of searching"
print_line " -n,--note <data> Set the data for a new note (only with -a)"
print_line " -t,--type <type1,type2> Search for a list of types, or set single type for add"
print_line " -h,--help Show this help information"
print_line " -R,--rhosts Set RHOSTS from the results of the search"
print_line " -S,--search Search string to filter by"
print_line " -o,--output Save the notes to a csv file"
print_line " -O <column> Order rows by specified column number"
print_line
print_line "Examples:"
print_line " notes --add -t apps -n 'winzip' 10.1.1.34 10.1.20.41"
print_line " notes -t smb.fingerprint 10.1.1.34 10.1.20.41"
print_line " notes -S 'nmap.nse.(http|rtsp)'"
print_line
end
def cmd_notes(*args)
return unless active?
::ApplicationRecord.connection_pool.with_connection {
mode = :search
data = nil
types = nil
set_rhosts = false