/
msfrpc.py
1995 lines (1623 loc) · 52.6 KB
/
msfrpc.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 python
from http.client import HTTPConnection, HTTPSConnection
import ssl
from numbers import Number
from msgpack import packb, unpackb
__author__ = 'Nadeem Douba'
__copyright__ = 'Copyright 2012, PyMetasploit Project'
__credits__ = []
__license__ = 'GPL'
__version__ = '0.4'
__maintainer__ = 'Nadeem Douba'
__email__ = 'ndouba@gmail.com'
__status__ = 'Development'
__all__ = ['MsfRpcError',
'MsfRpcMethod',
'MsfPlugins',
'MsfRpcClient',
'MsfTable',
'NotesTable',
'LootsTable',
'CredsTable',
'AuthInfoTable',
'HostsTable',
'ServicesTable',
'VulnsTable',
'EventsTable',
'ClientsTable',
'Workspace',
'MsfManager',
'WorkspaceManager',
'DbManager',
'AuthManager',
'PluginManager',
'JobManager',
'CoreManager',
'MsfModule',
'ExploitModule',
'PostModule',
'EncoderModule',
'AuxiliaryModule',
'PayloadModule',
'NopModule',
'ModuleManager',
'MsfSession',
'MeterpreterSession',
'ShellSession',
'SessionManager',
'MsfConsole',
'ConsoleManager',
'ReportFilter',
'ReportFilterQuery']
class MsfRpcError(Exception):
pass
class MsfRpcMethod(object):
AuthLogin = 'auth.login'
AuthLogout = 'auth.logout'
AuthTokenList = 'auth.token_list'
AuthTokenAdd = 'auth.token_add'
AuthTokenGenerate = 'auth.token_generate'
AuthTokenRemove = 'auth.token_remove'
ConsoleCreate = 'console.create'
ConsoleList = 'console.list'
ConsoleDestroy = 'console.destroy'
ConsoleRead = 'console.read'
ConsoleWrite = 'console.write'
ConsoleTabs = 'console.tabs'
ConsoleSessionKill = 'console.session_kill'
ConsoleSessionDetach = 'console.session_detach'
CoreVersion = 'core.version'
CoreStop = 'core.stop'
CoreSetG = 'core.setg'
CoreUnsetG = 'core.unsetg'
CoreSave = 'core.save'
CoreReloadModules = 'core.reload_modules'
CoreModuleStats = 'core.module_stats'
CoreAddModulePath = 'core.add_module_path'
CoreThreadList = 'core.thread_list'
CoreThreadKill = 'core.thread_kill'
DbHosts = 'db.hosts'
DbServices = 'db.services'
DbVulns = 'db.vulns'
DbWorkspaces = 'db.workspaces'
DbCurrentWorkspace = 'db.current_workspace'
DbGetWorkspace = 'db.get_workspace'
DbSetWorkspace = 'db.set_workspace'
DbDelWorkspace = 'db.del_workspace'
DbAddWorkspace = 'db.add_workspace'
DbGetHost = 'db.get_host'
DbReportHost = 'db.report_host'
DbReportService = 'db.report_service'
DbGetService = 'db.get_service'
DbGetNote = 'db.get_note'
DbGetClient = 'db.get_client'
DbReportClient = 'db.report_client'
DbReportNote = 'db.report_note'
DbNotes = 'db.notes'
DbReportAuthInfo = 'db.report_auth_info'
DbGetAuthInfo = 'db.get_auth_info'
DbGetRef = 'db.get_ref'
DbDelVuln = 'db.del_vuln'
DbDelNote = 'db.del_note'
DbDelService = 'db.del_service'
DbDelHost = 'db.del_host'
DbReportVuln = 'db.report_vuln'
DbEvents = 'db.events'
DbReportEvent = 'db.report_event'
DbReportLoot = 'db.report_loot'
DbLoots = 'db.loots'
DbReportCred = 'db.report_cred'
DbCreds = 'db.creds'
DbImportData = 'db.import_data'
DbGetVuln = 'db.get_vuln'
DbClients = 'db.clients'
DbDelClient = 'db.del_client'
DbDriver = 'db.driver'
DbConnect = 'db.connect'
DbStatus = 'db.status'
DbDisconnect = 'db.disconnect'
JobList = 'job.list'
JobStop = 'job.stop'
JobInfo = 'job.info'
ModuleExploits = 'module.exploits'
ModuleAuxiliary = 'module.auxiliary'
ModulePayloads = 'module.payloads'
ModuleEncoders = 'module.encoders'
ModuleNops = 'module.nops'
ModulePost = 'module.post'
ModuleInfo = 'module.info'
ModuleCompatiblePayloads = 'module.compatible_payloads'
ModuleCompatibleSessions = 'module.compatible_sessions'
ModuleTargetCompatiblePayloads = 'module.target_compatible_payloads'
ModuleOptions = 'module.options'
ModuleExecute = 'module.execute'
ModuleEncodeFormats = 'module.encode_formats'
ModuleEncode = 'module.encode'
PluginLoad = 'plugin.load'
PluginUnload = 'plugin.unload'
PluginLoaded = 'plugin.loaded'
SessionList = 'session.list'
SessionStop = 'session.stop'
SessionShellRead = 'session.shell_read'
SessionShellWrite = 'session.shell_write'
SessionShellUpgrade = 'session.shell_upgrade'
SessionMeterpreterRead = 'session.meterpreter_read'
SessionRingRead = 'session.ring_read'
SessionRingPut = 'session.ring_put'
SessionRingLast = 'session.ring_last'
SessionRingClear = 'session.ring_clear'
SessionMeterpreterWrite = 'session.meterpreter_write'
SessionMeterpreterSessionDetach = 'session.meterpreter_session_detach'
SessionMeterpreterSessionKill = 'session.meterpreter_session_kill'
SessionMeterpreterTabs = 'session.meterpreter_tabs'
SessionMeterpreterRunSingle = 'session.meterpreter_run_single'
SessionMeterpreterScript = 'session.meterpreter_script'
SessionMeterpreterDirectorySeparator = 'session.meterpreter_directory_separator'
SessionCompatibleModules = 'session.compatible_modules'
class MsfPlugins(object):
IpsFilter = "ips_filter"
SocketLogger = "socket_logger"
DbTracker = "db_tracker"
Sounds = "sounds"
AutoAddRoute = "auto_add_route"
DbCredCollect = "db_credcollect"
class MsfRpcClient(object):
_headers = {
'Content-Type' : 'binary/message-pack'
}
def __init__(self, password, **kwargs):
"""
Connects and authenticates to a Metasploit RPC daemon.
Mandatory Arguments:
- password : the password used to authenticate to msfrpcd
Optional Keyword Arguments:
- username : the username used to authenticate to msfrpcd (default: msf)
- uri : the msfrpcd URI (default: /api/)
- port : the remote msfrpcd port to connect to (default: 55553)
- server : the remote server IP address hosting msfrpcd (default: localhost)
- ssl : if true uses SSL else regular HTTP (default: SSL enabled)
- verify : if true, verify SSL cert when using SSL (default: False)
"""
self.uri = kwargs.get('uri', '/api/')
self.port = kwargs.get('port', 55552)
self.server = kwargs.get('server', '127.0.0.1')
self.ssl = kwargs.get('ssl', True)
self.verify_ssl = kwargs.get('verify', False)
self.sessionid = kwargs.get('token')
if self.ssl:
if self.verify_ssl:
self.client = HTTPSConnection(self.server, self.port)
else:
self.client = HTTPSConnection(self.server, self.port, context=ssl._create_unverified_context())
else:
self.client = HTTPConnection(self.server, self.port)
self.login(kwargs.get('username', 'msf'), password)
def unpackb_wrapper(self, data):
return self.unpackb_wrapf(data)
def unpackb_wrapf(self, item):
if type(item) == bytes:
return item.decode('ascii')
if type(item) == list:
nl = []
for j in item:
nl.append(self.unpackb_wrapf(j))
return nl
if type(item) == dict:
nd = {}
for j in item:
k = j
if type(k) == bytes:
k = j.decode('ascii')
nd[k] = self.unpackb_wrapf(item[j])
return nd
return item
def call(self, method, *args):
"""
Builds an RPC request and retrieves the result.
Mandatory Arguments:
- method : the RPC call method name (e.g. db.clients)
Optional Arguments:
- *args : the RPC method's parameters if necessary
Returns : RPC call result
"""
l = [method]
l.extend(args)
if method == MsfRpcMethod.AuthLogin:
self.client.request('POST', self.uri, packb(l), self._headers)
r = self.client.getresponse()
if r.status == 200:
return self.unpackb_wrapper(unpackb(r.read()))
raise MsfRpcError('An unknown error has occurred while logging in.')
elif self.authenticated:
l.insert(1, self.sessionid)
self.client.request('POST', self.uri, packb(l), self._headers)
r = self.client.getresponse()
if r.status == 200:
result = self.unpackb_wrapper(unpackb(r.read()))
if 'error' in result:
raise MsfRpcError(result['error_message'])
return result
raise MsfRpcError('An unknown error has occurred while performing the RPC call.')
raise MsfRpcError('You cannot perform this call because you are not authenticated.')
@property
def core(self):
"""
The msf RPC core manager.
"""
return CoreManager(self)
@property
def modules(self):
"""
The msf RPC modules RPC manager.
"""
return ModuleManager(self)
@property
def sessions(self):
"""
The msf RPC sessions (meterpreter & shell) manager.
"""
return SessionManager(self)
@property
def jobs(self):
"""
The msf RPC jobs manager.
"""
return JobManager(self)
@property
def consoles(self):
"""
The msf RPC consoles manager
"""
return ConsoleManager(self)
@property
def authenticated(self):
"""
Whether or not this client is authenticated.
"""
return self.sessionid is not None
@property
def plugins(self):
"""
The msf RPC plugins manager.
"""
return PluginManager(self)
@property
def db(self):
"""
The msf RPC database manager.
"""
return DbManager(self)
@property
def auth(self):
"""
The msf authentication manager.
"""
return AuthManager(self)
def login(self, username, password):
"""
Authenticates and reauthenticates the user to msfrpcd.
"""
if self.sessionid is None:
r = self.call(MsfRpcMethod.AuthLogin, username, password)
try:
if r['result'] == 'success':
self.sessionid = r['token']
except KeyError:
raise MsfRpcError('Login failed.')
else:
try:
r = self.call(MsfRpcMethod.DbStatus)
except MsfRpcError:
raise MsfRpcError('Login failed.')
def logout(self):
"""
Logs the current user out. Note: do not call directly.
"""
self.call(MsfRpcMethod.AuthLogout, self.sessionid)
class MsfTable(object):
def __init__(self, rpc, wname):
self.rpc = rpc
self.name = wname
def dbreport(self, atype, attrs):
attrs.update({ 'workspace' : self.name })
return self.rpc.call('db.report_%s' % atype, attrs)
def dbdel(self, atype, attrs):
attrs.update({ 'workspace' : self.name })
return self.rpc.call('db.del_%s' % atype, attrs)
def dbget(self, atype, attrs):
attrs.update({ 'workspace' : self.name })
return self.rpc.call('db.get_%s' % atype, attrs)[atype]
def records(self, atypes, **kwargs):
kwargs.update({'workspace' : self.name})
return self.rpc.call('db.%s' % atypes, kwargs)[atypes]
@property
def list(self):
raise NotImplementedError
def report(self, *args, **kwargs):
raise NotImplementedError
def delete(self, *args, **kwargs):
raise NotImplementedError
def find(self, **kwargs):
raise NotImplementedError
update = report
class NotesTable(MsfTable):
@property
def list(self):
return super(NotesTable, self).records('notes')
def find(self, **kwargs):
"""
Find notes based on search criteria.
Optional Keyword Arguments:
- limit : the maximum number of results.
- offset : skip n results.
- addresses : a list of addresses to search for.
- names : comma separated string of service names.
- ntype : the note type.
- ports : the port associated with the note.
- proto : the protocol associated with the note.
"""
if 'ports' in kwargs:
kwargs['port'] = True
return super(NotesTable, self).records('notes', **kwargs)
def report(self, type, data, **kwargs):
"""
Report a Note to the database. Notes can be tied to a Workspace, Host, or Service.
Mandatory Arguments:
- type : The type of note, e.g. 'smb_peer_os'.
- data : whatever it is you're making a note of.
Optional Keyword Arguments:
- host : an IP address or a Host object to associate with this Note.
- service : a dict containing 'host', 'port', 'proto' and optionally 'name' keys.
- port : along with 'host' and 'proto', a service to associate with this Note.
- proto : along with 'host' and 'port', a service to associate with this Note.
- update : what to do in case a similar Note exists, see below.
The 'update' option can have the following values:
- unique : allow only a single Note per host/type pair.
- unique_data : like 'unique', but also compare 'data'.
- insert : always insert a new Note even if one with identical values exists.
If the provided 'host' is an IP address and does not exist in the database,
it will be created. If 'host' and 'service' are all omitted, the new Note
will be associated with the current 'workspace'.
"""
kwargs.update({ 'data' : data, 'type' : type })
kwargs.update(kwargs.pop('service', {}))
self.dbreport('note', kwargs)
def delete(self, **kwargs):
"""
Delete one or more notes based on a search criteria.
Optional Keyword Arguments:
- host : the host associated with a Note, not required if 'address' or 'addresses' is specified
- address : the address associated with a Note, not required if 'host' or 'addresses' is specified.
- addresses : a list of addresses associated with Notes, not required if 'host' or 'address' is specified.
- port : the port associated with a Note.
- proto : the protocol associated with a Note.
- ntype : the note type, e.g. 'smb_peer_os'.
"""
self.dbdel('note', kwargs)
def get(self, **kwargs):
"""
Get a Note from the database based on the specifications of one or more keyword arguments.
Mandatory Keyword Arguments:
- host : the host associated with a Note, not required if 'address' or 'addr' is specified.
- address : the address associated with a Note, not required if 'host' or 'addr' is specified.
- addr : same as 'address', not required if 'host' or 'address' is specified.
Optional Keyword Arguments:
- proto : the protocol associated with the Note.
- port : the port associated with the Note.
- ntype : the type of Note.
"""
if not any([i in kwargs for i in ('host', 'address', 'addr')]):
raise TypeError('Expected a host, address, or addr.')
return self.dbget('note', kwargs)
update = report
class LootsTable(MsfTable):
@property
def list(self):
return super(LootsTable, self).records('loots')
def find(self, **kwargs):
"""
Find loot based on search criteria.
Optional Keyword Arguments:
- limit : the maximum number of results.
- offset : skip n results.
"""
return super(LootsTable, self).records('loots', **kwargs)
def report(self, path, type, **kwargs):
"""
Report Loot to the database
Mandatory Arguments:
- path : the filesystem path to the Loot
- type : the type of Loot
- ltype : the same as 'type', not required if 'type' is specified.
Optional Keyword Arguments:
- host : an IP address or a Host object to associate with this Note
- ctype : the content type of the loot, e.g. 'text/plain'
- content_type : same as 'ctype'.
- service : a service to associate Loot with.
- name : a name to associate with this Loot.
- info : additional information about this Loot.
- data : the data within the Loot.
"""
kwargs.update({ 'path' : path, 'type' : type })
self.dbreport('loot', kwargs)
update = report
class CredsTable(MsfTable):
@property
def list(self):
return super(CredsTable, self).records('creds')
def find(self, **kwargs):
"""
Find creds based on search criteria.
Optional Keyword Arguments:
- limit : the maximum number of results.
- offset : skip n results.
"""
return super(CredsTable, self).records('creds', **kwargs)
def report(self, host, port, **kwargs):
"""
Store a set of credentials in the database.
Mandatory Arguments:
- host : an IP address or Host object reference
- port : a port number
Optional Keyword Arguments:
- user : the username.
- password : the password, or path to ssh_key.
- ptype : the type of password (password(ish), hash, or ssh_key).
- proto : a transport name for the port.
- sname : service name.
- active : by default, a cred is active, unless explicitly false.
- proof : data used to prove the account is actually active.
Sources: Credentials can be sourced from another credential, or from
a vulnerability. For example, if an exploit was used to dump the
smb_hashes, and this credential comes from there, the source_id would
be the Vuln id (as reported by report_vuln) and the type would be "Vuln".
- source_id : The Vuln or Cred id of the source of this cred.
- source_type : Either Vuln or Cred.
"""
kwargs.update({'host' : host, 'port' : port})
kwargs['pass'] = kwargs.get('password')
self.dbreport('cred', kwargs)
update = report
class AuthInfoTable(MsfTable):
def report(self, host, port, **kwargs):
"""
Store a set of credentials in the database.
Mandatory Arguments:
- host : an IP address or Host object reference
- port : a port number
Optional Keyword Arguments:
- user : the username.
- pass : the password, or path to ssh_key.
- ptype : the type of password (password(ish), hash, or ssh_key).
- proto : a transport name for the port.
- sname : service name.
- active : by default, a cred is active, unless explicitly false.
- proof : data used to prove the account is actually active.
Sources: Credentials can be sourced from another credential, or from
a vulnerability. For example, if an exploit was used to dump the
smb_hashes, and this credential comes from there, the source_id would
be the Vuln id (as reported by report_vuln) and the type would be "Vuln".
- source_id : The Vuln or Cred id of the source of this cred.
- source_type : Either Vuln or Cred.
"""
kwargs.update({'host' : host, 'port' : port})
self.dbreport('auth_info', kwargs)
update = report
class HostsTable(MsfTable):
@property
def list(self):
return super(HostsTable, self).records('hosts')
def find(self, **kwargs):
"""
Find hosts based on search criteria.
Optional Keyword Arguments:
- limit : the maximum number of results.
- offset : skip n results.
- only_up : find only hosts that are alive.
- addresses : find hosts based on a list of addresses.
"""
return super(HostsTable, self).records('hosts', **kwargs)
def report(self, host, **kwargs):
"""
Store a host in the database.
Mandatory Keyword Arguments:
- host : an IP address or Host object reference.
Optional Keyword Arguments:
- state : a host state.
- os_name : an operating system.
- os_flavor : something like 'XP or 'Gentoo'.
- os_sp : something like 'SP2'.
- os_lang : something like 'English', 'French', or 'en-US'.
- arch : an architecture.
- mac : the host's MAC address.
- scope : interface identifier for link-local IPv6.
- virtual_host : the name of the VM host software, e.g. 'VMWare', 'QEMU', 'Xen', etc.
"""
kwargs.update({'host' : host})
self.dbreport('host', kwargs)
def delete(self, **kwargs):
"""
Deletes a host and associated data matching this address/comm.
Mandatory Keyword Arguments:
- host : the host associated with a Note, not required if 'address' or 'addresses' is specified
- address : the address associated with a Note, not required if 'host' or 'addresses' is specified.
- addresses : a list of addresses associated with Notes, not required if 'host' or 'address' is specified.
"""
if not any([ i in kwargs for i in ('host', 'address', 'addresses')]):
raise TypeError('Expected host, address, or addresses.')
self.dbdel('host', kwargs)
def get(self, **kwargs):
"""
Get a host in the database.
Mandatory Keyword Arguments:
- host : the host associated with a Note, not required if 'address' or 'addr' is specified.
- address : the address associated with a Note, not required if 'host' or 'addr' is specified.
- addr : same as 'address', not required if 'host' or 'address' is specified.
"""
if not any([ i in kwargs for i in ('addr', 'address', 'host')]):
raise TypeError('Expected addr, address, or host.')
return self.dbget('host', kwargs)
update = report
class ServicesTable(MsfTable):
@property
def list(self):
return super(ServicesTable, self).records('services')
def find(self, **kwargs):
"""
Find hosts based on search criteria.
Optional Keyword Arguments:
- limit : the maximum number of results.
- offset : skip n results.
- only_up : find only hosts that are alive.
- addresses : find hosts based on a list of addresses.
- proto : the protocol of the service.
- ports : a comma separated string of ports.
- names : a comma separated string of service names.
"""
return super(ServicesTable, self).records('services', **kwargs)
def report(self, host, port, proto, **kwargs):
"""
Record a service in the database.
Mandatory Arguments:
- host : the host where this service is running.
- port : the port where this service listens.
- proto : the transport layer protocol (e.g. tcp, udp).
Optional Keyword Arguments:
- name : the application layer protocol (e.g. ssh, mssql, smb)
- sname : an alias for the above
"""
kwargs.update({'host' : host, 'port' : port, 'proto' : proto})
self.dbreport('service', kwargs)
def delete(self, **kwargs):
"""
Deletes a port and associated vulns matching this port.
Mandatory Keyword Arguments:
- host : the host associated with a Note, not required if 'address' or 'addresses' is specified
- address : the address associated with a Note, not required if 'host' or 'addresses' is specified.
- addresses : a list of addresses associated with Notes, not required if 'host' or 'address' is specified.
or
- port : used along with 'proto', specifies a service.
- proto : used along with 'port', specifies a service.
"""
if not any([i in kwargs for i in ('host', 'address', 'addresses')]) and \
not all([i in kwargs for i in ('proto', 'port')]):
raise TypeError('Expected host or port/proto pair.')
self.dbdel('service', kwargs)
def get(self, **kwargs):
"""
Get a service record from the database.
Mandatory Keyword Arguments:
- host : the host associated with a Note, not required if 'address' or 'addresses' is specified
- address : the address associated with a Note, not required if 'host' or 'addresses' is specified.
- addresses : a list of addresses associated with Notes, not required if 'host' or 'address' is specified.
or
- port : used along with 'proto', specifies a service.
- proto : used along with 'port', specifies a service.
Optional Keyword Arguments:
- up : specifies whether or not the service is alive.
- names : a comma separated string of service names.
"""
if not any([i in kwargs for i in ('host', 'addr', 'address')]) and \
not all([i in kwargs for i in ('proto', 'port')]):
raise TypeError('Expected host or port/proto pair.')
return self.dbget('service', kwargs)
update = report
class VulnsTable(MsfTable):
@property
def list(self):
return super(VulnsTable, self).records('vulns')
def find(self, **kwargs):
"""
Find vulns based on search criteria.
Optional Keyword Arguments:
- limit : the maximum number of results.
- offset : skip n results.
- addresses : find hosts based on a list of addresses.
- proto : the protocol of the service.
- ports : a comma separated string of ports.
- names : a comma separated string of service names.
"""
return super(VulnsTable, self).records('vulns', **kwargs)
def report(self, host, name, **kwargs):
"""
Record a Vuln in the database.
Mandatory Arguments:
- host : the host where this vulnerability resides.
- name : the scanner-specific id of the vuln (e.g. NEXPOSE-cifs-acct-password-never-expires).
Optional Keyword Arguments:
- info : a human readable description of the vuln, free-form text.
- refs : an array of Ref objects or string names of references.
"""
kwargs.update({'host' : host, 'name' : name})
self.dbreport('vuln', kwargs)
def delete(self, **kwargs):
"""
Deletes a vuln and associated data matching this address/comm.
Mandatory Keyword Arguments:
- host : the host associated with a Note, not required if 'address' or 'addresses' is specified
- address : the address associated with a Note, not required if 'host' or 'addresses' is specified.
- addresses : a list of addresses associated with Notes, not required if 'host' or 'address' is specified.
"""
if not any([ i in kwargs for i in ('host', 'address', 'addresses')]):
raise TypeError('Expected host, address, or addresses.')
self.dbdel('vuln', kwargs)
def get(self, **kwargs):
"""
Get a vuln in the database.
Mandatory Keyword Arguments:
- host : the host associated with a Note, not required if 'address' or 'addr' is specified.
- address : the address associated with a Note, not required if 'host' or 'addr' is specified.
- addr : same as 'address', not required if 'host' or 'address' is specified.
"""
if not any([ i in kwargs for i in ('addr', 'address', 'host')]):
raise TypeError('Expected addr, address, or host.')
return self.dbreport('vuln', kwargs)
update = report
class EventsTable(MsfTable):
@property
def list(self):
return super(EventsTable, self).records('events')
def find(self, **kwargs):
"""
Find events based on search criteria.
Optional Keyword Arguments:
- limit : the maximum number of results.
- offset : skip n results.
"""
return super(EventsTable, self).records('events', **kwargs)
def report(self, **kwargs):
"""
Record a Vuln in the database.
Mandatory Arguments:
- username : user that invoked the event.
- host : host that invoked the event.
"""
if not any([i in kwargs for i in ('username', 'host')]):
raise TypeError('Expected either username or host')
self.dbreport('vuln', kwargs)
update = report
class ClientsTable(MsfTable):
@property
def list(self):
return super(ClientsTable, self).records('clients')
def find(self, **kwargs):
"""
Find clients based on search criteria.
Optional Keyword Arguments:
- limit : the maximum number of results.
- offset : skip n results.
- ua_name : a user-agent string.
- ua_ver : the user-agent version.
- addresses : a list of IP addresses.
"""
return super(ClientsTable, self).records('clients', **kwargs)
def report(self, ua_string, host, **kwargs):
"""
Report a client running on a host.
Mandatory Arguments:
- ua_string : the value of the User-Agent header
- host : the host where this client connected from, can be an ip address or a Host object
Optional Keyword Arguments
- ua_name : one of the user agent name constants
- ua_ver : detected version of the given client
- campaign : an id or Campaign object
Returns a Client.
"""
kwargs.update({'host' : host, 'ua_string' : ua_string})
self.dbreport('client', kwargs)
def delete(self, **kwargs):
"""
Deletes a client and associated data matching this address/comm.
Mandatory Keyword Arguments:
- host : the host associated with a Note, not required if 'address' or 'addresses' is specified
- address : the address associated with a Note, not required if 'host' or 'addresses' is specified.
- addresses : a list of addresses associated with Notes, not required if 'host' or 'address' is specified.
"""
self.dbdel('client', kwargs)
def get(self, **kwargs):
"""
Get a client in the database.
Mandatory Keyword Arguments:
- host : the host associated with a Note, not required if 'address' or 'addr' is specified.
- ua_string : the value of the User-Agent header
"""
if not any([ i in kwargs for i in ('host', 'ua_string')]):
raise TypeError('Expected host or ua_string.')
return self.dbreport('client', kwargs)
update = report
class Workspace(object):
def __init__(self, rpc, name):
"""
Initializes a workspace object.
Mandatory Arguments:
- rpc : the msfrpc client object
- name : the name of the workspace
"""
self.rpc = rpc
self.name = name
@property
def current(self):
"""
The name of the current workspace.
"""
return self.name
@current.setter
def current(self, name):
self.name = name
@property
def notes(self):
"""
Returns the notes table for the current workspace.
"""
return NotesTable(self.rpc, self.name)
@property
def hosts(self):
"""
Returns the hosts table for the current workspace.
"""
return HostsTable(self.rpc, self.name)
@property
def services(self):
"""
Returns the services table for the current workspace.
"""
return ServicesTable(self.rpc, self.name)
@property
def vulns(self):
"""
Returns the vulns table for the current workspace.
"""
return VulnsTable(self.rpc, self.name)
@property
def events(self):
"""
Returns the events table for the current workspace.
"""
return EventsTable(self.rpc, self.name)
@property
def loots(self):
"""
Returns the loots table for the current workspace.
"""
return LootsTable(self.rpc, self.name)
@property
def creds(self):
"""
Returns the creds table for the current workspace.
"""
return CredsTable(self.rpc, self.name)
@property
def clients(self):
"""
Returns the clients table for the current workspace.
"""
return ClientsTable(self.rpc, self.name)
def delete(self):
"""
Delete the current workspace.
"""
self.rpc.call(MsfRpcMethod.DbDelWorkspace, {'workspace' : self.name})
def importdata(self, data):
self.rpc.call(MsfRpcMethod.DbImportData, {'workspace' : self.name, 'data' : data})
def importfile(self, fname):
r = file(fname, mode='rb')
self.rpc.call(MsfRpcMethod.DbImportData, {'workspace' : self.name, 'data' : r.read()})
r.close()