├── test_data
├── ipl_5.bin
├── mbr_5.bin
├── disk_5.img
├── disk_60.img
├── disk_61.img
├── disk_62.img
├── disk_tc.img
├── ipl_60.bin
├── ipl_61.bin
├── ipl_62.bin
├── mbr_60.bin
├── mbr_61.bin
├── mbr_tc.bin
├── ipl_empty.bin
├── mbr_empty_code.bin
├── vbr_5_off_32256.bin
├── mbr_protect_uefi.bin
├── vbr_60_off_1048576.bin
├── vbr_61_off_1048576.bin
├── vbr_62_off_1048576.bin
├── vbr_61_bitlocker_off_525336576.bin
├── mbr_empty.bin
└── vbr_empty.bin
├── tests
├── conftest.py
├── test_ipl.py
├── test_img.py
├── test_vbr.py
└── test_mbr.py
├── data
└── bootrecord_whitelist.csv
├── README.md
├── LICENSE
└── bootcode_parser.py
/test_data/ipl_5.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/ipl_5.bin
--------------------------------------------------------------------------------
/test_data/mbr_5.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/mbr_5.bin
--------------------------------------------------------------------------------
/test_data/disk_5.img:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/disk_5.img
--------------------------------------------------------------------------------
/test_data/disk_60.img:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/disk_60.img
--------------------------------------------------------------------------------
/test_data/disk_61.img:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/disk_61.img
--------------------------------------------------------------------------------
/test_data/disk_62.img:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/disk_62.img
--------------------------------------------------------------------------------
/test_data/disk_tc.img:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/disk_tc.img
--------------------------------------------------------------------------------
/test_data/ipl_60.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/ipl_60.bin
--------------------------------------------------------------------------------
/test_data/ipl_61.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/ipl_61.bin
--------------------------------------------------------------------------------
/test_data/ipl_62.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/ipl_62.bin
--------------------------------------------------------------------------------
/test_data/mbr_60.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/mbr_60.bin
--------------------------------------------------------------------------------
/test_data/mbr_61.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/mbr_61.bin
--------------------------------------------------------------------------------
/test_data/mbr_tc.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/mbr_tc.bin
--------------------------------------------------------------------------------
/test_data/ipl_empty.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/ipl_empty.bin
--------------------------------------------------------------------------------
/test_data/mbr_empty_code.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/mbr_empty_code.bin
--------------------------------------------------------------------------------
/test_data/vbr_5_off_32256.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/vbr_5_off_32256.bin
--------------------------------------------------------------------------------
/test_data/mbr_protect_uefi.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/mbr_protect_uefi.bin
--------------------------------------------------------------------------------
/test_data/vbr_60_off_1048576.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/vbr_60_off_1048576.bin
--------------------------------------------------------------------------------
/test_data/vbr_61_off_1048576.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/vbr_61_off_1048576.bin
--------------------------------------------------------------------------------
/test_data/vbr_62_off_1048576.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/vbr_62_off_1048576.bin
--------------------------------------------------------------------------------
/test_data/vbr_61_bitlocker_off_525336576.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ANSSI-FR/bootcode_parser/HEAD/test_data/vbr_61_bitlocker_off_525336576.bin
--------------------------------------------------------------------------------
/test_data/mbr_empty.bin:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test_data/vbr_empty.bin:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/tests/conftest.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2
2 | # -*- coding:utf-8 -*-
3 |
4 | from __future__ import unicode_literals
5 | import csv
6 | import os
7 | import pytest
8 |
9 |
10 | BOOTRECORD_WHITELIST_PATH = os.path.join(os.path.dirname(__file__), '..', 'data', 'bootrecord_whitelist.csv')
11 |
12 |
13 | @pytest.fixture(scope='module')
14 | def whitelist(request):
15 | lWhitelist = []
16 | # CSV file content should be "Type,SHA256,Comment"
17 | with open(BOOTRECORD_WHITELIST_PATH, 'rb') as fd:
18 | reader = csv.DictReader(fd)
19 | for row in reader:
20 | lWhitelist.append(row)
21 | return lWhitelist
22 |
23 |
--------------------------------------------------------------------------------
/data/bootrecord_whitelist.csv:
--------------------------------------------------------------------------------
1 | "Type","SHA256","Comment"
2 | "MBR","b5ed343494f0326a08aa6abf7cc9aa4d96207532cf0d2b39453c6eb7bede19e3","NT5.1/NT5.2 MBR"
3 | "MBR","4799e8c92d32bca8e5103110a322523adb7a3909324132bd9abab8f3345e094a","NT6.0 MBR"
4 | "MBR","088995559ab317af9b3291408da689651e8353f62e0a478d92eb0b5a947063fd","NT6.1+ MBR"
5 | "MBR","955ff28fdffd869e617dfc1d44a6a40b45005c5d76491069e06ad48817499fea","GRUB2 MBR"
6 | "MBR","e6e6605c48665800786de4651ade2893970aafb1237a06db0943a8603dd4fce1","TrueCrypt MBR"
7 | "MBR","8a029cf94efd555b34d5564cc5c8e290a6ba5a52b6cdf9f02253f0d939f4dcec","Safeboot MBR"
8 | "MBR","eedc57fa55ab1c71aa2fd511ff121e7d635b1e4bf7e7aeaa2a860360442790e1","Safeboot MBR"
9 | "VBR","5cb5aa385e0ada266690a2821e3a36ad372720d2ff47c0b1cd9d6ebcab25bf4e","NT5.1/NT5.2 VBR"
10 | "VBR","a1932aaba7d6d3adb1637e2ee0c8355706842ba825ea811728165420c518c0b1","NT6.0 VBR"
11 | "VBR","96d38c1be37b9124fb71d1d0f5c52969f0074687fe17aef0e1bafc54428674f6","NT6.1 VBR"
12 | "VBR","51643dcce7e93d795b08e1f19e38374ae4deaf3b1217527561a44aa9913ded23","NT6.2+ VBR"
13 | "VBR","47138cbe995a20483209270ef55693c8c8e85ca870f28789229ce421aded92b4","NT6.1+ Bitlocker VBR"
14 | "IPL","525788a688cfbe9e416122f0bc3cfb32ce9699fd12356b6ccaa173444c7d8f3f","NT5.1/NT5.2 IPL"
15 | "IPL","ff1aae04bac3e29f062a7fa17320d7d26363256a69f96840718d45301da71291","NT6.0 IPL"
16 | "IPL","462afe2322bad3d1c2747d7437d5f6c157e00ca37e5d38ebedd25346b3b488ce","NT6.1 IPL"
17 | "IPL","c09d496a1f24086c333468d58256d5db9c73fee945fca74603bdab05f19a6d57","NT6.2+ IPL"
18 |
--------------------------------------------------------------------------------
/tests/test_ipl.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2
2 | # -*- coding:utf-8 -*-
3 |
4 | from __future__ import unicode_literals
5 | from bootcode_parser import InitialProgramLoader, InvalidIPLError
6 | import os
7 | import pytest
8 |
9 |
10 | def test_ipl_nt5_with_whitelist(whitelist):
11 | sampleName = os.path.join('test_data', 'ipl_5.bin')
12 |
13 | dParsed = {}
14 | dExpected = {
15 | 'record_type': 'IPL',
16 | 'sample_name': sampleName,
17 | 'partition_table': [],
18 | 'disk_signature': None,
19 | 'oem_id': None,
20 | 'code_SHA256': '525788a688cfbe9e416122f0bc3cfb32ce9699fd12356b6ccaa173444c7d8f3f'.decode('hex'),
21 | 'suspicious_behaviour': [],
22 | 'known_code_signature': ['NT5.1/NT5.2 IPL'],
23 | }
24 | with open(sampleName, 'rb') as f_ipl:
25 | objIPL = InitialProgramLoader(f_ipl, os.path.getsize(f_ipl.name), whitelist=whitelist)
26 | dParsed = objIPL.getDictRecord()
27 | dParsed.pop('record_raw')
28 | assert dParsed == dExpected
29 |
30 |
31 | def test_ipl_nt60_with_whitelist(whitelist):
32 | sampleName = os.path.join('test_data', 'ipl_60.bin')
33 |
34 | dParsed = {}
35 | dExpected = {
36 | 'record_type': 'IPL',
37 | 'sample_name': sampleName,
38 | 'partition_table': [],
39 | 'disk_signature': None,
40 | 'oem_id': None,
41 | 'code_SHA256': 'ff1aae04bac3e29f062a7fa17320d7d26363256a69f96840718d45301da71291'.decode('hex'),
42 | 'suspicious_behaviour': [],
43 | 'known_code_signature': ['NT6.0 IPL'],
44 | }
45 | with open(sampleName, 'rb') as f_ipl:
46 | objIPL = InitialProgramLoader(f_ipl, os.path.getsize(f_ipl.name), whitelist=whitelist)
47 | dParsed = objIPL.getDictRecord()
48 | dParsed.pop('record_raw')
49 | assert dParsed == dExpected
50 |
51 |
52 | def test_ipl_nt61_with_whitelist(whitelist):
53 | sampleName = os.path.join('test_data', 'ipl_61.bin')
54 |
55 | dParsed = {}
56 | dExpected = {
57 | 'record_type': 'IPL',
58 | 'sample_name': sampleName,
59 | 'partition_table': [],
60 | 'disk_signature': None,
61 | 'oem_id': None,
62 | 'code_SHA256': '462afe2322bad3d1c2747d7437d5f6c157e00ca37e5d38ebedd25346b3b488ce'.decode('hex'),
63 | 'suspicious_behaviour': [],
64 | 'known_code_signature': ['NT6.1 IPL'],
65 | }
66 | with open(sampleName, 'rb') as f_ipl:
67 | objIPL = InitialProgramLoader(f_ipl, os.path.getsize(f_ipl.name), whitelist=whitelist)
68 | dParsed = objIPL.getDictRecord()
69 | dParsed.pop('record_raw')
70 | assert dParsed == dExpected
71 |
72 |
73 | def test_ipl_nt62_with_whitelist(whitelist):
74 | sampleName = os.path.join('test_data', 'ipl_62.bin')
75 |
76 | dParsed = {}
77 | dExpected = {
78 | 'record_type': 'IPL',
79 | 'sample_name': sampleName,
80 | 'partition_table': [],
81 | 'disk_signature': None,
82 | 'oem_id': None,
83 | 'code_SHA256': 'c09d496a1f24086c333468d58256d5db9c73fee945fca74603bdab05f19a6d57'.decode('hex'),
84 | 'suspicious_behaviour': [],
85 | 'known_code_signature': ['NT6.2+ IPL'],
86 | }
87 | with open(sampleName, 'rb') as f_ipl:
88 | objIPL = InitialProgramLoader(f_ipl, os.path.getsize(f_ipl.name), whitelist=whitelist)
89 | dParsed = objIPL.getDictRecord()
90 | dParsed.pop('record_raw')
91 | assert dParsed == dExpected
92 |
93 |
94 | def test_ipl_empty_with_whitelist(whitelist):
95 | sampleName = os.path.join('test_data', 'ipl_empty.bin')
96 |
97 | with pytest.raises(InvalidIPLError) as e:
98 | with open(sampleName, 'rb') as f_ipl:
99 | objIPL = InitialProgramLoader(f_ipl, os.path.getsize(f_ipl.name), whitelist=whitelist)
100 | assert 'Invalid IPL structure: ' in str(e.value)
101 |
102 |
103 | def test_ipl_rovnix_with_whitelist(whitelist):
104 | sampleName = os.path.join('test_data', 'ipl_rovnix.bin')
105 |
106 | dParsed = {}
107 | dExpected = {
108 | 'record_type': 'IPL',
109 | 'sample_name': sampleName,
110 | 'partition_table': [],
111 | 'disk_signature': None,
112 | 'oem_id': None,
113 | 'code_SHA256': '51605476b580fd6e38b22cc0a2a2aad18102806117c45b70c73f39a6a93b7aed'.decode('hex'),
114 | 'suspicious_behaviour': ['Unknown Interrupt : 0x70'],
115 | 'known_code_signature': [],
116 | }
117 | with open(sampleName, 'rb') as f_ipl:
118 | objIPL = InitialProgramLoader(f_ipl, os.path.getsize(f_ipl.name), whitelist=whitelist)
119 | dParsed = objIPL.getDictRecord()
120 | dParsed.pop('record_raw')
121 | assert dParsed == dExpected
122 |
123 |
--------------------------------------------------------------------------------
/tests/test_img.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2
2 | # -*- coding:utf-8 -*-
3 |
4 | from __future__ import unicode_literals
5 | from bootcode_parser import *
6 | import bootcode_parser
7 | import pytest
8 | import pytest_catchlog
9 | import os
10 | import logging
11 |
12 |
13 | def test_img_nt5_with_whitelist(caplog, whitelist):
14 | sampleName = os.path.join('test_data', 'disk_5.img')
15 | caplog.set_level(logging.INFO)
16 | with open(sampleName, 'rb') as f_img:
17 | parseImageFile(f_img, sectorSize=512, whitelist=whitelist)
18 | assert caplog.record_tuples == [
19 | (bootcode_parser.__file__, logging.INFO, "Known signatures found: ['NT5.1/NT5.2 MBR']"),
20 | (bootcode_parser.__file__, logging.INFO, "Known signatures found: ['NT5.1/NT5.2 VBR']"),
21 | (bootcode_parser.__file__, logging.INFO, "Known signatures found: ['NT5.1/NT5.2 IPL']")
22 | ]
23 |
24 |
25 |
26 | def test_img_nt60_with_whitelist(caplog, whitelist):
27 | sampleName = os.path.join('test_data', 'disk_60.img')
28 | caplog.set_level(logging.INFO)
29 | with open(sampleName, 'rb') as f_img:
30 | parseImageFile(f_img, sectorSize=512, whitelist=whitelist)
31 | assert caplog.record_tuples == [
32 | (bootcode_parser.__file__, logging.INFO, "Known signatures found: ['NT6.0 MBR']"),
33 | (bootcode_parser.__file__, logging.INFO, "Known signatures found: ['NT6.0 VBR']"),
34 | (bootcode_parser.__file__, logging.INFO, "Known signatures found: ['NT6.0 IPL']")
35 | ]
36 |
37 |
38 | def test_img_nt61_with_whitelist(caplog, whitelist):
39 | sampleName = os.path.join('test_data', 'disk_61.img')
40 | caplog.set_level(logging.INFO)
41 | with open(sampleName, 'rb') as f_img:
42 | parseImageFile(f_img, sectorSize=512, whitelist=whitelist)
43 | assert caplog.record_tuples == [
44 | (bootcode_parser.__file__, logging.INFO, "Known signatures found: ['NT6.1+ MBR']"),
45 | (bootcode_parser.__file__, logging.INFO, "Known signatures found: ['NT6.1 VBR']"),
46 | (bootcode_parser.__file__, logging.INFO, "Known signatures found: ['NT6.1 IPL']")
47 | ]
48 |
49 |
50 | def test_img_nt62_with_whitelist(caplog, whitelist):
51 | sampleName = os.path.join('test_data', 'disk_62.img')
52 | caplog.set_level(logging.INFO)
53 | with open(sampleName, 'rb') as f_img:
54 | parseImageFile(f_img, sectorSize=512, whitelist=whitelist)
55 | assert caplog.record_tuples == [
56 | (bootcode_parser.__file__, logging.INFO, "Known signatures found: ['NT6.1+ MBR']"),
57 | (bootcode_parser.__file__, logging.INFO, "Known signatures found: ['NT6.2+ VBR']"),
58 | (bootcode_parser.__file__, logging.INFO, "Known signatures found: ['NT6.2+ IPL']")
59 | ]
60 |
61 |
62 | def test_img_gapz_with_whitelist(caplog, whitelist):
63 | sampleName = os.path.join('test_data', 'disk_gapz.img')
64 | caplog.set_level(logging.INFO)
65 | with open(sampleName, 'rb') as f_img:
66 | parseImageFile(f_img, sectorSize=512, whitelist=whitelist)
67 | assert caplog.record_tuples[:-1] == [
68 | (bootcode_parser.__file__, logging.INFO, "Known signatures found: ['NT6.1+ MBR']"),
69 | (bootcode_parser.__file__, logging.INFO, "Known signatures found: ['NT6.1 VBR']"),
70 | (bootcode_parser.__file__, logging.WARNING, "Suspicious behaviours were detected: [u'Suspicious HiddenSectors "
71 | "value: 209714414 (107373779968 bytes)']"),
72 | (bootcode_parser.__file__, logging.WARNING, "VBR of the active partition located at sector 2048 (offset "
73 | "1048576) is suspicious (see previous warning). This could mean "
74 | "that the partition table in the MBR or the BPB in the VBR has "
75 | "been tampered with !"),
76 | (bootcode_parser.__file__, logging.WARNING, "HiddenSectors value in BiosParameterBlock is different than actual"
77 | " offset in partition table ! HiddenSectors=209714414, partition"
78 | " table offset=2048"),
79 | ]
80 | name, level, msg = caplog.record_tuples[-1]
81 | assert (name, level) == (bootcode_parser.__file__, logging.ERROR)
82 | assert msg.startswith("Invalid IPL structure:")
83 |
84 |
85 | def test_img_rovnix_with_whitelist(caplog, whitelist):
86 | sampleName = os.path.join('test_data', 'disk_rovnix.img')
87 | caplog.set_level(logging.INFO)
88 | with open(sampleName, 'rb') as f_img:
89 | parseImageFile(f_img, sectorSize=512, whitelist=whitelist)
90 | assert caplog.record_tuples == [
91 | (bootcode_parser.__file__, logging.INFO, "Known signatures found: ['NT5.1/NT5.2 MBR']"),
92 | (bootcode_parser.__file__, logging.INFO, "Known signatures found: ['NT5.1/NT5.2 VBR']"),
93 | (bootcode_parser.__file__, logging.WARNING, "No known code signature were found, this is highly suspicious."),
94 | (bootcode_parser.__file__, logging.WARNING, "Suspicious behaviours were detected: [u'Unknown Interrupt : 0x70']")
95 | ]
96 |
97 |
98 | def test_img_tc_with_whitelist(caplog, whitelist):
99 | sampleName = os.path.join('test_data', 'disk_tc.img')
100 | caplog.set_level(logging.INFO)
101 | with open(sampleName, 'rb') as f_img:
102 | parseImageFile(f_img, sectorSize=512, whitelist=whitelist)
103 | assert caplog.record_tuples[0] == (bootcode_parser.__file__, logging.INFO, "Known signatures found: ['TrueCrypt MBR']")
104 | assert caplog.records[1].levelno == logging.ERROR
105 | assert caplog.records[1].message.startswith("Invalid VBR structure:")
106 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | :warning: **This project is in maintenance mode: issues and PRs will still be addressed, but no further development will be made.** :warning:
2 |
3 | bootcode_parser
4 | =================
5 | ```bootcode_parser.py``` is a Python script designed to perform a quick offline analysis of the boot records used by BIOS based systems (UEFI is *not* supported).
6 |
7 | It is intended to help the analyst triaging individual boot record dumps or whole disk images.
8 | The latter is preferred since it allows the script to perform additional checks that would not be possible on individual dumps alone.
9 |
10 | This script only detects anomalies that have to be manually investigated by an analyst.
11 | Because it works with a whitelist mechanism it will be able to detect a wide range of malicious codes,
12 | but it will also detect legitimate (encryption software, etc...) or benign modification of the boot records.
13 |
14 | This topic has been presented during a talk at the French conference CORI&IN 2017.
15 |
16 | How does it work ?
17 | ==================
18 | The script is based on the fact that boot records contain code sections that do not vary much from a machine to another.
19 | The differences can be identified and understood by performing a static analysis.
20 |
21 | This script merely implements the results of these analyses and tries to narrow down these "invariant" codes and hash them.
22 | The hash is then compared to a whitelist of known good signatures that has to be built by the analyst (an example is given, but it is advised to build its own).
23 | If no record is found in the whitelist then the boot record *must* be investigated by the analyst.
24 | In this case, static analysis is the only way to decide whether the boot record has been infected or not.
25 |
26 | How to interpret the results ?
27 | ==============================
28 | [INFO] messages mean the boot record was found in the whitelist
29 |
30 | [WARNING] messages mean the boot record or the boot sequence (when providing a whole disk image) needs to be investigated
31 |
32 | [ERROR] messages mean the script could not finish its operation, generally because the sample's structure could not be validated
33 |
34 | [DEBUG] messages (displayed with ```--logLevel DEBUG```) can be used to show internal details of the process of verification
35 | and display the newly calculated hash of an unknown boot record
36 |
37 | Dependencies
38 | ============
39 | * python2 >= 2.7
40 | * python-construct == 2.8
41 | * python-capstone >= 3.0.4
42 |
43 | Usage
44 | =====
45 | ```
46 | usage: bootcode_parser.py [-h] --type {VBR,MBR,IPL,IMG} --input INPUT
47 | [INPUT ...] [--offset OFFSET]
48 | [--sector-size SECTOR_SIZE] [--whitelist WHITELIST]
49 | [--logLevel {DEBUG,INFO,WARNING,ERROR,CRITICAL}]
50 |
51 | Check boot records for known good signatures
52 |
53 | optional arguments:
54 | -h, --help show this help message and exit
55 | --type {VBR,MBR,IPL,IMG}
56 | Type of boot record: MBR, VBR or IPL. Or whole disk image.
57 | --input INPUT [INPUT ...]
58 | Input file(s) to check
59 | --offset OFFSET Offset in bytes at which the boot record was dumped. Required only for VBR. Without it, some heuristics to detect malicious VBR will not work.
60 | --sector-size SECTOR_SIZE
61 | Disk sector size in bytes. Only applies for disk image input. Defaults to 512.
62 | --whitelist WHITELIST
63 | CSV file containing whitelisted boot record signatures. Without it, the boot record will always be flagged as suspicious. Defaults to ./data/bootrecord_whitelist.csv
64 | --logLevel {DEBUG,INFO,WARNING,ERROR,CRITICAL}
65 | Show debug messages according to the level provided.
66 | ```
67 |
68 | Examples
69 | ========
70 | Usage with individual boot records
71 | ----------------------------------
72 |
73 | * MBR from fresh installs of Windows XP, Vista and 7, empty MBR (completely empty or just the code section), protective MBR and TrueCrypt MBR
74 |
75 | ```shell
76 | python bootcode_parser.py --type MBR --input test_data/mbr_*
77 | ```
78 | ```
79 | INFO - [test_data/mbr_5.bin] [MBR] Known signatures found: ['NT5.1/5.2 MBR']
80 | INFO - [test_data/mbr_60.bin] [MBR] Known signatures found: ['NT6.0 MBR']
81 | INFO - [test_data/mbr_61.bin] [MBR] Known signatures found: ['NT6.1+ MBR']
82 | ERROR - [test_data/mbr_empty.bin] [MBR] Invalid MBR structure: expected 'U\xaa', found '\x00\x00'
83 | 00000000: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
84 | [...]
85 | 000001F0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
86 | WARNING - [test_data/mbr_empty_code.bin] [MBR] No known code signature were found, this is highly suspicious.
87 | WARNING - [test_data/mbr_empty_code.bin] [MBR] Suspicious behaviours were detected: [u'Code section is null']
88 | INFO - [test_data/mbr_protect_uefi.bin] [MBR] Known signatures found: [u'Protective MBR', u'UEFI (no legacy boot code)']
89 | INFO - [test_data/mbr_tc.bin] [MBR] Known signatures found: ['TrueCrypt MBR']
90 | ```
91 |
92 | * VBR from fresh installs of Windows Vista, 7 and 8
93 |
94 | ```shell
95 | python bootcode_parser.py --type VBR --offset $((2048*512)) --input test_data/vbr_*_off_$((2048*512)).bin
96 | ```
97 | ```
98 | INFO - [test_data/vbr_60_off_1048576.bin] [VBR] Known signatures found: ['NT6.0 VBR']
99 | INFO - [test_data/vbr_61_off_1048576.bin] [VBR] Known signatures found: ['NT6.1 VBR']
100 | INFO - [test_data/vbr_62_off_1048576.bin] [VBR] Known signatures found: ['NT6.2+ VBR']
101 | ```
102 |
103 | * VBR from a fresh install of Windows XP
104 |
105 | ```shell
106 | python bootcode_parser.py --type VBR --offset $((63*512)) --input test_data/vbr_*_off_$((63*512)).bin
107 | ```
108 | ```
109 | INFO - [test_data/vbr_5_off_32256.bin] [VBR] Known signatures found: ['NT5.1/NT5.2 VBR']
110 | ```
111 |
112 | * IPL from fresh installs of Windows XP, Vista, 7 and 8
113 |
114 | ```shell
115 | python bootcode_parser.py --type IPL --input test_data/ipl_*
116 | ```
117 | ```
118 | INFO - [test_data/ipl_5.bin] [IPL] Known signatures found: ['NT5.1/NT5.2 IPL']
119 | INFO - [test_data/ipl_60.bin] [IPL] Known signatures found: ['NT6.0 IPL']
120 | INFO - [test_data/ipl_61.bin] [IPL] Known signatures found: ['NT6.1 IPL']
121 | INFO - [test_data/ipl_62.bin] [IPL] Known signatures found: ['NT6.2+ IPL']
122 | ```
123 |
124 | Usage with whole disk images
125 | ----------------------------
126 | * Fresh install of Windows 7
127 |
128 | ```shell
129 | python bootcode_parser.py --input clean_win7.dd --type IMG
130 | ```
131 | ```
132 | INFO - [/dev/storage/VM-Win7] Known signatures found: ['NT6.1+ MBR']
133 | INFO - [/dev/storage/VM-Win7] Known signatures found: ['NT6.1 VBR']
134 | INFO - [/dev/storage/VM-Win7] Known signatures found: ['NT6.1 IPL']
135 | ```
136 |
137 | * Windows XP infected with Gapz
138 |
139 | ```shell
140 | python bootcode_parser.py --input infected_with_gapz.dd --type IMG
141 | ```
142 | ```
143 | INFO - [infected_with_gapz.dd] [MBR] Known signatures found: ['NT5.1/5.2 MBR']
144 | INFO - [infected_with_gapz.dd] [VBR] Known signatures found: ['NT5.1/NT5.2 VBR']
145 | WARNING - [infected_with_gapz.dd] [VBR] Suspicious behaviours were detected: [u'Suspicious HiddenSectors value: 41942254 (21474434048 bytes)']
146 | WARNING - [infected_with_gapz.dd] [VBR] VBR of the active partition located at sector 63 (offset 32256) is suspicious (see previous warning). This could mean that the partition table in the MBR or the BPB in the VBR has been tampered with !
147 | WARNING - [infected_with_gapz.dd] [IMG] HiddenSectors value in BiosParameterBlock is different than actual offset in partition table ! HiddenSectors=41942254, partition table offset=63
148 | ERROR - [infected_with_gapz.dd] [IMG] Invalid IPL structure: expected 74016, found 7678
149 | 00000000: 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 |................|
150 | [...]
151 | 000001F0: 90 90 90 90 90 90 90 90 90 90 90 90 eb 49 55 aa |.............IU.|
152 | ```
153 |
154 | * Windows XP infected with Rovnix
155 |
156 | ```shell
157 | python bootcode_parser.py --input infected_with_rovnix.dd --type IMG
158 | ```
159 | ```
160 | INFO - [infected_with_rovnix.dd] [MBR] Known signatures found: ['NT5.1/5.2 MBR']
161 | INFO - [infected_with_rovnix.dd] [VBR] Known signatures found: ['NT5.1/NT5.2 VBR']
162 | WARNING - [infected_with_rovnix.dd] [IPL] No known code signature were found, this is highly suspicious.
163 | WARNING - [infected_with_rovnix.dd] [IPL] Suspicious behaviours were detected: [u'Unknown Interrupt : 0x70']
164 | ```
165 |
--------------------------------------------------------------------------------
/tests/test_vbr.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2
2 | # -*- coding:utf-8 -*-
3 |
4 | from __future__ import unicode_literals
5 | from bootcode_parser import VolumeBootRecord, InvalidVBRError
6 | import os
7 | import pytest
8 |
9 |
10 | def test_vbr_nt5_with_whitelist(whitelist):
11 | sampleName = os.path.join('test_data', 'vbr_5_off_32256.bin')
12 |
13 | dParsed = {}
14 | dExpected = {
15 | 'record_type': 'VBR',
16 | 'sample_name': sampleName,
17 | 'partition_table': [],
18 | 'disk_signature': None,
19 | 'oem_id': 'NTFS ',
20 | 'code_SHA256': '5cb5aa385e0ada266690a2821e3a36ad372720d2ff47c0b1cd9d6ebcab25bf4e'.decode('hex'),
21 | 'record_raw': 'eb52904e5446532020202000020800000000000000f800003f00ff003f0000000000000080008000d7845f0400000000'
22 | '00000c00000000004df8450000000000f6000000010000000e11dfc051dfc0bc00000000fa33c08ed0bc007cfbb8c007'
23 | '8ed8e81600b8000d8ec033dbc6060e0010e8530068000d686a02cb8a162400b408cd137305b9ffff8af1660fb6c64066'
24 | '0fb6d180e23ff7e286cdc0ed0641660fb7c966f7e166a32000c3b441bbaa558a162400cd13720f81fb55aa7509f6c101'
25 | '7404fe061400c366601e0666a110006603061c00663b0620000f823a001e666a0066500653666810000100803e140000'
26 | '0f850c00e8b3ff803e1400000f846100b4428a162400161f8bf4cd1366585b07665866581feb2d6633d2660fb70e1800'
27 | '66f7f1fec28aca668bd066c1ea10f7361a0086d68a1624008ae8c0e4060accb80102cd130f8219008cc00520008ec066'
28 | 'ff061000ff0e0e000f856fff071f6661c3a0f801e80900a0fb01e80300fbebfeb4018bf0ac3c007409b40ebb0700cd10'
29 | 'ebf2c30d0a4572722e206c65637475726520646973717565000d0a4e544c4452206d616e717565000d0a4e544c445220'
30 | '65737420636f6d707265737382000d0a456e7472657a204374726c2b416c742b537570707220706f757220726564826d'
31 | '61727265720d0a000d0a00000000000000000000000000008399a8be000055aa'.decode('hex'),
32 | 'suspicious_behaviour': [],
33 | 'known_code_signature': ['NT5.1/NT5.2 VBR'],
34 | }
35 | with open(sampleName, 'rb') as f_mbr:
36 | objVBR = VolumeBootRecord(f_mbr, os.path.getsize(f_mbr.name), offset=32256, whitelist=whitelist)
37 | dParsed = objVBR.getDictRecord()
38 | assert dParsed == dExpected
39 |
40 |
41 | def test_vbr_nt60_with_whitelist(whitelist):
42 | sampleName = os.path.join('test_data', 'vbr_60_off_1048576.bin')
43 |
44 | dParsed = {}
45 | dExpected = {
46 | 'record_type': 'VBR',
47 | 'sample_name': sampleName,
48 | 'partition_table': [],
49 | 'disk_signature': None,
50 | 'oem_id': 'NTFS ',
51 | 'code_SHA256': 'a1932aaba7d6d3adb1637e2ee0c8355706842ba825ea811728165420c518c0b1'.decode('hex'),
52 | 'record_raw': 'eb52904e5446532020202000020800000000000000f800003f00ff00000800000000000080008000ffefdf0100000000'
53 | '00000c0000000000fffe1d0000000000f600000001000000acbf151cf6151c2800000000fa33c08ed0bc007cfb68c007'
54 | '1f1e686600cb88160e0066813e03004e5446537515b441bbaa55cd13720c81fb55aa7506f7c101007503e9d2001e83ec'
55 | '18681a00b4488a160e008bf4161fcd139f83c4189e581f72e13b060b0075dba30f00c12e0f00041e5a33dbb900202bc8'
56 | '66ff06110003160f008ec2ff061600e840002bc877efb800bbcd1a6623c0752d6681fb54435041752481f90201721e16'
57 | '6807bb1668700e1668090066536653665516161668b80166610e07cd1ae96a01909066601e0666a111006603061c001e'
58 | '66680000000066500653680100681000b4428a160e00161f8bf4cd1366595b5a665966591f0f82160066ff0611000316'
59 | '0f008ec2ff0e160075bc071f6661c3a0f801e80800a0fb01e80200ebfeb4018bf0ac3c007409b40ebb0700cd10ebf2c3'
60 | '0d0a41206469736b2072656164206572726f72206f63637572726564000d0a424f4f544d4752206973206d697373696e'
61 | '67000d0a424f4f544d475220697320636f6d70726573736564000d0a5072657373204374726c2b416c742b44656c2074'
62 | '6f20726573746172740d0a00000000000000000000000000809db2ca000055aa'.decode('hex'),
63 | 'suspicious_behaviour': [],
64 | 'known_code_signature': ['NT6.0 VBR'],
65 | }
66 | with open(sampleName, 'rb') as f_mbr:
67 | objVBR = VolumeBootRecord(f_mbr, os.path.getsize(f_mbr.name), offset=1048576, whitelist=whitelist)
68 | dParsed = objVBR.getDictRecord()
69 | assert dParsed == dExpected
70 |
71 |
72 | def test_vbr_nt61_with_whitelist(whitelist):
73 | sampleName = os.path.join('test_data', 'vbr_61_off_1048576.bin')
74 |
75 | dParsed = {}
76 | dExpected = {
77 | 'record_type': 'VBR',
78 | 'sample_name': sampleName,
79 | 'partition_table': [],
80 | 'disk_signature': None,
81 | 'oem_id': 'NTFS ',
82 | 'code_SHA256': '96d38c1be37b9124fb71d1d0f5c52969f0074687fe17aef0e1bafc54428674f6'.decode('hex'),
83 | 'record_raw': 'eb52904e5446532020202000020800000000000000f800003f00ff00000800000000000080008000ff1f030000000000'
84 | '55210000000000000200000000000000f6000000010000003231dc285edc286400000000fa33c08ed0bc007cfb68c007'
85 | '1f1e686600cb88160e0066813e03004e5446537515b441bbaa55cd13720c81fb55aa7506f7c101007503e9dd001e83ec'
86 | '18681a00b4488a160e008bf4161fcd139f83c4189e581f72e13b060b0075dba30f00c12e0f00041e5a33dbb900202bc8'
87 | '66ff06110003160f008ec2ff061600e84b002bc877efb800bbcd1a6623c0752d6681fb54435041752481f90201721e16'
88 | '6807bb1668700e1668090066536653665516161668b80166610e07cd1a33c0bf2810b9d80ffcf3aae95f01909066601e'
89 | '0666a111006603061c001e66680000000066500653680100681000b4428a160e00161f8bf4cd1366595b5a665966591f'
90 | '0f82160066ff06110003160f008ec2ff0e160075bc071f6661c3a0f801e80900a0fb01e80300f4ebfdb4018bf0ac3c00'
91 | '7409b40ebb0700cd10ebf2c30d0a41206469736b2072656164206572726f72206f63637572726564000d0a424f4f544d'
92 | '4752206973206d697373696e67000d0a424f4f544d475220697320636f6d70726573736564000d0a5072657373204374'
93 | '726c2b416c742b44656c20746f20726573746172740d0a008ca9bed6000055aa'.decode('hex'),
94 | 'suspicious_behaviour': [],
95 | 'known_code_signature': ['NT6.1 VBR'],
96 | }
97 | with open(sampleName, 'rb') as f_mbr:
98 | objVBR = VolumeBootRecord(f_mbr, os.path.getsize(f_mbr.name), offset=1048576, whitelist=whitelist)
99 | dParsed = objVBR.getDictRecord()
100 | assert dParsed == dExpected
101 |
102 |
103 | def test_vbr_nt61_bitlocker_with_whitelist(whitelist):
104 | sampleName = os.path.join('test_data', 'vbr_61_bitlocker_off_525336576.bin')
105 |
106 | dParsed = {}
107 | dExpected = {
108 | 'record_type': 'VBR',
109 | 'sample_name': sampleName,
110 | 'partition_table': [],
111 | 'disk_signature': None,
112 | 'oem_id': '-FVE-FS-',
113 | 'code_SHA256': '47138cbe995a20483209270ef55693c8c8e85ca870f28789229ce421aded92b4'.decode('hex'),
114 | 'record_raw': 'eb58902d4656452d46532d00020800000000000000f800003f00ff0000a80f0000000000e01f00000000000000000000'
115 | '01000600000000000000000000000000800029000000004e4f204e414d4520202020464154333220202033c98ed1bcf4'
116 | '7b8ec18ed9bd007ca0fb7db47d8bf0ac9840740c48740eb40ebb0700cd10ebefa0fd7debe6cd16cd1900000000000000'
117 | '000000000000000000000000000000003bd66749292ed84a8399f6a339e3d0010060cb0f000000000000504900000000'
118 | '008024bc0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
119 | '000000000000000000000000000000000d0a52656d6f7665206469736b73206f72206f74686572206d656469612eff0d'
120 | '0a4469736b206572726f72ff0d0a507265737320616e79206b657920746f20726573746172740d0a0000000000000000'
121 | '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
122 | '000000000000000000000000000000000000000000000000787878787878787878787878787878787878787878787878'
123 | '787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878'
124 | '7878787878787878ffffffffffffffffffffffffffffffffffffff001f2c55aa'.decode('hex'),
125 | 'suspicious_behaviour': [],
126 | 'known_code_signature': ['NT6.1+ Bitlocker VBR'],
127 | }
128 | with open(sampleName, 'rb') as f_mbr:
129 | objVBR = VolumeBootRecord(f_mbr, os.path.getsize(f_mbr.name), offset=525336576, whitelist=whitelist)
130 | dParsed = objVBR.getDictRecord()
131 | assert dParsed == dExpected
132 |
133 |
134 | def test_vbr_nt62_with_whitelist(whitelist):
135 | sampleName = os.path.join('test_data', 'vbr_62_off_1048576.bin')
136 |
137 | dParsed = {}
138 | dExpected = {
139 | 'record_type': 'VBR',
140 | 'sample_name': sampleName,
141 | 'partition_table': [],
142 | 'disk_signature': None,
143 | 'oem_id': 'NTFS ',
144 | 'code_SHA256': '51643dcce7e93d795b08e1f19e38374ae4deaf3b1217527561a44aa9913ded23'.decode('hex'),
145 | 'record_raw': 'eb52904e5446532020202000020800000000000000f800003f00ff00000800000000000080008000ff0f0e0000000000'
146 | '00960000000000000200000000000000f600000001000000f8c2981acf981a4000000000fa33c08ed0bc007cfb68c007'
147 | '1f1e686600cb88160e0066813e03004e5446537515b441bbaa55cd13720c81fb55aa7506f7c101007503e9dd001e83ec'
148 | '18681a00b4488a160e008bf4161fcd139f83c4189e581f72e13b060b0075dba30f00c12e0f00041e5a33dbb900202bc8'
149 | '66ff06110003160f008ec2ff061600e84b002bc877efb800bbcd1a6623c0752d6681fb54435041752481f90201721e16'
150 | '6807bb166852111668090066536653665516161668b80166610e07cd1a33c0bf0a13b9f60cfcf3aae9fe01909066601e'
151 | '0666a111006603061c001e66680000000066500653680100681000b4428a160e00161f8bf4cd1366595b5a665966591f'
152 | '0f82160066ff06110003160f008ec2ff0e160075bc071f6661c3a1f601e80900a1fa01e80300f4ebfd8bf0ac3c007409'
153 | 'b40ebb0700cd10ebf2c30d0a41206469736b2072656164206572726f72206f63637572726564000d0a424f4f544d4752'
154 | '20697320636f6d70726573736564000d0a5072657373204374726c2b416c742b44656c20746f20726573746172740d0a'
155 | '000000000000000000000000000000000000000000008a01a701bf01000055aa'.decode('hex'),
156 | 'suspicious_behaviour': [],
157 | 'known_code_signature': ['NT6.2+ VBR'],
158 | }
159 | with open(sampleName, 'rb') as f_mbr:
160 | objVBR = VolumeBootRecord(f_mbr, os.path.getsize(f_mbr.name), offset=1048576, whitelist=whitelist)
161 | dParsed = objVBR.getDictRecord()
162 | assert dParsed == dExpected
163 |
164 |
165 | def test_vbr_empty_with_whitelist(whitelist):
166 | sampleName = os.path.join('test_data', 'mbr_empty.bin')
167 |
168 | with pytest.raises(InvalidVBRError) as e:
169 | with open(sampleName, 'rb') as f_vbr:
170 | objMBR = VolumeBootRecord(f_vbr, os.path.getsize(f_vbr.name), offset=1048576, whitelist=whitelist)
171 | assert 'Invalid VBR structure: ' in str(e.value)
172 |
173 |
174 | def test_vbr_gapz_with_whitelist(whitelist):
175 | sampleName = os.path.join('test_data', 'vbr_gapz_off_1048576.bin')
176 |
177 | dParsed = {}
178 | dExpected = {
179 | 'record_type': 'VBR',
180 | 'sample_name': sampleName,
181 | 'partition_table': [],
182 | 'disk_signature': None,
183 | 'oem_id': 'NTFS ',
184 | 'code_SHA256': '96d38c1be37b9124fb71d1d0f5c52969f0074687fe17aef0e1bafc54428674f6'.decode('hex'),
185 | 'record_raw': 'eb52904e5446532020202000020800000000000000f800003f00ff00eefc7f0c0000000080008000ff1f030000000000'
186 | '55210000000000000200000000000000f600000001000000b83d71846071849c00000000fa33c08ed0bc007cfb68c007'
187 | '1f1e686600cb88160e0066813e03004e5446537515b441bbaa55cd13720c81fb55aa7506f7c101007503e9dd001e83ec'
188 | '18681a00b4488a160e008bf4161fcd139f83c4189e581f72e13b060b0075dba30f00c12e0f00041e5a33dbb900202bc8'
189 | '66ff06110003160f008ec2ff061600e84b002bc877efb800bbcd1a6623c0752d6681fb54435041752481f90201721e16'
190 | '6807bb1668700e1668090066536653665516161668b80166610e07cd1a33c0bf2810b9d80ffcf3aae95f01909066601e'
191 | '0666a111006603061c001e66680000000066500653680100681000b4428a160e00161f8bf4cd1366595b5a665966591f'
192 | '0f82160066ff06110003160f008ec2ff0e160075bc071f6661c3a0f801e80900a0fb01e80300f4ebfdb4018bf0ac3c00'
193 | '7409b40ebb0700cd10ebf2c30d0a41206469736b2072656164206572726f72206f63637572726564000d0a424f4f544d'
194 | '4752206973206d697373696e67000d0a424f4f544d475220697320636f6d70726573736564000d0a5072657373204374'
195 | '726c2b416c742b44656c20746f20726573746172740d0a008ca9bed6000055aa'.decode('hex'),
196 | 'suspicious_behaviour': ['Suspicious HiddenSectors value: 209714414 (107373779968 bytes)'],
197 | 'known_code_signature': ['NT6.1 VBR'],
198 | }
199 | with open(sampleName, 'rb') as f_mbr:
200 | objVBR = VolumeBootRecord(f_mbr, os.path.getsize(f_mbr.name), offset=32256, whitelist=whitelist)
201 | dParsed = objVBR.getDictRecord()
202 | assert dParsed == dExpected
203 |
204 |
--------------------------------------------------------------------------------
/tests/test_mbr.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2
2 | # -*- coding:utf-8 -*-
3 |
4 | from __future__ import unicode_literals
5 | from bootcode_parser import MasterBootRecord, InvalidMBRError
6 | import os
7 | import pytest
8 |
9 |
10 | def test_mbr_nt5_with_whitelist(whitelist):
11 | sampleName = os.path.join('test_data', 'mbr_5.bin')
12 |
13 | dParsed = {}
14 | dExpected = {
15 | 'record_type': 'MBR',
16 | 'sample_name': sampleName,
17 | 'partition_table': [{'Number': 1, 'Attributes': 'Active', 'Type': 'NTFS',
18 | 'Start sector': 63, 'Size in sectors': 73368792}],
19 | 'disk_signature': '059c059c'.decode('hex'),
20 | 'oem_id': None,
21 | 'code_SHA256': 'b5ed343494f0326a08aa6abf7cc9aa4d96207532cf0d2b39453c6eb7bede19e3'.decode('hex'),
22 | 'record_raw': '33c08ed0bc007cfb5007501ffcbe1b7cbf1b065057b9e501f3a4cbbdbe07b104386e007c09751383c510e2f4cd188bf5'
23 | '83c610497419382c74f6a0b507b4078bf0ac3c0074fcbb0700b40ecd10ebf2884e10e84600732afe4610807e040b740b'
24 | '807e040c7405a0b60775d2804602068346080683560a00e821007305a0b607ebbc813efe7d55aa740b807e100074c8a0'
25 | 'b707eba98bfc1e578bf5cbbf05008a5600b408cd1372238ac1243f988ade8afc43f7e38bd186d6b106d2ee42f7e23956'
26 | '0a77237205394608731cb80102bb007c8b4e028b5600cd1373514f744e32e48a5600cd13ebe48a560060bbaa55b441cd'
27 | '13723681fb55aa7530f6c101742b61606a006a00ff760aff76086a0068007c6a016a10b4428bf4cd136161730e4f740b'
28 | '32e48a5600cd13ebd661f9c35461626c6520646520706172746974696f6e206e6f6e2076616c69646500457272657572'
29 | '206c6f7273206475206368617267656d656e7420647520737973748a6d652064276578706c6f69746174690053797374'
30 | '8a6d652064276578706c6f69746174696f6e20616273656e740000000000000000000000000000000000000000000000'
31 | '00000000002c4a7c059c059c00008001010007feffff3f000000d8845f04000000000000000000000000000000000000'
32 | '00000000000000000000000000000000000000000000000000000000000055aa'.decode('hex'),
33 | 'suspicious_behaviour': [],
34 | 'known_code_signature': ['NT5.1/NT5.2 MBR'],
35 | }
36 | with open(sampleName, 'rb') as f_mbr:
37 | objMBR = MasterBootRecord(f_mbr, os.path.getsize(f_mbr.name), whitelist=whitelist)
38 | dParsed = objMBR.getDictRecord()
39 | assert dParsed == dExpected
40 |
41 |
42 | def test_mbr_nt60_with_whitelist(whitelist):
43 | sampleName = os.path.join('test_data', 'mbr_60.bin')
44 |
45 | dParsed = {}
46 | dExpected = {
47 | 'record_type': 'MBR',
48 | 'sample_name': sampleName,
49 | 'partition_table': [{'Number': 1, 'Attributes': 'Active', 'Type': 'NTFS',
50 | 'Start sector': 2048, 'Size in sectors': 41938944}],
51 | 'disk_signature': 'c9eda2df'.decode('hex'),
52 | 'oem_id': None,
53 | 'code_SHA256': '4799e8c92d32bca8e5103110a322523adb7a3909324132bd9abab8f3345e094a'.decode('hex'),
54 | 'record_raw': '33c08ed0bc007c8ec08ed8be007cbf0006b90002fcf3a450681c06cbfbb90400bdbe07807e00007c0b0f85100183c510'
55 | 'e2f1cd1888560055c6461105c6461000b441bbaa55cd135d720f81fb55aa7509f7c101007403fe46106660807e100074'
56 | '2666680000000066ff760868000068007c680100681000b4428a56008bf4cd139f83c4109eeb14b80102bb007c8a5600'
57 | '8a76018a4e028a6e03cd136661731efe4e110f850c00807e00800f848a00b280eb825532e48a5600cd135deb9c813efe'
58 | '7d55aa756eff7600e88a000f851500b0d1e664e87f00b0dfe660e87800b0ffe664e87100b800bbcd1a6623c0753b6681'
59 | 'fb54435041753281f90201722c666807bb00006668000200006668080000006653665366556668000000006668007c00'
60 | '00666168000007cd1a5a32f6ea007c0000cd18a0b707eb08a0b607eb03a0b50732e40500078bf0ac3c0074fcbb0700b4'
61 | '0ecd10ebf22bc9e464eb002402e0f82402c3496e76616c696420706172746974696f6e207461626c65004572726f7220'
62 | '6c6f6164696e67206f7065726174696e672073797374656d004d697373696e67206f7065726174696e67207379737465'
63 | '6d00000000627a99c9eda2df00008020210007feffff0008000000f07f02000000000000000000000000000000000000'
64 | '00000000000000000000000000000000000000000000000000000000000055aa'.decode('hex'),
65 | 'suspicious_behaviour': [],
66 | 'known_code_signature': ['NT6.0 MBR'],
67 | }
68 | with open(sampleName, 'rb') as f_mbr:
69 | objMBR = MasterBootRecord(f_mbr, os.path.getsize(f_mbr.name), whitelist=whitelist)
70 | dParsed = objMBR.getDictRecord()
71 | assert dParsed == dExpected
72 |
73 |
74 | def test_mbr_nt61_with_whitelist(whitelist):
75 | sampleName = os.path.join('test_data', 'mbr_61.bin')
76 |
77 | dParsed = {}
78 | dExpected = {
79 | 'record_type': 'MBR',
80 | 'sample_name': sampleName,
81 | 'partition_table': [{'Number': 1, 'Attributes': 'Active', 'Type': 'NTFS',
82 | 'Start sector': 2048, 'Size in sectors': 204800},
83 | {'Number': 2, 'Attributes': 'Inactive', 'Type': 'NTFS',
84 | 'Start sector': 206848, 'Size in sectors': 40685568},
85 | {'Number': 3, 'Attributes': 'Inactive', 'Type': 'NTFS',
86 | 'Start sector': 40892416, 'Size in sectors': 1046528},
87 | ],
88 | 'disk_signature': '14a90642'.decode('hex'),
89 | 'oem_id': None,
90 | 'code_SHA256': '088995559ab317af9b3291408da689651e8353f62e0a478d92eb0b5a947063fd'.decode('hex'),
91 | 'record_raw': '33c08ed0bc007c8ec08ed8be007cbf0006b90002fcf3a450681c06cbfbb90400bdbe07807e00007c0b0f850e0183c510'
92 | 'e2f1cd1888560055c6461105c6461000b441bbaa55cd135d720f81fb55aa7509f7c101007403fe46106660807e100074'
93 | '2666680000000066ff760868000068007c680100681000b4428a56008bf4cd139f83c4109eeb14b80102bb007c8a5600'
94 | '8a76018a4e028a6e03cd136661731cfe4e11750c807e00800f848a00b280eb845532e48a5600cd135deb9e813efe7d55'
95 | 'aa756eff7600e88d007517fab0d1e664e88300b0dfe660e87c00b0ffe664e87500fbb800bbcd1a6623c0753b6681fb54'
96 | '435041753281f90201722c666807bb00006668000200006668080000006653665366556668000000006668007c000066'
97 | '6168000007cd1a5a32f6ea007c0000cd18a0b707eb08a0b607eb03a0b50732e40500078bf0ac3c007409bb0700b40ecd'
98 | '10ebf2f4ebfd2bc9e464eb002402e0f82402c3496e76616c696420706172746974696f6e207461626c65004572726f72'
99 | '206c6f6164696e67206f7065726174696e672073797374656d004d697373696e67206f7065726174696e672073797374'
100 | '656d000000637b9a14a9064200008020210007df130c000800000020030000df140c07feffff0028030000d06c0200fe'
101 | 'ffff07feffff00f86f0200f80f000000000000000000000000000000000055aa'.decode('hex'),
102 | 'suspicious_behaviour': [],
103 | 'known_code_signature': ['NT6.1+ MBR'],
104 | }
105 | with open(sampleName, 'rb') as f_mbr:
106 | objMBR = MasterBootRecord(f_mbr, os.path.getsize(f_mbr.name), whitelist=whitelist)
107 | dParsed = objMBR.getDictRecord()
108 | assert dParsed == dExpected
109 |
110 |
111 | def test_mbr_empty_with_whitelist(whitelist):
112 | sampleName = os.path.join('test_data', 'mbr_empty.bin')
113 |
114 | with pytest.raises(InvalidMBRError) as e:
115 | with open(sampleName, 'rb') as f_mbr:
116 | objMBR = MasterBootRecord(f_mbr, os.path.getsize(f_mbr.name), whitelist=whitelist)
117 | assert "Invalid MBR structure: expected " in str(e.value)
118 |
119 |
120 | def test_mbr_empty_code_with_whitelist(whitelist):
121 | sampleName = os.path.join('test_data', 'mbr_empty_code.bin')
122 |
123 | dParsed = {}
124 | dExpected = {
125 | 'record_type': 'MBR',
126 | 'sample_name': sampleName,
127 | 'partition_table': [{'Number': 1, 'Attributes': 'Active', 'Type': 'NTFS',
128 | 'Start sector': 2048, 'Size in sectors': 204800},
129 | {'Number': 2, 'Attributes': 'Inactive', 'Type': 'NTFS',
130 | 'Start sector': 206848, 'Size in sectors': 40685568},
131 | {'Number': 3, 'Attributes': 'Inactive', 'Type': 'NTFS',
132 | 'Start sector': 40892416, 'Size in sectors': 1046528},
133 | ],
134 | 'disk_signature': '14a90642'.decode('hex'),
135 | 'oem_id': None,
136 | 'code_SHA256': None,
137 | 'record_raw': '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
138 | '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
139 | '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
140 | '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
141 | '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
142 | '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
143 | '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
144 | '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
145 | '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
146 | '000000000000000014a9064200008020210007df130c000800000020030000df140c07feffff0028030000d06c0200fe'
147 | 'ffff07feffff00f86f0200f80f000000000000000000000000000000000055aa'.decode('hex'),
148 | 'suspicious_behaviour': ['Code section is null'],
149 | 'known_code_signature': [],
150 | }
151 | with open(sampleName, 'rb') as f_mbr:
152 | objMBR = MasterBootRecord(f_mbr, os.path.getsize(f_mbr.name), whitelist=whitelist)
153 | dParsed = objMBR.getDictRecord()
154 | assert dParsed == dExpected
155 |
156 |
157 | def test_mbr_tc_with_whitelist(whitelist):
158 | sampleName = os.path.join('test_data', 'mbr_tc.bin')
159 |
160 | dParsed = {}
161 | dExpected = {
162 | 'record_type': 'MBR',
163 | 'sample_name': sampleName,
164 | 'partition_table': [{'Number': 1, 'Attributes': 'Active', 'Type': 'NTFS',
165 | 'Start sector': 2048, 'Size in sectors': 204800},
166 | {'Number': 2, 'Attributes': 'Inactive', 'Type': 'NTFS',
167 | 'Start sector': 206848, 'Size in sectors': 40685568},
168 | {'Number': 3, 'Attributes': 'Inactive', 'Type': 'NTFS',
169 | 'Start sector': 40892416, 'Size in sectors': 1046528},
170 | ],
171 | 'disk_signature': 'c9a7ee57'.decode('hex'),
172 | 'oem_id': None,
173 | 'code_SHA256': 'e6e6605c48665800786de4651ade2893970aafb1237a06db0943a8603dd4fce1'.decode('hex'),
174 | 'record_raw': 'ea1e7c00002054727565437279707420426f6f74204c6f616465720d0a00fa33c08ed88ed0bc007cfbf606b67d017507'
175 | '8d36057ce8dc00b80090813e13045c027d0eb80088813e13043c027d03b800208ec032c0bf0001b9ff6efcf3aa8cc02d'
176 | '00088ec0b102b004bb0001e8b4006633dbbe0001b90008e8ba006653bb000db106b039f606467d017404b01ab124e891'
177 | '00665bbe000d8b0eb07de89700663b1eb27d7425f606467d01750ec606467d01b120f606b77d0275ad8d36557de85300'
178 | '8d36057ce84c00ebfe8cc08ed8fa8ed0bc0080fb52680a0d68007a6800810e68e77c06680001cb83c4065a0e1f85c074'
179 | '098d36557de81b00ebfe8a36b77d8cc00500088ec08ed8fa8ed0bcfc6ffb06680001cb33dbb40efcac84c07404cd10eb'
180 | 'f7c3b500b600b402cd1373078d36477de8e0ffc31e061f6633c0fcac6603d866d1c3e2f71fc3004469736b206572726f'
181 | '720d0a0700074c6f616465722064616d61676564212055736520526573637565204469736b3a20526570616972204f70'
182 | '74696f6e73203e20526573746f726500000000000000000000000000000000000000000000000000000000000000071a'
183 | '722e832e05b50006c9a7ee5700008020210007df130c000800000020030000df140c07feffff0028030000d06c0200fe'
184 | 'ffff07feffff00f86f0200f80f000000000000000000000000000000000055aa'.decode('hex'),
185 | 'suspicious_behaviour': [],
186 | 'known_code_signature': ['TrueCrypt MBR'],
187 | }
188 | with open(sampleName, 'rb') as f_mbr:
189 | objMBR = MasterBootRecord(f_mbr, os.path.getsize(f_mbr.name), whitelist=whitelist)
190 | dParsed = objMBR.getDictRecord()
191 | assert dParsed == dExpected
192 |
193 | def test_mbr_uefi_with_whitelist(whitelist):
194 | sampleName = os.path.join('test_data', 'mbr_protect_uefi.bin')
195 |
196 | dParsed = {}
197 | dExpected = {
198 | 'record_type': 'MBR',
199 | 'sample_name': sampleName,
200 | 'partition_table': [{'Number': 1, 'Attributes': 'Inactive', 'Type': 'PROTECTIVE_MBR',
201 | 'Start sector': 1, 'Size in sectors': 41943039}],
202 | 'disk_signature': '00000000'.decode('hex'),
203 | 'oem_id': None,
204 | 'code_SHA256': None,
205 | 'record_raw': '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
206 | '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
207 | '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
208 | '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
209 | '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
210 | '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
211 | '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
212 | '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
213 | '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
214 | '000000000000000000000000000000000100eefeffff01000000ffff7f02000000000000000000000000000000000000'
215 | '00000000000000000000000000000000000000000000000000000000000055aa'.decode('hex'),
216 | 'suspicious_behaviour': [],
217 | 'known_code_signature': ['Protective MBR', 'UEFI (no legacy boot code)'],
218 | }
219 | with open(sampleName, 'rb') as f_mbr:
220 | objMBR = MasterBootRecord(f_mbr, os.path.getsize(f_mbr.name), whitelist=whitelist)
221 | dParsed = objMBR.getDictRecord()
222 | assert dParsed == dExpected
223 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/bootcode_parser.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2
2 | # -*- coding:utf-8 -*-
3 |
4 | from __future__ import unicode_literals, print_function
5 | from abc import ABCMeta, abstractmethod
6 | import logging
7 | import hashlib
8 | import csv
9 | import os
10 | import capstone
11 | import capstone.x86
12 | import sys
13 | from array import array
14 | try:
15 | from construct import ConstructError, Adapter, Struct, Sequence, Array, \
16 | Int8ul, Int8ub, Int16ul, Int32ul, Int64ul, Int8sl, Bytes, \
17 | Enum, String, Octet, BitsInteger, BitStruct, Padding, this, Pass, Const, \
18 | version as construct_version
19 | if construct_version[:2] != (2, 8):
20 | print('This version of {0} is compatible with Construct v2.8 only (you have v{1}.{2}).'
21 | .format(__file__, construct_version[0], construct_version[1]))
22 | sys.exit(1)
23 | except ImportError:
24 | print('This version of {0} is compatible with Construct v2.8.x only. '
25 | 'You either don\'t have the right version of Construct or don\'t have Construct at all.'
26 | .format(__file__))
27 | sys.exit(1)
28 |
29 |
30 |
31 | class _Utf16(Adapter):
32 | def _decode(self, obj, context):
33 | return array('B', obj[1]).tostring().decode('utf16').strip('\x00')
34 |
35 |
36 | def PascalUtf16(size_type=Int16ul):
37 | """Parse a length-defined string in UTF-16."""
38 |
39 | return _Utf16(Sequence(
40 | size_type,
41 | Bytes(this[0] * 2),
42 | ))
43 |
44 |
45 | BOOTRECORD_WHITELIST_PATH = os.path.join(os.path.dirname(__file__), 'data', 'bootrecord_whitelist.csv')
46 |
47 |
48 | class BootRecord(object):
49 | __metaclass__ = ABCMeta
50 |
51 | def __init__(self, source, size, offset=None, whitelist=()):
52 | """
53 | Default constructor which loads the raw data from a file.
54 | No sanity check is performed on the size or existence of the file.
55 | """
56 | # Common to MBR, VBR and IPL
57 | self._suspiciousBehaviour = []
58 | self._signature = []
59 | self._codeHash = None
60 | # MBR-specific
61 | self._partTable = []
62 | self._diskSignature = None
63 | # VBR-specific
64 | self._oemId = None
65 |
66 | self._whitelist = whitelist
67 | self._offset = offset
68 |
69 | # Input may be a file object, a list of file paths or directly the raw data (str)
70 | if isinstance(source, file):
71 | self._sample = source.name
72 | self._raw = source.read(size)
73 | elif isinstance(source, (list, tuple)):
74 | self._sample = ', '.join(source)
75 | self._raw = str()
76 | for f in source:
77 | with open(f, 'rb') as f_data:
78 | self._raw += f_data.read()
79 | elif isinstance(source, str):
80 | self._sample = None
81 | self._raw = source
82 | else:
83 | raise InvalidBootRecordError('Cannot instantiate a BootRecord object from {0}'.format(type(source)))
84 |
85 | self._logger = logging.LoggerAdapter(logging.getLogger('artefact'),
86 | {'objectid': getattr(self, '_sample', None), 'stage': self._type})
87 | self._parse()
88 |
89 | def __eq__(self, other):
90 | return self._raw == other.getRaw()
91 |
92 | def __ne__(self, other):
93 | return self._raw != other.getRaw()
94 |
95 | @abstractmethod
96 | def _parse(self):
97 | """
98 | Abstract private method called upon initialization to unpack the raw data into the boot record structure
99 | This method should only be called by BootRecord.__init__
100 | It returns nothing but updates several private attributes of the object
101 | """
102 | pass
103 |
104 | @abstractmethod
105 | def _checkCode(self, rawCode):
106 | """
107 | Abstract private helper method that tries to find malicious behaviour in the boot code.
108 | When something is found, self._suspiciousBehaviour is updated.
109 |
110 | Args:
111 | rawCode: str of the code section
112 |
113 | Returns: nothing
114 | """
115 | pass
116 |
117 | def _matchHash(self, codeHash, expectedLoader):
118 | """
119 | Private method that checks if the hash of the boot record's code section is present in the whitelist.
120 | If a match is found, self._signature is updated with the content of the "Comment" column of the whitelist.
121 | This method also checks that the whitelist entry matches what was expected from previous processing steps.
122 | This method updates self._codeHash with the hash of the code section
123 |
124 | Args:
125 | hash: hashlib.hash object
126 | expectedLoader: unicode string of the kind of loader that was expected from previous processing or None
127 |
128 | Returns: nothing
129 |
130 | """
131 | self._codeHash = codeHash.digest()
132 | # Use the hexdigest for whitelist matching
133 | hexDigest = codeHash.hexdigest()
134 | for dictWh in self._whitelist:
135 | if dictWh['Type'] == self._type and dictWh['SHA256'] == hexDigest:
136 | self._signature.append(dictWh['Comment'])
137 | # In addition to signature matching, also check that the loader is what we expected
138 | if expectedLoader and expectedLoader != dictWh['Comment']:
139 | self._suspiciousBehaviour.append('{0} earlier detection expected "{1}" but signature matched "{2}"'
140 | .format(self._type, expectedLoader, dictWh['Comment']))
141 |
142 | def getDictRecord(self):
143 | """
144 | Public method to retrieve a dict of the interesting values of the BootRecord
145 |
146 | Returns: dict
147 |
148 | """
149 | record = {
150 | 'record_type': self._type,
151 | 'sample_name': self._sample,
152 | 'partition_table': self._partTable,
153 | 'disk_signature': self._diskSignature,
154 | 'oem_id': self._oemId,
155 | 'code_SHA256': self._codeHash,
156 | 'record_raw': self._raw,
157 | 'suspicious_behaviour': self._suspiciousBehaviour,
158 | 'known_code_signature': self._signature,
159 | }
160 | return record
161 |
162 | def getRaw(self):
163 | return self._raw
164 |
165 |
166 | class MasterBootRecord(BootRecord):
167 | _MBR_STRUCT = Struct(
168 | 'bootloader_code' / Bytes(440),
169 | 'disk_signature' / Bytes(4),
170 | Padding(2),
171 | 'partitions' / Array(
172 | 4,
173 | Struct(
174 | 'state' / Int8sl,
175 | 'beginning' / BitStruct(
176 | 'head' / Octet,
177 | 'sect' / BitsInteger(6),
178 | 'cyl' / BitsInteger(10),
179 | ),
180 | Enum('type' / Int8ub,
181 | Nothing=0x00,
182 | FAT12=0x01,
183 | XENIX_ROOT=0x02,
184 | XENIX_USR=0x03,
185 | FAT16_old=0x04,
186 | Extended_DOS=0x05,
187 | FAT16=0x06,
188 | FAT32=0x0b,
189 | FAT32_LBA=0x0c,
190 | NTFS=0x07,
191 | LINUX_SWAP=0x82,
192 | LINUX_NATIVE=0x83,
193 | PROTECTIVE_MBR=0xee,
194 | _default_=Pass,
195 | ),
196 | 'ending' / BitStruct(
197 | 'head' / Octet,
198 | 'sect' / BitsInteger(6),
199 | 'cyl' / BitsInteger(10),
200 | ),
201 | 'sector_offset' / Int32ul, # offset from MBR in sectors
202 | 'size' / Int32ul, # in sectors
203 | )
204 | ),
205 | Const('55aa'.decode('hex')),
206 | )
207 |
208 | def __init__(self, filePath, size, offset=None, whitelist=()):
209 | self._type = 'MBR'
210 | super(MasterBootRecord, self).__init__(filePath, size, offset, whitelist)
211 |
212 | def _parse(self):
213 | """
214 | Main method in charge of parsing the MBR.
215 | It will try to parse the boot record according to documented known structure and extract the partition table
216 | disk signature and code section.
217 | It will then try to narrow down invariant code, hash it and match the hash against a whitelist.
218 | If no match was found, it will try some simple heuristics to detect malicious behaviours.
219 |
220 | Returns: nothing
221 |
222 | """
223 | try:
224 | mbr = self._MBR_STRUCT.parse(self._raw)
225 | except ConstructError as e:
226 | raise InvalidMBRError('Invalid MBR structure: {0}\n{1}'.format(e, hexdump(self._raw)))
227 |
228 | self._parsePartTable(mbr.partitions)
229 |
230 | # Windows stores the disk signature at 0x1B8, other MBRs seem to leave this area alone
231 | self._diskSignature = mbr.disk_signature
232 |
233 | # If code section is null, check for protective MBR signature (detected in partition table parsing). If found,
234 | # then the machine is likely using UEFI instead of BIOS to boot. If not, it could mean that the sample being
235 | # analyzed has been tampered by a bootkit
236 | if mbr.bootloader_code.encode('hex') == 440 * '00':
237 | if 'Protective MBR' in self._signature:
238 | self._signature.append('UEFI (no legacy boot code)')
239 | else:
240 | self._suspiciousBehaviour.append('Code section is null')
241 | else:
242 | expectedLoader, invariantCode = self._getInvariantCode(mbr.bootloader_code)
243 | codeHash = hashlib.sha256(invariantCode)
244 | self._matchHash(codeHash, expectedLoader)
245 | if len(self._signature) == 0:
246 | # No whitelisted signature matched, try some simple heuristics to flag this MBR as malicious
247 | # Note that the self._checkCode method is only given the "invariant" code section to help with the
248 | # disassembling. This will obviously leads to broken offsets, but it doesn't matter since the heuristics
249 | # don't use them.
250 | self._checkCode(invariantCode)
251 |
252 | def _parsePartTable(self, partitions):
253 | """
254 | Private method that parses the partition table of the MBR. Updates self._partTable list.
255 |
256 | Args:
257 | partitions: Construct.Container object of the partition table
258 |
259 | Returns: nothing
260 | """
261 | partNum = 0
262 | for part in partitions:
263 | partNum += 1
264 | # Assume a partition entry without size (in LBA) or type is invalid, and do not include it in the listing.
265 | if part.size != 0 and part.type != 'Nothing':
266 | dPart = {
267 | 'Number': partNum,
268 | 'Attributes': 'Active' if part.state < 0 else 'Inactive',
269 | 'Type': part.type,
270 | 'Start sector': part.sector_offset,
271 | 'Size in sectors': part.size
272 | }
273 | self._partTable.append(dPart)
274 | else:
275 | self._logger.debug('Ignoring invalid partition: %s', repr(part))
276 | # Protective MBR is just informative, keep on parsing partition table in case there is a valid
277 | # active partition
278 | if part.type == 'PROTECTIVE_MBR' and partNum == 1:
279 | self._logger.debug('Protective MBR detected, MBR partition table should not be taken into account. '
280 | 'Look for the GPT table partition instead')
281 | self._signature.append('Protective MBR')
282 |
283 | def _getInvariantCode(self, rawCode):
284 | """
285 | Helper method that tries to narrow down "invariant code" which can be hashed and compared to well known
286 | signatures. Most MBRs have localized error strings which must be excluded from the hash computation because
287 | they may vary from a country to another.
288 | First, this method tries to detect what kind of MBR it is dealing with. Most of the time, it is enough to
289 | to look for some known hardcoded strings that identify "well known" MBR (such as Truecrypt, GRUB2, etc...).
290 | Then, this method finds where the strings are and "removes" them (as in "does not include them").
291 | Finding these strings can be achieved by quickly studying the assembly code and looking for how these
292 | strings are echoed on screen at boot time (using interrupt 0x10).
293 | This research only needs to be done once for each type of MBR but requires an analyst to do it by static
294 | analysis. This script cannot take care of this. This method merely implements the results of such work.
295 |
296 | Currently supported MBR are:
297 | - Truecrypt
298 | - McAfee Endpoint Encryption (Safeboot)
299 | - GRUB2
300 | - Windows (XP to 10)
301 |
302 | Args:
303 | rawCode: str of the code section
304 |
305 | Returns: 2-tuple (unicode string of expected loader, concatenated strings of invariant sections of code)
306 |
307 | """
308 | # By default, assume all the MBR code section will be hashed. It is obviously wrong in most cases, but it allows
309 | # for a "default case" which will automatically matches no known hash in case something goes wrong with the
310 | # detection.
311 | codeStart = 0
312 | codeEnd = len(rawCode)
313 | expectedLoader = None
314 | invariantCode = str()
315 |
316 | # TrueCrypt (detected with the hardcoded string following the first jump: " TrueCrypt Boot Loader")
317 | if rawCode[0x5:0x1b].encode('hex').upper() == '2054727565437279707420426F6F74204C6F61646572':
318 | # TrueCrypt uses hardcoded and not-localized error strings. Therefore every TrueCrypt MBR should have the
319 | # same code from start to end
320 | expectedLoader = 'TrueCrypt MBR'
321 |
322 | # MacAfee SafeBoot (detected with the hardcoded string following the first jump: "Safeboot ")
323 | elif rawCode[0x3:0xc].encode('hex').upper() == '53616665426F6F7420':
324 | # Two versions have been seen but both start with a jump to the same offset (0x26).
325 | # There are some strings at the of the code section but localization is unlikely so it will be assumed
326 | # to be hardcoded (until a localized version is found...).
327 | # Therefore, Safeboot code can be hashed from 0x26 to the end of code section
328 | invariantCode += rawCode[:0x3] # Hash the first JMP
329 | codeStart = 0x26
330 | expectedLoader = 'Safeboot MBR'
331 |
332 | # GRUB (detected with the hardcoded string "GRUB " located at 0x188)
333 | elif rawCode[0x188:0x18d].encode('hex').upper() == '4752554220':
334 | # GRUB has some error strings but they are hardcoded and not localized so they can be included in the hash
335 | # computation. However GRUB can be installed on a disk (MBR) as well as on a partition (in a kind of VBR).
336 | # But in both cases the code used is the same. Since a BPB is needed for the latter case it is also present
337 | # in the MBR (but not needed). It therefore has to be excluded from the hash computation.
338 | # GRUB is jumping over the BIOS Parameter Block located between 0x3 and 0x5a.
339 | # It should be followed by the kernel address (word), kernel sector (dword), kernel sector high (dword) and
340 | # boot drive (byte). Therefore the code really starts at 0x65.
341 | # These values are hardcoded in boot.img and have little chance to change anytime soon.
342 | codeStart = 0x65
343 | invariantCode += rawCode[:0x3] # Hash the first JMP
344 | expectedLoader = 'GRUB2 MBR'
345 |
346 | # Windows MBR cannot be detected with hardcoded strings, so they fall in the default case and further checks
347 | # are then made based on the hypothesis that this is indeed a Windows MBR.
348 | else:
349 | # Starting with NT5.0, the MBR contains localized strings which must be excluded from the hash computation.
350 | # These strings are located after the code, at 3 different offsets which can be calculated by adding 0x100
351 | # to the values respectively stored in bytes 0x1b5, 0x1b6 and 0x1b7 (last bytes of the code section).
352 | # Eg: The first localized string is at : 0x100 + the value saved at offset 0x1B5
353 | # Even though localized strings can be of different lengths, the offset of the first one does not vary
354 | # given one Windows version. This can therefore be used to tell Windows versions apart.
355 | firstStrOffset = Int8ub.parse(rawCode[0x1b5])
356 | # Windows NT5
357 | if firstStrOffset == 0x2c:
358 | expectedLoader = 'NT5.1/NT5.2 MBR'
359 | codeEnd = 0x100 + firstStrOffset
360 | # Windows NT6.0
361 | elif firstStrOffset == 0x62:
362 | expectedLoader = 'NT6.0 MBR'
363 | codeEnd = 0x100 + firstStrOffset
364 | # Windows NT6.1+
365 | elif firstStrOffset == 0x63:
366 | expectedLoader = 'NT6.1+ MBR'
367 | codeEnd = 0x100 + firstStrOffset
368 | else:
369 | self._suspiciousBehaviour.append('Invalid string offset: {0:#x}'.format(firstStrOffset))
370 | self._logger.debug('First localized string offset is wrong for a windows MBR.'
371 | 'It should be 0x2c, 0x62 or 0x63) : {0:#x}'.format(firstStrOffset))
372 |
373 | self._logger.debug('Expecting {0}. Code starts at {1:#x} and ends at {2:#x}'
374 | .format(expectedLoader, codeStart, codeEnd))
375 |
376 | invariantCode += rawCode[codeStart:codeEnd]
377 | return expectedLoader, invariantCode
378 |
379 | def _checkCode(self, rawCode):
380 | md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_16)
381 | md.detail = True
382 |
383 | checkJmp = True
384 | for i in md.disasm(rawCode, 0):
385 | # Check for JUMPs and CALLs before the first PUSH/RET.
386 | if checkJmp and len(i.groups) > 0:
387 | # Group check if available
388 | if hasattr(capstone.x86, 'X86_GRP_CALL') and hasattr(capstone.x86, 'X86_GRP_RET'):
389 | if capstone.x86.X86_GRP_CALL in i.groups or capstone.x86.X86_GRP_JUMP in i.groups:
390 | self._suspiciousBehaviour.append('JMP or CALL before relocation')
391 | checkJmp = False
392 | elif capstone.x86.X86_GRP_RET in i.groups:
393 | # Stop search after the first PUSH/RET
394 | checkJmp = False
395 | # Manual check in case capstone version doesn't support CALL and RET groups
396 | else:
397 | if i.mnemonic[0] == 'j' or i.mnemonic == 'call':
398 | self._suspiciousBehaviour.append('JMP or CALL before relocation')
399 | checkJmp = False
400 | elif i.mnemonic[:3] == 'ret':
401 | # Stop search after the first PUSH/RET
402 | checkJmp = False
403 |
404 | # Check for unknown interrupt
405 | if i.mnemonic == 'int' and i.bytes[1] not in (0x10, 0x13, 0x18, 0x1a):
406 | self._suspiciousBehaviour.append('Unknown Interrupt : {0:#x}'.format(i.bytes[1]))
407 |
408 |
409 | class VolumeBootRecord(BootRecord):
410 | _NTFS_VBR_STRUCT = Struct(
411 | 'JumpOverBPB' / Bytes(3),
412 | 'OemId' / String( 8),
413 | 'BiosParameterBlock' / Struct(
414 | 'SectorSize' / Int16ul,
415 | 'SectorsPerCluster' / Int8ul,
416 | 'Reserved1' / Bytes(2),
417 | 'MustBeZero1' / Bytes(3),
418 | 'MustBeZero2' / Bytes(2),
419 | 'MediaDescriptor' / Int8ul,
420 | 'MustBeZero3' / Bytes(2),
421 | 'SectorsPerTrack' / Int16ul,
422 | 'NumberOfHeads' / Int16ul,
423 | 'HiddenSectors' / Int32ul,
424 | 'NotUsed1' / Bytes(4),
425 | 'DriveNumber' / Const('80'.decode('hex')),
426 | 'Reserved2' / Bytes(3),
427 | 'TotalSectors' / Int64ul,
428 | 'MFTCluster' / Int64ul,
429 | 'MFTMirrCluster' / Int64ul,
430 | 'ClustersPerMFTRecord' / Int8sl,
431 | 'NotUsed2' / Bytes(3),
432 | 'ClustersPerIdxBuffer' / Int8sl,
433 | 'NotUsed3' / Bytes(3),
434 | 'VolumneSN' / Int64ul,
435 | 'NotUsed4' / Bytes(4),
436 | ),
437 | 'Code' / Bytes( 426),
438 | Const('55aa'.decode('hex')),
439 | )
440 |
441 | _BITLOCKER_VBR_STRUCT = Struct(
442 | 'JumpOverBPB' / Bytes(3),
443 | 'OemId' / Const('-FVE-FS-'.encode('utf8')),
444 | 'BiosParameterBlock' / Struct(
445 | 'SectorSize' / Int16ul,
446 | 'SectorsPerCluster' / Int8ul,
447 | 'Reserved1' / Bytes(2),
448 | 'MustBeZero1' / Bytes(3),
449 | 'MustBeZero2' / Bytes(2),
450 | 'MediaDescriptor' / Int8ul,
451 | 'MustBeZero3' / Bytes(2),
452 | 'SectorsPerTrack' / Int16ul,
453 | 'NumberOfHeads' / Int16ul,
454 | 'HiddenSectors' / Int32ul,
455 | 'TotalSectors' / Int32ul,
456 | 'SectorsPerFAT' / Int32ul,
457 | 'FATFlags' / Int16ul,
458 | 'Version' / Int16ul,
459 | 'RootDirCluster' / Int32ul,
460 | 'FSInfoSector' / Int16ul,
461 | 'BackupSector' / Int16ul,
462 | 'Reserved2' / Bytes(12),
463 | 'DriveNumber' / Const('80'.decode('hex')),
464 | 'Reserved3' / Bytes(1),
465 | 'ExtendedBootSignature' / Bytes(1),
466 | 'VolumneSN' / Int32ul,
467 | 'VolumeLabel' / Const('NO NAME '.encode('utf8')),
468 | 'SystemId' / Const('FAT32 '.encode('utf8')),
469 | ),
470 | 'Code1' / Bytes(70),
471 | 'BitlockerGUID' / Bytes(16),
472 | 'FVEMetadataBlockOffset1' / Int64ul,
473 | 'FVEMetadataBlockOffset2' / Int64ul,
474 | 'FVEMetadataBlockOffset3' / Int64ul,
475 | 'Code2' / Bytes(307),
476 | 'FirstStrOffset' / Int8ul,
477 | 'SecondStrOffset' / Int8ul,
478 | 'ThirdStrOffset' / Int8ul,
479 | Const('55aa'.decode('hex')),
480 | )
481 |
482 | def __init__(self, filePath, size, offset=None, whitelist=()):
483 | self._type = 'VBR'
484 | super(VolumeBootRecord, self).__init__(filePath, size, offset, whitelist)
485 |
486 | def _parse(self):
487 | """
488 | Main method in charge of parsing the VBR.
489 | It will try to parse the boot record according to known structures (NTFS and Bitlocker supported).
490 | It will then try to narrow down invariant code, hash it and match the hash against a whitelist.
491 | If no match was found, it will try some simple heuristics to detect malicious behaviours.
492 | Finally it will compare the HiddenSectors value in BPB to that of the record's dump offset.
493 |
494 | Returns: nothing
495 |
496 | """
497 | try:
498 | # This will parse both NTFS and Vista bitlocker volumes since they only differ by their OEM ID
499 | vbr = self._NTFS_VBR_STRUCT.parse(self._raw)
500 | expectedLoader, invariantCode = self._getInvariantCode('NTFS', vbr)
501 | except ConstructError as e1:
502 | # Retry with Bitlocker (Win7+) volume header structure
503 | try:
504 | vbr = self._BITLOCKER_VBR_STRUCT.parse(self._raw)
505 | expectedLoader, invariantCode = self._getInvariantCode('bitlocker', vbr)
506 | except ConstructError as e2:
507 | raise InvalidVBRError('Invalid VBR structure: e1={0}, e2={1}\n{2}'.format(e1, e2, hexdump(self._raw)))
508 |
509 | self._oemId = vbr.OemId
510 | self._bpb = vbr.BiosParameterBlock
511 | codeHash = hashlib.sha256(invariantCode)
512 | self._matchHash(codeHash, expectedLoader)
513 |
514 | # If no whitelisted signature matched, try some simple heuristics to flag this VBR as malicious
515 | # Note that the self._checkCode method is only given the "invariant" code section to help with the
516 | # disassembling. This will obviously leads to broken offsets, but it doesn't matter since the heuristics don't
517 | # use them.
518 | if len(self._signature) == 0:
519 | self._checkCode(invariantCode)
520 |
521 | # At last, compare the offset at which this VBR was found with the value of the BPB HiddenSectors
522 | if self._offset is not None \
523 | and (vbr.BiosParameterBlock.HiddenSectors * vbr.BiosParameterBlock.SectorSize) != self._offset:
524 | self._suspiciousBehaviour.append(
525 | 'Suspicious HiddenSectors value: {0} ({1} bytes)'
526 | .format(vbr.BiosParameterBlock.HiddenSectors,
527 | vbr.BiosParameterBlock.HiddenSectors * vbr.BiosParameterBlock.SectorSize))
528 |
529 | def _getInvariantCode(self, vbrType, vbrStruct):
530 | """
531 | Helper method that finds all the sections of the boot code that can be hashed and compared to a whitelist.
532 | This means that localized strings and other variable parameters (BPB, etc...) are excluded.
533 | Currently, this method only supports NTFS and Bitlocker VBR.
534 |
535 | Args:
536 | vbrType: unicode string corresponding to the VBR type ('NTFS' or 'bitlocker')
537 | vbrStruct: construct.container of the VBR
538 |
539 | Returns: 2-tuple (unicode string of expected loader, concatenated strings of invariant sections of code)
540 |
541 | """
542 | codeStart = 0
543 | codeEnd = None
544 | invariantCode = str()
545 | expectedLoader = None
546 |
547 | if vbrType == 'NTFS':
548 | # The first three bytes are a jump over the NTFS BPB to where the code really starts (0x54) and a NOP
549 | invariantCode += vbrStruct.JumpOverBPB
550 | codeStart = 0x54
551 | # NTFS VBR contains localized strings which must be excluded from the hash computation.
552 | # Before Windows 8, these strings are located at 4 different offsets which can be calculated by adding
553 | # 0x100 to the values respectively stored in bytes 0x1f8, 0x1f9, 0x1fa and 0x1fb.
554 | # Starting from Windows 8, these strings are located at 3 different offsets which are directly stored in
555 | # little endian words respectively at 0x1f6, 0x1f8 and 0x1fa
556 | # Since there is no easy way to tell which version of Windows we are dealing with beforehand, we first
557 | # assume it is a Windows < 8 by testing 0x1f8 against all the known first offset. If all tests fail, assume
558 | # it is Windows >= 8 and check 0x1f6 against the only known first offset (to date)
559 | firstStrOffset = Int8ub.parse(self._raw[0x1f8])
560 | # Windows NT5
561 | if firstStrOffset == 0x83:
562 | expectedLoader = 'NT5.1/NT5.2 VBR'
563 | codeEnd = 0x100 + firstStrOffset
564 | # Windows NT6.0
565 | elif firstStrOffset == 0x80:
566 | expectedLoader = 'NT6.0 VBR'
567 | codeEnd = 0x100 + firstStrOffset
568 | # Windows NT6.1
569 | elif firstStrOffset == 0x8c:
570 | expectedLoader = 'NT6.1 VBR'
571 | codeEnd = 0x100 + firstStrOffset
572 | # Windows NT6.2+
573 | else:
574 | firstStrOffset = Int16ul.parse(self._raw[0x1f6:0x1f8])
575 | if firstStrOffset == 0x18a:
576 | expectedLoader = 'NT6.2+ VBR'
577 | codeEnd = firstStrOffset
578 |
579 | if codeEnd is None:
580 | self._suspiciousBehaviour.append('Invalid string offset: {0:#x}'.format(firstStrOffset))
581 | self._logger.debug('First localized string offset is wrong for a NTFS VBR: {0:#x}. '
582 | 'It should be 0x83, 0x80, 0x8c or 0x18a.'.format(firstStrOffset))
583 | codeEnd = 0
584 |
585 | elif vbrType == 'bitlocker':
586 | expectedLoader = 'NT6.1+ Bitlocker VBR'
587 | # The first three bytes are a jump over the NTFS BPB to where the code really starts (0x5A) and a NOP
588 | invariantCode += vbrStruct.JumpOverBPB
589 | # First section of code (_BITLOCKER_VBR_STRUCT.Code1)
590 | invariantCode += vbrStruct.Code1
591 | # In the second section of code, there are localized strings which must be excluded from hash computation.
592 | # Their offsets are stored in the last 3 bytes before the VBR signature (0x55aa).
593 | # For Windows 8, 8.1 and 10, the first string offset seems to always be 0x100 (ie. FirstStrOffset = 0x00)
594 | if vbrStruct.FirstStrOffset != 0:
595 | self._suspiciousBehaviour.append('Invalid string offset: {0:#x}'.format(vbrStruct.FirstStrOffset))
596 | self._logger.debug('First localized string offset is wrong for a Bitlocker VBR. '
597 | 'It should be 0x00) : {0:#x}'.format(vbrStruct.FirstStrOffset))
598 | codeStart = 0xc8 # Offset of Code2
599 | codeEnd = 0x100 + vbrStruct.FirstStrOffset
600 | else:
601 | raise NotImplementedError('VBR type "{0}" is not implemented yet'.format(vbrType))
602 |
603 | self._logger.debug('Expecting {0}. Code starts at {1:#x} and ends at {2:#x}'
604 | .format(expectedLoader, codeStart, codeEnd))
605 |
606 | invariantCode += self._raw[codeStart:codeEnd]
607 | return expectedLoader, invariantCode
608 |
609 | def _checkCode(self, code):
610 | md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_16)
611 | md.detail = True
612 | for i in md.disasm(code, 0):
613 | # Check for unknown interrupt
614 | if i.mnemonic == 'int' and i.bytes[1] not in (0x10, 0x13, 0x18, 0x1a):
615 | self._suspiciousBehaviour.append('Unknown Interrupt : {0:#x}'.format(i.bytes[1]))
616 |
617 |
618 | class InitialProgramLoader(BootRecord):
619 |
620 | def __init__(self, filePath, size, offset=None, whitelist=()):
621 | self._type = 'IPL'
622 | super(InitialProgramLoader, self).__init__(filePath, size, offset, whitelist)
623 |
624 | def _parse(self):
625 | try:
626 | header = PascalUtf16(Int16ul).parse(self._raw)
627 | except (ConstructError, UnicodeDecodeError) as e:
628 | raise InvalidIPLError('Invalid IPL structure: {0}\n{1}'.format(e, hexdump(self._raw[:0x200])))
629 |
630 | try:
631 | # IPL's code section is usually contained is the first 9 sectors. The remaining sectors are filled with
632 | # padding but it appears that the last (15th) sector can sometimes hold data not related to the boot process
633 | # and we need to exclude that from hash calculation.
634 | invariantCode = self._raw[:14*512]
635 | except IndexError:
636 | raise InvalidIPLError('Invalid sample size for IPL: {0} (should be 15 * 512-bytes sectors)'
637 | .format(len(self._raw)))
638 |
639 | expectedLoader = None
640 |
641 | # Starting with NT 6.2, IPL has a localized string that must be excluded from hash computation.
642 | # The difference between these two kinds of IPL can be told from the instruction located at 0x56 :
643 | # a Jump Short (EB) in case of IPL<6.2 or a Jump Near (E9) otherwise
644 | if header == 'BOOTMGR' and self._raw[0x56].encode('hex').upper() == 'E9':
645 | # The offset of the localized string seems to be stored in a DWORD at 0x117 (just before the beginning
646 | # of the assembly code). But the value seems to be an offset relative to the start of the whole
647 | # boot record (including the VBR) and not just the IPL.
648 | # Therefore we need to substract 0x200 to get the offset inside the IPL.
649 | strOffset = Int16ul.parse(self._raw[0x117:]) - 0x200
650 | # Exclude from hash calculation everything between the string offset and the beginning of code
651 | invariantCode = invariantCode[:strOffset] + invariantCode[0x119:]
652 | expectedLoader = 'NT6.2+ IPL'
653 |
654 | codeHash = hashlib.sha256(invariantCode)
655 | self._matchHash(codeHash, expectedLoader)
656 |
657 | # If no whitelisted signature matched, try some simple heuristics to flag this IPL as malicious
658 | # Note that the self._checkCode method is only given the "stripped" code section to help the disassembling.
659 | # This will obviously leads to broken offsets, but it doesn't matter since the heuristics don't use them.
660 | if len(self._signature) == 0:
661 | self._checkCode(invariantCode)
662 |
663 | def _checkCode(self, code):
664 | md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_16)
665 | md.detail = True
666 | for i in md.disasm(code, 0):
667 | # Check for unknown interrupt
668 | if i.mnemonic == 'int' and i.bytes[1] not in (0x10, 0x13, 0x18, 0x1a):
669 | self._suspiciousBehaviour.append('Unknown Interrupt : {0:#x}'.format(i.bytes[1]))
670 |
671 |
672 | class InvalidBootRecordError(Exception):
673 | pass
674 |
675 |
676 | class InvalidMBRError(InvalidBootRecordError):
677 | pass
678 |
679 |
680 | class InvalidVBRError(InvalidBootRecordError):
681 | pass
682 |
683 |
684 | class InvalidIPLError(InvalidBootRecordError):
685 | pass
686 |
687 |
688 | def hexdump(src, length=16, sep='.'):
689 | """
690 | @brief Return {src} in hex dump.
691 | @param[in] length {Int} Nb Bytes by row.
692 | @param[in] sep {Char} For the text part, {sep} will be used for non ASCII char.
693 | @return {Str} The hexdump
694 |
695 | @note Code borrowed from https://gist.github.com/ImmortalPC/c340564823f283fe530b
696 | """
697 | result = []
698 |
699 | # Python3 support
700 | try:
701 | xrange(0, 1)
702 | except NameError:
703 | xrange = range
704 |
705 | for i in xrange(0, len(src), length):
706 | subSrc = src[i:i + length]
707 | hexa = ''
708 | isMiddle = False
709 | for h in xrange(0, len(subSrc)):
710 | if h == length / 2:
711 | hexa += ' '
712 | h = subSrc[h]
713 | if not isinstance(h, int):
714 | h = ord(h)
715 | h = hex(h).replace('0x', '')
716 | if len(h) == 1:
717 | h = '0' + h
718 | hexa += h + ' '
719 | hexa = hexa.strip(' ')
720 | text = ''
721 | for c in subSrc:
722 | if not isinstance(c, int):
723 | c = ord(c)
724 | if 0x20 <= c < 0x7F:
725 | text += chr(c)
726 | else:
727 | text += sep
728 | result.append(('%08X: %-' + str(length * (2 + 1) + 1) + 's |%s|') % (i, hexa, text))
729 |
730 | return '\n'.join(result)
731 |
732 |
733 | def initWhitelist(fWhitelist):
734 | whitelist = []
735 | # CSV file content should be "Type,SHA256,Comment"
736 | with open(fWhitelist, 'rb') as fd:
737 | reader = csv.DictReader(fd)
738 | for row in reader:
739 | whitelist.append(row)
740 | return whitelist
741 |
742 |
743 | def checkResult(objBr, brType):
744 | """
745 | Simple function to check if anything is suspicious in the BootRecord
746 |
747 | :param objBr: BootRecord object
748 | :param brType: unicode string, type of BootRecord (MBR, VBR or IPL)
749 | :return: boolean, True if everything is OK, False otherwise
750 | """
751 | logger.extra.update({'stage': brType})
752 | ret = True
753 | if getattr(objBr, '_signature', None):
754 | logger.info('Known signatures found: %r', getattr(objBr, '_signature'))
755 | else:
756 | ret = False
757 | logger.warning('No known code signature were found, this is highly suspicious.')
758 | if getattr(objBr, '_codeHash'):
759 | logger.debug('Sample\'s code hash is: %r', getattr(objBr, '_codeHash').encode('hex'))
760 | if getattr(objBr, '_suspiciousBehaviour'):
761 | ret = False
762 | logger.warning('Suspicious behaviours were detected: %r', getattr(objBr, '_suspiciousBehaviour'))
763 | return ret
764 |
765 |
766 | def parseBootRecord(brType, input, offset, whitelist):
767 | logger.extra.update({'stage': brType})
768 | try:
769 | if brType == 'MBR':
770 | objBr = MasterBootRecord(input, 512, whitelist=whitelist)
771 | elif brType == 'VBR':
772 | objBr = VolumeBootRecord(input, 512, offset=offset, whitelist=whitelist)
773 | elif brType == 'IPL':
774 | objBr = InitialProgramLoader(input, 15 * 512, whitelist=whitelist)
775 | else:
776 | return
777 | checkResult(objBr, brType)
778 | except InvalidBootRecordError as e:
779 | logger.error(e)
780 | return
781 |
782 |
783 | def parseImageFile(input, sectorSize, whitelist):
784 | try:
785 | objMBR = MasterBootRecord(input, sectorSize, 0, whitelist)
786 | checkResult(objMBR, 'MBR')
787 | activePart = {}
788 | for part in getattr(objMBR, '_partTable'):
789 | # A partition is a dict with the following keys: (Number, Attributes, Type, Start sector, Size in sectors,
790 | # Name)
791 | if 'Active' in part['Attributes']:
792 | activePart = part
793 | # The first active partition is the one the MBR will load the VBR from
794 | break
795 | logger.extra.update({'stage': 'IMG'})
796 | if activePart:
797 | logger.debug('Found active partition n°%d starting at sector %d',
798 | activePart['Number'], activePart['Start sector'])
799 | offset = activePart['Start sector'] * sectorSize
800 | input.seek(offset)
801 | objVBR = VolumeBootRecord(input, sectorSize, offset=offset, whitelist=whitelist)
802 | if not checkResult(objVBR, 'VBR'):
803 | logger.warning('VBR of the active partition located at sector %d (offset %d) is suspicious (see '
804 | 'previous warning). This could mean that the partition table in the MBR or the BPB in '
805 | 'the VBR has been tampered with !', activePart['Start sector'], offset)
806 | hiddenSectors = getattr(objVBR, '_bpb').HiddenSectors
807 | logger.extra.update({'stage': 'IMG'})
808 | logger.debug('Found HiddenSectors value: %d', hiddenSectors)
809 | if hiddenSectors != (offset / sectorSize):
810 | logger.warning('HiddenSectors value in BiosParameterBlock is different than actual offset in partition '
811 | 'table ! HiddenSectors=%d, partition table offset=%d', hiddenSectors, offset/sectorSize)
812 | # IPL is just next to the VBR. Even when sectors are 4KB in size, the VBR and IPL will be contiguous : there
813 | # is no "slack space" between the VBR and IPL. Therefore, IPL will always be located at VBR offset + 512
814 | input.seek((hiddenSectors * sectorSize) + 512)
815 | objIPL = InitialProgramLoader(input, 15 * sectorSize, whitelist=whitelist)
816 | checkResult(objIPL, 'IPL')
817 | else:
818 | logger.warning('No active partition detected in MBR !')
819 | except InvalidBootRecordError as e:
820 | logger.error(e)
821 |
822 |
823 | if __name__ == '__main__':
824 | import argparse
825 | global logger
826 |
827 | parser = argparse.ArgumentParser(description='Check boot records for known good signatures',
828 | formatter_class=argparse.RawTextHelpFormatter,
829 | add_help=True)
830 | parser.add_argument('--type', choices=['VBR', 'MBR', 'IPL', 'IMG'], required=True,
831 | type=lambda x: x.decode(sys.getfilesystemencoding()).upper(),
832 | help='Type of boot record: MBR, VBR or IPL. Or whole disk image.')
833 | parser.add_argument('--input', required=True, type=lambda x: x.decode(sys.getfilesystemencoding()), nargs='+',
834 | help='Input file(s) to check')
835 | parser.add_argument('--offset', type=int,
836 | help='Offset in bytes at which the boot record was dumped. Required only for VBR. Without it, '
837 | 'some heuristics to detect malicious VBR will not work.')
838 | # Note that when using native 4K disks, Windows can only be installed in UEFI. Support for 4K sectors in this script
839 | # is mostly for testing purpose since no "default" Windows installation can ever be found on native 4K disks.
840 | # However, this option can be used to test a non-booting native 4K disk/volume.
841 | parser.add_argument('--sector-size', type=int, default=512,
842 | help='Disk sector size in bytes. Only applies for disk image input. Defaults to 512.')
843 | parser.add_argument('--whitelist', help='CSV file containing whitelisted boot record signatures. '
844 | 'Without it, the boot record will always be flagged as suspicious. '
845 | 'Defaults to {0}'.format(BOOTRECORD_WHITELIST_PATH),
846 | default=BOOTRECORD_WHITELIST_PATH, type=lambda x: x.decode(sys.getfilesystemencoding()))
847 | parser.add_argument('--logLevel', default='INFO', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
848 | help='Show debug messages according to the level provided.')
849 | args = parser.parse_args()
850 |
851 | logging.basicConfig(level=getattr(logging, args.logLevel.upper()),
852 | format='%(levelname)-8s - [%(objectid)s] [%(stage)s] %(message)s')
853 | logger = logging.LoggerAdapter(logging.getLogger(__file__), {'objectid': None, 'stage': 'main'})
854 |
855 | if args.type == 'VBR' and args.offset is None:
856 | logger.error('--offset is required when parsing VBR')
857 | sys.exit(1)
858 |
859 | if args.whitelist is not None:
860 | whitelist = initWhitelist(args.whitelist)
861 | else:
862 | whitelist = []
863 |
864 | for inputFile in args.input:
865 | logger.extra.update({'objectid': inputFile})
866 | with open(inputFile, 'rb') as f_input:
867 | if args.type == 'IMG':
868 | logger.debug('Parsing disk image file %s with %d whitelisted records', args.input, len(whitelist))
869 | parseImageFile(f_input, args.sector_size, whitelist)
870 | else:
871 | logger.debug('%s dumped %swith %d whitelisted records', args.type,
872 | 'at offset {0} '.format(args.offset) if args.offset else '',
873 | len(whitelist))
874 | parseBootRecord(args.type, f_input, args.offset, whitelist)
875 |
876 | # This is only useful for pytest
877 | logger = logging.LoggerAdapter(logging.getLogger(__file__), {'objectid': None, 'stage': 'main'})
878 |
--------------------------------------------------------------------------------