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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
use crate::bpf::Bpf;
use crate::{errors::Error, pcap_util, stats::Stats};
use log::*;
use std::os::raw::c_int;
use std::path::Path;
#[derive(Clone)]
pub struct Handle {
handle: *mut pcap_sys::pcap_t,
live_capture: bool,
interrupted: std::sync::Arc<std::sync::Mutex<bool>>,
}
unsafe impl Send for Handle {}
unsafe impl Sync for Handle {}
impl Handle {
pub fn is_live_capture(&self) -> bool {
self.live_capture
}
pub fn live_capture(iface: &str) -> Result<std::sync::Arc<Handle>, Error> {
let device_str = std::ffi::CString::new(iface).map_err(Error::Ffi)?;
let errbuf = ([0i8; 256]).as_mut_ptr();
let h = unsafe { pcap_sys::pcap_create(device_str.as_ptr(), errbuf) };
let r = if h.is_null() {
pcap_util::cstr_to_string(errbuf).and_then(|msg| {
error!("Failed to create live stream: {}", msg);
Err(Error::LiveCapture {
iface: iface.to_string(),
error: Error::LibPcapError { msg: msg }.into(),
})
})
} else {
info!("Live stream created for interface {}", iface);
let handle = std::sync::Arc::new(Handle {
handle: h,
live_capture: true,
interrupted: std::sync::Arc::new(std::sync::Mutex::new(false)),
});
Ok(handle)
};
drop(errbuf);
r
}
pub fn file_capture<P: AsRef<Path>>(path: P) -> Result<std::sync::Arc<Handle>, Error> {
let path = if let Some(s) = path.as_ref().to_str() {
s
} else {
return Err(Error::Custom {
msg: format!("Invalid path: {:?}", path.as_ref()),
});
};
let device_str = std::ffi::CString::new(path).map_err(Error::Ffi)?;
let errbuf = ([0i8; 256]).as_mut_ptr();
let h = unsafe { pcap_sys::pcap_open_offline(device_str.as_ptr(), errbuf) };
let r = if h.is_null() {
pcap_util::cstr_to_string(errbuf).and_then(|msg| {
error!("Failed to create file stream: {}", msg);
Err(Error::FileCapture {
file: path.to_string(),
error: Error::LibPcapError { msg: msg }.into(),
})
})
} else {
info!("File stream created for file {}", path);
let handle = std::sync::Arc::new(Handle {
handle: h,
live_capture: false,
interrupted: std::sync::Arc::new(std::sync::Mutex::new(false)),
});
Ok(handle)
};
drop(errbuf);
r
}
pub fn dead(linktype: i32, snaplen: i32) -> Result<std::sync::Arc<Handle>, Error> {
let h = unsafe { pcap_sys::pcap_open_dead(linktype as c_int, snaplen as c_int) };
if h.is_null() {
error!("Failed to create dead handle");
Err(Error::Custom {
msg: "Could not create dead handle".to_owned(),
})
} else {
info!("Dead handle created");
let handle = std::sync::Arc::new(Handle {
handle: h,
live_capture: false,
interrupted: std::sync::Arc::new(std::sync::Mutex::new(false)),
});
Ok(handle)
}
}
pub fn lookup() -> Result<std::sync::Arc<Handle>, Error> {
let errbuf = ([0i8; 256]).as_mut_ptr();
let dev = unsafe { pcap_sys::pcap_lookupdev(errbuf) };
let res = if dev.is_null() {
pcap_util::cstr_to_string(errbuf as _)
.and_then(|msg| Err(Error::LibPcapError { msg: msg }))
} else {
pcap_util::cstr_to_string(dev as _).and_then(|s| {
debug!("Lookup found interface {}", s);
Handle::live_capture(&s)
})
};
drop(errbuf);
res
}
pub fn set_non_block(&self) -> Result<&Self, Error> {
let errbuf = ([0i8; 256]).as_mut_ptr();
if -1 == unsafe { pcap_sys::pcap_setnonblock(self.handle, 1, errbuf) } {
pcap_util::cstr_to_string(errbuf as _).and_then(|msg| {
error!("Failed to set non block: {}", msg);
Err(Error::LibPcapError { msg: msg })
})
} else {
Ok(self)
}
}
pub fn set_promiscuous(&self) -> Result<&Self, Error> {
if 0 != unsafe { pcap_sys::pcap_set_promisc(self.handle, 1) } {
Err(pcap_util::convert_libpcap_error(self.handle))
} else {
Ok(self)
}
}
pub fn set_snaplen(&self, snaplen: u32) -> Result<&Self, Error> {
if 0 != unsafe { pcap_sys::pcap_set_snaplen(self.handle, snaplen as _) } {
Err(pcap_util::convert_libpcap_error(self.handle))
} else {
Ok(self)
}
}
pub fn set_timeout(&self, dur: &std::time::Duration) -> Result<&Self, Error> {
if 0 != unsafe { pcap_sys::pcap_set_timeout(self.handle, dur.as_millis() as _) } {
Err(pcap_util::convert_libpcap_error(self.handle))
} else {
Ok(self)
}
}
pub fn set_buffer_size(&self, buffer_size: u32) -> Result<&Self, Error> {
if 0 != unsafe { pcap_sys::pcap_set_buffer_size(self.handle, buffer_size as _) } {
Err(pcap_util::convert_libpcap_error(self.handle))
} else {
Ok(self)
}
}
pub fn compile_bpf(&self, bpf: &str) -> Result<Bpf, Error> {
let mut bpf_program = pcap_sys::bpf_program {
bf_len: 0,
bf_insns: std::ptr::null_mut(),
};
let bpf_str = std::ffi::CString::new(bpf.clone()).map_err(Error::Ffi)?;
if 0 != unsafe {
pcap_sys::pcap_compile(
self.handle,
&mut bpf_program,
bpf_str.as_ptr(),
1,
pcap_sys::PCAP_NETMASK_UNKNOWN,
)
} {
return Err(pcap_util::convert_libpcap_error(self.handle));
}
Ok(Bpf::new(bpf_program))
}
pub fn set_bpf(&self, bpf: Bpf) -> Result<&Self, Error> {
let mut bpf = bpf;
let ret_code = unsafe { pcap_sys::pcap_setfilter(self.handle, bpf.inner_mut()) };
if ret_code != 0 {
return Err(pcap_util::convert_libpcap_error(self.handle));
}
Ok(self)
}
pub fn activate(&self) -> Result<&Self, Error> {
if 0 != unsafe { pcap_sys::pcap_activate(self.handle) } {
Err(pcap_util::convert_libpcap_error(self.handle))
} else {
Ok(self)
}
}
pub fn as_mut_ptr(&self) -> *mut pcap_sys::pcap_t {
self.handle
}
pub fn interrupted(&self) -> bool {
self.interrupted.lock().map(|l| *l).unwrap_or(true)
}
pub fn interrupt(&self) {
let interrupted = self
.interrupted
.lock()
.map(|mut l| {
*l = true;
false
})
.unwrap_or(true);
if !interrupted {
unsafe {
pcap_sys::pcap_breakloop(self.handle);
}
}
}
pub fn stats(&self) -> Result<Stats, Error> {
let mut stats: pcap_sys::pcap_stat = pcap_sys::pcap_stat {
ps_recv: 0,
ps_drop: 0,
ps_ifdrop: 0,
};
if 0 != unsafe { pcap_sys::pcap_stats(self.handle, &mut stats) } {
Err(pcap_util::convert_libpcap_error(self.handle))
} else {
let stats = Stats {
received: stats.ps_recv,
dropped_by_kernel: stats.ps_drop,
dropped_by_interface: stats.ps_ifdrop,
};
Ok(stats)
}
}
pub fn close(&self) {
unsafe { pcap_sys::pcap_close(self.handle) }
}
}
impl Drop for Handle {
fn drop(&mut self) {
self.close();
}
}
#[cfg(test)]
mod tests {
extern crate env_logger;
use super::*;
use std::path::PathBuf;
#[test]
fn open_file() {
let _ = env_logger::try_init();
let pcap_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("resources")
.join("canary.pcap");
let handle = Handle::file_capture(pcap_path.to_str().expect("No path found"));
assert!(handle.is_ok());
}
#[test]
fn lookup() {
let _ = env_logger::try_init();
let handle = Handle::lookup();
assert!(handle.is_ok());
}
#[test]
fn open_dead() {
let _ = env_logger::try_init();
let handle = Handle::dead(0, 0);
assert!(handle.is_ok());
}
#[test]
fn bpf_compile() {
let _ = env_logger::try_init();
let handle = Handle::dead(0, 1555).expect("Could not create dead handle");
let bpf = handle.compile_bpf(
"(not (net 192.168.0.0/16 and port 443)) and (not (host 192.1.2.3 and port 443))",
);
assert!(bpf.is_ok(), "{:?}", bpf);
}
}