-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcanvasengine.py
More file actions
4260 lines (3573 loc) · 157 KB
/
canvasengine.py
File metadata and controls
4260 lines (3573 loc) · 157 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
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
##ImmunityHeader v1
###############################################################################
## File : canvasengine.py
## Description:
## :
## Created_On : Thu Aug 20 12:09:47 2009
## Created_By : Rich
## Modified_On: Mon Mar 22 13:43:57 2010
## Modified_By: Rich
##
## (c) Copyright 2009, Immunity, Inc. all rights reserved.
###############################################################################
#! /usr/bin/env python
#Proprietary CANVAS source code - use only under the license agreement
#specified in LICENSE.txt in your CANVAS distribution
#Copyright Immunity, Inc, 2002-2006
#http://www.immunityinc.com/CANVAS/ for more information
"""
canvasengine.py
CANVAS's Engine
"""
from __future__ import with_statement
from datetime import datetime
import logging
import warnings
#Change this to enable Project BALLOON features
BALLOON = 0
import os, sys
#this is a quick check to see if they are running the exploit from the wrong directory
if "." not in sys.path: sys.path.append(".")
import re
import time
import shutil
import platform
USE_COLORS = True
if platform.system() == "Windows":
USE_COLORS = False
from internal import *
# activate debugging if --debug in argv (for customers)
_debug_opt = "--debug"
_debug_file = "debug.log"
if _debug_opt in sys.argv:
sys.stderr = file(_debug_file, 'ab')
sys.stderr.write("\n\n-----[ NEW DEBUG SESSION ]-----\n\n\n")
add_debug_level('all')
# cleaning argv in case
while _debug_opt in sys.argv:
sys.argv.remove(_debug_opt)
from internal.utils import setup_logging, setup_session_logging
setup_logging(enable_debug=debug_enabled)
########################
#translation support
import gettext
do_auto_translations = False
if 0:
#define this if you are doing automatic translations
#but we cannot distribute this because it means people
#cannot run CANVAS headless
from gui.canvasguigtk2 import do_auto_translations
if do_auto_translations:
#use to create a .po
from gui.canvasguigtk2 import output_translatable_string
_=output_translatable_string
else:
#normal behavior
_ = gettext.gettext
gettext.bindtextdomain("CANVAS",localedir = "gui/locale/")
gettext.textdomain("CANVAS")
######
from engine import CanvasConfig
from engine.config import canvas_root_directory
from engine.config import canvas_resources_directory
from engine.config import canvas_reports_directory
from libs.daveutil import dmkdir
from engine.http_mosdef import http_mosdef
#for Unixshell Nodes
from libs.ctelnetlib import Telnet
from shelllistener import shelllistener
from shelllistener import androidShellListener
from shelllistener import shellfromtelnet
# Import our stuff first
sys.path.insert(0, os.path.abspath('./libs'))
from libs import yaml
import socket
from exploitutils import *
#import Threading
from threading import RLock, Thread
# mutexing
import mutex
from exploitmanager import exploitmanager
import ConfigParser
sys.path = uniqlist(sys.path)
import extras.versioncheck as versioncheck
import libs.canvasos as canvasos
if CanvasConfig['sound']:
import sounds.sound as sound
if CanvasConfig['sniffer']:
try:
import sniffer
from localsniffer import localsniffer
except:
logging.warning("No sniffer - CRI version?")
from localNode import localNode
# from SQLNode import SQLNode
# new style shellservers support ..
from MOSDEFShellServer import MosdefShellServer
# new reporter
from libs import reports
from internal.colors import color_text
from engine.features import *
VERSION = "5.0" #GUI Version, not CANVAS version
DEFAULTCOLOR = "black"
# ???
PHPMULTI = "PHP MULTI OS"
UNIXSHELL = "UNIXSHELL"
ANDROIDSHELL = "ANDROID SHELL"
# making a push to sanitize and clean our naming conventions ..
FREEBSDMOSDEF_INTEL = "FREEBSD MOSDEF INTEL"
WIN32MOSDEF_INTEL = "WIN32 MOSDEF INTEL"
WIN32MOSDEF_INTEL_FCT = "WIN32 MODSEF INTEL FromCreateThread"
WIN64MOSDEF_INTEL = "WIN64 MOSDEF INTEL"
OSXMOSDEF_PPC = "OSX MOSDEF PPC"
OSXMOSDEF_INTEL = "OSX MOSDEF INTEL"
OSXMOSDEF_X64 = "OSX MOSDEF X64"
AIXMOSDEF_51_PPC = "AIX 5.1 MOSDEF PPC"
AIXMOSDEF_52_PPC = "AIX 5.2 MOSDEF PPC"
SOLARISMOSDEF_INTEL = "SOLARIS MOSDEF INTEL"
SOLARISMOSDEF_SPARC = "SOLARIS MOSDEF SPARC"
LINUXMOSDEF_INTEL = "LINUX MOSDEF INTEL"
LINUXMOSDEF_X64 = "LINUX MOSDEF X64"
LINUXEXECVE_INTEL = "LINUX EXECVE INTEL"
HTTPMOSDEF = "HTTP MOSDEF PLAINTEXT"
HTTPMOSDEF_SSL = "HTTP MOSDEF SSL"
JAVASERVER = "JAVA MOSDEF"
UNIVERSAL_MOSDEF = "Universal MOSDEF"
DNSMOSDEF = "DNS MOSDEF"
LINUXMOSDEF_ARM9 = "LINUX MOSDEF ARM9"
POWERSHELL_MOSDEF = "POWERSHELL MOSDEF"
# backwards compatibility with old listener types ..
SOLARISSPARCMOSDEF = SOLARISMOSDEF_SPARC # backwards compatibility
LINUXMOSDEF = LINUXMOSDEF_INTEL # all the old sploits using this will be using intel
HTTPSMOSDEF = HTTPMOSDEF_SSL
WIN32MOSDEF = WIN32MOSDEF_INTEL
WIN64MOSDEF = WIN64MOSDEF_INTEL
def set_session_name(name=None, eng=None):
"""
Initialise/change a CANVAS session name
"""
# set our session name
global SESSION_NAME
if not name:
SESSION_NAME = CanvasConfig["canvas_session_name"]
else:
SESSION_NAME = name
global CANVAS_OUTPUT_DIR
CANVAS_OUTPUT_DIR = os.path.join(CanvasConfig["canvas_output"], SESSION_NAME)
dmkdir(CANVAS_OUTPUT_DIR)
logging.warning("Setting CANVAS session to: %s" % (SESSION_NAME))
# If we have been passed an existing canvasengine then we also need to update the logfile locations & reset
# our output directory for other output
if eng:
eng.reporter = reports.Reporter(SESSION_NAME, _backup_overwrite=True)
setup_session_logging(name=SESSION_NAME)
##Set our initial CANVAS session name
set_session_name()
#used by ms03026.py. Fd's placed in this list will not be closed when
#the exploit is done
global socket_save_list
socket_save_list=[]
global canvaslanguage
canvaslanguage = "EN" #english by default
# TODO use Fortune() from exploitutils
try:
fortunes = open("misfortunes.txt").readlines()
except:
try:
fortunes = open("fortunes.txt").readlines()
except:
fortunes = ["",""]
import random
random.shuffle(fortunes)
currentfortune=0
from libs.smartlist import smartlist, load_smartlist
def capme(astr):
"""
ABDC -> Abcd
"""
if not astr:
return ""
if len(astr) == 1:
return astr.upper()
ret = astr[0].upper() + astr[1:].lower()
return ret
def csvit(anobject):
"""
converts an object to a string and removes commas (which mess up our comma seperated values format)
"""
anobject = str(anobject).replace(",", "-")
return anobject
def html_docs_from_module(module):
"""
Returns a sort of HTML documentation string from a canvas module
You'll want to see gui/text_with_markup.py for rendering
TODO: order all documentations the same way instead of randomly based on the hash table's whims
TODO: support links and images in documentation
"""
# sometimes this blows up on instance methods ..
try:
if not hasattr(module, "DOCUMENTATION"):
module.DOCUMENTATION = {}
except:
return "", ""
docdic = module.DOCUMENTATION
showdoc = "\n<module>\n"
name = module.NAME.upper() # Reverted since we're not splitting
# Alexm: Added for Customer request, behold the total lack of regular expressions!
if module.DOCUMENTATION.has_key("CVE Name") and module.DOCUMENTATION["CVE Name"] != None:
docslite = name + " - " + module.DOCUMENTATION["CVE Name"] + " - "
# There's not a standard CVE URL vs. CVE Url, so I figured it better to be safe
if module.DOCUMENTATION.has_key("CVE Url") and module.DOCUMENTATION["CVE Url"] != None:
docslite += module.DOCUMENTATION["CVE Url"] + "\n"
else:
docslite += module.DOCUMENTATION.get("CVE URL", "*Unknown*") + "\n"
else:
docslite = None
csvdoc = [csvit(name)] #comma seperated value for spreadsheets
# TITLE setting
# XXX: header too strong imo
showdoc += "<b>%s</b><br/>\n"%xmlencode(name)
if module.DESCRIPTION and module.DESCRIPTION.upper() != module.NAME.upper():
showdoc += "%s"%xmlencode(_(module.DESCRIPTION))
showdoc += "<br/><br/>\n"
else:
showdoc += "<br/>\n"
csvdoc += [csvit(_(module.DESCRIPTION))] #TODO ADD ENCODING
# PROPERTY parsing
if hasattr(module, "PROPERTY"):
#handle properties dictionary
for key in module.PROPERTY:
if module.PROPERTY[key]: # XXX: don't do null strings or lists
showdoc += "<b>%s: </b>%s<br/>\n"%(xmlencode(key.upper()),xmlencode(module.PROPERTY[key]))
csvdoc += [csvit(key)+":"+csvit(module.PROPERTY[key])] #TODO ADD ENCODING
cKeys = module.PROPERTY.keys()
else:
cKeys = []
# DOCUMENTATION parsin
for ea in docdic.keys():
# XXX: if key is already handled by PROPERTY dict, don't show it here
# sometimes MSADV is shown double
if ea in cKeys:
pass
elif docdic[ea]: # XXX: do not show empty strings
showdoc += "<b>%s: </b>%s<br/>\n"%(xmlencode(ea.upper()),xmlencode(docdic.get(ea)))
csvdoc += [csvit(ea)+":"+csvit(docdic.get(ea))] #TODO ADD ENCODING
showdoc += "<br/>\n" #newline to separate our documentation from our other data
if not hasattr(module, "theexploit"):
logging.error("Module does not have 'theexploit' method")
return
sploit = module.theexploit()
try:
connectbackdata = sploit.neededListenerTypes()
except:
connectbackdata = []
if connectbackdata != []:
showdoc += "<b>Connectback type: </b>%s<br/>\n"%(connectbackdata)
if sploit.listenerArgsDict.get("fromcreatethread", 0):
#some modules, like ifids, have fromcreatethread set, but are
#not connectbacks
if not hasattr(sploit, "needsNoShellcode") or not sploit.needsNoShellcode:
showdoc += "<b>Commandline usage: </b>" + xmlencode("Requires a fromcreatethread WIN32 MOSDEF listener") + "\n"
showdoc += "</module>\n\n"
# XXX: why is this returning a tuple ? (also edit gui code if you edit return type here)
return showdoc, csvdoc, docslite
class CANVASENGINEException(Exception):
pass
defaultmodules=["osdetect", "addhost", "gethostbyname", "emailsender", "startservice"]
#,"oraclegetinfo","oraclegetuser","oraclegetpwd"]
#defaultmodules+=["ms05_040","enumservices","osdetect"]
defaultmodules += ["userenum"]
defaultmodules += ["shareenum"]
def interestingDirlist(dirlist, topdir = ".", wantdir = True):
"""
remove uninteresting dirs/files
i.e.: CVS .svn .vim.swp
"""
retlist = []
for dirname in dirlist:
# Temporary code for dealing with our new tree organization
if dirname in ["local",
"remote",
"clientside",
"trojan",
"DoS",
"tool",
"reporting",
"server",
"config",
"fuzzer",
"command",
"recon",
"web",
"incomplete",
"importexport"]:
continue
if dirname in ["CVS"] or dirname[0] == '.' or (wantdir and not os.path.isdir(topdir + os.path.sep + dirname)):
devlog('interestingDirlist', "%s discarded" % dirname)
continue
retlist.append(dirname)
return retlist
def checkAndSetPath(name):
dirname = ""
# not in root directory (e.g. VisualSploit)
cwd = os.getcwd()
if cwd.find("VisualSploit") != -1:
dirname = ".." + os.path.sep + "exploits" + os.path.sep + name
logging.info("Dirname set to: %s" % dirname)
# set ../ relative paths for anything that has ../../
# print sys.path
for path in sys.path:
if path.find("../../") != -1 or path.find("..\\..\\") != -1:
# we have to be cross os.path.sep compatible, because we hardcode "../../" a lot
# therefor we can't actually use os.path.sep effectively.
logging.info("Fixing path for VisualSploit: %s" % path)
path = path.replace("../../", ".." + os.path.sep) # doesn't change if not there
path = path.replace("..\\..\\", ".." + os.path.sep) # doesn't change if not there
if path not in sys.path:
sys.path.insert(0, path)
else:
path = ""
# This is a shortcut lookup table set by registerAll to make it easy for us
for k,v in moduleDirectoryMap.iteritems():
if name in v:
path = k
break
dirname = os.path.join(path, name)
return dirname
#global list of all exploit modules...
__exploitmods_old = {} # keep for compatibility *DEPRECATED*
__exploitmods = {} # new way
class CanvasModule:
"""
1 instance for each module
"""
def __init__(self, name, path, mod = None):
self.name = name
self.path = path
self.mod = mod
self.processModule()
def __str__(self):
return "<loaded CANVAS Module '%s'>" % self.name
def reload(self):
sys.path.insert(0, self.path)
self.mod = reload(self.mod)
sys.path.remove(self.path)
self.processModule()
return self.mod
def processModule(self):
"""
Here, we can perform set up for each module, such as processing/validating its PROPERTY dict. This
used to be done in the gui tree populationg code, but obviously doesn't belong in there.
"""
exploitmod = self.mod
name = self.name
#Changed name from "property" to "propertyDict", since the first one is reserved.
if hasattr(exploitmod, "PROPERTY"):
devlog("canvasengine", "Exploitmod %s has PROPERTY" % name)
propertyDict = exploitmod.PROPERTY
else:
logging.error("Attribute error found while processing %s/%s.py" % (self.path, self.name))
logging.error("PROPERTY{} dictionary is missing")
logging.error("Import of %s/%s.py failed" % (self.path, self.name))
raise AssertionError
# check properties
property_ref = {
'TYPE': "",
'SITE': "",
'ARCH': [],
'PROC': [],
'0DAY': False,
'MSADV': "",
}
# normalize property's keys -> all in CAPS
for key in propertyDict.keys():
if not key.isupper():
propertyDict[key.upper()] = propertyDict[key]
del propertyDict[key]
# check property's types once
for key in property_ref.keys():
if propertyDict.has_key(key):
assert type(propertyDict[key]) is type(property_ref[key]), \
"\n\n%s.PROPERTY['%s'] is %s\n%s expected\n" % \
(name, key, type(propertyDict[key]), type(property_ref[key]))
else:
# set default
propertyDict[key] = property_ref[key]
# we want DOCUMENTATION{}
if not hasattr(exploitmod, "DOCUMENTATION"):
devlog('import_exploits', "%s.DOCUMENTATION missing" % name)
exploitmod.DOCUMENTATION = {}
# process MSADV
if propertyDict['MSADV'] != "":
propertyDict['MSADV'] = propertyDict['MSADV'].upper()
if propertyDict['MSADV'][0:2] != "MS":
propertyDict['MSADV'] = "MS%s" % propertyDict['MSADV']
assert propertyDict['MSADV'][4] == "-", "MSADV has to be in the form \"MSxx-xxx\""
# force DOCUMENTATION['MSADV']
exploitmod.DOCUMENTATION['MSADV'] = propertyDict['MSADV']
if 'ARCH' not in propertyDict:
devlog('import_exploits', "%s.PROPERTY['ARCH'] missing" % name)
# push update into module for now, so that canvasos.fromModule gets it
# but before we butcher up Arch/Version/OS next :(
exploitmod.PROPERTY = propertyDict
exploitmod.TARGET_CANVASOS_LIST = canvasos.fromModule(exploitmod)
if not propertyDict['0DAY'] and "0DAY" in exploitmod.DESCRIPTION.upper():
devlog('import_exploits', "0DAY in description, but %s.PROPERTY['0DAY']=True not set" % name)
propertyDict['0DAY'] = True
if propertyDict['0DAY'] and exploitmod.DESCRIPTION[0:6] != "[0day]":
devlog('import_exploits', "%s.PROPERTY['0DAY']=True but not '[0day]' in description" % name)
exploitmod.DESCRIPTION = "[0day] " + exploitmod.DESCRIPTION
# </transition>
# common to 0days
if propertyDict['0DAY']:
# some exploits files are copy/paste from public bug
# and have some wrong "release date"
# here we reset that to be more coherent.
if exploitmod.DOCUMENTATION.has_key("Date public") and \
exploitmod.DOCUMENTATION["Date public"] not in \
["Not public/0day", "Not Public / 0day", "Not Public/0day"]:
devlog('import_exploits', "%s.PROPERTY['0DAY']=True but 'Date public' is %s" % \
(name, exploitmod.DOCUMENTATION["Date public"]))
exploitmod.DOCUMENTATION["Date public"] = "Not public/0day"
#Removed the "OS" property, since in 1179 modules it is literally never used.
for x in exploitPacks.itervalues():
if self.name in x.modules:
exploitmod.exploitPack = x
break
exploitmod.PROPERTY = propertyDict
def aaa__processModule(self):
"""
Here, we can perform set up for each module, such as processing/validating its PROPERTY dict. This
used to be done in the gui tree populationg code, but obviously doesn't belong in there.
"""
exploitmod = self.mod
name = self.name
if hasattr(exploitmod, "PROPERTY"):
devlog("canvasengine", "Exploitmod %s has PROPERTY" % name)
property = exploitmod.PROPERTY
else:
logging.error("Attribute error found while processing %s/%s.py" % (self.path, self.name))
logging.error("PROPERTY{} dictionary is missing")
logging.error("Import of %s/%s.py failed" % (self.path, self.name))
raise AssertionError
# check properties
property_ref = {
'TYPE': "",
'SITE': "",
'ARCH': [],
'OS': [],
'PROC': [],
'0DAY': False,
'MSADV': "",
}
# normalize property's keys -> all in CAPS
for key in property.keys():
if not key.isupper():
property[key.upper()] = property[key]
del property[key]
# check property's types once
for key in property_ref.keys():
if property.has_key(key):
assert type(property[key]) is type(property_ref[key]), \
"\n\n%s.PROPERTY['%s'] is %s\n%s expected\n" % \
(name, key, type(property[key]), type(property_ref[key]))
else:
# set default
property[key] = property_ref[key]
# we want DOCUMENTATION{}
if not hasattr(exploitmod, "DOCUMENTATION"):
devlog('import_exploits', "%s.DOCUMENTATION missing" % name)
exploitmod.DOCUMENTATION = {}
# process MSADV
if property['MSADV'] != "":
property['MSADV'] = property['MSADV'].upper()
if property['MSADV'][0:2] != "MS":
property['MSADV'] = "MS%s" % property['MSADV']
assert property['MSADV'][4] == "-", "MSADV has to be in the form \"MSxx-xxx\""
# force DOCUMENTATION['MSADV']
exploitmod.DOCUMENTATION['MSADV'] = property['MSADV']
# we would like PROPERTY['ARCH']
if not len(property['ARCH']):
devlog('import_exploits', "%s.PROPERTY['ARCH'] missing" % name)
# push update into module for now, so that canvasos.fromModule gets it
# but before we butcher up Arch/Version/OS next :(
exploitmod.PROPERTY = property
exploitmod.TARGET_CANVASOS_LIST = canvasos.fromModule(exploitmod)
# :(
#if len(exploitmod.TARGET_CANVASOS_LIST) == 0 and property['TYPE'] in ["Exploit", "Web Exploit"]:
# raise AssertionError("Module %s has no targets, according to canvasos.fromModule. ARCH: %s" % (name, property['ARCH']))
# build ARCH from OS + PROC
for OS in property['OS']:
f = True
# avoid duplicate ARCH / OS
for aOS in property['ARCH']:
#assert type(aOS) == type([])
if aOS[0] == OS:
f = False
if not f:
continue
aOS = [OS]
if property.has_key('PROC'):
for proc in property['PROC']:
aOS.append(proc)
property['ARCH'].append(aOS)
# TODO: clean that for()
devlog('gui::fillmoduletree', "property[ARCH] = %s" % property['ARCH'])
for arch in property['ARCH']:
if len(arch) == 1:
versions_list = ["All"]
else:
versions_list = arch[1:]
# for Windows, expand Version list
if arch[0] == "Windows": # caps?
if property.has_key('VERSION'):
import string
property['VERSION'] = map(string.upper, property['VERSION'])
if "ALL" in property['VERSION']:
#arch.append("ALL")
arch = ["Windows", "All"]
else:
versions_list = property['VERSION']
del property['VERSION']
else:
#arch.append("ALL")
arch = ["Windows", "All"]
if arch == ["Windows", "All"]: #len(arch) == 2 and arch[1].upper() == "ALL":
del arch[1]
versions_list = ["NT", "2000", "XP", "2003", "Vista"]
arch += versions_list
devlog('gui::fillmoduletree', "property[ARCH] = %s" % property['ARCH'])
if not property['0DAY'] and "0DAY" in exploitmod.DESCRIPTION.upper():
devlog('import_exploits', "0DAY in description, but %s.PROPERTY['0DAY']=True not set" % name)
property['0DAY'] = True
if property['0DAY'] and exploitmod.DESCRIPTION[0:6] != "[0day]":
devlog('import_exploits', "%s.PROPERTY['0DAY']=True but not '[0day]' in description" % name)
exploitmod.DESCRIPTION = "[0day] " + exploitmod.DESCRIPTION
# </transition>
# common to 0days
if property['0DAY']:
# some exploits files are copy/paste from public bug
# and have some wrong "release date"
# here we reset that to be more coherent.
if exploitmod.DOCUMENTATION.has_key("Date public") and \
exploitmod.DOCUMENTATION["Date public"] not in \
["Not public/0day", "Not Public / 0day", "Not Public/0day"]:
devlog('import_exploits', "%s.PROPERTY['0DAY']=True but 'Date public' is %s" % \
(name, exploitmod.DOCUMENTATION["Date public"]))
exploitmod.DOCUMENTATION["Date public"] = "Not public/0day"
ep = None
for x in exploitPacks.itervalues():
if self.name in x.modules:
ep = x
break
if ep:
exploitmod.exploitPack = ep
# Make sure changes are propagated back into the module.
exploitmod.PROPERTY = property
class __RegisterModulesLog:
def __init__(self):
self.modnum = 0
self.curidx = 0
def run(self, func):
func()
def setcuridx(self, idx):
self.curidx = idx
def setmax(self, maxnum):
self.modnum = maxnum
def log(self, name):
writeflush_for_status("[+] Loading %s ..." % name)
def setstatus(self, succeeded = 1):
out = {1: " ok ", 2: "fail"}
text = "[" + color_text(out[succeeded], succeeded, True, use_colors=USE_COLORS) + "]\n"
# writeflush(text)
self.curidx += 1
return text
def succeeded(self):
self.setstatus()
def failed(self):
self.setstatus(2)
registermoduleslog = __RegisterModulesLog()
class __CanvasModules:
"""
1 instance that hold all modules
"""
def __init__(self):
pass
# This stores a map of module names and the directory we are to load it from
# keys are directory names, value is a list of exploits from that directory
moduleDirectoryMap = {}
EXPLOITPACK_LICENSE_FLAG=".exploitPackLicenseSeen"
class ExploitPackError(Exception):
pass
class ExploitPack:
"""One of these is instantiated for each CANVAS exploit pack"""
def __init__(self, path):
self.path = path
self.exploitdirs = []
self.exploitSections = {}
self.modules = []
self.third_party = True
self.loadInfo(path)
self.setup()
#print "ExploitPack (%s)->%s"%(self.name, self.modules)
def hasModule(self, module):
""" Returns true if the module is one of ours """
return module in self.modules
def setup(self):
for p in self.libdirsWalked:
if p not in sys.path:
sys.path.append(p)
def unsetup(self):
for p in self.libdirsWalked:
if p in sys.path:
sys.path.remove(p)
def isDemo(self):
return self.demo == "Yes"
def loadInfo(self, path):
configPath = os.path.join(path, "package.info")
if os.path.exists(configPath):
cp = ConfigParser.SafeConfigParser()
try:
cp.read(configPath)
except:
logging.error("Failed to load config file: %s" % configPath)
#print this out because that pack will need to fix it:
logging.error("Printing exception for CANVAS Exploit Pack")
import traceback
traceback.print_exc(file=sys.stderr)
logging.error("Exploit pack config file could not be read: %s" % configPath)
raise ExploitPackError()
#this is where self.name comes from
for k in ["name", "longName", "author", "version", "libdirs", "demo", "readme", "contactUrl", "contactEmail", "contactPhone", "license"]:
setattr(self, k, cp.get("main", k))
# If exploit pack author == Immunity, it is not a third party pack
try:
if self.author.lower() == 'immunity': self.third_party = False
except Exception:
pass
self.license = os.path.join(path, self.license)
if not os.path.exists(self.license):
raise ExploitPackError("CANVAS Exploit pack License file %s missing" % self.license)
self.readme = os.path.join(path, self.readme)
if not os.path.exists(self.readme):
raise ExploitPackError("CANVAS Exploit pack Readme file %s missing" % self.readme)
if self.demo not in ["Yes", "No"]:
raise ExploitPackError("CANVAS Exploit Pack demo value %s is not one of 'Yes' or 'No'")
libdirs = []
def addDir(arg, dirname, names):
libdirs.append(dirname)
for i in self.libdirs.split(","):
os.path.walk(os.path.join(self.path, i), addDir, None)
self.libdirsWalked = libdirs
logging.info("Initializing exploit pack: [%s]" % self.longName)
for section in cp.sections():
if section == "main":
continue
x = os.path.join(path, section)
if os.path.exists(x):
self.exploitdirs.append(x)
devlog("canvasengine: Added exploit pack exploit path: %s" % x)
logging.info("Exploit pack [%s] initialized correctly" % self.longName)
# print "[+] Exploit pack (%s) initialized" % self.longName
# registermoduleslog.succeeded()
else:
raise ExploitPackError("Exploits directory (%s) specified in exploit pack (%s) is missing" % (x, self.name))
# print ""
for d in self.exploitdirs:
self.modules += processModuleDir(d)
else:
raise ExploitPackError("No package.info file in exploit pack directory %s" % path)
# Stores a name:exploitPack instances dict
exploitPacks = {}
loadedExploitPaths = None
def loadExploitPaths():
"""Single place to handle paths to exploit collections"""
# This might be called multiple times, so it must be safe to do so.
global exploitPacks
global loadedExploitPaths
if loadedExploitPaths != None:
return loadedExploitPaths
#
# XXX: We are still including exploits/ allowing people to simply drop modules
# in there only to provide time before the final change
#
exploitdirslist = ["exploits/web",
"exploits/remote/universal",
"exploits/remote/windows",
"exploits/remote/unix",
"exploits/remote/cisco",
"exploits/local/windows",
"exploits/local/unix",
"exploits/clientside/universal",
"exploits/clientside/windows",
"exploits/clientside/unix",
"exploits/trojan",
"exploits/command/universal",
"exploits/command/windows",
"exploits/command/unix",
"exploits/recon",
"exploits/DoS",
"exploits/tool",
"exploits/reporting",
"exploits/server",
"exploits/config",
"exploits/importexport",
"exploits/fuzzer",
"exploits"]
for d in exploitdirslist:
processModuleDir(d)
exploitpacks = CanvasConfig.get("exploit_pack_dirs", "").split(",")
if "EXPLOITPACKS" in os.environ:
for d in os.environ["EXPLOITPACKS"].split(","):
exploitpacks.append(d)
for epd in exploitpacks:
if os.path.exists(epd):
for i in os.listdir(epd):
if i == ".svn":
continue
p = os.path.join(epd, i)
if os.path.isdir(p):
try:
ep = ExploitPack(p)
if ep.name not in exploitPacks.keys():
exploitPacks[ep.name] = ep
else:
# If we have both the demo and the full versions of the same pack, we discard the demo one
# in favour of the full-flavoured version.
if ep.demo == "No" and exploitPacks[ep.name].demo == "Yes":
exploitPacks[ep.name].unsetup()
exploitPacks[ep.name] = ep
exploitdirslist += ep.exploitdirs
except ExploitPackError, i:
logging.error("Error loading exploit pack from %s: %s" % (p, i))
if "MOREEXPLOITS" in os.environ:
newpath = os.environ["MOREEXPLOITS"]
devlog("canvasengine", "Loading more exploits from %s" % newpath)
exploitdirslist.append(newpath)
processModuleDir(newpath)
loadedExploitPaths = exploitdirslist
return exploitdirslist
def processModuleDir(mydir):
global moduleDirectoryMap
exploitsNames = os.listdir(mydir)
exploitsNames = interestingDirlist(exploitsNames, mydir)
exploitsNames.sort()
moduleDirectoryMap[mydir] = exploitsNames
return exploitsNames
def exploitmodsGet(extmode = False):
global __exploitmods_old
global __exploitmods
if extmode:
return __exploitmods
return __exploitmods_old
def registeredModuleList(extmode = False, functype = 'keys'):
modulelist = getattr(exploitmodsGet(extmode), functype)()
modulelist.sort()
return modulelist
def registerModule(name):
"""
Imports and adds an exploit module to our list, returns 1 on success"
"""
assert not '-' in name, "[-] Can't import modules with '-' in name (tried to import %s)" % name
global __exploitmods_old
if __exploitmods_old.has_key(name):
devlog('registerModule', "return module from cache: %s" % __exploitmods_old[name])
return __exploitmods_old[name]
# Too verbose - A.
# registermoduleslog.log(name)
loadExploitPaths()
dirname = checkAndSetPath(name)
rname = name
sys.path.insert(0, dirname)
# XXX TODO clean VSP code here.
try:
exploitmod = __import__(rname, globals(), locals(), [dirname])
except ImportError:
# first module import on VisualSploit will fail because sys.path was not fixed yet
cwd = os.getcwd()
if cwd.find("VisualSploit") != -1:
logging.warning("Ignoring initial exception due to VisualSploit path fix")
dirname = checkAndSetPath(name)
try:
exploitmod = __import__(rname, globals(), locals(), [dirname])
except ImportError:
if debug_enabled:
import traceback
traceback.print_exc(file=sys.stdout)
devlog('all', "Was unable to import %s" % name)
exploitmod = None #failure
else:
if debug_enabled:
import traceback
traceback.print_exc(file=sys.stdout)
# XXX shouldn't be a print here? to tell the user smth is wrong.
devlog('all', "Was unable to import %s" % name)
exploitmod = None #failure
sys.path.remove(dirname)
if exploitmod:
yaml_path = os.path.join(dirname, "canvas.yaml")
if os.path.isfile(yaml_path):
try:
with open(yaml_path) as f:
metadata = yaml.load(f)
for _key, _val in metadata.iteritems():
setattr(exploitmod, _key, _val)
if not hasattr(exploitmod, "EXPLOIT_PACK_NAME"):
setattr(exploitmod, "EXPLOIT_PACK_NAME", getExploitPackName(exploitmod))
except Exception as e:
logging.error("Error while loading %s (%s)" % (exploitmod, str(e)))
try:
mod = CanvasModule(name, dirname, exploitmod)
__exploitmods_old[name] = exploitmod
__exploitmods[name] = mod
except Exception, ex:
registermoduleslog.failed()
bugreport()
# Too verbose - A
# registermoduleslog.succeeded()
else: