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
extern crate regex;
extern crate nix;
pub mod error;
use std::process::{Command, Output};
use regex::Regex;
use error::{IPTResult, IPTError};
use std::fs::File;
use std::os::unix::io::AsRawFd;
use nix::fcntl::{flock, FlockArg};
use std::vec::Vec;
use std::ffi::OsStr;
pub struct IPTables {
pub cmd: &'static str,
pub has_check: bool,
pub has_wait: bool,
}
#[cfg(not(target_os = "linux"))]
pub fn new(is_ipv6: bool) -> IPTResult<IPTables> {
Err(IPTError::Other("iptables only works on Linux"))
}
#[cfg(target_os = "linux")]
pub fn new(is_ipv6: bool) -> IPTResult<IPTables> {
let cmd = if is_ipv6 {
"ip6tables"
} else {
"iptables"
};
let version_output = Command::new(cmd).arg("--version").output()?;
let re = Regex::new(r"v(\d+)\.(\d+)\.(\d+)")?;
let version_string = String::from_utf8_lossy(&version_output.stdout).into_owned();
let versions = re.captures(&version_string).ok_or("invalid version number")?;
let v_major = versions.get(1).ok_or("unable to get major version number")?.as_str().parse::<i32>()?;
let v_minor = versions.get(2).ok_or("unable to get minor version number")?.as_str().parse::<i32>()?;
let v_patch = versions.get(3).ok_or("unable to get patch version number")?.as_str().parse::<i32>()?;
Ok(IPTables {
cmd: cmd,
has_check: (v_major > 1) || (v_major == 1 && v_minor > 4) || (v_major == 1 && v_minor == 4 && v_patch > 10),
has_wait: (v_major > 1) || (v_major == 1 && v_minor > 4) || (v_major == 1 && v_minor == 4 && v_patch > 19),
})
}
impl IPTables {
#[cfg(target_os = "linux")]
pub fn exists(&self, table: &str, chain: &str, rule: &str) -> IPTResult<bool> {
if !self.has_check {
return self.exists_old_version(table, chain, rule);
}
match self.run(&[&["-t", table, "-C", chain], rule.split(" ").collect::<Vec<&str>>().as_slice()].concat()) {
Ok(output) => Ok(output.status.success()),
Err(err) => Err(err),
}
}
pub fn insert(&self, table: &str, chain: &str, rule: &str, position: i32) -> IPTResult<bool> {
match self.run(&[&["-t", table, "-I", chain, &position.to_string()], rule.split(" ").collect::<Vec<&str>>().as_slice()].concat()) {
Ok(output) => Ok(output.status.success()),
Err(err) => Err(err),
}
}
pub fn insert_unique(&self, table: &str, chain: &str, rule: &str, position: i32) -> IPTResult<bool> {
if self.exists(table, chain, rule)? {
return Err(IPTError::Other("the rule exists in the table/chain"))
}
self.insert(table, chain, rule, position)
}
pub fn replace(&self, table: &str, chain: &str, rule: &str, position: i32) -> IPTResult<bool> {
match self.run(&[&["-t", table, "-R", chain, &position.to_string()], rule.split(" ").collect::<Vec<&str>>().as_slice()].concat()) {
Ok(output) => Ok(output.status.success()),
Err(err) => Err(err),
}
}
pub fn append(&self, table: &str, chain: &str, rule: &str) -> IPTResult<bool> {
match self.run(&[&["-t", table, "-A", chain], rule.split(" ").collect::<Vec<&str>>().as_slice()].concat()) {
Ok(output) => Ok(output.status.success()),
Err(err) => Err(err),
}
}
pub fn append_unique(&self, table: &str, chain: &str, rule: &str) -> IPTResult<bool> {
if self.exists(table, chain, rule)? {
return Err(IPTError::Other("the rule exists in the table/chain"))
}
self.append(table, chain, rule)
}
pub fn append_replace(&self, table: &str, chain: &str, rule: &str) -> IPTResult<bool> {
if self.exists(table, chain, rule)? {
self.delete(table, chain, rule)?;
}
self.append(table, chain, rule)
}
pub fn delete(&self, table: &str, chain: &str, rule: &str) -> IPTResult<bool> {
match self.run(&[&["-t", table, "-D", chain], rule.split(" ").collect::<Vec<&str>>().as_slice()].concat()) {
Ok(output) => Ok(output.status.success()),
Err(err) => Err(err),
}
}
pub fn delete_all(&self, table: &str, chain: &str, rule: &str) -> IPTResult<bool> {
while self.exists(table, chain, rule)? {
self.delete(table, chain, rule)?;
}
Ok(true)
}
pub fn list(&self, table: &str, chain: &str) -> IPTResult<Vec<String>> {
self.get_list(&["-t", table, "-S", chain])
}
pub fn list_table(&self, table: &str) -> IPTResult<Vec<String>> {
self.get_list(&["-t", table, "-S"])
}
pub fn list_chains(&self, table: &str) -> IPTResult<Vec<String>> {
let mut list = Vec::new();
let output = String::from_utf8_lossy(&self.run(&["-t", table, "-S"])?.stdout).into_owned();
for item in output.trim().split("\n") {
let fields = item.split(" ").collect::<Vec<&str>>();
if fields.len() > 1 && (fields[0] == "-P" || fields[0] == "-N") {
list.push(fields[1].to_string());
}
}
Ok(list)
}
pub fn new_chain(&self, table: &str, chain: &str) -> IPTResult<bool> {
match self.run(&["-t", table, "-N", chain]) {
Ok(output) => Ok(output.status.success()),
Err(err) => Err(err),
}
}
pub fn flush_chain(&self, table: &str, chain: &str) -> IPTResult<bool> {
match self.run(&["-t", table, "-F", chain]) {
Ok(output) => Ok(output.status.success()),
Err(err) => Err(err),
}
}
pub fn rename_chain(&self, table: &str, old_chain: &str, new_chain: &str) -> IPTResult<bool> {
match self.run(&["-t", table, "-E", old_chain, new_chain]) {
Ok(output) => Ok(output.status.success()),
Err(err) => Err(err),
}
}
pub fn delete_chain(&self, table: &str, chain: &str) -> IPTResult<bool> {
match self.run(&["-t", table, "-X", chain]) {
Ok(output) => Ok(output.status.success()),
Err(err) => Err(err),
}
}
pub fn flush_table(&self, table: &str) -> IPTResult<bool> {
match self.run(&["-t", table, "-F"]) {
Ok(output) => Ok(output.status.success()),
Err(err) => Err(err),
}
}
fn exists_old_version(&self, table: &str, chain: &str, rule: &str) -> IPTResult<bool> {
match self.run(&["-t", table, "-S"]) {
Ok(output) => Ok(String::from_utf8_lossy(&output.stdout).into_owned().contains(&format!("-A {} {}", chain, rule))),
Err(err) => Err(err),
}
}
fn get_list<S: AsRef<OsStr>>(&self, args: &[S]) -> IPTResult<Vec<String>> {
let mut list = Vec::new();
let output = String::from_utf8_lossy(&self.run(args)?.stdout).into_owned();
for item in output.trim().split("\n") {
list.push(item.to_string())
}
Ok(list)
}
fn run<S: AsRef<OsStr>>(&self, args: &[S]) -> IPTResult<Output> {
let mut file_lock = None;
let mut output_cmd = Command::new(self.cmd);
let output;
if self.has_wait {
output = output_cmd.args(args).arg("--wait").output()?;
} else {
file_lock = Some(File::create("/var/run/xtables_old.lock")?);
let mut need_retry = true;
while need_retry {
match flock(file_lock.as_ref().unwrap().as_raw_fd(), FlockArg::LockExclusiveNonblock) {
Ok(_) => need_retry = false,
Err(e) => if e.errno() == nix::errno::EAGAIN {
need_retry = true;
} else {
return Err(IPTError::Nix(e));
},
}
}
output = output_cmd.args(args).output()?;
}
if !self.has_wait {
match file_lock {
Some(f) => drop(f),
None => (),
};
}
Ok(output)
}
}