-
Notifications
You must be signed in to change notification settings - Fork 2
/
windows-exploit-suggester.py
1639 lines (1352 loc) · 69.2 KB
/
windows-exploit-suggester.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
# -*- coding: utf-8 -*-
#
# Windows Exploit Suggester
# revision 3.3, 2017-02-13
#
# author: Sam Bertram, Gotham Digital Science
# blog post: "Introducing Windows Exploit Suggester", http://blog.gdssecurity.com/
#
# DESCRIPTION
#
# This tool compares a targets patch levels against the Microsoft vulnerability
# database in order to detect potential missing patches on the target. It also
# notifies the user if there are public exploits and Metasploit modules
# available for the missing bulletins.
#
# It requires the 'systeminfo' command output from a Windows host in order to
# compare that the Microsoft security bulletin database and determine the
# patch level of the host.
#
# It has the ability to automatically download the security bulletin database
# from Microsoft with the --update flag, and saves it as an Excel spreadsheet.
#
# When looking at the command output, it is important to note that it assumes
# all vulnerabilities and then selectively removes them based upon the hotfix
# data. This can result in many false-positives, and it is key to know what
# software is actually running on the target host. For example, if there are
# known IIS exploits it will flag them even if IIS is not running on the
# target host.
#
# The output shows either public exploits (E), or Metasploit modules (M) as
# indicated by the character value.
#
# It was heavily inspired by Linux_Exploit_Suggester by Pentura.
#
# Blog Post: "Introducing Windows Exploit Suggester", https://blog.gdssecurity.com/labs/2014/7/11/introducing-windows-exploit-suggester.html
#
# USAGE
#
# update the database
#
# $ ./windows-exploit-suggester.py --update
# [*] initiating...
# [*] successfully requested base url
# [*] scraped ms download url
# [+] writing to file 2014-06-06-mssb.xlsx
# [*] done
#
# install dependencies
#
# (install python-xlrd, $ pip install xlrd --upgrade)
#
# feed it "systeminfo" input, and point it to the microsoft database
#
# $ ./windows-exploit-suggester.py --database 2014-06-06-mssb.xlsx --systeminfo win7sp1-systeminfo.txt
# [*] initiating...
# [*] database file detected as xls or xlsx based on extension
# [*] reading from the systeminfo input file
# [*] querying database file for potential vulnerabilities
# [*] comparing the 15 hotfix(es) against the 173 potential bulletins(s)
# [*] there are now 168 remaining vulns
# [+] windows version identified as 'Windows 7 SP1 32-bit'
# [*]
# [M] MS14-012: Cumulative Security Update for Internet Explorer (2925418) - Critical
# [E] MS13-101: Vulnerabilities in Windows Kernel-Mode Drivers Could Allow Elevation of Privilege (2880430) - Important
# [M] MS13-090: Cumulative Security Update of ActiveX Kill Bits (2900986) - Critical
# [M] MS13-080: Cumulative Security Update for Internet Explorer (2879017) - Critical
# [M] MS13-069: Cumulative Security Update for Internet Explorer (2870699) - Critical
# [M] MS13-059: Cumulative Security Update for Internet Explorer (2862772) - Critical
# [M] MS13-055: Cumulative Security Update for Internet Explorer (2846071) - Critical
# [M] MS13-053: Vulnerabilities in Windows Kernel-Mode Drivers Could Allow Remote Code Execution (2850851) - Critical
# [M] MS13-009: Cumulative Security Update for Internet Explorer (2792100) - Critical
# [M] MS13-005: Vulnerability in Windows Kernel-Mode Driver Could Allow Elevation of Privilege (2778930) - Important
# [*] done
#
# possible exploits for an operating system can be used without hotfix data
# $ ./windows-exploit-suggester.py --database 2014-06-06-mssb.xlsx --ostext 'windows server 2008 r2'
# [*] initiating...
# [*] database file detected as xls or xlsx based on extension
# [*] getting OS information from command line text
# [*] querying database file for potential vulnerabilities
# [*] comparing the 0 hotfix(es) against the 196 potential bulletins(s)
# [*] there are now 196 remaining vulns
# [+] windows version identified as 'Windows 2008 R2 64-bit'
# [*]
# [M] MS13-009: Cumulative Security Update for Internet Explorer (2792100) - Critical
# [M] MS13-005: Vulnerability in Windows Kernel-Mode Driver Could Allow Elevation of Privilege (2778930) - Important
# [E] MS11-011: Vulnerabilities in Windows Kernel Could Allow Elevation of Privilege (2393802) - Important
# [M] MS10-073: Vulnerabilities in Windows Kernel-Mode Drivers Could Allow Elevation of Privilege (981957) - Important
# [M] MS10-061: Vulnerability in Print Spooler Service Could Allow Remote Code Execution (2347290) - Critical
# [E] MS10-059: Vulnerabilities in the Tracing Feature for Services Could Allow Elevation of Privilege (982799) - Important
# [E] MS10-047: Vulnerabilities in Windows Kernel Could Allow Elevation of Privilege (981852) - Important
# [M] MS10-002: Cumulative Security Update for Internet Explorer (978207) - Critical
# [M] MS09-072: Cumulative Security Update for Internet Explorer (976325) - Critical
#
# TROUBLESHOOTING
#
# If you're receiving the following error message, update the xlrd library
# $ pip install xlrd --update
#
# [*] initiating winsploit version 24...
# [*] database file detected as xls or xlsx based on extension
# Traceback (most recent call last):
# File "windows-exploit-suggester/windows-exploit-suggester.py", line 1414, in <module>
# main()
# File "windows-exploit-suggester/windows-exploit-suggester.py", line 354, in main
# wb = xlrd.open_workbook(ARGS.database)
# File "/usr/lib/pymodules/python2.7/xlrd/__init__.py", line 370, in open_workbook
# biff_version = bk.getbof(XL_WORKBOOK_GLOBALS)
# File "/usr/lib/pymodules/python2.7/xlrd/__init__.py", line 1323, in getbof
# raise XLRDError('Expected BOF record; found 0x%04x' % opcode)
# xlrd.biffh.XLRDError: Expected BOF record; found 0x4b50
#
# LIMITATIONS
#
# Currently, if the 'systeminfo' command reveals 'File 1' as the output for
# the hotfixes, it will not be able to determine which are installed on
# the target. If this occurs, the list of hotfixes will need to be
# retrieved from the target host and passed in using the --hotfixes flag
#
# It currently does not seperate 'editions' of the Windows OS such as
# 'Tablet' or 'Media Center' for example, or different architectures, such as
# Itanium-based only
#
# False positives also occur where it assumes EVERYTHING is installed
# on the target Windows operating system. If you receive the 'File 1'
# output, try executing 'wmic qfe list full' and feed that as input
# with the --hotfixes flag, along with the 'systeminfo'
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# TODOLIST
#
# TODO better if/then/case when detecting OS. more flexibility with parsing
# different systeminfo output
# TODO seperate by editions? may result in false positives
# TODO count the number of exploits in the summary prior to outputting it?
# TODO finish -s --search function so that all info on an MS number can be
# returned
# TODO add titles to exploit list so that it is more portable
# TODO test for Windows RT systeminfo output
# TODO improved msf/poc output? perhaps adding details on each MS number?
# TODO if it's running on windows, then try and execute the systeminfo command?
# TODO SPEED. this is now way too slow... somewhat improved!
# TODO automatically install python module? xlrd.
# TODO manually override MS11-011 for Non-Affected Products. The bulletin
# database is wrong.
# Windows 7 for 32-bit Systems Service Pack 1
# Windows 7 for x64-based Systems Service Pack 1
# Windows Server 2008 R2 for x64-based Systems Service Pack 1
# Windows Server 2008 R2 for Itanium-based Systems Service Pack 1
#
# CHANGE LOG
# v33 2017-02-13
# - added links to exploits and resources for each bulletins. can be ignored with the -q/--quiet flag
# - hard coded ms11-011 to ignore false positives
# - added additional resources
#
# v31 2016-02-10
# - changed bulletin url, microsoft 404'd it
#
# v30 2016-01-04
# - added exploits and bulletins from the past six months
#
# v29 2015-09-16
# - adding support for windows 10
#
# v28 2015-07-30
# - added bulletin scraping for xlsx and xls files using regex. thanks to
# edebernis for reporting the bug
# - added ms15-022, ms15-015 update to msf
#
# v27 2015-06-18
# - added new bulletin url that is only xls and not xlsx. thanks to bstork for
# reporting the bug
# - added ms15-010, ms15-051, and ms15-052
#
# v26 2015-06-02
# - small bug fix with linked output
# - added duplicates flag that can allow for bulletins to be displayed
# multiple times. this will allow for greater analysis on linked bulletins
#
# v25 2015-05-18
# - added ms15-051 local priv
#
# v24 2015-01-30
# - added --sub/-s command in order to display output of msids as linked
# this aides in demonstrating what patches need to be applied precisely.
# this change was implemented in v23, but only followed the depth to level
# 1 instead of the entire way.
# - fixed a bug that know allows for multiple supercedes msids in the db
# - allowed for getarchitecture to be recursive, and reduced redunancy when
# it is called throughout the program
# - added ms14-070
#
# v23 2015-01-26
# - typo in --local flag case (pontential vs potential). issue #5 closed.
#
# v22 2015-01-23
# - speed optimisations! it was too slow beforehand. realised i could easily
# make it a bit more efficient
#
# v21 2015-01-22
# - changed display formatting to include nested/linked MS numbers. makes it
# easier to determine the dependencies
# - made args global
# - changed some code formatting, including double-space instead of \t
# - added some additional comments
# - disable ANSI output if on windows platform
# - added recent exploits
#
# v20 2014-12-16
# - added ms14-068,ms14-064,ms14-060, and ms14-058 to the internal vuln list
#
# v19 2014-10-08
# - added support for windows server 2012, this includes ignoring the
# architecture for 2012, and forcing from 32-bit to 64-bit
#
# v18 2014-09-02
# - added ms14-029 poc
#
# v17 2014-08-05
# - fixed a bug where it would not detect OS version when a unicode char comes
# before search string
#
# v16 2014-07-28
# - improved reading of various file encodings for systeminfo. now attempts to
# detect the file first, otherwise loops through common encodings
# - improved OS, service pack, architecture, and release detection. this is now
# not English-dependent as it was previously
# - better architecture detection of systeminfo input (look for -based string)
# - added /usr/bin/env python
# - added ms14-035 poc
#
# v15 2014-07-15
# - changed file open to io, and attempt to decode as utf-8; otherwise attempt
# utf-16
#
# v14 2014-07-13
# - allowed for --ostext flag to properly supersede OS detection of systeminfo
# input
#
# v13a 2014-07-01
# - added new msf flags for ms13-097, and ms14-009
#
# v12a 2014-06-06
# - quick cleanup for release
#
# v11a 2014-05-02
# - fixed the bulletin scrape regex for the update command. ms changed it
#
# v10a 2014-03-24
# - added a hotfixes argument, that can be used to supplement the list
# of hotfixes detected in the systeminfo input
# - added severity at the end of the output when reporting bulletins
# - added a 'patches' argument, that can be used to determine any
# of the hotfixes for a specific bulletin. this is good for debugging.
#
# v09a 2014-03-18
# - again, another massive bug on the linked kb searching function
# getlinkedms(). should be fixed now
# - also checks columns 11 and 12 for superseded, i think it has to
# do with dos and *nix output
#
# v08a 2014-02-14
# - bug where the superseded column wasn't being checked
# this may be because it's only xlsx and it parsed differently in csv
# - added some new exploits from edb
#
# v07a 2014-02-12
# - added indicator for os version, and in green
# - better parsing of architecture for itanium based support
#
# v06a 2014-01-19
# - added 'ostext' or 'o' option, when don't have any patch information
# but just know the OS
#
# v05a
# - added a check for "Kernel version" column, as well as "OS version"
#
# v04a
# - added support for XLSX files directly with the updated XLRD library, this
# requires the python-xlrd library to be installed and upgraded with:
# $ pip install xlrd --upgrade
# - changed MS13-101 to E, as there isn't a metasploit module (yet!)
#
# v03a
# - fixed an issue where component KB wasn't being checked
#
# FUNCTIONS
#
# def main():
# def run(database):
# def detect_encoding(filename):
# def trace(database):
# def patches(database):
# def getversion(name, release, servicepack, architecture):
# def getname(ostext):
# def getrelease(ostext):
# def getservicepack(ostext):
# def getarchitecture(ostext):
# def getitanium(ostext):
# def getpatch(ostext):
# def getbulletinids(haystack):
# def isaffected(name, release, servicepack, architecture, haystack):
# def getlinkedms(msids, database):
# def getexploit(msid = 0):
# def update():
# def merge_list(li):
#
import re
import platform
import argparse
import subprocess
import csv
import StringIO
import os
import datetime
import urllib2
import io
from random import randint
from time import sleep
from tempfile import NamedTemporaryFile
from sys import exit
# constants/globals
MSSB_URL = 'http://www.microsoft.com/en-gb/download/confirmation.aspx?id=36982'
BULLETIN_URL = 'http://download.microsoft.com/download/6/7/3/673E4349-1CA5-40B9-8879-095C72D5B49D/BulletinSearch.xlsx'
VERSION = "3.3"
# global parser
parser = argparse.ArgumentParser(description="search microsoft security bulletins for exploits based upon the patch level of the machine by feeding in systeminfo command")
parser.add_argument("-v", "--verbose", help="verbose output", action="store_true")
parser.add_argument("-i", "--systeminfo", help="feed in an input file that contains the 'systeminfo' command")
parser.add_argument("-d", "--database", help="the file that contains the microsoft security bulletin database")
parser.add_argument("-u", "--update", help="required flag to even run the script", action="store_true")
parser.add_argument("-a", "--audit", help="show all entries, not only exploits", action="store_true")
parser.add_argument("-t", "--trace", help="used to determine linked ms bulletins")
parser.add_argument("-p", "--patches", help="used to determine specific patches for a ms bulletin")
parser.add_argument("-o", "--ostext", help="a loose text representation of the windows OS (ex: \"windows xp home edition sp2\")")
parser.add_argument("-s", "--sub", help="generate output using linked/sub bulletins. WARNING: SLOW!", action="store_true")
parser.add_argument("-2", "--duplicates", help="allow duplicate ms bulletin output within the results. this will produce a lot of output, but is useful when determining linked ms bulletins", action="store_true")
parser.add_argument("-q", "--quiet", help="don't show exploit information. shorter output", action="store_true")
# hotfixes
# used to parse "wmic qfe list full" input, and to solve the 'File 1' errors
parser.add_argument("-H", "--hotfixes", help="a loose list of hotfixes to be added, for use with the following command: 'wmic qfe list full'")
# search by exploit type only
exptypegroup = parser.add_mutually_exclusive_group()
exptypegroup.add_argument("-r", "--remote", help="search remote exploits only", action="store_true")
exptypegroup.add_argument("-l", "--local", help="search local exploits only", action="store_true")
# global args parsed
ARGS = parser.parse_args()
def main():
ALERT("initiating winsploit version %s..." % VERSION)
database = ''
# if there is a database switch
if ARGS.database:
# split name and extension
name, extension = os.path.splitext(ARGS.database)
# csv
if 'csv' in extension:
ALERT("database file detected as csv based on extension", ALERT.NORMAL)
# attempt to open the file
try:
dbfile = open(ARGS.database, 'r')
except IOError, e:
ALERT("could not open the file %s" % filename, ALERT.BAD)
exit(1)
data = ''
for line in dbfile:
data += line
database = data
dbfile.close()
# xls or xslx
elif 'xls' in extension:
ALERT("database file detected as xls or xlsx based on extension", ALERT.NORMAL)
try:
import xlrd
except ImportError as e:
ALERT("please install and upgrade the python-xlrd library", ALERT.BAD)
exit(1)
# open the xls file
try:
wb = xlrd.open_workbook(ARGS.database)
except IOError as e:
ALERT("no such file or directory '%s'. ensure you have the correct database file passed in --database/-d" % ARGS.database, ALERT.BAD)
exit(1)
#sh = wb.sheet_by_name('Export Bulletin Search Spreadsh')
sh = wb.sheet_by_index(0)
# read the spreadsheet into a temp file
f = NamedTemporaryFile(mode='wb')
wr = csv.writer(f, quoting=csv.QUOTE_NONE, delimiter=',')
data = ''
# loop through xls
for rownum in xrange(sh.nrows):
values = sh.row_values(rownum)
# loop through row values, and process input
for i in range(len(values)):
values[i] = unicode(values[i]).encode('utf8')
values[i] = values[i].replace('\n',' ')
values[i] = values[i].replace(',','')
values[i] = values[i].replace('.0','')
data += ",".join(values)
data += '\n'
# set the database to the csv data
database = data
# unknown filetype, error
else:
ALERT("unknown filetype. change file extension to indicate csv or xls/xlsx", ALERT.BAD)
exit(1)
if ARGS.trace: trace(database)
elif ARGS.systeminfo or ARGS.ostext: run(database)
elif ARGS.update: update()
elif ARGS.patches: patches(database)
# error
else:
ALERT("an error occured while running, not enough arguments", ALERT.BAD)
exit(1)
ALERT("done")
# end main()
def run(database):
# variables used
ostext=None
name=None
release=None
servicepack=None
# will default to 32-bit, but can be 64 bit or itanium
architecture=None
hotfixes=set([])
bulletinids=set([])
potential=[]
vulns={}
ids=set([])
cmdoutput = []
# test for database
if not ARGS.database:
ALERT("please supply a MSSB database file with the --database or -d flag, this can be downloaded using the --update command", ALERT.BAD)
exit(1)
# read from ostext first
if ARGS.ostext:
ALERT("getting OS information from command line text")
name=getname(ARGS.ostext)
release=getrelease(ARGS.ostext)
servicepack=getservicepack(ARGS.ostext)
architecture=getarchitecture(ARGS.ostext)
# the os name at least has to be identified
if not name:
ALERT("unable to determine the windows version command line text from '%s'" % ARGS.ostext, ALERT.BAD)
exit(1)
# get the systeminfo information from the input file
if ARGS.systeminfo:
ALERT("attempting to read from the systeminfo input file")
# when reading the systeminfo file, we want to attempt to detect it using chardet
# if this doesn't work, we will loop through a list of common encodings and try them all
encodings = ['utf-8', 'utf-16', 'utf-16-le', 'utf-16-be', 'iso-8859-2']
detected_encoding = detect_encoding(ARGS.systeminfo)
# insert detected encoding to the front of the list
if detected_encoding:
if ARGS.verbose: ALERT("detected encoding of file as '%s'" % detected_encoding)
encodings.insert(0, detected_encoding)
cmdfile = None
cmdoutput = None
# now loop through all encodings, with the detected one first (if it was possible)
for encoding in encodings:
if ARGS.verbose: ALERT(" attempting to read with '%s' encoding" % encoding)
# if we can read the file, and read the command output, we are done with the loop
try:
cmdfile = io.open(ARGS.systeminfo, "r", encoding=encoding) # throws UnicodeDecodeError
cmdoutput = cmdfile.readlines() # throws UnicodeError
break
except (UnicodeError, UnicodeDecodeError) as e:
ALERT("could not read file using '%s' encoding: %s" % (encoding, e), ALERT.BAD)
# file might not exist
except:
ALERT("could not read from input file specified: %s" % ARGS.systeminfo, ALERT.BAD)
exit(1)
# general catchall if somehow it was able to keep processing
if not cmdfile or not cmdoutput:
ALERT("could not read from input file, or could not detect encoding", ALERT.BAD)
exit(1)
# file read successfully
ALERT("systeminfo input file read successfully (%s)" % encoding, ALERT.GOOD)
# error
if not ARGS.systeminfo and not ARGS.ostext and platform.system() != 'Windows':
ALERT("please run from a Windows machine, or provide an input file using --systeminfo, or use the --ostext option to get data with no patch information", ALERT.BAD)
exit(1)
# parse the systeminfo information
hotfix=False
# loop through the systeminfo input
for haystack in cmdoutput:
# only attempt to set the version, arch, service pack if there is no
# ostext flag
if not ARGS.ostext:
# when detecting the operating system version, every line (independent of language)
# appears to have Microsoft Windows in it, sometimes with (R)
if "Microsoft" in haystack and "Windows" in haystack and not name:
name = getname(haystack)
# the windows release is similar to the above and has the text 'Microsoft Windows' in the text
if "Microsoft" in haystack and "Windows" in haystack and not release:
release = getrelease(haystack)
# similar to OS, there is the words 'Service Pack'
if "Service Pack" in haystack and not servicepack:
servicepack = getservicepack(haystack)
# get architecture only if -based is in the line, and --ostext hasn't been used
if "-based" in haystack and not architecture:
architecture=getarchitecture(haystack)
# look for kbs
if ("KB" in haystack or "]: " in haystack):
patch=getpatch(haystack)
# if a patch was parsed
if patch:
if ARGS.verbose: ALERT("found hotfix %s" % patch)
hotfixes.add(patch)
# now process the hotfixes argument input
if ARGS.hotfixes:
encodings = ['utf-8', 'utf-16', 'utf-16-le', 'utf-16-be', 'iso-8859-2']
detected_encoding = detect_encoding(ARGS.systeminfo)
# insert detected encoding to the front of the list
if detected_encoding:
if ARGS.verbose: ALERT("detected encoding of file as '%s'" % detected_encoding)
encodings.insert(0, detected_encoding)
cmdfile = None
hotfixesfile = None
# now loop through all encodings, with the detected one first (if it was possible)
for encoding in encodings:
if ARGS.verbose: ALERT(" attempting to read with '%s' encoding" % encoding)
# if we can read the file, and read the command output, we are done with the loop
try:
cmdfile = io.open(ARGS.hotfixes, "r", encoding=encoding) # throws UnicodeDecodeError
hotfixesfile = cmdfile.readlines() # throws UnicodeError
break
except (UnicodeError, UnicodeDecodeError) as e:
if ARGS.verbose: ALERT("could not read file using '%s' encoding: %s" % (encoding, e), ALERT.BAD)
# file might not exist
except:
ALERT("could not read from input file specified: %s" % ARGS.hotfixes, ALERT.BAD)
exit(1)
# general catchall if somehow it was able to keep processing
if not cmdfile or not hotfixesfile:
ALERT("could not read from input file, or could not detect encoding", ALERT.BAD)
exit(1)
# file read successfully
ALERT("hotfixes input file read successfully (%s)" % encoding, ALERT.GOOD)
# loop through hotfixes file input
for haystack in hotfixesfile:
# look for kbs
if ("KB" in haystack or "]: " in haystack):
patch=getpatch(haystack)
# if a patch was parsed
if patch:
if ARGS.verbose: ALERT("found hotfix %s" % patch)
hotfixes.add(patch)
if ARGS.verbose:
ALERT("name: %s; release: %s; servicepack: %s; architecture: %s" % (name, release, servicepack, architecture))
# verify that a windows os was at least able to be parsed
if not name:
if ARGS.systeminfo:
ALERT("unable to determine the windows versions from the input file specified. consider using --ostext option to force detection (example: --ostext 'windows 7 sp1 64-bit')", ALERT.BAD)
exit(1)
if ARGS.verbose:
ALERT("name: %s" % name)
ALERT("release: %s" % release)
ALERT("service pack: %s" % servicepack)
ALERT("architecture: %s" % architecture)
ALERT("querying database file for potential vulnerabilities")
# potential, all matches within the CSV database for the name,release,sp,arch
# bulletinds, set of the above with MSIDs (good to keep count)
# get the potential bulletins
try:
for row in csv.reader(StringIO.StringIO(database)):
bulletinid=row[1]
affected=row[6]
if isaffected(name, release, servicepack, architecture, affected):
# only add the bulletin if it's not already in the list
if bulletinid not in bulletinids:
potential.append(row)
bulletinids.add(bulletinid)
if ARGS.verbose:
ALERT("%s has been added to potential list '%s'" % (bulletinid, affected))
except csv.Error, e:
ALERT('could not parse database file, make sure it is in the proper format', ALERT.BAD)
exit(1)
# there should always be some potential vulns, because of the amount of windows software and false positives
if len(bulletinid) == 0:
ALERT("there are no potential vulnerabilities for, ensure you're searching a valid windows OS", ALERT.BAD)
exit(1)
ALERT("comparing the %s hotfix(es) against the %s potential bulletins(s) with a database of %s known exploits" % (len(hotfixes), len(bulletinids), getexploit()))
# start removing the vulns because of hotfixes
for row in list(potential):
# ms bulletin
bulletinid=row[1]
kb=row[2]
componentkb=row[7]
for hotfix in hotfixes:
# if either the hotfixes match the kb or componentkb columns, and the bulletin is in the list
# of potential bulletins
if (hotfix == kb or hotfix == componentkb) and bulletinid in bulletinids:
if ARGS.verbose:
ALERT(" %s hotfix triggered a removal of %skb and the %s bulletin; componentkb is %s" % (hotfix,kb,bulletinid,componentkb))
# get the linked ms, this will automatically calculate the superseded by as well
linkedms = getlinkedms([bulletinid], csv.reader(StringIO.StringIO(database)))
linkedmsstr = ''
# calculate the pretty string, only care when verbose
if len(linkedms) > 0:
for m in linkedms:
linkedmsstr += ' ' + m
if ARGS.verbose:
if hotfix == kb:
ALERT(" due to presence of KB%s (Bulletin KB) removing%s bulletin(s)" % (kb, linkedmsstr))
elif componentkb == kb:
ALERT(" due to presence of KB%s (Component KB) removing%s bulletin(s)" % (componentkb, linkedmsstr))
bulletinids = bulletinids.difference(linkedms)
potential.remove(row)
ALERT("there are now %s remaining vulns" % len(bulletinids))
# search local exploits only
if ARGS.local:
ALERT("searching for local exploits only")
for row in list(potential):
bulletinid = row[1]
impact = row[4]
if bulletinid in bulletinids and not "elevation of privilege" in impact.lower():
remove = getlinkedms([bulletinid], csv.reader(StringIO.StringIO(database)))
if ARGS.verbose:
ALERT(" removing %s (total of %s MS ids), because of its impact %s" % (bulletinid, len(remove), impact))
bulletinids = bulletinids.difference(remove)
potential.remove(row)
# search remote exploits only
if ARGS.remote:
ALERT("searching for remote exploits only")
for row in list(potential):
bulletinid = row[1]
impact = row[4]
if bulletinid in bulletinids and not "remote code execution" in impact.lower():
remove = getlinkedms([bulletinid], csv.reader(StringIO.StringIO(database)))
if ARGS.verbose:
ALERT(" removing %s (total of %s MS ids), because of its impact %s" % (bulletinid, len(remove), impact))
bulletinids = bulletinids.difference(remove)
potential.remove(row)
# print windows version
version=getversion(name, release, servicepack, architecture)
ALERT("[E] exploitdb PoC, [M] Metasploit module, [*] missing bulletin", ALERT.GOOD)
ALERT("windows version identified as '%s'" % version, ALERT.GOOD)
# spacer
ALERT("")
# vulns, the dictionary of the bulletins based off of the potential bulletins
# also, a good opportunity to remove false-positives due to the
# differences in the technet post and bulletin
for row in potential:
id = row[1]
# start removing vulns because of false-positives
# Manual override for MS11-011 to reduce false positives. The article was updated, but the bulletin database wasn't (https://technet.microsoft.com/en-us/library/security/ms11-011.aspx)
# V1.2 (March 18, 2011): Added Windows 7 for 32-bit Systems Service Pack 1, Windows 7 for x64-based Systems Service Pack 1, Windows Server 2008 R2 for x64-based Systems Service Pack 1, and Windows Server 2008 R2 for Itanium-based Systems Service Pack 1 to Non-Affected Software. This is an informational change only. There were no changes to the security update files or detection logic.
if id == 'MS11-011':
ms11_011 = ['Windows 7 for 32-bit Systems Service Pack 1', 'Windows 7 for x64-based Systems Service Pack 1', 'Windows Server 2008 R2 for x64-based Systems Service Pack 1','Windows Server 2008 R2 for Itanium-based Systems Service Pack 1']
for not_affected in ms11_011:
compare_version = getversion(getname(not_affected),getrelease(not_affected),getservicepack(not_affected),getarchitecture(not_affected))
if version == compare_version:
if ARGS.verbose: ALERT("Ignoring MS11-011 false positive due to it not affecting '%s'" % compare_version)
id = False
for bulletinid in bulletinids:
if bulletinid == id:
title = row[5]
kb = row[2]
severity = row[3]
if id not in ids:
vulns[id] = [title,kb,severity]
ids.add(id)
# alerted, if a bulletin has been alerted to the user so that it doesn't appear twice
# this occurs when a bulletin has multiple parents
# msids, the actual data for all of the relevant msids (the row from the CSV)
alerted = set()
msids = sorted(vulns, reverse=True)
# loop through the bulletinids which is the set of the actual bulletins that are to
# be alerted
for msid in msids:
## don't alert twice, no matter the case
if msid not in alerted:
# get the msid, exploitability alert rating, and resources
m,exploit,resources = getexploit(msid)
# only display the message, if the exploit flag isn't used
# or if it is used, and the alert level is MSF or EXP
if ARGS.audit or (exploit == ALERT.MSF or exploit == ALERT.EXP):
alert = ALERT.NORMAL
if exploit: alert = exploit
ALERT("%s: %s (%s) - %s" % (msid, vulns[msid][0], vulns[msid][1], vulns[msid][2]), alert)
if resources and not ARGS.quiet:
for resource in resources:
ALERT(" %s" % resource)
ALERT("")
alerted.add(msid)
# only attempt to display linked/sub msids based on cli arguments
if ARGS.sub:
# linked ms, the children of this msid
linked = set(getlinkedms([msid], csv.reader(StringIO.StringIO(database))))
linked = linked.intersection(msids)
# loop through the linked msids, and only display those that qualify and
# those that have not been alerted yet
for lmsid in sorted(linked, reverse=True):
if lmsid in msids and lmsid not in alerted:
lexploit = getexploit(lmsid)
lalert = ALERT.NORMAL
if ARGS.audit or (lexploit == ALERT.MSF or lexploit == ALERT.EXP):
if lexploit: lalert = lexploit
ALERT("|_%s: %s (%s) - %s" % (lmsid, vulns[lmsid][0], vulns[lmsid][1], vulns[lmsid][2]), lalert)
# only allow duplicate events to be displayed when command-line args passed
if not ARGS.duplicates: alerted.add(lmsid)
# end run()
# attempt to detect character encoding of a file
# otherwise return None
# https://stackoverflow.com/questions/3323770/character-detection-in-a-text-file-in-python-using-the-universal-encoding-detect
def detect_encoding(filename):
try:
import chardet
data = open(filename, "r").read()
result = chardet.detect(data)
encoding = result['encoding']
return encoding
except:
return None
# the trace command is used to determine linked MS bulletins
# TODO much of this is duplicated from run(). should be merged
def trace(database):
# convert to upper
bulletinid = ARGS.trace.upper()
ALERT("searching for bulletin id %s" % bulletinid)
# get linked msids
lmsids = getlinkedms([bulletinid], csv.reader(StringIO.StringIO(database)))
msids = []
if ARGS.ostext:
ALERT("getting OS information from command line text")
name=getname(ARGS.ostext)
release=getrelease(ARGS.ostext)
servicepack=getservicepack(ARGS.ostext)
architecture=getarchitecture(ARGS.ostext)
if ARGS.verbose:
ALERT("name: %s" % name)
ALERT("release: %s" % release)
ALERT("service pack: %s" % servicepack)
ALERT("architecture: %s" % architecture)
# the os name at least has to be identified
if not name:
ALERT("unable to determine the windows version command line text from '%s'" % ARGS.ostext, ALERT.BAD)
exit(1)
# get linked msids, loop through the row
for row in csv.reader(StringIO.StringIO(database)):
msid = row[1]
affected = row[6]
if msid in lmsids:
# debug
#print ("%s,%s,%s,%s,%s,%s" % (msid, name, release, servicepack, architecture, affected))
if isaffected(name, release, servicepack, architecture, affected) and msid not in msids: msids.append(msid)
else: msids = lmsids
ALERT("linked msids %s" % msids, ALERT.GOOD)
def patches(database):
kbs = []
# convert to upper
bulletinid = ARGS.patches.upper()
ALERT("searching all kb's for bulletin id %s" % bulletinid)
# get linked msids, loop through the row
for row in csv.reader(StringIO.StringIO(database)):
bulletinkb=row[2]
componentkb=row[7]
# if there's a match
if bulletinid in row[1]:
kbs.append(bulletinkb)
kbs.append(componentkb)
ALERT("relevant kbs %s" % (sorted(set(kbs), reverse=True)), ALERT.GOOD)
def getversion(name, release, servicepack, architecture):
version = "Windows " + name
# append release first
if release: version += " R" + release
# then service pack
if servicepack: version += " SP" + servicepack
# architecture
if architecture == "Itanium": version += " Itanium-based"
else: version += " %s-bit" % architecture
return version
def getname(ostext):
if ostext == False:
return False
osname=False
osnamearray=[["xp","XP"],
["2000","2000"],
["2003","2003"],
["vista","Vista"],
["2008","2008"],
[" 7","7"],
[" 8","8"],
["2012","2012"],
["8.1","8.1"],
[" 10","10"]]
for needle in osnamearray:
ostext = ostext.lower()
if "windows" + needle[0] in ostext or "windows " + needle[0] in ostext or "server" + needle[0] in ostext or "server " + needle[0] in ostext:
osname = needle[1]
# the first loop is a more restrictive detection of the OS name, but it does not detect the following
# > Microsoft Windows\xFF7 Entreprise
# so if there is no detection from the first attempt, then search on a more loosely based string of
# needle and space
if not osname:
for needle in osnamearray:
if needle[0] + " " in ostext.lower():
osname = needle[1]
return osname
def getrelease(ostext):
if ostext == False:
return False
osrelease=False
regex="( r| rc|release|rel)[ ]*(\d)"
m=re.search(regex, ostext.lower())
if m and m.group(2):
osrelease=m.group(2)
return osrelease