alighieri 0.4.0

Alighieri — a lightweight, secure, asynchronous SOCKS5 proxy server with Dante-inspired configuration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
//! The access-control engine.
//!
//! Alighieri's rule model is inspired by Dante's `client`/`socks` rule blocks.
//! Rules are evaluated top-to-bottom and the **first matching rule wins**. If
//! no rule matches, the request is denied — Alighieri is deny-by-default, which
//! is the secure posture for an internet-facing proxy.
//!
//! Two rule scopes exist:
//!
//! - [`Scope::Client`]: evaluated when a TCP connection is accepted. It decides
//!   *who may talk to the proxy at all* (matched on the client's source address
//!   and the proxy's accepting address).
//! - [`Scope::Socks`]: evaluated once a SOCKS5 request has been parsed. It
//!   decides *what an authenticated client may ask the proxy to do* (matched on
//!   source, destination, command, protocol and negotiated auth method).

use std::net::IpAddr;
use std::sync::Arc;

use crate::config::{AuthKind, Protocol, RateLimit};
use crate::net::AddrSpec;
use crate::socks5::Command;

/// Whether a matching rule allows or denies the request.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
// Re-exported by the plugin SDK; `#[non_exhaustive]` so a future verdict stays an
// additive change for plugins that match on it.
#[non_exhaustive]
pub enum Verdict {
    Pass,
    Block,
}

/// The phase at which a rule applies.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Scope {
    /// `client` rules — connection admission.
    Client,
    /// `socks` rules — per-request authorisation.
    Socks,
}

/// A single access-control rule.
///
/// Optional selector fields (`commands`, `protocols`, `methods`) act as "any"
/// when empty: an empty `commands` list matches every command.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Rule {
    /// Optional operator-provided rule name for logs and metrics.
    pub name: Option<Arc<str>>,
    pub verdict: Verdict,
    pub scope: Scope,
    /// Source (client) address selector.
    pub from: AddrSpec,
    /// Destination selector. For `client` rules this is the proxy's own
    /// accepting address; for `socks` rules it is the request destination.
    pub to: AddrSpec,
    /// Allowed commands; empty means "any command".
    pub commands: Vec<Command>,
    /// Allowed protocols; empty means "any protocol".
    pub protocols: Vec<Protocol>,
    /// Allowed auth methods; empty means "any method".
    pub methods: Vec<AuthKind>,
    /// Optional per-session bandwidth limit (`socks` rules only): each matching
    /// CONNECT relay is shaped to this rate. `None` means unlimited.
    pub bandwidth: Option<RateLimit>,
    /// 1-based line number in the source config (for diagnostics).
    pub source_line: usize,
}

/// Context for evaluating a [`Scope::Client`] rule (connection admission).
#[derive(Debug, Clone, Copy)]
pub(crate) struct ClientContext {
    pub client_ip: IpAddr,
    pub client_port: u16,
    pub proxy_ip: IpAddr,
    pub proxy_port: u16,
}

/// Context for evaluating a [`Scope::Socks`] rule (request authorisation).
#[derive(Debug, Clone, Copy)]
pub(crate) struct SocksContext<'a> {
    pub client_ip: IpAddr,
    pub client_port: u16,
    /// The hostname the client requested, if it sent a domain rather than an IP
    /// literal. Matched against `to:` hostname patterns before resolution.
    pub dest_host: Option<&'a str>,
    pub dest_ip: IpAddr,
    pub dest_port: u16,
    pub command: Command,
    pub protocol: Protocol,
    pub method: AuthKind,
}

/// Access-control decision including the source line and optional name of the
/// matching rule. A missing source line means deny-by-default; a missing name
/// can also mean the matching rule was simply unnamed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RuleDecision {
    pub verdict: Verdict,
    pub source_line: Option<usize>,
    pub rule_name: Option<Arc<str>>,
    /// The matching `socks` rule's per-session bandwidth limit, if any.
    pub bandwidth: Option<RateLimit>,
}

impl Rule {
    fn matches_client(&self, ctx: &ClientContext) -> bool {
        self.scope == Scope::Client
            && self.from.matches(ctx.client_ip, ctx.client_port)
            && self.to.matches(ctx.proxy_ip, ctx.proxy_port)
    }

    fn matches_socks(&self, ctx: &SocksContext<'_>) -> bool {
        self.scope == Scope::Socks
            && self.from.matches(ctx.client_ip, ctx.client_port)
            && self
                .to
                .matches_dest(ctx.dest_host, ctx.dest_ip, ctx.dest_port)
            && (self.commands.is_empty() || self.commands.contains(&ctx.command))
            && (self.protocols.is_empty() || self.protocols.contains(&ctx.protocol))
            && (self.methods.is_empty() || self.methods.contains(&ctx.method))
    }
}

/// An ordered collection of rules with first-match-wins, deny-by-default
/// evaluation.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct RuleSet {
    pub rules: Vec<Rule>,
}

impl RuleSet {
    /// Builds a rule set from a vector of rules.
    pub fn new(rules: Vec<Rule>) -> Self {
        RuleSet { rules }
    }

    /// Evaluates connection admission. Returns the matching rule's verdict, or
    /// `Block` if no `client` rule matches.
    #[cfg(test)]
    pub(crate) fn evaluate_client(&self, ctx: &ClientContext) -> Verdict {
        self.evaluate_client_detail(ctx).verdict
    }

    /// Evaluates connection admission and includes the matching rule line.
    pub(crate) fn evaluate_client_detail(&self, ctx: &ClientContext) -> RuleDecision {
        for rule in &self.rules {
            if rule.matches_client(ctx) {
                return RuleDecision {
                    verdict: rule.verdict,
                    source_line: Some(rule.source_line),
                    rule_name: rule.name.clone(),
                    // `client` rules carry no bandwidth limit.
                    bandwidth: None,
                };
            }
        }
        RuleDecision {
            verdict: Verdict::Block,
            source_line: None,
            rule_name: None,
            bandwidth: None,
        }
    }

    /// Evaluates request authorisation. Returns the matching rule's verdict, or
    /// `Block` if no `socks` rule matches.
    #[cfg(test)]
    pub(crate) fn evaluate_socks(&self, ctx: &SocksContext<'_>) -> Verdict {
        self.evaluate_socks_detail(ctx).verdict
    }

    /// Whether a `UdpAssociate` from this client could be authorised for some
    /// destination, evaluated with the same first-match-wins ordering as
    /// [`Self::evaluate_socks`] but ignoring the not-yet-known datagram
    /// destination.
    ///
    /// Used to reject a UDP ASSOCIATE up front — before binding sockets and
    /// replying success — when the policy categorically forbids UDP for the
    /// client (e.g. only `command: connect` rules, or a wildcard `block`), so
    /// such a client cannot hold a relay socket open until the idle timeout. The
    /// per-datagram authoriser still filters the actual targets for clients that
    /// pass this gate.
    ///
    /// Rules are walked in order; the first one that could apply to a UDP
    /// ASSOCIATE from this client decides:
    /// - a `pass` rule means UDP is reachable (to at least its destination
    ///   range);
    /// - a `block` rule with a [match-all](crate::net::AddrSpec::matches_all)
    ///   `to:` denies the client categorically;
    /// - a narrower `block` only rules out some destinations, so a later rule can
    ///   still apply.
    ///
    /// The match-all check is conservative (single-family or port-restricted
    /// blocks are not treated as categorical), so this never falsely rejects a
    /// client that the per-datagram checks would have allowed.
    pub(crate) fn udp_associate_reachable(
        &self,
        client_ip: IpAddr,
        client_port: u16,
        method: AuthKind,
    ) -> bool {
        for rule in &self.rules {
            let applies = rule.scope == Scope::Socks
                && rule.from.matches(client_ip, client_port)
                && (rule.commands.is_empty() || rule.commands.contains(&Command::UdpAssociate))
                && (rule.protocols.is_empty() || rule.protocols.contains(&Protocol::Udp))
                && (rule.methods.is_empty() || rule.methods.contains(&method));
            if !applies {
                continue;
            }
            match rule.verdict {
                Verdict::Pass => return true,
                Verdict::Block if rule.to.matches_all() => return false,
                Verdict::Block => continue,
            }
        }
        false
    }

    /// Evaluates request authorisation and includes the matching rule line.
    pub(crate) fn evaluate_socks_detail(&self, ctx: &SocksContext<'_>) -> RuleDecision {
        for rule in &self.rules {
            if rule.matches_socks(ctx) {
                return RuleDecision {
                    verdict: rule.verdict,
                    source_line: Some(rule.source_line),
                    rule_name: rule.name.clone(),
                    bandwidth: rule.bandwidth.clone(),
                };
            }
        }
        RuleDecision {
            verdict: Verdict::Block,
            source_line: None,
            rule_name: None,
            bandwidth: None,
        }
    }

    /// Returns `true` if the rule set contains at least one rule of the given
    /// scope. Used to warn operators about configs that would deny everything.
    pub(crate) fn has_scope(&self, scope: Scope) -> bool {
        self.rules.iter().any(|r| r.scope == scope)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn spec(cidr: &str) -> AddrSpec {
        AddrSpec::new(cidr.parse().unwrap(), None)
    }

    fn client_rule(verdict: Verdict, from: &str) -> Rule {
        Rule {
            name: None,
            verdict,
            scope: Scope::Client,
            from: spec(from),
            to: spec("0.0.0.0/0"),
            commands: vec![],
            protocols: vec![],
            methods: vec![],
            bandwidth: None,
            source_line: 0,
        }
    }

    fn socks_rule(verdict: Verdict, to: &str, commands: Vec<Command>) -> Rule {
        Rule {
            name: None,
            verdict,
            scope: Scope::Socks,
            from: spec("0.0.0.0/0"),
            to: spec(to),
            commands,
            protocols: vec![],
            methods: vec![],
            bandwidth: None,
            source_line: 0,
        }
    }

    fn client_ctx(ip: &str) -> ClientContext {
        ClientContext {
            client_ip: ip.parse().unwrap(),
            client_port: 5000,
            proxy_ip: "0.0.0.0".parse().unwrap(),
            proxy_port: 1080,
        }
    }

    fn socks_ctx(dest: &str, cmd: Command) -> SocksContext<'static> {
        SocksContext {
            client_ip: "10.0.0.5".parse().unwrap(),
            client_port: 5000,
            dest_host: None,
            dest_ip: dest.parse().unwrap(),
            dest_port: 443,
            command: cmd,
            protocol: Protocol::Tcp,
            method: AuthKind::None,
        }
    }

    fn socks_ctx_host<'a>(host: &'a str, dest: &str, cmd: Command) -> SocksContext<'a> {
        SocksContext {
            dest_host: Some(host),
            ..socks_ctx(dest, cmd)
        }
    }

    #[test]
    fn udp_associate_reachable_gates_on_command() {
        // Only CONNECT permitted: UDP is categorically unreachable, so an
        // ASSOCIATE is rejected before any socket is bound.
        let connect_only = RuleSet::new(vec![socks_rule(
            Verdict::Pass,
            "0.0.0.0/0",
            vec![Command::Connect],
        )]);
        assert!(!connect_only.udp_associate_reachable(
            "10.0.0.5".parse().unwrap(),
            5000,
            AuthKind::None
        ));

        // A UDP-permitting rule admits the association even if its destination is
        // narrow (the per-datagram authoriser still filters actual targets).
        let with_udp = RuleSet::new(vec![socks_rule(
            Verdict::Pass,
            "10.0.0.0/8",
            vec![Command::UdpAssociate],
        )]);
        assert!(with_udp.udp_associate_reachable(
            "10.0.0.5".parse().unwrap(),
            5000,
            AuthKind::None
        ));

        // An "any command" rule (empty list) also permits UDP.
        let any_cmd = RuleSet::new(vec![socks_rule(Verdict::Pass, "0.0.0.0/0", vec![])]);
        assert!(any_cmd.udp_associate_reachable("10.0.0.5".parse().unwrap(), 5000, AuthKind::None));

        // A `block` rule does not count as reachability.
        let blocked = RuleSet::new(vec![socks_rule(
            Verdict::Block,
            "0.0.0.0/0",
            vec![Command::UdpAssociate],
        )]);
        assert!(!blocked.udp_associate_reachable(
            "10.0.0.5".parse().unwrap(),
            5000,
            AuthKind::None
        ));
    }

    #[test]
    fn udp_associate_reachable_respects_first_match() {
        let client: IpAddr = "10.0.0.5".parse().unwrap();
        let mk = |verdict: Verdict, from: &str, to: AddrSpec, commands: Vec<Command>| Rule {
            name: None,
            verdict,
            scope: Scope::Socks,
            from: spec(from),
            to,
            commands,
            protocols: vec![],
            methods: vec![],
            bandwidth: None,
            source_line: 0,
        };

        // A categorical (match-all `to:`) block before a UDP-permitting pass:
        // the client is blocked first, so UDP is unreachable.
        let blocked_first = RuleSet::new(vec![
            mk(Verdict::Block, "10.0.0.5/32", AddrSpec::any(), vec![]),
            mk(
                Verdict::Pass,
                "10.0.0.0/8",
                AddrSpec::any(),
                vec![Command::UdpAssociate],
            ),
        ]);
        assert!(!blocked_first.udp_associate_reachable(client, 5000, AuthKind::None));

        // A narrow block (single family, not match-all) before a pass does not
        // categorically block, so the later pass still makes UDP reachable.
        let narrow_block_first = RuleSet::new(vec![
            mk(
                Verdict::Block,
                "10.0.0.5/32",
                spec("10.0.0.0/8"),
                vec![Command::UdpAssociate],
            ),
            mk(
                Verdict::Pass,
                "10.0.0.0/8",
                AddrSpec::any(),
                vec![Command::UdpAssociate],
            ),
        ]);
        assert!(narrow_block_first.udp_associate_reachable(client, 5000, AuthKind::None));

        // A pass before a universal block wins (first match), so reachable.
        let pass_first = RuleSet::new(vec![
            mk(
                Verdict::Pass,
                "10.0.0.0/8",
                spec("8.8.8.8/32"),
                vec![Command::UdpAssociate],
            ),
            mk(Verdict::Block, "10.0.0.5/32", AddrSpec::any(), vec![]),
        ]);
        assert!(pass_first.udp_associate_reachable(client, 5000, AuthKind::None));
    }

    #[test]
    fn socks_rule_matches_requested_hostname() {
        use crate::net::HostPattern;
        let rs = RuleSet::new(vec![Rule {
            name: None,
            verdict: Verdict::Pass,
            scope: Scope::Socks,
            from: AddrSpec::any(),
            to: AddrSpec::host(HostPattern::Suffix("example.com".into()), None),
            commands: vec![],
            protocols: vec![],
            methods: vec![],
            bandwidth: None,
            source_line: 1,
        }]);

        // The requested host (or a subdomain) is allowed regardless of the IP.
        assert_eq!(
            rs.evaluate_socks(&socks_ctx_host(
                "api.example.com",
                "203.0.113.7",
                Command::Connect
            )),
            Verdict::Pass
        );
        // A different host, even resolving to the same IP, does not match.
        assert_eq!(
            rs.evaluate_socks(&socks_ctx_host("evil.com", "203.0.113.7", Command::Connect)),
            Verdict::Block
        );
        // An IP-literal request (no hostname) never matches a hostname rule.
        assert_eq!(
            rs.evaluate_socks(&socks_ctx("203.0.113.7", Command::Connect)),
            Verdict::Block
        );
    }

    #[test]
    fn socks_decision_carries_rule_bandwidth() {
        // A CONNECT-only rule with a bandwidth limit.
        let mut rule = socks_rule(Verdict::Pass, "0.0.0.0/0", vec![Command::Connect]);
        rule.bandwidth = Some(RateLimit {
            limit: 1024,
            window: std::time::Duration::from_secs(1),
        });
        let rs = RuleSet::new(vec![rule]);

        // A matching request surfaces the rule's bandwidth.
        let allowed = rs.evaluate_socks_detail(&socks_ctx("8.8.8.8", Command::Connect));
        assert_eq!(allowed.verdict, Verdict::Pass);
        assert_eq!(allowed.bandwidth.as_ref().map(|b| b.limit), Some(1024));

        // A non-matching request denies by default, with no bandwidth.
        let denied = rs.evaluate_socks_detail(&socks_ctx("8.8.8.8", Command::UdpAssociate));
        assert_eq!(denied.verdict, Verdict::Block);
        assert_eq!(denied.bandwidth, None);
    }

    #[test]
    fn deny_by_default_when_empty() {
        let rs = RuleSet::default();
        assert_eq!(rs.evaluate_client(&client_ctx("1.2.3.4")), Verdict::Block);
        assert_eq!(
            rs.evaluate_socks(&socks_ctx("8.8.8.8", Command::Connect)),
            Verdict::Block
        );
    }

    #[test]
    fn first_match_wins() {
        let rs = RuleSet::new(vec![
            client_rule(Verdict::Block, "10.0.0.0/8"),
            client_rule(Verdict::Pass, "0.0.0.0/0"),
        ]);
        // 10.x hits the block rule first.
        assert_eq!(rs.evaluate_client(&client_ctx("10.0.0.5")), Verdict::Block);
        // Other addresses fall through to the pass rule.
        assert_eq!(rs.evaluate_client(&client_ctx("8.8.8.8")), Verdict::Pass);
    }

    #[test]
    fn detailed_decision_includes_rule_line() {
        let mut rule = client_rule(Verdict::Pass, "0.0.0.0/0");
        rule.source_line = 42;
        let rs = RuleSet::new(vec![rule]);

        let decision = rs.evaluate_client_detail(&client_ctx("8.8.8.8"));

        assert_eq!(decision.verdict, Verdict::Pass);
        assert_eq!(decision.source_line, Some(42));
        assert_eq!(decision.rule_name, None);
    }

    #[test]
    fn detailed_decision_includes_rule_name() {
        let mut rule = client_rule(Verdict::Pass, "0.0.0.0/0");
        rule.name = Some(Arc::from("lan-clients"));
        let rs = RuleSet::new(vec![rule]);

        let decision = rs.evaluate_client_detail(&client_ctx("8.8.8.8"));

        assert_eq!(decision.rule_name.as_deref(), Some("lan-clients"));
    }

    #[test]
    fn socks_command_filtering() {
        let rs = RuleSet::new(vec![socks_rule(
            Verdict::Pass,
            "0.0.0.0/0",
            vec![Command::Connect],
        )]);
        assert_eq!(
            rs.evaluate_socks(&socks_ctx("8.8.8.8", Command::Connect)),
            Verdict::Pass
        );
        // UDP associate is not in the allowed command list → no match → deny.
        assert_eq!(
            rs.evaluate_socks(&socks_ctx("8.8.8.8", Command::UdpAssociate)),
            Verdict::Block
        );
    }

    #[test]
    fn socks_dest_filtering_blocks_loopback() {
        let rs = RuleSet::new(vec![
            socks_rule(Verdict::Block, "127.0.0.0/8", vec![]),
            socks_rule(Verdict::Pass, "0.0.0.0/0", vec![]),
        ]);
        assert_eq!(
            rs.evaluate_socks(&socks_ctx("127.0.0.1", Command::Connect)),
            Verdict::Block
        );
        assert_eq!(
            rs.evaluate_socks(&socks_ctx("93.184.216.34", Command::Connect)),
            Verdict::Pass
        );
    }

    #[test]
    fn has_scope_detection() {
        let rs = RuleSet::new(vec![client_rule(Verdict::Pass, "0.0.0.0/0")]);
        assert!(rs.has_scope(Scope::Client));
        assert!(!rs.has_scope(Scope::Socks));
    }
}