summaryrefslogtreecommitdiff
path: root/plugins/warp/src/plugin.rs
blob: dec62c2f0f46c32f7b240fa4c030af4712a2cbc4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
use crate::cache::register_cache_destructor;
use std::time::Instant;

use crate::cache::container::add_cached_container;
use crate::container::disk::DiskContainer;
use crate::container::network::{NetworkClient, NetworkContainer};
use crate::matcher::MatcherSettings;
use crate::plugin::render_layer::HighlightRenderLayer;
use crate::plugin::settings::PluginSettings;
use crate::{core_signature_dir, user_signature_dir};
use binaryninja::background_task::BackgroundTask;
use binaryninja::command::{
    register_command, register_command_for_function, register_command_for_project,
};
use binaryninja::settings::{QueryOptions, Settings};
use binaryninja::{is_ui_enabled, tracing};

mod commit;
mod create;
mod ffi;
mod file;
mod function;
mod load;
mod project;
mod render_layer;
mod settings;
mod workflow;

#[cfg(debug_assertions)]
mod debug;

fn load_bundled_signatures() {
    let global_bn_settings = Settings::new();
    let plugin_settings =
        PluginSettings::from_settings(&global_bn_settings, &mut QueryOptions::new());
    // We want to load all the bundled directories into the container cache.
    let background_task = BackgroundTask::new("Loading WARP files...", false);
    let start = Instant::now();
    if plugin_settings.load_bundled_files {
        let mut core_disk_container = DiskContainer::new_from_dir(core_signature_dir());
        core_disk_container.name = "Bundled".to_string();
        core_disk_container.writable = false;
        tracing::debug!("{:#?}", core_disk_container);
        add_cached_container(core_disk_container);
    }
    if plugin_settings.load_user_files {
        let mut user_disk_container = DiskContainer::new_from_dir(user_signature_dir());
        user_disk_container.name = "User".to_string();
        tracing::debug!("{:#?}", user_disk_container);
        add_cached_container(user_disk_container);
    }
    tracing::info!("Loading files took {:?}", start.elapsed());
    background_task.finish();
}

fn load_network_container() {
    let global_bn_settings = Settings::new();

    let add_network_container = |url: String, api_key: Option<String>| {
        let network_client = NetworkClient::new(url.clone(), api_key.clone());
        // Before constructing the container, let's make sure that the server is OK.
        if let Err(e) = network_client.status() {
            tracing::warn!("Server '{}' failed to connect: {}", url, e);
            return;
        }

        // Check if the user is logged in. If so, we should collect the writable sources.
        let mut writable_sources = Vec::new();
        match network_client.current_user() {
            Ok((id, username)) => {
                tracing::info!(
                    "Server '{}' connected, logged in as user '{}'",
                    url,
                    username
                );
                match network_client.query_sources(Some(id)) {
                    Ok(sources) => {
                        writable_sources = sources;
                    }
                    Err(e) => {
                        tracing::error!("Server '{}' failed to get sources for user: {}", url, e);
                    }
                }
            }
            Err(e) if api_key.is_some() => {
                tracing::error!(
                    "Server '{}' failed to authenticate with provided API key: {}",
                    url,
                    e
                );
            }
            Err(_) => {
                tracing::info!("Server '{}' connected, logged in as guest", url);
            }
        }

        // TODO: Make the cache path include the domain or url, so that we can have multiple servers.
        let main_cache_path = NetworkContainer::root_cache_location().join("main");
        let network_container =
            NetworkContainer::new(network_client, main_cache_path, &writable_sources);
        tracing::debug!("{:#?}", network_container);
        add_cached_container(network_container);
    };

    let plugin_settings =
        PluginSettings::from_settings(&global_bn_settings, &mut QueryOptions::new());
    let background_task = BackgroundTask::new("Initializing WARP server...", false);
    let start = Instant::now();
    if plugin_settings.enable_server {
        add_network_container(plugin_settings.server_url, plugin_settings.server_api_key);
        if let Some(second_server_url) = plugin_settings.second_server_url {
            add_network_container(second_server_url, plugin_settings.second_server_api_key);
        }
    }
    tracing::debug!("Initializing warp server took {:?}", start.elapsed());
    background_task.finish();
}

fn plugin_init() -> bool {
    binaryninja::tracing_init!("WARP");

    // Create the user signature directory if it does not exist, otherwise we will not be able to write to it.
    if !user_signature_dir().exists() {
        if let Err(e) = std::fs::create_dir_all(&user_signature_dir()) {
            tracing::error!("Failed to create user signature directory: {}", e);
        }
    }

    // Register our matcher and plugin settings globally.
    let mut global_bn_settings = Settings::new();
    global_bn_settings.register_group("warp", "WARP");
    MatcherSettings::register(&mut global_bn_settings);
    PluginSettings::register(&mut global_bn_settings);

    // Make sure caches are flushed when the views get destructed.
    register_cache_destructor();

    // Register our highlight render layer.
    HighlightRenderLayer::register();

    if workflow::insert_workflow().is_err() {
        tracing::error!("Failed to register WARP workflow");
        return false;
    }

    // TODO: Make the retrieval of containers wait on this to be done.
    // TODO: We could also have a mechanism for lazily loading the files using the chunk header target.
    // Loading bundled signatures might take a few hundred milliseconds.
    if is_ui_enabled() {
        std::thread::spawn(|| {
            load_bundled_signatures();
            load_network_container();
        });
    } else {
        load_bundled_signatures();
        std::thread::spawn(|| {
            // Dependence on this is likely to not matter in headless, so we throw it on another thread.
            load_network_container();
        });
    }

    register_command(
        "WARP\\Run Matcher",
        "Run the matcher manually",
        workflow::RunMatcher {},
    );

    #[cfg(debug_assertions)]
    register_command(
        "WARP\\Debug\\Cache",
        "Debug cache sizes... because...",
        debug::DebugCache {},
    );

    #[cfg(debug_assertions)]
    register_command(
        "WARP\\Debug\\Invalidate Caches",
        "Invalidate all WARP caches",
        debug::DebugInvalidateCache {},
    );

    #[cfg(debug_assertions)]
    register_command_for_function(
        "WARP\\Debug\\Function Signature",
        "Print the entire signature for the function",
        debug::DebugFunction {},
    );

    register_command(
        "WARP\\Load File",
        "Load file into the matcher, this does NOT kick off matcher analysis",
        load::LoadSignatureFile {},
    );

    register_command(
        "WARP\\Commit File",
        "Commit file to a source",
        commit::CommitFile {},
    );

    register_command_for_function(
        "WARP\\Include Function",
        "Add current function to the list of functions to add to the signature file",
        function::IncludeFunction {},
    );

    register_command_for_function(
        "WARP\\Ignore Function",
        "Add current function to the list of functions to ignore when matching",
        function::IgnoreFunction {},
    );

    register_command_for_function(
        "WARP\\Remove Matched Function",
        "Remove the current match from the selected function, to prevent matches in future use 'Ignore Function'",
        function::RemoveFunction {},
    );

    register_command_for_function(
        "WARP\\Copy GUID",
        "Copy the computed GUID for the function",
        function::CopyFunctionGUID {},
    );

    register_command(
        "WARP\\Find GUID",
        "Locate the function in the view using a GUID",
        function::FindFunctionFromGUID {},
    );

    register_command(
        "WARP\\Create\\From Current View",
        "Creates a signature file containing all selected functions",
        create::CreateFromCurrentView {},
    );

    register_command(
        "WARP\\Create\\From File(s)",
        "Creates a signature file containing all selected functions",
        create::CreateFromFiles {},
    );

    register_command(
        "WARP\\Show Report",
        "Creates a report for the selected file, displaying info on functions and types",
        file::ShowFileReport {},
    );

    register_command_for_project(
        "WARP\\Create\\From Project",
        "Create signature files from select project files",
        project::CreateSignatures {},
    );

    true
}

#[no_mangle]
#[allow(non_snake_case)]
#[cfg(feature = "demo")]
pub extern "C" fn WarpPluginInit() -> bool {
    plugin_init();
    true
}

#[no_mangle]
#[allow(non_snake_case)]
#[cfg(not(feature = "demo"))]
pub extern "C" fn CorePluginInit() -> bool {
    plugin_init();
    true
}