1# PROJECT:     Python tools for traversing BTRFS structures
2# LICENSE:     GPL-2.0+ (https://spdx.org/licenses/GPL-2.0+)
3# PURPOSE:     Script for obtaining freeldr.sys from BTRFS disk image
4# COPYRIGHT:   Copyright 2018 Victor Perevertkin (victor@perevertkin.ru)
5
6from btrfs_structures import *
7import crc32c
8
9fs = FileSystem('btrfs-big.bin', 0x7e00)
10
11fs.print_chunk_map()
12
13
14freeldr_dir_key = Key(256, DIR_ITEM_KEY, crc32c.name_hash('freeldr.sys')) # 256 - root dir objectid crc32c.name_hash('freeldr.sys')
15print(freeldr_dir_key)
16
17print('!!!!!!!!!!!!!!!!!!!! fs tree 1')
18fs_level, fs_root = fs.fs_root
19freeldr_dir_key, freeldr_dir_item = fs.search_tree(fs_level, fs_root, freeldr_dir_key)
20fs.search_tree(fs_level, fs_root, freeldr_dir_key, fs.print_node)
21
22freeldr_item, = (x for x in freeldr_dir_item if x.name.decode('utf-8') == 'freeldr.sys')
23freeldr_extent_data_key = Key(freeldr_item.location.objectid, EXTENT_DATA_KEY, 0)
24
25print('!!!!!!!!!!!!!!!!!!!! fs tree 2')
26freeldr_extent_data_key, freeldr_extent_data_item = fs.search_tree(fs_level, fs_root, freeldr_extent_data_key)
27fs.search_tree(fs_level, fs_root, freeldr_extent_data_key, fs.print_node)
28
29# # exploring extent tree
30print('!!!!!!!!!!!!!!!!!!!! extent tree')
31extent_level, extent_root = fs.extent_root
32exkey, extent_item = fs.search_tree(extent_level, extent_root, Key(freeldr_extent_data_item.disk_bytenr, EXTENT_ITEM_KEY, freeldr_extent_data_item.disk_num_bytes))
33
34print(freeldr_extent_data_item)
35fs.fd.seek(fs.logical_to_physical(extent_item.vaddr))
36freeldr = fs.fd.read(freeldr_extent_data_item.num_bytes)
37
38file = open("readed_freeldr.sys", "wb")
39file.write(freeldr)
40print(crc32c.name_hash('freeldr.sys'))
41