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
|
use crate::container::network::NetworkTargetId;
use crate::container::SourceId;
use reqwest::blocking::Client;
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
use reqwest::StatusCode;
use serde_json::json;
use std::collections::HashMap;
use std::str::FromStr;
use warp::signature::function::FunctionGUID;
use warp::target::Target;
use warp::WarpFile;
/// Responsible for sending and receiving data from the server.
///
/// NOTE: **All requests are blocking**.
#[derive(Clone, Debug)]
pub struct NetworkClient {
client: Client,
server_url: String,
}
impl NetworkClient {
pub fn new(
server_url: String,
server_token: Option<String>,
https_proxy: Option<String>,
) -> reqwest::Result<Self> {
let version_info = binaryninja::version_info();
// TODO: IIRC we had a user agent format already for some other thing.
let client_agent = format!(
"Binary Ninja/{}.{}.{}",
version_info.major, version_info.minor, version_info.build
);
// TODO: This might want to be kept for the request header?
let mut headers = HeaderMap::new();
if let Some(token) = &server_token {
headers.insert(
AUTHORIZATION,
HeaderValue::from_str(&format!("Bearer {}", token)).unwrap(),
);
}
// TODO: Configurable timeout?
let mut client_builder = Client::builder()
.connect_timeout(std::time::Duration::from_secs(10))
.default_headers(headers)
.user_agent(client_agent);
if let Some(https_proxy) = https_proxy {
client_builder = client_builder.proxy(reqwest::Proxy::all(&https_proxy)?);
}
Ok(Self {
client: client_builder.build()?,
server_url,
})
}
/// Check to see the status of the server.
///
/// This is useful if you want to fail early and prevent constructing a network container to a
/// server that is unresponsive.
///
/// Route: `api/v1/status`
pub fn status(&self) -> reqwest::Result<StatusCode> {
let status_url = format!("{}/api/v1/status", self.server_url);
let resp = self.client.get(&status_url).send()?;
Ok(resp.status())
}
/// Query the [`NetworkTargetId`] for the given [`Target`].
///
/// NOTE: **THIS IS BLOCKING**
///
/// Route: `api/v1/targets/query` (TODO: Comment about the query)
pub fn query_target_id(&self, target: &Target) -> Option<NetworkTargetId> {
let query_target_url = format!("{}/api/v1/targets/query", self.server_url);
let mut query = HashMap::new();
if let Some(platform) = &target.platform {
query.insert("platform", platform);
}
if let Some(architecture) = &target.architecture {
query.insert("architecture", architecture);
}
// NOTE: This is blocking.
let target_id: NetworkTargetId = self
.client
.get(query_target_url)
.query(&query)
.send()
.ok()?
.json::<NetworkTargetId>()
.ok()?;
Some(target_id)
}
fn query_functions_body(
target: Option<NetworkTargetId>,
source: Option<SourceId>,
guids: &[FunctionGUID],
) -> serde_json::Value {
let guids_str: Vec<String> = guids.iter().map(|g| g.to_string()).collect();
// TODO: The limit here needs to be somewhat flexible. But 1000 will do for now.
let mut body = json!({
"format": "flatbuffer",
"guids": guids_str,
"limit": 1000
});
if let Some(target_id) = target {
body["target_id"] = json!(target_id);
}
if let Some(source_id) = source {
body["source_id"] = json!(source_id.to_string());
}
body
}
/// Query the functions, returning the warp file response containing the entries.
///
/// NOTE: **THIS IS BLOCKING**
///
/// Route: `api/v1/functions/query` (TODO: Comment about the query)
pub fn query_functions(
&self,
target: Option<NetworkTargetId>,
source: Option<SourceId>,
guids: &[FunctionGUID],
) -> Option<WarpFile<'static>> {
let query_functions_url = format!("{}/api/v1/functions/query", self.server_url);
let payload = Self::query_functions_body(target, source, guids);
// Make the POST request
let response = self
.client
.post(&query_functions_url)
.json(&payload)
.send()
.ok()?;
if !response.status().is_success() {
log::error!("Failed to query functions: {}", response.status());
return None;
}
// Get response bytes and convert to WarpFile
let bytes = response.bytes().ok()?;
WarpFile::from_owned_bytes(bytes.to_vec())
}
/// Query the functions, returning the sources and the corresponding function guids.
///
/// NOTE: **THIS IS BLOCKING**
///
/// Route: `api/v1/functions/query/source` (TODO: Comment about the query)
pub fn query_functions_source(
&self,
target: Option<NetworkTargetId>,
guids: &[FunctionGUID],
) -> Option<HashMap<SourceId, Vec<FunctionGUID>>> {
let query_functions_source_url =
format!("{}/api/v1/functions/query/source", self.server_url);
let payload = Self::query_functions_body(target, None, guids);
// Make the POST request
let response = self
.client
.post(&query_functions_source_url)
.json(&payload)
.send()
.ok()?;
if !response.status().is_success() {
log::error!("Failed to query functions source: {}", response.status());
return None;
}
// Mapping of source id to function guids
let json_response: HashMap<String, Vec<String>> = response.json().ok()?;
let mapped_function_guids = json_response
.into_iter()
.filter_map(|(source_str, guid_strs)| {
let source_id = SourceId::from_str(&source_str).ok()?;
let guids = guid_strs
.into_iter()
.filter_map(|guid_str| FunctionGUID::from_str(&guid_str).ok())
.collect();
Some((source_id, guids))
})
.collect();
Some(mapped_function_guids)
}
/// Pushes the file to the remote source.
///
/// NOTE: **THIS IS BLOCKING**
///
/// Route: `api/v1/files/{source}`
pub fn push_file(&self, source_id: SourceId, file: &WarpFile) -> bool {
let push_file_url = format!("{}/api/v1/files/{}", self.server_url, source_id.to_string());
// Convert WarpFile to bytes
let file_bytes = file.to_bytes();
// Create the form part with the file
let form = reqwest::blocking::multipart::Form::new().part(
"file",
reqwest::blocking::multipart::Part::bytes(file_bytes)
.file_name("data.warp")
.mime_str("application/octet-stream")
.unwrap(),
);
// Send the request
match self.client.post(&push_file_url).multipart(form).send() {
Ok(response) => {
if response.status().is_success() {
true
} else {
log::error!("Failed to push file: {}", response.status());
false
}
}
Err(e) => {
log::error!("Failed to send push request: {}", e);
false
}
}
}
}
|