Commits:
-
0b737404
by Pier Angelo Vendrame at 2026-11-11T20:25:11+01:00
fixup! TB 44806: Implement the tor integration in Rust.
TB 44930: Implement the commands on the Rust control port
Simplify how we handle compulsory group in regexes.
-
8c10dd07
by Pier Angelo Vendrame at 2026-11-11T20:25:11+01:00
fixup! TB 44806: Implement the tor integration in Rust.
TB 44930: Implement the commands on the Rust control port
Implement Debug for Command to be able to use .unwrap_err() in tests.
-
7788d5fa
by Pier Angelo Vendrame at 2026-11-11T20:25:12+01:00
fixup! TB 44806: Implement the tor integration in Rust.
TB 44930: Implement the commands on the Rust control port
Added docstrings to code that was previously merged.
-
136d1f61
by Elena at 2026-11-11T20:25:12+01:00
fixup! TB 44806: Implement the tor integration in Rust.
TB 44930: Implement the commands on the Rust control port
Implemented parsers for some GETINFO-based commands.
-
938c4cb0
by Elena at 2026-11-11T20:25:12+01:00
fixup! TB 44806: Implement the tor integration in Rust.
TB 44930: Implement the commands on the Rust control port
Implemented GETINFO commands.
-
64100cf5
by Elena at 2026-11-11T20:25:13+01:00
fixup! TB 44806: Implement the tor integration in Rust.
TB 44930: Implement the commands on the Rust control port
Implemented Onion auth parsers and commands.
23 changed files:
Changes:
Cargo.lock
| ... |
... |
@@ -8124,6 +8124,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" |
|
8124
|
8124
|
checksum = "5d4f6d1145dcb577acf783d4e601bc1d76a13337bb54e6233add580b07344c8b"
|
|
8125
|
8125
|
dependencies = [
|
|
8126
|
8126
|
"displaydoc",
|
|
|
8127
|
+ "serde",
|
|
8127
|
8128
|
"zerovec",
|
|
8128
|
8129
|
]
|
|
8129
|
8130
|
|
| ... |
... |
@@ -8262,6 +8263,7 @@ name = "tor_provider" |
|
8262
|
8263
|
version = "0.1.0"
|
|
8263
|
8264
|
dependencies = [
|
|
8264
|
8265
|
"bytes",
|
|
|
8266
|
+ "data-encoding",
|
|
8265
|
8267
|
"hex",
|
|
8266
|
8268
|
"itoa",
|
|
8267
|
8269
|
"lazy_static",
|
| ... |
... |
@@ -8269,7 +8271,10 @@ dependencies = [ |
|
8269
|
8271
|
"memchr",
|
|
8270
|
8272
|
"regex",
|
|
8271
|
8273
|
"serde",
|
|
|
8274
|
+ "sha3",
|
|
|
8275
|
+ "smallvec",
|
|
8272
|
8276
|
"thiserror 2.0.12",
|
|
|
8277
|
+ "tinystr",
|
|
8273
|
8278
|
]
|
|
8274
|
8279
|
|
|
8275
|
8280
|
[[package]]
|
toolkit/components/tor-integration/tor_provider/Cargo.toml
| ... |
... |
@@ -6,6 +6,7 @@ edition = "2021" |
|
6
|
6
|
|
|
7
|
7
|
[dependencies]
|
|
8
|
8
|
bytes = "1.4.0"
|
|
|
9
|
+data-encoding = "2.3.3"
|
|
9
|
10
|
hex = "0.4.3"
|
|
10
|
11
|
itoa = "1.0.15"
|
|
11
|
12
|
lazy_static = "1"
|
| ... |
... |
@@ -13,4 +14,7 @@ log = "0.4" |
|
13
|
14
|
memchr = "2.7.4"
|
|
14
|
15
|
regex = "1"
|
|
15
|
16
|
serde = { version = "1.0", features = ["derive"] }
|
|
|
17
|
+sha3 = "0.10.8"
|
|
|
18
|
+smallvec = { version = "1.15.1", features = ["serde"] }
|
|
16
|
19
|
thiserror = "2"
|
|
|
20
|
+tinystr = { version = "0.8.1", features = ["serde"] } |
toolkit/components/tor-integration/tor_provider/src/ctor/controller/commands/command.rs
| ... |
... |
@@ -3,9 +3,66 @@ |
|
3
|
3
|
// <http://opensource.org/licenses/MIT>, at your option. This file may not be
|
|
4
|
4
|
// copied, modified, or distributed except according to those terms.
|
|
5
|
5
|
|
|
|
6
|
+use std::fmt;
|
|
|
7
|
+
|
|
6
|
8
|
use crate::ctor::{controller::ControllerError, reply_parser::Reply};
|
|
7
|
9
|
|
|
8
|
10
|
pub struct Command<T> {
|
|
9
|
11
|
pub command: String,
|
|
10
|
12
|
pub handler: Box<dyn Fn(Reply) -> Result<T, ControllerError>>,
|
|
11
|
13
|
}
|
|
|
14
|
+
|
|
|
15
|
+impl<T> fmt::Debug for Command<T> {
|
|
|
16
|
+ /// Custom formatter that redacts the arguments, as they might contain
|
|
|
17
|
+ /// sensitive information, such as passwords or keys.
|
|
|
18
|
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
19
|
+ let mut split = self.command.splitn(2, ' ');
|
|
|
20
|
+ let mut command = split.next().unwrap_or_default().to_string();
|
|
|
21
|
+ if split.next().is_some() {
|
|
|
22
|
+ command.push_str(" ...");
|
|
|
23
|
+ }
|
|
|
24
|
+ if command.is_empty() {
|
|
|
25
|
+ command = String::from("(empty)");
|
|
|
26
|
+ }
|
|
|
27
|
+
|
|
|
28
|
+ f.debug_struct("Command")
|
|
|
29
|
+ .field("command", &command)
|
|
|
30
|
+ .field("handler", &"<handler>")
|
|
|
31
|
+ .finish()
|
|
|
32
|
+ }
|
|
|
33
|
+}
|
|
|
34
|
+
|
|
|
35
|
+#[cfg(test)]
|
|
|
36
|
+mod tests {
|
|
|
37
|
+ use super::*;
|
|
|
38
|
+
|
|
|
39
|
+ #[test]
|
|
|
40
|
+ fn command_fmt_is_redacted() {
|
|
|
41
|
+ {
|
|
|
42
|
+ let cmd = Command {
|
|
|
43
|
+ command: String::from("QUIT"),
|
|
|
44
|
+ handler: Box::new(|_| Ok(())),
|
|
|
45
|
+ };
|
|
|
46
|
+ let cmd_fmt = format!("{:?}", cmd);
|
|
|
47
|
+ assert!(cmd_fmt.contains("command: \"QUIT\""));
|
|
|
48
|
+ }
|
|
|
49
|
+ {
|
|
|
50
|
+ let password = "p4ssw0rd";
|
|
|
51
|
+ let cmd = Command {
|
|
|
52
|
+ command: format!("SETCONF Socks5ProxyPassword={}", password),
|
|
|
53
|
+ handler: Box::new(|_| Ok(())),
|
|
|
54
|
+ };
|
|
|
55
|
+ let cmd_fmt = format!("{:?}", cmd);
|
|
|
56
|
+ assert!(cmd_fmt.contains("command: \"SETCONF ...\""));
|
|
|
57
|
+ assert!(!cmd_fmt.contains(password));
|
|
|
58
|
+ }
|
|
|
59
|
+ {
|
|
|
60
|
+ let cmd = Command {
|
|
|
61
|
+ command: String::from(""),
|
|
|
62
|
+ handler: Box::new(|_| Ok(())),
|
|
|
63
|
+ };
|
|
|
64
|
+ let cmd_fmt = format!("{:?}", cmd);
|
|
|
65
|
+ assert!(cmd_fmt.contains("command: \"(empty)\""));
|
|
|
66
|
+ }
|
|
|
67
|
+ }
|
|
|
68
|
+} |
toolkit/components/tor-integration/tor_provider/src/ctor/controller/commands/get_info.rs
|
|
1
|
+// Licensed under the Apache License, Version 2.0,
|
|
|
2
|
+// <http://apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
3
|
+// <http://opensource.org/licenses/MIT>, at your option. This file may not be
|
|
|
4
|
+// copied, modified, or distributed except according to those terms.
|
|
|
5
|
+
|
|
|
6
|
+use std::net::IpAddr;
|
|
|
7
|
+use tinystr::TinyAsciiStr;
|
|
|
8
|
+
|
|
|
9
|
+use super::Command;
|
|
|
10
|
+use crate::ctor::{
|
|
|
11
|
+ controller::{parsers::*, types::*, ControllerError},
|
|
|
12
|
+ reply_parser::{DetailReplyLine, Reply},
|
|
|
13
|
+};
|
|
|
14
|
+
|
|
|
15
|
+pub fn bootstrap_phase() -> Result<Command<BootstrapStatus>, ControllerError> {
|
|
|
16
|
+ get_info_single(
|
|
|
17
|
+ String::from("status/bootstrap-phase"),
|
|
|
18
|
+ parse_bootstrap_status,
|
|
|
19
|
+ )
|
|
|
20
|
+}
|
|
|
21
|
+
|
|
|
22
|
+pub fn circuits() -> Result<Command<Vec<Circuit>>, ControllerError> {
|
|
|
23
|
+ get_info(String::from("circuit-status"), |lines| {
|
|
|
24
|
+ lines
|
|
|
25
|
+ .iter()
|
|
|
26
|
+ .filter_map(|line| parse_circuit_built(*line).transpose())
|
|
|
27
|
+ .collect()
|
|
|
28
|
+ })
|
|
|
29
|
+}
|
|
|
30
|
+
|
|
|
31
|
+pub fn net_listeners_socks() -> Result<Command<Vec<SocksListener>>, ControllerError> {
|
|
|
32
|
+ get_info_single(String::from("net/listeners/socks"), parse_socks_listeners)
|
|
|
33
|
+}
|
|
|
34
|
+
|
|
|
35
|
+pub fn node_addresses(node: NodeFingerprint) -> Result<Command<NodeAddresses>, ControllerError> {
|
|
|
36
|
+ get_info(
|
|
|
37
|
+ format!("ns/id/{}", hex::encode(node)),
|
|
|
38
|
+ addresses_from_status_info,
|
|
|
39
|
+ )
|
|
|
40
|
+}
|
|
|
41
|
+
|
|
|
42
|
+pub fn ip_to_country(ip: IpAddr) -> Result<Command<TinyAsciiStr<2>>, ControllerError> {
|
|
|
43
|
+ get_info_single(format!("ip-to-country/{}", ip), parse_country_code)
|
|
|
44
|
+}
|
|
|
45
|
+
|
|
|
46
|
+fn get_info<F, T>(key: String, converter: F) -> Result<Command<T>, ControllerError>
|
|
|
47
|
+where
|
|
|
48
|
+ F: Fn(&[&[u8]]) -> Result<T, ControllerError> + 'static,
|
|
|
49
|
+{
|
|
|
50
|
+ Ok(Command {
|
|
|
51
|
+ command: format!("GETINFO {}\r\n", key),
|
|
|
52
|
+ handler: Box::new(move |reply| parse_get_info(&key, &converter, reply)),
|
|
|
53
|
+ })
|
|
|
54
|
+}
|
|
|
55
|
+
|
|
|
56
|
+fn get_info_single<F, T>(key: String, converter: F) -> Result<Command<T>, ControllerError>
|
|
|
57
|
+where
|
|
|
58
|
+ F: Fn(&[u8]) -> Result<T, ControllerError> + 'static,
|
|
|
59
|
+{
|
|
|
60
|
+ get_info(key, move |lines| {
|
|
|
61
|
+ if lines.len() != 1 {
|
|
|
62
|
+ Err(ControllerError::MalformedReply(String::from(
|
|
|
63
|
+ "Expected a single line on the reply.",
|
|
|
64
|
+ )))
|
|
|
65
|
+ } else {
|
|
|
66
|
+ converter(lines[0])
|
|
|
67
|
+ }
|
|
|
68
|
+ })
|
|
|
69
|
+}
|
|
|
70
|
+
|
|
|
71
|
+fn parse_get_info<S, F, T>(key: S, converter: &F, reply: Reply) -> Result<T, ControllerError>
|
|
|
72
|
+where
|
|
|
73
|
+ S: AsRef<str>,
|
|
|
74
|
+ F: Fn(&[&[u8]]) -> Result<T, ControllerError> + 'static,
|
|
|
75
|
+{
|
|
|
76
|
+ if let Some(e) = ControllerError::from_reply(&reply) {
|
|
|
77
|
+ return Err(e);
|
|
|
78
|
+ }
|
|
|
79
|
+
|
|
|
80
|
+ let k = key.as_ref().as_bytes();
|
|
|
81
|
+
|
|
|
82
|
+ for line in reply.details().iter() {
|
|
|
83
|
+ match line {
|
|
|
84
|
+ DetailReplyLine::MidReplyLine { code, line } => {
|
|
|
85
|
+ if *code != 250 {
|
|
|
86
|
+ continue;
|
|
|
87
|
+ }
|
|
|
88
|
+ if line.len() < k.len() + 1 {
|
|
|
89
|
+ continue;
|
|
|
90
|
+ }
|
|
|
91
|
+ if line[0..k.len()].eq_ignore_ascii_case(k) && line[k.len()] == b'=' {
|
|
|
92
|
+ return converter(&[&line[(k.len() + 1)..]]);
|
|
|
93
|
+ }
|
|
|
94
|
+ }
|
|
|
95
|
+ DetailReplyLine::DataReplyLine { code, lines } => {
|
|
|
96
|
+ if *code != 250 {
|
|
|
97
|
+ continue;
|
|
|
98
|
+ }
|
|
|
99
|
+ let first = &lines[0];
|
|
|
100
|
+ if first.len() == k.len() + 1
|
|
|
101
|
+ && first[0..k.len()].eq_ignore_ascii_case(k)
|
|
|
102
|
+ && first[k.len()] == b'='
|
|
|
103
|
+ {
|
|
|
104
|
+ let lines: Vec<&[u8]> = lines[1..].iter().map(|b| &b[..]).collect();
|
|
|
105
|
+ return converter(&lines);
|
|
|
106
|
+ }
|
|
|
107
|
+ }
|
|
|
108
|
+ }
|
|
|
109
|
+ }
|
|
|
110
|
+
|
|
|
111
|
+ // We should never arrive here. Instead, tor should send 552.
|
|
|
112
|
+ Err(ControllerError::KeyNotFound(key.as_ref().into()))
|
|
|
113
|
+}
|
|
|
114
|
+
|
|
|
115
|
+#[cfg(test)]
|
|
|
116
|
+mod tests {
|
|
|
117
|
+ use std::assert_matches;
|
|
|
118
|
+
|
|
|
119
|
+ use super::*;
|
|
|
120
|
+ use crate::ctor::reply_parser::make_reply;
|
|
|
121
|
+
|
|
|
122
|
+ fn identity_converter(v: &[&[u8]]) -> Result<Vec<Vec<u8>>, ControllerError> {
|
|
|
123
|
+ Ok(v.iter().map(|s| Vec::from(*s)).collect())
|
|
|
124
|
+ }
|
|
|
125
|
+
|
|
|
126
|
+ #[test]
|
|
|
127
|
+ fn mid_line() {
|
|
|
128
|
+ assert_eq!(
|
|
|
129
|
+ parse_get_info(
|
|
|
130
|
+ "version",
|
|
|
131
|
+ &identity_converter,
|
|
|
132
|
+ make_reply(b"250-version=0.5.0.0-alpha-dev\r\n250 OK\r\n")
|
|
|
133
|
+ )
|
|
|
134
|
+ .unwrap(),
|
|
|
135
|
+ &[b"0.5.0.0-alpha-dev"]
|
|
|
136
|
+ );
|
|
|
137
|
+ }
|
|
|
138
|
+
|
|
|
139
|
+ #[test]
|
|
|
140
|
+ fn data_line() {
|
|
|
141
|
+ assert_eq!(
|
|
|
142
|
+ parse_get_info(
|
|
|
143
|
+ "test",
|
|
|
144
|
+ &identity_converter,
|
|
|
145
|
+ make_reply(b"250+test=\r\n123\r\n456\r\n.\r\n250 OK\r\n")
|
|
|
146
|
+ )
|
|
|
147
|
+ .unwrap(),
|
|
|
148
|
+ vec![b"123", b"456"]
|
|
|
149
|
+ );
|
|
|
150
|
+ }
|
|
|
151
|
+
|
|
|
152
|
+ #[test]
|
|
|
153
|
+ fn data_line_empty() {
|
|
|
154
|
+ assert_eq!(
|
|
|
155
|
+ parse_get_info(
|
|
|
156
|
+ "test",
|
|
|
157
|
+ &identity_converter,
|
|
|
158
|
+ make_reply(b"250+test=\r\n.\r\n250 OK\r\n")
|
|
|
159
|
+ )
|
|
|
160
|
+ .unwrap(),
|
|
|
161
|
+ Vec::<&[u8]>::new()
|
|
|
162
|
+ );
|
|
|
163
|
+ }
|
|
|
164
|
+
|
|
|
165
|
+ #[test]
|
|
|
166
|
+ fn mid_line_prefix() {
|
|
|
167
|
+ assert_matches!(
|
|
|
168
|
+ parse_get_info(
|
|
|
169
|
+ "version",
|
|
|
170
|
+ &identity_converter,
|
|
|
171
|
+ make_reply(b"250-version__=0.5.0.0-alpha-dev\r\n250 OK\r\n")
|
|
|
172
|
+ )
|
|
|
173
|
+ .unwrap_err(),
|
|
|
174
|
+ ControllerError::KeyNotFound(_)
|
|
|
175
|
+ );
|
|
|
176
|
+ }
|
|
|
177
|
+
|
|
|
178
|
+ #[test]
|
|
|
179
|
+ fn data_line_prefix() {
|
|
|
180
|
+ assert_matches!(
|
|
|
181
|
+ parse_get_info(
|
|
|
182
|
+ "test",
|
|
|
183
|
+ &identity_converter,
|
|
|
184
|
+ make_reply(b"250+test__=\r\n123\r\n456\r\n.\r\n250 OK\r\n")
|
|
|
185
|
+ )
|
|
|
186
|
+ .unwrap_err(),
|
|
|
187
|
+ ControllerError::KeyNotFound(_)
|
|
|
188
|
+ );
|
|
|
189
|
+ }
|
|
|
190
|
+
|
|
|
191
|
+ #[test]
|
|
|
192
|
+ fn short_line_long_key() {
|
|
|
193
|
+ assert_matches!(
|
|
|
194
|
+ parse_get_info(
|
|
|
195
|
+ "averyverylongkey",
|
|
|
196
|
+ &identity_converter,
|
|
|
197
|
+ make_reply(b"250+short=\r\n123\r\n456\r\n.\r\n250 OK\r\n")
|
|
|
198
|
+ )
|
|
|
199
|
+ .unwrap_err(),
|
|
|
200
|
+ ControllerError::KeyNotFound(_)
|
|
|
201
|
+ );
|
|
|
202
|
+ assert_matches!(
|
|
|
203
|
+ parse_get_info(
|
|
|
204
|
+ "averyverylooooooooooongkey",
|
|
|
205
|
+ &identity_converter,
|
|
|
206
|
+ make_reply(b"250-short=\r\n250 OK\r\n")
|
|
|
207
|
+ )
|
|
|
208
|
+ .unwrap_err(),
|
|
|
209
|
+ ControllerError::KeyNotFound(_)
|
|
|
210
|
+ );
|
|
|
211
|
+ }
|
|
|
212
|
+
|
|
|
213
|
+ #[test]
|
|
|
214
|
+ fn tor_error() {
|
|
|
215
|
+ assert_eq!(
|
|
|
216
|
+ parse_get_info(
|
|
|
217
|
+ "test",
|
|
|
218
|
+ &identity_converter,
|
|
|
219
|
+ make_reply(b"552 Unrecognized key \"test\"\r\n")
|
|
|
220
|
+ )
|
|
|
221
|
+ .unwrap_err(),
|
|
|
222
|
+ ControllerError::TorError {
|
|
|
223
|
+ code: 552,
|
|
|
224
|
+ message: String::from("Unrecognized key \"test\"")
|
|
|
225
|
+ }
|
|
|
226
|
+ );
|
|
|
227
|
+ }
|
|
|
228
|
+
|
|
|
229
|
+ #[test]
|
|
|
230
|
+ fn error_in_success() {
|
|
|
231
|
+ // This case should not be possible in GETINFO.
|
|
|
232
|
+ // But we want to be sure we can handle it (as a key not found), just in
|
|
|
233
|
+ // case.
|
|
|
234
|
+ assert_matches!(
|
|
|
235
|
+ parse_get_info(
|
|
|
236
|
+ "test",
|
|
|
237
|
+ &identity_converter,
|
|
|
238
|
+ make_reply(b"552-test=0.5.0.0-alpha-dev\r\n250 OK\r\n")
|
|
|
239
|
+ )
|
|
|
240
|
+ .unwrap_err(),
|
|
|
241
|
+ ControllerError::KeyNotFound(_)
|
|
|
242
|
+ );
|
|
|
243
|
+ assert_matches!(
|
|
|
244
|
+ parse_get_info(
|
|
|
245
|
+ "test",
|
|
|
246
|
+ &identity_converter,
|
|
|
247
|
+ make_reply(b"552-test=\r\n250 OK\r\n")
|
|
|
248
|
+ )
|
|
|
249
|
+ .unwrap_err(),
|
|
|
250
|
+ ControllerError::KeyNotFound(_)
|
|
|
251
|
+ );
|
|
|
252
|
+ }
|
|
|
253
|
+
|
|
|
254
|
+ #[test]
|
|
|
255
|
+ fn only_end_line() {
|
|
|
256
|
+ assert_matches!(
|
|
|
257
|
+ parse_get_info(
|
|
|
258
|
+ "test",
|
|
|
259
|
+ &identity_converter,
|
|
|
260
|
+ make_reply(b"250 OK\r\n")
|
|
|
261
|
+ )
|
|
|
262
|
+ .unwrap_err(),
|
|
|
263
|
+ ControllerError::KeyNotFound(_)
|
|
|
264
|
+ );
|
|
|
265
|
+ }
|
|
|
266
|
+} |
toolkit/components/tor-integration/tor_provider/src/ctor/controller/commands/mod.rs
| ... |
... |
@@ -6,6 +6,10 @@ |
|
6
|
6
|
mod authenticate;
|
|
7
|
7
|
mod command;
|
|
8
|
8
|
pub mod get_conf;
|
|
|
9
|
+pub mod get_info;
|
|
|
10
|
+mod onion_auth_add;
|
|
|
11
|
+mod onion_auth_remove;
|
|
|
12
|
+mod onion_auth_view_keys;
|
|
9
|
13
|
mod reset_conf;
|
|
10
|
14
|
mod save_conf;
|
|
11
|
15
|
mod set_conf;
|
| ... |
... |
@@ -15,6 +19,9 @@ mod take_ownership; |
|
15
|
19
|
|
|
16
|
20
|
pub use authenticate::authenticate;
|
|
17
|
21
|
pub use command::Command;
|
|
|
22
|
+pub use onion_auth_add::onion_auth_add;
|
|
|
23
|
+pub use onion_auth_remove::onion_auth_remove;
|
|
|
24
|
+pub use onion_auth_view_keys::onion_auth_view_keys;
|
|
18
|
25
|
pub use reset_conf::reset_owning_controller_process;
|
|
19
|
26
|
pub use save_conf::save_conf;
|
|
20
|
27
|
pub use set_conf::set_conf;
|
toolkit/components/tor-integration/tor_provider/src/ctor/controller/commands/onion_auth_add.rs
|
|
1
|
+// Licensed under the Apache License, Version 2.0,
|
|
|
2
|
+// <http://apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
3
|
+// <http://opensource.org/licenses/MIT>, at your option. This file may not be
|
|
|
4
|
+// copied, modified, or distributed except according to those terms.
|
|
|
5
|
+
|
|
|
6
|
+use lazy_static::lazy_static;
|
|
|
7
|
+use regex::bytes::Regex;
|
|
|
8
|
+
|
|
|
9
|
+use super::Command;
|
|
|
10
|
+use crate::ctor::controller::{parsers::parse_ack, types::*, ControllerError};
|
|
|
11
|
+
|
|
|
12
|
+lazy_static! {
|
|
|
13
|
+ // This is not a strict base64 regex, but we are intrested only in making
|
|
|
14
|
+ // sure user input does not allow command injection.
|
|
|
15
|
+ static ref BASE64ISH_REGEX: Regex =
|
|
|
16
|
+ Regex::new(r"^[A-Za-z0-9+/]*={0,3}$").expect("The regex is hardcoded, it should be good.");
|
|
|
17
|
+}
|
|
|
18
|
+
|
|
|
19
|
+pub fn onion_auth_add(
|
|
|
20
|
+ address: HSAddress,
|
|
|
21
|
+ key: &[u8],
|
|
|
22
|
+ permanent: bool,
|
|
|
23
|
+) -> Result<Command<u16>, ControllerError> {
|
|
|
24
|
+ if !BASE64ISH_REGEX.is_match(key) {
|
|
|
25
|
+ return Err(ControllerError::InvalidArgument(String::from(
|
|
|
26
|
+ "the key is not in base64",
|
|
|
27
|
+ )));
|
|
|
28
|
+ }
|
|
|
29
|
+ let key = str::from_utf8(key).map_err(|e| ControllerError::InvalidArgument(e.to_string()))?;
|
|
|
30
|
+ let flags = if permanent { " Flags=Permanent" } else { "" };
|
|
|
31
|
+ let command = format!(
|
|
|
32
|
+ "ONION_CLIENT_AUTH_ADD {} x25519:{}{}\r\n",
|
|
|
33
|
+ address.as_ref(),
|
|
|
34
|
+ key,
|
|
|
35
|
+ flags
|
|
|
36
|
+ );
|
|
|
37
|
+ Ok(Command {
|
|
|
38
|
+ command,
|
|
|
39
|
+ handler: Box::new(parse_ack),
|
|
|
40
|
+ })
|
|
|
41
|
+}
|
|
|
42
|
+
|
|
|
43
|
+#[cfg(test)]
|
|
|
44
|
+mod tests {
|
|
|
45
|
+ use std::assert_matches;
|
|
|
46
|
+
|
|
|
47
|
+ use super::*;
|
|
|
48
|
+
|
|
|
49
|
+ #[test]
|
|
|
50
|
+ fn permanent() {
|
|
|
51
|
+ let command = onion_auth_add(
|
|
|
52
|
+ HSAddress::from_str("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd")
|
|
|
53
|
+ .unwrap(),
|
|
|
54
|
+ b"theKEYinbase64",
|
|
|
55
|
+ true,
|
|
|
56
|
+ )
|
|
|
57
|
+ .unwrap();
|
|
|
58
|
+ assert!(command.command.to_lowercase().contains("flags=permanent"));
|
|
|
59
|
+ }
|
|
|
60
|
+
|
|
|
61
|
+ #[test]
|
|
|
62
|
+ fn not_permanent() {
|
|
|
63
|
+ let command = onion_auth_add(
|
|
|
64
|
+ HSAddress::from_str("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd")
|
|
|
65
|
+ .unwrap(),
|
|
|
66
|
+ b"theKEYinbase64",
|
|
|
67
|
+ false,
|
|
|
68
|
+ )
|
|
|
69
|
+ .unwrap();
|
|
|
70
|
+ assert!(!command.command.to_lowercase().contains("permanent"));
|
|
|
71
|
+ }
|
|
|
72
|
+
|
|
|
73
|
+ #[test]
|
|
|
74
|
+ fn pad_and_unpadded() {
|
|
|
75
|
+ // Tor is liberal about the necessity of padding, so make sure that
|
|
|
76
|
+ // padded strings are accepted by us even when not padded.
|
|
|
77
|
+ assert!(onion_auth_add(
|
|
|
78
|
+ HSAddress::from_str("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd")
|
|
|
79
|
+ .unwrap(),
|
|
|
80
|
+ b"SGVsbG8sIHdvcmxkIQo=",
|
|
|
81
|
+ false,
|
|
|
82
|
+ )
|
|
|
83
|
+ .is_ok());
|
|
|
84
|
+ assert!(onion_auth_add(
|
|
|
85
|
+ HSAddress::from_str("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd")
|
|
|
86
|
+ .unwrap(),
|
|
|
87
|
+ b"SGVsbG8sIHdvcmxkIQo",
|
|
|
88
|
+ false,
|
|
|
89
|
+ )
|
|
|
90
|
+ .is_ok());
|
|
|
91
|
+ }
|
|
|
92
|
+
|
|
|
93
|
+ #[test]
|
|
|
94
|
+ fn reject_invalid_base64() {
|
|
|
95
|
+ assert_matches!(
|
|
|
96
|
+ onion_auth_add(
|
|
|
97
|
+ HSAddress::from_str("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd")
|
|
|
98
|
+ .unwrap(),
|
|
|
99
|
+ b"NotBase64!!!",
|
|
|
100
|
+ true,
|
|
|
101
|
+ )
|
|
|
102
|
+ .unwrap_err(),
|
|
|
103
|
+ ControllerError::InvalidArgument(_)
|
|
|
104
|
+ );
|
|
|
105
|
+ }
|
|
|
106
|
+} |
toolkit/components/tor-integration/tor_provider/src/ctor/controller/commands/onion_auth_remove.rs
|
|
1
|
+// Licensed under the Apache License, Version 2.0,
|
|
|
2
|
+// <http://apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
3
|
+// <http://opensource.org/licenses/MIT>, at your option. This file may not be
|
|
|
4
|
+// copied, modified, or distributed except according to those terms.
|
|
|
5
|
+
|
|
|
6
|
+use super::Command;
|
|
|
7
|
+use crate::ctor::controller::{parsers::parse_ack, types::*, ControllerError};
|
|
|
8
|
+
|
|
|
9
|
+pub fn onion_auth_remove(address: HSAddress) -> Result<Command<u16>, ControllerError> {
|
|
|
10
|
+ Ok(Command {
|
|
|
11
|
+ command: format!("ONION_CLIENT_AUTH_REMOVE {}\r\n", address.as_ref()),
|
|
|
12
|
+ handler: Box::new(parse_ack),
|
|
|
13
|
+ })
|
|
|
14
|
+} |
toolkit/components/tor-integration/tor_provider/src/ctor/controller/commands/onion_auth_view_keys.rs
|
|
1
|
+// Licensed under the Apache License, Version 2.0,
|
|
|
2
|
+// <http://apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
3
|
+// <http://opensource.org/licenses/MIT>, at your option. This file may not be
|
|
|
4
|
+// copied, modified, or distributed except according to those terms.
|
|
|
5
|
+
|
|
|
6
|
+use super::Command;
|
|
|
7
|
+use crate::ctor::controller::{parsers::parse_onion_client_auth_view, types::*, ControllerError};
|
|
|
8
|
+
|
|
|
9
|
+pub fn onion_auth_view_keys() -> Result<Command<Vec<OnionClientAuth>>, ControllerError> {
|
|
|
10
|
+ Ok(Command {
|
|
|
11
|
+ command: String::from("ONION_CLIENT_AUTH_VIEW\r\n"),
|
|
|
12
|
+ handler: Box::new(parse_onion_client_auth_view),
|
|
|
13
|
+ })
|
|
|
14
|
+} |
toolkit/components/tor-integration/tor_provider/src/ctor/controller/controller.rs
| ... |
... |
@@ -4,6 +4,8 @@ |
|
4
|
4
|
// copied, modified, or distributed except according to those terms.
|
|
5
|
5
|
|
|
6
|
6
|
use bytes::Bytes;
|
|
|
7
|
+use std::net::IpAddr;
|
|
|
8
|
+use tinystr::TinyAsciiStr;
|
|
7
|
9
|
|
|
8
|
10
|
use super::{
|
|
9
|
11
|
commands::{self, Command},
|
| ... |
... |
@@ -115,14 +117,73 @@ impl<CP: ControlPortInterface> TorController<CP> { |
|
115
|
117
|
self.send_command(commands::save_conf(), handler);
|
|
116
|
118
|
}
|
|
117
|
119
|
|
|
118
|
|
- pub fn get_bridges(&self, handler: Box<dyn FnOnce(Result<Vec<Bridge>, ControllerError>)>) {
|
|
119
|
|
- self.send_command(commands::get_conf::bridges(), handler);
|
|
|
120
|
+ pub fn get_bootstrap_phase(
|
|
|
121
|
+ &self,
|
|
|
122
|
+ handler: Box<dyn FnOnce(Result<BootstrapStatus, ControllerError>)>,
|
|
|
123
|
+ ) {
|
|
|
124
|
+ self.send_command(commands::get_info::bootstrap_phase(), handler);
|
|
|
125
|
+ }
|
|
|
126
|
+
|
|
|
127
|
+ pub fn get_socks_listeners(
|
|
|
128
|
+ &self,
|
|
|
129
|
+ handler: Box<dyn FnOnce(Result<Vec<SocksListener>, ControllerError>)>,
|
|
|
130
|
+ ) {
|
|
|
131
|
+ self.send_command(commands::get_info::net_listeners_socks(), handler);
|
|
120
|
132
|
}
|
|
121
|
133
|
|
|
122
|
134
|
// Circuit display
|
|
123
|
135
|
|
|
|
136
|
+ pub fn get_circuits(&self, handler: Box<dyn FnOnce(Result<Vec<Circuit>, ControllerError>)>) {
|
|
|
137
|
+ self.send_command(commands::get_info::circuits(), handler);
|
|
|
138
|
+ }
|
|
|
139
|
+
|
|
|
140
|
+ pub fn get_node_addresses(
|
|
|
141
|
+ &self,
|
|
|
142
|
+ node: NodeFingerprint,
|
|
|
143
|
+ handler: Box<dyn FnOnce(Result<NodeAddresses, ControllerError>)>,
|
|
|
144
|
+ ) {
|
|
|
145
|
+ self.send_command(commands::get_info::node_addresses(node), handler);
|
|
|
146
|
+ }
|
|
|
147
|
+
|
|
|
148
|
+ pub fn get_ip_country(
|
|
|
149
|
+ &self,
|
|
|
150
|
+ ip: IpAddr,
|
|
|
151
|
+ handler: Box<dyn FnOnce(Result<TinyAsciiStr<2>, ControllerError>)>,
|
|
|
152
|
+ ) {
|
|
|
153
|
+ self.send_command(commands::get_info::ip_to_country(ip), handler);
|
|
|
154
|
+ }
|
|
|
155
|
+
|
|
|
156
|
+ pub fn get_bridges(&self, handler: Box<dyn FnOnce(Result<Vec<Bridge>, ControllerError>)>) {
|
|
|
157
|
+ self.send_command(commands::get_conf::bridges(), handler);
|
|
|
158
|
+ }
|
|
|
159
|
+
|
|
124
|
160
|
// Onion authentication
|
|
125
|
161
|
|
|
|
162
|
+ pub fn onion_auth_view_keys(
|
|
|
163
|
+ &self,
|
|
|
164
|
+ handler: Box<dyn FnOnce(Result<Vec<OnionClientAuth>, ControllerError>)>,
|
|
|
165
|
+ ) {
|
|
|
166
|
+ self.send_command(commands::onion_auth_view_keys(), handler);
|
|
|
167
|
+ }
|
|
|
168
|
+
|
|
|
169
|
+ pub fn onion_auth_add(
|
|
|
170
|
+ &self,
|
|
|
171
|
+ address: HSAddress,
|
|
|
172
|
+ key: &[u8],
|
|
|
173
|
+ permanent: bool,
|
|
|
174
|
+ handler: Box<dyn FnOnce(Result<u16, ControllerError>)>,
|
|
|
175
|
+ ) {
|
|
|
176
|
+ self.send_command(commands::onion_auth_add(address, key, permanent), handler);
|
|
|
177
|
+ }
|
|
|
178
|
+
|
|
|
179
|
+ pub fn onion_auth_remove(
|
|
|
180
|
+ &self,
|
|
|
181
|
+ address: HSAddress,
|
|
|
182
|
+ handler: Box<dyn FnOnce(Result<u16, ControllerError>)>,
|
|
|
183
|
+ ) {
|
|
|
184
|
+ self.send_command(commands::onion_auth_remove(address), handler);
|
|
|
185
|
+ }
|
|
|
186
|
+
|
|
126
|
187
|
// Miscellaneous
|
|
127
|
188
|
|
|
128
|
189
|
pub fn get_pluggable_transports(
|
toolkit/components/tor-integration/tor_provider/src/ctor/controller/error.rs
| ... |
... |
@@ -5,6 +5,7 @@ |
|
5
|
5
|
|
|
6
|
6
|
use thiserror::Error;
|
|
7
|
7
|
|
|
|
8
|
+use super::OnionValidationError;
|
|
8
|
9
|
use crate::ctor::{
|
|
9
|
10
|
control_port::ControlPortError,
|
|
10
|
11
|
reply_parser::{Reply, ReplyError},
|
| ... |
... |
@@ -34,6 +35,8 @@ pub enum ControllerError { |
|
34
|
35
|
MalformedReply(String),
|
|
35
|
36
|
#[error("the argument passed to the command was not valid: {0}")]
|
|
36
|
37
|
InvalidArgument(String),
|
|
|
38
|
+ #[error("invalid onion address: {0}")]
|
|
|
39
|
+ InvalidOnionAddress(#[from] OnionValidationError),
|
|
37
|
40
|
}
|
|
38
|
41
|
|
|
39
|
42
|
impl ControllerError {
|
toolkit/components/tor-integration/tor_provider/src/ctor/controller/parsers/bootstrap_status.rs
|
|
1
|
+// Licensed under the Apache License, Version 2.0,
|
|
|
2
|
+// <http://apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
3
|
+// <http://opensource.org/licenses/MIT>, at your option. This file may not be
|
|
|
4
|
+// copied, modified, or distributed except according to those terms.
|
|
|
5
|
+
|
|
|
6
|
+use lazy_static::lazy_static;
|
|
|
7
|
+use regex::bytes::{Regex, RegexBuilder};
|
|
|
8
|
+
|
|
|
9
|
+use super::{parse_key_value_pairs, tor_unescape};
|
|
|
10
|
+use crate::ctor::controller::{types::*, ControllerError};
|
|
|
11
|
+
|
|
|
12
|
+lazy_static! {
|
|
|
13
|
+ static ref STATUS_REGEX: Regex = RegexBuilder::new(r"^(NOTICE|WARN) BOOTSTRAP (.+)$")
|
|
|
14
|
+ .case_insensitive(true)
|
|
|
15
|
+ .build()
|
|
|
16
|
+ .expect("The regex is hardcoded, it should be good.");
|
|
|
17
|
+}
|
|
|
18
|
+
|
|
|
19
|
+const STATUS_KEYWORDS: &[&'static str] =
|
|
|
20
|
+ &["PROGRESS", "TAG", "SUMMARY", "RECOMMENDATION", "REASON"];
|
|
|
21
|
+
|
|
|
22
|
+/// Parse a STATUS_CLIENT event.
|
|
|
23
|
+///
|
|
|
24
|
+/// We handle events that have this format:
|
|
|
25
|
+/// NOTICE BOOTSTRAP PROGRESS=n TAG=keyword SUMMARY="Human readable string" REASON=keyword
|
|
|
26
|
+/// WARN BOOTSTRAP PROGRESS=n TAG=keyword SUMMARY="Human readable string" REASON=keyword
|
|
|
27
|
+/// WARN BOOTSTRAP PROGRESS=n TAG=keyword SUMMARY="Human readable string" REASON=keyword RECOMMENDATION=warn
|
|
|
28
|
+pub fn parse_bootstrap_status(value: &[u8]) -> Result<BootstrapStatus, ControllerError> {
|
|
|
29
|
+ let groups = STATUS_REGEX
|
|
|
30
|
+ .captures(value)
|
|
|
31
|
+ .ok_or_else(|| ControllerError::WrongFormat(String::from_utf8_lossy(value).into_owned()))?;
|
|
|
32
|
+
|
|
|
33
|
+ let severity = groups[1].to_ascii_uppercase();
|
|
|
34
|
+ let severity = match severity.as_slice() {
|
|
|
35
|
+ b"NOTICE" => StatusSeverity::Notice,
|
|
|
36
|
+ b"WARN" => StatusSeverity::Warn,
|
|
|
37
|
+ _ => {
|
|
|
38
|
+ // Notice: the regex should make this case impossible...
|
|
|
39
|
+ return Err(ControllerError::MalformedReply(format!(
|
|
|
40
|
+ "unknown severity: {}",
|
|
|
41
|
+ String::from_utf8_lossy(&severity)
|
|
|
42
|
+ )));
|
|
|
43
|
+ }
|
|
|
44
|
+ };
|
|
|
45
|
+
|
|
|
46
|
+ let arguments = parse_key_value_pairs(
|
|
|
47
|
+ groups
|
|
|
48
|
+ .get(2)
|
|
|
49
|
+ .ok_or_else(|| {
|
|
|
50
|
+ ControllerError::MalformedReply(String::from(
|
|
|
51
|
+ "the bootstrap status does not contain the compulsory values",
|
|
|
52
|
+ ))
|
|
|
53
|
+ })?
|
|
|
54
|
+ .as_bytes(),
|
|
|
55
|
+ STATUS_KEYWORDS,
|
|
|
56
|
+ )?;
|
|
|
57
|
+
|
|
|
58
|
+ let progress = arguments
|
|
|
59
|
+ .get("PROGRESS")
|
|
|
60
|
+ .ok_or_else(|| ControllerError::KeyNotFound(String::from("progress")))
|
|
|
61
|
+ .and_then(|v| str::from_utf8(v).map_err(|e| ControllerError::MalformedReply(e.to_string())))
|
|
|
62
|
+ .and_then(|v| {
|
|
|
63
|
+ v.parse().map_err(|e| {
|
|
|
64
|
+ ControllerError::MalformedReply(format!("progress is not an integer: {}", e))
|
|
|
65
|
+ })
|
|
|
66
|
+ })?;
|
|
|
67
|
+ if progress > 100 {
|
|
|
68
|
+ return Err(ControllerError::MalformedReply(format!(
|
|
|
69
|
+ "progress exceeds 100: {}",
|
|
|
70
|
+ progress
|
|
|
71
|
+ )));
|
|
|
72
|
+ }
|
|
|
73
|
+
|
|
|
74
|
+ // For robustness, we do not check this value.
|
|
|
75
|
+ let tag = String::from_utf8_lossy(
|
|
|
76
|
+ arguments
|
|
|
77
|
+ .get("TAG")
|
|
|
78
|
+ .ok_or_else(|| ControllerError::KeyNotFound(String::from("tag")))?,
|
|
|
79
|
+ )
|
|
|
80
|
+ .into_owned();
|
|
|
81
|
+ let summary = String::from_utf8_lossy(
|
|
|
82
|
+ &tor_unescape(
|
|
|
83
|
+ arguments
|
|
|
84
|
+ .get("SUMMARY")
|
|
|
85
|
+ .ok_or_else(|| ControllerError::KeyNotFound(String::from("summary")))?,
|
|
|
86
|
+ )
|
|
|
87
|
+ .map_err(|e| ControllerError::MalformedReply(e.to_string()))?,
|
|
|
88
|
+ )
|
|
|
89
|
+ .into_owned();
|
|
|
90
|
+ let reason = arguments
|
|
|
91
|
+ .get("REASON")
|
|
|
92
|
+ .map(|r| String::from_utf8_lossy(r).into_owned());
|
|
|
93
|
+ let should_warn = arguments
|
|
|
94
|
+ .get("RECOMMENDATION")
|
|
|
95
|
+ // Recommendation can be either "warn" or "ignore".
|
|
|
96
|
+ // We chose to match warn as we want to be sure before issuing a warn,
|
|
|
97
|
+ // as connection assist will interrupt the bootstrap.
|
|
|
98
|
+ .map_or(false, |r| r.eq_ignore_ascii_case(b"warn"));
|
|
|
99
|
+
|
|
|
100
|
+ Ok(BootstrapStatus {
|
|
|
101
|
+ severity,
|
|
|
102
|
+ progress,
|
|
|
103
|
+ tag,
|
|
|
104
|
+ summary,
|
|
|
105
|
+ reason,
|
|
|
106
|
+ should_warn,
|
|
|
107
|
+ })
|
|
|
108
|
+}
|
|
|
109
|
+
|
|
|
110
|
+#[cfg(test)]
|
|
|
111
|
+mod tests {
|
|
|
112
|
+ use super::*;
|
|
|
113
|
+
|
|
|
114
|
+ use std::assert_matches;
|
|
|
115
|
+
|
|
|
116
|
+ #[test]
|
|
|
117
|
+ fn without_recommendation() {
|
|
|
118
|
+ let line = b"NOTICE BOOTSTRAP PROGRESS=10 TAG=conn_done SUMMARY=\"Connected to a relay\"";
|
|
|
119
|
+ let status = parse_bootstrap_status(line).unwrap();
|
|
|
120
|
+ assert_eq!(status.severity, StatusSeverity::Notice);
|
|
|
121
|
+ assert_eq!(status.progress, 10);
|
|
|
122
|
+ assert_eq!(status.tag, "conn_done");
|
|
|
123
|
+ assert_eq!(status.summary, "Connected to a relay");
|
|
|
124
|
+ assert!(status.reason.is_none());
|
|
|
125
|
+ assert!(!status.should_warn);
|
|
|
126
|
+ }
|
|
|
127
|
+
|
|
|
128
|
+ #[test]
|
|
|
129
|
+ fn with_recommendation() {
|
|
|
130
|
+ const PREFIX: &[u8] =
|
|
|
131
|
+ b"WARN BOOTSTRAP PROGRESS=14 TAG=handshake SUMMARY=\"Handshaking with a relay\" ";
|
|
|
132
|
+ {
|
|
|
133
|
+ let line = vec![PREFIX, b"RECOMMENDATION=warn"].concat();
|
|
|
134
|
+ let status = parse_bootstrap_status(&line).unwrap();
|
|
|
135
|
+ assert!(status.should_warn);
|
|
|
136
|
+ }
|
|
|
137
|
+ {
|
|
|
138
|
+ let line = vec![PREFIX, b"RECOMMENDATION=ignore"].concat();
|
|
|
139
|
+ let status = parse_bootstrap_status(&line).unwrap();
|
|
|
140
|
+ assert!(!status.should_warn);
|
|
|
141
|
+ }
|
|
|
142
|
+ {
|
|
|
143
|
+ let line = vec![PREFIX, b"RECOMMENDATION=invalid"].concat();
|
|
|
144
|
+ let status = parse_bootstrap_status(&line).unwrap();
|
|
|
145
|
+ assert!(!status.should_warn);
|
|
|
146
|
+ }
|
|
|
147
|
+ {
|
|
|
148
|
+ let line = vec![PREFIX, b"RECOMMENDATION="].concat();
|
|
|
149
|
+ let status = parse_bootstrap_status(&line).unwrap();
|
|
|
150
|
+ assert!(!status.should_warn);
|
|
|
151
|
+ }
|
|
|
152
|
+ }
|
|
|
153
|
+
|
|
|
154
|
+ #[test]
|
|
|
155
|
+ fn with_reason() {
|
|
|
156
|
+ let line = b"WARN BOOTSTRAP PROGRESS=30 TAG=conn SUMMARY=\"Connecting to a relay\" REASON=CLOCK_SKEW";
|
|
|
157
|
+ let status = parse_bootstrap_status(&line[..]).unwrap();
|
|
|
158
|
+ assert_eq!(status.severity, StatusSeverity::Warn);
|
|
|
159
|
+ assert_eq!(status.progress, 30);
|
|
|
160
|
+ assert_eq!(status.tag, "conn");
|
|
|
161
|
+ assert_eq!(status.summary, "Connecting to a relay");
|
|
|
162
|
+ assert_eq!(status.reason.unwrap(), "CLOCK_SKEW");
|
|
|
163
|
+ assert!(!status.should_warn);
|
|
|
164
|
+ }
|
|
|
165
|
+
|
|
|
166
|
+ #[test]
|
|
|
167
|
+ fn case_insensitive() {
|
|
|
168
|
+ let line = b"wARn Bootstrap pRoGrEsS=10 tAg=conn_DONE sUmmaRY=\"connected TO a ReLaY\" reCOmmeNdATIOn=waRn";
|
|
|
169
|
+ let status = parse_bootstrap_status(line).unwrap();
|
|
|
170
|
+ assert_eq!(status.severity, StatusSeverity::Warn);
|
|
|
171
|
+ assert_eq!(status.progress, 10);
|
|
|
172
|
+ assert_eq!(status.tag, "conn_DONE");
|
|
|
173
|
+ assert_eq!(status.summary, "connected TO a ReLaY");
|
|
|
174
|
+ assert!(status.should_warn);
|
|
|
175
|
+ }
|
|
|
176
|
+
|
|
|
177
|
+ #[test]
|
|
|
178
|
+ fn invalid_severity() {
|
|
|
179
|
+ let line = b"info bootstrap PROGRESS=10 TAG=test SUMMARY=\"Test\"";
|
|
|
180
|
+ assert_matches!(
|
|
|
181
|
+ parse_bootstrap_status(line).unwrap_err(),
|
|
|
182
|
+ ControllerError::WrongFormat(_)
|
|
|
183
|
+ );
|
|
|
184
|
+ }
|
|
|
185
|
+
|
|
|
186
|
+ #[test]
|
|
|
187
|
+ fn invalid_progress() {
|
|
|
188
|
+ // Sanity tests.
|
|
|
189
|
+ assert!(
|
|
|
190
|
+ parse_bootstrap_status(b"NOTICE bootstrap PROGRESS=0 TAG=test SUMMARY=\"Test\"")
|
|
|
191
|
+ .is_ok()
|
|
|
192
|
+ );
|
|
|
193
|
+ assert!(
|
|
|
194
|
+ parse_bootstrap_status(b"NOTICE bootstrap PROGRESS=1 TAG=test SUMMARY=\"Test\"")
|
|
|
195
|
+ .is_ok()
|
|
|
196
|
+ );
|
|
|
197
|
+ assert!(
|
|
|
198
|
+ parse_bootstrap_status(b"NOTICE bootstrap PROGRESS=10 TAG=test SUMMARY=\"Test\"")
|
|
|
199
|
+ .is_ok()
|
|
|
200
|
+ );
|
|
|
201
|
+ assert!(
|
|
|
202
|
+ parse_bootstrap_status(b"NOTICE bootstrap PROGRESS=99 TAG=test SUMMARY=\"Test\"")
|
|
|
203
|
+ .is_ok()
|
|
|
204
|
+ );
|
|
|
205
|
+ assert!(
|
|
|
206
|
+ parse_bootstrap_status(b"NOTICE bootstrap PROGRESS=100 TAG=test SUMMARY=\"Test\"")
|
|
|
207
|
+ .is_ok()
|
|
|
208
|
+ );
|
|
|
209
|
+
|
|
|
210
|
+ // Invalid lines.
|
|
|
211
|
+ assert_matches!(
|
|
|
212
|
+ parse_bootstrap_status(b"NOTICE bootstrap PROGRESS=aaa TAG=test SUMMARY=\"Test\"")
|
|
|
213
|
+ .unwrap_err(),
|
|
|
214
|
+ ControllerError::MalformedReply(_)
|
|
|
215
|
+ );
|
|
|
216
|
+ assert_matches!(
|
|
|
217
|
+ parse_bootstrap_status(b"NOTICE bootstrap PROGRESS=101 TAG=test SUMMARY=\"Test\"")
|
|
|
218
|
+ .unwrap_err(),
|
|
|
219
|
+ ControllerError::MalformedReply(_)
|
|
|
220
|
+ );
|
|
|
221
|
+ }
|
|
|
222
|
+
|
|
|
223
|
+ #[test]
|
|
|
224
|
+ fn missing_args() {
|
|
|
225
|
+ assert_matches!(
|
|
|
226
|
+ parse_bootstrap_status(b"NOTICE bootstrap TAG=test SUMMARY=\"Test\"").unwrap_err(),
|
|
|
227
|
+ ControllerError::KeyNotFound(_)
|
|
|
228
|
+ );
|
|
|
229
|
+ assert_matches!(
|
|
|
230
|
+ parse_bootstrap_status(b"NOTICE bootstrap PROGRESS=3 SUMMARY=\"Test\"").unwrap_err(),
|
|
|
231
|
+ ControllerError::KeyNotFound(_)
|
|
|
232
|
+ );
|
|
|
233
|
+ assert_matches!(
|
|
|
234
|
+ parse_bootstrap_status(b"NOTICE bootstrap PROGRESS=3 TAG=test").unwrap_err(),
|
|
|
235
|
+ ControllerError::KeyNotFound(_)
|
|
|
236
|
+ );
|
|
|
237
|
+ assert_matches!(
|
|
|
238
|
+ parse_bootstrap_status(b"NOTICE bootstrap PROGRESS=3").unwrap_err(),
|
|
|
239
|
+ ControllerError::KeyNotFound(_)
|
|
|
240
|
+ );
|
|
|
241
|
+ assert_matches!(
|
|
|
242
|
+ parse_bootstrap_status(b"NOTICE bootstrap TAG=test").unwrap_err(),
|
|
|
243
|
+ ControllerError::KeyNotFound(_)
|
|
|
244
|
+ );
|
|
|
245
|
+ assert_matches!(
|
|
|
246
|
+ parse_bootstrap_status(b"NOTICE bootstrap SUMMARY=\"Test\"").unwrap_err(),
|
|
|
247
|
+ ControllerError::KeyNotFound(_)
|
|
|
248
|
+ );
|
|
|
249
|
+ }
|
|
|
250
|
+
|
|
|
251
|
+ #[test]
|
|
|
252
|
+ fn reject_garbage() {
|
|
|
253
|
+ assert_matches!(
|
|
|
254
|
+ parse_bootstrap_status(b"UNALLOWED_PREFIX NOTICE BOOTSTRAP PROGRESS=10 TAG=conn_done SUMMARY=\"Connected to a relay\"").unwrap_err(),
|
|
|
255
|
+ ControllerError::WrongFormat(_)
|
|
|
256
|
+ );
|
|
|
257
|
+ assert!(parse_bootstrap_status(b"NOTICE BOOTSTRAP PROGRESS=10 TAG=conn_done SUMMARY=\"Connected to a relay\" UNKNOWN_ARG=\"value\"").is_ok());
|
|
|
258
|
+ assert!(parse_bootstrap_status(b"NOTICE BOOTSTRAP PROGRESS=10 UNKNOWN_ARG=\"value\" TAG=conn_done SUMMARY=\"Connected to a relay\"").is_ok());
|
|
|
259
|
+ assert!(parse_bootstrap_status(b"NOTICE BOOTSTRAP PROGRESS=10 TAG=conn_done SUMMARY=\"Connected to a relay\" UNKNOWN_ARG=").is_ok());
|
|
|
260
|
+ assert!(parse_bootstrap_status(b"NOTICE BOOTSTRAP PROGRESS=10 UNKNOWN_ARG= TAG=conn_done SUMMARY=\"Connected to a relay\"").is_ok());
|
|
|
261
|
+ // Arguments that are not key=value pair (e.g., they are missing the
|
|
|
262
|
+ // equal sign) are rejected.
|
|
|
263
|
+ assert!(parse_bootstrap_status(b"NOTICE BOOTSTRAP INVALID_ARG PROGRESS=10 TAG=conn_done SUMMARY=\"Connected to a relay\"").is_err());
|
|
|
264
|
+ assert!(parse_bootstrap_status(b"NOTICE BOOTSTRAP PROGRESS=10 INVALID_ARG TAG=conn_done SUMMARY=\"Connected to a relay\"").is_err());
|
|
|
265
|
+ assert!(parse_bootstrap_status(b"NOTICE BOOTSTRAP PROGRESS=10 TAG=conn_done SUMMARY=\"Connected to a relay\" INVALID_ARG").is_err());
|
|
|
266
|
+ }
|
|
|
267
|
+} |
toolkit/components/tor-integration/tor_provider/src/ctor/controller/parsers/bridge_line.rs
| ... |
... |
@@ -33,6 +33,9 @@ lazy_static! { |
|
33
|
33
|
.expect("The regex is hardcoded, it should be good.");
|
|
34
|
34
|
}
|
|
35
|
35
|
|
|
|
36
|
+/// Errors we might encounter when parsing the bridge line.
|
|
|
37
|
+/// We have a specific type in case we want to re-use this parser for other
|
|
|
38
|
+/// purposes.
|
|
36
|
39
|
#[derive(Error, Debug, Clone, PartialEq, Eq)]
|
|
37
|
40
|
pub enum BridgeParseError {
|
|
38
|
41
|
#[error("the bridge line has a wrong format and could not be parsed")]
|
| ... |
... |
@@ -47,6 +50,19 @@ pub enum BridgeParseError { |
|
47
|
50
|
ArgsWithoutTransport,
|
|
48
|
51
|
}
|
|
49
|
52
|
|
|
|
53
|
+/// Parse a bridge line.
|
|
|
54
|
+///
|
|
|
55
|
+/// Supported lines are:
|
|
|
56
|
+/// - <address> [<fingerprint>]
|
|
|
57
|
+/// - transport <address> [<fingerprint>] [<optional-arguments>]
|
|
|
58
|
+///
|
|
|
59
|
+/// There is not a spec for bridge lines.
|
|
|
60
|
+/// The closest one is on the man page, but checking src/app/config/config.c of
|
|
|
61
|
+/// c-tor reveals more information such as:
|
|
|
62
|
+/// - "vanilla" bridges cannot have optional arguments (as they do not have a
|
|
|
63
|
+/// pluggable transport)
|
|
|
64
|
+/// - transports must be C identifiers (i.e., they can contain letters, digits
|
|
|
65
|
+/// and '_', but cannot start with a number).
|
|
50
|
66
|
pub fn parse_bridge_line(value: &[u8]) -> Result<Bridge, BridgeParseError> {
|
|
51
|
67
|
let caps = BRIDGE_REGEX
|
|
52
|
68
|
.captures(value)
|
toolkit/components/tor-integration/tor_provider/src/ctor/controller/parsers/circuit_status.rs
|
|
1
|
+// Licensed under the Apache License, Version 2.0,
|
|
|
2
|
+// <http://apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
3
|
+// <http://opensource.org/licenses/MIT>, at your option. This file may not be
|
|
|
4
|
+// copied, modified, or distributed except according to those terms.
|
|
|
5
|
+
|
|
|
6
|
+use lazy_static::lazy_static;
|
|
|
7
|
+use regex::bytes::{Regex, RegexBuilder};
|
|
|
8
|
+use smallvec::SmallVec;
|
|
|
9
|
+
|
|
|
10
|
+use super::parse_key_value_pairs;
|
|
|
11
|
+use crate::ctor::controller::{types::*, ControllerError};
|
|
|
12
|
+
|
|
|
13
|
+lazy_static! {
|
|
|
14
|
+ // https://spec.torproject.org/control-spec/replies.html#CIRC
|
|
|
15
|
+ static ref CIRCUIT_BUILT_REGEX: Regex = RegexBuilder::new(
|
|
|
16
|
+ "^(?<CircuitID>[a-zA-Z0-9]{1,16}) BUILT (?<Path>[A-Za-z0-9,$~]+)(?: (?<Args>.*))?$",
|
|
|
17
|
+ )
|
|
|
18
|
+ .case_insensitive(true)
|
|
|
19
|
+ .build()
|
|
|
20
|
+ .expect("The regex is hardcoded, it should be good.");
|
|
|
21
|
+ static ref NODE_REGEX: Regex =
|
|
|
22
|
+ Regex::new("^\\$(?<Fingerprint>[0-9a-fA-F]{40})(?:~[a-zA-Z0-9]+)?$")
|
|
|
23
|
+ .expect("The regex is hardcoded, it should be good.");
|
|
|
24
|
+}
|
|
|
25
|
+
|
|
|
26
|
+/// The keywords we are interested in parsing for circuit statuses.
|
|
|
27
|
+const CIRC_KEYWORDS: &[&'static str] = &["CONFLUX_ID"];
|
|
|
28
|
+
|
|
|
29
|
+/// Parse CIRCUIT BUILT events.
|
|
|
30
|
+/// We parse lines that look like `<circuitID> BUILT <path> <args>`.
|
|
|
31
|
+/// We ignore circuits that do not match it, so that it can be used also to
|
|
|
32
|
+/// parse the output of `GETINFO circuit-status`, as long as every line is
|
|
|
33
|
+/// passed individually.
|
|
|
34
|
+/// However, if a CIRCUIT looks like a BUILT but has some errors, we might
|
|
|
35
|
+/// return an error instead (e.g., if one of the nodes in the path has a wrong
|
|
|
36
|
+/// fingerprint length, or if the keyword-value pairs are encoded in a wrong
|
|
|
37
|
+/// format).
|
|
|
38
|
+///
|
|
|
39
|
+/// The only keyword argument we parse is the conflux ID.
|
|
|
40
|
+pub fn parse_circuit_built(line: &[u8]) -> Result<Option<Circuit>, ControllerError> {
|
|
|
41
|
+ let Some(circuit) = CIRCUIT_BUILT_REGEX.captures(line) else {
|
|
|
42
|
+ // We might parse the status of all circuits together.
|
|
|
43
|
+ // Therefore we do not want to error when we are dealing with a status
|
|
|
44
|
+ // that is not "BUILT" but something else.
|
|
|
45
|
+ // Also, our regex forces a path to be available, even though the spec
|
|
|
46
|
+ // does not explicitly require it. However, we are already returning
|
|
|
47
|
+ // None, so we do not need to handle that case separately.
|
|
|
48
|
+ return Ok(None);
|
|
|
49
|
+ };
|
|
|
50
|
+
|
|
|
51
|
+ let id = CircuitID::new(&circuit["CircuitID"]).ok_or_else(|| {
|
|
|
52
|
+ ControllerError::MalformedReply(format!(
|
|
|
53
|
+ "invalid circuit id {}",
|
|
|
54
|
+ String::from_utf8_lossy(&circuit["CircuitID"])
|
|
|
55
|
+ ))
|
|
|
56
|
+ })?;
|
|
|
57
|
+
|
|
|
58
|
+ let path = circuit["Path"]
|
|
|
59
|
+ .split(|b| *b == b',')
|
|
|
60
|
+ .map(|node| {
|
|
|
61
|
+ let node = NODE_REGEX.captures(node).ok_or_else(|| {
|
|
|
62
|
+ ControllerError::MalformedReply(format!(
|
|
|
63
|
+ "Invalid path item: {}",
|
|
|
64
|
+ String::from_utf8_lossy(node)
|
|
|
65
|
+ ))
|
|
|
66
|
+ })?;
|
|
|
67
|
+ let mut fingerprint = NodeFingerprint::default();
|
|
|
68
|
+ hex::decode_to_slice(&node["Fingerprint"], &mut fingerprint)
|
|
|
69
|
+ .map_err(|e| ControllerError::MalformedReply(e.to_string()))?;
|
|
|
70
|
+ Ok(fingerprint)
|
|
|
71
|
+ })
|
|
|
72
|
+ .collect::<Result<SmallVec<_>, ControllerError>>()?;
|
|
|
73
|
+ debug_assert!(
|
|
|
74
|
+ !path.is_empty(),
|
|
|
75
|
+ "The path in the regex was not empty, if we arrived here we must have a path item."
|
|
|
76
|
+ );
|
|
|
77
|
+
|
|
|
78
|
+ let conflux_id = circuit
|
|
|
79
|
+ .name("Args")
|
|
|
80
|
+ .map(|args| parse_key_value_pairs(args.as_bytes(), CIRC_KEYWORDS))
|
|
|
81
|
+ .transpose()?
|
|
|
82
|
+ .and_then(|args| {
|
|
|
83
|
+ let mut id = ConfluxID::default();
|
|
|
84
|
+ args.get("CONFLUX_ID")
|
|
|
85
|
+ .and_then(|s| hex::decode_to_slice(s, &mut id).ok())?;
|
|
|
86
|
+ Some(id)
|
|
|
87
|
+ });
|
|
|
88
|
+
|
|
|
89
|
+ Ok(Some(Circuit {
|
|
|
90
|
+ id,
|
|
|
91
|
+ path,
|
|
|
92
|
+ conflux_id,
|
|
|
93
|
+ }))
|
|
|
94
|
+}
|
|
|
95
|
+
|
|
|
96
|
+#[cfg(test)]
|
|
|
97
|
+mod tests {
|
|
|
98
|
+ use super::*;
|
|
|
99
|
+
|
|
|
100
|
+ fn fingerprint_from_hex(hex: &str) -> NodeFingerprint {
|
|
|
101
|
+ let mut fp = NodeFingerprint::default();
|
|
|
102
|
+ hex::decode_to_slice(hex, &mut fp).unwrap();
|
|
|
103
|
+ fp
|
|
|
104
|
+ }
|
|
|
105
|
+
|
|
|
106
|
+ fn conflux_id_from_hex(hex: &str) -> ConfluxID {
|
|
|
107
|
+ let mut id = ConfluxID::default();
|
|
|
108
|
+ hex::decode_to_slice(hex, &mut id).unwrap();
|
|
|
109
|
+ id
|
|
|
110
|
+ }
|
|
|
111
|
+
|
|
|
112
|
+ #[test]
|
|
|
113
|
+ fn parse_single_node_circuit() {
|
|
|
114
|
+ let input = b"1 BUILT $0000000000000000000000000000000000000001";
|
|
|
115
|
+ let circuit = parse_circuit_built(input).unwrap().unwrap();
|
|
|
116
|
+
|
|
|
117
|
+ assert_eq!(circuit.id.as_str(), "1");
|
|
|
118
|
+ assert_eq!(circuit.path.len(), 1);
|
|
|
119
|
+ assert_eq!(
|
|
|
120
|
+ circuit.path[0],
|
|
|
121
|
+ fingerprint_from_hex("0000000000000000000000000000000000000001")
|
|
|
122
|
+ );
|
|
|
123
|
+ assert_eq!(circuit.conflux_id, None);
|
|
|
124
|
+ }
|
|
|
125
|
+
|
|
|
126
|
+ #[test]
|
|
|
127
|
+ fn parse_three_node_circuit() {
|
|
|
128
|
+ let input = b"abc123 BUILT $aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,$bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,$cccccccccccccccccccccccccccccccccccccccc";
|
|
|
129
|
+ let circuit = parse_circuit_built(input).unwrap().unwrap();
|
|
|
130
|
+
|
|
|
131
|
+ assert_eq!(circuit.id.as_str(), "abc123");
|
|
|
132
|
+ assert_eq!(circuit.path.len(), 3);
|
|
|
133
|
+ assert_eq!(
|
|
|
134
|
+ circuit.path[0],
|
|
|
135
|
+ fingerprint_from_hex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
|
|
|
136
|
+ );
|
|
|
137
|
+ assert_eq!(
|
|
|
138
|
+ circuit.path[1],
|
|
|
139
|
+ fingerprint_from_hex("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
|
|
|
140
|
+ );
|
|
|
141
|
+ assert_eq!(
|
|
|
142
|
+ circuit.path[2],
|
|
|
143
|
+ fingerprint_from_hex("cccccccccccccccccccccccccccccccccccccccc")
|
|
|
144
|
+ );
|
|
|
145
|
+ }
|
|
|
146
|
+
|
|
|
147
|
+ #[test]
|
|
|
148
|
+ fn parse_with_conflux_id() {
|
|
|
149
|
+ let input = b"qwerty999 BUILT $1111111111111111111111111111111111111111 CONFLUX_ID=0102030405060708090a0b0c0d0e0f10";
|
|
|
150
|
+ let circuit = parse_circuit_built(input).unwrap().unwrap();
|
|
|
151
|
+
|
|
|
152
|
+ assert_eq!(circuit.id.as_str(), "qwerty999");
|
|
|
153
|
+ assert_eq!(circuit.path.len(), 1);
|
|
|
154
|
+ assert_eq!(
|
|
|
155
|
+ circuit.conflux_id.unwrap(),
|
|
|
156
|
+ conflux_id_from_hex("0102030405060708090a0b0c0d0e0f10")
|
|
|
157
|
+ );
|
|
|
158
|
+ }
|
|
|
159
|
+
|
|
|
160
|
+ #[test]
|
|
|
161
|
+ fn parse_with_nicknames() {
|
|
|
162
|
+ let input = b"1234 BUILT $1111111111111111111111111111111111111111~relay1,$2222222222222222222222222222222222222222~relay2,$3333333333333333333333333333333333333333~relay3";
|
|
|
163
|
+ let circuit = parse_circuit_built(input).unwrap().unwrap();
|
|
|
164
|
+
|
|
|
165
|
+ assert_eq!(circuit.id.as_str(), "1234");
|
|
|
166
|
+ assert_eq!(circuit.path.len(), 3);
|
|
|
167
|
+ assert_eq!(
|
|
|
168
|
+ circuit.path[0],
|
|
|
169
|
+ fingerprint_from_hex("1111111111111111111111111111111111111111")
|
|
|
170
|
+ );
|
|
|
171
|
+ assert_eq!(
|
|
|
172
|
+ circuit.path[1],
|
|
|
173
|
+ fingerprint_from_hex("2222222222222222222222222222222222222222")
|
|
|
174
|
+ );
|
|
|
175
|
+ assert_eq!(
|
|
|
176
|
+ circuit.path[2],
|
|
|
177
|
+ fingerprint_from_hex("3333333333333333333333333333333333333333")
|
|
|
178
|
+ );
|
|
|
179
|
+ }
|
|
|
180
|
+
|
|
|
181
|
+ #[test]
|
|
|
182
|
+ fn parse_mixed_case() {
|
|
|
183
|
+ let input = b"test BuiLt $AaBbCcDdEeFf0123456789AaBbCcDdEeFf012345 conflux_ID=0102030405060708090a0b0c0d0E0F10";
|
|
|
184
|
+ let circuit = parse_circuit_built(input).unwrap().unwrap();
|
|
|
185
|
+
|
|
|
186
|
+ assert_eq!(circuit.path.len(), 1);
|
|
|
187
|
+ assert_eq!(
|
|
|
188
|
+ circuit.path[0],
|
|
|
189
|
+ fingerprint_from_hex("aabbccddeeff0123456789aabbccddeeff012345")
|
|
|
190
|
+ );
|
|
|
191
|
+ assert_eq!(
|
|
|
192
|
+ circuit.conflux_id.unwrap(),
|
|
|
193
|
+ conflux_id_from_hex("0102030405060708090a0b0c0d0e0f10")
|
|
|
194
|
+ );
|
|
|
195
|
+ }
|
|
|
196
|
+
|
|
|
197
|
+ #[test]
|
|
|
198
|
+ fn parse_multiple_args() {
|
|
|
199
|
+ let input = b"ID1 built $1111111111111111111111111111111111111111 PURPOSE=GENERAL CONFLUX_ID=aabbccddeeff00112233445566778899";
|
|
|
200
|
+ let circuit = parse_circuit_built(input).unwrap().unwrap();
|
|
|
201
|
+
|
|
|
202
|
+ assert_eq!(circuit.id.as_str(), "ID1");
|
|
|
203
|
+ assert_eq!(
|
|
|
204
|
+ circuit.conflux_id.unwrap(),
|
|
|
205
|
+ conflux_id_from_hex("aabbccddeeff00112233445566778899")
|
|
|
206
|
+ );
|
|
|
207
|
+ }
|
|
|
208
|
+
|
|
|
209
|
+ #[test]
|
|
|
210
|
+ fn long_circuit() {
|
|
|
211
|
+ let input = b"id1 BUILT $1111111111111111111111111111111111111111,$2222222222222222222222222222222222222222,$3333333333333333333333333333333333333333,$4444444444444444444444444444444444444444";
|
|
|
212
|
+ let circuit = parse_circuit_built(input).unwrap().unwrap();
|
|
|
213
|
+ assert_eq!(circuit.path.len(), 4);
|
|
|
214
|
+ }
|
|
|
215
|
+
|
|
|
216
|
+ #[test]
|
|
|
217
|
+ fn not_built() {
|
|
|
218
|
+ {
|
|
|
219
|
+ let input = b"1000 EXTENDED $1111111111111111111111111111111111111111,$2222222222222222222222222222222222222222";
|
|
|
220
|
+ assert!(parse_circuit_built(input).unwrap().is_none());
|
|
|
221
|
+ }
|
|
|
222
|
+ {
|
|
|
223
|
+ let input = b"2000 CLOSED";
|
|
|
224
|
+ assert!(parse_circuit_built(input).unwrap().is_none());
|
|
|
225
|
+ }
|
|
|
226
|
+ {
|
|
|
227
|
+ let input = b"3000 GUARD_WAIT";
|
|
|
228
|
+ assert!(parse_circuit_built(input).unwrap().is_none());
|
|
|
229
|
+ }
|
|
|
230
|
+ }
|
|
|
231
|
+
|
|
|
232
|
+ #[test]
|
|
|
233
|
+ fn missing_path() {
|
|
|
234
|
+ let input = b"circuit1 BUILT";
|
|
|
235
|
+ assert!(parse_circuit_built(input).unwrap().is_none());
|
|
|
236
|
+ }
|
|
|
237
|
+
|
|
|
238
|
+ #[test]
|
|
|
239
|
+ fn missing_circuit_id() {
|
|
|
240
|
+ assert!(
|
|
|
241
|
+ parse_circuit_built(b"BUILT $1111111111111111111111111111111111111111")
|
|
|
242
|
+ .unwrap()
|
|
|
243
|
+ .is_none()
|
|
|
244
|
+ );
|
|
|
245
|
+ assert!(
|
|
|
246
|
+ parse_circuit_built(b" BUILT $1111111111111111111111111111111111111111")
|
|
|
247
|
+ .unwrap()
|
|
|
248
|
+ .is_none()
|
|
|
249
|
+ );
|
|
|
250
|
+ }
|
|
|
251
|
+
|
|
|
252
|
+ #[test]
|
|
|
253
|
+ fn missing_status_keyword() {
|
|
|
254
|
+ let input = b"circuit1 $1111111111111111111111111111111111111111";
|
|
|
255
|
+ assert!(parse_circuit_built(input).unwrap().is_none());
|
|
|
256
|
+ }
|
|
|
257
|
+
|
|
|
258
|
+ #[test]
|
|
|
259
|
+ fn invalid_circuit_id() {
|
|
|
260
|
+ {
|
|
|
261
|
+ // CircuitID must be alphanumeric only
|
|
|
262
|
+ let input = b"circuit+1 BUILT $1111111111111111111111111111111111111111";
|
|
|
263
|
+ assert!(parse_circuit_built(input).unwrap().is_none());
|
|
|
264
|
+ }
|
|
|
265
|
+ {
|
|
|
266
|
+ // CircuitID max length is 16
|
|
|
267
|
+ let input = b"12345678901234567 BUILT $1111111111111111111111111111111111111111";
|
|
|
268
|
+ assert!(parse_circuit_built(input).unwrap().is_none());
|
|
|
269
|
+ }
|
|
|
270
|
+ }
|
|
|
271
|
+
|
|
|
272
|
+ #[test]
|
|
|
273
|
+ fn invalid_fingerprint() {
|
|
|
274
|
+ assert!(parse_circuit_built(b"circuit1 BUILT $123456").is_err());
|
|
|
275
|
+ assert!(parse_circuit_built(
|
|
|
276
|
+ b"circuit1 BUILT $11111111111111111111111111111111111111112222"
|
|
|
277
|
+ )
|
|
|
278
|
+ .is_err());
|
|
|
279
|
+ assert!(
|
|
|
280
|
+ parse_circuit_built(b"circuit1 BUILT $ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ")
|
|
|
281
|
+ .is_err()
|
|
|
282
|
+ );
|
|
|
283
|
+ }
|
|
|
284
|
+
|
|
|
285
|
+ #[test]
|
|
|
286
|
+ fn partially_invalid_path() {
|
|
|
287
|
+ assert!(parse_circuit_built(b"1 BUILT $1111111111111111111111111111111111111111,$222222222222222222222222222222222222222").is_err());
|
|
|
288
|
+ assert!(parse_circuit_built(b"2 BUILT $1111111111111111111111111111111111111111,junk,$2222222222222222222222222222222222222222").is_err());
|
|
|
289
|
+ assert!(parse_circuit_built(b"3 BUILT BUILT $1111111111111111111111111111111111111111$2222222222222222222222222222222222222222").is_err());
|
|
|
290
|
+ assert!(
|
|
|
291
|
+ parse_circuit_built(b"4 BUILT $1111111111111111111111111111111111111111,").is_err()
|
|
|
292
|
+ );
|
|
|
293
|
+ }
|
|
|
294
|
+
|
|
|
295
|
+ #[test]
|
|
|
296
|
+ fn invalid_conflux_id() {
|
|
|
297
|
+ // Wrong conflux ID is not a fatal error.
|
|
|
298
|
+ {
|
|
|
299
|
+ let input =
|
|
|
300
|
+ b"circuit1 BUILT $1111111111111111111111111111111111111111 CONFLUX_ID=GGGGGGGGGGGGGGGG";
|
|
|
301
|
+ let result = parse_circuit_built(input).unwrap().unwrap();
|
|
|
302
|
+ assert!(result.conflux_id.is_none());
|
|
|
303
|
+ }
|
|
|
304
|
+ {
|
|
|
305
|
+ let input = b"circuit1 BUILT $1111111111111111111111111111111111111111 CONFLUX_ID=0102";
|
|
|
306
|
+ let result = parse_circuit_built(input).unwrap().unwrap();
|
|
|
307
|
+ assert!(result.conflux_id.is_none());
|
|
|
308
|
+ }
|
|
|
309
|
+ {
|
|
|
310
|
+ let input = b"circuit1 BUILT $1111111111111111111111111111111111111111 CONFLUX_ID=000000001111111122222222";
|
|
|
311
|
+ let result = parse_circuit_built(input).unwrap().unwrap();
|
|
|
312
|
+ assert!(result.conflux_id.is_none());
|
|
|
313
|
+ }
|
|
|
314
|
+ }
|
|
|
315
|
+
|
|
|
316
|
+ #[test]
|
|
|
317
|
+ fn invalid_path() {
|
|
|
318
|
+ let input = b"circuit1 BUILT $";
|
|
|
319
|
+ assert!(parse_circuit_built(input).is_err());
|
|
|
320
|
+ }
|
|
|
321
|
+
|
|
|
322
|
+ #[test]
|
|
|
323
|
+ fn missing_dollar_sign() {
|
|
|
324
|
+ let input = b"circuit1 BUILT 1111111111111111111111111111111111111111";
|
|
|
325
|
+ assert!(parse_circuit_built(input).is_err());
|
|
|
326
|
+ }
|
|
|
327
|
+} |
toolkit/components/tor-integration/tor_provider/src/ctor/controller/parsers/client_transport_plugin.rs
| ... |
... |
@@ -19,6 +19,20 @@ lazy_static! { |
|
19
|
19
|
.expect("The regex is hardcoded, it should be good.");
|
|
20
|
20
|
}
|
|
21
|
21
|
|
|
|
22
|
+/// Parse the definition of a pluggable transport.
|
|
|
23
|
+/// We handle these formats (from tor's man page):
|
|
|
24
|
+/// - <transports> socks4 <ip:port>
|
|
|
25
|
+/// - <transports> socks5 <ip:port>
|
|
|
26
|
+/// - <transports> exec <path> [<options>]
|
|
|
27
|
+///
|
|
|
28
|
+/// Note:
|
|
|
29
|
+/// - each line can handle multiple transports (they are comma separated)
|
|
|
30
|
+/// - IPv4 and IPv6 addresses are supported. Hostnames and Unix sockets are not
|
|
|
31
|
+/// - we accept path with encoded strings, but tor might now. Also, the
|
|
|
32
|
+/// conversion between bytes and Windows paths (UTF-16ish) is not well defined
|
|
|
33
|
+/// - options can have spaces
|
|
|
34
|
+/// - tor allows to configure multiple transport plugins. This function must be
|
|
|
35
|
+/// called with one defition at the time
|
|
22
|
36
|
pub fn parse_client_transport_plugin(line: &[u8]) -> Result<PluggableTransport, ControllerError> {
|
|
23
|
37
|
if let Some(socks_line) = SOCKS_REGEX.captures(line) {
|
|
24
|
38
|
parse_socks(&socks_line)
|
| ... |
... |
@@ -31,11 +45,9 @@ pub fn parse_client_transport_plugin(line: &[u8]) -> Result<PluggableTransport, |
|
31
|
45
|
}
|
|
32
|
46
|
}
|
|
33
|
47
|
|
|
|
48
|
+/// Check and split the transports
|
|
34
|
49
|
fn get_transports(c: &Captures) -> Result<Vec<String>, ControllerError> {
|
|
35
|
|
- let transports = c
|
|
36
|
|
- .name("transport")
|
|
37
|
|
- .ok_or(ControllerError::KeyNotFound(String::from("transport")))?
|
|
38
|
|
- .as_bytes()
|
|
|
50
|
+ let transports = c["transport"]
|
|
39
|
51
|
.split(|b| *b == b',')
|
|
40
|
52
|
.map(|t| String::from_utf8_lossy(t).into_owned())
|
|
41
|
53
|
.collect::<Vec<_>>();
|
| ... |
... |
@@ -47,21 +59,13 @@ fn get_transports(c: &Captures) -> Result<Vec<String>, ControllerError> { |
|
47
|
59
|
Ok(transports)
|
|
48
|
60
|
}
|
|
49
|
61
|
|
|
|
62
|
+/// Parse the socks4/socks5 cases
|
|
50
|
63
|
fn parse_socks(socks_line: &Captures) -> Result<PluggableTransport, ControllerError> {
|
|
51
|
|
- let address = str::from_utf8(
|
|
52
|
|
- socks_line
|
|
53
|
|
- .name("address")
|
|
54
|
|
- .ok_or(ControllerError::KeyNotFound(String::from("address")))?
|
|
55
|
|
- .as_bytes(),
|
|
56
|
|
- )
|
|
57
|
|
- .expect("The regex matches only ASCII characters (hence valid UTF-8)")
|
|
58
|
|
- .parse()
|
|
59
|
|
- .map_err(|e| ControllerError::MalformedReply(format!("{}", e)))?;
|
|
60
|
|
- let plugin = match socks_line
|
|
61
|
|
- .name("protocol")
|
|
62
|
|
- .ok_or(ControllerError::KeyNotFound(String::from("protocol")))?
|
|
63
|
|
- .as_bytes()
|
|
64
|
|
- {
|
|
|
64
|
+ let address = str::from_utf8(&socks_line["address"])
|
|
|
65
|
+ .expect("The regex matches only ASCII characters (hence valid UTF-8)")
|
|
|
66
|
+ .parse()
|
|
|
67
|
+ .map_err(|e| ControllerError::MalformedReply(format!("{}", e)))?;
|
|
|
68
|
+ let plugin = match &socks_line["protocol"] {
|
|
65
|
69
|
b"socks4" => ClientTransportPlugin::Socks4(address),
|
|
66
|
70
|
b"socks5" => ClientTransportPlugin::Socks5(address),
|
|
67
|
71
|
_ => unreachable!("We validated this with the regex"),
|
| ... |
... |
@@ -72,19 +76,15 @@ fn parse_socks(socks_line: &Captures) -> Result<PluggableTransport, ControllerEr |
|
72
|
76
|
})
|
|
73
|
77
|
}
|
|
74
|
78
|
|
|
|
79
|
+/// Parse the exec cases
|
|
75
|
80
|
fn parse_exec(exec_line: &Captures) -> Result<PluggableTransport, ControllerError> {
|
|
76
|
81
|
let options = exec_line
|
|
77
|
82
|
.name("options")
|
|
78
|
83
|
.map(|o| o.as_bytes())
|
|
79
|
84
|
.and_then(|s| if s.is_empty() { None } else { Some(s.into()) });
|
|
80
|
|
- let path = tor_unescape(
|
|
81
|
|
- exec_line
|
|
82
|
|
- .name("path")
|
|
83
|
|
- .ok_or(ControllerError::KeyNotFound(String::from("path")))?
|
|
84
|
|
- .as_bytes(),
|
|
85
|
|
- )
|
|
86
|
|
- .map_err(|e| ControllerError::MalformedReply(e.to_string()))?
|
|
87
|
|
- .into_owned();
|
|
|
85
|
+ let path = tor_unescape(&exec_line["path"])
|
|
|
86
|
+ .map_err(|e| ControllerError::MalformedReply(e.to_string()))?
|
|
|
87
|
+ .into_owned();
|
|
88
|
88
|
if path.is_empty() {
|
|
89
|
89
|
return Err(ControllerError::MalformedReply(String::from("empty path")));
|
|
90
|
90
|
}
|
toolkit/components/tor-integration/tor_provider/src/ctor/controller/parsers/country_code.rs
|
|
1
|
+// Licensed under the Apache License, Version 2.0,
|
|
|
2
|
+// <http://apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
3
|
+// <http://opensource.org/licenses/MIT>, at your option. This file may not be
|
|
|
4
|
+// copied, modified, or distributed except according to those terms.
|
|
|
5
|
+
|
|
|
6
|
+use tinystr::TinyAsciiStr;
|
|
|
7
|
+
|
|
|
8
|
+use crate::ctor::ControllerError;
|
|
|
9
|
+
|
|
|
10
|
+/// Parse the country codes as passed by the
|
|
|
11
|
+/// `GETINFO ip-to-country/<ip-address>` command.
|
|
|
12
|
+/// The function checks that the country code is composed by two letters, or it
|
|
|
13
|
+/// is ??. Anything else will be rejected.
|
|
|
14
|
+/// Cases will be preserved.
|
|
|
15
|
+pub fn parse_country_code(line: &[u8]) -> Result<TinyAsciiStr<2>, ControllerError> {
|
|
|
16
|
+ if line.len() != 2 {
|
|
|
17
|
+ return Err(ControllerError::MalformedReply(format!(
|
|
|
18
|
+ "expected two bytes (got {})",
|
|
|
19
|
+ line.len(),
|
|
|
20
|
+ )));
|
|
|
21
|
+ }
|
|
|
22
|
+ let code = TinyAsciiStr::try_from_utf8(line)
|
|
|
23
|
+ .map_err(|e| ControllerError::MalformedReply(e.to_string()))?;
|
|
|
24
|
+ if code != "??" && !code.is_ascii_alphabetic() {
|
|
|
25
|
+ return Err(ControllerError::MalformedReply(String::from(
|
|
|
26
|
+ "country codes must be 2 letters or be ??",
|
|
|
27
|
+ )));
|
|
|
28
|
+ }
|
|
|
29
|
+ Ok(code)
|
|
|
30
|
+}
|
|
|
31
|
+
|
|
|
32
|
+#[cfg(test)]
|
|
|
33
|
+mod tests {
|
|
|
34
|
+ use super::*;
|
|
|
35
|
+ use std::assert_matches;
|
|
|
36
|
+
|
|
|
37
|
+ #[test]
|
|
|
38
|
+ fn country_code() {
|
|
|
39
|
+ assert_eq!(parse_country_code(b"IT").unwrap(), "IT");
|
|
|
40
|
+ }
|
|
|
41
|
+
|
|
|
42
|
+ #[test]
|
|
|
43
|
+ fn unknown() {
|
|
|
44
|
+ assert_eq!(parse_country_code(b"??").unwrap(), "??");
|
|
|
45
|
+ }
|
|
|
46
|
+
|
|
|
47
|
+ #[test]
|
|
|
48
|
+ fn case_preserved() {
|
|
|
49
|
+ assert_eq!(parse_country_code(b"aa").unwrap(), "aa");
|
|
|
50
|
+ assert_eq!(parse_country_code(b"aB").unwrap(), "aB");
|
|
|
51
|
+ assert_eq!(parse_country_code(b"Ba").unwrap(), "Ba");
|
|
|
52
|
+ assert_eq!(parse_country_code(b"BB").unwrap(), "BB");
|
|
|
53
|
+ }
|
|
|
54
|
+
|
|
|
55
|
+ #[test]
|
|
|
56
|
+ fn too_short() {
|
|
|
57
|
+ assert_matches!(
|
|
|
58
|
+ parse_country_code(b"I").unwrap_err(),
|
|
|
59
|
+ ControllerError::MalformedReply(_)
|
|
|
60
|
+ );
|
|
|
61
|
+ }
|
|
|
62
|
+
|
|
|
63
|
+ #[test]
|
|
|
64
|
+ fn too_long() {
|
|
|
65
|
+ assert_matches!(
|
|
|
66
|
+ parse_country_code(b"ITA").unwrap_err(),
|
|
|
67
|
+ ControllerError::MalformedReply(_)
|
|
|
68
|
+ );
|
|
|
69
|
+ }
|
|
|
70
|
+
|
|
|
71
|
+ #[test]
|
|
|
72
|
+ fn not_ascii() {
|
|
|
73
|
+ assert_matches!(
|
|
|
74
|
+ parse_country_code(b"\xF0\xF0").unwrap_err(),
|
|
|
75
|
+ ControllerError::MalformedReply(_)
|
|
|
76
|
+ );
|
|
|
77
|
+ }
|
|
|
78
|
+
|
|
|
79
|
+ #[test]
|
|
|
80
|
+ fn empty() {
|
|
|
81
|
+ assert_matches!(
|
|
|
82
|
+ parse_country_code(b"").unwrap_err(),
|
|
|
83
|
+ ControllerError::MalformedReply(_)
|
|
|
84
|
+ );
|
|
|
85
|
+ }
|
|
|
86
|
+
|
|
|
87
|
+ #[test]
|
|
|
88
|
+ fn not_alphabetic() {
|
|
|
89
|
+ assert_matches!(
|
|
|
90
|
+ parse_country_code(b"12").unwrap_err(),
|
|
|
91
|
+ ControllerError::MalformedReply(_)
|
|
|
92
|
+ );
|
|
|
93
|
+ assert_matches!(
|
|
|
94
|
+ parse_country_code(b"A2").unwrap_err(),
|
|
|
95
|
+ ControllerError::MalformedReply(_)
|
|
|
96
|
+ );
|
|
|
97
|
+ assert_matches!(
|
|
|
98
|
+ parse_country_code(b"1B").unwrap_err(),
|
|
|
99
|
+ ControllerError::MalformedReply(_)
|
|
|
100
|
+ );
|
|
|
101
|
+ assert_matches!(
|
|
|
102
|
+ parse_country_code(b"?c").unwrap_err(),
|
|
|
103
|
+ ControllerError::MalformedReply(_)
|
|
|
104
|
+ );
|
|
|
105
|
+ assert_matches!(
|
|
|
106
|
+ parse_country_code(b"d?").unwrap_err(),
|
|
|
107
|
+ ControllerError::MalformedReply(_)
|
|
|
108
|
+ );
|
|
|
109
|
+ }
|
|
|
110
|
+} |
toolkit/components/tor-integration/tor_provider/src/ctor/controller/parsers/key_value_pairs.rs
|
|
1
|
+// Licensed under the Apache License, Version 2.0,
|
|
|
2
|
+// <http://apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
3
|
+// <http://opensource.org/licenses/MIT>, at your option. This file may not be
|
|
|
4
|
+// copied, modified, or distributed except according to those terms.
|
|
|
5
|
+
|
|
|
6
|
+use lazy_static::lazy_static;
|
|
|
7
|
+use regex::bytes::Regex;
|
|
|
8
|
+use std::collections::HashMap;
|
|
|
9
|
+
|
|
|
10
|
+use crate::ctor::controller::ControllerError;
|
|
|
11
|
+
|
|
|
12
|
+lazy_static! {
|
|
|
13
|
+ // Matching the final group will assure we reject quotes in any unquoted
|
|
|
14
|
+ // string.
|
|
|
15
|
+ static ref KEY_VALUE_PAIR_REGEX: Regex = Regex::new(r#"^ *([A-Za-z0-9_]+)=("(?:\\.|[^"])*"|[^ "]*)(?: +|$)"#)
|
|
|
16
|
+ .expect("The regex is hardcoded, it should be good.");
|
|
|
17
|
+}
|
|
|
18
|
+
|
|
|
19
|
+/// Get multiple key-value pairs from a line.
|
|
|
20
|
+///
|
|
|
21
|
+/// Often the commands expect values to follow a certain format for the values.
|
|
|
22
|
+/// Validation needs to be performed by the caller.
|
|
|
23
|
+///
|
|
|
24
|
+/// Also, usually keywords are defined with double quotes, therefore they should
|
|
|
25
|
+/// be treated as case-insensitive.
|
|
|
26
|
+/// This function compares the keyword it finds with the keywords from the list
|
|
|
27
|
+/// in a case-insensitive fashion, and uses the list's string as a key.
|
|
|
28
|
+///
|
|
|
29
|
+/// All arguments are processed regardless of them being in the list, and the
|
|
|
30
|
+/// order in allowed_keys does not influence how this function works.
|
|
|
31
|
+/// In other words, this function does not validate the order in which the
|
|
|
32
|
+/// key/value pairs appear in the line.
|
|
|
33
|
+///
|
|
|
34
|
+/// Repeated entries are silently tolerated, and the last matching element will
|
|
|
35
|
+/// be assigned to the returned map. However, callers should not depend on this
|
|
|
36
|
+/// behavior.
|
|
|
37
|
+pub(super) fn parse_key_value_pairs<'a>(
|
|
|
38
|
+ line: &'a [u8],
|
|
|
39
|
+ allowed_keys: &[&'static str],
|
|
|
40
|
+) -> Result<HashMap<&'static str, &'a [u8]>, ControllerError> {
|
|
|
41
|
+ let mut values = HashMap::new();
|
|
|
42
|
+ let mut pos = 0;
|
|
|
43
|
+ while pos < line.len() {
|
|
|
44
|
+ let Some(kv) = KEY_VALUE_PAIR_REGEX.captures(&line[pos..]) else {
|
|
|
45
|
+ return Err(ControllerError::MalformedReply(format!(
|
|
|
46
|
+ "invalid key/value pair: {}",
|
|
|
47
|
+ String::from_utf8_lossy(&line[pos..])
|
|
|
48
|
+ )));
|
|
|
49
|
+ };
|
|
|
50
|
+ pos += kv[0].len();
|
|
|
51
|
+
|
|
|
52
|
+ let key = match allowed_keys
|
|
|
53
|
+ .iter()
|
|
|
54
|
+ .find(|k| kv[1].eq_ignore_ascii_case(k.as_bytes()))
|
|
|
55
|
+ {
|
|
|
56
|
+ Some(k) => *k,
|
|
|
57
|
+ None => {
|
|
|
58
|
+ continue;
|
|
|
59
|
+ }
|
|
|
60
|
+ };
|
|
|
61
|
+ // Notice that kv[2] does not work here as it has explicitly the same
|
|
|
62
|
+ // lifetime as the Captures, rather than the original buffer's.
|
|
|
63
|
+ let value = kv.get(2).expect("Group 2 is compulsory.").as_bytes();
|
|
|
64
|
+ values.insert(key, value);
|
|
|
65
|
+ }
|
|
|
66
|
+ Ok(values)
|
|
|
67
|
+}
|
|
|
68
|
+
|
|
|
69
|
+#[cfg(test)]
|
|
|
70
|
+mod tests {
|
|
|
71
|
+ use super::*;
|
|
|
72
|
+
|
|
|
73
|
+ #[test]
|
|
|
74
|
+ fn single_pair() {
|
|
|
75
|
+ {
|
|
|
76
|
+ let values = parse_key_value_pairs(b"KEY=Value", &["KEY"]).unwrap();
|
|
|
77
|
+ assert_eq!(values.len(), 1);
|
|
|
78
|
+ assert_eq!(values.get("KEY").unwrap(), b"Value");
|
|
|
79
|
+ }
|
|
|
80
|
+ {
|
|
|
81
|
+ let values = parse_key_value_pairs(b"KEY=\"Value with quotes\"", &["KEY"]).unwrap();
|
|
|
82
|
+ assert_eq!(values.len(), 1);
|
|
|
83
|
+ assert_eq!(values.get("KEY").unwrap(), b"\"Value with quotes\"");
|
|
|
84
|
+ }
|
|
|
85
|
+ {
|
|
|
86
|
+ let values = parse_key_value_pairs(b"KEY=\"Value\"", &["KEY"]).unwrap();
|
|
|
87
|
+ assert_eq!(values.len(), 1);
|
|
|
88
|
+ assert_eq!(values.get("KEY").unwrap(), b"\"Value\"");
|
|
|
89
|
+ }
|
|
|
90
|
+ }
|
|
|
91
|
+
|
|
|
92
|
+ #[test]
|
|
|
93
|
+ fn empty_value() {
|
|
|
94
|
+ let values = parse_key_value_pairs(b"KEY=", &["KEY"]).unwrap();
|
|
|
95
|
+ assert_eq!(values.len(), 1);
|
|
|
96
|
+ assert_eq!(values.get("KEY").unwrap(), b"");
|
|
|
97
|
+ }
|
|
|
98
|
+
|
|
|
99
|
+ #[test]
|
|
|
100
|
+ fn quotes() {
|
|
|
101
|
+ let values = parse_key_value_pairs(b"KEY=\"Value with \\\" esccape\"", &["KEY"]).unwrap();
|
|
|
102
|
+ assert_eq!(values.len(), 1);
|
|
|
103
|
+ assert_eq!(values.get("KEY").unwrap(), b"\"Value with \\\" esccape\"");
|
|
|
104
|
+ }
|
|
|
105
|
+
|
|
|
106
|
+ #[test]
|
|
|
107
|
+ fn test_multiple() {
|
|
|
108
|
+ let values = parse_key_value_pairs(
|
|
|
109
|
+ b"GOOD=yes QUOTED=\"Quoted value\" ANOTHER=1",
|
|
|
110
|
+ &["GOOD", "NOT_FOUND", "QUOTED", "ANOTHER"],
|
|
|
111
|
+ )
|
|
|
112
|
+ .unwrap();
|
|
|
113
|
+ assert_eq!(values.len(), 3);
|
|
|
114
|
+ assert_eq!(values.get("GOOD").unwrap(), b"yes");
|
|
|
115
|
+ assert_eq!(values.get("QUOTED").unwrap(), b"\"Quoted value\"");
|
|
|
116
|
+ assert_eq!(values.get("ANOTHER").unwrap(), b"1");
|
|
|
117
|
+ assert!(values.get("NOT_FOUND").is_none());
|
|
|
118
|
+ }
|
|
|
119
|
+
|
|
|
120
|
+ #[test]
|
|
|
121
|
+ fn ignore_if_unallowed() {
|
|
|
122
|
+ let values = parse_key_value_pairs(b"A=1 B=2 C=\"Quoted\"", &["A", "C"]).unwrap();
|
|
|
123
|
+ assert_eq!(values.len(), 2);
|
|
|
124
|
+ assert_eq!(values.get("A").unwrap(), b"1");
|
|
|
125
|
+ assert!(values.get("B").is_none());
|
|
|
126
|
+ assert_eq!(values.get("C").unwrap(), b"\"Quoted\"");
|
|
|
127
|
+ }
|
|
|
128
|
+
|
|
|
129
|
+ #[test]
|
|
|
130
|
+ fn only_in_allow_list() {
|
|
|
131
|
+ let values = parse_key_value_pairs(b"A=1 C=\"Quoted\"", &["A", "B", "C"]).unwrap();
|
|
|
132
|
+ assert_eq!(values.len(), 2);
|
|
|
133
|
+ assert_eq!(values.get("A").unwrap(), b"1");
|
|
|
134
|
+ assert!(values.get("B").is_none());
|
|
|
135
|
+ assert_eq!(values.get("C").unwrap(), b"\"Quoted\"");
|
|
|
136
|
+ }
|
|
|
137
|
+
|
|
|
138
|
+ #[test]
|
|
|
139
|
+ fn case_insensitive_keys() {
|
|
|
140
|
+ let values =
|
|
|
141
|
+ parse_key_value_pairs(b"A=123 tESt=value KEY=val", &["a", "TesT", "kEy"]).unwrap();
|
|
|
142
|
+ assert_eq!(values.len(), 3);
|
|
|
143
|
+ assert_eq!(values.get("a").unwrap(), b"123");
|
|
|
144
|
+ assert_eq!(values.get("TesT").unwrap(), b"value");
|
|
|
145
|
+ assert_eq!(values.get("kEy").unwrap(), b"val");
|
|
|
146
|
+ }
|
|
|
147
|
+
|
|
|
148
|
+ #[test]
|
|
|
149
|
+ fn missing_equal_sign() {
|
|
|
150
|
+ assert!(parse_key_value_pairs(b"KEY", &["KEY"]).is_err());
|
|
|
151
|
+ assert!(parse_key_value_pairs(
|
|
|
152
|
+ b"VALUE=something MISSING COUNT=3 QUOTED=\"Quoted value\"",
|
|
|
153
|
+ &["VALUE", "MISSING", "COUNT", "QUOTED"]
|
|
|
154
|
+ )
|
|
|
155
|
+ .is_err());
|
|
|
156
|
+ assert!(parse_key_value_pairs(
|
|
|
157
|
+ b"MISSING VALUE=something COUNT=3 QUOTED=\"Quoted value\"",
|
|
|
158
|
+ &["VALUE", "MISSING", "COUNT", "QUOTED"]
|
|
|
159
|
+ )
|
|
|
160
|
+ .is_err());
|
|
|
161
|
+ assert!(parse_key_value_pairs(
|
|
|
162
|
+ b"VALUE=something COUNT=3 QUOTED=\"Quoted value\" MISSING",
|
|
|
163
|
+ &["VALUE", "MISSING", "COUNT", "QUOTED"]
|
|
|
164
|
+ )
|
|
|
165
|
+ .is_err());
|
|
|
166
|
+ }
|
|
|
167
|
+
|
|
|
168
|
+ #[test]
|
|
|
169
|
+ fn problematic_quotes() {
|
|
|
170
|
+ assert!(parse_key_value_pairs(b"KEY=\"Unbalanced quote", &["KEY"]).is_err());
|
|
|
171
|
+ assert!(parse_key_value_pairs(b"KEY=value\"", &["KEY"]).is_err());
|
|
|
172
|
+ assert!(parse_key_value_pairs(b"KEY=val\"ue", &["KEY"]).is_err());
|
|
|
173
|
+ assert!(parse_key_value_pairs(
|
|
|
174
|
+ b"GOOD=yes INVALID=\"Unbalanced QUOTED=\"Quoted value\" ANOTHER=1",
|
|
|
175
|
+ &["GOOD", "INVALID", "QUOTED", "ANOTHER"]
|
|
|
176
|
+ )
|
|
|
177
|
+ .is_err());
|
|
|
178
|
+ assert!(parse_key_value_pairs(
|
|
|
179
|
+ b"GOOD=yes QUOTED=\"Quoted value\" INVALID=\"Unbalanced ANOTHER=1",
|
|
|
180
|
+ &["GOOD", "INVALID", "QUOTED", "ANOTHER"]
|
|
|
181
|
+ )
|
|
|
182
|
+ .is_err());
|
|
|
183
|
+ assert!(parse_key_value_pairs(
|
|
|
184
|
+ b"GOOD=yes QUOTED=\"Quoted value\" ANOTHER=1 INVALID=\"Unbalanced ",
|
|
|
185
|
+ &["GOOD", "INVALID", "QUOTED", "ANOTHER"]
|
|
|
186
|
+ )
|
|
|
187
|
+ .is_err());
|
|
|
188
|
+ }
|
|
|
189
|
+} |
toolkit/components/tor-integration/tor_provider/src/ctor/controller/parsers/mod.rs
| ... |
... |
@@ -4,16 +4,32 @@ |
|
4
|
4
|
// copied, modified, or distributed except according to those terms.
|
|
5
|
5
|
|
|
6
|
6
|
mod ack;
|
|
|
7
|
+mod bootstrap_status;
|
|
7
|
8
|
mod bridge_line;
|
|
|
9
|
+mod circuit_status;
|
|
8
|
10
|
mod client_transport_plugin;
|
|
|
11
|
+mod country_code;
|
|
9
|
12
|
mod escape;
|
|
|
13
|
+mod key_value_pairs;
|
|
|
14
|
+mod node_address;
|
|
|
15
|
+mod onion_client_auth_view;
|
|
|
16
|
+mod socks_listeners;
|
|
|
17
|
+mod stream_status;
|
|
10
|
18
|
mod unescape;
|
|
11
|
19
|
|
|
12
|
20
|
#[cfg(test)]
|
|
13
|
21
|
mod tests;
|
|
14
|
22
|
|
|
15
|
23
|
pub use ack::parse_ack;
|
|
|
24
|
+pub use bootstrap_status::parse_bootstrap_status;
|
|
16
|
25
|
pub use bridge_line::parse_bridge_line;
|
|
|
26
|
+pub use circuit_status::parse_circuit_built;
|
|
17
|
27
|
pub use client_transport_plugin::parse_client_transport_plugin;
|
|
|
28
|
+pub use country_code::parse_country_code;
|
|
18
|
29
|
pub use escape::tor_escape_into;
|
|
|
30
|
+use key_value_pairs::parse_key_value_pairs;
|
|
|
31
|
+pub use node_address::addresses_from_status_info;
|
|
|
32
|
+pub use onion_client_auth_view::parse_onion_client_auth_view;
|
|
|
33
|
+pub use socks_listeners::parse_socks_listeners;
|
|
|
34
|
+pub use stream_status::parse_stream_sentconnect;
|
|
19
|
35
|
pub use unescape::tor_unescape; |
toolkit/components/tor-integration/tor_provider/src/ctor/controller/parsers/node_address.rs
|
|
1
|
+// Licensed under the Apache License, Version 2.0,
|
|
|
2
|
+// <http://apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
3
|
+// <http://opensource.org/licenses/MIT>, at your option. This file may not be
|
|
|
4
|
+// copied, modified, or distributed except according to those terms.
|
|
|
5
|
+
|
|
|
6
|
+use lazy_static::lazy_static;
|
|
|
7
|
+use regex::bytes::Regex;
|
|
|
8
|
+use std::net::{Ipv4Addr, SocketAddrV6};
|
|
|
9
|
+
|
|
|
10
|
+use crate::ctor::controller::{types::*, ControllerError};
|
|
|
11
|
+
|
|
|
12
|
+lazy_static! {
|
|
|
13
|
+ // First line is always:
|
|
|
14
|
+ // `r nickname identity digest PubDate PubTime IP ORPort DirPort`
|
|
|
15
|
+ // https://spec.torproject.org/dir-spec/consensus-formats.html#section:router-status
|
|
|
16
|
+ static ref R_LINE_REGEX: Regex = Regex::new(
|
|
|
17
|
+ r"^r [A-Za-z0-9]+ [A-Za-z0-9+/]+ [A-Za-z0-9+/=]+ \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} ([0-9\.]{7,15}) \d{1,5} \d{1,5}$",
|
|
|
18
|
+ )
|
|
|
19
|
+ .expect("The regex is hardcoded, it should be good.");
|
|
|
20
|
+}
|
|
|
21
|
+
|
|
|
22
|
+/// Parse a router status and return its IPv4 (and IPv6, if available).
|
|
|
23
|
+/// We follow the specs from:
|
|
|
24
|
+/// https://spec.torproject.org/dir-spec/consensus-formats.html#section:router-status
|
|
|
25
|
+///
|
|
|
26
|
+/// We expect the first line to have this format:
|
|
|
27
|
+/// `r nickname identity digest PubDate PubTime IP ORPort DirPort`
|
|
|
28
|
+/// We only validate the allowed characters, we do not validate all the fields.
|
|
|
29
|
+///
|
|
|
30
|
+/// We ignore any other lines, except the ones for IPv6 addresses, that have
|
|
|
31
|
+/// this format: `a [<IPv6-address>]:port`.
|
|
|
32
|
+/// Only the first valid "a" line will be picked up.
|
|
|
33
|
+///
|
|
|
34
|
+/// This function parses one router at the time.
|
|
|
35
|
+pub fn addresses_from_status_info(lines: &[&[u8]]) -> Result<NodeAddresses, ControllerError> {
|
|
|
36
|
+ if lines.is_empty() {
|
|
|
37
|
+ return Err(ControllerError::MalformedReply(String::from(
|
|
|
38
|
+ "empty status info",
|
|
|
39
|
+ )));
|
|
|
40
|
+ }
|
|
|
41
|
+
|
|
|
42
|
+ let Some(r_line) = R_LINE_REGEX.captures(lines[0]) else {
|
|
|
43
|
+ return Err(ControllerError::MalformedReply(format!(
|
|
|
44
|
+ "the first line cannot be parsed: {}",
|
|
|
45
|
+ String::from_utf8_lossy(lines[0])
|
|
|
46
|
+ )));
|
|
|
47
|
+ };
|
|
|
48
|
+ let ipv4: Ipv4Addr = str::from_utf8(&r_line[1])
|
|
|
49
|
+ .map_err(|e| ControllerError::MalformedReply(e.to_string()))?
|
|
|
50
|
+ .parse()
|
|
|
51
|
+ .map_err(|e| ControllerError::MalformedReply(format!("{}", e)))?;
|
|
|
52
|
+
|
|
|
53
|
+ let ipv6 = lines[1..].iter().find_map(|line| {
|
|
|
54
|
+ if !line.starts_with(b"a ") {
|
|
|
55
|
+ return None;
|
|
|
56
|
+ }
|
|
|
57
|
+ let s = str::from_utf8(&line[2..]).ok()?;
|
|
|
58
|
+ let addrv6: SocketAddrV6 = s.parse().ok()?;
|
|
|
59
|
+ Some(*addrv6.ip())
|
|
|
60
|
+ });
|
|
|
61
|
+
|
|
|
62
|
+ Ok(NodeAddresses { ipv4, ipv6 })
|
|
|
63
|
+}
|
|
|
64
|
+
|
|
|
65
|
+#[cfg(test)]
|
|
|
66
|
+mod tests {
|
|
|
67
|
+ use super::*;
|
|
|
68
|
+ use std::{assert_matches, net::Ipv6Addr};
|
|
|
69
|
+
|
|
|
70
|
+ #[test]
|
|
|
71
|
+ fn happy_both() {
|
|
|
72
|
+ assert_eq!(
|
|
|
73
|
+ addresses_from_status_info(&[
|
|
|
74
|
+ b"r nickname abAB123+/xyzXYZaaaaaaaaaaaa bbbbbbbbabAB123+/xyzXYZbbbb 2038-01-01 00:00:00 192.168.1.3 9001 0",
|
|
|
75
|
+ b"a [fdc8:08d6:f860:d6c::3100]:9001",
|
|
|
76
|
+ b"s Fast Guard HSDir Running Stable V2Dir Valid",
|
|
|
77
|
+ b"w Bandwidth=5000",
|
|
|
78
|
+ ]).unwrap(),
|
|
|
79
|
+ NodeAddresses {
|
|
|
80
|
+ ipv4: Ipv4Addr::new(192, 168, 1, 3),
|
|
|
81
|
+ ipv6: Some(Ipv6Addr::new(
|
|
|
82
|
+ 0xfdc8, 0x08d6, 0xf860, 0xd6c, 0, 0, 0, 0x3100
|
|
|
83
|
+ )),
|
|
|
84
|
+ }
|
|
|
85
|
+ );
|
|
|
86
|
+ assert_eq!(
|
|
|
87
|
+ addresses_from_status_info(&[
|
|
|
88
|
+ b"r nickname aaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbb 2038-01-01 00:00:00 192.168.1.3 9001 0",
|
|
|
89
|
+ b"s Fast Guard HSDir Running Stable V2Dir Valid",
|
|
|
90
|
+ b"w Bandwidth=5000",
|
|
|
91
|
+ b"a [fdc8:08d6:f860:d6c::3100]:9001",
|
|
|
92
|
+ ]).unwrap(),
|
|
|
93
|
+ NodeAddresses {
|
|
|
94
|
+ ipv4: Ipv4Addr::new(192, 168, 1, 3),
|
|
|
95
|
+ ipv6: Some(Ipv6Addr::new(
|
|
|
96
|
+ 0xfdc8, 0x08d6, 0xf860, 0xd6c, 0, 0, 0, 0x3100
|
|
|
97
|
+ )),
|
|
|
98
|
+ }
|
|
|
99
|
+ );
|
|
|
100
|
+ }
|
|
|
101
|
+
|
|
|
102
|
+ #[test]
|
|
|
103
|
+ fn only_v4() {
|
|
|
104
|
+ assert_eq!(
|
|
|
105
|
+ addresses_from_status_info(&[b"r nickname aaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbb 2038-01-01 00:00:00 192.168.1.3 9001 0"]).unwrap(),
|
|
|
106
|
+ NodeAddresses {
|
|
|
107
|
+ ipv4: Ipv4Addr::new(192, 168, 1, 3),
|
|
|
108
|
+ ipv6: None
|
|
|
109
|
+ }
|
|
|
110
|
+ );
|
|
|
111
|
+ }
|
|
|
112
|
+
|
|
|
113
|
+ #[test]
|
|
|
114
|
+ fn invalid_v6_ignored() {
|
|
|
115
|
+ assert_eq!(
|
|
|
116
|
+ addresses_from_status_info(&[
|
|
|
117
|
+ b"r nickname aaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbb 2038-01-01 00:00:00 192.168.1.3 9001 0",
|
|
|
118
|
+ b"a [zzzz:08d6:f860:d6c::3100]:9001",
|
|
|
119
|
+ ]).unwrap(),
|
|
|
120
|
+ NodeAddresses {
|
|
|
121
|
+ ipv4: Ipv4Addr::new(192, 168, 1, 3),
|
|
|
122
|
+ ipv6: None
|
|
|
123
|
+ }
|
|
|
124
|
+ );
|
|
|
125
|
+
|
|
|
126
|
+ // Missing the port is also rejected for IPv6
|
|
|
127
|
+ assert_eq!(
|
|
|
128
|
+ addresses_from_status_info(&[
|
|
|
129
|
+ b"r nickname aaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbb 2038-01-01 00:00:00 192.168.1.3 9001 0",
|
|
|
130
|
+ b"a [fdc8:08d6:f860:d6c::3100]",
|
|
|
131
|
+ ]).unwrap(),
|
|
|
132
|
+ NodeAddresses {
|
|
|
133
|
+ ipv4: Ipv4Addr::new(192, 168, 1, 3),
|
|
|
134
|
+ ipv6: None
|
|
|
135
|
+ }
|
|
|
136
|
+ );
|
|
|
137
|
+
|
|
|
138
|
+ assert_eq!(
|
|
|
139
|
+ addresses_from_status_info(&[
|
|
|
140
|
+ b"r nickname aaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbb 2038-01-01 00:00:00 192.168.1.3 9001 0",
|
|
|
141
|
+ b"a",
|
|
|
142
|
+ ]).unwrap(),
|
|
|
143
|
+ NodeAddresses {
|
|
|
144
|
+ ipv4: Ipv4Addr::new(192, 168, 1, 3),
|
|
|
145
|
+ ipv6: None
|
|
|
146
|
+ }
|
|
|
147
|
+ );
|
|
|
148
|
+
|
|
|
149
|
+ assert_eq!(
|
|
|
150
|
+ addresses_from_status_info(&[
|
|
|
151
|
+ b"r nickname aaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbb 2038-01-01 00:00:00 192.168.1.3 9001 0",
|
|
|
152
|
+ b"a ",
|
|
|
153
|
+ ]).unwrap(),
|
|
|
154
|
+ NodeAddresses {
|
|
|
155
|
+ ipv4: Ipv4Addr::new(192, 168, 1, 3),
|
|
|
156
|
+ ipv6: None
|
|
|
157
|
+ }
|
|
|
158
|
+ );
|
|
|
159
|
+
|
|
|
160
|
+ assert_eq!(
|
|
|
161
|
+ addresses_from_status_info(&[
|
|
|
162
|
+ b"r nickname aaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbb 2038-01-01 00:00:00 192.168.1.3 9001 0",
|
|
|
163
|
+ b"abc [fdc8:dead:beef:d6c::3100]:9001",
|
|
|
164
|
+ ]).unwrap(),
|
|
|
165
|
+ NodeAddresses {
|
|
|
166
|
+ ipv4: Ipv4Addr::new(192, 168, 1, 3),
|
|
|
167
|
+ ipv6: None
|
|
|
168
|
+ }
|
|
|
169
|
+ );
|
|
|
170
|
+
|
|
|
171
|
+ assert_eq!(
|
|
|
172
|
+ addresses_from_status_info(&[
|
|
|
173
|
+ b"r nickname aaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbb 2038-01-01 00:00:00 192.168.1.3 9001 0",
|
|
|
174
|
+ b"a 127.0.0.1",
|
|
|
175
|
+ ]).unwrap(),
|
|
|
176
|
+ NodeAddresses {
|
|
|
177
|
+ ipv4: Ipv4Addr::new(192, 168, 1, 3),
|
|
|
178
|
+ ipv6: None
|
|
|
179
|
+ }
|
|
|
180
|
+ );
|
|
|
181
|
+ }
|
|
|
182
|
+
|
|
|
183
|
+ #[test]
|
|
|
184
|
+ fn multiple_a() {
|
|
|
185
|
+ assert_eq!(
|
|
|
186
|
+ addresses_from_status_info(&[
|
|
|
187
|
+ b"r nickname aaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbb 2038-01-01 00:00:00 192.168.1.3 9001 0",
|
|
|
188
|
+ b"a [cafe:dead:beef:0123::3100]:9001",
|
|
|
189
|
+ b"a [cafe:dead:beef:0123::3200]:9001",
|
|
|
190
|
+ ]).unwrap(),
|
|
|
191
|
+ NodeAddresses {
|
|
|
192
|
+ ipv4: Ipv4Addr::new(192, 168, 1, 3),
|
|
|
193
|
+ ipv6: Some(Ipv6Addr::new(
|
|
|
194
|
+ 0xcafe, 0xdead, 0xbeef, 0x0123, 0, 0, 0, 0x3100
|
|
|
195
|
+ ))
|
|
|
196
|
+ }
|
|
|
197
|
+ );
|
|
|
198
|
+
|
|
|
199
|
+ assert_eq!(
|
|
|
200
|
+ addresses_from_status_info(&[
|
|
|
201
|
+ b"r nickname aaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbb 2038-01-01 00:00:00 192.168.1.3 9001 0",
|
|
|
202
|
+ b"a [cafe:dead:beef:0123::3100]:9001",
|
|
|
203
|
+ b"a [cafe:dead:xxxx:0123::3200]:9001",
|
|
|
204
|
+ ]).unwrap(),
|
|
|
205
|
+ NodeAddresses {
|
|
|
206
|
+ ipv4: Ipv4Addr::new(192, 168, 1, 3),
|
|
|
207
|
+ ipv6: Some(Ipv6Addr::new(
|
|
|
208
|
+ 0xcafe, 0xdead, 0xbeef, 0x0123, 0, 0, 0, 0x3100
|
|
|
209
|
+ ))
|
|
|
210
|
+ }
|
|
|
211
|
+ );
|
|
|
212
|
+
|
|
|
213
|
+ assert_eq!(
|
|
|
214
|
+ addresses_from_status_info(&[
|
|
|
215
|
+ b"r nickname aaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbb 2038-01-01 00:00:00 192.168.1.3 9001 0",
|
|
|
216
|
+ b"a [cafe:dead:xxxx:0123::3200]:9001",
|
|
|
217
|
+ b"a [cafe:dead:beef:0123::3100]:9001",
|
|
|
218
|
+ ]).unwrap(),
|
|
|
219
|
+ NodeAddresses {
|
|
|
220
|
+ ipv4: Ipv4Addr::new(192, 168, 1, 3),
|
|
|
221
|
+ ipv6: Some(Ipv6Addr::new(
|
|
|
222
|
+ 0xcafe, 0xdead, 0xbeef, 0x0123, 0, 0, 0, 0x3100
|
|
|
223
|
+ ))
|
|
|
224
|
+ }
|
|
|
225
|
+ );
|
|
|
226
|
+
|
|
|
227
|
+ assert_eq!(
|
|
|
228
|
+ addresses_from_status_info(&[
|
|
|
229
|
+ b"r nickname aaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbb 2038-01-01 00:00:00 192.168.1.3 9001 0",
|
|
|
230
|
+ b"a ",
|
|
|
231
|
+ b"a [cafe:dead:beef:0123::3100]:9001",
|
|
|
232
|
+ ]).unwrap(),
|
|
|
233
|
+ NodeAddresses {
|
|
|
234
|
+ ipv4: Ipv4Addr::new(192, 168, 1, 3),
|
|
|
235
|
+ ipv6: Some(Ipv6Addr::new(
|
|
|
236
|
+ 0xcafe, 0xdead, 0xbeef, 0x0123, 0, 0, 0, 0x3100
|
|
|
237
|
+ ))
|
|
|
238
|
+ }
|
|
|
239
|
+ );
|
|
|
240
|
+
|
|
|
241
|
+ assert_eq!(
|
|
|
242
|
+ addresses_from_status_info(&[
|
|
|
243
|
+ b"r nickname aaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbb 2038-01-01 00:00:00 192.168.1.3 9001 0",
|
|
|
244
|
+ b"a",
|
|
|
245
|
+ b"a [cafe:dead:beef:0123::3100]:9001",
|
|
|
246
|
+ ]).unwrap(),
|
|
|
247
|
+ NodeAddresses {
|
|
|
248
|
+ ipv4: Ipv4Addr::new(192, 168, 1, 3),
|
|
|
249
|
+ ipv6: Some(Ipv6Addr::new(
|
|
|
250
|
+ 0xcafe, 0xdead, 0xbeef, 0x0123, 0, 0, 0, 0x3100
|
|
|
251
|
+ ))
|
|
|
252
|
+ }
|
|
|
253
|
+ );
|
|
|
254
|
+ }
|
|
|
255
|
+
|
|
|
256
|
+ #[test]
|
|
|
257
|
+ fn invalid_r() {
|
|
|
258
|
+ assert_matches!(
|
|
|
259
|
+ addresses_from_status_info(&[]).unwrap_err(),
|
|
|
260
|
+ ControllerError::MalformedReply(_)
|
|
|
261
|
+ );
|
|
|
262
|
+
|
|
|
263
|
+ assert_matches!(
|
|
|
264
|
+ addresses_from_status_info(&[b"does not start with r"]).unwrap_err(),
|
|
|
265
|
+ ControllerError::MalformedReply(_)
|
|
|
266
|
+ );
|
|
|
267
|
+
|
|
|
268
|
+ assert_matches!(
|
|
|
269
|
+ addresses_from_status_info(&[
|
|
|
270
|
+ b"r nick$$name aaaa bbbb 2038-01-01 00:00:00 127.0.0.1 9001 0"
|
|
|
271
|
+ ])
|
|
|
272
|
+ .unwrap_err(),
|
|
|
273
|
+ ControllerError::MalformedReply(_)
|
|
|
274
|
+ );
|
|
|
275
|
+
|
|
|
276
|
+ assert_matches!(
|
|
|
277
|
+ addresses_from_status_info(&[
|
|
|
278
|
+ b"r nickname aa!@aa bbbb 2038-01-01 00:00:00 127.0.0.1 9001 0"
|
|
|
279
|
+ ])
|
|
|
280
|
+ .unwrap_err(),
|
|
|
281
|
+ ControllerError::MalformedReply(_)
|
|
|
282
|
+ );
|
|
|
283
|
+
|
|
|
284
|
+ assert_matches!(
|
|
|
285
|
+ addresses_from_status_info(&[
|
|
|
286
|
+ b"r nickname aaaa bbbb 2038-1-01 00:00:00 127.0.0.1 9001 0"
|
|
|
287
|
+ ])
|
|
|
288
|
+ .unwrap_err(),
|
|
|
289
|
+ ControllerError::MalformedReply(_)
|
|
|
290
|
+ );
|
|
|
291
|
+
|
|
|
292
|
+ assert_matches!(
|
|
|
293
|
+ addresses_from_status_info(&[
|
|
|
294
|
+ b"r nickname aaaa bbbb 2038-01-01 00:00:00 127.0.0.1000 9001 0"
|
|
|
295
|
+ ])
|
|
|
296
|
+ .unwrap_err(),
|
|
|
297
|
+ ControllerError::MalformedReply(_)
|
|
|
298
|
+ );
|
|
|
299
|
+
|
|
|
300
|
+ assert_matches!(
|
|
|
301
|
+ addresses_from_status_info(&[
|
|
|
302
|
+ b"r nickname aaaa bbbb 2038-01-01 00:00:00 ....123 9001 0"
|
|
|
303
|
+ ])
|
|
|
304
|
+ .unwrap_err(),
|
|
|
305
|
+ ControllerError::MalformedReply(_)
|
|
|
306
|
+ );
|
|
|
307
|
+
|
|
|
308
|
+ // Bad IPv4 (an octet is 3 digits but higher than 255)
|
|
|
309
|
+ assert_matches!(
|
|
|
310
|
+ addresses_from_status_info(&[
|
|
|
311
|
+ b"r nickname aaaa bbbb 2038-01-01 00:00:00 127.0.0.300 9001 0"
|
|
|
312
|
+ ])
|
|
|
313
|
+ .unwrap_err(),
|
|
|
314
|
+ ControllerError::MalformedReply(_)
|
|
|
315
|
+ );
|
|
|
316
|
+
|
|
|
317
|
+ assert_matches!(
|
|
|
318
|
+ addresses_from_status_info(&[
|
|
|
319
|
+ b"r nickname aaaa bbbb 2000-06-08 15:10:00 1.2.3.4 100000 0"
|
|
|
320
|
+ ])
|
|
|
321
|
+ .unwrap_err(),
|
|
|
322
|
+ ControllerError::MalformedReply(_)
|
|
|
323
|
+ );
|
|
|
324
|
+
|
|
|
325
|
+ assert_matches!(
|
|
|
326
|
+ addresses_from_status_info(&[
|
|
|
327
|
+ b"rrr nickname aaaa bbbb 2000-06-08 15:10:00 1.2.3.4 1000 0"
|
|
|
328
|
+ ])
|
|
|
329
|
+ .unwrap_err(),
|
|
|
330
|
+ ControllerError::MalformedReply(_)
|
|
|
331
|
+ );
|
|
|
332
|
+
|
|
|
333
|
+ assert_matches!(
|
|
|
334
|
+ addresses_from_status_info(&[
|
|
|
335
|
+ b"garbage r nickname aaaa bbbb 2000-06-08 15:10:00 1.2.3.4 9000 0"
|
|
|
336
|
+ ])
|
|
|
337
|
+ .unwrap_err(),
|
|
|
338
|
+ ControllerError::MalformedReply(_)
|
|
|
339
|
+ );
|
|
|
340
|
+
|
|
|
341
|
+ assert_matches!(
|
|
|
342
|
+ addresses_from_status_info(&[
|
|
|
343
|
+ b"r nickname aaaa bbbb 2000-06-08 15:10:00 1.2.3.4 443 0 garbage"
|
|
|
344
|
+ ])
|
|
|
345
|
+ .unwrap_err(),
|
|
|
346
|
+ ControllerError::MalformedReply(_)
|
|
|
347
|
+ );
|
|
|
348
|
+
|
|
|
349
|
+ assert_matches!(
|
|
|
350
|
+ addresses_from_status_info(&[
|
|
|
351
|
+ b"R nickname aaaa bbbb 2000-06-08 15:10:00 1.2.3.4 443 0"
|
|
|
352
|
+ ])
|
|
|
353
|
+ .unwrap_err(),
|
|
|
354
|
+ ControllerError::MalformedReply(_)
|
|
|
355
|
+ );
|
|
|
356
|
+
|
|
|
357
|
+ // Only IPv6 is not valid
|
|
|
358
|
+ assert_matches!(
|
|
|
359
|
+ addresses_from_status_info(&[b"a [fdc8:08d6:f860:d6c::3100]:9001"]).unwrap_err(),
|
|
|
360
|
+ ControllerError::MalformedReply(_)
|
|
|
361
|
+ );
|
|
|
362
|
+
|
|
|
363
|
+ // r must come first
|
|
|
364
|
+ assert_matches!(
|
|
|
365
|
+ addresses_from_status_info(&[
|
|
|
366
|
+ b"a [fdc8:08d6:f860:d6c::3100]:9001",
|
|
|
367
|
+ b"r nickname aaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbb 2038-01-01 00:00:00 192.168.1.3 9001 0",
|
|
|
368
|
+ ]).unwrap_err(),
|
|
|
369
|
+ ControllerError::MalformedReply(_)
|
|
|
370
|
+ );
|
|
|
371
|
+ }
|
|
|
372
|
+
|
|
|
373
|
+ #[test]
|
|
|
374
|
+ fn fields_not_validated() {
|
|
|
375
|
+ // Some fiels are not validated on purposes.
|
|
|
376
|
+ // We might change this in the future, but for now we accept them, so
|
|
|
377
|
+ // we create these tests just to remind us about this.
|
|
|
378
|
+
|
|
|
379
|
+ // Digest is in base64. tor's convention is to use unpadded base64, but
|
|
|
380
|
+ // the specs are not explicit about it (while they are for identity).
|
|
|
381
|
+ // Let's check we accept a padded base64 for it.
|
|
|
382
|
+ assert!(addresses_from_status_info(&[
|
|
|
383
|
+ b"r nickname aaaa bbbb= 2026-11-09 10:34:58 1.2.3.4 7777 8888"
|
|
|
384
|
+ ])
|
|
|
385
|
+ .is_ok());
|
|
|
386
|
+
|
|
|
387
|
+ // No validation on date and time, except for the format.
|
|
|
388
|
+ assert!(addresses_from_status_info(&[
|
|
|
389
|
+ b"r nickname aaaa bbbb 2038-25-50 00:00:00 1.2.3.4 7777 8888"
|
|
|
390
|
+ ])
|
|
|
391
|
+ .is_ok());
|
|
|
392
|
+ assert!(addresses_from_status_info(&[
|
|
|
393
|
+ b"r nickname aaaa bbbb 2000-04-12 32:80:99 1.2.3.4 7777 8888"
|
|
|
394
|
+ ])
|
|
|
395
|
+ .is_ok());
|
|
|
396
|
+
|
|
|
397
|
+ // Ports are not validated either, except for length.
|
|
|
398
|
+ assert!(addresses_from_status_info(&[
|
|
|
399
|
+ b"r nickname aaaa bbbb 2000-10-15 12:34:56 1.2.3.4 99999 67890"
|
|
|
400
|
+ ])
|
|
|
401
|
+ .is_ok());
|
|
|
402
|
+ }
|
|
|
403
|
+} |
toolkit/components/tor-integration/tor_provider/src/ctor/controller/parsers/onion_client_auth_view.rs
|
|
1
|
+// Licensed under the Apache License, Version 2.0,
|
|
|
2
|
+// <http://apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
3
|
+// <http://opensource.org/licenses/MIT>, at your option. This file may not be
|
|
|
4
|
+// copied, modified, or distributed except according to those terms.
|
|
|
5
|
+
|
|
|
6
|
+use lazy_static::lazy_static;
|
|
|
7
|
+use regex::Regex;
|
|
|
8
|
+
|
|
|
9
|
+use super::parse_key_value_pairs;
|
|
|
10
|
+use crate::ctor::{
|
|
|
11
|
+ controller::{types::*, ControllerError},
|
|
|
12
|
+ reply_parser::{DetailReplyLine, Reply},
|
|
|
13
|
+};
|
|
|
14
|
+
|
|
|
15
|
+lazy_static! {
|
|
|
16
|
+ static ref CLIENT_REGEX: Regex = Regex::new(
|
|
|
17
|
+ r"^(?i)CLIENT (?<HSAddress>[a-zA-Z2-7]{56}) (?<KeyType>[A-Za-z0-9]+):(?<PrivateKeyBlob>[A-Za-z0-9+/]+={0,3})(?: (?<Args>.+))?$"
|
|
|
18
|
+ )
|
|
|
19
|
+ .expect("The regex is hardcoded, it should be good.");
|
|
|
20
|
+}
|
|
|
21
|
+
|
|
|
22
|
+const AUTH_VIEW_HEADER: &[u8] = b"ONION_CLIENT_AUTH_VIEW";
|
|
|
23
|
+
|
|
|
24
|
+/// Check the first line of the reply to ONION_CLIENT_AUTH_VIEW.
|
|
|
25
|
+fn check_auth_view(line: Option<&DetailReplyLine>) -> Result<(), ControllerError> {
|
|
|
26
|
+ if let Some(DetailReplyLine::MidReplyLine { code, line }) = line {
|
|
|
27
|
+ if *code != 250 {
|
|
|
28
|
+ // The first thing we check is that we end with "250 OK", so this
|
|
|
29
|
+ // error code is okay.
|
|
|
30
|
+ return Err(ControllerError::MixedCodes);
|
|
|
31
|
+ }
|
|
|
32
|
+ if line.eq_ignore_ascii_case(AUTH_VIEW_HEADER) {
|
|
|
33
|
+ return Ok(());
|
|
|
34
|
+ }
|
|
|
35
|
+ }
|
|
|
36
|
+ Err(ControllerError::MalformedReply(String::from(
|
|
|
37
|
+ "the first line must be 250-ONION_CLIENT_AUTH_VIEW.",
|
|
|
38
|
+ )))
|
|
|
39
|
+}
|
|
|
40
|
+
|
|
|
41
|
+/// Parse an individual 250-CLIENT line, which follows this format:
|
|
|
42
|
+/// `250-CLIENT <hs-address> <key-type>:<key-blob> <kw-args>`.
|
|
|
43
|
+///
|
|
|
44
|
+/// Note:
|
|
|
45
|
+/// - hs-address is expected not to have the .onion suffix
|
|
|
46
|
+/// - we will accept any key type, even though tor only supports x25519
|
|
|
47
|
+/// - key-blob is expected to be base64 (but we perform a light validation and
|
|
|
48
|
+/// return the key as we received it)
|
|
|
49
|
+/// - we only parse the Flags keyword argument, and only the permanent flag
|
|
|
50
|
+/// (in a case-insensitive manner)
|
|
|
51
|
+fn parse_client_line(data: &[u8]) -> Result<OnionClientAuth, ControllerError> {
|
|
|
52
|
+ // The reply for this command should not contain escaped strings, but only
|
|
|
53
|
+ // ASCII data. So, it must also be valid UTF-8.
|
|
|
54
|
+ let data = str::from_utf8(data).map_err(|e| ControllerError::MalformedReply(e.to_string()))?;
|
|
|
55
|
+ let groups = CLIENT_REGEX
|
|
|
56
|
+ .captures(data)
|
|
|
57
|
+ .ok_or_else(|| ControllerError::WrongFormat(data.to_string()))?;
|
|
|
58
|
+
|
|
|
59
|
+ let address =
|
|
|
60
|
+ HSAddress::from_str(&groups["HSAddress"]).map_err(|e| ControllerError::from(e))?;
|
|
|
61
|
+
|
|
|
62
|
+ let key_type = groups["KeyType"].into();
|
|
|
63
|
+ let key_blob = groups["PrivateKeyBlob"].into();
|
|
|
64
|
+
|
|
|
65
|
+ let is_permanent = groups
|
|
|
66
|
+ .name("Args")
|
|
|
67
|
+ .map(|a| parse_key_value_pairs(a.as_str().as_bytes(), &["Flags"]))
|
|
|
68
|
+ .transpose()?
|
|
|
69
|
+ .and_then(|args| {
|
|
|
70
|
+ args.get("Flags").map(|flags| {
|
|
|
71
|
+ flags
|
|
|
72
|
+ .split(|b| *b == b',')
|
|
|
73
|
+ .any(|flag| flag.eq_ignore_ascii_case(b"Permanent"))
|
|
|
74
|
+ })
|
|
|
75
|
+ })
|
|
|
76
|
+ .unwrap_or(false);
|
|
|
77
|
+
|
|
|
78
|
+ Ok(OnionClientAuth {
|
|
|
79
|
+ address,
|
|
|
80
|
+ key_type,
|
|
|
81
|
+ key_blob,
|
|
|
82
|
+ is_permanent,
|
|
|
83
|
+ })
|
|
|
84
|
+}
|
|
|
85
|
+
|
|
|
86
|
+/// Parse the full reply to a ONION_CLIENT_AUTH_VIEW command.
|
|
|
87
|
+pub fn parse_onion_client_auth_view(reply: Reply) -> Result<Vec<OnionClientAuth>, ControllerError> {
|
|
|
88
|
+ if let Some(e) = ControllerError::from_reply(&reply) {
|
|
|
89
|
+ return Err(e);
|
|
|
90
|
+ }
|
|
|
91
|
+ if reply.end_line().code != 250 {
|
|
|
92
|
+ return Err(ControllerError::MalformedReply(format!(
|
|
|
93
|
+ "expected the end line to be a '250 OK', found '{}'",
|
|
|
94
|
+ String::from_utf8_lossy(reply.end_line().line.as_ref())
|
|
|
95
|
+ )));
|
|
|
96
|
+ }
|
|
|
97
|
+
|
|
|
98
|
+ check_auth_view(reply.details().first())?;
|
|
|
99
|
+
|
|
|
100
|
+ reply.details()[1..]
|
|
|
101
|
+ .iter()
|
|
|
102
|
+ .map(|l| match l {
|
|
|
103
|
+ DetailReplyLine::MidReplyLine { code, line } => {
|
|
|
104
|
+ if *code == 250 {
|
|
|
105
|
+ parse_client_line(line.as_ref())
|
|
|
106
|
+ } else {
|
|
|
107
|
+ Err(ControllerError::MixedCodes)
|
|
|
108
|
+ }
|
|
|
109
|
+ }
|
|
|
110
|
+ DetailReplyLine::DataReplyLine { .. } => Err(ControllerError::MalformedReply(
|
|
|
111
|
+ String::from("Datalines are not allowed in ONION_CLIENT_AUTH_VIEW."),
|
|
|
112
|
+ )),
|
|
|
113
|
+ })
|
|
|
114
|
+ .collect()
|
|
|
115
|
+}
|
|
|
116
|
+
|
|
|
117
|
+#[cfg(test)]
|
|
|
118
|
+mod tests {
|
|
|
119
|
+ use std::assert_matches;
|
|
|
120
|
+
|
|
|
121
|
+ use super::*;
|
|
|
122
|
+ use crate::ctor::reply_parser::make_reply;
|
|
|
123
|
+
|
|
|
124
|
+ #[test]
|
|
|
125
|
+ fn single_no_permanent() {
|
|
|
126
|
+ let raw = concat!(
|
|
|
127
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n",
|
|
|
128
|
+ "250-CLIENT pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd x25519:abcdef1234567890+/==\r\n",
|
|
|
129
|
+ "250 OK\r\n"
|
|
|
130
|
+ );
|
|
|
131
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
132
|
+ let result = parse_onion_client_auth_view(reply).unwrap();
|
|
|
133
|
+ assert_eq!(
|
|
|
134
|
+ result,
|
|
|
135
|
+ vec![OnionClientAuth {
|
|
|
136
|
+ address: HSAddress::new(
|
|
|
137
|
+ b"pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd"
|
|
|
138
|
+ )
|
|
|
139
|
+ .unwrap(),
|
|
|
140
|
+ key_type: String::from("x25519"),
|
|
|
141
|
+ key_blob: String::from("abcdef1234567890+/=="),
|
|
|
142
|
+ is_permanent: false,
|
|
|
143
|
+ }]
|
|
|
144
|
+ )
|
|
|
145
|
+ }
|
|
|
146
|
+
|
|
|
147
|
+ #[test]
|
|
|
148
|
+ fn single_permanent() {
|
|
|
149
|
+ let raw = concat!(
|
|
|
150
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n",
|
|
|
151
|
+ "250-CLIENT pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd x25519:abcdef1234567890+/== Flags=Permanent\r\n",
|
|
|
152
|
+ "250 OK\r\n"
|
|
|
153
|
+ );
|
|
|
154
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
155
|
+ let result = parse_onion_client_auth_view(reply).unwrap();
|
|
|
156
|
+ assert_eq!(
|
|
|
157
|
+ result,
|
|
|
158
|
+ vec![OnionClientAuth {
|
|
|
159
|
+ address: HSAddress::new(
|
|
|
160
|
+ b"pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd"
|
|
|
161
|
+ )
|
|
|
162
|
+ .unwrap(),
|
|
|
163
|
+ key_type: String::from("x25519"),
|
|
|
164
|
+ key_blob: String::from("abcdef1234567890+/=="),
|
|
|
165
|
+ is_permanent: true,
|
|
|
166
|
+ }]
|
|
|
167
|
+ )
|
|
|
168
|
+ }
|
|
|
169
|
+
|
|
|
170
|
+ #[test]
|
|
|
171
|
+ fn empty() {
|
|
|
172
|
+ let reply = make_reply(b"250-ONION_CLIENT_AUTH_VIEW\r\n250 OK\r\n");
|
|
|
173
|
+ let result = parse_onion_client_auth_view(reply).unwrap();
|
|
|
174
|
+ assert_eq!(result, vec![]);
|
|
|
175
|
+ }
|
|
|
176
|
+
|
|
|
177
|
+ #[test]
|
|
|
178
|
+ fn multiple() {
|
|
|
179
|
+ let raw = concat!(
|
|
|
180
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n",
|
|
|
181
|
+ "250-CLIENT pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd x25519:abcdef1234567890+/== Flags=Permanent\r\n",
|
|
|
182
|
+ "250-CLIENT sp3k262uwy4r2k3ycr5awluarykdpag6a7y33jxop4cs2lu5uz5sseqd x25519:thekeyhere\r\n",
|
|
|
183
|
+ "250 OK\r\n"
|
|
|
184
|
+ );
|
|
|
185
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
186
|
+ let result = parse_onion_client_auth_view(reply).unwrap();
|
|
|
187
|
+ assert_eq!(
|
|
|
188
|
+ result,
|
|
|
189
|
+ vec![
|
|
|
190
|
+ OnionClientAuth {
|
|
|
191
|
+ address: HSAddress::new(
|
|
|
192
|
+ b"pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd"
|
|
|
193
|
+ )
|
|
|
194
|
+ .unwrap(),
|
|
|
195
|
+ key_type: String::from("x25519"),
|
|
|
196
|
+ key_blob: String::from("abcdef1234567890+/=="),
|
|
|
197
|
+ is_permanent: true,
|
|
|
198
|
+ },
|
|
|
199
|
+ OnionClientAuth {
|
|
|
200
|
+ address: HSAddress::new(
|
|
|
201
|
+ b"sp3k262uwy4r2k3ycr5awluarykdpag6a7y33jxop4cs2lu5uz5sseqd"
|
|
|
202
|
+ )
|
|
|
203
|
+ .unwrap(),
|
|
|
204
|
+ key_type: String::from("x25519"),
|
|
|
205
|
+ key_blob: String::from("thekeyhere"),
|
|
|
206
|
+ is_permanent: false,
|
|
|
207
|
+ },
|
|
|
208
|
+ ]
|
|
|
209
|
+ )
|
|
|
210
|
+ }
|
|
|
211
|
+
|
|
|
212
|
+ #[test]
|
|
|
213
|
+ fn case_insensitive() {
|
|
|
214
|
+ let raw = concat!(
|
|
|
215
|
+ "250-onioN_CLIENt_autH_VIEW\r\n",
|
|
|
216
|
+ "250-CLieNt Pg6MmjiYjMcRssLvyKFWNntLARu7P5SVn6y2YMMJu6NUbxNdf4PscRYD x25519:abcdef1234567890+/== fLaGs=permAnEnt\r\n",
|
|
|
217
|
+ "250 OK\r\n"
|
|
|
218
|
+ );
|
|
|
219
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
220
|
+ let result = parse_onion_client_auth_view(reply).unwrap();
|
|
|
221
|
+ assert_eq!(
|
|
|
222
|
+ result,
|
|
|
223
|
+ vec![OnionClientAuth {
|
|
|
224
|
+ address: HSAddress::new(
|
|
|
225
|
+ b"pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd"
|
|
|
226
|
+ )
|
|
|
227
|
+ .unwrap(),
|
|
|
228
|
+ key_type: String::from("x25519"),
|
|
|
229
|
+ key_blob: String::from("abcdef1234567890+/=="),
|
|
|
230
|
+ is_permanent: true,
|
|
|
231
|
+ }]
|
|
|
232
|
+ )
|
|
|
233
|
+ }
|
|
|
234
|
+
|
|
|
235
|
+ #[test]
|
|
|
236
|
+ fn unknown_flags() {
|
|
|
237
|
+ let raw = concat!(
|
|
|
238
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n",
|
|
|
239
|
+ "250-CLIENT pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd x25519:abcdef1234567890+/== Flags=SomeFlag,AnotherFlag\r\n",
|
|
|
240
|
+ "250 OK\r\n"
|
|
|
241
|
+ );
|
|
|
242
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
243
|
+ let result = parse_onion_client_auth_view(reply).unwrap();
|
|
|
244
|
+ assert_eq!(
|
|
|
245
|
+ result,
|
|
|
246
|
+ vec![OnionClientAuth {
|
|
|
247
|
+ address: HSAddress::new(
|
|
|
248
|
+ b"pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd"
|
|
|
249
|
+ )
|
|
|
250
|
+ .unwrap(),
|
|
|
251
|
+ key_type: String::from("x25519"),
|
|
|
252
|
+ key_blob: String::from("abcdef1234567890+/=="),
|
|
|
253
|
+ is_permanent: false,
|
|
|
254
|
+ }]
|
|
|
255
|
+ )
|
|
|
256
|
+ }
|
|
|
257
|
+
|
|
|
258
|
+ #[test]
|
|
|
259
|
+ fn multiple_flags() {
|
|
|
260
|
+ let raw = concat!(
|
|
|
261
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n",
|
|
|
262
|
+ "250-CLIENT pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd x25519:abcdef1234567890+/== Flags=SomeFlag,Permanent,AnotherFlag\r\n",
|
|
|
263
|
+ "250 OK\r\n"
|
|
|
264
|
+ );
|
|
|
265
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
266
|
+ let result = parse_onion_client_auth_view(reply).unwrap();
|
|
|
267
|
+ assert_eq!(
|
|
|
268
|
+ result,
|
|
|
269
|
+ vec![OnionClientAuth {
|
|
|
270
|
+ address: HSAddress::new(
|
|
|
271
|
+ b"pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd"
|
|
|
272
|
+ )
|
|
|
273
|
+ .unwrap(),
|
|
|
274
|
+ key_type: String::from("x25519"),
|
|
|
275
|
+ key_blob: String::from("abcdef1234567890+/=="),
|
|
|
276
|
+ is_permanent: true,
|
|
|
277
|
+ }]
|
|
|
278
|
+ )
|
|
|
279
|
+ }
|
|
|
280
|
+
|
|
|
281
|
+ #[test]
|
|
|
282
|
+ fn client_name_ignored() {
|
|
|
283
|
+ {
|
|
|
284
|
+ let raw = concat!(
|
|
|
285
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n",
|
|
|
286
|
+ "250-CLIENT pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd x25519:abcdef1234567890+/== ClientName=test\r\n",
|
|
|
287
|
+ "250 OK\r\n"
|
|
|
288
|
+ );
|
|
|
289
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
290
|
+ assert!(parse_onion_client_auth_view(reply).is_ok());
|
|
|
291
|
+ }
|
|
|
292
|
+
|
|
|
293
|
+ {
|
|
|
294
|
+ let raw = concat!(
|
|
|
295
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n",
|
|
|
296
|
+ "250-CLIENT pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd x25519:abcdef1234567890+/== ClientName=test Flags=Permanent\r\n",
|
|
|
297
|
+ "250 OK\r\n"
|
|
|
298
|
+ );
|
|
|
299
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
300
|
+ let result = parse_onion_client_auth_view(reply).unwrap();
|
|
|
301
|
+ assert!(result[0].is_permanent);
|
|
|
302
|
+ }
|
|
|
303
|
+ {
|
|
|
304
|
+ let raw = concat!(
|
|
|
305
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n",
|
|
|
306
|
+ "250-CLIENT pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd x25519:abcdef1234567890+/== ClientName=test Flags=\r\n",
|
|
|
307
|
+ "250 OK\r\n"
|
|
|
308
|
+ );
|
|
|
309
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
310
|
+ let result = parse_onion_client_auth_view(reply).unwrap();
|
|
|
311
|
+ assert!(!result[0].is_permanent);
|
|
|
312
|
+ }
|
|
|
313
|
+
|
|
|
314
|
+ // In the specs, Flags is listed after ClientName, but we accept any
|
|
|
315
|
+ // order.
|
|
|
316
|
+ {
|
|
|
317
|
+ let raw = concat!(
|
|
|
318
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n",
|
|
|
319
|
+ "250-CLIENT pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd x25519:abcdef1234567890+/== Flags=Permanent ClientName=test\r\n",
|
|
|
320
|
+ "250 OK\r\n"
|
|
|
321
|
+ );
|
|
|
322
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
323
|
+ let result = parse_onion_client_auth_view(reply).unwrap();
|
|
|
324
|
+ assert!(result[0].is_permanent);
|
|
|
325
|
+ }
|
|
|
326
|
+ {
|
|
|
327
|
+ let raw = concat!(
|
|
|
328
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n",
|
|
|
329
|
+ "250-CLIENT pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd x25519:abcdef1234567890+/== Flags= ClientName=test\r\n",
|
|
|
330
|
+ "250 OK\r\n"
|
|
|
331
|
+ );
|
|
|
332
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
333
|
+ let result = parse_onion_client_auth_view(reply).unwrap();
|
|
|
334
|
+ assert!(!result[0].is_permanent);
|
|
|
335
|
+ }
|
|
|
336
|
+ }
|
|
|
337
|
+
|
|
|
338
|
+ #[test]
|
|
|
339
|
+ fn unsuccessful_end_code() {
|
|
|
340
|
+ {
|
|
|
341
|
+ let reply = make_reply(b"512 Syntax error\r\n");
|
|
|
342
|
+ let result = parse_onion_client_auth_view(reply);
|
|
|
343
|
+ assert_matches!(
|
|
|
344
|
+ result.unwrap_err(),
|
|
|
345
|
+ ControllerError::TorError { code: 512, .. }
|
|
|
346
|
+ );
|
|
|
347
|
+ }
|
|
|
348
|
+ {
|
|
|
349
|
+ let reply = make_reply(b"250-ONION_CLIENT_AUTH_VIEW\r\n512 Syntax error\r\n");
|
|
|
350
|
+ let result = parse_onion_client_auth_view(reply);
|
|
|
351
|
+ assert_matches!(
|
|
|
352
|
+ result.unwrap_err(),
|
|
|
353
|
+ ControllerError::TorError { code: 512, .. }
|
|
|
354
|
+ );
|
|
|
355
|
+ }
|
|
|
356
|
+ }
|
|
|
357
|
+
|
|
|
358
|
+ #[test]
|
|
|
359
|
+ fn bad_header() {
|
|
|
360
|
+ {
|
|
|
361
|
+ let reply = make_reply(b"250 OK\r\n");
|
|
|
362
|
+ let result = parse_onion_client_auth_view(reply);
|
|
|
363
|
+ assert_matches!(result.unwrap_err(), ControllerError::MalformedReply(_));
|
|
|
364
|
+ }
|
|
|
365
|
+ {
|
|
|
366
|
+ let reply = make_reply(b"254-BAD HEADER\r\n250 OK\r\n");
|
|
|
367
|
+ let result = parse_onion_client_auth_view(reply);
|
|
|
368
|
+ assert_eq!(result.unwrap_err(), ControllerError::MixedCodes);
|
|
|
369
|
+ }
|
|
|
370
|
+ {
|
|
|
371
|
+ let reply = make_reply(b"250-BAD HEADER\r\n250 OK\r\n");
|
|
|
372
|
+ let result = parse_onion_client_auth_view(reply);
|
|
|
373
|
+ assert_matches!(result.unwrap_err(), ControllerError::MalformedReply(_));
|
|
|
374
|
+ }
|
|
|
375
|
+ {
|
|
|
376
|
+ let reply = make_reply(b"250+DataReply Header\r\n.\r\n250 OK\r\n");
|
|
|
377
|
+ let result = parse_onion_client_auth_view(reply);
|
|
|
378
|
+ assert_matches!(result.unwrap_err(), ControllerError::MalformedReply(_));
|
|
|
379
|
+ }
|
|
|
380
|
+ }
|
|
|
381
|
+
|
|
|
382
|
+ #[test]
|
|
|
383
|
+ fn datalines() {
|
|
|
384
|
+ {
|
|
|
385
|
+ let raw = concat!(
|
|
|
386
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n",
|
|
|
387
|
+ "250+CLIENT\r\n.\r\n",
|
|
|
388
|
+ "250 OK\r\n"
|
|
|
389
|
+ );
|
|
|
390
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
391
|
+ let result = parse_onion_client_auth_view(reply);
|
|
|
392
|
+ assert_matches!(result.unwrap_err(), ControllerError::MalformedReply(_));
|
|
|
393
|
+ }
|
|
|
394
|
+ {
|
|
|
395
|
+ let raw = concat!(
|
|
|
396
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n",
|
|
|
397
|
+ "250-CLIENT pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd x25519:abcdef1234567890+/==\r\n",
|
|
|
398
|
+ "250+CLIENT\r\n.\r\n",
|
|
|
399
|
+ "250 OK\r\n"
|
|
|
400
|
+ );
|
|
|
401
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
402
|
+ let result = parse_onion_client_auth_view(reply);
|
|
|
403
|
+ assert_matches!(result.unwrap_err(), ControllerError::MalformedReply(_));
|
|
|
404
|
+ }
|
|
|
405
|
+ {
|
|
|
406
|
+ let raw = concat!(
|
|
|
407
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n",
|
|
|
408
|
+ "250+CLIENT\r\n.\r\n",
|
|
|
409
|
+ "250-CLIENT pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd x25519:abcdef1234567890+/==\r\n",
|
|
|
410
|
+ "250 OK\r\n"
|
|
|
411
|
+ );
|
|
|
412
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
413
|
+ let result = parse_onion_client_auth_view(reply);
|
|
|
414
|
+ assert_matches!(result.unwrap_err(), ControllerError::MalformedReply(_));
|
|
|
415
|
+ }
|
|
|
416
|
+ }
|
|
|
417
|
+
|
|
|
418
|
+ #[test]
|
|
|
419
|
+ fn no_250_codes() {
|
|
|
420
|
+ {
|
|
|
421
|
+ let raw = concat!(
|
|
|
422
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n",
|
|
|
423
|
+ "251-CLIENT pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd x25519:abcdef1234567890+/==\r\n",
|
|
|
424
|
+ "250 OK\r\n"
|
|
|
425
|
+ );
|
|
|
426
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
427
|
+ let result = parse_onion_client_auth_view(reply);
|
|
|
428
|
+ assert_eq!(result.unwrap_err(), ControllerError::MixedCodes);
|
|
|
429
|
+ }
|
|
|
430
|
+ {
|
|
|
431
|
+ let raw = concat!(
|
|
|
432
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n",
|
|
|
433
|
+ "250-CLIENT pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd x25519:abcdef1234567890+/==\r\n",
|
|
|
434
|
+ "251-CLIENT sp3k262uwy4r2k3ycr5awluarykdpag6a7y33jxop4cs2lu5uz5sseqd x25519:abcdef1234567890+/==\r\n",
|
|
|
435
|
+ "250 OK\r\n"
|
|
|
436
|
+ );
|
|
|
437
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
438
|
+ let result = parse_onion_client_auth_view(reply);
|
|
|
439
|
+ assert_eq!(result.unwrap_err(), ControllerError::MixedCodes);
|
|
|
440
|
+ }
|
|
|
441
|
+ {
|
|
|
442
|
+ let raw = concat!(
|
|
|
443
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n",
|
|
|
444
|
+ "251-CLIENT sp3k262uwy4r2k3ycr5awluarykdpag6a7y33jxop4cs2lu5uz5sseqd x25519:abcdef1234567890+/==\r\n",
|
|
|
445
|
+ "250-CLIENT pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd x25519:abcdef1234567890+/==\r\n",
|
|
|
446
|
+ "250 OK\r\n"
|
|
|
447
|
+ );
|
|
|
448
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
449
|
+ let result = parse_onion_client_auth_view(reply);
|
|
|
450
|
+ assert_eq!(result.unwrap_err(), ControllerError::MixedCodes);
|
|
|
451
|
+ }
|
|
|
452
|
+ {
|
|
|
453
|
+ let raw = concat!("251-ONION_CLIENT_AUTH_VIEW\r\n", "250 OK\r\n");
|
|
|
454
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
455
|
+ let result = parse_onion_client_auth_view(reply);
|
|
|
456
|
+ assert_eq!(result.unwrap_err(), ControllerError::MixedCodes);
|
|
|
457
|
+ }
|
|
|
458
|
+ {
|
|
|
459
|
+ let raw = concat!("251-ONION_CLIENT_AUTH_VIEW\r\n", "251 OK\r\n");
|
|
|
460
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
461
|
+ assert!(parse_onion_client_auth_view(reply).is_err());
|
|
|
462
|
+ }
|
|
|
463
|
+ {
|
|
|
464
|
+ let raw = concat!("250-ONION_CLIENT_AUTH_VIEW\r\n", "251 OK\r\n");
|
|
|
465
|
+ let reply = make_reply(raw.as_bytes());
|
|
|
466
|
+ assert!(parse_onion_client_auth_view(reply).is_err());
|
|
|
467
|
+ }
|
|
|
468
|
+ }
|
|
|
469
|
+
|
|
|
470
|
+ #[test]
|
|
|
471
|
+ fn malformed_client_line() {
|
|
|
472
|
+ let make_error =
|
|
|
473
|
+ |r: &'static str| parse_onion_client_auth_view(make_reply(r.as_bytes())).unwrap_err();
|
|
|
474
|
+
|
|
|
475
|
+ assert_matches!(
|
|
|
476
|
+ make_error("250-ONION_CLIENT_AUTH_VIEW\r\n250-aaaaaaaaa\r\n250 OK\r\n"),
|
|
|
477
|
+ ControllerError::WrongFormat(_)
|
|
|
478
|
+ );
|
|
|
479
|
+ assert_matches!(
|
|
|
480
|
+ make_error("250-ONION_CLIENT_AUTH_VIEW\r\n250-client aaaaaaaaa\r\n250 OK\r\n"),
|
|
|
481
|
+ ControllerError::WrongFormat(_)
|
|
|
482
|
+ );
|
|
|
483
|
+ assert_matches!(
|
|
|
484
|
+ make_error(
|
|
|
485
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n250-client aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa x25519:aaaa\r\n250 OK\r\n"
|
|
|
486
|
+ ),
|
|
|
487
|
+ ControllerError::InvalidOnionAddress(_)
|
|
|
488
|
+ );
|
|
|
489
|
+ assert_matches!(
|
|
|
490
|
+ make_error(
|
|
|
491
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n250-CLIENT sp3k262uwy4r2k3ycr5awluarykdpag6a7y33jxop4cs2lu5uz5sseqd x25519:not_base_64!!\r\n250 OK\r\n"
|
|
|
492
|
+ ),
|
|
|
493
|
+ ControllerError::WrongFormat(_)
|
|
|
494
|
+ );
|
|
|
495
|
+ assert_matches!(
|
|
|
496
|
+ make_error(
|
|
|
497
|
+ "250-ONION_CLIENT_AUTH_VIEW\r\n250-CLIENT sp3k262uwy4r2k3ycr5awluarykdpag6a7y33jxop4cs2lu5uz5sseqd x25519:aaaa KeyWithoutEqual\r\n250 OK\r\n"
|
|
|
498
|
+ ),
|
|
|
499
|
+ ControllerError::MalformedReply(_)
|
|
|
500
|
+ );
|
|
|
501
|
+ }
|
|
|
502
|
+} |
toolkit/components/tor-integration/tor_provider/src/ctor/controller/parsers/socks_listeners.rs
|
|
1
|
+// Licensed under the Apache License, Version 2.0,
|
|
|
2
|
+// <http://apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
3
|
+// <http://opensource.org/licenses/MIT>, at your option. This file may not be
|
|
|
4
|
+// copied, modified, or distributed except according to those terms.
|
|
|
5
|
+
|
|
|
6
|
+use lazy_static::lazy_static;
|
|
|
7
|
+use regex::bytes::Regex;
|
|
|
8
|
+use std::path::PathBuf;
|
|
|
9
|
+
|
|
|
10
|
+use super::tor_unescape;
|
|
|
11
|
+use crate::ctor::controller::{types::*, ControllerError};
|
|
|
12
|
+
|
|
|
13
|
+lazy_static! {
|
|
|
14
|
+ // This regular _expression_ does not include $ on purpose, as we are looping
|
|
|
15
|
+ // on all values: we get the first quoted value and consume any spaces at
|
|
|
16
|
+ // end. Then we feed the rest of the string to the same regex, and if it
|
|
|
17
|
+ // fails it means there was garbage and we should reject the entire reply.
|
|
|
18
|
+ static ref LISTENERS_REGEX: Regex = Regex::new(r#"^ *("(?:[^"\\]|\\.)+")( +|$)"#)
|
|
|
19
|
+ .expect("The regex is hardcoded, it should be good.");
|
|
|
20
|
+}
|
|
|
21
|
+
|
|
|
22
|
+/// Parse a Unix-domain socket path on Windows.
|
|
|
23
|
+/// Since they are not supported on Windows, we return None.
|
|
|
24
|
+#[cfg(target_os = "windows")]
|
|
|
25
|
+fn make_path(_buf: &[u8]) -> Option<PathBuf> {
|
|
|
26
|
+ None
|
|
|
27
|
+}
|
|
|
28
|
+
|
|
|
29
|
+/// Parse a Unix-domain socket on a non-Windows platform.
|
|
|
30
|
+/// This function always returns a Some(<path>), even when the path is empty.
|
|
|
31
|
+#[cfg(not(target_os = "windows"))]
|
|
|
32
|
+fn make_path(buf: &[u8]) -> Option<PathBuf> {
|
|
|
33
|
+ use std::{ffi::OsStr, os::unix::ffi::OsStrExt};
|
|
|
34
|
+ Some(PathBuf::from(OsStr::from_bytes(buf)))
|
|
|
35
|
+}
|
|
|
36
|
+
|
|
|
37
|
+/// Parse a single SOCKS listener.
|
|
|
38
|
+fn parse_listener(listener: &[u8]) -> Option<Result<SocksListener, ControllerError>> {
|
|
|
39
|
+ let addr = match tor_unescape(listener) {
|
|
|
40
|
+ Ok(a) => a,
|
|
|
41
|
+ Err(e) => {
|
|
|
42
|
+ return Some(Err(ControllerError::MalformedReply(e.to_string())));
|
|
|
43
|
+ }
|
|
|
44
|
+ };
|
|
|
45
|
+ if addr.starts_with(b"unix:/") {
|
|
|
46
|
+ make_path(&addr[5..]).map(|p| Ok(SocksListener::UnixSocket(p)))
|
|
|
47
|
+ } else {
|
|
|
48
|
+ Some(
|
|
|
49
|
+ str::from_utf8(&*addr)
|
|
|
50
|
+ .map_err(|e| ControllerError::MalformedReply(format!("{}", e)))
|
|
|
51
|
+ .and_then(|s| {
|
|
|
52
|
+ s.parse()
|
|
|
53
|
+ .map_err(|e| ControllerError::MalformedReply(format!("{}", e)))
|
|
|
54
|
+ })
|
|
|
55
|
+ .map(|addr| SocksListener::Tcp(addr)),
|
|
|
56
|
+ )
|
|
|
57
|
+ }
|
|
|
58
|
+}
|
|
|
59
|
+
|
|
|
60
|
+/// Parse the output of a `GETINFO net/listeners/socks` command.
|
|
|
61
|
+/// The reply is expected to be a single line which can contain multiple
|
|
|
62
|
+/// listeners (each one quoted and separated by space).
|
|
|
63
|
+///
|
|
|
64
|
+/// A reply without listeners is valid (it will return an empty list) and
|
|
|
65
|
+/// expected before the bootstrap.
|
|
|
66
|
+///
|
|
|
67
|
+/// We support IPv4 and IPv6 listeners on all platforms.
|
|
|
68
|
+/// On non-Windows platforms, we support also Unix-domain sockets.
|
|
|
69
|
+/// On Windows we parse them but we do not add them to the list.
|
|
|
70
|
+pub fn parse_socks_listeners(line: &[u8]) -> Result<Vec<SocksListener>, ControllerError> {
|
|
|
71
|
+ let mut listeners = Vec::new();
|
|
|
72
|
+
|
|
|
73
|
+ // We use a manual loop because we want to make sure that items are head to
|
|
|
74
|
+ // tail and we are not simply ignoring invalid content.
|
|
|
75
|
+ let mut pos = 0;
|
|
|
76
|
+ while pos < line.len() {
|
|
|
77
|
+ let remaining = &line[pos..];
|
|
|
78
|
+ match LISTENERS_REGEX.captures(remaining) {
|
|
|
79
|
+ Some(cap) => {
|
|
|
80
|
+ if let Some(l) = parse_listener(&cap[1]) {
|
|
|
81
|
+ listeners.push(l?);
|
|
|
82
|
+ }
|
|
|
83
|
+ pos += cap[0].len();
|
|
|
84
|
+ }
|
|
|
85
|
+ None => {
|
|
|
86
|
+ return Err(ControllerError::WrongFormat(
|
|
|
87
|
+ String::from_utf8_lossy(line).into_owned(),
|
|
|
88
|
+ ));
|
|
|
89
|
+ }
|
|
|
90
|
+ }
|
|
|
91
|
+ }
|
|
|
92
|
+
|
|
|
93
|
+ Ok(listeners)
|
|
|
94
|
+}
|
|
|
95
|
+
|
|
|
96
|
+#[cfg(test)]
|
|
|
97
|
+mod tests {
|
|
|
98
|
+ use super::*;
|
|
|
99
|
+ use std::net::{Ipv4Addr, SocketAddrV4, SocketAddrV6};
|
|
|
100
|
+
|
|
|
101
|
+ #[test]
|
|
|
102
|
+ fn single_ipv4() {
|
|
|
103
|
+ assert_eq!(
|
|
|
104
|
+ parse_socks_listeners(b"\"127.0.0.1:9150\"").unwrap(),
|
|
|
105
|
+ vec![SocksListener::Tcp(
|
|
|
106
|
+ SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 9150).into()
|
|
|
107
|
+ )]
|
|
|
108
|
+ );
|
|
|
109
|
+ }
|
|
|
110
|
+
|
|
|
111
|
+ #[test]
|
|
|
112
|
+ fn single_ipv6() {
|
|
|
113
|
+ let addr_v6: SocketAddrV6 = "[2001:0db8:7000:0000:0000:dead:beef:1234]:9150"
|
|
|
114
|
+ .parse()
|
|
|
115
|
+ .unwrap();
|
|
|
116
|
+ assert_eq!(
|
|
|
117
|
+ parse_socks_listeners(b"\"[2001:0db8:7000:0000:0000:dead:beef:1234]:9150\"").unwrap(),
|
|
|
118
|
+ vec![SocksListener::Tcp(addr_v6.into())]
|
|
|
119
|
+ );
|
|
|
120
|
+ }
|
|
|
121
|
+
|
|
|
122
|
+ #[test]
|
|
|
123
|
+ fn single_unix() {
|
|
|
124
|
+ let line = b"\"unix:/tmp/test.sock\"";
|
|
|
125
|
+ if cfg!(target_os = "windows") {
|
|
|
126
|
+ assert_eq!(parse_socks_listeners(line).unwrap(), vec![]);
|
|
|
127
|
+ } else {
|
|
|
128
|
+ assert_eq!(
|
|
|
129
|
+ parse_socks_listeners(line).unwrap(),
|
|
|
130
|
+ vec![SocksListener::UnixSocket(PathBuf::from("/tmp/test.sock"))]
|
|
|
131
|
+ );
|
|
|
132
|
+ }
|
|
|
133
|
+ }
|
|
|
134
|
+
|
|
|
135
|
+ #[test]
|
|
|
136
|
+ fn no_listeners() {
|
|
|
137
|
+ assert_eq!(parse_socks_listeners(b"").unwrap(), vec![]);
|
|
|
138
|
+ }
|
|
|
139
|
+
|
|
|
140
|
+ #[test]
|
|
|
141
|
+ fn multiple_listeners() {
|
|
|
142
|
+ let mut listeners = vec![
|
|
|
143
|
+ SocksListener::Tcp(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 9050).into()),
|
|
|
144
|
+ SocksListener::Tcp(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 9150).into()),
|
|
|
145
|
+ ];
|
|
|
146
|
+ if cfg!(not(target_os = "windows")) {
|
|
|
147
|
+ listeners.push(SocksListener::UnixSocket(PathBuf::from("/tmp/test.sock")));
|
|
|
148
|
+ }
|
|
|
149
|
+ assert_eq!(
|
|
|
150
|
+ parse_socks_listeners(b"\"127.0.0.1:9050\" \"127.0.0.1:9150\" \"unix:/tmp/test.sock\"")
|
|
|
151
|
+ .unwrap(),
|
|
|
152
|
+ listeners
|
|
|
153
|
+ );
|
|
|
154
|
+ }
|
|
|
155
|
+
|
|
|
156
|
+ #[test]
|
|
|
157
|
+ fn unbalanced_quotes() {
|
|
|
158
|
+ assert!(parse_socks_listeners(b"\"127.0.0.1:9050").is_err());
|
|
|
159
|
+ assert!(parse_socks_listeners(b"127.0.0.1:9050\"").is_err());
|
|
|
160
|
+ assert!(parse_socks_listeners(b"\"127.0.0.1:9050\" \"127.0.0.1:9051").is_err());
|
|
|
161
|
+ assert!(
|
|
|
162
|
+ parse_socks_listeners(b"\"127.0.0.1:9050\" \"127.0.0.1:9051 \"127.0.0.1:9052\"")
|
|
|
163
|
+ .is_err()
|
|
|
164
|
+ );
|
|
|
165
|
+ }
|
|
|
166
|
+
|
|
|
167
|
+ #[test]
|
|
|
168
|
+ fn noise_in_reply() {
|
|
|
169
|
+ assert!(parse_socks_listeners(b"garbage \"127.0.0.1:9050\"").is_err());
|
|
|
170
|
+ assert!(parse_socks_listeners(b"\"127.0.0.1:9050\" garbage").is_err());
|
|
|
171
|
+ assert!(parse_socks_listeners(b"garbage \"127.0.0.1:9050\" garbage").is_err());
|
|
|
172
|
+ assert!(parse_socks_listeners(b"\"127.0.0.1:9050\" garbage \"127.0.0.1:9051\"").is_err());
|
|
|
173
|
+ assert!(
|
|
|
174
|
+ parse_socks_listeners(b"garbage \"127.0.0.1:9050\" garbage \"127.0.0.1:9051\"")
|
|
|
175
|
+ .is_err()
|
|
|
176
|
+ );
|
|
|
177
|
+ assert!(
|
|
|
178
|
+ parse_socks_listeners(b"\"127.0.0.1:9050\" garbage \"127.0.0.1:9051\" garbage")
|
|
|
179
|
+ .is_err()
|
|
|
180
|
+ );
|
|
|
181
|
+ assert!(parse_socks_listeners(
|
|
|
182
|
+ b"garbage \"127.0.0.1:9050\" garbage \"127.0.0.1:9051\" garbage"
|
|
|
183
|
+ )
|
|
|
184
|
+ .is_err());
|
|
|
185
|
+ assert!(parse_socks_listeners(b"\"127.0.0.1:9050\" 127.0.0.1:9150").is_err());
|
|
|
186
|
+ }
|
|
|
187
|
+
|
|
|
188
|
+ #[test]
|
|
|
189
|
+ fn spaces() {
|
|
|
190
|
+ assert!(parse_socks_listeners(b"\"127.0.0.1:9050\"\"127.0.0.1:9150\"").is_err());
|
|
|
191
|
+ assert_eq!(
|
|
|
192
|
+ parse_socks_listeners(b"\"127.0.0.1:9050\" \"127.0.0.1:9150\"").unwrap(),
|
|
|
193
|
+ vec![
|
|
|
194
|
+ SocksListener::Tcp(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 9050).into()),
|
|
|
195
|
+ SocksListener::Tcp(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 9150).into())
|
|
|
196
|
+ ]
|
|
|
197
|
+ );
|
|
|
198
|
+ assert_eq!(
|
|
|
199
|
+ parse_socks_listeners(b" \"127.0.0.1:9050\" \"127.0.0.1:9150\" ").unwrap(),
|
|
|
200
|
+ vec![
|
|
|
201
|
+ SocksListener::Tcp(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 9050).into()),
|
|
|
202
|
+ SocksListener::Tcp(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 9150).into())
|
|
|
203
|
+ ]
|
|
|
204
|
+ );
|
|
|
205
|
+ }
|
|
|
206
|
+
|
|
|
207
|
+ #[test]
|
|
|
208
|
+ fn invalid() {
|
|
|
209
|
+ assert!(parse_socks_listeners(b"\"127.0.0.1:9050\" \"127.0.0.1:100000\"").is_err());
|
|
|
210
|
+ assert!(parse_socks_listeners(b"\"127.0.0.1:100000\" \"127.0.0.1:9050\"").is_err());
|
|
|
211
|
+ assert!(parse_socks_listeners(b"\"127.0.0.1\"").is_err());
|
|
|
212
|
+ assert!(parse_socks_listeners(b"\"localhost:9050\"").is_err());
|
|
|
213
|
+ assert!(parse_socks_listeners(b"\"\"").is_err());
|
|
|
214
|
+ }
|
|
|
215
|
+} |
toolkit/components/tor-integration/tor_provider/src/ctor/controller/parsers/stream_status.rs
|
|
1
|
+// Licensed under the Apache License, Version 2.0,
|
|
|
2
|
+// <http://apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
3
|
+// <http://opensource.org/licenses/MIT>, at your option. This file may not be
|
|
|
4
|
+// copied, modified, or distributed except according to those terms.
|
|
|
5
|
+
|
|
|
6
|
+use lazy_static::lazy_static;
|
|
|
7
|
+use regex::bytes::Regex;
|
|
|
8
|
+
|
|
|
9
|
+use super::{parse_key_value_pairs, tor_unescape};
|
|
|
10
|
+use crate::ctor::controller::{CircuitID, ControllerError, Stream, StreamID};
|
|
|
11
|
+
|
|
|
12
|
+const STREAM_EVENT: &[u8] = b"SENTCONNECT";
|
|
|
13
|
+
|
|
|
14
|
+lazy_static! {
|
|
|
15
|
+ // https://spec.torproject.org/control-spec/replies.html#STREAM
|
|
|
16
|
+ static ref STATUS_REGEX: Regex = Regex::new(
|
|
|
17
|
+ "^(?<StreamID>[a-zA-Z0-9]{1,16}) (?<StreamStatus>[A-Za-z_]+) (?<CircuitID>[a-zA-Z0-9]{1,16}) (?:[^ ]+)(?: (?<Args>.*))?$"
|
|
|
18
|
+ )
|
|
|
19
|
+ .expect("The regex is hardcoded, it should be good.");
|
|
|
20
|
+}
|
|
|
21
|
+
|
|
|
22
|
+const USERNAME_KEYWORD: &'static str = "SOCKS_USERNAME";
|
|
|
23
|
+const PASSWORD_KEYWORD: &'static str = "SOCKS_PASSWORD";
|
|
|
24
|
+const STREAM_KEYWORDS: &[&'static str] = &[USERNAME_KEYWORD, PASSWORD_KEYWORD];
|
|
|
25
|
+
|
|
|
26
|
+/// Parse a stream update event.
|
|
|
27
|
+/// Only the SENTCONNECT events will be parsed, the other ones will be ignored.
|
|
|
28
|
+pub fn parse_stream_sentconnect(line: &[u8]) -> Result<Option<Stream>, ControllerError> {
|
|
|
29
|
+ let stream = STATUS_REGEX
|
|
|
30
|
+ .captures(line)
|
|
|
31
|
+ .ok_or_else(|| ControllerError::WrongFormat(String::from_utf8_lossy(line).into_owned()))?;
|
|
|
32
|
+
|
|
|
33
|
+ if !stream["StreamStatus"].eq_ignore_ascii_case(STREAM_EVENT) {
|
|
|
34
|
+ return Ok(None);
|
|
|
35
|
+ }
|
|
|
36
|
+
|
|
|
37
|
+ let stream_id = StreamID::new(&stream["StreamID"]).ok_or_else(|| {
|
|
|
38
|
+ ControllerError::MalformedReply(format!(
|
|
|
39
|
+ "invalid stream ID '{}'",
|
|
|
40
|
+ String::from_utf8_lossy(&stream["StreamID"])
|
|
|
41
|
+ ))
|
|
|
42
|
+ })?;
|
|
|
43
|
+ let circuit_id = CircuitID::new(&stream["CircuitID"]).ok_or_else(|| {
|
|
|
44
|
+ ControllerError::MalformedReply(format!(
|
|
|
45
|
+ "invalid circuit ID '{}'",
|
|
|
46
|
+ String::from_utf8_lossy(&stream["CircuitID"])
|
|
|
47
|
+ ))
|
|
|
48
|
+ })?;
|
|
|
49
|
+
|
|
|
50
|
+ let args = stream
|
|
|
51
|
+ .name("Args")
|
|
|
52
|
+ .map(|a| parse_key_value_pairs(a.as_bytes(), STREAM_KEYWORDS))
|
|
|
53
|
+ .transpose()?
|
|
|
54
|
+ .unwrap_or_default();
|
|
|
55
|
+ let get_credential = |name| {
|
|
|
56
|
+ args.get(name)
|
|
|
57
|
+ .map(|c| tor_unescape(c).map(|c| c.into_owned()))
|
|
|
58
|
+ .transpose()
|
|
|
59
|
+ .map_err(|e| ControllerError::MalformedReply(e.to_string()))
|
|
|
60
|
+ };
|
|
|
61
|
+ let socks_username = get_credential(USERNAME_KEYWORD)?;
|
|
|
62
|
+ let socks_password = get_credential(PASSWORD_KEYWORD)?;
|
|
|
63
|
+
|
|
|
64
|
+ Ok(Some(Stream {
|
|
|
65
|
+ stream_id,
|
|
|
66
|
+ circuit_id,
|
|
|
67
|
+ socks_username,
|
|
|
68
|
+ socks_password,
|
|
|
69
|
+ }))
|
|
|
70
|
+}
|
|
|
71
|
+
|
|
|
72
|
+#[cfg(test)]
|
|
|
73
|
+mod tests {
|
|
|
74
|
+ use std::assert_matches;
|
|
|
75
|
+
|
|
|
76
|
+ use super::*;
|
|
|
77
|
+
|
|
|
78
|
+ #[test]
|
|
|
79
|
+ fn simple() {
|
|
|
80
|
+ let line = b"1 SENTCONNECT 0 1.2.3.4:443";
|
|
|
81
|
+ let result = parse_stream_sentconnect(line);
|
|
|
82
|
+ let stream = result.unwrap().unwrap();
|
|
|
83
|
+ assert_eq!(stream.stream_id, StreamID::new(b"1").unwrap());
|
|
|
84
|
+ assert_eq!(stream.circuit_id, CircuitID::new(b"0").unwrap());
|
|
|
85
|
+ assert_eq!(stream.socks_username, None);
|
|
|
86
|
+ assert_eq!(stream.socks_password, None);
|
|
|
87
|
+ }
|
|
|
88
|
+
|
|
|
89
|
+ #[test]
|
|
|
90
|
+ fn with_socks_credentials() {
|
|
|
91
|
+ let line =
|
|
|
92
|
+ b"42 SENTCONNECT 100 (Tor_internal):80 SOCKS_USERNAME=\"user\" SOCKS_PASSWORD=\"pass\"";
|
|
|
93
|
+ let result = parse_stream_sentconnect(line);
|
|
|
94
|
+ let stream = result.unwrap().unwrap();
|
|
|
95
|
+ assert_eq!(stream.stream_id, StreamID::new(b"42").unwrap());
|
|
|
96
|
+ assert_eq!(stream.circuit_id, CircuitID::new(b"100").unwrap());
|
|
|
97
|
+ assert_eq!(stream.socks_username, Some(Vec::from("user")));
|
|
|
98
|
+ assert_eq!(stream.socks_password, Some(Vec::from("pass")));
|
|
|
99
|
+ }
|
|
|
100
|
+
|
|
|
101
|
+ #[test]
|
|
|
102
|
+ fn only_username() {
|
|
|
103
|
+ let line = b"5 SENTCONNECT 10 10.20.30.40:443 SOCKS_USERNAME=\"alice\"";
|
|
|
104
|
+ let result = parse_stream_sentconnect(line);
|
|
|
105
|
+ let stream = result.unwrap().unwrap();
|
|
|
106
|
+ assert_eq!(stream.stream_id, StreamID::new(b"5").unwrap());
|
|
|
107
|
+ assert_eq!(stream.circuit_id, CircuitID::new(b"10").unwrap());
|
|
|
108
|
+ assert_eq!(stream.socks_username, Some(Vec::from("alice")));
|
|
|
109
|
+ assert_eq!(stream.socks_password, None);
|
|
|
110
|
+ }
|
|
|
111
|
+
|
|
|
112
|
+ #[test]
|
|
|
113
|
+ fn only_password() {
|
|
|
114
|
+ let line = b"7 SENTCONNECT 20 192.168.1.2:22 SOCKS_PASSWORD=\"secret123\"";
|
|
|
115
|
+ let result = parse_stream_sentconnect(line);
|
|
|
116
|
+ let stream = result.unwrap().unwrap();
|
|
|
117
|
+ assert_eq!(stream.stream_id, StreamID::new(b"7").unwrap());
|
|
|
118
|
+ assert_eq!(stream.circuit_id, CircuitID::new(b"20").unwrap());
|
|
|
119
|
+ assert_eq!(stream.socks_username, None);
|
|
|
120
|
+ assert_eq!(stream.socks_password, Some(Vec::from("secret123")));
|
|
|
121
|
+ }
|
|
|
122
|
+
|
|
|
123
|
+ #[test]
|
|
|
124
|
+ fn valid_but_other_status() {
|
|
|
125
|
+ let line = b"1 DETACHED 0 172.16.10.2:8080";
|
|
|
126
|
+ let result = parse_stream_sentconnect(line);
|
|
|
127
|
+ assert!(result.unwrap().is_none());
|
|
|
128
|
+ }
|
|
|
129
|
+
|
|
|
130
|
+ #[test]
|
|
|
131
|
+ fn status_case_insensitive() {
|
|
|
132
|
+ let line = b"1 sentconnect 0 (Tor_internal):22 socks_username=USER socks_password=PASS";
|
|
|
133
|
+ let result = parse_stream_sentconnect(line);
|
|
|
134
|
+ let stream = result.unwrap().unwrap();
|
|
|
135
|
+ assert_eq!(stream.stream_id, StreamID::new(b"1").unwrap());
|
|
|
136
|
+ assert_eq!(stream.circuit_id, CircuitID::new(b"0").unwrap());
|
|
|
137
|
+ assert_eq!(stream.socks_username.unwrap(), b"USER");
|
|
|
138
|
+ assert_eq!(stream.socks_password.unwrap(), b"PASS");
|
|
|
139
|
+ }
|
|
|
140
|
+
|
|
|
141
|
+ #[test]
|
|
|
142
|
+ fn status_mixed_case() {
|
|
|
143
|
+ let line = b"1 SentConnect 0 192.168.4.5:22 SOcKs_USeRNAMe=User soCKS_paSSWoRd=paSs";
|
|
|
144
|
+ let result = parse_stream_sentconnect(line);
|
|
|
145
|
+ let stream = result.unwrap().unwrap();
|
|
|
146
|
+ assert_eq!(stream.stream_id, StreamID::new(b"1").unwrap());
|
|
|
147
|
+ assert_eq!(stream.circuit_id, CircuitID::new(b"0").unwrap());
|
|
|
148
|
+ assert_eq!(stream.socks_username.unwrap(), b"User");
|
|
|
149
|
+ assert_eq!(stream.socks_password.unwrap(), b"paSs");
|
|
|
150
|
+ }
|
|
|
151
|
+
|
|
|
152
|
+ #[test]
|
|
|
153
|
+ fn status_unescape_error() {
|
|
|
154
|
+ assert!(parse_stream_sentconnect(
|
|
|
155
|
+ b"5 SENTCONNECT 10 10.20.30.40:443 SOCKS_USERNAME=\"alice\\xyz\""
|
|
|
156
|
+ )
|
|
|
157
|
+ .is_err());
|
|
|
158
|
+ }
|
|
|
159
|
+
|
|
|
160
|
+ #[test]
|
|
|
161
|
+ fn large_ids() {
|
|
|
162
|
+ {
|
|
|
163
|
+ let line = b"9999999999999999 SENTCONNECT 1 5.6.7.8:80";
|
|
|
164
|
+ let result = parse_stream_sentconnect(line);
|
|
|
165
|
+ let stream = result.unwrap().unwrap();
|
|
|
166
|
+ assert_eq!(
|
|
|
167
|
+ stream.stream_id,
|
|
|
168
|
+ StreamID::new(b"9999999999999999").unwrap()
|
|
|
169
|
+ );
|
|
|
170
|
+ assert_eq!(stream.circuit_id, CircuitID::new(b"1").unwrap());
|
|
|
171
|
+ }
|
|
|
172
|
+ {
|
|
|
173
|
+ let line = b"2 SENTCONNECT 1234567890123456 5.6.7.8:80";
|
|
|
174
|
+ let result = parse_stream_sentconnect(line);
|
|
|
175
|
+ let stream = result.unwrap().unwrap();
|
|
|
176
|
+ assert_eq!(stream.stream_id, StreamID::new(b"2").unwrap());
|
|
|
177
|
+ assert_eq!(
|
|
|
178
|
+ stream.circuit_id,
|
|
|
179
|
+ CircuitID::new(b"1234567890123456").unwrap()
|
|
|
180
|
+ );
|
|
|
181
|
+ }
|
|
|
182
|
+ }
|
|
|
183
|
+
|
|
|
184
|
+ #[test]
|
|
|
185
|
+ fn escaped_credentials() {
|
|
|
186
|
+ let line =
|
|
|
187
|
+ b"1 SENTCONNECT 0 (Tor_internal):80 SOCKS_USERNAME=\"user\\x20example\" SOCKS_PASSWORD=\"pass\\167ord\"";
|
|
|
188
|
+ let result = parse_stream_sentconnect(line);
|
|
|
189
|
+ let stream = result.unwrap().unwrap();
|
|
|
190
|
+ assert_eq!(stream.socks_username.unwrap(), b"user example");
|
|
|
191
|
+ assert_eq!(stream.socks_password.unwrap(), b"password");
|
|
|
192
|
+ }
|
|
|
193
|
+
|
|
|
194
|
+ #[test]
|
|
|
195
|
+ fn alphanumeric_ids() {
|
|
|
196
|
+ let line = b"abcX1y2Z3 SENTCONNECT ABCxyz 10.10.10.10:80";
|
|
|
197
|
+ let result = parse_stream_sentconnect(line);
|
|
|
198
|
+ let stream = result.unwrap().unwrap();
|
|
|
199
|
+ assert_eq!(stream.stream_id, StreamID::new(b"abcX1y2Z3").unwrap());
|
|
|
200
|
+ assert_eq!(stream.circuit_id, CircuitID::new(b"ABCxyz").unwrap());
|
|
|
201
|
+ }
|
|
|
202
|
+
|
|
|
203
|
+ #[test]
|
|
|
204
|
+ fn stream_targets() {
|
|
|
205
|
+ // Valid: IPv4
|
|
|
206
|
+ assert!(
|
|
|
207
|
+ parse_stream_sentconnect(b"1234 SENTCONNECT 5678 10.10.10.10:80")
|
|
|
208
|
+ .unwrap()
|
|
|
209
|
+ .is_some()
|
|
|
210
|
+ );
|
|
|
211
|
+ // Valid: IPv6
|
|
|
212
|
+ assert!(
|
|
|
213
|
+ parse_stream_sentconnect(b"1 SENTCONNECT 2 [cafe:dead:beef:0123::3200]:443")
|
|
|
214
|
+ .unwrap()
|
|
|
215
|
+ .is_some()
|
|
|
216
|
+ );
|
|
|
217
|
+ // Valid: hostname
|
|
|
218
|
+ assert!(parse_stream_sentconnect(b"1 SENTCONNECT 2 example.org:443")
|
|
|
219
|
+ .unwrap()
|
|
|
220
|
+ .is_some());
|
|
|
221
|
+ // Valid: (Tor_internal) literal
|
|
|
222
|
+ assert!(
|
|
|
223
|
+ parse_stream_sentconnect(b"1 SENTCONNECT 2 (Tor_internal):22")
|
|
|
224
|
+ .unwrap()
|
|
|
225
|
+ .is_some()
|
|
|
226
|
+ );
|
|
|
227
|
+
|
|
|
228
|
+ // Invalid (no port) but accepted anyway for now
|
|
|
229
|
+ assert!(
|
|
|
230
|
+ parse_stream_sentconnect(b"1234 SENTCONNECT 5678 12.34.56.78")
|
|
|
231
|
+ .unwrap()
|
|
|
232
|
+ .is_some()
|
|
|
233
|
+ );
|
|
|
234
|
+ assert!(
|
|
|
235
|
+ parse_stream_sentconnect(b"1 SENTCONNECT 2 [cafe:dead:beef:0123::3200]")
|
|
|
236
|
+ .unwrap()
|
|
|
237
|
+ .is_some()
|
|
|
238
|
+ );
|
|
|
239
|
+ assert!(parse_stream_sentconnect(b"1 SENTCONNECT 2 example.net")
|
|
|
240
|
+ .unwrap()
|
|
|
241
|
+ .is_some());
|
|
|
242
|
+ assert!(parse_stream_sentconnect(b"1 SENTCONNECT 2 (Tor_internal)")
|
|
|
243
|
+ .unwrap()
|
|
|
244
|
+ .is_some());
|
|
|
245
|
+ }
|
|
|
246
|
+
|
|
|
247
|
+ #[test]
|
|
|
248
|
+ fn empty() {
|
|
|
249
|
+ let line = b"";
|
|
|
250
|
+ let result = parse_stream_sentconnect(line);
|
|
|
251
|
+ assert_matches!(result.unwrap_err(), ControllerError::WrongFormat(_));
|
|
|
252
|
+ }
|
|
|
253
|
+
|
|
|
254
|
+ #[test]
|
|
|
255
|
+ fn invalid() {
|
|
|
256
|
+ let line = b"invalid input";
|
|
|
257
|
+ let result = parse_stream_sentconnect(line);
|
|
|
258
|
+ assert_matches!(result.unwrap_err(), ControllerError::WrongFormat(_));
|
|
|
259
|
+ }
|
|
|
260
|
+
|
|
|
261
|
+ #[test]
|
|
|
262
|
+ fn missing_status() {
|
|
|
263
|
+ let line = b"1 0 10.0.0.1:80";
|
|
|
264
|
+ let result = parse_stream_sentconnect(line);
|
|
|
265
|
+ assert_matches!(result.unwrap_err(), ControllerError::WrongFormat(_));
|
|
|
266
|
+ }
|
|
|
267
|
+
|
|
|
268
|
+ #[test]
|
|
|
269
|
+ fn invalid_ids() {
|
|
|
270
|
+ {
|
|
|
271
|
+ let line = b"123+ SENTCONNECT 0 10.0.0.1:80";
|
|
|
272
|
+ let result = parse_stream_sentconnect(line);
|
|
|
273
|
+ assert_matches!(result.unwrap_err(), ControllerError::WrongFormat(_));
|
|
|
274
|
+ }
|
|
|
275
|
+ {
|
|
|
276
|
+ let line = b"+++ SENTCONNECT 0 10.0.0.1:80";
|
|
|
277
|
+ let result = parse_stream_sentconnect(line);
|
|
|
278
|
+ assert_matches!(result.unwrap_err(), ControllerError::WrongFormat(_));
|
|
|
279
|
+ }
|
|
|
280
|
+ {
|
|
|
281
|
+ let line = b"12345678901234567 SENTCONNECT 0 10.0.0.1:80";
|
|
|
282
|
+ let result = parse_stream_sentconnect(line);
|
|
|
283
|
+ assert_matches!(result.unwrap_err(), ControllerError::WrongFormat(_));
|
|
|
284
|
+ }
|
|
|
285
|
+ {
|
|
|
286
|
+ let line = b"1 SENTCONNECT 123+-+ 10.0.0.1:80";
|
|
|
287
|
+ let result = parse_stream_sentconnect(line);
|
|
|
288
|
+ assert_matches!(result.unwrap_err(), ControllerError::WrongFormat(_));
|
|
|
289
|
+ }
|
|
|
290
|
+ {
|
|
|
291
|
+ let line = b"1 SENTCONNECT +-+ 10.0.0.1:80";
|
|
|
292
|
+ let result = parse_stream_sentconnect(line);
|
|
|
293
|
+ assert_matches!(result.unwrap_err(), ControllerError::WrongFormat(_));
|
|
|
294
|
+ }
|
|
|
295
|
+ }
|
|
|
296
|
+} |
toolkit/components/tor-integration/tor_provider/src/ctor/controller/parsers/unescape.rs
| ... |
... |
@@ -21,7 +21,8 @@ pub enum UnescapeError { |
|
21
|
21
|
}
|
|
22
|
22
|
|
|
23
|
23
|
/// Adaptation of tor's unescape_string (src/lib/encoding/cstring.c).
|
|
24
|
|
-/// The main difference is that we allow unquoted strings.
|
|
|
24
|
+/// The main difference is that we allow unquoted strings, as long as they do
|
|
|
25
|
+/// not contain spaces.
|
|
25
|
26
|
pub fn tor_unescape<'a>(buf: &'a [u8]) -> Result<Cow<'a, [u8]>, UnescapeError> {
|
|
26
|
27
|
match buf.first() {
|
|
27
|
28
|
Some(b'"') => {
|
toolkit/components/tor-integration/tor_provider/src/ctor/controller/types.rs
| ... |
... |
@@ -3,9 +3,49 @@ |
|
3
|
3
|
// <http://opensource.org/licenses/MIT>, at your option. This file may not be
|
|
4
|
4
|
// copied, modified, or distributed except according to those terms.
|
|
5
|
5
|
|
|
6
|
|
-use serde::Serialize;
|
|
7
|
|
-use std::net::SocketAddr;
|
|
|
6
|
+use data_encoding::{DecodeError, BASE32_NOPAD};
|
|
|
7
|
+use serde::{Serialize, Serializer};
|
|
|
8
|
+use sha3::{Digest, Sha3_256};
|
|
|
9
|
+use smallvec::SmallVec;
|
|
|
10
|
+use std::{
|
|
|
11
|
+ fmt,
|
|
|
12
|
+ net::{Ipv4Addr, Ipv6Addr, SocketAddr},
|
|
|
13
|
+ path::PathBuf,
|
|
|
14
|
+};
|
|
|
15
|
+use thiserror::Error;
|
|
|
16
|
+use tinystr::TinyAsciiStr;
|
|
8
|
17
|
|
|
|
18
|
+/// The severity of STATUS_CLIENT updates. It is the first token:
|
|
|
19
|
+///
|
|
|
20
|
+/// NOTICE BOOTSTRAP PROGRESS=n ...
|
|
|
21
|
+/// WARN BOOTSTRAP PROGRESS=n ...
|
|
|
22
|
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
|
|
23
|
+pub enum StatusSeverity {
|
|
|
24
|
+ Notice,
|
|
|
25
|
+ Warn,
|
|
|
26
|
+}
|
|
|
27
|
+
|
|
|
28
|
+impl ToString for StatusSeverity {
|
|
|
29
|
+ fn to_string(&self) -> String {
|
|
|
30
|
+ match self {
|
|
|
31
|
+ StatusSeverity::Notice => String::from("NOTICE"),
|
|
|
32
|
+ StatusSeverity::Warn => String::from("WARN"),
|
|
|
33
|
+ }
|
|
|
34
|
+ }
|
|
|
35
|
+}
|
|
|
36
|
+
|
|
|
37
|
+/// Data structure with the information associated to a STATUS_CLIENT event.
|
|
|
38
|
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
|
|
39
|
+pub struct BootstrapStatus {
|
|
|
40
|
+ pub severity: StatusSeverity,
|
|
|
41
|
+ pub progress: u8,
|
|
|
42
|
+ pub tag: String,
|
|
|
43
|
+ pub summary: String,
|
|
|
44
|
+ pub reason: Option<String>,
|
|
|
45
|
+ pub should_warn: bool,
|
|
|
46
|
+}
|
|
|
47
|
+
|
|
|
48
|
+/// Information extracted from a bridge line.
|
|
9
|
49
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
|
10
|
50
|
pub struct Bridge {
|
|
11
|
51
|
pub transport: Option<String>,
|
| ... |
... |
@@ -14,6 +54,39 @@ pub struct Bridge { |
|
14
|
54
|
pub args: Option<Vec<u8>>,
|
|
15
|
55
|
}
|
|
16
|
56
|
|
|
|
57
|
+/// A circuit ID. It can be an alphanumeric string up to 16 characters.
|
|
|
58
|
+/// At the moment, comparison between them is case-sensitive, but tor uses only
|
|
|
59
|
+/// digits.
|
|
|
60
|
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
|
|
|
61
|
+pub struct CircuitID(TinyAsciiStr<16>);
|
|
|
62
|
+
|
|
|
63
|
+impl CircuitID {
|
|
|
64
|
+ pub fn new(data: &[u8]) -> Option<Self> {
|
|
|
65
|
+ if data.is_empty() || data.iter().any(|c| !c.is_ascii_alphanumeric()) {
|
|
|
66
|
+ return None;
|
|
|
67
|
+ }
|
|
|
68
|
+ let s = str::from_utf8(data).ok()?.parse().ok()?;
|
|
|
69
|
+ Some(Self(s))
|
|
|
70
|
+ }
|
|
|
71
|
+
|
|
|
72
|
+ pub fn as_str(&self) -> &str {
|
|
|
73
|
+ self.0.as_str()
|
|
|
74
|
+ }
|
|
|
75
|
+}
|
|
|
76
|
+
|
|
|
77
|
+/// A conflux cookie, used to group conflux circuits.
|
|
|
78
|
+pub type ConfluxID = [u8; 16];
|
|
|
79
|
+
|
|
|
80
|
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
|
|
81
|
+pub struct Circuit {
|
|
|
82
|
+ pub id: CircuitID,
|
|
|
83
|
+ pub path: SmallVec<[NodeFingerprint; 3]>,
|
|
|
84
|
+ pub conflux_id: Option<ConfluxID>,
|
|
|
85
|
+}
|
|
|
86
|
+
|
|
|
87
|
+/// The definition of a handler for a pluggable transport.
|
|
|
88
|
+/// The conversion between 8-bit characters and 16-bit characters on Windows is
|
|
|
89
|
+/// not well defined.
|
|
17
|
90
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
|
18
|
91
|
pub enum ClientTransportPlugin {
|
|
19
|
92
|
Executable {
|
| ... |
... |
@@ -24,6 +97,10 @@ pub enum ClientTransportPlugin { |
|
24
|
97
|
Socks5(SocketAddr),
|
|
25
|
98
|
}
|
|
26
|
99
|
|
|
|
100
|
+/// A configuration value to be used with the SETCONF command.
|
|
|
101
|
+/// Boolean will be converted to 1 and 0.
|
|
|
102
|
+/// Null can be used to reset a certain value. When building the SETCONF
|
|
|
103
|
+/// command, we will add `<key>`, rather than `<key>=<value>` or `<key>=`.
|
|
27
|
104
|
#[derive(Debug, Clone)]
|
|
28
|
105
|
pub enum ConfValue<'a> {
|
|
29
|
106
|
Bool(bool),
|
| ... |
... |
@@ -33,8 +110,243 @@ pub enum ConfValue<'a> { |
|
33
|
110
|
Null,
|
|
34
|
111
|
}
|
|
35
|
112
|
|
|
|
113
|
+/// Onion service address (in the canonical base32 representation, without the
|
|
|
114
|
+/// .onion suffix).
|
|
|
115
|
+/// The address is validated on construction, to make sure it adheres to the
|
|
|
116
|
+/// spec: https://spec.torproject.org/rend-spec/encoding-onion-addresses.html.
|
|
|
117
|
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
|
118
|
+pub struct HSAddress([u8; 56]);
|
|
|
119
|
+
|
|
|
120
|
+impl HSAddress {
|
|
|
121
|
+ pub fn new(base32_address: &[u8; 56]) -> Result<Self, OnionValidationError> {
|
|
|
122
|
+ validate_onion_address(base32_address).map(Self)
|
|
|
123
|
+ }
|
|
|
124
|
+
|
|
|
125
|
+ pub fn from_slice(base32_address: &[u8]) -> Result<Self, OnionValidationError> {
|
|
|
126
|
+ Self::new(
|
|
|
127
|
+ base32_address
|
|
|
128
|
+ .try_into()
|
|
|
129
|
+ .map_err(|_| OnionValidationError::InvalidLength)?,
|
|
|
130
|
+ )
|
|
|
131
|
+ }
|
|
|
132
|
+
|
|
|
133
|
+ pub fn from_str(base32_address: &str) -> Result<Self, OnionValidationError> {
|
|
|
134
|
+ Self::from_slice(base32_address.as_bytes())
|
|
|
135
|
+ }
|
|
|
136
|
+}
|
|
|
137
|
+
|
|
|
138
|
+impl AsRef<str> for HSAddress {
|
|
|
139
|
+ fn as_ref(&self) -> &str {
|
|
|
140
|
+ str::from_utf8(&self.0).expect(
|
|
|
141
|
+ "We validated the address on the constructor, therefore it must be valid UTF-8.",
|
|
|
142
|
+ )
|
|
|
143
|
+ }
|
|
|
144
|
+}
|
|
|
145
|
+
|
|
|
146
|
+impl Serialize for HSAddress {
|
|
|
147
|
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
|
|
148
|
+ where
|
|
|
149
|
+ S: Serializer,
|
|
|
150
|
+ {
|
|
|
151
|
+ serializer.serialize_str(self.as_ref())
|
|
|
152
|
+ }
|
|
|
153
|
+}
|
|
|
154
|
+
|
|
|
155
|
+/// Possible errors that can happen when validating an onion address.
|
|
|
156
|
+#[derive(Error, Debug, Clone, PartialEq, Eq)]
|
|
|
157
|
+pub enum OnionValidationError {
|
|
|
158
|
+ #[error("Invalid length")]
|
|
|
159
|
+ InvalidLength,
|
|
|
160
|
+ #[error("cannot decode the address")]
|
|
|
161
|
+ CannotDecode(#[from] DecodeError),
|
|
|
162
|
+ #[error("unsupported version: {0}")]
|
|
|
163
|
+ UnsupportedVersion(u8),
|
|
|
164
|
+ #[error("bad checksum")]
|
|
|
165
|
+ BadChecksum,
|
|
|
166
|
+}
|
|
|
167
|
+
|
|
|
168
|
+/// Check the validity of an onion address.
|
|
|
169
|
+///
|
|
|
170
|
+/// https://spec.torproject.org/rend-spec/encoding-onion-addresses.html
|
|
|
171
|
+fn validate_onion_address(base32_address: &[u8; 56]) -> Result<[u8; 56], OnionValidationError> {
|
|
|
172
|
+ let mut uppercased = *base32_address;
|
|
|
173
|
+ uppercased.make_ascii_uppercase();
|
|
|
174
|
+ let decoded = BASE32_NOPAD
|
|
|
175
|
+ .decode(&uppercased)
|
|
|
176
|
+ .map_err(|e| OnionValidationError::from(e))?;
|
|
|
177
|
+ debug_assert_eq!(
|
|
|
178
|
+ decoded.len(),
|
|
|
179
|
+ 35,
|
|
|
180
|
+ "We are using fixed size, how can the length be wrong?!"
|
|
|
181
|
+ );
|
|
|
182
|
+
|
|
|
183
|
+ let pubkey = &decoded[0..32];
|
|
|
184
|
+ let stored_checksum = &decoded[32..34];
|
|
|
185
|
+ let version = decoded[34];
|
|
|
186
|
+
|
|
|
187
|
+ if version != 3 {
|
|
|
188
|
+ return Err(OnionValidationError::UnsupportedVersion(version));
|
|
|
189
|
+ }
|
|
|
190
|
+
|
|
|
191
|
+ let hash = {
|
|
|
192
|
+ let mut hasher = Sha3_256::new();
|
|
|
193
|
+ hasher.update(b".onion checksum");
|
|
|
194
|
+ hasher.update(pubkey);
|
|
|
195
|
+ hasher.update(&[version]);
|
|
|
196
|
+ hasher.finalize()
|
|
|
197
|
+ };
|
|
|
198
|
+
|
|
|
199
|
+ let calculated_checksum = &hash[0..2];
|
|
|
200
|
+ if stored_checksum != calculated_checksum {
|
|
|
201
|
+ return Err(OnionValidationError::BadChecksum);
|
|
|
202
|
+ }
|
|
|
203
|
+
|
|
|
204
|
+ Ok(uppercased)
|
|
|
205
|
+}
|
|
|
206
|
+
|
|
|
207
|
+/// The information about the IP addresses of a relay.
|
|
|
208
|
+/// At the moment, all realys must have an IPv4 address, and tor will use at
|
|
|
209
|
+/// most one IPv6 address (which is optional).
|
|
|
210
|
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
|
|
211
|
+pub struct NodeAddresses {
|
|
|
212
|
+ pub ipv4: Ipv4Addr,
|
|
|
213
|
+ pub ipv6: Option<Ipv6Addr>,
|
|
|
214
|
+}
|
|
|
215
|
+
|
|
|
216
|
+/// The fingerprint of a node (as bytes, i.e., decoded from the 40 hex digits
|
|
|
217
|
+/// format).
|
|
|
218
|
+pub type NodeFingerprint = [u8; 20];
|
|
|
219
|
+
|
|
|
220
|
+/// A private key for onion authentication.
|
|
|
221
|
+/// The key_blob is a base64 string, rather than a binary blob.
|
|
|
222
|
+#[derive(Clone, PartialEq, Eq, Serialize)]
|
|
|
223
|
+pub struct OnionClientAuth {
|
|
|
224
|
+ pub address: HSAddress,
|
|
|
225
|
+ pub key_type: String,
|
|
|
226
|
+ pub key_blob: String,
|
|
|
227
|
+ pub is_permanent: bool,
|
|
|
228
|
+}
|
|
|
229
|
+
|
|
|
230
|
+impl fmt::Debug for OnionClientAuth {
|
|
|
231
|
+ /// Explicit implementation of fmt::Debug for OnionClientAuth that redacts
|
|
|
232
|
+ /// the private key.
|
|
|
233
|
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
234
|
+ f.debug_struct("OnionClientAuth")
|
|
|
235
|
+ .field("address", &self.address)
|
|
|
236
|
+ .field("key_type", &self.key_type)
|
|
|
237
|
+ .field("key_blob", &"[redacted]")
|
|
|
238
|
+ .field("is_permanent", &self.is_permanent)
|
|
|
239
|
+ .finish()
|
|
|
240
|
+ }
|
|
|
241
|
+}
|
|
|
242
|
+
|
|
|
243
|
+/// A pluggable transport, with its handler and the transport it can manages.
|
|
36
|
244
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
|
37
|
245
|
pub struct PluggableTransport {
|
|
38
|
246
|
pub transports: Vec<String>,
|
|
39
|
247
|
pub plugin: ClientTransportPlugin,
|
|
40
|
248
|
}
|
|
|
249
|
+
|
|
|
250
|
+/// A listener for the SOCKS port.
|
|
|
251
|
+/// On Windows, only TCP listeners are supported.
|
|
|
252
|
+#[derive(Debug, PartialEq, Eq, Serialize)]
|
|
|
253
|
+pub enum SocksListener {
|
|
|
254
|
+ Tcp(SocketAddr),
|
|
|
255
|
+ UnixSocket(PathBuf),
|
|
|
256
|
+}
|
|
|
257
|
+
|
|
|
258
|
+/// The bare minimum information we need about a stream to associate some
|
|
|
259
|
+/// isolation credentials to a circuit.
|
|
|
260
|
+///
|
|
|
261
|
+/// Notice: since tor uses SOCKS passwords as isolation parameters rather than
|
|
|
262
|
+/// as real passwords, we do not redact them, and we use the default Debug
|
|
|
263
|
+/// implementation.
|
|
|
264
|
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
|
|
265
|
+pub struct Stream {
|
|
|
266
|
+ pub stream_id: StreamID,
|
|
|
267
|
+ pub circuit_id: CircuitID,
|
|
|
268
|
+ pub socks_username: Option<Vec<u8>>,
|
|
|
269
|
+ pub socks_password: Option<Vec<u8>>,
|
|
|
270
|
+}
|
|
|
271
|
+
|
|
|
272
|
+/// A stream ID. It can be an alphanumeric string up to 16 characters.
|
|
|
273
|
+/// At the moment, comparison between them is case-sensitive, but tor uses only
|
|
|
274
|
+/// digits.
|
|
|
275
|
+/// Circuit IDs are defined in the same way, but we do not define them as alias
|
|
|
276
|
+/// to prevent exchanging them by mistake.
|
|
|
277
|
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
|
|
|
278
|
+pub struct StreamID(TinyAsciiStr<16>);
|
|
|
279
|
+
|
|
|
280
|
+impl StreamID {
|
|
|
281
|
+ pub fn new(data: &[u8]) -> Option<Self> {
|
|
|
282
|
+ if data.is_empty() || data.iter().any(|c| !c.is_ascii_alphanumeric()) {
|
|
|
283
|
+ return None;
|
|
|
284
|
+ }
|
|
|
285
|
+ let s = str::from_utf8(data).ok()?.parse().ok()?;
|
|
|
286
|
+ Some(Self(s))
|
|
|
287
|
+ }
|
|
|
288
|
+
|
|
|
289
|
+ pub fn as_str(&self) -> &str {
|
|
|
290
|
+ self.0.as_str()
|
|
|
291
|
+ }
|
|
|
292
|
+}
|
|
|
293
|
+
|
|
|
294
|
+#[cfg(test)]
|
|
|
295
|
+mod tests {
|
|
|
296
|
+ use super::*;
|
|
|
297
|
+
|
|
|
298
|
+ #[test]
|
|
|
299
|
+ fn test_onion_validation() {
|
|
|
300
|
+ assert!(validate_onion_address(
|
|
|
301
|
+ b"PG6MMJIYJMCRSSLVYKFWNNTLARU7P5SVN6Y2YMMJU6NUBXNDF4PSCRYD"
|
|
|
302
|
+ )
|
|
|
303
|
+ .is_ok());
|
|
|
304
|
+ assert!(validate_onion_address(
|
|
|
305
|
+ b"pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd"
|
|
|
306
|
+ )
|
|
|
307
|
+ .is_ok());
|
|
|
308
|
+ assert!(validate_onion_address(
|
|
|
309
|
+ b"pG6mMjIyJmCrSsLvYkFwNnTlArU7p5SvN6y2YmMjU6nuBxNdF4pScRyD"
|
|
|
310
|
+ )
|
|
|
311
|
+ .is_ok());
|
|
|
312
|
+
|
|
|
313
|
+ assert!(matches!(
|
|
|
314
|
+ validate_onion_address(b"+-6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd")
|
|
|
315
|
+ .unwrap_err(),
|
|
|
316
|
+ OnionValidationError::CannotDecode(_)
|
|
|
317
|
+ ));
|
|
|
318
|
+
|
|
|
319
|
+ assert_eq!(
|
|
|
320
|
+ validate_onion_address(b"pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscrye")
|
|
|
321
|
+ .unwrap_err(),
|
|
|
322
|
+ OnionValidationError::UnsupportedVersion(4)
|
|
|
323
|
+ );
|
|
|
324
|
+
|
|
|
325
|
+ assert_eq!(
|
|
|
326
|
+ validate_onion_address(b"pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscsyd")
|
|
|
327
|
+ .unwrap_err(),
|
|
|
328
|
+ OnionValidationError::BadChecksum
|
|
|
329
|
+ );
|
|
|
330
|
+ assert_eq!(
|
|
|
331
|
+ validate_onion_address(b"aaammjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscsyd")
|
|
|
332
|
+ .unwrap_err(),
|
|
|
333
|
+ OnionValidationError::BadChecksum
|
|
|
334
|
+ );
|
|
|
335
|
+ }
|
|
|
336
|
+
|
|
|
337
|
+ #[test]
|
|
|
338
|
+ fn onion_private_key_redacted() {
|
|
|
339
|
+ let auth = OnionClientAuth {
|
|
|
340
|
+ address: HSAddress::from_str(
|
|
|
341
|
+ "PG6MMJIYJMCRSSLVYKFWNNTLARU7P5SVN6Y2YMMJU6NUBXNDF4PSCRYD",
|
|
|
342
|
+ )
|
|
|
343
|
+ .unwrap(),
|
|
|
344
|
+ key_type: String::from("x25519"),
|
|
|
345
|
+ key_blob: String::from("abase64key"),
|
|
|
346
|
+ is_permanent: false,
|
|
|
347
|
+ };
|
|
|
348
|
+ let auth_fmt = format!("{:?}", auth);
|
|
|
349
|
+ assert!(!auth_fmt.contains(&auth.key_blob));
|
|
|
350
|
+ assert!(auth_fmt.contains("[redacted]"));
|
|
|
351
|
+ }
|
|
|
352
|
+} |
|