1
//! Exit streams
2

            
3
use std::io::ErrorKind;
4
use std::net::{IpAddr, SocketAddr};
5
use std::num::NonZero;
6
use std::time::Duration;
7

            
8
use either::Either;
9
use futures::io::BufReader;
10
use tor_cell::relaycell::msg::{BeginAddr, BeginFlags, Connected, End, EndReason};
11
use tor_error::{internal, trace_report, warn_report};
12
use tor_proto::stream::{IncomingStream, IncomingStreamRequest};
13
use tor_rtcompat::SleepProviderExt as _;
14
use tor_rtcompat::{NetStreamProvider, Runtime, TimeoutError};
15
use tracing::{info, trace};
16

            
17
use crate::stream::dns::resolver::{DnsResolver, LookupAnswers, LookupError, RecordData};
18

            
19
/// Handle an incoming exit stream.
20
///
21
/// This is expected to be called from a task dedicated to this stream,
22
/// so it may async-block (for example to establish the exit connection and proxy traffic).
23
/// It should not be used with a timeout.
24
pub(super) async fn handle_begin<R: Runtime>(
25
    runtime: R,
26
    incoming: IncomingStream,
27
    resolver: DnsResolver,
28
) -> anyhow::Result<()> {
29
    let connect_options = Default::default();
30

            
31
    // It would be nice to have a better API on `IncomingStream`
32
    // so that we don't need this extra match.
33
    let msg = match incoming.request() {
34
        IncomingStreamRequest::Begin(msg) => msg,
35
        s => {
36
            return Err(anyhow::anyhow!(
37
                "unexpected stream request type {s:?}; should be unreachable"
38
            ));
39
        }
40
    };
41

            
42
    // TODO(relay): This is temporary. Remove this once we have exit policy support.
43
    // This is to help prevent us from accidentally running a public exit while we're testing.
44
    match std::env::var("ARTI_EXIT") {
45
        Ok(val) if val.trim() == "1" => {}
46
        _ => {
47
            info!("Rejecting incoming stream since `ARTI_EXIT` env variable is not set to '1'");
48
            return Ok(());
49
        }
50
    }
51

            
52
    // Assign these to local variables to ensure we use all of them.
53
    let (addr, port, flags) = (msg.addr(), msg.port(), msg.flags());
54

            
55
    let addr = match addr.decode() {
56
        Ok(x) => x,
57
        Err(e) => {
58
            trace!("Rejecting incoming stream with invalid address: {e}");
59
            incoming
60
                .reject(End::new_with_reason(EndReason::TORPROTOCOL))
61
                .await?;
62
            return Ok(());
63
        }
64
    };
65

            
66
    // A future for everything we want to include within the timeout.
67
    // Returns the TCP stream, and on error returns the END reason.
68
    let exit_stream_fut = match addr {
69
        BeginAddr::Ip(addr) => {
70
            let addr = SocketAddr::new(addr, port.get());
71
            let fut = connect_ip(&runtime, addr, flags, &connect_options);
72
            Either::Left(fut)
73
        }
74
        BeginAddr::Hostname(ref addr) => {
75
            let fut = connect_hostname(
76
                &runtime,
77
                addr.as_ref(),
78
                port,
79
                flags,
80
                resolver,
81
                &connect_options,
82
            );
83
            Either::Right(fut)
84
        }
85
    };
86

            
87
    // TODO(relay-tuning): timeout chosen arbitrarily
88
    let timeout = Duration::from_secs(30);
89
    let exit_stream = match runtime.timeout(timeout, exit_stream_fut).await {
90
        Ok(Ok(stream)) => stream,
91
        Ok(Err(end_reason)) => {
92
            incoming.reject(End::new_with_reason(end_reason)).await?;
93
            return Ok(());
94
        }
95
        Err(TimeoutError) => {
96
            incoming
97
                .reject(End::new_with_reason(EndReason::TIMEOUT))
98
                .await?;
99
            return Ok(());
100
        }
101
    };
102

            
103
    let tor_stream = incoming.accept_data(Connected::new_empty()).await?;
104

            
105
    // TODO(relay-tuning): copied from arti
106
    const STREAM_BUF_LEN: usize = 4096;
107
    let exit_stream = BufReader::with_capacity(STREAM_BUF_LEN, exit_stream);
108
    let tor_stream = BufReader::with_capacity(STREAM_BUF_LEN, tor_stream);
109

            
110
    let res = futures_copy::copy_buf_bidirectional(
111
        tor_stream,
112
        exit_stream,
113
        futures_copy::eof::Close,
114
        futures_copy::eof::Close,
115
    )
116
    .await;
117

            
118
    match res {
119
        Ok((tor_to_exit, exit_to_tor)) => {
120
            trace!(
121
                count_fwd = tor_to_exit,
122
                count_bwd = exit_to_tor,
123
                "Stream bidirectional copy finished",
124
            );
125
        }
126
        // TODO(relay): arti does something complicated here; see `report_proxy_error()`
127
        Err(e) => {
128
            warn_report!(e, "Error while proxying data on exit stream");
129
        }
130
    }
131

            
132
    Ok(())
133
}
134

            
135
/// For a BEGIN message containing the socket address and flags,
136
/// attempt to connect to the address.
137
async fn connect_ip<R: Runtime>(
138
    runtime: &R,
139
    addr: SocketAddr,
140
    _flags: BeginFlags,
141
    connect_options: &<R as NetStreamProvider<SocketAddr>>::ConnectOptions,
142
) -> Result<<R as NetStreamProvider<SocketAddr>>::Stream, EndReason> {
143
    // We ignore the `IPV4_NOT_OKAY`, `IPV6_OKAY`, and `IPV6_PREFERRED` flags.
144
    //
145
    // torspec:
146
    // > Flags 1 through 3 are ignored if ADDRESS is an IP address.
147

            
148
    // Apply the exit policy filter.
149
    if !exit_policy_allows(addr) {
150
        trace!("Rejecting incoming stream due to the exit policy");
151
        return Err(EndReason::EXITPOLICY);
152
    }
153

            
154
    // TODO(relay): We need to check if the IP is in the consensus
155
    // to prevent exit streams from reentering the Tor network.
156
    // https://gitlab.torproject.org/tpo/core/arti/-/work_items/2841
157

            
158
    tcp_connect(runtime, &addr, connect_options).await
159
}
160

            
161
/// For a BEGIN message containing a hostname and flags,
162
/// attempt to connect to the hostname.
163
async fn connect_hostname<R: Runtime>(
164
    runtime: &R,
165
    hostname: &[u8],
166
    port: NonZero<u16>,
167
    flags: BeginFlags,
168
    mut resolver: DnsResolver,
169
    connect_options: &<R as NetStreamProvider<SocketAddr>>::ConnectOptions,
170
) -> Result<<R as NetStreamProvider<SocketAddr>>::Stream, EndReason> {
171
    let port = port.get();
172

            
173
    // We need to ensure that the case of each character in the hostname is randomized
174
    // to defend against certain DNS cache poisoning attacks,
175
    // but the `DnsResolver` takes care of this in `resolve()`.
176
    //
177
    // `DnsResolver::resolve`:
178
    // > The query will be transformed before resolving, as described in torspec:
179
    // > https://spec.torproject.org/tor-spec/remote-hostname-lookup.html#dns-requests
180

            
181
    let answers = match resolver.resolve(hostname).await {
182
        Ok(x) => x,
183
        Err(LookupError::NonAsciiHostname) => {
184
            // `Begin::decode_from_reader()` does not allow non-ascii addresses,
185
            // so if we get here something has gone wrong and we should probably investigate.
186
            let bug = internal!("the `Begin` type should have prevented this");
187
            trace_report!(bug, "Hostname for BEGIN message had non-ascii hostname");
188
            return Err(EndReason::TORPROTOCOL);
189
        }
190
        Err(LookupError::Hickory(e)) => {
191
            trace!("Name resolution for exit stream failed due to hickory error: {e}");
192
            return Err(EndReason::RESOLVEFAILED);
193
        }
194
        Err(LookupError::Bug(e)) => {
195
            trace_report!(e, "Name resolution for exit stream failed due to bug");
196
            return Err(EndReason::INTERNAL);
197
        }
198
    };
199

            
200
    // Remove any hostname answers.
201
    // We could instead error if any answers were hostnames,
202
    // but I don't see a reason to do that.
203
    let answers = answers.into_iter().filter_map(|x| match x {
204
        RecordData::Ip(x) => Some(x),
205
        RecordData::Hostname(_) => None,
206
    });
207

            
208
    // Filter the addresses based on provided flags.
209
    // I prefer it how it's written to how clippy wants it.
210
    #[allow(clippy::needless_bool)]
211
    let answers = answers.filter(|ip| {
212
        if ip.is_ipv4() && flags.contains(BeginFlags::IPV4_NOT_OKAY) {
213
            return false;
214
        }
215

            
216
        // torspec:
217
        // > 3 -- IPv6 preferred. [...] This flag implies the flag at bit "1" (IPv6 okay).
218
        let ipv6_okay = flags.intersects(BeginFlags::IPV6_OKAY | BeginFlags::IPV6_PREFERRED);
219
        if ip.is_ipv6() && !ipv6_okay {
220
            return false;
221
        }
222

            
223
        true
224
    });
225

            
226
    // Collect to check the length before we apply the exit policy.
227
    let answers: LookupAnswers<IpAddr> = answers.collect();
228
    if answers.is_empty() {
229
        trace!("Rejecting incoming stream since the domain resolution had no usable IP answers");
230
        return Err(EndReason::RESOLVEFAILED);
231
    }
232

            
233
    // Apply the exit policy filter.
234
    let answers = answers
235
        .into_iter()
236
        .filter(|ip| exit_policy_allows(SocketAddr::new(*ip, port)));
237

            
238
    // TODO(relay): We need to reject IPs that are in the consensus
239
    // to prevent exit streams from reentering the Tor network.
240
    // https://gitlab.torproject.org/tpo/core/arti/-/work_items/2841
241

            
242
    // Collect so that we can sort them.
243
    let mut answers: LookupAnswers<IpAddr> = answers.collect();
244
    if answers.is_empty() {
245
        trace!("Rejecting incoming stream due to the exit policy");
246
        return Err(EndReason::EXITPOLICY);
247
    }
248

            
249
    // torspec:
250
    // > 3 -- IPv6 preferred. If there are both IPv4 and IPv6 addresses,
251
    // >      we want to connect to the IPv6 one. (By default, we connect
252
    // >      to the IPv4 address.)
253
    if flags.contains(BeginFlags::IPV6_PREFERRED) {
254
        // `false` is sorted before `true`, and `!ip.is_ipv6()` is false for ipv6 addresses
255
        answers.sort_by_key(|ip| !ip.is_ipv6());
256
    } else {
257
        // `false` is sorted before `true`, and `!ip.is_ipv4()` is false for ipv4 addresses
258
        answers.sort_by_key(|ip| !ip.is_ipv4());
259
    }
260

            
261
    // TODO: We maybe want to do happy eyeballs in the future.
262
    // https://gitlab.torproject.org/tpo/core/arti/-/work_items/2878
263

            
264
    // Use the first address in the list.
265
    let addr = match answers.first() {
266
        Some(ip) => ip,
267
        None => {
268
            let bug = internal!("we checked above before sorting that the list is non-empty");
269
            trace_report!(bug, "No address answers for BEGIN hostname lookup");
270
            return Err(EndReason::RESOLVEFAILED);
271
        }
272
    };
273

            
274
    let addr = SocketAddr::new(*addr, port);
275

            
276
    tcp_connect(runtime, &addr, connect_options).await
277
}
278

            
279
/// Helper to establish the TCP connection and get the correct error "reason" to use in the END
280
/// message if needed.
281
async fn tcp_connect<R: Runtime>(
282
    runtime: &R,
283
    addr: &SocketAddr,
284
    connect_options: &<R as NetStreamProvider<SocketAddr>>::ConnectOptions,
285
) -> Result<<R as NetStreamProvider<SocketAddr>>::Stream, EndReason> {
286
    match runtime.connect(addr, connect_options).await {
287
        Ok(x) => Ok(x),
288
        Err(e) => {
289
            let reason = io_error_kind_to_end_reason(e.kind());
290
            if reason == EndReason::INTERNAL {
291
                let bug = internal!("Unexpected io error {}: {}", e.kind(), e);
292
                trace_report!(bug, "Unexpected {reason} when connecting to TCP address");
293
            }
294
            Err(reason)
295
        }
296
    }
297
}
298

            
299
/// Does our exit policy allow the given address?
300
//
301
// TODO: Later we will probably have some sort of exit policy object,
302
// and we can remove this function and just call `exit_policy.allows(addr)` or something.
303
fn exit_policy_allows(mut addr: SocketAddr) -> bool {
304
    // Canonicalize the IP address to ensure that we handle IPv4-mapped IPv6 addresses.
305
    // For example if an exit policy disallows `a.b.c.d`, we should also disallow `::ffff:a.b.c.d`.
306
    addr.set_ip(addr.ip().to_canonical());
307

            
308
    // TODO(relay): Need to support an exit policy. Currently we allow exits to anywhere (except
309
    // basic loopback checks) for testing purposes.
310
    !addr.ip().is_loopback() && !addr.ip().is_unspecified()
311
}
312

            
313
/// For a TCP error, get the reason we should use in the END message.
314
fn io_error_kind_to_end_reason(e: ErrorKind) -> EndReason {
315
    match e {
316
        ErrorKind::ConnectionRefused => EndReason::CONNECTREFUSED,
317
        ErrorKind::ConnectionReset => EndReason::CONNRESET,
318
        ErrorKind::HostUnreachable => EndReason::NOROUTE,
319
        // Linux "no route to host" errors are given for EHOSTUNREACH,
320
        // and "network is unreachable" errors are given for ENETUNREACH.
321
        // But `EndReason` doesn't have a `ENETUNREACH`-equivalent so
322
        // we just reuse `NOROUTE` here.
323
        ErrorKind::NetworkUnreachable => EndReason::NOROUTE,
324
        // We implement our own timeout in the async code and we don't expect to have a TCP timeout
325
        // here, so this is probably a bug.
326
        ErrorKind::TimedOut => EndReason::INTERNAL,
327
        ErrorKind::QuotaExceeded => EndReason::RESOURCELIMIT,
328
        ErrorKind::OutOfMemory => EndReason::RESOURCELIMIT,
329
        // TODO(nightly: io_error_too_many_open_files): `TooManyOpenFiles` should probably return
330
        // `RESOURCELIMIT`.
331
        _ => EndReason::MISC,
332
    }
333
}