Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make EFI Resolver a native plugin #5855

Draft
wants to merge 4 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions platform/efi/efi_resolver/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
cmake_minimum_required(VERSION 3.22 FATAL_ERROR)

project(efi_resolver)

option(DEBUG "DEBUG Mode" ON)

if((NOT BN_API_PATH) AND (NOT BN_INTERNAL_BUILD))
set(BN_API_PATH $ENV{BN_API_PATH})
if(NOT BN_API_PATH)
message(FATAL_ERROR "Provide path to Binary Ninja API source in BN_API_PATH")
endif()
endif()
if(NOT BN_INTERNAL_BUILD)
set(HEADLESS ON CACHE BOOL "")
add_subdirectory(${BN_API_PATH} ${PROJECT_BINARY_DIR}/api)
endif()

# Binary Ninja plugin ----------------------------------------------------------

file(
GLOB_RECURSE SOURCE_FILES
CONFIGURE_DEPENDS # Automatically reconfigure if source files are added/removed.
${PROJECT_SOURCE_DIR}/src/*.cpp ${PROJECT_SOURCE_DIR}/include/*.h
)

add_library(efi_resolver SHARED ${SOURCE_FILES})
target_link_libraries(efi_resolver binaryninjaapi)
target_include_directories(${PROJECT_NAME} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/include")
target_compile_features(efi_resolver PRIVATE cxx_std_17 c_std_99)

# Library targets linking against the Binary Ninja API need to be compiled with
# position-independent code on Linux.
if(${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
target_compile_options(efi_resolver PRIVATE "-fPIC")
endif()

# Configure plugin output directory for internal builds, otherwise configure
# plugin installation for public builds.

if(BN_INTERNAL_BUILD)
set_target_properties(efi_resolver PROPERTIES
LIBRARY_OUTPUT_DIRECTORY ${BN_CORE_PLUGIN_DIR}
RUNTIME_OUTPUT_DIRECTORY ${BN_CORE_PLUGIN_DIR})
else()
bn_install_plugin(${PROJECT_NAME})
endif()

13 changes: 13 additions & 0 deletions platform/efi/efi_resolver/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Copyright 2023-2024 Vector 35 Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
128 changes: 128 additions & 0 deletions platform/efi/efi_resolver/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# EFI Resolver
Author: **Vector 35 Inc**

_A Binary Ninja built-in plugin that automatically resolves type information for EFI protocol usage._

This repository contains C++ version of EFI Resolver, which is bundled with Binary Ninja. For the original Python
version, please refer to https://github.com/vector35/efi-resolver/tree/main

## Description:

EFI Resolver is a Binary Ninja plugin that automates the task of resolving EFI protocol type information. It supports both DXE files and PEI files. It propagates parameter pointers from entry points to system table, MM system table, boot services, and runtime services to any global variables where they are stored. For PEI files, it also supports identifying [processor-specific mechanisms](https://uefi.org/specs/PI/1.8/V1_PEI_Foundation.html#pei-services-table-retrieval) for retrieving PEI services pointers. The plugin also identifies references to the boot services, MM protocol functions and PEI services, and applies type information according to the GUID passed to these functions. The plugin supports the core UEFI specification, and allows users to provide custom vendor protocols.

## Build Instructions

```bash
git clone https://github.com/Vector35/binaryninja-api.git
git clone https://github.com/Vector35/efi-resolver.git && cd efi-resolver
export BN_API_PATH=../binaryninja-api # Or specifying the path to api repo
cmake -S . -B build -GNinja
cmake --build build -t install
```

## License

This plugin is released under an Apache-2.0 license.

## Supplying Custom UEFI Protocol GUIDs and Types

By default, EFI Resolver propagates types and GUIDs using Binary Ninja's native platform types for EFI. Many UEFI
firmware binaries include types (and GUIDs) for proprietary protocols. This section describes how users can supply
custom UEFI types and GUIDs for use with EFI Resolver type propagation.

### User-supplied EFI GUIDs

EFI Resolver uses a JSON file to associate user-supplied EFI GUIDs with types for propagation. GUIDs for proprietary
protocol types can be used with EFI Resolver by creating a file at `<user folder>/types/efi-guids.json` containing JSON
entries in the following format:

```json
{
"EFI_EXAMPLE_CUSTOM_PROTOCOL_GUID": [
19088743,
35243,
52719,
1,
35,
69,
103,
137,
171,
205,
239
]
}
```

In this example, the protocol type of `EFI_EXAMPLE_CUSTOM_PROTOCOL` is mapped to the
`{0x01234567,0x89ab,0xcdef,{0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef}}` GUID (named `EFI_EXAMPLE_CUSTOM_PROTOCOL_GUID`).
To test that the file is a valid JSON file, run `python -m json.tool < efi-guids.json`.

__Note: user-supplied proprietary GUIDs from `efi-guids.json` are used to name variables regardless of whether or not an associated platform type has been loaded. If EFI Resolver fails to query the type for an EFI protocol interface, it will set the variable type for the protocol interface pointer to `VOID*`.__

### User-supplied EFI Platform Types

Types and structures for proprietary protocols are to be imported using Binary Ninja's standard mechanism for loading
user-supplied platform types. Instructions on adding custom platform types can be found [here](https://docs.binary.ninja/guide/types/platformtypes.html). Available EFI platform names include:
- `efi-x86`
- `efi-x86_64`
- `efi-thumb2`
- `efi-armv7`
- `efi-aarch64`
- `efi-windows-aarch64`
- `efi-windows-x86`
- `efi-windows-x86_64`

To avoid having to add duplicate types in each platform-specific `*.c` file, it is recommended to add common types
to a top-level `efi.c` file and `#include` the file in the platform-specific `*.c` files. For example:

```C
// <user folder>/types/platform/efi-x86_64.c including <user folder>/types/efi.c
#include "../efi.c"
```

To test that C source files containing custom EFI platform types are in the correct format, use the `bv.platform.parse_types_from_source_file` API.

Alternatively, user types can be supplied manually from type libraries, header files, or any other mechanism supported
by Binary Ninja. Just ensure that the name for types associated with GUIDs match what is in `efi-guids.json`. Protocol
GUID names in `efi-guids.json` should end with `_PROTOCOL_GUID` and the prefix must be identical to the associated
protocol type name. For example, if the GUID is named `EFI_EXAMPLE_PROTOCOL_GUID`, EFI Resolver will attempt to
look up a type named `EFI_EXAMPLE_PROTOCOL`.

### Full Example

In summary, including a custom platform type of `EFI_EXAMPLE_CUSTOM_PROTOCOL` for the `efi-x86` platform and associating
it with a GUID named `EFI_EXAMPLE_CUSTOM_PROTOCOL_GUID` requires two steps:

1. Create the `<user folder>/types/platform/efi-x86.c` header file:

```C
struct EFI_EXAMPLE_CUSTOM_PROTOCOL
{
uint32_t length;
}
```

2. Create the `<user folder>/types/efi-guids.json` file:

```json
{
"EFI_EXAMPLE_CUSTOM_PROTOCOL_GUID": [
19088743,
35243,
52719,
1,
35,
69,
103,
137,
171,
205,
239
]
}
```

After a Binary Ninja restart, when a binary is loaded with the `efi-x86` platform, the `EFI_EXAMPLE_CUSTOM_PROTOCOL`
type will be imported. When EFI Resolver runs, it will detect uses of `EFI_EXAMPLE_CUSTOM_PROTOCOL_GUID` and propagate
the `EFI_EXAMPLE_CUSTOM_PROTOCOL` type.
26 changes: 26 additions & 0 deletions platform/efi/efi_resolver/include/DxeResolver.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#pragma once

#include "Resolver.h"

class DxeResolver : Resolver
{
bool resolveBootServices();
bool resolveRuntimeServices();

bool resolveSmmTables(string serviceName, string tableName);
bool resolveSmmServices();
bool resolveSmiHandlers();

public:
/*!
resolve BootServices and RuntimeServices, define protocol types that loaded by BootServices
*/
bool resolveDxe();

/*!
Define MMST/SMMST and resolve SMM related protocols
*/
bool resolveSmm();

DxeResolver(Ref<BinaryView> view, Ref<BackgroundTask> task);
};
20 changes: 20 additions & 0 deletions platform/efi/efi_resolver/include/GuidRenderer.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#pragma once

#include "binaryninjaapi.h"
#include <iomanip>

using namespace BinaryNinja;
using namespace std;

class EfiGuidRenderer : public BinaryNinja::DataRenderer
{
EfiGuidRenderer() = default;

public:
bool IsValidForData(BinaryView*, uint64_t address, Type*, vector<pair<Type*, size_t>>&) override;

vector<DisassemblyTextLine> GetLinesForData(BinaryView*, uint64_t address, Type*,
const vector<InstructionTextToken>& prefix, size_t width, vector<pair<Type*, size_t>>&) override;

static void Register();
};
23 changes: 23 additions & 0 deletions platform/efi/efi_resolver/include/ModuleType.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#pragma once

#include "binaryninjaapi.h"

using namespace BinaryNinja;

enum EFIModuleType
{
UNKNOWN,
PEI,
DXE,
};

static inline EFIModuleType identifyModuleType(BinaryView* bv)
{
std::string viewType = bv->GetCurrentView();
if (viewType == "Linear:PE")
return DXE;
else if (viewType == "Linear:TE")
return PEI;
else
return UNKNOWN;
}
21 changes: 21 additions & 0 deletions platform/efi/efi_resolver/include/PeiResolver.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#pragma once

#include "Resolver.h"

class PeiResolver : Resolver
{
bool resolvePeiIdt();
bool resolvePeiMrc();
bool resolvePeiMrs();
bool resolvePlatformPointers();
bool resolvePeiDescriptors();
bool resolvePeiServices();

public:
/*!
resolve Pei related types and PPIs, this function will also resolve processor-specific pointers
and tried to define the EFI_PEI_DESCRIPTORS
*/
bool resolvePei();
PeiResolver(Ref<BinaryView> view, Ref<BackgroundTask> task);
};
75 changes: 75 additions & 0 deletions platform/efi/efi_resolver/include/Resolver.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#pragma once

#include <fstream>
#include <thread>

#include "GuidRenderer.h"
#include "ModuleType.h"
#include "TypePropagation.h"
#include "binaryninjaapi.h"
#include "highlevelilinstruction.h"
#include "lowlevelilinstruction.h"
#include "mediumlevelilinstruction.h"

using namespace BinaryNinja;
using namespace std;

typedef array<uint8_t, 16> EFI_GUID;

class Resolver
{
protected:
Ref<BinaryView> m_view;
Ref<BackgroundTask> m_task;
size_t m_width;
map<EFI_GUID, pair<string, string>> m_protocol;
map<EFI_GUID, string> m_user_guids;

vector<pair<uint64_t, string>> m_service_usages;
vector<pair<uint64_t, string>> m_protocol_usages;
vector<pair<uint64_t, EFI_GUID>> m_guid_usages;
vector<pair<uint64_t, string>> m_variable_usages;

bool parseUserGuidIfExists(const string& filePath);
bool parseProtocolMapping(const string& filePath);

/*!
For backward compatibility, if a user saved a bndb with older version Binary Ninja
this function will try to retrieve types from Platform Types if it doesn't find one
in BinaryView
*/
Ref<Type> GetTypeFromViewAndPlatform(string type_name);
void initProtocolMapping();

public:
bool setModuleEntry(EFIModuleType fileType);
bool resolveGuidInterface(Ref<Function> func, uint64_t addr, int guid_pos, int interface_pos);
Resolver(Ref<BinaryView> view, Ref<BackgroundTask> task);

pair<string, string> lookupGuid(EFI_GUID guidBytes);
pair<string, string> defineAndLookupGuid(uint64_t addr);

string nonConflictingName(const string& basename);
static string nonConflictingLocalName(Ref<Function> func, const string& basename);

/*!
Define the structure used at the callsite with type `typeName`, propagate it to the data section. If it's a
structure type, define it fields according to the `followFields` parameter. The input `addr` should be a call
instruction \param func the function that contains the callsite (it's parent function) \param addr address of the
callsite \param typeName the type that need to define \param paramIdx the parameter index that want to define \param
followFields whether to define the structure's fields if they are pointers \return False if failed

\b Example:
\code{.cpp}
refs = bv->GetCodeReferencesForType(QualifiedName("EFI_GET_VARIABLE"));
for (auto ref : refs)
{
// ... some checking, need to make sure is a call instruction
bool ok = defineTypeAtCallsite(ref.func, ref.addr, "EFI_GUID", 2, false);
}
\endcode
*/
bool defineTypeAtCallsite(
Ref<Function> func, uint64_t addr, string typeName, int paramIdx, bool followFields = false);
vector<HighLevelILInstruction> HighLevelILExprsAt(Ref<Function> func, Ref<Architecture> arch, uint64_t addr);
};
18 changes: 18 additions & 0 deletions platform/efi/efi_resolver/include/TypePropagation.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#pragma once

#include "Utils.h"
#include "binaryninjaapi.h"

using namespace BinaryNinja;

class TypePropagation
{
Ref<BinaryView> m_view;
std::deque<uint64_t> m_queue;
Ref<Platform> m_platform;

public:
TypePropagation(BinaryView* view);
bool propagateFuncParamTypes(Function* func);
bool propagateFuncParamTypes(Function* func, SSAVariable ssa_var);
};
Loading